Files
JayuCloud/JC-Salon-Frontend/src/views/admin/UsersView.vue
T
2026-11-08 00:27:37 +08:00

1359 lines
49 KiB
Vue

<template>
<div class="users">
<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 && canCreateUser" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增店长
</a-button>
</div>
</template>
<AdminFilterPanel :active-count="activeMobileFilterCount">
<a-select
v-model:value="shopFilter"
:allow-clear="currentUserType === 4"
placeholder="所属店铺"
style="width: 180px"
:loading="shopLoading"
:disabled="currentUserType !== 4 && !!currentUserInfo?.shopId"
@change="handleSearch"
>
<a-select-option
v-for="shop in shopList"
:key="shop.id"
:value="getShopOptionValue(shop)"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
<a-select v-model:value="statusFilter" allow-clear placeholder="账号状态" style="width: 140px" @change="handleSearch">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">停用</a-select-option>
</a-select>
<a-range-picker v-model:value="createdRange" value-format="YYYY-MM-DD HH:mm:ss" show-time @change="handleSearch" />
<a-select v-model:value="hasPhoneFilter" allow-clear placeholder="手机号" style="width: 130px" @change="handleSearch">
<a-select-option value="true">有手机号</a-select-option>
<a-select-option value="false">无手机号</a-select-option>
</a-select>
<a-select v-model:value="hasOrderFilter" allow-clear placeholder="订单情况" style="width: 130px" @change="handleSearch">
<a-select-option value="true">有订单</a-select-option>
<a-select-option value="false">无订单</a-select-option>
</a-select>
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="userList"
:loading="loading"
:pagination="pagination"
row-key="id"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'avatar'">
<a-avatar :size="40" :src="record.avatar || DEFAULT_AVATAR" />
</template>
<template v-else-if="column.key === 'shopName'">
{{ getShopDisplay(record) || '-' }}
</template>
<template v-else-if="column.key === 'type'">
<a-tag :color="getUserTypeColor(record.type)">
{{ getUserTypeText(record.type) }}
</a-tag>
</template>
<template v-else-if="column.key === 'level'">
<a-tag :color="record.level && record.level !== '普通' ? 'gold' : 'default'">
{{ record.level || '普通' }}
</a-tag>
</template>
<template v-else-if="column.key === 'status'">
<a-switch
:checked="record.status === 1"
:disabled="!hasPermission('user:disable') || record.type === 4"
@change="(checked: any) => handleStatusChange(record, checked === true)"
/>
</template>
<template v-else-if="column.key === 'actions'">
<a-space wrap>
<a-button v-if="hasPermission('user:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('user:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button
v-if="hasPermission('user:reset_password')"
type="link"
size="small"
@click="handleResetPassword(record)"
>
重置密码
</a-button>
<a-popconfirm
v-if="canShowUnbind(record)"
:title="getUnbindConfirmText(record)"
@confirm="handleUnbind(record)"
>
<a-button type="link" size="small">
解绑
</a-button>
</a-popconfirm>
<a-popconfirm
v-if="canShowDelete(record)"
title="确定要删除这个用户吗?删除后账号将被标记为已删除。"
@confirm="handleDelete(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="userList" empty-description="暂无用户数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="mobile-user-head">
<a-avatar :size="44" :src="item.avatar || DEFAULT_AVATAR" />
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.nickname || item.account }}</div>
<div class="admin-mobile-card__subtitle">{{ item.account }} · {{ item.phone || '未绑定手机号' }}</div>
</div>
</div>
<a-tag :color="getUserTypeColor(item.type)">
{{ getUserTypeText(item.type) }}
</a-tag>
</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>所属店铺</span>
<strong>{{ getShopDisplay(item) || '-' }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>状态</span>
<strong>{{ item.status === 1 ? '正常' : '禁用' }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('user:view')" size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('user:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
<a-button v-if="hasPermission('user:reset_password')" size="small" @click="handleResetPassword(item)">
重置密码
</a-button>
<a-button v-if="canShowUnbind(item)" size="small" @click="handleUnbind(item)">解绑</a-button>
<a-button v-if="canShowDelete(item)" size="small" danger @click="handleDelete(item)">删除</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalVisible"
:title="isEdit ? '编辑店长' : '新增店长'"
: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="account">
<a-input
v-model:value="formState.account"
:placeholder="isEdit && isMaskedSensitiveValue(currentUser?.account) ? '已设置账号,留空保持不变' : '请输入账号'"
@input="handleAccountInput"
/>
</a-form-item>
<a-form-item label="昵称" name="nickname">
<a-input v-model:value="formState.nickname" placeholder="请输入昵称" />
</a-form-item>
<a-form-item label="手机号" name="phone">
<a-input
v-model:value="formState.phone"
:placeholder="phonePlaceholder"
:maxlength="11"
inputmode="numeric"
autocomplete="off"
@focus="handlePhoneFocus"
@input="handlePhoneInput"
/>
</a-form-item>
<a-form-item label="生日" name="birthday">
<a-date-picker
v-model:value="formState.birthday"
value-format="YYYY-MM-DD"
format="YYYY-MM-DD"
placeholder="请选择生日"
class="user-date-picker"
popup-class-name="jayucloud-salon-date-picker-panel"
/>
</a-form-item>
<a-form-item
label="微信号"
name="wechatId"
>
<a-input v-model:value="formState.wechatId" placeholder="选填" />
</a-form-item>
<a-form-item label="微信二维码" name="wechatQrCode">
<div class="wechat-qr-field">
<a-upload
accept="image/jpeg,image/png,image/webp"
:show-upload-list="false"
:before-upload="beforeUploadWechatQr"
:custom-request="handleWechatQrUpload"
>
<img
v-if="formState.wechatQrCode"
:src="formState.wechatQrCode"
alt="微信二维码"
class="wechat-qr-preview"
/>
<a-button v-else :loading="wechatQrUploading">上传二维码</a-button>
</a-upload>
<a-button v-if="formState.wechatQrCode" type="link" danger size="small" @click="formState.wechatQrCode = ''">
删除二维码
</a-button>
</div>
</a-form-item>
<a-form-item
v-if="!isEdit"
label="密码"
name="password"
extra="留空则使用系统设置中配置的店长默认密码"
>
<a-input-password
v-model:value="formState.password"
placeholder="不填则使用默认密码"
autocomplete="new-password"
/>
</a-form-item>
<a-form-item
label="所属店铺"
name="shopIds"
:required="Number(formState.type) !== 4"
>
<a-select
v-model:value="formState.shopIds"
mode="multiple"
:placeholder="Number(formState.type) === 4 ? '平台管理员无需绑定店铺' : (currentUserType === 4 ? '请选择一个或多个店铺' : '请选择店铺')"
:loading="shopLoading"
:disabled="Number(formState.type) === 4 || (currentUserType !== 4 && !!currentUserInfo?.shopId)"
>
<a-select-option
v-for="shop in shopList"
:key="shop.id"
:value="getShopOptionValue(shop)"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="用户类型" name="type" style="display: none">
<a-select v-model:value="formState.type" placeholder="请选择用户类型">
<a-select-option
v-for="option in availableUserTypeOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看用户详情"
:footer="null"
:desktop-width="640"
@cancel="viewModalVisible = false"
>
<a-descriptions bordered :column="1" size="small">
<a-descriptions-item label="联系电话">{{ viewRecord?.contactPhone || '-' }}</a-descriptions-item>
<a-descriptions-item label="生日">{{ viewRecord?.birthday || '-' }}</a-descriptions-item>
<a-descriptions-item label="微信号">{{ viewRecord?.wechatId || '-' }}</a-descriptions-item>
<a-descriptions-item label="微信二维码">
<img v-if="viewRecord?.wechatQrCode" :src="viewRecord.wechatQrCode" alt="微信二维码" class="wechat-qr-preview" />
<span v-else>-</span>
</a-descriptions-item>
<a-descriptions-item label="账号">{{ viewRecord?.account || '-' }}</a-descriptions-item>
<a-descriptions-item label="昵称">{{ viewRecord?.nickname || '-' }}</a-descriptions-item>
<a-descriptions-item label="手机号">{{ viewRecord?.phone || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ getShopDisplay(viewRecord) || '-' }}</a-descriptions-item>
<a-descriptions-item label="用户类型">{{ getUserTypeText(viewRecord?.type || 0) }}</a-descriptions-item>
<a-descriptions-item label="状态">{{ viewRecord?.status === 1 ? '正常' : '禁用' }}</a-descriptions-item>
<a-descriptions-item label="创建时间">{{ viewRecord?.createTime || '-' }}</a-descriptions-item>
</a-descriptions>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && canCreateUser && !modalVisible && !viewModalVisible"
label="新增店长"
@click="showAddModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* UsersView 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, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import { DEFAULT_AVATAR } from '@/constants'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
/**
* Purpose: AvailabilityCheckResponse supports UsersView.vue by holding or executing the availability check 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 { userApi, type AvailabilityCheckResponse } from '@/api/user'
import {
adminFileApi,
adminShopApi,
adminSystemParameterConfigApi,
adminUserApi,
type Shop,
type UserVO
} from '@/api/admin'
import { sameId } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
const FALLBACK_ADMIN_DEFAULT_PASSWORD = 'Fingertip@123'
/** 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
}
})()
const copyTextToClipboard = async (value: string) => {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(value)
} else {
const textarea = document.createElement('textarea')
textarea.value = value
textarea.setAttribute('readonly', 'readonly')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
message.success('默认密码已复制')
} catch (error) {
console.error('复制默认密码失败:', error)
message.warning('复制失败,请手动复制')
}
}
const resolveAdminDefaultPasswordForNotice = async () => {
try {
const response = await adminSystemParameterConfigApi.getUserDefaultPassword()
return response?.password?.trim() || FALLBACK_ADMIN_DEFAULT_PASSWORD
} catch (error) {
console.error('获取后台默认密码失败:', error)
return FALLBACK_ADMIN_DEFAULT_PASSWORD
}
}
const showDefaultPasswordCreateNotice = async () => {
const password = await resolveAdminDefaultPasswordForNotice()
Modal.success({
title: '用户创建成功',
content: h('div', { class: 'default-password-notice' }, [
h('p', '本次使用后台默认密码,请提醒用户首次登录后修改。'),
h('div', { class: 'default-password-notice__value' }, password)
]),
okText: '一键复制密码',
onOk: () => copyTextToClipboard(password)
})
}
const showDefaultPasswordResetNotice = async () => {
const password = await resolveAdminDefaultPasswordForNotice()
Modal.success({
title: '密码重置成功',
content: h('div', { class: 'default-password-notice' }, [
h('p', '该用户的密码已重置为后台默认密码,请及时告知用户并提醒首次登录后修改。'),
h('div', { class: 'default-password-notice__value' }, password)
]),
okText: '一键复制密码',
onOk: () => copyTextToClipboard(password)
})
}
/** normalizeUserType is a local helper used by this page script. */
const normalizeUserType = (value: unknown) => {
const type = Number(value)
return Number.isFinite(type) ? type : -1
}
/** 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)
/** 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)
/** 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: shopFilter supports UsersView.vue by holding or executing the shop filter 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 shopFilter = ref<string | undefined>()
/**
* Purpose: typeFilter supports UsersView.vue by holding or executing the type filter 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 typeFilter = ref<number | undefined>(2)
/**
* Purpose: statusFilter supports UsersView.vue by holding or executing the status filter 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 statusFilter = ref<number | undefined>()
/**
* Purpose: createdRange supports UsersView.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: hasPhoneFilter supports UsersView.vue by holding or executing the has phone filter 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 hasPhoneFilter = ref<'true' | 'false' | undefined>()
/**
* Purpose: hasOrderFilter supports UsersView.vue by holding or executing the has order filter 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 hasOrderFilter = ref<'true' | 'false' | undefined>()
/**
* Purpose: formRef supports UsersView.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: userList supports UsersView.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: shopList supports UsersView.vue by holding or executing the shop 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 shopList = ref<Shop[]>([])
/**
* Purpose: currentUser supports UsersView.vue by holding or executing the current 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 currentUser = ref<UserVO | null>(null)
/**
* Purpose: viewRecord supports UsersView.vue by holding or executing the view record 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 viewRecord = ref<UserVO | null>(null)
/**
* Purpose: draftSavedAt supports UsersView.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)
/** currentUserType is a reactive state variable used by the template and event handlers. */
const currentUserType = computed(() => normalizeUserType(currentUserInfo?.type))
/** availableUserTypeOptions is a reactive state variable used by the template and event handlers. */
const availableUserTypeOptions = computed(() => {
if (currentUserType.value === 4) {
return [
{ value: 0, label: '用户' },
{ value: 2, label: '店长' },
{ value: 3, label: '美甲师' },
{ value: 4, label: '管理员' }
]
}
if (currentUserType.value === 2) {
return [
{ value: 0, label: '用户' },
{ value: 3, label: '美甲师' }
]
}
if (currentUserType.value === 3) {
return [
{ value: 0, label: '用户' }
]
}
return []
})
/** canCreateUser is a reactive state variable used by the template and event handlers. */
const canCreateUser = computed(() =>
hasPermission('user:create') || currentUserType.value === 2 || currentUserType.value === 4
)
/** canDeleteUser is a reactive state variable used by the template and event handlers. */
const canDeleteUser = computed(() =>
currentUserType.value === 4 && hasPermission('user:delete')
)
/** canUnbindUser is a reactive state variable used by the template and event handlers. */
const canUnbindUser = computed(() =>
hasPermission('user:unbind')
)
/** activeMobileFilterCount summarizes applied filters while the mobile panel is collapsed. */
const activeMobileFilterCount = computed(() => {
const values = [
currentUserType.value === 4 ? shopFilter.value : undefined,
typeFilter.value,
statusFilter.value,
createdRange.value,
hasPhoneFilter.value,
hasOrderFilter.value
]
return values.filter(isActiveFilterValue).length
})
/**
* Purpose: PHONE_REGEX supports UsersView.vue by holding or executing the phone regex 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 PHONE_REGEX = /^1[3-9]\d{9}$/
/** isActiveFilterValue is a local helper used by the mobile filter summary. */
const isActiveFilterValue = (value: unknown) => {
if (Array.isArray(value)) {
return value.some(item => item !== undefined && item !== null && item !== '')
}
return value !== undefined && value !== null && value !== ''
}
/**
* Purpose: pagination supports UsersView.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 UsersView.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: '',
nickname: '',
phone: '',
contactPhone: '',
birthday: '',
wechatId: '',
wechatQrCode: '',
password: '',
type: 2,
shopIds: [] as string[]
})
/** wechatQrUploading tracks QR upload state in the user modal. */
const wechatQrUploading = ref(false)
/** originalPhone keeps the phone value loaded from the backend so edits can be detected. */
const originalPhone = ref('')
/** phonePlaceholder explains that an existing masked phone is kept unless a new number is typed. */
const phonePlaceholder = computed(() =>
isEdit.value && originalPhone.value ? '已设置手机号,留空表示不修改' : '请输入手机号'
)
/** phoneChanged is true only when the user typed a real, different phone number during editing. */
const phoneChanged = computed(() => {
if (!isEdit.value) return true
const current = formState.phone.trim()
if (!current || isMaskedSensitiveValue(current)) return false
return current !== originalPhone.value.trim()
})
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
/** handlePhoneInput is a local helper used by this page script. */
const handlePhoneInput = () => {
const normalized = formState.phone.replace(/\D/g, '').slice(0, 11)
if (normalized !== formState.phone) {
formState.phone = normalized
}
formState.contactPhone = formState.phone
}
/** handlePhoneFocus clears the masked placeholder value so stars can never be submitted as a phone number. */
const handlePhoneFocus = () => {
if (isMaskedSensitiveValue(formState.phone)) {
formState.phone = ''
formState.contactPhone = ''
}
}
/** beforeUploadWechatQr validates QR image files before upload. */
const beforeUploadWechatQr = (file: File) => {
const isImage = file.type.startsWith('image/') && file.type !== 'image/gif'
if (!isImage) {
message.error('二维码仅支持 JPG、PNG 或 WebP 图片')
}
return isImage
}
/** handleWechatQrUpload uploads a QR image through admin object storage and stores the signed URL. */
const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
wechatQrUploading.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-user-wechat-qr',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
try {
const { response: uploaded } = await task.promise
const signedUrl = await adminFileApi.getSignedUrl(uploaded.id)
formState.wechatQrCode = signedUrl as unknown as string
onSuccess?.(uploaded)
message.success('微信二维码上传成功')
} catch (error) {
const errorMessage = (error as Error)?.message || '微信二维码上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('微信二维码上传失败:', error)
message.error(errorMessage)
onError?.(error as Error)
}
} finally {
wechatQrUploading.value = false
}
}
/** validatePhoneUniqueness is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validatePhoneUniqueness = async (value: string) => {
const normalized = value?.trim()
if (!normalized) {
throw new Error('请输入手机号')
}
if (!PHONE_REGEX.test(normalized)) {
throw new Error('请输入正确的 11 位手机号')
}
if (isEdit.value && currentUser.value?.phone?.trim() === normalized) {
return
}
try {
const response = await userApi.checkPhoneAvailability(normalized) as unknown as AvailabilityCheckResponse
if (!response.available) {
throw new Error(response.message || '该手机号已绑定其他用户')
}
} catch (error: any) {
if (error instanceof Error && error.message) {
throw error
}
throw new Error('手机号校验失败,请稍后重试')
}
}
const isMaskedSensitiveValue = (value?: string | null) => /^1[3-9]\d\*{4}\d{4}$/.test(String(value || '').trim())
const validateOptionalPasswordStrength = (value?: string) => {
const password = value?.trim()
if (!password) {
return
}
if (password.length < 8 || password.length > 32) {
throw new Error('密码长度需为 8-32 位')
}
const categoryCount = [
/\d/.test(password),
/[a-z]/.test(password),
/[A-Z]/.test(password),
/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)
].filter(Boolean).length
if (categoryCount < 3) {
throw new Error('密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类')
}
}
/**
* Purpose: formRules supports UsersView.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: [
{
validator: (_rule: unknown, value: string) => {
if (isEdit.value && !value?.trim()) return Promise.resolve()
if (!value?.trim()) return Promise.reject('请输入账号')
if (!ACCOUNT_REGEX.test(value.trim())) return Promise.reject(ACCOUNT_RULE_MESSAGE)
return Promise.resolve()
},
trigger: 'blur'
}
],
nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
phone: [
{
validator: async (_rule: unknown, value: string) => {
if (isEdit.value && (!value?.trim() || isMaskedSensitiveValue(value))) return Promise.resolve()
await validatePhoneUniqueness(value)
return Promise.resolve()
},
trigger: 'blur'
}
],
wechatId: [],
password: [{
validator: async (_rule: unknown, value: string) => {
validateOptionalPasswordStrength(value)
return Promise.resolve()
},
trigger: 'blur'
}],
shopIds: [{
validator: async (_rule: unknown, value: string[]) => {
if (Number(formState.type) === 4) {
return Promise.resolve()
}
if (Array.isArray(value) && value.length > 0) {
return Promise.resolve()
}
if (currentUserType.value === 4 && shopList.value.length === 0) {
return Promise.reject('请先新增店铺后再创建店铺用户')
}
return Promise.reject('请选择至少一个店铺')
},
trigger: 'change'
}],
type: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
} as any
/**
* Purpose: columns supports UsersView.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: 'avatar', width: 80 },
{ title: '账号', dataIndex: 'account', key: 'account' },
{ title: '昵称', dataIndex: 'nickname', key: 'nickname' },
{ title: '手机号', dataIndex: 'phone', key: 'phone' },
{ title: '所属店铺', key: 'shopName', width: 140 },
{ title: '用户类型', key: 'type', width: 110 },
{ title: '状态', key: 'status', width: 100 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'actions', width: 280, fixed: 'right' as const }
]
/** 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] || '未知'
}
/** getUserTypeColor is a local helper used by this page script. */
const getUserTypeColor = (type: number) => {
const map: Record<number, string> = {
0: 'default',
2: 'blue',
3: 'green',
4: 'purple'
}
return map[type] || 'default'
}
/** canShowDelete is a local helper used by this page script. */
const canShowDelete = (record: Partial<UserVO> | Record<string, any>) => {
if (!canDeleteUser.value) {
return false
}
if (record.type === 4) {
return false
}
return String(record.id) !== String(currentUserInfo?.id ?? '')
}
/** canShowUnbind is a local helper used by this page script. */
const canShowUnbind = (record: Partial<UserVO> | Record<string, any>) => {
if (!canUnbindUser.value) {
return false
}
return record.type !== 4
}
/** getUnbindConfirmText is a local helper used by this page script. */
const getUnbindConfirmText = (record: Partial<UserVO> | Record<string, any>) => {
if (currentUserType.value === 2 && record.type === 3) {
return '确定要解绑该美甲师与当前店铺的关系吗?解绑后该账号会同步降级为普通用户。'
}
return '确定要解绑该用户与当前店铺的关系吗?'
}
/** filterVisibleUsers is a local helper used by this page script. */
const filterVisibleUsers = (list: UserVO[]) => {
if (!currentUserInfo || currentUserType.value === 4) {
return list
}
if (currentUserType.value === 2) {
return list.filter(user => user.type === 0 || user.type === 3)
}
if (currentUserType.value === 3) {
return list.filter(user => user.type === 0)
}
return list
}
/** normalizeShopId is a local helper used by this page script. */
const normalizeShopId = (value: unknown) => {
if (value === undefined || value === null || value === '') {
return undefined
}
return String(value)
}
/** getShopOptionValue is a local helper used by this page script. */
const getShopOptionValue = (shop: Shop) => normalizeShopId((shop as any).id) || ''
/** getShopNameById is a local helper used by this page script. */
const getShopNameById = (shopId?: string | number | null) => {
const targetShopId = normalizeShopId(shopId)
if (!targetShopId) {
return ''
}
const matchedShop = shopList.value.find(shop => getShopOptionValue(shop) === targetShopId)
return matchedShop?.shopName || ''
}
/** getShopDisplay is a local helper used by this page script. */
const getShopDisplay = (user?: Partial<UserVO> | Record<string, any> | null) => {
if (!user) {
return ''
}
const names = (user.shopNames || []).filter(Boolean)
if (names.length) {
return names.join('、')
}
if (user.shopName) {
return user.shopName
}
if (user.shopIds?.length) {
return (user.shopIds as Array<string | number>)
.map((id: string | number) => getShopNameById(id) || `店铺 ${id}`)
.join('、')
}
return getShopNameById(user.shopId) || ''
}
/** resolveEditableShopIds is a local helper used by this page script. */
const resolveEditableShopIds = (user?: UserVO | null) => {
const sourceIds = user?.shopIds?.length
? user.shopIds
: (user?.shopId ? [user.shopId] : [])
const normalizedIds = sourceIds
.map(id => normalizeShopId(id))
.filter((id): id is string => Boolean(id))
.filter(id => shopList.value.some(shop => getShopOptionValue(shop) === id))
if (normalizedIds.length) {
return normalizedIds
}
return currentUserType.value !== 4 && currentUserInfo?.shopId
? [normalizeShopId(currentUserInfo.shopId)!]
: []
}
/** fetchShopList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShopList = async () => {
shopLoading.value = true
try {
const shops = await adminShopApi.listAllShops() as unknown as Shop[]
shopList.value = shops || []
if (currentUserType.value !== 4 && currentUserInfo?.shopId) {
shopFilter.value = normalizeShopId(currentUserInfo.shopId)
formState.shopIds = [normalizeShopId(currentUserInfo.shopId)!]
}
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
shopLoading.value = false
}
}
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserList = async () => {
loading.value = true
try {
const params: Record<string, unknown> = {
page: pagination.current,
size: pagination.pageSize,
keyword: searchText.value || undefined,
type: typeFilter.value,
status: statusFilter.value,
createdFrom: createdRange.value?.[0],
createdTo: createdRange.value?.[1],
hasPhone: hasPhoneFilter.value === undefined ? undefined : hasPhoneFilter.value === 'true',
hasOrder: hasOrderFilter.value === undefined ? undefined : hasOrderFilter.value === 'true'
}
const scopedShopId = shopFilter.value || (currentUserType.value !== 4 ? normalizeShopId(currentUserInfo?.shopId) : undefined)
if (scopedShopId) {
params.shopId = scopedShopId
}
const res = await adminUserApi.listUsers(params as any)
const list = filterVisibleUsers(res.list || [])
userList.value = list
pagination.total = res.total || list.length
} catch (error) {
console.error('获取用户列表失败:', error)
message.error('获取用户列表失败')
} finally {
loading.value = false
}
}
/**
* Purpose: resetFilters supports UsersView.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 = () => {
searchText.value = ''
shopFilter.value = currentUserType.value !== 4 ? normalizeShopId(currentUserInfo?.shopId) : undefined
typeFilter.value = 2
statusFilter.value = undefined
createdRange.value = undefined
hasPhoneFilter.value = undefined
hasOrderFilter.value = undefined
handleSearch()
}
/** resetFormState is a local helper used by this page script. */
const resetFormState = () => {
originalPhone.value = ''
Object.assign(formState, {
account: '',
nickname: '',
phone: '',
contactPhone: '',
birthday: '',
wechatId: '',
wechatQrCode: '',
password: '',
type: 2,
shopIds: currentUserType.value !== 4 && currentUserInfo?.shopId
? [normalizeShopId(currentUserInfo.shopId)!]
: []
})
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-users', isEdit.value ? 'edit' : 'create', currentUser.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
account: formState.account,
nickname: formState.nickname,
phone: formState.phone,
contactPhone: formState.phone,
birthday: formState.birthday,
wechatId: formState.wechatId,
wechatQrCode: formState.wechatQrCode,
password: formState.password,
type: formState.type,
shopIds: [...formState.shopIds]
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey(), 'session')
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
if (!formState.phone && formState.contactPhone) {
formState.phone = formState.contactPhone
}
formState.contactPhone = formState.phone
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload(), 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey(), 'session')
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/** 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(() => fetchUserList())
}
/** 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 || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
await runWithGlobalLoading(() => fetchUserList())
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentUser.value = null
resetFormState()
restoreDraft()
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentUser.value = record
const loadedPhone = String(record.phone || record.contactPhone || '').trim()
originalPhone.value = loadedPhone
Object.assign(formState, {
account: isMaskedSensitiveValue(record.account) ? '' : record.account,
nickname: record.nickname,
phone: loadedPhone,
contactPhone: loadedPhone,
birthday: record.birthday || '',
wechatId: record.wechatId || '',
wechatQrCode: record.wechatQrCode || '',
password: '',
type: record.type,
shopIds: resolveEditableShopIds(record)
})
restoreDraft()
if (isMaskedSensitiveValue(formState.account)) formState.account = ''
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
viewRecord.value = record
viewModalVisible.value = true
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
if (wechatQrUploading.value) {
message.warning('微信二维码上传完成前不可保存')
return
}
await formRef.value?.validate()
modalLoading.value = true
await runWithGlobalLoading(async () => {
const requestShopIds = Number(formState.type) === 4 ? [] : formState.shopIds
const usedDefaultPassword = !isEdit.value && !formState.password.trim()
const primaryPhone = formState.phone.trim()
const requestData: Record<string, unknown> = {
account: formState.account.trim(),
nickname: formState.nickname.trim(),
phone: primaryPhone,
contactPhone: primaryPhone,
birthday: formState.birthday || undefined,
wechatId: formState.wechatId.trim(),
wechatQrCode: formState.wechatQrCode,
type: formState.type,
shopIds: requestShopIds,
shopId: requestShopIds.length ? requestShopIds[0] : undefined,
...(formState.password.trim() ? { password: formState.password.trim() } : {})
}
if (isEdit.value && (!formState.account.trim() || isMaskedSensitiveValue(formState.account))) {
delete requestData.account
}
if (isEdit.value && (!phoneChanged.value || !primaryPhone || isMaskedSensitiveValue(primaryPhone))) {
delete requestData.phone
delete requestData.contactPhone
}
if (isEdit.value && currentUserType.value !== 4) {
delete requestData.shopIds
delete requestData.shopId
}
if (isEdit.value && currentUser.value) {
await adminUserApi.updateUser(currentUser.value.id, requestData)
message.success('更新成功')
} else {
await adminUserApi.createUser(requestData)
if (usedDefaultPassword) {
await showDefaultPasswordCreateNotice()
} else {
message.success('创建成功')
}
}
handleClearDraft(false)
modalVisible.value = false
formRef.value?.resetFields()
await fetchUserList()
})
} 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()
}
/** handleStatusChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleStatusChange = async (record: any, checked: boolean) => {
try {
await runWithGlobalLoading(async () => {
const success = await adminUserApi.updateUserStatus(record.id, checked ? 1 : 0)
if (!success) {
message.warning('未找到可更新状态的用户')
await fetchUserList()
return
}
record.status = checked ? 1 : 0
message.success(`已${checked ? '启用' : '停用'}该用户账号`)
})
} catch (error) {
console.error('状态更新失败:', error)
message.error('状态更新失败')
}
}
/** handleResetPassword is a local helper used by this page script. */
const handleResetPassword = (record: any) => {
Modal.confirm({
title: '确认重置密码',
content: `确定要将用户 ${record.nickname} 的密码重置为后台默认密码吗?`,
async onOk() {
try {
await runWithGlobalLoading(async () => {
await adminUserApi.resetPassword(record.id)
await showDefaultPasswordResetNotice()
})
} catch (error) {
console.error('重置密码失败:', error)
message.error('密码重置失败')
}
}
})
}
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDelete = async (record: any) => {
try {
if (record.type === 4) {
message.warning('管理员账号无法被删除')
return
}
await runWithGlobalLoading(async () => {
const success = await adminUserApi.deleteUser(record.id)
if (!success) {
message.warning('未找到可删除的用户')
await fetchUserList()
return
}
userList.value = userList.value.filter(user => !sameId(user.id, record.id))
pagination.total = Math.max(0, Number(pagination.total || 0) - 1)
message.success('已删除用户账号')
await fetchUserList()
})
} catch (error) {
console.error('删除用户失败:', error)
message.error('删除失败')
}
}
/** handleUnbind is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUnbind = async (record: any) => {
try {
if (record.type === 4) {
message.warning('管理员账号无法解绑')
return
}
await runWithGlobalLoading(async () => {
const success = await adminUserApi.unbindUser(record.id)
if (!success) {
message.warning('未找到当前店铺下可解绑的用户绑定')
await fetchUserList()
return
}
userList.value = userList.value.filter(user => !sameId(user.id, record.id))
pagination.total = Math.max(0, Number(pagination.total || 0) - 1)
if (currentUserType.value === 2 && record.type === 3) {
message.success('已解绑当前店铺下的美甲师,并已同步降级为普通用户')
} else {
message.success('已解绑当前店铺下的用户')
}
await fetchUserList()
})
} catch (error) {
console.error('解绑用户失败:', error)
message.error('解绑失败')
}
}
watch(() => formState.type, type => {
if (Number(type) === 4) {
formState.shopIds = []
formRef.value?.clearValidate?.(['shopIds'])
}
})
onMounted(async () => {
await loadUserPermissions()
await fetchShopList()
await fetchUserList()
})
</script>
<style scoped>
.users {
padding: 0;
}
.mobile-user-head {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.wechat-qr-field {
display: grid;
justify-items: start;
gap: 8px;
}
.user-date-picker {
width: 100%;
}
.wechat-qr-preview {
width: 88px;
height: 88px;
border: 1px solid var(--admin-mobile-border);
border-radius: 8px;
object-fit: cover;
}
:global(.default-password-notice) {
display: grid;
gap: 12px;
}
:global(.default-password-notice p) {
margin: 0;
color: var(--text-secondary);
line-height: 1.7;
}
:global(.default-password-notice__value) {
padding: 12px 14px;
border: 1px solid var(--theme-border);
border-radius: 8px;
background: var(--theme-primary-soft);
color: var(--text-primary);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
font-size: 15px;
font-weight: 700;
overflow-wrap: break-word;
}
</style>