重构Salon后台单管理员与经营驾驶舱

This commit is contained in:
2026-10-26 01:19:23 +08:00
parent 17cf16db36
commit b8327146cb
35 changed files with 1087 additions and 4158 deletions
File diff suppressed because it is too large Load Diff
@@ -1,514 +1,78 @@
<template>
<div class="admin-login">
<div class="login-container">
<div class="login-header">
<h1>后台管理系统</h1>
<p>欢迎回来,请登录您的账户</p>
</div>
<main class="salon-admin-login">
<section class="login-panel">
<div class="brand-mark">S</div>
<p class="eyebrow">SALON PLATFORM</p>
<h1>Salon 管理驾驶舱</h1>
<p class="intro">平台管理员专用入口,统一查看门店经营与运营事项。</p>
<a-card class="login-card">
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleLogin"
>
<a-alert
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
show-icon
:message="loginShopMessage"
style="margin-bottom: 16px"
/>
<a-form :model="formState" :rules="formRules" layout="vertical" @finish="handleLogin">
<a-form-item label="管理员账号" name="account">
<a-input v-model:value="formState.account" size="large" autocomplete="username" placeholder="请输入管理员账号" />
</a-form-item>
<a-form-item label="登录密码" name="password">
<a-input-password v-model:value="formState.password" size="large" autocomplete="current-password" placeholder="请输入登录密码" />
</a-form-item>
<a-button type="primary" size="large" html-type="submit" block :loading="loading">进入管理后台</a-button>
</a-form>
<a-form-item label="用户名" name="account">
<a-input
v-model:value="formState.account"
size="large"
placeholder="请输入用户名"
:prefix-icon="UserOutlined"
@input="handleAccountInput"
/>
</a-form-item>
<a-form-item label="密码" name="password">
<a-input-password
v-model:value="formState.password"
size="large"
placeholder="请输入密码"
:prefix-icon="LockOutlined"
@pressEnter="handleLogin"
/>
</a-form-item>
<a-form-item v-if="hasAvailableShops || !allowShoplessLogin" label="登录店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="shopPlaceholder"
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
show-search
:filter-option="filterShopOption"
/>
</a-form-item>
<a-form-item>
<a-button
type="primary"
size="large"
html-type="submit"
:loading="loading"
block
>
登录
</a-button>
</a-form-item>
</a-form>
<div class="login-footer">
<a @click="goToFrontend">返回前台</a>
</div>
</a-card>
</div>
</div>
</section>
</main>
</template>
<script setup lang="ts">
/**
* AdminLoginView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { reactive, ref } 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'
/**
* Purpose: LoginShopSelectionResponse supports AdminLoginView.vue by holding or executing the login shop selection response page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
import { adminAuthApi } from '@/api/admin'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { resolveAdminLandingPath } from '@/utils/admin-auth-bootstrap'
/**
* Purpose: router supports AdminLoginView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
/**
* Purpose: formRef supports AdminLoginView.vue by holding or executing the form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** shopLoading is a reactive state variable used by the template and event handlers. */
const shopLoading = ref(false)
/**
* Purpose: shops supports AdminLoginView.vue by holding or executing the shops page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shops = ref<Array<{ id: IdType; shopName: string }>>([])
/** allowShoplessLogin is a reactive state variable used by the template and event handlers. */
const allowShoplessLogin = ref(false)
/** loginShopMessage is a reactive state variable used by the template and event handlers. */
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
/**
* Purpose: formState supports AdminLoginView.vue by holding or executing the form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formState = reactive({
account: '',
password: '',
shopId: undefined as string | undefined
})
let loginShopTimer: number | undefined
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
/** getShopIdValue is a local helper used by this page script. */
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
/** getShopLabel is a local helper used by this page script. */
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
}))
)
/** hasAvailableShops is a reactive state variable used by the template and event handlers. */
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
/** shouldRequireShop is a reactive state variable used by the template and event handlers. */
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
/** shopPlaceholder is a reactive state variable used by the template and event handlers. */
const shopPlaceholder = computed(() => {
if (shopLoading.value) {
return '正在加载可登录店铺'
}
if (hasAvailableShops.value) {
return allowShoplessLogin.value ? '可选择本次登录店铺,留空进入平台总览' : '请选择登录店铺'
}
if (allowShoplessLogin.value) {
return '当前无需选择店铺'
}
return '请先输入账号'
})
/**
* Purpose: formRules supports AdminLoginView.vue by holding or executing the form rules page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRules = {
const formState = reactive({ account: '', password: '' })
const formRules: any = {
account: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ required: true, message: '请输入管理员账号', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{
validator: async () => {
if (!shouldRequireShop.value || formState.shopId) {
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
},
trigger: 'change'
}]
} as any
/** filterShopOption is a local helper used by this page script. */
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
/** isLoginShopPrefetchUnsupported is a local helper used by this page script. */
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
}
/** resetLoginShopTimer is a local helper used by this page script. */
const resetLoginShopTimer = () => {
if (loginShopTimer !== undefined) {
window.clearTimeout(loginShopTimer)
loginShopTimer = undefined
}
}
/** restoreLoginShop is a local helper used by this page script. */
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
return
}
try {
const parsed = JSON.parse(cached)
if (parsed?.type === 4) {
return
}
if (parsed?.shopId) {
formState.shopId = String(parsed.shopId)
}
} catch (error) {
console.error('恢复后台登录店铺失败:', error)
}
}
/** applyLoginShopSelection is a local helper used by this page script. */
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
shops.value = selection?.shops || []
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
loginShopMessage.value = selection?.message || ''
if (!shops.value.length) {
formState.shopId = undefined
return
}
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
if (matchedShop) {
return
}
if (!allowShoplessLogin.value && shops.value.length === 1) {
formState.shopId = getShopIdValue(shops.value[0]!)
return
}
formState.shopId = undefined
}
/** loadLoginShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadLoginShops = async (account = formState.account) => {
const trimmedAccount = account.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
shopLoading.value = true
try {
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
}
} catch (error) {
if (formState.account.trim() === trimmedAccount) {
if (isLoginShopPrefetchUnsupported(error)) {
applyLoginShopSelection({
allowShoplessLogin: true,
message: '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。',
shops: []
})
} else {
applyLoginShopSelection(null)
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
}
}
if (!isLoginShopPrefetchUnsupported(error)) {
console.error('获取登录店铺列表失败:', error)
}
} finally {
shopLoading.value = false
}
}
/** handleLogin is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleLogin = async () => {
formState.account = sanitizeAccountInput(formState.account)
loading.value = true
try {
await formRef.value?.validate()
loading.value = true
const res = await runWithGlobalLoading(() => adminAuthApi.login({
const response = await runWithGlobalLoading(() => adminAuthApi.login({
account: formState.account,
password: formState.password,
shopId: formState.shopId
}))
const { accessToken, refreshToken, userInfo } = res as any
localStorage.setItem('adminAccessToken', accessToken)
localStorage.setItem('adminRefreshToken', refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(userInfo))
sessionStorage.setItem('adminAccessToken', accessToken)
sessionStorage.setItem('adminRefreshToken', refreshToken)
message.success('登录成功')
await runWithGlobalLoading(() => loadUserPermissions())
const landingPath = resolveAdminLandingPath()
router.push(landingPath).catch(err => {
console.error('跳转到后台默认页面失败:', err)
window.location.href = landingPath
})
password: formState.password
})) as any
localStorage.setItem('adminAccessToken', response.accessToken)
localStorage.setItem('adminRefreshToken', response.refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(response.userInfo))
sessionStorage.setItem('adminAccessToken', response.accessToken)
sessionStorage.setItem('adminRefreshToken', response.refreshToken)
message.success('管理员登录成功')
await router.push(resolveAdminLandingPath())
} catch (error: any) {
console.error('登录失败:', error)
message.error(error.message || '登录失败,请检查用户名和密码')
message.error(error?.message || '登录失败,请检查管理员账号和密码')
} finally {
loading.value = false
}
}
onMounted(() => {
restoreLoginShop()
})
watch(
() => formState.account,
value => {
resetLoginShopTimer()
const trimmedAccount = value.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
loginShopTimer = window.setTimeout(() => {
loginShopTimer = undefined
void loadLoginShops(trimmedAccount)
}, 400)
}
)
onBeforeUnmount(() => {
resetLoginShopTimer()
})
/** goToFrontend is a local helper used by this page script. */
const goToFrontend = () => {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
sessionStorage.removeItem('adminRefreshToken')
setTimeout(() => {
window.location.href = '/'
}, 100)
}
</script>
<style scoped>
.admin-login {
min-height: 100dvh;
background:
linear-gradient(color-mix(in srgb, var(--theme-page-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 90%, transparent)),
var(--theme-background-image),
linear-gradient(
160deg,
var(--theme-primary) 0%,
var(--theme-accent) 58%,
color-mix(in srgb, var(--theme-accent) 78%, var(--text-primary)) 100%
);
background-size: cover, cover, auto;
background-position: center top;
display: flex;
align-items: center;
justify-content: center;
padding: max(24px, env(safe-area-inset-top)) 24px max(24px, env(safe-area-inset-bottom));
}
.login-container {
width: 100%;
max-width: 440px;
}
.login-header {
text-align: center;
margin-bottom: 28px;
color: var(--text-primary);
}
.login-header h1 {
font-size: clamp(23px, 3.2vw, 28px);
font-weight: 700;
margin: 0 0 8px 0;
}
.login-header p {
font-size: 14px;
line-height: 1.7;
opacity: 0.82;
margin: 0;
}
.login-card {
border-radius: 24px;
border: 1px solid var(--theme-border);
box-shadow: var(--theme-button-shadow);
overflow: hidden;
}
.login-footer {
text-align: center;
margin-top: 18px;
}
.login-footer a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 36px;
padding: 0 14px;
border-radius: 999px;
color: var(--theme-primary);
background: var(--theme-primary-soft);
text-decoration: none;
font-size: 14px;
font-weight: 700;
box-shadow: 0 8px 20px color-mix(in srgb, var(--theme-primary) 18%, transparent);
}
.login-footer a:hover {
color: var(--theme-accent);
background: var(--theme-card-bg);
}
.login-card :deep(.ant-card-body) {
background: var(--theme-card-bg);
}
.login-card :deep(.ant-btn-primary) {
border-color: transparent;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.login-card :deep(.ant-btn-primary:hover),
.login-card :deep(.ant-btn-primary:focus) {
border-color: transparent;
background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%);
}
.login-card :deep(.ant-input:hover),
.login-card :deep(.ant-input-affix-wrapper:hover),
.login-card :deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
border-color: var(--theme-primary);
}
.login-card :deep(.ant-input:focus),
.login-card :deep(.ant-input-affix-wrapper-focused),
.login-card :deep(.ant-select-focused .ant-select-selector) {
border-color: var(--theme-primary);
box-shadow: var(--theme-focus-shadow);
}
@media (max-width: 960px) {
.admin-login {
align-items: flex-start;
justify-content: stretch;
padding: calc(22px + env(safe-area-inset-top)) 14px calc(18px + env(safe-area-inset-bottom));
}
.login-container {
max-width: none;
}
.login-header {
text-align: left;
margin-bottom: 18px;
padding: 0 4px;
}
.login-header h1 {
max-width: 8em;
}
.login-card {
border-radius: 26px;
}
.login-card :deep(.ant-card-body) {
padding: 20px 18px 18px;
}
.login-card :deep(.ant-form-item) {
margin-bottom: 18px;
}
.login-card :deep(.ant-btn-lg),
.login-card :deep(.ant-input-affix-wrapper-lg),
.login-card :deep(.ant-input-lg),
.login-card :deep(.ant-select-single.ant-select-lg .ant-select-selector) {
min-height: 48px;
}
}
.salon-admin-login { display: grid; place-items: center; min-height: 100dvh; padding: 32px 20px; background: var(--theme-gradient); color: var(--theme-neutral); }
.login-panel { position: relative; width: min(100%, 420px); padding: 42px 42px 34px; border: 1px solid rgba(59, 147, 132, .2); border-radius: 24px; background: var(--theme-card-bg); box-shadow: 0 28px 80px rgba(25, 83, 72, .15); backdrop-filter: blur(16px); }
.brand-mark { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 14px; background: #2d9d87; color: #fff; font-size: 23px; font-weight: 800; box-shadow: 0 10px 24px rgba(45, 157, 135, .28); }
.eyebrow { margin: 22px 0 8px; color: #2d9d87; font-size: 11px; font-weight: 800; letter-spacing: .16em; }
h1 { margin: 0; font-size: 29px; letter-spacing: -.03em; }
.intro { margin: 10px 0 30px; color: #6a8580; font-size: 13px; line-height: 1.7; }
:deep(.ant-form-item-label > label) { color: #476a64; font-size: 12px; font-weight: 700; }
:deep(.ant-input), :deep(.ant-input-affix-wrapper) { border-color: #dcebe6; border-radius: 10px; background: #fbfefd; }
:deep(.ant-btn-primary) { height: 46px; border: 0; border-radius: 11px; background: #2d9d87; box-shadow: 0 10px 22px rgba(45, 157, 135, .2); }
@media (max-width: 520px) { .login-panel { padding: 32px 24px 26px; border-radius: 20px; } h1 { font-size: 25px; } }
</style>
File diff suppressed because it is too large Load Diff
@@ -1,488 +0,0 @@
<template>
<div class="home">
<template v-if="!isMobile">
<a-page-header title="欢迎使用后台管理系统" :sub-title="welcomeMessage" />
<a-alert
v-if="isBootstrapAdmin"
class="bootstrap-alert"
type="info"
show-icon
message="当前处于平台总览模式"
description="当前后台仅面向平台管理员,负责维护店铺、用户账号、角色归属和平台运行状态。"
/>
<a-alert
v-if="isShopAuthorizationExpired"
class="bootstrap-alert"
type="error"
show-icon
message="授权已到期,请联系管理员"
description="当前店铺已超过授权有效期,后台业务功能已暂时禁用。"
/>
<a-card class="time-card">
<a-statistic title="当前时间" :value="currentTime" />
</a-card>
<a-card class="info-card">
<a-descriptions bordered>
<a-descriptions-item label="用户信息">
<div class="user-info">
<a-avatar :size="64" :src="userInfo?.avatar || DEFAULT_AVATAR" />
<div class="user-details">
<h3>{{ userInfo?.nickname || '管理员' }}</h3>
<p>{{ getUserTypeText(userInfo?.type) }}</p>
<p v-if="userInfo?.shopName">所属店铺:{{ userInfo?.shopName }}</p>
</div>
</div>
</a-descriptions-item>
</a-descriptions>
</a-card>
<a-card class="permissions-card">
<template #title>
<div class="card-title">
<SafetyCertificateOutlined class="title-icon" />
<span>我的权限</span>
</div>
</template>
<div class="permissions-content" v-if="userPermissions.length > 0">
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="permission-group">
<div class="group-title">{{ groupName }}</div>
<div class="permission-tags">
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
{{ permission.permissionName }}
</a-tag>
</div>
</div>
</div>
<div class="no-permissions" v-else>暂无权限信息</div>
</a-card>
<a-card class="quick-actions">
<template #title>
快捷操作
</template>
<a-row :gutter="[16, 16]">
<a-col v-for="item in quickActions" :key="item.key" :span="8">
<a-card hoverable @click="navigateTo(item.path, item.permissionCode)">
<template #cover>
<div class="action-icon">
<component :is="item.icon" />
</div>
</template>
<template #title>
{{ item.title }}
</template>
</a-card>
</a-col>
</a-row>
</a-card>
</template>
<template v-else>
<section class="admin-page-intro">
<span class="admin-page-intro__eyebrow">{{ userInfo?.nickname || userInfo?.account || '后台账号' }}</span>
<h1 class="admin-page-intro__title">{{ userInfo?.shopName || (isBootstrapAdmin ? '平台总览模式' : '游客模式') }}</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">{{ currentTime }}</span>
<span class="admin-page-chip">{{ getUserTypeText(userInfo?.type) }}</span>
<span v-if="isBootstrapAdmin" class="admin-page-chip">平台总览</span>
</div>
</section>
<section v-if="isBootstrapAdmin" class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">平台总览模式</div>
<a-button type="primary" size="large" block @click="navigateTo('/admin/shops', 'shop:view')">进入店铺管理</a-button>
</section>
<div class="admin-mobile-grid admin-mobile-grid--two">
<section class="admin-mobile-stat">
<div class="admin-mobile-stat__label">权限数量</div>
<div class="admin-mobile-stat__value">{{ userPermissions.length }}</div>
</section>
<section class="admin-mobile-stat">
<div class="admin-mobile-stat__label">快捷入口</div>
<div class="admin-mobile-stat__value">{{ quickActions.length }}</div>
</section>
</div>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">快捷入口</div>
<div class="mobile-actions">
<button
v-for="item in quickActions"
:key="item.key"
class="mobile-action"
type="button"
@click="navigateTo(item.path, item.permissionCode)"
>
<div class="mobile-action__icon">
<component :is="item.icon" />
</div>
<div class="mobile-action__body">
<div class="mobile-action__title">{{ item.title }}</div>
</div>
</button>
</div>
</section>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">权限分组</div>
<div v-if="userPermissions.length > 0" class="mobile-permission-groups">
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="mobile-permission-group">
<div class="mobile-permission-group__title">{{ groupName }}</div>
<div class="permission-tags">
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
{{ permission.permissionName }}
</a-tag>
</div>
</div>
</div>
<a-empty v-else description="暂无权限信息" />
</section>
</template>
</div>
</template>
<script setup lang="ts">
/**
* HomeView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
HomeOutlined,
SafetyCertificateOutlined,
UserOutlined
} from '@ant-design/icons-vue'
/**
* Purpose: UserVO supports HomeView.vue by holding or executing the user vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { userApi, type UserVO } from '@/api/admin'
/**
* Purpose: PermissionVO supports HomeView.vue by holding or executing the permission vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { permissionApi, type PermissionVO } from '@/api/permission'
import { DEFAULT_AVATAR } from '@/constants'
import { message } from 'ant-design-vue'
import { useAdminViewport } from '@/composables/useAdminViewport'
import { isBootstrapAdminUser } from './admin-helpers'
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
/**
* Purpose: router supports HomeView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
const { isMobile } = useAdminViewport()
/** currentTime is a reactive state variable used by the template and event handlers. */
const currentTime = ref('')
/**
* Purpose: userInfo supports HomeView.vue by holding or executing the user info page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userInfo = ref<UserVO | null>(null)
/**
* Purpose: userPermissions supports HomeView.vue by holding or executing the user permissions page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userPermissions = ref<PermissionVO[]>([])
let timer: number | null = null
/** welcomeMessage is a reactive state variable used by the template and event handlers. */
const welcomeMessage = computed(() => {
const hour = new Date().getHours()
if (hour < 12) {
return '早上好!'
} else if (hour < 18) {
return '下午好!'
} else {
return '晚上好!'
}
})
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** isShopAuthorizationExpired is a reactive state variable used by the template and event handlers. */
const isShopAuthorizationExpired = computed(() => Boolean(userInfo.value?.shopAuthorizationExpired) && userInfo.value?.type !== 4)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
userPermissions.value.forEach(permission => {
const groupName = permission.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(permission)
})
return groups
})
/** quickActions is a reactive state variable used by the template and event handlers. */
const quickActions = computed(() => {
if (isShopAuthorizationExpired.value) {
return []
}
const actions = [
{
key: 'users',
title: '店长账号',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view'
},
{
key: 'shops',
title: '店铺管理',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
}
]
const grantedPermissions = new Set(userPermissions.value.map(permission => permission.permissionCode))
if (isBootstrapAdmin.value) {
return actions.filter(item => isAllowedForShoplessPlatformAdmin(item.permissionCode))
}
return actions.filter(item => grantedPermissions.has(item.permissionCode))
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number | undefined) => {
switch (type) {
case 4:
return '平台管理员'
case 2:
return '店长'
case 3:
return '美甲师'
default:
return '后台账号'
}
}
/** updateCurrentTime is a local helper used by this page script. */
const updateCurrentTime = () => {
const now = new Date()
currentTime.value = now.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
if (adminUserInfoStr) {
userInfo.value = JSON.parse(adminUserInfoStr)
} else {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as UserVO
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
}
/** fetchUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserPermissions = async () => {
try {
const res = await permissionApi.getUserPermissions()
userPermissions.value = res as unknown as PermissionVO[]
} catch (error) {
console.error('获取用户权限失败:', error)
}
}
/** navigateTo is a local helper used by this page script. */
const navigateTo = (path: string, permissionCode?: string) => {
if (permissionCode) {
if (isBootstrapAdmin.value && isAllowedForShoplessPlatformAdmin(permissionCode)) {
router.push(path)
return
}
const hasPermission = userPermissions.value.some(p => p.permissionCode === permissionCode)
if (!hasPermission) {
message.warning('您没有该操作的权限')
return
}
}
router.push(path)
}
onMounted(() => {
updateCurrentTime()
timer = window.setInterval(updateCurrentTime, 1000)
void fetchUserInfo()
void fetchUserPermissions()
})
onBeforeUnmount(() => {
if (timer !== null) {
window.clearInterval(timer)
}
})
</script>
<style scoped>
.home {
padding: 0;
}
.time-card,
.bootstrap-alert,
.info-card,
.permissions-card {
margin-bottom: 24px;
}
.user-info {
display: flex;
align-items: center;
gap: 16px;
}
.user-details {
flex: 1;
}
.user-details h3 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.user-details p {
margin: 4px 0;
color: var(--text-secondary);
}
.card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 600;
color: var(--admin-mobile-ink);
}
.title-icon {
font-size: 20px;
color: var(--admin-mobile-accent);
}
.permissions-content,
.mobile-permission-groups {
display: flex;
flex-direction: column;
gap: 16px;
}
.permission-group,
.mobile-permission-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.group-title,
.mobile-permission-group__title {
font-size: 14px;
font-weight: 600;
color: var(--theme-primary);
margin-bottom: 4px;
}
.permission-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.permission-tag {
font-size: 13px;
padding: 4px 12px;
border-radius: 12px;
margin: 0;
}
.no-permissions {
text-align: center;
padding: 20px;
color: var(--text-secondary);
}
.quick-actions {
margin-top: 24px;
}
.action-icon {
display: flex;
align-items: center;
justify-content: center;
height: 80px;
font-size: 32px;
color: var(--theme-primary);
background: var(--admin-mobile-accent-soft);
}
.mobile-actions {
display: grid;
gap: 12px;
margin-top: 14px;
}
.mobile-action {
display: flex;
align-items: center;
gap: 14px;
padding: 14px 0;
border: 0;
border-bottom: 1px solid var(--admin-mobile-border);
background: transparent;
text-align: left;
}
.mobile-action:last-child {
border-bottom: 0;
}
.mobile-action__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border-radius: 14px;
background: var(--admin-mobile-accent-soft);
color: var(--theme-primary);
}
.mobile-action__body {
flex: 1;
min-width: 0;
}
.mobile-action__title {
font-size: 15px;
font-weight: 600;
color: var(--admin-mobile-ink);
}
.mobile-action__meta {
margin-top: 4px;
color: var(--text-secondary);
font-size: 12px;
}
</style>
@@ -1,396 +0,0 @@
<template>
<div class="admin-manage">
<section class="admin-page-intro admin-manage__intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">{{ currentShopName }}</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">{{ roleLabel }}</span>
<span class="admin-page-chip">可见模块 {{ visibleModules.length }}</span>
<span v-if="isBootstrapAdmin" class="admin-page-chip">平台总览</span>
</div>
</section>
<div class="module-grid">
<button
v-for="module in visibleModules"
:key="module.key"
class="module-card"
:class="{ 'is-disabled': !module.allowed }"
type="button"
@click="openModule(module)"
>
<div class="module-card__icon">
<component :is="module.icon" />
</div>
<div class="module-card__body">
<div class="module-card__head">
<div class="module-card__title">{{ module.title }}</div>
<span class="module-card__badge">
{{ module.readonly ? '仅查看' : (module.allowed ? '进入' : '受限') }}
</span>
</div>
<div class="module-card__subtitle">{{ module.description }}</div>
<div v-if="!module.allowed && module.disabledReason" class="module-card__hint">
{{ module.disabledReason }}
</div>
</div>
</button>
</div>
</div>
</template>
<script setup lang="ts">
/**
* ManageView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
DashboardOutlined,
FileProtectOutlined,
GiftOutlined,
HomeOutlined,
MessageOutlined,
SafetyCertificateOutlined,
ShopOutlined,
SettingOutlined,
TagOutlined,
TeamOutlined,
UserOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { usePermission } from '@/utils/permission'
import {
getAdminCurrentShopName,
getAdminRoleLabel,
isBootstrapAdminUser,
loadCachedAdminUserInfo
} from './admin-helpers'
/**
* Purpose: router supports ManageView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
const { hasPermission, loadUserPermissions } = usePermission()
/** userInfo is a reactive state variable used by the template and event handlers. */
const userInfo = computed(() => loadCachedAdminUserInfo())
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** visibleModules is a reactive state variable used by the template and event handlers. */
const visibleModules = computed(() => {
const definitions = [
{
key: 'dashboard',
title: '仪表盘',
description: '查看经营概览、近期动态和重点提醒。',
path: '/admin',
icon: DashboardOutlined,
permissionCode: 'dashboard:view'
},
{
key: 'users',
title: '用户管理',
description: '处理账号、资产、VIP 和店铺关系。',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view',
requireShopContext: true,
allowPlatformOverviewManage: true
},
{
key: 'products',
title: '作品管理',
description: '维护作品、标签、可预约员工和优惠券。',
path: '/admin/products',
icon: ShopOutlined,
permissionCode: 'product:view',
requireShopContext: true
},
{
key: 'coupons',
title: '优惠券',
description: '管理券模板、场景和批量发放入口。',
path: '/admin/coupons',
icon: GiftOutlined,
permissionCode: 'coupon:view',
requireShopContext: true
},
{
key: 'tags',
title: '标签管理',
description: '维护作品标签及颜色风格。',
path: '/admin/tags',
icon: TagOutlined,
permissionCode: 'tag:view',
requireShopContext: true
},
{
key: 'artists',
title: '员工',
description: '查看员工状态、技能与排班关系。',
path: '/admin/nail-artists',
icon: TeamOutlined,
permissionCode: 'nail_artist:view',
requireShopContext: true
},
{
key: 'shops',
title: '店铺管理',
description: '创建门店、调整营业信息与图片素材。',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
},
{
key: 'permissions',
title: '权限管理',
description: '查看权限列表并给后台账号分配权限。',
path: '/admin/permissions',
icon: SafetyCertificateOutlined,
permissionCode: 'permission:view'
},
{
key: 'messages',
title: '消息发布',
description: '发布站内消息,可面向全平台或指定范围。',
path: '/admin/messages',
icon: MessageOutlined,
permissionCode: 'message:view'
},
{
key: 'announcements',
title: '公告管理',
description: '维护首页滚动公告,支持平台和门店范围。',
path: '/admin/announcements',
icon: MessageOutlined,
permissionCode: 'announcement:view'
},
{
key: 'parameters',
title: '参数管理',
description: '维护短信验证码场景的 MessageHub 模板、队列和通道。',
path: '/admin/messagehub-push-configs',
icon: SettingOutlined,
permissionCode: 'messagehub:config:manage'
},
{
key: 'agreements',
title: '协议管理',
description: '维护用户协议和隐私政策版本。',
path: '/admin/legal-agreements',
icon: FileProtectOutlined,
permissionCode: 'legal_agreement:manage'
}
]
return definitions
.filter(module => !module.permissionCode || hasPermission(module.permissionCode))
.map(module => {
if (module.requireShopContext && isBootstrapAdmin.value && !module.allowPlatformOverviewManage) {
return {
...module,
allowed: true,
readonly: true,
disabledReason: '平台总览模式下该模块仅可查看,编辑操作已关闭。'
}
}
return {
...module,
allowed: true,
readonly: false,
disabledReason: ''
}
})
})
/** openModule is a local helper used by this page script. */
const openModule = (module: any) => {
if (!module.allowed) {
message.warning(module.disabledReason || '当前无法进入该模块')
return
}
router.push(module.path)
}
onMounted(() => {
void loadUserPermissions()
})
</script>
<style scoped>
.admin-manage {
display: grid;
gap: 18px;
}
.module-grid {
display: grid;
gap: 14px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.module-card {
display: flex;
align-items: flex-start;
gap: 14px;
padding: 18px;
border: 1px solid var(--admin-mobile-border);
border-radius: 24px;
background: var(--admin-mobile-card);
text-align: left;
box-shadow: 0 12px 30px rgba(23, 33, 31, 0.08);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.module-card:hover {
transform: translateY(-2px);
box-shadow: 0 18px 36px rgba(23, 33, 31, 0.12);
}
.module-card.is-disabled {
opacity: 0.78;
}
.module-card__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 52px;
height: 52px;
border-radius: 18px;
background: var(--admin-mobile-accent-soft);
color: var(--theme-primary);
flex-shrink: 0;
font-size: 20px;
}
.module-card__body {
flex: 1;
min-width: 0;
}
.module-card__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.module-card__title {
font-size: 17px;
font-weight: 700;
color: var(--admin-mobile-ink);
}
.module-card__badge {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 12px;
font-weight: 600;
}
.module-card__subtitle {
margin-top: 8px;
line-height: 1.6;
color: var(--text-secondary);
}
.module-card__hint {
margin-top: 10px;
padding: 10px 12px;
border-radius: 14px;
background: var(--theme-primary-soft);
color: var(--text-secondary);
line-height: 1.55;
}
@media (max-width: 960px) {
.admin-manage {
gap: 12px;
}
.admin-manage__intro {
display: none;
}
.module-grid {
grid-template-columns: 1fr;
gap: 10px;
}
.module-card {
gap: 12px;
padding: 14px 16px;
border-radius: 18px;
box-shadow: 0 8px 20px rgba(23, 33, 31, 0.07);
}
.module-card:hover {
transform: none;
box-shadow: 0 8px 20px rgba(23, 33, 31, 0.07);
}
.module-card__icon {
width: 44px;
height: 44px;
border-radius: 14px;
font-size: 18px;
}
.module-card__head {
align-items: flex-start;
}
.module-card__title {
font-size: 16px;
line-height: 1.25;
}
.module-card__badge {
min-height: 24px;
padding: 0 8px;
font-size: 11px;
}
.module-card__subtitle {
margin-top: 5px;
font-size: 13px;
line-height: 1.45;
}
.module-card__hint {
margin-top: 8px;
padding: 8px 10px;
border-radius: 12px;
font-size: 13px;
}
}
@media (max-width: 420px) {
.module-card {
padding: 12px 14px;
}
.module-card__icon {
width: 40px;
height: 40px;
}
.module-card__head {
gap: 8px;
}
}
</style>
+115 -69
View File
@@ -1,47 +1,52 @@
<template>
<div class="admin-profile">
<section class="profile-head">
<header class="profile-head">
<div>
<span class="profile-eyebrow">后台账号</span>
<h1>{{ userInfo?.nickname || '未设置昵称' }}</h1>
<p>{{ userInfo?.account || '当前登录账号' }} · {{ roleLabel }}</p>
<span class="profile-eyebrow">管理员账号</span>
<h1>{{ userInfo?.nickname || '平台管理员' }}</h1>
<p>{{ userInfo?.account || '当前登录账号' }}</p>
</div>
<a-avatar :size="58" :src="userInfo?.avatar || DEFAULT_AVATAR" />
</header>
<section class="profile-section">
<div class="profile-section__head">
<div><h2>账号资料</h2><p>该后台只服务平台管理员,数据范围为 Salon 全平台。</p></div>
</div>
<div class="profile-rows">
<div class="profile-row"><span>登录账号</span><strong>{{ userInfo?.account || '--' }}</strong></div>
<div class="profile-row"><span>显示昵称</span><strong>{{ userInfo?.nickname || '未设置昵称' }}</strong></div>
<div class="profile-row"><span>账号类型</span><strong>平台管理员</strong></div>
<div class="profile-row"><span>平台范围</span><strong>全平台门店与经营数据</strong></div>
</div>
<span class="profile-chip">{{ isPlatformOverview ? '平台总览' : currentShopName }}</span>
</section>
<section class="profile-section">
<div class="profile-section__head">
<div>
<h2>账号与门店</h2>
<p>账号资料、权限范围和门店切换已集中到系统设置。</p>
<div><h2>安全设置</h2><p>修改管理员密码后,所有后台会话都会失效,需要重新登录。</p></div>
</div>
<a-form class="password-form" :model="passwordForm" :rules="passwordRules" layout="vertical" @finish="handleChangePassword">
<div class="password-form__grid">
<a-form-item label="当前密码" name="currentPassword">
<a-input-password v-model:value="passwordForm.currentPassword" autocomplete="current-password" placeholder="请输入当前密码" />
</a-form-item>
<a-form-item label="新密码" name="newPassword">
<a-input-password v-model:value="passwordForm.newPassword" autocomplete="new-password" placeholder="8-32 位,至少包含 3 类字符" />
</a-form-item>
<a-form-item label="确认新密码" name="confirmPassword">
<a-input-password v-model:value="passwordForm.confirmPassword" autocomplete="new-password" placeholder="请再次输入新密码" />
</a-form-item>
</div>
</div>
<button class="profile-link" type="button" @click="router.push({ path: '/admin/settings', query: { section: 'account' } })">
<span class="profile-link__icon">◎</span>
<span class="profile-link__body"><strong>打开当前账号设置</strong><small>查看后台账号、权限范围和可用门店</small></span>
<span class="profile-link__arrow">›</span>
</button>
</section>
<section class="profile-section">
<div class="profile-section__head">
<div>
<h2>常用入口</h2>
<p>继续处理日常经营工作。</p>
<div class="password-form__actions">
<span>保存后当前设备和其他设备的后台登录都会退出。</span>
<a-button type="primary" html-type="submit" :loading="changingPassword">保存新密码</a-button>
</div>
</div>
<div class="profile-actions">
<a-button type="default" size="large" @click="router.push('/admin/orders')">查看订单</a-button>
<a-button type="default" size="large" @click="router.push('/admin/manage')">进入经营模块</a-button>
</div>
</a-form>
</section>
<section class="profile-section profile-section--logout">
<div class="profile-section__head">
<div>
<h2>退出登录</h2>
<p>退出后需要重新登录后台。</p>
</div>
<div><h2>退出登录</h2><p>退出后需要重新登录后台。</p></div>
</div>
<a-button danger size="large" block @click="handleLogout">退出当前账号</a-button>
</section>
@@ -49,57 +54,98 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { DEFAULT_AVATAR } from '@/constants'
import { adminAuthApi } from '@/api/admin'
import { clearAdminBootstrapSession } from '@/utils/admin-auth-bootstrap'
import { completeAdminLogout } from '@/utils/admin-logout'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { getAdminCurrentShopName, getAdminRoleLabel, isBootstrapAdminUser, loadCachedAdminUserInfo } from './admin-helpers'
import { loadCachedAdminUserInfo } from '@/utils/admin-session'
const router = useRouter()
const userInfo = ref(loadCachedAdminUserInfo())
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
const isPlatformOverview = computed(() => isBootstrapAdminUser(userInfo.value))
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
await completeAdminLogout(router)
message.success('已退出登录')
})
const changingPassword = ref(false)
const passwordForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })
const passwordRules: Record<string, Rule[]> = {
currentPassword: [{ required: true, message: '请输入当前密码' }],
newPassword: [
{ required: true, message: '请输入新密码' },
{ min: 8, max: 32, message: '密码长度需为 8-32 位' },
{
validator: async (_rule, value) => {
const password = String(value || '')
const categoryCount = [/[0-9]/, /[a-z]/, /[A-Z]/, /[^A-Za-z0-9]/].filter(pattern => pattern.test(password)).length
if (password && categoryCount < 3) throw new Error('密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类')
}
}
})
],
confirmPassword: [
{ required: true, message: '请再次输入新密码' },
{
validator: async (_rule, value) => {
if (value && value !== passwordForm.newPassword) throw new Error('两次输入的新密码不一致')
}
}
]
}
const handleChangePassword = async () => {
changingPassword.value = true
try {
await adminAuthApi.changePassword({ currentPassword: passwordForm.currentPassword, newPassword: passwordForm.newPassword })
clearAdminBootstrapSession()
message.success('密码已更新,请使用新密码重新登录')
await router.replace('/admin/login')
} catch (error: any) {
message.error(error?.message || '密码修改失败,请重试')
} finally {
changingPassword.value = false
}
}
const handleLogout = () => Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
await completeAdminLogout(router)
message.success('已退出登录')
})
}
})
</script>
<style scoped>
.admin-profile { display: grid; gap: 18px; color: var(--admin-mobile-ink); }
.profile-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; padding-bottom: 16px; border-bottom: 1px solid var(--admin-mobile-border); }
.profile-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .12em; }
.profile-head h1 { margin: 7px 0 4px; font-size: 27px; }
.profile-head { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 8px 0 18px; border-bottom: 1px solid var(--admin-mobile-border); }
.profile-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .14em; }
.profile-head h1 { margin: 7px 0 4px; font-size: 28px; }
.profile-head p, .profile-section__head p { margin: 0; color: var(--admin-mobile-muted); font-size: 13px; }
.profile-chip { padding: 7px 10px; border-radius: 999px; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 12px; font-weight: 700; white-space: nowrap; }
.profile-section { padding-top: 16px; border-top: 1px solid var(--admin-mobile-border); }
.profile-section__head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.profile-section__head h2 { margin: 0 0 4px; font-size: 15px; }
.profile-link { display: flex; width: 100%; align-items: center; gap: 12px; padding: 14px 2px; border: 0; border-bottom: 1px solid var(--admin-mobile-border); background: transparent; color: inherit; text-align: left; cursor: pointer; }
.profile-link:hover { color: var(--theme-primary-action); }
.profile-link__icon { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 12px; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 20px; }
.profile-link__body { display: grid; flex: 1; gap: 3px; min-width: 0; }
.profile-link__body strong { font-size: 14px; }
.profile-link__body small { color: var(--admin-mobile-muted); font-size: 12px; }
.profile-link__arrow { color: var(--admin-mobile-muted); font-size: 24px; line-height: 1; }
.profile-actions { display: flex; flex-wrap: wrap; gap: 10px; }
.profile-actions .ant-btn { flex: 1 1 180px; }
.profile-section--logout .ant-btn { max-width: 240px; }
@media (max-width: 560px) {
.profile-head { align-items: flex-start; flex-direction: column; }
.profile-section--logout .ant-btn { max-width: none; }
}
.profile-section { padding-top: 4px; border-top: 1px solid var(--admin-mobile-border); }
.profile-section__head { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 13px 0; }
.profile-section__head h2 { margin: 0 0 4px; font-size: 17px; }
.profile-rows { border-top: 1px solid var(--admin-mobile-border); }
.profile-row { display: grid; grid-template-columns: 160px 1fr; align-items: center; gap: 18px; min-height: 58px; padding: 10px 14px; border-bottom: 1px solid color-mix(in srgb, var(--admin-mobile-border) 70%, transparent); background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent); }
.profile-row span { color: var(--admin-mobile-muted); font-size: 12px; }
.profile-row strong { color: var(--admin-mobile-ink); font-size: 13px; }
.profile-link { display: flex; width: 100%; align-items: center; gap: 12px; padding: 14px; border: 1px solid var(--admin-mobile-border); background: var(--theme-card-bg); color: inherit; text-align: left; cursor: pointer; }
.profile-link:hover { border-color: var(--theme-primary); background: var(--admin-mobile-accent-soft); }
.profile-link__icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 50%; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 800; }
.profile-link__body { display: grid; flex: 1; gap: 3px; }
.profile-link__body small { color: var(--admin-mobile-muted); font-size: 11px; }
.profile-link__arrow { color: var(--theme-primary-action); font-size: 24px; }
.profile-section--logout { padding-bottom: 12px; }
.password-form { padding: 15px 14px 14px; border: 1px solid var(--admin-mobile-border); background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent); }
.password-form__grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
.password-form :deep(.ant-form-item) { margin-bottom: 12px; }
.password-form :deep(.ant-form-item-label) { padding-bottom: 4px; }
.password-form__actions { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding-top: 2px; color: var(--admin-mobile-muted); font-size: 11px; }
.password-form__actions .ant-btn { flex: 0 0 auto; }
@media (max-width: 760px) { .password-form__grid { grid-template-columns: 1fr; gap: 0; } .password-form__actions { align-items: flex-start; flex-direction: column; } .password-form__actions .ant-btn { width: 100%; } }
@media (max-width: 640px) { .profile-row { grid-template-columns: 1fr; gap: 4px; } }
</style>
@@ -0,0 +1,214 @@
<template>
<main class="salon-dashboard">
<header class="dashboard-head">
<div>
<span class="dashboard-eyebrow">SALON PLATFORM</span>
<h1>Salon 管理驾驶舱</h1>
<p>用门店、员工、客户和服务数据掌握平台经营状态。</p>
<div class="dashboard-freshness"><span>系统日期 {{ currentDateLabel }}</span><span>最近刷新 {{ lastRefreshedAt || '尚未刷新' }}</span></div>
</div>
<div class="dashboard-tools">
<label class="date-control"><span>统计日期</span><input v-model="date" type="date" @change="loadOverview" /></label>
<div class="range-control" role="group" aria-label="趋势范围">
<button v-for="item in ranges" :key="item.value" type="button" :class="{ active: days === item.value }" @click="changeRange(item.value)">{{ item.label }}</button>
</div>
<button class="refresh-button" type="button" :disabled="loading" @click="loadOverview"><ReloadOutlined :spin="loading" /> 刷新</button>
</div>
</header>
<a-alert v-if="overview.degraded" class="dashboard-alert" type="warning" show-icon :message="overview.degradedMessage || '经营数据暂时不可用'" description="当前页面已保留空数据展示,稍后可重新刷新。" />
<section class="kpi-strip" aria-label="今日经营指标">
<div class="kpi-item kpi-item--primary"><span class="kpi-label">{{ selectedToday ? '今日预约' : '当日预约' }}</span><strong>{{ overview.today.appointmentCount }}</strong><small>含已排期服务</small></div>
<div class="kpi-item"><span class="kpi-label">服务中</span><strong>{{ overview.today.serviceInProgressCount }}</strong><small>当前进行中的服务</small></div>
<div class="kpi-item"><span class="kpi-label">{{ selectedToday ? '今日完成' : '当日完成' }}</span><strong>{{ overview.today.completedServiceCount }}</strong><small>已完成服务</small></div>
<div class="kpi-item"><span class="kpi-label">{{ selectedToday ? '今日营业额' : '当日营业额' }}</span><strong>¥{{ money(overview.today.orderAmount) }}</strong><small>订单与历史补单</small></div>
<div class="kpi-item kpi-item--attention"><span class="kpi-label">待处理事项</span><strong>{{ attentionTotal }}</strong><small>需要管理员关注</small></div>
</section>
<div class="dashboard-grid">
<section class="dashboard-panel trend-panel">
<div class="panel-head"><div><h2>经营趋势</h2><p>最近 {{ days }} 天预约、完成和营业额</p></div><span class="panel-date">截至 {{ overview.date }}</span></div>
<div class="trend-chart" :class="{ 'trend-chart--empty': !hasTrend }">
<div v-for="item in overview.trend" :key="item.date" class="trend-column">
<div class="trend-bars">
<span class="trend-bar trend-bar--appointment" :style="{ height: `${barHeight(item.appointmentCount, maxTrendCount)}%` }" :title="`预约 ${item.appointmentCount}`" />
<span class="trend-bar trend-bar--completed" :style="{ height: `${barHeight(item.completedCount, maxTrendCount)}%` }" :title="`完成 ${item.completedCount}`" />
</div>
<strong>{{ shortDate(item.date) }}</strong>
<small>¥{{ money(item.amount) }}</small>
</div>
<div v-if="!hasTrend" class="empty-state">暂无趋势数据</div>
</div>
<div class="chart-legend"><span><i class="legend-dot legend-dot--appointment" />预约</span><span><i class="legend-dot legend-dot--completed" />完成</span><span class="legend-note">柱高按数量,金额显示在日期下方</span></div>
</section>
<section class="dashboard-panel attention-panel">
<div class="panel-head"><div><h2>待处理事项</h2><p>需要管理员进一步处理的业务</p></div><span class="attention-total">{{ attentionTotal }}</span></div>
<div class="attention-list">
<button v-for="item in attentionItems" :key="item.key" type="button" class="attention-row" @click="go(item.path)">
<span class="attention-icon" :class="`attention-icon--${item.tone}`"><component :is="item.icon" /></span>
<span class="attention-copy"><strong>{{ item.label }}</strong><small>{{ item.hint }}</small></span>
<b>{{ item.count }}</b><span class="attention-arrow">›</span>
</button>
<div v-if="attentionTotal === 0" class="empty-state empty-state--inline">当前没有待处理事项</div>
</div>
</section>
</div>
<div class="dashboard-grid dashboard-grid--lower">
<section class="dashboard-panel ranking-panel">
<div class="panel-head"><div><h2>门店经营排行</h2><p>按统计范围内的营业额排序</p></div><span class="panel-date">Top 10</span></div>
<div v-if="overview.shopRanking.length" class="ranking-list">
<div v-for="(shop, index) in overview.shopRanking" :key="String(shop.shopId)" class="ranking-row">
<span class="ranking-index">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="ranking-copy"><strong>{{ shop.shopName || '未命名门店' }}</strong><small>{{ shop.appointmentCount }} 次预约 · {{ shop.completedCount }} 次完成</small></span>
<strong class="ranking-amount">¥{{ money(shop.amount) }}</strong>
</div>
</div>
<div v-else class="empty-state">暂无门店经营数据</div>
</section>
<section class="dashboard-panel assets-panel">
<div class="panel-head"><div><h2>平台资产规模</h2><p>当前启用的 Salon 业务资源</p></div></div>
<div class="asset-list">
<div class="asset-row"><span><i class="asset-mark asset-mark--shop" />门店</span><strong>{{ overview.platform.activeShopCount }}</strong><small>启用中</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--manager" />店长</span><strong>{{ overview.platform.activeManagerCount }}</strong><small>有效账号</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--staff" />员工</span><strong>{{ overview.platform.activeStaffCount }}</strong><small>有效账号</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--customer" />客户</span><strong>{{ overview.platform.customerCount }}</strong><small>业务资料</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--style" />款式</span><strong>{{ overview.platform.styleCount }}</strong><small>已公开</small></div>
</div>
</section>
</div>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ReloadOutlined, AuditOutlined, SafetyCertificateOutlined, ShoppingOutlined, TeamOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { adminDashboardApi, type SalonDashboardOverviewVO } from '@/api/admin'
const router = useRouter()
const localDate = () => {
const now = new Date()
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
}
const date = ref(localDate())
const days = ref<7 | 30>(7)
const loading = ref(false)
const lastRefreshedAt = ref('')
const overview = ref<SalonDashboardOverviewVO>(emptyOverview(date.value, days.value))
const ranges = [{ label: '7 天', value: 7 as const }, { label: '30 天', value: 30 as const }]
const currentDateLabel = computed(() => localDate())
function emptyOverview(targetDate: string, range: number): SalonDashboardOverviewVO {
return {
date: targetDate,
degraded: false,
platform: { activeShopCount: 0, activeManagerCount: 0, activeStaffCount: 0, customerCount: 0, styleCount: 0 },
today: { appointmentCount: 0, serviceInProgressCount: 0, completedServiceCount: 0, orderAmount: 0, pendingOrderCount: 0 },
attention: { registrationReviewCount: 0, contentReviewCount: 0, afterSaleCount: 0, artistChangeCount: 0, lowStockCount: 0 },
trend: Array.from({ length: range }, (_, index) => ({ date: new Date(Date.parse(targetDate) - (range - index - 1) * 86400000).toISOString().slice(0, 10), appointmentCount: 0, completedCount: 0, amount: 0 })),
shopRanking: []
}
}
const attentionTotal = computed(() => Object.values(overview.value.attention).reduce((sum, value) => sum + Number(value || 0), 0))
const selectedToday = computed(() => date.value === localDate())
const attentionItems = computed(() => [
{ key: 'registration', label: '注册审核', hint: '员工与店长申请', count: overview.value.attention.registrationReviewCount, path: '/admin/registrations', tone: 'mint', icon: AuditOutlined },
{ key: 'content', label: '内容复核', hint: '文字与图片审核', count: overview.value.attention.contentReviewCount, path: '/admin/privacy', tone: 'blue', icon: SafetyCertificateOutlined },
{ key: 'afterSale', label: '售后处理', hint: '等待管理员处理', count: overview.value.attention.afterSaleCount, path: '/admin/after-sales', tone: 'amber', icon: ShoppingOutlined },
{ key: 'artistChange', label: '改派申请', hint: '等待重新分配员工', count: overview.value.attention.artistChangeCount, path: '/admin/orders', tone: 'violet', icon: TeamOutlined },
{ key: 'stock', label: '库存异常', hint: '低于库存预警线', count: overview.value.attention.lowStockCount, path: '/admin/inventory', tone: 'red', icon: WarningOutlined }
].filter(item => item.count > 0))
const hasTrend = computed(() => overview.value.trend.some(item => item.appointmentCount || item.completedCount || item.amount))
const maxTrendCount = computed(() => Math.max(1, ...overview.value.trend.flatMap(item => [item.appointmentCount, item.completedCount])))
const money = (value: number | undefined) => Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const shortDate = (value: string) => value.slice(5).replace('-', '/')
const barHeight = (value: number, max: number) => value ? Math.max(9, Math.round(value / max * 100)) : 3
const go = (path: string) => router.push(path)
const loadOverview = async () => {
loading.value = true
try {
const result = await adminDashboardApi.getOverview({ date: date.value, days: days.value })
overview.value = result || emptyOverview(date.value, days.value)
} catch (error: any) {
overview.value = { ...emptyOverview(date.value, days.value), degraded: true, degradedMessage: error?.message || '经营数据加载失败' }
} finally {
lastRefreshedAt.value = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
loading.value = false
}
}
const changeRange = (range: 7 | 30) => {
days.value = range
void loadOverview()
}
onMounted(() => { void loadOverview() })
</script>
<style scoped>
.salon-dashboard { display: grid; gap: 22px; color: var(--admin-mobile-ink); }
.dashboard-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; padding-bottom: 5px; }
.dashboard-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .16em; }
.dashboard-head h1 { margin: 7px 0 5px; font-size: 32px; }
.dashboard-head p { margin: 0; color: var(--admin-mobile-muted); font-size: 13px; }
.dashboard-freshness { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 8px; color: var(--admin-mobile-muted); font-size: 11px; }
.dashboard-tools { display: flex; align-items: flex-end; gap: 9px; flex-wrap: wrap; justify-content: flex-end; }
.date-control { display: grid; gap: 5px; color: var(--admin-mobile-muted); font-size: 11px; }
.date-control input { height: 34px; padding: 0 9px; border: 1px solid var(--admin-mobile-border); border-radius: 8px; background: var(--theme-card-bg); color: var(--admin-mobile-ink); font: inherit; }
.range-control { display: flex; height: 34px; padding: 3px; border: 1px solid var(--admin-mobile-border); border-radius: 8px; background: var(--theme-card-bg); }
.range-control button, .refresh-button { border: 0; border-radius: 6px; background: transparent; color: var(--admin-mobile-muted); font: inherit; font-size: 12px; cursor: pointer; }
.range-control button { padding: 0 11px; }
.range-control button.active { background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; }
.refresh-button { display: inline-flex; height: 34px; align-items: center; gap: 5px; padding: 0 11px; border: 1px solid var(--admin-mobile-border); background: var(--theme-card-bg); }
.refresh-button:disabled { cursor: wait; opacity: .6; }
.dashboard-alert { margin: -4px 0 0; }
.kpi-strip { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); border-top: 1px solid var(--admin-mobile-border); border-bottom: 1px solid var(--admin-mobile-border); background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent); }
.kpi-item { display: grid; gap: 6px; min-height: 128px; padding: 20px 18px; border-right: 1px solid var(--admin-mobile-border); }
.kpi-item:last-child { border-right: 0; }
.kpi-label { color: var(--admin-mobile-muted); font-size: 12px; }
.kpi-item strong { color: var(--admin-mobile-ink); font-size: 29px; }
.kpi-item small { color: var(--admin-mobile-muted); font-size: 11px; }
.kpi-item--primary strong { color: var(--theme-primary-action); }
.kpi-item--attention strong { color: #be7951; }
.dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.65fr) minmax(300px, .95fr); gap: 18px; }
.dashboard-grid--lower { grid-template-columns: minmax(0, 1.2fr) minmax(320px, .8fr); }
.dashboard-panel { min-width: 0; border-top: 2px solid var(--theme-primary); background: color-mix(in srgb, var(--theme-card-bg) 78%, transparent); }
.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 17px 0 13px; border-bottom: 1px solid var(--admin-mobile-border); }
.panel-head h2 { margin: 0 0 4px; font-size: 16px; }
.panel-head p, .panel-date { margin: 0; color: var(--admin-mobile-muted); font-size: 11px; }
.panel-date { white-space: nowrap; }
.trend-chart { display: grid; grid-template-columns: repeat(auto-fit, minmax(34px, 1fr)); align-items: end; gap: 9px; min-height: 230px; padding: 22px 4px 9px; border-bottom: 1px solid var(--admin-mobile-border); }
.trend-column { display: grid; min-width: 0; gap: 6px; align-items: end; text-align: center; }
.trend-bars { display: flex; height: 150px; align-items: end; justify-content: center; gap: 3px; border-bottom: 1px solid var(--admin-mobile-border); }
.trend-bar { display: block; width: 9px; min-height: 3px; border-radius: 3px 3px 0 0; transition: height .25s ease; }
.trend-bar--appointment { background: #55bfa4; }
.trend-bar--completed { background: #275f58; }
.trend-column strong { color: var(--admin-mobile-ink); font-size: 10px; font-weight: 700; }
.trend-column small { overflow: hidden; color: var(--admin-mobile-muted); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
.chart-legend { display: flex; align-items: center; gap: 15px; padding-top: 12px; color: var(--admin-mobile-muted); font-size: 11px; }
.chart-legend span { display: inline-flex; align-items: center; gap: 5px; }
.legend-dot { width: 7px; height: 7px; border-radius: 50%; }
.legend-dot--appointment { background: #55bfa4; }.legend-dot--completed { background: #275f58; }.legend-note { margin-left: auto; }
.attention-total { display: grid; place-items: center; min-width: 27px; height: 27px; border-radius: 50%; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 12px; font-weight: 800; }
.attention-list { display: grid; }
.attention-row { display: flex; align-items: center; gap: 10px; min-height: 60px; padding: 9px 0; border: 0; border-bottom: 1px solid var(--admin-mobile-border); background: transparent; color: inherit; text-align: left; cursor: pointer; }
.attention-row:hover { background: var(--admin-mobile-accent-soft); }
.attention-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; font-size: 14px; }
.attention-icon--mint { background: #e2f5ee; color: #2a9a7f; }.attention-icon--blue { background: #e5f0fa; color: #397ba8; }.attention-icon--amber { background: #fff2d9; color: #b77a27; }.attention-icon--violet { background: #eee8fa; color: #7559a5; }.attention-icon--red { background: #fde8e4; color: #bd665d; }
.attention-copy { display: grid; flex: 1; gap: 2px; min-width: 0; }.attention-copy strong { font-size: 12px; }.attention-copy small { color: var(--admin-mobile-muted); font-size: 10px; }.attention-row b { color: var(--admin-mobile-ink); font-size: 14px; }.attention-arrow { color: var(--admin-mobile-muted); font-size: 20px; }
.ranking-list, .asset-list { display: grid; }
.ranking-row { display: flex; align-items: center; gap: 12px; min-height: 61px; border-bottom: 1px solid var(--admin-mobile-border); }
.ranking-index { width: 26px; color: var(--theme-primary-action); font-size: 11px; font-weight: 800; }.ranking-copy { display: grid; flex: 1; gap: 3px; min-width: 0; }.ranking-copy strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.ranking-copy small { color: var(--admin-mobile-muted); font-size: 10px; }.ranking-amount { font-size: 12px; white-space: nowrap; }
.asset-row { display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 12px; min-height: 50px; border-bottom: 1px solid var(--admin-mobile-border); }.asset-row span { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; }.asset-row strong { font-size: 16px; }.asset-row small { width: 46px; color: var(--admin-mobile-muted); font-size: 10px; text-align: right; }.asset-mark { width: 7px; height: 7px; border-radius: 50%; background: var(--theme-primary); }.asset-mark--manager { background: #6f9fd1; }.asset-mark--staff { background: #a887d1; }.asset-mark--customer { background: #d89b64; }.asset-mark--style { background: #78a8a1; }
.empty-state { display: grid; place-items: center; min-height: 160px; color: var(--admin-mobile-muted); font-size: 12px; }.empty-state--inline { min-height: 180px; }.trend-chart--empty { opacity: .8; }
@media (max-width: 1000px) { .dashboard-head { align-items: flex-start; flex-direction: column; }.dashboard-tools { justify-content: flex-start; }.dashboard-grid, .dashboard-grid--lower { grid-template-columns: 1fr; } }
@media (max-width: 680px) { .dashboard-head h1 { font-size: 27px; } }
@media (max-width: 680px) { .dashboard-head h1 { font-size: 27px; }.kpi-strip { grid-template-columns: repeat(2, 1fr); }.kpi-item { min-height: 100px; padding: 15px 13px; }.kpi-item:nth-child(2n) { border-right: 0; }.kpi-item:nth-child(-n+3) { border-bottom: 1px solid var(--admin-mobile-border); }.kpi-item strong { font-size: 24px; }.trend-chart { gap: 3px; }.trend-bar { width: 6px; }.chart-legend { flex-wrap: wrap; }.legend-note { width: 100%; margin-left: 0; }.dashboard-tools { width: 100%; }.date-control { flex: 1; }.date-control input { width: 100%; }.range-control button { padding: 0 8px; } }
</style>
@@ -110,8 +110,8 @@
<section v-else class="settings-section-panel">
<div class="pane-head">
<div>
<h2>当前账号</h2>
<p>查看后台账号、权限范围和当前门店,不与小程序账号设置混用。</p>
<h2>管理员账号</h2>
<p>查看后台登录账号与当前会话状态。</p>
</div>
<span class="account-status"><i />会话正常</span>
</div>
@@ -128,27 +128,10 @@
<div class="setting-value">{{ userInfo?.nickname || '未设置昵称' }}</div>
<span class="control-note">只读</span>
</div>
<div class="setting-row">
<div class="setting-copy"><strong>角色</strong><span>当前后台角色与平台管理范围。</span></div>
<div class="setting-value">{{ roleLabel }}</div>
<span v-if="isPlatformOverview" class="status-pill">平台总览</span>
<span v-else class="control-note">只读</span>
</div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>权限范围</strong><span>当前账号可访问的功能权限数量。</span></div>
<div class="setting-value">{{ permissionCount }} 项权限</div>
<span class="control-note">{{ shopScopeText }}</span>
</div>
</div>
<div class="setting-group">
<div class="setting-group__head"><strong>{{ isPlatformOverview ? '管理范围' : '当前门店' }}</strong><span>SHOP</span></div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>{{ isPlatformOverview ? '平台总览模式' : '门店上下文' }}</strong><span>{{ isPlatformOverview ? '平台管理员可查看全平台数据。' : '切换后会刷新权限和业务数据上下文。' }}</span></div>
<div v-if="isPlatformOverview" class="setting-value">平台总览模式</div>
<a-select v-else-if="shopOptions.length > 1" v-model:value="selectedShopId" class="account-shop-select" :options="shopSelectOptions" :loading="shopSwitchLoading" @change="handleShopChange" />
<div v-else class="setting-value">{{ currentShopName }}</div>
<span class="control-note">{{ shopOptions.length > 1 ? `${shopOptions.length} 家可用门店` : '当前会话' }}</span>
<div class="setting-copy"><strong>后台会话</strong><span>后台请求使用管理员身份校验,退出登录后当前会话立即失效。</span></div>
<div class="setting-value">{{ userInfo?.id ? '已登录' : '状态未知' }}</div>
<span class="status-pill" :class="{ 'is-muted': !userInfo?.id }">{{ userInfo?.id ? '正常' : '待验证' }}</span>
</div>
</div>
</section>
@@ -158,15 +141,12 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ApiOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { adminAuthApi, adminSystemParameterConfigApi, type SystemParameterConfigVO } from '@/api/admin'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { notifyShopThemeChanged } from '@/utils/shop-theme'
import { getAdminCurrentShopName, getAdminRoleLabel, getAdminShopOptions, isBootstrapAdminUser, loadCachedAdminUserInfo } from './admin-helpers'
import { adminSystemParameterConfigApi, type SystemParameterConfigVO } from '@/api/admin'
import { loadCachedAdminUserInfo } from '@/utils/admin-session'
type SettingsSection = 'runtime' | 'services' | 'account'
type MapKey = 'tencentWeb' | 'amapWeb' | 'amapMini'
@@ -178,7 +158,6 @@ const savingDefaultPassword = ref(false)
const savingReviewNotice = ref(false)
const savingMap = ref(false)
const savingSmsProvider = ref(false)
const shopSwitchLoading = ref(false)
const defaultPasswordEnabled = ref(true)
const reviewNoticeEnabled = ref(true)
const mapEnabled = ref(true)
@@ -221,27 +200,6 @@ const mapForms = reactive<Record<MapKey | 'provider', SystemParameterConfigVO>>(
})
const userInfo = ref(loadCachedAdminUserInfo())
const selectedShopId = ref(userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined)
const { userPermissions, loadUserPermissions } = usePermission()
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
const isPlatformOverview = computed(() => isBootstrapAdminUser(userInfo.value))
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
const shopOptions = computed(() => getAdminShopOptions(userInfo.value))
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
const permissionCount = computed(() => userPermissions.value.length)
const shopScopeText = computed(() => shopOptions.value.length ? shopOptions.value.map(item => item.name).join(' / ') : (isPlatformOverview.value ? '平台总览模式' : '游客模式'))
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 refreshLocalUserInfo = () => {
userInfo.value = loadCachedAdminUserInfo()
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
}
const load = async () => {
loading.value = true
@@ -271,8 +229,7 @@ const load = async () => {
if (mapByKey.AMAP_MINI_KEY) Object.assign(mapForms.amapMini, mapByKey.AMAP_MINI_KEY)
mapForms.provider.configValue = mapForms.provider.configValue === 'AMAP' ? 'AMAP' : 'TENCENT'
mapEnabled.value = mapForms.provider.enabled === 1
refreshLocalUserInfo()
await loadUserPermissions()
userInfo.value = loadCachedAdminUserInfo()
} catch (error) {
message.error(error instanceof Error ? error.message : '系统设置加载失败')
} finally {
@@ -348,27 +305,6 @@ const saveSmsProvider = async () => {
}
}
const handleShopChange = async (shopId: unknown) => {
if ((typeof shopId !== 'string' && typeof shopId !== 'number') || !String(shopId) || String(shopId) === String(userInfo.value?.shopId || '')) return
shopSwitchLoading.value = true
try {
await runWithGlobalLoading(async () => {
const response = await adminAuthApi.switchShop(String(shopId))
persistAdminSession(response as any)
refreshLocalUserInfo()
await loadUserPermissions()
notifyShopThemeChanged()
})
message.success('门店切换成功')
window.location.reload()
} catch (error: any) {
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
message.error(error?.message || '切换门店失败')
} finally {
shopSwitchLoading.value = false
}
}
onMounted(() => {
void load()
})
@@ -418,7 +354,6 @@ onMounted(() => {
.warning-note { display: inline-flex; align-items: center; gap: 5px; color: #a66d22; font-size: 11px; white-space: nowrap; }
.warning-note::before { content: '!'; display: inline-flex; align-items: center; justify-content: center; width: 14px; height: 14px; border-radius: 50%; background: #fff3d9; font-size: 10px; font-weight: 800; }
.section-footnote { margin: 12px 2px 0; color: var(--admin-mobile-muted); font-size: 11px; }
.account-shop-select { width: 100%; min-width: 0; }
@media (max-width: 760px) {
.settings-header { align-items: flex-start; }
.settings-health, .account-status { display: none; }
@@ -1,45 +0,0 @@
/**
* Purpose: AdminCachedUserInfo supports admin-helpers.ts by holding or executing the admin cached user info page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { loadCachedAdminUserInfo, isBootstrapAdminUser, type AdminCachedUserInfo } from '@/utils/admin-session'
export { loadCachedAdminUserInfo, isBootstrapAdminUser }
export type { AdminCachedUserInfo }
/**
* Purpose: getAdminRoleLabel supports admin-helpers.ts by holding or executing the get admin role label page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const getAdminRoleLabel = (type?: number) => {
switch (type) {
case 4:
return '平台管理员'
case 2:
return '店长'
case 3:
return '店员'
default:
return '后台账号'
}
}
/**
* Purpose: getAdminShopOptions supports admin-helpers.ts by holding or executing the get admin shop options page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const getAdminShopOptions = (userInfo?: AdminCachedUserInfo | null) => {
const ids = userInfo?.shopIds || []
const names = userInfo?.shopNames || []
return ids.map((id, index) => ({
id: String(id),
name: names[index] || `门店 ${id}`
}))
}
/**
* Purpose: getAdminCurrentShopName supports admin-helpers.ts by holding or executing the get admin current shop name page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const getAdminCurrentShopName = (userInfo?: AdminCachedUserInfo | null) =>
userInfo?.shopName || (isBootstrapAdminUser(userInfo) ? '平台总览模式' : '游客模式')