feat(账号到期+公司超管): 级联过期判定、过期停任务巡检与两端续费提醒弹窗

需求两条:站点超管可开设其他公司的超级管理员(站点超管看全站、公司超管只看本公司、
组内管理员仍只看本组);账号要有过期时间,管理员过期后名下普通账户一并停用、
正在跑的任务也要停掉。落库只有 users.expires_at(V146,NULL=永不过期),级联一律现算,
不写"上级过期就把下级置成过期"那种续费也救不回来的数据。

- AccountExpiryService:生效到期 = min(自身, 本公司公司超管, 成员表组长, 创建人)。
  登录拦 403(文案给续费提示)、每次请求鉴权拦 401(前端按下线踢回登录页),super_admin
  永不适用。级联口径与数据可见范围同源(成员表基本未用、实际按 created_by_id 派生)。
- ExpiredAccountTaskStopService:每分钟把过期账号(含级联成员)名下 biz_file_task
  PENDING/SCHEDULED/RUNNING → FAILED,含未领取的 PENDING(防内部通道继续派发)。原因文案
  刻意不以「客户端异常中断」开头,否则会被 TaskResumeService 自动复活。品牌采集与跟价循环
  不在那张表上,经 ExpiredAccountTaskStopSpi 由各自模块停:品牌 pending/running→cancelled
  且 UPDATE 的 WHERE 二次核对状态(抢到行后被客户端推进成完成的行不得误杀),跟价循环只置
  stop_requested=1、沿用用户点「停止循环」那条收尾路径,绝不动 status。任务心跳接口保持匿名
  不走 requireUser,所以过期账号的客户端仍能拿到 alive=false 协作停止。
- 角色 company_super_admin:由站点超管开设(唯一要显式选公司的建号场景),建号/授菜单/改用户/
  看数据四条链路都按"本公司"收口;公司超管之间、以及公司超管与站点超管互相碰不得。
- 续费提醒:剩余 <5 天在数富后台与用户端弹窗,只能收起不能关闭(无关闭按钮,收起态是右下角
  浮标),续费到 ≥5 天自动消失。后台读 /api/admin/current-user 的 expiresAt/daysToExpire;
  用户端无 Pinia,走 localStorage 的 account_expires_at(登录/check_login 落键、被顶下线清键,
  换账号不残留)。只反映账号自身到期,弹窗不做任何级联推断。
- V146 撞掉了 V145 那批的一条护栏:它按"db/ 里不许出现 V146__ 前缀"编死号位,被一条正常的
  前向迁移占用就红。改成钉动作——剥注释后的可执行 SQL 不得写 flyway_schema_history(回滚
  一律是扫描路径外的人工补丁),并把盘点文档改 V146 时丢掉的 V145 文件名补回去。

