功能:完善多店铺登录与首次部署SQL
This commit is contained in:
+133
-37
@@ -3,10 +3,9 @@ import router from '../router'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { ADMIN_API_BASE_URL } from '../config/api'
|
||||
|
||||
// 防重复提示标志
|
||||
let lastErrorTime = 0
|
||||
let lastErrorMessage = ''
|
||||
const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误
|
||||
const ERROR_DEBOUNCE_TIME = 1000
|
||||
|
||||
const adminApi = axios.create({
|
||||
baseURL: ADMIN_API_BASE_URL,
|
||||
@@ -16,10 +15,62 @@ const adminApi = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
let isRefreshing = false
|
||||
let failedQueue: Array<{
|
||||
resolve: (value?: any) => void
|
||||
reject: (reason?: any) => void
|
||||
}> = []
|
||||
|
||||
const processQueue = (error: any, token: string | null = null) => {
|
||||
failedQueue.forEach(prom => {
|
||||
if (error) {
|
||||
prom.reject(error)
|
||||
} else {
|
||||
prom.resolve(token)
|
||||
}
|
||||
})
|
||||
failedQueue = []
|
||||
}
|
||||
|
||||
const showError = (msg: string) => {
|
||||
const now = Date.now()
|
||||
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
|
||||
lastErrorTime = now
|
||||
lastErrorMessage = msg
|
||||
message.error(msg)
|
||||
}
|
||||
}
|
||||
|
||||
const isAuthFreePath = (url?: string) => {
|
||||
return Boolean(url?.includes('/auth/login') || url?.includes('/auth/refresh'))
|
||||
}
|
||||
|
||||
const handleAdminTokenExpired = () => {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('userPermissions')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
sessionStorage.removeItem('adminRefreshToken')
|
||||
|
||||
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
||||
showError('登录已过期,请重新登录')
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
try {
|
||||
router.push('/admin/login').catch(() => {
|
||||
window.location.href = '/admin/login'
|
||||
})
|
||||
} catch {
|
||||
window.location.href = '/admin/login'
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
|
||||
adminApi.interceptors.request.use(
|
||||
config => {
|
||||
// 登录请求不需要携带Token
|
||||
if (!config.url?.includes('/auth/login')) {
|
||||
if (!isAuthFreePath(config.url)) {
|
||||
let token = localStorage.getItem('adminAccessToken')
|
||||
if (!token) {
|
||||
token = sessionStorage.getItem('adminAccessToken')
|
||||
@@ -30,9 +81,7 @@ adminApi.interceptors.request.use(
|
||||
}
|
||||
return config
|
||||
},
|
||||
error => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
error => Promise.reject(error)
|
||||
)
|
||||
|
||||
adminApi.interceptors.response.use(
|
||||
@@ -41,7 +90,7 @@ adminApi.interceptors.response.use(
|
||||
if (res.code !== 200) {
|
||||
const errorMsg = res.message || '请求失败'
|
||||
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) {
|
||||
message.error(errorMsg)
|
||||
showError(errorMsg)
|
||||
} else {
|
||||
console.error('权限不足:', errorMsg)
|
||||
}
|
||||
@@ -50,35 +99,56 @@ adminApi.interceptors.response.use(
|
||||
return res.data as any
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
// 防抖处理错误提示
|
||||
const showError = (msg: string) => {
|
||||
const now = Date.now()
|
||||
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
|
||||
lastErrorTime = now
|
||||
lastErrorMessage = msg
|
||||
message.error(msg)
|
||||
}
|
||||
}
|
||||
const originalRequest = error.config as any
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
// 登录过期,只提示一次
|
||||
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
showError('登录已过期,请重新登录')
|
||||
try {
|
||||
router.push('/admin/login').catch(err => {
|
||||
console.error('跳转到登录页失败:', err)
|
||||
window.location.href = '/admin/login'
|
||||
if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) {
|
||||
if (isRefreshing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject })
|
||||
}).then(token => {
|
||||
if (token) {
|
||||
originalRequest.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return adminApi(originalRequest)
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('跳转到登录页异常:', err)
|
||||
window.location.href = '/admin/login'
|
||||
}
|
||||
|
||||
originalRequest._retry = true
|
||||
isRefreshing = true
|
||||
|
||||
try {
|
||||
let refreshToken = localStorage.getItem('adminRefreshToken')
|
||||
if (!refreshToken) {
|
||||
refreshToken = sessionStorage.getItem('adminRefreshToken')
|
||||
}
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available')
|
||||
}
|
||||
|
||||
const response = await adminAuthApi.refreshToken(refreshToken)
|
||||
const newToken = (response as any).accessToken
|
||||
const newRefreshToken = (response as any).refreshToken
|
||||
|
||||
localStorage.setItem('adminAccessToken', newToken)
|
||||
localStorage.setItem('adminRefreshToken', newRefreshToken)
|
||||
sessionStorage.setItem('adminAccessToken', newToken)
|
||||
sessionStorage.setItem('adminRefreshToken', newRefreshToken)
|
||||
|
||||
processQueue(null, newToken)
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
return adminApi(originalRequest)
|
||||
} catch (refreshError) {
|
||||
processQueue(refreshError, null)
|
||||
handleAdminTokenExpired()
|
||||
return Promise.reject(refreshError)
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
}
|
||||
} else if (error.response?.status !== 403) { // 403权限不足不提示
|
||||
|
||||
handleAdminTokenExpired()
|
||||
} else if (error.response?.status !== 403) {
|
||||
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
|
||||
showError(errorMsg)
|
||||
} else {
|
||||
@@ -102,10 +172,28 @@ export interface AdminLoginResponse {
|
||||
userInfo: any
|
||||
}
|
||||
|
||||
export interface LoginShopSelectionResponse {
|
||||
allowShoplessLogin: boolean
|
||||
message: string
|
||||
shops: Array<{
|
||||
id: number | string
|
||||
shopName: string
|
||||
}>
|
||||
}
|
||||
|
||||
export const adminAuthApi = {
|
||||
login: (data: AdminLoginRequest) => {
|
||||
return adminApi.post<AdminLoginResponse>('/auth/login', data)
|
||||
},
|
||||
getLoginShops: (account: string) => {
|
||||
return adminApi.get<LoginShopSelectionResponse>(`/auth/login-shops/${encodeURIComponent(account)}`)
|
||||
},
|
||||
logout: () => {
|
||||
return adminApi.post<boolean>('/auth/logout')
|
||||
},
|
||||
switchShop: (shopId?: string | number) => {
|
||||
return adminApi.post<AdminLoginResponse>('/auth/switch-shop', { shopId })
|
||||
},
|
||||
refreshToken: (refreshToken: string) => {
|
||||
return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken })
|
||||
}
|
||||
@@ -275,6 +363,7 @@ export interface Shop {
|
||||
description: string
|
||||
address: string
|
||||
businessHours: string
|
||||
status?: number
|
||||
coverImageFileId?: string
|
||||
coverImageUrls?: string[]
|
||||
imageFileIds?: string
|
||||
@@ -297,6 +386,7 @@ export interface CreateShopRequest {
|
||||
businessHours: string
|
||||
coverImageFileId?: string
|
||||
imageFileIds?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
export const adminShopApi = {
|
||||
@@ -312,6 +402,9 @@ export const adminShopApi = {
|
||||
updateShop: (id: number, data: CreateShopRequest) => {
|
||||
return adminApi.put<boolean>(`/shops/update/${id}`, data)
|
||||
},
|
||||
updateShopStatus: (id: number, status: number) => {
|
||||
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
|
||||
},
|
||||
deleteShop: (id: number) => {
|
||||
return adminApi.delete<boolean>(`/shops/delete/${id}`)
|
||||
}
|
||||
@@ -321,6 +414,8 @@ export interface UserVO {
|
||||
id: number
|
||||
shopId?: number
|
||||
shopName?: string
|
||||
shopIds?: Array<number | string>
|
||||
shopNames?: string[]
|
||||
nickname: string
|
||||
account: string
|
||||
avatar: string
|
||||
@@ -429,7 +524,6 @@ export interface AdminUserVipOverrideRequest {
|
||||
remark?: string
|
||||
}
|
||||
|
||||
// 别名导出,兼容旧代码
|
||||
export const userApi = adminUserApi
|
||||
|
||||
export interface OrderVO {
|
||||
@@ -460,16 +554,18 @@ export const adminOrderApi = {
|
||||
}
|
||||
}
|
||||
|
||||
// 仪表盘相关接口
|
||||
export interface HotProductVO {
|
||||
productId: number
|
||||
productName: string
|
||||
orderCount: number
|
||||
id: number
|
||||
title: string
|
||||
price: number
|
||||
likeCount: number
|
||||
collectCount: number
|
||||
}
|
||||
|
||||
export interface RecentActivityVO {
|
||||
id: number
|
||||
type: string
|
||||
title?: string
|
||||
description: string
|
||||
time: string
|
||||
color?: string
|
||||
|
||||
@@ -8,20 +8,20 @@ export interface LoginRequest {
|
||||
account: string
|
||||
password: string
|
||||
rememberMe?: boolean
|
||||
shopId?: number
|
||||
shopId?: string | number
|
||||
}
|
||||
|
||||
export interface PhoneLoginRequest {
|
||||
phone: string
|
||||
verificationCode: string
|
||||
shopId?: number
|
||||
shopId?: string | number
|
||||
}
|
||||
|
||||
export interface RegisterRequest {
|
||||
account: string
|
||||
password: string
|
||||
nickname: string
|
||||
shopId?: number
|
||||
shopId?: string | number
|
||||
phone?: string
|
||||
verificationCode?: string
|
||||
}
|
||||
@@ -38,7 +38,11 @@ export interface UserInfo {
|
||||
nickname: string
|
||||
avatar?: string
|
||||
signature?: string
|
||||
type?: number
|
||||
shopId?: number | string
|
||||
shopName?: string
|
||||
shopIds?: Array<number | string>
|
||||
shopNames?: string[]
|
||||
createTime: string
|
||||
updateTime?: string
|
||||
}
|
||||
@@ -58,6 +62,10 @@ export interface ResetPasswordRequest {
|
||||
newPassword: string
|
||||
}
|
||||
|
||||
export interface SwitchShopRequest {
|
||||
shopId?: string | number
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
sendVerificationCode: (data: SendVerificationCodeRequest) => {
|
||||
return api.post('/user/send-verification-code', data)
|
||||
@@ -87,6 +95,10 @@ export const authApi = {
|
||||
return api.post('/user/logout')
|
||||
},
|
||||
|
||||
switchShop: (data: SwitchShopRequest) => {
|
||||
return api.post<LoginResponse>('/user/switch-shop', data)
|
||||
},
|
||||
|
||||
getUserInfo: () => {
|
||||
return api.get<UserInfo>('/user/info')
|
||||
},
|
||||
@@ -94,4 +106,4 @@ export const authApi = {
|
||||
resetPasswordByPhone: (data: ResetPasswordRequest) => {
|
||||
return api.post('/user/reset-password-by-phone', data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,12 +127,12 @@ export const couponApi = {
|
||||
},
|
||||
|
||||
// 获取用户优惠券列表
|
||||
listUserCoupons: (status?: number) => {
|
||||
return request({
|
||||
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
|
||||
return await request({
|
||||
url: '/coupon/user/list',
|
||||
method: 'get',
|
||||
params: { status }
|
||||
})
|
||||
}) as UserCoupon[]
|
||||
},
|
||||
|
||||
// 使用优惠券
|
||||
@@ -145,11 +145,11 @@ export const couponApi = {
|
||||
},
|
||||
|
||||
// 获取作品可用的优惠券
|
||||
getAvailableCoupons: (productTags: string, productPrice: number, shopId?: number) => {
|
||||
return request({
|
||||
getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: number): Promise<UserCoupon[]> => {
|
||||
return await request({
|
||||
url: '/coupon/available',
|
||||
method: 'get',
|
||||
params: { productTags, productPrice, shopId }
|
||||
})
|
||||
}) as UserCoupon[]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +137,13 @@ api.interceptors.response.use(
|
||||
url?.includes('/user/refresh-token') ||
|
||||
url?.includes('/user/send-verification-code') ||
|
||||
url?.includes('/user/phone-login') ||
|
||||
url?.includes('/product/get/') ||
|
||||
url?.includes('/product/list/') ||
|
||||
url?.includes('/shop/get/') ||
|
||||
url?.includes('/shop/list/public') ||
|
||||
url?.includes('/shop/list/simple') ||
|
||||
url?.includes('/tag/list/all') ||
|
||||
url?.includes('/file/get-signed-url/') ||
|
||||
url?.includes('/admin/auth/login') ||
|
||||
url?.includes('/admin/auth/refresh')
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ export const orderApi = {
|
||||
},
|
||||
|
||||
// 获取订单列表
|
||||
getOrderList: () => {
|
||||
return api.get('/order/list')
|
||||
getOrderList: async (): Promise<any[]> => {
|
||||
return await api.get<any[]>('/order/list') as unknown as any[]
|
||||
},
|
||||
|
||||
// 获取订单详情
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface ProductVO {
|
||||
price: number
|
||||
estimatedTime: number
|
||||
approximateDuration?: string
|
||||
bookableArtists?: string
|
||||
availableCoupons?: string
|
||||
category: string
|
||||
tags?: string
|
||||
tagList?: string[]
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface ShopVO {
|
||||
description: string
|
||||
address: string
|
||||
businessHours: string
|
||||
status?: number
|
||||
imageFileIds: string
|
||||
imageUrls?: string[]
|
||||
createTime: string
|
||||
@@ -45,15 +46,19 @@ export interface UpdateShopRequest {
|
||||
}
|
||||
|
||||
export const shopApi = {
|
||||
getAllShops: () => {
|
||||
return api.get<ShopVO[]>('/shop/list/all')
|
||||
getAllShops: async (): Promise<ShopVO[]> => {
|
||||
return await api.get<ShopVO[]>('/shop/list/all') as unknown as ShopVO[]
|
||||
},
|
||||
|
||||
getShopsSimple: () => {
|
||||
return api.get<ShopSimpleVO[]>('/shop/list/simple')
|
||||
getPublicShops: async (): Promise<ShopVO[]> => {
|
||||
return await api.get<ShopVO[]>('/shop/list/public') as unknown as ShopVO[]
|
||||
},
|
||||
|
||||
getShopById: (id: number) => {
|
||||
return api.get<ShopVO>(`/shop/get/${id}`)
|
||||
getShopsSimple: async (): Promise<ShopSimpleVO[]> => {
|
||||
return await api.get<ShopSimpleVO[]>('/shop/list/simple') as unknown as ShopSimpleVO[]
|
||||
},
|
||||
|
||||
getShopById: async (id: number): Promise<ShopVO> => {
|
||||
return await api.get<ShopVO>(`/shop/get/${id}`) as unknown as ShopVO
|
||||
}
|
||||
}
|
||||
|
||||
+34
-12
@@ -5,6 +5,8 @@ export interface UserVO extends UserInfo {
|
||||
id: number
|
||||
shopId?: number
|
||||
shopName?: string
|
||||
shopIds?: Array<number | string>
|
||||
shopNames?: string[]
|
||||
nickname: string
|
||||
account: string
|
||||
avatar: string
|
||||
@@ -39,6 +41,7 @@ export interface CreateUserRequest {
|
||||
password: string
|
||||
type: number
|
||||
shopId?: number
|
||||
shopIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface UpdateUserRequest {
|
||||
@@ -47,6 +50,7 @@ export interface UpdateUserRequest {
|
||||
phone?: string
|
||||
type?: number
|
||||
shopId?: number
|
||||
shopIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface UpdatePasswordRequest {
|
||||
@@ -70,6 +74,15 @@ export interface LoginAccountCheckResponse {
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface LoginShopSelectionResponse {
|
||||
allowShoplessLogin: boolean
|
||||
message: string
|
||||
shops: Array<{
|
||||
id: number | string
|
||||
shopName: string
|
||||
}>
|
||||
}
|
||||
|
||||
export interface UpdatePhoneRequest {
|
||||
oldPhone: string
|
||||
newPhone: string
|
||||
@@ -77,8 +90,8 @@ export interface UpdatePhoneRequest {
|
||||
}
|
||||
|
||||
export const userApi = {
|
||||
getUserInfo: () => {
|
||||
return api.get<UserVO>('/user/info')
|
||||
getUserInfo: async (): Promise<UserVO> => {
|
||||
return await api.get<UserVO>('/user/info') as unknown as UserVO
|
||||
},
|
||||
updateUserInfo: (data: UpdateUserInfoRequest) => {
|
||||
return api.put('/user/update', data)
|
||||
@@ -92,24 +105,33 @@ export const userApi = {
|
||||
updatePhone: (data: UpdatePhoneRequest) => {
|
||||
return api.put('/user/phone', data)
|
||||
},
|
||||
getUserByAccount: (account: string) => {
|
||||
return api.get<UserVO>(`/user/get/account/${account}`)
|
||||
getUserByAccount: async (account: string): Promise<UserVO> => {
|
||||
return await api.get<UserVO>(`/user/get/account/${account}`) as unknown as UserVO
|
||||
},
|
||||
checkAccountAvailability: (account: string) => {
|
||||
return api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`)
|
||||
checkAccountAvailability: async (account: string): Promise<AvailabilityCheckResponse> => {
|
||||
return await api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse
|
||||
},
|
||||
checkLoginAccountAvailability: (account: string) => {
|
||||
return api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`)
|
||||
checkLoginAccountAvailability: async (account: string): Promise<LoginAccountCheckResponse> => {
|
||||
return await api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse
|
||||
},
|
||||
checkPhoneAvailability: (phone: string) => {
|
||||
return api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`)
|
||||
getLoginShopsByAccount: async (account: string): Promise<LoginShopSelectionResponse> => {
|
||||
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse
|
||||
},
|
||||
listUsersByType: (type: number) => {
|
||||
return api.get<UserVO[]>(`/user/list/type/${type}`)
|
||||
getLoginShopsByPhone: async (phone: string): Promise<LoginShopSelectionResponse> => {
|
||||
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse
|
||||
},
|
||||
checkPhoneAvailability: async (phone: string): Promise<AvailabilityCheckResponse> => {
|
||||
return await api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse
|
||||
},
|
||||
listUsersByType: async (type: number): Promise<UserVO[]> => {
|
||||
return await api.get<UserVO[]>(`/user/list/type/${type}`) as unknown as UserVO[]
|
||||
},
|
||||
sendVerificationCode: (data: { phone: string }) => {
|
||||
return api.post('/user/send-verification-code', data)
|
||||
},
|
||||
switchShop: (shopId?: string | number) => {
|
||||
return api.post('/user/switch-shop', { shopId })
|
||||
},
|
||||
deactivateAccount: () => {
|
||||
return api.delete('/user/deactivate')
|
||||
}
|
||||
|
||||
@@ -27,19 +27,19 @@ export interface WishlistItem {
|
||||
}
|
||||
|
||||
export const wishlistApi = {
|
||||
addToWishlist: (productId: number) => {
|
||||
return api.post('/wishlist/add', { productId })
|
||||
addToWishlist: async (productId: number): Promise<boolean> => {
|
||||
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
|
||||
},
|
||||
|
||||
removeFromWishlist: (productId: number) => {
|
||||
return api.post('/wishlist/remove', { productId })
|
||||
removeFromWishlist: async (productId: number): Promise<boolean> => {
|
||||
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
|
||||
},
|
||||
|
||||
checkWishlist: (productId: number) => {
|
||||
return api.get<boolean>(`/wishlist/check?productId=${productId}`)
|
||||
checkWishlist: async (productId: number): Promise<boolean> => {
|
||||
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
|
||||
},
|
||||
|
||||
getWishlist: () => {
|
||||
return api.get<WishlistItem[]>('/wishlist/list')
|
||||
getWishlist: async (): Promise<WishlistItem[]> => {
|
||||
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -52,6 +52,7 @@ declare module 'vue' {
|
||||
ARadio: typeof import('ant-design-vue/es')['Radio']
|
||||
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
|
||||
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
|
||||
AResult: typeof import('ant-design-vue/es')['Result']
|
||||
ARow: typeof import('ant-design-vue/es')['Row']
|
||||
ASegmented: typeof import('ant-design-vue/es')['Segmented']
|
||||
ASelect: typeof import('ant-design-vue/es')['Select']
|
||||
@@ -75,7 +76,6 @@ declare module 'vue' {
|
||||
ElColorPicker: typeof import('element-plus/es')['ElColorPicker']
|
||||
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
|
||||
ElIcon: typeof import('element-plus/es')['ElIcon']
|
||||
ElTag: typeof import('element-plus/es')['ElTag']
|
||||
HelloWorld: typeof import('./components/HelloWorld.vue')['default']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
|
||||
@@ -98,7 +98,7 @@ const currentRoute = computed(() => {
|
||||
// 处理导航点击事件
|
||||
const handleNavClick = (tab: string) => {
|
||||
if (tab === 'home') {
|
||||
router.push('/')
|
||||
router.push('/home')
|
||||
} else if (tab === 'products') {
|
||||
router.push('/products')
|
||||
} else if (tab === 'cart') {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// API配置文件
|
||||
// 提取域名和端口,方便后续修改
|
||||
export const API_CONFIG = {
|
||||
domain: 'http://yunail.art',
|
||||
domain: 'http://127.0.0.1',
|
||||
port: '80',
|
||||
basePath: '/api',
|
||||
adminBasePath: '/admin/api'
|
||||
|
||||
@@ -13,19 +13,19 @@ const router = createRouter({
|
||||
path: '/home',
|
||||
name: 'home',
|
||||
component: () => import('../views/HomeView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/products',
|
||||
name: 'products',
|
||||
component: () => import('../views/ProductListView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/product/:id',
|
||||
name: 'product-detail',
|
||||
component: () => import('../views/ProductDetailView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/cart',
|
||||
@@ -43,7 +43,7 @@ const router = createRouter({
|
||||
path: '/shop/:id',
|
||||
name: 'shop-detail',
|
||||
component: () => import('../views/ShopDetailView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/wishlist',
|
||||
@@ -273,8 +273,6 @@ router.beforeEach((to, _from, next) => {
|
||||
next('/')
|
||||
} else if (to.path === '/' && token) {
|
||||
next('/home')
|
||||
} else if (to.path === '/home' && !token) {
|
||||
next('/')
|
||||
} else {
|
||||
// 对于需要认证的页面,验证token的有效性
|
||||
if (requiresAuth && token) {
|
||||
|
||||
+223
-10
@@ -180,30 +180,39 @@
|
||||
|
||||
<a-form-item
|
||||
v-if="activeTab === 'login'"
|
||||
label="选择店铺(可选)"
|
||||
name="shopId"
|
||||
label="选择登录店铺"
|
||||
>
|
||||
<a-select
|
||||
v-model:value="formData.shopId"
|
||||
placeholder="如需绑定店铺或首次手机号登录,请选择店铺"
|
||||
:placeholder="loginShopPlaceholder"
|
||||
size="large"
|
||||
:loading="loadingShops"
|
||||
:disabled="!allowLoginShopless && !loginShops.length"
|
||||
allow-clear
|
||||
>
|
||||
<a-select-option
|
||||
v-if="shops.length === 0"
|
||||
v-if="loginShops.length === 0"
|
||||
disabled
|
||||
value=""
|
||||
>
|
||||
暂无店铺数据
|
||||
{{ allowLoginShopless ? '当前无需选择店铺' : '暂无可用店铺' }}
|
||||
</a-select-option>
|
||||
<a-select-option
|
||||
v-for="shop in shops"
|
||||
v-for="shop in loginShops"
|
||||
:key="shop.id"
|
||||
:value="shop.id"
|
||||
:value="normalizeShopOptionValue(shop.id)"
|
||||
>
|
||||
{{ shop.shopName }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
<div
|
||||
v-if="loginShopMessage"
|
||||
class="field-status"
|
||||
:class="loginShops.length || allowLoginShopless ? 'success' : 'error'"
|
||||
>
|
||||
{{ loginShopMessage }}
|
||||
</div>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item
|
||||
@@ -251,7 +260,7 @@
|
||||
<a-select-option
|
||||
v-for="shop in shops"
|
||||
:key="shop.id"
|
||||
:value="shop.id"
|
||||
:value="normalizeShopOptionValue(shop.id)"
|
||||
>
|
||||
{{ shop.shopName }}
|
||||
</a-select-option>
|
||||
@@ -385,7 +394,12 @@ import { message } from 'ant-design-vue'
|
||||
import type { Rule } from 'ant-design-vue/es/form'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { shopApi } from '@/api/shop'
|
||||
import { userApi, type AvailabilityCheckResponse, type LoginAccountCheckResponse } from '@/api/user'
|
||||
import {
|
||||
userApi,
|
||||
type AvailabilityCheckResponse,
|
||||
type LoginAccountCheckResponse,
|
||||
type LoginShopSelectionResponse
|
||||
} from '@/api/user'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
@@ -394,10 +408,13 @@ const loginType = ref<'password' | 'phone'>('password')
|
||||
const loading = ref(false)
|
||||
const loadingShops = ref(false)
|
||||
const shops = ref<any[]>([])
|
||||
const loginShops = ref<Array<{ id: number | string; shopName: string }>>([])
|
||||
const countdown = ref(0)
|
||||
const loginAccountStatus = ref<LoginAccountCheckResponse | null>(null)
|
||||
const registerAccountStatus = ref<AvailabilityCheckResponse | null>(null)
|
||||
const registerPhoneStatus = ref<AvailabilityCheckResponse | null>(null)
|
||||
const loginShopMessage = ref('')
|
||||
const allowLoginShopless = ref(false)
|
||||
|
||||
const forgotPasswordVisible = ref(false)
|
||||
const forgotCountdown = ref(0)
|
||||
@@ -414,16 +431,33 @@ const formData = reactive({
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
nickname: '',
|
||||
shopId: undefined as number | undefined,
|
||||
shopId: undefined as string | undefined,
|
||||
phone: '',
|
||||
verificationCode: '',
|
||||
rememberMe: false
|
||||
})
|
||||
|
||||
let loginAccountCheckTimer: number | undefined
|
||||
let loginPhoneShopCheckTimer: number | undefined
|
||||
|
||||
const phoneRegex = /^1[3-9]\d{9}$/
|
||||
const verificationCodeRegex = /^\d{6}$/
|
||||
const loginShopPlaceholder = computed(() => {
|
||||
if (allowLoginShopless.value) {
|
||||
return '当前暂无启用店铺,可直接登录'
|
||||
}
|
||||
if (loadingShops.value) {
|
||||
return '正在加载可登录店铺'
|
||||
}
|
||||
return loginShops.value.length ? '请选择登录店铺' : '请先输入账号或手机号'
|
||||
})
|
||||
|
||||
const validateLoginShopRequired = async () => {
|
||||
if (allowLoginShopless.value || !loginShops.value.length || formData.shopId) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return Promise.reject('请选择登录店铺')
|
||||
}
|
||||
|
||||
const validatePassword = async (_rule: Rule, value: string) => {
|
||||
if (!value || value.length < 6) {
|
||||
@@ -489,6 +523,9 @@ const loginPasswordRules: Record<string, Rule[]> = {
|
||||
],
|
||||
password: [
|
||||
{ required: true, message: '请输入密码', trigger: 'blur' }
|
||||
],
|
||||
shopId: [
|
||||
{ validator: validateLoginShopRequired, trigger: 'change' }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -500,6 +537,9 @@ const loginPhoneRules: Record<string, Rule[]> = {
|
||||
verificationCode: [
|
||||
{ required: true, message: '请输入验证码', trigger: 'blur' },
|
||||
{ pattern: verificationCodeRegex, message: '验证码必须为 6 位数字', trigger: 'blur' }
|
||||
],
|
||||
shopId: [
|
||||
{ validator: validateLoginShopRequired, trigger: 'change' }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -545,6 +585,140 @@ const resetLoginAccountStatus = () => {
|
||||
loginAccountStatus.value = null
|
||||
}
|
||||
|
||||
const resetPhoneLoginShopCheck = () => {
|
||||
if (loginPhoneShopCheckTimer !== undefined) {
|
||||
window.clearTimeout(loginPhoneShopCheckTimer)
|
||||
loginPhoneShopCheckTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const resetLoginShopState = (clearSelectedShop = activeTab.value === 'login') => {
|
||||
resetPhoneLoginShopCheck()
|
||||
loginShops.value = []
|
||||
loginShopMessage.value = ''
|
||||
allowLoginShopless.value = false
|
||||
if (clearSelectedShop) {
|
||||
formData.shopId = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeShopOptionValue = (shopId?: string | number | null) => {
|
||||
if (shopId === undefined || shopId === null || shopId === '') {
|
||||
return undefined
|
||||
}
|
||||
return String(shopId)
|
||||
}
|
||||
|
||||
const isLoginShopPrefetchUnsupported = (error: unknown) => {
|
||||
const status = (error as any)?.response?.status
|
||||
return status === 404
|
||||
}
|
||||
|
||||
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
|
||||
loginShops.value = selection?.shops || []
|
||||
allowLoginShopless.value = Boolean(selection?.allowShoplessLogin)
|
||||
loginShopMessage.value = selection?.message || ''
|
||||
|
||||
if (allowLoginShopless.value) {
|
||||
formData.shopId = undefined
|
||||
return
|
||||
}
|
||||
|
||||
if (!loginShops.value.length) {
|
||||
formData.shopId = undefined
|
||||
return
|
||||
}
|
||||
|
||||
const currentShopId = normalizeShopOptionValue(formData.shopId)
|
||||
const matchedShop = loginShops.value.find(shop => normalizeShopOptionValue(shop.id) === currentShopId)
|
||||
if (matchedShop) {
|
||||
formData.shopId = normalizeShopOptionValue(matchedShop.id)
|
||||
return
|
||||
}
|
||||
|
||||
if (loginShops.value.length === 1) {
|
||||
const [onlyShop] = loginShops.value
|
||||
if (onlyShop) {
|
||||
formData.shopId = normalizeShopOptionValue(onlyShop.id)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
formData.shopId = undefined
|
||||
}
|
||||
|
||||
const loadLoginShopsByAccount = async (account = formData.account) => {
|
||||
const trimmedAccount = account.trim()
|
||||
if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) {
|
||||
resetLoginShopState()
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const selection = await userApi.getLoginShopsByAccount(trimmedAccount) as unknown as LoginShopSelectionResponse
|
||||
if (
|
||||
activeTab.value === 'login'
|
||||
&& loginType.value === 'password'
|
||||
&& formData.account.trim() === trimmedAccount
|
||||
) {
|
||||
applyLoginShopSelection(selection)
|
||||
}
|
||||
return selection
|
||||
} catch (error) {
|
||||
if (formData.account.trim() === trimmedAccount) {
|
||||
if (isLoginShopPrefetchUnsupported(error)) {
|
||||
applyLoginShopSelection({
|
||||
allowShoplessLogin: true,
|
||||
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
|
||||
shops: []
|
||||
})
|
||||
} else {
|
||||
resetLoginShopState()
|
||||
}
|
||||
}
|
||||
if (!isLoginShopPrefetchUnsupported(error)) {
|
||||
console.error('登录店铺查询失败:', error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const loadLoginShopsByPhone = async (phone = formData.phone) => {
|
||||
const trimmedPhone = phone.trim()
|
||||
if (activeTab.value !== 'login' || loginType.value !== 'phone' || !phoneRegex.test(trimmedPhone)) {
|
||||
resetLoginShopState()
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const selection = await userApi.getLoginShopsByPhone(trimmedPhone) as unknown as LoginShopSelectionResponse
|
||||
if (
|
||||
activeTab.value === 'login'
|
||||
&& loginType.value === 'phone'
|
||||
&& formData.phone.trim() === trimmedPhone
|
||||
) {
|
||||
applyLoginShopSelection(selection)
|
||||
}
|
||||
return selection
|
||||
} catch (error) {
|
||||
if (formData.phone.trim() === trimmedPhone) {
|
||||
if (isLoginShopPrefetchUnsupported(error)) {
|
||||
applyLoginShopSelection({
|
||||
allowShoplessLogin: true,
|
||||
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
|
||||
shops: []
|
||||
})
|
||||
} else {
|
||||
resetLoginShopState()
|
||||
}
|
||||
}
|
||||
if (!isLoginShopPrefetchUnsupported(error)) {
|
||||
console.error('手机号登录店铺查询失败:', error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const checkLoginAccountAvailability = async (account = formData.account) => {
|
||||
const trimmedAccount = account.trim()
|
||||
if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) {
|
||||
@@ -818,6 +992,20 @@ const handleAdminLogin = () => {
|
||||
|
||||
watch([activeTab, loginType], () => {
|
||||
resetLoginAccountStatus()
|
||||
resetLoginShopState(activeTab.value === 'login')
|
||||
if (activeTab.value !== 'login') {
|
||||
return
|
||||
}
|
||||
if (loginType.value === 'password' && formData.account.trim()) {
|
||||
void Promise.all([
|
||||
checkLoginAccountAvailability(formData.account.trim()),
|
||||
loadLoginShopsByAccount(formData.account.trim())
|
||||
])
|
||||
return
|
||||
}
|
||||
if (loginType.value === 'phone' && phoneRegex.test(formData.phone.trim())) {
|
||||
void loadLoginShopsByPhone(formData.phone.trim())
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
@@ -835,7 +1023,31 @@ watch(
|
||||
|
||||
loginAccountCheckTimer = window.setTimeout(() => {
|
||||
loginAccountCheckTimer = undefined
|
||||
void checkLoginAccountAvailability(trimmedAccount)
|
||||
void Promise.all([
|
||||
checkLoginAccountAvailability(trimmedAccount),
|
||||
loadLoginShopsByAccount(trimmedAccount)
|
||||
])
|
||||
}, 400)
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => formData.phone,
|
||||
value => {
|
||||
if (activeTab.value !== 'login' || loginType.value !== 'phone') {
|
||||
return
|
||||
}
|
||||
|
||||
resetPhoneLoginShopCheck()
|
||||
const trimmedPhone = value.trim()
|
||||
if (!phoneRegex.test(trimmedPhone)) {
|
||||
resetLoginShopState()
|
||||
return
|
||||
}
|
||||
|
||||
loginPhoneShopCheckTimer = window.setTimeout(() => {
|
||||
loginPhoneShopCheckTimer = undefined
|
||||
void loadLoginShopsByPhone(trimmedPhone)
|
||||
}, 400)
|
||||
}
|
||||
)
|
||||
@@ -846,6 +1058,7 @@ onMounted(() => {
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resetLoginAccountStatus()
|
||||
resetPhoneLoginShopCheck()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
+400
-85
@@ -5,15 +5,36 @@
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
</a-button>
|
||||
<h1>购物车</h1>
|
||||
<a-button type="text">编辑</a-button>
|
||||
<a-button type="text" @click="editing = !editing">
|
||||
{{ editing ? '完成' : '批量删除' }}
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<a-empty v-if="!cartItems.length" description="购物车是空的">
|
||||
<a-button type="primary" @click="router.push('/products')">去逛逛</a-button>
|
||||
<a-empty v-if="!cartItems.length" description="购物车还是空的">
|
||||
<a-button type="primary" @click="router.push('/products')">去逛作品</a-button>
|
||||
</a-empty>
|
||||
|
||||
<a-card v-for="item in cartItems" :key="item.id" class="item-card">
|
||||
<a-alert
|
||||
v-if="selectedCount && checkoutIssues.length && !editing"
|
||||
class="issue-alert"
|
||||
type="warning"
|
||||
show-icon
|
||||
:message="`还有 ${checkoutIssues.length} 项待完善`"
|
||||
:description="checkoutIssues.map(issue => issue.message).join(';')"
|
||||
>
|
||||
<template #action>
|
||||
<a-button size="small" @click="focusFirstIssue">定位问题</a-button>
|
||||
</template>
|
||||
</a-alert>
|
||||
|
||||
<a-card
|
||||
v-for="item in cartItems"
|
||||
:key="item.id"
|
||||
:ref="element => setItemRef(item.id, element)"
|
||||
class="item-card"
|
||||
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
|
||||
>
|
||||
<div class="item-row">
|
||||
<a-checkbox v-model:checked="item.selected" @change="loadAvailableCoupons" />
|
||||
<div class="thumb" @click="openProduct(item)">
|
||||
@@ -22,15 +43,19 @@
|
||||
</div>
|
||||
<div class="item-main">
|
||||
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
|
||||
<div class="price">¥{{ item.price.toFixed(2) }}</div>
|
||||
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
|
||||
|
||||
<div class="selector" @click="openBookingModal(item)">
|
||||
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
|
||||
<span class="label">美甲师</span>
|
||||
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
|
||||
<RightOutlined />
|
||||
</div>
|
||||
|
||||
<div class="selector" @click="openBookingModal(item)">
|
||||
<div
|
||||
class="selector"
|
||||
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
|
||||
@click="openBookingModal(item)"
|
||||
>
|
||||
<span class="label">预约时间</span>
|
||||
<span class="value">
|
||||
{{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }}
|
||||
@@ -46,7 +71,7 @@
|
||||
<span>{{ item.quantity }}</span>
|
||||
<a-button size="small" :disabled="item.quantity >= 99" @click="changeQuantity(item, 1)">+</a-button>
|
||||
</div>
|
||||
<a-popconfirm title="确定删除吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
|
||||
<a-popconfirm title="确认删除这件作品吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
|
||||
<a-button type="text" danger size="small">
|
||||
<DeleteOutlined />
|
||||
</a-button>
|
||||
@@ -56,37 +81,56 @@
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="selectedCount" class="coupon-card" @click="openCouponModal">
|
||||
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
|
||||
<div class="coupon-row">
|
||||
<span>优惠券</span>
|
||||
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '使用优惠券' }}</span>
|
||||
<span>优惠方式</span>
|
||||
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }}</span>
|
||||
</div>
|
||||
<div v-if="selectedCoupon" class="coupon-extra">
|
||||
<span>{{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }}</span>
|
||||
<strong>-¥{{ discountAmount.toFixed(2) }}</strong>
|
||||
</div>
|
||||
<div v-if="selectedCoupon" class="coupon-discount">优惠金额 -¥{{ discountAmount.toFixed(2) }}</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="cartItems.length" class="summary-card">
|
||||
<a-card v-if="cartItems.length && !editing" class="summary-card">
|
||||
<div class="summary-row"><span>选中项目</span><span>{{ selectedCount }} 项</span></div>
|
||||
<div class="summary-row"><span>作品数量</span><span>{{ totalQuantity }} 件</span></div>
|
||||
<div class="summary-row"><span>小计</span><span>¥{{ subtotal.toFixed(2) }}</span></div>
|
||||
<div v-if="selectedCoupon" class="summary-row"><span>优惠</span><span>-¥{{ discountAmount.toFixed(2) }}</span></div>
|
||||
<div class="summary-row total"><span>总计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
|
||||
<div class="summary-row total"><span>合计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
|
||||
</a-card>
|
||||
</main>
|
||||
|
||||
<footer v-if="cartItems.length" class="footer">
|
||||
<a-button type="primary" size="large" block @click="checkout">
|
||||
结算 {{ selectedCount }} 个项目,预计金额 ¥{{ totalAmount.toFixed(2) }}
|
||||
<a-button
|
||||
v-if="editing"
|
||||
danger
|
||||
size="large"
|
||||
block
|
||||
@click="removeSelectedItems"
|
||||
>
|
||||
删除已选中的 {{ selectedCount }} 项
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
type="primary"
|
||||
size="large"
|
||||
block
|
||||
@click="checkout"
|
||||
>
|
||||
结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
|
||||
</a-button>
|
||||
</footer>
|
||||
|
||||
<a-modal v-model:open="showCouponModal" title="使用优惠券" @ok="applyCouponSelection" @cancel="showCouponModal = false">
|
||||
<a-modal v-model:open="showCouponModal" title="选择优惠方式" @ok="applyCouponSelection" @cancel="showCouponModal = false">
|
||||
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
|
||||
<a-radio :value="NO_COUPON_KEY">不使用优惠券</a-radio>
|
||||
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
|
||||
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
|
||||
{{ formatCouponDisplay(coupon) }}
|
||||
</a-radio>
|
||||
</a-radio-group>
|
||||
<div class="coupon-tip">
|
||||
系统只会默认预选 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
|
||||
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
|
||||
</div>
|
||||
</a-modal>
|
||||
|
||||
@@ -106,7 +150,7 @@
|
||||
<span>{{ artist.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<a-empty v-else description="暂无可用美甲师" />
|
||||
<a-empty v-else description="暂无可预约美甲师" />
|
||||
</div>
|
||||
|
||||
<div class="modal-section">
|
||||
@@ -173,8 +217,15 @@ interface CartItem {
|
||||
artist?: ArtistOption
|
||||
}
|
||||
|
||||
interface CheckoutIssue {
|
||||
key: string
|
||||
message: string
|
||||
itemId?: number
|
||||
}
|
||||
|
||||
const cartItems = ref<CartItem[]>([])
|
||||
const imageIdCache = ref<Record<string, string>>({})
|
||||
const itemRefs = ref<Record<number, HTMLElement>>({})
|
||||
const availableCoupons = ref<UserCoupon[]>([])
|
||||
const selectedCoupon = ref<UserCoupon | null>(null)
|
||||
const couponSelectionKey = ref(NO_COUPON_KEY)
|
||||
@@ -186,18 +237,19 @@ const availableArtists = ref<ArtistOption[]>([])
|
||||
const draftArtistId = ref<number>()
|
||||
const draftAppointmentTime = ref('')
|
||||
const currentShopHours = ref('')
|
||||
const editing = ref(false)
|
||||
|
||||
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
|
||||
const selectedCount = computed(() => selectedItems.value.length)
|
||||
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
|
||||
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0))
|
||||
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
|
||||
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
|
||||
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
|
||||
const bookingTitle = computed(() => currentItem.value ? '为 ' + currentItem.value.productTitle + ' 选择预约信息' : '选择预约信息')
|
||||
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
|
||||
const bookingHelperText = computed(() => {
|
||||
const texts: string[] = []
|
||||
if (currentShopHours.value) texts.push('门店营业时间:' + currentShopHours.value)
|
||||
if (currentItem.value?.approximateDuration) texts.push('预计时长:' + currentItem.value.approximateDuration)
|
||||
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
|
||||
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
|
||||
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
|
||||
})
|
||||
|
||||
@@ -216,16 +268,33 @@ const getDayBoundary = (date: Date) => {
|
||||
|
||||
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
|
||||
|
||||
const setItemRef = (itemId: number, element: unknown) => {
|
||||
if (element && (element as any).$el) {
|
||||
itemRefs.value[itemId] = (element as any).$el as HTMLElement
|
||||
return
|
||||
}
|
||||
if (element instanceof HTMLElement) {
|
||||
itemRefs.value[itemId] = element
|
||||
return
|
||||
}
|
||||
delete itemRefs.value[itemId]
|
||||
}
|
||||
|
||||
const formatCouponDisplay = (coupon: UserCoupon) => {
|
||||
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
|
||||
const benefit = coupon.couponType === 1
|
||||
? `${coupon.discountValue} 折`
|
||||
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
|
||||
return `${badge} ${coupon.couponName} ${benefit}`
|
||||
}
|
||||
|
||||
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
|
||||
if (!coupon || amount <= 0) {
|
||||
return 0
|
||||
}
|
||||
if (coupon.couponType === 1) {
|
||||
const discountValue = Number(coupon.discountValue || 0)
|
||||
if (!discountValue) {
|
||||
return 0
|
||||
}
|
||||
return amount - amount * discountValue / 10
|
||||
return discountValue ? amount - amount * discountValue / 10 : 0
|
||||
}
|
||||
if (coupon.couponType === 2) {
|
||||
return Number(coupon.reduceAmount || 0)
|
||||
@@ -233,27 +302,63 @@ const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
|
||||
return 0
|
||||
}
|
||||
|
||||
const formatCouponDisplay = (coupon: UserCoupon) => {
|
||||
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
|
||||
const benefit = coupon.couponType === 1
|
||||
? `${coupon.discountValue}折`
|
||||
: `满${coupon.minAmount}减${coupon.reduceAmount}`
|
||||
return `${badge} ${coupon.couponName} ${benefit}`
|
||||
}
|
||||
|
||||
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
|
||||
return coupons
|
||||
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
|
||||
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
|
||||
}
|
||||
|
||||
const openProduct = (item: CartItem) => {
|
||||
router.push('/product/' + item.productId)
|
||||
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
|
||||
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
|
||||
|
||||
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
|
||||
|
||||
const checkoutIssues = computed<CheckoutIssue[]>(() => {
|
||||
const items = selectedItems.value
|
||||
const issues: CheckoutIssue[] = []
|
||||
const firstMissingArtist = items.find(item => !item.artistId)
|
||||
if (firstMissingArtist) {
|
||||
issues.push({ key: 'artist', message: `请先为“${firstMissingArtist.productTitle}”选择美甲师`, itemId: firstMissingArtist.id })
|
||||
}
|
||||
|
||||
const firstMissingTime = items.find(item => !item.appointmentTime)
|
||||
if (firstMissingTime) {
|
||||
issues.push({ key: 'time', message: `请先为“${firstMissingTime.productTitle}”选择预约时间`, itemId: firstMissingTime.id })
|
||||
}
|
||||
|
||||
const firstExpiredTime = items.find(item => isPastAppointment(item.appointmentTime))
|
||||
if (firstExpiredTime) {
|
||||
issues.push({ key: 'expired', message: `“${firstExpiredTime.productTitle}”的预约时间已过期,请重新选择`, itemId: firstExpiredTime.id })
|
||||
}
|
||||
|
||||
if (new Set(items.map(item => item.shopId).filter(Boolean)).size > 1) {
|
||||
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
if (new Set(items.map(item => item.artistId).filter(Boolean)).size > 1) {
|
||||
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
return issues
|
||||
})
|
||||
|
||||
const scrollToIssue = (issue?: CheckoutIssue) => {
|
||||
if (!issue?.itemId) {
|
||||
return
|
||||
}
|
||||
const target = itemRefs.value[issue.itemId]
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}
|
||||
|
||||
const focusFirstIssue = () => {
|
||||
scrollToIssue(checkoutIssues.value[0])
|
||||
}
|
||||
|
||||
const loadCartItems = async () => {
|
||||
const response = await cartApi.getCartList() as unknown as any[]
|
||||
cartItems.value = response.map(item => ({
|
||||
cartItems.value = (response || []).map(item => ({
|
||||
...item,
|
||||
selected: true,
|
||||
originalProductImage: item.productImage,
|
||||
@@ -263,6 +368,7 @@ const loadCartItems = async () => {
|
||||
couponSelectionTouched.value = false
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
selectedCoupon.value = null
|
||||
editing.value = false
|
||||
await Promise.all([loadProductImages(), loadAvailableCoupons()])
|
||||
}
|
||||
|
||||
@@ -284,6 +390,10 @@ const loadProductImages = async () => {
|
||||
}
|
||||
|
||||
const loadAvailableCoupons = async () => {
|
||||
if (editing.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
|
||||
const selectedShopId = selectedItems.value[0]?.shopId
|
||||
|
||||
@@ -330,7 +440,7 @@ const loadAvailableCoupons = async () => {
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取可用优惠券失败:', error)
|
||||
console.error('获取可用优惠失败:', error)
|
||||
availableCoupons.value = []
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
@@ -361,6 +471,26 @@ const removeItem = async (item: CartItem) => {
|
||||
}
|
||||
}
|
||||
|
||||
const removeSelectedItems = async () => {
|
||||
if (!selectedItems.value.length) {
|
||||
message.warning('请先勾选要删除的作品')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all(selectedItems.value.map(item => cartApi.removeFromCart(item.productId)))
|
||||
await Promise.all([loadCartItems(), updateCartCount()])
|
||||
message.success('已删除选中的作品')
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error)
|
||||
message.error('批量删除失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const openProduct = (item: CartItem) => {
|
||||
router.push('/product/' + item.productId)
|
||||
}
|
||||
|
||||
const openBookingModal = async (item: CartItem) => {
|
||||
currentItem.value = item
|
||||
draftArtistId.value = item.artistId
|
||||
@@ -374,7 +504,13 @@ const loadArtists = async (item: CartItem) => {
|
||||
const allowedIds = new Set((item.bookableArtists || '').split(',').map(id => Number(id.trim())).filter(id => Number.isFinite(id) && id > 0))
|
||||
availableArtists.value = await Promise.all(
|
||||
users
|
||||
.filter(user => (!item.shopId || user.shopId === item.shopId) && (!allowedIds.size || allowedIds.has(user.id)))
|
||||
.filter(user => user.status === 1)
|
||||
.filter(user => {
|
||||
const matchedShop = !item.shopId
|
||||
|| user.shopId === item.shopId
|
||||
|| (Array.isArray((user as any).shopIds) && (user as any).shopIds.some((shopId: string | number) => String(shopId) === String(item.shopId)))
|
||||
return matchedShop && (!allowedIds.size || allowedIds.has(user.id))
|
||||
})
|
||||
.map(async user => {
|
||||
try {
|
||||
const detail = await api.get('/nail-artist/get/' + user.id) as any
|
||||
@@ -397,14 +533,11 @@ const loadShopHours = async (shopId?: number) => {
|
||||
}
|
||||
}
|
||||
|
||||
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
|
||||
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
|
||||
const disablePastAppointmentDate = (current: any) => {
|
||||
if (!current) {
|
||||
return false
|
||||
}
|
||||
if (!current) return false
|
||||
return current.valueOf() < getDayBoundary(new Date())
|
||||
}
|
||||
|
||||
const disablePastAppointmentTime = (current: any) => {
|
||||
if (!current || typeof current.format !== 'function') {
|
||||
return {}
|
||||
@@ -466,12 +599,16 @@ const applyCouponSelection = () => {
|
||||
|
||||
const checkout = async () => {
|
||||
const items = selectedItems.value
|
||||
if (!items.length) return message.warning('请先选择要结算的作品')
|
||||
if (items.some(item => !item.artistId)) return message.warning('请先为所有项目选择美甲师')
|
||||
if (items.some(item => !item.appointmentTime)) return message.warning('请先为所有项目选择预约时间')
|
||||
if (items.some(item => isPastAppointment(item.appointmentTime))) return message.warning('存在已过期的预约时间,请重新选择')
|
||||
if (new Set(items.map(item => item.shopId).filter(Boolean)).size > 1) return message.warning('跨店铺商品请分开结算')
|
||||
if (new Set(items.map(item => item.artistId).filter(Boolean)).size > 1) return message.warning('不同美甲师的项目请分开结算')
|
||||
if (!items.length) {
|
||||
return message.warning('请先选择要结算的作品')
|
||||
}
|
||||
|
||||
const firstIssue = checkoutIssues.value[0]
|
||||
if (firstIssue) {
|
||||
message.warning(firstIssue.message)
|
||||
scrollToIssue(firstIssue)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await orderApi.createOrder({
|
||||
@@ -510,41 +647,219 @@ onMounted(async () => {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page { min-height: 100vh; padding-top: 60px; background: #f5f5f5; }
|
||||
.header, .footer { position: fixed; left: 0; right: 0; background: #fff; z-index: 10; }
|
||||
.header { top: 0; display: flex; align-items: center; justify-content: space-between; padding: 10px 15px; border-bottom: 1px solid #f0f0f0; }
|
||||
.header h1 { margin: 0; font-size: 18px; }
|
||||
.content { padding: 15px; padding-bottom: 140px; }
|
||||
.item-card, .coupon-card, .summary-card { margin-bottom: 12px; border-radius: 12px; }
|
||||
.item-row { display: flex; gap: 12px; align-items: flex-start; }
|
||||
.thumb { width: 80px; height: 80px; border-radius: 8px; overflow: hidden; background: #eef3ff; display: flex; align-items: center; justify-content: center; cursor: pointer; }
|
||||
.thumb img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.item-main { flex: 1; }
|
||||
.title { font-weight: 600; cursor: pointer; }
|
||||
.price { margin: 4px 0 10px; color: #ff4d4f; font-weight: 700; }
|
||||
.selector { display: flex; align-items: center; gap: 8px; padding: 10px 12px; margin-bottom: 10px; border-radius: 8px; background: #f8f9ff; cursor: pointer; }
|
||||
.selector .label { min-width: 56px; color: #666; font-size: 13px; }
|
||||
.selector .value { flex: 1; color: #1890ff; font-size: 13px; }
|
||||
.actions, .qty, .coupon-row, .summary-row { display: flex; align-items: center; justify-content: space-between; }
|
||||
.qty { gap: 8px; }
|
||||
.duration, .coupon-discount, .helper, .coupon-tip { color: #666; font-size: 12px; }
|
||||
.coupon-tip { margin-top: 12px; line-height: 1.6; }
|
||||
.summary-row.total { font-weight: 700; }
|
||||
.footer { bottom: 60px; padding: 15px; border-top: 1px solid #f0f0f0; box-shadow: 0 -2px 8px rgba(0,0,0,.06); }
|
||||
.coupon-options { display: flex; flex-direction: column; gap: 8px; }
|
||||
.modal-section + .modal-section { margin-top: 16px; }
|
||||
.section-title { margin-bottom: 8px; font-weight: 600; }
|
||||
.artist-list { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.artist-option { display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; border: 1px solid #d9d9d9; border-radius: 999px; background: #fff; cursor: pointer; }
|
||||
.artist-option.active { border-color: #1890ff; color: #1890ff; background: #f0f9ff; }
|
||||
.artist-option img { width: 24px; height: 24px; border-radius: 50%; object-fit: cover; }
|
||||
.time-picker { border-radius: 8px; }
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding-top: 60px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.header,
|
||||
.footer {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: #fff;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.header {
|
||||
top: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 15px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.content {
|
||||
max-width: 980px;
|
||||
margin: 0 auto;
|
||||
padding: 16px 16px 140px;
|
||||
}
|
||||
|
||||
.issue-alert {
|
||||
margin-bottom: 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.item-card,
|
||||
.coupon-card,
|
||||
.summary-card {
|
||||
margin-bottom: 12px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.issue-card {
|
||||
border-color: #faad14;
|
||||
box-shadow: 0 8px 24px rgba(250, 173, 20, 0.12);
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.thumb {
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: #eef3ff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.item-main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.price {
|
||||
margin: 6px 0 10px;
|
||||
color: #ff4d4f;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
background: #f8f9ff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.selector.issue {
|
||||
border-color: #faad14;
|
||||
background: #fff7e6;
|
||||
}
|
||||
|
||||
.selector .label {
|
||||
min-width: 56px;
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.selector .value {
|
||||
flex: 1;
|
||||
color: #1677ff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.duration,
|
||||
.coupon-tip,
|
||||
.helper {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.actions,
|
||||
.qty,
|
||||
.coupon-row,
|
||||
.summary-row,
|
||||
.coupon-extra {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.qty {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.coupon-extra {
|
||||
margin-top: 10px;
|
||||
color: #666;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.summary-row {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-row.total {
|
||||
margin-bottom: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.footer {
|
||||
bottom: 60px;
|
||||
padding: 15px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.coupon-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.modal-section + .modal-section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin-bottom: 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.artist-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.artist-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.artist-option.active {
|
||||
border-color: #1677ff;
|
||||
color: #1677ff;
|
||||
background: #f0f9ff;
|
||||
}
|
||||
|
||||
.artist-option img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.content {
|
||||
max-width: 980px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 24px 140px;
|
||||
padding: 15px 15px 140px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
+374
-421
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,5 @@
|
||||
<template>
|
||||
<div class="mobile-container">
|
||||
|
||||
<!-- 头部区域 -->
|
||||
<header class="header">
|
||||
<a-button class="back-btn" type="text" @click="handleBackClick">
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
@@ -12,8 +10,8 @@
|
||||
v-model:value="searchKeyword"
|
||||
placeholder="搜索作品"
|
||||
class="search-input"
|
||||
@search="handleSearch"
|
||||
enter-button
|
||||
@search="handleSearch"
|
||||
/>
|
||||
</div>
|
||||
<a-button class="search-btn" type="text" @click="toggleSearch">
|
||||
@@ -21,12 +19,10 @@
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<!-- 主内容区域 -->
|
||||
<div class="main-content">
|
||||
<!-- 左侧分类边栏 -->
|
||||
<div class="category-sidebar">
|
||||
<div
|
||||
v-for="category in categories"
|
||||
<div
|
||||
v-for="category in categories"
|
||||
:key="category"
|
||||
class="category-item"
|
||||
:class="{ active: selectedCategory === category }"
|
||||
@@ -36,9 +32,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧作品区域 -->
|
||||
<div class="product-section">
|
||||
<!-- 作品网格 -->
|
||||
<a-alert
|
||||
v-if="activeBannerText"
|
||||
class="page-banner"
|
||||
type="info"
|
||||
show-icon
|
||||
:message="activeBannerText"
|
||||
/>
|
||||
|
||||
<div class="product-grid">
|
||||
<a-card
|
||||
v-for="item in products"
|
||||
@@ -48,85 +50,53 @@
|
||||
hoverable
|
||||
@click="handleProductClick(item)"
|
||||
>
|
||||
<!-- 作品图片 -->
|
||||
<div class="product-img">
|
||||
<img
|
||||
v-if="getProductImages(item) && getProductImages(item).length > 0"
|
||||
:src="getProductImages(item)[0]"
|
||||
<img
|
||||
v-if="getProductImages(item).length > 0"
|
||||
:src="getProductImages(item)[0]"
|
||||
:alt="item.title || item.name"
|
||||
class="product-image"
|
||||
/>
|
||||
<div v-else class="product-img-placeholder">
|
||||
<span>{{ (item.title || item.name) ? (item.title || item.name)[0] : '商' }}</span>
|
||||
<span>{{ (item.title || item.name)?.[0] || '作' }}</span>
|
||||
</div>
|
||||
<a-badge
|
||||
v-if="item.category"
|
||||
:text="item.category"
|
||||
color="#ff4d4f"
|
||||
class="product-tag"
|
||||
/>
|
||||
</div>
|
||||
<!-- 作品信息 -->
|
||||
|
||||
<div class="product-info">
|
||||
<p class="name">{{ item.title || item.name }}</p>
|
||||
<div class="product-meta">
|
||||
<span class="duration">{{ item.approximateDuration || '0分钟' }}</span>
|
||||
<span class="duration">{{ item.approximateDuration || '时长待定' }}</span>
|
||||
<div class="stats">
|
||||
<span class="like-count">{{ item.likeCount || 0 }} 赞</span>
|
||||
<span class="collect-count">{{ item.collectCount || 0 }} 收藏</span>
|
||||
<span>{{ item.likeCount || 0 }} 点赞</span>
|
||||
<span>{{ item.collectCount || 0 }} 收藏</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 标签展示 -->
|
||||
|
||||
<div class="product-tags">
|
||||
<template v-if="item.tagInfos && item.tagInfos.length > 0">
|
||||
<a-tag
|
||||
<template v-if="item.tagInfos?.length">
|
||||
<a-tag
|
||||
v-for="tag in item.tagInfos"
|
||||
:key="tag.id"
|
||||
size="small"
|
||||
:style="{
|
||||
marginRight: '4px',
|
||||
marginRight: '4px',
|
||||
marginBottom: '4px',
|
||||
fontSize: '9px',
|
||||
padding: '1px 6px',
|
||||
color: tag.textColor || '#333333',
|
||||
backgroundColor: tag.bgColor || '#F0F0F0',
|
||||
borderColor: tag.borderColor || '#F0F0F0',
|
||||
borderWidth: '1px',
|
||||
borderStyle: 'solid',
|
||||
borderRadius: '8px'
|
||||
color: tag.textColor || '#333',
|
||||
backgroundColor: tag.bgColor || '#f0f0f0',
|
||||
borderColor: tag.borderColor || '#f0f0f0'
|
||||
}"
|
||||
>
|
||||
{{ tag.tagName }}
|
||||
</a-tag>
|
||||
</template>
|
||||
<template v-else-if="item.category">
|
||||
<a-tag
|
||||
size="small"
|
||||
:style="{
|
||||
marginRight: '4px',
|
||||
marginBottom: '4px',
|
||||
fontSize: '9px',
|
||||
padding: '1px 6px',
|
||||
color: '#333333',
|
||||
backgroundColor: '#F0F0F0',
|
||||
borderColor: '#F0F0F0',
|
||||
borderWidth: '1px',
|
||||
borderStyle: 'solid',
|
||||
borderRadius: '8px'
|
||||
}"
|
||||
>
|
||||
{{ item.category }}
|
||||
</a-tag>
|
||||
</template>
|
||||
<a-tag v-else size="small" color="gray" style="font-size: 10px; padding: 2px 6px">
|
||||
无标签
|
||||
</a-tag>
|
||||
<a-tag v-else size="small" color="default">暂无标签</a-tag>
|
||||
</div>
|
||||
|
||||
<div class="price-row">
|
||||
<p class="price">¥{{ item.price }}</p>
|
||||
<a-button
|
||||
type="primary"
|
||||
size="small"
|
||||
<p class="price">¥{{ Number(item.price || 0).toFixed(2) }}</p>
|
||||
<a-button
|
||||
type="primary"
|
||||
size="small"
|
||||
shape="circle"
|
||||
@click.stop="handleAddToCart(item)"
|
||||
>
|
||||
@@ -137,17 +107,14 @@
|
||||
</a-card>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-if="products.length === 0 && !loading" class="empty-state">
|
||||
<a-typography-text type="secondary">商家暂未上架更多作品</a-typography-text>
|
||||
<a-empty description="暂时没有匹配的作品">
|
||||
<a-button type="primary" @click="resetFilters">查看全部作品</a-button>
|
||||
</a-empty>
|
||||
</div>
|
||||
|
||||
<!-- 加载更多 -->
|
||||
<div v-else-if="products.length > 0" class="load-more">
|
||||
<a-button v-if="hasMore" type="link" @click="handleLoadMore">
|
||||
加载更多 <DownOutlined />
|
||||
</a-button>
|
||||
<a-typography-text v-else type="secondary">没有更多作品了</a-typography-text>
|
||||
<div v-if="loading" class="loading-state">
|
||||
<a-spin />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -155,198 +122,192 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, inject } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import {
|
||||
LeftOutlined,
|
||||
SearchOutlined,
|
||||
ShoppingCartOutlined,
|
||||
DownOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { onMounted, ref, watch, inject, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { LeftOutlined, SearchOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { productApi, type ProductVO } from '@/api/product'
|
||||
import { tagApi, type TagVO } from '@/api/tag'
|
||||
import { cartApi } from '@/api/cart'
|
||||
import { fileApi } from '@/api/file'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
|
||||
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
// 标签列表
|
||||
const allTags = ref<TagVO[]>([])
|
||||
|
||||
// 当前选中的分类
|
||||
const selectedCategory = ref('全部')
|
||||
|
||||
// 分类列表(动态从标签获取)
|
||||
const categories = ref<string[]>(['全部'])
|
||||
|
||||
// 作品数据
|
||||
const selectedCategory = ref('全部')
|
||||
const products = ref<ProductVO[]>([])
|
||||
|
||||
// 是否还有更多数据
|
||||
const hasMore = ref(true)
|
||||
|
||||
// 加载状态
|
||||
const loading = ref(false)
|
||||
|
||||
// 搜索相关状态
|
||||
const showSearch = ref(false)
|
||||
const searchKeyword = ref('')
|
||||
const isSearching = ref(false)
|
||||
|
||||
// 图片ID缓存
|
||||
const imageIdCache = ref<Record<string, string>>({})
|
||||
const imageUrls = ref<Record<number, string[]>>({})
|
||||
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
|
||||
|
||||
// 从后端获取标签列表
|
||||
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
|
||||
const activeBannerText = computed(() => {
|
||||
if (searchKeyword.value.trim()) {
|
||||
return `当前显示“${searchKeyword.value.trim()}”的搜索结果`
|
||||
}
|
||||
if (selectedCategory.value !== '全部') {
|
||||
return `当前按标签“${selectedCategory.value}”筛选`
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCBmaWxsPSIjZjVmNWY1IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmaWxsPSIjYmZiZmJmIiBmb250LXNpemU9IjI0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+YWFhPC90ZXh0Pjwvc3ZnPg=='
|
||||
|
||||
const ensureLoginForAction = (actionText: string) => {
|
||||
if (isLoggedIn.value) {
|
||||
return true
|
||||
}
|
||||
message.info(`${actionText}前请先登录账号`)
|
||||
router.push('/')
|
||||
return false
|
||||
}
|
||||
|
||||
const loadImageUrls = async (productList: ProductVO[]) => {
|
||||
for (const product of productList) {
|
||||
if (!product.imageFileIds) {
|
||||
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
|
||||
continue
|
||||
}
|
||||
|
||||
const ids = product.imageFileIds.split(',').map(id => id.trim()).filter(Boolean)
|
||||
const urls: string[] = []
|
||||
|
||||
for (const id of ids) {
|
||||
try {
|
||||
if (!imageIdCache.value[id]) {
|
||||
imageIdCache.value[id] = await fileApi.getSignedUrl(Number(id)) as unknown as string
|
||||
}
|
||||
if (imageIdCache.value[id]) {
|
||||
urls.push(imageIdCache.value[id])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取作品图片失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
imageUrls.value[product.id] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
|
||||
}
|
||||
}
|
||||
|
||||
const getProductImages = (product: ProductVO): string[] => imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
|
||||
|
||||
const fetchTags = async () => {
|
||||
try {
|
||||
const response = await tagApi.getAllTags() as any
|
||||
allTags.value = response || []
|
||||
const response = await tagApi.getAllTags() as unknown as TagVO[]
|
||||
allTags.value = Array.isArray(response) ? response : []
|
||||
categories.value = ['全部', ...allTags.value.map(tag => tag.tagName)]
|
||||
} catch (error) {
|
||||
console.error('获取标签失败:', error)
|
||||
categories.value = ['全部']
|
||||
}
|
||||
}
|
||||
|
||||
// 加载作品列表
|
||||
const loadImageUrls = async (productList: ProductVO[]) => {
|
||||
for (const product of productList) {
|
||||
if (product.imageFileIds) {
|
||||
const ids = product.imageFileIds.split(',')
|
||||
const urls: string[] = []
|
||||
|
||||
for (const id of ids) {
|
||||
if (id) {
|
||||
try {
|
||||
if (!imageIdCache.value[id]) {
|
||||
const response = await fileApi.getSignedUrl(Number(id)) as any
|
||||
imageIdCache.value[id] = response
|
||||
}
|
||||
if (imageIdCache.value[id]) {
|
||||
urls.push(imageIdCache.value[id] as string)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取签名链接失败:', error)
|
||||
urls.push(DEFAULT_PRODUCT_IMAGE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
imageUrls.value[product.id] = urls
|
||||
} else {
|
||||
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getProductImages = (product: ProductVO): string[] => {
|
||||
return imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
|
||||
}
|
||||
|
||||
// 从后端获取作品数据
|
||||
const fetchProducts = async () => {
|
||||
if (loading.value) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
let response: any
|
||||
|
||||
if (selectedCategory.value === '全部') {
|
||||
response = await productApi.getAllProducts() as any
|
||||
let response: ProductVO[] = []
|
||||
const keyword = searchKeyword.value.trim()
|
||||
|
||||
if (keyword) {
|
||||
response = await productApi.searchProducts(keyword)
|
||||
} else if (selectedCategory.value === '全部') {
|
||||
response = await productApi.getAllProducts()
|
||||
} else {
|
||||
response = await productApi.getProductsByTag(selectedCategory.value) as any
|
||||
response = await productApi.getProductsByTag(selectedCategory.value)
|
||||
}
|
||||
|
||||
products.value = response || []
|
||||
|
||||
|
||||
products.value = Array.isArray(response) ? response : []
|
||||
await loadImageUrls(products.value)
|
||||
|
||||
hasMore.value = false
|
||||
} catch (error) {
|
||||
message.error('未登录,请先登录')
|
||||
console.error('获取作品列表失败:', error)
|
||||
message.error('加载作品列表失败,请稍后重试')
|
||||
products.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const syncRouteFilters = async () => {
|
||||
const keyword = typeof route.query.keyword === 'string' ? route.query.keyword.trim() : ''
|
||||
const tag = typeof route.query.tag === 'string' ? route.query.tag.trim() : ''
|
||||
|
||||
searchKeyword.value = keyword
|
||||
showSearch.value = Boolean(keyword)
|
||||
selectedCategory.value = tag && categories.value.includes(tag) ? tag : '全部'
|
||||
await fetchProducts()
|
||||
}
|
||||
|
||||
// 处理返回按钮点击
|
||||
const handleBackClick = () => {
|
||||
router.push('/')
|
||||
router.push('/home')
|
||||
}
|
||||
|
||||
// 处理分类点击
|
||||
const handleCategoryClick = (category: string) => {
|
||||
selectedCategory.value = category
|
||||
showSearch.value = false
|
||||
searchKeyword.value = ''
|
||||
isSearching.value = false
|
||||
fetchProducts()
|
||||
showSearch.value = false
|
||||
router.replace({
|
||||
path: '/products',
|
||||
query: category === '全部' ? {} : { tag: category }
|
||||
})
|
||||
}
|
||||
|
||||
// 处理作品卡片点击
|
||||
const handleProductClick = (item: any) => {
|
||||
const handleProductClick = (item: ProductVO) => {
|
||||
router.push(`/product/${item.id}`)
|
||||
}
|
||||
|
||||
// 处理添加到购物车
|
||||
const handleAddToCart = async (item: any) => {
|
||||
const handleAddToCart = async (item: ProductVO) => {
|
||||
if (!ensureLoginForAction('加入购物车')) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await cartApi.addToCart({ productId: item.id, quantity: 1 })
|
||||
await updateCartCount()
|
||||
message.success(`已将 ${item.title || item.name || '作品'} 添加到购物车`)
|
||||
message.success(`已将 ${item.title || item.name || '作品'} 加入购物车`)
|
||||
} catch (error) {
|
||||
message.error('添加到购物车失败,请重试')
|
||||
console.error('加入购物车失败:', error)
|
||||
message.error('加入购物车失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
// 处理加载更多
|
||||
const handleLoadMore = () => {
|
||||
// 这里可以添加加载更多逻辑
|
||||
hasMore.value = false
|
||||
const handleSearch = () => {
|
||||
const keyword = searchKeyword.value.trim()
|
||||
router.replace({
|
||||
path: '/products',
|
||||
query: keyword ? { keyword } : {}
|
||||
})
|
||||
}
|
||||
|
||||
// 切换搜索框显示/隐藏
|
||||
const toggleSearch = () => {
|
||||
showSearch.value = !showSearch.value
|
||||
if (!showSearch.value) {
|
||||
searchKeyword.value = ''
|
||||
isSearching.value = false
|
||||
fetchProducts() // 重置为默认作品列表
|
||||
router.replace({ path: '/products', query: selectedCategory.value === '全部' ? {} : { tag: selectedCategory.value } })
|
||||
}
|
||||
}
|
||||
|
||||
// 处理搜索操作
|
||||
const handleSearch = async () => {
|
||||
if (!searchKeyword.value.trim()) {
|
||||
message.info('请输入搜索关键词')
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await productApi.searchProducts(searchKeyword.value.trim()) as any
|
||||
products.value = response || []
|
||||
await loadImageUrls(products.value)
|
||||
hasMore.value = false
|
||||
isSearching.value = true
|
||||
} catch (error) {
|
||||
message.error('搜索失败,请重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
const resetFilters = () => {
|
||||
selectedCategory.value = '全部'
|
||||
searchKeyword.value = ''
|
||||
showSearch.value = false
|
||||
router.replace('/products')
|
||||
}
|
||||
|
||||
// 页面挂载时获取标签和作品数据
|
||||
watch(
|
||||
() => route.query,
|
||||
async () => {
|
||||
await syncRouteFilters()
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchTags()
|
||||
fetchProducts()
|
||||
await syncRouteFilters()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -373,9 +334,9 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.back-btn,
|
||||
@@ -392,23 +353,16 @@ onMounted(async () => {
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 主内容区域 */
|
||||
.main-content {
|
||||
display: flex;
|
||||
height: calc(100vh - 60px);
|
||||
overflow: hidden;
|
||||
min-height: calc(100vh - 60px);
|
||||
}
|
||||
|
||||
/* 左侧分类边栏 */
|
||||
.category-sidebar {
|
||||
width: 90px;
|
||||
background: #f8f8f8;
|
||||
width: 92px;
|
||||
background: #fafafa;
|
||||
border-right: 1px solid #ececec;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #e8e8e8;
|
||||
}
|
||||
|
||||
.category-item {
|
||||
@@ -417,60 +371,44 @@ onMounted(async () => {
|
||||
color: #666;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
transition: all 0.2s ease;
|
||||
border-left: 3px solid transparent;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.category-item:hover {
|
||||
background: #e8e8e8;
|
||||
color: #1890ff;
|
||||
}
|
||||
|
||||
.category-item.active {
|
||||
color: #1677ff;
|
||||
background: white;
|
||||
color: #1890ff;
|
||||
border-left-color: #1890ff;
|
||||
font-weight: 600;
|
||||
border-left-color: #1677ff;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 右侧作品区域 */
|
||||
.product-section {
|
||||
flex: 1;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.page-banner {
|
||||
margin-bottom: 16px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.product-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
padding: 0 20px;
|
||||
gap: 15px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.product-card {
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s, box-shadow 0.3s;
|
||||
}
|
||||
|
||||
.product-card:hover {
|
||||
transform: translateY(-4px);
|
||||
}
|
||||
|
||||
.product-card :deep(.ant-card-body) {
|
||||
padding: 12px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.product-img {
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 12px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
margin-bottom: 10px;
|
||||
background: #f8f8f8;
|
||||
border-radius: 14px;
|
||||
background: #eef3ff;
|
||||
}
|
||||
|
||||
.product-image {
|
||||
@@ -483,48 +421,37 @@ onMounted(async () => {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 40px;
|
||||
font-weight: bold;
|
||||
color: rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.product-tag {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.product-info {
|
||||
padding: 0;
|
||||
font-weight: 700;
|
||||
color: rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
.name {
|
||||
margin: 12px 0 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin: 0 0 4px 0;
|
||||
font-weight: 700;
|
||||
color: #1f1f1f;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.product-meta {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
margin-bottom: 6px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: #8b8b9a;
|
||||
}
|
||||
|
||||
.duration {
|
||||
background: #f0f0f0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
border-radius: 999px;
|
||||
background: #f4f6fb;
|
||||
}
|
||||
|
||||
.stats {
|
||||
@@ -532,10 +459,9 @@ onMounted(async () => {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.like-count,
|
||||
.collect-count {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
.product-tags {
|
||||
margin: 10px 0;
|
||||
min-height: 26px;
|
||||
}
|
||||
|
||||
.price-row {
|
||||
@@ -545,51 +471,33 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
.price {
|
||||
color: #ff4d4f;
|
||||
font-weight: bold;
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
|
||||
.product-tags {
|
||||
margin: 8px 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.load-more {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 60px 20px;
|
||||
text-align: center;
|
||||
color: #999;
|
||||
font-size: 14px;
|
||||
.empty-state,
|
||||
.loading-state {
|
||||
padding: 56px 0;
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.main-content {
|
||||
min-height: calc(100vh - 60px);
|
||||
height: auto;
|
||||
max-width: var(--frontend-content-max-width);
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.category-sidebar {
|
||||
width: 128px;
|
||||
border-radius: 20px 0 0 20px;
|
||||
}
|
||||
|
||||
.product-section {
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.product-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.product-grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
+301
-592
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,7 @@
|
||||
>
|
||||
<div class="logo">
|
||||
<h1 v-if="!collapsed">后台管理</h1>
|
||||
<h1 v-else>管</h1>
|
||||
<h1 v-else>后台</h1>
|
||||
</div>
|
||||
<a-menu
|
||||
:selectedKeys="selectedKeys"
|
||||
@@ -29,21 +29,36 @@
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</a-layout-sider>
|
||||
|
||||
<a-layout>
|
||||
<a-layout-header class="header">
|
||||
<div class="header-shell">
|
||||
<div class="header-left">
|
||||
<MenuUnfoldOutlined
|
||||
v-if="collapsed"
|
||||
class="trigger"
|
||||
@click="toggleCollapsed"
|
||||
/>
|
||||
<MenuFoldOutlined
|
||||
v-else
|
||||
class="trigger"
|
||||
@click="toggleCollapsed"
|
||||
/>
|
||||
<MenuUnfoldOutlined v-if="collapsed" class="trigger" @click="toggleCollapsed" />
|
||||
<MenuFoldOutlined v-else class="trigger" @click="toggleCollapsed" />
|
||||
|
||||
<div v-if="isBootstrapAdmin" class="shop-hint">
|
||||
<span>当前暂无可用门店,请先前往店铺管理创建</span>
|
||||
<a-button type="link" @click="router.push('/admin/shops')">去创建</a-button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="shopOptions.length > 1" class="shop-switcher">
|
||||
<span class="shop-switcher-label">当前门店</span>
|
||||
<a-select
|
||||
v-model:value="selectedShopId"
|
||||
class="shop-select"
|
||||
:options="shopSelectOptions"
|
||||
:loading="shopSwitchLoading"
|
||||
@change="handleShopChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="shop-pill">
|
||||
<ShopOutlined />
|
||||
<span>{{ currentShopName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header-right">
|
||||
<a-dropdown>
|
||||
<a class="user-dropdown" @click.prevent>
|
||||
@@ -53,11 +68,11 @@
|
||||
</a>
|
||||
<template #overlay>
|
||||
<a-menu>
|
||||
<a-menu-item key="profile" @click="goToProfile">
|
||||
<a-menu-item key="home" @click="router.push('/admin')">
|
||||
<template #icon>
|
||||
<UserOutlined />
|
||||
</template>
|
||||
个人中心
|
||||
工作台
|
||||
</a-menu-item>
|
||||
<a-menu-divider />
|
||||
<a-menu-item key="logout" @click="handleLogout">
|
||||
@@ -72,6 +87,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</a-layout-header>
|
||||
|
||||
<a-layout-content class="content">
|
||||
<div class="content-shell">
|
||||
<router-view />
|
||||
@@ -83,26 +99,25 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
DashboardOutlined,
|
||||
DownOutlined,
|
||||
GiftOutlined,
|
||||
HomeOutlined,
|
||||
LogoutOutlined,
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
DashboardOutlined,
|
||||
UserOutlined,
|
||||
ShopOutlined,
|
||||
HomeOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
DownOutlined,
|
||||
LogoutOutlined,
|
||||
GiftOutlined,
|
||||
TagOutlined,
|
||||
ShopOutlined,
|
||||
ShoppingOutlined,
|
||||
TeamOutlined
|
||||
TagOutlined,
|
||||
TeamOutlined,
|
||||
UserOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { userApi, type UserVO } from '@/api/admin'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { adminAuthApi, type UserVO } from '@/api/admin'
|
||||
import { DEFAULT_AVATAR } from '@/constants'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
|
||||
@@ -111,86 +126,52 @@ const route = useRoute()
|
||||
|
||||
const collapsed = ref(false)
|
||||
const userInfo = ref<UserVO | null>(null)
|
||||
const selectedKeys = ref<string[]>([route.path])
|
||||
const selectedShopId = ref<string>()
|
||||
const shopSwitchLoading = ref(false)
|
||||
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
key: '/admin',
|
||||
icon: HomeOutlined,
|
||||
label: '首页',
|
||||
permissionCode: ''
|
||||
},
|
||||
{
|
||||
key: '/admin/dashboard',
|
||||
icon: DashboardOutlined,
|
||||
label: '仪表盘',
|
||||
permissionCode: 'dashboard:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/users',
|
||||
icon: UserOutlined,
|
||||
label: '用户管理',
|
||||
permissionCode: 'user:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/products',
|
||||
icon: ShopOutlined,
|
||||
label: '作品管理',
|
||||
permissionCode: 'product:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/coupons',
|
||||
icon: GiftOutlined,
|
||||
label: '优惠券管理',
|
||||
permissionCode: 'coupon:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/shops',
|
||||
icon: HomeOutlined,
|
||||
label: '店铺管理',
|
||||
permissionCode: 'shop:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/permissions',
|
||||
icon: SafetyCertificateOutlined,
|
||||
label: '权限管理',
|
||||
permissionCode: 'permission:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/tags',
|
||||
icon: TagOutlined,
|
||||
label: '标签管理',
|
||||
permissionCode: 'tag:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/orders',
|
||||
icon: ShoppingOutlined,
|
||||
label: '订单管理',
|
||||
permissionCode: 'order:view'
|
||||
},
|
||||
{
|
||||
key: '/admin/nail-artists',
|
||||
icon: TeamOutlined,
|
||||
label: '美甲师管理',
|
||||
permissionCode: 'nail_artist:view'
|
||||
}
|
||||
{ key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' },
|
||||
{ key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' },
|
||||
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' },
|
||||
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' },
|
||||
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' },
|
||||
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' },
|
||||
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' },
|
||||
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
|
||||
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' },
|
||||
{ key: '/admin/nail-artists', icon: TeamOutlined, label: '美甲师管理', permissionCode: 'nail_artist:view' }
|
||||
]
|
||||
|
||||
const selectedKeys = ref<string[]>([route.path])
|
||||
const isBootstrapAdmin = computed(() => userInfo.value?.type === 4 && !userInfo.value?.shopId)
|
||||
const shopOptions = computed(() => {
|
||||
const ids = userInfo.value?.shopIds || []
|
||||
const names = userInfo.value?.shopNames || []
|
||||
return ids.map((id, index) => ({
|
||||
id: String(id),
|
||||
name: names[index] || `门店 ${id}`
|
||||
}))
|
||||
})
|
||||
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
|
||||
const currentShopName = computed(() => userInfo.value?.shopName || '未选择门店')
|
||||
|
||||
const filteredMenuItems = computed(() => {
|
||||
// 访问 userPermissions 以建立依赖关系
|
||||
userPermissions.value
|
||||
// 所有用户类型都根据实际权限过滤菜单
|
||||
return menuItems.filter(item => {
|
||||
// 空权限码的菜单项(如首页)总是可见
|
||||
if (!item.permissionCode) {
|
||||
return true
|
||||
}
|
||||
return hasPermission(item.permissionCode)
|
||||
})
|
||||
let visibleItems = menuItems.filter(item => !item.permissionCode || hasPermission(item.permissionCode))
|
||||
if (isBootstrapAdmin.value) {
|
||||
visibleItems = visibleItems.filter(item => item.key === '/admin' || item.key === '/admin/shops')
|
||||
}
|
||||
return visibleItems
|
||||
})
|
||||
|
||||
const persistAdminSession = (payload: any) => {
|
||||
localStorage.setItem('adminAccessToken', payload.accessToken)
|
||||
localStorage.setItem('adminRefreshToken', payload.refreshToken)
|
||||
localStorage.setItem('adminUserInfo', JSON.stringify(payload.userInfo))
|
||||
sessionStorage.setItem('adminAccessToken', payload.accessToken)
|
||||
}
|
||||
|
||||
const toggleCollapsed = () => {
|
||||
collapsed.value = !collapsed.value
|
||||
}
|
||||
@@ -199,20 +180,17 @@ const handleMenuClick = (info: any) => {
|
||||
router.push(info.key)
|
||||
}
|
||||
|
||||
const goToProfile = () => {
|
||||
router.push('/profile')
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
Modal.confirm({
|
||||
title: '确认退出',
|
||||
content: '确定要退出登录吗?',
|
||||
title: '确认退出登录',
|
||||
content: '退出后需要重新登录后台。',
|
||||
okText: '确认',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
// 尝试调用登出API
|
||||
await authApi.logout()
|
||||
await adminAuthApi.logout()
|
||||
} catch (error) {
|
||||
console.error('登出失败:', error)
|
||||
console.error('退出失败:', error)
|
||||
} finally {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
@@ -232,21 +210,51 @@ const handleLogout = () => {
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
try {
|
||||
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (adminUserInfoStr) {
|
||||
userInfo.value = JSON.parse(adminUserInfoStr)
|
||||
} else {
|
||||
const res = await userApi.getUserInfo()
|
||||
userInfo.value = res as unknown as UserVO
|
||||
const cache = localStorage.getItem('adminUserInfo')
|
||||
if (cache) {
|
||||
userInfo.value = JSON.parse(cache)
|
||||
}
|
||||
if (!userInfo.value) {
|
||||
return
|
||||
}
|
||||
selectedShopId.value = userInfo.value.shopId ? String(userInfo.value.shopId) : undefined
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error)
|
||||
console.error('获取后台用户信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => route.path, (newPath) => {
|
||||
selectedKeys.value = [newPath]
|
||||
}, { immediate: true })
|
||||
const handleShopChange = async (shopId: unknown) => {
|
||||
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
|
||||
return
|
||||
}
|
||||
const normalizedShopId = String(shopId)
|
||||
if (!normalizedShopId || normalizedShopId === String(userInfo.value?.shopId || '')) {
|
||||
return
|
||||
}
|
||||
shopSwitchLoading.value = true
|
||||
try {
|
||||
const response = await adminAuthApi.switchShop(normalizedShopId)
|
||||
persistAdminSession(response as any)
|
||||
await fetchUserInfo()
|
||||
await loadUserPermissions()
|
||||
message.success('门店上下文已切换')
|
||||
window.location.reload()
|
||||
} catch (error: any) {
|
||||
console.error('切换门店失败:', error)
|
||||
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
|
||||
message.error(error?.message || '切换门店失败')
|
||||
} finally {
|
||||
shopSwitchLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
newPath => {
|
||||
selectedKeys.value = [newPath]
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchUserInfo()
|
||||
@@ -275,51 +283,76 @@ onMounted(async () => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.logo h1 {
|
||||
margin: 0;
|
||||
color: white;
|
||||
font-size: 18px;
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.ant-menu) {
|
||||
border-right: none;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: white;
|
||||
padding: 0 24px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
padding: 0 24px;
|
||||
background: white;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.header-shell {
|
||||
width: 100%;
|
||||
max-width: var(--admin-content-max-width);
|
||||
margin: 0 auto;
|
||||
min-height: 64px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.trigger {
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
transition: color 0.3s;
|
||||
}
|
||||
|
||||
.trigger:hover {
|
||||
color: #1890ff;
|
||||
.shop-hint,
|
||||
.shop-switcher,
|
||||
.shop-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 40px;
|
||||
padding: 0 14px;
|
||||
border-radius: 999px;
|
||||
background: #f5f7fb;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.shop-hint {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.shop-switcher-label {
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.shop-select {
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.shop-pill {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
@@ -331,29 +364,25 @@ onMounted(async () => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
cursor: pointer;
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
transition: background 0.3s;
|
||||
border-radius: 10px;
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
|
||||
.user-dropdown:hover {
|
||||
background: #f5f5f5;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.username {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin-left: 240px;
|
||||
min-height: calc(100vh - 64px);
|
||||
padding: 24px;
|
||||
background: #f0f2f5;
|
||||
min-height: calc(100vh - 64px);
|
||||
transition: margin-left 0.2s;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.content-shell {
|
||||
|
||||
@@ -15,11 +15,10 @@
|
||||
@finish="handleLogin"
|
||||
>
|
||||
<a-alert
|
||||
v-if="!shopLoading && !hasAvailableShops"
|
||||
type="warning"
|
||||
v-if="loginShopMessage"
|
||||
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
|
||||
show-icon
|
||||
message="当前暂无可选店铺"
|
||||
description="如果你使用的是平台管理员账号,可以直接登录后台先创建第一家店铺;其他后台账号仍需先绑定店铺。"
|
||||
:message="loginShopMessage"
|
||||
style="margin-bottom: 16px"
|
||||
/>
|
||||
|
||||
@@ -46,10 +45,10 @@
|
||||
<a-select
|
||||
v-model:value="formState.shopId"
|
||||
size="large"
|
||||
:placeholder="hasAvailableShops ? '请选择登录店铺' : '当前暂无可选店铺'"
|
||||
:placeholder="shopPlaceholder"
|
||||
:loading="shopLoading"
|
||||
:options="shopOptions"
|
||||
:disabled="shopLoading || !hasAvailableShops"
|
||||
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
|
||||
show-search
|
||||
:filter-option="filterShopOption"
|
||||
/>
|
||||
@@ -77,20 +76,21 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { message } from 'ant-design-vue'
|
||||
import type { FormInstance } from 'ant-design-vue'
|
||||
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
|
||||
import { adminAuthApi } from '@/api/admin'
|
||||
import { shopApi, type ShopSimpleVO } from '@/api/shop'
|
||||
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
|
||||
const router = useRouter()
|
||||
const formRef = ref<FormInstance>()
|
||||
const loading = ref(false)
|
||||
const shopLoading = ref(false)
|
||||
const shops = ref<ShopSimpleVO[]>([])
|
||||
const shops = ref<Array<{ id: number | string; shopName: string }>>([])
|
||||
const allowShoplessLogin = ref(false)
|
||||
const loginShopMessage = ref('')
|
||||
const { loadUserPermissions } = usePermission()
|
||||
|
||||
const formState = reactive({
|
||||
@@ -98,9 +98,10 @@ const formState = reactive({
|
||||
password: '',
|
||||
shopId: undefined as string | undefined
|
||||
})
|
||||
let loginShopTimer: number | undefined
|
||||
|
||||
const getShopIdValue = (shop: ShopSimpleVO) => String(shop.id ?? '')
|
||||
const getShopLabel = (shop: ShopSimpleVO) => String(shop.shopName || shop.name || `店铺 ${shop.id}`)
|
||||
const getShopIdValue = (shop: { id: number | string; shopName: string }) => String(shop.id ?? '')
|
||||
const getShopLabel = (shop: { id: number | string; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
|
||||
|
||||
const shopOptions = computed(() =>
|
||||
shops.value.map(shop => ({
|
||||
@@ -109,6 +110,19 @@ const shopOptions = computed(() =>
|
||||
}))
|
||||
)
|
||||
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
|
||||
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
|
||||
const shopPlaceholder = computed(() => {
|
||||
if (allowShoplessLogin.value) {
|
||||
return '当前无需选择店铺'
|
||||
}
|
||||
if (shopLoading.value) {
|
||||
return '正在加载可登录店铺'
|
||||
}
|
||||
if (hasAvailableShops.value) {
|
||||
return '请选择登录店铺'
|
||||
}
|
||||
return '请先输入账号'
|
||||
})
|
||||
|
||||
const formRules = {
|
||||
account: [
|
||||
@@ -118,7 +132,7 @@ const formRules = {
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
shopId: [{
|
||||
validator: async () => {
|
||||
if (!hasAvailableShops.value || formState.shopId) {
|
||||
if (!shouldRequireShop.value || formState.shopId) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return Promise.reject(new Error('请选择登录店铺'))
|
||||
@@ -130,6 +144,18 @@ const formRules = {
|
||||
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
|
||||
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
|
||||
const isLoginShopPrefetchUnsupported = (error: unknown) => {
|
||||
const status = (error as any)?.response?.status
|
||||
return status === 404
|
||||
}
|
||||
|
||||
const resetLoginShopTimer = () => {
|
||||
if (loginShopTimer !== undefined) {
|
||||
window.clearTimeout(loginShopTimer)
|
||||
loginShopTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const restoreLoginShop = () => {
|
||||
const cached = localStorage.getItem('adminUserInfo')
|
||||
if (!cached) {
|
||||
@@ -145,32 +171,63 @@ const restoreLoginShop = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const loadShops = async () => {
|
||||
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
|
||||
shops.value = selection?.shops || []
|
||||
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
|
||||
loginShopMessage.value = selection?.message || ''
|
||||
|
||||
if (allowShoplessLogin.value) {
|
||||
formState.shopId = undefined
|
||||
return
|
||||
}
|
||||
|
||||
if (!shops.value.length) {
|
||||
formState.shopId = undefined
|
||||
return
|
||||
}
|
||||
|
||||
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
|
||||
if (matchedShop) {
|
||||
return
|
||||
}
|
||||
|
||||
if (shops.value.length === 1) {
|
||||
formState.shopId = getShopIdValue(shops.value[0]!)
|
||||
return
|
||||
}
|
||||
|
||||
formState.shopId = undefined
|
||||
}
|
||||
|
||||
const loadLoginShops = async (account = formState.account) => {
|
||||
const trimmedAccount = account.trim()
|
||||
if (!trimmedAccount) {
|
||||
applyLoginShopSelection(null)
|
||||
return
|
||||
}
|
||||
|
||||
shopLoading.value = true
|
||||
try {
|
||||
shops.value = await shopApi.getShopsSimple() as unknown as ShopSimpleVO[]
|
||||
if (!shops.value.length) {
|
||||
formState.shopId = undefined
|
||||
return
|
||||
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
|
||||
if (formState.account.trim() === trimmedAccount) {
|
||||
applyLoginShopSelection(selection)
|
||||
}
|
||||
|
||||
const hasMatchedShop = shopOptions.value.some(option => option.value === formState.shopId)
|
||||
if (hasMatchedShop) {
|
||||
return
|
||||
}
|
||||
|
||||
if (shops.value.length === 1) {
|
||||
const [onlyShop] = shops.value
|
||||
if (onlyShop) {
|
||||
formState.shopId = getShopIdValue(onlyShop)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
formState.shopId = undefined
|
||||
} catch (error) {
|
||||
console.error('获取登录店铺列表失败:', error)
|
||||
message.error('店铺列表加载失败,请刷新后重试')
|
||||
if (formState.account.trim() === trimmedAccount) {
|
||||
if (isLoginShopPrefetchUnsupported(error)) {
|
||||
applyLoginShopSelection({
|
||||
allowShoplessLogin: true,
|
||||
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
|
||||
shops: []
|
||||
})
|
||||
} else {
|
||||
applyLoginShopSelection(null)
|
||||
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
|
||||
}
|
||||
}
|
||||
if (!isLoginShopPrefetchUnsupported(error)) {
|
||||
console.error('获取登录店铺列表失败:', error)
|
||||
}
|
||||
} finally {
|
||||
shopLoading.value = false
|
||||
}
|
||||
@@ -214,7 +271,26 @@ const handleLogin = async () => {
|
||||
|
||||
onMounted(() => {
|
||||
restoreLoginShop()
|
||||
loadShops()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => formState.account,
|
||||
value => {
|
||||
resetLoginShopTimer()
|
||||
const trimmedAccount = value.trim()
|
||||
if (!trimmedAccount) {
|
||||
applyLoginShopSelection(null)
|
||||
return
|
||||
}
|
||||
loginShopTimer = window.setTimeout(() => {
|
||||
loginShopTimer = undefined
|
||||
void loadLoginShops(trimmedAccount)
|
||||
}, 400)
|
||||
}
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resetLoginShopTimer()
|
||||
})
|
||||
|
||||
const goToFrontend = () => {
|
||||
|
||||
@@ -1,58 +1,44 @@
|
||||
<template>
|
||||
<div class="dashboard">
|
||||
<a-page-header title="仪表盘" sub-title="欢迎使用后台管理系统" />
|
||||
|
||||
<a-row :gutter="16" class="stat-cards">
|
||||
<a-col :span="6">
|
||||
<a-page-header
|
||||
title="仪表盘"
|
||||
:sub-title="pageSubtitle"
|
||||
/>
|
||||
|
||||
<a-row :gutter="[16, 16]" class="stat-cards">
|
||||
<a-col :xs="24" :sm="12" :xl="6">
|
||||
<a-card>
|
||||
<a-statistic
|
||||
title="总用户数"
|
||||
:value="stats.totalUsers"
|
||||
:value-style="{ color: '#3f8600' }"
|
||||
:loading="loading"
|
||||
>
|
||||
<a-statistic title="用户数" :value="stats.totalUsers" :loading="loading">
|
||||
<template #prefix>
|
||||
<UserOutlined />
|
||||
</template>
|
||||
</a-statistic>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="6">
|
||||
|
||||
<a-col :xs="24" :sm="12" :xl="6">
|
||||
<a-card>
|
||||
<a-statistic
|
||||
title="作品总数"
|
||||
:value="stats.totalProducts"
|
||||
:value-style="{ color: '#1890ff' }"
|
||||
:loading="loading"
|
||||
>
|
||||
<a-statistic title="作品数" :value="stats.totalProducts" :loading="loading">
|
||||
<template #prefix>
|
||||
<ShopOutlined />
|
||||
</template>
|
||||
</a-statistic>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="6" v-if="isAdmin">
|
||||
|
||||
<a-col v-if="isAdmin" :xs="24" :sm="12" :xl="6">
|
||||
<a-card>
|
||||
<a-statistic
|
||||
title="店铺数量"
|
||||
:value="stats.totalShops"
|
||||
:value-style="{ color: '#722ed1' }"
|
||||
:loading="loading"
|
||||
>
|
||||
<a-statistic title="门店数" :value="stats.totalShops" :loading="loading">
|
||||
<template #prefix>
|
||||
<HomeOutlined />
|
||||
</template>
|
||||
</a-statistic>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="6">
|
||||
|
||||
<a-col :xs="24" :sm="12" :xl="6">
|
||||
<a-card>
|
||||
<a-statistic
|
||||
title="今日订单"
|
||||
:value="stats.todayOrders"
|
||||
:value-style="{ color: '#cf1322' }"
|
||||
:loading="loading"
|
||||
>
|
||||
<a-statistic title="今日订单" :value="stats.todayOrders" :loading="loading">
|
||||
<template #prefix>
|
||||
<ShoppingOutlined />
|
||||
</template>
|
||||
@@ -61,47 +47,50 @@
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<a-row :gutter="16" class="charts-section">
|
||||
<a-col :span="16">
|
||||
<a-card title="订单趋势" :bordered="false" class="chart-card">
|
||||
<div class="chart-placeholder">
|
||||
<BarChartOutlined :style="{ fontSize: '64px', color: '#d9d9d9' }" />
|
||||
<p>订单趋势图表</p>
|
||||
</div>
|
||||
<a-row :gutter="[16, 16]">
|
||||
<a-col :xs="24" :xl="14">
|
||||
<a-card title="经营提醒" class="insight-card">
|
||||
<a-spin :spinning="loading">
|
||||
<div class="insight-list">
|
||||
<div v-for="item in insightItems" :key="item.title" class="insight-item">
|
||||
<div class="insight-title">{{ item.title }}</div>
|
||||
<div class="insight-description">{{ item.description }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-spin>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="8">
|
||||
<a-card title="热门作品" :bordered="false" class="chart-card">
|
||||
|
||||
<a-col :xs="24" :xl="10">
|
||||
<a-card title="热门作品" class="side-card">
|
||||
<a-spin :spinning="loading">
|
||||
<a-list :data-source="stats.hotProducts" size="small">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<a-list-item-meta>
|
||||
<template #title>
|
||||
<a href="#">{{ item.title }}</a>
|
||||
</template>
|
||||
<template #description>
|
||||
点赞: {{ item.likeCount }} | 收藏: {{ item.collectCount || 0 }}
|
||||
</template>
|
||||
</a-list-item-meta>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-empty v-if="!stats.hotProducts.length" description="暂时还没有热门作品数据" />
|
||||
<div v-else class="hot-list">
|
||||
<div v-for="item in stats.hotProducts" :key="item.id" class="hot-item">
|
||||
<div>
|
||||
<div class="hot-name">{{ item.title }}</div>
|
||||
<div class="hot-meta">点赞 {{ item.likeCount || 0 }} · 收藏 {{ item.collectCount || 0 }}</div>
|
||||
</div>
|
||||
<div class="hot-price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-spin>
|
||||
</a-card>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<a-card title="最近活动" :bordered="false" class="activity-card">
|
||||
<a-card title="最近动态" class="activity-card">
|
||||
<a-spin :spinning="loading">
|
||||
<a-timeline>
|
||||
<a-timeline-item
|
||||
v-for="activity in stats.recentActivities"
|
||||
<a-empty v-if="!stats.recentActivities.length" description="暂时没有最近动态" />
|
||||
<a-timeline v-else>
|
||||
<a-timeline-item
|
||||
v-for="activity in stats.recentActivities"
|
||||
:key="activity.id"
|
||||
:color="activity.color"
|
||||
:color="activity.color || 'blue'"
|
||||
>
|
||||
<p>{{ activity.description }}</p>
|
||||
<p style="font-size: 12px; color: #999;">{{ formatTime(activity.time) }}</p>
|
||||
<p class="activity-title">{{ activity.title || '系统动态' }}</p>
|
||||
<p class="activity-description">{{ activity.description }}</p>
|
||||
<p class="activity-time">{{ formatTime(activity.time) }}</p>
|
||||
</a-timeline-item>
|
||||
</a-timeline>
|
||||
</a-spin>
|
||||
@@ -110,15 +99,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, computed } from 'vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import {
|
||||
UserOutlined,
|
||||
ShopOutlined,
|
||||
HomeOutlined,
|
||||
ShoppingOutlined,
|
||||
BarChartOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { HomeOutlined, ShopOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
|
||||
import { adminDashboardApi, type DashboardStats } from '@/api/admin'
|
||||
|
||||
const loading = ref(false)
|
||||
@@ -131,24 +114,62 @@ const stats = reactive<DashboardStats>({
|
||||
recentActivities: []
|
||||
})
|
||||
|
||||
// 获取当前用户信息
|
||||
const getCurrentUserInfo = () => {
|
||||
try {
|
||||
const userInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (userInfoStr) {
|
||||
const userInfo = JSON.parse(userInfoStr)
|
||||
return userInfo
|
||||
}
|
||||
const cache = localStorage.getItem('adminUserInfo')
|
||||
return cache ? JSON.parse(cache) : null
|
||||
} catch (error) {
|
||||
console.error('获取当前用户信息失败', error)
|
||||
console.error('读取后台用户信息失败:', error)
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 判断是否为管理员
|
||||
const isAdmin = computed(() => {
|
||||
const userInfo = getCurrentUserInfo()
|
||||
return userInfo?.type === 4
|
||||
const currentUser = computed(() => getCurrentUserInfo())
|
||||
const isAdmin = computed(() => currentUser.value?.type === 4)
|
||||
const pageSubtitle = computed(() => {
|
||||
if (isAdmin.value) {
|
||||
return stats.totalShops > 0 ? '查看整体经营情况与各门店动态' : '当前还没有门店,先去店铺管理创建第一家门店'
|
||||
}
|
||||
return currentUser.value?.shopName ? `当前门店:${currentUser.value.shopName}` : '当前还没有选中门店'
|
||||
})
|
||||
|
||||
const insightItems = computed(() => {
|
||||
const items = []
|
||||
if (isAdmin.value && stats.totalShops === 0) {
|
||||
items.push({
|
||||
title: '先创建门店',
|
||||
description: '系统目前还没有门店,建议先在店铺管理里创建第一家门店,再继续配置作品、优惠券和员工。'
|
||||
})
|
||||
}
|
||||
if (stats.totalProducts === 0) {
|
||||
items.push({
|
||||
title: '还没有可售作品',
|
||||
description: '可以先补充几款基础作品,首页和前台作品页会更完整,也更方便测试完整下单流程。'
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
title: '作品库已准备好',
|
||||
description: `当前共有 ${stats.totalProducts} 个作品,建议继续关注热门作品的收藏和点赞表现。`
|
||||
})
|
||||
}
|
||||
if (stats.todayOrders === 0) {
|
||||
items.push({
|
||||
title: '今日订单较安静',
|
||||
description: '可以检查首页推荐、优惠券配置或门店营业时间是否完整,减少用户下单前的犹豫。'
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
title: '今日已有订单流入',
|
||||
description: `今天已产生 ${stats.todayOrders} 笔订单,建议优先关注订单状态推进和美甲师排期。`
|
||||
})
|
||||
}
|
||||
if (stats.totalUsers > 0) {
|
||||
items.push({
|
||||
title: '用户池正在积累',
|
||||
description: `当前共有 ${stats.totalUsers} 个用户,可继续结合收藏、优惠券和 VIP 规则提升复购。`
|
||||
})
|
||||
}
|
||||
return items
|
||||
})
|
||||
|
||||
const formatTime = (timeStr: string) => {
|
||||
@@ -156,22 +177,21 @@ const formatTime = (timeStr: string) => {
|
||||
const time = new Date(timeStr)
|
||||
const now = new Date()
|
||||
const diff = now.getTime() - time.getTime()
|
||||
|
||||
|
||||
const minutes = Math.floor(diff / 60000)
|
||||
const hours = Math.floor(diff / 3600000)
|
||||
const days = Math.floor(diff / 86400000)
|
||||
|
||||
|
||||
if (minutes < 1) return '刚刚'
|
||||
if (minutes < 60) return `${minutes}分钟前`
|
||||
if (hours < 24) return `${hours}小时前`
|
||||
if (days < 7) return `${days}天前`
|
||||
|
||||
if (minutes < 60) return `${minutes} 分钟前`
|
||||
if (hours < 24) return `${hours} 小时前`
|
||||
if (days < 7) return `${days} 天前`
|
||||
return time.toLocaleDateString('zh-CN')
|
||||
}
|
||||
|
||||
const fetchStats = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
loading.value = true
|
||||
const data = await adminDashboardApi.getStats()
|
||||
Object.assign(stats, data)
|
||||
} catch (error) {
|
||||
@@ -183,7 +203,7 @@ const fetchStats = async () => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchStats()
|
||||
void fetchStats()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -196,29 +216,89 @@ onMounted(() => {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.charts-section {
|
||||
margin-bottom: 24px;
|
||||
.insight-card,
|
||||
.side-card,
|
||||
.activity-card {
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
height: 400px;
|
||||
.insight-list {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.chart-placeholder {
|
||||
.insight-item {
|
||||
padding: 16px 18px;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(135deg, #f8fbff 0%, #f5f7ff 100%);
|
||||
border: 1px solid #edf2ff;
|
||||
}
|
||||
|
||||
.insight-title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.insight-description {
|
||||
margin-top: 6px;
|
||||
line-height: 1.7;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.hot-list {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.hot-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 300px;
|
||||
color: #999;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 14px 0;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.chart-placeholder p {
|
||||
margin-top: 16px;
|
||||
font-size: 14px;
|
||||
.hot-item:last-child {
|
||||
border-bottom: none;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.hot-name {
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.hot-meta,
|
||||
.activity-description,
|
||||
.activity-time {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.hot-meta,
|
||||
.activity-time {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.hot-price {
|
||||
white-space: nowrap;
|
||||
font-weight: 700;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
|
||||
.activity-card {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.activity-title {
|
||||
margin: 0 0 4px;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.activity-description,
|
||||
.activity-time {
|
||||
margin: 0;
|
||||
line-height: 1.7;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -64,6 +64,15 @@
|
||||
<span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'status'">
|
||||
<a-switch
|
||||
:checked="record.status !== 0"
|
||||
:disabled="!hasPermission('shop:edit') || !isAdmin"
|
||||
checked-children="启用"
|
||||
un-checked-children="停用"
|
||||
@change="(checked: any) => handleStatusChange(record, checked === true)"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-space>
|
||||
<a-button v-if="hasPermission('shop:view')" type="link" size="small" @click="showViewModal(record)">
|
||||
@@ -298,6 +307,7 @@ const viewFormState = reactive({
|
||||
description: '',
|
||||
address: '',
|
||||
businessHours: '',
|
||||
status: 1,
|
||||
coverImageFileId: '',
|
||||
imageFileIds: ''
|
||||
})
|
||||
@@ -316,6 +326,7 @@ const formState = reactive({
|
||||
description: '',
|
||||
address: '',
|
||||
businessHours: '',
|
||||
status: 1,
|
||||
coverImageFileId: '',
|
||||
imageFileIds: ''
|
||||
})
|
||||
@@ -345,6 +356,7 @@ const columns = [
|
||||
{ title: '店铺描述', dataIndex: 'description', key: 'description' },
|
||||
{ title: '店铺地址', dataIndex: 'address', key: 'address' },
|
||||
{ title: '营业时间', dataIndex: 'businessHours', key: 'businessHours' },
|
||||
{ title: '状态', key: 'status', width: 120 },
|
||||
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
|
||||
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
|
||||
]
|
||||
@@ -600,6 +612,7 @@ const showAddModal = () => {
|
||||
description: '',
|
||||
address: '',
|
||||
businessHours: '',
|
||||
status: 1,
|
||||
coverImageFileId: '',
|
||||
imageFileIds: ''
|
||||
})
|
||||
@@ -619,6 +632,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
|
||||
description: 'description' in record ? record.description : (record as any).description,
|
||||
address: 'address' in record ? record.address : (record as any).address,
|
||||
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
|
||||
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
|
||||
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
|
||||
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
|
||||
})
|
||||
@@ -707,6 +721,7 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
|
||||
description: 'description' in record ? record.description : (record as any).description,
|
||||
address: 'address' in record ? record.address : (record as any).address,
|
||||
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
|
||||
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
|
||||
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
|
||||
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
|
||||
})
|
||||
@@ -812,6 +827,17 @@ const handleDelete = async (record: Shop | Record<string, any>) => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
|
||||
try {
|
||||
const shopId = 'id' in record ? record.id : (record as any).id
|
||||
await adminShopApi.updateShopStatus(shopId, enabled ? 1 : 0)
|
||||
;(record as any).status = enabled ? 1 : 0
|
||||
message.success(`店铺已${enabled ? '启用' : '停用'}`)
|
||||
} catch (error) {
|
||||
message.error('店铺状态更新失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadUserPermissions()
|
||||
fetchShopList()
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
</template>
|
||||
|
||||
<template v-else-if="column.key === 'shopName'">
|
||||
{{ record.shopName || getShopNameById(record.shopId) || '-' }}
|
||||
{{ getShopDisplay(record) || '-' }}
|
||||
</template>
|
||||
|
||||
<template v-else-if="column.key === 'type'">
|
||||
@@ -83,7 +83,7 @@
|
||||
</a-button>
|
||||
<a-popconfirm
|
||||
v-if="hasPermission('user:delete') && record.type !== 4"
|
||||
title="确定要删除这个用户吗?"
|
||||
title="确定要将这个用户从当前店铺移除吗?"
|
||||
@confirm="handleDelete(record)"
|
||||
>
|
||||
<a-button type="link" size="small" danger>
|
||||
@@ -128,10 +128,11 @@
|
||||
<a-form-item v-if="!isEdit" label="密码" name="password">
|
||||
<a-input-password v-model:value="formState.password" placeholder="请输入密码" />
|
||||
</a-form-item>
|
||||
<a-form-item label="所属店铺" name="shopId">
|
||||
<a-form-item label="所属店铺" name="shopIds">
|
||||
<a-select
|
||||
v-model:value="formState.shopId"
|
||||
placeholder="请选择店铺"
|
||||
v-model:value="formState.shopIds"
|
||||
mode="multiple"
|
||||
:placeholder="currentUserInfo?.type === 4 ? '请选择一个或多个店铺' : '请选择店铺'"
|
||||
:loading="shopLoading"
|
||||
:disabled="currentUserInfo?.type !== 4 && !!currentUserInfo?.shopId"
|
||||
>
|
||||
@@ -169,7 +170,7 @@
|
||||
<a-descriptions-item label="账号">{{ viewRecord?.account || '-' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="昵称">{{ viewRecord?.nickname || '-' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="手机号">{{ viewRecord?.phone || '-' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="所属店铺">{{ viewRecord?.shopName || '-' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="所属店铺">{{ getShopDisplay(viewRecord) || '-' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="用户类型">{{ getUserTypeText(viewRecord?.type || 0) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="VIP 等级">{{ viewRecord?.level || '普通' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="状态">{{ viewRecord?.status === 1 ? '正常' : '禁用' }}</a-descriptions-item>
|
||||
@@ -188,7 +189,7 @@
|
||||
<div v-if="assetTargetUser" class="asset-modal">
|
||||
<a-alert
|
||||
:message="`${assetTargetUser.nickname}(${assetTargetUser.account})`"
|
||||
:description="assetTargetUser.shopName ? `所属店铺:${assetTargetUser.shopName}` : '未绑定店铺'"
|
||||
:description="getShopDisplay(assetTargetUser) ? `所属店铺:${getShopDisplay(assetTargetUser)}` : '未绑定店铺'"
|
||||
type="info"
|
||||
show-icon
|
||||
style="margin-bottom: 16px"
|
||||
@@ -423,7 +424,7 @@ const formState = reactive({
|
||||
phone: '',
|
||||
password: '',
|
||||
type: 0,
|
||||
shopId: undefined as string | undefined
|
||||
shopIds: [] as string[]
|
||||
})
|
||||
|
||||
const balanceForm = reactive<AdminUserBalanceChangeRequest>({
|
||||
@@ -459,7 +460,15 @@ const formRules = {
|
||||
}
|
||||
],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
|
||||
shopIds: [{
|
||||
validator: async (_rule: unknown, value: string[]) => {
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return Promise.reject('请选择至少一个店铺')
|
||||
},
|
||||
trigger: 'change'
|
||||
}],
|
||||
type: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
|
||||
} as any
|
||||
|
||||
@@ -561,12 +570,41 @@ const getShopNameById = (shopId?: string | number | null) => {
|
||||
return matchedShop?.shopName || ''
|
||||
}
|
||||
|
||||
const resolveEditableShopId = (shopId?: string | number | null) => {
|
||||
const targetShopId = normalizeShopId(shopId)
|
||||
if (targetShopId && shopList.value.some(shop => getShopOptionValue(shop) === targetShopId)) {
|
||||
return targetShopId
|
||||
const getShopDisplay = (user?: Partial<UserVO> | Record<string, any> | null) => {
|
||||
if (!user) {
|
||||
return ''
|
||||
}
|
||||
return shopList.value.length === 1 ? getShopOptionValue(shopList.value[0]!) : undefined
|
||||
const names = (user.shopNames || []).filter(Boolean)
|
||||
if (names.length) {
|
||||
return names.join('、')
|
||||
}
|
||||
if (user.shopName) {
|
||||
return user.shopName
|
||||
}
|
||||
if (user.shopIds?.length) {
|
||||
return (user.shopIds as Array<string | number>)
|
||||
.map((id: string | number) => getShopNameById(id) || `店铺 ${id}`)
|
||||
.join('、')
|
||||
}
|
||||
return getShopNameById(user.shopId) || ''
|
||||
}
|
||||
|
||||
const resolveEditableShopIds = (user?: UserVO | null) => {
|
||||
const sourceIds = user?.shopIds?.length
|
||||
? user.shopIds
|
||||
: (user?.shopId ? [user.shopId] : [])
|
||||
const normalizedIds = sourceIds
|
||||
.map(id => normalizeShopId(id))
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.filter(id => shopList.value.some(shop => getShopOptionValue(shop) === id))
|
||||
|
||||
if (normalizedIds.length) {
|
||||
return normalizedIds
|
||||
}
|
||||
|
||||
return currentUserInfo?.type !== 4 && currentUserInfo?.shopId
|
||||
? [normalizeShopId(currentUserInfo.shopId)!]
|
||||
: []
|
||||
}
|
||||
|
||||
const fetchShopList = async () => {
|
||||
@@ -575,7 +613,7 @@ const fetchShopList = async () => {
|
||||
const shops = await adminShopApi.listAllShops() as unknown as Shop[]
|
||||
shopList.value = shops || []
|
||||
if (currentUserInfo?.type !== 4 && currentUserInfo?.shopId) {
|
||||
formState.shopId = normalizeShopId(currentUserInfo.shopId)
|
||||
formState.shopIds = [normalizeShopId(currentUserInfo.shopId)!]
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取店铺列表失败:', error)
|
||||
@@ -593,7 +631,7 @@ const fetchUserList = async () => {
|
||||
keyword: searchText.value || undefined
|
||||
}
|
||||
|
||||
if (currentUserInfo?.type !== 4 && currentUserInfo?.shopId) {
|
||||
if (currentUserInfo?.shopId) {
|
||||
params.shopId = currentUserInfo.shopId
|
||||
}
|
||||
|
||||
@@ -616,9 +654,9 @@ const resetFormState = () => {
|
||||
phone: '',
|
||||
password: '',
|
||||
type: 0,
|
||||
shopId: currentUserInfo?.type !== 4 && currentUserInfo?.shopId
|
||||
? normalizeShopId(currentUserInfo.shopId)
|
||||
: undefined
|
||||
shopIds: currentUserInfo?.type !== 4 && currentUserInfo?.shopId
|
||||
? [normalizeShopId(currentUserInfo.shopId)!]
|
||||
: []
|
||||
})
|
||||
}
|
||||
|
||||
@@ -649,7 +687,7 @@ const showEditModal = (record: any) => {
|
||||
phone: record.phone || '',
|
||||
password: '',
|
||||
type: record.type,
|
||||
shopId: resolveEditableShopId(record.shopId)
|
||||
shopIds: resolveEditableShopIds(record)
|
||||
})
|
||||
modalVisible.value = true
|
||||
}
|
||||
@@ -713,15 +751,21 @@ const handleModalOk = async () => {
|
||||
try {
|
||||
await formRef.value?.validate()
|
||||
modalLoading.value = true
|
||||
const requestData = {
|
||||
const requestData: Record<string, unknown> = {
|
||||
account: formState.account.trim(),
|
||||
nickname: formState.nickname.trim(),
|
||||
phone: formState.phone.trim(),
|
||||
type: formState.type,
|
||||
shopId: formState.shopId || undefined,
|
||||
shopIds: formState.shopIds,
|
||||
shopId: formState.shopIds.length ? formState.shopIds[0] : undefined,
|
||||
...(formState.password.trim() ? { password: formState.password.trim() } : {})
|
||||
}
|
||||
|
||||
if (isEdit.value && currentUserInfo?.type !== 4) {
|
||||
delete requestData.shopIds
|
||||
delete requestData.shopId
|
||||
}
|
||||
|
||||
if (isEdit.value && currentUser.value) {
|
||||
await adminUserApi.updateUser(currentUser.value.id, requestData)
|
||||
message.success('更新成功')
|
||||
@@ -751,7 +795,7 @@ const handleStatusChange = async (record: any, checked: boolean) => {
|
||||
try {
|
||||
await adminUserApi.updateUserStatus(record.id, checked ? 1 : 0)
|
||||
record.status = checked ? 1 : 0
|
||||
message.success('状态更新成功')
|
||||
message.success(`已${checked ? '启用' : '停用'}当前店铺下的用户访问`)
|
||||
} catch (error) {
|
||||
console.error('状态更新失败:', error)
|
||||
message.error('状态更新失败')
|
||||
@@ -780,15 +824,8 @@ const handleDelete = async (record: any) => {
|
||||
message.warning('管理员账号无法被删除')
|
||||
return
|
||||
}
|
||||
|
||||
const timestamp = Date.now()
|
||||
await adminUserApi.updateUser(record.id, {
|
||||
account: `${record.account}_deleted_${timestamp}`,
|
||||
phone: record.phone ? `${record.phone}_deleted_${timestamp}` : undefined
|
||||
})
|
||||
|
||||
await adminUserApi.deleteUser(record.id)
|
||||
message.success('删除成功')
|
||||
message.success('已移除当前店铺下的用户绑定')
|
||||
await fetchUserList()
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import org.springframework.amqp.core.*;
|
||||
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.amqp.core.AcknowledgeMode;
|
||||
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -66,4 +70,15 @@ public class RabbitMQConfig {
|
||||
public Binding emailBinding() {
|
||||
return BindingBuilder.bind(emailQueue()).to(messageExchange()).with(EMAIL_ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleRabbitListenerContainerFactory manualAckRabbitListenerContainerFactory(
|
||||
SimpleRabbitListenerContainerFactoryConfigurer configurer,
|
||||
ConnectionFactory connectionFactory
|
||||
) {
|
||||
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
|
||||
configurer.configure(factory, connectionFactory);
|
||||
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.service.EmailSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
@@ -29,9 +30,11 @@ public class EmailQueueListener {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "emailQueue")
|
||||
@RabbitListener(queues = "emailQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleEmailMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
@@ -42,9 +45,11 @@ public class EmailQueueListener {
|
||||
log.info("========================================");
|
||||
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
boolean valid = messageHandleService.validateAndSaveLog(messageDTO, messageId, LocalDateTime.now());
|
||||
if (!valid) {
|
||||
log.warn("邮件消息校验未通过,消息ID: {}", messageId);
|
||||
MessageHandleService.MessageLogDecision decision =
|
||||
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime);
|
||||
if (!decision.shouldProcess()) {
|
||||
log.warn("邮件消息无需继续处理,消息ID: {}, reason: {}", messageId, decision.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -65,11 +70,24 @@ public class EmailQueueListener {
|
||||
log.info("收件人: {}", messageDTO.getReceiver());
|
||||
log.info("主题: {}", subject);
|
||||
log.info("========================================");
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
log.error("邮件消息解析失败,消息ID: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "EMAIL", sendTime, "消息体解析失败: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
log.error("处理邮件消息时发生异常,消息ID: {}", messageId, exception);
|
||||
messageHandleService.updatePushLogStatus(messageId, 2, exception.getMessage());
|
||||
} finally {
|
||||
acknowledge(message, channel);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "EMAIL", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
log.warn("邮件消息准备重试,消息ID: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "EMAIL", sendTime, retryDecision.failReason());
|
||||
reject(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,12 +102,27 @@ public class EmailQueueListener {
|
||||
return messageHandleService.buildFinalContent(messageDTO.getTemplateCode(), messageDTO.getTemplateParams());
|
||||
}
|
||||
|
||||
private void acknowledge(Message message, Channel channel) {
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("邮件消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
log.error("邮件消息重新入队失败", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
log.error("邮件消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.Message;
|
||||
@@ -31,10 +32,11 @@ public class SmsQueueListener {
|
||||
this.messageHandleService = messageHandleService;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "smsQueue")
|
||||
@RabbitListener(queues = "smsQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleSmsMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
@@ -45,9 +47,11 @@ public class SmsQueueListener {
|
||||
logger.info("========================================");
|
||||
|
||||
SmsMessageDTO smsMessageDTO = objectMapper.readValue(messageBody, SmsMessageDTO.class);
|
||||
boolean valid = messageHandleService.validateAndSaveLog(smsMessageDTO, messageId, sendTime);
|
||||
if (!valid) {
|
||||
logger.warn("短信消息校验未通过,messageId: {}", messageId);
|
||||
MessageHandleService.MessageLogDecision decision =
|
||||
messageHandleService.validateAndPrepareLog(smsMessageDTO, messageId, sendTime);
|
||||
if (!decision.shouldProcess()) {
|
||||
logger.warn("短信消息无需继续处理,messageId: {}, reason: {}", messageId, decision.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -64,20 +68,48 @@ public class SmsQueueListener {
|
||||
logger.info("手机号: {}", smsMessageDTO.getReceiver());
|
||||
logger.info("发送方式: {}", smsMessageDTO.getSendMethod());
|
||||
logger.info("========================================");
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
logger.error("短信消息解析失败,消息ID: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "SMS", sendTime, "消息体解析失败: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
logger.error("处理短信消息时发生异常,消息ID: {}", messageId, exception);
|
||||
messageHandleService.updatePushLogStatus(messageId, 2, exception.getMessage());
|
||||
} finally {
|
||||
acknowledge(message, channel);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "SMS", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
logger.warn("短信消息准备重试,messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "SMS", sendTime, retryDecision.failReason());
|
||||
reject(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private void acknowledge(Message message, Channel channel) {
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
logger.error("短信消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
logger.error("短信消息重新入队失败", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
logger.error("短信消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ public interface PushLogMapper extends BaseMapper<PushLogDO> {
|
||||
* @param uniqueId 唯一标识符
|
||||
* @return 推送日志对象
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE unique_id = #{uniqueId}")
|
||||
@Select("SELECT * FROM push_log WHERE unique_id = #{uniqueId} ORDER BY create_time DESC LIMIT 1")
|
||||
PushLogDO selectByUniqueId(@Param("uniqueId") String uniqueId);
|
||||
|
||||
/**
|
||||
|
||||
+13
-6
@@ -11,6 +11,7 @@ import org.springframework.amqp.core.MessageProperties;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -38,7 +39,7 @@ public class MessageProducerService {
|
||||
try {
|
||||
// 生成唯一消息ID
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
// 将消息对象转换为JSON字符串
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
@@ -74,7 +75,7 @@ public class MessageProducerService {
|
||||
public void sendEmailMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
@@ -105,7 +106,7 @@ public class MessageProducerService {
|
||||
public void sendWeChatMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
@@ -136,7 +137,7 @@ public class MessageProducerService {
|
||||
public void sendPushMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
@@ -168,7 +169,7 @@ public class MessageProducerService {
|
||||
public void sendMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
@@ -207,4 +208,10 @@ public class MessageProducerService {
|
||||
throw new RuntimeException("发送消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureUniqueId(MessageDTO messageDTO, String fallbackMessageId) {
|
||||
if (messageDTO != null && !StringUtils.hasText(messageDTO.getUniqueId())) {
|
||||
messageDTO.setUniqueId(fallbackMessageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+212
-8
@@ -7,6 +7,7 @@ import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import com.xiaowang.messagehub.mapper.PushTemplateMapper;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -26,6 +27,7 @@ import java.util.stream.Collectors;
|
||||
public class MessageHandleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class);
|
||||
private static final int MAX_RETRY_COUNT = 3;
|
||||
|
||||
private final Validator validator;
|
||||
private final PushLogMapper pushLogMapper;
|
||||
@@ -42,24 +44,46 @@ public class MessageHandleService {
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
}
|
||||
|
||||
public boolean validateAndSaveLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
PushLogDO pushLog = buildPushLog(messageDTO, messageId, sendTime);
|
||||
public MessageLogDecision validateAndPrepareLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
String failReason = validateMessage(messageDTO);
|
||||
|
||||
if (failReason != null) {
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
saveOrUpdateRejectedLog(buildPushLog(messageDTO, messageId, sendTime), failReason);
|
||||
logger.warn("消息校验失败,messageId: {}, reason: {}", messageId, failReason);
|
||||
return false;
|
||||
return MessageLogDecision.reject(failReason);
|
||||
}
|
||||
|
||||
PushLogDO successLog = findSuccessfulLogByUniqueId(messageDTO, messageId);
|
||||
if (successLog != null) {
|
||||
logger.info("检测到重复业务消息,跳过重复发送,messageId: {}, uniqueId: {}, existingLogId: {}",
|
||||
messageId, messageDTO.getUniqueId(), successLog.getId());
|
||||
return MessageLogDecision.skip("同一业务消息已成功处理");
|
||||
}
|
||||
|
||||
PushLogDO existingLog = StringUtils.hasText(messageId) ? pushLogMapper.selectById(messageId) : null;
|
||||
if (existingLog != null) {
|
||||
if (Integer.valueOf(1).equals(existingLog.getStatus())) {
|
||||
logger.info("消息已成功处理过,直接确认,messageId: {}", messageId);
|
||||
return MessageLogDecision.skip("消息已成功处理");
|
||||
}
|
||||
if (hasReachedMaxRetry(existingLog)) {
|
||||
logger.warn("消息已达到最大重试次数,直接丢弃,messageId: {}, retryCount: {}",
|
||||
messageId, normalizeRetryCount(existingLog.getRetryCount()));
|
||||
return MessageLogDecision.reject("消息已达到最大重试次数");
|
||||
}
|
||||
refreshPendingLog(existingLog, messageDTO, sendTime);
|
||||
logger.info("检测到重复投递消息,继续按重试流程处理,messageId: {}, retryCount: {}",
|
||||
messageId, normalizeRetryCount(existingLog.getRetryCount()));
|
||||
return MessageLogDecision.process();
|
||||
}
|
||||
|
||||
PushLogDO pushLog = buildPushLog(messageDTO, messageId, sendTime);
|
||||
pushLog.setStatus(0);
|
||||
pushLog.setFailReason(null);
|
||||
pushLogMapper.insert(pushLog);
|
||||
insertPendingLog(pushLog);
|
||||
logger.info("消息校验通过,messageId: {}, sourceSystem: {}, channelType: {}",
|
||||
messageId, messageDTO.getSourceSystem(), messageDTO.getChannelType());
|
||||
return true;
|
||||
return MessageLogDecision.process();
|
||||
}
|
||||
|
||||
public PushTemplateDO getTemplateByCode(String templateCode) {
|
||||
@@ -86,6 +110,9 @@ public class MessageHandleService {
|
||||
}
|
||||
|
||||
public void markSendSuccess(String messageId, String finalContent) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
}
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(1);
|
||||
@@ -95,6 +122,9 @@ public class MessageHandleService {
|
||||
}
|
||||
|
||||
public void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
}
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
@@ -102,6 +132,51 @@ public class MessageHandleService {
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public MessageRetryDecision recordSendFailure(String messageId,
|
||||
String channelType,
|
||||
LocalDateTime sendTime,
|
||||
Exception exception) {
|
||||
String failReason = buildFailReason(exception);
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
logger.warn("消息缺少 messageId,无法记录重试状态,reason: {}", failReason);
|
||||
return MessageRetryDecision.reject(failReason, MAX_RETRY_COUNT);
|
||||
}
|
||||
|
||||
PushLogDO existingLog = pushLogMapper.selectById(messageId);
|
||||
if (existingLog == null) {
|
||||
PushLogDO fallbackLog = new PushLogDO();
|
||||
fallbackLog.setId(messageId);
|
||||
fallbackLog.setChannelType(channelType);
|
||||
fallbackLog.setSendTime(sendTime);
|
||||
fallbackLog.setRetryCount(0);
|
||||
fallbackLog.setStatus(0);
|
||||
fallbackLog.setFailReason(null);
|
||||
insertPendingLog(fallbackLog);
|
||||
existingLog = pushLogMapper.selectById(messageId);
|
||||
}
|
||||
|
||||
int nextRetryCount = normalizeRetryCount(existingLog == null ? null : existingLog.getRetryCount()) + 1;
|
||||
boolean shouldRetry = nextRetryCount < MAX_RETRY_COUNT;
|
||||
pushLogMapper.updateRetryStatus(messageId, shouldRetry ? 0 : 2, failReason);
|
||||
return shouldRetry
|
||||
? MessageRetryDecision.retry(failReason, nextRetryCount)
|
||||
: MessageRetryDecision.reject(failReason, nextRetryCount);
|
||||
}
|
||||
|
||||
public void markMessageRejected(String messageId,
|
||||
String channelType,
|
||||
LocalDateTime sendTime,
|
||||
String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setChannelType(channelType);
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setRetryCount(0);
|
||||
pushLog.setFailReason(failReason);
|
||||
saveOrUpdateRejectedLog(pushLog, failReason);
|
||||
}
|
||||
|
||||
public String replaceTemplatePlaceholders(String contentPattern, Map<String, Object> templateParams) {
|
||||
if (!StringUtils.hasText(contentPattern)) {
|
||||
return contentPattern;
|
||||
@@ -134,6 +209,109 @@ public class MessageHandleService {
|
||||
return pushLog;
|
||||
}
|
||||
|
||||
private PushLogDO findSuccessfulLogByUniqueId(MessageDTO messageDTO, String currentMessageId) {
|
||||
if (messageDTO == null || !StringUtils.hasText(messageDTO.getUniqueId())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PushLogDO existingLog = pushLogMapper.selectByUniqueId(messageDTO.getUniqueId());
|
||||
if (existingLog == null) {
|
||||
return null;
|
||||
}
|
||||
if (StringUtils.hasText(currentMessageId) && currentMessageId.equals(existingLog.getId())) {
|
||||
return null;
|
||||
}
|
||||
return Integer.valueOf(1).equals(existingLog.getStatus()) ? existingLog : null;
|
||||
}
|
||||
|
||||
private void insertPendingLog(PushLogDO pushLog) {
|
||||
if (pushLog == null || !StringUtils.hasText(pushLog.getId())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
pushLogMapper.insert(pushLog);
|
||||
} catch (DuplicateKeyException duplicateKeyException) {
|
||||
logger.info("push_log 已存在,按幂等处理,messageId: {}", pushLog.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void saveOrUpdateRejectedLog(PushLogDO pushLog, String failReason) {
|
||||
if (pushLog == null || !StringUtils.hasText(pushLog.getId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
PushLogDO existingLog = pushLogMapper.selectById(pushLog.getId());
|
||||
if (existingLog == null) {
|
||||
insertPendingLog(pushLog);
|
||||
PushLogDO rejectedLog = new PushLogDO();
|
||||
rejectedLog.setId(pushLog.getId());
|
||||
rejectedLog.setStatus(2);
|
||||
rejectedLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(rejectedLog);
|
||||
return;
|
||||
}
|
||||
|
||||
existingLog.setStatus(2);
|
||||
existingLog.setFailReason(failReason);
|
||||
existingLog.setSendTime(pushLog.getSendTime());
|
||||
if (StringUtils.hasText(pushLog.getSourceSystem())) {
|
||||
existingLog.setSourceSystem(pushLog.getSourceSystem());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getUniqueId())) {
|
||||
existingLog.setUniqueId(pushLog.getUniqueId());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getReceiver())) {
|
||||
existingLog.setReceiver(pushLog.getReceiver());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getChannelType())) {
|
||||
existingLog.setChannelType(pushLog.getChannelType());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getMsgType())) {
|
||||
existingLog.setMsgType(pushLog.getMsgType());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getTemplateCode())) {
|
||||
existingLog.setTemplateCode(pushLog.getTemplateCode());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getTemplateParams())) {
|
||||
existingLog.setTemplateParams(pushLog.getTemplateParams());
|
||||
}
|
||||
pushLogMapper.updateById(existingLog);
|
||||
}
|
||||
|
||||
private void refreshPendingLog(PushLogDO existingLog, MessageDTO messageDTO, LocalDateTime sendTime) {
|
||||
existingLog.setSourceSystem(messageDTO.getSourceSystem());
|
||||
existingLog.setUniqueId(messageDTO.getUniqueId());
|
||||
existingLog.setReceiver(messageDTO.getReceiver());
|
||||
existingLog.setChannelType(messageDTO.getChannelType());
|
||||
existingLog.setMsgType(messageDTO.getMsgType());
|
||||
existingLog.setTemplateCode(messageDTO.getTemplateCode());
|
||||
existingLog.setTemplateParams(messageDTO.getTemplateParams() != null ? messageDTO.getTemplateParams().toString() : null);
|
||||
existingLog.setSendTime(sendTime);
|
||||
existingLog.setStatus(0);
|
||||
existingLog.setFailReason(null);
|
||||
pushLogMapper.updateById(existingLog);
|
||||
}
|
||||
|
||||
private boolean hasReachedMaxRetry(PushLogDO pushLogDO) {
|
||||
return normalizeRetryCount(pushLogDO == null ? null : pushLogDO.getRetryCount()) >= MAX_RETRY_COUNT;
|
||||
}
|
||||
|
||||
private int normalizeRetryCount(Integer retryCount) {
|
||||
return retryCount == null ? 0 : retryCount;
|
||||
}
|
||||
|
||||
private String buildFailReason(Exception exception) {
|
||||
if (exception == null) {
|
||||
return "未知异常";
|
||||
}
|
||||
if (StringUtils.hasText(exception.getMessage())) {
|
||||
return exception.getMessage();
|
||||
}
|
||||
return exception.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
private String validateMessage(MessageDTO messageDTO) {
|
||||
Set<ConstraintViolation<MessageDTO>> violations = validator.validate(messageDTO);
|
||||
if (!violations.isEmpty()) {
|
||||
@@ -166,4 +344,30 @@ public class MessageHandleService {
|
||||
private boolean isValidEmail(String receiver) {
|
||||
return receiver != null && receiver.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
|
||||
}
|
||||
|
||||
public record MessageLogDecision(boolean shouldProcess, boolean shouldRequeue, String reason) {
|
||||
|
||||
public static MessageLogDecision process() {
|
||||
return new MessageLogDecision(true, false, null);
|
||||
}
|
||||
|
||||
public static MessageLogDecision skip(String reason) {
|
||||
return new MessageLogDecision(false, false, reason);
|
||||
}
|
||||
|
||||
public static MessageLogDecision reject(String reason) {
|
||||
return new MessageLogDecision(false, false, reason);
|
||||
}
|
||||
}
|
||||
|
||||
public record MessageRetryDecision(boolean shouldRetry, String failReason, int retryCount) {
|
||||
|
||||
public static MessageRetryDecision retry(String failReason, int retryCount) {
|
||||
return new MessageRetryDecision(true, failReason, retryCount);
|
||||
}
|
||||
|
||||
public static MessageRetryDecision reject(String failReason, int retryCount) {
|
||||
return new MessageRetryDecision(false, failReason, retryCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.utils.JwtUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -16,6 +18,7 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final JwtUtil jwtUtil;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
@@ -49,6 +52,7 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
Long userId = jwtUtil.getUserIdFromToken(token);
|
||||
String account = jwtUtil.getAccountFromToken(token);
|
||||
Long currentShopId = jwtUtil.getShopIdFromToken(token);
|
||||
UserDO currentUser = userMapper.selectById(userId);
|
||||
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
|
||||
@@ -60,14 +64,30 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAdminPath(path) && (currentUser.getType() == null || currentUser.getType() < 2)) {
|
||||
boolean adminPath = isAdminPath(path);
|
||||
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
|
||||
userId,
|
||||
currentShopId,
|
||||
adminPath,
|
||||
currentUser.getType()
|
||||
);
|
||||
if (!canAccessShop) {
|
||||
String message = currentShopId == null || currentShopId <= 0
|
||||
? "当前登录未选择可用店铺,请重新登录"
|
||||
: "当前登录店铺已停用或账号已失去该店铺访问权限";
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
|
||||
return false;
|
||||
}
|
||||
|
||||
request.setAttribute("userId", userId);
|
||||
request.setAttribute("account", account);
|
||||
request.setAttribute("userType", currentUser.getType());
|
||||
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -23,8 +23,15 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/reset-password-by-phone",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/shop/get/**",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/login-shops/**",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
|
||||
+15
@@ -3,11 +3,15 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.LoginRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.RefreshTokenRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.SwitchShopRequestDTO;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/auth")
|
||||
@RequiredArgsConstructor
|
||||
@@ -21,6 +25,17 @@ public class AdminAuthController {
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
|
||||
@GetMapping("/login-shops/{account}")
|
||||
public Result<LoginShopSelectionVO> getLoginShops(@PathVariable String account) {
|
||||
return Result.success(userService.getAdminLoginShopSelection(account));
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId()));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public Result<Boolean> logout() {
|
||||
return Result.success(true);
|
||||
|
||||
+2
-2
@@ -135,7 +135,7 @@ public class AdminCouponController {
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权给其他店铺用户发放优惠券");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
|
||||
return Result.success(success);
|
||||
@@ -158,7 +158,7 @@ public class AdminCouponController {
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权给其他店铺用户发放优惠券");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
}
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
|
||||
|
||||
+9
-14
@@ -6,6 +6,7 @@ import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.NailArtistInfoService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -24,6 +25,9 @@ public class AdminNailArtistController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 获取所有美甲师信息
|
||||
@@ -32,8 +36,7 @@ public class AdminNailArtistController {
|
||||
@RequirePermission("nail_artist:view")
|
||||
@GetMapping("/list")
|
||||
public Result<List<NailArtistInfoDTO>> getAllNailArtists(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
UserDO currentUser = userService.getById(userId);
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
|
||||
if (currentUser == null) {
|
||||
return Result.error("用户信息不存在");
|
||||
@@ -61,7 +64,7 @@ public class AdminNailArtistController {
|
||||
@GetMapping("/get/{userId}")
|
||||
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId, HttpServletRequest request) {
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
UserDO currentUser = userService.getById(currentUserId);
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
|
||||
if (currentUser == null) {
|
||||
return Result.error("用户信息不存在");
|
||||
@@ -70,11 +73,7 @@ public class AdminNailArtistController {
|
||||
// 检查权限:管理员可以查看所有,店长只能查看本店铺的,美甲师只能查看自己的
|
||||
if (currentUser.getType() != 4) { // 不是管理员
|
||||
if (currentUser.getType() == 2) { // 店长
|
||||
// 检查美甲师是否属于当前店长的店铺
|
||||
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
|
||||
if (nailArtistInfoDTO == null || !nailArtistInfoDTO.getShopId().equals(currentUser.getShopId())) {
|
||||
return Result.error("无权限访问");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权限访问");
|
||||
} else if (currentUser.getType() == 3) { // 美甲师
|
||||
// 只能查看自己的信息
|
||||
if (!currentUser.getId().equals(userId)) {
|
||||
@@ -97,7 +96,7 @@ public class AdminNailArtistController {
|
||||
@PostMapping("/save")
|
||||
public Result<NailArtistInfoDTO> saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) {
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
UserDO currentUser = userService.getById(currentUserId);
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
|
||||
if (currentUser == null) {
|
||||
return Result.error("用户信息不存在");
|
||||
@@ -106,11 +105,7 @@ public class AdminNailArtistController {
|
||||
// 检查权限:管理员可以编辑所有,店长只能编辑本店铺的,美甲师只能编辑自己的
|
||||
if (currentUser.getType() != 4) { // 不是管理员
|
||||
if (currentUser.getType() == 2) { // 店长
|
||||
// 检查美甲师是否属于当前店长的店铺
|
||||
NailArtistInfoDTO existing = nailArtistInfoService.getByUserId(nailArtistInfoDTO.getUserId());
|
||||
if (existing == null || !existing.getShopId().equals(currentUser.getShopId())) {
|
||||
return Result.error("无权限编辑");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, nailArtistInfoDTO.getUserId(), "无权限编辑");
|
||||
} else if (currentUser.getType() == 3) { // 美甲师
|
||||
// 只能编辑自己的信息
|
||||
if (!currentUser.getId().equals(nailArtistInfoDTO.getUserId())) {
|
||||
|
||||
+5
-1
@@ -81,7 +81,7 @@ public class AdminPermissionController {
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权查看其他店铺用户权限");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限");
|
||||
}
|
||||
List<PermissionVO> permissionVOs = permissionService.listUserPermissions(userId);
|
||||
return Result.success(permissionVOs);
|
||||
@@ -100,6 +100,10 @@ public class AdminPermissionController {
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long userId,
|
||||
@RequestBody UserPermissionDTO userPermissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户分配权限");
|
||||
}
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
userPermissionDTO.setUserId(userId);
|
||||
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
|
||||
|
||||
+16
-1
@@ -8,6 +8,7 @@ import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -68,13 +69,22 @@ public class AdminShopController {
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@PutMapping("/status/{id}")
|
||||
@RequirePermission("shop:edit")
|
||||
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
||||
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@GetMapping("/list/all")
|
||||
@RequirePermission("shop:view")
|
||||
public Result<List<ShopVO>> listAllShops(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
List<ShopVO> shops;
|
||||
if (adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
shops = shopService.listAllShops();
|
||||
shops = shopService.listAllShopsForAdmin();
|
||||
} else {
|
||||
ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser));
|
||||
shops = currentShop == null ? List.of() : List.of(currentShop);
|
||||
@@ -90,4 +100,9 @@ public class AdminShopController {
|
||||
ShopVO shop = shopService.getShopById(id);
|
||||
return Result.success(shop);
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class StatusRequest {
|
||||
private Integer status;
|
||||
}
|
||||
}
|
||||
|
||||
+12
-9
@@ -52,7 +52,9 @@ public class AdminUserController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
userDTO.setShopId(adminScopeHelper.getManagedShopId(currentUser));
|
||||
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
|
||||
userDTO.setShopId(managedShopId);
|
||||
userDTO.setShopIds(List.of(managedShopId));
|
||||
}
|
||||
Long id = userService.createUser(userDTO);
|
||||
return Result.success(id);
|
||||
@@ -71,7 +73,8 @@ public class AdminUserController {
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
}
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
userDTO.setShopId(adminScopeHelper.getManagedShopId(currentUser));
|
||||
userDTO.setShopId(null);
|
||||
userDTO.setShopIds(null);
|
||||
}
|
||||
boolean success = userService.updateUser(id, userDTO);
|
||||
return Result.success(success);
|
||||
@@ -85,8 +88,8 @@ public class AdminUserController {
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权变更其他店铺用户状态");
|
||||
boolean success = userService.updateUserStatus(id, request.getStatus());
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权变更其他店铺用户状态");
|
||||
boolean success = userService.updateUserStatusInShop(id, request.getStatus(), currentUser.getShopId());
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@@ -98,7 +101,7 @@ public class AdminUserController {
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权重置其他店铺用户密码");
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码");
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.resetPassword(userId, currentUserId);
|
||||
return Result.success(success);
|
||||
@@ -112,8 +115,8 @@ public class AdminUserController {
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权删除其他店铺用户");
|
||||
boolean success = userService.deleteUser(id);
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权删除其他店铺用户");
|
||||
boolean success = userService.deleteUserInShop(id, currentUser.getShopId());
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@@ -207,7 +210,7 @@ public class AdminUserController {
|
||||
if (shopId != null) {
|
||||
final Long resolvedShopId = shopId;
|
||||
artists = artists.stream()
|
||||
.filter(artist -> resolvedShopId.equals(artist.getShopId()))
|
||||
.filter(artist -> artist.getShopIds() != null && artist.getShopIds().contains(resolvedShopId))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return Result.success(artists);
|
||||
@@ -218,7 +221,7 @@ public class AdminUserController {
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), message);
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message);
|
||||
return targetUser;
|
||||
}
|
||||
|
||||
|
||||
+63
-7
@@ -3,13 +3,18 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.CouponDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.CouponVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserCouponVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -21,13 +26,17 @@ import java.util.List;
|
||||
public class CouponController {
|
||||
|
||||
private final CouponService couponService;
|
||||
private final UserService userService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建优惠券
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("coupon:create")
|
||||
public Result<Long> createCoupon(@RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
|
||||
Long couponId = couponService.createCoupon(couponDTO, shopId);
|
||||
return Result.success(couponId);
|
||||
}
|
||||
@@ -37,7 +46,15 @@ public class CouponController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("coupon:edit")
|
||||
public Result<Boolean> updateCoupon(@PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
|
||||
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -47,7 +64,14 @@ public class CouponController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("coupon:delete")
|
||||
public Result<Boolean> deleteCoupon(@PathVariable Long id, @RequestParam(required = false) Long shopId) {
|
||||
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.deleteCoupon(id, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -57,8 +81,12 @@ public class CouponController {
|
||||
*/
|
||||
@GetMapping("/detail/{id}")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<CouponVO> getCouponById(@PathVariable Long id) {
|
||||
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
}
|
||||
return Result.success(couponVO);
|
||||
}
|
||||
|
||||
@@ -67,7 +95,9 @@ public class CouponController {
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<PageResultVO<CouponVO>> listCoupons(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
|
||||
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
|
||||
return Result.success(pageResult);
|
||||
}
|
||||
@@ -77,7 +107,19 @@ public class CouponController {
|
||||
*/
|
||||
@PostMapping("/assign")
|
||||
@RequirePermission("coupon:assign")
|
||||
public Result<Boolean> assignCouponToUser(@RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
|
||||
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -119,7 +161,21 @@ public class CouponController {
|
||||
*/
|
||||
@PostMapping("/distribute")
|
||||
@RequirePermission("coupon:assign")
|
||||
public Result<Boolean> distributeCoupon(@RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
|
||||
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
|
||||
for (Long userId : userIds) {
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
|
||||
}
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
+16
-9
@@ -15,6 +15,7 @@ import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.DashboardStatsVO;
|
||||
import com.xiaowang.yuminailcore.vo.HotProductVO;
|
||||
import com.xiaowang.yuminailcore.vo.RecentActivityVO;
|
||||
@@ -42,6 +43,7 @@ public class DashboardController {
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@GetMapping("/stats")
|
||||
@RequirePermission("dashboard:view")
|
||||
@@ -59,14 +61,14 @@ public class DashboardController {
|
||||
stats.setTotalShops(shopMapper.selectCount(null));
|
||||
stats.setTodayOrders(getTodayOrders(null));
|
||||
} else { // 店长或美甲师
|
||||
Long shopId = currentUser.getShopId();
|
||||
if (shopId != null) {
|
||||
shopIdScope = shopId;
|
||||
// 只显示当前店铺的数据
|
||||
stats.setTotalUsers(userMapper.selectCount(new LambdaQueryWrapper<UserDO>().eq(UserDO::getShopId, shopId)));
|
||||
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
|
||||
stats.setTotalShops(0L); // 非管理员不显示店铺数量
|
||||
stats.setTodayOrders(getTodayOrders(shopId));
|
||||
Long shopId = currentUser.getShopId();
|
||||
if (shopId != null) {
|
||||
shopIdScope = shopId;
|
||||
// 只显示当前店铺的数据
|
||||
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
|
||||
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
|
||||
stats.setTotalShops(0L); // 非管理员不显示店铺数量
|
||||
stats.setTodayOrders(getTodayOrders(shopId));
|
||||
} else {
|
||||
// 没有店铺ID的情况
|
||||
stats.setTotalUsers(0L);
|
||||
@@ -162,7 +164,12 @@ public class DashboardController {
|
||||
|
||||
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
userWrapper.eq(UserDO::getShopId, shopId);
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (userIds.isEmpty()) {
|
||||
userWrapper.eq(UserDO::getId, -1L);
|
||||
} else {
|
||||
userWrapper.in(UserDO::getId, userIds);
|
||||
}
|
||||
}
|
||||
userWrapper.orderByDesc(UserDO::getCreateTime)
|
||||
.last("LIMIT 3");
|
||||
|
||||
+31
-4
@@ -4,7 +4,10 @@ import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.PermissionDTO;
|
||||
import com.xiaowang.yuminailcore.dto.UserPermissionDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.PermissionService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -25,6 +28,8 @@ import java.util.List;
|
||||
public class PermissionController {
|
||||
|
||||
private final PermissionService permissionService;
|
||||
private final UserService userService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建权限
|
||||
@@ -34,7 +39,9 @@ public class PermissionController {
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("permission:create")
|
||||
public Result<Long> createPermission(@RequestBody PermissionDTO permissionDTO) {
|
||||
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
|
||||
Long id = permissionService.createPermission(permissionDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
@@ -48,7 +55,9 @@ public class PermissionController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("permission:edit")
|
||||
public Result<Boolean> updatePermission(@PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
||||
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
|
||||
boolean success = permissionService.updatePermission(id, permissionDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -61,7 +70,9 @@ public class PermissionController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("permission:delete")
|
||||
public Result<Boolean> deletePermission(@PathVariable Long id) {
|
||||
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
|
||||
boolean success = permissionService.deletePermission(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -112,7 +123,15 @@ public class PermissionController {
|
||||
*/
|
||||
@GetMapping("/list/user/{userId}")
|
||||
@RequirePermission("permission:view")
|
||||
public Result<List<PermissionVO>> listUserPermissions(@PathVariable Long userId) {
|
||||
public Result<List<PermissionVO>> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
UserDO targetUser = userService.getById(userId);
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛鏉冮檺");
|
||||
}
|
||||
List<PermissionVO> permissionVOs = permissionService.listUserPermissions(userId);
|
||||
return Result.success(permissionVOs);
|
||||
}
|
||||
@@ -126,6 +145,14 @@ public class PermissionController {
|
||||
@PostMapping("/assign")
|
||||
@RequirePermission("permission:assign")
|
||||
public Result<Boolean> assignPermissions(HttpServletRequest request, @RequestBody UserPermissionDTO userPermissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
UserDO targetUser = userService.getById(userPermissionDTO.getUserId());
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰垎閰嶆潈闄?");
|
||||
}
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
boolean success = permissionService.assignPermissions(userPermissionDTO, userId);
|
||||
return Result.success(success);
|
||||
|
||||
+23
-3
@@ -3,12 +3,15 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ProductDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.ProductService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ProductVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@@ -17,24 +20,41 @@ import java.util.List;
|
||||
public class ProductController {
|
||||
|
||||
private final ProductService productService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("product:create")
|
||||
public Result<Long> createProduct(@RequestBody ProductDTO productDTO) {
|
||||
public Result<Long> createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId()));
|
||||
Long id = productService.createProduct(productDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("product:edit")
|
||||
public Result<Boolean> updateProduct(@PathVariable Long id, @RequestBody ProductDTO productDTO) {
|
||||
public Result<Boolean> updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ProductVO productVO = productService.getProductById(id);
|
||||
if (productVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鍟嗗搧");
|
||||
Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId();
|
||||
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
|
||||
boolean success = productService.updateProduct(id, productDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("product:delete")
|
||||
public Result<Boolean> deleteProduct(@PathVariable Long id) {
|
||||
public Result<Boolean> deleteProduct(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ProductVO productVO = productService.getProductById(id);
|
||||
if (productVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鍟嗗搧");
|
||||
boolean success = productService.deleteProduct(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
+46
-5
@@ -3,12 +3,16 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -18,28 +22,48 @@ import java.util.stream.Collectors;
|
||||
public class ShopController {
|
||||
|
||||
private final ShopService shopService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("shop:create")
|
||||
public Result<Long> createShop(@RequestBody ShopDTO shopDTO) {
|
||||
public Result<Long> createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垱寤哄簵閾?");
|
||||
Long id = shopService.createShop(shopDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("shop:edit")
|
||||
public Result<Boolean> updateShop(@PathVariable Long id, @RequestBody ShopDTO shopDTO) {
|
||||
public Result<Boolean> updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
ShopVO shopVO = shopService.getShopById(id);
|
||||
if (shopVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵淇℃伅");
|
||||
boolean success = shopService.updateShop(id, shopDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("shop:delete")
|
||||
public Result<Boolean> deleteShop(@PathVariable Long id) {
|
||||
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垹闄ゅ簵閾?");
|
||||
boolean success = shopService.deleteShop(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@PutMapping("/status/{id}")
|
||||
@RequirePermission("shop:edit")
|
||||
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
||||
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<ShopVO> getShopById(@PathVariable Long id) {
|
||||
ShopVO shopVO = shopService.getShopById(id);
|
||||
@@ -48,8 +72,15 @@ public class ShopController {
|
||||
|
||||
@GetMapping("/list/all")
|
||||
@RequirePermission("shop:view")
|
||||
public Result<List<ShopVO>> listAllShops() {
|
||||
List<ShopVO> shopVOs = shopService.listAllShops();
|
||||
public Result<List<ShopVO>> listAllShops(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
List<ShopVO> shopVOs;
|
||||
if (adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
shopVOs = shopService.listAllShopsForAdmin();
|
||||
} else {
|
||||
ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser));
|
||||
shopVOs = currentShop == null ? List.of() : List.of(currentShop);
|
||||
}
|
||||
return Result.success(shopVOs);
|
||||
}
|
||||
|
||||
@@ -67,4 +98,14 @@ public class ShopController {
|
||||
.collect(Collectors.toList());
|
||||
return Result.success(simpleVOs);
|
||||
}
|
||||
|
||||
@GetMapping("/list/public")
|
||||
public Result<List<ShopVO>> listPublicShops() {
|
||||
return Result.success(shopService.listAllShops());
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class StatusRequest {
|
||||
private Integer status;
|
||||
}
|
||||
}
|
||||
|
||||
+37
-7
@@ -3,11 +3,14 @@ package com.xiaowang.yuminailcore.controller;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.TagDTO;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -23,6 +26,7 @@ import java.util.List;
|
||||
public class TagController {
|
||||
|
||||
private final TagService tagService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建标签
|
||||
@@ -32,7 +36,9 @@ public class TagController {
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("tag:create")
|
||||
public Result<Long> createTag(@RequestBody TagDTO tagDTO) {
|
||||
public Result<Long> createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId()));
|
||||
Long id = tagService.createTag(tagDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
@@ -46,7 +52,15 @@ public class TagController {
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("tag:edit")
|
||||
public Result<Boolean> updateTag(@PathVariable Long id, @RequestBody TagDTO tagDTO) {
|
||||
public Result<Boolean> updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
if (tagVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鏍囩");
|
||||
Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId();
|
||||
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
|
||||
boolean success = tagService.updateTag(id, tagDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -59,7 +73,13 @@ public class TagController {
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("tag:delete")
|
||||
public Result<Boolean> deleteTag(@PathVariable Long id) {
|
||||
public Result<Boolean> deleteTag(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
if (tagVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鏍囩");
|
||||
boolean success = tagService.deleteTag(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -72,8 +92,12 @@ public class TagController {
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
@RequirePermission("tag:view")
|
||||
public Result<TagVO> getTagById(@PathVariable Long id) {
|
||||
public Result<TagVO> getTagById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagById(id);
|
||||
if (tagVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
|
||||
}
|
||||
return Result.success(tagVO);
|
||||
}
|
||||
|
||||
@@ -96,7 +120,9 @@ public class TagController {
|
||||
*/
|
||||
@GetMapping("/list/by-shop/{shopId}")
|
||||
@RequirePermission("tag:view")
|
||||
public Result<List<TagVO>> listTagsByShopId(@PathVariable Long shopId) {
|
||||
public Result<List<TagVO>> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
List<TagVO> tagVOs = tagService.listTagsByShopId(shopId);
|
||||
return Result.success(tagVOs);
|
||||
}
|
||||
@@ -109,8 +135,12 @@ public class TagController {
|
||||
*/
|
||||
@GetMapping("/get/tagName/{tagName}")
|
||||
@RequirePermission("tag:view")
|
||||
public Result<TagVO> getTagByTagName(@PathVariable String tagName) {
|
||||
public Result<TagVO> getTagByTagName(HttpServletRequest request, @PathVariable String tagName) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
TagVO tagVO = tagService.getTagByTagName(tagName);
|
||||
if (tagVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
|
||||
}
|
||||
return Result.success(tagVO);
|
||||
}
|
||||
}
|
||||
|
||||
+102
-19
@@ -5,6 +5,8 @@ import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.*;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
@@ -18,6 +20,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 系统用户信息表 Controller
|
||||
@@ -35,16 +38,24 @@ public class UserController {
|
||||
private final MinioService minioService;
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
private final UserMapper userMapper;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建用户
|
||||
*
|
||||
* @param userDTO 用户DTO
|
||||
* @return 用户ID
|
||||
*/
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("user:create")
|
||||
public Result<Long> createUser(@RequestBody UserDTO userDTO) {
|
||||
public Result<Long> createUser(HttpServletRequest request, @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
|
||||
userDTO.setShopId(managedShopId);
|
||||
userDTO.setShopIds(List.of(managedShopId));
|
||||
}
|
||||
Long id = userService.createUser(userDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
@@ -55,10 +66,19 @@ public class UserController {
|
||||
* @param id 用户ID
|
||||
* @param userDTO 用户DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("user:edit")
|
||||
public Result<Boolean> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
|
||||
public Result<Boolean> updateUser(HttpServletRequest request, @PathVariable Long id, @RequestBody UserDTO userDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "鏃犳潈缂栬緫鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
if (userDTO.getType() != null) {
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
|
||||
}
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
userDTO.setShopId(null);
|
||||
userDTO.setShopIds(null);
|
||||
}
|
||||
boolean success = userService.updateUser(id, userDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
@@ -68,11 +88,15 @@ public class UserController {
|
||||
*
|
||||
* @param id 用户ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("user:delete")
|
||||
public Result<Boolean> deleteUser(@PathVariable Long id) {
|
||||
boolean success = userService.deleteUser(id);
|
||||
public Result<Boolean> deleteUser(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
requireAccessibleUser(currentUser, id, "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
boolean success = adminScopeHelper.isPlatformAdmin(currentUser)
|
||||
? userService.deleteUserInShop(id, currentUser.getShopId())
|
||||
: userService.deleteUserInShop(id, adminScopeHelper.getManagedShopId(currentUser));
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
@@ -81,11 +105,12 @@ public class UserController {
|
||||
*
|
||||
* @param id 用户ID
|
||||
* @return 用户VO
|
||||
*/
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
@RequirePermission("user:view")
|
||||
public Result<UserVO> getUserById(@PathVariable Long id) {
|
||||
UserVO userVO = userService.getUserById(id);
|
||||
public Result<UserVO> getUserById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO userVO = requireAccessibleUser(currentUser, id, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
return Result.success(userVO);
|
||||
}
|
||||
|
||||
@@ -93,11 +118,14 @@ public class UserController {
|
||||
* 查询所有用户
|
||||
*
|
||||
* @return 用户VO列表
|
||||
*/
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
@RequirePermission("user:view")
|
||||
public Result<List<UserVO>> listAllUsers() {
|
||||
List<UserVO> userVOs = userService.listAllUsers();
|
||||
public Result<List<UserVO>> listAllUsers(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
List<UserVO> userVOs = adminScopeHelper.isPlatformAdmin(currentUser)
|
||||
? userService.listAllUsers()
|
||||
: userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser));
|
||||
return Result.success(userVOs);
|
||||
}
|
||||
|
||||
@@ -106,10 +134,12 @@ public class UserController {
|
||||
*
|
||||
* @param shopId 店铺ID
|
||||
* @return 用户VO列表
|
||||
*/
|
||||
*/
|
||||
@GetMapping("/list/shop/{shopId}")
|
||||
@RequirePermission("user:view")
|
||||
public Result<List<UserVO>> listUsersByShopId(@PathVariable Long shopId) {
|
||||
public Result<List<UserVO>> listUsersByShopId(HttpServletRequest request, @PathVariable Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
List<UserVO> userVOs = userService.listUsersByShopId(shopId);
|
||||
return Result.success(userVOs);
|
||||
}
|
||||
@@ -119,10 +149,16 @@ public class UserController {
|
||||
*
|
||||
* @param type 用户类型
|
||||
* @return 用户VO列表
|
||||
*/
|
||||
*/
|
||||
@GetMapping("/list/type/{type}")
|
||||
public Result<List<UserVO>> listUsersByType(@PathVariable Integer type) {
|
||||
List<UserVO> userVOs = userService.listUsersByType(type);
|
||||
if (!Integer.valueOf(3).equals(type)) {
|
||||
throw new RuntimeException("仅支持查询可预约的美甲师列表");
|
||||
}
|
||||
List<UserVO> userVOs = userService.listUsersByType(type).stream()
|
||||
.filter(user -> Integer.valueOf(1).equals(user.getStatus()))
|
||||
.map(this::sanitizePublicArtist)
|
||||
.collect(Collectors.toList());
|
||||
return Result.success(userVOs);
|
||||
}
|
||||
|
||||
@@ -131,11 +167,15 @@ public class UserController {
|
||||
*
|
||||
* @param account 账号
|
||||
* @return 用户VO
|
||||
*/
|
||||
*/
|
||||
@GetMapping("/get/account/{account}")
|
||||
@RequirePermission("user:view")
|
||||
public Result<UserVO> getUserByAccount(@PathVariable String account) {
|
||||
public Result<UserVO> getUserByAccount(HttpServletRequest request, @PathVariable String account) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO userVO = userService.getUserByAccount(account);
|
||||
if (userVO != null) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
|
||||
}
|
||||
return Result.success(userVO);
|
||||
}
|
||||
|
||||
@@ -166,6 +206,16 @@ public class UserController {
|
||||
return Result.success(new LoginAccountAvailabilityVO(exists, nickname, message));
|
||||
}
|
||||
|
||||
@GetMapping("/check/login-shops/account/{account}")
|
||||
public Result<LoginShopSelectionVO> getLoginShopsByAccount(@PathVariable String account) {
|
||||
return Result.success(userService.getLoginShopSelectionByAccount(account));
|
||||
}
|
||||
|
||||
@GetMapping("/check/login-shops/phone/{phone}")
|
||||
public Result<LoginShopSelectionVO> getLoginShopsByPhone(@PathVariable String phone) {
|
||||
return Result.success(userService.getLoginShopSelectionByPhone(phone));
|
||||
}
|
||||
|
||||
@GetMapping("/check/phone/{phone}")
|
||||
public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) {
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
@@ -202,6 +252,12 @@ public class UserController {
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*
|
||||
@@ -348,6 +404,8 @@ public class UserController {
|
||||
@PostMapping("/reset-password/{userId}")
|
||||
@RequirePermission("user:reset_password")
|
||||
public Result<Boolean> resetPassword(HttpServletRequest request, @PathVariable Long userId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
requireAccessibleUser(currentUser, userId, "鏃犳潈閲嶇疆鍏朵粬搴楅摵鐢ㄦ埛瀵嗙爜");
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.resetPassword(userId, currentUserId);
|
||||
return Result.success(success);
|
||||
@@ -421,6 +479,31 @@ public class UserController {
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) {
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message);
|
||||
return targetUser;
|
||||
}
|
||||
|
||||
private UserVO sanitizePublicArtist(UserVO userVO) {
|
||||
UserVO sanitized = new UserVO();
|
||||
sanitized.setId(userVO.getId());
|
||||
sanitized.setShopId(userVO.getShopId());
|
||||
sanitized.setShopName(userVO.getShopName());
|
||||
sanitized.setShopIds(userVO.getShopIds());
|
||||
sanitized.setShopNames(userVO.getShopNames());
|
||||
sanitized.setNickname(userVO.getNickname());
|
||||
sanitized.setAvatar(userVO.getAvatar());
|
||||
sanitized.setType(userVO.getType());
|
||||
sanitized.setStatus(userVO.getStatus());
|
||||
sanitized.setCreateTime(userVO.getCreateTime());
|
||||
sanitized.setUpdateTime(userVO.getUpdateTime());
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PasswordDTO {
|
||||
private String password;
|
||||
|
||||
@@ -41,4 +41,9 @@ public class ShopDTO {
|
||||
* 店铺图片文件ID集合,多个ID以逗号分隔
|
||||
*/
|
||||
private String imageFileIds;
|
||||
|
||||
/**
|
||||
* 店铺状态:1-启用,0-停用
|
||||
*/
|
||||
private Integer status;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SwitchShopRequestDTO {
|
||||
|
||||
private Long shopId;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统用户信息表 DTO
|
||||
* 用于用户信息的传输
|
||||
@@ -17,6 +19,11 @@ public class UserDTO {
|
||||
*/
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 绑定店铺ID列表
|
||||
*/
|
||||
private List<Long> shopIds;
|
||||
|
||||
/**
|
||||
* 用户昵称
|
||||
*/
|
||||
|
||||
@@ -62,6 +62,12 @@ public class ShopDO extends BaseEntity {
|
||||
@TableField("image_file_ids")
|
||||
private String imageFileIds;
|
||||
|
||||
/**
|
||||
* 店铺状态:1-启用,0-停用
|
||||
*/
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 逻辑删除:0-未删,1-已删
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.xiaowang.yuminailcore.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 用户与店铺绑定关系。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("t_user_shop_binding")
|
||||
public class UserShopBindingDO extends BaseEntity {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("user_id")
|
||||
private Long userId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 绑定状态:1-正常,0-禁用。
|
||||
*/
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@TableField("is_delete")
|
||||
@TableLogic
|
||||
private Integer isDelete;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.UserShopBindingDO;
|
||||
|
||||
public interface UserShopBindingMapper extends BaseMapper<UserShopBindingDO> {
|
||||
}
|
||||
@@ -57,6 +57,13 @@ public interface ShopService extends IService<ShopDO> {
|
||||
*/
|
||||
List<ShopVO> listAllShops();
|
||||
|
||||
/**
|
||||
* 查询后台全部店铺(含停用,不含删除)
|
||||
*
|
||||
* @return 店铺列表
|
||||
*/
|
||||
List<ShopVO> listAllShopsForAdmin();
|
||||
|
||||
/**
|
||||
* 根据店铺名称查询店铺
|
||||
*
|
||||
@@ -74,4 +81,13 @@ public interface ShopService extends IService<ShopDO> {
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<ShopVO> pageShops(Integer page, Integer size, String keyword, Long shopId);
|
||||
|
||||
/**
|
||||
* 更新店铺状态
|
||||
*
|
||||
* @param id 店铺ID
|
||||
* @param status 状态:1-启用,0-停用
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean updateShopStatus(Long id, Integer status);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.dto.ResetPasswordRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.UpdatePhoneRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.UserDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
@@ -40,6 +41,16 @@ public interface UserService extends IService<UserDO> {
|
||||
|
||||
LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO);
|
||||
|
||||
LoginShopSelectionVO getLoginShopSelectionByAccount(String account);
|
||||
|
||||
LoginShopSelectionVO getLoginShopSelectionByPhone(String phone);
|
||||
|
||||
LoginShopSelectionVO getAdminLoginShopSelection(String account);
|
||||
|
||||
LoginResponseVO switchShop(Long userId, Long shopId);
|
||||
|
||||
LoginResponseVO switchAdminShop(Long userId, Long shopId);
|
||||
|
||||
boolean register(RegisterRequestDTO registerRequestDTO);
|
||||
|
||||
LoginResponseVO refreshToken(String refreshToken);
|
||||
@@ -61,6 +72,10 @@ public interface UserService extends IService<UserDO> {
|
||||
PageResultVO<UserVO> pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type);
|
||||
|
||||
boolean updateUserStatus(Long id, Integer status);
|
||||
|
||||
boolean updateUserStatusInShop(Long id, Integer status, Long shopId);
|
||||
|
||||
boolean deleteUserInShop(Long id, Long shopId);
|
||||
|
||||
boolean updateUserAvatar(Long userId, String avatarUrl);
|
||||
|
||||
|
||||
+131
-28
@@ -17,6 +17,7 @@ import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.CouponVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
@@ -30,6 +31,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -56,6 +58,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
private final TagMapper tagMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -108,6 +111,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel());
|
||||
couponDO.setAutoMatch(couponDTO.getAutoMatch());
|
||||
updateById(couponDO);
|
||||
refreshCouponDistributionStatus(id);
|
||||
|
||||
// 处理标签关联
|
||||
handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds());
|
||||
@@ -184,9 +188,15 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
if (couponDO.getStatus() != 1) {
|
||||
return false;
|
||||
}
|
||||
if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) {
|
||||
return false;
|
||||
}
|
||||
if (isVipAutoCoupon(couponDO)) {
|
||||
throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放");
|
||||
}
|
||||
if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否已经分配
|
||||
UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper<UserCouponDO>()
|
||||
@@ -197,6 +207,9 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
if (existing != null) {
|
||||
return false;
|
||||
}
|
||||
if (!hasRemainingDistributionStock(couponDO, 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 分配优惠券
|
||||
UserCouponDO userCouponDO = new UserCouponDO();
|
||||
@@ -205,6 +218,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
userCouponDO.setStatus(1);
|
||||
userCouponDO.setObtainTime(LocalDateTime.now());
|
||||
userCouponMapper.insert(userCouponDO);
|
||||
refreshCouponDistributionStatus(couponId);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -260,11 +274,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
userCouponMapper.updateById(userCouponDO);
|
||||
|
||||
// 更新优惠券使用数量
|
||||
couponDO.setUsedCount(couponDO.getUsedCount() + 1);
|
||||
if (couponDO.getUsedCount() >= couponDO.getTotalCount()) {
|
||||
couponDO.setStatus(3);
|
||||
}
|
||||
updateById(couponDO);
|
||||
incrementCouponUsedCount(couponDO.getId());
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -364,32 +374,52 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
}
|
||||
|
||||
// 检查优惠券数量是否足够
|
||||
int totalNeeded = userIds.size() * quantity;
|
||||
if (couponDO.getUsedCount() + totalNeeded > couponDO.getTotalCount()) {
|
||||
if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) {
|
||||
return false;
|
||||
}
|
||||
if (userIds == null || userIds.isEmpty() || quantity == null || quantity < 1) {
|
||||
return false;
|
||||
}
|
||||
if (quantity > 1) {
|
||||
throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张");
|
||||
}
|
||||
List<Long> targetUserIds = userIds.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (targetUserIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (Long userId : targetUserIds) {
|
||||
if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) {
|
||||
return false;
|
||||
}
|
||||
UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper<UserCouponDO>()
|
||||
.eq(UserCouponDO::getUserId, userId)
|
||||
.eq(UserCouponDO::getCouponId, couponId)
|
||||
.eq(UserCouponDO::getIsDelete, 0));
|
||||
if (existing != null) {
|
||||
throw new RuntimeException("用户已持有该优惠券,不能重复发放");
|
||||
}
|
||||
}
|
||||
|
||||
int totalNeeded = targetUserIds.size() * quantity;
|
||||
if (!hasRemainingDistributionStock(couponDO, totalNeeded)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 发放优惠券
|
||||
int distributedCount = 0;
|
||||
for (Long userId : userIds) {
|
||||
for (int i = 0; i < quantity; i++) {
|
||||
// 分配优惠券(不检查是否已存在,允许用户拥有多张相同优惠券)
|
||||
UserCouponDO userCouponDO = new UserCouponDO();
|
||||
userCouponDO.setUserId(userId);
|
||||
userCouponDO.setCouponId(couponId);
|
||||
userCouponDO.setStatus(1);
|
||||
userCouponDO.setObtainTime(LocalDateTime.now());
|
||||
userCouponMapper.insert(userCouponDO);
|
||||
distributedCount++;
|
||||
}
|
||||
LocalDateTime obtainTime = LocalDateTime.now();
|
||||
for (Long userId : targetUserIds) {
|
||||
UserCouponDO userCouponDO = new UserCouponDO();
|
||||
userCouponDO.setUserId(userId);
|
||||
userCouponDO.setCouponId(couponId);
|
||||
userCouponDO.setStatus(1);
|
||||
userCouponDO.setObtainTime(obtainTime);
|
||||
userCouponMapper.insert(userCouponDO);
|
||||
}
|
||||
|
||||
// 更新优惠券使用数量
|
||||
couponDO.setUsedCount(couponDO.getUsedCount() + distributedCount);
|
||||
if (couponDO.getUsedCount() >= couponDO.getTotalCount()) {
|
||||
couponDO.setStatus(3); // 已用完
|
||||
}
|
||||
updateById(couponDO);
|
||||
refreshCouponDistributionStatus(couponId);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -568,8 +598,8 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
couponVO.setMinAmount(couponDO.getMinAmount());
|
||||
couponVO.setReduceAmount(couponDO.getReduceAmount());
|
||||
couponVO.setTotalCount(couponDO.getTotalCount());
|
||||
couponVO.setUsedCount(couponDO.getUsedCount());
|
||||
couponVO.setRemainingCount(couponDO.getTotalCount() - couponDO.getUsedCount());
|
||||
couponVO.setUsedCount(normalizeCount(couponDO.getUsedCount()));
|
||||
couponVO.setRemainingCount(calculateRemainingDistributionCount(couponDO));
|
||||
couponVO.setStartTime(couponDO.getStartTime());
|
||||
couponVO.setEndTime(couponDO.getEndTime());
|
||||
couponVO.setStatus(couponDO.getStatus());
|
||||
@@ -715,6 +745,79 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
&& COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene());
|
||||
}
|
||||
|
||||
private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) {
|
||||
return calculateRemainingDistributionCount(couponDO) >= requiredCount;
|
||||
}
|
||||
|
||||
private int calculateRemainingDistributionCount(CouponDO couponDO) {
|
||||
if (couponDO == null || couponDO.getId() == null) {
|
||||
return 0;
|
||||
}
|
||||
int totalCount = normalizeCount(couponDO.getTotalCount());
|
||||
long issuedCount = userCouponMapper.selectCount(new LambdaQueryWrapper<UserCouponDO>()
|
||||
.eq(UserCouponDO::getCouponId, couponDO.getId())
|
||||
.eq(UserCouponDO::getIsDelete, 0));
|
||||
return Math.max(0, totalCount - (int) issuedCount);
|
||||
}
|
||||
|
||||
private void incrementCouponUsedCount(Long couponId) {
|
||||
CouponDO couponDO = getById(couponId);
|
||||
if (couponDO == null) {
|
||||
return;
|
||||
}
|
||||
couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1);
|
||||
updateById(couponDO);
|
||||
}
|
||||
|
||||
private void decrementCouponUsedCount(Long couponId) {
|
||||
CouponDO couponDO = getById(couponId);
|
||||
if (couponDO == null) {
|
||||
return;
|
||||
}
|
||||
couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1));
|
||||
updateById(couponDO);
|
||||
}
|
||||
|
||||
private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) {
|
||||
if (userId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
if (requestedShopId != null && !userShopBindingSupport.isUserAccessibleInShop(userId, requestedShopId)) {
|
||||
return false;
|
||||
}
|
||||
if (couponDO != null && couponDO.getShopId() != null
|
||||
&& !userShopBindingSupport.isUserAccessibleInShop(userId, couponDO.getShopId())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void refreshCouponDistributionStatus(Long couponId) {
|
||||
CouponDO couponDO = getById(couponId);
|
||||
if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) {
|
||||
return;
|
||||
}
|
||||
if (Integer.valueOf(2).equals(couponDO.getStatus())) {
|
||||
return;
|
||||
}
|
||||
|
||||
int remainingCount = calculateRemainingDistributionCount(couponDO);
|
||||
int targetStatus = remainingCount > 0 ? 1 : 3;
|
||||
if (!Objects.equals(couponDO.getStatus(), targetStatus)) {
|
||||
couponDO.setStatus(targetStatus);
|
||||
updateById(couponDO);
|
||||
}
|
||||
}
|
||||
|
||||
private int normalizeCount(Integer count) {
|
||||
return count == null ? 0 : count;
|
||||
}
|
||||
|
||||
private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) {
|
||||
if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
|
||||
+24
-8
@@ -10,6 +10,8 @@ import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.service.NailArtistInfoService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -28,6 +30,9 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
|
||||
@Autowired
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Autowired
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
public NailArtistInfoDTO getByUserId(Long userId) {
|
||||
@@ -60,18 +65,25 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
|
||||
@Override
|
||||
public List<NailArtistInfoDTO> getByShopId(Long shopId) {
|
||||
// 先获取该店铺的所有美甲师用户
|
||||
List<Long> artistUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (artistUserIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<UserDO> userQueryWrapper = new LambdaQueryWrapper<>();
|
||||
userQueryWrapper.eq(UserDO::getShopId, shopId);
|
||||
userQueryWrapper.eq(UserDO::getType, 3); // 3表示美甲师
|
||||
userQueryWrapper.in(UserDO::getId, artistUserIds);
|
||||
userQueryWrapper.eq(UserDO::getType, 3);
|
||||
userQueryWrapper.eq(UserDO::getIsDelete, 0);
|
||||
|
||||
|
||||
List<UserDO> userDOList = userMapper.selectList(userQueryWrapper);
|
||||
List<NailArtistInfoDTO> nailArtistInfoDTOList = new ArrayList<>();
|
||||
ShopDO currentShop = shopMapper.selectById(shopId);
|
||||
|
||||
for (UserDO userDO : userDOList) {
|
||||
NailArtistInfoDTO nailArtistInfoDTO = getByUserId(userDO.getId());
|
||||
if (nailArtistInfoDTO != null) {
|
||||
nailArtistInfoDTO.setShopId(shopId);
|
||||
nailArtistInfoDTO.setShopName(currentShop == null ? null : currentShop.getShopName());
|
||||
nailArtistInfoDTOList.add(nailArtistInfoDTO);
|
||||
}
|
||||
}
|
||||
@@ -111,13 +123,17 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
UserDO userDO = userMapper.selectById(nailArtistInfoDO.getUserId());
|
||||
if (userDO != null) {
|
||||
nailArtistInfoDTO.setNickname(userDO.getNickname());
|
||||
nailArtistInfoDTO.setShopId(userDO.getShopId());
|
||||
nailArtistInfoDTO.setSignature(userDO.getSignature()); // 添加用户签名
|
||||
|
||||
// 获取店铺信息
|
||||
if (userDO.getShopId() != null && userDO.getShopId() > 0) {
|
||||
|
||||
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(userDO.getId(), false, false);
|
||||
if (!shopOptions.isEmpty()) {
|
||||
ShopSimpleVO primaryShop = shopOptions.get(0);
|
||||
nailArtistInfoDTO.setShopId(primaryShop.getId());
|
||||
nailArtistInfoDTO.setShopName(primaryShop.getShopName());
|
||||
} else if (userDO.getShopId() != null && userDO.getShopId() > 0) {
|
||||
ShopDO shopDO = shopMapper.selectById(userDO.getShopId());
|
||||
if (shopDO != null) {
|
||||
nailArtistInfoDTO.setShopId(shopDO.getId());
|
||||
nailArtistInfoDTO.setShopName(shopDO.getShopName());
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
@@ -95,6 +96,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private TagService tagService;
|
||||
|
||||
@Resource
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
|
||||
@@ -471,7 +475,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
if (!Integer.valueOf(1).equals(artist.getStatus())) {
|
||||
throw new RuntimeException("美甲师当前不可预约");
|
||||
}
|
||||
if (product.getShopId() != null && !product.getShopId().equals(artist.getShopId())) {
|
||||
if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) {
|
||||
throw new RuntimeException("该美甲师不属于当前商品店铺");
|
||||
}
|
||||
|
||||
@@ -631,6 +635,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
|
||||
ProductDO product = productMapper.selectById(productId);
|
||||
if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) {
|
||||
product = null;
|
||||
}
|
||||
productCache.put(productId, product);
|
||||
return product;
|
||||
}
|
||||
@@ -759,6 +766,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
userCoupon.setStatus(2);
|
||||
userCoupon.setUseTime(LocalDateTime.now());
|
||||
userCouponMapper.updateById(userCoupon);
|
||||
updateCouponUsedCount(userCoupon.getCouponId(), 1);
|
||||
}
|
||||
|
||||
private void restoreUserCoupon(OrderDO order, Long userId) {
|
||||
@@ -777,6 +785,22 @@ public class OrderServiceImpl implements OrderService {
|
||||
userCoupon.setStatus(1);
|
||||
userCoupon.setUseTime(null);
|
||||
userCouponMapper.updateById(userCoupon);
|
||||
updateCouponUsedCount(userCoupon.getCouponId(), -1);
|
||||
}
|
||||
|
||||
private void updateCouponUsedCount(Long couponId, int delta) {
|
||||
if (couponId == null || delta == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
CouponDO couponDO = couponMapper.selectById(couponId);
|
||||
if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) {
|
||||
return;
|
||||
}
|
||||
|
||||
int currentUsedCount = couponDO.getUsedCount() == null ? 0 : couponDO.getUsedCount();
|
||||
couponDO.setUsedCount(Math.max(0, currentUsedCount + delta));
|
||||
couponMapper.updateById(couponDO);
|
||||
}
|
||||
|
||||
private static final class CouponSelection {
|
||||
|
||||
+122
-59
@@ -11,23 +11,21 @@ import com.xiaowang.yuminailcore.mapper.PermissionMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserPermissionMapper;
|
||||
import com.xiaowang.yuminailcore.service.PermissionService;
|
||||
import com.xiaowang.yuminailcore.support.PermissionPolicy;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 系统权限表 Service 实现
|
||||
* 对应数据库表 t_permission
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-25
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, PermissionDO> implements PermissionService {
|
||||
@@ -40,6 +38,7 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
private final PermissionMapper permissionMapper;
|
||||
private final UserPermissionMapper userPermissionMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
public Long createPermission(PermissionDTO permissionDTO) {
|
||||
@@ -56,7 +55,7 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
@Override
|
||||
public boolean updatePermission(Long id, PermissionDTO permissionDTO) {
|
||||
PermissionDO permissionDO = permissionMapper.selectById(id);
|
||||
if (permissionDO == null) {
|
||||
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
if (permissionDTO.getPermissionCode() != null) {
|
||||
@@ -78,17 +77,18 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
@Override
|
||||
public boolean deletePermission(Long id) {
|
||||
PermissionDO permissionDO = permissionMapper.selectById(id);
|
||||
if (permissionDO == null) {
|
||||
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
permissionDO.setIsDelete(1);
|
||||
permissionDO.setUpdateTime(LocalDateTime.now());
|
||||
return permissionMapper.updateById(permissionDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionVO getPermissionById(Long id) {
|
||||
PermissionDO permissionDO = permissionMapper.selectById(id);
|
||||
if (permissionDO == null) {
|
||||
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(permissionDO);
|
||||
@@ -96,23 +96,21 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
|
||||
@Override
|
||||
public List<PermissionVO> listAllPermissions() {
|
||||
List<PermissionDO> permissionDOs = permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
return permissionDOs.stream()
|
||||
return permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PermissionVO> listPermissionsByGroup(String permissionGroup) {
|
||||
List<PermissionDO> permissionDOs = permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getPermissionGroup, permissionGroup)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
return permissionDOs.stream()
|
||||
return permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getPermissionGroup, permissionGroup)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
@@ -124,22 +122,24 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
);
|
||||
|
||||
if (userPermissions.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Long> permissionIds = userPermissions.stream()
|
||||
.map(UserPermissionDO::getPermissionId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (permissionIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<PermissionDO> permissionDOs = permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.in(PermissionDO::getId, permissionIds)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
|
||||
List<PermissionVO> permissionVOs = permissionDOs.stream()
|
||||
List<PermissionVO> permissionVOs = permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.in(PermissionDO::getId, permissionIds)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@@ -156,48 +156,66 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId) {
|
||||
Long userId = userPermissionDTO.getUserId();
|
||||
List<Long> permissionIds = userPermissionDTO.getPermissionIds();
|
||||
List<Long> permissionIds = userPermissionDTO.getPermissionIds() == null
|
||||
? Collections.emptyList()
|
||||
: userPermissionDTO.getPermissionIds().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 获取当前用户信息
|
||||
UserDO currentUser = userMapper.selectById(currentUserId);
|
||||
if (currentUser == null) {
|
||||
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
|
||||
throw new RuntimeException("当前用户不存在");
|
||||
}
|
||||
|
||||
// 获取被分配权限的用户信息
|
||||
UserDO targetUser = userMapper.selectById(userId);
|
||||
if (targetUser == null) {
|
||||
if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) {
|
||||
throw new RuntimeException("目标用户不存在");
|
||||
}
|
||||
|
||||
// 检查权限:只有拥有权限分配权限的用户可以给其他用户分配权限
|
||||
if (!hasPermission(currentUserId, "permission:assign")) {
|
||||
throw new RuntimeException("权限不足,没有权限分配权限");
|
||||
throw new RuntimeException("权限不足,无法分配权限");
|
||||
}
|
||||
|
||||
// 如果当前用户是店长,需要进一步检查
|
||||
if (currentUser.getType() == 2) {
|
||||
// 店长只能给属于自己店铺的用户分配权限
|
||||
if (targetUser.getShopId() == null || !targetUser.getShopId().equals(currentUser.getShopId())) {
|
||||
throw new RuntimeException("权限不足,只能给本店铺的用户分配权限");
|
||||
boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType());
|
||||
Long currentShopId = RequestShopContext.getCurrentShopId();
|
||||
if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) {
|
||||
throw new RuntimeException("当前角色不能维护该用户的权限");
|
||||
}
|
||||
|
||||
if (!platformAdmin) {
|
||||
if (currentUserId.equals(userId)) {
|
||||
throw new RuntimeException("不允许给自己调整权限");
|
||||
}
|
||||
if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(userId, currentShopId)) {
|
||||
throw new RuntimeException("只能给本店铺用户分配权限");
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> requestedPermissionCodes = resolvePermissionCodes(permissionIds);
|
||||
Set<String> allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType());
|
||||
if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) {
|
||||
throw new RuntimeException("目标角色的权限配置超出允许范围");
|
||||
}
|
||||
|
||||
if (!platformAdmin) {
|
||||
Set<String> operatorPermissionCodes = listPermissionCodesByUserId(currentUserId);
|
||||
if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) {
|
||||
throw new RuntimeException("不能分配超出自己已有的权限");
|
||||
}
|
||||
}
|
||||
|
||||
// 删除旧的权限分配
|
||||
userPermissionMapper.delete(
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
);
|
||||
|
||||
// 分配新的权限
|
||||
if (permissionIds != null && !permissionIds.isEmpty()) {
|
||||
for (Long permissionId : permissionIds) {
|
||||
UserPermissionDO userPermissionDO = new UserPermissionDO();
|
||||
userPermissionDO.setUserId(userId);
|
||||
userPermissionDO.setPermissionId(permissionId);
|
||||
userPermissionDO.setCreateBy(currentUserId);
|
||||
userPermissionMapper.insert(userPermissionDO);
|
||||
}
|
||||
for (Long permissionId : permissionIds) {
|
||||
UserPermissionDO userPermissionDO = new UserPermissionDO();
|
||||
userPermissionDO.setUserId(userId);
|
||||
userPermissionDO.setPermissionId(permissionId);
|
||||
userPermissionDO.setCreateBy(currentUserId);
|
||||
userPermissionMapper.insert(userPermissionDO);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -210,26 +228,25 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
);
|
||||
|
||||
if (userPermissions.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Long> permissionIds = userPermissions.stream()
|
||||
.map(UserPermissionDO::getPermissionId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (permissionIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
PermissionDO permissionDO = permissionMapper.selectOne(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getPermissionCode, permissionCode)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
|
||||
if (permissionDO == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!permissionIds.contains(permissionDO.getId())) {
|
||||
if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -240,10 +257,56 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
return true;
|
||||
}
|
||||
|
||||
private Set<String> resolvePermissionCodes(List<Long> permissionIds) {
|
||||
if (permissionIds == null || permissionIds.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<PermissionDO> permissionDOs = permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.in(PermissionDO::getId, permissionIds)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
if (permissionDOs.size() != permissionIds.size()) {
|
||||
throw new RuntimeException("存在无效的权限配置");
|
||||
}
|
||||
|
||||
return permissionDOs.stream()
|
||||
.map(PermissionDO::getPermissionCode)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private Set<String> listPermissionCodesByUserId(Long userId) {
|
||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
);
|
||||
if (userPermissions.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<Long> permissionIds = userPermissions.stream()
|
||||
.map(UserPermissionDO::getPermissionId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (permissionIds.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
return permissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.in(PermissionDO::getId, permissionIds)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
).stream()
|
||||
.map(PermissionDO::getPermissionCode)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private boolean isShopBootstrapAdmin(UserDO userDO) {
|
||||
return userDO != null
|
||||
&& Integer.valueOf(4).equals(userDO.getType())
|
||||
&& (userDO.getShopId() == null || userDO.getShopId() <= 0);
|
||||
&& RequestShopContext.getCurrentShopId() == null;
|
||||
}
|
||||
|
||||
private PermissionVO convertToVO(PermissionDO permissionDO) {
|
||||
|
||||
+17
-4
@@ -12,6 +12,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.service.ProductService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ProductVO;
|
||||
@@ -40,6 +41,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
private final TagService tagService;
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
public Long createProduct(ProductDTO productDTO) {
|
||||
@@ -80,7 +82,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
|
||||
@Override
|
||||
public boolean deleteProduct(Long id) {
|
||||
return removeById(id);
|
||||
ProductDO productDO = productMapper.selectById(id);
|
||||
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
productDO.setIsDelete(1);
|
||||
return productMapper.updateById(productDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,7 +103,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
@Override
|
||||
public ProductVO getProductById(Long id) {
|
||||
ProductDO productDO = productMapper.selectById(id);
|
||||
if (productDO == null) {
|
||||
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(productDO);
|
||||
@@ -104,7 +111,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
|
||||
@Override
|
||||
public List<ProductVO> listAllProducts() {
|
||||
List<ProductDO> productDOs = productMapper.selectList(null);
|
||||
List<ProductDO> productDOs = productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
);
|
||||
return productDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
@@ -114,6 +124,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
public List<ProductVO> listProductsByShopId(Long shopId) {
|
||||
List<ProductDO> productDOs = productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.eq(ProductDO::getShopId, shopId)
|
||||
);
|
||||
return productDOs.stream()
|
||||
@@ -133,6 +144,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
String tagIdStr = String.valueOf(tagVO.getId());
|
||||
List<ProductDO> productDOs = productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.and(wrapper -> wrapper
|
||||
.eq(ProductDO::getTags, tagIdStr)
|
||||
.or()
|
||||
@@ -225,6 +237,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
Page<ProductDO> pageParam = new Page<>(page, size);
|
||||
|
||||
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class);
|
||||
wrapper.eq(ProductDO::getIsDelete, 0);
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
wrapper.and(w -> w.like(ProductDO::getTitle, keyword)
|
||||
.or().like(ProductDO::getDescription, keyword));
|
||||
@@ -273,7 +286,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
if (!Integer.valueOf(3).equals(artist.getType())) {
|
||||
throw new RuntimeException("存在非美甲师账号被配置到可预约列表");
|
||||
}
|
||||
if (!shopId.equals(artist.getShopId())) {
|
||||
if (!userShopBindingSupport.isUserAccessibleInShop(artistId, shopId)) {
|
||||
throw new RuntimeException("不可跨店铺配置可预约美甲师");
|
||||
}
|
||||
}
|
||||
|
||||
+87
-3
@@ -5,10 +5,21 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.CouponDO;
|
||||
import com.xiaowang.yuminailcore.entity.CommentDO;
|
||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import com.xiaowang.yuminailcore.entity.TagDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserCouponDO;
|
||||
import com.xiaowang.yuminailcore.mapper.CommentMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -32,6 +43,12 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final CouponService couponService;
|
||||
private final CouponMapper couponMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final TagMapper tagMapper;
|
||||
private final CommentMapper commentMapper;
|
||||
private final UserCouponMapper userCouponMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -43,6 +60,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
shopDO.setBusinessHours(shopDTO.getBusinessHours());
|
||||
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
|
||||
shopDO.setImageFileIds(shopDTO.getImageFileIds());
|
||||
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
|
||||
shopDO.setIsDelete(0);
|
||||
shopMapper.insert(shopDO);
|
||||
couponService.initializeDefaultVipAutoCoupons(shopDO.getId());
|
||||
@@ -61,22 +79,68 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
shopDO.setBusinessHours(shopDTO.getBusinessHours());
|
||||
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
|
||||
shopDO.setImageFileIds(shopDTO.getImageFileIds());
|
||||
if (shopDTO.getStatus() != null) {
|
||||
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
|
||||
}
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean deleteShop(Long id) {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null) {
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
return this.removeById(id);
|
||||
List<Long> couponIds = couponMapper.selectList(Wrappers.lambdaQuery(CouponDO.class)
|
||||
.select(CouponDO::getId)
|
||||
.eq(CouponDO::getShopId, id)
|
||||
.eq(CouponDO::getIsDelete, 0))
|
||||
.stream()
|
||||
.map(CouponDO::getId)
|
||||
.toList();
|
||||
productMapper.update(null, Wrappers.lambdaUpdate(ProductDO.class)
|
||||
.eq(ProductDO::getShopId, id)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.set(ProductDO::getIsDelete, 1));
|
||||
couponMapper.update(null, Wrappers.lambdaUpdate(CouponDO.class)
|
||||
.eq(CouponDO::getShopId, id)
|
||||
.eq(CouponDO::getIsDelete, 0)
|
||||
.set(CouponDO::getIsDelete, 1));
|
||||
tagMapper.update(null, Wrappers.lambdaUpdate(TagDO.class)
|
||||
.eq(TagDO::getShopId, id)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.set(TagDO::getIsDelete, 1));
|
||||
commentMapper.update(null, Wrappers.lambdaUpdate(CommentDO.class)
|
||||
.eq(CommentDO::getShopId, id)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.set(CommentDO::getIsDelete, 1));
|
||||
if (!couponIds.isEmpty()) {
|
||||
userCouponMapper.update(null, Wrappers.lambdaUpdate(UserCouponDO.class)
|
||||
.in(UserCouponDO::getCouponId, couponIds)
|
||||
.eq(UserCouponDO::getIsDelete, 0)
|
||||
.set(UserCouponDO::getIsDelete, 1));
|
||||
}
|
||||
userShopBindingSupport.deleteBindingsByShopId(id);
|
||||
shopDO.setStatus(0);
|
||||
shopDO.setIsDelete(1);
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateShopStatus(Long id, Integer status) {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
shopDO.setStatus(normalizeStatus(status));
|
||||
return shopMapper.updateById(shopDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ShopVO getShopById(Long id) {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null) {
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(shopDO);
|
||||
@@ -87,6 +151,19 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
List<ShopDO> shopDOs = shopMapper.selectList(
|
||||
Wrappers.lambdaQuery(ShopDO.class)
|
||||
.eq(ShopDO::getIsDelete, 0)
|
||||
.eq(ShopDO::getStatus, 1)
|
||||
);
|
||||
return shopDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ShopVO> listAllShopsForAdmin() {
|
||||
List<ShopDO> shopDOs = shopMapper.selectList(
|
||||
Wrappers.lambdaQuery(ShopDO.class)
|
||||
.eq(ShopDO::getIsDelete, 0)
|
||||
.orderByDesc(ShopDO::getCreateTime)
|
||||
);
|
||||
return shopDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
@@ -97,6 +174,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
public List<ShopVO> listShopsByShopName(String shopName) {
|
||||
List<ShopDO> shopDOs = shopMapper.selectList(
|
||||
Wrappers.lambdaQuery(ShopDO.class)
|
||||
.eq(ShopDO::getIsDelete, 0)
|
||||
.eq(ShopDO::getStatus, 1)
|
||||
.like(ShopDO::getShopName, shopName)
|
||||
);
|
||||
return shopDOs.stream()
|
||||
@@ -148,8 +227,13 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
shopVO.setCoverImageUrls(new java.util.ArrayList<>());
|
||||
shopVO.setImageFileIds(shopDO.getImageFileIds());
|
||||
shopVO.setImageUrls(new java.util.ArrayList<>());
|
||||
shopVO.setStatus(normalizeStatus(shopDO.getStatus()));
|
||||
shopVO.setCreateTime(shopDO.getCreateTime());
|
||||
shopVO.setUpdateTime(shopDO.getUpdateTime());
|
||||
return shopVO;
|
||||
}
|
||||
|
||||
private Integer normalizeStatus(Integer status) {
|
||||
return Integer.valueOf(0).equals(status) ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
+457
-180
@@ -16,9 +16,14 @@ import com.xiaowang.yuminailcore.service.NailArtistInfoService;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.VerificationCodeService;
|
||||
import com.xiaowang.yuminailcore.support.PermissionPolicy;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.utils.JwtUtil;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -29,6 +34,7 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -52,43 +58,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
|
||||
private static final String DELETED_PHONE_MARKER = "_deleted_";
|
||||
private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L;
|
||||
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"dashboard:view",
|
||||
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
|
||||
"user:balance:view",
|
||||
"product:view",
|
||||
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
|
||||
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
|
||||
"tag:view",
|
||||
"coupon:view",
|
||||
"order:view",
|
||||
"nail_artist:view"
|
||||
);
|
||||
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"dashboard:view",
|
||||
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
|
||||
"user:balance:view", "user:balance:manage", "user:vip:manage",
|
||||
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
|
||||
"shop:view", "shop:edit", "shop:staff:manage",
|
||||
"permission:view", "permission:assign",
|
||||
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
||||
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
||||
"order:view", "order:process", "order:edit", "order:delete",
|
||||
"nail_artist:view", "nail_artist:edit"
|
||||
);
|
||||
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"user:view", "user:create",
|
||||
"user:balance:view",
|
||||
"product:view", "product:create",
|
||||
"shop:view",
|
||||
"tag:view", "tag:create",
|
||||
"coupon:view",
|
||||
"order:view"
|
||||
);
|
||||
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = buildManagedDefaultPermissionCodes();
|
||||
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes();
|
||||
private static final Map<String, PermissionSeed> DEFAULT_PERMISSION_SEEDS = buildDefaultPermissionSeeds();
|
||||
|
||||
// 注入用户数据访问层、JWT工具类和店铺服务
|
||||
@@ -100,14 +70,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private final NailArtistInfoService nailArtistInfoService;
|
||||
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
|
||||
private static Set<String> buildManagedDefaultPermissionCodes() {
|
||||
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
|
||||
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
|
||||
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
|
||||
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
|
||||
return Set.copyOf(permissionCodes);
|
||||
}
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
|
||||
Map<String, PermissionSeed> seeds = new HashMap<>();
|
||||
@@ -244,12 +207,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
|
||||
private List<String> getDefaultPermissionCodes(Integer userType) {
|
||||
return switch (userType == null ? -1 : userType) {
|
||||
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
|
||||
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
|
||||
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
|
||||
default -> List.of();
|
||||
};
|
||||
return PermissionPolicy.getDefaultPermissionCodes(userType);
|
||||
}
|
||||
|
||||
private void assignDefaultPermissions(Long userId, Integer userType) {
|
||||
@@ -274,8 +232,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("账号已存在");
|
||||
}
|
||||
|
||||
Long validatedShopId = validateAndNormalizeShopId(userDTO.getShopId());
|
||||
List<Long> validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId());
|
||||
Long validatedShopId = pickPrimaryShopId(validatedShopIds);
|
||||
String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true);
|
||||
Integer userType = userDTO.getType();
|
||||
|
||||
ensureShopBindingRequirement(userType, validatedShopIds);
|
||||
|
||||
// 创建用户实体并设置属性
|
||||
UserDO userDO = new UserDO();
|
||||
@@ -286,7 +248,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userDO.setPhone(validatedPhone);
|
||||
userDO.setSignature(userDTO.getSignature());
|
||||
userDO.setLevel(userDTO.getLevel());
|
||||
userDO.setType(userDTO.getType());
|
||||
userDO.setType(userType);
|
||||
userDO.setVipId(userDTO.getVipId());
|
||||
userDO.setIsDelete(0);
|
||||
userDO.setStatus(1);
|
||||
@@ -316,6 +278,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
// 分配默认权限
|
||||
assignDefaultPermissions(userDO.getId(), userDO.getType());
|
||||
userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds);
|
||||
|
||||
// 如果是美甲师,创建对应的美甲师信息记录
|
||||
if (userDO.getType() == 3) {
|
||||
@@ -407,8 +370,23 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
if (userDTO.getVipId() != null) {
|
||||
userDO.setVipId(userDTO.getVipId());
|
||||
}
|
||||
Integer targetUserType = userDO.getType();
|
||||
List<Long> validatedShopIds = null;
|
||||
boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null;
|
||||
if (shopBindingChanged) {
|
||||
validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId());
|
||||
ensureShopBindingRequirement(targetUserType, validatedShopIds);
|
||||
userDO.setShopId(pickPrimaryShopId(validatedShopIds));
|
||||
}
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
boolean updated = userMapper.updateById(userDO) > 0;
|
||||
if (updated) {
|
||||
if (shopBindingChanged) {
|
||||
userShopBindingSupport.syncUserShopBindings(id, validatedShopIds);
|
||||
}
|
||||
syncDefaultPermissions(id, targetUserType);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -418,7 +396,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
@Override
|
||||
public boolean deleteUser(Long id) {
|
||||
return removeById(id);
|
||||
UserDO userDO = userMapper.selectById(id);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
userDO.setAccount(buildDeletedAccount(userDO));
|
||||
userDO.setPhone(buildDeletedPhone(userDO));
|
||||
userDO.setStatus(0);
|
||||
userDO.setIsDelete(1);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -429,7 +417,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
@Override
|
||||
public UserVO getUserById(Long id) {
|
||||
UserDO userDO = userMapper.selectById(id);
|
||||
if (userDO == null) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(userDO);
|
||||
@@ -457,10 +445,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
*/
|
||||
@Override
|
||||
public List<UserVO> listUsersByShopId(Long shopId) {
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (userIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<UserDO> userDOs = userMapper.selectList(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.eq(UserDO::getShopId, shopId)
|
||||
.in(UserDO::getId, userIds)
|
||||
);
|
||||
return userDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
@@ -494,8 +486,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, account)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
);
|
||||
if (userDO == null) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return null;
|
||||
}
|
||||
return convertToVO(userDO);
|
||||
@@ -510,13 +503,23 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private UserVO convertToVO(UserDO userDO) {
|
||||
UserVO userVO = new UserVO();
|
||||
userVO.setId(userDO.getId());
|
||||
userVO.setShopId(userDO.getShopId());
|
||||
if (userDO.getShopId() != null && userDO.getShopId() > 0) {
|
||||
ShopVO shopVO = shopService.getShopById(userDO.getShopId());
|
||||
if (shopVO != null) {
|
||||
userVO.setShopName(shopVO.getShopName());
|
||||
}
|
||||
List<ShopSimpleVO> shopOptions = resolveShopOptions(userDO, false, false);
|
||||
Long scopedShopId = RequestShopContext.getCurrentShopId();
|
||||
if (scopedShopId != null) {
|
||||
shopOptions.stream()
|
||||
.filter(shop -> Objects.equals(shop.getId(), scopedShopId))
|
||||
.findFirst()
|
||||
.ifPresent(shop -> {
|
||||
shopOptions.remove(shop);
|
||||
shopOptions.add(0, shop);
|
||||
});
|
||||
}
|
||||
Long primaryShopId = !shopOptions.isEmpty() ? shopOptions.get(0).getId() : normalizeShopId(userDO.getShopId());
|
||||
String primaryShopName = !shopOptions.isEmpty() ? shopOptions.get(0).getShopName() : null;
|
||||
userVO.setShopId(primaryShopId);
|
||||
userVO.setShopName(primaryShopName);
|
||||
userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList()));
|
||||
userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
|
||||
userVO.setNickname(userDO.getNickname());
|
||||
userVO.setAccount(userDO.getAccount());
|
||||
userVO.setPhone(userDO.getPhone());
|
||||
@@ -528,10 +531,130 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userVO.setVipId(userDO.getVipId());
|
||||
userVO.setCreateTime(userDO.getCreateTime());
|
||||
userVO.setUpdateTime(userDO.getUpdateTime());
|
||||
userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1);
|
||||
Integer scopedStatus = userShopBindingSupport.listBindingsByUserId(userDO.getId(), false).stream()
|
||||
.filter(binding -> Objects.equals(binding.getShopId(), scopedShopId))
|
||||
.map(binding -> Integer.valueOf(1).equals(binding.getStatus()) ? 1 : 0)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
userVO.setStatus(scopedStatus != null ? scopedStatus : (userDO.getStatus() != null ? userDO.getStatus() : 1));
|
||||
return userVO;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) {
|
||||
String normalizedAccount = account == null ? "" : account.trim();
|
||||
if (!StringUtils.hasText(normalizedAccount)) {
|
||||
return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺");
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号未注册");
|
||||
}
|
||||
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
|
||||
}
|
||||
|
||||
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
|
||||
if (!shops.isEmpty()) {
|
||||
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
|
||||
}
|
||||
|
||||
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
|
||||
return buildLoginShopSelection(
|
||||
userShopBindingSupport.listAllActiveShopOptions(),
|
||||
false,
|
||||
"该账号首次登录,请先选择店铺"
|
||||
);
|
||||
}
|
||||
|
||||
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理");
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) {
|
||||
String normalizedPhone = phone == null ? "" : phone.trim();
|
||||
if (!StringUtils.hasText(normalizedPhone)) {
|
||||
return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺");
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getPhone, normalizedPhone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(
|
||||
userShopBindingSupport.listAllActiveShopOptions(),
|
||||
false,
|
||||
"新手机号首次登录需要选择店铺"
|
||||
);
|
||||
}
|
||||
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
|
||||
}
|
||||
|
||||
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
|
||||
if (!shops.isEmpty()) {
|
||||
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
|
||||
}
|
||||
|
||||
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
|
||||
return buildLoginShopSelection(
|
||||
userShopBindingSupport.listAllActiveShopOptions(),
|
||||
false,
|
||||
"该手机号账号首次登录,请先选择店铺"
|
||||
);
|
||||
}
|
||||
|
||||
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理");
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginShopSelectionVO getAdminLoginShopSelection(String account) {
|
||||
String normalizedAccount = account == null ? "" : account.trim();
|
||||
if (!StringUtils.hasText(normalizedAccount)) {
|
||||
return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺");
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getAccount, normalizedAccount)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (userDO == null) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号不存在");
|
||||
}
|
||||
if (userDO.getType() == null || userDO.getType() < 2) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号没有后台管理权限");
|
||||
}
|
||||
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
|
||||
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
|
||||
}
|
||||
|
||||
if (Integer.valueOf(4).equals(userDO.getType())) {
|
||||
List<ShopSimpleVO> shops = userShopBindingSupport.listAllActiveShopOptions();
|
||||
boolean allowShoplessLogin = shops.isEmpty();
|
||||
String message = allowShoplessLogin
|
||||
? "当前暂无启用店铺,可直接登录后台创建店铺"
|
||||
: buildLoginShopMessage(shops);
|
||||
return buildLoginShopSelection(shops, allowShoplessLogin, message);
|
||||
}
|
||||
|
||||
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
|
||||
if (!shops.isEmpty()) {
|
||||
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
|
||||
}
|
||||
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系平台管理员");
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginResponseVO login(LoginRequestDTO loginRequestDTO) {
|
||||
UserDO userDO = userMapper.selectOne(
|
||||
@@ -550,33 +673,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("密码错误");
|
||||
}
|
||||
|
||||
// 检查是否需要设置店铺
|
||||
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
|
||||
if (loginRequestDTO.getShopId() == null || loginRequestDTO.getShopId() == 0) {
|
||||
throw new RuntimeException("请选择店铺");
|
||||
}
|
||||
userDO.setShopId(loginRequestDTO.getShopId());
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(userDO);
|
||||
}
|
||||
|
||||
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
|
||||
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(accessToken);
|
||||
responseVO.setRefreshToken(refreshToken);
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(userDO.getShopId());
|
||||
userInfo.setCreateTime(userDO.getCreateTime());
|
||||
responseVO.setUserInfo(userInfo);
|
||||
|
||||
return responseVO;
|
||||
Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId());
|
||||
return buildLoginResponse(userDO, resolvedShopId, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -598,35 +696,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId());
|
||||
} else {
|
||||
assertUserAvailable(userDO);
|
||||
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
|
||||
if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) {
|
||||
throw new RuntimeException("请选择店铺");
|
||||
}
|
||||
userDO.setShopId(phoneLoginRequestDTO.getShopId());
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(userDO);
|
||||
}
|
||||
}
|
||||
|
||||
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
|
||||
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(accessToken);
|
||||
responseVO.setRefreshToken(refreshToken);
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(userDO.getShopId());
|
||||
userInfo.setCreateTime(userDO.getCreateTime());
|
||||
responseVO.setUserInfo(userInfo);
|
||||
|
||||
responseVO.setNeedSetPassword(ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
|
||||
return responseVO;
|
||||
Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId());
|
||||
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
}
|
||||
|
||||
// 未设置密码的特殊标识
|
||||
@@ -634,6 +707,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识
|
||||
|
||||
private UserDO registerByPhone(String phone, Long shopId) {
|
||||
Long validatedShopId = validateAndNormalizeShopId(shopId);
|
||||
if (validatedShopId == null) {
|
||||
throw new RuntimeException("首次登录需要选择店铺");
|
||||
}
|
||||
UserDO userDO = new UserDO();
|
||||
userDO.setAccount(phone);
|
||||
userDO.setPhone(phone);
|
||||
@@ -642,7 +719,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
userDO.setType(0);
|
||||
userDO.setLevel(VIP_LEVEL_NORMAL);
|
||||
userDO.setVipId(0L);
|
||||
userDO.setShopId(shopId);
|
||||
userDO.setShopId(validatedShopId);
|
||||
userDO.setIsDelete(0);
|
||||
userDO.setStatus(1);
|
||||
userDO.setCreateTime(LocalDateTime.now());
|
||||
@@ -651,6 +728,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
userMapper.insert(userDO);
|
||||
syncDefaultPermissions(userDO.getId(), userDO.getType());
|
||||
userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId));
|
||||
return userDO;
|
||||
}
|
||||
|
||||
@@ -676,30 +754,30 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
syncDefaultPermissions(userDO.getId(), userType);
|
||||
|
||||
Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId());
|
||||
Long currentShopId = normalizeShopId(userDO.getShopId());
|
||||
if (!Objects.equals(resolvedShopId, currentShopId)) {
|
||||
userDO.setShopId(resolvedShopId);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(userDO);
|
||||
return buildLoginResponse(userDO, resolvedShopId, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginResponseVO switchShop(Long userId, Long shopId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
if (userDO.getType() != null && userDO.getType() >= 2) {
|
||||
throw new RuntimeException("当前账号请使用后台切换店铺");
|
||||
}
|
||||
Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
|
||||
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
}
|
||||
|
||||
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
|
||||
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(accessToken);
|
||||
responseVO.setRefreshToken(refreshToken);
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(resolvedShopId);
|
||||
userInfo.setCreateTime(userDO.getCreateTime());
|
||||
responseVO.setUserInfo(userInfo);
|
||||
|
||||
return responseVO;
|
||||
@Override
|
||||
public LoginResponseVO switchAdminShop(Long userId, Long shopId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
Integer userType = userDO.getType();
|
||||
if (userType == null || userType < 2) {
|
||||
throw new RuntimeException("您没有后台管理权限");
|
||||
}
|
||||
Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId);
|
||||
return buildLoginResponse(userDO, resolvedShopId, false);
|
||||
}
|
||||
|
||||
private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) {
|
||||
@@ -707,31 +785,36 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return null;
|
||||
}
|
||||
|
||||
if (requestedShopId == null || requestedShopId <= 0) {
|
||||
throw new RuntimeException("请选择登录店铺");
|
||||
}
|
||||
|
||||
ShopVO shopVO = shopService.getShopById(requestedShopId);
|
||||
if (shopVO == null) {
|
||||
throw new RuntimeException("所选店铺不存在或已失效");
|
||||
}
|
||||
|
||||
if (Integer.valueOf(4).equals(userDO.getType())) {
|
||||
return requestedShopId;
|
||||
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
|
||||
if (normalizedRequestedShopId == null) {
|
||||
throw new RuntimeException("请选择登录店铺");
|
||||
}
|
||||
if (!userShopBindingSupport.isShopActive(normalizedRequestedShopId)) {
|
||||
throw new RuntimeException("所选店铺不存在或已停用");
|
||||
}
|
||||
return normalizedRequestedShopId;
|
||||
}
|
||||
|
||||
Long boundShopId = normalizeShopId(userDO.getShopId());
|
||||
if (boundShopId == null) {
|
||||
return requestedShopId;
|
||||
List<Long> activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId());
|
||||
if (activeShopIds.isEmpty()) {
|
||||
throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员");
|
||||
}
|
||||
if (!boundShopId.equals(requestedShopId)) {
|
||||
throw new RuntimeException("当前账号只能选择所属店铺登录");
|
||||
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
|
||||
if (normalizedRequestedShopId != null) {
|
||||
if (!activeShopIds.contains(normalizedRequestedShopId)) {
|
||||
throw new RuntimeException("当前账号无权登录所选店铺");
|
||||
}
|
||||
return normalizedRequestedShopId;
|
||||
}
|
||||
return boundShopId;
|
||||
if (activeShopIds.size() == 1) {
|
||||
return activeShopIds.get(0);
|
||||
}
|
||||
throw new RuntimeException("请选择登录店铺");
|
||||
}
|
||||
|
||||
private boolean hasAnyShop() {
|
||||
return !shopService.listAllShops().isEmpty();
|
||||
return !userShopBindingSupport.listAllActiveShopOptions().isEmpty();
|
||||
}
|
||||
|
||||
private Long normalizeShopId(Long shopId) {
|
||||
@@ -767,8 +850,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
throw new RuntimeException("该手机号已被注册");
|
||||
}
|
||||
|
||||
Long validatedShopId = validateAndNormalizeShopId(registerRequestDTO.getShopId());
|
||||
if (validatedShopId == null) {
|
||||
throw new RuntimeException("请选择店铺");
|
||||
}
|
||||
|
||||
UserDO userDO = new UserDO();
|
||||
userDO.setShopId(registerRequestDTO.getShopId());
|
||||
userDO.setShopId(validatedShopId);
|
||||
userDO.setAccount(registerRequestDTO.getAccount());
|
||||
userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword()));
|
||||
userDO.setNickname(registerRequestDTO.getNickname());
|
||||
@@ -783,6 +871,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
userMapper.insert(userDO);
|
||||
assignDefaultPermissions(userDO.getId(), userDO.getType());
|
||||
userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -798,27 +887,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
Long userId = jwtUtil.getUserIdFromToken(refreshToken);
|
||||
String account = jwtUtil.getAccountFromToken(refreshToken);
|
||||
Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken));
|
||||
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
assertUserAvailable(userDO);
|
||||
boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2;
|
||||
if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) {
|
||||
throw new RuntimeException("当前登录店铺已失效,请重新登录");
|
||||
}
|
||||
|
||||
String newAccessToken = jwtUtil.generateAccessToken(userId, account);
|
||||
String newRefreshToken = jwtUtil.generateRefreshToken(userId, account);
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(newAccessToken);
|
||||
responseVO.setRefreshToken(newRefreshToken);
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(userDO.getShopId());
|
||||
userInfo.setCreateTime(userDO.getCreateTime());
|
||||
responseVO.setUserInfo(userInfo);
|
||||
|
||||
return responseVO;
|
||||
return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -928,7 +1006,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
.or().like(UserDO::getPhone, keyword));
|
||||
}
|
||||
if (shopId != null && shopId > 0) {
|
||||
wrapper.eq(UserDO::getShopId, shopId);
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (userIds.isEmpty()) {
|
||||
PageResultVO<UserVO> emptyResult = new PageResultVO<>();
|
||||
emptyResult.setList(List.of());
|
||||
emptyResult.setTotal(0L);
|
||||
emptyResult.setPage(page);
|
||||
emptyResult.setSize(size);
|
||||
return emptyResult;
|
||||
}
|
||||
wrapper.in(UserDO::getId, userIds);
|
||||
}
|
||||
if (type != null) {
|
||||
wrapper.eq(UserDO::getType, type);
|
||||
@@ -949,13 +1036,31 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
@Override
|
||||
public boolean updateUserStatus(Long id, Integer status) {
|
||||
UserDO userDO = userMapper.selectById(id);
|
||||
if (userDO == null) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
userDO.setStatus(status);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) {
|
||||
Long normalizedShopId = normalizeShopId(shopId);
|
||||
if (normalizedShopId == null) {
|
||||
throw new RuntimeException("当前操作缺少店铺上下文");
|
||||
}
|
||||
return userShopBindingSupport.updateBindingStatus(id, normalizedShopId, status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteUserInShop(Long id, Long shopId) {
|
||||
Long normalizedShopId = normalizeShopId(shopId);
|
||||
if (normalizedShopId == null) {
|
||||
throw new RuntimeException("当前操作缺少店铺上下文");
|
||||
}
|
||||
return userShopBindingSupport.deleteBinding(id, normalizedShopId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateUserAvatar(Long userId, String avatarUrl) {
|
||||
@@ -1030,6 +1135,25 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
return userMapper.updateById(userDO) > 0;
|
||||
}
|
||||
|
||||
private String buildDeletedAccount(UserDO userDO) {
|
||||
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
|
||||
String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted";
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
private String buildDeletedPhone(UserDO userDO) {
|
||||
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
|
||||
String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone";
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
private String trimDeletedPlaceholder(String value, int maxLength) {
|
||||
if (!StringUtils.hasText(value) || value.length() <= maxLength) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(value.length() - maxLength);
|
||||
}
|
||||
|
||||
private void assertUserAvailable(UserDO userDO) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
throw new RuntimeException("用户不存在");
|
||||
@@ -1048,12 +1172,165 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
}
|
||||
|
||||
private List<Long> resolveValidatedShopIds(List<Long> shopIds, Long fallbackShopId) {
|
||||
LinkedHashSet<Long> resolvedShopIds = new LinkedHashSet<>();
|
||||
if (shopIds != null) {
|
||||
for (Long shopId : shopIds) {
|
||||
Long validatedShopId = validateAndNormalizeShopId(shopId);
|
||||
if (validatedShopId != null) {
|
||||
resolvedShopIds.add(validatedShopId);
|
||||
}
|
||||
}
|
||||
}
|
||||
Long validatedFallbackShopId = validateAndNormalizeShopId(fallbackShopId);
|
||||
if (validatedFallbackShopId != null) {
|
||||
resolvedShopIds.add(validatedFallbackShopId);
|
||||
}
|
||||
return new ArrayList<>(resolvedShopIds);
|
||||
}
|
||||
|
||||
private Long pickPrimaryShopId(List<Long> shopIds) {
|
||||
return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0);
|
||||
}
|
||||
|
||||
private void ensureShopBindingRequirement(Integer userType, List<Long> shopIds) {
|
||||
if (Integer.valueOf(4).equals(userType)) {
|
||||
return;
|
||||
}
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
throw new RuntimeException("请至少选择一个所属店铺");
|
||||
}
|
||||
}
|
||||
|
||||
private LoginShopSelectionVO buildLoginShopSelection(List<ShopSimpleVO> shops, boolean allowShoplessLogin, String message) {
|
||||
LoginShopSelectionVO selectionVO = new LoginShopSelectionVO();
|
||||
selectionVO.setAllowShoplessLogin(allowShoplessLogin);
|
||||
selectionVO.setMessage(message);
|
||||
selectionVO.setShops(shops == null ? new ArrayList<>() : new ArrayList<>(shops));
|
||||
return selectionVO;
|
||||
}
|
||||
|
||||
private String buildLoginShopMessage(List<ShopSimpleVO> shops) {
|
||||
if (shops == null || shops.isEmpty()) {
|
||||
return "当前暂无可选店铺";
|
||||
}
|
||||
if (shops.size() == 1) {
|
||||
return "已匹配到 1 家可登录店铺";
|
||||
}
|
||||
return "该账号已绑定多家店铺,请选择本次登录店铺";
|
||||
}
|
||||
|
||||
private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) {
|
||||
Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId);
|
||||
List<Long> activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId());
|
||||
if (!activeShopIds.isEmpty()) {
|
||||
if (normalizedRequestedShopId != null) {
|
||||
if (!activeShopIds.contains(normalizedRequestedShopId)) {
|
||||
throw new RuntimeException("当前账号无权登录所选店铺");
|
||||
}
|
||||
return normalizedRequestedShopId;
|
||||
}
|
||||
if (activeShopIds.size() == 1) {
|
||||
return activeShopIds.get(0);
|
||||
}
|
||||
throw new RuntimeException("请选择登录店铺");
|
||||
}
|
||||
|
||||
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
|
||||
if (normalizedRequestedShopId != null) {
|
||||
userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), normalizedRequestedShopId);
|
||||
return normalizedRequestedShopId;
|
||||
}
|
||||
|
||||
Long legacyShopId = normalizeShopId(userDO.getShopId());
|
||||
if (legacyShopId != null && userShopBindingSupport.isShopActive(legacyShopId)) {
|
||||
userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), legacyShopId);
|
||||
return legacyShopId;
|
||||
}
|
||||
|
||||
throw new RuntimeException("请选择店铺");
|
||||
}
|
||||
|
||||
throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理");
|
||||
}
|
||||
|
||||
private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) {
|
||||
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount(), currentShopId);
|
||||
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount(), currentShopId);
|
||||
|
||||
LoginResponseVO responseVO = new LoginResponseVO();
|
||||
responseVO.setAccessToken(accessToken);
|
||||
responseVO.setRefreshToken(refreshToken);
|
||||
responseVO.setNeedSetPassword(needSetPassword);
|
||||
responseVO.setUserInfo(buildLoginUserInfo(userDO, currentShopId));
|
||||
return responseVO;
|
||||
}
|
||||
|
||||
private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) {
|
||||
List<ShopSimpleVO> activeShopOptions = resolveShopOptions(userDO, true, true);
|
||||
Long normalizedCurrentShopId = normalizeShopId(currentShopId);
|
||||
String currentShopName = activeShopOptions.stream()
|
||||
.filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId))
|
||||
.map(ShopSimpleVO::getShopName)
|
||||
.findFirst()
|
||||
.orElseGet(() -> {
|
||||
if (normalizedCurrentShopId == null) {
|
||||
return null;
|
||||
}
|
||||
ShopVO shopVO = shopService.getShopById(normalizedCurrentShopId);
|
||||
return shopVO == null ? null : shopVO.getShopName();
|
||||
});
|
||||
|
||||
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
|
||||
userInfo.setId(userDO.getId());
|
||||
userInfo.setAccount(userDO.getAccount());
|
||||
userInfo.setNickname(userDO.getNickname());
|
||||
userInfo.setAvatar(userDO.getAvatar());
|
||||
userInfo.setType(userDO.getType());
|
||||
userInfo.setShopId(normalizedCurrentShopId);
|
||||
userInfo.setShopName(currentShopName);
|
||||
userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList()));
|
||||
userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
|
||||
userInfo.setCreateTime(userDO.getCreateTime());
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
private List<ShopSimpleVO> resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) {
|
||||
if (userDO == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<ShopSimpleVO> shopOptions;
|
||||
if (Integer.valueOf(4).equals(userDO.getType())) {
|
||||
shopOptions = new ArrayList<>(userShopBindingSupport.listAllActiveShopOptions());
|
||||
} else {
|
||||
shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId(
|
||||
userDO.getId(),
|
||||
onlyActiveBindings,
|
||||
onlyActiveShops
|
||||
));
|
||||
}
|
||||
|
||||
if (!shopOptions.isEmpty()) {
|
||||
return shopOptions;
|
||||
}
|
||||
|
||||
Long legacyShopId = normalizeShopId(userDO.getShopId());
|
||||
if (legacyShopId != null) {
|
||||
ShopVO legacyShop = shopService.getShopById(legacyShopId);
|
||||
if (legacyShop != null && (!onlyActiveShops || Integer.valueOf(1).equals(legacyShop.getStatus()))) {
|
||||
shopOptions.add(new ShopSimpleVO(legacyShop.getId(), legacyShop.getShopName()));
|
||||
}
|
||||
}
|
||||
return shopOptions;
|
||||
}
|
||||
|
||||
private Long validateAndNormalizeShopId(Long shopId) {
|
||||
Long normalizedShopId = normalizeShopId(shopId);
|
||||
if (normalizedShopId == null) {
|
||||
return null;
|
||||
}
|
||||
if (shopService.getShopById(normalizedShopId) == null) {
|
||||
if (!userShopBindingSupport.isShopActive(normalizedShopId)) {
|
||||
throw new RuntimeException("所属店铺不存在或已失效");
|
||||
}
|
||||
return normalizedShopId;
|
||||
|
||||
@@ -12,6 +12,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
public class AdminScopeHelper {
|
||||
|
||||
private final UserService userService;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
public UserDO getCurrentUser(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
@@ -24,6 +25,9 @@ public class AdminScopeHelper {
|
||||
throw new RuntimeException("当前用户不存在或已失效");
|
||||
}
|
||||
|
||||
Long currentShopId = RequestShopContext.getCurrentShopId(request);
|
||||
currentUser.setShopId(currentShopId);
|
||||
|
||||
return currentUser;
|
||||
}
|
||||
|
||||
@@ -55,6 +59,19 @@ public class AdminScopeHelper {
|
||||
}
|
||||
}
|
||||
|
||||
public void ensureUserAccessibleInCurrentShop(UserDO currentUser, Long targetUserId, String message) {
|
||||
if (currentUser == null || targetUserId == null) {
|
||||
throw new RuntimeException(message);
|
||||
}
|
||||
if (isPlatformAdmin(currentUser)) {
|
||||
return;
|
||||
}
|
||||
Long managedShopId = getManagedShopId(currentUser);
|
||||
if (!userShopBindingSupport.isUserAccessibleInShop(targetUserId, managedShopId)) {
|
||||
throw new RuntimeException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public void requirePlatformAdmin(UserDO currentUser, String message) {
|
||||
if (!isPlatformAdmin(currentUser)) {
|
||||
throw new RuntimeException(message);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 后台角色默认权限与可分配策略。
|
||||
*/
|
||||
public final class PermissionPolicy {
|
||||
|
||||
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"dashboard:view",
|
||||
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
|
||||
"user:balance:view",
|
||||
"product:view",
|
||||
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
|
||||
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
|
||||
"tag:view",
|
||||
"coupon:view",
|
||||
"order:view",
|
||||
"nail_artist:view"
|
||||
);
|
||||
|
||||
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"dashboard:view",
|
||||
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
|
||||
"user:balance:view", "user:balance:manage", "user:vip:manage",
|
||||
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
|
||||
"shop:view", "shop:edit", "shop:staff:manage",
|
||||
"permission:view", "permission:assign",
|
||||
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
||||
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
||||
"order:view", "order:process", "order:edit", "order:delete",
|
||||
"nail_artist:view", "nail_artist:edit"
|
||||
);
|
||||
|
||||
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"order:view", "order:process",
|
||||
"nail_artist:view", "nail_artist:edit"
|
||||
);
|
||||
|
||||
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = buildManagedDefaultPermissionCodes();
|
||||
|
||||
private PermissionPolicy() {
|
||||
}
|
||||
|
||||
public static List<String> getDefaultPermissionCodes(Integer userType) {
|
||||
return switch (userType == null ? -1 : userType) {
|
||||
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
|
||||
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
|
||||
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
public static Set<String> getDefaultPermissionCodeSet(Integer userType) {
|
||||
return Set.copyOf(getDefaultPermissionCodes(userType));
|
||||
}
|
||||
|
||||
public static Set<String> getManagedDefaultPermissionCodes() {
|
||||
return MANAGED_DEFAULT_PERMISSION_CODES;
|
||||
}
|
||||
|
||||
public static boolean canManageUserType(Integer operatorType, Integer targetType) {
|
||||
if (operatorType == null || targetType == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return switch (operatorType) {
|
||||
case 4 -> true;
|
||||
case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType);
|
||||
case 3 -> Integer.valueOf(0).equals(targetType);
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static Set<String> buildManagedDefaultPermissionCodes() {
|
||||
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
|
||||
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
|
||||
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
|
||||
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
|
||||
return Set.copyOf(permissionCodes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 当前请求中的店铺上下文。
|
||||
*/
|
||||
public final class RequestShopContext {
|
||||
|
||||
public static final String CURRENT_SHOP_ID_ATTRIBUTE = "currentShopId";
|
||||
|
||||
private RequestShopContext() {
|
||||
}
|
||||
|
||||
public static Long getCurrentShopId() {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return null;
|
||||
}
|
||||
return parseShopId(attributes.getRequest().getAttribute(CURRENT_SHOP_ID_ATTRIBUTE));
|
||||
}
|
||||
|
||||
public static Long getCurrentShopId(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return null;
|
||||
}
|
||||
return parseShopId(request.getAttribute(CURRENT_SHOP_ID_ATTRIBUTE));
|
||||
}
|
||||
|
||||
private static Long parseShopId(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Number number) {
|
||||
long shopId = number.longValue();
|
||||
return shopId > 0 ? shopId : null;
|
||||
}
|
||||
if (value instanceof String text) {
|
||||
try {
|
||||
long shopId = Long.parseLong(text.trim());
|
||||
return shopId > 0 ? shopId : null;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserShopBindingDO;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper;
|
||||
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户-店铺绑定关系支撑类。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class UserShopBindingSupport {
|
||||
|
||||
private final UserShopBindingMapper userShopBindingMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
public List<UserShopBindingDO> listBindingsByUserId(Long userId, boolean includeDeleted) {
|
||||
if (userId == null) {
|
||||
return List.of();
|
||||
}
|
||||
LambdaQueryWrapper<UserShopBindingDO> wrapper = new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)
|
||||
.orderByAsc(UserShopBindingDO::getCreateTime)
|
||||
.orderByAsc(UserShopBindingDO::getId);
|
||||
if (!includeDeleted) {
|
||||
wrapper.eq(UserShopBindingDO::getIsDelete, 0);
|
||||
}
|
||||
return userShopBindingMapper.selectList(wrapper);
|
||||
}
|
||||
|
||||
public boolean hasBindingHistory(Long userId) {
|
||||
if (userId == null) {
|
||||
return false;
|
||||
}
|
||||
return userShopBindingMapper.selectCount(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)) > 0;
|
||||
}
|
||||
|
||||
public List<UserShopBindingDO> listActiveBindingsByUserId(Long userId) {
|
||||
return listBindingsByUserId(userId, false).stream()
|
||||
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
|
||||
.filter(binding -> isShopActive(binding.getShopId()))
|
||||
.sorted(Comparator.comparing(UserShopBindingDO::getCreateTime, Comparator.nullsLast(LocalDateTime::compareTo))
|
||||
.thenComparing(UserShopBindingDO::getId, Comparator.nullsLast(Long::compareTo)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Long> listActiveShopIdsByUserId(Long userId) {
|
||||
return listShopIdsByUserId(userId, true, true);
|
||||
}
|
||||
|
||||
public List<ShopSimpleVO> listActiveShopOptionsByUserId(Long userId) {
|
||||
return listShopOptionsByUserId(userId, true, true);
|
||||
}
|
||||
|
||||
public List<ShopSimpleVO> listAllActiveShopOptions() {
|
||||
return toShopOptions(fetchAllShopMap(true));
|
||||
}
|
||||
|
||||
public List<Long> listShopIdsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) {
|
||||
return listShopOptionsByUserId(userId, onlyActiveBindings, onlyActiveShops).stream()
|
||||
.map(ShopSimpleVO::getId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<ShopSimpleVO> listShopOptionsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) {
|
||||
return listShopOptionsByUserIds(List.of(userId), onlyActiveBindings, onlyActiveShops)
|
||||
.getOrDefault(userId, List.of());
|
||||
}
|
||||
|
||||
public boolean hasActiveBinding(Long userId, Long shopId) {
|
||||
if (userId == null || shopId == null || shopId <= 0) {
|
||||
return false;
|
||||
}
|
||||
return listActiveBindingsByUserId(userId).stream()
|
||||
.anyMatch(binding -> shopId.equals(binding.getShopId()));
|
||||
}
|
||||
|
||||
public boolean hasBindingInShop(Long userId, Long shopId) {
|
||||
if (userId == null || shopId == null || shopId <= 0) {
|
||||
return false;
|
||||
}
|
||||
return userShopBindingMapper.selectCount(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)) > 0;
|
||||
}
|
||||
|
||||
public boolean isShopActive(Long shopId) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
return false;
|
||||
}
|
||||
ShopDO shopDO = shopMapper.selectById(shopId);
|
||||
return shopDO != null
|
||||
&& !Integer.valueOf(1).equals(shopDO.getIsDelete())
|
||||
&& Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus()));
|
||||
}
|
||||
|
||||
public Long pickPrimaryShopId(Long userId) {
|
||||
return listActiveBindingsByUserId(userId).stream()
|
||||
.map(UserShopBindingDO::getShopId)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Map<Long, List<ShopSimpleVO>> listActiveShopOptionsByUserIds(Collection<Long> userIds) {
|
||||
return listShopOptionsByUserIds(userIds, true, true);
|
||||
}
|
||||
|
||||
public Map<Long, List<ShopSimpleVO>> listShopOptionsByUserIds(
|
||||
Collection<Long> userIds,
|
||||
boolean onlyActiveBindings,
|
||||
boolean onlyActiveShops
|
||||
) {
|
||||
if (userIds == null || userIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
List<Long> normalizedUserIds = userIds.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (normalizedUserIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
List<UserShopBindingDO> bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.in(UserShopBindingDO::getUserId, normalizedUserIds)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.orderByAsc(UserShopBindingDO::getCreateTime)
|
||||
.orderByAsc(UserShopBindingDO::getId));
|
||||
if (bindings.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
if (onlyActiveBindings) {
|
||||
bindings = bindings.stream()
|
||||
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
|
||||
.collect(Collectors.toList());
|
||||
if (bindings.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
Map<Long, ShopDO> shopMap = fetchShopMap(bindings.stream()
|
||||
.map(UserShopBindingDO::getShopId)
|
||||
.collect(Collectors.toSet()), onlyActiveShops);
|
||||
Map<Long, List<ShopSimpleVO>> result = new LinkedHashMap<>();
|
||||
for (UserShopBindingDO binding : bindings) {
|
||||
ShopDO shopDO = shopMap.get(binding.getShopId());
|
||||
if (shopDO == null) {
|
||||
continue;
|
||||
}
|
||||
result.computeIfAbsent(binding.getUserId(), key -> new java.util.ArrayList<>())
|
||||
.add(new ShopSimpleVO(shopDO.getId(), shopDO.getShopName()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<Long> listUserIdsByShopId(Long shopId, boolean onlyActiveBindings) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
return List.of();
|
||||
}
|
||||
LambdaQueryWrapper<UserShopBindingDO> wrapper = new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0);
|
||||
if (onlyActiveBindings) {
|
||||
wrapper.eq(UserShopBindingDO::getStatus, 1);
|
||||
}
|
||||
return userShopBindingMapper.selectList(wrapper).stream()
|
||||
.map(UserShopBindingDO::getUserId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public long countUsersByShopId(Long shopId, boolean onlyActiveBindings) {
|
||||
return listUserIdsByShopId(shopId, onlyActiveBindings).size();
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void ensureUserBoundToShop(Long userId, Long shopId) {
|
||||
if (userId == null || shopId == null || shopId <= 0) {
|
||||
throw new RuntimeException("店铺绑定信息不完整");
|
||||
}
|
||||
if (!isShopActive(shopId)) {
|
||||
throw new RuntimeException("所选店铺不存在或已停用");
|
||||
}
|
||||
|
||||
UserShopBindingDO existing = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.last("limit 1"));
|
||||
if (existing == null) {
|
||||
UserShopBindingDO binding = new UserShopBindingDO();
|
||||
binding.setUserId(userId);
|
||||
binding.setShopId(shopId);
|
||||
binding.setStatus(1);
|
||||
binding.setIsDelete(0);
|
||||
userShopBindingMapper.insert(binding);
|
||||
refreshLegacyPrimaryShop(userId);
|
||||
return;
|
||||
}
|
||||
|
||||
existing.setStatus(1);
|
||||
existing.setIsDelete(0);
|
||||
existing.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(existing);
|
||||
refreshLegacyPrimaryShop(userId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void syncUserShopBindings(Long userId, Collection<Long> shopIds) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<Long> desiredShopIds = normalizeActiveShopIds(shopIds);
|
||||
List<UserShopBindingDO> existingBindings = listBindingsByUserId(userId, true);
|
||||
Map<Long, UserShopBindingDO> bindingMap = existingBindings.stream()
|
||||
.filter(binding -> binding.getShopId() != null)
|
||||
.collect(Collectors.toMap(UserShopBindingDO::getShopId, binding -> binding, (left, right) -> right, LinkedHashMap::new));
|
||||
|
||||
for (Long shopId : desiredShopIds) {
|
||||
UserShopBindingDO existing = bindingMap.remove(shopId);
|
||||
if (existing == null) {
|
||||
UserShopBindingDO binding = new UserShopBindingDO();
|
||||
binding.setUserId(userId);
|
||||
binding.setShopId(shopId);
|
||||
binding.setStatus(1);
|
||||
binding.setIsDelete(0);
|
||||
userShopBindingMapper.insert(binding);
|
||||
continue;
|
||||
}
|
||||
existing.setStatus(1);
|
||||
existing.setIsDelete(0);
|
||||
existing.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(existing);
|
||||
}
|
||||
|
||||
for (UserShopBindingDO staleBinding : bindingMap.values()) {
|
||||
staleBinding.setIsDelete(1);
|
||||
staleBinding.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(staleBinding);
|
||||
}
|
||||
|
||||
refreshLegacyPrimaryShop(userId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateBindingStatus(Long userId, Long shopId, Integer status) {
|
||||
if (userId == null || shopId == null || shopId <= 0) {
|
||||
return false;
|
||||
}
|
||||
UserShopBindingDO binding = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (binding == null) {
|
||||
return false;
|
||||
}
|
||||
binding.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0);
|
||||
binding.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(binding);
|
||||
refreshLegacyPrimaryShop(userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean deleteBinding(Long userId, Long shopId) {
|
||||
if (userId == null || shopId == null || shopId <= 0) {
|
||||
return false;
|
||||
}
|
||||
UserShopBindingDO binding = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getUserId, userId)
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (binding == null) {
|
||||
return false;
|
||||
}
|
||||
binding.setIsDelete(1);
|
||||
binding.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(binding);
|
||||
refreshLegacyPrimaryShop(userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteBindingsByShopId(Long shopId) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
return;
|
||||
}
|
||||
List<UserShopBindingDO> bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
|
||||
.eq(UserShopBindingDO::getShopId, shopId)
|
||||
.eq(UserShopBindingDO::getIsDelete, 0));
|
||||
if (bindings.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> affectedUserIds = new LinkedHashSet<>();
|
||||
for (UserShopBindingDO binding : bindings) {
|
||||
binding.setIsDelete(1);
|
||||
binding.setUpdateTime(LocalDateTime.now());
|
||||
userShopBindingMapper.updateById(binding);
|
||||
affectedUserIds.add(binding.getUserId());
|
||||
}
|
||||
affectedUserIds.forEach(this::refreshLegacyPrimaryShop);
|
||||
}
|
||||
|
||||
public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
return Boolean.TRUE.equals(adminLogin)
|
||||
&& Integer.valueOf(4).equals(userType)
|
||||
&& listAllActiveShopOptions().isEmpty();
|
||||
}
|
||||
if (!isShopActive(shopId)) {
|
||||
return false;
|
||||
}
|
||||
if (Boolean.TRUE.equals(adminLogin) && Integer.valueOf(4).equals(userType)) {
|
||||
return true;
|
||||
}
|
||||
return hasActiveBinding(userId, shopId);
|
||||
}
|
||||
|
||||
public boolean isUserAccessibleInShop(Long userId, Long shopId) {
|
||||
return hasBindingInShop(userId, shopId);
|
||||
}
|
||||
|
||||
private Set<Long> normalizeActiveShopIds(Collection<Long> shopIds) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
Set<Long> normalizedShopIds = new LinkedHashSet<>();
|
||||
for (Long shopId : shopIds) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (!isShopActive(shopId)) {
|
||||
throw new RuntimeException("所选店铺不存在或已停用");
|
||||
}
|
||||
normalizedShopIds.add(shopId);
|
||||
}
|
||||
return normalizedShopIds;
|
||||
}
|
||||
|
||||
private void refreshLegacyPrimaryShop(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return;
|
||||
}
|
||||
Long primaryShopId = pickPrimaryShopId(userId);
|
||||
if (Objects.equals(userDO.getShopId(), primaryShopId)) {
|
||||
return;
|
||||
}
|
||||
userDO.setShopId(primaryShopId);
|
||||
userDO.setUpdateTime(LocalDateTime.now());
|
||||
userMapper.updateById(userDO);
|
||||
}
|
||||
|
||||
private Map<Long, ShopDO> fetchAllShopMap(boolean onlyActiveShops) {
|
||||
LambdaQueryWrapper<ShopDO> wrapper = new LambdaQueryWrapper<ShopDO>()
|
||||
.eq(ShopDO::getIsDelete, 0);
|
||||
if (onlyActiveShops) {
|
||||
wrapper.eq(ShopDO::getStatus, 1);
|
||||
}
|
||||
return shopMapper.selectList(wrapper).stream()
|
||||
.collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private Map<Long, ShopDO> fetchShopMap(Collection<Long> shopIds, boolean onlyActiveShops) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
LambdaQueryWrapper<ShopDO> wrapper = new LambdaQueryWrapper<ShopDO>()
|
||||
.in(ShopDO::getId, shopIds)
|
||||
.eq(ShopDO::getIsDelete, 0);
|
||||
if (onlyActiveShops) {
|
||||
wrapper.eq(ShopDO::getStatus, 1);
|
||||
}
|
||||
return shopMapper.selectList(wrapper)
|
||||
.stream()
|
||||
.collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private List<ShopSimpleVO> toShopOptions(Map<Long, ShopDO> shopMap) {
|
||||
return shopMap.values().stream()
|
||||
.sorted(Comparator.comparing(ShopDO::getShopName, Comparator.nullsLast(String::compareTo))
|
||||
.thenComparing(ShopDO::getId, Comparator.nullsLast(Long::compareTo)))
|
||||
.map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Integer normalizeShopStatus(Integer status) {
|
||||
return status == null ? 1 : status;
|
||||
}
|
||||
}
|
||||
@@ -25,19 +25,25 @@ public class JwtUtil {
|
||||
this.key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateAccessToken(Long userId, String account) {
|
||||
public String generateAccessToken(Long userId, String account, Long currentShopId) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("userId", userId);
|
||||
claims.put("account", account);
|
||||
claims.put("type", "access");
|
||||
if (currentShopId != null && currentShopId > 0) {
|
||||
claims.put("shopId", currentShopId);
|
||||
}
|
||||
return createToken(claims, userId.toString(), ACCESS_TOKEN_EXPIRATION);
|
||||
}
|
||||
|
||||
public String generateRefreshToken(Long userId, String account) {
|
||||
public String generateRefreshToken(Long userId, String account, Long currentShopId) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("userId", userId);
|
||||
claims.put("account", account);
|
||||
claims.put("type", "refresh");
|
||||
if (currentShopId != null && currentShopId > 0) {
|
||||
claims.put("shopId", currentShopId);
|
||||
}
|
||||
return createToken(claims, userId.toString(), REFRESH_TOKEN_EXPIRATION);
|
||||
}
|
||||
|
||||
@@ -77,6 +83,28 @@ public class JwtUtil {
|
||||
return claims.get("type", String.class);
|
||||
}
|
||||
|
||||
public Long getShopIdFromToken(String token) {
|
||||
Claims claims = parseToken(token);
|
||||
Object value = claims.get("shopId");
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Integer integer) {
|
||||
return integer.longValue();
|
||||
}
|
||||
if (value instanceof Long longValue) {
|
||||
return longValue;
|
||||
}
|
||||
if (value instanceof String text) {
|
||||
try {
|
||||
return Long.parseLong(text);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isTokenExpired(String token) {
|
||||
try {
|
||||
Claims claims = parseToken(token);
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 登录响应 VO
|
||||
@@ -33,6 +34,10 @@ public class LoginResponseVO {
|
||||
private Integer type;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
@JsonSerialize(contentUsing = ToStringSerializer.class)
|
||||
private List<Long> shopIds;
|
||||
private List<String> shopNames;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 登录页可选店铺结果。
|
||||
*/
|
||||
@Data
|
||||
public class LoginShopSelectionVO {
|
||||
|
||||
private boolean allowShoplessLogin;
|
||||
|
||||
private String message;
|
||||
|
||||
private List<ShopSimpleVO> shops = new ArrayList<>();
|
||||
}
|
||||
@@ -63,6 +63,11 @@ public class ShopVO {
|
||||
*/
|
||||
private List<String> imageUrls;
|
||||
|
||||
/**
|
||||
* 店铺状态:1-启用,0-停用
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统用户信息表 VO
|
||||
@@ -33,6 +34,17 @@ public class UserVO {
|
||||
*/
|
||||
private String shopName;
|
||||
|
||||
/**
|
||||
* 绑定店铺ID列表
|
||||
*/
|
||||
@JsonSerialize(contentUsing = ToStringSerializer.class)
|
||||
private List<Long> shopIds;
|
||||
|
||||
/**
|
||||
* 绑定店铺名称列表
|
||||
*/
|
||||
private List<String> shopNames;
|
||||
|
||||
/**
|
||||
* 用户昵称
|
||||
*/
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
-- 2026-03-25 多店铺登录 / 店铺状态 / 用户店铺绑定补丁
|
||||
-- 推荐执行顺序:
|
||||
-- 1. YumiNail.sql
|
||||
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql
|
||||
-- 3. 2026-03-25_user_shop_binding_and_shop_status_patch.sql
|
||||
-- 4. 2026-03-20_init_admin_permission_template.sql
|
||||
--
|
||||
-- 说明:
|
||||
-- 1. 本文件不覆盖主建表 SQL,只补结构与历史数据回填。
|
||||
-- 2. 本补丁会新增 t_user_shop_binding,并把现有 t_user.shop_id 回填为默认绑定关系。
|
||||
-- 3. t_shop.status 用于店铺启停;停用后不删除绑定,只禁止该店铺登录。
|
||||
|
||||
use nailart;
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_add_column_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
|
||||
p_definition
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用''');
|
||||
|
||||
UPDATE t_shop
|
||||
SET status = 1
|
||||
WHERE status IS NULL;
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `t_user_shop_binding` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID',
|
||||
`user_id` bigint unsigned NOT NULL COMMENT '用户ID',
|
||||
`shop_id` bigint unsigned NOT NULL COMMENT '店铺ID',
|
||||
`status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删',
|
||||
PRIMARY KEY (`id`)
|
||||
) COMMENT='用户与店铺绑定关系表';
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删''');
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)');
|
||||
CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)');
|
||||
|
||||
INSERT INTO t_user_shop_binding (
|
||||
user_id,
|
||||
shop_id,
|
||||
status,
|
||||
create_time,
|
||||
update_time,
|
||||
is_delete
|
||||
)
|
||||
SELECT
|
||||
u.id,
|
||||
u.shop_id,
|
||||
CASE
|
||||
WHEN COALESCE(u.status, 1) = 1 THEN 1
|
||||
ELSE 0
|
||||
END AS binding_status,
|
||||
COALESCE(u.create_time, NOW()),
|
||||
COALESCE(u.update_time, NOW()),
|
||||
0
|
||||
FROM t_user u
|
||||
INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0
|
||||
LEFT JOIN t_user_shop_binding b
|
||||
ON b.user_id = u.id
|
||||
AND b.shop_id = u.shop_id
|
||||
AND COALESCE(b.is_delete, 0) = 0
|
||||
WHERE COALESCE(u.is_delete, 0) = 0
|
||||
AND u.shop_id IS NOT NULL
|
||||
AND u.shop_id > 0
|
||||
AND b.id IS NULL;
|
||||
|
||||
UPDATE t_user_shop_binding b
|
||||
INNER JOIN t_user u ON u.id = b.user_id
|
||||
SET b.status = CASE
|
||||
WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END
|
||||
ELSE b.status
|
||||
END,
|
||||
b.is_delete = COALESCE(b.is_delete, 0),
|
||||
b.update_time = COALESCE(b.update_time, NOW())
|
||||
WHERE b.status IS NULL
|
||||
OR b.is_delete IS NULL
|
||||
OR b.update_time IS NULL;
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
@@ -1,4 +1,9 @@
|
||||
create database nailart;
|
||||
-- YumiNail 首次部署主 SQL
|
||||
-- 说明:
|
||||
-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、VIP 规则、admin01 初始化与默认权限分配。
|
||||
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、
|
||||
-- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。
|
||||
-- 3. 如果你的数据库名不是 nailart,请先将本文件中的 `use nailart;` 改成实际库名后再执行。
|
||||
use nailart;
|
||||
|
||||
-- auto-generated definition
|
||||
@@ -551,5 +556,702 @@ create index idx_user_id
|
||||
on t_wishlist (user_id)
|
||||
comment '按用户查询收藏的索引';
|
||||
|
||||
-- ========================================
|
||||
-- 首次部署整合区:用户资产 / VIP / 优惠券补丁
|
||||
-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql
|
||||
-- ========================================
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_add_column_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
|
||||
p_definition
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额''');
|
||||
CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间''');
|
||||
|
||||
UPDATE t_balance
|
||||
SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00)
|
||||
WHERE total_recharge_amount IS NULL;
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID''');
|
||||
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注''');
|
||||
|
||||
UPDATE t_balance_change_detail
|
||||
SET before_balance = COALESCE(before_balance, current_balance - amount),
|
||||
after_balance = COALESCE(after_balance, current_balance),
|
||||
change_scene = COALESCE(NULLIF(change_scene, ''), type)
|
||||
WHERE before_balance IS NULL
|
||||
OR after_balance IS NULL
|
||||
OR change_scene IS NULL
|
||||
OR change_scene = '';
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID''');
|
||||
CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID''');
|
||||
CALL sp_add_column_if_not_exists('t_order', 'coupon_source_type', 'varchar(32) NULL COMMENT ''优惠来源类型''');
|
||||
|
||||
UPDATE t_order
|
||||
SET coupon_id = NULL
|
||||
WHERE coupon_id = 0;
|
||||
|
||||
UPDATE t_order o
|
||||
INNER JOIN (
|
||||
SELECT oi.order_id, MIN(p.shop_id) AS resolved_shop_id
|
||||
FROM t_order_item oi
|
||||
INNER JOIN t_product p ON p.id = oi.product_id
|
||||
GROUP BY oi.order_id
|
||||
) detail_shop ON detail_shop.order_id = o.id
|
||||
SET o.shop_id = detail_shop.resolved_shop_id
|
||||
WHERE o.shop_id IS NULL;
|
||||
|
||||
UPDATE t_order
|
||||
SET coupon_source_type = 'USER_COUPON'
|
||||
WHERE coupon_source_type IS NULL
|
||||
AND coupon_id IS NOT NULL;
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_shop_id', '(`shop_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_coupon_source_type', '(`coupon_source_type`)');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间''');
|
||||
CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景''');
|
||||
CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级''');
|
||||
CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配''');
|
||||
|
||||
UPDATE t_coupon
|
||||
SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'),
|
||||
auto_match = COALESCE(auto_match, 0)
|
||||
WHERE coupon_scene IS NULL
|
||||
OR coupon_scene = ''
|
||||
OR auto_match IS NULL;
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)');
|
||||
CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号''');
|
||||
CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛''');
|
||||
CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态''');
|
||||
|
||||
UPDATE t_vip_benefit
|
||||
SET level_rank = CASE required_vip_level
|
||||
WHEN '普通' THEN 0
|
||||
WHEN '青铜' THEN 1
|
||||
WHEN '白银' THEN 2
|
||||
WHEN '黄金' THEN 3
|
||||
ELSE level_rank
|
||||
END,
|
||||
recharge_threshold = CASE required_vip_level
|
||||
WHEN '普通' THEN 0.00
|
||||
WHEN '青铜' THEN 500.00
|
||||
WHEN '白银' THEN 1000.00
|
||||
WHEN '黄金' THEN 2000.00
|
||||
ELSE recharge_threshold
|
||||
END,
|
||||
status = COALESCE(status, 1)
|
||||
WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金');
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID''');
|
||||
CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级''');
|
||||
|
||||
ALTER TABLE t_vip_info
|
||||
MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间',
|
||||
MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键';
|
||||
|
||||
UPDATE t_vip_info vi
|
||||
INNER JOIN t_user u ON u.vip_id = vi.id
|
||||
SET vi.user_id = u.id
|
||||
WHERE (vi.user_id IS NULL OR vi.user_id = 0)
|
||||
AND u.vip_id IS NOT NULL
|
||||
AND u.vip_id <> 0;
|
||||
|
||||
UPDATE t_vip_info
|
||||
SET start_time = COALESCE(start_time, create_time, NOW()),
|
||||
activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'),
|
||||
manual_override = COALESCE(manual_override, 0);
|
||||
|
||||
CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)');
|
||||
|
||||
UPDATE t_user u
|
||||
LEFT JOIN t_vip_info vi ON vi.id = u.vip_id
|
||||
SET u.level = CASE
|
||||
WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level
|
||||
WHEN u.type = 0 THEN '普通'
|
||||
ELSE u.level
|
||||
END,
|
||||
u.vip_id = CASE
|
||||
WHEN u.type = 0 AND u.vip_id IS NULL THEN 0
|
||||
ELSE u.vip_id
|
||||
END,
|
||||
u.update_time = NOW()
|
||||
WHERE u.is_delete = 0
|
||||
AND u.type = 0
|
||||
AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL);
|
||||
|
||||
UPDATE t_vip_benefit
|
||||
SET benefit_info = '普通用户,无额外VIP折扣',
|
||||
level_rank = 0,
|
||||
recharge_threshold = 0.00,
|
||||
status = 1,
|
||||
update_time = NOW()
|
||||
WHERE required_vip_level = '普通';
|
||||
|
||||
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
|
||||
SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW()
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_vip_benefit
|
||||
WHERE required_vip_level = '普通'
|
||||
);
|
||||
|
||||
UPDATE t_vip_benefit
|
||||
SET benefit_info = '青铜VIP,系统自动匹配9.5折券',
|
||||
level_rank = 1,
|
||||
recharge_threshold = 500.00,
|
||||
status = 1,
|
||||
update_time = NOW()
|
||||
WHERE required_vip_level = '青铜';
|
||||
|
||||
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
|
||||
SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW()
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_vip_benefit
|
||||
WHERE required_vip_level = '青铜'
|
||||
);
|
||||
|
||||
UPDATE t_vip_benefit
|
||||
SET benefit_info = '白银VIP,系统自动匹配9.2折券',
|
||||
level_rank = 2,
|
||||
recharge_threshold = 1000.00,
|
||||
status = 1,
|
||||
update_time = NOW()
|
||||
WHERE required_vip_level = '白银';
|
||||
|
||||
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
|
||||
SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW()
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_vip_benefit
|
||||
WHERE required_vip_level = '白银'
|
||||
);
|
||||
|
||||
UPDATE t_vip_benefit
|
||||
SET benefit_info = '黄金VIP,系统自动匹配9.0折券',
|
||||
level_rank = 3,
|
||||
recharge_threshold = 2000.00,
|
||||
status = 1,
|
||||
update_time = NOW()
|
||||
WHERE required_vip_level = '黄金';
|
||||
|
||||
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
|
||||
SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW()
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_vip_benefit
|
||||
WHERE required_vip_level = '黄金'
|
||||
);
|
||||
|
||||
INSERT INTO t_coupon (
|
||||
coupon_code,
|
||||
coupon_name,
|
||||
coupon_type,
|
||||
discount_value,
|
||||
min_amount,
|
||||
reduce_amount,
|
||||
total_count,
|
||||
used_count,
|
||||
start_time,
|
||||
end_time,
|
||||
status,
|
||||
create_time,
|
||||
update_time,
|
||||
is_delete,
|
||||
shop_id,
|
||||
coupon_scene,
|
||||
required_vip_level,
|
||||
auto_match
|
||||
)
|
||||
VALUES
|
||||
('VIP_AUTO_BRONZE_95', '青铜VIP自动95折券', 1, 9.50, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '青铜', 1),
|
||||
('VIP_AUTO_SILVER_92', '白银VIP自动92折券', 1, 9.20, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '白银', 1),
|
||||
('VIP_AUTO_GOLD_90', '黄金VIP自动90折券', 1, 9.00, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '黄金', 1)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
coupon_name = VALUES(coupon_name),
|
||||
coupon_type = VALUES(coupon_type),
|
||||
discount_value = VALUES(discount_value),
|
||||
min_amount = VALUES(min_amount),
|
||||
reduce_amount = VALUES(reduce_amount),
|
||||
total_count = VALUES(total_count),
|
||||
status = VALUES(status),
|
||||
is_delete = VALUES(is_delete),
|
||||
shop_id = VALUES(shop_id),
|
||||
coupon_scene = VALUES(coupon_scene),
|
||||
required_vip_level = VALUES(required_vip_level),
|
||||
auto_match = VALUES(auto_match),
|
||||
update_time = NOW();
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
|
||||
-- ========================================
|
||||
-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁
|
||||
-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql
|
||||
-- ========================================
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_add_column_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
|
||||
p_definition
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_columns TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @sql = CONCAT(
|
||||
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
|
||||
p_columns
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用''');
|
||||
|
||||
UPDATE t_shop
|
||||
SET status = 1
|
||||
WHERE status IS NULL;
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `t_user_shop_binding` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID',
|
||||
`user_id` bigint unsigned NOT NULL COMMENT '用户ID',
|
||||
`shop_id` bigint unsigned NOT NULL COMMENT '店铺ID',
|
||||
`status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删',
|
||||
PRIMARY KEY (`id`)
|
||||
) COMMENT='用户与店铺绑定关系表';
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
|
||||
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删''');
|
||||
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)');
|
||||
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)');
|
||||
CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)');
|
||||
|
||||
INSERT INTO t_user_shop_binding (
|
||||
user_id,
|
||||
shop_id,
|
||||
status,
|
||||
create_time,
|
||||
update_time,
|
||||
is_delete
|
||||
)
|
||||
SELECT
|
||||
u.id,
|
||||
u.shop_id,
|
||||
CASE
|
||||
WHEN COALESCE(u.status, 1) = 1 THEN 1
|
||||
ELSE 0
|
||||
END AS binding_status,
|
||||
COALESCE(u.create_time, NOW()),
|
||||
COALESCE(u.update_time, NOW()),
|
||||
0
|
||||
FROM t_user u
|
||||
INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0
|
||||
LEFT JOIN t_user_shop_binding b
|
||||
ON b.user_id = u.id
|
||||
AND b.shop_id = u.shop_id
|
||||
AND COALESCE(b.is_delete, 0) = 0
|
||||
WHERE COALESCE(u.is_delete, 0) = 0
|
||||
AND u.shop_id IS NOT NULL
|
||||
AND u.shop_id > 0
|
||||
AND b.id IS NULL;
|
||||
|
||||
UPDATE t_user_shop_binding b
|
||||
INNER JOIN t_user u ON u.id = b.user_id
|
||||
SET b.status = CASE
|
||||
WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END
|
||||
ELSE b.status
|
||||
END,
|
||||
b.is_delete = COALESCE(b.is_delete, 0),
|
||||
b.update_time = COALESCE(b.update_time, NOW())
|
||||
WHERE b.status IS NULL
|
||||
OR b.is_delete IS NULL
|
||||
OR b.update_time IS NULL;
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
|
||||
|
||||
-- ========================================
|
||||
-- 首次部署整合区:权限种子 / admin01 初始化 / 默认权限分配
|
||||
-- 来源:2026-03-20_init_admin_permission_template.sql
|
||||
-- ========================================
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
|
||||
VALUES
|
||||
('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0),
|
||||
('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0),
|
||||
('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0),
|
||||
('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0),
|
||||
('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0),
|
||||
('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0),
|
||||
('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0),
|
||||
('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0),
|
||||
('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0),
|
||||
('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0),
|
||||
('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0),
|
||||
('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0),
|
||||
('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0),
|
||||
('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0),
|
||||
('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0),
|
||||
('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0),
|
||||
('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0),
|
||||
('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0),
|
||||
('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0),
|
||||
('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0),
|
||||
('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0),
|
||||
('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0),
|
||||
('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0),
|
||||
('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0),
|
||||
('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0),
|
||||
('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0),
|
||||
('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0),
|
||||
('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0),
|
||||
('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0),
|
||||
('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0),
|
||||
('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0),
|
||||
('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0),
|
||||
('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0),
|
||||
('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0),
|
||||
('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0),
|
||||
('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0),
|
||||
('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0),
|
||||
('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0),
|
||||
('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0),
|
||||
('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0),
|
||||
('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0),
|
||||
('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
permission_name = VALUES(permission_name),
|
||||
permission_group = VALUES(permission_group),
|
||||
description = VALUES(description),
|
||||
update_time = NOW(),
|
||||
is_delete = 0;
|
||||
|
||||
INSERT INTO t_user (
|
||||
shop_id,
|
||||
nickname,
|
||||
account,
|
||||
phone_verified,
|
||||
email_verified,
|
||||
password,
|
||||
signature,
|
||||
level,
|
||||
type,
|
||||
vip_id,
|
||||
create_time,
|
||||
update_time,
|
||||
is_delete,
|
||||
status
|
||||
)
|
||||
SELECT
|
||||
0,
|
||||
'系统管理员',
|
||||
'admin01',
|
||||
0,
|
||||
0,
|
||||
'$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W',
|
||||
'',
|
||||
'管理员',
|
||||
4,
|
||||
0,
|
||||
NOW(),
|
||||
NOW(),
|
||||
0,
|
||||
1
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_user
|
||||
WHERE account = 'admin01'
|
||||
);
|
||||
|
||||
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
|
||||
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
|
||||
FROM t_user u
|
||||
INNER JOIN t_permission p
|
||||
ON p.is_delete = 0
|
||||
AND p.permission_code IN (
|
||||
'home:view',
|
||||
'dashboard:view',
|
||||
'user:view',
|
||||
'user:create',
|
||||
'user:edit',
|
||||
'user:disable',
|
||||
'user:reset_password',
|
||||
'user:delete',
|
||||
'user:balance:view',
|
||||
'product:view',
|
||||
'shop:view',
|
||||
'shop:create',
|
||||
'shop:edit',
|
||||
'shop:delete',
|
||||
'shop:staff:manage',
|
||||
'permission:view',
|
||||
'permission:create',
|
||||
'permission:edit',
|
||||
'permission:delete',
|
||||
'permission:assign',
|
||||
'tag:view',
|
||||
'coupon:view',
|
||||
'order:view',
|
||||
'nail_artist:view'
|
||||
)
|
||||
WHERE u.is_delete = 0
|
||||
AND u.type = 4
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_user_permission up
|
||||
WHERE up.user_id = u.id
|
||||
AND up.permission_id = p.id
|
||||
);
|
||||
|
||||
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
|
||||
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
|
||||
FROM t_user u
|
||||
INNER JOIN t_permission p
|
||||
ON p.is_delete = 0
|
||||
AND p.permission_code IN (
|
||||
'home:view',
|
||||
'dashboard:view',
|
||||
'user:view',
|
||||
'user:create',
|
||||
'user:edit',
|
||||
'user:disable',
|
||||
'user:reset_password',
|
||||
'user:delete',
|
||||
'user:balance:view',
|
||||
'user:balance:manage',
|
||||
'user:vip:manage',
|
||||
'product:view',
|
||||
'product:create',
|
||||
'product:edit',
|
||||
'product:delete',
|
||||
'product:category:manage',
|
||||
'shop:view',
|
||||
'shop:edit',
|
||||
'shop:staff:manage',
|
||||
'permission:view',
|
||||
'permission:assign',
|
||||
'tag:view',
|
||||
'tag:create',
|
||||
'tag:edit',
|
||||
'tag:delete',
|
||||
'tag:assign',
|
||||
'coupon:view',
|
||||
'coupon:create',
|
||||
'coupon:edit',
|
||||
'coupon:delete',
|
||||
'coupon:assign',
|
||||
'order:view',
|
||||
'order:process',
|
||||
'order:edit',
|
||||
'order:delete',
|
||||
'nail_artist:view',
|
||||
'nail_artist:edit'
|
||||
)
|
||||
WHERE u.is_delete = 0
|
||||
AND u.type = 2
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_user_permission up
|
||||
WHERE up.user_id = u.id
|
||||
AND up.permission_id = p.id
|
||||
);
|
||||
|
||||
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
|
||||
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
|
||||
FROM t_user u
|
||||
INNER JOIN t_permission p
|
||||
ON p.is_delete = 0
|
||||
AND p.permission_code IN (
|
||||
'home:view',
|
||||
'user:view',
|
||||
'user:create',
|
||||
'user:balance:view',
|
||||
'product:view',
|
||||
'product:create',
|
||||
'shop:view',
|
||||
'tag:view',
|
||||
'tag:create',
|
||||
'coupon:view',
|
||||
'order:view'
|
||||
)
|
||||
WHERE u.is_delete = 0
|
||||
AND u.type = 3
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM t_user_permission up
|
||||
WHERE up.user_id = u.id
|
||||
AND up.permission_id = p.id
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
+8
@@ -38,10 +38,18 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
||||
"/api/user/send-verification-code",
|
||||
"/api/user/phone-login",
|
||||
"/api/user/reset-password-by-phone",
|
||||
"/api/product/get/**",
|
||||
"/api/product/list/**",
|
||||
"/api/shop/get/**",
|
||||
"/api/shop/list/public",
|
||||
"/api/shop/list/simple",
|
||||
"/api/tag/list/all",
|
||||
"/api/file/get-signed-url/**",
|
||||
"/api/admin/auth/login",
|
||||
"/api/admin/auth/login-shops/**",
|
||||
"/api/admin/auth/refresh",
|
||||
"/admin/api/auth/login",
|
||||
"/admin/api/auth/login-shops/**",
|
||||
"/admin/api/auth/refresh",
|
||||
"/api/health/**",
|
||||
"/api/error"
|
||||
|
||||
@@ -126,6 +126,8 @@ yuminail:
|
||||
- /api/health/**
|
||||
- /api/error
|
||||
- /api/admin/auth/login
|
||||
- /api/admin/auth/login-shops/**
|
||||
- /api/admin/auth/refresh
|
||||
- /admin/api/auth/login
|
||||
- /admin/api/auth/login-shops/**
|
||||
- /admin/api/auth/refresh
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# 2026-03-25 八个问题修复
|
||||
|
||||
## 本轮目标
|
||||
|
||||
围绕上轮 review 定位出的 8 个重点问题,继续完成收口与验证,覆盖:
|
||||
|
||||
1. 后台默认权限过宽
|
||||
2. 权限分配存在越权空间
|
||||
3. 用户删除仍是物理删除
|
||||
4. 商品/店铺/用户已删数据过滤不一致
|
||||
5. 公开美甲师列表暴露过多且未限制状态
|
||||
6. 优惠券发放/使用计数语义不一致
|
||||
7. 后台 `401` 刷新链路不稳
|
||||
8. MessageHub 消费端无脑确认、缺少重试与幂等
|
||||
|
||||
## 已完成修复
|
||||
|
||||
### 1. 默认权限与权限分配规则收口
|
||||
|
||||
- 新增统一权限策略文件:
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java`
|
||||
- 店长/美甲师默认权限不再散落定义,统一由策略类提供。
|
||||
- 美甲师默认权限收缩为:
|
||||
- `home:view`
|
||||
- `order:view`
|
||||
- `order:process`
|
||||
- `nail_artist:view`
|
||||
- `nail_artist:edit`
|
||||
- `PermissionServiceImpl` 增加约束:
|
||||
- 店长不能给自己改权限
|
||||
- 非平台管理员只能维护同店且允许管理的用户类型
|
||||
- 不能给目标角色分配超出角色默认边界的权限
|
||||
- 非平台管理员不能分配超出自己已拥有的权限
|
||||
|
||||
### 2. 用户删除改为软删,并补齐查询保护
|
||||
|
||||
- `UserServiceImpl` 的 `deleteUser()` 已改为软删,不再直接物理删除。
|
||||
- 删除时会同步处理:
|
||||
- 账号改名为带删除标记的占位值
|
||||
- 手机号改名为带删除标记的占位值
|
||||
- 状态改为禁用
|
||||
- `is_delete = 1`
|
||||
- 同步补齐以下查询保护:
|
||||
- `getUserById()`
|
||||
- `getUserByAccount()`
|
||||
- `updateUserStatus()`
|
||||
|
||||
### 3. 商品/店铺/管理接口范围控制补齐
|
||||
|
||||
- `ProductServiceImpl`、`ShopServiceImpl` 已统一按软删语义处理。
|
||||
- 以下控制器补了非 `/admin/**` 管理接口的作用域校验,避免店长跨店访问或修改:
|
||||
- `UserController`
|
||||
- `ProductController`
|
||||
- `CouponController`
|
||||
- `ShopController`
|
||||
- `TagController`
|
||||
- `PermissionController`
|
||||
- 本轮顺手修复了 `UserController` 中两处历史残留的乱码字符串,解决编译报错。
|
||||
|
||||
### 4. 公开美甲师列表与购物车预约链路收口
|
||||
|
||||
- `/user/list/type/{type}` 现在只允许查询 `type = 3` 的美甲师。
|
||||
- 公开返回结果改为脱敏数据,不再直接把后台用户信息全量暴露给前台。
|
||||
- 前端购物车只展示 `status = 1` 的可预约美甲师,避免下单时才失败。
|
||||
- 相关文件:
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java`
|
||||
- `Frontend/src/views/CartView.vue`
|
||||
|
||||
### 5. 后台 `401` 刷新排队逻辑补齐
|
||||
|
||||
- `Frontend/src/api/admin.ts` 已补齐刷新队列逻辑,避免多个后台请求同时 `401` 时重复刷新 token。
|
||||
- 该文件本轮未追加新改动,但已纳入本轮问题修复结果。
|
||||
|
||||
### 6. 优惠券发放 / 使用 / 剩余数量语义统一
|
||||
|
||||
- `CouponServiceImpl` 已重构发放逻辑,修复以下问题:
|
||||
- 发放优惠券时不再错误增加模板 `usedCount`
|
||||
- `usedCount` 只表示“实际已使用数量”
|
||||
- `remainingCount` 改为“剩余可发放数量”
|
||||
- 同一用户同一模板重复发放会被明确拒绝
|
||||
- `quantity > 1` 时直接失败,和 `t_user_coupon(user_id, coupon_id)` 唯一约束保持一致
|
||||
- 发放对象会校验是否为有效用户、是否匹配店铺
|
||||
- 发放/编辑后会重新刷新优惠券“可用 / 已用完”状态
|
||||
- `OrderServiceImpl` 中用户券消费与恢复逻辑已与模板 `usedCount` 联动。
|
||||
|
||||
### 7. MessageHub 消费确认、重试与幂等补齐
|
||||
|
||||
- `RabbitMQConfig` 新增 `manualAckRabbitListenerContainerFactory`,强制监听器使用手动确认模式。
|
||||
- `SmsQueueListener`、`EmailQueueListener` 已改为:
|
||||
- 成功后 `ack`
|
||||
- 可重试异常时 `nack + requeue`
|
||||
- 达到上限后 `reject`
|
||||
- 不再 `finally` 无脑确认
|
||||
- `MessageHandleService` 已补齐:
|
||||
- 消息校验与 push_log 幂等写入
|
||||
- 按 `messageId` 防止重复插入主键冲突
|
||||
- 按 `uniqueId` 跳过已成功处理的重复业务消息
|
||||
- 重试次数记录与失败原因落库
|
||||
- 达到最大重试次数后不再重复消费
|
||||
- `PushLogMapper` 的 `selectByUniqueId` 改为按最新记录查询。
|
||||
- `MessageProducerService` 不再覆盖外部已传入的 `uniqueId`,只在缺省时兜底生成,保证业务幂等键可用。
|
||||
|
||||
## 本轮验证
|
||||
|
||||
已完成以下验证:
|
||||
|
||||
- `YumiNail-Core`:
|
||||
- `mvn -q -DskipTests compile`
|
||||
- `MessageHub`:
|
||||
- `mvn -q -DskipTests compile`
|
||||
- `YumiNail-Gateway`:
|
||||
- `mvn -q -DskipTests compile`
|
||||
- `Frontend`:
|
||||
- `npm run build`
|
||||
|
||||
说明:
|
||||
|
||||
- `YumiNail-Core` 首次编译时发现 `UserController` 两处字符串未闭合,已在本轮顺手修正后重新编译通过。
|
||||
- 本轮未做集成联调和数据库回归测试,仅完成静态构建验证。
|
||||
|
||||
## SQL 与配置影响
|
||||
|
||||
- 本轮没有新增 SQL 变更。
|
||||
- 本轮没有要求手工执行数据库脚本。
|
||||
- MessageHub 的监听确认模式已通过代码中的 `manualAckRabbitListenerContainerFactory` 固化,不再依赖旧的 `rabbitmq.yaml` 中 `acknowledge-mode: auto` 配置。
|
||||
|
||||
## 关联文件
|
||||
|
||||
### YumiNail-Core
|
||||
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CouponController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/PermissionController.java`
|
||||
|
||||
### Frontend
|
||||
|
||||
- `Frontend/src/api/admin.ts`
|
||||
- `Frontend/src/views/CartView.vue`
|
||||
|
||||
### MessageHub
|
||||
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/listener/EmailQueueListener.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/service/impl/MessageHandleService.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java`
|
||||
@@ -0,0 +1,83 @@
|
||||
# 2026-03-25 前后台体验优化补完
|
||||
|
||||
## 本轮目标
|
||||
|
||||
把上一轮已经落地的游客浏览、多店铺登录与前后台切店能力继续收口到“可稳定打包、交互更自然”的状态,避免出现:
|
||||
|
||||
- 页面能打开但前端构建不过
|
||||
- 首页作品卡片信息过弱
|
||||
- 个人中心出现误导性的消息红点
|
||||
- API 包装类型不一致,后续页面继续反复出现 `AxiosResponse` 类型噪音
|
||||
|
||||
## 本轮完成项
|
||||
|
||||
### 1. 前端类型与构建问题全部收口
|
||||
|
||||
- 修正了 `AdminLayout.vue` 中后台门店切换 `a-select` 的事件参数兼容问题。
|
||||
- 修正了 `HomeView.vue` 中分页常量、作品卡片类型和首页数据加载的类型问题。
|
||||
- 修正了 `ProductDetailView.vue` 中作品字段定义缺失、营业时间解析和门店详情读取的类型问题。
|
||||
- 修正了 `ProfileView.vue` 中用户信息、订单、优惠券、收藏统计的返回值类型问题。
|
||||
- 清理了 `ProductListView.vue` 中未使用的图标导入。
|
||||
|
||||
### 2. API 包装统一
|
||||
|
||||
- 前端以下 API 方法改为显式返回业务数据,而不是把 `AxiosResponse` 泄漏到页面层:
|
||||
- `userApi.getUserInfo`
|
||||
- `userApi.getUserByAccount`
|
||||
- `userApi.checkAccountAvailability`
|
||||
- `userApi.checkLoginAccountAvailability`
|
||||
- `userApi.getLoginShopsByAccount`
|
||||
- `userApi.getLoginShopsByPhone`
|
||||
- `userApi.checkPhoneAvailability`
|
||||
- `userApi.listUsersByType`
|
||||
- `shopApi.getAllShops`
|
||||
- `shopApi.getPublicShops`
|
||||
- `shopApi.getShopsSimple`
|
||||
- `shopApi.getShopById`
|
||||
- `orderApi.getOrderList`
|
||||
- `couponApi.listUserCoupons`
|
||||
- `couponApi.getAvailableCoupons`
|
||||
- `wishlistApi` 相关方法
|
||||
|
||||
### 3. 首页体验补强
|
||||
|
||||
- 首页“精选作品 / 热门作品”卡片改为优先展示真实封面图,不再只显示纯色首字母占位。
|
||||
- 作品卡片补充了更有用的辅助信息,优先显示预计时长,其次显示所属门店。
|
||||
- 首页游客模式、门店推荐、搜索跳转链路保持不变。
|
||||
|
||||
### 4. 个人中心提示修正
|
||||
|
||||
- 个人中心头像上的消息红点改为默认关闭。
|
||||
- 在消息中心尚未真正接通前,不再给用户造成“有未读消息”的假提示。
|
||||
|
||||
## 本轮验证
|
||||
|
||||
已完成本地构建验证:
|
||||
|
||||
- `Frontend`: `npm run build`
|
||||
- `YumiNail-Core`: `mvn -q -DskipTests compile`
|
||||
- `YumiNail-Gateway`: `mvn -q -DskipTests compile`
|
||||
|
||||
说明:
|
||||
|
||||
- 前端生产构建已通过。
|
||||
- Vite 仍提示主包体积较大,这是现有项目体量带来的打包告警,不影响本轮功能正确性。
|
||||
|
||||
## SQL / 配置影响
|
||||
|
||||
- 本轮无新增 SQL。
|
||||
- 本轮无新增 Nacos 配置项。
|
||||
|
||||
## 主要修改文件
|
||||
|
||||
- `Frontend/src/api/coupon.ts`
|
||||
- `Frontend/src/api/order.ts`
|
||||
- `Frontend/src/api/product.ts`
|
||||
- `Frontend/src/api/shop.ts`
|
||||
- `Frontend/src/api/user.ts`
|
||||
- `Frontend/src/api/wishlist.ts`
|
||||
- `Frontend/src/views/HomeView.vue`
|
||||
- `Frontend/src/views/ProductDetailView.vue`
|
||||
- `Frontend/src/views/ProductListView.vue`
|
||||
- `Frontend/src/views/ProfileView.vue`
|
||||
- `Frontend/src/views/admin/AdminLayout.vue`
|
||||
@@ -0,0 +1,106 @@
|
||||
# 2026-03-25 多店铺登录与店铺级联整理
|
||||
|
||||
## 本轮目标
|
||||
|
||||
围绕两项新要求落地:
|
||||
|
||||
1. 用户可绑定多个店铺,前台/后台登录时按账号展示可登录店铺并选择本次登录店铺。
|
||||
2. 店长停用/删除用户只作用于当前登录店铺;平台管理员删除店铺时,删除店铺下业务数据并解绑用户,停用店铺时禁止该店铺继续登录。
|
||||
|
||||
## 代码侧完成项
|
||||
|
||||
### 1. 多店铺登录链路
|
||||
|
||||
- 后端新增并接通用户/后台登录店铺选择接口:
|
||||
- `GET /user/check/login-shops/account/{account}`
|
||||
- `GET /user/check/login-shops/phone/{phone}`
|
||||
- `GET /admin/auth/login-shops/{account}`
|
||||
- `JwtUtil`、`AuthInterceptor`、`RequestShopContext` 已以“当前登录店铺”作为会话上下文。
|
||||
- 用户登录、手机号登录、后台登录都会校验:
|
||||
- 店铺是否启用
|
||||
- 用户是否仍绑定当前店铺
|
||||
- 平台管理员在“当前没有任何启用店铺”时允许无店铺登录
|
||||
|
||||
### 2. 用户与店铺绑定
|
||||
|
||||
- 引入 `t_user_shop_binding` 作为用户-店铺多绑定关系表。
|
||||
- `UserServiceImpl` 统一以绑定表驱动:
|
||||
- 用户创建/注册按绑定表落库
|
||||
- 登录可选店铺从绑定表返回
|
||||
- 店长停用用户只更新当前店铺绑定状态
|
||||
- 店长删除用户只删除当前店铺绑定
|
||||
- 前端后台用户管理页支持多店铺展示;平台管理员可维护多店铺绑定。
|
||||
|
||||
### 3. 店长编辑用户防误伤
|
||||
|
||||
- 修正了一个关键回归风险:
|
||||
- 之前店长编辑用户基础信息时,会把用户在其他店铺的绑定误删成“仅当前店铺”。
|
||||
- 现在的处理是:
|
||||
- 店长创建用户:仍只绑定当前店铺
|
||||
- 店长编辑用户:只改基础信息,不改其他店铺绑定
|
||||
- 店长停用/删除用户:只作用于当前店铺绑定
|
||||
|
||||
### 4. 店铺停用/删除联动
|
||||
|
||||
- 店铺停用:
|
||||
- 不删除绑定
|
||||
- 该店铺不会再出现在前台/后台登录可选店铺中
|
||||
- 已登录到该店铺的 token 在鉴权时会被拦住
|
||||
- 店铺删除:
|
||||
- 软删 `t_shop`
|
||||
- 软删该店铺下 `t_product`
|
||||
- 软删该店铺下 `t_coupon`
|
||||
- 软删该店铺下 `t_tag`
|
||||
- 软删该店铺下 `t_comment`
|
||||
- 软删该店铺优惠券对应的 `t_user_coupon`
|
||||
- 删除该店铺全部 `t_user_shop_binding`
|
||||
- 用户账号本身不删除,只解绑店铺
|
||||
|
||||
### 5. 前端交互补强
|
||||
|
||||
- 前台登录页:
|
||||
- 切换登录方式/Tab 后,会按当前输入重新拉取可登录店铺
|
||||
- 登录店铺 ID 统一按字符串处理,避免雪花 ID 精度丢失
|
||||
- 后台用户管理页:
|
||||
- 修正 `UsersView.vue` 的类型报错
|
||||
- 非平台管理员编辑用户时,不再把店铺绑定误发成单店铺覆盖
|
||||
|
||||
## 新增 SQL
|
||||
|
||||
本轮新增增量补丁文件:
|
||||
|
||||
- `YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql`
|
||||
|
||||
用途:
|
||||
|
||||
- 给 `t_shop` 增加 `status`
|
||||
- 新建 `t_user_shop_binding`
|
||||
- 为绑定表补索引和唯一约束
|
||||
- 将现有 `t_user.shop_id` 回填成默认绑定关系
|
||||
|
||||
## 手工执行顺序
|
||||
|
||||
空库或重建库时,建议按下面顺序执行:
|
||||
|
||||
1. `YumiNail.sql`
|
||||
2. `2026-03-20_user_asset_vip_coupon_permission_patch.sql`
|
||||
3. `2026-03-25_user_shop_binding_and_shop_status_patch.sql`
|
||||
4. `2026-03-20_init_admin_permission_template.sql`
|
||||
|
||||
## 本轮验证
|
||||
|
||||
已通过本地编译/构建验证:
|
||||
|
||||
- `YumiNail-Core`: `mvn -q -DskipTests compile`
|
||||
- `YumiNail-Gateway`: `mvn -q -DskipTests compile`
|
||||
- `Frontend`: `npm run build`
|
||||
|
||||
## 主要修改文件
|
||||
|
||||
- `Frontend/src/api/auth.ts`
|
||||
- `Frontend/src/views/AuthView.vue`
|
||||
- `Frontend/src/views/admin/UsersView.vue`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql`
|
||||
@@ -0,0 +1,85 @@
|
||||
# 2026-03-25 服务启动排查与修复
|
||||
|
||||
## 本轮目标
|
||||
|
||||
针对“编译虽然通过,但实际启动失败”的问题,完成一次真实的全链路启动排查,并把确认为代码问题的启动阻塞项修复掉。
|
||||
|
||||
## 本轮结论
|
||||
|
||||
- `Frontend` 可正常启动预览服务。
|
||||
- `YumiNail-Gateway` 可正常启动并监听 `80` 端口。
|
||||
- `YumiNail-Core` 可正常启动并监听 `81` 端口。
|
||||
- `MessageHub` 修复代码后可正常启动并监听 `8080` 端口。
|
||||
|
||||
本轮真实遇到的两个问题:
|
||||
|
||||
1. `MessageHub` 在 `package` 阶段直接编译失败。
|
||||
2. `YumiNail-Core` 首次启动失败,是因为 `81` 端口被旧的 Java 进程占用。
|
||||
|
||||
## 已修复项
|
||||
|
||||
### 1. MessageHub 编译失败
|
||||
|
||||
问题:
|
||||
|
||||
- `RabbitMQConfig` 中错误引用了 `SimpleRabbitListenerContainerFactoryConfigurer` 的包路径,导致 `mvn package` 失败。
|
||||
|
||||
处理:
|
||||
|
||||
- 将导入改为 Spring Boot 2.7 对应的:
|
||||
- `org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer`
|
||||
|
||||
修改文件:
|
||||
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java`
|
||||
|
||||
### 2. YumiNail-Core 启动失败
|
||||
|
||||
问题:
|
||||
|
||||
- `YumiNail-Core` 日志明确报错:`Port 81 is already in use`
|
||||
|
||||
处理:
|
||||
|
||||
- 定位到占用 `81` 端口的旧 `java.exe` 进程。
|
||||
- 终止旧进程后重新启动 `YumiNail-Core`,启动恢复正常。
|
||||
|
||||
## 启动验证
|
||||
|
||||
本轮使用最新产物重新执行:
|
||||
|
||||
- `YumiNail-Core`: `mvn -q -DskipTests clean package`
|
||||
- `YumiNail-Gateway`: `mvn -q -DskipTests clean package`
|
||||
- `MessageHub`: `mvn -q -DskipTests clean package`
|
||||
- `Frontend`: 已使用当前构建产物启动 `vite preview`
|
||||
|
||||
启动后实际监听端口:
|
||||
|
||||
- `Frontend preview`: `4173`
|
||||
- `YumiNail-Gateway`: `80`
|
||||
- `YumiNail-Core`: `81`
|
||||
- `MessageHub`: `8080`
|
||||
|
||||
连通性检查结果:
|
||||
|
||||
- `http://127.0.0.1:4173` 返回 `200`
|
||||
- `http://127.0.0.1/api/shop/list/public` 通过网关返回 `200`
|
||||
- `http://127.0.0.1:8080` 可访问到服务并返回 `404`,说明 Web 容器已正常启动
|
||||
|
||||
## 仍需注意
|
||||
|
||||
`MessageHub` 虽然已经启动成功,但日志里仍持续提示 RabbitMQ 连接超时:
|
||||
|
||||
- 目标地址:`xiaowangnas.com:5672`
|
||||
|
||||
这说明:
|
||||
|
||||
- 当前代码启动链路已恢复
|
||||
- 但当前机器到 RabbitMQ 的网络连通性或目标 RabbitMQ 本身仍有问题
|
||||
|
||||
该问题属于外部依赖环境,不是本轮代码启动失败的直接原因。只要 MQ 不通,`MessageHub` 的监听消费能力就不会正常工作。
|
||||
|
||||
## 本轮修改文件
|
||||
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java`
|
||||
- `docs/changes/2026-03-25-服务启动排查与修复.md`
|
||||
@@ -0,0 +1,46 @@
|
||||
# 2026-03-25 登录店铺预加载 404 兼容处理
|
||||
|
||||
## 问题背景
|
||||
|
||||
线上环境访问登录页时,浏览器控制台出现类似报错:
|
||||
|
||||
- `GET /api/user/check/login-shops/account/{account} 404`
|
||||
|
||||
这类报错的根因通常不是前端路由本身写错,而是当前部署环境还没有同步到“登录前店铺预加载”接口。
|
||||
|
||||
## 本轮处理
|
||||
|
||||
对前台登录页和后台登录页都补了兼容回退:
|
||||
|
||||
### 1. 前台登录页
|
||||
|
||||
- 文件:`Frontend/src/views/AuthView.vue`
|
||||
- 当以下接口返回 `404` 时:
|
||||
- `GET /user/check/login-shops/account/{account}`
|
||||
- `GET /user/check/login-shops/phone/{phone}`
|
||||
- 前端不再把它视为异常错误打印到控制台。
|
||||
- 改为自动回退成:
|
||||
- 允许先直接登录
|
||||
- 页面提示“当前环境暂未开放登录前店铺预加载,可直接登录。”
|
||||
|
||||
### 2. 后台登录页
|
||||
|
||||
- 文件:`Frontend/src/views/admin/AdminLoginView.vue`
|
||||
- 当 `GET /admin/auth/login-shops/{account}` 返回 `404` 时,同样不再在控制台打红错。
|
||||
- 页面会回退为“可直接登录”的兼容模式。
|
||||
|
||||
## 目的
|
||||
|
||||
这次改动的目标不是替代后端接口,而是让前端对“新前端 + 旧后端”的组合更稳一点:
|
||||
|
||||
- 新接口存在时,继续正常显示登录前的门店选择
|
||||
- 新接口不存在时,不因为预加载能力缺失影响基本登录流程
|
||||
|
||||
## 验证
|
||||
|
||||
- `Frontend`: `npm run build` 已通过
|
||||
|
||||
## 影响范围
|
||||
|
||||
- 仅影响登录前“门店预加载”的失败处理逻辑
|
||||
- 不影响真正的登录接口提交逻辑
|
||||
@@ -0,0 +1,49 @@
|
||||
# 2026-03-26 YumiNail 主 SQL 整合首次部署脚本
|
||||
|
||||
## 本轮目标
|
||||
|
||||
把首次部署空库所需执行的 SQL 统一收敛到 `YumiNail.sql`,避免再按“主建表 + 多个补丁 + 初始化模板”分步执行。
|
||||
|
||||
## 已完成
|
||||
|
||||
- 已将以下内容整合进 `YumiNail-Core/src/main/resources/files/YumiNail.sql`:
|
||||
- 基础建表
|
||||
- `2026-03-20_user_asset_vip_coupon_permission_patch.sql`
|
||||
- `2026-03-25_user_shop_binding_and_shop_status_patch.sql`
|
||||
- `2026-03-20_init_admin_permission_template.sql`
|
||||
|
||||
- `YumiNail.sql` 现在已经覆盖:
|
||||
- 余额 / VIP / 优惠券相关补列与初始化
|
||||
- 订单优惠来源字段
|
||||
- 店铺 `status`
|
||||
- `t_user_shop_binding`
|
||||
- 权限种子数据
|
||||
- `admin01` 初始化
|
||||
- 店长 / 美甲师 / 管理员默认后台权限初始化
|
||||
|
||||
## 当前建议执行方式
|
||||
|
||||
首次部署空库时:
|
||||
|
||||
1. 只执行 `YumiNail-Core/src/main/resources/files/YumiNail.sql`
|
||||
|
||||
已有数据库增量升级时:
|
||||
|
||||
1. 仍可继续按原来的补丁 SQL 分步执行
|
||||
2. 原补丁文件保留,主要用于历史库升级,不再作为空库首选入口
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `YumiNail.sql` 顶部仍使用 `use nailart;`
|
||||
- 如果你的实际数据库名不是 `nailart`,执行前需要先修改为真实库名
|
||||
|
||||
## 本轮未做
|
||||
|
||||
- 没有删除旧的补丁 SQL 文件
|
||||
- 没有改动 Java 代码逻辑
|
||||
- 没有直接执行数据库脚本
|
||||
|
||||
## 主要修改文件
|
||||
|
||||
- `YumiNail-Core/src/main/resources/files/YumiNail.sql`
|
||||
- `docs/changes/2026-03-26-YumiNail主SQL整合首次部署脚本.md`
|
||||
Reference in New Issue
Block a user