重构项目文件夹目录

This commit is contained in:
2026-06-15 15:53:55 +08:00
parent 8093e07190
commit 7cbe5b3de5
1098 changed files with 34 additions and 4441 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,514 @@
<template>
<div class="admin-login">
<div class="login-container">
<div class="login-header">
<h1>后台管理系统</h1>
<p>欢迎回来,请登录您的账户</p>
</div>
<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-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>
</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 { 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 { 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 = {
account: [
{ 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
}
/** 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 () => {
try {
await formRef.value?.validate()
loading.value = true
const res = 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
})
} catch (error: any) {
console.error('登录失败:', error)
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;
}
}
</style>
@@ -0,0 +1,295 @@
<template>
<div class="after-sales">
<a-page-header v-if="!isMobile" title="售后处理" sub-title="处理客户退款与售后申请" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">售后</span>
<h1 class="admin-page-intro__title">售后处理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">申请 {{ pagination.total }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">售后列表</template>
<AdminFilterPanel :active-count="activeFilterCount">
<a-select
v-model:value="statusFilter"
:options="statusOptions"
style="width: 160px"
@change="reload"
/>
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="visibleAfterSales"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="statusColor(record.status)">{{ statusText(record.status) }}</a-tag>
</template>
<template v-else-if="column.key === 'amount'">¥{{ money(record.refundAmount) }}</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="currentAfterSale = record as AfterSaleVO">查看</a-button>
<a-button v-if="record.status === 'PENDING'" type="primary" size="small" @click="openAudit(record as AfterSaleVO, 'approve')">通过</a-button>
<a-button v-if="record.status === 'PENDING'" danger size="small" @click="openAudit(record as AfterSaleVO, 'reject')">驳回</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="visibleAfterSales" empty-description="暂无售后申请">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.afterSaleNo || `售后 ${item.id}` }}</div>
<div class="admin-mobile-card__subtitle">订单 {{ item.orderId }} · {{ item.createTime || '-' }}</div>
</div>
<a-tag :color="statusColor(item.status)">{{ statusText(item.status) }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>类型</span>
<strong>{{ typeText(item.type) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>退款金额</span>
<strong>¥{{ money(item.refundAmount) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>原因</span>
<strong>{{ item.reason || '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="currentAfterSale = item">查看</a-button>
<a-button v-if="item.status === 'PENDING'" type="primary" size="small" @click="openAudit(item, 'approve')">通过</a-button>
<a-button v-if="item.status === 'PENDING'" danger size="small" @click="openAudit(item, 'reject')">驳回</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="detailOpen"
title="售后详情"
:desktop-width="760"
:footer="null"
@cancel="currentAfterSale = null"
>
<a-descriptions v-if="currentAfterSale" bordered :column="1" size="small">
<a-descriptions-item label="售后单号">{{ currentAfterSale.afterSaleNo || '-' }}</a-descriptions-item>
<a-descriptions-item label="订单ID">{{ currentAfterSale.orderId }}</a-descriptions-item>
<a-descriptions-item label="订单项ID">{{ currentAfterSale.orderItemId || '-' }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ currentAfterSale.userId || '-' }}</a-descriptions-item>
<a-descriptions-item label="类型">{{ typeText(currentAfterSale.type) }}</a-descriptions-item>
<a-descriptions-item label="退款金额">¥{{ money(currentAfterSale.refundAmount) }}</a-descriptions-item>
<a-descriptions-item label="状态">{{ statusText(currentAfterSale.status) }}</a-descriptions-item>
<a-descriptions-item label="申请原因">{{ currentAfterSale.reason || '-' }}</a-descriptions-item>
<a-descriptions-item label="审核原因">{{ currentAfterSale.auditReason || '-' }}</a-descriptions-item>
<a-descriptions-item label="申请时间">{{ currentAfterSale.createTime || '-' }}</a-descriptions-item>
</a-descriptions>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="auditOpen"
:title="auditAction === 'approve' ? '通过售后' : '驳回售后'"
:desktop-width="620"
:confirm-loading="auditing"
@ok="submitAudit"
@cancel="closeAudit"
>
<a-form layout="vertical">
<a-alert
v-if="auditTarget"
class="audit-alert"
type="info"
show-icon
:message="`${auditTarget.afterSaleNo || auditTarget.id} · 退款 ¥${money(auditTarget.refundAmount)}`"
:description="auditTarget.reason || '暂无申请原因'"
/>
<a-form-item label="处理备注">
<a-textarea v-model:value="auditReason" :rows="4" :maxlength="300" placeholder="填写给客户和门店留痕的处理说明" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { adminAfterSaleApi, type AfterSaleVO } from '@/api/admin'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const route = useRoute()
const loading = ref(false)
const auditing = ref(false)
const statusFilter = ref('all')
const afterSales = ref<AfterSaleVO[]>([])
const currentAfterSale = ref<AfterSaleVO | null>(null)
const auditOpen = ref(false)
const auditTarget = ref<AfterSaleVO | null>(null)
const auditAction = ref<'approve' | 'reject'>('approve')
const auditReason = ref('')
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showTotal: (total: number) => `共 ${total} 条`
})
const detailOpen = computed({
get: () => !!currentAfterSale.value,
set: value => { if (!value) currentAfterSale.value = null }
})
const activeFilterCount = computed(() => statusFilter.value === 'all' ? 0 : 1)
const visibleAfterSales = computed(() => {
const orderId = route.query.orderId
if (!orderId) {
return afterSales.value
}
return afterSales.value.filter(item => String(item.orderId) === String(orderId))
})
const statusOptions = [
{ label: '全部状态', value: 'all' },
{ label: '待处理', value: 'PENDING' },
{ label: '已通过', value: 'APPROVED' },
{ label: '已驳回', value: 'REJECTED' }
]
const columns = [
{ title: '售后单号', dataIndex: 'afterSaleNo', key: 'afterSaleNo' },
{ title: '订单ID', dataIndex: 'orderId', key: 'orderId', width: 110 },
{ title: '用户ID', dataIndex: 'userId', key: 'userId', width: 110 },
{ title: '类型', dataIndex: 'type', key: 'type', width: 110 },
{ title: '退款金额', key: 'amount', width: 120 },
{ title: '状态', key: 'status', width: 110 },
{ title: '申请时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'actions', width: 190 }
]
const money = (value?: number) => Number(value || 0).toFixed(2)
const typeText = (type?: string) => {
if (type === 'REFUND') return '退款'
if (type === 'AFTER_SALE') return '售后'
return type || '-'
}
const statusText = (status?: string) => {
if (status === 'PENDING') return '待处理'
if (status === 'APPROVED') return '已通过'
if (status === 'REJECTED') return '已驳回'
return status || '-'
}
const statusColor = (status?: string) => {
if (status === 'PENDING') return 'orange'
if (status === 'APPROVED') return 'green'
if (status === 'REJECTED') return 'red'
return 'default'
}
const loadAfterSales = async () => {
loading.value = true
try {
const result = await adminAfterSaleApi.listAfterSales({
status: statusFilter.value === 'all' ? undefined : statusFilter.value,
page: pagination.current,
size: pagination.pageSize
})
afterSales.value = result.list || []
pagination.total = result.total || 0
} catch (error) {
console.error('加载售后失败:', error)
message.error('加载售后失败')
} finally {
loading.value = false
}
}
const reload = () => {
pagination.current = 1
void loadAfterSales()
}
const resetFilters = () => {
statusFilter.value = 'all'
reload()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
void loadAfterSales()
}
const openAudit = (record: AfterSaleVO, action: 'approve' | 'reject') => {
auditTarget.value = record
auditAction.value = action
auditReason.value = ''
auditOpen.value = true
}
const closeAudit = () => {
auditOpen.value = false
auditTarget.value = null
auditReason.value = ''
}
const submitAudit = async () => {
if (!auditTarget.value) return
auditing.value = true
try {
await runWithGlobalLoading(async () => {
const payload = { auditReason: auditReason.value.trim() || undefined }
if (auditAction.value === 'approve') {
await adminAfterSaleApi.approveAfterSale(auditTarget.value!.id, payload)
} else {
await adminAfterSaleApi.rejectAfterSale(auditTarget.value!.id, payload)
}
await loadAfterSales()
})
message.success('售后已处理')
closeAudit()
} catch (error: any) {
console.error('处理售后失败:', error)
message.error(error?.message || '处理售后失败')
} finally {
auditing.value = false
}
}
onMounted(loadAfterSales)
</script>
<style scoped>
.after-sales {
padding: 0;
}
.audit-alert {
margin-bottom: 16px;
}
</style>
@@ -0,0 +1,216 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>公告管理</h2>
<p>发布后会在用户首页顶部持续滚动展示。</p>
</div>
<a-button type="primary" @click="openCreate">发布公告</a-button>
</div>
<a-table
class="announcement-table"
:columns="columns"
:data-source="announcements"
:loading="loading"
row-key="id"
:scroll="{ x: 'max-content' }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'content'">
<span class="ellipsis">{{ extractRichText(record.content) }}</span>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.status === 1 ? '已发布' : '已撤回' }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="preview(record as AnnouncementVO)">查看</a-button>
<a-button v-if="record.status === 1" size="small" danger @click="revoke(record.id)">撤回</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" title="发布公告" :mask-closable="false" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="标题">
<a-input v-model:value="form.title" :maxlength="100" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="4" :maxlength="1000" placeholder="支持 HTML / Markdown,也可以直接输入纯文本" />
</a-form-item>
<a-form-item label="接收范围">
<a-select v-model:value="form.targetType" :options="targetOptions" />
</a-form-item>
<a-form-item v-if="needsShop" label="指定店铺">
<a-select v-model:value="form.shopIds" mode="multiple" :options="shopOptions" />
</a-form-item>
<a-form-item v-if="needsUser" label="指定用户">
<a-select v-model:value="form.userIds" mode="multiple" show-search option-filter-prop="label" :options="userOptions" />
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="form.sortOrder" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* AnnouncementsView 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, h, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
/**
* Purpose: AnnouncementVO supports AnnouncementsView.vue by holding or executing the announcement 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 { adminAnnouncementApi, type AnnouncementVO, type MessageTargetOptionsVO } from '@/api/admin'
import { extractRichText, renderRichContent } from '@/utils/rich-content'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
/**
* Purpose: announcements supports AnnouncementsView.vue by holding or executing the announcements 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 announcements = ref<AnnouncementVO[]>([])
/**
* Purpose: options supports AnnouncementsView.vue by holding or executing the 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.
*/
const options = ref<MessageTargetOptionsVO>({ shops: [], users: [] })
/**
* Purpose: form supports AnnouncementsView.vue by holding or executing the form 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 form = reactive<any>({ title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 })
/**
* Purpose: columns supports AnnouncementsView.vue by holding or executing the columns 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 columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '内容', dataIndex: 'content', key: 'content' },
{ title: '发布人', dataIndex: 'publisherName', key: 'publisherName' },
{ title: '范围', dataIndex: 'targetTypeName', key: 'targetTypeName' },
{ title: '状态', dataIndex: 'status', key: 'status' },
{ title: '发布时间', dataIndex: 'publishTime', key: 'publishTime' },
{ title: '操作', key: 'action', width: 150 }
]
/**
* Purpose: targetOptions supports AnnouncementsView.vue by holding or executing the target 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.
*/
const targetOptions = [
{ label: '全平台', value: 'PLATFORM_ALL' },
{ label: '当前门店全部用户', value: 'CURRENT_SHOP_ALL' },
{ label: '指定门店全部用户', value: 'SELECTED_SHOPS' },
{ label: '指定用户', value: 'SELECTED_USERS' }
]
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => options.value.shops.map(item => ({ label: item.shopName, value: item.id })))
/** userOptions is a reactive state variable used by the template and event handlers. */
const userOptions = computed(() => options.value.users.map(item => ({ label: `${item.nickname || item.account} ${item.shopName ? `(${item.shopName})` : ''}`, value: item.id })))
/** needsShop is a reactive state variable used by the template and event handlers. */
const needsShop = computed(() => ['SHOP_ALL', 'SELECTED_SHOPS'].includes(form.targetType))
/** needsUser is a reactive state variable used by the template and event handlers. */
const needsUser = computed(() => form.targetType === 'SELECTED_USERS')
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [list, target] = await Promise.all([
adminAnnouncementApi.listAnnouncements(),
adminAnnouncementApi.getTargetOptions().catch(() => ({ shops: [], users: [] }))
])
announcements.value = list || []
options.value = target
} finally {
loading.value = false
}
}
/** openCreate is a local helper used by this page script. */
const openCreate = () => {
Object.assign(form, { title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 })
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.title || !form.content) {
message.warning('请填写标题和内容')
return
}
saving.value = true
try {
await adminAnnouncementApi.createAnnouncement(form)
message.success('公告已发布')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** preview is a local helper used by this page script. */
const preview = (record: AnnouncementVO) => {
Modal.info({
title: record.title,
width: 560,
content: h('div', {
class: 'announcement-preview-content',
innerHTML: renderRichContent(record.content)
})
})
}
/** revoke is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const revoke = async (id: any) => {
await adminAnnouncementApi.revokeAnnouncement(id)
message.success('公告已撤回')
await load()
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p { margin: 0; color: var(--text-secondary); }
.ellipsis { display: inline-block; max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; }
.announcement-table :deep(.ant-table) { min-width: 880px; }
.announcement-table :deep(.ant-table-cell) { white-space: nowrap; word-break: keep-all; overflow-wrap: normal; }
.announcement-table :deep(.ant-table-content) { overflow-x: auto; }
:global(.announcement-preview-content) { line-height: 1.8; overflow-wrap: break-word; }
:global(.announcement-preview-content *) { max-width: 100%; }
:global(.announcement-preview-content p),
:global(.announcement-preview-content ul),
:global(.announcement-preview-content ol),
:global(.announcement-preview-content blockquote),
:global(.announcement-preview-content pre),
:global(.announcement-preview-content table) { margin: 0 0 12px; }
:global(.announcement-preview-content p:last-child),
:global(.announcement-preview-content ul:last-child),
:global(.announcement-preview-content ol:last-child),
:global(.announcement-preview-content blockquote:last-child),
:global(.announcement-preview-content pre:last-child),
:global(.announcement-preview-content table:last-child) { margin-bottom: 0; }
:global(.announcement-preview-content ul),
:global(.announcement-preview-content ol) { padding-left: 1.25em; }
:global(.announcement-preview-content img) { display: block; max-width: 100%; border-radius: 8px; }
:global(.announcement-preview-content pre) { overflow-x: auto; padding: 10px 12px; border-radius: 8px; background: var(--theme-primary-soft); }
</style>
@@ -0,0 +1,312 @@
<template>
<div class="campaigns">
<a-page-header v-if="!isMobile" title="活动管理" sub-title="维护营销活动、推荐位和关联资源" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">活动</span>
<h1 class="admin-page-intro__title">活动管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">活动 {{ pagination.total }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">活动列表</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-button type="primary" @click="openCreateModal">
<template #icon>
<PlusOutlined />
</template>
新增活动
</a-button>
</div>
</template>
<AdminFilterPanel :active-count="activeFilterCount">
<a-select
v-model:value="statusFilter"
:options="statusOptions"
style="width: 160px"
@change="reload"
/>
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="campaigns"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 0 ? 'red' : 'green'">{{ campaignStatusText(record.status) }}</a-tag>
</template>
<template v-else-if="column.key === 'time'">
{{ record.startTime || '-' }} 至 {{ record.endTime || '-' }}
</template>
<template v-else-if="column.key === 'actions'">
<a-button type="link" size="small" @click="openEditModal(record as CampaignVO)">编辑</a-button>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="campaigns" empty-description="暂无活动数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.title }}</div>
<div class="admin-mobile-card__subtitle">{{ item.scene || 'GENERAL' }} · 排序 {{ item.sortOrder ?? 0 }}</div>
</div>
<a-tag :color="item.status === 0 ? 'red' : 'green'">{{ campaignStatusText(item.status) }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>时间</span>
<strong>{{ item.startTime || '-' }} 至 {{ item.endTime || '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>作品ID</span>
<strong>{{ item.productIds || '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>优惠券ID</span>
<strong>{{ item.couponIds || '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="openEditModal(item)">编辑</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalOpen"
:title="editingCampaign ? '编辑活动' : '新增活动'"
:desktop-width="760"
:confirm-loading="saving"
@ok="saveCampaign"
@cancel="closeModal"
>
<a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="活动标题" name="title">
<a-input v-model:value="formState.title" placeholder="请输入活动标题" />
</a-form-item>
<a-form-item label="活动场景">
<a-input v-model:value="formState.scene" placeholder="HOME / DETAIL / POPUP" />
</a-form-item>
<a-form-item label="活动说明">
<a-textarea v-model:value="formState.description" :rows="3" :maxlength="500" />
</a-form-item>
<a-form-item label="关联作品ID">
<a-input v-model:value="formState.productIds" placeholder="多个 ID 用英文逗号分隔" />
</a-form-item>
<a-form-item label="关联券ID">
<a-input v-model:value="formState.couponIds" placeholder="多个 ID 用英文逗号分隔" />
</a-form-item>
<a-form-item label="开始时间">
<a-date-picker
v-model:value="formState.startTime"
show-time
value-format="YYYY-MM-DDTHH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="结束时间">
<a-date-picker
v-model:value="formState.endTime"
show-time
value-format="YYYY-MM-DDTHH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="formState.sortOrder" :min="0" style="width: 100%" />
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="formState.status">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">停用</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { adminCampaignApi, type CampaignRequest, type CampaignVO } from '@/api/admin'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const loading = ref(false)
const saving = ref(false)
const statusFilter = ref<'all' | number>('all')
const campaigns = ref<CampaignVO[]>([])
const modalOpen = ref(false)
const editingCampaign = ref<CampaignVO | null>(null)
const formRef = ref<FormInstance>()
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive<CampaignRequest>({
title: '',
description: '',
scene: 'HOME',
productIds: '',
couponIds: '',
status: 1,
startTime: undefined,
endTime: undefined,
sortOrder: 0
})
const rules = {
title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }]
} as any
const statusOptions = [
{ label: '全部状态', value: 'all' },
{ label: '启用', value: 1 },
{ label: '停用', value: 0 }
]
const activeFilterCount = computed(() => statusFilter.value === 'all' ? 0 : 1)
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '场景', dataIndex: 'scene', key: 'scene', width: 120 },
{ title: '活动时间', key: 'time', width: 280 },
{ title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 90 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 90 }
]
const campaignStatusText = (status?: number) => status === 0 ? '停用' : '启用'
const resetForm = () => {
Object.assign(formState, {
title: '',
description: '',
scene: 'HOME',
productIds: '',
couponIds: '',
status: 1,
startTime: undefined,
endTime: undefined,
sortOrder: 0
})
}
const loadCampaigns = async () => {
loading.value = true
try {
const result = await adminCampaignApi.listCampaigns({
status: statusFilter.value === 'all' ? undefined : Number(statusFilter.value),
page: pagination.current,
size: pagination.pageSize
})
campaigns.value = result.list || []
pagination.total = result.total || 0
} catch (error) {
console.error('加载活动失败:', error)
message.error('加载活动失败')
} finally {
loading.value = false
}
}
const reload = () => {
pagination.current = 1
void loadCampaigns()
}
const resetFilters = () => {
statusFilter.value = 'all'
reload()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
void loadCampaigns()
}
const openCreateModal = () => {
editingCampaign.value = null
resetForm()
modalOpen.value = true
}
const openEditModal = (record: CampaignVO) => {
editingCampaign.value = record
Object.assign(formState, {
title: record.title || '',
description: record.description || '',
scene: record.scene || 'HOME',
productIds: record.productIds || '',
couponIds: record.couponIds || '',
status: record.status ?? 1,
startTime: record.startTime,
endTime: record.endTime,
sortOrder: record.sortOrder ?? 0
})
modalOpen.value = true
}
const closeModal = () => {
modalOpen.value = false
formRef.value?.resetFields()
}
const saveCampaign = async () => {
try {
await formRef.value?.validate()
saving.value = true
await runWithGlobalLoading(async () => {
await adminCampaignApi.saveCampaign({ ...formState })
await loadCampaigns()
})
message.success('活动已保存')
closeModal()
} catch (error: any) {
if (error?.errorFields) return
console.error('保存活动失败:', error)
message.error(error?.message || '保存活动失败')
} finally {
saving.value = false
}
}
onMounted(loadCampaigns)
</script>
<style scoped>
.campaigns {
padding: 0;
}
</style>
@@ -0,0 +1,245 @@
<template>
<div class="comments-page">
<header class="page-head">
<div>
<h2>评论管理</h2>
<p>查看作品评论与回复,删除不合规内容。</p>
</div>
<a-input-search v-model:value="keyword" class="search" allow-clear placeholder="搜索评论内容" @search="loadComments" />
</header>
<AdminFilterPanel :active-count="activeFilterCount">
<a-input v-model:value="shopKeyword" allow-clear placeholder="店铺" style="width: 160px" @pressEnter="loadComments" />
<a-input v-model:value="productKeyword" allow-clear placeholder="作品" style="width: 160px" @pressEnter="loadComments" />
<a-input v-model:value="userKeyword" allow-clear placeholder="用户" style="width: 160px" @pressEnter="loadComments" />
<a-range-picker v-model:value="createdRange" value-format="YYYY-MM-DD HH:mm:ss" show-time />
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
:columns="columns"
:data-source="filteredComments"
:loading="loading"
:pagination="{ pageSize: 10 }"
row-key="id"
:scroll="{ x: 'max-content' }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'commentContent'">
<div class="comment-cell">
<strong>{{ record.commentContent }}</strong>
<span v-if="record.parentCommentContent">回复:{{ record.parentCommentContent }}</span>
</div>
</template>
<template v-else-if="column.key === 'action'">
<a-popconfirm title="确认删除这条评论?" ok-text="删除" cancel-text="取消" @confirm="deleteComment(record.id)">
<a-button danger type="link">删除</a-button>
</a-popconfirm>
</template>
</template>
</a-table>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
/**
* Purpose: AdminCommentVO supports CommentsView.vue by holding or executing the admin comment 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 { adminCommentApi, type AdminCommentVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
/**
* Purpose: loading supports CommentsView.vue by holding or executing the loading 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 loading = ref(false)
/**
* Purpose: keyword supports CommentsView.vue by holding or executing the keyword 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 keyword = ref('')
/**
* Purpose: shopKeyword supports CommentsView.vue by holding or executing the shop keyword 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 shopKeyword = ref('')
/**
* Purpose: productKeyword supports CommentsView.vue by holding or executing the product keyword 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 productKeyword = ref('')
/**
* Purpose: userKeyword supports CommentsView.vue by holding or executing the user keyword 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 userKeyword = ref('')
/**
* Purpose: createdRange supports CommentsView.vue by holding or executing the created range 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 createdRange = ref<[string, string] | undefined>()
/**
* Purpose: comments supports CommentsView.vue by holding or executing the comments 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 comments = ref<AdminCommentVO[]>([])
const activeFilterCount = computed(() => [
keyword.value,
shopKeyword.value,
productKeyword.value,
userKeyword.value,
createdRange.value?.length ? 'date' : ''
].filter(Boolean).length)
/**
* Purpose: columns supports CommentsView.vue by holding or executing the columns 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 columns = [
{ title: '评论内容', dataIndex: 'commentContent', key: 'commentContent' },
{ title: '用户', dataIndex: 'userNickname', key: 'userNickname', width: 140 },
{ title: '作品', dataIndex: 'productTitle', key: 'productTitle', width: 180 },
{ title: '店铺', dataIndex: 'shopName', key: 'shopName', width: 160 },
{ title: '时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'action', width: 100 }
]
/**
* Purpose: filteredComments supports CommentsView.vue by holding or executing the filtered comments 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 filteredComments = computed(() => comments.value.filter(comment => {
if (!matchText(shopKeyword.value, [comment.shopName, comment.shopId])) return false
if (!matchText(productKeyword.value, [comment.productTitle, comment.productId])) return false
if (!matchText(userKeyword.value, [comment.userNickname, comment.userId])) return false
return matchRange(comment.createTime, createdRange.value)
}))
/**
* Purpose: matchText supports CommentsView.vue by holding or executing the match text 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 matchText = (needle: string, values: any[]) => {
const normalized = needle.trim().toLowerCase()
if (!normalized) return true
return values.some(value => String(value ?? '').toLowerCase().includes(normalized))
}
/**
* Purpose: matchRange supports CommentsView.vue by holding or executing the match range 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 matchRange = (value?: string, range?: [string, string]) => {
if (!range?.length) return true
if (!value) return false
const time = new Date(value).getTime()
return time >= new Date(range[0]).getTime() && time <= new Date(range[1]).getTime()
}
/**
* Purpose: loadComments supports CommentsView.vue by holding or executing the load comments 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 loadComments = async () => {
loading.value = true
try {
comments.value = await adminCommentApi.listComments({ keyword: keyword.value || undefined })
} catch (error: any) {
message.error(error?.message || '评论加载失败')
} finally {
loading.value = false
}
}
/**
* Purpose: deleteComment supports CommentsView.vue by holding or executing the delete comment 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 deleteComment = async (id: IdType) => {
await adminCommentApi.deleteComment(id)
message.success('评论已删除')
await loadComments()
}
/**
* Purpose: resetFilters supports CommentsView.vue by holding or executing the reset filters 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 resetFilters = () => {
keyword.value = ''
shopKeyword.value = ''
productKeyword.value = ''
userKeyword.value = ''
createdRange.value = undefined
loadComments()
}
onMounted(loadComments)
</script>
<style scoped>
.comments-page {
display: grid;
gap: 18px;
}
.page-head {
display: flex;
justify-content: space-between;
gap: 16px;
align-items: flex-start;
}
.page-head h2 {
margin: 0;
font-size: 22px;
color: var(--text-primary);
}
.page-head p {
margin: 6px 0 0;
color: var(--text-secondary);
}
.search {
width: min(360px, 100%);
}
.comment-cell {
display: grid;
gap: 6px;
}
.comment-cell strong {
color: var(--text-primary);
font-weight: 600;
}
.comment-cell span {
color: var(--text-secondary);
font-size: 12px;
}
@media (max-width: 960px) {
.comments-page {
gap: 12px;
}
.page-head {
align-items: stretch;
}
.page-head > div {
display: none;
}
.search {
width: 100%;
}
}
</style>
+987
View File
@@ -0,0 +1,987 @@
<template>
<div class="coupons">
<a-page-header v-if="!isMobile" title="优惠券管理" sub-title="管理系统优惠券" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">优惠券管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">优惠券 {{ couponList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">
优惠券列表
</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="searchText"
placeholder="搜索优惠券名称"
:style="isMobile ? { width: '100%' } : { width: '260px' }"
@search="handleSearch"
/>
<a-button v-if="!isMobile && hasPermission('coupon:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增优惠券
</a-button>
</div>
</template>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="couponList"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'shop'">
{{ record.shopName || '未指定店铺' }}
</template>
<template v-else-if="column.key === 'couponType'">
<a-tag :color="record.couponType === 1 ? 'blue' : 'green'">
{{ record.couponTypeName || (record.couponType === 1 ? '折扣券' : '满减券') }}
</a-tag>
</template>
<template v-else-if="column.key === 'couponScene'">
<a-tag :color="record.couponScene === 'VIP_AUTO' ? 'gold' : 'default'">
{{ getCouponSceneText(record.couponScene) }}
</a-tag>
</template>
<template v-else-if="column.key === 'requiredVipLevel'">
{{ record.requiredVipLevel || '-' }}
</template>
<template v-else-if="column.key === 'value'">
<template v-if="record.couponType === 1">
{{ record.discountValue }} 折
</template>
<template v-else>
满 {{ record.minAmount }} 减 {{ record.reduceAmount }}
</template>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="getStatusColor(record.status || 1)">
{{ record.statusName || '未知' }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space wrap>
<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') && !isVipAutoCoupon(record) && record.status === 1"
type="link"
size="small"
@click="showDistributeModal(record)"
>
发放
</a-button>
<a-button
v-if="hasPermission('coupon:delete') && record.status !== 2"
type="link"
size="small"
danger
@click="handleDelete(record)"
>
删除
</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="couponList" empty-description="暂无优惠券数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.couponName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.shopName || '未指定店铺' }}</div>
</div>
<a-tag :color="getStatusColor(item.status || 1)">
{{ item.statusName || '未知' }}
</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>类型</span>
<strong>{{ item.couponType === 1 ? '折扣券' : '满减券' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>场景</span>
<strong>{{ getCouponSceneText(item.couponScene) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>优惠值</span>
<strong>{{ getCouponValueText(item) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>剩余数量</span>
<strong>{{ item.remainingCount ?? '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('coupon:view')" size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('coupon:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
<a-button
v-if="hasPermission('coupon:assign') && !isVipAutoCoupon(item) && item.status === 1"
size="small"
@click="showDistributeModal(item)"
>
发放
</a-button>
<a-button
v-if="hasPermission('coupon:delete') && item.status !== 2"
size="small"
danger
@click="handleDelete(item)"
>
删除
</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalVisible"
:title="isEdit ? '编辑优惠券' : '新增优惠券'"
:desktop-width="820"
:confirm-loading="modalLoading"
@ok="handleModalOk"
@cancel="handleModalCancel"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券名称" name="couponName">
<a-input v-model:value="formState.couponName" placeholder="请输入优惠券名称" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择所属店铺"
:loading="loadingShops"
:disabled="currentUserInfo?.type === 2"
>
<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="couponType">
<a-select v-model:value="formState.couponType" placeholder="请选择优惠券类型">
<a-select-option :value="1">折扣券</a-select-option>
<a-select-option :value="2">满减券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠场景" name="couponScene">
<a-select v-model:value="formState.couponScene" placeholder="请选择优惠场景">
<a-select-option value="GENERAL">普通券</a-select-option>
<a-select-option value="VIP_AUTO">VIP 自动券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="自动匹配">
<a-switch :checked="formState.autoMatch === 1" @change="(checked: any) => handleAutoMatchChange(checked === true)" />
</a-form-item>
<a-form-item v-if="isVipAutoForm" label="所需 VIP 等级" name="requiredVipLevel">
<a-select v-model:value="formState.requiredVipLevel" placeholder="请选择 VIP 等级">
<a-select-option v-for="level in vipLevelOptions" :key="level" :value="level">{{ level }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="formState.couponType === 1" label="折扣值" name="discountValue">
<a-input-number v-model:value="formState.discountValue" :min="0.1" :max="9.9" :step="0.1" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="最低消费" name="minAmount">
<a-input-number v-model:value="formState.minAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="减免金额" name="reduceAmount">
<a-input-number v-model:value="formState.reduceAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item label="总数量" name="totalCount">
<a-input-number v-model:value="formState.totalCount" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item label="开始时间" name="startTime">
<a-date-picker v-model:value="formState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="yumi-date-picker-panel yumi-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="结束时间" name="endTime">
<a-date-picker v-model:value="formState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="yumi-date-picker-panel yumi-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="可用标签" name="availableTagIds">
<a-select v-model:value="formState.availableTagIds" mode="multiple" placeholder="请选择可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id" :disabled="formState.unavailableTagIds.includes(Number(tag.id))">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="不可用标签" name="unavailableTagIds">
<a-select v-model:value="formState.unavailableTagIds" mode="multiple" placeholder="请选择不可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id" :disabled="formState.availableTagIds.includes(Number(tag.id))">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看优惠券详情"
:footer="null"
:desktop-width="760"
@cancel="viewModalVisible = false"
>
<a-descriptions bordered :column="1" size="small">
<a-descriptions-item label="优惠券名称">{{ currentCoupon?.couponName || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ currentCoupon?.shopName || '-' }}</a-descriptions-item>
<a-descriptions-item label="优惠券类型">{{ currentCoupon?.couponType === 1 ? '折扣券' : '满减券' }}</a-descriptions-item>
<a-descriptions-item label="优惠场景">{{ getCouponSceneText(currentCoupon?.couponScene) }}</a-descriptions-item>
<a-descriptions-item label="所需 VIP 等级">{{ currentCoupon?.requiredVipLevel || '-' }}</a-descriptions-item>
<a-descriptions-item label="自动匹配">{{ currentCoupon?.autoMatch === 1 ? '是' : '否' }}</a-descriptions-item>
<a-descriptions-item label="优惠信息">{{ getCouponValueText(currentCoupon) }}</a-descriptions-item>
<a-descriptions-item label="总数量">{{ currentCoupon?.totalCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="已使用">{{ currentCoupon?.usedCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="开始时间">{{ currentCoupon?.startTime || '-' }}</a-descriptions-item>
<a-descriptions-item label="结束时间">{{ currentCoupon?.endTime || '-' }}</a-descriptions-item>
</a-descriptions>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="distributeModalVisible"
title="发放优惠券"
:desktop-width="760"
:confirm-loading="distributeLoading"
@ok="handleDistributeOk"
@cancel="handleDistributeCancel"
>
<a-form
ref="distributeFormRef"
:model="distributeFormState"
:rules="distributeFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券">
<a-input v-model:value="distributeFormState.couponName" disabled />
</a-form-item>
<a-form-item label="选择用户" name="userIds">
<a-select
v-model:value="distributeFormState.userIds"
mode="multiple"
placeholder="请选择要发放的用户"
>
<a-select-option v-for="user in userList" :key="user.id" :value="user.id">
{{ user.nickname }}({{ user.account }})
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="发放数量" name="quantity">
<a-input-number v-model:value="distributeFormState.quantity" :min="1" style="width: 100%" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && hasPermission('coupon:create') && !modalVisible && !viewModalVisible && !distributeModalVisible"
label="新增优惠券"
@click="showAddModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* CouponsView 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, reactive, ref, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
/**
* Purpose: Dayjs supports CouponsView.vue by holding or executing the dayjs 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 dayjs, { type Dayjs } from 'dayjs'
import {
adminCouponApi,
adminVipRechargePlanApi,
adminShopApi,
adminTagApi,
adminUserApi,
type Coupon,
type Shop,
type Tag,
type UserVO
} from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** currentUserInfo is a local helper used by this page script. */
const currentUserInfo = (() => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
return userInfoStr ? JSON.parse(userInfoStr) : null
} catch (error) {
console.error('获取当前用户信息失败', error)
return null
}
})()
/**
* Purpose: CouponFormState supports CouponsView.vue by holding or executing the coupon form state page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface CouponFormState {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime?: Dayjs
endTime?: Dayjs
availableTagIds: number[]
unavailableTagIds: number[]
shopId?: number
couponScene: string
requiredVipLevel?: string
autoMatch: number
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
/**
* Purpose: formRef supports CouponsView.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>()
/**
* Purpose: distributeFormRef supports CouponsView.vue by holding or executing the distribute 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 distributeFormRef = ref<FormInstance>()
/**
* Purpose: currentCoupon supports CouponsView.vue by holding or executing the current coupon 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 currentCoupon = ref<Coupon | null>(null)
/**
* Purpose: draftSavedAt supports CouponsView.vue by holding or executing the draft saved at 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 draftSavedAt = ref<number | null>(null)
/**
* Purpose: couponList supports CouponsView.vue by holding or executing the coupon list 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 couponList = ref<Coupon[]>([])
/**
* Purpose: tagList supports CouponsView.vue by holding or executing the tag list 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 tagList = ref<Tag[]>([])
/**
* Purpose: userList supports CouponsView.vue by holding or executing the user list 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 userList = ref<UserVO[]>([])
/**
* Purpose: shops supports CouponsView.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<Shop[]>([])
/**
* Purpose: vipLevelOptions supports CouponsView.vue by holding or executing the vip level 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.
*/
const vipLevelOptions = ref<string[]>(['普通', '青铜', '白银', '黄金'])
/** distributeModalVisible is a reactive state variable used by the template and event handlers. */
const distributeModalVisible = ref(false)
/** distributeLoading is a reactive state variable used by the template and event handlers. */
const distributeLoading = ref(false)
/**
* Purpose: currentDistributeCoupon supports CouponsView.vue by holding or executing the current distribute coupon 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 currentDistributeCoupon = ref<Coupon | null>(null)
/**
* Purpose: pagination supports CouponsView.vue by holding or executing the pagination 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 pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: formState supports CouponsView.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<CouponFormState>({
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
/**
* Purpose: distributeFormState supports CouponsView.vue by holding or executing the distribute 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 distributeFormState = reactive({
couponName: '',
userIds: [] as number[],
quantity: 1
})
/**
* Purpose: formRules supports CouponsView.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 = {
couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
couponScene: [{ required: true, message: '请选择优惠场景', trigger: 'change' }],
requiredVipLevel: [{ required: true, message: '请选择所需 VIP 等级', trigger: 'change' }],
totalCount: [{ required: true, message: '请输入优惠券总数量', trigger: 'blur' }],
startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
} as any
/**
* Purpose: distributeFormRules supports CouponsView.vue by holding or executing the distribute 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 distributeFormRules = {
userIds: [{ required: true, message: '请选择要发放的用户', trigger: 'change' }],
quantity: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
} as any
/**
* Purpose: columns supports CouponsView.vue by holding or executing the columns 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 columns = [
{ title: '优惠券名称', dataIndex: 'couponName', key: 'couponName' },
{ title: '所属店铺', key: 'shop', width: 140 },
{ title: '类型', key: 'couponType', width: 100 },
{ title: '场景', key: 'couponScene', width: 120 },
{ title: '所需 VIP', key: 'requiredVipLevel', width: 110 },
{ title: '优惠信息', key: 'value', width: 170 },
{ title: '总数量', dataIndex: 'totalCount', key: 'totalCount', width: 90 },
{ title: '已使用', dataIndex: 'usedCount', key: 'usedCount', width: 90 },
{ title: '剩余', dataIndex: 'remainingCount', key: 'remainingCount', width: 90 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 180, fixed: 'right' as const }
]
/** isVipAutoForm is a reactive state variable used by the template and event handlers. */
const isVipAutoForm = computed(() => formState.couponScene === 'VIP_AUTO' || formState.autoMatch === 1)
/** getStatusColor is a local helper used by this page script. */
const getStatusColor = (status: number) => {
switch (status) {
case 1:
return 'green'
case 2:
return 'red'
case 3:
return 'orange'
default:
return 'default'
}
}
/** getCouponSceneText is a local helper used by this page script. */
const getCouponSceneText = (scene?: string) => {
if (scene === 'VIP_AUTO') {
return 'VIP 自动券'
}
return '普通券'
}
/** isVipAutoCoupon is a local helper used by this page script. */
const isVipAutoCoupon = (coupon: any) => coupon?.couponScene === 'VIP_AUTO' || coupon?.autoMatch === 1
/** getCouponValueText is a local helper used by this page script. */
const getCouponValueText = (coupon: Coupon | null) => {
if (!coupon) {
return '-'
}
return coupon.couponType === 1
? `${coupon.discountValue} 折`
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
/** resetFormState is a local helper used by this page script. */
const resetFormState = () => {
Object.assign(formState, {
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: currentUserInfo?.shopId || undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-coupons', isEdit.value ? 'edit' : 'create', currentCoupon.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.discountValue,
minAmount: formState.minAmount,
reduceAmount: formState.reduceAmount,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DDTHH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DDTHH:mm:ss'),
availableTagIds: [...formState.availableTagIds],
unavailableTagIds: [...formState.unavailableTagIds],
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: formState.requiredVipLevel,
autoMatch: formState.autoMatch
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, {
...draft.payload,
startTime: draft.payload.startTime ? dayjs(draft.payload.startTime) : undefined,
endTime: draft.payload.endTime ? dayjs(draft.payload.endTime) : undefined
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/**
* Purpose: isSameTagSelection supports CouponsView.vue by holding or executing the is same tag selection 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 isSameTagSelection = (left: number[], right: number[]) =>
left.length === right.length && left.every((id, index) => Number(id) === Number(right[index]))
/**
* Purpose: removeSelectedTags supports CouponsView.vue by holding or executing the remove selected tags 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 removeSelectedTags = (target: number[], selected: number[]) => {
const selectedIds = new Set(selected.map(Number))
return target.filter(id => !selectedIds.has(Number(id)))
}
watch(
() => formState.couponScene,
value => {
if (value === 'VIP_AUTO') {
formState.autoMatch = 1
if (!formState.requiredVipLevel) {
formState.requiredVipLevel = vipLevelOptions.value.find(level => level !== '普通') || vipLevelOptions.value[0]
}
} else {
formState.autoMatch = 0
formState.requiredVipLevel = undefined
}
}
)
watch(
() => formState.availableTagIds.slice(),
value => {
const nextUnavailableTagIds = removeSelectedTags(formState.unavailableTagIds, value)
if (!isSameTagSelection(formState.unavailableTagIds, nextUnavailableTagIds)) {
formState.unavailableTagIds = nextUnavailableTagIds
}
}
)
watch(
() => formState.unavailableTagIds.slice(),
value => {
const nextAvailableTagIds = removeSelectedTags(formState.availableTagIds, value)
if (!isSameTagSelection(formState.availableTagIds, nextAvailableTagIds)) {
formState.availableTagIds = nextAvailableTagIds
}
}
)
/** handleAutoMatchChange is a local helper used by this page script. */
const handleAutoMatchChange = (checked: boolean) => {
formState.autoMatch = checked ? 1 : 0
formState.couponScene = checked ? 'VIP_AUTO' : 'GENERAL'
}
/** fetchCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCoupons = async () => {
loading.value = true
try {
const shopId = currentUserInfo?.shopId || undefined
const coupons = await adminCouponApi.listAllCoupons(shopId) as unknown as Coupon[]
const list = Array.isArray(coupons) ? coupons : []
const keyword = searchText.value.trim()
couponList.value = keyword
? list.filter(item => (item.couponName || '').includes(keyword))
: list
pagination.total = couponList.value.length
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async () => {
try {
const tags = await adminTagApi.listAllTags() as unknown as Tag[]
tagList.value = tags || []
} catch (error) {
console.error('获取标签列表失败:', error)
}
}
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
const shopList = await adminShopApi.listAllShops() as unknown as Shop[]
shops.value = shopList || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
/** fetchUsers is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUsers = async () => {
try {
const params: Record<string, unknown> = { page: 1, size: 200 }
if (currentUserInfo?.shopId) {
params.shopId = currentUserInfo.shopId
}
const result = await adminUserApi.listUsers(params as any)
userList.value = result.list || []
} catch (error) {
console.error('获取用户列表失败:', error)
userList.value = []
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchCoupons())
}
/** handleTableChange is a local helper used by this page script. */
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentCoupon.value = null
resetFormState()
restoreDraft()
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentCoupon.value = record
Object.assign(formState, {
couponCode: record.couponCode || '',
couponName: record.couponName || '',
couponType: record.couponType || 1,
discountValue: record.discountValue ? Number(record.discountValue) : 9.5,
minAmount: record.minAmount ? Number(record.minAmount) : 100,
reduceAmount: record.reduceAmount ? Number(record.reduceAmount) : 20,
totalCount: record.totalCount || 100,
startTime: record.startTime ? dayjs(record.startTime) : undefined,
endTime: record.endTime ? dayjs(record.endTime) : undefined,
availableTagIds: record.availableTags?.map((tag: Tag) => tag.id) || [],
unavailableTagIds: record.unavailableTags?.map((tag: Tag) => tag.id) || [],
shopId: record.shopId,
couponScene: record.couponScene || 'GENERAL',
requiredVipLevel: record.requiredVipLevel || undefined,
autoMatch: record.autoMatch || 0
})
restoreDraft()
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
currentCoupon.value = record
viewModalVisible.value = true
}
/** buildCouponPayload is a local helper used by this page script. */
const buildCouponPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.couponType === 1 ? formState.discountValue : undefined,
minAmount: formState.couponType === 2 ? formState.minAmount : undefined,
reduceAmount: formState.couponType === 2 ? formState.reduceAmount : undefined,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DDTHH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DDTHH:mm:ss'),
availableTagIds: formState.availableTagIds,
unavailableTagIds: formState.unavailableTagIds,
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: isVipAutoForm.value ? formState.requiredVipLevel : undefined,
autoMatch: isVipAutoForm.value ? 1 : 0
})
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
await runWithGlobalLoading(async () => {
const payload = buildCouponPayload()
if (isEdit.value && currentCoupon.value) {
await adminCouponApi.updateCoupon(currentCoupon.value.id, payload)
message.success('更新成功')
} else {
await adminCouponApi.createCoupon(payload)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
formRef.value?.resetFields()
await fetchCoupons()
})
} catch (error: any) {
console.error('保存优惠券失败:', error)
message.error(error.message || '操作失败')
} finally {
modalLoading.value = false
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
resetFormState()
}
/** handleDelete is a local helper used by this page script. */
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除优惠券 ${record.couponName} 吗?`,
async onOk() {
try {
await runWithGlobalLoading(async () => {
await adminCouponApi.deleteCoupon(record.id)
message.success('删除成功')
await fetchCoupons()
})
} catch (error) {
console.error('删除优惠券失败:', error)
message.error('删除失败')
}
}
})
}
/** showDistributeModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showDistributeModal = async (record: any) => {
currentDistributeCoupon.value = record
distributeFormState.couponName = record.couponName
distributeFormState.userIds = []
distributeFormState.quantity = 1
await runWithGlobalLoading(() => fetchUsers())
distributeModalVisible.value = true
}
/** handleDistributeOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDistributeOk = async () => {
if (!currentDistributeCoupon.value) {
return
}
const couponId = currentDistributeCoupon.value.id
if (isVipAutoCoupon(currentDistributeCoupon.value)) {
message.warning('VIP 自动券为系统模板券,不能手动发放')
return
}
try {
await distributeFormRef.value?.validate()
distributeLoading.value = true
await runWithGlobalLoading(async () => {
await adminCouponApi.distributeCoupon({
couponId,
userIds: distributeFormState.userIds,
quantity: distributeFormState.quantity
})
message.success('发放成功')
distributeModalVisible.value = false
})
} catch (error: any) {
console.error('发放优惠券失败:', error)
message.error(error.message || '发放失败')
} finally {
distributeLoading.value = false
}
}
/** handleDistributeCancel is a local helper used by this page script. */
const handleDistributeCancel = () => {
distributeModalVisible.value = false
distributeFormRef.value?.resetFields()
}
/**
* Purpose: fetchVipLevelOptions supports CouponsView.vue by holding or executing the fetch vip level 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.
*/
const fetchVipLevelOptions = async () => {
try {
const levels = await adminVipRechargePlanApi.listVipLevelOptions(currentUserInfo?.shopId)
if (Array.isArray(levels) && levels.length) {
vipLevelOptions.value = ['普通', ...levels.filter(level => level !== '普通')]
}
} catch (error) {
console.error('VIP 等级选项加载失败:', error)
}
}
onMounted(async () => {
await loadUserPermissions()
await Promise.all([fetchTags(), fetchShops(), fetchCoupons(), fetchVipLevelOptions()])
})
</script>
<style scoped>
.coupons {
padding: 0;
}
</style>
File diff suppressed because it is too large Load Diff
+583
View File
@@ -0,0 +1,583 @@
<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 {
DashboardOutlined,
FileProtectOutlined,
GiftOutlined,
HomeOutlined,
MessageOutlined,
SafetyCertificateOutlined,
SettingOutlined,
ShopOutlined,
ShoppingOutlined,
TagOutlined,
TeamOutlined,
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: 'dashboard',
title: '仪表盘',
path: '/admin/dashboard',
icon: DashboardOutlined,
permissionCode: 'dashboard:view'
},
{
key: 'users',
title: '用户管理',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view'
},
{
key: 'products',
title: '作品管理',
path: '/admin/products',
icon: ShopOutlined,
permissionCode: 'product:view'
},
{
key: 'coupons',
title: '优惠券',
path: '/admin/coupons',
icon: GiftOutlined,
permissionCode: 'coupon:view'
},
{
key: 'orders',
title: '订单管理',
path: '/admin/orders',
icon: ShoppingOutlined,
permissionCode: 'order:view'
},
{
key: 'tags',
title: '标签管理',
path: '/admin/tags',
icon: TagOutlined,
permissionCode: 'tag:view'
},
{
key: 'artists',
title: '美甲师管理',
path: '/admin/nail-artists',
icon: TeamOutlined,
permissionCode: 'nail_artist:view'
},
{
key: 'shops',
title: '店铺管理',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
},
{
key: 'permissions',
title: '权限管理',
path: '/admin/permissions',
icon: SafetyCertificateOutlined,
permissionCode: 'permission:view'
},
{
key: 'messages',
title: '消息发布',
path: '/admin/messages',
icon: MessageOutlined,
permissionCode: 'message:view'
},
{
key: 'announcements',
title: '公告管理',
path: '/admin/announcements',
icon: MessageOutlined,
permissionCode: 'announcement:view'
},
{
key: 'vip-plans',
title: 'VIP充值配置',
path: '/admin/vip-recharge-plans',
icon: GiftOutlined,
permissionCode: 'user:vip:manage'
},
{
key: 'parameters',
title: '参数管理',
path: '/admin/messagehub-push-configs',
icon: SettingOutlined,
permissionCode: 'messagehub:config:manage'
},
{
key: 'agreements',
title: '协议管理',
path: '/admin/legal-agreements',
icon: FileProtectOutlined,
permissionCode: 'legal_agreement:manage'
}
]
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>
@@ -0,0 +1,344 @@
<template>
<div class="inventory">
<a-page-header v-if="!isMobile" title="库存管理" sub-title="维护门店耗材库存和预警阈值" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">库存</span>
<h1 class="admin-page-intro__title">库存管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">物料 {{ pagination.total }}</span>
<span class="admin-page-chip">预警 {{ warningCount }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">库存列表</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="keyword"
placeholder="搜索物料或分类"
:style="isMobile ? { width: '100%' } : { width: '220px' }"
/>
<a-button type="primary" @click="openCreateModal">
<template #icon>
<PlusOutlined />
</template>
新增物料
</a-button>
</div>
</template>
<a-alert
v-if="warningCount"
class="inventory-alert"
type="warning"
show-icon
:message="`当前有 ${warningCount} 个物料低于预警阈值`"
/>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="filteredItems"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'stock'">
<a-tag :color="record.warning ? 'red' : 'green'">{{ numberText(record.stockQuantity) }} {{ record.unit || '' }}</a-tag>
</template>
<template v-else-if="column.key === 'warning'">{{ numberText(record.warningThreshold) }} {{ record.unit || '' }}</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 0 ? 'red' : 'green'">{{ record.status === 0 ? '停用' : '启用' }}</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="openAdjustModal(record as InventoryItemVO, 'IN')">入库</a-button>
<a-button type="link" size="small" @click="openAdjustModal(record as InventoryItemVO, 'OUT')">出库</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="filteredItems" empty-description="暂无库存物料">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.itemName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.category || '未分类' }}</div>
</div>
<a-tag :color="item.warning ? 'red' : 'green'">{{ item.warning ? '预警' : '正常' }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>库存</span>
<strong>{{ numberText(item.stockQuantity) }} {{ item.unit || '' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>预警阈值</span>
<strong>{{ numberText(item.warningThreshold) }} {{ item.unit || '' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="openAdjustModal(item, 'IN')">入库</a-button>
<a-button size="small" @click="openAdjustModal(item, 'OUT')">出库</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="itemModalOpen"
title="新增物料"
:desktop-width="680"
:confirm-loading="savingItem"
@ok="saveItem"
@cancel="closeItemModal"
>
<a-form ref="itemFormRef" :model="itemForm" :rules="itemRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="物料名称" name="itemName">
<a-input v-model:value="itemForm.itemName" placeholder="例如:底胶" />
</a-form-item>
<a-form-item label="分类">
<a-input v-model:value="itemForm.category" placeholder="例如:胶类/工具/耗材" />
</a-form-item>
<a-form-item label="单位">
<a-input v-model:value="itemForm.unit" placeholder="瓶、盒、个" />
</a-form-item>
<a-form-item label="初始库存">
<a-input-number v-model:value="itemForm.stockQuantity" :min="0" :step="1" style="width: 100%" />
</a-form-item>
<a-form-item label="预警阈值">
<a-input-number v-model:value="itemForm.warningThreshold" :min="0" :step="1" style="width: 100%" />
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="itemForm.status">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">停用</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="adjustModalOpen"
:title="adjustForm.changeType === 'OUT' ? '出库调整' : '入库调整'"
:desktop-width="600"
:confirm-loading="adjusting"
@ok="submitAdjust"
@cancel="closeAdjustModal"
>
<a-form ref="adjustFormRef" :model="adjustForm" :rules="adjustRules" layout="vertical">
<a-alert
v-if="adjustTarget"
class="inventory-alert"
type="info"
show-icon
:message="adjustTarget.itemName"
:description="`当前库存:${numberText(adjustTarget.stockQuantity)} ${adjustTarget.unit || ''}`"
/>
<a-form-item label="调整数量" name="changeQuantity">
<a-input-number v-model:value="adjustForm.changeQuantity" :step="1" style="width: 100%" />
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="adjustForm.remark" :rows="3" :maxlength="200" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { adminInventoryApi, type InventoryItemVO } from '@/api/admin'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const loading = ref(false)
const savingItem = ref(false)
const adjusting = ref(false)
const keyword = ref('')
const items = ref<InventoryItemVO[]>([])
const itemModalOpen = ref(false)
const adjustModalOpen = ref(false)
const adjustTarget = ref<InventoryItemVO | null>(null)
const itemFormRef = ref<FormInstance>()
const adjustFormRef = ref<FormInstance>()
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showTotal: (total: number) => `共 ${total} 条`
})
const itemForm = reactive({
itemName: '',
category: '',
unit: '',
stockQuantity: 0,
warningThreshold: 0,
status: 1
})
const adjustForm = reactive({
changeType: 'IN' as 'IN' | 'OUT',
changeQuantity: 1,
remark: ''
})
const itemRules = {
itemName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }]
} as any
const adjustRules = {
changeQuantity: [{ required: true, message: '请输入调整数量', trigger: 'blur' }]
} as any
const columns = [
{ title: '物料名称', dataIndex: 'itemName', key: 'itemName' },
{ title: '分类', dataIndex: 'category', key: 'category', width: 140 },
{ title: '库存', key: 'stock', width: 140 },
{ title: '预警阈值', key: 'warning', width: 140 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 130 }
]
const warningCount = computed(() => items.value.filter(item => item.warning).length)
const filteredItems = computed(() => {
const value = keyword.value.trim().toLowerCase()
if (!value) return items.value
return items.value.filter(item => [item.itemName, item.category, item.unit].join(' ').toLowerCase().includes(value))
})
const numberText = (value?: number) => Number(value || 0).toFixed(2).replace(/\.00$/, '')
const resetItemForm = () => {
Object.assign(itemForm, {
itemName: '',
category: '',
unit: '',
stockQuantity: 0,
warningThreshold: 0,
status: 1
})
}
const loadItems = async () => {
loading.value = true
try {
const result = await adminInventoryApi.listItems({
page: pagination.current,
size: pagination.pageSize
})
items.value = result.list || []
pagination.total = result.total || 0
} catch (error) {
console.error('加载库存失败:', error)
message.error('加载库存失败')
} finally {
loading.value = false
}
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
void loadItems()
}
const openCreateModal = () => {
resetItemForm()
itemModalOpen.value = true
}
const closeItemModal = () => {
itemModalOpen.value = false
itemFormRef.value?.resetFields()
}
const saveItem = async () => {
try {
await itemFormRef.value?.validate()
savingItem.value = true
await runWithGlobalLoading(async () => {
await adminInventoryApi.saveItem({ ...itemForm })
await loadItems()
})
message.success('物料已保存')
closeItemModal()
} catch (error: any) {
if (error?.errorFields) return
console.error('保存物料失败:', error)
message.error(error?.message || '保存物料失败')
} finally {
savingItem.value = false
}
}
const openAdjustModal = (record: InventoryItemVO, changeType: 'IN' | 'OUT') => {
adjustTarget.value = record
adjustForm.changeType = changeType
adjustForm.changeQuantity = changeType === 'OUT' ? -1 : 1
adjustForm.remark = ''
adjustModalOpen.value = true
}
const closeAdjustModal = () => {
adjustModalOpen.value = false
adjustTarget.value = null
adjustFormRef.value?.resetFields()
}
const submitAdjust = async () => {
if (!adjustTarget.value) return
const quantity = Number(adjustForm.changeQuantity || 0)
if (quantity === 0) {
message.warning('调整数量不能为 0')
return
}
adjusting.value = true
try {
await runWithGlobalLoading(async () => {
await adminInventoryApi.adjustStock(adjustTarget.value!.id, {
changeType: adjustForm.changeType,
changeQuantity: quantity,
remark: adjustForm.remark.trim() || undefined
})
await loadItems()
})
message.success('库存已调整')
closeAdjustModal()
} catch (error: any) {
console.error('库存调整失败:', error)
message.error(error?.message || '库存调整失败')
} finally {
adjusting.value = false
}
}
onMounted(loadItems)
</script>
<style scoped>
.inventory {
padding: 0;
}
.inventory-alert {
margin-bottom: 16px;
}
</style>
@@ -0,0 +1,214 @@
<template>
<div class="admin-page">
<div class="page-header">
<div>
<h2>协议管理</h2>
<p>维护用户登录/注册前需要阅读并同意的用户协议和隐私政策。</p>
</div>
<a-button type="primary" @click="openCreate">新增协议</a-button>
</div>
<a-table :columns="columns" :data-source="agreements" :loading="loading" row-key="id" :scroll="{ x: 'max-content' }" bordered>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.statusText || (record.status === 1 ? '已发布' : '草稿/停用') }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="openEdit(record)">编辑</a-button>
<a-button size="small" type="primary" :disabled="record.status === 1" @click="publishAgreement(record.id)">发布</a-button>
<a-button size="small" danger :disabled="record.status !== 1" @click="disableAgreement(record.id)">停用</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal
v-model:open="modalOpen"
:title="editingId ? '编辑协议' : '新增协议'"
width="760px"
:mask-closable="false"
:confirm-loading="saving"
@ok="saveAgreement"
>
<a-form layout="vertical">
<a-form-item label="协议类型">
<a-select v-model:value="form.agreementType">
<a-select-option value="USER_TERMS">用户协议</a-select-option>
<a-select-option value="PRIVACY_POLICY">隐私政策</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="标题">
<a-input v-model:value="form.title" placeholder="例如:Fingertip Designer 用户协议" />
</a-form-item>
<a-form-item label="版本">
<a-input v-model:value="form.version" placeholder="例如:2026-05-18" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="12" placeholder="请输入协议正文,支持 HTML / Markdown" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
/**
* Purpose: LegalAgreementAdminVO supports LegalAgreementsView.vue by holding or executing the legal agreement admin 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 { adminLegalAgreementApi, type LegalAgreementAdminVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
/**
* Purpose: loading supports LegalAgreementsView.vue by holding or executing the loading 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 loading = ref(false)
/**
* Purpose: saving supports LegalAgreementsView.vue by holding or executing the saving 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 saving = ref(false)
/**
* Purpose: modalOpen supports LegalAgreementsView.vue by holding or executing the modal open 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 modalOpen = ref(false)
/**
* Purpose: editingId supports LegalAgreementsView.vue by holding or executing the editing id 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 editingId = ref<IdType | null>(null)
/**
* Purpose: agreements supports LegalAgreementsView.vue by holding or executing the agreements 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 agreements = ref<LegalAgreementAdminVO[]>([])
/**
* Purpose: form supports LegalAgreementsView.vue by holding or executing the form 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 form = reactive({
agreementType: 'USER_TERMS' as 'USER_TERMS' | 'PRIVACY_POLICY',
title: '',
version: '',
content: ''
})
/**
* Purpose: columns supports LegalAgreementsView.vue by holding or executing the columns 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 columns = [
{ title: '类型', dataIndex: 'agreementTypeName', key: 'agreementTypeName' },
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '版本', dataIndex: 'version', key: 'version' },
{ title: '状态', dataIndex: 'status', key: 'status' },
{ title: '生效时间', dataIndex: 'effectiveTime', key: 'effectiveTime' },
{ title: '操作', key: 'action', width: 220 }
]
/**
* Purpose: loadAgreements supports LegalAgreementsView.vue by holding or executing the load agreements 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 loadAgreements = async () => {
loading.value = true
try {
agreements.value = await adminLegalAgreementApi.list() as unknown as LegalAgreementAdminVO[]
} finally {
loading.value = false
}
}
/**
* Purpose: resetForm supports LegalAgreementsView.vue by holding or executing the reset form 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 resetForm = () => {
editingId.value = null
form.agreementType = 'USER_TERMS'
form.title = ''
form.version = ''
form.content = ''
}
/**
* Purpose: openCreate supports LegalAgreementsView.vue by holding or executing the open create 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 openCreate = () => {
resetForm()
modalOpen.value = true
}
/**
* Purpose: openEdit supports LegalAgreementsView.vue by holding or executing the open edit 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 openEdit = (record: Record<string, any>) => {
const agreement = record as LegalAgreementAdminVO
editingId.value = agreement.id
form.agreementType = agreement.agreementType
form.title = agreement.title
form.version = agreement.version
form.content = agreement.content
modalOpen.value = true
}
/**
* Purpose: saveAgreement supports LegalAgreementsView.vue by holding or executing the save agreement 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 saveAgreement = async () => {
if (!form.title || !form.version || !form.content) {
message.warning('请填写完整协议信息')
return
}
saving.value = true
try {
if (editingId.value) {
await adminLegalAgreementApi.update(editingId.value, { ...form })
} else {
await adminLegalAgreementApi.create({ ...form })
}
message.success('保存成功')
modalOpen.value = false
await loadAgreements()
} finally {
saving.value = false
}
}
/**
* Purpose: publishAgreement supports LegalAgreementsView.vue by holding or executing the publish agreement 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 publishAgreement = async (id: IdType) => {
await adminLegalAgreementApi.publish(id)
message.success('发布成功')
await loadAgreements()
}
/**
* Purpose: disableAgreement supports LegalAgreementsView.vue by holding or executing the disable agreement 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 disableAgreement = async (id: IdType) => {
await adminLegalAgreementApi.disable(id)
message.success('已停用')
await loadAgreements()
}
onMounted(loadAgreements)
</script>
<style scoped>
.admin-page { padding: 16px; }
.page-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 16px; }
.page-header h2 { margin: 0 0 6px; }
.page-header p { margin: 0; color: var(--text-secondary); }
</style>
+405
View File
@@ -0,0 +1,405 @@
<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/dashboard',
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: 'vip-plans',
title: 'VIP充值配置',
description: '维护充值档位和 VIP 等级来源。',
path: '/admin/vip-recharge-plans',
icon: GiftOutlined,
permissionCode: 'user:vip:manage',
requireShopContext: true
},
{
key: 'parameters',
title: '参数管理',
description: '维护地图 Key、短信 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(144, 103, 84, 0.08);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.module-card:hover {
transform: translateY(-2px);
box-shadow: 0 18px 36px rgba(144, 103, 84, 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(144, 103, 84, 0.07);
}
.module-card:hover {
transform: none;
box-shadow: 0 8px 20px rgba(144, 103, 84, 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>
@@ -0,0 +1,480 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>参数管理</h2>
<p>统一维护地图 Key、短信 MessageHub 对接参数等平台级配置,仅平台管理员可修改。</p>
</div>
<a-button type="primary" @click="openCreate">新增配置</a-button>
</div>
<a-card title="地图服务配置" :bordered="false">
<a-form layout="vertical">
<a-form-item label="当前地图渠道">
<a-radio-group v-model:value="mapProvider">
<a-radio-button value="TENCENT">腾讯地图</a-radio-button>
<a-radio-button value="AMAP">高德地图</a-radio-button>
</a-radio-group>
</a-form-item>
<a-form-item label="腾讯 Web Key">
<a-input-password v-model:value="mapForms.tencentWeb.configValue" placeholder="用于后台腾讯地图选点和 Web 展示" />
</a-form-item>
<a-form-item label="高德 Web Key">
<a-input-password v-model:value="mapForms.amapWeb.configValue" placeholder="用于后台高德地图选点和 Web 展示" />
</a-form-item>
<a-form-item label="高德小程序 Key">
<a-input-password v-model:value="mapForms.amapMini.configValue" placeholder="用于后续小程序端高德 SDK / API 调用" />
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="mapRemark" :rows="2" placeholder="例如:默认使用腾讯地图,高德小程序 Key 单独申请填写" />
</a-form-item>
<a-form-item>
<a-space>
<a-switch v-model:checked="mapEnabled" checked-children="启用" un-checked-children="停用" />
<a-button type="primary" :loading="savingMap" @click="saveMapConfig">保存地图配置</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<a-card title="用户默认密码" :bordered="false">
<a-form layout="vertical">
<a-alert
type="info"
show-icon
message="后台新增用户时,密码留空会自动使用这里配置的默认密码。"
class="inline-alert"
/>
<a-form-item label="后台新增用户默认密码">
<a-input-password
v-model:value="defaultPasswordForm.configValue"
placeholder="请输入 8-32 位强密码"
autocomplete="new-password"
/>
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="defaultPasswordForm.remark" :rows="2" />
</a-form-item>
<a-form-item>
<a-space>
<a-switch v-model:checked="defaultPasswordEnabled" checked-children="启用" un-checked-children="停用" />
<a-button type="primary" :loading="savingDefaultPassword" @click="saveDefaultPasswordConfig">
保存默认密码
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<a-alert
type="info"
show-icon
message="这里不配置 Spug、阿里云等供应商密钥;真实短信通道仍在 MessageHub 中独立管理。"
/>
<a-table :columns="columns" :data-source="configs" :loading="loading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'scene'">
<strong>{{ record.sceneName }}</strong>
<div class="muted">{{ record.sceneCode }}</div>
</template>
<template v-else-if="column.key === 'messagehub'">
<div>队列:{{ record.queueName }}</div>
<div class="muted">来源:{{ record.sourceSystem }}</div>
</template>
<template v-else-if="column.key === 'template'">
<div>{{ record.templateCode }}</div>
<div class="muted">通道ID:{{ record.channelId || '由 MessageHub 自动选择' }}</div>
</template>
<template v-else-if="column.key === 'enabled'">
<a-switch :checked="record.enabled === 1" @change="(checked: any) => toggleStatus(record as MessageHubPushConfigVO, Boolean(checked))" />
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="openEdit(record as MessageHubPushConfigVO)">编辑</a-button>
<a-button size="small" @click="openTest(record as MessageHubPushConfigVO)">测试</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" :title="editingId ? '编辑配置' : '新增配置'" :mask-closable="false" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="业务场景">
<a-select v-model:value="form.sceneCode" :options="sceneOptions" show-search @change="handleSceneChange" />
</a-form-item>
<a-form-item label="场景名称">
<a-input v-model:value="form.sceneName" />
</a-form-item>
<a-form-item label="MessageHub 队列">
<a-input v-model:value="form.queueName" placeholder="smsQueue" />
</a-form-item>
<a-form-item label="来源系统">
<a-input v-model:value="form.sourceSystem" placeholder="yuminail" />
</a-form-item>
<a-form-item label="模板编码">
<a-input v-model:value="form.templateCode" placeholder="MessageHub 中维护的模板编码" />
</a-form-item>
<a-form-item label="指定通道 ID">
<a-input-number v-model:value="form.channelId" :min="1" style="width: 100%" placeholder="不填则由 MessageHub 选择" />
</a-form-item>
<a-form-item label="发送方式">
<a-select v-model:value="form.sendMethod" allow-clear :options="sendMethodOptions" />
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="form.remark" :rows="3" />
</a-form-item>
</a-form>
</a-modal>
<a-modal v-model:open="testOpen" title="测试投递" :mask-closable="false" @ok="submitTest" :confirm-loading="testing">
<a-form layout="vertical">
<a-form-item label="测试手机号">
<a-input v-model:value="testPhone" :maxlength="11" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* MessageHubPushConfigsView 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 { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
/**
* Purpose: MessageHubPushConfigVO supports MessageHubPushConfigsView.vue by holding or executing the message hub push config 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 {
adminMessageHubPushConfigApi,
adminSystemParameterConfigApi,
type MessageHubPushConfigVO,
type SystemParameterConfigVO
} from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** testing is a reactive state variable used by the template and event handlers. */
const testing = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
/** testOpen is a reactive state variable used by the template and event handlers. */
const testOpen = ref(false)
/**
* Purpose: editingId supports MessageHubPushConfigsView.vue by holding or executing the editing id 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 editingId = ref<any>()
/**
* Purpose: testingId supports MessageHubPushConfigsView.vue by holding or executing the testing id 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 testingId = ref<any>()
/** testPhone is a reactive state variable used by the template and event handlers. */
const testPhone = ref('')
/**
* Purpose: configs supports MessageHubPushConfigsView.vue by holding or executing the configs 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 configs = ref<MessageHubPushConfigVO[]>([])
/**
* Purpose: savingMap supports MessageHubPushConfigsView.vue by holding or executing the saving map 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 savingMap = ref(false)
const savingDefaultPassword = ref(false)
/**
* Purpose: mapEnabled supports MessageHubPushConfigsView.vue by holding or executing the map enabled 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 mapEnabled = ref(true)
const defaultPasswordEnabled = ref(true)
/**
* Purpose: mapProvider supports MessageHubPushConfigsView.vue by holding or executing the map provider 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 mapProvider = ref<'TENCENT' | 'AMAP'>('TENCENT')
/**
* Purpose: mapRemark supports MessageHubPushConfigsView.vue by holding or executing the map remark 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 mapRemark = ref('地图渠道由平台管理员选择;高德 Web Key 与高德小程序 Key 分开填写。')
/**
* Purpose: createMapForm supports MessageHubPushConfigsView.vue by holding or executing the create map form 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 createMapForm = (configKey: string, configName: string, remark: string) => ({
configGroup: 'MAP',
configKey,
configName,
configValue: '',
enabled: 1,
remark
})
/**
* Purpose: mapForms supports MessageHubPushConfigsView.vue by holding or executing the map forms 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 mapForms = reactive({
provider: createMapForm('MAP_PROVIDER', '当前地图渠道', 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道'),
tencentWeb: createMapForm('TENCENT_MAP_KEY', '腾讯 Web Key', '用于后台腾讯地图选点和 Web 展示'),
amapWeb: createMapForm('AMAP_WEB_KEY', '高德 Web Key', '用于后台高德地图选点和 Web 展示'),
amapMini: createMapForm('AMAP_MINI_KEY', '高德小程序 Key', '用于后续小程序端高德 SDK / API 调用')
})
const defaultPasswordForm = reactive<SystemParameterConfigVO>({
configGroup: 'USER',
configKey: 'DEFAULT_PASSWORD',
configName: '后台新增用户默认密码',
configValue: 'Fingertip@123',
enabled: 1,
remark: '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类'
})
/**
* Purpose: sceneOptions supports MessageHubPushConfigsView.vue by holding or executing the scene 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.
*/
const sceneOptions = [
{ label: '用户注册验证码', value: 'USER_REGISTER_SMS_CODE' },
{ label: '手机号登录验证码', value: 'USER_LOGIN_SMS_CODE' },
{ label: '找回密码验证码', value: 'USER_RESET_PASSWORD_SMS_CODE' },
{ label: '绑定手机号验证码', value: 'USER_BIND_PHONE_SMS_CODE' },
{ label: '修改手机号验证码', value: 'USER_CHANGE_PHONE_SMS_CODE' },
{ label: '修改密码验证码', value: 'USER_CHANGE_PASSWORD_SMS_CODE' }
]
/**
* Purpose: sendMethodOptions supports MessageHubPushConfigsView.vue by holding or executing the send method 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.
*/
const sendMethodOptions = [
{ label: 'SPUG', value: 'SPUG' },
{ label: 'OTHER', value: 'OTHER' }
]
/**
* Purpose: form supports MessageHubPushConfigsView.vue by holding or executing the form 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 form = reactive<any>({
sceneCode: 'USER_LOGIN_SMS_CODE',
sceneName: '手机号登录验证码',
platform: 'SMS',
msgType: 'VERIFICATION',
queueName: 'smsQueue',
sourceSystem: 'yuminail',
templateCode: 'SPUG0001',
channelId: undefined,
sendMethod: 'SPUG',
enabled: 1,
remark: ''
})
/**
* Purpose: columns supports MessageHubPushConfigsView.vue by holding or executing the columns 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 columns = [
{ title: '业务场景', key: 'scene' },
{ title: 'MessageHub', key: 'messagehub' },
{ title: '模板/通道', key: 'template' },
{ title: '消息类型', dataIndex: 'msgType', key: 'msgType', width: 110 },
{ title: '启用', key: 'enabled', width: 90 },
{ title: '操作', key: 'action', width: 150 }
]
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [messageConfigs, mapConfigs, userConfigs] = await Promise.all([
adminMessageHubPushConfigApi.listConfigs(),
adminSystemParameterConfigApi.listConfigs('MAP'),
adminSystemParameterConfigApi.listConfigs('USER')
])
configs.value = messageConfigs
const providerConfig = mapConfigs.find(item => item.configKey === 'MAP_PROVIDER')
const tencentMapConfig = mapConfigs.find(item => item.configKey === 'TENCENT_MAP_KEY')
const amapWebConfig = mapConfigs.find(item => item.configKey === 'AMAP_WEB_KEY')
const amapMiniConfig = mapConfigs.find(item => item.configKey === 'AMAP_MINI_KEY')
if (providerConfig?.configValue) {
mapProvider.value = providerConfig.configValue === 'AMAP' ? 'AMAP' : 'TENCENT'
mapEnabled.value = providerConfig.enabled === 1
Object.assign(mapForms.provider, providerConfig)
}
if (tencentMapConfig) Object.assign(mapForms.tencentWeb, tencentMapConfig)
if (amapWebConfig) Object.assign(mapForms.amapWeb, amapWebConfig)
if (amapMiniConfig) Object.assign(mapForms.amapMini, amapMiniConfig)
const defaultPasswordConfig = userConfigs.find(item => item.configKey === 'DEFAULT_PASSWORD')
if (defaultPasswordConfig) {
Object.assign(defaultPasswordForm, defaultPasswordConfig)
defaultPasswordEnabled.value = defaultPasswordConfig.enabled === 1
}
} finally {
loading.value = false
}
}
/**
* Purpose: saveMapConfig supports MessageHubPushConfigsView.vue by holding or executing the save map config 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 saveMapConfig = async () => {
savingMap.value = true
try {
await adminSystemParameterConfigApi.saveConfig({
...mapForms.provider,
configValue: mapProvider.value,
enabled: mapEnabled.value ? 1 : 0
})
await adminSystemParameterConfigApi.saveConfig({
...mapForms.tencentWeb,
enabled: mapEnabled.value ? 1 : 0
})
await adminSystemParameterConfigApi.saveConfig({
...mapForms.amapWeb,
enabled: mapEnabled.value ? 1 : 0
})
await adminSystemParameterConfigApi.saveConfig({
...mapForms.amapMini,
enabled: mapEnabled.value ? 1 : 0
})
message.success('地图配置已保存')
await load()
} finally {
savingMap.value = false
}
}
const validateDefaultPasswordInput = () => {
const password = defaultPasswordForm.configValue.trim()
if (password.length < 8 || password.length > 32) {
message.warning('默认密码长度需为 8-32 位')
return false
}
const categoryCount = [
/\d/.test(password),
/[a-z]/.test(password),
/[A-Z]/.test(password),
/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)
].filter(Boolean).length
if (categoryCount < 3) {
message.warning('默认密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类')
return false
}
return true
}
const saveDefaultPasswordConfig = async () => {
if (!validateDefaultPasswordInput()) {
return
}
savingDefaultPassword.value = true
try {
await adminSystemParameterConfigApi.saveConfig({
...defaultPasswordForm,
configValue: defaultPasswordForm.configValue.trim(),
enabled: defaultPasswordEnabled.value ? 1 : 0
})
message.success('默认密码已保存')
await load()
} finally {
savingDefaultPassword.value = false
}
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => Object.assign(form, {
sceneCode: 'USER_LOGIN_SMS_CODE',
sceneName: '手机号登录验证码',
platform: 'SMS',
msgType: 'VERIFICATION',
queueName: 'smsQueue',
sourceSystem: 'yuminail',
templateCode: 'SPUG0001',
channelId: undefined,
sendMethod: 'SPUG',
enabled: 1,
remark: ''
})
/** handleSceneChange is a local helper used by this page script. */
const handleSceneChange = (value: any) => {
const option = sceneOptions.find(item => item.value === String(value || ''))
if (option) form.sceneName = option.label
}
/** openCreate is a local helper used by this page script. */
const openCreate = () => { editingId.value = undefined; resetForm(); formOpen.value = true }
/** openEdit is a local helper used by this page script. */
const openEdit = (record: MessageHubPushConfigVO) => {
editingId.value = record.id
Object.assign(form, record)
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.sceneCode || !form.sceneName || !form.queueName || !form.sourceSystem || !form.templateCode) {
message.warning('请填写场景、队列、来源系统和模板编码')
return
}
saving.value = true
try {
if (editingId.value) {
await adminMessageHubPushConfigApi.updateConfig(editingId.value, form)
} else {
await adminMessageHubPushConfigApi.createConfig(form)
}
message.success('配置已保存')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** toggleStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const toggleStatus = async (record: MessageHubPushConfigVO, checked: boolean) => {
await adminMessageHubPushConfigApi.updateStatus(record.id, checked ? 1 : 0)
record.enabled = checked ? 1 : 0
}
/** openTest is a local helper used by this page script. */
const openTest = (record: MessageHubPushConfigVO) => {
testingId.value = record.id
testPhone.value = ''
testOpen.value = true
}
/** submitTest is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submitTest = async () => {
if (!/^1[3-9]\d{9}$/.test(testPhone.value)) {
message.warning('请输入正确的测试手机号')
return
}
testing.value = true
try {
await adminMessageHubPushConfigApi.testConfig(testingId.value, testPhone.value)
message.success('测试消息已投递到 MessageHub')
testOpen.value = false
} finally {
testing.value = false
}
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p, .muted { margin: 0; color: var(--text-secondary); }
.inline-alert { margin-bottom: 16px; }
</style>
@@ -0,0 +1,708 @@
<template>
<div class="nail-artists">
<a-page-header v-if="!isMobile" title="美甲师管理" sub-title="管理美甲师详细信息" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">美甲师管理</h1>
<p class="admin-page-intro__subtitle">
把状态、技能和作品挂载关系收成单列卡片,手机端可以直接查看和编辑。
</p>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">美甲师 {{ nailArtistList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">
美甲师列表
</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="searchText"
placeholder="搜索美甲师姓名"
:style="isMobile ? { width: '100%' } : { width: '250px' }"
@search="handleSearch"
/>
</div>
</template>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="nailArtistList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="userId"
:scroll="{ x: 'max-content' }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="getStatusColor(record.status)">
{{ getStatusText(record.status) }}
</a-tag>
</template>
<template v-else-if="column.key === 'userTypeName'">
<a-tag :color="record.userType === 2 ? 'gold' : 'blue'">
{{ record.userTypeName || (record.userType === 2 ? '店长' : '美甲师') }}
</a-tag>
</template>
<template v-else-if="column.key === 'participateProduction'">
<a-tag :color="record.participateProduction === 1 ? 'green' : 'default'">
{{ record.participateProduction === 1 ? '参与制作' : '不参与' }}
</a-tag>
</template>
<template v-else-if="column.key === 'workTime'">
{{ formatWorkTime(record) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('nail_artist:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('nail_artist:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="nailArtistList" item-key="userId" empty-description="暂无美甲师数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.nickname }}</div>
<div class="admin-mobile-card__subtitle">{{ item.shopName || '未绑定店铺' }}</div>
</div>
<a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>身份</span>
<strong>{{ item.identity || '--' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>从业年限</span>
<strong>{{ item.experience ?? '--' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>评分</span>
<strong>{{ item.rating || '--' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('nail_artist:view')" size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('nail_artist:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<!-- 编辑美甲师信息模态框 -->
<AdminResponsiveModal
v-model:open="modalVisible"
title="编辑美甲师信息"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
:desktop-width="800"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="美甲师姓名" name="nickname">
<a-input v-model:value="formState.nickname" :disabled="true" />
</a-form-item>
<a-form-item label="身份" name="identity">
<a-input
v-model:value="formState.identity"
placeholder="请输入身份"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="从业年限" name="experience">
<a-input-number
v-model:value="formState.experience"
:min="0"
placeholder="请输入从业年限"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="技能标签" name="skills">
<a-select
v-model:value="formState.skills"
mode="multiple"
placeholder="请选择技能标签"
:loading="tagLoading"
>
<a-select-option
v-for="tag in tagList"
:key="tag.id"
:value="tag.id.toString()"
>
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="状态" name="status">
<a-select
v-model:value="formState.status"
placeholder="请选择状态"
:disabled="!isShopOwner"
>
<a-select-option :value="1">营业中</a-select-option>
<a-select-option :value="0">休息中</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="参与制作" name="participateProduction">
<a-switch
v-model:checked="formState.participateProduction"
:checked-value="1"
:un-checked-value="0"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="工作时间">
<a-input v-model:value="formState.workStartTime" type="time" placeholder="开始" />
<span class="time-separator">至</span>
<a-input v-model:value="formState.workEndTime" type="time" placeholder="结束" />
</a-form-item>
<a-form-item label="作品" name="portfolio">
<a-select
v-model:value="formState.portfolio"
mode="multiple"
placeholder="请选择作品作品"
:loading="productLoading"
>
<a-select-option
v-for="product in productList"
:key="product.id"
:value="product.id.toString()"
>
{{ product.title }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="评分">
<a-input v-model:value="formState.rating" :disabled="true" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
<!-- 查看美甲师详情模态框 -->
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看美甲师详情"
:footer="null"
@cancel="handleViewModalCancel"
:desktop-width="600"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<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.shopName" :disabled="true" />
</a-form-item>
<a-form-item label="身份">
<a-input v-model:value="viewFormState.identity" :disabled="true" />
</a-form-item>
<a-form-item label="从业年限">
<a-input v-model:value="viewFormState.experience" :disabled="true" />
</a-form-item>
<a-form-item label="技能标签">
<a-input v-model:value="viewFormState.skillsText" :disabled="true" />
</a-form-item>
<a-form-item label="状态">
<a-input v-model:value="viewFormState.statusText" :disabled="true" />
</a-form-item>
<a-form-item label="人员类型">
<a-input v-model:value="viewFormState.userTypeName" :disabled="true" />
</a-form-item>
<a-form-item label="工作时间">
<a-input v-model:value="viewFormState.workTime" :disabled="true" />
</a-form-item>
<a-form-item label="评分">
<a-input v-model:value="viewFormState.rating" :disabled="true" />
</a-form-item>
<a-form-item label="作品">
<a-input v-model:value="viewFormState.portfolioText" :disabled="true" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
/**
* NailArtistsView 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 { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import DraftActions from '@/components/DraftActions.vue'
/**
* Purpose: NailArtistInfoVO supports NailArtistsView.vue by holding or executing the nail artist info 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 { adminNailArtistApi, type NailArtistInfoVO } from '@/api/admin'
/**
* Purpose: Tag supports NailArtistsView.vue by holding or executing the tag 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 { adminTagApi, type Tag } from '@/api/admin'
/**
* Purpose: Product supports NailArtistsView.vue by holding or executing the product 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 { adminProductApi, type Product } from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
isAdmin.value = userInfo.type === 4
isShopOwner.value = userInfo.type === 2
return userInfo
}
} catch (error: any) {
console.error('获取当前用户信息失败', error)
}
return null
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** tagLoading is a reactive state variable used by the template and event handlers. */
const tagLoading = ref(false)
/** productLoading is a reactive state variable used by the template and event handlers. */
const productLoading = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
/**
* Purpose: nailArtistList supports NailArtistsView.vue by holding or executing the nail artist list 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 nailArtistList = ref<NailArtistInfoVO[]>([])
/**
* Purpose: tagList supports NailArtistsView.vue by holding or executing the tag list 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 tagList = ref<Tag[]>([])
/**
* Purpose: productList supports NailArtistsView.vue by holding or executing the product list 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 productList = ref<Product[]>([])
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
/** isShopOwner is a reactive state variable used by the template and event handlers. */
const isShopOwner = ref(false)
/**
* Purpose: formRef supports NailArtistsView.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>()
/**
* Purpose: currentNailArtist supports NailArtistsView.vue by holding or executing the current nail artist 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 currentNailArtist = ref<NailArtistInfoVO | null>(null)
/**
* Purpose: currentUserInfo supports NailArtistsView.vue by holding or executing the current 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 currentUserInfo = getCurrentUserInfo()
/**
* Purpose: draftSavedAt supports NailArtistsView.vue by holding or executing the draft saved at 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 draftSavedAt = ref<number | null>(null)
/**
* Purpose: viewFormState supports NailArtistsView.vue by holding or executing the view 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 viewFormState = reactive({
nickname: '',
shopName: '',
identity: '',
experience: '',
skillsText: '',
statusText: '',
userTypeName: '',
workTime: '',
rating: '',
portfolioText: ''
})
/**
* Purpose: pagination supports NailArtistsView.vue by holding or executing the pagination 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 pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: formState supports NailArtistsView.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({
userId: 0,
identity: '',
experience: 0,
skills: [] as string[],
rating: 0,
status: 1,
participateProduction: 1,
workStartTime: '',
workEndTime: '',
portfolio: [] as string[],
nickname: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-nail-artists', 'edit', currentNailArtist.value?.userId ?? formState.userId ?? 'unknown')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
identity: formState.identity,
experience: formState.experience,
skills: [...formState.skills],
status: formState.status,
participateProduction: formState.participateProduction,
workStartTime: formState.workStartTime,
workEndTime: formState.workEndTime,
portfolio: [...formState.portfolio]
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, {
identity: draft.payload.identity ?? formState.identity,
experience: typeof draft.payload.experience === 'number' ? draft.payload.experience : formState.experience,
skills: Array.isArray(draft.payload.skills) ? draft.payload.skills : formState.skills,
status: typeof draft.payload.status === 'number'
? (draft.payload.status === 0 ? 0 : 1)
: formState.status,
participateProduction: typeof draft.payload.participateProduction === 'number'
? (draft.payload.participateProduction === 1 ? 1 : 0)
: formState.participateProduction,
workStartTime: draft.payload.workStartTime ?? formState.workStartTime,
workEndTime: draft.payload.workEndTime ?? formState.workEndTime,
portfolio: Array.isArray(draft.payload.portfolio) ? draft.payload.portfolio : formState.portfolio
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/**
* Purpose: formRules supports NailArtistsView.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 = {
identity: [{ required: true, message: '请输入身份', trigger: 'blur' }],
experience: [{ required: true, message: '请输入从业年限', trigger: 'blur' }],
skills: [{ required: true, message: '请选择技能标签', trigger: 'change' }],
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
portfolio: [{ required: true, message: '请选择作品作品', trigger: 'change' }]
} as any
/**
* Purpose: columns supports NailArtistsView.vue by holding or executing the columns 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 columns = [
{ title: '美甲师姓名', dataIndex: 'nickname', key: 'nickname' },
{ title: '所属店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '人员类型', key: 'userTypeName', width: 110 },
{ title: '参与制作', key: 'participateProduction', width: 120 },
{ title: '工作时间', key: 'workTime', width: 150 },
{ title: '身份', dataIndex: 'identity', key: 'identity' },
{ title: '从业年限', dataIndex: 'experience', key: 'experience' },
{ title: '评分', dataIndex: 'rating', key: 'rating' },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** getStatusText is a local helper used by this page script. */
const getStatusText = (status: number) => {
return status === 1 ? '营业中' : '休息中'
}
/** getStatusColor is a local helper used by this page script. */
const getStatusColor = (status: number) => {
return status === 1 ? 'green' : 'default'
}
/** formatWorkTime is a local helper used by this page script. */
const formatWorkTime = (record: Partial<NailArtistInfoVO>) => {
const start = record.workStartTime ? String(record.workStartTime).slice(0, 5) : ''
const end = record.workEndTime ? String(record.workEndTime).slice(0, 5) : ''
return start && end ? `${start} - ${end}` : '--'
}
/** normalizeTime is a local helper used by this page script. */
const normalizeTime = (value?: string) => value ? (String(value).length === 5 ? `${value}:00` : String(value)) : undefined
/** fetchTagList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTagList = async () => {
tagLoading.value = true
try {
const res = await adminTagApi.listAllTags() as unknown as Tag[]
tagList.value = res || []
} catch (error) {
console.error('获取标签列表失败:', error)
} finally {
tagLoading.value = false
}
}
/** fetchProductList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProductList = async () => {
productLoading.value = true
try {
const params: any = {
page: 1,
size: 1000
}
if (currentUserInfo && currentUserInfo.type !== 4 && currentUserInfo.shopId) {
params.shopId = currentUserInfo.shopId
}
const res = await adminProductApi.listProducts(params) as unknown as { list: Product[] }
productList.value = res.list || []
} catch (error) {
console.error('获取作品列表失败:', error)
} finally {
productLoading.value = false
}
}
/** fetchNailArtistList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchNailArtistList = async () => {
loading.value = true
try {
const res = await adminNailArtistApi.listNailArtists() as unknown as NailArtistInfoVO[]
let filteredList = res || []
// 按搜索词过滤
if (searchText.value) {
filteredList = filteredList.filter((item: NailArtistInfoVO) =>
item.nickname?.includes(searchText.value)
)
}
nailArtistList.value = filteredList
pagination.total = filteredList.length || 0
} catch (error) {
message.error('获取美甲师列表失败')
} finally {
loading.value = false
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchNailArtistList())
}
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
await runWithGlobalLoading(() => fetchNailArtistList())
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: Record<string, any>) => {
currentNailArtist.value = record as NailArtistInfoVO
const lockedFields = {
userId: record.userId,
rating: record.rating || 0,
nickname: record.nickname || ''
}
Object.assign(formState, {
identity: record.identity || '',
experience: record.experience || 0,
skills: record.skills ? record.skills.split(',').filter(Boolean) : [],
status: record.status || 1,
participateProduction: record.participateProduction ?? (record.userType === 3 ? 1 : 0),
workStartTime: record.workStartTime || '',
workEndTime: record.workEndTime || '',
portfolio: record.portfolio ? record.portfolio.split(',').filter(Boolean) : [],
...lockedFields
})
restoreDraft()
Object.assign(formState, lockedFields)
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: Record<string, any>) => {
const nailArtist = record as NailArtistInfoVO
// 构建技能标签文本
const skillsArray = nailArtist.skills ? nailArtist.skills.split(',').filter(Boolean) : []
const skillsText = skillsArray.map(skillId => {
const tag = tagList.value.find(t => t.id.toString() === skillId)
return tag ? tag.tagName : skillId
}).join(', ')
// 构建作品文本
const portfolioArray = nailArtist.portfolio ? nailArtist.portfolio.split(',').filter(Boolean) : []
const portfolioText = portfolioArray.map(productId => {
const product = productList.value.find(p => p.id.toString() === productId)
return product ? product.title : productId
}).join(', ')
Object.assign(viewFormState, {
nickname: nailArtist.nickname || '',
shopName: nailArtist.shopName || '',
identity: nailArtist.identity || '',
experience: (nailArtist.experience || 0).toString(),
skillsText: skillsText,
statusText: getStatusText(nailArtist.status || 1),
userTypeName: nailArtist.userTypeName || (nailArtist.userType === 2 ? '店长' : '美甲师'),
workTime: formatWorkTime(nailArtist),
rating: (nailArtist.rating || 0).toString(),
portfolioText: portfolioText
})
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
const targetUserId = currentNailArtist.value?.userId ?? formState.userId
if (!targetUserId) {
message.error('未获取到当前美甲师信息,请关闭弹窗后重试')
return
}
modalLoading.value = true
await runWithGlobalLoading(async () => {
// 准备提交数据
const submitData = {
userId: targetUserId,
identity: formState.identity,
experience: formState.experience,
rating: formState.rating,
status: formState.status,
participateProduction: formState.participateProduction,
workStartTime: normalizeTime(formState.workStartTime),
workEndTime: normalizeTime(formState.workEndTime),
skills: formState.skills.join(','),
portfolio: formState.portfolio.join(',')
}
await adminNailArtistApi.saveNailArtistInfo(submitData)
message.success('保存成功')
handleClearDraft(false)
modalVisible.value = false
await fetchNailArtistList()
})
} catch (error) {
console.error(error)
const errorMessage = (error as Error)?.message
if (errorMessage) {
message.error(errorMessage)
return
}
message.error('操作失败')
} finally {
modalLoading.value = false
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
currentNailArtist.value = null
formRef.value?.resetFields()
}
onMounted(async () => {
await loadUserPermissions()
fetchTagList()
fetchProductList()
fetchNailArtistList()
})
</script>
<style scoped>
.nail-artists {
padding: 0;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,835 @@
<template>
<div class="permissions">
<a-page-header v-if="!isMobile" title="权限管理" sub-title="管理系统权限和用户权限分配" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">权限管理</h1>
<p class="admin-page-intro__subtitle">
手机端拆成“权限列表”和“用户权限”两段流程,先选人再分配,避免保留桌面双栏布局。
</p>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">权限 {{ permissionList.length }}</span>
<span class="admin-page-chip">用户 {{ filteredUserList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<a-tabs v-model:activeKey="activeTab">
<a-tab-pane key="permissions" tab="权限列表">
<div style="margin-bottom: 16px;" :style="isMobile ? {} : { textAlign: 'right' }">
<a-button v-if="!isMobile && hasPermission('permission:create')" type="primary" @click="showAddPermissionModal">
<template #icon>
<PlusOutlined />
</template>
新增权限
</a-button>
</div>
<a-table
v-if="!isMobile"
:columns="permissionColumns"
:data-source="permissionList"
:loading="loading"
:pagination="permissionPagination"
:scroll="{ x: 'max-content' }"
@change="handlePermissionTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'permissionGroup'">
<a-tag color="purple">{{ record.permissionGroup }}</a-tag>
</template>
<template v-else-if="column.key === 'permissionCode'">
<div style="max-width: 220px;">
<TableEllipsisText :text="record.permissionCode" />
</div>
</template>
<template v-else-if="column.key === 'permissionName'">
<div style="max-width: 180px;">
<TableEllipsisText :text="record.permissionName" />
</div>
</template>
<template v-else-if="column.key === 'description'">
<div style="max-width: 320px;">
<TableEllipsisText :text="record.description" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('permission:edit')" type="link" size="small" @click="showEditPermissionModal(record)">
编辑
</a-button>
<a-popconfirm
v-if="hasPermission('permission:delete')"
title="确定要删除这个权限吗?"
@confirm="handleDeletePermission(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="permissionList" empty-description="暂无权限数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.permissionName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.permissionCode }}</div>
</div>
<a-tag color="purple">{{ item.permissionGroup }}</a-tag>
</div>
<div class="admin-mobile-card__description">{{ item.description }}</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>创建时间</span>
<strong>{{ item.createTime }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('permission:edit')" size="small" @click="showEditPermissionModal(item)">编辑</a-button>
<a-button v-if="hasPermission('permission:delete')" size="small" danger @click="handleDeletePermission(item)">删除</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-tab-pane>
<a-tab-pane v-if="hasPermission('permission:assign')" key="user-permissions" tab="用户权限分配">
<template v-if="!isMobile">
<a-row :gutter="16">
<a-col :span="8">
<a-card title="选择用户" :bordered="false">
<a-input-search
v-model:value="userSearchText"
placeholder="搜索用户"
style="margin-bottom: 16px"
@search="handleUserSearch"
/>
<a-list
:data-source="filteredUserList"
:loading="userLoading"
item-layout="horizontal"
size="small"
>
<template #renderItem="{ item }">
<a-list-item
:class="{ selected: sameId(selectedUser?.id, item.id) }"
style="cursor: pointer;"
@click="selectUser(item)"
>
<a-list-item-meta>
<template #avatar>
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
</template>
<template #title>{{ item.nickname }}</template>
<template #description>{{ item.account }} - {{ getUserTypeText(item.type) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</a-col>
<a-col :span="16">
<a-card
title="分配权限"
:bordered="false"
>
<template #extra>
<a-button v-if="selectedUser && hasPermission('permission:assign')" type="primary" @click="handleSaveUserPermissions">
保存权限
</a-button>
</template>
<template v-if="selectedUser">
<a-alert
:message="`当前用户: ${selectedUser.nickname}`"
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-alert
v-if="disabledPermissionCount > 0"
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁止选择`"
type="warning"
show-icon
style="margin-bottom: 16px"
/>
<a-spin :spinning="assignLoading">
<a-checkbox-group v-model:value="selectedPermissions">
<a-collapse v-model:activeKey="activeCollapseKeys">
<a-collapse-panel
v-for="(permissions, group) in groupedPermissions"
:key="group"
:header="group"
>
<a-space direction="vertical" style="width: 100%">
<a-checkbox
v-for="permission in permissions"
:key="permission.id"
:value="permission.id"
:disabled="isPermissionDisabled(permission)"
>
{{ permission.permissionName }}
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
({{ permission.permissionCode }})
</span>
<span
v-if="isPermissionDisabled(permission)"
style="color: #ff4d4f; font-size: 12px; margin-left: 8px;"
>
不可分配
</span>
</a-checkbox>
</a-space>
</a-collapse-panel>
</a-collapse>
</a-checkbox-group>
</a-spin>
</template>
<a-empty v-else description="请先选择一个用户" />
</a-card>
</a-col>
</a-row>
</template>
<template v-else>
<div class="mobile-permission-flow">
<template v-if="mobilePermissionStep === 'users' || !selectedUser">
<a-input-search
v-model:value="userSearchText"
placeholder="搜索用户"
style="margin-bottom: 16px"
@search="handleUserSearch"
/>
<AdminMobileCardList :items="filteredUserList" empty-description="暂无可分配权限的用户">
<template #item="{ item }">
<article class="admin-mobile-card" @click="selectUser(item)">
<div class="admin-mobile-card__head">
<div class="mobile-user-pick">
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.nickname }}</div>
<div class="admin-mobile-card__subtitle">{{ item.account }} · {{ getUserTypeText(item.type) }}</div>
</div>
</div>
<span class="admin-mobile-card__badge">选择</span>
</div>
</article>
</template>
</AdminMobileCardList>
</template>
<template v-else>
<div class="mobile-assign-actions">
<a-button @click="mobilePermissionStep = 'users'">返回选用户</a-button>
<a-button type="primary" @click="handleSaveUserPermissions">保存权限</a-button>
</div>
<a-alert
:message="`当前用户: ${selectedUser.nickname}`"
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-alert
v-if="disabledPermissionCount > 0"
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁用`"
type="warning"
show-icon
style="margin-bottom: 16px"
/>
<a-spin :spinning="assignLoading">
<a-checkbox-group v-model:value="selectedPermissions" style="width: 100%">
<a-collapse v-model:activeKey="activeCollapseKeys">
<a-collapse-panel
v-for="(permissions, group) in groupedPermissions"
:key="group"
:header="group"
>
<a-space direction="vertical" style="width: 100%">
<a-checkbox
v-for="permission in permissions"
:key="permission.id"
:value="permission.id"
:disabled="isPermissionDisabled(permission)"
>
{{ permission.permissionName }}
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
({{ permission.permissionCode }})
</span>
</a-checkbox>
</a-space>
</a-collapse-panel>
</a-collapse>
</a-checkbox-group>
</a-spin>
</template>
</div>
</template>
</a-tab-pane>
</a-tabs>
</a-card>
<AdminResponsiveModal
v-model:open="permissionModalVisible"
:title="isEditPermission ? '编辑权限' : '新增权限'"
@ok="handlePermissionModalOk"
@cancel="handlePermissionModalCancel"
:confirmLoading="permissionModalLoading"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="permissionFormRef"
:model="permissionFormState"
:rules="permissionFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="权限编码" name="permissionCode">
<a-input v-model:value="permissionFormState.permissionCode" placeholder="例如:product:add" />
</a-form-item>
<a-form-item label="权限名称" name="permissionName">
<a-input v-model:value="permissionFormState.permissionName" placeholder="例如:添加作品" />
</a-form-item>
<a-form-item label="权限分组" name="permissionGroup">
<a-select v-model:value="permissionFormState.permissionGroup" placeholder="请选择权限分组">
<a-select-option value="作品管理">作品管理</a-select-option>
<a-select-option value="店铺管理">店铺管理</a-select-option>
<a-select-option value="用户管理">用户管理</a-select-option>
<a-select-option value="权限管理">权限管理</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="权限描述" name="description">
<a-textarea
v-model:value="permissionFormState.description"
placeholder="请输入权限描述"
:rows="3"
/>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && activeTab === 'permissions' && hasPermission('permission:create') && !permissionModalVisible"
label="新增权限"
@click="showAddPermissionModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* PermissionsView 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 { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
import { DEFAULT_AVATAR } from '@/constants'
/**
* Purpose: UserVO supports PermissionsView.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 PermissionsView.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 { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** activeTab is a reactive state variable used by the template and event handlers. */
const activeTab = ref('permissions')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/**
* Purpose: permissionList supports PermissionsView.vue by holding or executing the permission list 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 permissionList = ref<PermissionVO[]>([])
/** permissionModalVisible is a reactive state variable used by the template and event handlers. */
const permissionModalVisible = ref(false)
/** permissionModalLoading is a reactive state variable used by the template and event handlers. */
const permissionModalLoading = ref(false)
/** isEditPermission is a reactive state variable used by the template and event handlers. */
const isEditPermission = ref(false)
/**
* Purpose: permissionFormRef supports PermissionsView.vue by holding or executing the permission 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 permissionFormRef = ref<FormInstance>()
/**
* Purpose: currentPermission supports PermissionsView.vue by holding or executing the current permission 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 currentPermission = ref<PermissionVO | null>(null)
/**
* Purpose: draftSavedAt supports PermissionsView.vue by holding or executing the draft saved at 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 draftSavedAt = ref<number | null>(null)
/**
* Purpose: permissionPagination supports PermissionsView.vue by holding or executing the permission pagination 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 permissionPagination = reactive({
current: 1,
pageSize: 20,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: permissionFormState supports PermissionsView.vue by holding or executing the permission 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 permissionFormState = reactive({
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-permissions', isEditPermission.value ? 'edit' : 'create', currentPermission.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
permissionCode: permissionFormState.permissionCode,
permissionName: permissionFormState.permissionName,
permissionGroup: permissionFormState.permissionGroup,
description: permissionFormState.description
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(permissionFormState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const permissionFormRules: Record<string, Rule[]> = {
permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
permissionGroup: [{ required: true, message: '请选择权限分组', trigger: 'change' }],
description: [{ required: true, message: '请输入权限描述', trigger: 'blur' }]
}
/**
* Purpose: permissionColumns supports PermissionsView.vue by holding or executing the permission columns 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 permissionColumns = [
{ title: '权限编码', dataIndex: 'permissionCode', key: 'permissionCode' },
{ title: '权限名称', dataIndex: 'permissionName', key: 'permissionName' },
{ title: '权限分组', key: 'permissionGroup', width: 120 },
{ title: '权限描述', dataIndex: 'description', key: 'description' },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** userLoading is a reactive state variable used by the template and event handlers. */
const userLoading = ref(false)
/** userSearchText is a reactive state variable used by the template and event handlers. */
const userSearchText = ref('')
/**
* Purpose: userList supports PermissionsView.vue by holding or executing the user list 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 userList = ref<UserVO[]>([])
/**
* Purpose: selectedUser supports PermissionsView.vue by holding or executing the selected user 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 selectedUser = ref<UserVO | null>(null)
/** assignLoading is a reactive state variable used by the template and event handlers. */
const assignLoading = ref(false)
/**
* Purpose: selectedPermissions supports PermissionsView.vue by holding or executing the selected 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 selectedPermissions = ref<IdType[]>([])
/**
* Purpose: assignablePermissionIds supports PermissionsView.vue by holding or executing the assignable permission ids 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 assignablePermissionIds = ref<IdType[]>([])
/**
* Purpose: activeCollapseKeys supports PermissionsView.vue by holding or executing the active collapse keys 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 activeCollapseKeys = ref<string[]>(['作品管理', '店铺管理', '用户管理', '权限管理'])
/**
* Purpose: currentLoginUser supports PermissionsView.vue by holding or executing the current login user 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 currentLoginUser = ref<UserVO | null>(null)
/**
* Purpose: mobilePermissionStep supports PermissionsView.vue by holding or executing the mobile permission step 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 mobilePermissionStep = ref<'users' | 'assign'>('users')
// 权限 ID 同样可能以字符串形式返回,所以这里统一转成字符串集合做包含判断。
/** assignablePermissionIdSet is a reactive state variable used by the template and event handlers. */
const assignablePermissionIdSet = computed(() => new Set(assignablePermissionIds.value.map(id => String(id))))
/** disabledPermissionCount is a reactive state variable used by the template and event handlers. */
const disabledPermissionCount = computed(() =>
permissionList.value.filter(permission => !assignablePermissionIdSet.value.has(String(permission.id))).length
)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
permissionList.value.forEach(p => {
const groupName = p.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(p)
})
return groups
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number) => {
const map: Record<number, string> = {
0: '用户',
2: '店长',
3: '美甲师',
4: '管理员'
}
return map[type] || '未知'
}
/** filteredUserList is a reactive state variable used by the template and event handlers. */
const filteredUserList = computed(() => {
if (!currentLoginUser.value) return []
const currentUserId = currentLoginUser.value.id
// 管理员可以看到所有用户(除了普通用户和自己)
if (currentLoginUser.value.type === 4) {
return userList.value.filter(user => user.type !== 0 && !sameId(user.id, currentUserId))
}
// 店长只能看到美甲师(除了自己)
if (currentLoginUser.value.type === 2) {
return userList.value.filter(user => user.type === 3 && !sameId(user.id, currentUserId))
}
// 其他用户类型(如美甲师)不能管理权限
return []
})
/** isPermissionDisabled is a local helper used by this page script. */
const isPermissionDisabled = (permission: PermissionVO) => {
if (!selectedUser.value) {
return true
}
return !assignablePermissionIdSet.value.has(String(permission.id))
}
/** resolveRequestErrorMessage is a local helper used by this page script. */
const resolveRequestErrorMessage = (error: any, fallback: string) => {
return error?.response?.data?.message || error?.message || fallback
}
/** fetchCurrentUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCurrentUser = async () => {
try {
// 尝试从API获取用户信息
try {
const res = await userApi.getUserInfo()
currentLoginUser.value = res as unknown as UserVO
} catch (apiError) {
// 如果API调用失败,尝试从本地存储获取
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
try {
const userInfo = JSON.parse(userInfoStr)
currentLoginUser.value = userInfo as UserVO
} catch (parseError) {
console.error('解析本地存储的用户信息失败:', parseError)
}
} else {
console.error('获取当前用户信息失败,本地存储也没有用户信息')
}
}
} catch (error) {
console.error('获取当前用户信息失败:', error)
}
}
/** fetchPermissionList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchPermissionList = async () => {
loading.value = true
try {
const res = await permissionApi.listAllPermissions() as unknown as PermissionVO[]
permissionList.value = res || []
permissionPagination.total = res?.length || 0
} catch (error) {
message.error('获取权限列表失败')
} finally {
loading.value = false
}
}
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserList = async () => {
userLoading.value = true
try {
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) as unknown as { list: UserVO[] }
userList.value = res.list || []
} catch (error) {
message.error('获取用户列表失败')
} finally {
userLoading.value = false
}
}
/** handlePermissionTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionTableChange = async (pag: any) => {
permissionPagination.current = pag.current
permissionPagination.pageSize = pag.pageSize
await runWithGlobalLoading(() => fetchPermissionList())
}
/** handleUserSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUserSearch = async () => {
await runWithGlobalLoading(() => fetchUserList())
}
/** selectUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const selectUser = async (user: UserVO) => {
selectedUser.value = user
assignLoading.value = true
try {
await runWithGlobalLoading(async () => {
// 已分配权限和“当前角色允许分配的权限”需要分开拿,前端只保留交集,避免保存时越权。
const [assignedPermissions, allowedIds] = await Promise.all([
permissionApi.getUserPermissions(user.id) as unknown as Promise<PermissionVO[]>,
permissionApi.getAssignablePermissionIds(user.id) as unknown as Promise<IdType[]>
])
assignablePermissionIds.value = allowedIds || []
const allowedIdSet = new Set(assignablePermissionIds.value.map(id => String(id)))
/** assignedIds is a local helper used by this page script. */
const assignedIds = (assignedPermissions || []).map((p: PermissionVO) => p.id)
selectedPermissions.value = assignedIds.filter(id => allowedIdSet.has(String(id)))
const trimmedCount = assignedIds.length - selectedPermissions.value.length
if (trimmedCount > 0) {
message.warning(`已自动排除 ${trimmedCount} 项超出当前角色允许范围的权限`)
}
})
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '获取用户权限失败'))
assignablePermissionIds.value = []
selectedPermissions.value = []
} finally {
assignLoading.value = false
if (isMobile.value) {
mobilePermissionStep.value = 'assign'
}
}
}
/** handleSaveUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSaveUserPermissions = async () => {
if (!selectedUser.value) return
const userId = selectedUser.value.id
try {
await runWithGlobalLoading(async () => {
await permissionApi.assignUserPermissions(userId, selectedPermissions.value)
message.success('权限保存成功')
// 重新加载当前用户的权限
await loadUserPermissions()
})
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '权限保存失败'))
}
}
/** showAddPermissionModal is a local helper used by this page script. */
const showAddPermissionModal = () => {
isEditPermission.value = false
currentPermission.value = null
Object.assign(permissionFormState, {
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
restoreDraft()
permissionModalVisible.value = true
}
/** showEditPermissionModal is a local helper used by this page script. */
const showEditPermissionModal = (record: Record<string, any>) => {
isEditPermission.value = true
currentPermission.value = record as PermissionVO
Object.assign(permissionFormState, {
permissionCode: record.permissionCode,
permissionName: record.permissionName,
permissionGroup: record.permissionGroup,
description: record.description
})
restoreDraft()
permissionModalVisible.value = true
}
/** handlePermissionModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionModalOk = async () => {
try {
await permissionFormRef.value?.validate()
permissionModalLoading.value = true
await runWithGlobalLoading(async () => {
if (isEditPermission.value && currentPermission.value) {
await permissionApi.updatePermission(currentPermission.value.id, permissionFormState)
message.success('更新成功')
} else {
await permissionApi.createPermission(permissionFormState)
message.success('创建成功')
}
handleClearDraft(false)
permissionModalVisible.value = false
await fetchPermissionList()
})
} catch (error) {
console.error(error)
} finally {
permissionModalLoading.value = false
}
}
/** handlePermissionModalCancel is a local helper used by this page script. */
const handlePermissionModalCancel = () => {
permissionModalVisible.value = false
permissionFormRef.value?.resetFields()
}
/** handleDeletePermission is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeletePermission = async (record: Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
await permissionApi.deletePermission((record as PermissionVO).id)
message.success('删除成功')
await fetchPermissionList()
})
} catch (error) {
message.error('删除失败')
}
}
onMounted(async () => {
await fetchCurrentUser()
await loadUserPermissions()
fetchPermissionList()
// 确保在获取当前用户信息后再获取用户列表
setTimeout(() => {
fetchUserList()
}, 100)
})
watch(
() => activeTab.value,
value => {
if (value !== 'user-permissions') {
mobilePermissionStep.value = 'users'
}
}
)
</script>
<style scoped>
.permissions {
padding: 0;
}
.selected {
background: var(--theme-primary-soft) !important;
border-left: 3px solid var(--theme-primary);
}
.mobile-permission-flow {
display: grid;
gap: 16px;
}
.mobile-user-pick {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.mobile-assign-actions {
display: flex;
justify-content: space-between;
gap: 10px;
}
</style>
File diff suppressed because it is too large Load Diff
+260
View File
@@ -0,0 +1,260 @@
<template>
<div class="admin-profile">
<section class="admin-page-intro">
<span class="admin-page-intro__eyebrow">{{ userInfo?.account || '后台账号' }}</span>
<h1 class="admin-page-intro__title">{{ userInfo?.nickname || '未设置昵称' }}</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">权限 {{ permissionCount }}</span>
<span class="admin-page-chip">门店 {{ shopOptions.length || 0 }}</span>
<span class="admin-page-chip">{{ roleLabel }}</span>
<span v-if="isPlatformOverview" class="admin-page-chip">平台总览</span>
</div>
</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">{{ currentShopName }}</div>
</section>
<section class="admin-mobile-stat">
<div class="admin-mobile-stat__label">角色</div>
<div class="admin-mobile-stat__value">{{ roleLabel }}</div>
</section>
</div>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">账号信息</div>
<div class="profile-meta-list">
<div class="profile-meta-list__row">
<span>账号</span>
<strong>{{ userInfo?.account || '--' }}</strong>
</div>
<div class="profile-meta-list__row">
<span>昵称</span>
<strong>{{ userInfo?.nickname || '--' }}</strong>
</div>
<div class="profile-meta-list__row">
<span>权限数量</span>
<strong>{{ permissionCount }}</strong>
</div>
<div class="profile-meta-list__row">
<span>可登录门店</span>
<strong>{{ shopScopeText }}</strong>
</div>
</div>
</section>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">{{ isPlatformOverview ? '管理范围' : '门店切换' }}</div>
<div v-if="isPlatformOverview" class="profile-static-shop">
平台总览模式,店铺业务仅可查看
</div>
<a-select
v-else-if="shopOptions.length > 1"
v-model:value="selectedShopId"
class="profile-shop-select"
:options="shopSelectOptions"
:loading="shopSwitchLoading"
@change="handleShopChange"
/>
<div v-else class="profile-static-shop">
{{ currentShopName }}
</div>
</section>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">常用入口</div>
<div class="profile-actions">
<a-button type="default" size="large" block @click="router.push('/admin/orders')">查看订单</a-button>
<a-button type="default" size="large" block @click="router.push('/admin/manage')">进入经营模块</a-button>
</div>
</section>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">退出登录</div>
<a-button danger size="large" block @click="handleLogout">退出当前账号</a-button>
</section>
</div>
</template>
<script setup lang="ts">
/**
* ProfileView 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, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { adminAuthApi } 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'
/**
* Purpose: router supports ProfileView.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 { userPermissions, loadUserPermissions, clearPermissions } = usePermission()
/** userInfo is a reactive state variable used by the template and event handlers. */
const userInfo = ref(loadCachedAdminUserInfo())
/** selectedShopId is a reactive state variable used by the template and event handlers. */
const selectedShopId = ref(userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined)
/** shopSwitchLoading is a reactive state variable used by the template and event handlers. */
const shopSwitchLoading = ref(false)
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/**
* Purpose: isPlatformOverview supports ProfileView.vue by holding or executing the is platform overview 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 isPlatformOverview = computed(() => isBootstrapAdminUser(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => getAdminShopOptions(userInfo.value))
/** shopSelectOptions is a reactive state variable used by the template and event handlers. */
const shopSelectOptions = computed(() => {
const options = shopOptions.value.map(shop => ({ label: shop.name, value: shop.id }))
return options
})
/** permissionCount is a reactive state variable used by the template and event handlers. */
const permissionCount = computed(() => userPermissions.value.length)
/** shopScopeText is a reactive state variable used by the template and event handlers. */
const shopScopeText = computed(() => {
if (!shopOptions.value.length) {
return isPlatformOverview.value ? '平台总览模式' : '游客模式'
}
return shopOptions.value.map(item => item.name).join(' / ')
})
/** persistAdminSession is a local helper used by this page script. */
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)
}
/** refreshLocalUserInfo is a local helper used by this page script. */
const refreshLocalUserInfo = () => {
userInfo.value = loadCachedAdminUserInfo()
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
}
/** handleShopChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleShopChange = async (shopId: unknown) => {
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
return
}
const normalizedShopId = String(shopId)
if (!normalizedShopId || normalizedShopId === String(userInfo.value?.shopId || '')) {
return
}
shopSwitchLoading.value = true
try {
await runWithGlobalLoading(async () => {
const response = await adminAuthApi.switchShop(normalizedShopId)
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
}
}
/** handleLogout is a local helper used by this page script. */
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
try {
await adminAuthApi.logout()
} catch (error) {
console.error('退出失败:', error)
} finally {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
clearPermissions()
message.success('已退出登录')
window.location.href = '/admin/login'
}
})
}
})
}
onMounted(async () => {
refreshLocalUserInfo()
await loadUserPermissions()
})
</script>
<style scoped>
.admin-profile {
display: grid;
gap: 18px;
}
.profile-meta-list {
display: grid;
gap: 10px;
margin-top: 14px;
}
.profile-meta-list__row {
display: flex;
justify-content: space-between;
gap: 12px;
color: var(--text-secondary);
}
.profile-meta-list__row strong {
color: var(--admin-mobile-ink);
}
.profile-shop-select {
width: 100%;
margin-top: 14px;
}
.profile-static-shop {
margin-top: 14px;
min-height: 46px;
display: flex;
align-items: center;
padding: 0 14px;
border-radius: 16px;
background: var(--admin-mobile-accent-soft);
color: var(--admin-mobile-ink);
}
.profile-actions {
display: grid;
gap: 10px;
margin-top: 14px;
}
</style>
@@ -0,0 +1,309 @@
<template>
<div class="schedules">
<a-page-header v-if="!isMobile" title="排班管理" sub-title="维护美甲师班次、容量和可约状态" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">排班</span>
<h1 class="admin-page-intro__title">排班管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">班次 {{ schedules.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">班次列表</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-button type="primary" @click="openCreateModal">
<template #icon>
<PlusOutlined />
</template>
新增排班
</a-button>
</div>
</template>
<AdminFilterPanel :active-count="activeFilterCount">
<a-select
v-model:value="filters.artistId"
allow-clear
placeholder="选择美甲师"
:options="artistOptions"
style="width: 180px"
@change="loadSchedules"
/>
<a-range-picker
v-model:value="filters.dateRange"
value-format="YYYY-MM-DD"
style="width: 240px"
@change="loadSchedules"
/>
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table v-if="!isMobile" :columns="columns" :data-source="schedules" :loading="loading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'artist'">{{ artistName(record.artistId) }}</template>
<template v-else-if="column.key === 'time'">{{ record.startTime }} - {{ record.endTime }}</template>
<template v-else-if="column.key === 'capacity'">{{ record.capacity ?? '-' }} / {{ record.slotMinutes ?? '-' }} 分钟</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 0 ? 'red' : 'green'">{{ scheduleStatusText(record.status) }}</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-button type="link" size="small" @click="openEditModal(record as ArtistScheduleVO)">编辑</a-button>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="schedules" empty-description="暂无排班数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ artistName(item.artistId) }}</div>
<div class="admin-mobile-card__subtitle">{{ item.workDate }} {{ item.startTime }} - {{ item.endTime }}</div>
</div>
<a-tag :color="item.status === 0 ? 'red' : 'green'">{{ scheduleStatusText(item.status) }}</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>容量</span>
<strong>{{ item.capacity ?? '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>间隔</span>
<strong>{{ item.slotMinutes ?? '-' }} 分钟</strong>
</div>
<div class="admin-mobile-card__row">
<span>备注</span>
<strong>{{ item.remark || '-' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="openEditModal(item)">编辑</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalOpen"
:title="editingSchedule ? '编辑排班' : '新增排班'"
:desktop-width="720"
:confirm-loading="saving"
@ok="saveSchedule"
@cancel="closeModal"
>
<a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="美甲师" name="artistId">
<a-select v-model:value="formState.artistId" placeholder="选择美甲师" :options="artistOptions" />
</a-form-item>
<a-form-item label="工作日期" name="workDate">
<a-date-picker v-model:value="formState.workDate" value-format="YYYY-MM-DD" style="width: 100%" />
</a-form-item>
<a-form-item label="开始时间" name="startTime">
<a-input v-model:value="formState.startTime" placeholder="09:00:00" />
</a-form-item>
<a-form-item label="结束时间" name="endTime">
<a-input v-model:value="formState.endTime" placeholder="18:00:00" />
</a-form-item>
<a-form-item label="预约间隔">
<a-input-number v-model:value="formState.slotMinutes" :min="5" :step="5" style="width: 100%" />
</a-form-item>
<a-form-item label="容量">
<a-input-number v-model:value="formState.capacity" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="formState.status">
<a-select-option :value="1">可预约</a-select-option>
<a-select-option :value="0">停用</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="formState.remark" :rows="3" :maxlength="200" />
</a-form-item>
</a-form>
</AdminResponsiveModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
adminArtistScheduleApi,
adminNailArtistApi,
type ArtistScheduleRequest,
type ArtistScheduleVO,
type NailArtistInfoVO
} from '@/api/admin'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const loading = ref(false)
const saving = ref(false)
const modalOpen = ref(false)
const schedules = ref<ArtistScheduleVO[]>([])
const artists = ref<NailArtistInfoVO[]>([])
const editingSchedule = ref<ArtistScheduleVO | null>(null)
const formRef = ref<FormInstance>()
const filters = reactive({
artistId: undefined as string | undefined,
dateRange: undefined as [string, string] | undefined
})
const formState = reactive<ArtistScheduleRequest>({
artistId: undefined,
workDate: '',
startTime: '09:00:00',
endTime: '18:00:00',
slotMinutes: 30,
capacity: 1,
status: 1,
remark: ''
})
const rules = {
artistId: [{ required: true, message: '请选择美甲师', trigger: 'change' }],
workDate: [{ required: true, message: '请选择工作日期', trigger: 'change' }],
startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
} as any
const columns = [
{ title: '美甲师', key: 'artist', width: 160 },
{ title: '工作日期', dataIndex: 'workDate', key: 'workDate', width: 140 },
{ title: '工作时段', key: 'time', width: 180 },
{ title: '容量 / 间隔', key: 'capacity', width: 140 },
{ title: '状态', key: 'status', width: 100 },
{ title: '备注', dataIndex: 'remark', key: 'remark' },
{ title: '操作', key: 'actions', width: 90 }
]
const artistOptions = computed(() => artists.value.map(artist => ({
label: artist.nickname || artist.identity || `美甲师 ${artist.userId}`,
value: String(artist.userId || artist.id)
})))
const activeFilterCount = computed(() => [
filters.artistId,
filters.dateRange?.length ? 'date' : ''
].filter(Boolean).length)
const artistName = (artistId?: unknown) => {
const artist = artists.value.find(item => String(item.userId || item.id) === String(artistId))
return artist?.nickname || artist?.identity || (artistId ? `美甲师 ${artistId}` : '-')
}
const scheduleStatusText = (status?: number) => status === 0 ? '停用' : '可预约'
const resetForm = () => {
Object.assign(formState, {
artistId: undefined,
workDate: '',
startTime: '09:00:00',
endTime: '18:00:00',
slotMinutes: 30,
capacity: 1,
status: 1,
remark: ''
})
}
const loadArtists = async () => {
try {
artists.value = await adminNailArtistApi.listNailArtists() as unknown as NailArtistInfoVO[]
} catch (error) {
console.error('加载美甲师失败:', error)
artists.value = []
}
}
const loadSchedules = async () => {
loading.value = true
try {
schedules.value = await adminArtistScheduleApi.listSchedules({
artistId: filters.artistId,
startDate: filters.dateRange?.[0],
endDate: filters.dateRange?.[1]
})
} catch (error) {
console.error('加载排班失败:', error)
message.error('加载排班失败')
} finally {
loading.value = false
}
}
const resetFilters = () => {
filters.artistId = undefined
filters.dateRange = undefined
void loadSchedules()
}
const openCreateModal = () => {
editingSchedule.value = null
resetForm()
modalOpen.value = true
}
const openEditModal = (record: ArtistScheduleVO) => {
editingSchedule.value = record
Object.assign(formState, {
artistId: String(record.artistId),
workDate: record.workDate,
startTime: record.startTime,
endTime: record.endTime,
slotMinutes: record.slotMinutes ?? 30,
capacity: record.capacity ?? 1,
status: record.status ?? 1,
remark: record.remark || ''
})
modalOpen.value = true
}
const closeModal = () => {
modalOpen.value = false
formRef.value?.resetFields()
}
const saveSchedule = async () => {
try {
await formRef.value?.validate()
saving.value = true
await runWithGlobalLoading(async () => {
await adminArtistScheduleApi.saveSchedule({ ...formState })
await loadSchedules()
})
message.success('排班已保存')
closeModal()
} catch (error: any) {
if (error?.errorFields) {
return
}
console.error('保存排班失败:', error)
message.error(error?.message || '保存排班失败')
} finally {
saving.value = false
}
}
onMounted(async () => {
await loadArtists()
await loadSchedules()
})
</script>
<style scoped>
.schedules {
padding: 0;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,727 @@
<template>
<div class="system-messages admin-page">
<section class="message-page-head">
<a-page-header title="消息发布" sub-title="发布站内消息,支持文本和单张图片" />
</section>
<section class="message-composer-shell">
<div class="message-composer-grid">
<article class="message-editor-panel">
<div class="panel-heading">
<div class="panel-heading__icon">
<SendOutlined />
</div>
<div>
<p class="panel-eyebrow">站内消息</p>
<h2>发布消息</h2>
</div>
</div>
<a-form layout="vertical" :model="form" class="message-form">
<a-form-item label="标题" required>
<a-input v-model:value="form.title" :maxlength="100" placeholder="请输入消息标题" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="6" :maxlength="2000" placeholder="支持 HTML / Markdown,可配合图片展示" />
</a-form-item>
<a-form-item label="消息图片">
<div class="image-upload-row">
<a-upload accept="image/*" list-type="picture-card" :show-upload-list="false" :custom-request="handleImageUpload">
<div v-if="!imagePreviewUrl" class="upload-placeholder">
<PictureOutlined />
<span>上传图片</span>
</div>
<img v-else class="message-image-preview" :src="imagePreviewUrl" alt="消息图片预览" />
</a-upload>
<div class="image-upload-copy">
<div>每条消息最多上传一张图片。</div>
<small>建议使用 JPG/PNG/WebP,图片会在弹窗和通知详情中展示。</small>
<a-button v-if="form.imageFileId" type="link" danger size="small" @click="removeImage">移除图片</a-button>
</div>
</div>
</a-form-item>
<div class="scope-panel">
<a-row :gutter="16">
<a-col :xs="24" :md="10">
<a-form-item label="接收范围" required>
<a-select v-model:value="form.targetType" @change="handleTargetTypeChange">
<a-select-option v-for="item in targetTypes" :key="item.value" :value="item.value">
{{ item.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col v-if="needsShopSelection" :xs="24" :md="14">
<a-form-item label="接收店铺" required>
<a-select v-model:value="form.shopIds" mode="multiple" :options="shopOptions" placeholder="请选择店铺" />
</a-form-item>
</a-col>
<a-col v-if="form.targetType === 'SELECTED_USERS'" :xs="24" :md="14">
<a-form-item label="接收用户" required>
<a-select
v-model:value="form.userIds"
mode="multiple"
show-search
option-filter-prop="label"
:options="userOptions"
placeholder="请选择用户"
/>
</a-form-item>
</a-col>
</a-row>
</div>
<div class="publish-footer">
<a-checkbox v-model:checked="popupEnabled" class="popup-checkbox">弹窗显示一次</a-checkbox>
<a-space>
<a-button @click="resetForm">清空</a-button>
<a-button type="primary" :loading="saving" @click="handlePublish">
<template #icon>
<SendOutlined />
</template>
发布
</a-button>
</a-space>
</div>
</a-form>
</article>
<aside class="message-preview-panel">
<SystemMessageCard
:title="previewTitle"
:content="previewContent"
:image-url="imagePreviewUrl"
:meta="previewMeta"
surface="preview"
footer-align="end"
>
<template #footer>
<button class="preview-read-button" type="button" tabindex="-1">
<CheckOutlined />
我知道了
</button>
</template>
</SystemMessageCard>
</aside>
</div>
</section>
<a-card :bordered="false" class="admin-section-card">
<template #title>发布记录</template>
<a-table :columns="columns" :data-source="messages" :loading="loading" row-key="id" :pagination="{ pageSize: 8 }" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'">
<a-image v-if="record.imageUrl" :src="record.imageUrl" :width="54" :height="54" class="table-image" />
<span v-else class="muted">无</span>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.status === 1 ? '已发布' : '已撤回' }}</a-tag>
</template>
<template v-else-if="column.key === 'popupEnabled'">
<a-tag :color="record.popupEnabled === 1 ? 'blue' : 'default'">{{ record.popupEnabled === 1 ? '弹窗' : '不弹窗' }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="previewMessage(record as SystemMessageVO)">查看</a-button>
<a-popconfirm v-if="record.status === 1" title="确定撤回这条消息吗?" @confirm="handleRevoke(record.id)">
<a-button type="link" size="small" danger>撤回</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal v-model:open="previewVisible" :footer="null" width="560px" wrap-class-name="message-detail-modal-wrap" :mask-closable="false">
<SystemMessageCard
:title="currentMessage?.title || '消息详情'"
:content="currentMessage?.content || ''"
:image-url="currentMessage?.imageUrl || ''"
:meta="currentMessageMeta"
surface="modal"
footer-align="end"
>
<template #footer>
<a-button type="primary" class="message-detail-close-button" @click="previewVisible = false">
<template #icon>
<CheckOutlined />
</template>
我知道了
</a-button>
</template>
</SystemMessageCard>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
CheckOutlined,
PictureOutlined,
SendOutlined
} from '@ant-design/icons-vue'
import SystemMessageCard from '@/components/SystemMessageCard.vue'
/**
* Purpose: SystemMessageCreateRequest supports SystemMessagesView.vue by holding or executing the system message create request 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 { adminFileApi, adminSystemMessageApi, type SystemMessageCreateRequest, type SystemMessageVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
/**
* Purpose: loading supports SystemMessagesView.vue by holding or executing the loading 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 loading = ref(false)
/**
* Purpose: saving supports SystemMessagesView.vue by holding or executing the saving 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 saving = ref(false)
/**
* Purpose: imageUploading supports SystemMessagesView.vue by holding or executing the image uploading 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 imageUploading = ref(false)
/**
* Purpose: messages supports SystemMessagesView.vue by holding or executing the messages 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 messages = ref<SystemMessageVO[]>([])
/**
* Purpose: targetOptions supports SystemMessagesView.vue by holding or executing the target 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.
*/
const targetOptions = ref({ shops: [] as any[], users: [] as any[] })
/**
* Purpose: popupEnabled supports SystemMessagesView.vue by holding or executing the popup enabled 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 popupEnabled = ref(true)
/**
* Purpose: previewVisible supports SystemMessagesView.vue by holding or executing the preview visible 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 previewVisible = ref(false)
/**
* Purpose: currentMessage supports SystemMessagesView.vue by holding or executing the current message 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 currentMessage = ref<SystemMessageVO | null>(null)
/**
* Purpose: imagePreviewUrl supports SystemMessagesView.vue by holding or executing the image preview url 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 imagePreviewUrl = ref('')
/**
* Purpose: form supports SystemMessagesView.vue by holding or executing the form 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 form = reactive<SystemMessageCreateRequest>({
title: '',
content: '',
imageFileId: undefined,
targetType: 'CURRENT_SHOP_ALL',
shopIds: [],
userIds: [],
popupEnabled: 1
})
/**
* Purpose: currentAdminUser supports SystemMessagesView.vue by holding or executing the current admin user 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 currentAdminUser = computed(() => {
try {
const cache = localStorage.getItem('adminUserInfo') || sessionStorage.getItem('adminUserInfo')
return cache ? JSON.parse(cache) : null
} catch {
return null
}
})
/**
* Purpose: isPlatformAdmin supports SystemMessagesView.vue by holding or executing the is platform admin 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 isPlatformAdmin = computed(() => Number(currentAdminUser.value?.type) === 4)
/**
* Purpose: targetTypes supports SystemMessagesView.vue by holding or executing the target types 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 targetTypes = computed(() => [
...(isPlatformAdmin.value ? [{ label: '全平台', value: 'PLATFORM_ALL' }] : []),
{ label: isPlatformAdmin.value ? '指定店铺全员' : '本店全员', value: isPlatformAdmin.value ? 'SELECTED_SHOPS' : 'CURRENT_SHOP_ALL' },
{ label: '指定用户', value: 'SELECTED_USERS' }
])
/**
* Purpose: needsShopSelection supports SystemMessagesView.vue by holding or executing the needs shop selection 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 needsShopSelection = computed(() => form.targetType === 'SELECTED_SHOPS' || form.targetType === 'SHOP_ALL')
/**
* Purpose: shopOptions supports SystemMessagesView.vue by holding or executing the 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.
*/
const shopOptions = computed(() => targetOptions.value.shops.map(shop => ({ label: shop.shopName, value: shop.id })))
/**
* Purpose: userOptions supports SystemMessagesView.vue by holding or executing the user 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.
*/
const userOptions = computed(() => targetOptions.value.users.map(user => ({
label: `${user.nickname || user.account} ${user.shopName ? `(${user.shopName})` : ''}`,
value: user.id
})))
/**
* Purpose: previewTitle supports SystemMessagesView.vue by holding or executing the preview title 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 previewTitle = computed(() => form.title.trim() || '消息标题预览')
/**
* Purpose: previewContent supports SystemMessagesView.vue by holding or executing the preview content 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 previewContent = computed(() => form.content.trim() || (imagePreviewUrl.value ? '' : '这里会显示消息正文。支持纯文本,也可以配合一张图片展示给用户。'))
/**
* Purpose: previewMeta supports SystemMessagesView.vue by holding or executing the preview meta 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 previewMeta = computed(() => `系统消息 · ${popupEnabled.value ? '弹窗预览' : '列表预览'}`)
/**
* Purpose: currentMessageMeta supports SystemMessagesView.vue by holding or executing the current message meta 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 currentMessageMeta = computed(() => {
if (!currentMessage.value) return ''
return [
currentMessage.value.publisherName || '系统消息',
currentMessage.value.publishTime || currentMessage.value.createTime
].filter(Boolean).join(' · ')
})
/**
* Purpose: columns supports SystemMessagesView.vue by holding or executing the columns 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 columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '图片', key: 'image', width: 84 },
{ title: '范围', dataIndex: 'targetTypeName', key: 'targetTypeName', width: 140 },
{ title: '发布人', dataIndex: 'publisherName', key: 'publisherName', width: 140 },
{ title: '弹窗', key: 'popupEnabled', width: 90 },
{ title: '状态', key: 'status', width: 90 },
{ title: '发布时间', dataIndex: 'publishTime', key: 'publishTime', width: 180 },
{ title: '操作', key: 'action', width: 120 }
]
/**
* Purpose: syncDefaultTargetType supports SystemMessagesView.vue by holding or executing the sync default target type 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 syncDefaultTargetType = () => {
if (isPlatformAdmin.value && form.targetType === 'CURRENT_SHOP_ALL') {
form.targetType = 'PLATFORM_ALL'
}
if (!isPlatformAdmin.value && form.targetType === 'PLATFORM_ALL') {
form.targetType = 'CURRENT_SHOP_ALL'
}
}
/**
* Purpose: loadData supports SystemMessagesView.vue by holding or executing the load data 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 loadData = async () => {
loading.value = true
try {
const [messageList, options] = await Promise.all([
adminSystemMessageApi.listMessages(),
adminSystemMessageApi.getTargetOptions()
])
messages.value = messageList || []
targetOptions.value = options || { shops: [], users: [] }
syncDefaultTargetType()
} catch (error: any) {
message.error(error?.message || '消息数据加载失败')
} finally {
loading.value = false
}
}
/**
* Purpose: handleTargetTypeChange supports SystemMessagesView.vue by holding or executing the handle target type change 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 handleTargetTypeChange = () => {
form.shopIds = []
form.userIds = []
}
/**
* Purpose: removeImage supports SystemMessagesView.vue by holding or executing the remove image 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 removeImage = () => {
form.imageFileId = undefined
imagePreviewUrl.value = ''
}
/**
* Purpose: resetForm supports SystemMessagesView.vue by holding or executing the reset form 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 resetForm = () => {
form.title = ''
form.content = ''
form.imageFileId = undefined
form.targetType = isPlatformAdmin.value ? 'PLATFORM_ALL' : 'CURRENT_SHOP_ALL'
form.shopIds = []
form.userIds = []
popupEnabled.value = true
imagePreviewUrl.value = ''
}
/**
* Purpose: handleImageUpload supports SystemMessagesView.vue by holding or executing the handle image upload 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 handleImageUpload = async (options: any) => {
const file = options.file as File
if (!file?.type?.startsWith('image/')) {
message.warning('请上传图片文件')
options.onError?.(new Error('invalid image'))
return
}
if (file.size > 5 * 1024 * 1024) {
message.warning('图片不能超过 5MB')
options.onError?.(new Error('image too large'))
return
}
imageUploading.value = true
try {
const uploaded = await adminFileApi.uploadFile(file)
form.imageFileId = uploaded.id
imagePreviewUrl.value = await adminFileApi.getSignedUrl(uploaded.id)
options.onSuccess?.(uploaded)
} catch (error: any) {
message.error(error?.message || '图片上传失败')
options.onError?.(error)
} finally {
imageUploading.value = false
}
}
/**
* Purpose: handlePublish supports SystemMessagesView.vue by holding or executing the handle publish 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 handlePublish = async () => {
if (!form.title.trim()) return message.warning('请填写消息标题')
if (!form.content.trim() && !form.imageFileId) return message.warning('请填写消息内容或上传消息图片')
if (imageUploading.value) return message.warning('图片还在上传中,请稍后发布')
if (needsShopSelection.value && !form.shopIds?.length) return message.warning('请选择接收店铺')
if (form.targetType === 'SELECTED_USERS' && !form.userIds?.length) return message.warning('请选择接收用户')
saving.value = true
try {
await adminSystemMessageApi.createMessage({ ...form, popupEnabled: popupEnabled.value ? 1 : 0 })
message.success('消息已发布')
resetForm()
await loadData()
} catch (error: any) {
message.error(error?.message || '消息发布失败')
} finally {
saving.value = false
}
}
/**
* Purpose: handleRevoke supports SystemMessagesView.vue by holding or executing the handle revoke 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 handleRevoke = async (id: IdType) => {
await adminSystemMessageApi.revokeMessage(id)
message.success('消息已撤回')
await loadData()
}
/**
* Purpose: previewMessage supports SystemMessagesView.vue by holding or executing the preview message 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 previewMessage = (record: SystemMessageVO) => {
currentMessage.value = record
previewVisible.value = true
}
onMounted(loadData)
</script>
<style scoped>
.system-messages {
padding: 18px;
max-width: 1180px;
margin: 0 auto;
}
.message-page-head {
max-width: 1120px;
margin: 0 auto 12px;
}
.message-page-head :deep(.ant-page-header) {
padding: 0 0 12px;
}
.message-page-head :deep(.ant-page-header-heading-title) {
color: var(--text-primary);
font-weight: 700;
}
.message-composer-shell {
max-width: 1120px;
margin: 0 auto 24px;
}
.message-composer-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(330px, 420px);
gap: 22px;
align-items: stretch;
}
.message-editor-panel,
.message-preview-panel {
min-width: 0;
}
.message-editor-panel {
padding: 24px;
border: 1px solid var(--theme-border);
border-radius: 22px;
background: var(--theme-card-bg);
box-shadow: 0 18px 48px color-mix(in srgb, var(--theme-primary) 12%, transparent);
}
.panel-heading {
display: flex;
gap: 14px;
align-items: center;
margin-bottom: 22px;
}
.panel-heading__icon {
display: grid;
width: 46px;
height: 46px;
flex: 0 0 auto;
place-items: center;
border-radius: 14px;
color: #ffffff;
font-size: 20px;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.panel-eyebrow {
margin: 0 0 4px;
color: var(--theme-primary);
font-size: 13px;
font-weight: 600;
}
.panel-heading h2 {
margin: 0;
color: var(--text-primary);
font-size: 22px;
font-weight: 750;
}
.message-form :deep(.ant-form-item-label > label) {
color: var(--text-primary);
font-weight: 600;
}
.message-form :deep(.ant-input),
.message-form :deep(.ant-input-number),
.message-form :deep(.ant-select-selector),
.message-form :deep(.ant-input-affix-wrapper) {
border-color: var(--theme-border);
border-radius: 10px;
}
.message-form :deep(.ant-input:focus),
.message-form :deep(.ant-input-focused),
.message-form :deep(.ant-select-focused .ant-select-selector),
.message-form :deep(.ant-input-affix-wrapper-focused) {
border-color: var(--theme-primary);
box-shadow: var(--theme-focus-shadow);
}
.scope-panel {
padding: 16px 16px 0;
margin-bottom: 18px;
border: 1px solid var(--theme-border);
border-radius: 16px;
background: var(--theme-gradient-soft);
}
.publish-footer {
display: flex;
gap: 16px;
align-items: center;
justify-content: space-between;
padding-top: 18px;
border-top: 1px solid var(--theme-border);
}
.popup-checkbox {
color: var(--text-secondary);
}
.message-preview-panel {
display: flex;
align-items: center;
justify-content: center;
}
.message-preview-panel :deep(.system-message-card) {
max-width: 420px;
}
.preview-read-button {
display: inline-flex;
min-height: 40px;
align-items: center;
justify-content: center;
gap: 8px;
padding: 0 18px;
border: 0;
border-radius: 12px;
color: #ffffff;
font-weight: 700;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
cursor: default;
}
.admin-section-card {
max-width: 1120px;
margin-bottom: 16px;
margin-left: auto;
margin-right: auto;
border: 1px solid var(--theme-border);
border-radius: 18px;
box-shadow: 0 18px 42px color-mix(in srgb, var(--theme-primary) 10%, transparent);
overflow: hidden;
}
.admin-section-card :deep(.ant-card-head) {
color: var(--theme-primary);
background: var(--theme-gradient-soft);
}
.image-upload-row {
display: flex;
gap: 16px;
align-items: center;
}
.upload-placeholder {
display: grid;
gap: 4px;
place-items: center;
color: var(--text-secondary);
text-align: center;
}
.message-image-preview {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 6px;
}
.image-upload-copy {
color: var(--text-secondary);
line-height: 1.7;
}
.image-upload-copy small,
.muted {
color: var(--text-secondary);
font-size: 13px;
}
.table-image {
object-fit: cover;
border-radius: 6px;
}
:global(.message-detail-modal-wrap .ant-modal-content) {
padding: 0;
overflow: hidden;
border-radius: 8px;
background: transparent;
}
:global(.message-detail-modal-wrap .ant-modal-body) {
padding: 0;
}
:global(.message-detail-modal-wrap .ant-modal-close) {
color: var(--text-secondary);
}
:global(.message-detail-modal-wrap .message-detail-close-button) {
border: 0;
border-radius: 12px;
color: #ffffff;
font-weight: 700;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
:global(.message-detail-modal-wrap .message-detail-close-button:hover),
:global(.message-detail-modal-wrap .message-detail-close-button:focus) {
color: #ffffff;
background: var(--theme-gradient);
filter: brightness(0.98);
}
@media (max-width: 960px) {
.message-composer-grid {
grid-template-columns: 1fr;
}
.message-preview-panel :deep(.system-message-card) {
max-width: 640px;
}
}
@media (max-width: 640px) {
.system-messages {
padding: 12px;
}
.message-editor-panel {
border-radius: 18px;
}
.image-upload-row,
.publish-footer {
align-items: stretch;
flex-direction: column;
}
.publish-footer :deep(.ant-space) {
justify-content: flex-end;
}
.preview-read-button {
width: 100%;
}
}
</style>
+662
View File
@@ -0,0 +1,662 @@
<template>
<div class="tags">
<a-page-header v-if="!isMobile" title="标签管理" sub-title="管理系统标签" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">标签管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">标签 {{ tagList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">
标签列表
</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="searchText"
placeholder="搜索标签名称"
:style="isMobile ? { width: '100%' } : { width: '250px' }"
@search="handleSearch"
/>
<a-button v-if="!isMobile && hasPermission('tag:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增标签
</a-button>
</div>
</template>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="tagList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="id"
:scroll="{ x: 'max-content' }"
>
<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>{{ record.shopName || 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>
<AdminMobileCardList v-else :items="tagList" empty-description="暂无标签数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.tagName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.shopName || getShopName(item.shopId) || '未关联店铺' }}</div>
</div>
<span
class="tag-preview"
:style="{ backgroundColor: item.bgColor, color: item.textColor, borderColor: item.borderColor }"
>
{{ item.tagName }}
</span>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>创建时间</span>
<strong>{{ item.createTime || '--' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('tag:view')" size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('tag:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
<a-button v-if="hasPermission('tag:delete')" size="small" danger @click="handleDelete(item)">删除</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalVisible"
:title="isEdit ? '编辑标签' : '新增标签'"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
:desktop-width="600"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<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="场景分组" name="sceneGroup">
<a-input v-model:value="formState.sceneGroup" placeholder="如:风格、场合、季节" />
</a-form-item>
<a-form-item label="前台名称" name="displayName">
<a-input v-model:value="formState.displayName" placeholder="留空则使用标签名称" />
</a-form-item>
<a-form-item label="前台排序" name="sortOrder">
<a-input-number v-model:value="formState.sortOrder" :min="0" style="width: 100%" />
</a-form-item>
<a-form-item label="前台展示" name="frontVisible">
<a-switch v-model:checked="formState.frontVisible" :checked-value="1" :un-checked-value="0" />
</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>
</AdminResponsiveModal>
<!-- 查看标签详情模态框 -->
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看标签详情"
:footer="null"
@cancel="handleViewModalCancel"
:desktop-width="600"
>
<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="场景分组">
<a-input v-model:value="viewFormState.sceneGroup" :disabled="true" />
</a-form-item>
<a-form-item label="前台名称">
<a-input v-model:value="viewFormState.displayName" :disabled="true" />
</a-form-item>
<a-form-item label="前台排序">
<a-input-number v-model:value="viewFormState.sortOrder" :disabled="true" style="width: 100%" />
</a-form-item>
<a-form-item label="前台展示">
<a-switch v-model:checked="viewFormState.frontVisible" :checked-value="1" :un-checked-value="0" 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>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && hasPermission('tag:create') && !modalVisible && !viewModalVisible"
label="新增标签"
@click="showAddModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* TagsView 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 { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
/**
* Purpose: Shop supports TagsView.vue by holding or executing the shop 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 { adminTagApi, adminShopApi, type Shop } from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
/**
* Purpose: formRef supports TagsView.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>()
/**
* Purpose: currentTag supports TagsView.vue by holding or executing the current tag 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 currentTag = ref<any>(null)
/**
* Purpose: draftSavedAt supports TagsView.vue by holding or executing the draft saved at 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 draftSavedAt = ref<number | null>(null)
// 查看标签相关状态
const viewFormState = reactive({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5',
sceneGroup: '',
displayName: '',
sortOrder: 100,
frontVisible: 1
})
/**
* Purpose: tagList supports TagsView.vue by holding or executing the tag list 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 tagList = ref<any[]>([])
/**
* Purpose: shops supports TagsView.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<Shop[]>([])
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
/**
* Purpose: pagination supports TagsView.vue by holding or executing the pagination 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 pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: formState supports TagsView.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({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5',
sceneGroup: '',
displayName: '',
sortOrder: 100,
frontVisible: 1
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-tags', isEdit.value ? 'edit' : 'create', currentTag.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
tagName: formState.tagName,
shopId: formState.shopId,
textColor: formState.textColor,
bgColor: formState.bgColor,
borderColor: formState.borderColor,
sceneGroup: formState.sceneGroup,
displayName: formState.displayName,
sortOrder: formState.sortOrder,
frontVisible: formState.frontVisible
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/**
* Purpose: formRules supports TagsView.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 = {
tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
} as any
/**
* Purpose: columns supports TagsView.vue by holding or executing the columns 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 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: 'sceneGroup', key: 'sceneGroup', width: 120 },
{ title: '前台名称', dataIndex: 'displayName', key: 'displayName', width: 120 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
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) as unknown as any[]
} else {
tags = await adminTagApi.listAllTags() as unknown as any[]
}
tagList.value = tags || []
pagination.total = tagList.value.length
} catch (error) {
console.error('获取标签列表失败:', error)
message.error('获取标签列表失败')
} finally {
loading.value = false
}
}
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
const res = await adminShopApi.listAllShops() as unknown as any[]
shops.value = res || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
/** normalizeShopIdValue is a local helper used by this page script. */
const normalizeShopIdValue = (value: string | number | undefined | null) => {
if (value === undefined || value === null || value === '') {
return ''
}
return String(value)
}
/** getShopName is a local helper used by this page script. */
const getShopName = (shopId: IdType | undefined) => {
const normalizedShopId = normalizeShopIdValue(shopId)
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
return shop ? shop.shopName : '未知店铺'
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchTags())
}
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
await runWithGlobalLoading(() => fetchTags())
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentTag.value = null
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
Object.assign(formState, {
tagName: '',
shopId: shopId,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5',
sceneGroup: '',
displayName: '',
sortOrder: 100,
frontVisible: 1
})
restoreDraft()
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentTag.value = record
Object.assign(formState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor,
sceneGroup: record.sceneGroup || '',
displayName: record.displayName || '',
sortOrder: record.sortOrder ?? 100,
frontVisible: record.frontVisible ?? 1
})
restoreDraft()
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
Object.assign(viewFormState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor,
sceneGroup: record.sceneGroup || '',
displayName: record.displayName || '',
sortOrder: record.sortOrder ?? 100,
frontVisible: record.frontVisible ?? 1
})
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
await runWithGlobalLoading(async () => {
const requestData = {
tagName: formState.tagName,
shopId: formState.shopId,
textColor: formState.textColor,
bgColor: formState.bgColor,
borderColor: formState.borderColor,
sceneGroup: formState.sceneGroup,
displayName: formState.displayName,
sortOrder: formState.sortOrder,
frontVisible: formState.frontVisible
}
if (isEdit.value && currentTag.value) {
await adminTagApi.updateTag(currentTag.value.id, requestData)
message.success('更新成功')
} else {
await adminTagApi.createTag(requestData)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
await fetchTags()
})
} catch (error: any) {
console.error('Error:', error)
message.error(error?.message || (isEdit.value ? '更新失败' : '创建失败'))
} finally {
modalLoading.value = false
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
}
/** handleDelete is a local helper used by this page script. */
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除标签 ${record.tagName} 吗?`,
onOk: async () => {
try {
await runWithGlobalLoading(async () => {
await adminTagApi.deleteTag(record.id)
message.success('删除成功')
await 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>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,189 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>VIP 充值配置</h2>
<p>这里只配置展示档位,不会创建支付订单或修改余额。</p>
</div>
<a-button type="primary" @click="openCreate">新增档位</a-button>
</div>
<a-table :columns="columns" :data-source="plans" :loading="loading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'amount'">
充 {{ money(record.rechargeAmount) }} 送 {{ money(record.giftAmount) }}
</template>
<template v-else-if="column.key === 'status'">
<a-switch :checked="record.status === 1" @change="(checked: any) => toggleStatus(record as VipRechargePlanVO, Boolean(checked))" />
</template>
<template v-else-if="column.key === 'action'">
<a-button size="small" @click="openEdit(record as VipRechargePlanVO)">编辑</a-button>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" :title="editingId ? '编辑档位' : '新增档位'" :mask-closable="false" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="所属店铺">
<a-select v-model:value="form.shopId" :options="shopOptions" allow-clear placeholder="店长默认当前店铺" />
</a-form-item>
<a-form-item label="标题">
<a-input v-model:value="form.title" />
</a-form-item>
<a-form-item label="充值金额">
<a-input-number v-model:value="form.rechargeAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="赠送金额">
<a-input-number v-model:value="form.giftAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="对应 VIP 等级">
<a-input v-model:value="form.vipLevel" placeholder="如 青铜 / 白银 / 黄金,也可以输入自定义等级" />
<div class="level-shortcuts">
<a-tag v-for="level in vipLevelOptions" :key="level" @click="form.vipLevel = level">{{ level }}</a-tag>
</div>
</a-form-item>
<a-form-item label="展示说明">
<a-textarea v-model:value="form.description" :rows="3" />
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="form.sortOrder" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* VipRechargePlansView 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 { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
/**
* Purpose: Shop supports VipRechargePlansView.vue by holding or executing the shop 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 { adminShopApi, adminVipRechargePlanApi, type Shop, type VipRechargePlanVO } from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
/**
* Purpose: editingId supports VipRechargePlansView.vue by holding or executing the editing id 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 editingId = ref<any>()
/**
* Purpose: plans supports VipRechargePlansView.vue by holding or executing the plans 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 plans = ref<VipRechargePlanVO[]>([])
/**
* Purpose: shops supports VipRechargePlansView.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<Shop[]>([])
/**
* Purpose: vipLevelOptions supports VipRechargePlansView.vue by holding or executing the vip level 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.
*/
const vipLevelOptions = ref<string[]>(['普通', '青铜', '白银', '黄金'])
/**
* Purpose: form supports VipRechargePlansView.vue by holding or executing the form 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 form = reactive<any>({ shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
/**
* Purpose: columns supports VipRechargePlansView.vue by holding or executing the columns 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 columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '金额', key: 'amount' },
{ title: 'VIP 等级', dataIndex: 'vipLevel', key: 'vipLevel' },
{ title: '说明', dataIndex: 'description', key: 'description' },
{ title: '启用', key: 'status', width: 100 },
{ title: '操作', key: 'action', width: 100 }
]
/**
* Purpose: shopOptions supports VipRechargePlansView.vue by holding or executing the 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.
*/
const shopOptions = ref<Array<{ label: string; value: any }>>([])
/** money is a local helper used by this page script. */
const money = (value: number | string) => Number(value || 0).toFixed(2)
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [planList, shopList] = await Promise.all([
adminVipRechargePlanApi.listPlans(),
adminShopApi.listAllShops().catch(() => [])
])
plans.value = planList || []
const configuredLevels = Array.from(new Set(plans.value.map(item => item.vipLevel).filter(Boolean)))
vipLevelOptions.value = Array.from(new Set(['普通', '青铜', '白银', '黄金', ...configuredLevels]))
shops.value = shopList || []
shopOptions.value = shops.value.map(item => ({ label: item.shopName, value: item.id }))
} finally {
loading.value = false
}
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => Object.assign(form, { shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
/** openCreate is a local helper used by this page script. */
const openCreate = () => { editingId.value = undefined; resetForm(); formOpen.value = true }
/** openEdit is a local helper used by this page script. */
const openEdit = (record: VipRechargePlanVO) => {
editingId.value = record.id
Object.assign(form, record)
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.title || !form.vipLevel || Number(form.rechargeAmount) <= 0) {
message.warning('请填写标题、充值金额和 VIP 等级')
return
}
saving.value = true
try {
if (editingId.value) {
await adminVipRechargePlanApi.updatePlan(editingId.value, form)
} else {
await adminVipRechargePlanApi.createPlan(form)
}
message.success('档位已保存')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** toggleStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const toggleStatus = async (record: VipRechargePlanVO, checked: boolean) => {
await adminVipRechargePlanApi.updateStatus(record.id, checked ? 1 : 0)
record.status = checked ? 1 : 0
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p { margin: 0; color: var(--text-secondary); }
.level-shortcuts { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
.level-shortcuts :deep(.ant-tag) { cursor: pointer; }
</style>
@@ -0,0 +1,45 @@
/**
* 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) ? '平台总览模式' : '游客模式')
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import { readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
const sourceRoot = join(process.cwd(), 'src')
const adminViewsPath = join(sourceRoot, 'views', 'admin')
function readSource(relativePath: string) {
return readFileSync(join(sourceRoot, relativePath), 'utf-8')
}
function findModalTags(source: string) {
return Array.from(source.matchAll(/<a-modal\b[\s\S]*?>/g), match => match[0])
}
function findUserFormModal(source: string) {
const match = source.match(/<AdminResponsiveModal\b[\s\S]*?@cancel="handleModalCancel"[\s\S]*?<\/AdminResponsiveModal>/)
return match?.[0] ?? ''
}
function findFormItem(source: string, name: string) {
const match = source.match(new RegExp(`<a-form-item\\b[\\s\\S]*?name="${name}"[\\s\\S]*?</a-form-item>`))
return match?.[0] ?? ''
}
describe('admin modal and user form behavior', () => {
it('keeps every backend modal open when users click the blank mask area', () => {
const responsiveModal = readSource('components/admin/AdminResponsiveModal.vue')
expect(responsiveModal).toMatch(/<a-modal\b[\s\S]*:mask-closable="false"/)
const missingMaskLock = readdirSync(adminViewsPath)
.filter(fileName => fileName.endsWith('.vue'))
.flatMap(fileName => {
const source = readFileSync(join(adminViewsPath, fileName), 'utf-8')
return findModalTags(source)
.map((tag, index) => ({ fileName, index: index + 1, tag }))
.filter(({ tag }) => !/:mask-closable\s*=\s*"false"/.test(tag))
.map(({ fileName, index }) => `${fileName} modal #${index}`)
})
expect(missingMaskLock).toEqual([])
})
it('shows only one editable phone field in the user create and edit form', () => {
const usersView = readSource('views/admin/UsersView.vue')
const userFormModal = findUserFormModal(usersView)
expect(userFormModal).toContain('name="phone"')
expect(userFormModal).not.toContain('name="contactPhone"')
expect(userFormModal).not.toContain('formState.contactPhone')
expect(usersView).toContain('const primaryPhone = formState.phone.trim()')
expect(usersView).toContain('phone: primaryPhone')
expect(usersView).toContain('contactPhone: primaryPhone')
})
it('uses a polished date picker and visible required markers for conditional user fields', () => {
const usersView = readSource('views/admin/UsersView.vue')
const userFormModal = findUserFormModal(usersView)
const wechatIdField = findFormItem(userFormModal, 'wechatId')
const shopIdsField = findFormItem(userFormModal, 'shopIds')
expect(userFormModal).not.toContain('type="date"')
expect(userFormModal).toContain('<a-date-picker')
expect(userFormModal).toContain('value-format="YYYY-MM-DD"')
expect(userFormModal).toContain('class="user-date-picker"')
expect(usersView).toContain('.user-date-picker')
expect(wechatIdField).toContain(':required="[2, 3].includes(Number(formState.type))"')
expect(shopIdsField).toContain(':required="Number(formState.type) !== 4"')
})
})
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
const sourceRoot = join(process.cwd(), 'src')
const adminViewsPath = join(sourceRoot, 'views', 'admin')
function readSource(relativePath: string) {
return readFileSync(join(sourceRoot, relativePath), 'utf-8')
}
function findTableTags(source: string) {
return Array.from(source.matchAll(/<a-table\b[\s\S]*?>/g), match => match[0])
}
describe('admin table layout', () => {
it('keeps every admin table wide enough to scroll horizontally', () => {
const missingScrollX = readdirSync(adminViewsPath)
.filter(fileName => fileName.endsWith('.vue'))
.flatMap(fileName => {
const source = readFileSync(join(adminViewsPath, fileName), 'utf-8')
return findTableTags(source)
.map((tag, index) => ({ fileName, index: index + 1, tag }))
.filter(({ tag }) => !/:scroll\s*=\s*"\{[\s\S]*x:\s*'max-content'/.test(tag))
.map(({ fileName, index }) => `${fileName} table #${index}`)
})
expect(missingScrollX).toEqual([])
})
it('prevents backend table cells from breaking text into vertical columns', () => {
const adminLayout = readSource('views/admin/AdminLayout.vue')
expect(adminLayout).not.toMatch(/\.mobile-content\s+:deep\(\.ant-table-cell\)\s*\{[\s\S]*overflow-wrap:\s*anywhere/)
expect(adminLayout).toContain('table-layout: auto;')
expect(adminLayout).toContain('width: max-content;')
expect(adminLayout).toContain('word-break: keep-all;')
})
it('keeps table ellipsis text content-sized without arbitrary character breaking', () => {
const ellipsisText = readSource('components/TableEllipsisText.vue')
expect(ellipsisText).toContain('display: inline-block;')
expect(ellipsisText).not.toMatch(/^\s*width:\s*100%;$/m)
expect(ellipsisText).not.toContain('word-break: break-all;')
})
})