验证(本会话亲跑,不是转述):后端定向 14 类 123/0(同一轮 mvn 里连批次③的 4 类 53 例、以及既有 ShopDataCrawl/SimilarAsin 两条回归对照 21 例一起跑,合计 197 例 0 红);admin-frontend-vue 本批定向 44/0(弹窗 7 +
公司建号/列表/入口/日期默认 21 + 角色 task-48/task-251 16),全量 1726 例里那 1 支红是另一条
会话刻意留的「公司 tab 接线缺口」尺子(点名 admin_task_center 等 6 页,与本批无关);
frontend-vue 弹窗 9/0、全量 710/0。变异自证两批共 34 点:弹窗语义 16 点全杀(阈值 5、只能收起
不能关闭、挂载点含"注释掉挂载"、落键/清键链路),本批 SPI+迁移护栏 17 点全杀(含 G2 反向:
前向迁移只在注释里提 flyway_schema_history 必须照样绿),注入文件还原 dirty=0、探针残留 0。
This commit is contained in:
2026-10-05 11:51:33 +08:00
parent 265f31681f
commit 95e2318c42
62 changed files with 2866 additions and 112 deletions
@@ -27,6 +27,8 @@ export function toAdminUserItem(raw: unknown): AdminUser | null {
if (updatedAt) item.updatedAt = updatedAt
const creator = text(r.creator_username)
if (creator) item.creatorUsername = creator
const expiresAt = text(r.expires_at)
if (expiresAt) item.expiresAt = expiresAt
const abbr = text(r.pinyin_abbr)
if (abbr) item.pinyinAbbr = abbr
return item
@@ -0,0 +1,164 @@
<script setup lang="ts">
/**
* 到期续费提醒(V146,2026-10-05 需求):
* 「管理员快过期的时候(仅剩 5 天不到开始)要在数富后台界面上有个弹窗去提醒,
* 只能缩小但是不能关闭,直到续费超过 5 天才消失。」
*
* - 数据源:/api/admin/current-user 的 expiresAt/daysToExpire(session store 的 user 上);
* 只反映账号自身 expires_at,不级联——续费是账号自己的事。
* - 触发:0 ≤ daysToExpire < 5(剩余不足 5 天)。刷新/重新登录后按最新值判定,
* 续费到 ≥5 天自动消失,无需手动关。
* - 只能缩小不能关闭:无关闭按钮;缩小态是右下角常驻浮标,点开即恢复。
* - 缩小状态按「用户 + 到期值」记 localStorage:续费(到期值变化)后重置为展开。
*/
import { computed, ref, watch } from 'vue'
import { useAdminSessionStore } from '@/stores/admin-session'
const props = defineProps<{
/** 展示阈值(天):daysToExpire < EXPIRY_NOTICE_DAYS 时展示。需求口径 = 5(不足 5 天)。 */
threshold?: number
}>()
const THRESHOLD = props.threshold ?? 5
const session = useAdminSessionStore()
const user = computed(() => session.user)
const daysToExpire = computed<number | null>(() => {
const value = user.value?.daysToExpire
return typeof value === 'number' && Number.isFinite(value) ? value : null
})
const visible = computed(() => daysToExpire.value !== null && daysToExpire.value < THRESHOLD)
const expiresAt = computed(() => (user.value?.expiresAt || '').trim())
const minimized = ref(false)
const minimizedKey = computed(() =>
user.value ? `admin-expiry-notice-min:${user.value.id}:${expiresAt.value}` : '',
)
watch(
minimizedKey,
(key) => {
minimized.value = key ? localStorage.getItem(key) === '1' : false
},
{ immediate: true },
)
function minimize(): void {
minimized.value = true
if (minimizedKey.value) {
try {
localStorage.setItem(minimizedKey.value, '1')
} catch {
/* localStorage 不可用时仅本次会话生效 */
}
}
}
function restore(): void {
minimized.value = false
if (minimizedKey.value) {
try {
localStorage.removeItem(minimizedKey.value)
} catch {
/* 同上 */
}
}
}
const daysText = computed(() => {
const days = daysToExpire.value
if (days === null) return ''
return days <= 0 ? '不足 1 天' : `还剩 ${days} 天`
})
</script>
<template>
<template v-if="visible">
<div
v-if="!minimized"
class="expiry-notice"
role="alert"
aria-live="assertive"
>
<div class="expiry-notice-body">
<strong>服务即将到期</strong>
<span>
您的账号{{ expiresAt ? `(${expiresAt})` : '' }}即将到期,{{ daysText }}。
到期后账号将无法登录,名下账号与正在执行的任务也会一并停止,请联系管理员续费。
</span>
</div>
<button
class="expiry-notice-min"
type="button"
title="收起(不可关闭,续费前会一直提醒)"
@click="minimize"
>
收起
</button>
</div>
<button
v-else
class="expiry-notice-chip"
type="button"
:title="`服务即将到期:${daysText},点击展开`"
@click="restore"
>
⏰ {{ daysText }}
</button>
</template>
</template>
<style scoped>
.expiry-notice {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 3000;
display: flex;
align-items: center;
gap: 12px;
max-width: 420px;
padding: 14px 16px;
border: 1px solid #e4b363;
border-radius: 12px;
background: #fffaf0;
color: #7a4d0b;
box-shadow: 0 12px 32px -18px rgba(122, 77, 11, 0.55);
}
.expiry-notice-body {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 13px;
line-height: 1.55;
}
.expiry-notice-body strong {
font-size: 14px;
}
.expiry-notice-min {
flex-shrink: 0;
padding: 6px 12px;
border: 1px solid #e4b363;
border-radius: 8px;
background: #ffffff;
color: #7a4d0b;
font-size: 12.5px;
cursor: pointer;
}
.expiry-notice-min:hover {
background: #fdf3dd;
}
.expiry-notice-chip {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 3000;
padding: 8px 14px;
border: 1px solid #e4b363;
border-radius: 999px;
background: #fffaf0;
color: #7a4d0b;
font-size: 13px;
cursor: pointer;
box-shadow: 0 8px 20px -12px rgba(122, 77, 11, 0.5);
}
</style>
@@ -13,6 +13,7 @@ import {
} from '@/layout/empty-state'
import GlobalErrorContainer from '@/layout/GlobalErrorContainer.vue'
import NotificationBell from '@/components/NotificationBell.vue'
import ExpiryNotice from '@/components/ExpiryNotice.vue'
import OperationGuide from '@/layout/OperationGuide.vue'
import CompanyTabs from '@/layout/CompanyTabs.vue'
import { crumbsForActiveRoute, resolveDocumentTitle, updateDocumentTitle } from '@/layout/title-breadcrumb'
@@ -127,6 +128,7 @@ async function signOut() {
<RouterView v-else />
</main>
</section>
<ExpiryNotice />
</div>
</template>
@@ -56,7 +56,7 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'],
},
admin_companies: {
text: '公司决定账号归属:新建账号自动落在操作者自己所在的公司,页面上不出现公司选项——要给别的公司建号,请用那个公司自己的管理员登录。公司只做启用/停用,不提供删除。',
text: '公司决定账号归属:新建普通账号/管理员自动落在操作者自己所在的公司,页面上不出现公司选项——要给别的公司建号,请用那个公司自己的管理员登录。唯一例外是「公司超级管理员」:由站点超管开设、需在建号弹窗中显式选择所属公司。公司只做启用/停用,不提供删除。',
steps: ['查看公司列表', '新建公司', '改名或启停'],
},
admin_dedupe_total_data: {
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { computed, reactive, ref, watch } from 'vue'
import { submitCreateUser } from './user-create-adapter'
import {
createEmptyCreateUserForm,
@@ -14,8 +14,12 @@ import UserMenuAuthTree from './UserMenuAuthTree.vue'
const props = defineProps<{
modelValue: boolean
operatorSuper?: boolean
/** 操作者角色(company_super_admin 也能建管理员/普通账号)。 */
operatorRole?: string | null
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示)。 */
adminOptions?: Array<{ id: number; username: string }>
/** 公司候选(站点超管创建公司超级管理员时必选)。 */
companyOptions?: Array<{ id: number; companyName: string }>
}>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
@@ -23,11 +27,17 @@ const form = reactive<CreateUserForm>(createEmptyCreateUserForm())
const errors = reactive<CreateUserFormErrors>({})
const busy = ref(false)
/** 角色下拉(对齐 admin.html:普通账号/管理员;超管才显示可改)。 */
const ROLE_CHOICES: Array<{ value: 'admin' | 'normal'; label: string }> = [
{ value: 'normal', label: '普通账号' },
/** 角色下拉:站点超管可选公司超管/管理员/普通账号;公司超管只可选管理员/普通账号;
* 普通管理员不显示角色选择(后端强制 normal)。 */
const ROLE_CHOICES: Array<{ value: 'company_super_admin' | 'admin' | 'normal'; label: string }> = [
{ value: 'company_super_admin', label: '公司超级管理员' },
{ value: 'admin', label: '管理员' },
{ value: 'normal', label: '普通账号' },
]
const canChooseRole = computed(() => props.operatorSuper || props.operatorRole === 'company_super_admin')
const roleChoices = computed(() =>
props.operatorSuper ? ROLE_CHOICES : ROLE_CHOICES.filter((opt) => opt.value !== 'company_super_admin'),
)
watch(
() => props.modelValue,
@@ -38,8 +48,11 @@ watch(
form.role = 'normal'
form.columnIds = []
form.createdBy = null
form.expiresAt = ''
form.companyId = null
errors.username = undefined
errors.password = undefined
errors.companyId = undefined
},
)
@@ -92,9 +105,29 @@ async function create(): Promise<void> {
@input="errors.password = undefined"
/>
</el-form-item>
<el-form-item v-if="operatorSuper" label="角色">
<el-form-item v-if="canChooseRole" label="角色">
<el-select filterable v-model="form.role" style="width: 200px">
<el-option v-for="opt in ROLE_CHOICES" :key="opt.value" :label="opt.label" :value="opt.value" />
<el-option v-for="opt in roleChoices" :key="opt.value" :label="opt.label" :value="opt.value" />
</el-select>
</el-form-item>
<el-form-item
v-if="operatorSuper && form.role === 'company_super_admin'"
label="所属公司"
:error="errors.companyId"
>
<el-select
v-model="form.companyId"
filterable
placeholder="请选择公司(必选)"
style="width: 240px"
@change="errors.companyId = undefined"
>
<el-option
v-for="company in props.companyOptions || []"
:key="company.id"
:label="company.companyName"
:value="company.id"
/>
</el-select>
</el-form-item>
<el-form-item v-if="operatorSuper && form.role === 'normal'" label="所属管理员">
@@ -107,6 +140,16 @@ async function create(): Promise<void> {
/>
</el-select>
</el-form-item>
<el-form-item label="到期时间(留空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-date-picker
v-model="form.expiresAt"
type="datetime"
placeholder="选择到期时间"
value-format="YYYY-MM-DD HH:mm:ss"
format="YYYY-MM-DD HH:mm"
style="width: 240px"
/>
</el-form-item>
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
<div class="auth-tree-box">
<UserMenuAuthTree v-model:checked="form.columnIds" />
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { computed, reactive, ref, watch } from 'vue'
import type { AdminUser } from '@/types/admin'
import { fillEditUserForm, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model'
import { submitEditUser } from './user-edit-adapter'
@@ -11,12 +11,14 @@ import UserMenuAuthTree from './UserMenuAuthTree.vue'
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean }>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'updated'): void }>()
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '' })
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '' })
const errors = reactive<EditUserFormErrors>({})
const busy = ref(false)
const loadingAuth = ref(false)
/** 授权是否已成功加载:未就绪时保存会把空 columnIds 提交为“清空授权”,必须拦住。 */
const authReady = ref(false)
/** 公司超管目标:角色单选隐藏(请求体也不带 role),只允许改密码/到期时间/菜单。 */
const targetIsCompanySuperAdmin = computed(() => (props.user?.role || '').trim().toLowerCase() === 'company_super_admin')
watch(
() => props.modelValue,
@@ -29,6 +31,7 @@ watch(
form.role = base.role
form.columnIds = []
form.originalRole = base.originalRole
form.expiresAt = base.expiresAt
errors.password = undefined
authReady.value = false
void refreshAuth()
@@ -100,12 +103,25 @@ async function save(): Promise<void> {
@input="errors.password = undefined"
/>
</el-form-item>
<el-form-item v-if="operatorSuper" label="角色">
<el-form-item v-if="operatorSuper && !targetIsCompanySuperAdmin" label="角色">
<el-radio-group v-model="form.role">
<el-radio-button value="normal">普通账号</el-radio-button>
<el-radio-button value="admin">管理员</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item v-if="targetIsCompanySuperAdmin" label="角色">
<el-input model-value="公司超级管理员" readonly />
</el-form-item>
<el-form-item label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-date-picker
v-model="form.expiresAt"
type="datetime"
placeholder="选择到期时间"
value-format="YYYY-MM-DD HH:mm:ss"
format="YYYY-MM-DD HH:mm"
style="width: 240px"
/>
</el-form-item>
<el-form-item v-if="props.user && props.user.creatorUsername" label="所属管理员">
<el-input :model-value="props.user.creatorUsername" readonly />
</el-form-item>
@@ -8,11 +8,13 @@ import type { AdminUser } from '@/types/admin'
import { roleLabel } from '@/types/admin'
import { useAdminSessionStore } from '@/stores/admin-session'
import { deleteUser, fetchUserList } from '@/api/users'
import { fetchCompanies } from '@/api/companies'
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
import { totalPageCount } from './user-pagination'
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
import { listPhaseOf, userListEmptyHint } from './user-list-state'
import { isEditableUser } from './user-edit-model'
import { editableBy } from './user-edit-model'
import { formatExpiryCell } from './user-expiry'
import CreateUserDialog from './CreateUserDialog.vue'
import EditUserDialog from './EditUserDialog.vue'
import OldPagination from '@/components/OldPagination.vue'
@@ -24,8 +26,11 @@ const rows = ref<AdminUser[]>([])
const total = ref(0)
/** 所属管理员候选(来自列表响应的 admins),供超管筛选下拉使用。 */
const admins = ref<Array<{ id: number; username: string }>>([])
/** 公司候选(仅供建号弹窗的「公司超级管理员」下拉使用,2026-10-05 唯一豁免)。 */
const companyOptions = ref<Array<{ id: number; companyName: string }>>([])
const filters = reactive<UserFilterState>(createUserFilterState())
const isSuperAdmin = computed(() => session.isSuperAdmin)
const operatorRole = computed(() => session.user?.role ?? null)
const currentUserId = computed(() => session.user?.id ?? null)
const statePhase = computed(() => listPhaseOf({ loading: loading.value, error: loadError.value, items: rows.value, total: total.value }))
const jumpPage = ref('')
@@ -40,13 +45,13 @@ function openCreate(): void {
}
function openEdit(row: AdminUser): void {
if (!isEditableUser(row.role)) return
if (!editableBy(row.role, operatorRole.value)) return
editUser.value = row
editVisible.value = true
}
function editableOf(row: AdminUser): boolean {
return isEditableUser(row.role)
return editableBy(row.role, operatorRole.value)
}
async function loadUsers() {
@@ -123,6 +128,16 @@ function goJump() {
onMounted(() => {
void loadUsers()
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底
if (isSuperAdmin.value) {
void fetchCompanies()
.then((items) => {
companyOptions.value = items.map((c) => ({ id: c.id, companyName: c.companyName }))
})
.catch(() => {
companyOptions.value = []
})
}
})
</script>
@@ -150,6 +165,7 @@ onMounted(() => {
<label>角色</label>
<el-select v-model="filters.role" class="admin-filter" filterable clearable placeholder="全部角色" @change="search">
<el-option label="超级管理员" value="super_admin" />
<el-option label="公司超级管理员" value="company_super_admin" />
<el-option label="管理员" value="admin" />
<el-option label="普通账号" value="normal" />
</el-select>
@@ -170,6 +186,7 @@ onMounted(() => {
<th style="width: 180px">用户名</th>
<th style="width: 140px">角色</th>
<th style="width: 160px">所属管理员</th>
<th style="width: 160px">到期时间</th>
<th style="width: 180px">创建时间</th>
<th style="width: 180px">更新时间</th>
<th style="width: 160px">操作</th>
@@ -182,6 +199,9 @@ onMounted(() => {
<td>{{ row.username }}</td>
<td>{{ roleLabel(row.role) }}</td>
<td>{{ row.creatorUsername || '-' }}</td>
<td :class="{ 'expiry-cell-expired': formatExpiryCell(row).expired }">
{{ formatExpiryCell(row).text }}
</td>
<td>{{ formatDateTime(row.createdAt) }}</td>
<td>{{ formatDateTime(row.updatedAt) }}</td>
<td class="ops-cell">
@@ -207,10 +227,10 @@ onMounted(() => {
</tr>
</template>
<tr v-else-if="loading">
<td colspan="7" class="empty-tip">加载中...</td>
<td colspan="8" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td colspan="7" class="empty-tip">{{ userListEmptyHint() }}</td>
<td colspan="8" class="empty-tip">{{ userListEmptyHint() }}</td>
</tr>
</tbody>
</table>
@@ -222,7 +242,9 @@ onMounted(() => {
<CreateUserDialog
v-model="createVisible"
:operator-super="isSuperAdmin"
:operator-role="operatorRole"
:admin-options="admins"
:company-options="companyOptions"
@created="loadUsers"
/>
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" @updated="loadUsers" />
@@ -415,6 +437,10 @@ h3 {
gap: 8px;
white-space: nowrap;
}
.expiry-cell-expired {
color: #c0392b;
font-weight: 600;
}
.empty-tip {
padding: 44px 24px;
@@ -3,8 +3,11 @@
export const CREATE_USERNAME_MIN_LEN = 2
export const CREATE_PASSWORD_MIN_LEN = 6
/** 新建用户可选角色:super_admin 不可由表单创建(后端只收 admin|normal)。 */
export type CreatableUserRole = 'normal' | 'admin'
/**
* 新建用户可选角色:super_admin 不可由表单创建;company_super_admin 仅站点超管可选
* (后端 403「只有超级管理员可以创建公司超级管理员」兜底)。
*/
export type CreatableUserRole = 'normal' | 'admin' | 'company_super_admin'
export interface CreateUserForm {
username: string
@@ -14,11 +17,16 @@ export interface CreateUserForm {
columnIds: number[]
/** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */
createdBy?: number | null
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期(V146)。 */
expiresAt: string
/** 所属公司 id:仅 role=company_super_admin 时由站点超管必选(2026-10-05 需求)。 */
companyId?: number | null
}
export interface CreateUserFormErrors {
username?: string
password?: string
companyId?: string
}
/** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */
@@ -29,18 +37,27 @@ export interface CreateUserPayload {
columnIds: number[]
/** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */
createdById?: number
/** 到期时间;空串=永不过期,不下发。 */
expiresAt?: string
/** 仅 role=company_super_admin 且显式选了公司时下发——这是「建号不带 company_id」
* 反向钉(company-user-create.test.ts)唯一豁免的例外:公司超管必须落指定公司,
* 否则会静默落操作者自己的公司(公司 1),用户需求就是给别家公司开超管。 */
companyId?: number
}
export function createEmptyCreateUserForm(): CreateUserForm {
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null }
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, expiresAt: '', companyId: null }
}
/** 未知/空白/超管角色一律归一到 normal,与后端 "admin"/"normal" 白名单一致。 */
/** 未知/空白/超管角色归一:admin/company_super_admin/normal 白名单,其余归 normal。 */
export function normalizeCreateRole(role: string | null | undefined): CreatableUserRole {
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
const value = (role || '').trim().toLowerCase()
if (value === 'admin') return 'admin'
if (value === 'company_super_admin') return 'company_super_admin'
return 'normal'
}
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填);返回逐字段错误。 */
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填;公司超管必须选公司);返回逐字段错误。 */
export function validateCreateUserForm(form: CreateUserForm): {
valid: boolean
errors: CreateUserFormErrors
@@ -58,6 +75,9 @@ export function validateCreateUserForm(form: CreateUserForm): {
} else if (password.length < CREATE_PASSWORD_MIN_LEN) {
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符`
}
if (normalizeCreateRole(form.role) === 'company_super_admin' && form.companyId == null) {
errors.companyId = '公司超级管理员必须指定所属公司'
}
return { valid: Object.keys(errors).length === 0, errors }
}
@@ -65,19 +85,26 @@ export function validateCreateUserForm(form: CreateUserForm): {
* 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用;
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义)。
*
* <p>故意不带 company_id:归属由后端 `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司。
* 页面上没有公司可选项(2026-10-04 定案),所以这条是"新账号归哪家公司"的唯一口径 ——
* 想给别的公司建号,得用那个公司自己的 admin 登录,不是在这里改请求体。</p>
* <p>company_id 仅在 role=company_super_admin 且显式选择时下发(见 CreateUserPayload 注释);
* 其余角色不带——归属由后端 `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司,
* 想给别的公司建普通账号,得用那个公司自己的管理员登录,不是在这里改请求体。</p>
*/
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
const role = normalizeCreateRole(form.role)
const payload: CreateUserPayload = {
username: (form.username || '').trim(),
password: form.password || '',
role: normalizeCreateRole(form.role),
role,
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
}
if (payload.role === 'normal' && form.createdBy != null) {
payload.createdById = form.createdBy
}
if (form.expiresAt && String(form.expiresAt).trim()) {
payload.expiresAt = String(form.expiresAt).trim()
}
if (role === 'company_super_admin' && form.companyId != null) {
payload.companyId = form.companyId
}
return payload
}
@@ -2,7 +2,7 @@
import type { AdminUser } from '../../types/admin'
import { CREATE_PASSWORD_MIN_LEN } from './user-create-model.ts'
/** 编辑可选角色:超管不可改,未知归 normal;后端只收 admin|normal。 */
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
export type EditUserRole = 'normal' | 'admin'
export interface EditUserForm {
@@ -16,6 +16,8 @@ export interface EditUserForm {
columnIds: number[]
/** 后端原角色字符串,用于超管禁止编辑判定。 */
originalRole: string
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期。null = 后端本来就无到期。 */
expiresAt: string
}
export interface EditUserFormErrors {
@@ -24,9 +26,12 @@ export interface EditUserFormErrors {
/** 序列化到 PUT /api/admin/user/{uid} 的请求体(Java AdminUserUpdateRequest,空密码不下发)。 */
export interface EditUserUpdateRequest {
role: EditUserRole
/** 目标是公司超管时不携带(防止表单把公司超管误降级);站点超管改其密码/到期时间即可。 */
role?: EditUserRole
columnIds: number[]
password?: string
/** 到期时间:空串=清除(恢复永不过期),有值=改期;总是下发(与后端"传了就更新"对齐)。 */
expiresAt: string
}
/** 行角色 → 可编辑角色:仅 admin 映射 admin,其余(含 unknown)归 normal。 */
@@ -34,9 +39,31 @@ export function editRoleOf(role: string | null | undefined): EditUserRole {
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
}
/** 该角色是否允许被编辑:超级管理员不可编辑(镜像后端“不能修改超级管理员”)。 */
/** 该角色是否允许被编辑:站点/公司超级管理员不可经普通编辑入口修改(镜像后端闸门)。 */
export function isEditableUser(role: string | null | undefined): boolean {
return (role || '').trim().toLowerCase() !== 'super_admin'
const value = (role || '').trim().toLowerCase()
return value !== 'super_admin' && value !== 'company_super_admin'
}
/**
* 结合操作者角色判断可编辑性(UsersPage 用):公司超管的目标只有站点超管能编辑
* (改密码/到期时间做续费),站点超管目标谁都不能编辑。
*/
export function editableBy(
targetRole: string | null | undefined,
operatorRole: string | null | undefined,
): boolean {
const target = (targetRole || '').trim().toLowerCase()
if (target === 'super_admin') return false
if (target === 'company_super_admin') return (operatorRole || '').trim().toLowerCase() === 'super_admin'
return true
}
/** 列表的 expires_at 是 yyyy-MM-dd HH:mm;日期选择器按 yyyy-MM-dd HH:mm:ss 回填,秒位补 :00。 */
export function normalizeExpiryForPicker(raw: string | null | undefined): string {
const value = (raw || '').trim()
if (!value) return ''
return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(value) ? `${value}:00` : value
}
/** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。 */
@@ -49,6 +76,7 @@ export function fillEditUserForm(user: AdminUser): EditUserForm {
role: editRoleOf(role),
columnIds: [],
originalRole: role,
expiresAt: normalizeExpiryForPicker(user.expiresAt),
}
}
@@ -62,16 +90,20 @@ export function validateEditUserForm(form: EditUserForm): { valid: boolean; erro
return { valid: Object.keys(errors).length === 0, errors }
}
/** 编辑表单 → 更新请求体:超管拒绝、空密码不下发、columnIds 拷贝不共享引用。 */
/** 编辑表单 → 更新请求体:站点超管拒绝、空密码不下发、columnIds 拷贝不共享引用。 */
export function toEditUserUpdateRequest(form: EditUserForm): EditUserUpdateRequest {
const originalRole = (form.originalRole || '').trim().toLowerCase()
if (originalRole === 'super_admin') {
throw new Error('不能修改超级管理员')
}
const role: EditUserRole = form.role === 'admin' ? 'admin' : 'normal'
const request: EditUserUpdateRequest = {
role,
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
expiresAt: (form.expiresAt || '').trim(),
}
// 公司超管目标不带 role:弹窗里的单选是给管理员/普通用户用的,带着它会整树提交把
// 公司超管静默降级。站点超管要调角色,请删号重建或走接口。
if (originalRole !== 'company_super_admin') {
request.role = form.role === 'admin' ? 'admin' : 'normal'
}
const password = form.password || ''
if (password) request.password = password
@@ -0,0 +1,19 @@
/** 用户列表「到期时间」单元格渲染(V146):永不过期 / 具体时间 / 已过期。 */
export interface ExpiryCell {
text: string
expired: boolean
}
/** 行 expiresAt 是 yyyy-MM-dd HH:mm 或空(后端空串=永不过期);解析失败按永不过期兜底。 */
export function formatExpiryCell(row: { expiresAt?: string | null }): ExpiryCell {
const raw = (row?.expiresAt || '').trim()
if (!raw) {
return { text: '永不过期', expired: false }
}
const parsed = new Date(raw.replace(' ', 'T'))
if (Number.isNaN(parsed.getTime())) {
return { text: raw, expired: false }
}
return { text: raw, expired: parsed.getTime() < Date.now() }
}
@@ -2,24 +2,26 @@
import { roleKind } from '../../types/admin.ts'
/** 后台角色域(与 AdminUserItemVo.role / is_admin 对齐)。 */
export type RoleDomain = 'super_admin' | 'admin' | 'normal'
export type RoleDomain = 'super_admin' | 'company_super_admin' | 'admin' | 'normal'
/** 用户角色下拉可选值;super_admin 只能由系统持有,不入下拉。 */
export type EditableRole = 'admin' | 'normal'
export type EditableRole = 'company_super_admin' | 'admin' | 'normal'
export interface UserRoleOption {
value: EditableRole
label: string
}
/** 编辑/创建表单角色下拉候选(镜像后端 admin|normal 白名单)。 */
/** 建/编辑表单角色下拉候选(镜像后端白名单;company_super_admin 仅站点超管可选)。 */
export const USER_ROLE_OPTIONS: readonly UserRoleOption[] = [
{ value: 'company_super_admin', label: '公司超级管理员' },
{ value: 'admin', label: '管理员' },
{ value: 'normal', label: '普通用户' },
]
const ROLE_DOMAIN_LABELS: Record<RoleDomain, string> = {
super_admin: '超级管理员',
company_super_admin: '公司超级管理员',
admin: '管理员',
normal: '普通用户',
}
@@ -27,14 +29,15 @@ const ROLE_DOMAIN_LABELS: Record<RoleDomain, string> = {
/** 行字段 → 角色域:优先 role;为空时按 is_admin 布尔推断(1=管理员);未知归 normal。 */
export function roleDomainOf(row: { role?: string | null; isAdmin?: boolean }): RoleDomain {
const kind = roleKind(row?.role)
if (kind === 'super_admin' || kind === 'admin' || kind === 'normal') return kind
if (kind === 'super_admin' || kind === 'company_super_admin' || kind === 'admin' || kind === 'normal') return kind
return row?.isAdmin ? 'admin' : 'normal'
}
/** 行 → 可编辑角色值:超级管理员返回 null(不可编辑),其余返回 admin/normal。 */
/** 行 → 可编辑角色值:站点/公司超管不可在此编辑角色(返回 null),其余返回对应值。 */
export function selectRoleOf(row: { role?: string | null; isAdmin?: boolean }): EditableRole | null {
const domain = roleDomainOf(row)
return domain === 'super_admin' ? null : domain
if (domain === 'super_admin' || domain === 'company_super_admin') return null
return domain
}
/** 角色域展示文案。 */
@@ -43,14 +46,16 @@ export function roleDomainLabel(domain: RoleDomain): string {
}
/**
* 角色下拉锁定原因:目标为超管、或操作者非超管(镜像后端:admin 编辑时强制不调角色、
* super_admin 不可改)。无锁定时返回 undefined。
* 角色下拉锁定原因:目标为站点/公司超管、或操作者非站点超管(镜像后端:admin/公司超管
* 编辑时角色不可调、super_admin 与同公司公司超管不可改)。无锁定时返回 undefined。
*/
export function userRoleLockMessage(
operatorRole: string | null | undefined,
target: { role?: string | null; isAdmin?: boolean },
): string | undefined {
if (roleDomainOf(target) === 'super_admin') return '不能修改超级管理员'
const targetDomain = roleDomainOf(target)
if (targetDomain === 'super_admin') return '不能修改超级管理员'
if (targetDomain === 'company_super_admin') return '只有超级管理员可以修改公司超级管理员'
if (roleKind(operatorRole) !== 'super_admin') return '仅超级管理员可调整角色'
return undefined
}
+16 -4
View File
@@ -1,7 +1,7 @@
/** 后台前端类型契约(任务 21):与 Java Admin 接口返回字段对齐。 */
/** 管理角色域(与后端 current-user / users 返回一致)。 */
export type AdminRole = 'super_admin' | 'admin' | 'normal'
export type AdminRole = 'super_admin' | 'company_super_admin' | 'admin' | 'normal'
export interface AdminUser {
id: number
@@ -13,6 +13,10 @@ export interface AdminUser {
creatorUsername?: string
createdAt?: string
updatedAt?: string
/** 到期时间(yyyy-MM-dd HH:mm);空串/缺省 = 永不过期(V146)。 */
expiresAt?: string
/** 自身到期剩余整天数(floor,来自 current-user);null/缺省 = 永不过期。续费提醒按它 <5 判定。 */
daysToExpire?: number | null
pinyinAbbr?: string
}
@@ -28,12 +32,13 @@ export interface AdminMenuNode {
icon?: string
}
export type AdminRoleKind = 'super_admin' | 'admin' | 'normal' | null
export type AdminRoleKind = 'super_admin' | 'company_super_admin' | 'admin' | 'normal' | null
/** 把任意角色字符串归一为角色域;未知/空返回 null。 */
export function roleKind(role: string | null | undefined): AdminRoleKind {
const value = (role || '').trim().toLowerCase()
if (value === 'super_admin') return 'super_admin'
if (value === 'company_super_admin') return 'company_super_admin'
if (value === 'admin') return 'admin'
if (value === 'normal') return 'normal'
return null
@@ -44,10 +49,15 @@ export function isSuperAdminRole(role: string | null | undefined): boolean {
return roleKind(role) === 'super_admin'
}
/** 是否管理员级(super_admin 或 admin,可进后台菜单管理类)。 */
/** 是否公司超级管理员(单家公司内的最高账号,数据只看本公司)。 */
export function isCompanySuperAdminRole(role: string | null | undefined): boolean {
return roleKind(role) === 'company_super_admin'
}
/** 是否管理员级(super_admin / company_super_admin / admin,可进后台菜单管理类)。 */
export function isAdminRole(role: string | null | undefined): boolean {
const kind = roleKind(role)
return kind === 'super_admin' || kind === 'admin'
return kind === 'super_admin' || kind === 'company_super_admin' || kind === 'admin'
}
/** 顶部栏角色展示文案。 */
@@ -55,6 +65,8 @@ export function roleLabel(role: string | null | undefined): string {
switch (roleKind(role)) {
case 'super_admin':
return '超级管理员'
case 'company_super_admin':
return '公司超级管理员'
case 'admin':
return '管理员'
case 'normal':
@@ -31,13 +31,16 @@ test('名单里的每个 menuKey 都在页面注册表上打了 superAdminOnly',
}
})
test('公司 API 模块的消费者集合恰好是公司管理两文件 + 公司 tab store(账号页已摘干净)', () => {
test('公司 API 模块的消费者集合是公司管理两文件 + 用户页(建公司超管选公司,2026-10-05 唯一豁免)', () => {
const found = filesWithSuffix(['.vue', '.ts'])
.filter((rel) => readSource(rel).includes("from '@/api/companies'"))
.sort()
assert.deepEqual(found, [
'src/pages/account/CompaniesPage.vue',
'src/pages/account/CompanyEditorDialog.vue',
// 2026-10-05 例外:站点超管建「公司超级管理员」必须选公司,UsersPage 因此拉公司目录。
// 该用例的姊妹钉在 company-user-create.test.ts:公司下拉被「站点超管 + 公司超管角色」双重门控。
'src/pages/account/UsersPage.vue',
// 2026-10-05 公司 tab(spec §4):store 是目录的第二个消费者,仅超管侧 visibleForOperator 会发 GET。
'src/stores/company-tab.ts',
].sort())
@@ -9,31 +9,40 @@ import {
import { OPERATION_GUIDES } from '../src/layout/operation-guides.ts'
/**
* 建号不再让用户挑公司(2026-10-04 15:4x 定案)。
* 建号公司口径(2026-10-05 修订):admin/normal 建号仍不让用户挑公司——请求体不带
* company_id 时,`resolveTargetCompanyId` 落操作者自己的公司(下面的 Java 钉子仍然有效)。
*
* <p>归属这件事改由后端单点决定:请求体不带 company_id 时,`resolveTargetCompanyId` 落操作者自己的公司。
* 所以"前端删掉下拉是安全的"这个结论完全靠那条后端分支撑着 —— 下面最后一用例把它钉成可执行断言,
* 谁把那边改成"必填公司",这边立刻红。</p>
* <p>唯一例外是<b>公司超级管理员</b>(2026-10-05 用户需求「admin 超管可以新建其他公司的
* 超级管理员」):不显式选公司就会静默落进操作者自己的公司(公司 1),所以这一例必须
* 让站点超管选公司、必选、并随请求体下发。除这一例外,公司维度仍然不回流界面。</p>
*/
function form(overrides: Record<string, unknown> = {}) {
return { ...createEmptyCreateUserForm(), username: 'zhangsan', password: 'secret123', ...overrides }
}
test('空表单里没有公司这一项', () => {
test('空表单默认没有公司、没有到期时间', () => {
const blank = createEmptyCreateUserForm()
assert.equal('companyId' in blank, false)
assert.deepEqual(blank, { username: '', password: '', role: 'normal', columnIds: [], createdBy: null })
assert.equal(blank.companyId ?? null, null, 'companyId 默认 null(仅公司超管角色使用)')
assert.equal(blank.expiresAt, '', '到期时间默认空 = 永不过期')
assert.deepEqual(
{ ...blank, companyId: null, expiresAt: '' },
{ username: '', password: '', role: 'normal', columnIds: [], createdBy: null, companyId: null, expiresAt: '' },
)
})
test('校验只看用户名与密码,不再要求选公司', () => {
test('普通账号校验只看用户名与密码;公司超管必须选公司', () => {
assert.deepEqual(validateCreateUserForm(form()), { valid: true, errors: {} })
assert.equal(validateCreateUserForm(form({ username: 'a' })).errors.username !== undefined, true)
assert.equal(validateCreateUserForm(form({ password: '123' })).errors.password !== undefined, true)
const missingCompany = validateCreateUserForm(form({ role: 'company_super_admin' }))
assert.equal(missingCompany.valid, false, '公司超级管理员必须指定所属公司')
assert.equal(missingCompany.errors.companyId !== undefined, true)
const withCompany = validateCreateUserForm(form({ role: 'company_super_admin', companyId: 2 }))
assert.equal(withCompany.valid, true)
})
// 反向钉:公司维度不得回流到界面(2026-10-04 定口径)
test('请求体不带 companyId,其余字段照旧', () => {
test('请求体:admin/normal 一律不带 companyId;公司超管必须带且选了公司才带', () => {
assert.deepEqual(toCreateUserRequest(form({ columnIds: [3, 1] })), {
username: 'zhangsan',
password: 'secret123',
@@ -44,17 +53,31 @@ test('请求体不带 companyId,其余字段照旧', () => {
assert.equal(toCreateUserRequest(form({ role: 'normal', createdBy: 5 })).createdById, 5)
assert.equal('createdById' in toCreateUserRequest(form({ role: 'admin', createdBy: 5 })), false)
assert.equal('companyId' in toCreateUserRequest(form()), false,
'不传 company_id 才会走后端"落操作者公司"那条分支')
'不传 company_id 才会走后端"落操作者公司"那条分支(admin/normal 永远如此)')
// 2026-10-05 例外:公司超级管理员
const companyAdmin = toCreateUserRequest(form({ role: 'company_super_admin', companyId: 2 }))
assert.equal(companyAdmin.companyId, 2, '公司超管必须把选中的公司带给后端,否则会静默落操作者本公司')
assert.equal(companyAdmin.role, 'company_super_admin')
assert.equal('companyId' in toCreateUserRequest(form({ role: 'company_super_admin' })), false,
'没选公司就不许带(校验层会先拦住,这里兜底不静默)')
})
// 反向钉:公司维度不得回流到界面(2026-10-04 定口径)
test('建号模型源码里公司口径已摘干净', () => {
test('到期时间:空串不下发,有值随请求体走', () => {
assert.equal('expiresAt' in toCreateUserRequest(form()), false, '留空 = 永不过期,不下发')
assert.equal(toCreateUserRequest(form({ expiresAt: '2026-12-31 23:59:59' })).expiresAt,
'2026-12-31 23:59:59')
})
test('建号模型源码:公司口径只对「公司超管」这一例放行', () => {
const mod = readSource('src/pages/account/user-create-model.ts')
assert.equal(/companyId|CompanyItem|selectableCompanies|initialCompanyId|CreateOperatorScope/.test(mod), false,
'公司相关的类型、可选项收窄函数、预选函数都应整体删除')
assert.match(mod, /company_super_admin/, '角色白名单要包含公司超管')
assert.match(mod, /role === 'company_super_admin' && form\.companyId != null/,
'companyId 只在「角色=公司超管且已选公司」时下发——这是唯一豁免,别放宽成所有角色')
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
assert.equal(/companyId|CompanyItem|所属公司|selectableCompanies/.test(dialog), false,
'弹窗不再有公司选择;操作者角色门控(operatorSuper)保留,它管的是角色与所属管理员下拉')
assert.match(dialog, /operatorSuper && form\.role === 'company_super_admin'/,
'公司下拉必须同时被「站点超管 + 公司超管角色」双重门控,普通建号不能看到公司维度')
assert.match(dialog, /公司超级管理员必须指定所属公司|请选择公司/, '公司下拉要有必选提示')
assert.match(dialog, /operatorSuper/, '角色/所属管理员仍按操作者是否超管收窄')
})
@@ -64,12 +87,14 @@ test('建号模型源码里公司口径已摘干净', () => {
* 同理"停用后不能再用于新建账号"也不成立了——requireActive 只在显式传 company_id 时才走,
* 而页面现在一律不传(接口直连的老调用方仍受它保护,那条由上一用例盯着)。
*/
test('「公司管理」引导文案说的是自动继承,不再让操作员挑公司', () => {
test('「公司管理」引导文案说的是自动继承,并写清公司超管这一例外', () => {
const guide = OPERATION_GUIDES.admin_companies.text
assert.match(guide, /操作者自己所在的公司/, '要写清归属的真实口径:落在操作者本公司')
assert.match(guide, /请用那个公司自己的管理员登录|用该公司自己的管理员登录/,
'要给别家建号只能换账号登录——不写这句,超管会以为自己建的号能归到别家')
for (const stale of ['建号时选哪家公司', '选哪家公司', '停用后不能再用于新建账号']) {
assert.match(guide, /公司超级管理员/,
'2026-10-05 起开设公司超管是唯一要在建号时选公司的例外,文案要说清,别让人以为下拉没了是坏了')
for (const stale of ['建号时选哪家公司', '停用后不能再用于新建账号']) {
assert.equal(guide.includes(stale), false, `文案仍含已失效的说法:${stale}`)
}
})
@@ -93,7 +118,7 @@ function javaMethod(source: string, signature: string): string {
return ''
}
test('后端仍然把"没传公司"落成操作者自己公司(前端删下拉的前提)', () => {
test('后端仍然把"没传公司"落成操作者自己公司(admin/normal 不带下拉的前提)', () => {
const java = readSource(
'../backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java',
)
@@ -59,12 +59,18 @@ test('顶栏不再渲染公司名', () => {
assert.equal(topbarUserOf(null).hasUser, false)
})
// 反向钉:公司维度不得回流到界面(2026-10-04 定口径)
// 反向钉:公司维度不得回流到「列表/筛选/顶栏」(2026-10-04 定口径;2026-10-05 修订——
// 唯一例外是建号弹窗里的「公司超级管理员」所属公司下拉,由 company-user-create.test.ts 单独钉住)
test('账号页与顶栏的源码里公司维度已摘干净', () => {
const page = readSource('src/pages/account/UsersPage.vue')
assert.equal(/所属公司/.test(page), false, '账号页不该再出现「所属公司」标签')
assert.equal(/companyId|companyName|companies/.test(page), false, '页面不再持有公司目录或公司筛选状态')
assert.equal(/fetchCompanies/.test(page), false, '公司目录接口不该再被账号页调用')
// 列表契约层面不许出现公司维度:查询参数 company_id、筛选状态、行级公司列。
// (companyOptions/c.companyName 是 2026-10-05 建公司超管选公司的唯一豁免,不在此列。)
assert.equal(/company_id|filters\.company|row\.company|companyId/.test(page), false,
'列表查询/筛选/行渲染不允许出现公司维度')
assert.match(page, /fetchCompanies/, '公司目录仅供建号弹窗的「公司超管」下拉使用(唯一豁免)')
assert.match(page, /isSuperAdmin[\s\S]{0,200}fetchCompanies/,
'拉公司目录必须按站点超管门控,非超管不发这个请求(后端 403 兜底)')
// 「删了列忘了改占位行 colspan」是这类改动最常留下的残行:按表头列数交叉核对
// (`<th` 是 `<thead` 的前缀,必须带上后随字符才数得准)
@@ -74,8 +80,10 @@ test('账号页与顶栏的源码里公司维度已摘干净', () => {
for (const span of spans) assert.equal(span, headers, `占位行 colspan=${span} 与表头列数 ${headers} 不符`)
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
assert.equal(/所属公司|selectableCompanies|initialCompanyId|companyId/.test(dialog), false,
'建号弹窗不该再有公司选择')
assert.match(dialog, /operatorSuper && form\.role === 'company_super_admin'/,
'建号弹窗的公司下拉只许在「站点超管 + 公司超管角色」时出现(例外口径见 company-user-create.test.ts)')
assert.equal(/selectableCompanies|initialCompanyId/.test(dialog), false,
'一次性预选/收窄的旧公司逻辑不许回流')
const layout = readSource('src/layout/AdminLayout.vue')
assert.equal(/userVm\.company|admin-user-company/.test(layout), false, '顶栏旁白只剩用户名与角色')
@@ -34,6 +34,10 @@ const EXEMPT = new Set([
'src/pages/tasks/ShopDataTasksPage.vue',
'src/pages/tasks/ImageVideoTasksPage.vue',
'src/pages/records/RecordsHistoryPage.vue',
// 2026-10-05(V146):两处是「到期时间」表单字段而非列表筛选——留空 = 永不过期,
// 是有业务语义的默认值,绝不能默认当天(默认当天等于建号即过期)。
'src/pages/account/CreateUserDialog.vue',
'src/pages/account/EditUserDialog.vue',
])
/** 把日期筛选清回空值的写法(默认当天的页里初值或重置都不许出现)。
@@ -0,0 +1,102 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { occurrences, readSource } from './helpers.ts'
/**
* 数富后台「服务即将到期」续费提醒弹窗(V146,2026-10-05 需求)的口径护栏。
*
* 需求原话:仅剩不到 5 天开始提醒、只能缩小不能关闭、续费到超过 5 天才消失。
* 这三条全靠 ExpiryNotice.vue 一个组件兑现,而组件是 SFC、node --test 编译不了,
* 所以断言打在实际源码上:阈值、渲染条件、可点的按钮、收起态记的是什么键、挂在哪。
*
* 每个正则都必须在真源码上匹配得到(先确认真命中再断言),否则就是恒绿的摆设。
*/
const COMPONENT = 'src/components/ExpiryNotice.vue'
const LAYOUT = 'src/layout/AdminLayout.vue'
const TYPES = 'src/types/admin.ts'
/** SFC 的 <template> 段:从第一个 <template> 到最后一个 </template>(内层还有 v-if 包裹)。 */
function templateOf(source: string): string {
const start = source.indexOf('<template>')
const end = source.lastIndexOf('</template>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <template> 段`)
return source.slice(start, end)
}
/** <script setup> 段。 */
function scriptOf(source: string): string {
const start = source.indexOf('<script setup')
const end = source.indexOf('</script>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <script setup> 段`)
return source.slice(start, end)
}
/** 剥掉 HTML 注释:注释掉的 `<ExpiryNotice />` 在源码里照样匹配得上,挂载点断言必须是活代码。 */
function withoutComments(source: string): string {
return source.replace(/<!--[\s\S]*?-->/g, '')
}
const source = readSource(COMPONENT)
const template = templateOf(source)
const script = scriptOf(source)
test('提醒阈值就是 5 天:THRESHOLD 取 props 兜底 5,且全文件没有第二个数字阈值', () => {
assert.match(script, /const THRESHOLD = props\.threshold \?\? 5\b/, '阈值没写成 5 的兜底')
// 排他:别处再写一个数字兜底,就等于偷偷加了第二套口径
const numericFallbacks = script.match(/\?\?\s*\d+/g) ?? []
assert.deepEqual(numericFallbacks, ['?? 5'], '数字兜底只能有阈值 5 这一个')
})
test('渲染条件是「剩余 < 5」而不是「<= 5」:整 5 天不弹,第 4 天起才弹', () => {
assert.match(
script,
/daysToExpire\.value !== null && daysToExpire\.value < THRESHOLD/,
'visible 没按「有到期值且 < 阈值」判定',
)
assert.doesNotMatch(script, /daysToExpire\.value <= THRESHOLD/, '写成了 <=,整 5 天也会弹')
})
test('没有关闭这条路:模板里只有「收起」和浮标两个可点项,没有任何对话框自带的关闭件', () => {
assert.equal(occurrences(template, '@click="'), 2, '可点项必须恰好是收起 + 浮标恢复两个')
assert.match(template, /@click="minimize"/, '收起按钮没接 minimize')
assert.match(template, /@click="restore"/, '缩小态浮标没接 restore')
assert.match(template, /收起\s*<\/button>/, '唯一的收起动作文案是「收起」')
// 关闭语义的三种实际载体:对话框组件、显式 close 处理器、Element 的关闭开关
assert.equal(occurrences(source, 'el-dialog'), 0, '用对话框会带来关闭件')
assert.doesNotMatch(source, /@click="[^"]*close/i, '存在 close 点击处理器')
assert.doesNotMatch(source, /show-close|close-on-click-modal|close-on-press-escape|:closable/, '存在任何关闭开关')
})
test('收起态按「用户 id + 到期值」记键:续费换了到期值,键变了就自动回到展开', () => {
assert.equal(occurrences(script, 'admin-expiry-notice-min:'), 1, '收起态键名只应有一处定义')
assert.match(
script,
/`admin-expiry-notice-min:\$\{user\.value\.id\}:\$\{expiresAt\.value\}`/,
'键里必须同时带用户 id 与到期值,缺到期值则续费后仍停在收起态',
)
// 全组件只写这一个键:任何形式的「已读/忽略」持久化都会让提醒在续费前被永久关掉
assert.equal(occurrences(script, 'localStorage.setItem('), 1, '持久化写入只能有收起态这一处')
assert.equal(occurrences(script, 'localStorage.removeItem('), 1, '只有恢复展开时清键')
})
test('到期值变化会重新判定收起态:watch 键值且 immediate', () => {
assert.match(script, /watch\(\s*minimizedKey,/, '没有监听 minimizedKey')
assert.match(script, /minimized\.value = key \? localStorage\.getItem\(key\) === '1' : false/, '展开态直接由键值决定')
assert.match(script, /\{ immediate: true \}/, '缺 immediate 则首屏不判定,刷新后不提醒')
})
test('挂在后台布局上:AdminLayout 引了组件并且渲染,不挂就整站看不见', () => {
const layout = withoutComments(readSource(LAYOUT))
assert.match(layout, /import ExpiryNotice from '@\/components\/ExpiryNotice\.vue'/, '布局没引组件')
assert.match(layout, /<ExpiryNotice\s*\/>/, '布局没渲染组件(注释掉等于没挂)')
})
test('数据源键名与前端类型对齐:daysToExpire/expiresAt 来自 current-user,没有映射层', () => {
const types = readSource(TYPES)
assert.match(types, /daysToExpire\?: number \| null/, 'AdminUser 类型缺 daysToExpire')
assert.match(types, /expiresAt\?: string/, 'AdminUser 类型缺 expiresAt')
assert.match(readSource('src/api/session.ts'), /\/api\/admin\/current-user/, '会话数据源不是 current-user')
// 组件读的是 store 上的这两个键,不是自己算时间
assert.match(script, /session\.user/, '弹窗数据源是后台会话 store')
assert.match(script, /user\.value\?\.daysToExpire/, '读 daysToExpire 而不是本地算')
})
+2 -2
View File
@@ -36,10 +36,10 @@ test('test_task_251_user_dialog_boundary_empty_input', () => {
})
test('test_task_251_user_dialog_boundary_single_item', () => {
// 超管用户不可编辑(行按钮禁用)。
// 超管用户不可编辑(行按钮禁用);2026-10-05 起判定结合操作者角色(公司超管目标仅站点超管可编辑)。
const page = readSource('src/pages/account/UsersPage.vue')
assert.match(page, /editableOf/, '需有可编辑判定')
assert.match(page, /isEditableUser/, '可编辑判定应复用 user-edit-model')
assert.match(page, /editableBy/, '可编辑判定应复用 user-edit-model')
})
test('test_task_251_user_dialog_boundary_limit_or_missing_field', () => {
+8 -2
View File
@@ -14,6 +14,8 @@ test('test_task_048_user_role_map_normal_primary_path', () => {
assert.equal(roleDomainOf({ role: 'admin' }), 'admin')
assert.equal(roleDomainOf({ role: 'normal' }), 'normal')
assert.equal(roleDomainOf({ role: 'super_admin' }), 'super_admin')
// 2026-10-05 新增角色:公司超级管理员(数据只看本公司,由站点超管开设)
assert.equal(roleDomainOf({ role: 'company_super_admin' }), 'company_super_admin')
})
test('test_task_048_user_role_map_normal_variant_input', () => {
@@ -43,10 +45,11 @@ test('test_task_048_user_role_map_boundary_single_item', () => {
})
test('test_task_048_user_role_map_boundary_limit_or_missing_field', () => {
// 边界上限:超级管理员不可作为可编辑角色(null);候选不含 super_admin。
// 边界上限:站点/公司超管不可作为可编辑角色(null);候选含公司超管但绝不含站点超管。
assert.equal(selectRoleOf({ role: 'super_admin' }), null)
assert.equal(selectRoleOf({ role: 'company_super_admin' }), null)
const values = USER_ROLE_OPTIONS.map((o) => o.value)
assert.deepEqual([...values].sort(), ['admin', 'normal'])
assert.deepEqual([...values].sort(), ['admin', 'company_super_admin', 'normal'])
assert.equal(values.includes('super_admin'), false)
})
@@ -55,6 +58,8 @@ test('test_task_048_user_role_map_invalid_input_rejected', () => {
assert.match(userRoleLockMessage('super_admin', { role: 'super_admin' }) || '', /超级管理员/)
assert.match(userRoleLockMessage('admin', { role: 'normal' }) || '', /超管|管理员/)
assert.equal(userRoleLockMessage('super_admin', { role: 'normal' }), undefined)
// 2026-10-05:公司超管目标只有站点超管能编辑(改密码/到期时间做续费),角色锁定要单独说清
assert.match(userRoleLockMessage('super_admin', { role: 'company_super_admin' }) || '', /公司超级管理员/)
})
test('test_task_048_user_role_map_dependency_failure_returns_actionable_message', () => {
@@ -64,4 +69,5 @@ test('test_task_048_user_role_map_dependency_failure_returns_actionable_message'
assert.equal(roleDomainLabel('admin'), '管理员')
assert.equal(roleDomainLabel('normal'), '普通用户')
assert.equal(roleDomainLabel('super_admin'), '超级管理员')
assert.equal(roleDomainLabel('company_super_admin'), '公司超级管理员')
})
+5 -5
View File
@@ -1,14 +1,14 @@
# Flyway 迁移盘点(task-193)
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步。
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步。
## 概览
- 版本化迁移文件数:**144**(`src/main/resources/db/V*.sql`,其中整数版本 143 个 + 小版本 V25_1)
- 整数版本范围:**V1..V145**,其中 V132/V133 为已退役空号(见下),其余连续
- 版本化迁移文件数:**145**(`src/main/resources/db/V*.sql`,其中整数版本 144 个 + 小版本 V25_1)
- 整数版本范围:**V1..V146**,其中 V132/V133 为已退役空号(见下),其余连续
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
- 最新版本:**V145__brand_dedupe_company_scope.sql**(V142 已于 10-03 18:23 应用、V143 已于 10-04 10:48 应用、**V144 已于 10-04 13:22 应用**;V145 待下一次 jar 发版执行)
- 最新版本:**V146__users_expires_at_admin_expiry.sql**(上一版 **V145__brand_dedupe_company_scope.sql**;V142 已于 10-03 18:23 应用、V143 已于 10-04 10:48 应用、**V144 已于 10-04 13:22 应用**;V145/V146 待下一次 jar 发版执行)
- 重复版本:无
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
@@ -20,7 +20,7 @@
本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。
后续新增迁移从 **V146** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。
后续新增迁移从 **V147** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。
原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。
@@ -144,6 +144,19 @@ public interface ShopManageGroupMapper extends BaseMapper<ShopManageGroupEntity>
""")
List<ShopManageGroupEntity> selectLedGroups(@Param("operatorId") Long operatorId);
/**
* 某用户所属分组(成员表)的组长 id 集合(到期级联用,AccountExpiryService)。
* 与数据可见范围同源:组长的旧字段 user_id 与新字段 created_by_id 都算(COALESCE 取新优先旧兜底)。
*/
@Select("""
SELECT DISTINCT COALESCE(g.created_by_id, g.user_id) AS leader_id
FROM biz_shop_manage_group_member gm
INNER JOIN biz_shop_manage_group g ON g.id = gm.group_id
WHERE gm.user_id = #{userId}
AND COALESCE(g.created_by_id, g.user_id) IS NOT NULL
""")
List<Long> selectLeaderIdsByMemberUserId(@Param("userId") Long userId);
/** 全部分组(超管筛选项用)。 */
@Select("""
SELECT g.id AS id, g.group_name AS groupName
@@ -26,6 +26,12 @@ public class AdminUserEntity {
/** 所属公司(company.id,V143 新增)。列 NOT NULL,建号必须显式写,见 AdminUserService#createUser。 */
@TableField("company_id")
private Long companyId;
/**
* 到期时间(V146 新增):NULL=永不过期。管理员到期则组下普通账户跟随停用、公司超级管理员
* 到期则全公司跟随停用——级联判定在 AccountExpiryService,库里不改值。super_admin 不适用。
*/
@TableField("expires_at")
private LocalDateTime expiresAt;
@TableField("created_at")
private LocalDateTime createdAt;
/**
@@ -0,0 +1,161 @@
package com.nanri.aiimage.common.security;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* 账号到期(expires_at,V146)的级联判定与拦截。
*
* <p><b>判定口径(库里不改值,全部现算):</b>生效到期 = 自身 expires_at 与所有上级约束里最早的那个。</p>
* <ul>
* <li>super_admin:永不适用(返回 null);</li>
* <li>公司级:本公司所有 company_super_admin 的 expires_at 约束全公司(管理员/普通用户跟随);
* 公司没有公司超管时无此约束(站点自己的公司通常如此);</li>
* <li>组级:普通用户受两条链约束——所属分组组长(成员表)与创建人(管理员),
* 与数据可见范围的派生口径一致(成员表基本未用、按创建人派生);</li>
* <li>管理员(admin):自身 + 公司级。</li>
* </ul>
*
* <p>拦截点:登录(403,提示续费)与每次请求鉴权 {@code AdminAuthSupport.requireUser}
* (401,前端按下线处理踢回登录页)。任务心跳接口刻意匿名、不走 requireUser,所以
* {@code ExpiredAccountTaskStopService} 把任务置终态后,客户端心跳仍能拿到 alive=false
* 协作停止——这是"过期停任务"不走 401 的原因。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class AccountExpiryService {
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
/** 生效到期时间;null=永不过期。入参见 {@link #computeEffective(Long, String, Integer, Long, Long, LocalDateTime)}。 */
public LocalDateTime effectiveExpiresAt(AdminUserEntity user) {
if (user == null) {
return null;
}
return computeEffective(user.getId(), user.getRole(), user.getIsAdmin(), user.getCompanyId(),
user.getCreatedById(), user.getExpiresAt());
}
/** 同上,登录链路的 users 实体(与 {@code AdminUserEntity} 同表同列)。 */
public LocalDateTime effectiveExpiresAt(LoginUserEntity user) {
if (user == null) {
return null;
}
return computeEffective(user.getId(), user.getRole(), user.getIsAdmin(), user.getCompanyId(),
user.getCreatedById(), user.getExpiresAt());
}
/** 登录拦截:已到期(含级联)抛 403,文案给续费提示。 */
public void assertLoginAllowed(AdminUserEntity user) {
assertNotExpired(effectiveExpiresAt(user), 403);
}
/** 同上,登录链路的 users 实体。 */
public void assertLoginAllowed(LoginUserEntity user) {
assertNotExpired(effectiveExpiresAt(user), 403);
}
/** 会话拦截:已到期(含级联)抛 401,前端踢回登录页。 */
public void assertSessionAllowed(AdminUserEntity user) {
assertNotExpired(effectiveExpiresAt(user), 401);
}
/** 同上,登录链路的 users 实体(check_login 恢复会话时走这里)。 */
public void assertSessionAllowed(LoginUserEntity user) {
assertNotExpired(effectiveExpiresAt(user), 401);
}
/** 弹窗用:自身 expires_at 还剩整天数(floor);无到期返回 null。只反映自身,不级联——续费是账号自己的事。 */
public static Long ownDaysToExpire(LocalDateTime ownExpiresAt) {
if (ownExpiresAt == null) {
return null;
}
long seconds = java.time.Duration.between(LocalDateTime.now(), ownExpiresAt).getSeconds();
return Math.floorDiv(seconds, 86400L);
}
private void assertNotExpired(LocalDateTime effective, int code) {
if (effective != null && effective.isBefore(LocalDateTime.now())) {
throw new BusinessException(code, "账号已过期,请联系管理员续费");
}
}
private LocalDateTime computeEffective(Long userId, String storedRole, Integer isAdmin, Long companyId,
Long createdById, LocalDateTime ownExpiresAt) {
String role = DeviceSessionPolicy.resolveRole(storedRole, isAdmin, createdById);
if ("super_admin".equals(role)) {
return null;
}
LocalDateTime effective = ownExpiresAt;
effective = min(effective, companyCascadeExpiresAt(companyId));
if (role == null) {
// 普通用户:组级约束(组长 + 创建人)。管理员不级联到组长(上级是公司超管/超管,走公司级)。
effective = min(effective, leaderCascadeExpiresAt(userId));
effective = min(effective, creatorCascadeExpiresAt(createdById));
}
return effective;
}
/** 公司级:本公司公司超管里最早的 expires_at;没有公司超管(含 companyId 为空)返回 null。 */
private LocalDateTime companyCascadeExpiresAt(Long companyId) {
if (companyId == null || companyId <= 0) {
return null;
}
List<AdminUserEntity> csas = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.select(AdminUserEntity::getExpiresAt)
.eq(AdminUserEntity::getRole, "company_super_admin")
.eq(AdminUserEntity::getCompanyId, companyId));
LocalDateTime earliest = null;
for (AdminUserEntity csa : csas) {
earliest = min(earliest, csa.getExpiresAt());
}
return earliest;
}
/** 组级:该用户所属分组(成员表)的组长(created_by_id/user_id)若是管理员,取其最早 expires_at。 */
private LocalDateTime leaderCascadeExpiresAt(Long userId) {
if (userId == null || userId <= 0) {
return null;
}
LocalDateTime earliest = null;
for (Long leaderId : shopManageGroupMapper.selectLeaderIdsByMemberUserId(userId)) {
AdminUserEntity leader = adminUserMapper.selectById(leaderId);
if (leader != null && "admin".equals(DeviceSessionPolicy.resolveRole(
leader.getRole(), leader.getIsAdmin(), leader.getCreatedById()))) {
earliest = min(earliest, leader.getExpiresAt());
}
}
return earliest;
}
/** 组级:创建人是管理员(普通账户的归属主管)时,取其 expires_at。 */
private LocalDateTime creatorCascadeExpiresAt(Long createdById) {
if (createdById == null || createdById <= 0) {
return null;
}
AdminUserEntity creator = adminUserMapper.selectById(createdById);
if (creator == null || !"admin".equals(DeviceSessionPolicy.resolveRole(
creator.getRole(), creator.getIsAdmin(), creator.getCreatedById()))) {
return null;
}
return creator.getExpiresAt();
}
private static LocalDateTime min(LocalDateTime a, LocalDateTime b) {
if (a == null) return b;
if (b == null) return a;
return b.isBefore(a) ? b : a;
}
}
@@ -30,6 +30,7 @@ public class AdminAuthSupport {
private final JwtService jwtService;
private final AdminUserMapper adminUserMapper;
private final AuthProperties authProperties;
private final AccountExpiryService accountExpiryService;
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@@ -67,6 +68,9 @@ public class AdminAuthSupport {
DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById()),
user.getId(), user.getUsername());
}
// 到期拦截(含级联):管理员过期→组下账户停、公司超管过期→全公司停。
// 任务心跳接口刻意匿名、不走本方法,过期账号的在跑任务仍能靠 alive=false 协作停止。
accountExpiryService.assertSessionAllowed(user);
return user;
}
@@ -22,12 +22,17 @@ public final class DeviceSessionPolicy {
private DeviceSessionPolicy() {
}
/** 计算用户管理角色:super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
/** 计算用户管理角色:super_admin / company_super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
public static String resolveRole(String role, Integer isAdmin, Long createdById) {
String storedRole = role == null ? "" : role.trim().toLowerCase();
if ("super_admin".equals(storedRole)) {
return "super_admin";
}
if ("company_super_admin".equals(storedRole)) {
// 公司超级管理员(2026-10-05):单家公司内的最高账号,数据只看本公司,由站点
// super_admin 创建。必须先于 is_admin 兼容推断返回,否则会被顶成站点超管。
return "company_super_admin";
}
if ("admin".equals(storedRole)) {
return "admin";
}
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.admin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.company.service.CompanyService;
@@ -64,17 +65,22 @@ public class AdminConsoleController {
}
@GetMapping("/api/admin/current-user")
@Operation(summary = "当前登录管理员概要")
@Operation(summary = "获取当前管理员信息")
public ApiResponse<Map<String, Object>> currentUser(HttpServletRequest request) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Map<String, Object> item = new LinkedHashMap<>();
item.put("id", operator.getId());
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
item.put("role", adminAuthSupport.currentRole(operator));
// 键名固定 camelCase:session.ts 把 item 原样当 AdminUser 用,没有字段映射层,
// 拼错只会让顶栏静默少一行字(前端 || '' 兜底),不会报错。
// 这里刻意用 camelCase:session.ts 把 item 当作 AdminUser 用,不再经解析器,
// 所以这些键要与既有 companyId/companyName 的形状一致(前端 || '' 兜底)
item.put("companyId", operator.getCompanyId());
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
// 到期续费提醒(V146):只反映自身 expires_at,不级联——续费是账号自己的事。
// expiresAt 为 yyyy-MM-dd HH:mm 或 null;daysToExpire 为剩余整天数或 null。
item.put("expiresAt", operator.getExpiresAt() == null ? null
: operator.getExpiresAt().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
item.put("daysToExpire", AccountExpiryService.ownDaysToExpire(operator.getExpiresAt()));
return ApiResponse.success(Map.of("item", item));
}
@@ -11,5 +11,10 @@ public class AdminUserCreateRequest {
private String role;
private Long createdById;
private Long companyId;
/**
* 到期时间(V146):支持 yyyy-MM-dd / yyyy-MM-dd HH:mm / yyyy-MM-dd HH:mm:ss。
* 空/不传 = 永不过期;super_admin 目标不存在本字段语义(超管建不出超管)。
*/
private String expiresAt;
private List<Long> columnIds;
}
@@ -11,4 +11,9 @@ public class AdminUserUpdateRequest {
private List<Long> columnIds;
/** 移人目标公司(V143 §2.2,仅超管可用);null 或与账号现公司相同都表示「不动」。 */
private Long companyId;
/**
* 到期时间(V146):null=不动;空串=清除(恢复永不过期);否则为
* yyyy-MM-dd[ HH:mm[:ss]],允许过去时间(立即到期 = 手工停用)。
*/
private String expiresAt;
}
@@ -22,6 +22,9 @@ public class AdminUserItemVo {
private String createdAt;
@JsonProperty("updated_at")
private String updatedAt;
/** 到期时间(yyyy-MM-dd HH:mm);空串=永不过期,前端按此渲染。 */
@JsonProperty("expires_at")
private String expiresAt;
@JsonProperty("pinyin_abbr")
private String pinyinAbbr;
}
@@ -72,8 +72,9 @@ public class AdminUserService {
query.eq(AdminUserEntity::getRole, roleFilterValue);
}
boolean isSuperAdmin = "super_admin".equals(role);
boolean isCompanySuperAdmin = "company_super_admin".equals(role);
if (companyIdFilter != null && !isSuperAdmin) {
// 公司内管理员:筛自己公司 = 不加条件(他的可见范围本来就只有本公司),
// 公司内管理员/公司超管:筛自己公司 = 不加条件(可见范围本来就只有本公司),
// 筛别家公司 = 直接空页。这里故意不报错也不越权(设计文档 §2.3)。
if (!companyIdFilter.equals(currentUser.getCompanyId())) {
return emptyListVo(currentUser, role, safePage, safeSize);
@@ -89,6 +90,13 @@ public class AdminUserService {
if (companyIdFilter != null) {
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
}
} else if (isCompanySuperAdmin) {
// 公司超管看本公司全部账号(站点超管账号除外——那是平台自己的身份)
query.eq(AdminUserEntity::getCompanyId, currentUser.getCompanyId())
.ne(AdminUserEntity::getRole, "super_admin");
if (!kw.isEmpty()) {
query.like(AdminUserEntity::getUsername, kw);
}
} else {
Long adminId = currentUser.getId();
query.and(w -> w
@@ -140,13 +148,13 @@ public class AdminUserService {
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
String username = request.getUsername() == null ? "" : request.getUsername().trim();
String password = request.getPassword() == null ? "" : request.getPassword();
String wantRole = request.getRole() == null ? "normal" : request.getRole().trim();
if (wantRole.isEmpty()) wantRole = "normal";
if (!"admin".equals(wantRole) && !"normal".equals(wantRole)) {
wantRole = "normal";
String wantRole = normalizeWantRole(request.getRole());
if ("admin".equals(wantRole) && "admin".equals(role)) {
throw new BusinessException("仅超级管理员或公司超级管理员可创建管理员");
}
if ("admin".equals(role) && "admin".equals(wantRole)) {
throw new BusinessException("仅超级管理员可创建管理员");
if ("company_super_admin".equals(wantRole) && !"super_admin".equals(role)) {
// 公司超管是「某一家公司的最高账号」,只能由站点超管开设,谁都不能自己造一级
throw new BusinessException(403, "只有超级管理员可以创建公司超级管理员");
}
if (username.isEmpty() || password.isEmpty()) {
throw new BusinessException("用户名和密码不能为空");
@@ -159,7 +167,8 @@ public class AdminUserService {
}
Long wantCreatedBy;
if ("admin".equals(wantRole)) {
if ("admin".equals(wantRole) || "company_super_admin".equals(wantRole)) {
// 组长/公司超管的创建人就是操作者本人:公司超管不能替别的主管“认领”管理员
wantCreatedBy = currentUser.getId();
} else if ("super_admin".equals(role)) {
wantCreatedBy = request.getCreatedById();
@@ -174,7 +183,8 @@ public class AdminUserService {
wantCreatedBy = currentUser.getId();
}
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)) ? 1 : 0;
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)
|| "company_super_admin".equals(wantRole)) ? 1 : 0;
AdminUserEntity entity = new AdminUserEntity();
entity.setUsername(username);
entity.setPasswordHash(passwordEncoder.hash(password));
@@ -182,6 +192,7 @@ public class AdminUserService {
entity.setRole(wantRole);
entity.setCreatedById(wantCreatedBy);
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
entity.setExpiresAt(parseExpiresAt(request.getExpiresAt()));
try {
adminUserMapper.insert(entity);
} catch (DuplicateKeyException e) {
@@ -191,6 +202,49 @@ public class AdminUserService {
return entity.getId();
}
/**
* 建号角色归一:白名单 admin / company_super_admin / normal,其余一律归 normal。 */
private static String normalizeWantRole(String rawRole) {
String wantRole = rawRole == null ? "normal" : rawRole.trim();
if (wantRole.isEmpty()) {
wantRole = "normal";
}
if (!"admin".equals(wantRole) && !"normal".equals(wantRole)
&& !"company_super_admin".equals(wantRole)) {
wantRole = "normal";
}
return wantRole;
}
/**
* 解析请求里的到期时间:null/空白 = null(永不过期);支持 yyyy-MM-dd、
* yyyy-MM-dd HH:mm、yyyy-MM-dd HH:mm:ss 与 ISO(yyyy-MM-ddTHH:mm)。
* 格式不对直接报错,不静默归 null——那会把"想设到期"变成"设了永不过期"。
*/
private static LocalDateTime parseExpiresAt(String raw) {
if (raw == null || raw.trim().isEmpty()) {
return null;
}
String value = raw.trim().replace('T', ' ');
for (String pattern : new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd"}) {
try {
java.time.format.DateTimeFormatter formatter =
java.time.format.DateTimeFormatter.ofPattern(pattern);
java.time.temporal.TemporalAccessor parsed = formatter.parseBest(value,
LocalDateTime::from, java.time.LocalDate::from);
if (parsed instanceof LocalDateTime dateTime) {
return dateTime;
}
if (parsed instanceof java.time.LocalDate date) {
return date.atStartOfDay();
}
} catch (java.time.format.DateTimeParseException ignored) {
// 试下一个格式
}
}
throw new BusinessException("到期时间格式不正确,请使用 yyyy-MM-dd 或 yyyy-MM-dd HH:mm");
}
/**
* 建号落哪家公司(设计文档 §2.2,与 createdById 同构):超管可指定任意启用中的公司,
* 其余角色只能落自己所属公司——显式传别家即 403,不静默改写。
@@ -266,7 +320,8 @@ public class AdminUserService {
if ((password == null || password.isEmpty())
&& (wantRole == null || wantRole.isEmpty())
&& request.getColumnIds() == null
&& request.getCompanyId() == null) {
&& request.getCompanyId() == null
&& request.getExpiresAt() == null) {
throw new BusinessException("请提供要修改的内容");
}
@@ -282,13 +337,27 @@ public class AdminUserService {
}
wantRole = null;
} else {
boolean operatorIsSiteSuperAdmin = "super_admin".equals(role);
if ("super_admin".equals(targetRole)) {
throw new BusinessException("不能修改超级管理员");
}
if ("company_super_admin".equals(role)) {
// 公司超管只能编辑本公司管理员/普通用户;同公司的公司超管与站点超管都碰不得
if ("company_super_admin".equals(targetRole)) {
throw new BusinessException(403, "只有超级管理员可以修改公司超级管理员");
}
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
throw new BusinessException(403, "只能编辑本公司名下的账号");
}
}
if ("super_admin".equals(wantRole)) {
throw new BusinessException("不能将用户设为超级管理员");
}
if (wantRole != null && !"admin".equals(wantRole) && !"normal".equals(wantRole) && !wantRole.isEmpty()) {
if ("company_super_admin".equals(wantRole) && !operatorIsSiteSuperAdmin) {
throw new BusinessException(403, "只有超级管理员可以设置公司超级管理员");
}
if (wantRole != null && !"admin".equals(wantRole) && !"normal".equals(wantRole)
&& !"company_super_admin".equals(wantRole) && !wantRole.isEmpty()) {
wantRole = null;
}
}
@@ -314,11 +383,18 @@ public class AdminUserService {
dirty = true;
}
if (wantRole != null && !wantRole.isEmpty()) {
int isAdmin = "admin".equals(wantRole) ? 1 : 0;
int isAdmin = ("admin".equals(wantRole) || "company_super_admin".equals(wantRole)) ? 1 : 0;
update.set(AdminUserEntity::getIsAdmin, isAdmin);
update.set(AdminUserEntity::getRole, wantRole);
dirty = true;
}
if (request.getExpiresAt() != null) {
// null=不动;空串=清除(恢复永不过期);有值=改期(允许过去时间,等于立即停用)。
// super_admin / 同公司公司超管目标在上面的闸门里已拒绝,到不了这里。
update.set(AdminUserEntity::getExpiresAt,
request.getExpiresAt().trim().isEmpty() ? null : parseExpiresAt(request.getExpiresAt()));
dirty = true;
}
if (dirty) {
adminUserMapper.update(null, update);
}
@@ -387,6 +463,14 @@ public class AdminUserService {
if (!"normal".equals(targetRole) || !currentUser.getId().equals(target.getCreatedById())) {
throw new BusinessException(403, "只能删除自己创建的普通用户");
}
} else if ("company_super_admin".equals(role)) {
// 公司超管可清退本公司的管理员/普通用户;公司超管之间互删与站点超管一样被拒
if ("company_super_admin".equals(targetRole)) {
throw new BusinessException(403, "只有超级管理员可以删除公司超级管理员");
}
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
throw new BusinessException(403, "只能删除本公司名下的账号");
}
}
int affected = adminUserMapper.deleteById(uid);
if (affected == 0) {
@@ -459,6 +543,8 @@ public class AdminUserService {
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
LocalDateTime updatedAt = entity.getUpdatedAt();
vo.setUpdatedAt(updatedAt == null ? "" : updatedAt.format(CREATED_AT_FORMATTER));
// 到期时间:null(永不过期)与空字符串在列表里都要有明确渲染,前端按空串判"永不过期"
vo.setExpiresAt(entity.getExpiresAt() == null ? "" : entity.getExpiresAt().format(CREATED_AT_FORMATTER));
vo.setPinyinAbbr(PinyinAbbrUtil.abbr(entity.getUsername()));
return vo;
}
@@ -6,6 +6,8 @@ import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("users")
public class LoginUserEntity {
@@ -29,4 +31,10 @@ public class LoginUserEntity {
*/
@TableField("company_id")
private Long companyId;
/**
* 到期时间(V146 新增,NULL=永不过期)。与 {@code AdminUserEntity.expiresAt} 同列:
* 级联判定(管理员过期→组下账户停、公司超管过期→全公司停)在 AccountExpiryService。
*/
@TableField("expires_at")
private LocalDateTime expiresAt;
}
@@ -16,6 +16,10 @@ public class LoginResultVo {
private Long companyId;
/** 所属公司名,只显示用;查不到公司一律空串,绝不拿它当登录条件。 */
private String companyName;
/** 自身账号到期时间(yyyy-MM-dd HH:mm,V146);null=永不过期。只用于前端续费提醒,不级联。 */
private String expiresAt;
/** 自身到期剩余整天数(floor);null=永不过期。前端按 <5 天弹续费提醒。 */
private Long daysToExpire;
private String deviceId;
private String token;
private Long expiresIn;
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
@@ -20,6 +21,8 @@ import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.nanri.aiimage.common.security.JwtService;
@@ -29,12 +32,15 @@ import com.nanri.aiimage.common.security.JwtService;
@Slf4j
public class AuthService {
private static final DateTimeFormatter EXPIRES_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final LoginUserMapper loginUserMapper;
private final WerkzeugPasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final PermissionMenuService permissionMenuService;
private final AuthProperties authProperties;
private final CompanyService companyService;
private final AccountExpiryService accountExpiryService;
/**
* 登录失败计数与锁定(2026-09 全维度审查补):生产是公网域名,此前无任何失败限制
@@ -102,6 +108,10 @@ public class AuthService {
}
clearLoginFailures(username);
// 到期拦截(含级联:管理员过期→组下账户、公司超管过期→全公司)。放在设备绑定之前:
// 过期账号不应产生任何登录副作用,machine 保持原值即可。
accountExpiryService.assertLoginAllowed(user);
boolean isAdmin = user.getIsAdmin() != null && user.getIsAdmin() == 1;
// 单设备登录:登录成功即把账号绑定到当前设备(last-login-wins),原设备下一次请求被顶下线
if (authProperties.isSingleDeviceEnabled()) {
@@ -141,6 +151,8 @@ public class AuthService {
DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById()),
user.getId(), user.getUsername());
}
// 到期拦截(含级联):登录态在到期那一刻起全部失效,前端按 401 踢回登录页
accountExpiryService.assertSessionAllowed(user);
String headerDevice = trim(currentDeviceId);
if (!headerDevice.isEmpty() && !claimDeviceId.isEmpty() && !headerDevice.equals(claimDeviceId)) {
log.warn("[auth] check_login 请求头设备与登录态内设备不一致(以登录态为准)userId={} headerDevice={} loginDevice={}",
@@ -185,6 +197,10 @@ public class AuthService {
// 公司身份只做显示:nameOrEmpty 查不到就空串,登录不因此被打回
vo.setCompanyId(user.getCompanyId());
vo.setCompanyName(companyService.nameOrEmpty(user.getCompanyId()));
// 到期信息只做弹窗提醒(剩余不足 5 天时前端展示),只反映自身 expires_at,不级联——
// 续费是账号自己的事,组员不替组长看续费弹窗。
vo.setExpiresAt(user.getExpiresAt() == null ? null : user.getExpiresAt().format(EXPIRES_AT_FORMATTER));
vo.setDaysToExpire(AccountExpiryService.ownDaysToExpire(user.getExpiresAt()));
vo.setDeviceId(deviceId);
vo.setToken(token);
vo.setExpiresIn(jwtService.ttlSeconds());
@@ -0,0 +1,53 @@
package com.nanri.aiimage.modules.brand.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
/**
* 账号过期时停止品牌采集任务(brand_crawl_tasks):pending/running 一律取消。
* 客户端下一次心跳(≤60s)拿到 alive=false 自行收尾——与 markInterrupted 同一条协作停止通道。
*/
@Service
@RequiredArgsConstructor
public class BrandTaskExpiredStopSpiImpl implements ExpiredAccountTaskStopSpi {
private static final String STATUS_PENDING = "pending";
private static final String STATUS_RUNNING = "running";
private static final String STATUS_CANCELLED = "cancelled";
private final BrandCrawlTaskMapper brandCrawlTaskMapper;
@Override
public String moduleType() {
return "BRAND";
}
@Override
public int stopActiveTasks(Collection<Long> userIds, String reason) {
if (userIds == null || userIds.isEmpty()) {
return 0;
}
List<Long> ids = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
.select(BrandCrawlTaskEntity::getId)
.in(BrandCrawlTaskEntity::getUserId, userIds)
.in(BrandCrawlTaskEntity::getStatus, STATUS_PENDING, STATUS_RUNNING)
.last("limit 500"))
.stream().map(BrandCrawlTaskEntity::getId).toList();
if (ids.isEmpty()) {
return 0;
}
return brandCrawlTaskMapper.update(null, new LambdaUpdateWrapper<BrandCrawlTaskEntity>()
.in(BrandCrawlTaskEntity::getId, ids)
.in(BrandCrawlTaskEntity::getStatus, STATUS_PENDING, STATUS_RUNNING)
.set(BrandCrawlTaskEntity::getStatus, STATUS_CANCELLED)
.set(BrandCrawlTaskEntity::getErrorMessage, reason));
}
}
@@ -19,6 +19,7 @@ import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
@@ -80,6 +81,7 @@ public class DedupeTotalDataService {
private final DedupeTotalDataMapper dedupeTotalDataMapper;
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
private final CompanyScopeSupport companyScopeSupport;
private final PlatformTransactionManager transactionManager;
// 2026-09 全维度审查 D2:进度/归属/分组改由 NodeSharedStore 承载(本地快路径 + Redis 跨节点),
@@ -96,12 +98,14 @@ public class DedupeTotalDataService {
public DedupeTotalDataService(DedupeTotalDataMapper dedupeTotalDataMapper,
AdminUserMapper adminUserMapper,
ShopManageGroupMapper shopManageGroupMapper,
CompanyScopeSupport companyScopeSupport,
PlatformTransactionManager transactionManager,
org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper) {
this.dedupeTotalDataMapper = dedupeTotalDataMapper;
this.adminUserMapper = adminUserMapper;
this.shopManageGroupMapper = shopManageGroupMapper;
this.companyScopeSupport = companyScopeSupport;
this.transactionManager = transactionManager;
this.importProgressMap = progressStore("aiimage:dedupe:import:progress", stringRedisTemplate, objectMapper);
this.deleteImportProgressMap = progressStore("aiimage:dedupe:delete-import:progress", stringRedisTemplate, objectMapper);
@@ -1179,7 +1183,18 @@ public class DedupeTotalDataService {
private AccessScope resolveAccessScope(Long operatorId) {
AdminUserEntity operator = getOperator(operatorId);
if (isSuperAdmin(operator)) {
return new AccessScope(true, Set.of(), Set.of());
return new AccessScope(true, Set.of(), Set.of(), false);
}
if ("company_super_admin".equals(operator.getRole() == null
? "" : operator.getRole().trim().toLowerCase(Locale.ROOT))) {
LinkedHashSet<Long> companyUserIds = new LinkedHashSet<>();
companyUserIds.add(operator.getId());
for (Long memberId : companyScopeSupport.memberUserIds(operator.getCompanyId())) {
if (memberId != null && memberId > 0) {
companyUserIds.add(memberId);
}
}
return new AccessScope(false, Set.of(), Set.copyOf(companyUserIds), true);
}
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
@@ -1201,7 +1216,8 @@ public class DedupeTotalDataService {
return new AccessScope(
false,
Set.copyOf(accessibleGroupIds == null ? List.of() : accessibleGroupIds),
Set.copyOf(visibleUserIds));
Set.copyOf(visibleUserIds),
false);
}
private void applyGroupScope(LambdaQueryWrapper<DedupeTotalDataEntity> query,
@@ -1221,6 +1237,11 @@ public class DedupeTotalDataService {
if (scope.allUsers()) {
return;
}
if (scope.wholeCompany()) {
// 公司超管:整家公司成员上传的行全可见,不再按 group_id 切
query.in(DedupeTotalDataEntity::getUploaderUserId, scope.userIds());
return;
}
query.and(wrapper -> {
if (!scope.groupIds().isEmpty()) {
wrapper.in(DedupeTotalDataEntity::getGroupId, scope.groupIds())
@@ -1402,6 +1423,11 @@ public class DedupeTotalDataService {
return vo;
}
private record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds) {
/**
* @param allUsers 超管直通
* @param wholeCompany 公司超管:不做分组维度裁剪,userIds = 本公司全体成员,
* 查询条件退化为 uploader_user_id IN (成员)——公司超管的"组"就是整家公司
*/
private record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds, boolean wholeCompany) {
}
}
@@ -944,6 +944,18 @@ public class PermissionMenuService {
if (!isAdmin(operator)) {
throw new BusinessException(403, "需要管理员权限");
}
if ("company_super_admin".equals(normalizeRole(operator.getRole()))) {
// 公司超管:本公司管理员/普通用户都可授;同公司的公司超管与站点超管碰不得
String targetRole = normalizeRole(target.getRole());
if ("company_super_admin".equals(targetRole) || "super_admin".equals(targetRole)) {
throw new BusinessException(403, "只有超级管理员可以修改公司超级管理员");
}
if (operator.getCompanyId() == null
|| !operator.getCompanyId().equals(target.getCompanyId())) {
throw new BusinessException(403, "只能授权本公司名下的账号");
}
return;
}
boolean ownedNormal = isNormalUser(target)
&& operator.getId() != null
&& operator.getId().equals(target.getCreatedById());
@@ -1030,7 +1042,8 @@ public class PermissionMenuService {
}
String role = normalizeRole(user.getRole());
if (!role.isEmpty()) {
return "super_admin".equals(role) || "admin".equals(role);
// company_super_admin 也是授权链上的一级主管(可给本公司的管理员/普通用户授权)
return "super_admin".equals(role) || "admin".equals(role) || "company_super_admin".equals(role);
}
return Integer.valueOf(1).equals(user.getIsAdmin());
}
@@ -1054,7 +1067,8 @@ public class PermissionMenuService {
}
String role = normalizeRole(user.getRole());
if (!role.isEmpty()) {
return !"admin".equals(role) && !"super_admin".equals(role);
return !"admin".equals(role) && !"super_admin".equals(role)
&& !"company_super_admin".equals(role);
}
return !Integer.valueOf(1).equals(user.getIsAdmin());
}
@@ -5,6 +5,8 @@ import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -18,6 +20,9 @@ import java.util.Set;
* 数据权限范围解析:由主管(admin)uid 得到其可见/管辖的用户 id 集合。
* 与后台密钥管理页(UserApiSecretService.adminPage)同源规则:
* 自己带的「数据权限分组」成员(组长本人 + 名下子账户),无分组记录时回退按「名下子账户」兜底。
*
* <p>公司超级管理员(2026-10-05)看<b>本公司全部成员</b>:不分组长,公司就是他们的"组"。
* 由 {@link #resolveVisibleUserIds(AdminUserEntity)} 统一判角色,调用方无需各自 if。</p>
*/
@Component
@Slf4j
@@ -28,12 +33,32 @@ public class UserDataScopeSupport {
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
private final CompanyScopeSupport companyScopeSupport;
/** 主管可见用户:自己 + 自己带的分组下的子账户(名下 users.created_by_id=自己)。 */
public List<Long> resolveVisibleUserIds(Long operatorId) {
if (operatorId == null) {
return List.of();
}
return resolveVisibleUserIds(adminUserMapper.selectById(operatorId));
}
/** 按操作者实体解析;公司超管 → 本公司全部成员,其余与旧口径一致。 */
public List<Long> resolveVisibleUserIds(AdminUserEntity operator) {
if (operator == null || operator.getId() == null) {
return List.of();
}
if ("company_super_admin".equals(DeviceSessionPolicy.resolveRole(
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById()))) {
Set<Long> userIds = new LinkedHashSet<>(
companyScopeSupport.memberUserIds(operator.getCompanyId()));
userIds.add(operator.getId());
return new ArrayList<>(userIds);
}
return resolveByGroupScope(operator.getId());
}
private List<Long> resolveByGroupScope(Long operatorId) {
List<Long> ledGroupIds = listLedGroupIds(operatorId);
Set<Long> userIds = new LinkedHashSet<>();
for (Long groupId : ledGroupIds) {
@@ -0,0 +1,42 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackLoopRunMapper;
import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackLoopRunEntity;
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* 账号过期时请求停止跟价循环(biz_price_track_loop_run):只置 stop_requested=1,
* 不直接改状态——与用户点「停止循环」的 {@code requestStop} 同一条收尾路径,
* 循环在下一个派发/子任务收尾点落 STOPPED。当前在跑的子任务是 biz_file_task 行,
* 由 ExpiredAccountTaskStopService 直接置终态后经心跳 alive=false 协作停止。
*/
@Service
@RequiredArgsConstructor
public class PriceTrackLoopExpiredStopSpiImpl implements ExpiredAccountTaskStopSpi {
private static final String STATUS_RUNNING = "RUNNING";
private final PriceTrackLoopRunMapper loopRunMapper;
@Override
public String moduleType() {
return "PRICE_TRACK_LOOP";
}
@Override
public int stopActiveTasks(Collection<Long> userIds, String reason) {
if (userIds == null || userIds.isEmpty()) {
return 0;
}
return loopRunMapper.update(null, new LambdaUpdateWrapper<PriceTrackLoopRunEntity>()
.in(PriceTrackLoopRunEntity::getUserId, userIds)
.eq(PriceTrackLoopRunEntity::getStatus, STATUS_RUNNING)
.eq(PriceTrackLoopRunEntity::getStopRequested, false)
.set(PriceTrackLoopRunEntity::getStopRequested, true));
}
}
@@ -0,0 +1,150 @@
package com.nanri.aiimage.modules.task.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 账号过期停任务巡检(V146,2026-10-05)。
*
* <p>到期那一刻起,登录与全部鉴权请求已被 {@code AccountExpiryService} 拦下;但客户端
* <b>已经在跑的任务</b>不会自己停——客户端唯一的"服务端发令"停止通道是心跳返回 alive=false,
* 而它只看任务状态。本巡检每分钟把过期账号(含级联成员)名下的活跃任务置终态:
* biz_file_task PENDING/SCHEDULED/RUNNING → FAILED(含未领取的 PENDING,防内部通道继续派发);
* 品牌/跟价循环经 {@link ExpiredAccountTaskStopSpi} 由各业务模块自行停止。</p>
*
* <p>级联口径与登录侧 {@code AccountExpiryService} 严格一致:管理员过期 → 名下子账户
* (created_by_id)+ 所带分组的成员表成员;公司超管过期 → 全公司成员。置终态原因固定为
* {@link #STOP_REASON}(刻意不以「客户端异常中断」开头,绝不触发 TaskResumeService 自动续跑)。
* 续费后任务不会复活,需要用户重新发起。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ExpiredAccountTaskStopService {
/** ASCII 标记,供 _prod_watch.py 按 docker logs grep(中文在容器里可能变编码,签名必须 ASCII)。 */
static final String MARKER = "EXPIRED_ACCOUNT_TASKS_STOPPED";
/** 刻意避开 TaskResumeService 的「客户端异常中断」前缀,过期停止的任务不许被自动复活。 */
public static final String STOP_REASON = "账号已过期,任务已自动停止";
private static final String STATUS_PENDING = "PENDING";
private static final String STATUS_SCHEDULED = "SCHEDULED";
private static final String STATUS_RUNNING = "RUNNING";
private static final String STATUS_FAILED = "FAILED";
private static final int BATCH_LIMIT = 500;
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
private final CompanyScopeSupport companyScopeSupport;
private final FileTaskMapper fileTaskMapper;
private final DistributedJobLockService distributedJobLockService;
private final List<ExpiredAccountTaskStopSpi> moduleStops;
@Scheduled(fixedDelay = 60 * 1000, initialDelay = 45 * 1000)
public void stopTasksOfExpiredAccounts() {
var lock = distributedJobLockService.tryLock("expired-account-task-stop", Duration.ofSeconds(55));
if (lock == null) {
return;
}
try (lock) {
runOnce();
} catch (Exception ex) {
log.warn("[expired-account-stop] 巡检失败 msg={}", ex.getMessage(), ex);
}
}
void runOnce() {
LocalDateTime now = LocalDateTime.now();
List<AdminUserEntity> boundary = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.select(AdminUserEntity::getId, AdminUserEntity::getRole,
AdminUserEntity::getCompanyId, AdminUserEntity::getCreatedById)
.isNotNull(AdminUserEntity::getExpiresAt)
.le(AdminUserEntity::getExpiresAt, now)
.ne(AdminUserEntity::getRole, "super_admin"));
if (boundary.isEmpty()) {
return;
}
Set<Long> affected = resolveAffectedUserIds(boundary);
if (affected.isEmpty()) {
return;
}
int fileTaskCount = stopFileTasks(affected, now);
int moduleCount = 0;
for (ExpiredAccountTaskStopSpi spi : moduleStops) {
moduleCount += spi.stopActiveTasks(affected, STOP_REASON);
}
if (fileTaskCount > 0 || moduleCount > 0) {
log.warn("{} 账号过期已停止任务 expiredUsers={} fileTasks={} moduleStops={}",
MARKER, affected.size(), fileTaskCount, moduleCount);
}
}
/**
* 过期账号 → 需要连带停任务的成员集合。与登录侧级联判定同口径:
* 公司超管过期圈全公司;管理员过期圈名下子账户 + 所带分组的成员表成员;普通用户只有自己。
*/
private Set<Long> resolveAffectedUserIds(List<AdminUserEntity> boundary) {
LinkedHashSet<Long> affected = new LinkedHashSet<>();
for (AdminUserEntity account : boundary) {
if (account.getId() == null) {
continue;
}
affected.add(account.getId());
String role = account.getRole() == null ? "" : account.getRole();
if ("company_super_admin".equals(role)) {
if (account.getCompanyId() != null && account.getCompanyId() > 0) {
affected.addAll(companyScopeSupport.memberUserIds(account.getCompanyId()));
}
} else if ("admin".equals(role) || role.isEmpty()) {
// 名下子账户(组员归属的主链路:按创建人派生)
adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.select(AdminUserEntity::getId)
.eq(AdminUserEntity::getCreatedById, account.getId()))
.forEach(member -> {
if (member.getId() != null) {
affected.add(member.getId());
}
});
// 成员表直挂的成员(手工绑进分组、创建人不是该管理员的兜底)
affected.addAll(shopManageGroupMapper.selectManagedMemberUserIds(account.getId()));
}
}
return affected;
}
/** biz_file_task:PENDING/SCHEDULED/RUNNING → FAILED。先查 id 再条件更新,照 StaleTaskRepairService 的写法。 */
private int stopFileTasks(Set<Long> userIds, LocalDateTime now) {
List<FileTaskEntity> active = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.select(FileTaskEntity::getId)
.in(FileTaskEntity::getUserId, userIds)
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
.last("limit " + BATCH_LIMIT));
if (active.isEmpty()) {
return 0;
}
return fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.in(FileTaskEntity::getId, active.stream().map(FileTaskEntity::getId).toList())
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
.set(FileTaskEntity::getStatus, STATUS_FAILED)
.set(FileTaskEntity::getErrorMessage, STOP_REASON)
.set(FileTaskEntity::getFinishedAt, now));
}
}
@@ -0,0 +1,25 @@
package com.nanri.aiimage.modules.task.spi;
import java.util.Collection;
/**
* 账号过期时停止「独立于 biz_file_task 的任务载体」(2026-10-05,G5 同款:task 模块不 import 业务模块)。
*
* <p>{@code ExpiredAccountTaskStopService} 每分钟把过期账号(含级联)名下的 biz_file_task
* 置终态;品牌任务(brand_crawl_tasks)与跟价循环(biz_price_track_loop_run)不在那张表里,
* 由各业务模块实现本 SPI 自行停止——谁的数据谁停,task 侧只发令。</p>
*/
public interface ExpiredAccountTaskStopSpi {
/** 实现负责的模块标识(日志归因用)。 */
String moduleType();
/**
* 把属于这些用户的活跃任务停止。要求幂等:非活跃状态的行一律不动。
*
* @param userIds 过期账号及其级联成员(登录侧会全部拦截,这里只负责在跑的任务)
* @param reason 写进 errorMessage 的统一文案(勿以「客户端异常中断」开头,避免被自动续跑复活)
* @return 实际发生变更的行数(0 = 本轮无事发生,调用方据此决定是否打日志)
*/
int stopActiveTasks(Collection<Long> userIds, String reason);
}
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -23,12 +24,21 @@ public class TaskCenterScopeService {
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
private final CompanyScopeSupport companyScopeSupport;
public ScopeContext resolve(Long operatorId) {
AdminUserEntity operator = requireOperator(operatorId);
if (isSuperAdmin(operator)) {
return new ScopeContext(true, Set.of());
}
if ("company_super_admin".equals(normalizeRole(operator))) {
// 公司超管看本公司全部成员的任务;空公司按 [-1] 兜底,不放大成全量
List<Long> memberIds = companyScopeSupport.memberUserIds(operator.getCompanyId());
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
visibleUserIds.add(operator.getId());
addAll(visibleUserIds, memberIds);
return new ScopeContext(false, Set.copyOf(visibleUserIds));
}
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
visibleUserIds.add(operator.getId());
@@ -63,6 +73,11 @@ public class TaskCenterScopeService {
|| (role.isEmpty() && Integer.valueOf(1).equals(user.getIsAdmin()) && user.getCreatedById() == null);
}
/** 公司超管判定(老数据 role 为空不参与:公司超管是新角色,只认显式取值)。 */
private static String normalizeRole(AdminUserEntity user) {
return user.getRole() == null ? "" : user.getRole().trim().toLowerCase(Locale.ROOT);
}
/**
* @param allUsers 超管直通,不按用户裁剪
* @param visibleUserIds 非超管的可见用户集合(至少含本人)
@@ -0,0 +1,54 @@
-- =============================================================
-- 迁移 V146__users_expires_at_admin_expiry
-- 模板:docs/flyway-migration-template.md
-- 设计:本文件「变更目的」段给口径;判定与停任务的实现分别承载在
-- AccountExpiryService(生效到期=自身∧公司超管∧组长/创建人)与
-- ExpiredAccountTaskStopService(过期账号的在跑任务置终态)的类注释里。
--
-- 1. 变更目的:给 users 加 expires_at(datetime NULL),支撑「管理员到期停用」:
-- - NULL = 永不过期(全部存量账号回填后仍为 NULL,行为零变化);
-- - 管理员(admin)到期 ⇒ 组下普通账户跟着停(级联判定在 AccountExpiryService,落库不改值);
-- - 公司超级管理员(company_super_admin,角色值本身不加列,随本批 Java 代码启用)到期 ⇒ 全公司停;
-- - 到期账号的进行中任务由 ExpiredAccountTaskStopService 扫描置终态(业务表零 DDL)。
-- 只加一列:角色的新取值 company_super_admin 是 users.role 的数据行级取值,不需要 DDL;
-- company 表、columns 表、57 张业务表一律不动。
-- 2. 影响表与数据量:仅 users 一列。生产实查 139+ 行 / data 0.06MB + index 0.03MB 量级。
-- 3. 锁表风险:低。MySQL 8 的 ADD COLUMN(无默认值)走 INSTANT,users 是百行量级。
-- 不碰 biz_task_file_job 等锁热点表。
-- 4. 验证 SQL:见文件末尾「验证」段。
-- 5. 回滚步骤:人工补丁,不写成版本化迁移(那样 Flyway 会在下次启动时自动执行)。
-- 顺序:停两台应用 → 执行
-- ALTER TABLE `users` DROP COLUMN `expires_at`;
-- → 删 flyway_schema_history 里 version='146' 那一行 → 回滚 jar → 起应用。
-- 漏掉删历史那步,将来重装时 Flyway 判定"已应用"而跳过,Java 实体读写 expires_at
-- 会在运行期报 unknown column。丢弃 expires_at 即放弃全部到期设置(本来也只影响新功能)。
-- 6. 上线窗口:随 jar 双节点同窗口发布。加列对旧 jar 无影响(旧代码不认识新列),
-- 混合版本窗口零行为差异;新代码读该列前 Flyway 已保证列存在。
--
-- 【可重跑性】加列前先查 information_schema(照 V143 的条件 DDL 惯例):迁移中途失败时
-- flyway repair + 重启会让 Flyway 从第一条语句重跑整个文件,裸 ADD COLUMN 会撞 1060。
-- =============================================================
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'users'
AND COLUMN_NAME = 'expires_at'
);
SET @ddl := IF(@col_exists = 0,
'ALTER TABLE `users` ADD COLUMN `expires_at` datetime NULL COMMENT ''到期时间(NULL=永不过期)。管理员到期则其组下普通账户与所在公司整体跟随停用,见 AccountExpiryService。super_admin 恒不适用''',
'SELECT ''users.expires_at already exists, skipped'' AS note');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- =============================================================
-- 验证 SQL(迁移后在库上执行)
-- SHOW COLUMNS FROM `users` LIKE 'expires_at';
-- -> 期望 Null = YES、Default = NULL
-- SELECT COUNT(*) AS total, SUM(expires_at IS NOT NULL) AS with_expiry FROM `users`;
-- -> 期望 with_expiry = 0(本迁移只加列,不回填任何到期值)
-- SELECT DISTINCT role FROM `users`;
-- -> 现存取值不变(super_admin / admin / normal);company_super_admin 由建号接口
-- 此后写入,不是本迁移的产物
-- =============================================================
@@ -0,0 +1,210 @@
package com.nanri.aiimage.common.security;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 到期级联判定(V146)口径钉:
* super_admin 永不适用;公司超管到期 → 全公司跟随;管理员到期 → 创建人链上的普通用户跟随;
* 普通用户同时受自身/创建人/组长/公司超管四条约束取最早;库里不改值,全部现算。
*/
class AccountExpiryServiceTest {
private AdminUserMapper adminUserMapper;
private ShopManageGroupMapper groupMapper;
private AccountExpiryService service;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
AdminUserEntity.class);
adminUserMapper = mock(AdminUserMapper.class);
groupMapper = mock(ShopManageGroupMapper.class);
service = new AccountExpiryService(adminUserMapper, groupMapper);
// 默认:无公司超管、无组长、无创建人约束
when(adminUserMapper.selectList(any())).thenReturn(List.of());
when(adminUserMapper.selectById(any(Long.class))).thenReturn(null);
when(groupMapper.selectLeaderIdsByMemberUserId(any())).thenReturn(List.of());
}
// ---------- 基本口径 ----------
@Test
void superAdminNeverExpires() {
assertThat(service.effectiveExpiresAt(entity(1L, "super_admin", null, 1L, past()))).isNull();
}
@Test
void ownExpiryAppliesToAdminDirectly() {
LocalDateTime expiry = LocalDateTime.now().plusDays(3);
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, expiry))).isEqualTo(expiry);
}
@Test
void nullExpiryMeansNeverWithoutSuperiorConstraints() {
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, null))).isNull();
}
// ---------- 公司级联:公司超管到期 → 全公司 ----------
@Test
void companySuperAdminExpiryCapsEveryoneInTheCompany() {
LocalDateTime companyExpiry = LocalDateTime.now().plusDays(2);
AdminUserEntity csa = new AdminUserEntity();
csa.setId(9L);
csa.setRole("company_super_admin");
csa.setExpiresAt(companyExpiry);
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
// 普通用户(自身无到期)被公司超管的到期拉进去
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, null))).isEqualTo(companyExpiry);
// 管理员同样被拉进去
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, null))).isEqualTo(companyExpiry);
}
@Test
void companySuperAdminWithoutExpiryLeavesCompanyUnaffected() {
AdminUserEntity csa = new AdminUserEntity();
csa.setId(9L);
csa.setRole("company_super_admin");
csa.setExpiresAt(null);
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, null))).isNull();
}
@Test
void earliestConstraintWinsOverOwnExpiry() {
LocalDateTime own = LocalDateTime.now().plusDays(10);
LocalDateTime company = LocalDateTime.now().plusDays(1);
AdminUserEntity csa = new AdminUserEntity();
csa.setId(9L);
csa.setRole("company_super_admin");
csa.setExpiresAt(company);
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, own))).isEqualTo(company);
}
// ---------- 组级联:管理员到期 → 名下/组内普通用户 ----------
@Test
void expiredCreatorAdminCascadesToNormalUser() {
LocalDateTime adminExpiry = LocalDateTime.now().plusDays(4);
AdminUserEntity creator = new AdminUserEntity();
creator.setId(2L);
creator.setRole("admin");
creator.setExpiresAt(adminExpiry);
when(adminUserMapper.selectById(2L)).thenReturn(creator);
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 2L, 1L, null))).isEqualTo(adminExpiry);
}
@Test
void expiredGroupLeaderCascadesToGroupMember() {
LocalDateTime leaderExpiry = LocalDateTime.now().plusDays(6);
AdminUserEntity leader = new AdminUserEntity();
leader.setId(5L);
leader.setRole("admin");
leader.setExpiresAt(leaderExpiry);
when(groupMapper.selectLeaderIdsByMemberUserId(3L)).thenReturn(List.of(5L));
when(adminUserMapper.selectById(5L)).thenReturn(leader);
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 8L, 1L, null))).isEqualTo(leaderExpiry);
}
@Test
void normalUserIsNotCascadedByNormalCreator() {
// 创建人自己是普通用户(历史脏数据):不构成组级约束
AdminUserEntity creator = new AdminUserEntity();
creator.setId(8L);
creator.setRole("normal");
creator.setExpiresAt(past());
when(adminUserMapper.selectById(8L)).thenReturn(creator);
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 8L, 1L, null))).isNull();
}
@Test
void adminIsNotCascadedByItsCreatorAdmin() {
// 管理员的上级是公司超管/超管(走公司级),不按"创建人是管理员"级联——否则两家管理员互相锁
AdminUserEntity creator = new AdminUserEntity();
creator.setId(2L);
creator.setRole("admin");
creator.setExpiresAt(past());
when(adminUserMapper.selectById(2L)).thenReturn(creator);
assertThat(service.effectiveExpiresAt(entity(6L, "admin", 2L, 1L, null))).isNull();
}
// ---------- 拦截行为 ----------
@Test
void expiredLoginIsRejectedWithRenewalMessage() {
AccountExpiryService raw = new AccountExpiryService(adminUserMapper, groupMapper);
AdminUserEntity expired = entity(3L, "admin", null, 1L, past());
BusinessException ex = catchThrowableOfType(() -> raw.assertLoginAllowed(expired), BusinessException.class);
assertThat(ex).isNotNull();
assertThat(ex.getMessage()).contains("已过期").contains("续费");
}
@Test
void liveAccountPassesSessionCheck() {
AdminUserEntity live = entity(3L, "admin", null, 1L, LocalDateTime.now().plusDays(9));
assertThatCode(() -> service.assertSessionAllowed(live)).doesNotThrowAnyException();
}
// ---------- 弹窗口径:只看自身 ----------
@Test
void ownDaysToExpireFloorsToWholeDays() {
assertThat(AccountExpiryService.ownDaysToExpire(null)).isNull();
LocalDateTime inSixDays = LocalDateTime.now().plusDays(6);
Long days = AccountExpiryService.ownDaysToExpire(inSixDays);
assertThat(days).isNotNull();
assertThat(days).isBetween(5L, 6L);
// 已过期是负数(调用方按 <5 判展示,登录侧已被 403 拦住,负数不会出现在弹窗里)
assertThat(AccountExpiryService.ownDaysToExpire(past())).isNegative();
}
// ---------- helpers ----------
private static LocalDateTime past() {
return LocalDateTime.now().minusDays(1);
}
private static AdminUserEntity entity(Long id, String role, Long createdById, Long companyId,
LocalDateTime expiresAt) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setUsername("u" + id);
user.setRole(role);
user.setIsAdmin("super_admin".equals(role) || "admin".equals(role)
|| "company_super_admin".equals(role) ? 1 : 0);
user.setCreatedById(createdById);
user.setCompanyId(companyId);
user.setExpiresAt(expiresAt);
return user;
}
}
@@ -29,7 +29,7 @@ class AdminAuthSupportTest {
void explicitLowestIdAdminIsNotPromotedToSuperAdmin() {
AdminUserMapper userMapper = mock(AdminUserMapper.class);
AdminAuthSupport support = new AdminAuthSupport(
mock(JwtService.class), userMapper, mock(AuthProperties.class));
mock(JwtService.class), userMapper, mock(AuthProperties.class), mock(AccountExpiryService.class));
AdminUserEntity user = user(1L, "admin", 1, null);
assertThat(support.currentRole(user)).isEqualTo("admin");
@@ -39,7 +39,8 @@ class AdminAuthSupportTest {
@Test
void legacyBlankRoleRootRemainsSuperAdmin() {
AdminAuthSupport support = new AdminAuthSupport(
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
mock(AccountExpiryService.class));
assertThat(support.currentRole(user(1L, null, 1, null))).isEqualTo("super_admin");
}
@@ -47,7 +48,8 @@ class AdminAuthSupportTest {
@Test
void explicitNormalRoleIsNotPromotedByLegacyAdminFields() {
AdminAuthSupport support = new AdminAuthSupport(
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
mock(AccountExpiryService.class));
assertThat(support.currentRole(user(1L, "normal", 1, null))).isNull();
}
@@ -188,7 +190,8 @@ class AdminAuthSupportTest {
private AdminAuthSupport tokenSupport(String current, String previous, String tokenFile) {
AdminAuthSupport support = new AdminAuthSupport(
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
mock(AccountExpiryService.class));
ReflectionTestUtils.setField(support, "internalToken", current);
ReflectionTestUtils.setField(support, "internalTokenPrevious", previous);
ReflectionTestUtils.setField(support, "internalTokenFile", tokenFile);
@@ -207,7 +210,7 @@ class AdminAuthSupportTest {
when(userMapper.selectById(user.getId())).thenReturn(user);
when(props.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
return new AdminAuthSupport(jwtService, userMapper, props);
return new AdminAuthSupport(jwtService, userMapper, props, mock(AccountExpiryService.class));
}
private HttpServletRequest requestWithBearer(String token) {
@@ -19,6 +19,17 @@ class DeviceSessionPolicyTest {
assertThat(DeviceSessionPolicy.resolveRole("super_admin", 1, 9L)).isEqualTo("super_admin");
}
@Test
void companySuperAdminResolvedWithoutBeingPromotedToSiteAdmin() {
assertThat(DeviceSessionPolicy.resolveRole("company_super_admin", 1, 1L))
.isEqualTo("company_super_admin");
// 大小写/空白容错与既有取值一致
assertThat(DeviceSessionPolicy.resolveRole(" Company_Super_Admin ", 1, 1L))
.isEqualTo("company_super_admin");
// 关键反向钉:公司超管绝不能被顶成站点超管(isSuperAdmin 是单设备豁免+全站判定的入口)
assertThat(DeviceSessionPolicy.isSuperAdmin("company_super_admin", 1, null)).isFalse();
}
@Test
void explicitAdminNotPromotedToSuperAdmin() {
assertThat(DeviceSessionPolicy.resolveRole("admin", 1, null)).isEqualTo("admin");
@@ -295,14 +295,22 @@ class CompanyScopeMigrationV145Test {
}
/**
* 破坏点:回滚被编成 V146(Flyway 扫描路径里的任何 V*.sql 都会在下次启动自动执行),
* 破坏点:回滚被编成版本化迁移(Flyway 扫描路径里的任何 V*.sql 都会在下次启动自动执行),
* 或者回滚脚本没删历史行(重装时 Flyway 判定"已应用"而跳过重建)。
*
* <p>钉的是<b>动作</b>不是号位:这里原本写的是"db/ 里不许出现 V146__ 前缀",而 V146 随后被一条
* 毫不相关的前向迁移(users.expires_at)正常占用,用例便红了。不变的是"回滚不得版本化",
* 所以断言打在剥注释后的可执行 SQL 上:谁在迁移文件里写 flyway_schema_history,谁就是在偷偷自动回滚。</p>
*/
@Test
void rollbackStaysOutOfFlywayScanAndCoversTheHistoryRow() throws IOException {
try (Stream<Path> s = Files.list(DB_DIR)) {
assertTrue(s.noneMatch(p -> p.getFileName().toString().startsWith("V146__")),
"回滚不许编成版本化迁移:V146 会被 Flyway 在下次启动自动执行");
Pattern writesHistoryTable = Pattern.compile(
"\\b(DELETE|UPDATE|INSERT|TRUNCATE|ALTER|DROP)\\b[^;]*\\bflyway_schema_history\\b",
Pattern.CASE_INSENSITIVE);
for (Path file : versionFiles()) {
String executable = normalize(stripComments(raw(file)));
assertFalse(writesHistoryTable.matcher(executable).find(),
"回滚不许编成版本化迁移:" + file.getFileName() + " 的执行段写了 flyway_schema_history");
}
Path rollback = ROOT.resolve("docs/rollback-V145-company-scope.sql");
assertTrue(Files.isRegularFile(rollback), "回滚人工补丁必须存在:" + rollback);
@@ -0,0 +1,111 @@
package com.nanri.aiimage.config;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* V146(users.expires_at,管理员到期停用的数据模型)的文件审计。
* 设计口径见 AccountExpiryService(级联判定)与 ExpiredAccountTaskStopService(过期停任务)的类注释。
*
* <p>本仓 pom 无 H2、无 testcontainers,迁移跑不起来,文件审计是唯一能守住的层——
* 与 {@link CompanyMigrationV144Test} / {@link CompanyScopeMigrationV145Test} 同口径:
* 断言打在剥掉注释后的可执行 SQL 上。</p>
*/
class UsersExpiryMigrationV146Test {
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
// ---------------------------------------------------------------- 取文件
private static Path migration() throws IOException {
List<Path> hits;
try (Stream<Path> s = Files.list(DB_DIR)) {
hits = s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
.filter(p -> p.getFileName().toString().startsWith("V146__"))
.toList();
}
assertFalse(hits.isEmpty(), "缺少 V146__*.sql:users.expires_at 还没落盘");
assertEquals(1, hits.size(), "V146 只允许一个迁移文件(撞号会让 Flyway 启动失败)");
return hits.get(0);
}
private static String rawMigration() throws IOException {
return Files.readString(migration(), StandardCharsets.UTF_8);
}
/** 粗剥离注释后的可执行 SQL(本迁移无字符串内 -- 字面量,简化实现即可,勿复制到含 -- 的迁移)。 */
private static String statements() throws IOException {
String body = rawMigration();
// 防呆:字符串字面量里若出现 "--"(如注释文案),先按行处理会误伤——这里断言它不存在
assertFalse(body.contains("'--"), "字符串字面量内出现 -- 时不能用简化剥离,请改用逐字扫描");
return body.replaceAll("(?m)^\\s*--.*$", "")
.replaceAll("\\s+", " ")
.trim();
}
// ---------------------------------------------------------------- 断言
@Test
void versionIsUniqueAndSequential() throws IOException {
assertEquals("V146__users_expires_at_admin_expiry.sql",
migration().getFileName().toString(), "迁移名与描述须一致");
}
@Test
void headerCarriesTemplateFields() throws IOException {
String head = rawMigration().substring(0, Math.min(2400, rawMigration().length()));
assertTrue(head.contains("变更目的"), "头注释缺「变更目的」");
assertTrue(head.contains("影响表与数据量"), "头注释缺「影响表与数据量」");
assertTrue(head.contains("锁表风险"), "头注释缺「锁表风险」");
assertTrue(head.contains("验证 SQL"), "头注释缺「验证 SQL」");
assertTrue(head.contains("回滚步骤"), "头注释缺「回滚步骤」");
assertTrue(head.contains("上线窗口"), "头注释缺「上线窗口」");
}
@Test
void onlyTouchesUsersTable() throws IOException {
String sql = statements();
assertTrue(sql.contains("ALTER TABLE `users` ADD COLUMN `expires_at`"), "必须给 users 加 expires_at");
// 业务表零 DDL:这条迁移不得 CREATE TABLE / DROP,也不得碰 company / columns
assertFalse(sql.toUpperCase().contains("CREATE TABLE"), "本迁移不应建表");
assertFalse(sql.toUpperCase().contains("DROP "), "本迁移不应删任何对象");
assertFalse(sql.contains("`company`") || sql.contains("`columns`"), "company/columns 不许动");
assertFalse(sql.contains("biz_"), "业务表零 DDL(57 张业务表不许出现在本迁移)");
}
@Test
void addColumnIsConditionalAndRerunnable() throws IOException {
String sql = statements();
assertTrue(sql.contains("information_schema.COLUMNS"), "加列前必须查 information_schema(可重跑性)");
assertTrue(sql.contains("PREPARE stmt FROM @ddl"), "条件 DDL 要走 PREPARE");
assertTrue(sql.contains("DEALLOCATE PREPARE stmt"), "PREPARE 之后必须 DEALLOCATE");
assertTrue(sql.contains("already exists"), "列已存在时要有跳过分支(flyway repair 重跑不撞 1060)");
}
@Test
void columnIsNullableWithoutDefault() throws IOException {
String sql = statements();
assertTrue(sql.contains("datetime NULL"), "expires_at 必须可空且无默认值:NULL=永不过期");
assertFalse(sql.contains("NOT NULL"), "不许 NOT NULL:全部存量账号必须保持永不过期");
}
@Test
void shipsVerificationSql() throws IOException {
String sql = rawMigration();
assertTrue(sql.contains("SHOW COLUMNS FROM `users` LIKE 'expires_at'"), "验证段要能核对列存在性");
assertTrue(sql.contains("with_expiry"), "验证段要断言没有任何存量回填(with_expiry = 0)");
}
}
@@ -100,4 +100,32 @@ class AdminConsoleCurrentUserCompanyTest {
.containsEntry("companyName", "")
.containsEntry("username", "op");
}
/**
* 续费提醒弹窗(V146)的数据源:admin-frontend-vue 的 {@code components/ExpiryNotice.vue}
* 直接读 store 里 user 的 {@code daysToExpire/expiresAt},没有映射层也没有本地兜底计算。
* 键名拼错或格式化改了,表现是「快到期了界面一声不响」——不报错,只能由用例盯着。
*/
@Test
@DisplayName("current-user 带 expiresAt(yyyy-MM-dd HH:mm)与 daysToExpire(floor 整天)")
void currentUserCarriesExpiryFieldsForTheRenewalNotice() {
operator.setExpiresAt(java.time.LocalDateTime.now().plusDays(4).plusHours(12));
assertThat(item())
.containsKeys("expiresAt", "daysToExpire")
.containsEntry("daysToExpire", 4L);
assertThat((String) item().get("expiresAt"))
.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}");
}
@Test
@DisplayName("永不过期的账号:两个键照样写、值为 null,前端按 null 一律不弹")
void accountWithoutExpiryStillWritesBothKeysAsNull() {
operator.setExpiresAt(null);
assertThat(item())
.containsKeys("expiresAt", "daysToExpire")
.containsEntry("expiresAt", null)
.containsEntry("daysToExpire", null);
}
}
@@ -0,0 +1,251 @@
package com.nanri.aiimage.modules.admin.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 公司超级管理员角色(2026-10-05)与管理员到期设置(V146)的服务层口径钉。
* 镜像 Java 约束:公司超管由站点超管开设;公司超管可在本公司建管理员/普通账号;
* 到期时间谁可编辑目标就谁可设置,格式不对必须报错而不是静默归「永不过期」。
*/
class AdminUserServiceCompanySuperAdminTest {
private AdminUserMapper userMapper;
private WerkzeugPasswordEncoder passwordEncoder;
private AdminAuthSupport authSupport;
private PermissionMenuService permissionService;
private CompanyService companyService;
private AdminUserService service;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
AdminUserEntity.class);
userMapper = mock(AdminUserMapper.class);
passwordEncoder = mock(WerkzeugPasswordEncoder.class);
authSupport = mock(AdminAuthSupport.class);
permissionService = mock(PermissionMenuService.class);
companyService = mock(CompanyService.class);
service = new AdminUserService(userMapper, passwordEncoder, authSupport, permissionService,
mock(UserApiSecretService.class), companyService);
when(passwordEncoder.hash(any())).thenReturn("hashed");
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
}
// ---------- 建号 ----------
@Test
void superAdminCreatesCompanySuperAdminInTargetCompanyWithExpiry() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("boss-b");
request.setPassword("secret1");
request.setRole("company_super_admin");
request.setCompanyId(2L);
request.setExpiresAt("2026-12-31 23:59");
when(authSupport.currentRole(operator)).thenReturn("super_admin");
service.createUser(operator, request);
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
verify(userMapper).insert(captor.capture());
AdminUserEntity saved = captor.getValue();
assertThat(saved.getRole()).isEqualTo("company_super_admin");
assertThat(saved.getIsAdmin()).isEqualTo(1);
assertThat(saved.getCompanyId()).isEqualTo(2L);
assertThat(saved.getCreatedById()).isEqualTo(1L);
assertThat(saved.getExpiresAt()).isEqualTo(LocalDateTime.of(2026, 12, 31, 23, 59));
verify(companyService).requireActive(2L);
}
@Test
void companySuperAdminCreatesAdminInOwnCompany() {
// helper 签名:user(id, role, companyId, createdById) —— 公司超管挂公司 2
AdminUserEntity operator = user(9L, "company_super_admin", 2L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("team-lead");
request.setPassword("secret1");
request.setRole("admin");
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
service.createUser(operator, request);
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
verify(userMapper).insert(captor.capture());
assertThat(captor.getValue().getRole()).isEqualTo("admin");
assertThat(captor.getValue().getCompanyId()).isEqualTo(2L);
assertThat(captor.getValue().getCreatedById()).isEqualTo(9L);
}
@Test
void plainAdminStillCannotCreateAdmin() {
AdminUserEntity operator = user(10L, "admin", 1L, 1L);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("someone");
request.setPassword("secret1");
request.setRole("admin");
when(authSupport.currentRole(operator)).thenReturn("admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("公司超级管理员")
.hasMessageContaining("管理员");
}
@Test
void companySuperAdminCannotMintAnotherCompanySuperAdmin() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("rival-boss");
request.setPassword("secret1");
request.setRole("company_super_admin");
request.setCompanyId(3L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以创建公司超级管理员");
}
@Test
void badExpiryFormatIsRejectedLoudly() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("someone");
request.setPassword("secret1");
request.setRole("admin");
request.setExpiresAt("12/31/2026");
when(authSupport.currentRole(operator)).thenReturn("super_admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("到期时间格式不正确");
}
// ---------- 列表 ----------
@Test
void companySuperAdminListsOwnCompanyWithoutSiteSuperAdmin() {
AdminUserEntity operator = user(9L, "company_super_admin", 2L, null);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectCount(any())).thenReturn(0L);
when(userMapper.selectList(any())).thenReturn(List.of());
service.listUsers(operator, 1, 15, null, null, null, null);
ArgumentCaptor<LambdaQueryWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(userMapper).selectCount(captor.capture());
// 先碰一次 SqlSegment 才会铺出参数(MP 惯例)
captor.getValue().getSqlSegment();
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(2L);
}
// ---------- 编辑 ----------
@Test
void siteSuperAdminRenewsCompanySuperAdminExpiryWithoutTouchingRole() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setExpiresAt("2027-01-31 00:00");
service.updateUser(operator, 9L, request);
ArgumentCaptor<LambdaUpdateWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(userMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
String sqlSet = captor.getValue().getSqlSet();
assertThat(sqlSet).contains("expires_at");
assertThat(sqlSet).doesNotContain("role");
assertThat(sqlSet).doesNotContain("is_admin");
}
@Test
void clearingExpiryWritesNull() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setExpiresAt("");
service.updateUser(operator, 9L, request);
ArgumentCaptor<LambdaUpdateWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(userMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
assertThat(captor.getValue().getSqlSet()).contains("expires_at");
}
@Test
void companySuperAdminCannotEditCompanySuperAdminTarget() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserEntity target = user(11L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setPassword("secret1");
assertThatThrownBy(() -> service.updateUser(operator, 11L, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以修改公司超级管理员");
}
@Test
void companySuperAdminCannotDeleteCompanySuperAdminTarget() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserEntity target = user(11L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
assertThatThrownBy(() -> service.deleteUser(operator, 11L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以删除公司超级管理员");
}
// ---------- helpers ----------
private static AdminUserEntity user(Long id, String role, Long companyId, Long createdById) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setUsername("u" + id);
user.setRole(role);
user.setIsAdmin(1);
user.setCompanyId(companyId);
user.setCreatedById(createdById);
return user;
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.common.security.JwtService;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
@@ -57,7 +58,8 @@ class AuthServiceCompanyTest {
when(authProperties.isSingleDeviceEnabled()).thenReturn(false);
when(jwtService.ttlSeconds()).thenReturn(604800L);
service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
mock(PermissionMenuService.class), authProperties, companyService);
mock(PermissionMenuService.class), authProperties, companyService,
mock(AccountExpiryService.class));
}
private LoginUserEntity user(Long companyId) {
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
@@ -158,7 +159,8 @@ class AuthServiceTest {
when(authProperties.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
when(jwtService.ttlSeconds()).thenReturn(604800L);
AuthService service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
permissionMenuService, authProperties, mock(CompanyService.class));
permissionMenuService, authProperties, mock(CompanyService.class),
mock(AccountExpiryService.class));
return new Fixture(service, loginUserMapper, passwordEncoder, jwtService);
}
@@ -0,0 +1,165 @@
package com.nanri.aiimage.modules.brand.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
import com.nanri.aiimage.modules.task.service.ExpiredAccountTaskStopService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 品牌采集任务的「过期即停」实现口径钉(V146 的 SPI 一侧)。
*
* <p>巡检主类那份用例只用了假 SPI,所以这里补真实现的两条边界:
* <b>该圈的圈到</b>——只有这批用户名下 pending/running 的行进入 SELECT 与 UPDATE;
* <b>不该碰的不碰</b>——已完成的行不得被改写(UPDATE 的 WHERE 二次核对状态,抢到行后状态被
* 客户端推进也不会误杀),且只写 status/error_message 两列,不碰结果与进度。</p>
*/
class BrandTaskExpiredStopSpiImplTest {
private static final String REASON = ExpiredAccountTaskStopService.STOP_REASON;
private static final Pattern WHERE_PARAM = Pattern.compile("#\\{ew\\.paramNameValuePairs\\.(\\w+)}");
private BrandCrawlTaskMapper mapper;
private BrandTaskExpiredStopSpiImpl spi;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
BrandCrawlTaskEntity.class);
mapper = mock(BrandCrawlTaskMapper.class);
spi = new BrandTaskExpiredStopSpiImpl(mapper);
}
@Test
@DisplayName("moduleType 固定 BRAND:巡检日志按它归因,改名等于丢掉归因")
void moduleTypeIsTheBrandKey() {
assertThat(spi.moduleType()).isEqualTo("BRAND");
}
@Test
@DisplayName("没有过期用户:不查也不写(null 与空集一样短路)")
void emptyUserScopeTouchesNothing() {
assertThat(spi.stopActiveTasks(List.of(), REASON)).isZero();
assertThat(spi.stopActiveTasks(null, REASON)).isZero();
verifyNoInteractions(mapper);
}
@Test
@DisplayName("SELECT 只圈这批用户名下的 pending/running,且带批量上限")
void selectionIsScopedToTheseUsersAndOnlyActiveStates() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L), brandTask(12L)));
when(mapper.update(any(), any())).thenReturn(2);
spi.stopActiveTasks(List.of(7L, 8L), REASON);
LambdaQueryWrapper<BrandCrawlTaskEntity> query = captureQuery();
assertThat(query.getSqlSegment()).contains("user_id").contains("status").contains("limit 500");
assertThat(query.getParamNameValuePairs().values())
.contains(7L, 8L, "pending", "running");
// 已完成/已取消的状态不许进集合:否则过期巡检会把历史行刷成 cancelled
assertThat(query.getParamNameValuePairs().values())
.doesNotContain("success", "completed", "failed", "cancelled");
}
@Test
@DisplayName("UPDATE 按 id 收口并二次核对 pending/running,SET 只写 status/error_message")
void updateCancelsOnlyRowsStillActiveAndWritesOnlyTwoColumns() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L)));
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
LambdaUpdateWrapper<BrandCrawlTaskEntity> update = captureUpdate();
assertThat(update.getSqlSet()).contains("status").contains("error_message")
.doesNotContain("result_paths", "progress_current", "progress_total", "user_id");
assertThat(update.getParamNameValuePairs().values())
.contains("cancelled", REASON);
List<Object> where = whereValues(update);
assertThat(where).contains("pending", "running");
// WHERE 里出现 cancelled/success 意味着"把已终态的行再刷一遍",行数与归因都会失真
assertThat(where).doesNotContain("cancelled", "success", "completed", "failed");
assertThat(update.getSqlSegment()).contains("id").contains("status");
}
@Test
@DisplayName("停止原因照原样透传:不得以「客户端异常中断」开头,否则被自动续跑复活")
void reasonIsPassedThroughUnchangedAndStaysNonResumable() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L)));
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
assertThat(captureUpdate().getParamNameValuePairs().values()).contains(REASON);
assertThat(REASON).doesNotStartWith("客户端异常中断");
}
@Test
@DisplayName("名下没有活跃品牌任务:零写库、返回 0(巡检据此决定打不打日志)")
void nothingActiveMeansNoUpdateAndZero() {
when(mapper.selectList(any())).thenReturn(List.of());
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isZero();
org.mockito.Mockito.verify(mapper, org.mockito.Mockito.never()).update(any(), any());
}
@Test
@DisplayName("返回值 = mapper 实际影响行数,供巡检汇总")
void affectedRowsComeBackFromMapper() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(1L), brandTask(2L), brandTask(3L)));
when(mapper.update(any(), any())).thenReturn(3);
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isEqualTo(3);
}
// ---------- helpers ----------
private static BrandCrawlTaskEntity brandTask(Long id) {
BrandCrawlTaskEntity task = new BrandCrawlTaskEntity();
task.setId(id);
return task;
}
@SuppressWarnings("unchecked")
private LambdaQueryWrapper<BrandCrawlTaskEntity> captureQuery() {
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(mapper).selectList(captor.capture());
return captor.getValue();
}
@SuppressWarnings("unchecked")
private LambdaUpdateWrapper<BrandCrawlTaskEntity> captureUpdate() {
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(mapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
return captor.getValue();
}
/** 只取 WHERE 段引用的参数值:SET 侧的值也躺在同一个 paramNameValuePairs 里,整表断言分不开两侧。 */
private static List<Object> whereValues(LambdaUpdateWrapper<BrandCrawlTaskEntity> wrapper) {
List<Object> values = new ArrayList<>();
Matcher matcher = WHERE_PARAM.matcher(wrapper.getSqlSegment());
while (matcher.find()) {
values.add(wrapper.getParamNameValuePairs().get(matcher.group(1)));
}
assertThat(values).as("WHERE 段没解析到任何参数=正则或 MP 占位符格式变了,本用例断言恒真").isNotEmpty();
return values;
}
}
@@ -0,0 +1,126 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackLoopRunMapper;
import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackLoopRunEntity;
import com.nanri.aiimage.modules.task.service.ExpiredAccountTaskStopService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 跟价循环的「过期即停」实现口径钉(V146 的 SPI 一侧)。
*
* <p>这条的实现刻意<b>不</b>直接落终态:只把 stop_requested 置 1,走用户点「停止循环」那条收尾路径,
* 循环自己在下一个派发点落 STOPPED。所以本用例集最要紧的两条是——
* status 一列不许出现在 SET 里(否则在跑的子任务的收尾会被打断),
* 以及已停止/已完成的循环(stop_requested 已为 1,或状态不是 RUNNING)不得被再次圈进 WHERE。</p>
*/
class PriceTrackLoopExpiredStopSpiImplTest {
private static final String REASON = ExpiredAccountTaskStopService.STOP_REASON;
private static final Pattern WHERE_PARAM = Pattern.compile("#\\{ew\\.paramNameValuePairs\\.(\\w+)}");
private PriceTrackLoopRunMapper mapper;
private PriceTrackLoopExpiredStopSpiImpl spi;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
PriceTrackLoopRunEntity.class);
mapper = mock(PriceTrackLoopRunMapper.class);
spi = new PriceTrackLoopExpiredStopSpiImpl(mapper);
}
@Test
@DisplayName("moduleType 固定 PRICE_TRACK_LOOP:巡检日志按它归因")
void moduleTypeIsTheLoopKey() {
assertThat(spi.moduleType()).isEqualTo("PRICE_TRACK_LOOP");
}
@Test
@DisplayName("没有过期用户:一条 UPDATE 都不发(null 与空集一样短路)")
void emptyUserScopeWritesNothing() {
assertThat(spi.stopActiveTasks(List.of(), REASON)).isZero();
assertThat(spi.stopActiveTasks(null, REASON)).isZero();
verifyNoInteractions(mapper);
}
@Test
@DisplayName("只圈这批用户「RUNNING 且还没请求停止」的循环")
void predicateIsRunningAndStopNotRequestedYet() {
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L, 8L), REASON);
LambdaUpdateWrapper<PriceTrackLoopRunEntity> update = captureUpdate();
assertThat(update.getSqlSegment()).contains("user_id").contains("status").contains("stop_requested");
List<Object> where = whereValues(update);
assertThat(where).contains("RUNNING", false);
// 用户收口必须真的进 WHERE:换成 isNotNull(user_id) 时列名照样在、谓词值也照样在,
// 只断上面两条抓不到——那是一条把「停这批过期账号」写成「停全站 RUNNING 循环」的路径。
assertThat(where).contains(7L, 8L);
// 已请求停止/已结束的循环再刷一次=幂等性破了,也会把巡检的计数虚高
assertThat(where).doesNotContain("STOPPED", "SUCCESS", "FAILED", "CANCELLED", true);
}
@Test
@DisplayName("SET 只写 stop_requested:status 一列由收尾路径自己落")
void setWritesOnlyTheStopRequestFlag() {
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
LambdaUpdateWrapper<PriceTrackLoopRunEntity> update = captureUpdate();
assertThat(update.getSqlSet()).contains("stop_requested");
assertThat(update.getSqlSet()).doesNotContain("status", "error_message", "finished_at", "current_round");
assertThat(update.getParamNameValuePairs().values()).containsExactly(true);
}
@Test
@DisplayName("返回值 = mapper 实际影响行数;零行时不谎报")
void affectedRowsComeBackFromMapper() {
when(mapper.update(any(), any())).thenReturn(4);
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isEqualTo(4);
when(mapper.update(any(), any())).thenReturn(0);
assertThat(spi.stopActiveTasks(List.of(9L), REASON)).isZero();
}
// ---------- helpers ----------
@SuppressWarnings("unchecked")
private LambdaUpdateWrapper<PriceTrackLoopRunEntity> captureUpdate() {
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(mapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
return captor.getValue();
}
/** 只取 WHERE 段引用的参数值:SET 侧的值也躺在同一个 paramNameValuePairs 里,整表断言分不开两侧。 */
private static List<Object> whereValues(LambdaUpdateWrapper<PriceTrackLoopRunEntity> wrapper) {
List<Object> values = new ArrayList<>();
Matcher matcher = WHERE_PARAM.matcher(wrapper.getSqlSegment());
while (matcher.find()) {
values.add(wrapper.getParamNameValuePairs().get(matcher.group(1)));
}
assertThat(values).as("WHERE 段没解析到任何参数=正则或 MP 占位符格式变了,本用例断言恒真").isNotEmpty();
return values;
}
}
@@ -0,0 +1,182 @@
package com.nanri.aiimage.modules.task.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 过期停任务巡检(V146)口径钉:
* 边界账号(expires_at ≤ now 且非超管)→ 级联成员集合与登录侧一致;
* biz_file_task 的 PENDING/SCHEDULED/RUNNING 全部置终态(PENDING 也要,防内部通道继续派发);
* 置终态原因绝不以「客户端异常中断」开头(否则被 TaskResumeService 自动复活);
* SPI 由业务模块各自实现,一个用户都没有时全链路零写库。
*/
class ExpiredAccountTaskStopServiceTest {
private AdminUserMapper adminUserMapper;
private ShopManageGroupMapper groupMapper;
private CompanyScopeSupport companyScopeSupport;
private FileTaskMapper fileTaskMapper;
private DistributedJobLockService jobLockService;
private RecordingSpi spi;
private ExpiredAccountTaskStopService service;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
AdminUserEntity.class);
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
FileTaskEntity.class);
adminUserMapper = mock(AdminUserMapper.class);
groupMapper = mock(ShopManageGroupMapper.class);
companyScopeSupport = mock(CompanyScopeSupport.class);
fileTaskMapper = mock(FileTaskMapper.class);
jobLockService = mock(DistributedJobLockService.class);
when(jobLockService.tryLock(anyString(), any()))
.thenReturn(mock(DistributedJobLockService.LockHandle.class));
when(adminUserMapper.selectList(any())).thenReturn(List.of());
when(groupMapper.selectManagedMemberUserIds(any())).thenReturn(List.of());
spi = new RecordingSpi();
service = new ExpiredAccountTaskStopService(adminUserMapper, groupMapper, companyScopeSupport,
fileTaskMapper, jobLockService, List.of(spi));
}
@Test
void noExpiredAccountsMeansZeroWrites() {
service.runOnce();
verify(fileTaskMapper, never()).update(any(), any());
assertThat(spi.calls).isZero();
}
@Test
void expiredAdminCollectsCreatedNormalsAndGroupMembers() {
AdminUserEntity admin = boundary(2L, "admin");
AdminUserEntity createdNormal = new AdminUserEntity();
createdNormal.setId(30L);
// 第一次调用是边界扫描(返回过期的管理员),第二次是「名下子账户」查询
AtomicInteger call = new AtomicInteger();
when(adminUserMapper.selectList(any())).thenAnswer(inv -> {
int n = call.incrementAndGet();
return n == 1 ? List.of(admin) : List.of(createdNormal);
});
when(groupMapper.selectManagedMemberUserIds(2L)).thenReturn(List.of(31L));
when(fileTaskMapper.selectList(any())).thenReturn(List.of(fileTask(11L)));
when(fileTaskMapper.update(any(), any())).thenReturn(1);
service.runOnce();
assertThat(spi.lastUserIds).containsExactlyInAnyOrder(2L, 30L, 31L);
verify(fileTaskMapper).update(any(), any());
}
@Test
void expiredCompanySuperAdminCollectsWholeCompany() {
AdminUserEntity csa = boundary(9L, "company_super_admin");
csa.setCompanyId(2L);
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
when(companyScopeSupport.memberUserIds(2L)).thenReturn(List.of(101L, 102L));
when(fileTaskMapper.selectList(any())).thenReturn(List.of());
service.runOnce();
assertThat(spi.lastUserIds).containsExactlyInAnyOrder(9L, 101L, 102L);
}
@Test
void fileTaskUpdateCarriesTerminalStateWithNonResumeReason() {
AdminUserEntity admin = boundary(2L, "admin");
when(adminUserMapper.selectList(any())).thenReturn(List.of(admin));
when(fileTaskMapper.selectList(any())).thenReturn(List.of(fileTask(11L)));
when(fileTaskMapper.update(any(), any())).thenReturn(1);
service.runOnce();
var wrapperCaptor = org.mockito.ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(), wrapperCaptor.capture());
LambdaUpdateWrapper<FileTaskEntity> wrapper = wrapperCaptor.getValue();
// SET 子句在 getSqlSet()(只有列名=占位符),写入值在参数表里——两边一起断
String sqlSet = wrapper.getSqlSet();
assertThat(sqlSet).contains("status").contains("error_message").contains("finished_at");
// WHERE 条件更新钉住状态集合(user_id 在 SELECT 侧过滤、UPDATE 按 id 收口),
// 避免并发下把刚续跑的新任务误杀
String where = wrapper.getSqlSegment();
assertThat(where).contains("status").contains("id IN");
Collection<Object> params = wrapper.getParamNameValuePairs().values();
assertThat(params).contains("FAILED", "PENDING", "SCHEDULED", "RUNNING",
ExpiredAccountTaskStopService.STOP_REASON);
// 原因文案绝不以「客户端异常中断」开头,否则会被 TaskResumeService 自动续跑复活
assertThat(ExpiredAccountTaskStopService.STOP_REASON).doesNotStartWith("客户端异常中断");
}
@Test
void nothingActiveLeavesModuleSpisWithoutWorkButStillNotified() {
// file_task 全是终态 → fileTaskMapper.update 不发生;SPI 仍会被询问一次(幂等、0 行)
AdminUserEntity admin = boundary(2L, "admin");
when(adminUserMapper.selectList(any())).thenReturn(List.of(admin));
when(fileTaskMapper.selectList(any())).thenReturn(List.of());
service.runOnce();
verify(fileTaskMapper, never()).update(any(), any());
assertThat(spi.calls).isEqualTo(1);
assertThat(spi.lastUserIds).containsExactly(2L);
}
// ---------- helpers ----------
private static AdminUserEntity boundary(Long id, String role) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setRole(role);
user.setCompanyId(1L);
user.setExpiresAt(LocalDateTime.now().minusMinutes(1));
return user;
}
private static FileTaskEntity fileTask(Long id) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
return task;
}
private static final class RecordingSpi implements ExpiredAccountTaskStopSpi {
private int calls;
private Collection<Long> lastUserIds = List.of();
@Override
public String moduleType() {
return "RECORDING";
}
@Override
public int stopActiveTasks(Collection<Long> userIds, String reason) {
calls++;
lastUserIds = userIds == null ? List.of() : List.copyOf(userIds);
return 0;
}
}
}
+2
View File
@@ -1,6 +1,7 @@
<template>
<el-config-provider :locale="zhCn">
<router-view />
<ExpiryNotice />
</el-config-provider>
</template>
@@ -11,4 +12,5 @@
// app.use(ElementPlus, { locale }) 全局注入,改由 ConfigProvider 提供;
// 否则分页/日期选择器/上传等组件的内置文案会退回英文。
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import ExpiryNotice from '@/shared/components/ExpiryNotice.vue'
</script>
@@ -113,6 +113,7 @@ import { useRouter } from 'vue-router'
import { loginWithDevice } from '@/shared/api/user'
import { KICK_NOTICE_KEY } from '@/shared/auth/kick-handler'
import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/company-identity'
import { clearAccountExpiry, writeAccountExpiry } from '@/shared/auth/account-expiry'
import { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
@@ -435,6 +436,8 @@ async function submitLogin() {
}
// 公司名随后端可选返回:没有就删键,顶栏不显示该段(见 shared/auth/company-identity)
writeCompanyIdentity(data)
// 到期时间随后端可选返回:没有就删键(续费提醒弹窗的数据源,见 shared/auth/account-expiry)
writeAccountExpiry(data)
// 登录成功即持久化记住/自动登录凭据(桌面与网页均可,密码 AES 加密落 localStorage)
void saveCredentials(account)
// 桌面端 Flask cookie 同步已随瘦身下线:登录态只存 localStorage(JWT 走 Bearer),无 cookie 依赖
@@ -457,6 +460,7 @@ onMounted(() => {
window.localStorage.removeItem('uid')
window.localStorage.removeItem('username')
window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY)
clearAccountExpiry()
} catch {
/* 忽略 */
}
+2
View File
@@ -20,6 +20,8 @@ export interface LoginData {
/** 所属公司(company.id,V143 新增;旧 jar 不返回该字段) */
companyId?: number | string
companyName?: string
/** 自身账号到期时间(yyyy-MM-dd HH:mm,V146);缺省 = 永不过期,续费提醒用 */
expiresAt?: string
[key: string]: unknown
}
@@ -0,0 +1,66 @@
/**
* 用户端账号到期信息(V146,2026-10-05)
*
* app-web 无 Pinia,登录态走 localStorage;到期时间同理:登录 / check_login 的 data 里带
* expiresAt(yyyy-MM-dd HH:mm)就落键,没有就删键——换账号登录时不能残留上一个账号的到期值。
* 只反映账号自身 expires_at(续费提醒用),级联停用判定全部在服务端,这里不做任何本地推断。
*/
export const ACCOUNT_EXPIRY_STORAGE_KEY = 'account_expires_at'
function storage(): Storage | null {
if (typeof window === 'undefined') return null
try {
return window.localStorage
} catch {
return null
}
}
/** 从登录/check_login 的 data 段落到期时间;缺字段或空白一律清键(= 永不过期/未知)。 */
export function writeAccountExpiry(data: unknown): void {
const db = storage()
if (!db) return
const raw =
data && typeof data === 'object'
? (data as { expiresAt?: unknown; expires_at?: unknown }).expiresAt ??
(data as { expires_at?: unknown }).expires_at
: undefined
const value = typeof raw === 'string' ? raw.trim() : ''
if (value) db.setItem(ACCOUNT_EXPIRY_STORAGE_KEY, value)
else db.removeItem(ACCOUNT_EXPIRY_STORAGE_KEY)
}
/** 当前账号到期时间字符串(yyyy-MM-dd HH:mm);无到期/未知返回空串。 */
export function readAccountExpiry(): string {
const db = storage()
if (!db) return ''
try {
return (db.getItem(ACCOUNT_EXPIRY_STORAGE_KEY) || '').trim()
} catch {
return ''
}
}
/** 登出/切号/被顶下线时清键。 */
export function clearAccountExpiry(): void {
const db = storage()
if (!db) return
try {
db.removeItem(ACCOUNT_EXPIRY_STORAGE_KEY)
} catch {
/* 忽略 */
}
}
/**
* 距到期还剩整天数(floor);无到期返回 null,已过期返回负数。
* 续费提醒按 0 ≤ days < 5 判定(剩余不足 5 天开始提醒,续到 ≥5 天消失)。
*/
export function daysToAccountExpiry(): number | null {
const raw = readAccountExpiry()
if (!raw) return null
const parsed = new Date(raw.replace(' ', 'T'))
if (Number.isNaN(parsed.getTime())) return null
return Math.floor((parsed.getTime() - Date.now()) / 86400_000)
}
@@ -10,6 +10,7 @@
import { get } from '@/shared/api/http'
import { writeCompanyIdentity } from './company-identity'
import { writeAccountExpiry } from './account-expiry'
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
const UID_KEY = 'uid'
@@ -42,6 +43,7 @@ export async function ensureAuth(): Promise<boolean> {
window.localStorage.setItem('username', String(response.data.username))
}
writeCompanyIdentity(response.data)
writeAccountExpiry(response.data)
return true
} catch {
// token 失效:清掉本地登录态(跳转交给路由守卫)
@@ -79,6 +81,7 @@ export async function restoreLoginUser(): Promise<{ username?: string } | null>
window.localStorage.setItem('username', String(response.data.username))
}
writeCompanyIdentity(response.data)
writeAccountExpiry(response.data)
return { username: response.data.username }
} catch {
return null
@@ -9,6 +9,7 @@
*/
import { COMPANY_NAME_STORAGE_KEY } from './company-identity.ts'
import { ACCOUNT_EXPIRY_STORAGE_KEY } from './account-expiry.ts'
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
const UID_KEY = 'uid'
@@ -72,6 +73,7 @@ export function handleKicked(): void {
storage.removeItem(UID_KEY)
storage.removeItem(USERNAME_KEY)
storage.removeItem(COMPANY_NAME_STORAGE_KEY)
storage.removeItem(ACCOUNT_EXPIRY_STORAGE_KEY)
storage.setItem(AUTO_LOGIN_KEY, '0')
storage.setItem(KICK_NOTICE_KEY, '1')
} catch {
@@ -0,0 +1,153 @@
<script setup lang="ts">
/**
* 用户端到期续费提醒(V146,2026-10-05 需求):
* 「管理员快过期的时候(仅剩 5 天不到开始)要在数富界面上有个弹窗去提醒,
* 只能缩小但是不能关闭,直到续费超过 5 天才消失。」
*
* - 数据源:localStorage 的 account_expires_at(登录/check_login 落键,见 shared/auth/account-expiry);
* 只反映账号自身 expires_at,级联停用判定全部在服务端。
* - 触发:0 ≤ 剩余天数 < 5。刷新页面按当前时间重算;续费到 ≥5 天自动消失。
* - 只能缩小不能关闭:无关闭按钮;缩小态是右下角常驻浮标,点开即恢复。
* - 未登录(无 uid)不渲染。
*/
import { computed, onUnmounted, ref } from 'vue'
import { daysToAccountExpiry, readAccountExpiry } from '@/shared/auth/account-expiry'
const props = defineProps<{
/** 展示阈值(天):剩余天数 < EXPIRY_NOTICE_DAYS 时展示。需求口径 = 5(不足 5 天)。 */
threshold?: number
}>()
const THRESHOLD = props.threshold ?? 5
const uid = typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '' : ''
const expiresAt = ref(readAccountExpiry())
// 剩余天数随时间流逝而变小:每分钟重算一次(页面常开也会在跨过阈值时出现提醒)
const now = ref(Date.now())
const timer = typeof window !== 'undefined' ? window.setInterval(() => { now.value = Date.now() }, 60_000) : null
onUnmounted(() => {
if (timer !== null) window.clearInterval(timer)
})
const days = computed(() => {
const raw = expiresAt.value
if (!raw) return null
const parsed = new Date(raw.replace(' ', 'T'))
if (Number.isNaN(parsed.getTime())) return null
return Math.floor((parsed.getTime() - now.value) / 86400_000)
})
const visible = computed(() => Boolean(uid) && days.value !== null && days.value >= 0 && days.value < THRESHOLD)
const minimized = ref(false)
const minimizedKey = computed(() => `expiry-notice-min:${uid}:${expiresAt.value}`)
if (typeof window !== 'undefined') {
minimized.value = window.localStorage.getItem(minimizedKey.value) === '1'
}
function minimize(): void {
minimized.value = true
try {
window.localStorage.setItem(minimizedKey.value, '1')
} catch {
/* localStorage 不可用时仅本次会话生效 */
}
}
function restore(): void {
minimized.value = false
try {
window.localStorage.removeItem(minimizedKey.value)
} catch {
/* 同上 */
}
}
const daysText = computed(() => {
const value = days.value
if (value === null) return ''
return value <= 0 ? '不足 1 天' : `还剩 ${value} 天`
})
</script>
<template>
<template v-if="visible">
<div v-if="!minimized" class="expiry-notice" role="alert" aria-live="assertive">
<div class="expiry-notice-body">
<strong>服务即将到期</strong>
<span>
您的账号{{ expiresAt ? `(${expiresAt})` : '' }}即将到期,{{ daysText }}。
到期后账号将无法登录,名下账号与正在执行的任务也会一并停止,请联系管理员续费。
</span>
</div>
<button class="expiry-notice-min" type="button" title="收起(不可关闭,续费前会一直提醒)" @click="minimize">
收起
</button>
</div>
<button
v-else
class="expiry-notice-chip"
type="button"
:title="`服务即将到期:${daysText},点击展开`"
@click="restore"
>
⏰ {{ daysText }}
</button>
</template>
</template>
<style scoped>
.expiry-notice {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 3000;
display: flex;
align-items: center;
gap: 12px;
max-width: 420px;
padding: 14px 16px;
border: 1px solid #e4b363;
border-radius: 12px;
background: #fffaf0;
color: #7a4d0b;
box-shadow: 0 12px 32px -18px rgba(122, 77, 11, 0.55);
}
.expiry-notice-body {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 13px;
line-height: 1.55;
}
.expiry-notice-body strong {
font-size: 14px;
}
.expiry-notice-min {
flex-shrink: 0;
padding: 6px 12px;
border: 1px solid #e4b363;
border-radius: 8px;
background: #ffffff;
color: #7a4d0b;
font-size: 12.5px;
cursor: pointer;
}
.expiry-notice-min:hover {
background: #fdf3dd;
}
.expiry-notice-chip {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 3000;
padding: 8px 14px;
border: 1px solid #e4b363;
border-radius: 999px;
background: #fffaf0;
color: #7a4d0b;
font-size: 13px;
cursor: pointer;
box-shadow: 0 8px 20px -12px rgba(122, 77, 11, 0.5);
}
</style>
+201
View File
@@ -0,0 +1,201 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
/**
* 用户端(app-web / 桌面壳内页)「服务即将到期」续费提醒护栏(V146,2026-10-05 需求)。
*
* 需求原话:仅剩不到 5 天开始提醒、只能缩小不能关闭、续费到超过 5 天才消失。
* 用户端与后台不同:后端只在登录/check_login 时下发 expiresAt,剩余天数由页面自己按
* 当前时间算——所以分两层钉:
* ① 行为层:account-expiry.ts 的落键/清键/算天数(可真跑,用 window 桩);
* ② 源码层:ExpiryNotice.vue 的阈值、按钮、收起态键(SFC 编译不了,断言打在实际源码上)。
* 链路断言(登录写键、恢复会话写键、被顶下线清键、挂载点)防的是"数据源断了但界面静默不弹"。
*/
const COMPONENT = 'src/shared/components/ExpiryNotice.vue'
const APP = 'src/App.vue'
const LOGIN = 'src/pages/login/DesktopLoginPage.vue'
const ENSURE = 'src/shared/auth/ensure-auth.ts'
const KICK = 'src/shared/auth/kick-handler.ts'
function read(rel: string): string {
return readFileSync(join(process.cwd(), rel), 'utf8')
}
/** 非重叠子串计数。不走 execSync('grep'):node 在 Windows 上交给 cmd.exe,那里没 grep,命令会「成功返回空串」而不是报错——正是恒绿的形状。 */
function occurrences(text: string, token: string): number {
if (!token) return 0
let count = 0
let index = text.indexOf(token)
while (index !== -1) {
count += 1
index = text.indexOf(token, index + token.length)
}
return count
}
function templateOf(source: string): string {
const start = source.indexOf('<template>')
const end = source.lastIndexOf('</template>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <template> 段`)
return source.slice(start, end)
}
function scriptOf(source: string): string {
const start = source.indexOf('<script setup')
const end = source.indexOf('</script>')
assert.ok(start !== -1 && end > start, `${COMPONENT} 没有 <script setup> 段`)
return source.slice(start, end)
}
/** 剥掉 HTML 注释:注释掉的 `<ExpiryNotice />` 在源码里照样匹配得上,挂载点断言必须是活代码。 */
function withoutComments(source: string): string {
return source.replace(/<!--[\s\S]*?-->/g, '')
}
// ---------------------------------------------------------------- 行为层:window.localStorage 桩
interface Store {
[k: string]: string
}
/** 装一个最小 localStorage 桩跑一遍,跑完还原 globalThis.window。 */
function withStorage(run: (store: Store) => void): void {
const store: Store = {}
const localStorageStub = {
getItem: (k: string) => (Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null),
setItem: (k: string, v: string) => {
store[k] = String(v)
},
removeItem: (k: string) => {
delete store[k]
},
}
const hadWindow = 'window' in globalThis
const previous = (globalThis as Record<string, unknown>).window
;(globalThis as Record<string, unknown>).window = { localStorage: localStorageStub }
try {
run(store)
} finally {
if (hadWindow) (globalThis as Record<string, unknown>).window = previous
else delete (globalThis as Record<string, unknown>).window
}
}
const DAY = 86_400_000
/** 把「距今 msFromNow 毫秒」写成后端的 yyyy-MM-dd HH:mm(分钟精度,秒被截掉)。 */
function stamp(msFromNow: number): string {
const d = new Date(Date.now() + msFromNow)
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
}
test('落键:带 expiresAt 就存(trim 后),缺字段/空白一律清键,snake_case 也认', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage((store) => {
const key = expiry.ACCOUNT_EXPIRY_STORAGE_KEY
expiry.writeAccountExpiry({ expiresAt: ' 2026-12-31 23:59 ' })
assert.equal(store[key], '2026-12-31 23:59', '到期值没 trim 落键')
expiry.writeAccountExpiry({ expires_at: '2026-11-01 08:00' })
assert.equal(store[key], '2026-11-01 08:00', 'snake_case 也要认(老接口形状)')
expiry.writeAccountExpiry({})
assert.equal(Object.prototype.hasOwnProperty.call(store, key), false, '缺字段必须删键')
expiry.writeAccountExpiry({ expiresAt: '2026-12-31 23:59' })
expiry.writeAccountExpiry({ expiresAt: ' ' })
assert.equal(Object.prototype.hasOwnProperty.call(store, key), false, '空白一律清键')
expiry.writeAccountExpiry(null)
expiry.writeAccountExpiry(undefined)
assert.equal(expiry.readAccountExpiry(), '', '无键读出来是空串,不是 undefined')
})
})
test('换账号不残留:清键后读不到上一账号的到期值,天数返回 null 而不是 0', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage(() => {
expiry.writeAccountExpiry({ expiresAt: '2026-12-31 23:59' })
assert.equal(expiry.readAccountExpiry(), '2026-12-31 23:59')
expiry.clearAccountExpiry()
assert.equal(expiry.readAccountExpiry(), '', '登出/切号/被顶下线后必须读不到')
assert.equal(expiry.daysToAccountExpiry(), null, '无到期返回 null,弹窗不得按 0 天渲染')
})
})
test('剩余天数 floor 取整:4 天 12 小时算 4 天,已过期给负数,非法值给 null', async () => {
const expiry = await import('../src/shared/auth/account-expiry.ts')
withStorage(() => {
expiry.writeAccountExpiry({ expiresAt: stamp(4.5 * DAY) })
assert.equal(expiry.daysToAccountExpiry(), 4, '必须 floor,四舍五入会把 4.5 天报成 5 天而漏掉提醒')
expiry.writeAccountExpiry({ expiresAt: stamp(-1.5 * DAY) })
assert.ok((expiry.daysToAccountExpiry() ?? 0) < 0, '已过期要返回负数,由弹窗的 >=0 分支挡掉')
expiry.writeAccountExpiry({ expiresAt: '不是日期' })
assert.equal(expiry.daysToAccountExpiry(), null, '解析失败必须 null,不能当成今天到期')
})
})
// ---------------------------------------------------------------- 源码层:弹窗口径
const source = read(COMPONENT)
const template = templateOf(source)
const script = scriptOf(source)
test('提醒阈值 5 天,渲染条件 0 ≤ 剩余 < 5(整 5 天不弹,已过期不弹)', () => {
assert.match(script, /const THRESHOLD = props\.threshold \?\? 5\b/, '阈值没写成 5 的兜底')
const numericFallbacks = script.match(/\?\?\s*\d+/g) ?? []
assert.deepEqual(numericFallbacks, ['?? 5'], '数字兜底只能有阈值 5 这一个')
assert.match(script, /days\.value >= 0 && days\.value < THRESHOLD/, '没按「未过期且不足阈值」判定')
assert.doesNotMatch(script, /days\.value <= THRESHOLD/, '写成 <= 则整 5 天也弹')
})
test('只能缩小不能关闭:模板里恰好「收起 + 浮标」两个可点项,没有任何关闭件', () => {
assert.equal(occurrences(template, '@click="'), 2, '可点项必须恰好两个:minimize 与 restore')
assert.match(template, /@click="minimize"/, '收起按钮没接 minimize')
assert.match(template, /@click="restore"/, '缩小态浮标没接 restore')
assert.match(template, /收起\s*<\/button>/, '收起动作文案是「收起」')
assert.equal(occurrences(source, 'el-dialog'), 0, '对话框会带来关闭件')
assert.doesNotMatch(source, /@click="[^"]*close/i, '存在 close 点击处理器')
assert.doesNotMatch(source, /show-close|close-on-click-modal|close-on-press-escape|:closable/, '存在任何关闭开关')
})
test('收起态按「uid + 到期值」记键:续费换了到期值,新键没记录,回到展开', () => {
assert.equal(occurrences(script, 'expiry-notice-min:'), 1, '收起态键名只应有一处定义')
assert.match(script, /`expiry-notice-min:\$\{uid\}:\$\{expiresAt\.value\}`/, '键必须同时带 uid 与到期值')
assert.equal(occurrences(script, 'window.localStorage.setItem('), 1, '持久化写入只能有收起态这一处')
assert.equal(occurrences(script, 'window.localStorage.removeItem('), 1, '只有恢复展开时清键')
assert.match(
script,
/minimized\.value = window\.localStorage\.getItem\(minimizedKey\.value\) === '1'/,
'初值必须由「当前键」读出,键含到期值才会在续费后自动展开',
)
})
test('页面常开也要跨阈值出现:按分钟重算剩余,卸载时清计时器,未登录不渲染', () => {
assert.match(script, /window\.setInterval\(\(\) => \{ now\.value = Date\.now\(\) \}, 60_000\)/, '没有按分钟重算剩余天数')
assert.match(script, /onUnmounted\(\(\) => \{[\s\S]*?window\.clearInterval\(timer\)/, '卸载没清计时器')
assert.match(script, /Boolean\(uid\)/, '未登录(无 uid)不该渲染')
})
test('挂在 App.vue:桌面壳与网页共用同一个根组件,不挂就整站看不见', () => {
const app = withoutComments(read(APP))
assert.match(app, /import ExpiryNotice from '@\/shared\/components\/ExpiryNotice\.vue'/, 'App.vue 没引组件')
assert.match(app, /<ExpiryNotice\s*\/>/, 'App.vue 没渲染组件(注释掉等于没挂)')
})
test('数据源链路:登录写键、恢复会话两处写键、被顶下线清键,断了就静默不弹', () => {
const login = read(LOGIN)
const ensure = read(ENSURE)
const kick = read(KICK)
assert.equal(occurrences(login, 'writeAccountExpiry(data)'), 1, '登录成功没落到期键')
assert.equal(occurrences(login, 'clearAccountExpiry()'), 1, '登录页挂载清理没接上')
assert.equal(occurrences(ensure, 'writeAccountExpiry(response.data)'), 2, 'ensure-auth 两条恢复路径都要落键')
assert.match(kick, /storage\.removeItem\(ACCOUNT_EXPIRY_STORAGE_KEY\)/, '被顶下线没清到期键,换账号会残留')
})