feat: 管理端补充工作台图表、列表导出与批量操作

- 工作台新增近 7 日预约趋势与订单状态分布图

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

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

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

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

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

- ESLint 开启 vue/no-undef-properties,修复 EChart 扩展只注册一次的问题
This commit is contained in:
lik
2026-11-08 11:12:38 +08:00
parent b8b5c81352
commit c30ca3ed41
18 changed files with 1324 additions and 187 deletions
@@ -427,7 +427,7 @@ export const getRevenueChartOptions = (): EChartsOption => {
show: true,
color: getColor('secondary-color'),
margin: 15,
formatter: function (value: any) {
formatter: function (value: number | string) {
return '$' + value
},
},
+447 -36
View File
@@ -2,7 +2,17 @@
<PageBreadcrumb title="陪诊师管理" subtitle="业务管理" />
<div class="container-xxl">
<BCard no-body>
<div class="d-flex align-items-center gap-2 mb-3">
<BButton :variant="activeTab === 'employees' ? 'primary' : 'light'" @click="switchTab('employees')">
在职陪诊师
</BButton>
<BButton :variant="activeTab === 'applications' ? 'primary' : 'light'" @click="switchTab('applications')">
入驻审核
<span v-if="pendingTotal > 0" class="badge bg-danger ms-1">{{ pendingTotal }}</span>
</BButton>
</div>
<BCard v-if="activeTab === 'employees'" 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">
@@ -32,6 +42,10 @@
<div class="d-flex align-items-center gap-2">
<span class="text-muted fs-12">共 {{ total }} 人</span>
<BButton variant="light" :disabled="exporting" @click="exportEmployees">
<Icon icon="download" class="me-1" />
{{ exporting ? '导出中...' : '导出 CSV' }}
</BButton>
<BButton variant="success" @click="openCreate">
<Icon icon="plus" class="me-1" />
新增陪诊师
@@ -43,6 +57,15 @@
<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
@@ -117,11 +140,127 @@
</template>
</BTable>
<BCardFooter v-if="!loading" class="border-0">
<BCardFooter v-if="!loading && !loadError" class="border-0">
<TablePagination v-model:currentPage="page" :per-page="pageSize" :total-items="total" label="人" />
</BCardFooter>
</BCard>
<!-- 入驻审核:列表不带证件大图与身份证号,材料单独点开 -->
<BCard v-else 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="appFilters.keyword"
type="search"
class="form-control"
placeholder="姓名、手机号"
@keyup.enter="searchApplications"
/>
<Icon icon="search" class="app-search-icon text-muted" />
</div>
<BFormSelect v-model="appFilters.status" class="form-select" style="width: 130px">
<option value="pending">待审核</option>
<option value="approved">已通过</option>
<option value="rejected">已驳回</option>
<option value="all">全部</option>
</BFormSelect>
<BButton variant="primary" @click="searchApplications">
<Icon icon="search" class="me-1" />
查询
</BButton>
</div>
<span class="text-muted fs-12">共 {{ appTotal }} 条</span>
</BCardHeader>
<div v-if="appLoading" class="text-center py-5">
<BSpinner variant="primary" />
</div>
<div v-else-if="appLoadError" 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="loadApplications">
<Icon icon="refresh" class="me-1" />
重新加载
</BButton>
</div>
<BTable
v-else
show-empty
empty-text="没有符合条件的申请"
:items="applications"
:fields="appFields"
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">
<span class="text-uppercase fs-xxs">{{ data.label }}</span>
</template>
<template #cell(person)="{ 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.applicant?.name || '申').slice(0, 1) }}
</span>
<div>
<p class="fw-semibold mb-0">{{ item.applicant?.name || '-' }}</p>
<p class="text-muted mb-0 fs-12">{{ item.applicant?.mobile || '-' }}</p>
</div>
</div>
</template>
<template #cell(area)="{ item }">
<div class="text-truncate" style="max-width: 200px">
{{ (item.applicant?.serviceAreas || []).join('、') || '未填写服务城市' }}
</div>
<p class="text-muted mb-0 fs-12 text-truncate" style="max-width: 200px">
{{ item.applicant?.introduction || '未填写简介' }}
</p>
</template>
<template #cell(submittedAt)="{ item }">
{{ formatTimestamp(item.meta?.createtime) }}
</template>
<template #cell(status)="{ item }">
<span class="badge fs-xxs" :class="`badge-soft-${APPLICATION_STATUS_VARIANTS[item.status || 'pending']}`">
{{ APPLICATION_STATUS_LABELS[item.status || 'pending'] }}
</span>
<p
v-if="item.status === 'rejected' && item.review?.rejectReason"
class="text-muted mb-0 fs-12 mt-1 text-truncate"
style="max-width: 200px"
>
{{ item.review.rejectReason }}
</p>
</template>
<template #cell(action)="{ item }">
<div class="d-flex justify-content-center gap-1">
<BButton variant="light" class="btn btn-icon btn-sm rounded-circle" title="查看材料" @click="openMaterials(item)">
<Icon icon="photo" class="fs-lg" />
</BButton>
<template v-if="item.status === 'pending'">
<BButton variant="success" class="btn btn-icon btn-sm rounded-circle" title="通过" @click="openApprove(item)">
<Icon icon="check" class="fs-lg" />
</BButton>
<BButton variant="danger" class="btn btn-icon btn-sm rounded-circle" title="驳回" @click="openReject(item)">
<Icon icon="x" class="fs-lg" />
</BButton>
</template>
</div>
</template>
</BTable>
<BCardFooter v-if="!appLoading && !appLoadError" class="border-0">
<TablePagination v-model:currentPage="appPage" :per-page="appPageSize" :total-items="appTotal" label="条" />
</BCardFooter>
</BCard>
<BModal v-model="formVisible" :title="editingId ? '编辑陪诊师' : '新增陪诊师'" size="xl" hide-footer>
<BAlert v-if="formError" variant="danger" show class="py-2">{{ formError }}</BAlert>
@@ -256,26 +395,109 @@
</p>
<p class="text-muted mb-0 fs-12">停用后将不再出现在用户端陪诊师公示列表中。</p>
</ConfirmModal>
<BModal v-model="materialsVisible" title="申请材料" size="lg" hide-footer>
<div v-if="materialsLoading" class="text-center py-4">
<BSpinner variant="primary" />
</div>
<template v-else>
<p class="mb-3">
身份证号:<span class="font-monospace">{{ materials.applicantIdNumber || '未填写' }}</span>
</p>
<div class="mb-4">
<p class="fw-semibold mb-2">资质证书照片</p>
<img
v-if="materials.qualification"
:src="materials.qualification.data"
class="img-fluid rounded border"
alt="资质证书"
/>
<p v-else class="text-muted mb-0">未上传</p>
</div>
<div>
<p class="fw-semibold mb-2">健康证明照片</p>
<img
v-if="materials.healthCertificate"
:src="materials.healthCertificate.data"
class="img-fluid rounded border"
alt="健康证明"
/>
<p v-else class="text-muted mb-0">未上传</p>
<p v-if="materials.healthCertificate?.expireDate" class="text-muted fs-12 mt-2 mb-0">
有效期至 {{ String(materials.healthCertificate.expireDate).slice(0, 10) }}
</p>
</div>
</template>
</BModal>
<BModal v-model="rejectVisible" title="驳回申请" hide-footer>
<p class="mb-2">申请人:<strong>{{ rejectTarget?.applicant?.name || '-' }}</strong></p>
<label class="form-label">驳回原因 <span class="text-danger">*</span></label>
<BFormTextarea
v-model="rejectReason"
rows="3"
maxlength="200"
placeholder="请说明驳回原因,用户会在小程序申请页看到"
/>
<div class="d-flex justify-content-end gap-2 mt-3">
<BButton variant="light" @click="rejectVisible = false">取消</BButton>
<BButton variant="danger" :disabled="reviewing" @click="confirmReject">确认驳回</BButton>
</div>
</BModal>
<ConfirmModal
v-model="approveVisible"
title="通过入驻申请"
ok-title="确认通过"
ok-variant="success"
@confirm="confirmApprove"
>
<p class="mb-1">
确定通过 <strong>{{ approveTarget?.applicant?.name || '-' }}</strong> 的入驻申请吗?
</p>
<p class="text-muted mb-0 fs-12">
通过后将自动为其创建(或启用)陪诊师档案,小程序端权限立即生效。
</p>
</ConfirmModal>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { attendantApplicationApi } from '~/api/attendantApplication'
import { employeeApi } from '~/api/employee'
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 UserSelect from '~/components/UserSelect.vue'
import Icon from '~/components/wrappers/Icon.vue'
import type { Employee } from '~/types/api'
import type { AttendantApplication, Employee } from '~/types/api'
import { exportCsv } from '~/utils/csv'
import { fetchAllPages } from '~/utils/paging'
import {
EMPLOYEE_STATUS_LABELS,
EMPLOYEE_STATUS_VARIANTS,
ROLE_LABELS,
today,
} from '~/utils/format'
import { notify } from '~/utils/notify'
const APPLICATION_STATUS_LABELS: Record<string, string> = {
pending: '待审核',
approved: '已通过',
rejected: '已驳回',
}
const APPLICATION_STATUS_VARIANTS: Record<string, string> = {
pending: 'warning',
approved: 'success',
rejected: 'danger',
}
const activeTab = ref<'employees' | 'applications'>('employees')
const filters = reactive({
keyword: '',
role: 'attendant',
@@ -292,11 +514,73 @@ const fields = [
{ key: 'action', label: '操作' },
]
const employees = ref<Employee[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const {
items: employees,
total,
page,
pageSize,
loading,
loadError,
load,
search,
} = useTableQuery<Employee>(
(p, size) =>
employeeApi.list({
page: p,
pageSize: size,
keyword: filters.keyword.trim() || undefined,
role: filters.role || undefined,
status: filters.status || undefined,
}),
// 同页两个列表,页码监听由原有 watch 手动控制
{ autoWatch: false }
)
const exporting = ref(false)
const exportEmployees = async () => {
exporting.value = true
try {
const { items, total: all, truncated } = await fetchAllPages<Employee>(
async (p, size) => {
const data = await employeeApi.list({
page: p,
pageSize: size,
keyword: filters.keyword.trim() || undefined,
role: filters.role || undefined,
status: filters.status || undefined,
})
return { items: data.employees, total: data.total }
},
// 员工列表接口单页上限 100
{ pageSize: 100 }
)
exportCsv(
`attendants-${today()}.csv`,
['工号', '姓名', '手机号', '邮箱', '角色', '职称/部门', '状态', '工作年限', '累计接单', '服务区域', '擅长领域', '简介'],
items.map((item) => [
item.employeeNo || '',
item.profile?.name || '',
item.profile?.phone || '',
item.profile?.email || '',
ROLE_LABELS[item.role || ''] || item.role || '',
[item.work?.title, item.work?.department].filter(Boolean).join(' / '),
EMPLOYEE_STATUS_LABELS[item.status || ''] || item.status || '',
item.work?.workYears ?? 0,
item.attendantInfo?.orderCount ?? 0,
(item.attendantInfo?.serviceAreas || []).join('、'),
(item.attendantInfo?.specialties || []).join('、'),
item.introduction || '',
])
)
if (truncated) notify.warning(`已导出前 ${items.length} 条(共 ${all} 条),如需全量请缩小筛选范围`)
else notify.success(`已导出 ${items.length} 名员工`)
} catch {
// 错误提示由请求层统一弹出
} finally {
exporting.value = false
}
}
const formVisible = ref(false)
const formError = ref('')
@@ -330,39 +614,159 @@ const form = reactive({
const statusVisible = ref(false)
const statusTarget = ref<Employee | null>(null)
// ==================== 入驻审核 ====================
const appFields = [
{ key: 'person', label: '申请人' },
{ key: 'area', label: '服务城市 / 简介' },
{ key: 'submittedAt', label: '提交时间' },
{ key: 'status', label: '状态' },
{ key: 'action', label: '操作' },
]
const appFilters = reactive({ keyword: '', status: 'pending' })
const {
items: applications,
total: appTotal,
page: appPage,
pageSize: appPageSize,
loading: appLoading,
loadError: appLoadError,
load: loadApplications,
search: runApplicationSearch,
} = useTableQuery<AttendantApplication>(
(p, size) =>
attendantApplicationApi.list({
page: p,
pageSize: size,
status: appFilters.status || undefined,
keyword: appFilters.keyword.trim() || undefined,
}),
{ autoWatch: false }
)
const pendingTotal = ref(0)
const materialsVisible = ref(false)
const materialsLoading = ref(false)
const materials = ref<{
applicantIdNumber: string
qualification: { data: string; mime: string } | null
healthCertificate: { data: string; mime: string; expireDate?: string } | null
}>({ applicantIdNumber: '', qualification: null, healthCertificate: null })
const rejectVisible = ref(false)
const rejectTarget = ref<AttendantApplication | null>(null)
const rejectReason = ref('')
const approveVisible = ref(false)
const approveTarget = ref<AttendantApplication | null>(null)
const reviewing = ref(false)
const formatTimestamp = (value?: number) => {
if (!value) return '-'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return '-'
const pad = (n: number) => String(n).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
const searchApplications = () => runApplicationSearch()
// 页签角标统计的是待审核总数,不随当前筛选条件变化
const refreshPendingCount = async () => {
try {
const data = await attendantApplicationApi.list({ page: 1, pageSize: 1, status: 'pending' })
pendingTotal.value = data.total
} catch {
// 角标失败不影响主流程
}
}
const switchTab = (tab: 'employees' | 'applications') => {
activeTab.value = tab
if (tab !== 'applications') return
// 页码变化本身会触发 watch 加载,已停留在第 1 页时才需要手动拉一次
if (appPage.value === 1) loadApplications()
else appPage.value = 1
}
const openMaterials = async (row: AttendantApplication) => {
materialsVisible.value = true
materialsLoading.value = true
materials.value = { applicantIdNumber: '', qualification: null, healthCertificate: null }
try {
const data = await attendantApplicationApi.materials(row._id)
materials.value = {
applicantIdNumber: data.applicantIdNumber,
qualification: data.qualification,
healthCertificate: data.healthCertificate,
}
} catch {
// 请求层已统一提示
} finally {
materialsLoading.value = false
}
}
const openApprove = (row: AttendantApplication) => {
approveTarget.value = row
approveVisible.value = true
}
const confirmApprove = async () => {
const target = approveTarget.value
approveVisible.value = false
if (!target || reviewing.value) return
reviewing.value = true
try {
await attendantApplicationApi.review(target._id, { action: 'approve' })
notify.success('已通过,陪诊师权限已开通')
await Promise.all([loadApplications(), refreshPendingCount()])
} catch {
// 请求层已统一提示
} finally {
reviewing.value = false
}
}
const openReject = (row: AttendantApplication) => {
rejectTarget.value = row
rejectReason.value = ''
rejectVisible.value = true
}
const confirmReject = async () => {
const target = rejectTarget.value
if (!target || reviewing.value) return
if (!rejectReason.value.trim()) {
notify.error('请填写驳回原因')
return
}
reviewing.value = true
try {
await attendantApplicationApi.review(target._id, {
action: 'reject',
reason: rejectReason.value.trim(),
})
rejectVisible.value = false
notify.success('已驳回')
await Promise.all([loadApplications(), refreshPendingCount()])
} catch {
// 请求层已统一提示
} finally {
reviewing.value = false
}
}
const splitList = (value: string) =>
value
.split(/[,,、]/)
.map((item) => item.trim())
.filter(Boolean)
const load = async () => {
loading.value = true
try {
const data = await employeeApi.list({
page: page.value,
pageSize: pageSize.value,
keyword: filters.keyword.trim() || undefined,
role: filters.role || undefined,
status: filters.status || undefined,
})
employees.value = data.employees
total.value = data.total
const maxPage = Math.max(1, Math.ceil(data.total / pageSize.value))
if (page.value > maxPage) {
page.value = maxPage
return
}
} finally {
loading.value = false
}
}
const search = () => {
if (page.value === 1) load()
else page.value = 1
}
const reset = () => {
filters.keyword = ''
filters.role = 'attendant'
@@ -520,5 +924,12 @@ const confirmStatus = async () => {
watch(page, () => load())
onMounted(load)
watch(appPage, () => {
if (activeTab.value === 'applications') loadApplications()
})
onMounted(() => {
load()
refreshPendingCount()
})
</script>
+139 -3
View File
@@ -23,6 +23,36 @@
</BCol>
</BRow>
<BRow class="g-3 mt-1">
<BCol xl="8">
<BCard no-body class="h-100">
<BCardHeader>
<h5 class="card-title mb-0">近 7 日预约趋势</h5>
</BCardHeader>
<BCardBody>
<div v-if="loading" class="text-center py-5">
<BSpinner variant="primary" />
</div>
<EChart v-else :get-options="trendOptions" :extensions="CHART_EXTENSIONS" style="height: 280px; width: 100%" />
</BCardBody>
</BCard>
</BCol>
<BCol xl="4">
<BCard no-body class="h-100">
<BCardHeader>
<h5 class="card-title mb-0">订单状态分布</h5>
</BCardHeader>
<BCardBody>
<div v-if="loading" class="text-center py-5">
<BSpinner variant="primary" />
</div>
<EChart v-else :get-options="statusOptions" :extensions="CHART_EXTENSIONS" style="height: 280px; width: 100%" />
</BCardBody>
</BCard>
</BCol>
</BRow>
<BRow class="g-3 mt-1">
<BCol xl="8">
<BCard no-body class="h-100">
@@ -134,7 +164,12 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { LineChart, PieChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import type { EChartsOption } from 'echarts'
import { CanvasRenderer } from 'echarts/renderers'
import { escortApi } from '~/api/escort'
import EChart from '~/components/wrappers/EChart.vue'
import PageBreadcrumb from '~/components/PageBreadcrumb.vue'
import Icon from '~/components/wrappers/Icon.vue'
import type { EscortRecord } from '~/types/api'
@@ -148,6 +183,17 @@ import {
today,
} from '~/utils/format'
const CHART_EXTENSIONS = [LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer]
// 状态分布环形图配色(与 badge-soft 语义色对应)
const STATUS_COLORS: Record<string, string> = {
pending: '#f0ad4e',
confirmed: '#4d9ce8',
in_progress: '#5b6ee8',
completed: '#34c38f',
cancelled: '#98a6ad',
}
const loading = ref(true)
const recent = ref<EscortRecord[]>([])
const cancelRequests = ref<EscortRecord[]>([])
@@ -159,6 +205,9 @@ const summary = reactive({
unpaid: 0,
})
const statusCounts = reactive<Record<string, number>>({})
const trend = reactive<{ dates: string[]; counts: number[] }>({ dates: [], counts: [] })
const statCards = computed(() => [
{
label: '今日预约订单',
@@ -202,24 +251,111 @@ const recentFields = [
{ key: 'status', label: '状态' },
]
const trendOptions = computed<EChartsOption>(() => ({
tooltip: { trigger: 'axis' },
grid: { left: 8, right: 16, top: 28, bottom: 0, containLabel: true },
xAxis: {
type: 'category',
boundaryGap: false,
data: trend.dates,
axisTick: { show: false },
},
yAxis: { type: 'value', minInterval: 1, splitLine: { lineStyle: { type: 'dashed' } } },
series: [
{
name: '预约订单',
type: 'line',
smooth: true,
symbolSize: 6,
data: trend.counts,
lineStyle: { width: 2.5 },
areaStyle: { opacity: 0.08 },
itemStyle: { color: '#5b6ee8' },
},
],
}))
const statusOptions = computed<EChartsOption>(() => ({
tooltip: { trigger: 'item' },
legend: { bottom: 0, icon: 'circle', itemWidth: 8, itemHeight: 8, textStyle: { fontSize: 12 } },
series: [
{
name: '订单状态',
type: 'pie',
radius: ['52%', '76%'],
center: ['50%', '44%'],
avoidLabelOverlap: true,
label: { show: false },
itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
data: Object.keys(STATUS_LABELS).map((status) => ({
name: STATUS_LABELS[status],
value: statusCounts[status] || 0,
itemStyle: { color: STATUS_COLORS[status] },
})),
},
],
}))
const shiftDate = (days: number) => {
const date = new Date()
date.setDate(date.getDate() - days)
return formatDate(date)
}
const load = async () => {
loading.value = true
try {
const [todayRes, pendingRes, cancelRes, unpaidRes, recentRes, cancelListRes] = await Promise.all([
const statusKeys = Object.keys(STATUS_LABELS)
const [
todayRes,
cancelRes,
unpaidRes,
recentRes,
cancelListRes,
trendRes,
...statusResList
] = await Promise.all([
escortApi.list({ page: 1, pageSize: 1, appointmentDate: today() }),
escortApi.list({ page: 1, pageSize: 1, status: 'pending' }),
escortApi.list({ page: 1, pageSize: 1, cancelStatus: 'requested' }),
escortApi.list({ page: 1, pageSize: 1, paymentStatus: 'unpaid' }),
escortApi.list({ page: 1, pageSize: 8 }),
escortApi.list({ page: 1, pageSize: 5, cancelStatus: 'requested' }),
// 近 7 日订单,按预约日期在前端聚合出趋势
escortApi.list({
page: 1,
pageSize: 500,
startDate: shiftDate(6),
endDate: today(),
includeCancelled: '1',
}),
...statusKeys.map((status) => escortApi.list({ page: 1, pageSize: 1, status })),
])
summary.today = todayRes.total
summary.pending = pendingRes.total
summary.cancelRequested = cancelRes.total
summary.unpaid = unpaidRes.total
recent.value = recentRes.records
cancelRequests.value = cancelListRes.records
statusKeys.forEach((status, index) => {
statusCounts[status] = statusResList[index]?.total || 0
})
summary.pending = statusCounts.pending || 0
const countsByDate: Record<string, number> = {}
trendRes.records.forEach((item) => {
const date = formatDate(item.schedule?.date)
if (date !== '-') countsByDate[date] = (countsByDate[date] || 0) + 1
})
const dates: string[] = []
const counts: number[] = []
for (let i = 6; i >= 0; i--) {
const date = shiftDate(i)
dates.push(date.slice(5))
counts.push(countsByDate[date] || 0)
}
trend.dates = dates
trend.counts = counts
} finally {
loading.value = false
}
+97 -1
View File
@@ -42,6 +42,15 @@
>
{{ action.label }}
</BButton>
<BButton
v-if="canAssignAttendant"
variant="light"
:disabled="actionLoading"
@click="openAssign"
>
<Icon icon="user-check" class="me-1" />
{{ record.attendant?.id || record.attendant?.name ? '更换陪诊师' : '指派陪诊师' }}
</BButton>
<BButton v-if="canRecordOffline" variant="success" :disabled="actionLoading" @click="openPayment">
线下收款补录
</BButton>
@@ -324,6 +333,35 @@
<BButton variant="primary" @click="router.replace('/orders')">返回订单列表</BButton>
</div>
<BModal v-model="assignVisible" title="指派陪诊师" hide-footer>
<div v-if="assignLoading" class="text-center py-4">
<BSpinner variant="primary" />
</div>
<template v-else>
<p v-if="!attendants.length" class="text-muted mb-0">暂无在职陪诊师,请先在「陪诊师管理」中新增。</p>
<template v-else>
<BFormGroup label="选择陪诊师" label-for="assignAttendant" class="mb-3">
<BFormSelect id="assignAttendant" v-model="assignTarget">
<option :value="null" disabled>请选择在职陪诊师</option>
<option v-for="emp in attendants" :key="emp._id" :value="emp">
{{ emp.profile?.name || emp.employeeNo || emp._id }}{{ emp.profile?.phone ? `(${emp.profile.phone})` : '' }}
</option>
</BFormSelect>
</BFormGroup>
<BAlert v-if="assignTarget && !assignTarget.userId" variant="warning" show class="py-2 fs-12 mb-3">
该陪诊师未关联登录账号,指派后其无法在小程序端看到该订单。
</BAlert>
<p class="text-muted fs-12 mb-0">指派后陪诊师可在小程序端查看并处理该订单。</p>
</template>
<div class="d-flex justify-content-end gap-2 mt-4">
<BButton variant="light" @click="assignVisible = false">取消</BButton>
<BButton variant="primary" :disabled="assignSubmitting || !assignTarget" @click="submitAssign">
{{ assignSubmitting ? '提交中...' : '确认指派' }}
</BButton>
</div>
</template>
</BModal>
<BModal v-model="statusVisible" :title="statusTarget?.label || '确认操作'" :ok-title="statusTarget?.label || '确定'" @ok="confirmStatus">
<p class="mb-3">
确定将订单状态变更为
@@ -391,10 +429,11 @@
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { escortApi } from '~/api/escort'
import { employeeApi } from '~/api/employee'
import ConfirmModal from '~/components/ConfirmModal.vue'
import PageBreadcrumb from '~/components/PageBreadcrumb.vue'
import Icon from '~/components/wrappers/Icon.vue'
import type { EscortRecord, PaymentStatusResult } from '~/types/api'
import type { Employee, EscortRecord, PaymentStatusResult } from '~/types/api'
import {
CHANNEL_LABELS,
METHOD_LABELS,
@@ -470,6 +509,63 @@ const canRecordOffline = computed(() => {
&& ['pending', 'confirmed'].includes(record.value.status || '')
})
// 指派陪诊师:仅未进入取消流程且服务未结束时允许
const canAssignAttendant = computed(() => {
if (!record.value) return false
return (record.value.cancelStatus || 'none') === 'none'
&& ['pending', 'confirmed', 'in_progress'].includes(record.value.status || '')
})
const assignVisible = ref(false)
const assignLoading = ref(false)
const assignSubmitting = ref(false)
const attendants = ref<Employee[]>([])
const assignTarget = ref<Employee | null>(null)
const openAssign = async () => {
const currentId = record.value?.attendant?.id
assignTarget.value = currentId
? attendants.value.find((emp) => emp.userId && String(emp.userId) === String(currentId)) || null
: null
assignVisible.value = true
if (!attendants.value.length) {
assignLoading.value = true
try {
const data = await employeeApi.list({ page: 1, pageSize: 100, role: 'attendant', status: 'active' })
attendants.value = data.employees
} catch {
// 错误提示由请求层统一弹出
} finally {
assignLoading.value = false
}
}
}
const submitAssign = async () => {
if (!record.value || !assignTarget.value) return
const emp = assignTarget.value
// 后端 attendant.sex 枚举仅 none/male/female,员工档案里的 other 需归一到 none
const rawSex = emp.profile?.sex
const attendant = {
name: emp.profile?.name || '',
sex: rawSex === 'male' || rawSex === 'female' ? rawSex : 'none',
mobile: emp.profile?.phone || '',
...(emp.userId ? { id: emp.userId } : {}),
}
assignSubmitting.value = true
try {
// 后端 attendant 子文档结构:{ id: 关联登录用户ID, name, sex, mobile }
await escortApi.update(record.value._id, { attendant })
notify.success('陪诊师已指派')
assignVisible.value = false
await load()
} catch {
// 错误提示由请求层统一弹出
} finally {
assignSubmitting.value = false
}
}
const statusActions = computed<StatusAction[]>(() => {
const current = record.value
if (!current || current.cancelStatus === 'cancelled' || current.status === 'cancelled') return []
+128 -47
View File
@@ -11,25 +11,44 @@
type="search"
class="form-control"
placeholder="就诊人、手机号、医院、订单号"
@keyup.enter="search"
@keyup.enter="doSearch"
/>
<Icon icon="search" class="app-search-icon text-muted" />
</div>
<BButton variant="primary" @click="search">
<BButton variant="primary" @click="doSearch">
<Icon icon="search" class="me-1" />
查询
</BButton>
<BButton variant="light" @click="reset">重置</BButton>
</div>
<div class="text-muted fs-12">
共 <span class="fw-semibold">{{ total }}</span> 条
<span class="mx-2">|</span>
进行中 <span class="fw-semibold">{{ counts.ongoing }}</span> 条
<div class="d-flex align-items-center gap-2">
<div class="text-muted fs-12">
共 <span class="fw-semibold">{{ total }}</span> 条
<span class="mx-2">|</span>
进行中 <span class="fw-semibold">{{ counts.ongoing }}</span> 条
</div>
<BButton variant="light" :disabled="exporting" @click="exportRecords">
<Icon icon="download" class="me-1" />
{{ exporting ? '导出中...' : '导出 CSV' }}
</BButton>
</div>
</BCardHeader>
<BCardBody class="border-bottom border-light py-3">
<div class="d-flex flex-wrap gap-1 mb-3">
<BButton size="sm" :variant="filters.status === '' ? 'primary' : 'light'" @click="setStatus('')">全部</BButton>
<BButton
v-for="(label, value) in STATUS_LABELS"
:key="value"
size="sm"
:variant="filters.status === value ? 'primary' : 'light'"
@click="setStatus(value)"
>
{{ label }}
</BButton>
</div>
<BRow class="g-2">
<BCol md="6" xl="2">
<label class="form-label fs-12 mb-1">服务状态</label>
@@ -82,6 +101,15 @@
<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
@@ -165,7 +193,7 @@
</template>
</BTable>
<BCardFooter v-if="!loading" class="border-0">
<BCardFooter v-if="!loading && !loadError" class="border-0">
<TablePagination v-model:currentPage="page" :per-page="pageSize" :total-items="total" label="条" />
</BCardFooter>
</BCard>
@@ -184,15 +212,19 @@
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { escortApi, type EscortListQuery } from '~/api/escort'
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 type { EscortRecord } from '~/types/api'
import { exportCsv } from '~/utils/csv'
import { fetchAllPages } from '~/utils/paging'
import {
CANCEL_LABELS,
CHANNEL_LABELS,
PAYMENT_LABELS,
PAYMENT_VARIANTS,
@@ -201,10 +233,12 @@ import {
formatDate,
formatMoney,
shortId,
today,
} from '~/utils/format'
import { notify } from '~/utils/notify'
const route = useRoute()
const router = useRouter()
const queryText = (value: unknown) => (typeof value === 'string' ? value : '')
@@ -220,6 +254,8 @@ const filters = reactive({
userId: queryText(route.query.userId),
})
const counts = reactive({ ongoing: 0 })
const fields = [
{ key: 'patient', label: '就诊人' },
{ key: 'schedule', label: '预约时间' },
@@ -231,19 +267,12 @@ const fields = [
{ key: 'action', label: '操作' },
]
const records = ref<EscortRecord[]>([])
const total = ref(0)
const counts = reactive({ all: 0, ongoing: 0 })
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const deleteVisible = ref(false)
const deleteTarget = ref<EscortRecord | null>(null)
const buildQuery = (): EscortListQuery => ({
page: page.value,
pageSize: pageSize.value,
const buildQuery = (page: number, pageSize: number): EscortListQuery => ({
page,
pageSize,
keyword: filters.keyword.trim() || undefined,
status: filters.status || undefined,
cancelStatus: filters.cancelStatus || undefined,
@@ -257,28 +286,85 @@ const buildQuery = (): EscortListQuery => ({
userId: filters.userId || undefined,
})
const load = async () => {
loading.value = true
try {
const data = await escortApi.list(buildQuery())
records.value = data.records
total.value = data.total
counts.all = data.counts?.all || 0
counts.ongoing = data.counts?.ongoing || 0
const maxPage = Math.max(1, Math.ceil(data.total / pageSize.value))
if (page.value > maxPage) {
page.value = maxPage
return
}
} finally {
loading.value = false
}
// 筛选条件写回地址栏,刷新 / 分享链接后不丢
const syncUrl = () => {
const query: Record<string, string> = {}
Object.entries(filters).forEach(([key, value]) => {
if (value) query[key] = value
})
router.replace({ query })
}
const search = () => {
const {
items: records,
total,
page,
pageSize,
loading,
loadError,
load,
search,
refreshAfterRemove,
} = useTableQuery<EscortRecord>(async (p, size) => {
const data = await escortApi.list(buildQuery(p, size))
counts.ongoing = data.counts?.ongoing || 0
return { items: data.records, total: data.total }
})
const loadAndSync = async () => {
await load()
if (!loadError.value) syncUrl()
}
// 预约日期与日期范围互斥,选了范围时清掉单日筛选;同时把筛选写回地址栏
const doSearch = () => {
if (filters.startDate || filters.endDate) filters.appointmentDate = ''
if (page.value === 1) load()
else page.value = 1
syncUrl()
search()
}
const setStatus = (status: string) => {
filters.status = status
doSearch()
}
const exporting = ref(false)
const exportRecords = async () => {
exporting.value = true
try {
const { items, total: all, truncated } = await fetchAllPages<EscortRecord>(async (p, size) => {
const data = await escortApi.list(buildQuery(p, size))
return { items: data.records, total: data.total }
})
exportCsv(
`escort-orders-${today()}.csv`,
['订单号', '就诊人', '手机号', '医院', '科室', '服务', '陪诊师', '预约日期', '开始时间', '金额', '实收', '支付渠道', '支付状态', '服务状态', '取消状态'],
items.map((item) => [
item._id,
item.patient?.name || '',
item.patient?.mobile || '',
item.hospital?.name || '',
item.hospital?.department || '',
item.escort?.serviceName || '',
item.attendant?.name || '',
formatDate(item.schedule?.date),
item.schedule?.startTime || '',
(Number(item.payment?.totalFee) || 0).toFixed(2),
(Number(item.payment?.paidFee) || 0).toFixed(2),
CHANNEL_LABELS[item.payment?.payChannel || ''] || '',
PAYMENT_LABELS[item.payment?.status || 'unpaid'] || '',
STATUS_LABELS[item.status || ''] || '',
CANCEL_LABELS[item.cancelStatus || ''] || '',
])
)
if (truncated) notify.warning(`已导出前 ${items.length} 条(共 ${all} 条),如需全量请缩小筛选范围`)
else notify.success(`已导出 ${items.length} 条订单`)
} catch {
// 错误提示由请求层统一弹出
} finally {
exporting.value = false
}
}
const reset = () => {
@@ -293,12 +379,12 @@ const reset = () => {
endDate: '',
userId: '',
})
search()
doSearch()
}
const clearAppointmentDate = () => {
filters.appointmentDate = ''
search()
doSearch()
}
const openDelete = (item: EscortRecord) => {
@@ -313,16 +399,11 @@ const confirmDelete = async () => {
try {
await escortApi.remove(target._id)
notify.success('订单已删除')
const remaining = total.value - 1
const nextPage = Math.max(1, Math.min(page.value, Math.ceil(remaining / pageSize.value) || 1))
if (nextPage !== page.value) page.value = nextPage
else load()
refreshAfterRemove()
} catch {
// 错误提示由请求层统一弹出
}
}
watch(page, () => load())
onMounted(load)
onMounted(loadAndSync)
</script>
+110 -44
View File
@@ -6,11 +6,11 @@
<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.name" type="search" class="form-control" placeholder="就诊人姓名" @keyup.enter="search" />
<input v-model="filters.name" type="search" class="form-control" placeholder="就诊人姓名" @keyup.enter="doSearch" />
<Icon icon="search" class="app-search-icon text-muted" />
</div>
<BFormInput v-model="filters.mobile" placeholder="就诊人手机号" style="width: 160px" @keyup.enter="search" />
<BButton variant="primary" @click="search">
<BFormInput v-model="filters.mobile" placeholder="就诊人手机号" style="width: 160px" @keyup.enter="doSearch" />
<BButton variant="primary" @click="doSearch">
<Icon icon="search" class="me-1" />
查询
</BButton>
@@ -19,6 +19,10 @@
<div class="d-flex align-items-center gap-2">
<span class="text-muted fs-12">共 {{ total }} 位就诊人</span>
<BButton variant="light" :disabled="exporting" @click="exportProfiles">
<Icon icon="download" class="me-1" />
{{ exporting ? '导出中...' : '导出 CSV' }}
</BButton>
<BButton variant="success" @click="openCreate">
<Icon icon="plus" class="me-1" />
新增就诊人
@@ -37,6 +41,15 @@
<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
@@ -99,7 +112,7 @@
</template>
</BTable>
<BCardFooter v-if="!loading" class="border-0">
<BCardFooter v-if="!loading && !loadError" class="border-0">
<TablePagination v-model:currentPage="page" :per-page="pageSize" :total-items="total" label="位就诊人" />
</BCardFooter>
</BCard>
@@ -196,20 +209,24 @@
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, 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 UserSelect from '~/components/UserSelect.vue'
import Icon from '~/components/wrappers/Icon.vue'
import type { HealthProfile } from '~/types/api'
import { SEX_LABELS, formatDateTime } from '~/utils/format'
import { exportCsv } from '~/utils/csv'
import { fetchAllPages } from '~/utils/paging'
import { SEX_LABELS, formatDateTime, today } from '~/utils/format'
import { notify } from '~/utils/notify'
const route = useRoute()
const router = useRouter()
const queryText = (value: unknown) => (typeof value === 'string' ? value : '')
@@ -229,12 +246,7 @@ const fields = [
{ key: 'action', label: '操作' },
]
const profiles = ref<HealthProfile[]>([])
const ownerMap = ref<Record<string, string>>({})
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const formVisible = ref(false)
const formError = ref('')
@@ -275,32 +287,91 @@ const resolveOwners = async (list: HealthProfile[]) => {
}
}
const load = async () => {
loading.value = true
try {
const data = await profileApi.list({
page: page.value,
pageSize: pageSize.value,
name: filters.name.trim() || undefined,
mobile: filters.mobile.trim() || undefined,
userId: filters.userId || undefined,
})
profiles.value = data.list
total.value = data.total
await resolveOwners(data.list)
const maxPage = Math.max(1, Math.ceil(data.total / pageSize.value))
if (page.value > maxPage) {
page.value = maxPage
return
}
} finally {
loading.value = false
}
const buildQuery = (page: number, pageSize: number) => ({
page,
pageSize,
name: filters.name.trim() || undefined,
mobile: filters.mobile.trim() || undefined,
userId: filters.userId || undefined,
})
// 筛选条件写回地址栏,刷新 / 分享链接后不丢
const syncUrl = () => {
const query: Record<string, string> = {}
if (filters.name.trim()) query.name = filters.name.trim()
if (filters.mobile.trim()) query.mobile = filters.mobile.trim()
if (filters.userId) query.userId = filters.userId
router.replace({ query })
}
const search = () => {
if (page.value === 1) load()
else page.value = 1
const {
items: profiles,
total,
page,
pageSize,
loading,
loadError,
load,
search,
refreshAfterRemove,
} = useTableQuery<HealthProfile>(async (p, size) => {
const data = await profileApi.list(buildQuery(p, size))
await resolveOwners(data.list)
return { items: data.list, total: data.total }
})
const loadAndSync = async () => {
await load()
if (!loadError.value) syncUrl()
}
// 查询时把筛选写回地址栏,刷新 / 分享链接后不丢
const doSearch = () => {
syncUrl()
search()
}
const exporting = ref(false)
const exportProfiles = async () => {
exporting.value = true
try {
const { items, total: all, truncated } = await fetchAllPages<HealthProfile>(async (p, size) => {
const data = await profileApi.list(buildQuery(p, size))
return { items: data.list, total: data.total }
})
// 预取所有归属用户名称(每批 100,接口有单次上限),失败则回退显示用户ID
const ownerIds = [...new Set(items.map((item) => item.userId).filter(Boolean))] as string[]
for (let i = 0; i < ownerIds.length; i += 100) {
await resolveOwners(ownerIds.slice(i, i + 100).map((id) => ({ userId: id }) as HealthProfile))
}
exportCsv(
`health-profiles-${today()}.csv`,
['就诊人ID', '姓名', '手机号', '性别', '出生年月', '证件号', '身高cm', '体重kg', '血型', '归属用户', '省市', '详细地址', '备注', '创建时间'],
items.map((item) => [
item._id,
item.profile?.name || '',
item.profile?.mobile || '',
SEX_LABELS[item.profile?.sex || ''] || '',
item.profile?.birth || '',
item.profile?.idnumber || '',
item.health?.height ?? '',
item.health?.weight ?? '',
item.health?.bloodType || '',
item.userId ? ownerMap.value[item.userId] || item.userId : '未绑定',
[item.location?.province, item.location?.city].filter(Boolean).join(' / '),
item.location?.address || '',
item.health?.remark || '',
formatDateTime(item.meta?.createtime),
])
)
if (truncated) notify.warning(`已导出前 ${items.length} 条(共 ${all} 条),如需全量请缩小筛选范围`)
else notify.success(`已导出 ${items.length} 位就诊人`)
} catch {
// 错误提示由请求层统一弹出
} finally {
exporting.value = false
}
}
const reset = () => {
@@ -308,7 +379,7 @@ const reset = () => {
filters.mobile = ''
filters.userId = ''
filters.ownerName = ''
search()
doSearch()
}
const openCreate = () => {
@@ -415,19 +486,14 @@ const confirmDelete = async () => {
try {
await profileApi.remove(target._id)
notify.success('就诊人已删除')
const remaining = total.value - 1
const nextPage = Math.max(1, Math.min(page.value, Math.ceil(remaining / pageSize.value) || 1))
if (nextPage !== page.value) page.value = nextPage
else load()
refreshAfterRemove()
} catch {
// 错误提示由请求层统一弹出
}
}
watch(page, () => load())
onMounted(async () => {
await load()
await loadAndSync()
if (filters.userId && !filters.ownerName) {
await resolveOwners([{ userId: filters.userId } as HealthProfile])
filters.ownerName = ownerMap.value[filters.userId] || ''
+206 -43
View File
@@ -11,7 +11,7 @@
type="search"
class="form-control"
placeholder="昵称、手机号、邮箱"
@keyup.enter="search"
@keyup.enter="doSearch"
/>
<Icon icon="search" class="app-search-icon text-muted" />
</div>
@@ -20,15 +20,29 @@
<option value="normal">正常</option>
<option value="lock">已锁定</option>
</BFormSelect>
<BButton variant="primary" @click="search">
<BButton variant="primary" @click="doSearch">
<Icon icon="search" class="me-1" />
查询
</BButton>
<BButton variant="light" @click="reset">重置</BButton>
</div>
<div class="text-muted fs-12">
共 <span class="fw-semibold">{{ total }}</span> 位用户
<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>
@@ -49,6 +63,15 @@
<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
@@ -61,7 +84,25 @@
class="table table-custom table-nowrap table-centered mb-0 w-100"
>
<template #head()="data">
<span class="text-uppercase fs-xxs">{{ data.label }}</span>
<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 }">
@@ -142,7 +183,7 @@
</template>
</BTable>
<BCardFooter v-if="!loading" class="border-0">
<BCardFooter v-if="!loading && !loadError" class="border-0">
<TablePagination v-model:currentPage="page" :per-page="pageSize" :total-items="total" label="位用户" />
</BCardFooter>
</BCard>
@@ -163,22 +204,40 @@
锁定后该账号将无法登录,已登录会话也会失效。
</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 { onMounted, reactive, ref, watch } from 'vue'
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 { ACCOUNT_STATUS_LABELS, ROLE_LABELS, formatDateTime } from '~/utils/format'
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> = {
@@ -198,6 +257,7 @@ const filters = reactive({
})
const fields = [
{ key: 'select', label: '' },
{ key: 'user', label: '用户' },
{ key: 'email', label: '邮箱' },
{ key: 'province', label: '所在省份' },
@@ -208,16 +268,29 @@ const fields = [
{ key: 'action', label: '操作' },
]
const users = ref<UserView[]>([])
const profileCounts = ref<Record<string, number>>({})
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
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) {
@@ -232,33 +305,125 @@ const loadProfileCounts = async (list: UserView[]) => {
}
}
const load = async () => {
loading.value = true
try {
const data = await userApi.list({
page: page.value,
pageSize: pageSize.value,
keyword: filters.keyword.trim() || undefined,
accountStatus: filters.accountStatus || undefined,
startDate: filters.startDate || undefined,
endDate: filters.endDate || undefined,
})
users.value = data.users
total.value = data.total
await loadProfileCounts(data.users)
const maxPage = Math.max(1, Math.ceil(data.total / pageSize.value))
if (page.value > maxPage) {
page.value = maxPage
return
}
} finally {
loading.value = false
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 search = () => {
if (page.value === 1) load()
else page.value = 1
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 = () => {
@@ -266,7 +431,7 @@ const reset = () => {
filters.accountStatus = ''
filters.startDate = ''
filters.endDate = ''
search()
doSearch()
}
const openLock = (user: UserView) => {
@@ -288,7 +453,5 @@ const confirmLock = async () => {
}
}
watch(page, () => load())
onMounted(load)
onMounted(loadAndSync)
</script>