1992 lines
72 KiB
Vue
1992 lines
72 KiB
Vue
<template>
|
||
<div class="users">
|
||
<a-page-header v-if="!isMobile" title="用户管理" sub-title="管理系统用户" />
|
||
|
||
<section v-else class="admin-page-intro">
|
||
<span class="admin-page-intro__eyebrow">经营</span>
|
||
<h1 class="admin-page-intro__title">用户管理</h1>
|
||
<div class="admin-page-intro__meta">
|
||
<span class="admin-page-chip">用户 {{ userList.length }}</span>
|
||
</div>
|
||
</section>
|
||
|
||
<a-card :bordered="false">
|
||
<template #title v-if="isMobile">
|
||
用户列表
|
||
</template>
|
||
<template #extra>
|
||
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
|
||
<a-input-search
|
||
v-model:value="searchText"
|
||
placeholder="搜索账号、昵称或手机号"
|
||
:style="isMobile ? { width: '100%' } : { width: '260px' }"
|
||
@search="handleSearch"
|
||
/>
|
||
<a-button v-if="!isMobile && 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="typeFilter" allow-clear placeholder="用户类型" style="width: 140px" @change="handleSearch">
|
||
<a-select-option :value="0">普通用户</a-select-option>
|
||
<a-select-option :value="2">店长</a-select-option>
|
||
<a-select-option :value="3">美甲师</a-select-option>
|
||
<a-select-option :value="4">管理员</a-select-option>
|
||
</a-select>
|
||
<a-select v-model:value="vipLevelFilter" allow-clear placeholder="VIP等级" style="width: 140px" @change="handleSearch">
|
||
<a-select-option v-for="level in vipLevelOptions" :key="level" :value="level">{{ level }}</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="canOpenAssetPanel"
|
||
type="link"
|
||
size="small"
|
||
@click="showAssetModal(record)"
|
||
>
|
||
余额/VIP
|
||
</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>VIP 等级</span>
|
||
<strong>{{ item.level || '普通' }}</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="canOpenAssetPanel" size="small" @click="showAssetModal(item)">余额/VIP</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="请输入账号"
|
||
@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="请输入手机号"
|
||
:maxlength="11"
|
||
inputmode="numeric"
|
||
autocomplete="off"
|
||
@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="fingertip-designer-date-picker-panel"
|
||
/>
|
||
</a-form-item>
|
||
<a-form-item
|
||
label="微信号"
|
||
name="wechatId"
|
||
:required="[2, 3].includes(Number(formState.type))"
|
||
>
|
||
<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/*"
|
||
: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">
|
||
<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="VIP 等级">{{ viewRecord?.level || '普通' }}</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>
|
||
|
||
<AdminResponsiveModal
|
||
v-model:open="assetModalVisible"
|
||
title="余额 / VIP 管理"
|
||
:desktop-width="960"
|
||
:footer="null"
|
||
@cancel="handleAssetModalCancel"
|
||
>
|
||
<a-spin :spinning="assetLoading">
|
||
<div v-if="assetTargetUser" class="asset-modal">
|
||
<a-alert
|
||
:message="`${assetTargetUser.nickname}(${assetTargetUser.account})`"
|
||
:description="getShopDisplay(assetTargetUser) ? `所属店铺:${getShopDisplay(assetTargetUser)}` : '未绑定店铺'"
|
||
type="info"
|
||
show-icon
|
||
style="margin-bottom: 16px"
|
||
/>
|
||
|
||
<a-row :gutter="16" class="asset-summary">
|
||
<a-col :span="8">
|
||
<a-card size="small" title="当前余额">
|
||
<div class="summary-value">¥{{ formatMoney(assetData?.balance) }}</div>
|
||
<div class="summary-sub">累计充值:¥{{ formatMoney(assetData?.totalRechargeAmount) }}</div>
|
||
</a-card>
|
||
</a-col>
|
||
<a-col :span="8">
|
||
<a-card size="small" title="VIP 状态">
|
||
<div class="summary-value">{{ assetData?.vipLevel || '普通' }}</div>
|
||
<div class="summary-sub">
|
||
{{ assetData?.manualOverride ? '当前为手工指定' : '当前按累计充值自动判级' }}
|
||
</div>
|
||
</a-card>
|
||
</a-col>
|
||
<a-col :span="8">
|
||
<a-card size="small" title="最近充值">
|
||
<div class="summary-value">{{ formatDate(assetData?.lastRechargeTime) }}</div>
|
||
<div class="summary-sub">权益说明:{{ assetData?.benefitInfo || '-' }}</div>
|
||
</a-card>
|
||
</a-col>
|
||
</a-row>
|
||
|
||
<a-row :gutter="16" class="asset-actions">
|
||
<a-col :span="12">
|
||
<a-card size="small" title="余额变动">
|
||
<DraftActions
|
||
:saved-at="balanceDraftSavedAt"
|
||
@save="handleSaveBalanceDraft"
|
||
@clear="handleClearBalanceDraft"
|
||
/>
|
||
<a-form layout="vertical">
|
||
<a-form-item label="变动场景">
|
||
<a-select v-model:value="balanceForm.changeScene">
|
||
<a-select-option value="RECHARGE">充值</a-select-option>
|
||
<a-select-option value="MANUAL_ADD">手工增加余额</a-select-option>
|
||
<a-select-option value="MANUAL_DEDUCT">手工扣减余额</a-select-option>
|
||
</a-select>
|
||
</a-form-item>
|
||
<a-form-item label="变动金额">
|
||
<a-input-number
|
||
v-model:value="balanceForm.amount"
|
||
:min="0.01"
|
||
:precision="2"
|
||
style="width: 100%"
|
||
placeholder="请输入金额"
|
||
/>
|
||
</a-form-item>
|
||
<a-form-item label="关联系统订单 ID(可选)">
|
||
<a-input-number
|
||
v-model:value="balanceForm.relatedOrderId"
|
||
:min="1"
|
||
:precision="0"
|
||
style="width: 100%"
|
||
placeholder="如有系统订单可填写"
|
||
/>
|
||
</a-form-item>
|
||
<a-form-item label="外部单号(扣减时二选一)">
|
||
<a-input
|
||
v-model:value="balanceForm.externalOrderNo"
|
||
placeholder="没有系统订单时请填写外部单号"
|
||
/>
|
||
</a-form-item>
|
||
<a-form-item label="备注">
|
||
<a-textarea
|
||
v-model:value="balanceForm.remark"
|
||
:rows="3"
|
||
placeholder="请输入备注"
|
||
/>
|
||
</a-form-item>
|
||
<a-button
|
||
v-if="hasPermission('user:balance:manage')"
|
||
type="primary"
|
||
:loading="assetSaving"
|
||
@click="handleBalanceChange"
|
||
>
|
||
提交余额变动
|
||
</a-button>
|
||
<a-typography-text v-else type="secondary">
|
||
当前账号只有查看权限,不能调整余额。
|
||
</a-typography-text>
|
||
</a-form>
|
||
</a-card>
|
||
</a-col>
|
||
|
||
<a-col :span="12">
|
||
<a-card size="small" title="VIP 管理">
|
||
<DraftActions
|
||
:saved-at="vipDraftSavedAt"
|
||
@save="handleSaveVipDraft"
|
||
@clear="handleClearVipDraft"
|
||
/>
|
||
<a-form layout="vertical">
|
||
<a-form-item label="目标等级">
|
||
<a-select v-model:value="vipForm.vipLevel">
|
||
<a-select-option v-for="level in vipLevelOptions" :key="level" :value="level">{{ level }}</a-select-option>
|
||
</a-select>
|
||
</a-form-item>
|
||
<a-form-item label="备注">
|
||
<a-textarea
|
||
v-model:value="vipForm.remark"
|
||
:rows="3"
|
||
placeholder="可填写手工调整原因"
|
||
/>
|
||
</a-form-item>
|
||
<a-space>
|
||
<a-button
|
||
v-if="hasPermission('user:vip:manage')"
|
||
type="primary"
|
||
:loading="assetSaving"
|
||
@click="handleVipOverride"
|
||
>
|
||
手工设置 VIP
|
||
</a-button>
|
||
<a-button
|
||
v-if="hasPermission('user:vip:manage')"
|
||
:loading="assetSaving"
|
||
@click="handleVipRecalculate"
|
||
>
|
||
恢复自动判级
|
||
</a-button>
|
||
</a-space>
|
||
<div class="vip-note">
|
||
{{ assetData?.manualOverride ? '当前处于手工指定状态。' : '当前按累计充值自动判级。' }}
|
||
</div>
|
||
</a-form>
|
||
</a-card>
|
||
</a-col>
|
||
</a-row>
|
||
|
||
<a-card size="small" title="余额流水" class="history-card">
|
||
<a-table
|
||
:columns="historyColumns"
|
||
:data-source="balanceHistory"
|
||
:pagination="false"
|
||
size="small"
|
||
row-key="id"
|
||
:scroll="{ x: 'max-content', y: 320 }"
|
||
>
|
||
<template #bodyCell="{ column, record }">
|
||
<template v-if="column.key === 'amount'">
|
||
<span :class="Number(record.amount) >= 0 ? 'amount-plus' : 'amount-minus'">
|
||
{{ Number(record.amount) >= 0 ? '+' : '' }}{{ formatMoney(record.amount) }}
|
||
</span>
|
||
</template>
|
||
<template v-else-if="column.key === 'changeScene'">
|
||
{{ getSceneText(record.changeScene) }}
|
||
</template>
|
||
<template v-else-if="column.key === 'balanceRange'">
|
||
{{ formatMoney(record.beforeBalance) }} -> {{ formatMoney(record.afterBalance) }}
|
||
</template>
|
||
<template v-else-if="column.key === 'relatedOrder'">
|
||
{{ record.relatedOrderNo || record.externalOrderNo || '-' }}
|
||
</template>
|
||
<template v-else-if="column.key === 'changeTime'">
|
||
{{ formatDate(record.changeTime) }}
|
||
</template>
|
||
</template>
|
||
</a-table>
|
||
</a-card>
|
||
</div>
|
||
</a-spin>
|
||
</AdminResponsiveModal>
|
||
|
||
<AdminMobileFab
|
||
:visible="isMobile && canCreateUser && !modalVisible && !viewModalVisible && !assetModalVisible"
|
||
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 } 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,
|
||
adminVipRechargePlanApi,
|
||
type AdminUserBalanceChangeRequest,
|
||
type AdminUserVipOverrideRequest,
|
||
type Shop,
|
||
type UserAssetVO,
|
||
type UserBalanceHistoryItem,
|
||
type UserVO
|
||
} from '@/api/admin'
|
||
import type { IdType } from '@/utils/id'
|
||
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, hasAnyPermission, 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>()
|
||
/**
|
||
* Purpose: vipLevelFilter supports UsersView.vue by holding or executing the vip level 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 vipLevelFilter = ref<string | undefined>()
|
||
/**
|
||
* 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: vipLevelOptions supports UsersView.vue by holding or executing the vip level options page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const vipLevelOptions = ref<string[]>(['普通', '青铜', '白银', '黄金'])
|
||
/**
|
||
* Purpose: 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)
|
||
|
||
/** assetModalVisible is a reactive state variable used by the template and event handlers. */
|
||
const assetModalVisible = ref(false)
|
||
/** assetLoading is a reactive state variable used by the template and event handlers. */
|
||
const assetLoading = ref(false)
|
||
/** assetSaving is a reactive state variable used by the template and event handlers. */
|
||
const assetSaving = ref(false)
|
||
/**
|
||
* Purpose: assetTargetUser supports UsersView.vue by holding or executing the asset target 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 assetTargetUser = ref<UserVO | null>(null)
|
||
/**
|
||
* Purpose: assetData supports UsersView.vue by holding or executing the asset data page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const assetData = ref<UserAssetVO | null>(null)
|
||
/**
|
||
* Purpose: balanceHistory supports UsersView.vue by holding or executing the balance history 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 balanceHistory = ref<UserBalanceHistoryItem[]>([])
|
||
/**
|
||
* Purpose: balanceDraftSavedAt supports UsersView.vue by holding or executing the balance 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 balanceDraftSavedAt = ref<number | null>(null)
|
||
/**
|
||
* Purpose: vipDraftSavedAt supports UsersView.vue by holding or executing the vip 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 vipDraftSavedAt = ref<number | null>(null)
|
||
|
||
/** canOpenAssetPanel is a reactive state variable used by the template and event handlers. */
|
||
const canOpenAssetPanel = computed(() =>
|
||
hasAnyPermission(['user:balance:view', 'user:balance:manage', 'user:vip:manage'])
|
||
)
|
||
/** 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,
|
||
vipLevelFilter.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: 0,
|
||
shopIds: [] as string[]
|
||
})
|
||
|
||
/** wechatQrUploading tracks QR upload state in the user modal. */
|
||
const wechatQrUploading = ref(false)
|
||
|
||
/** 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
|
||
}
|
||
|
||
/** beforeUploadWechatQr validates QR image files before upload. */
|
||
const beforeUploadWechatQr = (file: File) => {
|
||
const isImage = file.type.startsWith('image/')
|
||
if (!isImage) {
|
||
message.error('只能上传图片文件')
|
||
}
|
||
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 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: balanceForm supports UsersView.vue by holding or executing the balance form page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const balanceForm = reactive<AdminUserBalanceChangeRequest>({
|
||
changeScene: 'RECHARGE',
|
||
amount: undefined as unknown as number,
|
||
relatedOrderId: undefined,
|
||
externalOrderNo: '',
|
||
remark: ''
|
||
})
|
||
|
||
/**
|
||
* Purpose: vipForm supports UsersView.vue by holding or executing the vip form page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const vipForm = reactive<AdminUserVipOverrideRequest>({
|
||
vipLevel: '普通',
|
||
remark: ''
|
||
})
|
||
|
||
/** getBalanceDraftKey is a local helper used by this page script. */
|
||
const getBalanceDraftKey = () => buildDraftStorageKey('admin-user-assets', 'balance', assetTargetUser.value?.id ?? 'unknown')
|
||
/** getVipDraftKey is a local helper used by this page script. */
|
||
const getVipDraftKey = () => buildDraftStorageKey('admin-user-assets', 'vip', assetTargetUser.value?.id ?? 'unknown')
|
||
|
||
/** restoreBalanceDraft is a local helper used by this page script. */
|
||
const restoreBalanceDraft = () => {
|
||
const draft = loadDraftRecord<{
|
||
changeScene: string
|
||
amount?: number
|
||
relatedOrderId?: number
|
||
externalOrderNo: string
|
||
remark: string
|
||
}>(getBalanceDraftKey())
|
||
if (!draft) {
|
||
balanceDraftSavedAt.value = null
|
||
return
|
||
}
|
||
Object.assign(balanceForm, draft.payload)
|
||
balanceDraftSavedAt.value = draft.savedAt
|
||
message.success('已恢复余额变动暂存')
|
||
}
|
||
|
||
/** handleSaveBalanceDraft is a local helper used by this page script. */
|
||
const handleSaveBalanceDraft = () => {
|
||
const draft = saveDraftRecord(getBalanceDraftKey(), {
|
||
changeScene: balanceForm.changeScene,
|
||
amount: balanceForm.amount,
|
||
relatedOrderId: balanceForm.relatedOrderId,
|
||
externalOrderNo: balanceForm.externalOrderNo,
|
||
remark: balanceForm.remark
|
||
})
|
||
balanceDraftSavedAt.value = draft.savedAt
|
||
message.success('余额变动已暂存到本地')
|
||
}
|
||
|
||
/** handleClearBalanceDraft is a local helper used by this page script. */
|
||
const handleClearBalanceDraft = (showMessage = true) => {
|
||
clearDraftRecord(getBalanceDraftKey())
|
||
balanceDraftSavedAt.value = null
|
||
if (showMessage) {
|
||
message.success('已清除余额变动暂存')
|
||
}
|
||
}
|
||
|
||
/** restoreVipDraft is a local helper used by this page script. */
|
||
const restoreVipDraft = () => {
|
||
const draft = loadDraftRecord<{
|
||
vipLevel: string
|
||
remark: string
|
||
}>(getVipDraftKey())
|
||
if (!draft) {
|
||
vipDraftSavedAt.value = null
|
||
return
|
||
}
|
||
Object.assign(vipForm, draft.payload)
|
||
vipDraftSavedAt.value = draft.savedAt
|
||
message.success('已恢复 VIP 暂存')
|
||
}
|
||
|
||
/** handleSaveVipDraft is a local helper used by this page script. */
|
||
const handleSaveVipDraft = () => {
|
||
const draft = saveDraftRecord(getVipDraftKey(), {
|
||
vipLevel: vipForm.vipLevel,
|
||
remark: vipForm.remark || ''
|
||
})
|
||
vipDraftSavedAt.value = draft.savedAt
|
||
message.success('VIP 设置已暂存到本地')
|
||
}
|
||
|
||
/** handleClearVipDraft is a local helper used by this page script. */
|
||
const handleClearVipDraft = (showMessage = true) => {
|
||
clearDraftRecord(getVipDraftKey())
|
||
vipDraftSavedAt.value = null
|
||
if (showMessage) {
|
||
message.success('已清除 VIP 暂存')
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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: [
|
||
{ required: true, message: '请输入账号', trigger: 'blur' },
|
||
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
|
||
],
|
||
nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
|
||
phone: [
|
||
{ required: true, message: '请输入手机号', trigger: 'blur' },
|
||
{
|
||
validator: async (_rule: unknown, value: string) => {
|
||
await validatePhoneUniqueness(value)
|
||
return Promise.resolve()
|
||
},
|
||
trigger: 'blur'
|
||
}
|
||
],
|
||
wechatId: [{
|
||
validator: async (_rule: unknown, value: string) => {
|
||
if ([2, 3].includes(Number(formState.type)) && !value?.trim()) {
|
||
return Promise.reject('店长和美甲师必须填写微信号')
|
||
}
|
||
return Promise.resolve()
|
||
},
|
||
trigger: ['blur', 'change']
|
||
}],
|
||
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: 'VIP 等级', key: 'level', width: 110 },
|
||
{ title: '状态', key: 'status', width: 100 },
|
||
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
|
||
{ title: '操作', key: 'actions', width: 280, fixed: 'right' as const }
|
||
]
|
||
|
||
/**
|
||
* Purpose: historyColumns supports UsersView.vue by holding or executing the history 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 historyColumns = [
|
||
{ title: '场景', key: 'changeScene', width: 120 },
|
||
{ title: '金额', key: 'amount', width: 110 },
|
||
{ title: '余额变化', key: 'balanceRange', width: 170 },
|
||
{ title: '关联单号', key: 'relatedOrder', width: 180 },
|
||
{ title: '备注', dataIndex: 'remark', key: 'remark' },
|
||
{ title: '时间', key: 'changeTime', width: 180 }
|
||
]
|
||
|
||
/** 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 '确定要解绑该用户与当前店铺的关系吗?'
|
||
}
|
||
|
||
/** getSceneText is a local helper used by this page script. */
|
||
const getSceneText = (scene?: string) => {
|
||
const map: Record<string, string> = {
|
||
RECHARGE: '充值',
|
||
MANUAL_ADD: '手工增加',
|
||
MANUAL_DEDUCT: '手工扣减',
|
||
ORDER_CONSUME: '订单消费',
|
||
ORDER_REFUND: '订单退款'
|
||
}
|
||
return scene ? map[scene] || scene : '-'
|
||
}
|
||
|
||
/** formatMoney is a local helper used by this page script. */
|
||
const formatMoney = (value?: number | string | null) => {
|
||
if (value === undefined || value === null || value === '') {
|
||
return '0.00'
|
||
}
|
||
return Number(value).toFixed(2)
|
||
}
|
||
|
||
/** formatDate is a local helper used by this page script. */
|
||
const formatDate = (value?: string) => {
|
||
if (!value) {
|
||
return '-'
|
||
}
|
||
return value.replace('T', ' ').slice(0, 19)
|
||
}
|
||
|
||
/** 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,
|
||
vipLevel: vipLevelFilter.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 = undefined
|
||
vipLevelFilter.value = undefined
|
||
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 = () => {
|
||
const defaultUserType = currentUserType.value === 4 && shopList.value.length === 0
|
||
? availableUserTypeOptions.value.find(option => option.value === 4)?.value
|
||
: availableUserTypeOptions.value[0]?.value
|
||
|
||
Object.assign(formState, {
|
||
account: '',
|
||
nickname: '',
|
||
phone: '',
|
||
contactPhone: '',
|
||
birthday: '',
|
||
wechatId: '',
|
||
wechatQrCode: '',
|
||
password: '',
|
||
type: defaultUserType ?? 0,
|
||
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
|
||
Object.assign(formState, {
|
||
account: record.account,
|
||
nickname: record.nickname,
|
||
phone: record.phone || record.contactPhone || '',
|
||
contactPhone: record.phone || record.contactPhone || '',
|
||
birthday: record.birthday || '',
|
||
wechatId: record.wechatId || '',
|
||
wechatQrCode: record.wechatQrCode || '',
|
||
password: '',
|
||
type: record.type,
|
||
shopIds: resolveEditableShopIds(record)
|
||
})
|
||
restoreDraft()
|
||
modalVisible.value = true
|
||
}
|
||
|
||
/** showViewModal is a local helper used by this page script. */
|
||
const showViewModal = (record: any) => {
|
||
viewRecord.value = record
|
||
viewModalVisible.value = true
|
||
}
|
||
|
||
/** loadUserAssetData is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||
const loadUserAssetData = async (userId: IdType) => {
|
||
const [asset, history] = await Promise.all([
|
||
adminUserApi.getUserAsset(userId),
|
||
adminUserApi.getUserBalanceHistory(userId)
|
||
])
|
||
assetData.value = asset
|
||
balanceHistory.value = history || []
|
||
vipForm.vipLevel = asset.vipLevel || '普通'
|
||
}
|
||
|
||
/** resetAssetForms is a local helper used by this page script. */
|
||
const resetAssetForms = () => {
|
||
Object.assign(balanceForm, {
|
||
changeScene: 'RECHARGE',
|
||
amount: undefined,
|
||
relatedOrderId: undefined,
|
||
externalOrderNo: '',
|
||
remark: ''
|
||
})
|
||
Object.assign(vipForm, {
|
||
vipLevel: assetData.value?.vipLevel || '普通',
|
||
remark: ''
|
||
})
|
||
}
|
||
|
||
/** showAssetModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||
const showAssetModal = async (record: any) => {
|
||
assetTargetUser.value = record
|
||
assetModalVisible.value = true
|
||
assetLoading.value = true
|
||
assetData.value = null
|
||
balanceHistory.value = []
|
||
resetAssetForms()
|
||
try {
|
||
await runWithGlobalLoading(() => loadUserAssetData(record.id))
|
||
resetAssetForms()
|
||
restoreBalanceDraft()
|
||
restoreVipDraft()
|
||
} catch (error) {
|
||
console.error('获取用户资产失败:', error)
|
||
message.error('获取用户资产失败')
|
||
} finally {
|
||
assetLoading.value = false
|
||
}
|
||
}
|
||
|
||
/** handleAssetModalCancel is a local helper used by this page script. */
|
||
const handleAssetModalCancel = () => {
|
||
assetModalVisible.value = false
|
||
assetTargetUser.value = null
|
||
assetData.value = null
|
||
balanceHistory.value = []
|
||
resetAssetForms()
|
||
}
|
||
|
||
/** 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 && 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('解绑失败')
|
||
}
|
||
}
|
||
|
||
/** refreshAssetPanel is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||
const refreshAssetPanel = async () => {
|
||
if (!assetTargetUser.value) {
|
||
return
|
||
}
|
||
assetLoading.value = true
|
||
try {
|
||
await loadUserAssetData(assetTargetUser.value.id)
|
||
const matchedUser = userList.value.find(user => sameId(user.id, assetTargetUser.value?.id))
|
||
if (matchedUser && assetData.value) {
|
||
matchedUser.level = assetData.value.vipLevel
|
||
matchedUser.vipId = assetData.value.vipInfoId
|
||
}
|
||
} finally {
|
||
assetLoading.value = false
|
||
}
|
||
}
|
||
|
||
/** handleBalanceChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||
const handleBalanceChange = async () => {
|
||
if (!assetTargetUser.value) {
|
||
return
|
||
}
|
||
const targetUserId = assetTargetUser.value.id
|
||
if (!balanceForm.amount || Number(balanceForm.amount) <= 0) {
|
||
message.warning('请输入大于 0 的金额')
|
||
return
|
||
}
|
||
if (
|
||
balanceForm.changeScene === 'MANUAL_DEDUCT'
|
||
&& !balanceForm.relatedOrderId
|
||
&& !balanceForm.externalOrderNo?.trim()
|
||
) {
|
||
message.warning('手工扣减余额时必须填写系统订单 ID 或外部单号')
|
||
return
|
||
}
|
||
|
||
assetSaving.value = true
|
||
try {
|
||
await runWithGlobalLoading(async () => {
|
||
await adminUserApi.changeUserBalance(targetUserId, {
|
||
amount: Number(balanceForm.amount),
|
||
changeScene: balanceForm.changeScene,
|
||
relatedOrderId: balanceForm.relatedOrderId,
|
||
externalOrderNo: balanceForm.externalOrderNo?.trim() || undefined,
|
||
remark: balanceForm.remark?.trim() || undefined
|
||
})
|
||
message.success('余额变动已保存')
|
||
handleClearBalanceDraft(false)
|
||
Object.assign(balanceForm, {
|
||
amount: undefined,
|
||
relatedOrderId: undefined,
|
||
externalOrderNo: '',
|
||
remark: ''
|
||
})
|
||
await refreshAssetPanel()
|
||
})
|
||
} catch (error: any) {
|
||
console.error('余额变动失败:', error)
|
||
message.error(error.message || '余额变动失败')
|
||
} finally {
|
||
assetSaving.value = false
|
||
}
|
||
}
|
||
|
||
/** handleVipOverride is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||
const handleVipOverride = async () => {
|
||
if (!assetTargetUser.value) {
|
||
return
|
||
}
|
||
const targetUserId = assetTargetUser.value.id
|
||
assetSaving.value = true
|
||
try {
|
||
await runWithGlobalLoading(async () => {
|
||
await adminUserApi.overrideUserVip(targetUserId, {
|
||
vipLevel: vipForm.vipLevel,
|
||
remark: vipForm.remark?.trim() || undefined
|
||
})
|
||
message.success('VIP 已更新')
|
||
handleClearVipDraft(false)
|
||
vipForm.remark = ''
|
||
await refreshAssetPanel()
|
||
})
|
||
} catch (error: any) {
|
||
console.error('VIP 更新失败:', error)
|
||
message.error(error.message || 'VIP 更新失败')
|
||
} finally {
|
||
assetSaving.value = false
|
||
}
|
||
}
|
||
|
||
/** handleVipRecalculate is a local helper used by this page script. */
|
||
const handleVipRecalculate = () => {
|
||
if (!assetTargetUser.value) {
|
||
return
|
||
}
|
||
Modal.confirm({
|
||
title: '恢复自动判级',
|
||
content: '恢复后会清除手工指定状态,并按累计充值金额重新计算 VIP 等级,是否继续?',
|
||
async onOk() {
|
||
assetSaving.value = true
|
||
try {
|
||
await runWithGlobalLoading(async () => {
|
||
await adminUserApi.recalculateUserVip(assetTargetUser.value!.id)
|
||
message.success('已恢复自动判级')
|
||
handleClearVipDraft(false)
|
||
vipForm.remark = ''
|
||
await refreshAssetPanel()
|
||
})
|
||
} catch (error: any) {
|
||
console.error('恢复自动判级失败:', error)
|
||
message.error(error.message || '恢复自动判级失败')
|
||
} finally {
|
||
assetSaving.value = false
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
/**
|
||
* Purpose: fetchVipLevelOptions supports UsersView.vue by holding or executing the fetch vip level options page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const fetchVipLevelOptions = async () => {
|
||
try {
|
||
const levels = await adminVipRechargePlanApi.listVipLevelOptions(currentUserInfo?.shopId)
|
||
if (Array.isArray(levels) && levels.length) {
|
||
vipLevelOptions.value = ['普通', ...levels.filter(level => level !== '普通')]
|
||
}
|
||
} catch (error) {
|
||
console.error('VIP 等级选项加载失败:', error)
|
||
}
|
||
}
|
||
|
||
watch(() => formState.type, type => {
|
||
if (Number(type) === 4) {
|
||
formState.shopIds = []
|
||
formRef.value?.clearValidate?.(['shopIds'])
|
||
}
|
||
})
|
||
|
||
onMounted(async () => {
|
||
await loadUserPermissions()
|
||
await Promise.all([fetchShopList(), fetchVipLevelOptions()])
|
||
await fetchUserList()
|
||
})
|
||
</script>
|
||
|
||
<style scoped>
|
||
.users {
|
||
padding: 0;
|
||
}
|
||
|
||
.asset-modal {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 16px;
|
||
}
|
||
|
||
.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;
|
||
}
|
||
|
||
.asset-summary,
|
||
.asset-actions,
|
||
.history-card {
|
||
margin-top: 0;
|
||
}
|
||
|
||
.summary-value {
|
||
font-size: 22px;
|
||
font-weight: 600;
|
||
line-height: 1.4;
|
||
}
|
||
|
||
.summary-sub {
|
||
margin-top: 8px;
|
||
color: var(--text-secondary);
|
||
font-size: 12px;
|
||
line-height: 1.6;
|
||
}
|
||
|
||
.vip-note {
|
||
margin-top: 12px;
|
||
color: var(--text-secondary);
|
||
font-size: 12px;
|
||
}
|
||
|
||
.amount-plus {
|
||
color: #52c41a;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.amount-minus {
|
||
color: #ff4d4f;
|
||
font-weight: 600;
|
||
}
|
||
|
||
@media (max-width: 960px) {
|
||
.asset-summary,
|
||
.asset-actions {
|
||
row-gap: 12px;
|
||
}
|
||
|
||
.asset-summary :deep(.ant-col),
|
||
.asset-actions :deep(.ant-col) {
|
||
flex: 0 0 100%;
|
||
max-width: 100%;
|
||
}
|
||
|
||
.asset-actions :deep(.ant-space) {
|
||
width: 100%;
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 8px !important;
|
||
}
|
||
|
||
.asset-actions :deep(.ant-space-item) {
|
||
max-width: 100%;
|
||
}
|
||
}
|
||
|
||
: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>
|