后台管理功能进行一些优化

This commit is contained in:
xiaowang
2026-02-28 14:32:28 +08:00
parent 36e2950a99
commit 725cb07fcf
23 changed files with 2297 additions and 92 deletions
+2 -1
View File
@@ -22,7 +22,8 @@ const route = useRoute()
const isHiddenNav = computed(() => {
// 检查当前路由及其所有父路由是否有 hideNav: true
const result = route.matched.some(r => r.meta.hideNav)
// 或者检查是否是后台页面
const result = route.matched.some(r => r.meta.hideNav) || route.matched.some(r => r.meta.isAdmin)
console.log('isHiddenNav:', result, 'matched routes:', route.matched)
return result
})
+66 -19
View File
@@ -43,23 +43,44 @@ const showError = (msg: string) => {
}
}
const handleTokenExpired = () => {
const handleTokenExpired = (isAdmin = false) => {
// 登录过期,只提示一次
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
console.log('Token 过期,清理本地存储并跳转到登录页')
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
sessionStorage.removeItem('accessToken')
showError('登录已过期,请重新登录')
try {
router.push('/').catch(err => {
console.error('跳转到登录页失败:', err)
if (isAdmin) {
// 清理后台管理的token
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
showError('登录已过期,请重新登录')
try {
router.push('/admin/login').catch(err => {
console.error('跳转到后台登录页失败:', err)
window.location.href = '/admin/login'
})
} catch (err) {
console.error('跳转到后台登录页异常:', err)
window.location.href = '/admin/login'
}
} else {
// 清理前台的token
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
sessionStorage.removeItem('accessToken')
showError('登录已过期,请重新登录')
try {
router.push('/').catch(err => {
console.error('跳转到登录页失败:', err)
window.location.href = '/'
})
} catch (err) {
console.error('跳转到登录页异常:', err)
window.location.href = '/'
})
} catch (err) {
console.error('跳转到登录页异常:', err)
window.location.href = '/'
}
}
}
}
@@ -70,6 +91,15 @@ api.interceptors.request.use(
if (!token) {
token = sessionStorage.getItem('accessToken')
}
// 检查是否是后台管理的API请求
if (!token && (config.url?.includes('/admin/') || config.url?.includes('/order/admin/'))) {
token = localStorage.getItem('adminAccessToken')
if (!token) {
token = sessionStorage.getItem('adminAccessToken')
}
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
@@ -107,6 +137,9 @@ api.interceptors.response.use(
}
if (error.response?.status === 401) {
// 检查是否是后台管理的API请求
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
@@ -125,18 +158,32 @@ api.interceptors.response.use(
isRefreshing = true
try {
const refreshToken = localStorage.getItem('refreshToken')
let refreshToken
if (isAdminRequest) {
refreshToken = localStorage.getItem('adminRefreshToken')
} else {
refreshToken = localStorage.getItem('refreshToken')
}
if (!refreshToken) {
throw new Error('No refresh token available')
}
// 这里需要根据是否是后台请求调用不同的refreshToken API
// 暂时使用同一个API,实际项目中可能需要分开
const response = await authApi.refreshToken({ refreshToken })
const newToken = (response as any).accessToken
const newRefreshToken = (response as any).refreshToken
localStorage.setItem('accessToken', newToken)
localStorage.setItem('refreshToken', newRefreshToken)
sessionStorage.setItem('accessToken', newToken)
if (isAdminRequest) {
localStorage.setItem('adminAccessToken', newToken)
localStorage.setItem('adminRefreshToken', newRefreshToken)
sessionStorage.setItem('adminAccessToken', newToken)
} else {
localStorage.setItem('accessToken', newToken)
localStorage.setItem('refreshToken', newRefreshToken)
sessionStorage.setItem('accessToken', newToken)
}
processQueue(null, newToken)
@@ -144,13 +191,13 @@ api.interceptors.response.use(
return api(originalRequest)
} catch (refreshError) {
processQueue(refreshError, null)
handleTokenExpired()
handleTokenExpired(isAdminRequest)
return Promise.reject(refreshError)
} finally {
isRefreshing = false
}
} else {
handleTokenExpired()
handleTokenExpired(isAdminRequest)
return Promise.reject(error)
}
} else if (error.response?.status !== 403) { // 403权限不足不提示
+1
View File
@@ -2,6 +2,7 @@ import api from './index'
interface CreateOrderRequest {
couponId?: number
artistId?: number
}
export const orderApi = {
+1
View File
@@ -24,6 +24,7 @@ declare module 'vue' {
ADatePicker: typeof import('ant-design-vue/es')['DatePicker']
ADescriptions: typeof import('ant-design-vue/es')['Descriptions']
ADescriptionsItem: typeof import('ant-design-vue/es')['DescriptionsItem']
ADivider: typeof import('ant-design-vue/es')['Divider']
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
AEmpty: typeof import('ant-design-vue/es')['Empty']
AForm: typeof import('ant-design-vue/es')['Form']
+24 -3
View File
@@ -45,19 +45,40 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { computed, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
import { cartApi } from '../api/cart'
import { message } from 'ant-design-vue'
const router = useRouter()
const route = useRoute()
// 购物车商品数量(示例数据)
const cartCount = ref(3)
// 购物车商品数量
const cartCount = ref(0)
// 是否有未读通知
const hasNotification = ref(true)
// 加载购物车数量
const loadCartCount = async () => {
try {
const data = await cartApi.getCartList()
cartCount.value = data.reduce((sum: number, item: any) => sum + item.quantity, 0)
} catch (error) {
console.error('获取购物车数量失败:', error)
}
}
// 页面加载时获取购物车数量
onMounted(() => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = window.location.pathname.startsWith('/admin')
if (!isAdminPage) {
loadCartCount()
}
})
// 根据当前路由判断激活的导航项
const currentRoute = computed(() => {
const path = route.path
+28 -19
View File
@@ -145,14 +145,21 @@ router.beforeEach((to, _from, next) => {
if (isAdminRoute) {
const adminToken = localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
console.log('Admin route check:', { to: to.path, adminToken: !!adminToken, requiresAuth })
console.log('Admin route check:', { to: to.path, adminToken: !!adminToken, adminUserInfo: !!adminUserInfoStr, requiresAuth })
if (requiresAuth && !adminToken) {
console.log('No token, redirecting to login')
if (requiresAuth && (!adminToken || !adminUserInfoStr)) {
console.log('No token or user info, redirecting to login')
// 清除可能存在的过期信息
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
} else if (to.path === '/admin/login' && adminToken) {
console.log('Token exists, redirecting from login to dashboard')
} else if (to.path === '/admin/login' && adminToken && adminUserInfoStr) {
console.log('Token and user info exist, redirecting from login to dashboard')
next('/admin/dashboard')
} else {
// 检查用户权限
@@ -206,13 +213,14 @@ router.beforeEach((to, _from, next) => {
}
} catch (parseError) {
console.error('Failed to parse user info:', parseError)
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
console.log('Allowing access to home due to parse error')
next()
} else {
next('/admin')
}
// 解析失败,重定向到登录页
console.log('User info parse error, redirecting to login')
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
}
} else {
console.log('No user info found, redirecting to login')
@@ -221,13 +229,14 @@ router.beforeEach((to, _from, next) => {
}
} catch (error) {
console.error('解析用户信息失败:', error)
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
console.log('Allowing access to home due to error')
next()
} else {
next('/admin')
}
// 解析失败,重定向到登录页
console.log('Error parsing user info, redirecting to login')
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
}
} else {
// 没有权限要求,直接通过
+106 -4
View File
@@ -153,15 +153,42 @@
<div class="coupon-time">
{{ coupon.startTime }} 至 {{ coupon.endTime }}
</div>
</div>
<div class="coupon-select" v-if="selectedCoupon && selectedCoupon.id === coupon.id">
<CheckCircleOutlined />
<div class="coupon-select" v-if="selectedCoupon && selectedCoupon.id === coupon.id">
<CheckCircleOutlined />
</div>
</div>
</div>
</a-card>
</div>
</div>
</a-modal>
<!-- 美甲师选择弹窗 -->
<a-modal
v-model:visible="showArtistModal"
title="选择美甲师"
width="90%"
@ok="selectArtistAndCheckout"
@cancel="closeArtistModal"
>
<div class="artist-modal-content">
<a-empty v-if="availableArtists.length === 0" description="暂无可用美甲师" />
<div v-else class="artist-list">
<a-radio-group v-model:value="selectedArtist" name="artist">
<a-radio
v-for="artist in availableArtists"
:key="artist.id"
:value="artist"
class="artist-item"
>
<div class="artist-info">
<span class="artist-name">{{ artist.name }}</span>
</div>
</a-radio>
</a-radio-group>
</div>
</div>
</a-modal>
</div>
</template>
@@ -397,6 +424,26 @@ const selectCoupon = (coupon: UserCoupon) => {
showCouponModal.value = false
}
// 美甲师选择相关状态
const showArtistModal = ref(false)
const selectedArtist = ref<{id: number, name: string} | null>(null)
const availableArtists = ref<{id: number, name: string}[]>([])
// 加载可用美甲师
const loadAvailableArtists = async () => {
try {
// 这里需要根据商品ID获取可用的美甲师
// 暂时使用模拟数据
availableArtists.value = [
{ id: 1, name: '美甲师1' },
{ id: 2, name: '美甲师2' },
{ id: 3, name: '美甲师3' }
]
} catch (error) {
console.error('获取美甲师列表失败:', error)
}
}
// 处理结算
const handleCheckout = async () => {
const selectedItems = cartItems.value.filter(item => item.selected)
@@ -405,17 +452,39 @@ const handleCheckout = async () => {
return
}
// 加载可用美甲师
await loadAvailableArtists()
// 显示美甲师选择弹窗
showArtistModal.value = true
}
// 选择美甲师并创建订单
const selectArtistAndCheckout = async () => {
if (!selectedArtist.value) {
message.warning('请选择美甲师')
return
}
try {
const order = await orderApi.createOrder({
couponId: selectedCoupon.value ? selectedCoupon.value.id : undefined
couponId: selectedCoupon.value ? selectedCoupon.value.id : undefined,
artistId: selectedArtist.value.id
})
message.success('订单创建成功')
showArtistModal.value = false
router.push('/profile')
} catch (error) {
message.error('创建订单失败')
}
}
// 关闭美甲师选择弹窗
const closeArtistModal = () => {
showArtistModal.value = false
selectedArtist.value = null
}
// 监听选中商品变化,重新加载可用优惠券
watch(
() => cartItems.value.map(item => ({ id: item.id, selected: item.selected, quantity: item.quantity })),
@@ -745,4 +814,37 @@ onMounted(() => {
font-size: 20px;
flex-shrink: 0;
}
/* 美甲师选择弹窗样式 */
.artist-modal-content {
max-height: 400px;
overflow-y: auto;
}
.artist-list {
padding: 8px 0;
}
.artist-item {
display: block;
width: 100%;
padding: 12px 0;
border-bottom: 1px solid #f0f0f0;
}
.artist-item:last-child {
border-bottom: none;
}
.artist-info {
display: flex;
align-items: center;
gap: 12px;
}
.artist-name {
font-size: 15px;
font-weight: 600;
color: #333;
}
</style>
+166 -13
View File
@@ -6,11 +6,11 @@
<!-- 用户信息区域 -->
<div class="user-info" @click="handleUserClick">
<div class="avatar">
<a-avatar :size="40" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
<a-avatar :size="40" :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
</div>
<div class="welcome">
<p class="greeting">Hello!</p>
<p class="username">昵称</p>
<p class="username">{{ userInfo.nickname || '用户' }}</p>
</div>
</div>
<!-- 通知按钮 -->
@@ -102,12 +102,25 @@
</div>
</a-card>
</div>
<!-- 加载状态 -->
<div v-if="loading" class="loading-more">
<a-spin size="small" />
<span style="margin-left: 8px;">加载中...</span>
</div>
<!-- 暂无更多商品 -->
<div v-else-if="!hasMore && popularItems.length > 0" class="no-more">
暂无更多商品推荐
</div>
<!-- 无商品时的提示 -->
<div v-else-if="popularItems.length === 0 && !loading" class="no-products">
暂无热门商品
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import {
BellOutlined,
@@ -115,25 +128,142 @@ import {
FilterOutlined,
RightOutlined
} from '@ant-design/icons-vue'
import { userApi, type UserVO } from '../api/user'
import { productApi } from '../api/product'
const router = useRouter()
// 用户信息
const userInfo = ref<UserVO>({
id: 0,
nickname: '',
account: '',
avatar: '',
createTime: '',
updateTime: ''
})
// 搜索关键词
const searchQuery = ref('')
// 精选商品数据
const featuredItems = ref([
{ id: 1, name: 'Watch', price: 40, bgColor: '#ffe4d6' },
{ id: 2, name: 'Nike Shoes', price: 430, bgColor: '#d6eaff' },
{ id: 3, name: 'Airpods', price: 333, bgColor: '#e2ffd6' }
])
const featuredItems = ref<any[]>([])
// 热门商品数据
const popularItems = ref([
{ id: 4, name: 'LG TV', price: 330, bgColor: '#f0d6ff' },
{ id: 5, name: 'Hoodie', price: 50, bgColor: '#ffd6e2' },
{ id: 6, name: 'Jacket', price: 400, bgColor: '#d6fff0' }
])
const popularItems = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)
// 加载用户信息
const loadUserInfo = async () => {
try {
const data = await userApi.getUserInfo()
userInfo.value = data as unknown as UserVO
} catch (error) {
console.error('获取用户信息失败:', error)
}
}
// 加载精选商品
const loadFeaturedProducts = async () => {
try {
const data = await productApi.getProductsByTag('精选')
// 随机选择5个商品
const shuffled = data.sort(() => 0.5 - Math.random())
featuredItems.value = shuffled.slice(0, 5).map(item => ({
id: item.id,
name: item.name,
price: item.price,
bgColor: getRandomColor()
}))
} catch (error) {
console.error('获取精选商品失败:', error)
}
}
// 加载热门商品
const loadPopularProducts = async (loadMore = false) => {
if (loading.value || !hasMore.value) return
loading.value = true
try {
const data = await productApi.getProductsByTag('热门')
if (loadMore) {
// 模拟分页,实际应该在API中实现
const start = (page.value - 1) * pageSize.value
const end = start + pageSize.value
const newItems = data.slice(start, end)
if (newItems.length < pageSize.value) {
hasMore.value = false
}
popularItems.value = [...popularItems.value, ...newItems.map(item => ({
id: item.id,
name: item.name,
price: item.price,
bgColor: getRandomColor()
}))]
} else {
// 初始加载
popularItems.value = data.slice(0, pageSize.value).map(item => ({
id: item.id,
name: item.name,
price: item.price,
bgColor: getRandomColor()
}))
if (data.length <= pageSize.value) {
hasMore.value = false
}
}
} catch (error) {
console.error('获取热门商品失败:', error)
} finally {
loading.value = false
}
}
// 处理滚动事件,实现懒加载
const handleScroll = () => {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
const clientHeight = document.documentElement.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 100 && !loading.value && hasMore.value) {
page.value++
loadPopularProducts(true)
}
}
// 添加滚动监听
onMounted(() => {
loadUserInfo()
loadFeaturedProducts()
loadPopularProducts()
window.addEventListener('scroll', handleScroll)
})
// 移除滚动监听
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll)
})
// 生成随机颜色
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
}
// 页面加载时获取数据
onMounted(() => {
loadUserInfo()
loadFeaturedProducts()
loadPopularProducts()
})
// 处理用户头像点击
const handleUserClick = () => {
@@ -419,4 +549,27 @@ const handleProductClick = (item: any) => {
.popular-section {
padding-bottom: 20px;
}
.loading-more {
display: flex;
justify-content: center;
align-items: center;
padding: 20px 0;
color: #999;
font-size: 14px;
}
.no-more {
text-align: center;
padding: 20px 0;
color: #999;
font-size: 14px;
}
.no-products {
text-align: center;
padding: 40px 0;
color: #999;
font-size: 14px;
}
</style>
+11 -2
View File
@@ -58,11 +58,11 @@
</div>
</a-col>
<a-col :span="8">
<div class="stat-item">
<div class="stat-item" @click="handleCouponClick" style="cursor: pointer;">
<div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
<CreditCardOutlined />
</div>
<a-statistic title="优惠券" :value="3" />
<a-statistic title="优惠券" :value="couponCount" />
</div>
</a-col>
</a-row>
@@ -252,6 +252,7 @@ const orders = ref<any[]>([])
const coupons = ref<any[]>([])
const loading = ref(false)
const orderCount = ref(0)
const couponCount = ref(0)
const editForm = ref({
nickname: '',
@@ -411,6 +412,7 @@ const loadCoupons = async () => {
try {
const data = await couponApi.listUserCoupons()
coupons.value = data
couponCount.value = data.length
} catch (error) {
message.error('获取优惠券列表失败')
} finally {
@@ -418,6 +420,12 @@ const loadCoupons = async () => {
}
}
// 处理优惠券点击
const handleCouponClick = () => {
activeTab.value = 'coupons'
loadCoupons()
}
// 处理取消订单
const handleCancelOrder = async (orderId: number) => {
Modal.confirm({
@@ -500,6 +508,7 @@ const getRandomColor = () => {
onMounted(() => {
fetchUserInfo()
loadOrders()
loadCoupons()
})
</script>
+8 -1
View File
@@ -92,7 +92,8 @@ import {
DownOutlined,
LogoutOutlined,
GiftOutlined,
TagOutlined
TagOutlined,
ShoppingOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { userApi, type UserVO, adminAuthApi } from '@/api/admin'
@@ -154,6 +155,12 @@ const menuItems = [
icon: TagOutlined,
label: '标签管理',
permissionCode: 'tag:view'
},
{
key: '/admin/orders',
icon: ShoppingOutlined,
label: '订单管理',
permissionCode: 'order:view'
}
]
+140 -3
View File
@@ -52,7 +52,10 @@
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="showEditModal(record)">
<a-button v-if="hasPermission('coupon:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('coupon:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button v-if="hasPermission('coupon:assign') && record.status === 1" type="link" size="small" @click="showDistributeModal(record)">
@@ -199,6 +202,86 @@
</a-form-item>
</a-form>
</a-modal>
<!-- 查看优惠券详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看优惠券详情"
@cancel="handleViewModalCancel"
width="800px"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券编码">
<a-input v-model:value="viewFormState.couponCode" :disabled="true" />
</a-form-item>
<a-form-item label="优惠券名称">
<a-input v-model:value="viewFormState.couponName" :disabled="true" />
</a-form-item>
<a-form-item label="所属店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠券类型">
<a-select v-model:value="viewFormState.couponType" :disabled="true">
<a-select-option :value="1">折扣券</a-select-option>
<a-select-option :value="2">满减券</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="viewFormState.couponType === 1" label="折扣值">
<a-input-number v-model:value="viewFormState.discountValue" :disabled="true" />
</a-form-item>
<a-form-item v-if="viewFormState.couponType === 2" label="最低消费">
<a-input-number v-model:value="viewFormState.minAmount" :disabled="true" />
</a-form-item>
<a-form-item v-if="viewFormState.couponType === 2" label="减免金额">
<a-input-number v-model:value="viewFormState.reduceAmount" :disabled="true" />
</a-form-item>
<a-form-item label="总数量">
<a-input-number v-model:value="viewFormState.totalCount" :disabled="true" />
</a-form-item>
<a-form-item label="开始时间">
<a-date-picker v-model:value="viewFormState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="true" />
</a-form-item>
<a-form-item label="结束时间">
<a-date-picker v-model:value="viewFormState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="true" />
</a-form-item>
<a-form-item label="可用标签">
<a-select
v-model:value="viewFormState.availableTagIds"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="不可用标签">
<a-select
v-model:value="viewFormState.unavailableTagIds"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
@@ -255,6 +338,7 @@ const getCurrentUserInfo = () => {
const loading = ref(false)
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const searchText = ref('')
@@ -267,6 +351,22 @@ const distributeLoading = ref(false)
const distributeFormRef = ref<FormInstance>()
const currentDistributeCoupon = ref<Coupon | null>(null)
// 查看优惠券相关状态
const viewFormState = reactive({
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: undefined,
endTime: undefined,
availableTagIds: [] as number[],
unavailableTagIds: [] as number[],
shopId: undefined as number | undefined
})
const couponList = ref<Coupon[]>([])
const tagList = ref<TagVO[]>([])
const userList = ref<any[]>([])
@@ -453,6 +553,37 @@ const showEditModal = (record: Coupon) => {
}
}
const showViewModal = (record: Coupon) => {
if (!record) {
message.error('优惠券数据不存在')
return
}
try {
Object.assign(viewFormState, {
couponCode: record.couponCode || '',
couponName: record.couponName || '',
couponType: record.couponType || 1,
discountValue: record.discountValue || 0,
minAmount: record.minAmount || 0,
reduceAmount: record.reduceAmount || 0,
totalCount: record.totalCount || 0,
startTime: record.startTime ? dayjs(record.startTime) : undefined,
endTime: record.endTime ? dayjs(record.endTime) : undefined,
availableTagIds: record.availableTags ? record.availableTags.map(tag => tag.id) : [],
unavailableTagIds: record.unavailableTags ? record.unavailableTags.map(tag => tag.id) : [],
shopId: record.shopId
})
viewModalVisible.value = true
} catch (error) {
console.error('Error in showViewModal:', error)
message.error('打开查看模态框失败')
}
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
@@ -525,8 +656,14 @@ const handleModalOk = async () => {
}
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
message.confirm({
title: '确认关闭',
content: '确定要关闭编辑模态框吗?未保存的更改将会丢失。',
onOk: () => {
modalVisible.value = false
formRef.value?.resetFields()
}
})
}
const handleDelete = (record: Coupon) => {
+22 -2
View File
@@ -31,7 +31,7 @@
</a-statistic>
</a-card>
</a-col>
<a-col :span="6">
<a-col :span="6" v-if="isAdmin">
<a-card>
<a-statistic
title="店铺数量"
@@ -110,7 +110,7 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
UserOutlined,
@@ -131,6 +131,26 @@ const stats = reactive<DashboardStats>({
recentActivities: []
})
// 获取当前用户信息
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
// 判断是否为管理员
const isAdmin = computed(() => {
const userInfo = getCurrentUserInfo()
return userInfo?.type === 4
})
const formatTime = (timeStr: string) => {
if (!timeStr) return ''
const time = new Date(timeStr)
+55
View File
@@ -28,6 +28,9 @@
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="showOrderDetail(record)">
查看
</a-button>
<a-button v-if="record.status === 1" type="primary" size="small" @click="processOrder(record.id, 2)">
确认完成
</a-button>
@@ -40,6 +43,38 @@
</a-table>
</a-card>
</div>
<!-- 订单详情模态框 -->
<a-modal
v-model:open="detailModalVisible"
title="订单详情"
@cancel="handleDetailModalCancel"
width="800px"
>
<div v-if="currentOrder">
<a-descriptions :column="2">
<a-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ currentOrder.userId }}</a-descriptions-item>
<a-descriptions-item label="总金额">¥{{ currentOrder.totalAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="实际金额">¥{{ currentOrder.actualAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="优惠券">{{ currentOrder.couponName || '无' }}</a-descriptions-item>
<a-descriptions-item label="订单状态">{{ currentOrder.statusText }}</a-descriptions-item>
<a-descriptions-item label="创建时间" :span="2">{{ currentOrder.createTime }}</a-descriptions-item>
</a-descriptions>
<a-divider>订单商品</a-divider>
<a-table :columns="orderItemColumns" :data-source="currentOrder.items" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'price'">
¥{{ record.price.toFixed(2) }}
</template>
<template v-else-if="column.key === 'totalPrice'">
¥{{ (record.price * record.quantity).toFixed(2) }}
</template>
</template>
</a-table>
</div>
</a-modal>
</template>
<script setup lang="ts">
@@ -64,6 +99,8 @@ interface Order {
const orders = ref<Order[]>([])
const loading = ref(false)
const searchText = ref('')
const detailModalVisible = ref(false)
const currentOrder = ref<Order | null>(null)
const pagination = reactive({
current: 1,
@@ -74,6 +111,14 @@ const pagination = reactive({
showTotal: (total: number) => `共 ${total} 条`
})
const orderItemColumns = [
{ title: '商品ID', dataIndex: 'productId', key: 'productId' },
{ title: '商品名称', dataIndex: 'productTitle', key: 'productTitle' },
{ title: '单价', key: 'price', width: 100 },
{ title: '数量', dataIndex: 'quantity', key: 'quantity', width: 100 },
{ title: '总价', key: 'totalPrice', width: 100 }
]
const columns = [
{ title: '订单编号', dataIndex: 'orderNo', key: 'orderNo' },
{ title: '用户ID', dataIndex: 'userId', key: 'userId' },
@@ -138,6 +183,16 @@ const processOrder = async (orderId: number, status: number) => {
}
}
const showOrderDetail = (order: Order) => {
currentOrder.value = order
detailModalVisible.value = true
}
const handleDetailModalCancel = () => {
detailModalVisible.value = false
currentOrder.value = null
}
onMounted(() => {
loadOrders()
})
+46 -6
View File
@@ -256,13 +256,43 @@ const getUserTypeText = (type: number) => {
const filteredUserList = computed(() => {
if (!currentLoginUser.value) return []
return userList.value.filter(user => user.type < currentLoginUser.value!.type && user.type !== 0)
// 管理员可以看到所有用户(除了普通用户和自己)
if (currentLoginUser.value.type === 4) {
return userList.value.filter(user => user.type !== 0 && user.id !== currentLoginUser.value!.id)
}
// 店长只能看到美甲师(除了自己)
if (currentLoginUser.value.type === 2) {
return userList.value.filter(user => user.type === 3 && user.id !== currentLoginUser.value!.id)
}
// 其他用户类型(如美甲师)不能管理权限
return []
})
const fetchCurrentUser = async () => {
try {
const res = await userApi.getUserInfo()
currentLoginUser.value = res as unknown as UserVO
// 尝试从API获取用户信息
try {
const res = await userApi.getUserInfo()
currentLoginUser.value = res as unknown as UserVO
console.log('从API获取当前用户信息:', currentLoginUser.value)
} catch (apiError) {
// 如果API调用失败,尝试从本地存储获取
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
try {
const userInfo = JSON.parse(userInfoStr)
currentLoginUser.value = userInfo as UserVO
console.log('从本地存储获取当前用户信息:', currentLoginUser.value)
} catch (parseError) {
console.error('解析本地存储的用户信息失败:', parseError)
}
} else {
console.error('获取当前用户信息失败,本地存储也没有用户信息')
}
}
} catch (error) {
console.error('获取当前用户信息失败:', error)
}
@@ -284,11 +314,18 @@ const fetchPermissionList = async () => {
const fetchUserList = async () => {
userLoading.value = true
try {
const res = await userApi.listUsers({
const params: any = {
page: 1,
size: 100,
keyword: userSearchText.value
})
}
// 如果当前用户不是管理员,只获取当前店铺的用户
if (currentLoginUser.value && currentLoginUser.value.type !== 4 && currentLoginUser.value.shopId) {
params.shopId = currentLoginUser.value.shopId
}
const res = await userApi.listUsers(params)
userList.value = res.list || []
} catch (error) {
message.error('获取用户列表失败')
@@ -397,7 +434,10 @@ onMounted(async () => {
await fetchCurrentUser()
await loadUserPermissions()
fetchPermissionList()
fetchUserList()
// 确保在获取当前用户信息后再获取用户列表
setTimeout(() => {
fetchUserList()
}, 100)
})
</script>
+186
View File
@@ -61,6 +61,9 @@
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('product:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
@@ -241,6 +244,117 @@
</template>
</a-form>
</a-modal>
<!-- 查看商品详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看商品详情"
width="700px"
@cancel="handleViewModalCancel"
>
<a-form
:model="viewFormState"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
<a-form-item label="商品名称">
<a-input v-model:value="viewFormState.title" :disabled="true" />
</a-form-item>
<a-form-item label="商品描述">
<a-textarea
v-model:value="viewFormState.description"
:rows="3"
:disabled="true"
/>
</a-form-item>
<a-form-item label="店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="商品图片">
<div class="product-images">
<a-image
v-for="(url, index) in viewImageUrls"
:key="index"
:width="80"
:height="80"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 8px; margin-bottom: 8px;"
:preview="false"
/>
</div>
</a-form-item>
<a-form-item label="价格">
<a-input-number
v-model:value="viewFormState.price"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="预计时长">
<a-input-number
v-model:value="viewFormState.approximateDuration"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="标签">
<a-select
v-model:value="viewFormState.tags"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="tag in tags"
:key="tag.id"
:value="tag.id.toString()"
>
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可预约美甲师">
<a-select
v-model:value="viewFormState.bookableArtists"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="artist in artists"
:key="artist.id"
:value="artist.id.toString()"
>
{{ artist.nickname }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可用优惠券">
<a-select
v-model:value="viewFormState.availableCoupons"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="coupon in coupons"
:key="coupon?.id"
:value="coupon?.id?.toString()"
>
{{ coupon?.couponName || '' }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
@@ -258,6 +372,7 @@ const loading = ref(false)
const searchText = ref('')
const productList = ref<Product[]>([])
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const currentProduct = ref<Product | null>(null)
@@ -274,10 +389,23 @@ const previewImage = ref('')
const imageFileList = ref<any[]>([])
const uploadedFileIds = ref<string[]>([])
const imageUrls = ref<Record<number, string[]>>({})
const viewImageUrls = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const isAdmin = ref(false)
const formRef = ref<any>(null)
const viewFormState = reactive({
shopId: undefined,
title: '',
description: '',
imageFileIds: '',
price: 0,
tags: [] as string[],
approximateDuration: undefined,
bookableArtists: [] as string[],
availableCoupons: [] as string[]
})
const pagination = reactive({
current: 1,
pageSize: 10,
@@ -585,6 +713,64 @@ const showEditModal = async (record: Product) => {
modalVisible.value = true
}
const showViewModal = async (record: Product) => {
// 处理标签
const tagsArray = record.tags ? record.tags.split(';').filter(tag => tag) : []
// 处理美甲师
const artistsArray = record.bookableArtists ? record.bookableArtists.split(',').filter(artist => artist) : []
// 处理优惠券
const couponsArray = record.availableCoupons ? record.availableCoupons.split(',').filter(coupon => coupon) : []
// 处理预计时长,将字符串转换为数字
const durationNumber = record.approximateDuration ? parseInt(record.approximateDuration.replace('分钟', '')) : undefined
Object.assign(viewFormState, {
shopId: record.shopId,
title: record.title,
description: record.description,
imageFileIds: record.imageFileIds,
price: record.price,
tags: tagsArray,
approximateDuration: durationNumber,
bookableArtists: artistsArray,
availableCoupons: couponsArray
})
// 加载图片URL
if (record.imageFileIds) {
const ids = record.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const signedUrl = await adminFileApi.getSignedUrl(Number(id))
imageIdCache.value[id] = signedUrl
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = [DEFAULT_PRODUCT_IMAGE]
}
// 获取该店铺的美甲师列表
if (record.shopId) {
await fetchArtists(record.shopId)
}
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
}
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
+98
View File
@@ -52,6 +52,9 @@
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('shop:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('shop:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
@@ -122,6 +125,50 @@
</a-form-item>
</a-form>
</a-modal>
<!-- 查看店铺详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看店铺详情"
width="600px"
@cancel="handleViewModalCancel"
>
<a-form
:model="viewFormState"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
<a-form-item label="店铺名称">
<a-input v-model:value="viewFormState.shopName" :disabled="true" />
</a-form-item>
<a-form-item label="店铺描述">
<a-textarea
v-model:value="viewFormState.description"
:rows="3"
:disabled="true"
/>
</a-form-item>
<a-form-item label="店铺地址">
<a-input v-model:value="viewFormState.address" :disabled="true" />
</a-form-item>
<a-form-item label="营业时间">
<a-input v-model:value="viewFormState.businessHours" :disabled="true" />
</a-form-item>
<a-form-item label="店铺图片">
<div class="shop-images">
<a-image
v-for="(url, index) in viewImageUrls"
:key="index"
:width="80"
:height="80"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 8px; margin-bottom: 8px;"
:preview="false"
/>
</div>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
@@ -140,6 +187,7 @@ const loading = ref(false)
const searchText = ref('')
const shopList = ref<Shop[]>([])
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
@@ -151,9 +199,19 @@ const imageFileList = ref<any[]>([])
const uploadedFileIds = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const shopImageUrls = ref<Record<number, string[]>>({})
const viewImageUrls = ref<string[]>([])
const previewVisible = ref(false)
const previewImage = ref('')
// 查看店铺相关状态
const viewFormState = reactive({
shopName: '',
description: '',
address: '',
businessHours: '',
imageFileIds: ''
})
const pagination = reactive({
current: 1,
pageSize: 10,
@@ -387,6 +445,46 @@ const showEditModal = async (record: Shop) => {
modalVisible.value = true
}
const showViewModal = async (record: Shop) => {
Object.assign(viewFormState, {
shopName: record.shopName,
description: record.description,
address: record.address,
businessHours: record.businessHours,
imageFileIds: record.imageFileIds
})
// 加载图片URL
if (record.imageFileIds) {
const ids = record.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const signedUrl = await adminFileApi.getSignedUrl(Number(id))
imageIdCache.value[id] = signedUrl
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = [DEFAULT_SHOP_IMAGE]
}
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
+427
View File
@@ -0,0 +1,427 @@
<template>
<div class="tags">
<a-page-header title="标签管理" sub-title="管理系统标签" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索标签名称"
style="width: 250px"
@search="handleSearch"
/>
<a-button v-if="hasPermission('tag:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增标签
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="tagList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'color'">
<span
class="tag-preview"
:style="{
backgroundColor: record.bgColor,
color: record.textColor,
borderColor: record.borderColor
}"
>
{{ record.tagName }}
</span>
</template>
<template v-else-if="column.key === 'shop'">
<span>{{ getShopName(record.shopId) }}</span>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('tag:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('tag:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button v-if="hasPermission('tag:delete')" type="link" size="small" danger @click="handleDelete(record)">
删除
</a-button>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal
v-model:open="modalVisible"
:title="isEdit ? '编辑标签' : '新增标签'"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
width="600px"
>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="标签名称" name="tagName">
<a-input v-model:value="formState.tagName" placeholder="请输入标签名称" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择所属店铺"
style="width: 100%"
:loading="loadingShops"
:disabled="getCurrentUserInfo()?.type === 2"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="文字颜色" name="textColor">
<el-color-picker v-model="formState.textColor" />
</a-form-item>
<a-form-item label="背景颜色" name="bgColor">
<el-color-picker v-model="formState.bgColor" />
</a-form-item>
<a-form-item label="边框颜色" name="borderColor">
<el-color-picker v-model="formState.borderColor" />
</a-form-item>
<a-form-item label="预览">
<span
class="tag-preview"
:style="{
backgroundColor: formState.bgColor,
color: formState.textColor,
borderColor: formState.borderColor
}"
>
{{ formState.tagName }}
</span>
</a-form-item>
</a-form>
</a-modal>
<!-- 查看标签详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看标签详情"
@cancel="handleViewModalCancel"
width="600px"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="标签名称">
<a-input v-model:value="viewFormState.tagName" :disabled="true" />
</a-form-item>
<a-form-item label="所属店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="文字颜色">
<el-color-picker v-model="viewFormState.textColor" disabled />
</a-form-item>
<a-form-item label="背景颜色">
<el-color-picker v-model="viewFormState.bgColor" disabled />
</a-form-item>
<a-form-item label="边框颜色">
<el-color-picker v-model="viewFormState.borderColor" disabled />
</a-form-item>
<a-form-item label="预览">
<span
class="tag-preview"
:style="{
backgroundColor: viewFormState.bgColor,
color: viewFormState.textColor,
borderColor: viewFormState.borderColor
}"
>
{{ viewFormState.tagName }}
</span>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { adminTagApi, adminShopApi, type Shop } from '@/api/admin'
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
const loading = ref(false)
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const searchText = ref('')
const formRef = ref<FormInstance>()
const currentTag = ref<any>(null)
// 查看标签相关状态
const viewFormState = reactive({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
const tagList = ref<any[]>([])
const shops = ref<Shop[]>([])
const loadingShops = ref(false)
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
const formRules = {
tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
}
const columns = [
{ title: '标签名称', dataIndex: 'tagName', key: 'tagName' },
{ title: '所属店铺', key: 'shop', width: 150 },
{ title: '预览', key: 'color', width: 150 },
{ title: '文字颜色', dataIndex: 'textColor', key: 'textColor', width: 120 },
{ title: '背景颜色', dataIndex: 'bgColor', key: 'bgColor', width: 120 },
{ title: '边框颜色', dataIndex: 'borderColor', key: 'borderColor', width: 120 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const fetchTags = async () => {
loading.value = true
try {
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
let tags
if (shopId) {
tags = await adminTagApi.listTagsByShopId(shopId)
} else {
tags = await adminTagApi.listAllTags()
}
console.log('Tags data:', tags)
tagList.value = tags || []
pagination.total = tagList.value.length
} catch (error) {
console.error('获取标签列表失败:', error)
message.error('获取标签列表失败')
} finally {
loading.value = false
}
}
const fetchShops = async () => {
loadingShops.value = true
try {
const res = await adminShopApi.listAllShops()
shops.value = res || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
const getShopName = (shopId: number) => {
const shop = shops.value.find(s => s.id === shopId)
return shop ? shop.shopName : '未知店铺'
}
const handleSearch = () => {
pagination.current = 1
fetchTags()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
fetchTags()
}
const showAddModal = () => {
isEdit.value = false
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
Object.assign(formState, {
tagName: '',
shopId: shopId,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
modalVisible.value = true
}
const showEditModal = (record: any) => {
console.log('Edit record:', record)
isEdit.value = true
currentTag.value = record
Object.assign(formState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor
})
modalVisible.value = true
}
const showViewModal = (record: any) => {
Object.assign(viewFormState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor
})
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
const requestData = {
tagName: formState.tagName,
shopId: formState.shopId,
textColor: formState.textColor,
bgColor: formState.bgColor,
borderColor: formState.borderColor
}
console.log('Request data:', requestData)
console.log('Current tag:', currentTag.value)
if (isEdit.value && currentTag.value) {
console.log('Updating tag with id:', currentTag.value.id)
await adminTagApi.updateTag(currentTag.value.id, requestData)
message.success('更新成功')
} else {
await adminTagApi.createTag(requestData)
message.success('创建成功')
}
modalVisible.value = false
fetchTags()
} catch (error) {
console.error('Error:', error)
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
}
const handleDelete = (record: any) => {
message.confirm({
title: '确认删除',
content: `确定要删除标签 ${record.tagName} 吗?`,
onOk: async () => {
try {
await adminTagApi.deleteTag(record.id)
message.success('删除成功')
fetchTags()
} catch (error) {
message.error('删除失败')
}
}
})
}
onMounted(async () => {
await loadUserPermissions()
await fetchShops()
await fetchTags()
})
</script>
<style scoped>
.tags {
padding: 0;
}
.tag-preview {
display: inline-block;
padding: 4px 12px;
border-radius: 4px;
border: 1px solid;
font-size: 14px;
}
</style>
+83
View File
@@ -48,6 +48,9 @@
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('user:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('user:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
@@ -128,12 +131,66 @@
</a-form-item>
<a-form-item label="用户类型" name="type">
<a-select v-model:value="formState.type" placeholder="请选择用户类型">
<!-- 管理员可以新建所有类型 -->
<a-select-option v-if="currentUserInfo?.type === 4" :value="0">用户</a-select-option>
<a-select-option v-if="currentUserInfo?.type === 4" :value="2">店长</a-select-option>
<a-select-option v-if="currentUserInfo?.type === 4" :value="3">美甲师</a-select-option>
<a-select-option v-if="currentUserInfo?.type === 4" :value="4">管理员</a-select-option>
<!-- 店长可以新建美甲师和用户 -->
<a-select-option v-else-if="currentUserInfo?.type === 2" :value="0">用户</a-select-option>
<a-select-option v-else-if="currentUserInfo?.type === 2" :value="3">美甲师</a-select-option>
<!-- 美甲师只能新建用户 -->
<a-select-option v-else-if="currentUserInfo?.type === 3" :value="0">用户</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
<!-- 查看用户详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看用户详情"
@cancel="handleViewModalCancel"
width="600px"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="账号">
<a-input v-model:value="viewFormState.account" :disabled="true" />
</a-form-item>
<a-form-item label="昵称">
<a-input v-model:value="viewFormState.nickname" :disabled="true" />
</a-form-item>
<a-form-item label="手机号">
<a-input v-model:value="viewFormState.phone" :disabled="true" />
</a-form-item>
<a-form-item label="所属店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shopList"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="用户类型">
<a-select v-model:value="viewFormState.type" :disabled="true">
<a-select-option :value="0">用户</a-select-option>
<a-select-option :value="2">店长</a-select-option>
<a-select-option :value="3">美甲师</a-select-option>
<a-select-option :value="4">管理员</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="创建时间">
<a-input v-model:value="viewFormState.createTime" :disabled="true" />
</a-form-item>
</a-form>
</a-modal>
</div>
@@ -172,12 +229,22 @@ const userList = ref<UserVO[]>([])
const shopList = ref<Shop[]>([])
const modalVisible = ref(false)
const modalLoading = ref(false)
const viewModalVisible = ref(false)
const isEdit = ref(false)
const isAdmin = ref(false)
const formRef = ref<FormInstance>()
const currentUser = ref<UserVO | null>(null)
const currentUserInfo = getCurrentUserInfo()
const viewFormState = reactive({
account: '',
nickname: '',
phone: '',
shopId: undefined as number | undefined,
type: 0,
createTime: ''
})
const pagination = reactive({
current: 1,
pageSize: 10,
@@ -339,6 +406,22 @@ const showEditModal = (record: UserVO) => {
modalVisible.value = true
}
const showViewModal = (record: UserVO) => {
Object.assign(viewFormState, {
account: record.account,
nickname: record.nickname,
phone: record.phone,
shopId: record.shopId,
type: record.type,
createTime: record.createTime
})
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
const checkAccountExists = async (account: string) => {
try {
const res = await userApi.listUsers({ page: 1, size: 1000, keyword: account, status: 1 })