feat(admin): account governance and user sync pages
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* 账号治理接口(对齐 @photo/contracts tags [admin]:listAdminUsers 管理列表
|
||||
* 模式 / updateAdminUser / resetAdminUserPassword / activateAdminUser /
|
||||
* deactivateAdminUser)
|
||||
*
|
||||
* - 管理列表不带 accountPrefix(带了即切到邀请前缀查询模式,见 api/albums
|
||||
* fetchLookupUsers):全量用户 + query/status 过滤 + createdAt+ID 倒序游标
|
||||
* - PATCH 部分语义(role/localLocked/displayName;sourceStatus 只读展示)
|
||||
* - 自我保护在服务层(自改角色/自锁 400 VALIDATION_FAILED,http 层已本地化)
|
||||
* - activate 仅管 credentialStatus 维度(pending→active,初始凭据经
|
||||
* reset-password 出具);deactivate = localLocked=true + 撤全部会话
|
||||
*/
|
||||
import request from '@/utils/http'
|
||||
|
||||
/** 管理列表(全量用户 + query/status 过滤 + 游标分页) */
|
||||
export function fetchAdminUsers(params: Api.AdminUser.ListParams) {
|
||||
return request.get<Api.AdminUser.ListResponse>({ url: '/v1/admin/users', params })
|
||||
}
|
||||
|
||||
/** 更新用户治理属性(部分更新;服务端幂等 no-op 不落审计) */
|
||||
export function fetchUpdateAdminUser(userId: string, data: Api.AdminUser.UpdatePayload) {
|
||||
return request.patch<Api.AdminUser.Item>({ url: `/v1/admin/users/${userId}`, data })
|
||||
}
|
||||
|
||||
/** 管理员重置用户密码(指定或服务端生成;撤销目标全部既有会话) */
|
||||
export function fetchResetAdminUserPassword(
|
||||
userId: string,
|
||||
data: Api.AdminUser.ResetPasswordPayload
|
||||
) {
|
||||
return request.post<Api.AdminUser.ResetPasswordResponse>({
|
||||
url: `/v1/admin/users/${userId}/reset-password`,
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
/** 激活待激活用户(credentialStatus pending→active,幂等;不出凭据) */
|
||||
export function fetchActivateAdminUser(userId: string) {
|
||||
return request.post<Api.AdminUser.Item>({ url: `/v1/admin/users/${userId}/activate` })
|
||||
}
|
||||
|
||||
/** 停用用户(localLocked=true + 撤销全部会话,幂等;上游状态不动) */
|
||||
export function fetchDeactivateAdminUser(userId: string) {
|
||||
return request.post<Api.AdminUser.Item>({ url: `/v1/admin/users/${userId}/deactivate` })
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 用户同步管理接口(对齐 @photo/contracts tags [admin]:getUserSyncStatus /
|
||||
* listUserSyncRuns / triggerUserSyncRun / listUserSyncErrors)
|
||||
*
|
||||
* - status/runs/errors 为纯读;runs 为 startedAt+ID 倒序键集游标
|
||||
* - POST runs → 202 受理(异步执行;运行中批次复用其 runId),结果经
|
||||
* status/runs 轮询查询——页面侧的等待/轮询逻辑见 utils/system/syncPolling
|
||||
* - errors 按 runId 查单批次坏行明细(未知批次=空数组,契约无 404)
|
||||
*/
|
||||
import request from '@/utils/http'
|
||||
|
||||
/** 同步引擎状态 + 最近批次计数 */
|
||||
export function fetchUserSyncStatus() {
|
||||
return request.get<Api.UserSync.Status>({ url: '/v1/admin/user-sync/status' })
|
||||
}
|
||||
|
||||
/** 运行历史(游标分页) */
|
||||
export function fetchUserSyncRuns(params: { cursor?: string; limit?: number }) {
|
||||
return request.get<Api.UserSync.RunListResponse>({
|
||||
url: '/v1/admin/user-sync/runs',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
/** 手动触发同步补拉(202 受理;与定时共用互斥锁) */
|
||||
export function fetchTriggerUserSyncRun() {
|
||||
return request.post<Api.UserSync.RunCreatedResponse>({ url: '/v1/admin/user-sync/runs' })
|
||||
}
|
||||
|
||||
/** 单批次失败明细(runId 必填) */
|
||||
export function fetchUserSyncErrors(runId: string) {
|
||||
return request.get<Api.UserSync.ErrorListResponse>({
|
||||
url: '/v1/admin/user-sync/errors',
|
||||
params: { runId }
|
||||
})
|
||||
}
|
||||
@@ -230,6 +230,11 @@
|
||||
"outside": {
|
||||
"title": "Outside"
|
||||
},
|
||||
"system": {
|
||||
"title": "Accounts & Sync",
|
||||
"users": "Account Management",
|
||||
"userSync": "User Sync"
|
||||
},
|
||||
"albums": {
|
||||
"title": "Albums",
|
||||
"manage": "Album Management",
|
||||
@@ -436,6 +441,152 @@
|
||||
"empty": "No photos"
|
||||
}
|
||||
},
|
||||
"usersManage": {
|
||||
"list": {
|
||||
"title": "Account Management",
|
||||
"loadMore": "Load more",
|
||||
"noMore": "No more",
|
||||
"empty": "No users",
|
||||
"loadFailed": "Failed to load",
|
||||
"retry": "Retry",
|
||||
"selfTag": "Me",
|
||||
"colAccount": "Account",
|
||||
"colDisplayName": "Display Name",
|
||||
"colRole": "Role",
|
||||
"colSourceStatus": "Source",
|
||||
"colCredentialStatus": "Credential",
|
||||
"colLocalLocked": "Local Lock",
|
||||
"colCreatedAt": "Created At",
|
||||
"colActions": "Actions",
|
||||
"locked": "Locked",
|
||||
"unlocked": "Unlocked",
|
||||
"actionEdit": "Edit",
|
||||
"actionResetPassword": "Reset Password",
|
||||
"actionActivate": "Activate",
|
||||
"actionDeactivate": "Deactivate",
|
||||
"actionUnlock": "Unlock"
|
||||
},
|
||||
"filter": {
|
||||
"queryPlaceholder": "Account/name prefix",
|
||||
"statusAll": "All statuses",
|
||||
"search": "Search",
|
||||
"reset": "Reset"
|
||||
},
|
||||
"role": {
|
||||
"staff": "Staff",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"source": {
|
||||
"local": "Local",
|
||||
"active": "Active",
|
||||
"disabled": "Upstream Disabled"
|
||||
},
|
||||
"credential": {
|
||||
"active": "Active",
|
||||
"pending": "Pending"
|
||||
},
|
||||
"bucket": {
|
||||
"active": "Active",
|
||||
"pending": "Pending",
|
||||
"disabled": "Upstream Disabled",
|
||||
"locked": "Locally Locked"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Edit account: {account}",
|
||||
"displayNamePlaceholder": "Display name (1-128 chars)",
|
||||
"lockedHint": "Locking equals deactivation: revokes all sessions of this user; independent of upstream status",
|
||||
"selfGuardHint": "You cannot change your own role or lock yourself (server rejects likewise)",
|
||||
"noChanges": "No changes",
|
||||
"submit": "Save",
|
||||
"success": "Saved"
|
||||
},
|
||||
"reset": {
|
||||
"title": "Reset password: {account}",
|
||||
"revokeHint": "All existing sessions of this user will be revoked immediately",
|
||||
"modeLabel": "Mode",
|
||||
"modeGenerate": "Generate random password",
|
||||
"modeCustom": "Specify password",
|
||||
"customLabel": "New password",
|
||||
"customPlaceholder": "At least 8 characters",
|
||||
"onceWarning": "Shown only once — copy and hand it over to the user",
|
||||
"copy": "Copy",
|
||||
"copied": "Copied to clipboard",
|
||||
"submit": "Reset",
|
||||
"handedOver": "Handed over",
|
||||
"errors": {
|
||||
"required": "Please enter a new password",
|
||||
"length": "Password must be 8-128 characters"
|
||||
}
|
||||
},
|
||||
"confirm": {
|
||||
"activateBody": "Activate user {account}? An initial password must be issued via \"Reset Password\" before login",
|
||||
"deactivateBody": "Deactivate user {account}? All sessions will be revoked (existing tokens fail immediately)",
|
||||
"unlockBody": "Unlock {account}? Upstream disabled status is not affected"
|
||||
},
|
||||
"toast": {
|
||||
"activated": "Activated (reset password to issue initial credentials)",
|
||||
"deactivated": "Deactivated and all sessions revoked",
|
||||
"unlocked": "Local lock released"
|
||||
}
|
||||
},
|
||||
"userSync": {
|
||||
"status": {
|
||||
"title": "User Sync Status",
|
||||
"state": "Engine state",
|
||||
"lastRunAt": "Last run",
|
||||
"lastSuccessAt": "Last success",
|
||||
"sourceVersion": "Watermark",
|
||||
"noRuns": "Sync has never run",
|
||||
"trigger": "Sync Now",
|
||||
"triggerAccepted": "Accepted, syncing…",
|
||||
"runFinished": "Sync finished ({state})",
|
||||
"runFailed": "Sync failed; check run history",
|
||||
"waitFailed": "Timed out or failed waiting for the result; refresh status",
|
||||
"loadFailed": "Failed to load status",
|
||||
"retry": "Retry"
|
||||
},
|
||||
"state": {
|
||||
"idle": "Idle",
|
||||
"running": "Running",
|
||||
"success": "Success",
|
||||
"partial": "Partial",
|
||||
"failed": "Failed"
|
||||
},
|
||||
"trigger": {
|
||||
"cron": "Cron",
|
||||
"manual": "Manual"
|
||||
},
|
||||
"counts": {
|
||||
"added": "Added",
|
||||
"updated": "Updated",
|
||||
"disabled": "Disabled",
|
||||
"failed": "Failed"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Run History (click a row for failures)",
|
||||
"loadMore": "Load more",
|
||||
"noMore": "No more",
|
||||
"empty": "No runs yet",
|
||||
"loadFailed": "Failed to load",
|
||||
"retry": "Retry",
|
||||
"colTrigger": "Trigger",
|
||||
"colState": "State",
|
||||
"colCounts": "Counts",
|
||||
"colStartedAt": "Started At",
|
||||
"colFinishedAt": "Finished At",
|
||||
"colError": "Error"
|
||||
},
|
||||
"errors": {
|
||||
"title": "Failures (run {runId})",
|
||||
"loadFailed": "Failed to load",
|
||||
"retry": "Retry",
|
||||
"empty": "No failures in this run",
|
||||
"colExternalId": "External User",
|
||||
"colCode": "Code",
|
||||
"colDetail": "Detail",
|
||||
"colCreatedAt": "Recorded At"
|
||||
}
|
||||
},
|
||||
"apiMsg": {
|
||||
"AUTH_INVALID_CREDENTIALS": "Invalid account or password",
|
||||
"AUTH_RATE_LIMITED": "Too many failed login attempts; try again later",
|
||||
|
||||
@@ -230,6 +230,11 @@
|
||||
"outside": {
|
||||
"title": "内嵌页面"
|
||||
},
|
||||
"system": {
|
||||
"title": "账号与同步",
|
||||
"users": "账号管理",
|
||||
"userSync": "用户同步"
|
||||
},
|
||||
"albums": {
|
||||
"title": "相册管理",
|
||||
"manage": "相册管理",
|
||||
@@ -436,6 +441,152 @@
|
||||
"empty": "暂无照片"
|
||||
}
|
||||
},
|
||||
"usersManage": {
|
||||
"list": {
|
||||
"title": "账号管理",
|
||||
"loadMore": "加载更多",
|
||||
"noMore": "没有更多了",
|
||||
"empty": "暂无用户",
|
||||
"loadFailed": "加载失败",
|
||||
"retry": "重试",
|
||||
"selfTag": "我",
|
||||
"colAccount": "账号",
|
||||
"colDisplayName": "展示姓名",
|
||||
"colRole": "角色",
|
||||
"colSourceStatus": "来源状态",
|
||||
"colCredentialStatus": "凭据状态",
|
||||
"colLocalLocked": "本地锁定",
|
||||
"colCreatedAt": "创建时间",
|
||||
"colActions": "操作",
|
||||
"locked": "已锁定",
|
||||
"unlocked": "未锁定",
|
||||
"actionEdit": "编辑",
|
||||
"actionResetPassword": "重置密码",
|
||||
"actionActivate": "激活",
|
||||
"actionDeactivate": "停用",
|
||||
"actionUnlock": "解锁"
|
||||
},
|
||||
"filter": {
|
||||
"queryPlaceholder": "账号/姓名前缀",
|
||||
"statusAll": "全部状态",
|
||||
"search": "查询",
|
||||
"reset": "重置"
|
||||
},
|
||||
"role": {
|
||||
"staff": "员工",
|
||||
"admin": "管理员"
|
||||
},
|
||||
"source": {
|
||||
"local": "本地",
|
||||
"active": "正常",
|
||||
"disabled": "上游停用"
|
||||
},
|
||||
"credential": {
|
||||
"active": "已激活",
|
||||
"pending": "待激活"
|
||||
},
|
||||
"bucket": {
|
||||
"active": "正常",
|
||||
"pending": "待激活",
|
||||
"disabled": "上游停用",
|
||||
"locked": "本地锁定"
|
||||
},
|
||||
"edit": {
|
||||
"title": "编辑账号:{account}",
|
||||
"displayNamePlaceholder": "展示姓名(1-128 字符)",
|
||||
"lockedHint": "锁定即停用:撤销该用户全部会话;与上游状态独立",
|
||||
"selfGuardHint": "不能修改自己的角色或锁定自己(服务端同口径拒绝)",
|
||||
"noChanges": "没有变更",
|
||||
"submit": "保存",
|
||||
"success": "已保存"
|
||||
},
|
||||
"reset": {
|
||||
"title": "重置密码:{account}",
|
||||
"revokeHint": "重置后该用户全部既有会话立即失效",
|
||||
"modeLabel": "重置方式",
|
||||
"modeGenerate": "生成随机密码",
|
||||
"modeCustom": "指定新密码",
|
||||
"customLabel": "新密码",
|
||||
"customPlaceholder": "至少 8 位",
|
||||
"onceWarning": "新密码仅此一次展示,请复制转交给用户",
|
||||
"copy": "复制",
|
||||
"copied": "已复制到剪贴板",
|
||||
"submit": "重置",
|
||||
"handedOver": "我已转交",
|
||||
"errors": {
|
||||
"required": "请输入新密码",
|
||||
"length": "密码长度须为 8-128 位"
|
||||
}
|
||||
},
|
||||
"confirm": {
|
||||
"activateBody": "激活用户 {account}?激活后需经「重置密码」出具初始凭据方可登录",
|
||||
"deactivateBody": "停用用户 {account}?其全部会话将被撤销(既有令牌即刻失效)",
|
||||
"unlockBody": "解除 {account} 的本地锁定?上游停用状态不受影响"
|
||||
},
|
||||
"toast": {
|
||||
"activated": "已激活(待重置密码出初始凭据)",
|
||||
"deactivated": "已停用并撤销全部会话",
|
||||
"unlocked": "已解除本地锁定"
|
||||
}
|
||||
},
|
||||
"userSync": {
|
||||
"status": {
|
||||
"title": "用户同步状态",
|
||||
"state": "引擎状态",
|
||||
"lastRunAt": "最近批次",
|
||||
"lastSuccessAt": "最近成功",
|
||||
"sourceVersion": "源水位",
|
||||
"noRuns": "从未运行过同步",
|
||||
"trigger": "手动补拉",
|
||||
"triggerAccepted": "已受理,正在同步…",
|
||||
"runFinished": "同步完成({state})",
|
||||
"runFailed": "同步失败,请查看运行历史",
|
||||
"waitFailed": "等待同步结果超时或出错,请刷新状态",
|
||||
"loadFailed": "状态加载失败",
|
||||
"retry": "重试"
|
||||
},
|
||||
"state": {
|
||||
"idle": "空闲",
|
||||
"running": "同步中",
|
||||
"success": "成功",
|
||||
"partial": "部分成功",
|
||||
"failed": "失败"
|
||||
},
|
||||
"trigger": {
|
||||
"cron": "定时",
|
||||
"manual": "手动"
|
||||
},
|
||||
"counts": {
|
||||
"added": "新增",
|
||||
"updated": "更新",
|
||||
"disabled": "停用",
|
||||
"failed": "失败"
|
||||
},
|
||||
"runs": {
|
||||
"title": "运行历史(点击行查看失败明细)",
|
||||
"loadMore": "加载更多",
|
||||
"noMore": "没有更多了",
|
||||
"empty": "暂无运行记录",
|
||||
"loadFailed": "加载失败",
|
||||
"retry": "重试",
|
||||
"colTrigger": "触发",
|
||||
"colState": "状态",
|
||||
"colCounts": "计数",
|
||||
"colStartedAt": "开始时间",
|
||||
"colFinishedAt": "结束时间",
|
||||
"colError": "错误摘要"
|
||||
},
|
||||
"errors": {
|
||||
"title": "失败明细(批次 {runId})",
|
||||
"loadFailed": "加载失败",
|
||||
"retry": "重试",
|
||||
"empty": "该批次无失败记录",
|
||||
"colExternalId": "上游用户",
|
||||
"colCode": "分类码",
|
||||
"colDetail": "详情",
|
||||
"colCreatedAt": "记录时间"
|
||||
}
|
||||
},
|
||||
"apiMsg": {
|
||||
"AUTH_INVALID_CREDENTIALS": "账号或密码错误",
|
||||
"AUTH_RATE_LIMITED": "登录失败次数过多,请稍后再试",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { AppRouteRecord } from '@/types/router'
|
||||
import { albumsRoutes } from './albums'
|
||||
import { systemRoutes } from './system'
|
||||
|
||||
/**
|
||||
* 导出所有模块化路由
|
||||
* @photo/admin 裁剪:模板演示路由(dashboard/template/widgets/examples/system/
|
||||
* article/result/exception/safeguard/help)已移除,仅保留业务菜单。
|
||||
*/
|
||||
export const routeModules: AppRouteRecord[] = [albumsRoutes]
|
||||
export const routeModules: AppRouteRecord[] = [albumsRoutes, systemRoutes]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 账号治理路由(P4a Task 8:账号管理 + 用户同步)
|
||||
*/
|
||||
import { AppRouteRecord } from '@/types/router'
|
||||
|
||||
export const systemRoutes: AppRouteRecord = {
|
||||
name: 'System',
|
||||
path: '/system',
|
||||
component: '/index/index',
|
||||
meta: {
|
||||
title: 'menus.system.title',
|
||||
icon: 'ri:shield-user-line'
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'users',
|
||||
name: 'SystemUsers',
|
||||
component: '/system/users',
|
||||
meta: {
|
||||
title: 'menus.system.users',
|
||||
icon: 'ri:user-settings-line',
|
||||
keepAlive: false
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'user-sync',
|
||||
name: 'SystemUserSync',
|
||||
component: '/system/user-sync',
|
||||
meta: {
|
||||
title: 'menus.system.userSync',
|
||||
icon: 'ri:refresh-line',
|
||||
keepAlive: false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* 账号治理与用户同步域接口类型(对齐 @photo/contracts openapi.yaml tags
|
||||
* [admin]:AdminUser / AdminUserList / AdminPasswordResetResponse 与
|
||||
* UserSyncStatus / UserSyncRun / UserSyncErrorList)
|
||||
*
|
||||
* 与 album.d.ts 同用全局 Api 命名空间(declare namespace 自动合并)。
|
||||
* 契约要点:
|
||||
* - 管理列表(未带 accountPrefix 的 GET /admin/users):全量用户 + query/status
|
||||
* 过滤 + createdAt+ID 倒序键集游标(与相册域同一 CursorPageMeta 不变式)
|
||||
* - AdminUser.sourceStatus 只读(上游状态仅同步任务维护);localLocked 与
|
||||
* 上游状态独立(技术方案 3.1A:本地锁定不因上游恢复解除)
|
||||
* - 重置密码响应 newPassword 仅此一次返回(转交用户后不再可见)
|
||||
* - 同步状态 counts = 最近批次计数(从未运行为 null)
|
||||
*
|
||||
* @module types/api/adminUser
|
||||
*/
|
||||
|
||||
declare namespace Api {
|
||||
/** 账号治理域(P4a Task 6 端点) */
|
||||
namespace AdminUser {
|
||||
/** 公司角色(相册角色另表) */
|
||||
type Role = 'staff' | 'admin'
|
||||
|
||||
/** 来源状态:local=本地创建;active/disabled=同步源状态 */
|
||||
type SourceStatus = 'local' | 'active' | 'disabled'
|
||||
|
||||
/** 凭据状态:active=可登录;pending=同步创建待激活 */
|
||||
type CredentialStatus = 'active' | 'pending'
|
||||
|
||||
/**
|
||||
* 管理列表治理状态过滤(单值归类,后端优先级 pending > disabled >
|
||||
* locked > active;多态用户只落一个桶)
|
||||
*/
|
||||
type StatusFilter = 'active' | 'pending' | 'disabled' | 'locked'
|
||||
|
||||
/** 用户治理条目(不含邮箱/手机/密码等凭据字段) */
|
||||
interface Item {
|
||||
id: string
|
||||
account: string
|
||||
displayName: string
|
||||
role: Role
|
||||
sourceStatus: SourceStatus
|
||||
localLocked: boolean
|
||||
credentialStatus: CredentialStatus
|
||||
locale: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** 管理列表响应(游标分页) */
|
||||
interface ListResponse {
|
||||
items: Item[]
|
||||
nextCursor: string | null
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
/** 管理列表查询参数(双模式分流:不带 accountPrefix 即管理列表模式) */
|
||||
interface ListParams {
|
||||
/** account/displayName 二进制前缀(1..64,大小写敏感,非全文搜索) */
|
||||
query?: string
|
||||
/** 治理状态单值过滤 */
|
||||
status?: StatusFilter
|
||||
cursor?: string
|
||||
limit?: number
|
||||
}
|
||||
|
||||
/** 治理属性部分更新(仅提交字段被修改;sourceStatus 不在可更新集) */
|
||||
interface UpdatePayload {
|
||||
role?: Role
|
||||
localLocked?: boolean
|
||||
displayName?: string
|
||||
}
|
||||
|
||||
/** 重置密码请求(newPassword 缺省由服务端生成 16 位随机密码) */
|
||||
interface ResetPasswordPayload {
|
||||
newPassword?: string
|
||||
}
|
||||
|
||||
/** 重置结果(newPassword 仅此一次返回) */
|
||||
interface ResetPasswordResponse {
|
||||
newPassword: string
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户同步域(P4a Task 7 端点) */
|
||||
namespace UserSync {
|
||||
/** 引擎状态:idle=空闲/从未运行;其余为最近批次结局 */
|
||||
type State = 'idle' | 'running' | 'success' | 'partial' | 'failed'
|
||||
|
||||
/** 批次状态(partial=部分行失败,其余行照常应用) */
|
||||
type RunState = 'running' | 'success' | 'partial' | 'failed'
|
||||
|
||||
/** 触发方式 */
|
||||
type Trigger = 'cron' | 'manual'
|
||||
|
||||
/** 批次计数 */
|
||||
interface Counts {
|
||||
/** 新增用户数(建为待激活) */
|
||||
added: number
|
||||
/** 幂等更新数(改名等) */
|
||||
updated: number
|
||||
/** 上游停用数(撤会话) */
|
||||
disabled: number
|
||||
/** 失败行数(明细见 /admin/user-sync/errors) */
|
||||
failed: number
|
||||
}
|
||||
|
||||
/** 同步引擎状态 */
|
||||
interface Status {
|
||||
lastRunAt: string | null
|
||||
lastSuccessAt: string | null
|
||||
state: State
|
||||
/** 已提交的源水位(版本游标);从未同步为 null */
|
||||
sourceVersion: number | null
|
||||
/** 最近批次计数;从未运行为 null */
|
||||
counts: Counts | null
|
||||
}
|
||||
|
||||
/** 同步批次条目 */
|
||||
interface RunItem {
|
||||
id: string
|
||||
trigger: Trigger
|
||||
state: RunState
|
||||
/** 本批次已提交的源水位(同步游标,非分页游标);未提交为 null */
|
||||
cursor: number | null
|
||||
counts: Counts
|
||||
startedAt: string
|
||||
finishedAt: string | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
/** 运行历史响应(startedAt+ID 倒序键集游标) */
|
||||
interface RunListResponse {
|
||||
items: RunItem[]
|
||||
nextCursor: string | null
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
/** 手动触发受理结果(202;运行中批次复用其 runId) */
|
||||
interface RunCreatedResponse {
|
||||
runId: string
|
||||
}
|
||||
|
||||
/** 同步失败行明细(坏行记录) */
|
||||
interface ErrorItem {
|
||||
runId: string
|
||||
externalUserId: string
|
||||
code: string
|
||||
detail: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** 失败明细列表(无游标即取即用) */
|
||||
interface ErrorListResponse {
|
||||
items: ErrorItem[]
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -80,6 +80,7 @@ declare module 'vue' {
|
||||
ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
|
||||
ElOption: typeof import('element-plus/es')['ElOption']
|
||||
ElPopover: typeof import('element-plus/es')['ElPopover']
|
||||
ElRadio: typeof import('element-plus/es')['ElRadio']
|
||||
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
||||
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
||||
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createAutoRefresh, waitSyncTerminal } from './syncPolling'
|
||||
|
||||
const statusOf = (state: Api.UserSync.State): Api.UserSync.Status => ({
|
||||
lastRunAt: null,
|
||||
lastSuccessAt: null,
|
||||
state,
|
||||
sourceVersion: null,
|
||||
counts: null
|
||||
})
|
||||
|
||||
describe('waitSyncTerminal 批次终态等待', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('首次查询即终态 → 立刻 resolve,不排定后续轮询', async () => {
|
||||
const fetchStatus = vi.fn().mockResolvedValue(statusOf('success'))
|
||||
const result = await waitSyncTerminal(fetchStatus, { intervalMs: 100 })
|
||||
expect(result.state).toBe('success')
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('running → 按间隔轮询直到离开 running', async () => {
|
||||
const fetchStatus = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(statusOf('running'))
|
||||
.mockResolvedValueOnce(statusOf('running'))
|
||||
.mockResolvedValueOnce(statusOf('partial'))
|
||||
const promise = waitSyncTerminal(fetchStatus, { intervalMs: 100 })
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
const settled = await promise
|
||||
expect(settled.state).toBe('partial')
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(3)
|
||||
// 终态后不再轮询
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('超时上限 → reject(不再无限轮询)', async () => {
|
||||
const fetchStatus = vi.fn().mockResolvedValue(statusOf('running'))
|
||||
const promise = waitSyncTerminal(fetchStatus, { intervalMs: 100, timeoutMs: 250 })
|
||||
// 先挂 rejection 断言再推进时间,避免 reject 先于 handler 的未处理窗口
|
||||
const expectation = expect(promise).rejects.toThrow('timeout')
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await expectation
|
||||
const callsAfterTimeout = fetchStatus.mock.calls.length
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(fetchStatus.mock.calls.length).toBe(callsAfterTimeout)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createAutoRefresh 周期刷新', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('start 立即执行一次,之后按间隔触发;stop 即停止', async () => {
|
||||
const fn = vi.fn().mockResolvedValue(undefined)
|
||||
const handle = createAutoRefresh(fn, 10_000)
|
||||
handle.start()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(fn).toHaveBeenCalledTimes(3)
|
||||
|
||||
handle.stop()
|
||||
expect(handle.isRunning()).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
expect(fn).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('重复 start 幂等(不叠加定时器)', async () => {
|
||||
const fn = vi.fn().mockResolvedValue(undefined)
|
||||
const handle = createAutoRefresh(fn, 10_000)
|
||||
handle.start()
|
||||
handle.start()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
handle.stop()
|
||||
})
|
||||
|
||||
it('慢响应不堆叠:上一次未完成时间隔到点跳过', async () => {
|
||||
let release: (() => void) | undefined
|
||||
const fn = vi.fn().mockImplementation(() => new Promise<void>((resolve) => (release = resolve)))
|
||||
const handle = createAutoRefresh(fn, 100)
|
||||
handle.start()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(200)
|
||||
// 首次仍在执行 → 间隔到点不重入
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
release?.()
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
handle.stop()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 用户同步页轮询逻辑(纯函数/可注入依赖,vitest 用 fake timers 覆盖)
|
||||
*
|
||||
* - waitSyncTerminal:手动补拉 202 受理后等待批次离开 running(间隔轮询 +
|
||||
* 超时上限;终态即 resolve,避免页面无限转圈)
|
||||
* - createAutoRefresh:页面打开期间的定时状态刷新(10s);立即执行一次 +
|
||||
* 间隔触发 + 重入保护(慢响应不堆叠)+ 幂等 start/stop(组件
|
||||
* onUnmounted 清理,防路由离开后仍在请求)
|
||||
*/
|
||||
|
||||
export interface WaitSyncOptions {
|
||||
/** 轮询间隔(默认 1.5s:批次通常秒级完成) */
|
||||
intervalMs?: number
|
||||
/** 总超时(默认 45s:超过视为异常,交调用方展示错误) */
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 1500
|
||||
const DEFAULT_TIMEOUT_MS = 45_000
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询同步状态直到批次离开 running(首次查询即终态则立刻 resolve)。
|
||||
* 超时 reject(Error.message = 'timeout');fetchStatus 的网络错误向上抛。
|
||||
*/
|
||||
export function waitSyncTerminal(
|
||||
fetchStatus: () => Promise<Api.UserSync.Status>,
|
||||
options: WaitSyncOptions = {}
|
||||
): Promise<Api.UserSync.Status> {
|
||||
const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
||||
const deadline = Date.now() + timeoutMs
|
||||
return (async function poll(): Promise<Api.UserSync.Status> {
|
||||
const status = await fetchStatus()
|
||||
if (status.state !== 'running') return status
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error('timeout')
|
||||
}
|
||||
await delay(intervalMs)
|
||||
return poll()
|
||||
})()
|
||||
}
|
||||
|
||||
export interface AutoRefreshHandle {
|
||||
/** 开始(立即执行一次 + 间隔触发;重复调用幂等) */
|
||||
start: () => void
|
||||
/** 停止并清理定时器(重复调用幂等) */
|
||||
stop: () => void
|
||||
/** 是否在刷新周期内 */
|
||||
isRunning: () => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 周期刷新:start 立即触发一次;执行中的回调未完成时不堆叠下一次。
|
||||
* 返回的 handle 由组件持有,onUnmounted 时 stop()。
|
||||
*/
|
||||
export function createAutoRefresh(
|
||||
fn: () => void | Promise<unknown>,
|
||||
intervalMs = 10_000
|
||||
): AutoRefreshHandle {
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let inFlight = false
|
||||
|
||||
async function run(): Promise<void> {
|
||||
if (inFlight) return
|
||||
inFlight = true
|
||||
try {
|
||||
await fn()
|
||||
} finally {
|
||||
inFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
if (timer !== null) return
|
||||
void run()
|
||||
timer = setInterval(() => void run(), intervalMs)
|
||||
},
|
||||
stop() {
|
||||
if (timer === null) return
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
},
|
||||
isRunning() {
|
||||
return timer !== null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
ADMIN_STATUS_FILTER_VALUES,
|
||||
buildAdminUserParams,
|
||||
buildResetPasswordPayload,
|
||||
buildUserUpdatePayload,
|
||||
statusBucketOf
|
||||
} from './userAdmin'
|
||||
|
||||
const baseUser: Api.AdminUser.Item = {
|
||||
id: 'u1',
|
||||
account: 'li.demo',
|
||||
displayName: '李演示',
|
||||
role: 'staff',
|
||||
sourceStatus: 'active',
|
||||
localLocked: false,
|
||||
credentialStatus: 'active',
|
||||
locale: null,
|
||||
createdAt: '2026-09-20T00:00:00.000Z'
|
||||
}
|
||||
|
||||
describe('buildAdminUserParams 过滤参数映射', () => {
|
||||
it('空查询与「全部」状态均不上送(undefined 语义)', () => {
|
||||
const params = buildAdminUserParams({ query: ' ', status: '' })
|
||||
expect(params).not.toHaveProperty('query')
|
||||
expect(params).not.toHaveProperty('status')
|
||||
})
|
||||
|
||||
it('query 去首尾空白后上送;合法状态透传', () => {
|
||||
const params = buildAdminUserParams({ query: ' li ', status: 'pending' })
|
||||
expect(params.query).toBe('li')
|
||||
expect(params.status).toBe('pending')
|
||||
})
|
||||
|
||||
it('游标与 limit 透传(加载更多)', () => {
|
||||
const params = buildAdminUserParams({ query: '', status: 'locked' }, 'c1', 20)
|
||||
expect(params.cursor).toBe('c1')
|
||||
expect(params.limit).toBe(20)
|
||||
expect(params.status).toBe('locked')
|
||||
})
|
||||
})
|
||||
|
||||
describe('statusBucketOf 治理状态归类(与后端过滤同口径)', () => {
|
||||
it('优先级 pending > disabled > locked > active', () => {
|
||||
expect(statusBucketOf({ ...baseUser, credentialStatus: 'pending', localLocked: true })).toBe(
|
||||
'pending'
|
||||
)
|
||||
expect(statusBucketOf({ ...baseUser, sourceStatus: 'disabled', localLocked: true })).toBe(
|
||||
'disabled'
|
||||
)
|
||||
expect(statusBucketOf({ ...baseUser, localLocked: true })).toBe('locked')
|
||||
expect(statusBucketOf(baseUser)).toBe('active')
|
||||
})
|
||||
|
||||
it('取值集与契约 AdminUserStatusFilter 一致', () => {
|
||||
expect([...ADMIN_STATUS_FILTER_VALUES]).toEqual(['active', 'pending', 'disabled', 'locked'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildUserUpdatePayload 编辑载荷收敛', () => {
|
||||
it('只提交变更字段(role + localLocked 变更、displayName 不变则省略)', () => {
|
||||
const payload = buildUserUpdatePayload(baseUser, {
|
||||
role: 'admin',
|
||||
displayName: baseUser.displayName,
|
||||
localLocked: true
|
||||
})
|
||||
expect(payload).toEqual({ role: 'admin', localLocked: true })
|
||||
})
|
||||
|
||||
it('displayName 空串视为「不改」(契约 1..128,清空不是合法目标态)', () => {
|
||||
const payload = buildUserUpdatePayload(baseUser, {
|
||||
role: 'staff',
|
||||
displayName: ' ',
|
||||
localLocked: false
|
||||
})
|
||||
expect(payload).toEqual({})
|
||||
})
|
||||
|
||||
it('displayName 变更去首尾空白后上送', () => {
|
||||
const payload = buildUserUpdatePayload(baseUser, {
|
||||
role: 'staff',
|
||||
displayName: ' 王演示 ',
|
||||
localLocked: false
|
||||
})
|
||||
expect(payload).toEqual({ displayName: '王演示' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildResetPasswordPayload 重置密码载荷', () => {
|
||||
it('generate 模式不上送 newPassword(服务端生成)', () => {
|
||||
expect(buildResetPasswordPayload('generate', '')).toEqual({ ok: true, payload: {} })
|
||||
})
|
||||
|
||||
it('custom 模式镜像契约边界:空 → required;长度越界 → length;合法 → 透传', () => {
|
||||
expect(buildResetPasswordPayload('custom', ' ')).toEqual({ ok: false, error: 'required' })
|
||||
expect(buildResetPasswordPayload('custom', 'short')).toEqual({ ok: false, error: 'length' })
|
||||
expect(buildResetPasswordPayload('custom', 'a'.repeat(129))).toEqual({
|
||||
ok: false,
|
||||
error: 'length'
|
||||
})
|
||||
expect(buildResetPasswordPayload('custom', ' new-password-1 ')).toEqual({
|
||||
ok: true,
|
||||
payload: { newPassword: 'new-password-1' }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* 账号治理页纯逻辑(无组件依赖,vitest 直接覆盖)
|
||||
*
|
||||
* - 过滤参数映射:空查询/「全部」状态不上送(axios 亦会丢弃 undefined,
|
||||
* 这里显式省略让请求 URL 干净、单测可断言)
|
||||
* - 治理状态归类:与后端管理列表 status 过滤同一优先级
|
||||
* (pending > disabled > locked > active),前端展示与过滤口径一致
|
||||
* - PATCH 载荷收敛:只提交变更字段(服务端幂等 no-op 不落审计,前端不
|
||||
* 制造 no-op 噪音);displayName 清空视为「不改」(契约 1..128)
|
||||
* - 重置密码载荷:generate 模式不上送 newPassword(服务端生成 16 位);
|
||||
* custom 模式镜像契约 8..128 边界
|
||||
*/
|
||||
|
||||
/** 治理状态过滤取值(「全部」= 空串,不上送) */
|
||||
export const ADMIN_STATUS_FILTER_VALUES = ['active', 'pending', 'disabled', 'locked'] as const
|
||||
|
||||
export type AdminStatusFilter = (typeof ADMIN_STATUS_FILTER_VALUES)[number]
|
||||
|
||||
export interface AdminUserFilterInput {
|
||||
/** account/displayName 前缀(1..64;空 = 不过滤) */
|
||||
query: string
|
||||
/** 治理状态('' = 全部) */
|
||||
status: string
|
||||
}
|
||||
|
||||
function isStatusFilter(value: string): value is AdminStatusFilter {
|
||||
return (ADMIN_STATUS_FILTER_VALUES as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** 过滤条件 → 列表查询参数(空值省略;query 去首尾空白) */
|
||||
export function buildAdminUserParams(
|
||||
filter: AdminUserFilterInput,
|
||||
cursor?: string,
|
||||
limit?: number
|
||||
): Api.AdminUser.ListParams {
|
||||
const params: Api.AdminUser.ListParams = { cursor, limit }
|
||||
const query = filter.query.trim()
|
||||
if (query !== '') params.query = query
|
||||
if (isStatusFilter(filter.status)) params.status = filter.status
|
||||
return params
|
||||
}
|
||||
|
||||
/** 用户 → 治理状态桶(与后端过滤同一归类优先级) */
|
||||
export function statusBucketOf(
|
||||
user: Pick<Api.AdminUser.Item, 'credentialStatus' | 'sourceStatus' | 'localLocked'>
|
||||
): AdminStatusFilter {
|
||||
if (user.credentialStatus === 'pending') return 'pending'
|
||||
if (user.sourceStatus === 'disabled') return 'disabled'
|
||||
if (user.localLocked) return 'locked'
|
||||
return 'active'
|
||||
}
|
||||
|
||||
/** 治理状态桶 → ElTag type(展示层配色) */
|
||||
export const BUCKET_TAG_TYPE: Record<AdminStatusFilter, 'success' | 'warning' | 'danger' | 'info'> =
|
||||
{
|
||||
active: 'success',
|
||||
pending: 'warning',
|
||||
disabled: 'danger',
|
||||
locked: 'danger'
|
||||
}
|
||||
|
||||
/** 同步引擎状态 → ElTag type */
|
||||
export const SYNC_STATE_TAG_TYPE: Record<
|
||||
Api.UserSync.State,
|
||||
'success' | 'warning' | 'danger' | 'info'
|
||||
> = {
|
||||
idle: 'info',
|
||||
running: 'warning',
|
||||
success: 'success',
|
||||
partial: 'warning',
|
||||
failed: 'danger'
|
||||
}
|
||||
|
||||
/** 编辑对话框草稿(三项治理属性) */
|
||||
export interface AdminUserEditDraft {
|
||||
role: Api.AdminUser.Role
|
||||
displayName: string
|
||||
localLocked: boolean
|
||||
}
|
||||
|
||||
/** 编辑草稿 → PATCH 载荷(只提交变更字段;displayName 空串视为不改) */
|
||||
export function buildUserUpdatePayload(
|
||||
target: Api.AdminUser.Item,
|
||||
draft: AdminUserEditDraft
|
||||
): Api.AdminUser.UpdatePayload {
|
||||
const payload: Api.AdminUser.UpdatePayload = {}
|
||||
if (draft.role !== target.role) payload.role = draft.role
|
||||
const displayName = draft.displayName.trim()
|
||||
if (displayName !== '' && displayName !== target.displayName) {
|
||||
payload.displayName = displayName
|
||||
}
|
||||
if (draft.localLocked !== target.localLocked) payload.localLocked = draft.localLocked
|
||||
return payload
|
||||
}
|
||||
|
||||
export type ResetPasswordMode = 'generate' | 'custom'
|
||||
|
||||
export type ResetPayloadResult =
|
||||
| { ok: true; payload: Api.AdminUser.ResetPasswordPayload }
|
||||
| { ok: false; error: 'required' | 'length' }
|
||||
|
||||
/** 重置密码表单 → 请求载荷(custom 模式镜像契约 8..128 边界) */
|
||||
export function buildResetPasswordPayload(
|
||||
mode: ResetPasswordMode,
|
||||
customPassword: string
|
||||
): ResetPayloadResult {
|
||||
if (mode === 'generate') return { ok: true, payload: {} }
|
||||
const password = customPassword.trim()
|
||||
if (password === '') return { ok: false, error: 'required' }
|
||||
if (password.length < 8 || password.length > 128) return { ok: false, error: 'length' }
|
||||
return { ok: true, payload: { newPassword: password } }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { useSyncErrors } from './useSyncErrors'
|
||||
|
||||
const errorOf = (runId: string, externalId: string): Api.UserSync.ErrorItem => ({
|
||||
runId,
|
||||
externalUserId: externalId,
|
||||
code: 'invalid_record',
|
||||
detail: `missing displayName for ${externalId}`,
|
||||
createdAt: '2026-09-20T00:00:00.000Z'
|
||||
})
|
||||
|
||||
describe('useSyncErrors 失败明细抽屉', () => {
|
||||
it('open(runId) 拉取该批次明细并打开抽屉', async () => {
|
||||
const list = vi.fn().mockResolvedValue({ items: [errorOf('r1', 'mock-u-001')] })
|
||||
const drawer = useSyncErrors({ list })
|
||||
await drawer.open('r1')
|
||||
expect(list).toHaveBeenCalledWith('r1')
|
||||
expect(drawer.drawerVisible.value).toBe(true)
|
||||
expect(drawer.drawerRunId.value).toBe('r1')
|
||||
expect(drawer.items.value.map((item) => item.externalUserId)).toEqual(['mock-u-001'])
|
||||
})
|
||||
|
||||
it('切换批次整表替换;close 清空并收起', async () => {
|
||||
const list = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ items: [errorOf('r1', 'mock-u-001'), errorOf('r1', 'mock-u-002')] })
|
||||
.mockResolvedValueOnce({ items: [errorOf('r2', 'mock-u-003')] })
|
||||
const drawer = useSyncErrors({ list })
|
||||
await drawer.open('r1')
|
||||
expect(drawer.items.value).toHaveLength(2)
|
||||
await drawer.open('r2')
|
||||
expect(drawer.drawerRunId.value).toBe('r2')
|
||||
expect(drawer.items.value.map((item) => item.externalUserId)).toEqual(['mock-u-003'])
|
||||
drawer.close()
|
||||
expect(drawer.drawerVisible.value).toBe(false)
|
||||
expect(drawer.items.value).toEqual([])
|
||||
expect(drawer.drawerRunId.value).toBeNull()
|
||||
})
|
||||
|
||||
it('拉取失败置 error(抽屉保持打开),load 重试成功后恢复', async () => {
|
||||
const list = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('network'))
|
||||
.mockResolvedValueOnce({ items: [errorOf('r1', 'mock-u-009')] })
|
||||
const drawer = useSyncErrors({ list })
|
||||
await drawer.open('r1')
|
||||
expect(drawer.error.value).toBeInstanceOf(Error)
|
||||
expect(drawer.items.value).toEqual([])
|
||||
expect(drawer.drawerVisible.value).toBe(true)
|
||||
await drawer.load()
|
||||
expect(drawer.error.value).toBeNull()
|
||||
expect(drawer.items.value).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 失败明细抽屉状态(逻辑层抽离,vitest 覆盖按批次打开/关闭/重试)
|
||||
*
|
||||
* open(runId) 拉取该批次坏行;切批次整表替换;close 清空(items 归零,
|
||||
* 下次打开重新拉取——错误明细无游标,量小即取即用)。
|
||||
*/
|
||||
import { computed, ref, shallowRef } from 'vue'
|
||||
import { fetchUserSyncErrors } from '@/api/userSync'
|
||||
|
||||
export interface SyncErrorsApi {
|
||||
list: (runId: string) => Promise<Api.UserSync.ErrorListResponse>
|
||||
}
|
||||
|
||||
export function useSyncErrors(api: SyncErrorsApi = { list: fetchUserSyncErrors }) {
|
||||
/** 当前抽屉指向的批次(null = 关闭) */
|
||||
const drawerRunId = ref<string | null>(null)
|
||||
const items = shallowRef<Api.UserSync.ErrorItem[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<Error | null>(null)
|
||||
|
||||
const drawerVisible = computed({
|
||||
get: () => drawerRunId.value !== null,
|
||||
set: (visible: boolean) => {
|
||||
if (!visible) close()
|
||||
}
|
||||
})
|
||||
|
||||
/** 拉取当前批次明细(重试复用同一入口) */
|
||||
async function load(): Promise<void> {
|
||||
const runId = drawerRunId.value
|
||||
if (runId === null || loading.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const res = await api.list(runId)
|
||||
items.value = res.items
|
||||
} catch (e) {
|
||||
error.value = e as Error
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开抽屉并拉取该批次(正在拉取时切批次:等完成后以下一次 open 为准) */
|
||||
async function open(runId: string): Promise<void> {
|
||||
if (drawerRunId.value === runId) {
|
||||
await load()
|
||||
return
|
||||
}
|
||||
drawerRunId.value = runId
|
||||
items.value = []
|
||||
await load()
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
drawerRunId.value = null
|
||||
items.value = []
|
||||
error.value = null
|
||||
}
|
||||
|
||||
return { drawerVisible, drawerRunId, items, loading, error, open, load, close }
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
<!-- 用户同步管理页(P4a Task 8):状态卡(引擎状态/水位/计数 + 手动补拉)、
|
||||
运行历史(游标累积)、失败明细抽屉(点行打开)。页面存续期间 10s 自动
|
||||
刷新状态(onUnmounted 清理);手动补拉 202 受理后轮询至批次离开 running。 -->
|
||||
<template>
|
||||
<div class="p-5">
|
||||
<!-- ── 状态卡 ── -->
|
||||
<ElCard data-test="sync-status-card" class="mb-4">
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>{{ $t('userSync.status.title') }}</span>
|
||||
<ElButton
|
||||
type="primary"
|
||||
:loading="triggering"
|
||||
:disabled="status?.state === 'running'"
|
||||
data-test="sync-trigger-btn"
|
||||
@click="triggerSync"
|
||||
>
|
||||
{{ $t('userSync.status.trigger') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="statusError && !status" data-test="sync-status-error">
|
||||
<ElAlert type="error" :closable="false">
|
||||
<div class="flex items-center gap-2">
|
||||
<span>{{ $t('userSync.status.loadFailed') }}:{{ statusError.message }}</span>
|
||||
<ElButton size="small" data-test="sync-status-retry" @click="refreshStatus">
|
||||
{{ $t('userSync.status.retry') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElAlert>
|
||||
</div>
|
||||
|
||||
<div v-else v-loading="statusLoading" data-test="sync-status-body">
|
||||
<div class="flex flex-wrap items-center gap-6">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-gray-500">{{ $t('userSync.status.state') }}</span>
|
||||
<ElTag
|
||||
:type="status ? SYNC_STATE_TAG_TYPE[status.state] : 'info'"
|
||||
:data-state="status?.state ?? 'idle'"
|
||||
data-test="sync-state-tag"
|
||||
>
|
||||
{{ $t(`userSync.state.${status?.state ?? 'idle'}`) }}
|
||||
</ElTag>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500">{{ $t('userSync.status.lastRunAt') }}</span>
|
||||
<span class="ml-2">{{ formatDateTime(status?.lastRunAt) }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500">{{ $t('userSync.status.lastSuccessAt') }}</span>
|
||||
<span class="ml-2">{{ formatDateTime(status?.lastSuccessAt) }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500">{{ $t('userSync.status.sourceVersion') }}</span>
|
||||
<span class="ml-2" data-test="sync-source-version">
|
||||
{{ status?.sourceVersion ?? '-' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近批次计数 chips(从未运行为空展示) -->
|
||||
<div v-if="status?.counts" class="flex flex-wrap gap-2 mt-3" data-test="sync-counts">
|
||||
<ElTag
|
||||
v-for="key in COUNT_KEYS"
|
||||
:key="key"
|
||||
:type="key === 'failed' && status.counts[key] > 0 ? 'danger' : 'info'"
|
||||
:data-test="`sync-count-${key}`"
|
||||
>
|
||||
{{ $t(`userSync.counts.${key}`) }} {{ status.counts[key] }}
|
||||
</ElTag>
|
||||
</div>
|
||||
<div v-else class="text-gray-400 text-sm mt-3" data-test="sync-counts-empty">
|
||||
{{ $t('userSync.status.noRuns') }}
|
||||
</div>
|
||||
</div>
|
||||
</ElCard>
|
||||
|
||||
<!-- ── 运行历史 ── -->
|
||||
<ElCard data-test="sync-runs-card">
|
||||
<template #header>
|
||||
<span>{{ $t('userSync.runs.title') }}</span>
|
||||
</template>
|
||||
|
||||
<ElAlert
|
||||
v-if="runsError && !runs.length"
|
||||
type="error"
|
||||
:closable="false"
|
||||
data-test="sync-runs-error"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span>{{ $t('userSync.runs.loadFailed') }}:{{ runsError.message }}</span>
|
||||
<ElButton size="small" data-test="sync-runs-retry" @click="loadFirstRuns()">
|
||||
{{ $t('userSync.runs.retry') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElAlert>
|
||||
|
||||
<ElTable
|
||||
v-else
|
||||
v-loading="runsLoading"
|
||||
:data="runs"
|
||||
row-class-name="sync-run-row"
|
||||
data-test="sync-runs-table"
|
||||
@row-click="onRunClick"
|
||||
>
|
||||
<ElTableColumn :label="$t('userSync.runs.colTrigger')" width="110">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="row.trigger === 'manual' ? 'warning' : 'info'" effect="plain">
|
||||
{{ $t(`userSync.trigger.${row.trigger}`) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.runs.colState')" width="110">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="runStateTagOf(row.state)">
|
||||
{{ $t(`userSync.state.${row.state}`) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.runs.colCounts')" min-width="240">
|
||||
<template #default="{ row }">
|
||||
<span class="text-sm" data-test="sync-run-counts">
|
||||
{{ $t('userSync.counts.added') }} {{ row.counts.added }} ·
|
||||
{{ $t('userSync.counts.updated') }} {{ row.counts.updated }} ·
|
||||
{{ $t('userSync.counts.disabled') }} {{ row.counts.disabled }} ·
|
||||
{{ $t('userSync.counts.failed') }} {{ row.counts.failed }}
|
||||
</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.runs.colStartedAt')" width="160">
|
||||
<template #default="{ row }">
|
||||
<span>{{ formatDateTime(row.startedAt) }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.runs.colFinishedAt')" width="160">
|
||||
<template #default="{ row }">
|
||||
<span>{{ formatDateTime(row.finishedAt) }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.runs.colError')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<span class="text-gray-500 text-sm break-all">{{ row.error ?? '-' }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
|
||||
<template #empty>
|
||||
<ElEmpty v-if="!runsLoading" :description="$t('userSync.runs.empty')" />
|
||||
</template>
|
||||
</ElTable>
|
||||
|
||||
<div v-if="runs.length" class="mt-4 text-center">
|
||||
<ElButton
|
||||
v-if="runsHasMore"
|
||||
:loading="runsLoading"
|
||||
data-test="sync-runs-load-more"
|
||||
@click="loadMoreRuns()"
|
||||
>
|
||||
{{ $t('userSync.runs.loadMore') }}
|
||||
</ElButton>
|
||||
<span v-else class="text-gray-400 text-sm">{{ $t('userSync.runs.noMore') }}</span>
|
||||
</div>
|
||||
</ElCard>
|
||||
|
||||
<!-- ── 失败明细抽屉(点运行历史行打开) ── -->
|
||||
<ElDrawer
|
||||
v-model="errors.drawerVisible.value"
|
||||
:title="$t('userSync.errors.title', { runId: errors.drawerRunId.value ?? '' })"
|
||||
size="560px"
|
||||
data-test="sync-errors-drawer"
|
||||
>
|
||||
<div v-if="errors.error.value" data-test="sync-errors-error">
|
||||
<ElAlert type="error" :closable="false">
|
||||
<div class="flex items-center gap-2">
|
||||
<span>{{ $t('userSync.errors.loadFailed') }}:{{ errors.error.value.message }}</span>
|
||||
<ElButton size="small" data-test="sync-errors-retry" @click="errors.load()">
|
||||
{{ $t('userSync.errors.retry') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElAlert>
|
||||
</div>
|
||||
<ElTable
|
||||
v-else
|
||||
v-loading="errors.loading.value"
|
||||
:data="errors.items.value"
|
||||
data-test="sync-errors-table"
|
||||
>
|
||||
<ElTableColumn :label="$t('userSync.errors.colExternalId')" min-width="130">
|
||||
<template #default="{ row }">
|
||||
<span class="font-mono text-sm">{{ row.externalUserId }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.errors.colCode')" width="170">
|
||||
<template #default="{ row }">
|
||||
<ElTag type="danger" effect="plain" size="small">{{ row.code }}</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.errors.colDetail')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<span class="text-sm break-all">{{ row.detail }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('userSync.errors.colCreatedAt')" width="160">
|
||||
<template #default="{ row }">
|
||||
<span>{{ formatDateTime(row.createdAt) }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<template #empty>
|
||||
<ElEmpty
|
||||
v-if="!errors.loading.value"
|
||||
:description="$t('userSync.errors.empty')"
|
||||
data-test="sync-errors-empty"
|
||||
/>
|
||||
</template>
|
||||
</ElTable>
|
||||
</ElDrawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { fetchTriggerUserSyncRun, fetchUserSyncRuns, fetchUserSyncStatus } from '@/api/userSync'
|
||||
import { useCursorList } from '@/views/albums/composables/useCursorList'
|
||||
import { formatDateTime } from '@/utils/albums/format'
|
||||
import { createAutoRefresh, waitSyncTerminal } from '@/utils/system/syncPolling'
|
||||
import { SYNC_STATE_TAG_TYPE } from '@/utils/system/userAdmin'
|
||||
import { useSyncErrors } from './composables/useSyncErrors'
|
||||
|
||||
defineOptions({ name: 'SystemUserSync' })
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
const COUNT_KEYS = ['added', 'updated', 'disabled', 'failed'] as const
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
/** 模板取值桥(ElTable 行槽位为 any,模板表达式不可写 as 断言) */
|
||||
function runStateTagOf(state: Api.UserSync.RunState): 'success' | 'warning' | 'danger' | 'info' {
|
||||
return SYNC_STATE_TAG_TYPE[state]
|
||||
}
|
||||
|
||||
// ── 状态卡:手动加载 + 10s 自动刷新(页面存续期间) ──
|
||||
const status = ref<Api.UserSync.Status | null>(null)
|
||||
const statusLoading = ref(false)
|
||||
const statusError = ref<Error | null>(null)
|
||||
|
||||
async function refreshStatus(): Promise<void> {
|
||||
statusLoading.value = true
|
||||
statusError.value = null
|
||||
try {
|
||||
status.value = await fetchUserSyncStatus()
|
||||
} catch (e) {
|
||||
statusError.value = e as Error
|
||||
} finally {
|
||||
statusLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const autoRefresh = createAutoRefresh(() => refreshStatus(), 10_000)
|
||||
|
||||
// ── 手动补拉:202 受理 → 轮询至离开 running → 刷新状态与历史 ──
|
||||
const triggering = ref(false)
|
||||
|
||||
async function triggerSync(): Promise<void> {
|
||||
triggering.value = true
|
||||
try {
|
||||
await fetchTriggerUserSyncRun()
|
||||
ElMessage.info(t('userSync.status.triggerAccepted'))
|
||||
const final = await waitSyncTerminal(fetchUserSyncStatus, { intervalMs: 1500 })
|
||||
ElMessage.success(
|
||||
final.state === 'failed'
|
||||
? t('userSync.status.runFailed')
|
||||
: t('userSync.status.runFinished', { state: t(`userSync.state.${final.state}`) })
|
||||
)
|
||||
status.value = final
|
||||
await loadFirstRuns()
|
||||
} catch {
|
||||
// 受理/轮询失败已由 http 层弹出(waitSyncTerminal 超时为 Error('timeout')
|
||||
// ——此处补一条本地化提示)
|
||||
ElMessage.error(t('userSync.status.waitFailed'))
|
||||
} finally {
|
||||
triggering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── 运行历史(游标累积 + 加载更多) ──
|
||||
const {
|
||||
items: runs,
|
||||
hasMore: runsHasMore,
|
||||
loading: runsLoading,
|
||||
error: runsError,
|
||||
loadFirst: loadFirstRuns,
|
||||
loadMore: loadMoreRuns
|
||||
} = useCursorList<Api.UserSync.RunItem>(
|
||||
(cursor?: string) => fetchUserSyncRuns({ cursor, limit: PAGE_SIZE }),
|
||||
(item) => item.id
|
||||
)
|
||||
|
||||
// ── 失败明细抽屉 ──
|
||||
const errors = useSyncErrors()
|
||||
|
||||
function onRunClick(row: Api.UserSync.RunItem): void {
|
||||
void errors.open(row.id)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void refreshStatus()
|
||||
void loadFirstRuns()
|
||||
autoRefresh.start()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
autoRefresh.stop()
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,135 @@
|
||||
<!-- 重置密码对话框:生成随机(默认)或指定新密码 → 提交后一次性展示结果密码
|
||||
(复制转交;关闭即焚——契约 newPassword 仅响应返回一次)。 -->
|
||||
<template>
|
||||
<ElDialog
|
||||
v-model="visible"
|
||||
:title="$t('usersManage.reset.title', { account: user?.account ?? '' })"
|
||||
width="520px"
|
||||
destroy-on-close
|
||||
data-test="user-reset-dialog"
|
||||
@closed="flow.dismiss()"
|
||||
>
|
||||
<!-- 步骤一:选择方式(生成 / 指定) -->
|
||||
<template v-if="flow.step.value === 'form'">
|
||||
<ElAlert
|
||||
type="warning"
|
||||
:closable="false"
|
||||
:title="$t('usersManage.reset.revokeHint')"
|
||||
data-test="user-reset-revoke-hint"
|
||||
/>
|
||||
<ElForm label-width="120px" class="mt-4">
|
||||
<ElFormItem :label="$t('usersManage.reset.modeLabel')">
|
||||
<ElRadioGroup v-model="mode" data-test="user-reset-mode">
|
||||
<ElRadio value="generate" data-test="user-reset-mode-generate">
|
||||
{{ $t('usersManage.reset.modeGenerate') }}
|
||||
</ElRadio>
|
||||
<ElRadio value="custom" data-test="user-reset-mode-custom">
|
||||
{{ $t('usersManage.reset.modeCustom') }}
|
||||
</ElRadio>
|
||||
</ElRadioGroup>
|
||||
</ElFormItem>
|
||||
<ElFormItem
|
||||
v-if="mode === 'custom'"
|
||||
:label="$t('usersManage.reset.customLabel')"
|
||||
:error="fieldError"
|
||||
>
|
||||
<ElInput
|
||||
v-model="customPassword"
|
||||
type="password"
|
||||
show-password
|
||||
:placeholder="$t('usersManage.reset.customPlaceholder')"
|
||||
data-test="user-reset-custom-input"
|
||||
/>
|
||||
</ElFormItem>
|
||||
</ElForm>
|
||||
</template>
|
||||
|
||||
<!-- 步骤二:结果(一次性展示 + 复制) -->
|
||||
<template v-else>
|
||||
<ElAlert
|
||||
type="warning"
|
||||
:closable="false"
|
||||
:title="$t('usersManage.reset.onceWarning')"
|
||||
data-test="user-reset-once-warning"
|
||||
/>
|
||||
<div class="flex items-center gap-2 mt-4" data-test="user-reset-result">
|
||||
<code
|
||||
class="bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded text-base font-mono break-all"
|
||||
data-test="user-reset-password"
|
||||
>
|
||||
{{ flow.password.value }}
|
||||
</code>
|
||||
<ElButton type="primary" data-test="user-reset-copy" @click="copyPassword">
|
||||
{{ $t('usersManage.reset.copy') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<template v-if="flow.step.value === 'form'">
|
||||
<ElButton data-test="user-reset-cancel" @click="visible = false">
|
||||
{{ $t('common.cancel') }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
type="primary"
|
||||
:loading="flow.submitting.value"
|
||||
data-test="user-reset-submit"
|
||||
@click="submit"
|
||||
>
|
||||
{{ $t('usersManage.reset.submit') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
<ElButton v-else type="primary" data-test="user-reset-close" @click="visible = false">
|
||||
{{ $t('usersManage.reset.handedOver') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useResetPassword } from './composables/useResetPassword'
|
||||
import type { ResetPasswordMode } from '@/utils/system/userAdmin'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 重置目标(null 时对话框不应打开) */
|
||||
user: Api.AdminUser.Item | null
|
||||
}>()
|
||||
|
||||
const visible = defineModel<boolean>({ default: false })
|
||||
const { t } = useI18n()
|
||||
|
||||
const flow = useResetPassword()
|
||||
const mode = ref<ResetPasswordMode>('generate')
|
||||
const customPassword = ref('')
|
||||
const fieldError = ref('')
|
||||
|
||||
// 关闭即焚由 @closed → dismiss() 负责;打开时重置方式选择
|
||||
watch(visible, (open) => {
|
||||
if (open) {
|
||||
mode.value = 'generate'
|
||||
customPassword.value = ''
|
||||
fieldError.value = ''
|
||||
}
|
||||
})
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
if (!props.user) return
|
||||
fieldError.value = ''
|
||||
const ok = await flow.submit(props.user.id, mode.value, customPassword.value)
|
||||
if (!ok) {
|
||||
// 指定密码为空/越界(契约 8..128)——表单内联提示,不发请求
|
||||
fieldError.value =
|
||||
customPassword.value.trim() === ''
|
||||
? t('usersManage.reset.errors.required')
|
||||
: t('usersManage.reset.errors.length')
|
||||
}
|
||||
}
|
||||
|
||||
async function copyPassword(): Promise<void> {
|
||||
await navigator.clipboard.writeText(flow.password.value)
|
||||
ElMessage.success(t('usersManage.reset.copied'))
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,129 @@
|
||||
<!-- 编辑用户治理属性对话框:role/localLocked/displayName(sourceStatus 只读展示)。
|
||||
自我保护:自身行禁用角色与锁定编辑(服务端 400 双保险——http 层已本地化)。 -->
|
||||
<template>
|
||||
<ElDialog
|
||||
v-model="visible"
|
||||
:title="$t('usersManage.edit.title', { account: user?.account ?? '' })"
|
||||
width="520px"
|
||||
destroy-on-close
|
||||
data-test="user-edit-dialog"
|
||||
>
|
||||
<ElForm :model="form" label-width="120px">
|
||||
<ElFormItem :label="$t('usersManage.list.colAccount')">
|
||||
<span class="text-gray-500">{{ user?.account }}</span>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="$t('usersManage.list.colRole')">
|
||||
<ElSelect
|
||||
v-model="form.role"
|
||||
:disabled="isSelf"
|
||||
style="width: 200px"
|
||||
data-test="user-edit-role"
|
||||
>
|
||||
<ElOption value="staff" :label="$t('usersManage.role.staff')" />
|
||||
<ElOption value="admin" :label="$t('usersManage.role.admin')" />
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="$t('usersManage.list.colDisplayName')" :error="fieldErrors.displayName">
|
||||
<ElInput
|
||||
v-model="form.displayName"
|
||||
:placeholder="$t('usersManage.edit.displayNamePlaceholder')"
|
||||
data-test="user-edit-name"
|
||||
/>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="$t('usersManage.list.colLocalLocked')">
|
||||
<div class="flex flex-col gap-1">
|
||||
<ElSwitch v-model="form.localLocked" :disabled="isSelf" data-test="user-edit-locked" />
|
||||
<span class="text-gray-400 text-xs">{{ $t('usersManage.edit.lockedHint') }}</span>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
</ElForm>
|
||||
|
||||
<ElAlert
|
||||
v-if="isSelf"
|
||||
type="info"
|
||||
:closable="false"
|
||||
:title="$t('usersManage.edit.selfGuardHint')"
|
||||
data-test="user-edit-self-hint"
|
||||
/>
|
||||
|
||||
<template #footer>
|
||||
<ElButton data-test="user-edit-cancel" @click="visible = false">
|
||||
{{ $t('common.cancel') }}
|
||||
</ElButton>
|
||||
<ElButton type="primary" :loading="submitting" data-test="user-edit-submit" @click="submit">
|
||||
{{ $t('usersManage.edit.submit') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { fetchUpdateAdminUser } from '@/api/adminUsers'
|
||||
import { buildUserUpdatePayload } from '@/utils/system/userAdmin'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 编辑目标(null 时对话框不应打开) */
|
||||
user: Api.AdminUser.Item | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void
|
||||
(e: 'saved', user: Api.AdminUser.Item): void
|
||||
}>()
|
||||
|
||||
const visible = defineModel<boolean>({ default: false })
|
||||
const { t } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const form = reactive({
|
||||
role: 'staff' as Api.AdminUser.Role,
|
||||
displayName: '',
|
||||
localLocked: false
|
||||
})
|
||||
const fieldErrors = reactive({ displayName: '' })
|
||||
const submitting = ref(false)
|
||||
|
||||
/** 自身行:角色/锁定禁改(服务端同口径 400;displayName 自改放行) */
|
||||
const isSelf = computed(
|
||||
() => props.user !== null && props.user.account === (userStore.info?.userName ?? '')
|
||||
)
|
||||
|
||||
watch(visible, (open) => {
|
||||
if (!open || !props.user) return
|
||||
form.role = props.user.role
|
||||
form.displayName = props.user.displayName
|
||||
form.localLocked = props.user.localLocked
|
||||
fieldErrors.displayName = ''
|
||||
})
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
if (!props.user) return
|
||||
fieldErrors.displayName = ''
|
||||
const payload = buildUserUpdatePayload(props.user, {
|
||||
role: form.role,
|
||||
displayName: form.displayName,
|
||||
localLocked: form.localLocked
|
||||
})
|
||||
if (Object.keys(payload).length === 0) {
|
||||
// 无变更:不制造服务端 no-op(幂等返回也不落审计,前端直接收口)
|
||||
ElMessage.info(t('usersManage.edit.noChanges'))
|
||||
visible.value = false
|
||||
return
|
||||
}
|
||||
submitting.value = true
|
||||
try {
|
||||
const updated = await fetchUpdateAdminUser(props.user.id, payload)
|
||||
ElMessage.success(t('usersManage.edit.success'))
|
||||
emit('saved', updated)
|
||||
visible.value = false
|
||||
} catch {
|
||||
// 错误已由 http 层统一弹出(ElMessage),此处仅吸收避免未处理拒绝
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { useResetPassword } from './useResetPassword'
|
||||
|
||||
describe('useResetPassword 生成密码一次性展示', () => {
|
||||
it('generate 提交成功 → step=result,password 为服务端返回值', async () => {
|
||||
const reset = vi.fn().mockResolvedValue({ newPassword: 'Gen-Random-Pass' })
|
||||
const flow = useResetPassword({ reset })
|
||||
const ok = await flow.submit('u1', 'generate', '')
|
||||
expect(ok).toBe(true)
|
||||
expect(reset).toHaveBeenCalledWith('u1', {})
|
||||
expect(flow.step.value).toBe('result')
|
||||
expect(flow.password.value).toBe('Gen-Random-Pass')
|
||||
})
|
||||
|
||||
it('dismiss 即焚:回到 form 且 password 清空(关闭后不再可见)', async () => {
|
||||
const reset = vi.fn().mockResolvedValue({ newPassword: 'Once-Only-Pass' })
|
||||
const flow = useResetPassword({ reset })
|
||||
await flow.submit('u1', 'generate', '')
|
||||
flow.dismiss()
|
||||
expect(flow.step.value).toBe('form')
|
||||
expect(flow.password.value).toBe('')
|
||||
})
|
||||
|
||||
it('custom 非法(空/长度越界)→ false 且停留 form,不发请求', async () => {
|
||||
const reset = vi.fn()
|
||||
const flow = useResetPassword({ reset })
|
||||
expect(await flow.submit('u1', 'custom', ' ')).toBe(false)
|
||||
expect(await flow.submit('u1', 'custom', 'short')).toBe(false)
|
||||
expect(flow.step.value).toBe('form')
|
||||
expect(reset).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('custom 合法 → 载荷携带 newPassword(trim 后)', async () => {
|
||||
const reset = vi.fn().mockResolvedValue({ newPassword: 'hand-made-pass' })
|
||||
const flow = useResetPassword({ reset })
|
||||
const ok = await flow.submit('u1', 'custom', ' hand-made-pass ')
|
||||
expect(ok).toBe(true)
|
||||
expect(reset).toHaveBeenCalledWith('u1', { newPassword: 'hand-made-pass' })
|
||||
expect(flow.password.value).toBe('hand-made-pass')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 重置密码流程状态机(逻辑层抽离,vitest 覆盖「生成密码仅展示一次」语义)
|
||||
*
|
||||
* step: form(选择 指定/生成)→ result(一次性展示 newPassword)
|
||||
* dismiss 后 password 立即清空(组件 destroy-on-close 兜底,双保险):
|
||||
* 契约 newPassword 仅响应返回一次,页面不留存、不复查。
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
import { fetchResetAdminUserPassword } from '@/api/adminUsers'
|
||||
import { buildResetPasswordPayload, type ResetPasswordMode } from '@/utils/system/userAdmin'
|
||||
|
||||
export interface ResetPasswordApi {
|
||||
reset: (
|
||||
userId: string,
|
||||
payload: Api.AdminUser.ResetPasswordPayload
|
||||
) => Promise<Api.AdminUser.ResetPasswordResponse>
|
||||
}
|
||||
|
||||
/** 校验错误文案键由调用方渲染(返回 false 时表单停留 form 步骤) */
|
||||
export function useResetPassword(api: ResetPasswordApi = { reset: fetchResetAdminUserPassword }) {
|
||||
const step = ref<'form' | 'result'>('form')
|
||||
/** 一次性展示的新密码(仅 result 步骤非空;dismiss 即焚) */
|
||||
const password = ref('')
|
||||
const submitting = ref(false)
|
||||
|
||||
async function submit(
|
||||
userId: string,
|
||||
mode: ResetPasswordMode,
|
||||
customPassword: string
|
||||
): Promise<boolean> {
|
||||
const built = buildResetPasswordPayload(mode, customPassword)
|
||||
if (!built.ok) return false
|
||||
submitting.value = true
|
||||
try {
|
||||
const res = await api.reset(userId, built.payload)
|
||||
password.value = res.newPassword
|
||||
step.value = 'result'
|
||||
return true
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 关闭结果(或表单):密码即刻清空,回到初始态 */
|
||||
function dismiss(): void {
|
||||
step.value = 'form'
|
||||
password.value = ''
|
||||
}
|
||||
|
||||
return { step, password, submitting, submit, dismiss }
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
<!-- 账号管理页(P4a Task 8):过滤(前缀+治理状态)+ 游标累积列表 + 行内治理
|
||||
操作(编辑/重置密码/激活/停用/解锁)。自我保护双保险:UI 对自身行禁用
|
||||
角色/锁定编辑,服务端 400 仍会经 http 层本地化弹出。 -->
|
||||
<template>
|
||||
<div class="p-5">
|
||||
<ElCard data-test="users-card">
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>{{ $t('usersManage.list.title') }}</span>
|
||||
<!-- 过滤栏:前缀查询(account/displayName)+ 治理状态单选 -->
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<ElInput
|
||||
v-model="filters.query"
|
||||
clearable
|
||||
:placeholder="$t('usersManage.filter.queryPlaceholder')"
|
||||
style="width: 220px"
|
||||
data-test="users-query-input"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<ElSelect v-model="filters.status" style="width: 160px" data-test="users-status-select">
|
||||
<ElOption
|
||||
v-for="opt in statusOptions"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
:label="opt.label"
|
||||
:data-test="`users-status-option-${opt.value || 'all'}`"
|
||||
/>
|
||||
</ElSelect>
|
||||
<ElButton type="primary" data-test="users-search-btn" @click="search">
|
||||
{{ $t('usersManage.filter.search') }}
|
||||
</ElButton>
|
||||
<ElButton data-test="users-reset-btn" @click="resetFilters">
|
||||
{{ $t('usersManage.filter.reset') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<ElAlert
|
||||
v-if="error && !items.length"
|
||||
type="error"
|
||||
:closable="false"
|
||||
data-test="users-list-error"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span>{{ $t('usersManage.list.loadFailed') }}:{{ error.message }}</span>
|
||||
<ElButton size="small" data-test="users-list-retry" @click="loadFirst()">
|
||||
{{ $t('usersManage.list.retry') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElAlert>
|
||||
|
||||
<ElTable v-else v-loading="loading" :data="items" data-test="users-table">
|
||||
<ElTableColumn :label="$t('usersManage.list.colAccount')" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium" data-test="user-account">{{ row.account }}</span>
|
||||
<ElTag v-if="isSelf(row)" size="small" type="primary">
|
||||
{{ $t('usersManage.list.selfTag') }}
|
||||
</ElTag>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
:label="$t('usersManage.list.colDisplayName')"
|
||||
min-width="140"
|
||||
prop="displayName"
|
||||
/>
|
||||
<ElTableColumn :label="$t('usersManage.list.colRole')" width="100">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="row.role === 'admin' ? 'warning' : 'info'" data-test="user-role-tag">
|
||||
{{ $t(`usersManage.role.${row.role}`) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('usersManage.list.colSourceStatus')" width="110">
|
||||
<template #default="{ row }">
|
||||
<ElTag
|
||||
:type="sourceTagOf(row.sourceStatus)"
|
||||
:effect="row.sourceStatus === 'local' ? 'plain' : 'light'"
|
||||
>
|
||||
{{ $t(`usersManage.source.${row.sourceStatus}`) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('usersManage.list.colCredentialStatus')" width="110">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="row.credentialStatus === 'pending' ? 'warning' : 'success'">
|
||||
{{ $t(`usersManage.credential.${row.credentialStatus}`) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('usersManage.list.colLocalLocked')" width="100">
|
||||
<template #default="{ row }">
|
||||
<ElTag
|
||||
:type="row.localLocked ? 'danger' : 'info'"
|
||||
:effect="row.localLocked ? 'light' : 'plain'"
|
||||
>
|
||||
{{
|
||||
row.localLocked ? $t('usersManage.list.locked') : $t('usersManage.list.unlocked')
|
||||
}}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('usersManage.list.colCreatedAt')" width="160">
|
||||
<template #default="{ row }">
|
||||
<span>{{ formatDateTime(row.createdAt) }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="$t('usersManage.list.colActions')" width="280" fixed="right">
|
||||
<template #default="{ row, $index }">
|
||||
<ElButton link type="primary" data-test="user-edit-btn" @click="openEdit(row)">
|
||||
{{ $t('usersManage.list.actionEdit') }}
|
||||
</ElButton>
|
||||
<ElButton link type="primary" data-test="user-reset-btn" @click="openReset(row)">
|
||||
{{ $t('usersManage.list.actionResetPassword') }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
v-if="row.credentialStatus === 'pending'"
|
||||
link
|
||||
type="success"
|
||||
data-test="user-activate-btn"
|
||||
@click="confirmActivate(row, $index)"
|
||||
>
|
||||
{{ $t('usersManage.list.actionActivate') }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
v-if="row.localLocked"
|
||||
link
|
||||
type="success"
|
||||
data-test="user-unlock-btn"
|
||||
@click="confirmUnlock(row, $index)"
|
||||
>
|
||||
{{ $t('usersManage.list.actionUnlock') }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
v-else
|
||||
link
|
||||
type="danger"
|
||||
:disabled="isSelf(row)"
|
||||
data-test="user-deactivate-btn"
|
||||
@click="confirmDeactivate(row, $index)"
|
||||
>
|
||||
{{ $t('usersManage.list.actionDeactivate') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
|
||||
<template #empty>
|
||||
<ElEmpty v-if="!loading" :description="$t('usersManage.list.empty')" />
|
||||
</template>
|
||||
</ElTable>
|
||||
|
||||
<div v-if="items.length" class="mt-4 text-center">
|
||||
<ElButton v-if="hasMore" :loading="loading" data-test="users-load-more" @click="loadMore()">
|
||||
{{ $t('usersManage.list.loadMore') }}
|
||||
</ElButton>
|
||||
<span v-else class="text-gray-400 text-sm">{{ $t('usersManage.list.noMore') }}</span>
|
||||
</div>
|
||||
</ElCard>
|
||||
|
||||
<UserEditDialog v-model="editVisible" :user="editingUser" @saved="onSaved" />
|
||||
<ResetPasswordDialog v-model="resetVisible" :user="resettingUser" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import UserEditDialog from './UserEditDialog.vue'
|
||||
import ResetPasswordDialog from './ResetPasswordDialog.vue'
|
||||
import {
|
||||
fetchActivateAdminUser,
|
||||
fetchDeactivateAdminUser,
|
||||
fetchUpdateAdminUser,
|
||||
fetchAdminUsers
|
||||
} from '@/api/adminUsers'
|
||||
import { useCursorList } from '@/views/albums/composables/useCursorList'
|
||||
import { formatDateTime } from '@/utils/albums/format'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
|
||||
defineOptions({ name: 'SystemUsers' })
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
const { t } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
|
||||
// ── 过滤(查询即整页重载:游标键集依赖过滤条件稳定) ──
|
||||
const filters = reactive({ query: '', status: '' })
|
||||
/** 过滤选项(computed:语言切换时标签随 i18n 响应式刷新) */
|
||||
const statusOptions = computed(() => [
|
||||
{ value: '', label: t('usersManage.filter.statusAll') },
|
||||
{ value: 'active', label: t('usersManage.bucket.active') },
|
||||
{ value: 'pending', label: t('usersManage.bucket.pending') },
|
||||
{ value: 'disabled', label: t('usersManage.bucket.disabled') },
|
||||
{ value: 'locked', label: t('usersManage.bucket.locked') }
|
||||
])
|
||||
|
||||
const { items, hasMore, loading, error, loadFirst, loadMore, replaceItem } =
|
||||
useCursorList<Api.AdminUser.Item>(
|
||||
(cursor?: string) =>
|
||||
fetchAdminUsers({
|
||||
query: filters.query.trim() || undefined,
|
||||
status: (filters.status || undefined) as Api.AdminUser.StatusFilter | undefined,
|
||||
cursor,
|
||||
limit: PAGE_SIZE
|
||||
}),
|
||||
(item) => item.id
|
||||
)
|
||||
|
||||
function search(): void {
|
||||
loadFirst()
|
||||
}
|
||||
|
||||
function resetFilters(): void {
|
||||
filters.query = ''
|
||||
filters.status = ''
|
||||
loadFirst()
|
||||
}
|
||||
|
||||
/** 自身行判定:本地会话只存账号(无 /users/me 端点),按 account 对齐 */
|
||||
function isSelf(row: Api.AdminUser.Item): boolean {
|
||||
return row.account === (userStore.info?.userName ?? '')
|
||||
}
|
||||
|
||||
const SOURCE_TAG_TYPE: Record<Api.AdminUser.SourceStatus, 'success' | 'danger' | 'info'> = {
|
||||
local: 'info',
|
||||
active: 'success',
|
||||
disabled: 'danger'
|
||||
}
|
||||
|
||||
/** 模板取值桥(ElTable 行槽位为 any,模板表达式不可写 as 断言) */
|
||||
function sourceTagOf(sourceStatus: Api.AdminUser.SourceStatus): 'success' | 'danger' | 'info' {
|
||||
return SOURCE_TAG_TYPE[sourceStatus]
|
||||
}
|
||||
|
||||
// ── 编辑 ──
|
||||
const editVisible = ref(false)
|
||||
const editingUser = ref<Api.AdminUser.Item | null>(null)
|
||||
|
||||
function openEdit(row: Api.AdminUser.Item): void {
|
||||
editingUser.value = row
|
||||
editVisible.value = true
|
||||
}
|
||||
|
||||
function onSaved(updated: Api.AdminUser.Item): void {
|
||||
const index = items.value.findIndex((item) => item.id === updated.id)
|
||||
if (index >= 0) replaceItem(index, updated)
|
||||
}
|
||||
|
||||
// ── 重置密码 ──
|
||||
const resetVisible = ref(false)
|
||||
const resettingUser = ref<Api.AdminUser.Item | null>(null)
|
||||
|
||||
function openReset(row: Api.AdminUser.Item): void {
|
||||
resettingUser.value = row
|
||||
resetVisible.value = true
|
||||
}
|
||||
|
||||
// ── 激活 / 停用 / 解锁(确认框 → 调用 → 行内回显) ──
|
||||
async function confirmActivate(row: Api.AdminUser.Item, index: number): Promise<void> {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
t('usersManage.confirm.activateBody', { account: row.account }),
|
||||
t('usersManage.list.actionActivate'),
|
||||
{
|
||||
type: 'info',
|
||||
confirmButtonText: t('common.confirm'),
|
||||
cancelButtonText: t('common.cancel')
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const updated = await fetchActivateAdminUser(row.id)
|
||||
replaceItem(index, updated)
|
||||
// §10 语义:激活不出凭据,初始密码经重置密码出具(闭环提示)
|
||||
ElMessage.success(t('usersManage.toast.activated'))
|
||||
}
|
||||
|
||||
async function confirmDeactivate(row: Api.AdminUser.Item, index: number): Promise<void> {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
t('usersManage.confirm.deactivateBody', { account: row.account }),
|
||||
t('usersManage.list.actionDeactivate'),
|
||||
{
|
||||
type: 'warning',
|
||||
confirmButtonText: t('common.confirm'),
|
||||
cancelButtonText: t('common.cancel')
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const updated = await fetchDeactivateAdminUser(row.id)
|
||||
replaceItem(index, updated)
|
||||
ElMessage.success(t('usersManage.toast.deactivated'))
|
||||
}
|
||||
|
||||
async function confirmUnlock(row: Api.AdminUser.Item, index: number): Promise<void> {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
t('usersManage.confirm.unlockBody', { account: row.account }),
|
||||
t('usersManage.list.actionUnlock'),
|
||||
{
|
||||
type: 'info',
|
||||
confirmButtonText: t('common.confirm'),
|
||||
cancelButtonText: t('common.cancel')
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const updated = await fetchUpdateAdminUser(row.id, { localLocked: false })
|
||||
replaceItem(index, updated)
|
||||
ElMessage.success(t('usersManage.toast.unlocked'))
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadFirst()
|
||||
})
|
||||
</script>
|
||||
Reference in New Issue
Block a user