Files
web_escort_admin/src/views/users/index.vue
T
lik c30ca3ed41 feat: 管理端补充工作台图表、列表导出与批量操作
- 工作台新增近 7 日预约趋势与订单状态分布图

- 订单/用户/就诊人/陪诊师支持 CSV 导出,逐页拉取规避接口分页上限

- 订单列表增加状态快筛、筛选条件同步地址栏、加载失败重试

- 订单详情支持指派/更换陪诊师,性别值归一到订单枚举

- 用户列表支持批量锁定/解锁,导出补齐就诊人数量与归属信息

- 抽取 useTableQuery 统一分页、搜索与删除后页码回退

- ESLint 开启 vue/no-undef-properties,修复 EChart 扩展只注册一次的问题
2026-11-08 11:12:38 +08:00

458 lines
15 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<PageBreadcrumb title="用户管理" subtitle="业务管理" />
<div class="container-xxl">
<BCard no-body>
<BCardHeader class="border-light d-flex flex-wrap justify-content-between align-items-center gap-2">
<div class="d-flex flex-wrap align-items-center gap-2">
<div class="app-search">
<input
v-model="filters.keyword"
type="search"
class="form-control"
placeholder="昵称、手机号、邮箱"
@keyup.enter="doSearch"
/>
<Icon icon="search" class="app-search-icon text-muted" />
</div>
<BFormSelect v-model="filters.accountStatus" class="form-select" style="width: 130px">
<option value="">全部状态</option>
<option value="normal">正常</option>
<option value="lock">已锁定</option>
</BFormSelect>
<BButton variant="primary" @click="doSearch">
<Icon icon="search" class="me-1" />
查询
</BButton>
<BButton variant="light" @click="reset">重置</BButton>
</div>
<div class="d-flex align-items-center gap-2">
<span class="text-muted fs-12">共 <span class="fw-semibold">{{ total }}</span> 位用户</span>
<template v-if="selected.length">
<BButton variant="danger" size="sm" @click="openBatchLock(true)">
<Icon icon="lock" class="me-1" />
锁定所选({{ selected.length }})
</BButton>
<BButton variant="success" size="sm" @click="openBatchLock(false)">
<Icon icon="lock-open" class="me-1" />
解锁所选
</BButton>
</template>
<BButton variant="light" :disabled="exporting" @click="exportUsers">
<Icon icon="download" class="me-1" />
{{ exporting ? '导出中...' : '导出 CSV' }}
</BButton>
</div>
</BCardHeader>
<BCardBody class="border-bottom border-light py-3">
<BRow class="g-2">
<BCol md="3">
<label class="form-label fs-12 mb-1">注册开始日期</label>
<BFormInput v-model="filters.startDate" type="date" />
</BCol>
<BCol md="3">
<label class="form-label fs-12 mb-1">注册结束日期</label>
<BFormInput v-model="filters.endDate" type="date" />
</BCol>
</BRow>
</BCardBody>
<div v-if="loading" class="text-center py-5">
<BSpinner variant="primary" />
</div>
<div v-else-if="loadError" class="text-center py-5">
<Icon icon="cloud-off" class="fs-32 text-muted mb-2" />
<p class="text-muted">数据加载失败,请检查网络后重试</p>
<BButton variant="primary" size="sm" @click="load">
<Icon icon="refresh" class="me-1" />
重新加载
</BButton>
</div>
<BTable
v-else
show-empty
empty-text="没有符合条件的用户"
:items="users"
:fields="fields"
thead-class="bg-light align-middle bg-opacity-25 thead-sm"
hover
responsive
class="table table-custom table-nowrap table-centered mb-0 w-100"
>
<template #head()="data">
<input
v-if="data.field.key === 'select'"
type="checkbox"
class="form-check-input"
:checked="allSelected"
title="全选本页"
@change="toggleAll"
/>
<span v-else class="text-uppercase fs-xxs">{{ data.label }}</span>
</template>
<template #cell(select)="{ item }">
<input
v-if="item._id !== auth.user?._id"
v-model="selected"
type="checkbox"
class="form-check-input"
:value="item._id"
/>
</template>
<template #cell(user)="{ item }">
<div class="d-flex align-items-center">
<span class="avatar-md d-flex align-items-center justify-content-center rounded-circle bg-primary-subtle text-primary fw-semibold me-2">
{{ (item.profile?.name || item.profile?.mobile || '用').slice(0, 1) }}
</span>
<div>
<RouterLink :to="`/users/${item._id}`" class="fw-semibold link-reset">
{{ item.profile?.name || '未填写昵称' }}
</RouterLink>
<p class="text-muted mb-0 fs-12">{{ item.profile?.mobile || '-' }}</p>
</div>
</div>
</template>
<template #cell(email)="{ item }">
{{ item.profile?.email || '-' }}
</template>
<template #cell(province)="{ item }">
<template v-if="item.location?.province">
{{ item.location.province }}
<span v-if="item.location.city" class="text-muted fs-12">/ {{ item.location.city }}</span>
</template>
<span v-else class="text-muted">-</span>
</template>
<template #cell(profiles)="{ item }">
<RouterLink :to="`/profiles?userId=${item._id}`" class="link-reset">
{{ profileCounts[item._id] ?? 0 }} 位
</RouterLink>
</template>
<template #cell(apps)="{ item }">
<template v-if="item.apps?.length">
<span
v-for="app in item.apps"
:key="app.appId"
class="badge badge-soft-secondary me-1"
:class="{ 'badge-soft-danger': app.status !== 'active' }"
>
{{ appLabel(app.appId) }}
<span v-if="app.roles?.length"> / {{ app.roles.map(roleLabel).join(',') }}</span>
</span>
</template>
<span v-else class="text-muted">-</span>
</template>
<template #cell(account)="{ item }">
<span
class="badge fs-xxs"
:class="item.status?.account === 'lock' ? 'badge-soft-danger' : 'badge-soft-success'"
>
{{ ACCOUNT_STATUS_LABELS[item.status?.account || 'normal'] || '正常' }}
</span>
</template>
<template #cell(createdAt)="{ item }">
{{ formatDateTime(item.meta?.createtime) }}
</template>
<template #cell(action)="{ item }">
<div class="d-flex justify-content-center gap-1">
<RouterLink :to="`/users/${item._id}`" class="btn btn-light btn-icon btn-sm rounded-circle" title="查看详情">
<Icon icon="eye" class="fs-lg" />
</RouterLink>
<BButton
v-if="item._id !== auth.user?._id"
:variant="item.status?.account === 'lock' ? 'success' : 'danger'"
class="btn btn-icon btn-sm rounded-circle"
:title="item.status?.account === 'lock' ? '解锁账号' : '锁定账号'"
@click="openLock(item)"
>
<Icon :icon="item.status?.account === 'lock' ? 'lock-open' : 'lock'" class="fs-lg" />
</BButton>
</div>
</template>
</BTable>
<BCardFooter v-if="!loading && !loadError" class="border-0">
<TablePagination v-model:currentPage="page" :per-page="pageSize" :total-items="total" label="位用户" />
</BCardFooter>
</BCard>
<ConfirmModal
v-model="lockVisible"
:title="lockTarget?.status?.account === 'lock' ? '解锁账号' : '锁定账号'"
:ok-title="lockTarget?.status?.account === 'lock' ? '确认解锁' : '确认锁定'"
:ok-variant="lockTarget?.status?.account === 'lock' ? 'success' : 'danger'"
@confirm="confirmLock"
>
<p class="mb-1">
确定{{ lockTarget?.status?.account === 'lock' ? '解锁' : '锁定' }}用户
<strong>{{ lockTarget?.profile?.name || lockTarget?.profile?.mobile || lockTarget?._id }}</strong>
吗?
</p>
<p v-if="lockTarget?.status?.account !== 'lock'" class="text-muted mb-0 fs-12">
锁定后该账号将无法登录,已登录会话也会失效。
</p>
</ConfirmModal>
<ConfirmModal
v-model="batchLockVisible"
:title="batchLocked ? '批量锁定账号' : '批量解锁账号'"
:ok-title="batchLocked ? '确认锁定' : '确认解锁'"
:ok-variant="batchLocked ? 'danger' : 'success'"
@confirm="confirmBatchLock"
>
<p class="mb-1">
确定{{ batchLocked ? '锁定' : '解锁' }}所选的 <strong>{{ selected.length }}</strong> 个账号吗?
</p>
<p v-if="batchLocked" class="text-muted mb-0 fs-12">锁定后这些账号将无法登录,已登录会话也会失效。</p>
</ConfirmModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { profileApi } from '~/api/profile'
import { userApi } from '~/api/user'
import { useTableQuery } from '~/composables/useTableQuery'
import ConfirmModal from '~/components/ConfirmModal.vue'
import PageBreadcrumb from '~/components/PageBreadcrumb.vue'
import TablePagination from '~/components/TablePagination.vue'
import Icon from '~/components/wrappers/Icon.vue'
import { useAuthStore } from '~/stores/auth'
import type { UserView } from '~/types/api'
import { exportCsv } from '~/utils/csv'
import { fetchAllPages } from '~/utils/paging'
import { ACCOUNT_STATUS_LABELS, ROLE_LABELS, formatDateTime, today } from '~/utils/format'
import { notify } from '~/utils/notify'
const router = useRouter()
const auth = useAuthStore()
const APP_LABELS: Record<string, string> = {
'wxapp-escort': 'C端用户',
'wxapp-escort-admin': '陪诊小程序',
'web-escort-admin': 'Web后台',
}
const appLabel = (appId: string) => APP_LABELS[appId] || appId
const roleLabel = (role: string) => ROLE_LABELS[role] || role
const filters = reactive({
keyword: '',
accountStatus: '',
startDate: '',
endDate: '',
})
const fields = [
{ key: 'select', label: '' },
{ key: 'user', label: '用户' },
{ key: 'email', label: '邮箱' },
{ key: 'province', label: '所在省份' },
{ key: 'profiles', label: '就诊人' },
{ key: 'apps', label: '应用与角色' },
{ key: 'account', label: '账号状态' },
{ key: 'createdAt', label: '注册时间' },
{ key: 'action', label: '操作' },
]
const lockVisible = ref(false)
const lockTarget = ref<UserView | null>(null)
const buildQuery = (page: number, pageSize: number) => ({
page,
pageSize,
keyword: filters.keyword.trim() || undefined,
accountStatus: filters.accountStatus || undefined,
startDate: filters.startDate || undefined,
endDate: filters.endDate || undefined,
})
// 筛选条件写回地址栏,刷新 / 分享链接后不丢
const syncUrl = () => {
const query: Record<string, string> = {}
Object.entries(filters).forEach(([key, value]) => {
if (value) query[key] = value
})
router.replace({ query })
}
const profileCounts = ref<Record<string, number>>({})
// 就诊人数量仅用于展示,接口失败时显示 0,不影响用户列表
const loadProfileCounts = async (list: UserView[]) => {
if (!list.length) {
profileCounts.value = {}
return
}
try {
const data = await profileApi.counts(list.map((item) => item._id))
profileCounts.value = data.counts
} catch {
profileCounts.value = {}
}
}
const selected = ref<string[]>([])
const {
items: users,
total,
page,
pageSize,
loading,
loadError,
load,
search,
} = useTableQuery<UserView>(async (p, size) => {
const data = await userApi.list(buildQuery(p, size))
await loadProfileCounts(data.users)
// 换页 / 重新搜索后清空选择,避免误操作不可见账号
selected.value = []
return { items: data.users, total: data.total }
})
// 查询时把筛选写回地址栏,刷新 / 分享链接后不丢
const doSearch = () => {
syncUrl()
search()
}
// ==================== 批量锁定 / 解锁 ====================
const allSelected = computed(
() => users.value.length > 0 && users.value.every((u) => u._id === auth.user?._id || selected.value.includes(u._id))
)
const toggleAll = () => {
if (allSelected.value) {
selected.value = []
} else {
selected.value = users.value.filter((u) => u._id !== auth.user?._id).map((u) => u._id)
}
}
const batchLockVisible = ref(false)
const batchLocked = ref(true)
const batchRunning = ref(false)
const openBatchLock = (locked: boolean) => {
batchLocked.value = locked
batchLockVisible.value = true
}
// 后端 /user/lock 为单用户接口,这里串行逐个调用并汇总结果
const confirmBatchLock = async () => {
if (!selected.value.length || batchRunning.value) return
batchRunning.value = true
try {
let ok = 0
let fail = 0
for (const userId of selected.value) {
try {
await userApi.lock(userId, batchLocked.value)
ok++
} catch {
fail++
}
}
if (fail) notify.warning(`批量操作完成:${ok} 个成功,${fail} 个失败`)
else notify.success(`已${batchLocked.value ? '锁定' : '解锁'} ${ok} 个账号`)
batchLockVisible.value = false
selected.value = []
await load()
} finally {
batchRunning.value = false
}
}
const loadAndSync = async () => {
await load()
if (!loadError.value) syncUrl()
}
const exporting = ref(false)
const exportUsers = async () => {
exporting.value = true
try {
const { items, total: all, truncated } = await fetchAllPages<UserView>(async (p, size) => {
const data = await userApi.list(buildQuery(p, size))
return { items: data.users, total: data.total }
})
// 补齐所有导出用户的就诊人数量(接口单次上限 200,按批查询)
const counts: Record<string, number> = { ...profileCounts.value }
for (let i = 0; i < items.length; i += 200) {
try {
const data = await profileApi.counts(items.slice(i, i + 200).map((u) => u._id))
Object.assign(counts, data.counts)
} catch {
// 统计失败时回退到已有缓存,不阻断导出
}
}
exportCsv(
`users-${today()}.csv`,
['用户ID', '昵称', '手机号', '邮箱', '省份', '城市', '就诊人数', '应用与角色', '账号状态', '注册时间'],
items.map((item) => [
item._id,
item.profile?.name || '',
item.profile?.mobile || '',
item.profile?.email || '',
item.location?.province || '',
item.location?.city || '',
counts[item._id] ?? 0,
(item.apps || []).map((app) => `${appLabel(app.appId)}${app.roles?.length ? `/${app.roles.map(roleLabel).join(',')}` : ''}`).join(' '),
ACCOUNT_STATUS_LABELS[item.status?.account || 'normal'] || '正常',
formatDateTime(item.meta?.createtime),
])
)
if (truncated) notify.warning(`已导出前 ${items.length} 条(共 ${all} 条),如需全量请缩小筛选范围`)
else notify.success(`已导出 ${items.length} 位用户`)
} catch {
// 错误提示由请求层统一弹出
} finally {
exporting.value = false
}
}
const reset = () => {
filters.keyword = ''
filters.accountStatus = ''
filters.startDate = ''
filters.endDate = ''
doSearch()
}
const openLock = (user: UserView) => {
lockTarget.value = user
lockVisible.value = true
}
const confirmLock = async () => {
const target = lockTarget.value
lockVisible.value = false
if (!target) return
const locked = target.status?.account !== 'lock'
try {
await userApi.lock(target._id, locked)
notify.success(locked ? '账号已锁定' : '账号已解锁')
await load()
} catch {
// 错误提示由请求层统一弹出
}
}
onMounted(loadAndSync)
</script>