Compare commits

...

9 Commits

Author SHA1 Message Date
huangzd1997 d2977a308c feat(公司tab): 接线 密钥管理与用量统计——分组∩公司取交集,空集不退化
两页都从 controller 这一个唯一出口算范围:收了 company_id 的 handler 自己调
dataReadScope.readScope(operator, companyId),把算好的 ReadScope 交给 service;
service 里 scopedUserIds() 只做 companyScope.userIdsOr(base),不再出现第二个判公司的 if。
readScope 落在 controller 而非计划原文写的 service,是因为 Task 8 补的 G2 尺子
CompanyIdParamGoesThroughReadScopeTest 逐 controller 断言"收参数就得自己调出口并把结果当实参交出去"。

空集一律早退(交给 in(...) 会渲染成 IN () → 500),且两条"筛空"日志按超管/主管分开,
排障时看得出是筛空还是查空;非超管空页仍返回带分组下拉的空页,下拉不缩水。

新增 6 条行为用例(超管 group_id∩公司成员集、交集空早退且不查库、不传公司保持不筛、
主管锁定集只被收窄不放大)。分母 3716 → 3722,Failures/Errors 均 0。
FE 侧两页带 company_id 并把 company-tab-wiring 缺口清单从 6 页收到 4 页。
2026-10-05 12:18:18 +08:00
huangzd1997 8be9892522 fix(看板): 任务状态收成三态,外观专利终态进度带真实状态落库
两次定案方向相反,所以分开钉:主看板只要 执行中/成功/失败 三态(其他状态不再当筛选项);
变体采集那页反过来——撤掉「在跑=0∪1 合并」口径,直接显示 待执行/处理中/成功/失败,
历史终态也要能看到。

- 后端 statusFilter 做同义词展开:成功 = SUCCESS∪COMPLETED,失败 = FAILED∪ERROR∪CANCELLED
  (取消=没成功也不在跑,并入失败),展开只住这一处,页面模型不再各自 if。前端筛选项随之
  收成 全部/执行中/成功/失败 四项(原 待执行/执行中/已排期/已完成/已取消 那一排撤掉)。
- 变体采集:不传 status = 全部状态,后端原样直查麦象(含历史终态),不再有 0∪1 合并哨兵;
  前端选项与 label 同步改。上线顺序仍是先 jar 后前端——新前端发 ACTIVE 打旧 jar 会整页空。
- AppearancePatentTaskService.saveFileBuildProgress 的终态必须带任务真实状态落库:save() 只对
  终态豁免 500ms 节流,而收尾三连写(组装/上传/完成)都在同一次调用里,若全按 RUNNING 写
  就只有第一条落地,满格「结果文件已生成」必被吞——2026-10-04 生产实测的「已完成 0/130、
  57/59」就是这么来的。对齐货源查询侧的 isTerminalFileBuildProgress。
- 节流侧补一条用例钉住"终态不受节流",模块侧补一条钉住"终态写的是任务状态而不是 RUNNING"——
  这两条分别在 service 与 mapper 出口,任一处回退都会红。

验证:后端定向 4 类 53/0(外观终态快照 4、进度节流 9、看板查询 34、变体采集 6;与批次①同一轮 mvn 197 例 0 红);admin-frontend-vue 定向 task-center-board 25/0(含三态选项、默认视图、
汇总卡口径)、全量 1726 例中本批 0 红。
2026-10-05 11:52:07 +08:00
huangzd1997 47f24162d5 feat(采集页省钱线): 派发即裁剪已匹配行、候选勾选记忆、摘掉跟价旧逐行派发
代理按「提取次数」计费而不是按流量,所以把同一批店铺重复派发一次就是真花钱。三处改动的
共同口径是「用户多点一次启动,不再多买一轮」。纯逻辑各抽成一个可单测的模块,页面只接线。

- dispatch-row-prune:查 ASIN 页匹配好的店铺交给后台执行后从结果表里移除。删行本身一句 filter,
  两个坑要钉住——行键口径必须与该页 rowKeyForMatch 一致(名字带两端空格的行删不掉,就留着
  下次再买一轮);历史行明细靠本地匹配表回退(withQueryAsinFallback 读 matchedItems),直接删行
  等于把已派发店铺的历史明细一起删掉 ⇒ 移除的行进一份上限 50 的归档,继续当回退数据源。
- candidate-selection-memory:候选店铺每天重拉时保住勾选。记的是店铺名不是行 id(候选行会被
  删了再加、id 会变,店铺名才是人眼认的那个身份);键按 uid + 页签隔离;selection-change 只带
  当前渲染窗口里的行,整份覆盖会把别的页刚记住的勾选一起抹掉 ⇒ 只按本窗口可见行重算;
  店铺已被删除时不得恢复勾选(否则匹配的是不存在的店)。
- 跟价页摘掉 processMatchedQueue 这条旧逐行派发路径:入口只有 if (autoQueueEnabled),而本页
  从来没把它置 true ⇒ 永远进不去。留着不是无害死代码——它是一套能重复买提取的并行派发路径,
  谁接错一次就再花钱。用例反向钉「不得回流」,不给死代码补测试。

验证:frontend-vue 定向 29/0(dispatch-row-prune 7、candidate-selection-memory 5、
wiring 10、query-asin-dispatch-prune 5、price-track-dead-queue-removed 反向钉 2),
全量 710/0(含本会话另加的到期弹窗 9 支,那 9 支随上一笔走)。接线由 wiring 用例钉住
"纯模块真被这两个页面 import",不是只测纯函数。
2026-10-05 11:51:53 +08:00
huangzd1997 271e98543b 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。
2026-10-05 11:51:33 +08:00
huangzd1997 5e721cb255 test(公司tab): 两把尺子补洞——范围"算过"要"用出去",company_id 要写明取值口
评审用变异证明现有护栏各有半个洞,而这两个洞接下来会被 Task 9–12 六页照抄,
所以在本任务收口,不留到批次尾。

- G2 断言 C:handler 里 `readScope(` 的结果必须先赋给变量、再出现在另一条方法调用的
  实参列表里。原来只断"体内出现了 readScope(",于是 `listHistory(…, scoped)` 改成
  `listHistory(…, null)` 时 20 支用例一支不红(控制方实测 rc=0)——范围算了又丢掉,
  页面照样看全量。`if (scoped != null) throw` 这类装饰不算接住。带 2 支负探针 + 1 支
  正探针 + 第二形探针,分母三条自检(取样集非空 / 走完两步的支数为正 / 射程必须覆盖
  已接线的两页),不许恒绿也不许恒红。
- G1 取值口登记表:`/company_id\s*[:=]/` 对"右半边从哪个对象读"是瞎的,
  `= normalized.companyId` 与 baseline 缺口清单逐字相同(normalizeHistoryParams 是
  白名单构造,运行时恒 undefined)。每页登记该页 api 函数自己的入参形状;8 页全覆盖、
  缺条目红、接了线没登记同样红——没有"未登记就退回宽松判据"的默认分支。
- helpers.readSource 归一行尾:仓库 autocrlf=true,新检出是 CRLF 而源码 blob 是 LF,
  `[\s\S]{0,N}` 这类有界窗口会被多出来的 `\r` 挤红——同一份 company-tab store
  (LF 3565B / CRLF 3629B,内容等价)在干净检出树上多红一条无关用例。归一后实测
  CRLF 树回到 6/5/1(只剩批次那条刻意留红)。

读数:后端全量 3663/0/0 Skipped 7 BUILD SUCCESS(最终字节亲跑);定向 9/0,变异
`scoped`→`null` 后 1 Failures 红在 CompanyIdParamGoesThroughReadScopeTest:393;
前端全量 1726/1725/1、`vue-tsc` rc=0;`= normalized.companyId`(连守卫一起换的静默变体)
实测红且点名 admin_history。产品码一支未动。
2026-10-05 10:11:08 +08:00
huangzd1997 81818c0ccd feat(公司tab): 接线 生成记录——company_id 走 DataReadScope,空成员集一律空页
「tab 画出来了、请求真带了 company_id、后端读都不读」是撒谎窗口,比不接更坏:
页面标题写某公司、数据仍是全量。所以后半页必须同时落地读侧与前端。

- controller 收显式 company_id,菜单闸门仍在算范围之前;范围只在 DataReadScope
  一处出口(不再有第二个 if)。DELETE /history 与 clearAllHistory 一字未动:
  写操作不吃 company_id。
- service 的总数与行集共用同一个 filterOf,"同范围"由结构保证;空成员集在
  分页归一之后早退,绝不把 [] 交给 in()(渲染成 IN () 就是 500)。
- 前端从原始 params 读 companyId——normalizeHistoryParams 是白名单构造,从
  normalized 读会静默拿到 undefined,编译绿、请求里没有参数。

验证:ImageHistoryServiceTest 7/0,后端全量 3663 例 0 红;G1 缺口清单 7 页 →
6 页(admin_history 消失);前端 1726/1725/1(那条红是刻意留的接线缺口尺子)、
vue-tsc rc=0。变异 M-A(删 filter.in)与 M-B(早退改永假)各杀 2 支。
2026-10-05 08:32:40 +08:00
huangzd1997 bdd34356d6 feat(公司tab): 接线 视频任务记录——company_id 走 DataReadScope,detail/zip 用同一把 ReadScope 门住
Task 8 的前半页(生成记录那半页 BLOCKED,见账本裁定)。
- controller 接住 requireAdminOrInternal 的返回值算范围,page 侧 readScope(operator, companyId)
  .userIdsOr(base):显式 user_id 与公司 tab 是交集,不是替换。
- mapper 的 userId 单值条件保留、并列 userIds IN <foreach>;null=不筛,空集在 service 首行早退,
  绝不把 [] 交给 mapper(渲染成 IN () 是 500)。
- selectAdminZipRows 补 t.user_id:download-zip 的闸门要不越权就得先拿得到行主人。
- detail 的 404 文案拆开:404 只留给"真查不到行",越权是 403。zip 整单任一条越界 ⇒ 403,
  不借 X-Archive-Error-Count 的"部分失败"语义盖越权。
- 前端 company_id 落在 builder 之后、发请求之前的唯一一处(normalizeHistoryParams 那类白名单
  构造会把键静默丢掉);页面 watch(activeId) + 读 requestCompanyId。

验证(我自己复跑,不是转述):干净树定向 7/0(新 5 支 + G2 2 支)、全量前端 1726/1725/1
(G1 缺口清单 8 页→7 页,admin_image_video_tasks 已消失)、vue-tsc rc=0。
2026-10-05 07:51:19 +08:00
huangzd1997 71b15b088c test(前端): 接线尺子补两处盲区——SFC 注释假接线与 tab 失败路径
(a) stripComments 增剥 <!-- -->:往页面追加两行 HTML 注释就能同时骗过
    「watch activeId」与「读 requestCompanyId」两条断言,实测缺口现在仍在列。
(c) I5 失败路径三支钉子:store 必须 catch 出 error 再 rethrow(口径照
    admin-session.ts:37-39)、模板不得出现 tab.error(提示条不在已批的两处
    界面暴露里)、组件必须 .catch 接住 rethrow。变异取证 M1/M2/M3 各判红
    6/4/2,对照轮 6/5/1(唯一红仍是计划明令的接线正向半支)。

全量前端 1726/1725/1、vue-tsc rc=0。
2026-10-05 07:06:09 +08:00
huangzd1997 6a56f79bd5 test(公司范围): G2 块边界改由括号差算,handler 之间不再互借证据
Task 6 修复轮 3 的四条 finding:文档行不得判成绑定行(含 @RequestParam 的行
先归绑定)、方法体开界用 parenDelta 跳过字符串字面量里的括号、闭界按 mapping
行缩进找同级 },text() 只截到块尾——否则下一支 handler 的 readScope 会被当成
这一支的证据,正是「新请求无失败出口」那一型。

全量后端在 detached worktree 跑:3653 例 0 红、Skipped 7、BUILD SUCCESS。
2026-10-05 07:06:01 +08:00
109 changed files with 5176 additions and 566 deletions
@@ -31,6 +31,8 @@ export interface UserSecretUsageQuery {
keyword?: string
/** 按数据权限分组筛选(仅超管生效);后端参数为 snake_case。 */
groupId?: number
/** 公司 tab 的当前口径;不传 = 后端按操作者自己的公司(批次 1 里非超管只有这一家)。 */
companyId?: number | null
page: number
pageSize: number
}
@@ -42,6 +44,9 @@ export async function fetchUserSecretUsage(params: UserSecretUsageQuery): Promis
if (params.endDate) query.endDate = params.endDate
if (params.keyword) query.keyword = params.keyword
if (params.groupId) query.group_id = params.groupId
// 用 `!= null` 而不是上面那几行的 truthy 写法:company_id=0 会让后端 requireCompanyId 直接抛,
// 宁可让参数缺失时它不出现,也别把 0 悄悄当没传。
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get('/api/admin/user-secret-usage', { params: query })
return unwrap<AdminUserSecretUsagePage>(data)
}
@@ -56,6 +56,8 @@ export interface UserSecretQuery {
checkStatus?: string
/** 按数据权限分组筛选(仅超管生效);后端参数为 snake_case。 */
groupId?: number
/** 公司 tab 的当前口径;不传 = 后端按操作者自己的公司(批次 1 里非超管只有这一家)。 */
companyId?: number | null
page: number
pageSize: number
}
@@ -66,6 +68,9 @@ export async function fetchUserSecretList(params: UserSecretQuery): Promise<Admi
if (params.keyword) query.keyword = params.keyword
if (params.checkStatus) query.checkStatus = params.checkStatus
if (params.groupId) query.group_id = params.groupId
// 用 `!= null` 而不是上面那几行的 truthy 写法:company_id=0 会让后端 requireCompanyId 直接抛,
// 宁可让参数缺失时它不出现,也别把 0 悄悄当没传。
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get('/api/admin/user-secrets', { params: query })
return unwrap<AdminUserSecretPage>(data)
}
@@ -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>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import OldPagination from '@/components/OldPagination.vue'
import { todayDateInput } from '@/utils/datetime'
@@ -9,8 +9,10 @@ import {
} from '@/api/user-secret-usage'
import type { GroupOption } from '@/api/user-secrets'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin)
@@ -43,6 +45,7 @@ async function load() {
endDate: endDate.value || undefined,
keyword: keyword.value.trim() || undefined,
groupId: groupFilter.value || undefined,
companyId: companyTab.requestCompanyId,
page: page.value,
pageSize: pageSize.value,
})
@@ -62,6 +65,9 @@ async function load() {
}
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
function search() {
page.value = 1
load()
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/datetime'
import OldPagination from '@/components/OldPagination.vue'
@@ -14,8 +14,10 @@ import {
type GroupOption,
} from '@/api/user-secrets'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin)
@@ -114,6 +116,7 @@ async function load() {
keyword: keyword.value.trim() || undefined,
checkStatus: statusFilter.value || undefined,
groupId: groupFilter.value || undefined,
companyId: companyTab.requestCompanyId,
page: page.value,
pageSize: pageSize.value,
})
@@ -127,6 +130,9 @@ async function load() {
}
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
function search() {
page.value = 1
load()
@@ -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
}
@@ -2,15 +2,17 @@
/** 生成记录页 · 像素复刻旧版 admin.html panel-history(自绘:form-box 筛选 + panel-box 表格 + 旧式分页 + thumb 缩略图)。
* script 逻辑沿用现有 Vue 实现(查询/翻页/跳页/点击缩略图放大预览)。 */
import { formatDateTime } from '@/utils/datetime'
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { fetchHistoryList, fetchHistoryUserOptions } from './history-api.ts'
import type { HistoryUserOption } from './history-user-option.ts'
import type { HistoryRecordItem } from './history-dto.ts'
import { historyEmptyText, historyErrorText } from './history-feedback.ts'
import { historyPanelTypeLabel } from './history-type.ts'
import { ElMessage } from 'element-plus'
import { useCompanyTabStore } from '@/stores/company-tab'
import OldPagination from '@/components/OldPagination.vue'
const companyTab = useCompanyTabStore()
const loading = ref(false)
const userLoading = ref(false)
const rows = ref<HistoryRecordItem[]>([])
@@ -62,6 +64,7 @@ async function load() {
userId: filter.userId ? Number(filter.userId) : undefined,
timeStart: toApiTime(filter.timeStart),
timeEnd: toApiTime(filter.timeEnd),
companyId: companyTab.requestCompanyId,
})
rows.value = result.items
total.value = result.total
@@ -73,6 +76,9 @@ async function load() {
}
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
async function loadUserOptions() {
userLoading.value = true
try {
@@ -8,7 +8,12 @@ export const HISTORY_ENDPOINT = '/api/admin/history'
export async function fetchHistoryList(params: Partial<HistoryListParams> = {}): Promise<HistoryPageResult> {
const normalized = normalizeHistoryParams(params)
const { data } = await http.get<unknown>(HISTORY_ENDPOINT, { params: toHistoryListQuery(normalized) })
// 公司 tab 的值落在 builder 之后、发请求之前的唯一一处:normalizeHistoryParams 是白名单构造
// (只点名 page/pageSize/userId/timeStart/timeEnd),所以这里必须从原始 params 读 companyId,
// 从 normalized 读会拿到 undefined —— TS 绿、请求里没参数、页面永远看全量。
const query = toHistoryListQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(HISTORY_ENDPOINT, { params: query })
return parseHistoryPage(data)
}
@@ -33,6 +33,8 @@ export interface HistoryListParams {
userId?: number | null
timeStart?: string
timeEnd?: string
/** 公司 tab 的当前值;页面传入,不参与 normalizeHistoryParams 的归一(它是白名单构造)。 */
companyId?: number | null
}
export interface HistoryListQuery {
@@ -41,6 +43,7 @@ export interface HistoryListQuery {
user_id?: number
time_start?: string
time_end?: string
company_id?: number
}
function finiteInt(value: unknown): number | null {
@@ -25,6 +25,7 @@ import {
VARIANT_STATUS_OPTIONS,
buildTaskQuery,
buildVariantQuery,
countryLabel,
createTaskFilter,
createVariantFilter,
deviceDisplayName,
@@ -50,7 +51,7 @@ const activeTab = ref<BoardTab>('tasks')
const overview = ref<TaskCenterOverview | null>(null)
const shopOptions = ref<string[]>([])
/** 默认视图 = 只看在跑(合并哨兵,后端展开成三个进行中状态),**不锁创建时间**:
/** 默认视图 = 只看执行中(合并哨兵,后端展开成三个进行中状态),**不锁创建时间**:
* 卡片「进行中任务」的 SQL 不带时间窗,锁当天必然比卡片少一截(10-04 实测 21 vs 39,
* 差的 18 个是跨天仍在上报的长任务)。历史状态与时间窗仍在筛选里,用户自己选。 */
function defaultTaskFilter(): TaskCenterTaskFilter {
@@ -282,7 +283,7 @@ onUnmounted(() => {
客户端任务 <span class="t-count" title="当前在跑任务数,与上方「进行中任务」同源">{{ runningBadge ?? '—' }}</span>
</button>
<button class="tab" :class="{ active: activeTab === 'variant' }" type="button" @click="switchTab('variant')">
变体采集 <span class="t-count" title="麦象在跑批量任务条数(等待执行∪处理中),「—」= 还没查到">{{ variantTotal ?? '—' }}</span>
变体采集 <span class="t-count" title="麦象变体采集任务条数(全部状态),「—」= 还没查到">{{ variantTotal ?? '—' }}</span>
</button>
</div>
<div class="tc-head-tools">
@@ -327,7 +328,7 @@ onUnmounted(() => {
<section class="panel-box">
<div class="box-head">
<h3>任务筛选</h3>
<span class="box-note">默认列出全部在跑任务(待执行/执行中/已排期算一个口径),条数与上方「进行中任务」同源;看历史请换状态或选创建时间</span>
<span class="box-note">默认列出执行中的任务(待执行/已排期并入执行中口径),条数与上方「进行中任务」同源;看历史请换状态或选创建时间</span>
</div>
<div class="form-row">
<div class="form-group" style="min-width: 160px">
@@ -401,7 +402,7 @@ onUnmounted(() => {
<span class="strong">{{ accountOf(row) }}</span>
</td>
<td>{{ shopDisplayName(row.shopName, row.shopCount) }}</td>
<td class="mono">{{ row.country || '—' }}</td>
<td>{{ countryLabel(row.country) }}</td>
<td>{{ row.moduleLabel || row.moduleType }}</td>
<td>
<span class="st-pill" :class="`is-${taskStatusType(row.status)}`">{{ taskStatusLabel(row.status) }}</span>
@@ -418,13 +419,19 @@ onUnmounted(() => {
</td>
<td>{{ row.finishedAt ? formatDateTime(row.finishedAt) : '—' }}</td>
<td>
<div class="progress-line">
<span>{{ progressText(row) }}</span>
<template v-if="taskStatusType(row.status) === 'failed'">
<span v-if="row.progressFailed > 0" class="badge danger">失败 {{ row.progressFailed }}</span>
</div>
<div class="p-track" v-if="row.progressTotal > 0">
<div class="p-fill" :style="{ width: progressPercent(row) + '%' }"></div>
</div>
<span v-else>—</span>
</template>
<template v-else>
<div class="progress-line">
<span>{{ progressText(row) }}</span>
<span v-if="row.progressFailed > 0" class="badge danger">失败 {{ row.progressFailed }}</span>
</div>
<div class="p-track" v-if="row.progressTotal > 0">
<div class="p-fill" :style="{ width: progressPercent(row) + '%' }"></div>
</div>
</template>
</td>
</tr>
</template>
@@ -452,7 +459,7 @@ onUnmounted(() => {
<section class="panel-box">
<div class="box-head">
<h3>变体采集(麦象批量任务)</h3>
<span class="box-note">数据来自麦象平台,范围限本组账号,只看在跑(历史不展示)</span>
<span class="box-note">数据来自麦象平台,范围限本组账号,默认全部状态(待执行/处理中/成功/失败)</span>
</div>
<div class="form-row">
<div class="form-group" style="min-width: 150px">
@@ -501,7 +508,6 @@ onUnmounted(() => {
<td>{{ formatDateTime(row.updateTime) }}</td>
<td>
<span class="res-mes" :title="row.resMes || ''">{{ row.resMes || '—' }}</span>
<span v-if="row.taskData" class="sub mono" :title="row.taskData">{{ row.taskData }}</span>
</td>
</tr>
</template>
@@ -509,7 +515,7 @@ onUnmounted(() => {
<td colspan="6" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td colspan="6" class="empty-tip">暂无在跑的变体采集任务</td>
<td colspan="6" class="empty-tip">暂无变体采集任务</td>
</tr>
</tbody>
</table>
@@ -543,8 +549,14 @@ onUnmounted(() => {
<el-descriptions-item label="最近上报">{{ detail.lastReportAt ? formatDateTime(detail.lastReportAt) : '—' }}</el-descriptions-item>
<el-descriptions-item label="结束时间">{{ detail.finishedAt ? formatDateTime(detail.finishedAt) : '—' }}</el-descriptions-item>
<el-descriptions-item label="进度">
{{ progressText(detail) }}
<span v-if="detail.progressFailed > 0" class="badge danger">失败 {{ detail.progressFailed }}</span>
<template v-if="taskStatusType(detail.status) === 'failed'">
<span v-if="detail.progressFailed > 0" class="badge danger">失败 {{ detail.progressFailed }}</span>
<span v-else>—</span>
</template>
<template v-else>
{{ progressText(detail) }}
<span v-if="detail.progressFailed > 0" class="badge danger">失败 {{ detail.progressFailed }}</span>
</template>
</el-descriptions-item>
<el-descriptions-item label="当前处理">{{ currentScopeOf(detail) }}</el-descriptions-item>
<el-descriptions-item label="错误信息" :span="2">{{ detail.errorMessage || detail.message || '—' }}</el-descriptions-item>
@@ -871,11 +883,6 @@ td {
background: #f8ebeb;
border-color: #e4c2c5;
}
.st-pill.is-cancelled {
color: #5b6f83;
background: #f1f6fa;
border-color: #d6e2ec;
}
.st-pill.is-pending {
color: #8a6d3b;
background: #fbf4ea;
@@ -1,5 +1,6 @@
/** 客户端任务管理看板纯逻辑:下拉选项、状态/设备/店铺/进度展示映射、查询参数构建。
* 无框架依赖,可直接被 node 单测导入(对齐 tasks 域 image-video-model 的拆法)。 */
import { asinCountryLabel } from '../asin/asin-country.ts'
export interface TaskCenterTaskFilter {
username: string
@@ -12,7 +13,7 @@ export interface TaskCenterTaskFilter {
}
export interface TaskCenterVariantFilter {
/** 麦象状态码字符串(''=在跑(0∪1,后端合并)/ 0 等待 / 1 处理中);历史状态不再可选。 */
/** 麦象状态码字符串(''=全部状态 / 0 待执行 / 1 处理中 / 2 成功 / 3 失败)。 */
status: string
}
@@ -50,63 +51,67 @@ export const MODULE_OPTIONS: Array<{ value: string; label: string }> = [
*/
export const ACTIVE_TASK_STATUS = 'ACTIVE'
/**
* 状态三态收敛(用户 2026-10-04 定案:任务状态只要 执行中/成功/失败,其他不用):
* 「执行中」= ACTIVE 合并哨兵(待执行/已排期并入,与默认视图、汇总卡同口径);
* 成功/失败的同义词展开(COMPLETED/ERROR/取消)在后端 TaskCenterQueryService.statusFilter。
*/
export const TASK_STATUS_OPTIONS: Array<{ value: string; label: string }> = [
{ value: '', label: '全部状态' },
{ value: ACTIVE_TASK_STATUS, label: '在跑' },
{ value: 'PENDING', label: '待执行' },
{ value: 'RUNNING', label: '执行中' },
{ value: 'SCHEDULED', label: '已排期' },
{ value: 'SUCCESS', label: '已完成' },
{ value: ACTIVE_TASK_STATUS, label: '执行中' },
{ value: 'SUCCESS', label: '成功' },
{ value: 'FAILED', label: '失败' },
{ value: 'CANCELLED', label: '已取消' },
]
/**
* 变体采集只看「在跑」:空值即后端合并口径(0 等待 ∪ 1 处理中),
* 已完成 / 处理失败按用户要求彻底不再提供入口(历史不展示)。
* 变体采集状态四态(用户 2026-10-05 定案:在跑口径不要,就显示 待执行/处理中/成功/失败):
* 空值 = 全部状态(后端原样直查麦象,含历史终态),不再有「在跑」合并口径。
*/
export const VARIANT_STATUS_OPTIONS: Array<{ value: string; label: string }> = [
{ value: '', label: '在跑' },
{ value: '0', label: '等待执行' },
{ value: '', label: '全部状态' },
{ value: '0', label: '待执行' },
{ value: '1', label: '处理中' },
{ value: '2', label: '成功' },
{ value: '3', label: '失败' },
]
/** 三态展示映射(2026-10-04 收敛):进行中各态统一「执行中」,完成态统一「成功」,
* 失败/出错/取消统一「失败」(取消 = 没成功也不在跑,并入失败)。 */
const TASK_STATUS_LABELS: Record<string, string> = {
PENDING: '待执行',
PENDING: '执行中',
RUNNING: '执行中',
SCHEDULED: '已排期',
SUCCESS: '已完成',
COMPLETED: '已完成',
SCHEDULED: '执行中',
SUCCESS: '成功',
COMPLETED: '成功',
FAILED: '失败',
ERROR: '失败',
CANCELLED: '已取消',
CANCELED: '已取消',
CANCELLED: '失败',
CANCELED: '失败',
}
/** 麦象批量任务状态四态文案(2026-10-05 用户定案):0 待执行 / 1 处理中 / 2 成功 / 3 失败。 */
const VARIANT_STATUS_LABELS: Record<number, string> = {
0: '等待执行',
0: '待执行',
1: '处理中',
2: '已完成',
3: '处理失败',
2: '成功',
3: '失败',
}
export type TaskStatusType = 'pending' | 'running' | 'success' | 'failed' | 'cancelled'
export function taskStatusLabel(status: string | null | undefined): string {
const key = (status || '').toUpperCase()
return TASK_STATUS_LABELS[key] || key || '未知'
return TASK_STATUS_LABELS[key] || '执行中'
}
export function taskStatusType(status: string | null | undefined): TaskStatusType {
const key = (status || '').toUpperCase()
if (key === 'SUCCESS' || key === 'COMPLETED') return 'success'
if (key === 'FAILED' || key === 'ERROR') return 'failed'
if (key === 'CANCELLED' || key === 'CANCELED') return 'cancelled'
if (key === 'PENDING') return 'pending'
if (key === 'FAILED' || key === 'ERROR' || key === 'CANCELLED' || key === 'CANCELED') return 'failed'
return 'running'
}
/** 麦象批量任务状态:0 等待 / 1 处理中 / 2 已完成 / 3 失败(不冒充成功)。 */
/** 麦象批量任务状态:0 待执行 / 1 处理中 / 2 成功 / 3 失败(未识别不冒充成功)。 */
export function variantStatusLabel(status: number | string | null | undefined): string {
if (status == null || status === '') return '未知'
const code = Number(status)
@@ -144,6 +149,18 @@ export function shopDisplayName(shopName: string | null | undefined, shopCount:
return count > 1 ? `${name} 等${count}个` : name
}
/** 国家列展示:后端已归一成 `UK` / `UK/DE` 形状,逐段走共享国家字典转中文(用户 2026-10-04 要求);
* 字典外的国家码原样保留,取不到画「—」。 */
export function countryLabel(country: string | null | undefined): string {
const value = (country || '').trim()
if (!value) return '—'
return value
.split('/')
.map((part) => asinCountryLabel(part.trim()))
.filter((label) => label !== '')
.join('/')
}
/** 页签徽章用的条数:只有接口真的回了非负数才算一个数,否则回 null 画「—」。
* 麦象在结果表未注册时把 total 回成 -1 哨兵,`Number(x || 0)` 会把它读成 0 条。 */
export function tabCount(total: unknown): number | null {
@@ -2,7 +2,7 @@
import { formatDateTime } from '@/utils/datetime'
/** 视频任务记录页 · 像素复刻旧版 admin.html panel-image-video-tasks(自绘:form-box 筛选[用户名/提交起止+查询/重置] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 任务卡片网格 + 旧式分页)。
* script 逻辑沿用现有 Vue 实现(批量打包/明细抽屉/权限授权)。 */
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { requestVideoZipDownload, fetchImageVideoTasks, fetchImageVideoTaskDetail } from './image-video-api.ts'
import { fetchImageVideoPermissionUsers, saveImageVideoPermissions } from './image-video-api.ts'
@@ -18,9 +18,11 @@ import {
import { grantedUserIds, type TaskPermissionItem } from './task-permission.ts'
import { imageVideoDownloadFilename, videoKeysOf } from './image-video-view.ts'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import OldPagination from '@/components/OldPagination.vue'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
const loading = ref(false)
const tasks = ref<ImageVideoRow[]>([])
const totalTasks = ref(0)
@@ -114,7 +116,7 @@ function toFilter(): ImageVideoFilter {
async function load() {
loading.value = true
try {
const result = await fetchImageVideoTasks(toFilter(), page.value, pageSize.value)
const result = await fetchImageVideoTasks(toFilter(), page.value, pageSize.value, companyTab.requestCompanyId)
tasks.value = result.items
totalTasks.value = result.total
page.value = result.page
@@ -125,6 +127,9 @@ async function load() {
}
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
function apply() {
page.value = 1
void load()
@@ -12,10 +12,12 @@ export async function fetchImageVideoTasks(
filter: ImageVideoFilter,
page: number,
pageSize: number,
companyId?: number | null,
): Promise<ImageVideoPageResult> {
const { data } = await http.get<unknown>(IMAGE_VIDEO_TASKS_ENDPOINT, {
params: toImageVideoQuery(filter, page, pageSize),
})
// 公司 tab 的值由页面传进来,落在 builder 之后(filter 里塞不进:toImageVideoQuery 是白名单构造)。
const query = toImageVideoQuery(filter, page, pageSize)
if (companyId != null) query.company_id = companyId
const { data } = await http.get<unknown>(IMAGE_VIDEO_TASKS_ENDPOINT, { params: query })
return parseImageVideoPage(data)
}
@@ -27,6 +27,7 @@ export interface ImageVideoQuery {
coze_execute_id?: string
submitted_from?: string
submitted_to?: string
company_id?: number
}
export function createImageVideoFilter(): ImageVideoFilter {
+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())
@@ -7,9 +7,80 @@ import { COMPANY_SCOPED_PAGES, SUPER_ADMIN_ONLY_MENU_KEYS } from '../src/config/
const read = (p: string) => {
assert.ok(existsSync(p), `护栏读不到 ${p}:api 文件改名了,清单必须同步(别把用例改成"不存在就跳过")`)
return readFileSync(p, 'utf8')
// 与 helpers.readSource 同口径归一行尾(CRLF 检出树会把有界窗口判据挤红,见 helpers 里的注释)。
return readFileSync(p, 'utf8').replace(/\r\n/g, '\n')
}
/**
* 取值口登记表(2026-10-05 修复轮 1,复评 I-2)。上面那条正向判据原本只问「有没有把 company_id 当成查询
* 参数下传」,`/company_id\s*[:=]/` 对**右半边从哪儿取值**是瞎的:评审把
* `history-api.ts` 的 `query.company_id = params.companyId` 改成 `= normalized.companyId` 之后,
* 缺口清单与 baseline **逐字相同**(`admin_history` 都不出现)、`vue-tsc` 也不红
* (`normalizeHistoryParams` 的返回类型就是 `HistoryListParams`,本轮刚给它加了 `companyId?: number | null`,
* 所以 `normalized.companyId` 类型合法、运行时恒 `undefined`)。tab 画了、请求发了、参数没有——
* 这正是本批次要杀的那类静默失效,尺子却看不见。
* <p>于是每页登记一条"company_id 右侧的根标识符**必须**是该页 api 函数自己的入参"的形状:
* `shape` 为 `RegExp` 时,对**剥完注释的源码**求值,不匹配即红并点名文件;`shape` 为 `null` 是
* "这一页还没接线"的显式声明(今天 6 页如此,它们本来就在缺口清单里)。
* <p>两道不留缝:① `COMPANY_SCOPED_PAGES` 里每一页都必须在表里有条目,缺条目直接红;
* ② 一旦某个文件真的出现了 `company_id` 下传而它的 `shape` 还是 `null`,同样红——
* 所以"新页接线时顺手不改登记表"过不去,也**没有**"没登记就退回宽松判据"的默认分支。
*/
type CompanyIdPin = { readonly file: string; readonly shape: RegExp | null; readonly note: string }
const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>> = {
admin_history: [
{
file: 'src/pages/records/history-api.ts',
// fetchHistoryList(params: Partial<HistoryListParams>):唯一入参对象是 params(history-api.ts:15 的形状)。
shape: /company_id\s*=\s*params\.companyId\b/,
note: 'normalizeHistoryParams 是白名单构造(只点名 page/pageSize/userId/timeStart/timeEnd),从 normalized 读 companyId 恒 undefined',
},
],
admin_image_video_tasks: [
{
file: 'src/pages/tasks/image-video-api.ts',
// fetchImageVideoTasks(filter, page, pageSize, companyId):公司值的入参就是第 4 个形参本身(:19 的形状),
// 不是 filter 的字段——toImageVideoQuery 同样是白名单构造。
shape: /company_id\s*=\s*companyId\b/,
note: 'filter 走 toImageVideoQuery 白名单构造,公司值只能落在 companyId 形参上',
},
],
admin_task_center: [
{ file: 'src/api/task-center.ts', shape: null, note: 'Task 9 未接线(已在缺口清单里);谁接线谁把 null 换成本函数真实取值口' },
{ file: 'src/pages/task-center/task-center-model.ts', shape: null, note: '同上:这一页有两个取数模块,两个都得登记' },
],
admin_user_secret_usage: [
{
file: 'src/api/user-secret-usage.ts',
// fetchUserSecretUsage(params: UserSecretUsageQuery):唯一入参对象是 params(:45 那一行的形状)。
shape: /company_id\s*=\s*params\.companyId\b/,
note: 'query 由本函数自己从零构造,companyId 只能取自 params;api 模块不碰 Pinia store(node --test 直接 import 会抛 no active pinia)',
},
],
admin_user_secrets: [
{
file: 'src/api/user-secrets.ts',
// fetchUserSecretList(params: UserSecretQuery):唯一入参对象是 params(:71 那一行的形状)。
shape: /company_id\s*=\s*params\.companyId\b/,
note: '同上:值由 UserSecretsPage.vue 传 companyTab.requestCompanyId,api 里不读任何归一化/构造出来的中间对象',
},
],
admin_device_logs: [
{ file: 'src/api/device-logs.ts', shape: null, note: 'Task 10 未接线(已在缺口清单里)' },
],
admin_group_manage: [
{ file: 'src/pages/account/shop-group-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' },
],
admin_shop_manage: [
{ file: 'src/pages/shop/shop-manage-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' },
],
}
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
let strictPinsEvaluated = 0
let strictPinsPassed = 0
test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company_id,页面组件必须 watch activeId', () => {
// 循环里**收集**、循环后一次性断言:Task 8-12 是 5 个任务共用这把尺子,fail-fast 时做完自己那页的同事
// 仍然只看到一句指向**别人页**的红(今天只报 src/api/task-center.ts),判断不出本页是否已收敛。
@@ -29,10 +100,35 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
gaps.push(`${file} 没把 company_id 当成查询参数下传`)
}
}
// 取值口登记(复评 I-2):光"把 company_id 塞进查询对象"不够,右半边必须取自**本函数自己的入参**。
for (const pin of COMPANY_ID_SOURCE_PINS[page.menuKey] ?? []) {
if (!page.apiFiles.includes(pin.file)) {
gaps.push(`${pin.file} 登记在 ${page.menuKey} 名下,但 COMPANY_SCOPED_PAGES 的 apiFiles 里没有它:登记表与清单两处口径打架`)
continue
}
const src = stripComments(read(pin.file))
const wired = /company_id\s*[:=]/.test(src)
if (pin.shape === null) {
// 没登记取值口却已经下传了参数 = 这一页的取值口径没人看守(洞就是这么留下的)。
if (wired) gaps.push(`${pin.file} 已经把 company_id 当下传参数了,登记表里 shape 却还是 null —— 把它换成"company_id 右侧 = 本函数入参"的正则`)
continue
}
strictPinsEvaluated++
if (!wired) {
gaps.push(`${pin.file} 登记了取值口 ${pin.shape},文件里却一个 company_id 都没下传:登记表与代码漂移(要么接线回来,要么把 shape 改回 null)`)
continue
}
if (!pin.shape.test(src)) {
gaps.push(`${pin.file} 的 company_id 右半边不是本函数入参(登记表要求 ${pin.shape};${pin.note})`
+ '—— tab 画了、请求发了、参数没有;编译器不一定看得见(normalizeHistoryParams 的返回类型里就有这个字段)')
continue
}
strictPinsPassed++
}
for (const file of page.pageFiles) {
// 与 api 侧同口径先剥注释(约束 6:注释里出现字面量不算接线)——否则一句
// `// 这里读 companyTab.requestCompanyId` 就能同时骗过下面两条断言。
// 残留面:stripComments 只剥 JS 的 `//` 与 `/* */`,Vue 模板的 `<!-- -->` 不剥。
// 残留面已封:stripComments 现在 JS 的 `//`、`/* */` 与 Vue 模板的 `<!-- -->` 三类都剥。
const source = stripComments(read(file))
if (!/watch\(\(\)\s*=>\s*companyTab\.activeId/.test(source)) {
gaps.push(`${file} 没监听公司 tab:切 tab 不重取数 = 这页的 tab 是装饰品`)
@@ -43,8 +139,23 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
gaps.push(`${file} 没读 companyTab.requestCompanyId(页面取公司值的唯一出口)`)
}
}
// 覆盖性自检:清单里每一页都必须在登记表里有条目。**没有**"没登记就退回宽松判据"这条路。
if (!(page.menuKey in COMPANY_ID_SOURCE_PINS)) {
gaps.push(`${page.menuKey} 在 COMPANY_ID_SOURCE_PINS 里没有条目:接线的页必须登记取值口,护栏不许留默认分支`)
}
if (gaps.length) problems.push(`${page.menuKey}:${gaps.join(';')}`)
}
// 正样本自检:求值了却一条都没通过 ⇒ 严格判据恒红(或形状不认),红在缺口清单里、不抢本页的诊断信息。
if (strictPinsEvaluated > 0 && strictPinsPassed === 0) {
problems.push(`(取值口取样自检)shape 求值了 ${strictPinsEvaluated} 条、通过 0 条 —— 判据恒红或形状不认,不可信`)
}
// 严格半支的取样自检:登记表是空的、或一页都没走完 shape 求值 ⇒ 这半支等于没写,用例自己红。
assert.ok(strictPinsEvaluated >= 2,
`取值口严格判据本轮只求值了 ${strictPinsEvaluated} 条(登记表里 admin_history / admin_image_video_tasks 两条 shape 都在,`
+ `求值数不可能低于已接线页数)——判据空转,normalized-vs-params 那个洞又没人看守了`)
assert.ok(COMPANY_ID_SOURCE_PINS.admin_history.some((p) => p.shape !== null)
&& COMPANY_ID_SOURCE_PINS.admin_image_video_tasks.some((p) => p.shape !== null),
'Task 8 已接线的两页在登记表里的 shape 被改回 null 了:严格判据对这两页不再起作用(正样本归零)')
assert.deepEqual(problems, [],
`公司 tab 接线缺口(逐页列全;Task 8-12 补齐后这支自动收敛,本轮刻意留红):\n`
+ problems.map((p) => ` - ${p}`).join('\n'))
@@ -98,6 +209,9 @@ function listTs(dir: string): string[] {
// 放进块注释会把注释当场截断,node 的 TS 解析器随即报 ERR_INVALID_TYPESCRIPT_SYNTAX——整支用例加载都失败。)
function stripComments(source: string): string {
return source
// Vue 模板的 <!-- --> 也要剥:pageFiles 取样全是 .sfc.vue,一句 `<!-- watch(() => companyTab.activeId) -->`
// 在只剥 JS 注释时能同时骗过 page 侧两条钉子(2026-10-05 复评 (a))。
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/\/\*[\s\S]*?\*\//g, '')
.split(/\r?\n/)
.filter((line) => !line.trimStart().startsWith('//'))
@@ -171,4 +285,14 @@ test('挂载与单一尺子:tab 条挂在壳层、公司名读 companyName、
'visibleForOperator 必须含「有可选公司」判定,全是停用公司时 tab 条整体不渲染')
assert.match(store, /requestCompanyId\(\)[\s\S]{0,120}companyIdForRequest/,
'requestCompanyId 必须是 companyIdForRequest 的唯一出口(页面只读这个 getter)')
// 失败路径也要有钉子(2026-10-05 复评 (c)):改前 `initialize` 只有 try/finally ⇒ GET /companies 抛错时
// loaded 永远 false、tab 条静默消失、异常落 unhandled rejection(全仓 src 无 errorHandler 兜底)。
// 只补代码不补钉子的话,Task 8-12 里谁把它改回 try/finally,1726 支用例一支都不会红——那是"修好了但没护栏"。
assert.match(store, /catch \(error\)[\s\S]{0,420}this\.error =[\s\S]{0,120}throw error/,
'initialize 必须 catch 出 error 状态再 rethrow(口径照 admin-session.ts:37-39),不许退回只有 try/finally')
// error 只许住 store 与 console:一旦进模板就是§12 第 5 条没批的那一处新界面暴露。
assert.equal(tabs.includes('tab.error'), false, '不许把 error 渲染进模板:提示条/文案都不在已批的两处暴露里')
assert.match(tabs, /initialize\(\)\.catch\(/,
'组件侧必须 .catch 接住 store 的 rethrow,否则又变回 unhandled rejection')
})
@@ -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 而不是本地算')
})
+10 -2
View File
@@ -6,9 +6,17 @@ const SRC = join(ROOT, 'src')
const EXTENSIONS = ['', '.ts', '.tsx', '.vue', '.js', '.json']
const INDEX_CANDIDATES = ['/index.ts', '/index.tsx', '/index.vue', '/index.js']
/** 读取工程内源码文件(相对工程根)。 */
/**
* 读取工程内源码文件(相对工程根)。
*
* 行尾一律归一成 LF:仓库 `core.autocrlf=true`,新检出的工作树是 CRLF 而源码 blob 是 LF,
* 而本仓多数判据是 `[\s\S]{0,N}` 这类**有界窗口**(例如 company-tab-wiring 里 catch→this.error→throw
* 那记 420 字符的钉子)。每个换行多背一个 `\r` 就把窗口预算吃掉一截——实测同一份 `src/stores/company-tab.ts`
* (内容逐字节等价,主树 LF 3565 B / 新检出 CRLF 3629 B)在干净检出树上会多红一条与本任务无关的用例。
* 归一之后判据只取决于内容,不取决于在哪台机器、哪个 worktree 里跑。
*/
export function readSource(rel: string): string {
return readFileSync(join(ROOT, rel), 'utf8')
return readFileSync(join(ROOT, rel), 'utf8').replace(/\r\n/g, '\n')
}
/** 统计非重叠子串出现次数(幂等、只读)。 */
+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'), '公司超级管理员')
})
@@ -12,6 +12,7 @@ import {
buildVariantQuery,
createTaskFilter,
createVariantFilter,
countryLabel,
deviceDisplayName,
progressPercent,
progressText,
@@ -83,18 +84,25 @@ test('task_center_device_dimension_is_gone', () => {
})
test('task_center_status_labels_cover_backend_states', () => {
assert.equal(taskStatusLabel('PENDING'), '待执行')
// 三态收敛(2026-10-04 用户定案:只要 执行中/成功/失败):进行中各态并入执行中,
// 完成态并入成功,失败/出错/取消并入失败(取消 = 没成功也不在跑)。
assert.equal(taskStatusLabel('PENDING'), '执行中')
assert.equal(taskStatusLabel('RUNNING'), '执行中')
assert.equal(taskStatusLabel('SUCCESS'), '已完成')
assert.equal(taskStatusLabel('SCHEDULED'), '执行中')
assert.equal(taskStatusLabel('SUCCESS'), '成功')
assert.equal(taskStatusLabel('COMPLETED'), '成功', '完成态历史拼写并入成功')
assert.equal(taskStatusLabel('FAILED'), '失败')
assert.equal(taskStatusLabel('CANCELLED'), '已取消')
assert.equal(taskStatusLabel(''), '未知')
assert.equal(taskStatusLabel('ERROR'), '失败', '出错并入失败')
assert.equal(taskStatusLabel('CANCELLED'), '失败', '取消并入失败')
assert.equal(taskStatusLabel('CANCELED'), '失败', '历史脏拼写同样并入失败')
assert.equal(taskStatusLabel(''), '执行中', '未知状态不是终态,按执行中读')
assert.equal(taskStatusLabel('WEIRD'), '执行中')
assert.equal(taskStatusType('SUCCESS'), 'success')
assert.equal(taskStatusType('FAILED'), 'failed')
assert.equal(taskStatusType('CANCELLED'), 'cancelled')
assert.equal(taskStatusType('PENDING'), 'pending')
assert.equal(taskStatusType('CANCELLED'), 'failed')
assert.equal(taskStatusType('PENDING'), 'running')
assert.equal(taskStatusType('RUNNING'), 'running')
assert.ok(TASK_STATUS_OPTIONS.length >= 5)
assert.ok(TASK_STATUS_OPTIONS.length >= 4)
assert.equal(TASK_STATUS_OPTIONS[0].value, '')
assert.equal(MODULE_OPTIONS[0].value, '', '首项为「全部业务」')
assert.equal(MODULE_OPTIONS.slice(1).every((o) => o.value && o.label), true)
@@ -102,34 +110,33 @@ test('task_center_status_labels_cover_backend_states', () => {
})
test('task_center_variant_status_map_follows_maixiang_semantics', () => {
assert.equal(variantStatusLabel(0), '等待执行')
// 四态文案(2026-10-05 用户定案):待执行/处理中/成功/失败,不再有 等待执行/已完成/处理失败 旧词。
assert.equal(variantStatusLabel(0), '待执行')
assert.equal(variantStatusLabel(1), '处理中')
assert.equal(variantStatusLabel(2), '已完成')
assert.equal(variantStatusLabel(3), '处理失败')
assert.equal(variantStatusLabel(2), '成功')
assert.equal(variantStatusLabel(3), '失败')
assert.equal(variantStatusLabel(9), '未知')
assert.equal(variantStatusLabel(null), '未知')
assert.equal(variantStatusLabel('2'), '已完成', '字符串数字同样识别')
assert.equal(variantStatusLabel('2'), '成功', '字符串数字同样识别')
})
/**
* 变体采集页签只讲「在跑」(2026-10-04 用户口径:历史彻底不看):
* 状态下拉必须收掉 2 已完成 / 3 处理失败 两个入口,空值改成「在跑」而不是「全部状态」——
* 文案留着「全部状态」会让用户以为后端还在给他合并历史。
* 变体采集状态四态(2026-10-05 用户定案,取代同日早先「只看在跑」的口径):
* 空值恢复「全部状态」,2 成功 / 3 失败 回列入口,「在跑」合并口径从下拉与文案里彻底撤掉。
*/
test('task_center_variant_status_options_drop_history_states', () => {
test('task_center_variant_status_options_are_the_four_states', () => {
assert.deepEqual(VARIANT_STATUS_OPTIONS, [
{ value: '', label: '在跑' },
{ value: '0', label: '等待执行' },
{ value: '', label: '全部状态' },
{ value: '0', label: '待执行' },
{ value: '1', label: '处理中' },
{ value: '2', label: '成功' },
{ value: '3', label: '失败' },
])
const values = VARIANT_STATUS_OPTIONS.map((o) => o.value)
assert.equal(values.includes('2'), false, '已完成不再是可选项')
assert.equal(values.includes('3'), false, '处理失败不再是可选项')
const page = readSource(PAGE)
assert.match(page, /只看在跑/, '面板说明写明只看在跑')
assert.match(page, /title="麦象在跑批量任务条数/, '徽章 tooltip 是在跑口径不是全部状态')
assert.equal(/麦象批量任务条数(全部状态)/.test(page), false)
assert.equal(/只看在跑/.test(page), false, '面板说明不再写只看在跑')
assert.match(page, /title="麦象变体采集任务条数(全部状态)/, '徽章 tooltip 换成全部状态口径')
assert.match(page, /默认全部状态(待执行\/处理中\/成功\/失败)/, '面板说明写明四态')
})
test('task_center_device_display_falls_back_to_truncated_id', () => {
@@ -211,6 +218,25 @@ test('task_center_progress_bar_is_dropped_when_there_is_no_progress', () => {
assert.match(page, /<div class="p-track" v-if="row\.progressTotal > 0">/, '无进度时不画进度轨')
})
/**
* 失败任务的进度列(2026-10-04 用户要求):失败任务的进度快照要么冻在中间阶段、
* 要么按构建单位写满格,列表继续画「已完成 N / 总 N」+ 满格条会被读成「跑完了」——
* 失败行(含详情抽屉)只给失败徽标,不给进度条也不说「已完成」。
*/
test('task_center_failed_rows_never_render_a_progress_bar', () => {
const page = readSource(PAGE)
for (const scope of ['row', 'detail']) {
const branch = new RegExp(
`<template v-if="taskStatusType\\(${scope}\\.status\\) === 'failed'">[\\s\\S]{0,400}?</template>`,
).exec(page)
assert.ok(branch, `${scope} 的失败分支存在`)
assert.equal(branch[0].includes('p-track'), false, '失败分支不画进度轨')
assert.equal(branch[0].includes('progressText'), false, '失败分支不说「已完成 X / 总 Y」')
assert.match(branch[0], /badge danger/, '有失败数时给红色失败徽标')
assert.match(branch[0], /v-else/, '无失败数时画「—」')
}
})
test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
const query = buildTaskQuery(
{ username: ' 张三 ', moduleType: 'COLLECT_DATA', status: 'RUNNING', shop: '林芳旗舰店', startTime: '2026-09-28T10:00', endTime: '' },
@@ -232,7 +258,7 @@ test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
test('task_center_variant_query_builder_keeps_paging', () => {
const empty = buildVariantQuery({ status: '' }, 1, 20)
assert.equal(empty.status, undefined, '空状态不下传 status ⇒ 后端按在跑(0∪1)合并')
assert.equal(empty.status, undefined, '空状态不下传 status ⇒ 后端返回全部状态')
assert.equal(empty.page, 1)
const filtered = buildVariantQuery({ status: '1' }, 3, 50)
assert.equal(filtered.status, 1)
@@ -254,7 +280,7 @@ test('task_center_filter_reset_clears_every_field', () => {
test('task_center_page_handles_empty_and_error_states', () => {
const page = readSource(PAGE)
assert.match(page, /暂无符合条件的任务/, '任务空态')
assert.match(page, /暂无在跑的变体采集任务/, '变体空态:口径是在跑不是全部')
assert.match(page, /暂无变体采集任务/, '变体空态:四态口径下不再限定「在跑」')
assert.match(page, /ElMessage\.error/, '接口失败提示')
assert.match(page, /resetFilter/, '筛选重置接线')
assert.match(page, /@size-change="changeTaskSize"/, '分页每页条数切换')
@@ -311,8 +337,8 @@ test('task_center_country_column_is_display_only', () => {
const page = readSource(PAGE)
assert.match(page, /<th style="width: 90px">国家<\/th>/, '国家列在店铺与业务之间')
assert.match(page, /<td class="mono">\{\{ row\.country \|\| '—' \}\}<\/td>/,
'取不到国家画「—」:七条 JSON 路径只覆盖约七成行,留白会被读成数据缺失')
assert.match(page, /<td>\{\{ countryLabel\(row\.country\) \}\}<\/td>/,
'国家码转中文展示(UK→英国),空值由 countryLabel 画「—」')
assert.equal(readSource(API).includes('country: string | null'), true, '接口类型带 country 且可为 null')
// 只加列,不做筛选(用户 2026-10-04 定案):不许冒出国家筛选或 country 查询参数
@@ -321,25 +347,41 @@ test('task_center_country_column_is_display_only', () => {
'查询参数不带 country')
})
/** 国家码 → 中文(用户 2026-10-04 要求):复用 ASIN 五国共享字典,逐段转,未知码原样保留。 */
test('task_center_country_labels_are_chinese_with_passthrough_for_unknown', () => {
assert.equal(countryLabel('UK'), '英国')
assert.equal(countryLabel('DE'), '德国')
assert.equal(countryLabel('FR'), '法国')
assert.equal(countryLabel('UK/DE'), '英国/德国', '多国家逐段转(后端用 / 连)')
assert.equal(countryLabel('UK / DE'), '英国/德国', '带空格的段先归一')
assert.equal(countryLabel('US'), 'US', '字典外国家码原样保留,不装死')
assert.equal(countryLabel(null), '—', '无国家的模块画「—」')
assert.equal(countryLabel(''), '—')
assert.equal(countryLabel(' '), '—')
})
/**
* 默认「在跑」(用户 2026-10-04 要求:其他状态保留,但默认看执行中的):
* 默认「执行中」(2026-10-04 状态三态收敛,取代同日早先「历史状态保留入口」的口径):
* ACTIVE 是三个进行中状态的合并哨兵,展开发生在后端,所以这里只钉
* ① 选项在位且排在「全部状态」之后,② 页面默认值与重置都走它,③ createTaskFilter 仍是全空
* ① 选项四项:全部状态/执行中/成功/失败(待执行/已排期/已取消不再单独出现),
* ② 页面默认值与重置都走它,③ createTaskFilter 仍是全空
* (全空 = 不裁剪,是「重置到无筛选」语义的底座,页面默认值再覆盖上去)。
*/
test('task_center_defaults_to_the_merged_active_status', () => {
assert.equal(TASK_STATUS_OPTIONS[0].value, '', '首项仍是全部状态')
assert.equal(TASK_STATUS_OPTIONS[1].value, ACTIVE_TASK_STATUS, '第二项就是默认的在跑')
assert.equal(TASK_STATUS_OPTIONS[1].value, ACTIVE_TASK_STATUS, '第二项就是默认的执行中')
assert.deepEqual(TASK_STATUS_OPTIONS.map((o) => o.value),
['', 'ACTIVE', 'PENDING', 'RUNNING', 'SCHEDULED', 'SUCCESS', 'FAILED', 'CANCELLED'],
'七个状态一个不少(用户要求历史状态保留入口)')
['', 'ACTIVE', 'SUCCESS', 'FAILED'],
'三态收敛:待执行/已排期/已取消不再单独设选项')
assert.deepEqual(TASK_STATUS_OPTIONS.map((o) => o.label),
['全部状态', '执行中', '成功', '失败'])
assert.equal(buildTaskQuery({ ...createTaskFilter(), status: ACTIVE_TASK_STATUS }, 1, 20).status, 'ACTIVE',
'哨兵原样下传,展开在后端做')
assert.equal(createTaskFilter().status, '', 'createTaskFilter 保持全空')
const page = readSource(PAGE)
assert.match(page, /status: ACTIVE_TASK_STATUS/, '页面默认筛在跑')
assert.match(page, /Object\.assign\(filter, defaultTaskFilter\(\)\)/, '重置回到默认「在跑」而不是全部状态')
assert.match(page, /status: ACTIVE_TASK_STATUS/, '页面默认筛执行中')
assert.match(page, /Object\.assign\(filter, defaultTaskFilter\(\)\)/, '重置回到默认「执行中」而不是全部状态')
})
// 2026-10-04 生产对不上账:卡片「进行中任务」的 SQL 不带创建时间窗(实测 39 个),
@@ -376,6 +418,17 @@ test('task_center_page_wires_tabs_filters_and_polling', () => {
assert.equal(/shopName/.test(readSource(PAGE)), true)
})
/**
* 变体表「结果信息」列不再附带 taskData 原始 JSON(2026-10-05 用户要求):
* 那是任务原始入参(file_url/execute_country/proxy_url/proxy_mode),proxy_url
* 内含代理提取 key,写在页面上等于把凭据挂出来。接口层仍透传该字段
* (task-center.ts 的类型保持如实),只是页面不渲染。
*/
test('task_center_variant_result_column_dumps_no_raw_task_data', () => {
const page = readSource(PAGE)
assert.doesNotMatch(page, /taskData/, '变体表不再渲染 task_data 原始 JSON')
})
/**
* 页签徽章的两个口径缺陷:
* ① 「客户端任务」曾绑列表 total(默认全部状态、全部时间 = 历史全量,线上 1135 条,
+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;
}
@@ -2139,10 +2139,18 @@ public class AppearancePatentTaskService {
if (previousDisplayPercent > displayPercent && safeCompleted < safeTotal) {
displayPercent = previousDisplayPercent;
}
// 终态必须带任务真实状态落库:save() 只对终态豁免 500ms 节流,收尾三连写(组装/上传/完成)
// 都在同一次调用里,若全按 RUNNING 写,只有第一条落地,满格「结果文件已生成」必被吞——
// 看板就会永远停在 0/N 或 N-2/N(2026-10-04 生产实测)。对齐货源查询 isTerminalFileBuildProgress。
boolean terminalProgress = safeCompleted >= safeTotal
&& (STATUS_SUCCESS.equals(task.getStatus()) || STATUS_FAILED.equals(task.getStatus()));
if (terminalProgress) {
displayPercent = 100;
}
taskProgressSnapshotService.save(
task.getId(),
MODULE_TYPE,
STATUS_RUNNING,
terminalProgress ? task.getStatus() : STATUS_RUNNING,
safeTotal,
safeCompleted,
0,
@@ -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) {
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.imagehistory.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.imagehistory.model.vo.ImageHistoryListVo;
import com.nanri.aiimage.modules.imagehistory.service.ImageHistoryService;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
@@ -28,6 +29,7 @@ public class ImageHistoryController {
private final AdminAuthSupport adminAuthSupport;
private final ImageHistoryService imageHistoryService;
private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@GetMapping("/history")
@Operation(summary = "分页查询所有用户生成历史")
@@ -36,12 +38,16 @@ public class ImageHistoryController {
@RequestParam(name = "page_size", required = false, defaultValue = "15") Integer pageSize,
@RequestParam(name = "user_id", required = false) Long userId,
@RequestParam(name = "time_start", required = false) String timeStart,
@RequestParam(name = "time_end", required = false) String timeEnd) {
@RequestParam(name = "time_end", required = false) String timeEnd,
@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
if (!permissionMenuService.hasAnyAdminMenu(operator, List.of("admin_history"))) {
throw new BusinessException(403, "无权访问生成记录模块");
}
ImageHistoryListVo vo = imageHistoryService.listHistory(page, pageSize, userId, timeStart, timeEnd);
// 既有语义保留:显式传 user_id 时按那一个人筛;公司 tab 叠在它上面(交集)。
List<Long> base = userId != null && userId > 0 ? List.of(userId) : null;
List<Long> scoped = dataReadScope.readScope(operator, companyId).userIdsOr(base);
ImageHistoryListVo vo = imageHistoryService.listHistory(page, pageSize, userId, timeStart, timeEnd, scoped);
return ApiResponse.success(vo);
}
@@ -43,19 +43,31 @@ public class ImageHistoryService {
private final ObjectMapper objectMapper;
public ImageHistoryListVo listHistory(Integer page, Integer pageSize, Long userId,
String timeStart, String timeEnd) {
String timeStart, String timeEnd, List<Long> userIds) {
int safePage = page == null || page < 1 ? 1 : page;
int safeSize = pageSize == null ? 15 : pageSize;
if (safeSize < 10) safeSize = 10;
if (safeSize > 50) safeSize = 50;
if (userIds != null && userIds.isEmpty()) {
// 空集 = 这个公司在这页没有任何成员账号 ⇒ 空页。绝不退化成"不筛"(那是越权);
// 也绝不把 [] 交给 filterOf:MP 的 in(boolean, …) 只看 condition 不看集合空不空,
// [] 会渲染成 `IN ()`(MySQL 语法错 → 500)。两条都由 ImageHistoryServiceTest 钉着。
ImageHistoryListVo empty = new ImageHistoryListVo();
empty.setItems(List.of());
empty.setTotal(0L);
empty.setPage(safePage);
empty.setPageSize(safeSize);
return empty;
}
LocalDateTime startDt = parseDateTime(timeStart, false);
LocalDateTime endDt = parseDateTime(timeEnd, true);
Long total = imageHistoryMapper.selectCount(filterOf(userId, startDt, endDt));
Long total = imageHistoryMapper.selectCount(filterOf(userId, userIds, startDt, endDt));
// 先只取本页 id(仅排 id/时间小列,避免对大文本 filesort 撑爆 sort buffer),再按 id 取行。
LambdaQueryWrapper<ImageHistoryEntity> idPage = filterOf(userId, startDt, endDt)
LambdaQueryWrapper<ImageHistoryEntity> idPage = filterOf(userId, userIds, startDt, endDt)
.select(ImageHistoryEntity::getId)
.orderByDesc(ImageHistoryEntity::getCreatedAt);
int offset = (safePage - 1) * safeSize;
@@ -89,12 +101,20 @@ public class ImageHistoryService {
return removed;
}
/** 按用户/时间范围构造筛选条件(不排序、不分页)。 */
private LambdaQueryWrapper<ImageHistoryEntity> filterOf(Long userId, LocalDateTime startDt, LocalDateTime endDt) {
/**
* 按用户/公司成员集/时间范围构造筛选条件(不排序、不分页)。
*
* <p>总数与 id 页共用它,所以两条天然同范围。</p>
*/
private LambdaQueryWrapper<ImageHistoryEntity> filterOf(Long userId, List<Long> userIds,
LocalDateTime startDt, LocalDateTime endDt) {
LambdaQueryWrapper<ImageHistoryEntity> filter = new LambdaQueryWrapper<>();
if (userId != null && userId > 0) {
filter.eq(ImageHistoryEntity::getUserId, userId);
}
// userIds 由 controller 经 DataReadScope 算好:null = 不筛(超管没选公司,今天的行为),
// 非 null = 只查这批账号。空集在 listHistory 已拦,这里不会收到 []。
filter.in(userIds != null, ImageHistoryEntity::getUserId, userIds);
if (startDt != null) {
filter.ge(ImageHistoryEntity::getCreatedAt, startDt);
}
@@ -2,6 +2,8 @@ package com.nanri.aiimage.modules.imagevideo.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.imagevideo.service.ImageVideoAdminTaskService;
@@ -63,6 +65,7 @@ public class AdminImageVideoTaskController {
private final ImageVideoAdminTaskService adminTaskService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping
@Operation(summary = "分页查询图生视频任务", description = "管理端按用户/任务状态/提交时间等条件分页查询近 3 天的工作流任务")
@@ -75,8 +78,12 @@ public class AdminImageVideoTaskController {
@RequestParam(name = "coze_execute_id", required = false) String executeId,
@RequestParam(name = "submitted_from", required = false) String submittedFrom,
@RequestParam(name = "submitted_to", required = false) String submittedTo,
@RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) {
adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
// 既有语义保留:显式传 user_id 时按那一个人筛;公司 tab 叠在它上面(交集)。
List<Long> base = userId != null && userId > 0 ? List.of(userId) : null;
List<Long> scoped = dataReadScope.readScope(operator, companyId).userIdsOr(base);
int safePage = Math.max(1, page == null ? 1 : page);
int safePageSize = Math.min(100, Math.max(10, pageSize == null ? 20 : pageSize));
String cleanUsername = username == null ? null : username.trim();
@@ -84,26 +91,26 @@ public class AdminImageVideoTaskController {
String cleanExecuteId = executeId == null ? null : executeId.trim();
LocalDateTime from = parseAdminDatetimeParam("submitted_from", submittedFrom);
LocalDateTime to = parseAdminDatetimeParam("submitted_to", submittedTo);
log.info("[image-video] 管理端查询图生视频任务 page={} pageSize={} userId={} username={} status={}",
safePage, safePageSize, userId, cleanUsername, cleanStatus);
log.info("[image-video] 管理端查询图生视频任务 page={} pageSize={} userId={} username={} status={} "
+ "companyId={}", safePage, safePageSize, userId, cleanUsername, cleanStatus, companyId);
return ApiResponse.success(adminTaskService.page(userId, cleanUsername, cleanStatus,
cleanExecuteId, from, to, safePage, safePageSize));
cleanExecuteId, from, to, safePage, safePageSize, scoped));
}
@GetMapping("/{taskId}")
@Operation(summary = "查询图生视频任务详情", description = "返回单个任务详情(含脱敏后的请求参数与结果 JSON)")
public ApiResponse<Map<String, Object>> detail(@PathVariable Long taskId, HttpServletRequest request) {
adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(adminTaskService.detail(taskId));
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(adminTaskService.detail(taskId, scopeOf(operator)));
}
@PostMapping("/download-zip")
@Operation(summary = "批量打包下载视频", description = "按任务+视频下标批量打包 zip;部分失败通过响应头 X-Archive-Error-Count 提示")
public ResponseEntity<StreamingResponseBody> downloadZip(@RequestBody(required = false) Map<String, Object> body,
HttpServletRequest request) {
adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
List<VideoSelection> selections = parseSelections(body);
ZipBundle bundle = adminTaskService.buildZip(selections);
ZipBundle bundle = adminTaskService.buildZip(selections, scopeOf(operator));
String filename = "video-tasks-" + LocalDateTime.now().format(ZIP_FILENAME_FORMATTER) + ".zip";
StreamingResponseBody stream = outputStream -> writeZipFile(bundle.file(), outputStream);
return ResponseEntity.ok()
@@ -114,6 +121,15 @@ public class AdminImageVideoTaskController {
.body(stream);
}
/**
* 按 id 的两个读出口(详情/打包下载)与列表同一把范围,判据都是行主人落不落得进同一批成员集。
* <p>它们收不到 tab 的公司 id(tab 不是安全边界),所以 base 与 requestedCompanyId 都传 null:
* 超管=不筛(返回 null),非超管/内部令牌=按会话裁剪到本公司成员。</p>
*/
private List<Long> scopeOf(AdminUserEntity operator) {
return dataReadScope.readScope(operator, null).userIdsOr(null);
}
private void writeZipFile(Path file, OutputStream output) throws IOException {
try (InputStream input = Files.newInputStream(file)) {
input.transferTo(output);
@@ -35,6 +35,9 @@ public interface ImageVideoAdminTaskMapper {
WHERE t.task_type = 'IMAGE_VIDEO_WORKFLOW'
AND t.submitted_at &gt;= DATE_SUB(NOW(), INTERVAL 3 DAY)
<if test="userId != null"> AND t.user_id = #{userId}</if>
<if test="userIds != null"> AND t.user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
</if>
<if test="username != null and username != ''"> AND u.username LIKE CONCAT('%', #{username}, '%')</if>
<if test="status != null and status != ''"> AND t.status = #{status}</if>
<if test="executeId != null and executeId != ''"> AND t.coze_execute_id LIKE CONCAT('%', #{executeId}, '%')</if>
@@ -46,6 +49,7 @@ public interface ImageVideoAdminTaskMapper {
""")
List<Map<String, Object>> selectAdminTaskPage(
@Param("userId") Long userId,
@Param("userIds") List<Long> userIds,
@Param("username") String username,
@Param("status") String status,
@Param("executeId") String executeId,
@@ -62,6 +66,9 @@ public interface ImageVideoAdminTaskMapper {
WHERE t.task_type = 'IMAGE_VIDEO_WORKFLOW'
AND t.submitted_at &gt;= DATE_SUB(NOW(), INTERVAL 3 DAY)
<if test="userId != null"> AND t.user_id = #{userId}</if>
<if test="userIds != null"> AND t.user_id IN
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
</if>
<if test="username != null and username != ''"> AND u.username LIKE CONCAT('%', #{username}, '%')</if>
<if test="status != null and status != ''"> AND t.status = #{status}</if>
<if test="executeId != null and executeId != ''"> AND t.coze_execute_id LIKE CONCAT('%', #{executeId}, '%')</if>
@@ -71,6 +78,7 @@ public interface ImageVideoAdminTaskMapper {
""")
Long countAdminTaskPage(
@Param("userId") Long userId,
@Param("userIds") List<Long> userIds,
@Param("username") String username,
@Param("status") String status,
@Param("executeId") String executeId,
@@ -79,7 +87,7 @@ public interface ImageVideoAdminTaskMapper {
@Select("""
<script>
SELECT t.id, t.video_urls_json, t.archived_videos_json
SELECT t.id, t.user_id, t.video_urls_json, t.archived_videos_json
FROM biz_image_video_async_task t
WHERE t.task_type = 'IMAGE_VIDEO_WORKFLOW'
AND t.submitted_at &gt;= DATE_SUB(NOW(), INTERVAL 3 DAY)
@@ -70,15 +70,27 @@ public class ImageVideoAdminTaskService {
/**
* 分页查询图生视频工作流任务,返回 {items, total, page, page_size}。
*
* <p>{@code userIds} 是 controller 经 {@code DataReadScope} 算好的公司成员集:
* {@code null} = 不筛(超管没选公司,保持今天的行为),空集 = 这家公司没有成员账号。</p>
*/
public Map<String, Object> page(Long userId, String username, String status, String executeId,
LocalDateTime submittedFrom, LocalDateTime submittedTo,
int page, int pageSize) {
int page, int pageSize, List<Long> userIds) {
if (userIds != null && userIds.isEmpty()) {
// 空集 = 这个公司今天没有任何成员账号 ⇒ 空页。绝不退化成"不筛"(那是越权)。
Map<String, Object> empty = new LinkedHashMap<>();
empty.put("items", List.of());
empty.put("total", 0L);
empty.put("page", (long) page);
empty.put("page_size", (long) pageSize);
return empty;
}
int offset = (page - 1) * pageSize;
List<Map<String, Object>> rows = adminTaskMapper.selectAdminTaskPage(
userId, username, status, executeId, submittedFrom, submittedTo, pageSize, offset);
userId, userIds, username, status, executeId, submittedFrom, submittedTo, pageSize, offset);
Long total = adminTaskMapper.countAdminTaskPage(
userId, username, status, executeId, submittedFrom, submittedTo);
userId, userIds, username, status, executeId, submittedFrom, submittedTo);
List<Map<String, Object>> items = new ArrayList<>(rows.size());
for (Map<String, Object> row : rows) {
items.add(toListItem(row, false));
@@ -93,19 +105,27 @@ public class ImageVideoAdminTaskService {
/**
* 单任务详情(含 request/submit_response/result 原始 JSON,request 脱敏)。
*
* <p>闸门与列表同一把范围(spec §6.1「列表筛了、按 id 照读」= 越权):
* {@code userIds} 非 null 而行主人不在里面 ⇒ 403;404 只留给真查不到行。</p>
*/
public Map<String, Object> detail(Long taskId) {
public Map<String, Object> detail(Long taskId, List<Long> userIds) {
Map<String, Object> row = adminTaskMapper.selectAdminTaskDetail(taskId);
if (row == null) {
throw new BusinessException(404, "视频任务不存在或无权访问");
throw new BusinessException(404, "视频任务不存在");
}
assertRowInScope(row, userIds);
return Map.of("item", toListItem(row, true));
}
/**
* 批量打包下载选中的视频。逐文件远程拉取写入 zip,部分失败时记录错误清单文件。
*
* <p>范围闸门在打包之前:一次请求里任一条越界就整单 403,绝不并进
* {@code X-Archive-Error-Count} 的"部分失败"语义(那是给拉不到文件用的,
* 拿它掩盖越权等于把越权报成网络问题)。</p>
*/
public ZipBundle buildZip(List<VideoSelection> selections) {
public ZipBundle buildZip(List<VideoSelection> selections, List<Long> userIds) {
List<Long> taskIds = selections.stream()
.map(VideoSelection::taskId)
.distinct()
@@ -113,6 +133,7 @@ public class ImageVideoAdminTaskService {
.collect(Collectors.toList());
Map<Long, Map<String, Object>> tasks = new HashMap<>();
for (Map<String, Object> row : adminTaskMapper.selectAdminZipRows(taskIds)) {
assertRowInScope(row, userIds);
if (row.get("id") instanceof Number id) {
tasks.put(id.longValue(), row);
}
@@ -187,6 +208,20 @@ public class ImageVideoAdminTaskService {
}
}
/**
* 行主人落不落得进列表那条同样的成员集:{@code userIds == null} 才是"这一页不筛",
* 空集与非 null 集合都按"落不进就 403"处理(读不出主人同样算越界,不放行)。
*/
private void assertRowInScope(Map<String, Object> row, List<Long> userIds) {
if (userIds == null) {
return;
}
Object ownerId = row.get("user_id");
if (!(ownerId instanceof Number owner) || !userIds.contains(owner.longValue())) {
throw new BusinessException(403, "该任务不属于当前公司");
}
}
private HttpURLConnection openRemoteConnection(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
connection.setConnectTimeout(HTTP_CONNECT_TIMEOUT_MILLIS);
@@ -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);
}
@@ -84,10 +84,10 @@ public class AdminTaskCenterController {
}
@GetMapping("/variant-tasks")
@Operation(summary = "变体采集列表(只看在跑)",
@Operation(summary = "变体采集列表(全部状态)",
description = "代理麦象 console 批量任务(默认只看 variant-collection):非超管按可见用户 uid 过滤,"
+ "超管看全部;麦象未配置或不可达时返回空页。status 为麦象状态码:0 等待/1 处理中/2 已完成/3 失败;"
+ "不传 status = 只看在跑(0∪1 合并,历史不再展示)。")
+ "超管看全部;麦象未配置或不可达时返回空页。status 为麦象状态码:0 待执行/1 处理中/2 成功/3 失败;"
+ "不传 status = 全部状态(2026-10-05 定案:撤掉在跑合并口径)。")
public ApiResponse<TaskCenterVariantPageVo> variantTasks(HttpServletRequest request,
@RequestParam(required = false) Integer status,
@RequestParam(required = false) String taskType,
@@ -55,6 +55,15 @@ public interface TaskCenterQueryMapper {
/** 状态筛选的合并哨兵值:它不是表里的状态,服务层负责展开成 {@link #ACTIVE_STATUSES_ORDERED}。 */
String ACTIVE_STATUS_SENTINEL = "ACTIVE";
/**
* 前端「成功」筛选项的展开口径(2026-10-04 状态三态收敛:只留 执行中/成功/失败):
* COMPLETED 是完成态的历史拼写,展示上已并入成功,筛选必须命中同样的行。
*/
List<String> SUCCESS_STATUSES_ORDERED = List.of("SUCCESS", "COMPLETED");
/** 前端「失败」筛选项的展开口径:ERROR 与取消/出错都按「没成功」并入失败(SQL 里 CANCELED 已归一为 CANCELLED)。 */
List<String> FAILED_STATUSES_ORDERED = List.of("FAILED", "ERROR", "CANCELLED");
/** biz_file_task 终态(CANCELLED 与历史脏值 CANCELED 并存)。 */
Set<String> TERMINAL_STATUS_SET = Set.of("SUCCESS", "FAILED", "CANCELLED", "CANCELED");
@@ -130,9 +130,10 @@ public class TaskCenterQueryService {
}
/**
* 状态筛选展开:空白 = 不裁剪;{@code ACTIVE} = 前端默认的「在跑」,等于三个进行中状态的合并
* (与判卡住用的 {@link #ACTIVE_STATUSES} 同一组,不另定口径);其余按单值下传。
* 品牌表状态本是小写,SQL 里 {@code STATUS_B} 已 UPPER 归一,这里只统一入参大小写。
* 状态筛选展开:空白 = 不裁剪;{@code ACTIVE} = 前端默认的「执行中」,等于三个进行中状态的合并
* (与判卡住用的 {@link #ACTIVE_STATUSES} 同一组,不另定口径);{@code SUCCESS}/{@code FAILED}
* 按三态收敛口径展开同义词(历史拼写 COMPLETED/ERROR 与取消并入,见 mapper 常量);
* 其余按单值下传。品牌表状态本是小写,SQL 里 {@code STATUS_B} 已 UPPER 归一,这里只统一入参大小写。
*/
static List<String> statusFilter(String status) {
if (status == null || status.isBlank()) {
@@ -142,6 +143,12 @@ public class TaskCenterQueryService {
if (TaskCenterQueryMapper.ACTIVE_STATUS_SENTINEL.equals(key)) {
return TaskCenterQueryMapper.ACTIVE_STATUSES_ORDERED;
}
if ("SUCCESS".equals(key)) {
return TaskCenterQueryMapper.SUCCESS_STATUSES_ORDERED;
}
if ("FAILED".equals(key)) {
return TaskCenterQueryMapper.FAILED_STATUSES_ORDERED;
}
return List.of(key);
}
@@ -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 非超管的可见用户集合(至少含本人)
@@ -12,7 +12,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -26,8 +25,8 @@ import java.util.stream.Collectors;
* <p>可见范围靠 uid 过滤实现:非超管把可见用户号拼成逗号分隔的 uid 参数(麦象侧拆分后 IN),
* 超管不传 uid(看全部)。麦象未配置或不可达时返回空页并记日志,页面不因外部依赖炸掉。</p>
*
* <p>不传 status 时只看在跑(等待 0 ∪ 处理中 1):麦象一次只能筛一个状态,
* 服务层各拉一页合并;历史终态不再作为页签默认口径(徽章说的必须是「在跑几条」)。</p>
* <p>不传 status = 全部状态:麦象侧 status 不过滤即返回四态(0 待执行/1 处理中/2 成功/3 失败),
* 分页、total 都由麦象完成,服务层原样透传——2026-10-05 用户定案:撤掉「在跑」合并口径。</p>
*/
@Service
@Slf4j
@@ -37,12 +36,6 @@ public class TaskCenterVariantService {
/** 页签默认只看变体采集这一类批量任务;传 taskType 可覆盖。 */
public static final String VARIANT_TASK_TYPE = "variant-collection";
/** 麦象状态码:0 等待 / 1 处理中,两者合起来才是「在跑」。 */
private static final int STATUS_WAITING = 0;
private static final int STATUS_PROCESSING = 1;
/** 在跑任务正常在几十量级;触顶时 total 仍按麦象回值,但翻页尾部会缺行(记 warn)。 */
private static final int ACTIVE_FETCH_SIZE = 200;
private static final long DEFAULT_PAGE_SIZE = 20;
private static final long MAX_PAGE_SIZE = 100;
@@ -70,43 +63,14 @@ public class TaskCenterVariantService {
String uidsCsv = scope.allUsers() ? null
: scope.visibleUserIds().stream().sorted().map(String::valueOf).collect(Collectors.joining(","));
int size = (int) normalizedSize;
if (status != null) {
BatchTaskPage maixiang = consoleClient.batchTasksPage(uidsCsv, status, type,
(int) normalizedPage, size);
vo.setTotal(maixiang.total());
vo.setItems(assemble(maixiang.items()));
return vo;
}
// 不传状态 = 只看在跑(用户 2026-10-04 定案:历史的不看了)。
// 麦象一次只能筛一个状态,等待(0) 与处理中(1) 各拉一页后在内存合并分页。
BatchTaskPage waiting = consoleClient.batchTasksPage(uidsCsv, STATUS_WAITING, type, 1, ACTIVE_FETCH_SIZE);
BatchTaskPage processing = consoleClient.batchTasksPage(uidsCsv, STATUS_PROCESSING, type, 1, ACTIVE_FETCH_SIZE);
List<BatchTaskItem> active = new ArrayList<>(waiting.items());
active.addAll(processing.items());
active.sort(Comparator.comparing(BatchTaskItem::createTime,
Comparator.nullsLast(Comparator.reverseOrder())));
// total 用麦象回值(-1 哨兵或缺字段时回落为已拉到的行数),保证徽章说的是「在跑」而不是历史全量。
long total = effectiveTotal(waiting) + effectiveTotal(processing);
vo.setTotal(total);
if (total > active.size()) {
log.warn("[task-center] 变体采集在跑数 {} 超过单状态拉取上限 {},翻页尾部会缺行",
total, ACTIVE_FETCH_SIZE);
}
long from = (normalizedPage - 1) * normalizedSize;
if (from >= active.size()) {
return vo;
}
long to = Math.min(from + normalizedSize, active.size());
vo.setItems(assemble(active.subList((int) from, (int) to)));
// status 直传麦象:null = 全部状态(待执行/处理中/成功/失败),分页与 total 都由麦象完成。
BatchTaskPage maixiang = consoleClient.batchTasksPage(uidsCsv, status, type,
(int) normalizedPage, (int) normalizedSize);
vo.setTotal(maixiang.total());
vo.setItems(assemble(maixiang.items()));
return vo;
}
private static long effectiveTotal(BatchTaskPage page) {
return Math.max(page.total(), page.items().size());
}
/** uid → 账号名映射只对数字 uid 生效;麦象任务可能带非数字伪 uid(如 collect-27475)。 */
private List<TaskCenterVariantTaskVo> assemble(List<BatchTaskItem> items) {
Set<Long> userIds = new LinkedHashSet<>();
@@ -162,13 +126,13 @@ public class TaskCenterVariantService {
}
}
/** 麦象状态码:0 等待 / 1 处理中 / 2 已完成 / 3 失败;未识别的一律「未知」不冒充成功。 */
/** 麦象状态码四态文案(2026-10-05 用户定案):0 待执行 / 1 处理中 / 2 成功 / 3 失败;未识别的一律「未知」不冒充成功。 */
private static String statusLabel(int status) {
return switch (status) {
case 0 -> "等待执行";
case 0 -> "待执行";
case 1 -> "处理中";
case 2 -> "已完成";
case 3 -> "处理失败";
case 2 -> "成功";
case 3 -> "失败";
default -> "未知";
};
}
@@ -3,6 +3,8 @@ package com.nanri.aiimage.modules.usersecret.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
@@ -43,6 +45,7 @@ public class AdminUserApiSecretController {
private final UserApiSecretService userApiSecretService;
private final UserSecretProperties userSecretProperties;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping
@Operation(summary = "分页查询用户密钥", description = "一行一用户;keyword 匹配用户名,checkStatus 按行级状态筛选。主管只能看自己带的分组成员,超管看全量并可按分组筛选。")
@@ -51,6 +54,7 @@ public class AdminUserApiSecretController {
@Parameter(description = "关键字:用户名") @RequestParam(required = false) String keyword,
@Parameter(description = "行级状态筛选:passed/failed/incomplete/error/unknown") @RequestParam(required = false) String checkStatus,
@Parameter(description = "按数据权限分组筛选(仅超管生效)") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪,越界公司为空页)") @RequestParam(name = "company_id", required = false) Long companyId,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
@@ -60,7 +64,9 @@ public class AdminUserApiSecretController {
query.setGroupId(groupId);
query.setPage(page);
query.setPageSize(pageSize);
return ApiResponse.success(userApiSecretService.adminPage(operator, query));
// 读范围只在 controller 这唯一出口算一次;service 拿到的是算好的范围,自己不判公司。
ReadScope companyScope = dataReadScope.readScope(operator, companyId);
return ApiResponse.success(userApiSecretService.adminPage(operator, query, companyScope));
}
@PostMapping("/{userId}/check")
@@ -2,6 +2,8 @@ package com.nanri.aiimage.modules.usersecret.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretUsageQuery;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretUsagePageVo;
@@ -31,6 +33,7 @@ public class AdminUserSecretUsageController {
private final UserSecretUsageService userSecretUsageService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping
@Operation(summary = "分页查询密钥用量",
@@ -43,6 +46,7 @@ public class AdminUserSecretUsageController {
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@Parameter(description = "关键字:用户名") @RequestParam(required = false) String keyword,
@Parameter(description = "按数据权限分组筛选(仅超管生效)") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪,越界公司为空页)") @RequestParam(name = "company_id", required = false) Long companyId,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
@@ -53,6 +57,8 @@ public class AdminUserSecretUsageController {
query.setGroupId(groupId);
query.setPage(page);
query.setPageSize(pageSize);
return ApiResponse.success(userSecretUsageService.adminPage(operator, query));
// 读范围只在 controller 这唯一出口算一次;service 拿到的是算好的范围,自己不判公司。
ReadScope companyScope = dataReadScope.readScope(operator, companyId);
return ApiResponse.success(userSecretUsageService.adminPage(operator, query, companyScope));
}
}
@@ -7,6 +7,7 @@ import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
import com.nanri.aiimage.modules.notification.service.NotificationService;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
@@ -314,8 +315,9 @@ public class UserApiSecretService implements UserSecretCleanupPort {
* 先按关键字圈定用户,再全量聚合、行级状态筛选、按最近更新时间倒序后内存分页
* (当前规模为用户数×3,内存聚合成本可控;量级上来后可改为 GROUP BY 下推)。
*/
/** 后台分页查询:主管(admin)只看自己带的「数据权限分组」成员;超管看全量、可按分组筛选。 */
public AdminUserSecretPageVo adminPage(AdminUserEntity operator, AdminUserSecretQuery query) {
/** 后台分页查询:主管(admin)只看自己带的「数据权限分组」成员;超管看全量、可按分组与公司筛选。 */
public AdminUserSecretPageVo adminPage(AdminUserEntity operator, AdminUserSecretQuery query,
ReadScope companyScope) {
AdminUserSecretQuery safeQuery = query == null ? new AdminUserSecretQuery() : query;
long page = safeQuery.getPage() == null || safeQuery.getPage() < 1 ? 1L : safeQuery.getPage();
long pageSize = safeQuery.getPageSize() == null || safeQuery.getPageSize() < 1
@@ -323,18 +325,19 @@ public class UserApiSecretService implements UserSecretCleanupPort {
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
Long requestedGroupId = safeQuery.getGroupId();
// 组隔离:主管强制锁定自己带的分组(组长本人 + 名下子账户);超管按 group_id 筛选(空 = 全部)。
List<Long> scopedUserIds = null;
if (superAdmin) {
if (requestedGroupId != null && requestedGroupId > 0) {
scopedUserIds = adminGroupMapper.selectUserIdsByGroupId(requestedGroupId);
}
} else {
scopedUserIds = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
if (scopedUserIds.isEmpty()) {
// 组隔离(主管锁定自己带的分组、超管按 group_id 筛)叠上公司 tab:两条维度取**交集**,
// 公司 tab 只能收窄,绝不放大分组看不到的行;范围本身由 controller 经唯一出口算好交下来。
List<Long> scopedUserIds = scopedUserIds(operator, requestedGroupId, companyScope);
// 空集必须早退:交给下面的 in(...) 会渲染成 IN () → SQL 语法错 → 500。
// 两条日志分开,排障时看得出是「筛空」(范围交集为空)还是「查空」(库里没记录)。
if (scopedUserIds != null && scopedUserIds.isEmpty()) {
if (superAdmin) {
log.info("[user-secret] 后台密钥列表:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={}",
operator.getId(), requestedGroupId);
} else {
log.info("[user-secret] 后台密钥列表:主管名下无子账户,返回空 operatorId={}", operator.getId());
return emptyPageWithGroups(page, pageSize, groupOptions(operator, false));
}
return emptyPageWithGroups(page, pageSize, groupOptions(operator, superAdmin));
}
List<Long> ledGroupIds = superAdmin ? List.of() : userDataScopeSupport.listLedGroupIds(operator.getId());
@@ -399,6 +402,25 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return vo;
}
/**
* 后台列表的可见用户集:组长锁定 ∩ 超管 group_id ∩ 公司 tab。
* <p>{@code null} = 不筛(超管既没选公司也没选分组,今天的行为);<b>空集由调用方早退</b>,
* 不许交给 {@code LambdaQueryWrapper.in(...)}。交集只在 {@link ReadScope#userIdsOr(java.util.List)}
* 这一处发生——service 里不许再写第二个判公司的 if。
*/
List<Long> scopedUserIds(AdminUserEntity operator, Long requestedGroupId, ReadScope companyScope) {
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
List<Long> base = null;
if (superAdmin) {
if (requestedGroupId != null && requestedGroupId > 0) {
base = adminGroupMapper.selectUserIdsByGroupId(requestedGroupId);
}
} else {
base = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
}
return companyScope.userIdsOr(base);
}
/** 分组筛选项:超管=全部;主管=自己带的分组。 */
private List<AdminUserSecretPageVo.GroupOptionVo> groupOptions(AdminUserEntity operator, boolean superAdmin) {
List<ShopManageGroupEntity> groups = superAdmin
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.usersecret.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
@@ -90,7 +91,8 @@ public class UserSecretUsageService {
* 隔离规则同密钥列表:主管只看自己带的「数据权限分组」成员,超管看全量并可按分组筛选;
* 先全量聚合、再按合计次数倒序内存分页(当前规模可控,量级上来后可改 GROUP BY 下推)。
*/
public AdminUserSecretUsagePageVo adminPage(AdminUserEntity operator, AdminUserSecretUsageQuery query) {
public AdminUserSecretUsagePageVo adminPage(AdminUserEntity operator, AdminUserSecretUsageQuery query,
ReadScope companyScope) {
AdminUserSecretUsageQuery safeQuery = query == null ? new AdminUserSecretUsageQuery() : query;
long page = safeQuery.getPage() == null || safeQuery.getPage() < 1 ? 1L : safeQuery.getPage();
long pageSize = safeQuery.getPageSize() == null || safeQuery.getPageSize() < 1
@@ -98,17 +100,18 @@ public class UserSecretUsageService {
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
Long requestedGroupId = safeQuery.getGroupId();
List<Long> scopedUserIds = null;
if (superAdmin) {
if (requestedGroupId != null && requestedGroupId > 0) {
scopedUserIds = adminGroupMapper.selectUserIdsByGroupId(requestedGroupId);
}
} else {
scopedUserIds = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
if (scopedUserIds.isEmpty()) {
// 组隔离(主管锁定自己带的分组、超管按 group_id 筛)叠上公司 tab:取**交集**,公司 tab 只收窄。
List<Long> scopedUserIds = scopedUserIds(operator, requestedGroupId, companyScope);
// 空集必须早退:交给下面的 in(...) 会渲染成 IN () → SQL 语法错 → 500。
// 两条日志分开,排障时看得出是「筛空」(范围交集为空)还是「查空」(库里没记录)。
if (scopedUserIds != null && scopedUserIds.isEmpty()) {
if (superAdmin) {
log.info("[user-secret-usage] 用量统计:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={}",
operator.getId(), requestedGroupId);
} else {
log.info("[user-secret-usage] 用量统计:主管名下无子账户,返回空 operatorId={}", operator.getId());
return emptyPage(page, pageSize, groupOptions(operator, false));
}
return emptyPage(page, pageSize, groupOptions(operator, superAdmin));
}
LambdaQueryWrapper<UserSecretUsageEntity> wrapper = new LambdaQueryWrapper<>();
@@ -207,6 +210,24 @@ public class UserSecretUsageService {
return vo;
}
/**
* 用量统计的可见用户集:组长锁定 ∩ 超管 group_id ∩ 公司 tab(与密钥列表同形)。
* <p>{@code null} = 不筛(超管既没选公司也没选分组);<b>空集由调用方早退</b>,不许交给
* {@code LambdaQueryWrapper.in(...)}。交集只在 {@link ReadScope#userIdsOr(java.util.List)} 这一处发生。
*/
List<Long> scopedUserIds(AdminUserEntity operator, Long requestedGroupId, ReadScope companyScope) {
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
List<Long> base = null;
if (superAdmin) {
if (requestedGroupId != null && requestedGroupId > 0) {
base = adminGroupMapper.selectUserIdsByGroupId(requestedGroupId);
}
} else {
base = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
}
return companyScope.userIdsOr(base);
}
/** 本页行补用户名与分组名(各一次批量查询)。 */
private void fillRowMeta(List<AdminUserSecretUsageRowVo> pageItems) {
List<Long> userIds = pageItems.stream()
@@ -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");
@@ -7,10 +7,10 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -37,23 +37,64 @@ import org.junit.jupiter.api.Test;
* "一个文件多个 handler 只接一个"因此是默认形状,而 Task 8 明写 {@code detail}/{@code download-zip}
* 也要补(评审 I-4b:文件级比对下 list() 没收、detail() 收了 ⇒ 整文件仍绿)。
* 所以按 mapping 注解把文件切成 handler 块,逐块跑两条断言;切不进 handler 的残块
* (package/import/类级注解/字段)由一条<b>显式</b>断言看守,不许静默跳过。</li>
* (package/import/类级注解/字段,以及一支 handler 收口之后、下一支之前的尾随方法)
* 由一条<b>显式</b>断言看守,不许静默跳过(触发形状按第 9 条收窄)。</li>
* <li><b>白名单键是 handler 级</b>(相对 {@code src/main/java} 的路径 + 该 handler 的 mapping 注解文本,
* 形如 {@code .../AdminUserController.java#@GetMapping("/users")})。round 1 用文件级键,往被豁免
* 文件里新加的任何端点会被一并免掉;round 1 的裸文件名版更是让任意包下同名文件自动豁免(评审 I-5)。
* 降级到 handler 级后,{@code hasSize(1)} 钉条目数、liveness 钉"每一项仍对应一个真在收公司 id 的
* handler",并额外咬住"被豁免文件里冒出第二个没点名的公司 id handler"。</li>
* <li><b>断言 A 与 B 用同一个"该 handler 是否收公司 id 参数"谓词</b>({@link Block#takesCompanyParam()})。
* <li><b>断言 A 与 B 用同一个"该 handler 是否收公司 id 参数"谓词</b>({@link Block#takesCompanyParam()},
* B 再按本轮 F-C 收窄到 {@code @RequestParam} 那一族,见下面第 8 条)。
* round 1 的 B 用下划线字面量 {@code company_id} 当触发键、A 用参数形状键,两者不同源 ⇒
* "驼峰参数名 + 真调 readScope + 全文不出现下划线"这种形状 A 绿、B 根本不触发(评审 N1:
* 正是"接口 200、前端发 company_id=、参数恒 null、tab 切了纹丝不动"那一记)。统一谓词后它必红。</li>
* <li><b>"公司参数"判定认声明窗口,不认同行</b>。round 1 要求公司 token 与 {@code @RequestParam}
* 落在同一物理行,本仓签名大量折行({@code AdminUserController:36-43} 一次摊 7 个参数),
* 折行写法就被静默跳过(评审 N2)。现从该 handler 的 mapping 注解行起、到第一个以 <code>{</code>
* 结尾的行为止取"声明窗口",窗口内同时出现 {@code @RequestParam} 与公司 token(排除
* {@code @Operation}/{@code description=} 这类文档串)即算"收公司 id 参数";另把
* {@code request.getParameter("company_id"/"companyId")} 这一族也纳入触发。窗口取不到(整块没有
* 以 <code>{</code> 结尾的行)判红并报块名,不许"窗口取不到就当没有公司参数"。</li>
* 折行写法就被静默跳过(评审 N2)。现从该 handler 的 mapping 注解行起、到<b>方法体开行</b>为止取
* "声明窗口"。方法体开行的判据是<b>可判别</b>的那一条:以 <code>{</code> 结尾<b>且到该行左右括号配平</b>
* (括号只在字符串字面量与行尾注释之外计数)。于是 <code>@ApiResponses({</code> 这类注解数组开行
* (括号未闭合)不会把窗口截在参数表之前(评审 F-B:真树 13 支 controller 有 61 行 {@code ApiResponses},
* {@code ShopManageController.page}、{@code ZiniaoAuthController:44-46} 都是这个形状),
* 而 <code>throws IOException {</code>、折行签名的收尾行 <code>...Long companyId) {</code> 照样收口(N2 仍成立)。
* 窗口内同时出现 {@code @RequestParam} 与公司 token 即算"收公司 id 参数";另把
* {@code request.getParameter("company_id"/"companyId")} 这一族也纳入触发。</li>
* <li><b>出现绑定注解的那一行不是文档行</b>(评审 F-A)。本仓写"被文档化的查询参数"的主流约定是把
* {@code @Parameter(description = "公司 ID")} 与 {@code @RequestParam(name = "company_id")} 挤在同一行:
* 全树 controller 里含 {@code @Parameter(description} 的行 289 行,其中 93 行同行还带
* {@code @RequestParam};{@code ShopManageController.page} 的四个参数<b>全部</b>是这个形状,而它正是
* Task 11 要接线的旗舰端点。round 2 的 {@code isDocLine} 用<b>整行</b> {@code contains("description =")}
* 判定,把这一族真参数整行当文档吃掉 ⇒ 谓词判"没收公司参数"⇒ A、B 都不跑 = 护栏静默绿(相对
* round 1 的覆盖倒退)。现规则:一行里出现绑定注解({@code @RequestParam}/{@code @PathVariable}/
* {@code @ModelAttribute})它就不是文档行;纯文档行({@code @Operation(summary = …)}、单独成行的
* {@code @Parameter(description = …)}、{@code @ApiResponse})仍然排除,免得把 {@code @Operation}
* 文案里提一句 companyId 当成参数声明而误伤别人。</li>
* <li><b>handler 块止于它自己的闭括号</b>(复评"范围外观察 1",本轮第 5 条)。round 2 里最后一个 handler
* 的块一路开到文件尾,于是<b>尾随私有方法</b>里的 {@code readScope(} 能替那支没接出口的 handler 过关
* ——而计划的 Task 11 模板恰恰鼓励在 controller 里写私有收口方法,这一刀会真的放空。现在每个块的主体
* 收口在"与 mapping 注解同缩进的单独 <code>}</code> 行"上,断言 A 只在该块内找 {@code readScope(};
* 最后一个块也一样收口,不许开到 EOF。收口找不到 = 边界不可判定,判红并报块名,绝不退回"整块到文件尾"。</li>
* <li><b>断言 B 只咬绑定注解那一族</b>(评审 F-C)。{@code request.getParameter("company_id")} 这一族的下划线
* 本来就在串里,而那个形状永远给不出 {@code name = "company_id"} 字面量 ⇒ 一支只用 getParameter 且
* <b>确实</b>走了出口的完全合规 handler 会被 B 判红,只能改写法或塞一句无关声明才绿。现 A 由
* {@code viaRequestParam || viaGetParameter} 触发(两种都必须走出口),B 只在 {@code viaRequestParam} 时要求。</li>
* <li><b>结构守卫只在相关时响</b>(评审 F-D)。"窗口不可判定""主体收口不可判定"这两道新守卫若对本文件的
* <b>每一支</b> handler 生效,射程就随取样键一起扩大(今天 3 支、Task 8-12 后约 10 支),别人的
* 无关单行体 handler 会红在一道与他无关的护栏上。现两道都加了同一把 {@code hasCompanyToken} 门槛:
* 块内不出现公司 token 就不判。残块守卫同样从"行里有公司 token 就红"收到"行里既有公司 token、又有
* 参数绑定形状(绑定注解或 {@code getParameter(})才红"——那才是"某支 handler 根本没被切成块"的唯一
* 可观察证据;私有辅助方法或字段里提一句 {@code companyId}(Task 11 就会写)不再误伤。
* 取舍写在这里:这样会漏掉"公司 token 落在 handler 之外但形状不像参数声明"那一族(如类级常量),
* 那一族交给人审与变异测试,换的是"不红在无关代码上"。</li>
* <li><b>算了范围不等于接了出口</b>(复评 I-1;修复轮 1 新增的断言 C)。断言 A 只看 handler 体内有没有
* {@code readScope(} 这个字面量,于是 {@code listHistory(page, pageSize, userId, timeStart, timeEnd,
* scoped)} 的末位实参被改成 {@code null} 时 A、B 全绿——控制方实测 rc=0、9 支用例一支不红。
* 范围"算过"而没"用出去",页面照样看全量。断言 C 因此钉两步:
* ① {@code readScope(} 的结果必须<b>被赋值给一个变量</b>({@code List<Long> scoped = …readScope(…);} 与
* {@code ReadScope s = …readScope(…);} 两种形状都认);找不到赋值目标 = 裸语句、结果被丢掉 ⇒ 红。
* ② 该变量必须出现在 handler 体内<b>另一条方法调用的实参列表</b>里(扣掉它自己那条赋值语句,
* 单层括号够用,今天两页都是这一形)。只要求"在别处被引用一次"不够:
* {@code if (scoped != null) throw …} 是装饰,不算把范围交给谁 ⇒ 控制语句关键字不认。</li>
* </ol>
*
* <p>取样键:可执行行里出现 {@code company_id} <b>或</b> {@code companyId}(裸 token 即入样本,交给逐 handler
@@ -61,7 +102,9 @@ import org.junit.jupiter.api.Test;
* 连窗口判定都不会跑(N2 的静默跳过正是这么发生的)。真实树今天含这两个 token 的 controller 恰有 3 支
* ({@code AdminUserController}/{@code AdminConsoleController}/{@code ZiniaoAuthController}),后两支的公司
* token 只在 {@code @Operation}/{@code item.put} 里、不在 {@code @RequestParam} 声明窗口上 ⇒ 零假阳性,
* 白名单不必重写。</p>
* 白名单不必重写。round 3 没有动这把键(放宽到裸 token 是修 N2 静默跳过的前提),动的是逐 handler 的窗口
* 判定与块边界;上面 F-A/F-B 两条修的正是"进了样本却被谓词判成没收公司参数"的静默绿,取样面不缩,
* 结构守卫与残块守卫的射程按第 9 条收窄到"与公司相关"。</p>
*/
class CompanyIdParamGoesThroughReadScopeTest {
@@ -87,6 +130,16 @@ class CompanyIdParamGoesThroughReadScopeTest {
private static final Set<String> READ_SCOPE_ALLOWLIST =
Set.of("com/nanri/aiimage/modules/admin/controller/AdminUserController.java#@GetMapping(\"/users\")");
/**
* 断言 C 的<b>射程下限</b>(复评 I-1):Task 8 已经接线的两页必须真被 C 扫到。
* 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了
* mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。
*/
private static final String SCOPE_CAUGHT_HISTORY_KEY =
"com/nanri/aiimage/modules/imagehistory/controller/ImageHistoryController.java#@GetMapping(\"/history\")";
private static final String SCOPE_CAUGHT_VIDEO_KEY =
"com/nanri/aiimage/modules/imagevideo/controller/AdminImageVideoTaskController.java#@GetMapping";
private static final String READ_SCOPE_CALL = "readScope(";
private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\"";
private static final String SNAKE_PARAM = "company_id";
@@ -94,6 +147,36 @@ class CompanyIdParamGoesThroughReadScopeTest {
private static final String REQUEST_PARAM = "@RequestParam";
private static final String GET_PARAMETER = "getParameter(";
private static final String WINDOW_OPEN = "{";
private static final String CLOSE_BRACE = "}";
private static final String SEMICOLON = ";";
/**
* 断言 C 第 ① 步的赋值形状:{@code 标识符 =}。比较运算符吃不到——{@code a == b} 的两个 {@code =}
* 前面都不是标识符尾字符({@code =}/{@code空格=} 前面是 {@code =}),{@code !=}/{@code <=}/{@code >=}
* 同理中间隔了别种符号,{@code (ident)\s*=(?!=)} 匹配不上。取<b>最后一个</b>匹配:
* {@code List<Long> scoped = dataReadScope.readScope(…)} 里 {@code Long} 后面跟的是 {@code >},
* 不会被当成目标,目标只能是 {@code scoped}。
*/
private static final Pattern SCOPE_ASSIGNMENT = Pattern.compile("([A-Za-z_$][\\w$]*)\\s*=(?!=)");
/** 断言 C 第 ② 步的消费形状:{@code 名字(实参)},单层括号(现有两页都是这一形)。 */
private static final Pattern CALL_ARGUMENTS =
Pattern.compile("([A-Za-z_$][\\w$]*)\\s*\\(([^()]*)\\)");
/**
* 控制语句关键字:读了变量但<b>没把它交给任何人</b>。{@code if (scoped != null) throw …} 这种装饰
* 若算"接住了",C 就等于没写(复评点名的正是这一族)。
*/
private static final Set<String> NOT_VALUE_CONSUMERS = Set.of(
"if", "for", "while", "switch", "do", "catch", "synchronized", "return", "throw", "else", "try");
/**
* 参数绑定注解(F-A):一行里出现它们,这一行就是<b>真参数声明</b>,无论同行是否还写着
* {@code description =}——本仓 93 行 {@code @Parameter(description = "…") @RequestParam(…)} 挤同一行的
* 主流写法靠这条区分。
*/
private static final List<String> BINDING_ANNOTATIONS =
List.of("@RequestParam", "@PathVariable", "@ModelAttribute");
/** handler 的边界:这些注解组后面跟方法签名的是端点,跟类型声明的是类级。 */
private static final List<String> MAPPING_ANNOTATIONS = List.of(
@@ -113,6 +196,66 @@ class CompanyIdParamGoesThroughReadScopeTest {
}
""";
/**
* 块边界自检样本(第 5 条):handler 自己<b>不</b>走出口,尾随的私有方法里写着 {@code readScope(}。
* 块边界若一路开到 EOF(round 2 的最后一个块正是这样),这一支就静默绿。
* 文本块的去缩进让它第一行缩进 = 0:mapping 行缩进 0、方法闭括号行缩进 0 ⇒ 与真树 controller 的形状同构。
*/
private static final String BLOCK_BOUNDARY_PROBE = """
@GetMapping("/probe")
public String probe(@RequestParam(name = "company_id", required = false) Long companyId) {
return "probe=" + companyId;
}
private String tailCall(Long companyId) {
return String.valueOf(readScope(null, companyId));
}
""";
/**
* 断言 C 的负探针 1:{@code readScope(} 写成裸语句、结果当场丢掉——第 ① 步就该红。
* 这合法 Java(方法调用是合法的表达式语句),不是为了让探针"看起来像坏代码"。
*/
private static final String SCOPE_DISCARD_PROBE = """
@GetMapping("/probe")
public String discard(@RequestParam(name = "company_id", required = false) Long companyId) {
dataReadScope.readScope(null, companyId);
return "ok";
}
""";
/** 断言 C 的负探针 2:变量接住了,但只在 {@code if} 里装饰一次,没交给任何方法调用——第 ② 步该红。 */
private static final String SCOPE_DECOR_PROBE = """
@GetMapping("/probe")
public String decor(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(null, companyId).userIdsOr(null);
if (scoped != null) throw new IllegalStateException("x");
return "ok";
}
""";
/**
* 断言 C 的另一种赋值形状探针:{@code ReadScope s = …readScope(…);}(规格点名的第二形)。
* 今天真树两页都是 {@code List<Long> scoped = …userIdsOr(base);},这一形还没有使用者,
* 但判据必须认它——否则哪天有人改成返回 ReadScope 的写法,红的是护栏而不是接线。
*/
private static final String SCOPE_TYPE_FORM_PROBE = """
@GetMapping("/probe")
public String typed(@RequestParam(name = "company_id", required = false) Long companyId) {
ReadScope s = dataReadScope.readScope(null, companyId);
return String.valueOf(imageVideoAdminTaskService.page(1, 20, s));
}
""";
/** 断言 C 的正探针:接住并且进了另一条调用的实参列表 ⇒ 判据不许恒红。 */
private static final String SCOPE_CAUGHT_PROBE = """
@GetMapping("/probe")
public String caught(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(null, companyId).userIdsOr(null);
return String.valueOf(imageHistoryService.listHistory(1, 15, null, null, null, scoped));
}
""";
@Test
@DisplayName("每个收公司 id 参数的 handler 都走唯一出口,并且显式写了 name = \"company_id\"")
void everyCompanyIdHandlerGoesThroughReadScope() throws IOException {
@@ -130,6 +273,47 @@ class CompanyIdParamGoesThroughReadScopeTest {
"return \"list=\" + companyId;",
"}");
// 口径 7 的自检(本轮第 5 条):块边界必须止于该 handler 自己的闭括号。两条一起写才不是恒真断言——
// 反面证据(整段里确有 readScope()说明 readScope( 只出现在收口之后的尾随方法里。
List<Block> probeBlocks = splitBlocks(sourceLines(BLOCK_BOUNDARY_PROBE)).handlers();
assertThat(probeBlocks)
.as("块边界自检:切块连探针样本里的 handler 都认不出来,扫描无从判定")
.hasSize(1);
Block probe = probeBlocks.get(0);
assertThat(probe.takesCompanyParam())
.as("块边界自检:探针 handler 必须被认成收公司 id 参数,否则下面的边界断言是空跑")
.isTrue();
assertThat(probe.text())
.as("块边界自检:handler 块必须止于与 mapping 注解同缩进的 } 行 —— "
+ "否则尾随私有方法里的 readScope( 会替这支没接出口的 handler 过关")
.doesNotContain(READ_SCOPE_CALL);
assertThat(probe.spanText())
.as("块边界自检的反面证据:readScope( 确实写在收口之后的尾随方法里")
.contains(READ_SCOPE_CALL);
// 断言 C 的判据自检(全局约束 15:每条判据都要有"能红"与"能绿"两个方向的证据):
// 两个负探针必须各自红在第 ①/② 步、一个正探针必须绿,且三个探针都得先被切成
// "1 支 handler + 真收公司 id 参数 + 体内真写了 readScope(" —— 这三条不成立下面的断言就是空跑。
assertThat(scopeProbeReason(SCOPE_DISCARD_PROBE, "SCOPE_DISCARD_PROBE"))
.as("断言 C 自检(负样本 1,第 ① 步):readScope( 写成裸语句、结果被丢掉时必须判红")
.isNotNull()
.contains("范围算了但没接住");
assertThat(scopeProbeReason(SCOPE_DECOR_PROBE, "SCOPE_DECOR_PROBE"))
.as("断言 C 自检(负样本 2,第 ② 步):范围赋给了变量但只在 if 里装饰一次、没交给任何方法调用 ⇒ 同样要红")
.isNotNull()
.contains("实参");
assertThat(scopeProbeReason(SCOPE_CAUGHT_PROBE, "SCOPE_CAUGHT_PROBE"))
.as("断言 C 自检(正样本):范围接住了并当实参传给了 service.listHistory ⇒ 判据不是恒红")
.isNull();
assertThat(scopeProbeReason(SCOPE_TYPE_FORM_PROBE, "SCOPE_TYPE_FORM_PROBE"))
.as("断言 C 自检(第二形):ReadScope s = dataReadScope.readScope(…) 且 s 进了 service.page(…) 的实参 ⇒ 同样要认")
.isNull();
// 断言 C 的分母由本轮实扫得出(不写死数字):扫进射程的 handler 键、走完两步的正样本支数、红因先攒后判。
List<String> scopeCaughtSample = new ArrayList<>();
List<String> scopeDiscarded = new ArrayList<>();
int scopeCaughtHandlers = 0;
List<Path> sampled = sampledControllers();
assertThat(sampled)
.as("取样集非空自检:一条都没扫到说明扫描失效,护栏等于没写")
@@ -137,16 +321,19 @@ class CompanyIdParamGoesThroughReadScopeTest {
for (Path controller : sampled) {
String rel = relativeKey(controller);
List<String> lines = executableLines(read(controller));
List<SrcLine> lines = sourceLines(read(controller));
assertThat(lines).as(rel + " 的可执行行为空:整份文件只剩注释,扫描无从判定").isNotEmpty();
Blocks blocks = splitBlocks(lines);
for (Block handler : blocks.handlers()) {
String where = rel + " 的 handler " + handler.header();
// 声明窗口取不到 = 切块形状失效,绝不能"当作没公司参数"静默放过,必须红并报块名。
if (handler.windowUndeterminable()) {
fail(where + " 里找不到以 " + WINDOW_OPEN + " 结尾的行,无法确定声明窗口 —— "
+ "切块形状失效(折行签名/单行体等),必须人工核对,不许当作\"该 handler 没收公司参数\"静默跳过");
// 结构守卫(F-D:只在相关时响——块内没有公司 token 就不判,免得别人红在无关护栏上)。
// 窗口/主体收口取不到 = 切块形状失效,绝不能"当作没公司参数"、也不能把块边界退到
// 下一支 handler 或文件尾(那样尾随私有方法里的 readScope( 会替这支过关),必须红并报块名。
String structure = handler.structureFailure();
if (structure != null && handler.hasCompanyTokenInSpan()) {
fail(where + structure + " —— 切块形状失效(单行体、闭括号缩进与 mapping 注解不一致等),"
+ "必须人工核对,不许当作\"该 handler 没收公司参数\"静默跳过");
}
// A 与 B 共用同一个参数形状谓词(N1:触发键必须同源,否则"驼峰+走了出口"的错没人看守)。
boolean takesCompanyParam = handler.takesCompanyParam();
@@ -156,23 +343,54 @@ class CompanyIdParamGoesThroughReadScopeTest {
.as(where + " 收了公司 id 参数,但该 handler 体内没有出现 readScope( —— 文件里别处接了不算")
.contains(READ_SCOPE_CALL);
}
// 断言 B:收了公司 id 参数的 handler 必须写显式 name=(白名单不豁免这条)。
if (takesCompanyParam) {
// 断言 B:显式 name= 只咬 @RequestParam 那一族(F-C:getParameter("company_id") 的下划线
// 本来就在串里,那个形状永远给不出 name = "company_id",合规写法不该被逼着改写法才绿)。
if (handler.viaRequestParam()) {
assertThat(handler.text())
.as(where + " 的公司 id 参数没写显式 name = \"company_id\"")
.contains(EXPLICIT_PARAM_NAME);
}
// 断言 C(复评 I-1):体内写了 readScope( 只说明"算过",不说明"用出去了"。
// 白名单只免 A 不免 C——被豁免的那支哪天自己算了个范围又丢掉,一样得红。
if (takesCompanyParam && handler.text().contains(READ_SCOPE_CALL)) {
scopeCaughtSample.add(exemptionKey(rel, handler));
String dropped = handler.scopeCatchFailure();
if (dropped == null) {
scopeCaughtHandlers++;
} else {
scopeDiscarded.add(where + dropped);
}
}
}
// 残块(package/import/类级注解/字段)显式看守:公司 id 形状落在 handler 之外说明切块形状失效,
// 静默跳过 = 又一处惰护栏,所以这里必须红并交人工核对。
// 残块(package/import/类级注解/字段,以及 handler 收口之后、下一支 handler 之前的尾随方法)
// 显式看守(F-D 收窄触发形状):只有"公司 token + 参数绑定形状"才红——那才是"某支 handler 根本没
// 被切成块、它的公司参数在块外"的唯一可观察证据,静默跳过 = 又一处惰护栏,必须红并交人工核对。
// 取舍:handler 之外的类级常量/字段里提一句 companyId 不再判红(否则 Task 8-12 后取样面里的
// 无关代码会红在这道与他无关的护栏上)。
List<String> unattributed = blocks.residual().stream()
.filter(CompanyIdParamGoesThroughReadScopeTest::isCompanyShapeLine)
.filter(CompanyIdParamGoesThroughReadScopeTest::isCompanyParamDeclarationLine)
.collect(Collectors.toList());
assertThat(unattributed)
.as(rel + " 的公司 id 形状落在 handler 之外(切块没覆盖到,可能是类级注解或字段)—— 必须显式核对,不许静默跳过")
.as(rel + " 的公司参数声明落在 handler 之外(切块没覆盖到,可能是类级注解/字段/尾随方法)—— 必须显式核对,不许静默跳过")
.isEmpty();
}
// 断言 C 的取样自检(全局约束 15):三个读数任一为 0 都是"护栏自己空转",用例必须当场红,
// 不许因为"这一轮没扫到东西"而恒绿,也不许靠放宽判据蒙过去。
assertThat(scopeCaughtSample)
.as("断言 C 取样集非空自检:一支『收了公司 id 参数、体内又写了 readScope(』的 handler 都没扫到")
.isNotEmpty();
assertThat(scopeCaughtHandlers)
.as("断言 C 正样本自检:扫到 " + scopeCaughtSample.size()
+ " 支 handler,走完『接住变量 → 当实参传出去』两步的是 0 支 —— 判据恒红或形状不认,不可信")
.isPositive();
assertThat(scopeCaughtSample)
.as("断言 C 的射程必须覆盖 Task 8 已接线的两页(改名/换 mapping 会让它静默脱离射程,分母不能自造)")
.contains(SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_VIDEO_KEY);
assertThat(scopeDiscarded)
.as("范围算了但没接住(断言 C):readScope( 的结果要么没赋给变量,要么赋了却没交给任何方法调用")
.isEmpty();
}
@Test
@@ -198,6 +416,26 @@ class CompanyIdParamGoesThroughReadScopeTest {
.isEmpty();
}
/**
* 断言 C 的探针驱动器:先确认这段样本真被切成"1 支收公司 id 参数、体内写了 readScope(" 的 handler,
* 再跑 {@link Block#scopeCatchFailure()}。切不出 handler / 不认公司参数 / 没有 readScope( 这三种
* "探针失效"都由调用方的前置断言红,不留静默空跑。
*/
private static String scopeProbeReason(String probeSource, String probeName) {
List<Block> blocks = splitBlocks(sourceLines(probeSource)).handlers();
assertThat(blocks)
.as(probeName + " 应当恰好切出 1 支 handler;切不出来则断言 C 的自检无从判定")
.hasSize(1);
Block handler = blocks.get(0);
assertThat(handler.takesCompanyParam())
.as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效")
.isTrue();
assertThat(handler.text())
.as(probeName + " 的 handler 体内没有 readScope( ,断言 C 扫不到它 ⇒ 探针失效")
.contains(READ_SCOPE_CALL);
return handler.scopeCatchFailure();
}
/** 取样=可执行行里出现公司 token(下划线或驼峰),逐 handler 的窗口谓词再判定是否真收参数。 */
private static List<Path> sampledControllers() throws IOException {
if (!Files.isDirectory(MAIN_ROOT)) fail("找不到 " + MAIN_ROOT + " —— 用例依赖以 backend-java 为工作目录");
@@ -216,7 +454,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
Set<String> keys = new HashSet<>();
for (Path controller : sampledControllers()) {
String rel = relativeKey(controller);
for (Block handler : splitBlocks(executableLines(read(controller))).handlers()) {
for (Block handler : splitBlocks(sourceLines(read(controller))).handlers()) {
if (handler.takesCompanyParam()) keys.add(exemptionKey(rel, handler));
}
}
@@ -233,11 +471,20 @@ class CompanyIdParamGoesThroughReadScopeTest {
return hash < 0 ? key : key.substring(0, hash);
}
/** 取样与残块的触发条件:可执行行里出现公司 token(下划线或驼峰)。 */
/** 取样的触发条件:可执行行里出现公司 token(下划线或驼峰)即入样本,交给逐 handler 的窗口谓词判定。 */
private static boolean isCompanyShapeLine(String line) {
return hasCompanyToken(line);
}
/**
* 残块守卫的触发条件(F-D):公司 token <b>且</b>参数绑定形状(绑定注解或 {@code getParameter(})。
* 只有这种行才说明"某支 handler 根本没被切成块";类级常量或尾随私有方法里提一句 {@code companyId}
* 是本仓正常写法(Task 11 就会写私有收口方法),不该红在无关护栏上。
*/
private static boolean isCompanyParamDeclarationLine(String line) {
return hasCompanyToken(line) && (isBindingLine(line) || line.contains(GET_PARAMETER));
}
private static boolean hasCompanyToken(String line) {
return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM);
}
@@ -246,11 +493,22 @@ class CompanyIdParamGoesThroughReadScopeTest {
return MAPPING_ANNOTATIONS.stream().anyMatch(line::startsWith);
}
/** 绑定注解所在行=真参数声明(F-A)。 */
private static boolean isBindingLine(String line) {
return BINDING_ANNOTATIONS.stream().anyMatch(line::contains);
}
/**
* 文档串行:{@code @Operation}/{@code @Parameter}/{@code @ApiResponse} 或带 {@code summary =}/
* {@code description =} 的注解行——这些里出现的 companyId 只是文案,不代表该 handler 真收了公司参数。
* 文档行:纯 {@code @Operation}/{@code @Parameter}/{@code @ApiResponse},或带 {@code summary =}/
* {@code description =} 的注解行——里面出现的 companyId 只是文案,不代表该 handler 真收了公司参数。
* <p><b>判定顺序</b>(F-A 的关键):先认绑定注解,再认文档串。
* {@code @Parameter(description = "公司 ID") @RequestParam(name = "company_id") Long companyId}
* 这种"文档 + 绑定挤在一行"的本仓主流写法(真树 93 行,{@code ShopManageController.page} 四个参数全中)
* 是真参数声明,round 2 的整行 {@code contains("description =")} 把它当文档吃掉 ⇒ 谓词判"没收公司参数"
* ⇒ A、B 都不跑 = 静默绿。纯文档行仍按原样排除,免得 {@code @Operation} 文案里的 companyId 误伤。</p>
*/
private static boolean isDocLine(String line) {
if (isBindingLine(line)) return false;
return line.startsWith("@Operation")
|| line.startsWith("@Parameter")
|| line.startsWith("@ApiResponse")
@@ -259,101 +517,287 @@ class CompanyIdParamGoesThroughReadScopeTest {
}
/**
* 按 mapping 注解切 handler 块:连续的注解行(含至少一个 mapping 注解)后面紧跟的不是类型声明,
* 就是一个端点;块尾=下一个端点的注解组首行(最后一个块到文件尾)。
* 第一个端点之前的所有行(package/import/类级注解/字段)是残块,交给上面那条显式断言。
* 一行的括号增量:只数<b>字符串字面量、字符字面量与行尾注释之外</b>的 {@code (} 与 {@code )}。
* 注解里的中文文案常带不成对括号,数进去会让窗口收口找不到(判红),那是误伤。
*/
private static Blocks splitBlocks(List<String> ex) {
private static int parenDelta(String line) {
int delta = 0;
boolean inString = false;
for (int j = 0; j < line.length(); j++) {
char c = line.charAt(j);
if (inString) {
if (c == '\\') j++;
else if (c == '"') inString = false;
} else if (c == '"') {
inString = true;
} else if (c == '/' && j + 1 < line.length() && line.charAt(j + 1) == '/') {
break;
} else if (c == '\'' && j + 2 < line.length() && line.charAt(j + 2) == '\'') {
j += 2;
} else if (c == '(') {
delta++;
} else if (c == ')') {
delta--;
}
}
return delta;
}
private static List<String> textsOf(List<SrcLine> lines) {
return lines.stream().map(SrcLine::text).collect(Collectors.toList());
}
/**
* 按 mapping 注解切 handler 块:连续的注解行(含至少一个 mapping 注解)后面紧跟的不是类型声明,
* 就是一个端点;块尾=下一个端点的注解组首行,但<b>每个块再按自己的闭括号收口</b>(第 5 条),
* 于是尾随的私有方法不再算在这支 handler 头上。
* <p>残块=第一个端点之前的行(package/import/类级注解/字段)<b>加上</b>每两支 handler 收口之后、
* 下一支注解组之前的行(尾随私有方法/字段);两者都交给那条"公司参数声明不许落在 handler 之外"的
* 显式断言(触发形状见 F-D)。收口找不到的块整段留在块内(由结构守卫判红),不留缝隙。</p>
*/
private static Blocks splitBlocks(List<SrcLine> ex) {
List<Integer> starts = new ArrayList<>();
int i = 0;
while (i < ex.size()) {
if (!ex.get(i).startsWith("@")) {
if (!ex.get(i).text().startsWith("@")) {
i++;
continue;
}
int runEnd = i;
while (runEnd + 1 < ex.size() && ex.get(runEnd + 1).startsWith("@")) runEnd++;
while (runEnd + 1 < ex.size() && ex.get(runEnd + 1).text().startsWith("@")) runEnd++;
boolean mappingRun = ex.subList(i, runEnd + 1).stream()
.map(SrcLine::text)
.anyMatch(CompanyIdParamGoesThroughReadScopeTest::isMappingLine);
String signature = runEnd + 1 < ex.size() ? ex.get(runEnd + 1) : "";
String signature = runEnd + 1 < ex.size() ? ex.get(runEnd + 1).text() : "";
if (mappingRun && !signature.isEmpty() && !TYPE_DECL.matcher(signature).find()) {
starts.add(i);
}
i = runEnd + 1;
}
List<Block> handlers = new ArrayList<>();
List<String> residual = new ArrayList<>();
int prevEnd = 0;
for (int k = 0; k < starts.size(); k++) {
int from = starts.get(k);
int to = k + 1 < starts.size() ? starts.get(k + 1) : ex.size();
handlers.add(new Block(ex.subList(from, to)));
Block block = new Block(ex.subList(from, to));
handlers.add(block);
residual.addAll(textsOf(ex.subList(prevEnd, from)));
prevEnd = from + block.blockEndIdx() + 1;
}
int first = starts.isEmpty() ? ex.size() : starts.get(0);
return new Blocks(handlers, new ArrayList<>(ex.subList(0, first)));
residual.addAll(textsOf(ex.subList(prevEnd, ex.size())));
return new Blocks(handlers, residual);
}
private record Block(List<String> lines) {
private record Block(List<SrcLine> span) {
String header() {
return lines.get(0);
return span.get(0).text();
}
String text() {
return String.join("\n", lines);
/** 未收口的整段文本:块边界自检的反面证据用({@code readScope(} 是否只出现在收口之后)。 */
String spanText() {
return String.join("\n", textsOf(span));
}
int mappingIdx() {
for (int j = 0; j < span.size(); j++) {
if (isMappingLine(span.get(j).text())) return j;
}
return -1;
}
/** 该 handler 的 mapping 注解文本,作为 handler 级豁免键的后缀;没有 mapping 行就退回块首行。 */
String mappingLine() {
return lines.stream()
.filter(CompanyIdParamGoesThroughReadScopeTest::isMappingLine)
.findFirst()
.orElse(lines.get(0));
int i = mappingIdx();
return i < 0 ? header() : span.get(i).text();
}
/**
* 声明窗口:从本块的 mapping 注解行起、到第一个以 <code>{</code> 结尾的行为止(含该行)。
* 返回 {@code null} 表示整块找不到以 <code>{</code> 结尾的行(切块形状失效),由调用方判红并报块名。
* 方法体开行(声明窗口的收口行,F-B):从 mapping 行起累计括号增量,第一个
* "以 <code>{</code> 结尾<b>且累计配平为 0</b>"的行就是它。判据是两条可区分的字面事实:
* 注解数组开行 <code>@ApiResponses({</code> 的括号没闭合(累计 &gt; 0),方法体开行是
* <code>) {</code>、<code> {</code>、<code>throws IOException {</code> 这类闭合之后的开行。
* 于是 <code>@ApiResponses({</code> 夹在 mapping 行与参数表之间时,整张参数表照样在窗口内(不再静默绿),
* 折行签名(N2)也照样命中。返回 -1 = 整块找不到这样的行(单行体等切块形状失效)。
*/
int bodyOpenIdx() {
int start = mappingIdx();
if (start < 0) return -1;
int depth = 0;
for (int j = start; j < span.size(); j++) {
depth += parenDelta(span.get(j).text());
if (span.get(j).text().endsWith(WINDOW_OPEN) && depth == 0) return j;
}
return -1;
}
/**
* 声明窗口:mapping 注解行 → 方法体开行(含该行)。返回 {@code null} 表示窗口不可判定,
* 由结构守卫判红并报块名,不许"窗口取不到就当没有公司参数"。
*/
List<String> declarationWindow() {
int start = 0;
while (start < lines.size() && !isMappingLine(lines.get(start))) start++;
for (int j = start; j < lines.size(); j++) {
if (lines.get(j).endsWith(WINDOW_OPEN)) {
return lines.subList(start, j + 1);
int start = mappingIdx();
int open = bodyOpenIdx();
return open < 0 ? null : textsOf(span.subList(start, open + 1));
}
/**
* 主体收口行(第 5 条):方法体开行之后,第一个"与 mapping 注解同缩进的单独 <code>}</code> 行"。
* 最后一个 handler 也一样收口,块边界不许开到 EOF —— 否则尾随私有方法里的 {@code readScope(}
* 能替那支没接出口的 handler 过关(计划的 Task 11 模板恰恰鼓励在 controller 里写私有收口方法)。
* 返回 -1 = 收口找不到(闭括号缩进与 mapping 注解不一致等),由结构守卫判红。
*/
int bodyCloseIdx() {
int open = bodyOpenIdx();
if (open < 0) return -1;
int indent = span.get(mappingIdx()).indent();
for (int j = open + 1; j < span.size(); j++) {
SrcLine line = span.get(j);
if (line.indent() == indent && CLOSE_BRACE.equals(line.text())) return j;
}
return -1;
}
/** 块的有效末行:主体收口行;收口找不到时退回整段(那种形状由 {@link #structureFailure()} 判红)。 */
int blockEndIdx() {
int close = bodyCloseIdx();
return close >= 0 ? close : span.size() - 1;
}
/** 断言 A/B 的作用域:从该 handler 的注解组到它<b>自己的</b>闭括号行。 */
String text() {
return String.join("\n", textsOf(span.subList(0, blockEndIdx() + 1)));
}
/** 块内(含收口之后的尾随部分)是否出现公司 token:结构守卫只在相关时才响(F-D)。 */
boolean hasCompanyTokenInSpan() {
return span.stream().anyMatch(line -> hasCompanyToken(line.text()));
}
/**
* 结构守卫的失败原因,{@code null} = 形状可判定。调用方必须再过一道 {@link #hasCompanyTokenInSpan()}
* (F-D):这两道守卫管的是"本护栏能不能看清这一支",与别人收不收公司参数无关时不该响。
*/
String structureFailure() {
if (bodyOpenIdx() < 0) {
return " 里找不到方法体开行(以 " + WINDOW_OPEN + " 结尾、且从 mapping 注解行起左右括号配平)的行,"
+ "无法确定声明窗口";
}
if (bodyCloseIdx() < 0) {
return " 里找不到与 mapping 注解同缩进的单独 " + CLOSE_BRACE + " 收口行,无法确定该 handler 的主体边界";
}
return null;
}
/**
* ① 声明窗口里同时出现 {@code @RequestParam} 与非文档行的公司 token(覆盖 inline 与折行签名;
* F-A:绑定注解所在行不是文档行)。这是 A、B 共同的触发键里"能给出 name="的那一支。
*/
boolean viaRequestParam() {
List<String> window = declarationWindow();
return window != null
&& window.stream().anyMatch(line -> line.contains(REQUEST_PARAM))
&& window.stream().anyMatch(line -> hasCompanyToken(line) && !isDocLine(line));
}
/** ② 该 handler 主体里的 {@code request.getParameter("company_id"/"companyId")} 同族写法(只触发 A,F-C)。 */
boolean viaGetParameter() {
return textsOf(span.subList(0, blockEndIdx() + 1)).stream()
.anyMatch(line -> line.contains(GET_PARAMETER) && hasCompanyToken(line));
}
/** 该 handler 是否收公司 id 参数(断言 A 的触发键,N1 要求同源;B 另按 {@link #viaRequestParam()})。 */
boolean takesCompanyParam() {
return viaRequestParam() || viaGetParameter();
}
/**
* 断言 C(复评 I-1):这一支 handler 里每一次 {@code readScope(} 都必须
* ① 把结果<b>赋给一个变量</b>(认 {@code List<Long> scoped = …readScope(…).userIdsOr(base);}
* 与 {@code ReadScope s = …readScope(…);} 两种形状,也认不带类型的重新赋值 {@code scoped = …});
* ② 让那个变量出现在<b>另一条方法调用的实参列表</b>里(自己那条赋值语句先从文本里扣掉,
* 免得 {@code readScope(operator, scopedCompanyId)} 之类自指算数)。
* <p>返回 {@code null} = 两步都过;否则返回红因片段,由调用方拼上 handler 名。
* <p>已知放过的那一族:把变量喂给 {@code log.info("…", scoped)} 也算"给了实参"。要做成
* "只有交给 service/mapper 那一层才算"就得枚举消费者名字,那是第二把尺子,本轮不做,交人审。
*/
String scopeCatchFailure() {
String src = text();
for (int at = src.indexOf(READ_SCOPE_CALL); at >= 0;
at = src.indexOf(READ_SCOPE_CALL, at + READ_SCOPE_CALL.length())) {
// 语句边界:往前取最近的 ';' 或 '{'(方法体开行),往后取第一个 ';'。
int stmtStart = Math.max(src.lastIndexOf(SEMICOLON, at), src.lastIndexOf(WINDOW_OPEN, at)) + 1;
int stmtEnd = src.indexOf(SEMICOLON, at);
String statement = stmtEnd < 0 ? src.substring(stmtStart) : src.substring(stmtStart, stmtEnd + 1);
String target = assignedTo(statement, at - stmtStart);
if (target == null) {
return " 的 readScope( 是条裸语句:算完了没赋给任何变量,范围算了但没接住"
+ "(要写成 List<Long> scoped = dataReadScope.readScope(…)…; 再把 scoped 交出去)";
}
String rest = src.substring(0, stmtStart) + (stmtEnd < 0 ? "" : src.substring(stmtEnd + 1));
if (!passedAsArgument(rest, target)) {
return " 的 readScope( 结果赋给了 `" + target + "`,但 handler 体内没有任何方法调用的"
+ "实参列表用到 `" + target + "`:范围接住了却没交出去(把 service 那层的实参改成 "
+ "null 就是这个形状)";
}
}
return null;
}
boolean windowUndeterminable() {
return declarationWindow() == null;
/** 赋值目标={@code readScope(} 之前最后一个 {@code 标识符 =}({@code == != <= >=} 不算赋值)。 */
private static String assignedTo(String statement, int readScopeOffset) {
int cut = Math.max(0, Math.min(readScopeOffset, statement.length()));
Matcher m = SCOPE_ASSIGNMENT.matcher(statement.substring(0, cut));
String target = null;
while (m.find()) {
target = m.group(1);
}
return target;
}
/**
* 该 handler 是否收公司 id 参数(A、B 共用,N1 要求同源):
* ① 声明窗口里同时出现 {@code @RequestParam} 与非文档行的公司 token(覆盖 inline 与折行签名,
* 排除 {@code @Operation}/{@code description=} 里的文案提及);
* ② 或整块里出现 {@code request.getParameter("company_id"/"companyId")} 同族写法(这一族写在方法体内)。
*/
boolean takesCompanyParam() {
List<String> window = declarationWindow();
boolean viaRequestParam = window != null
&& window.stream().anyMatch(line -> line.contains(REQUEST_PARAM))
&& window.stream().anyMatch(line -> hasCompanyToken(line) && !isDocLine(line));
boolean viaGetParameter = lines.stream()
.anyMatch(line -> line.contains(GET_PARAMETER) && hasCompanyToken(line));
return viaRequestParam || viaGetParameter;
/** {@code id} 有没有落在某个 {@code 名字(…)} 的实参列表里;控制语句关键字读它不算"交出去"。 */
private static boolean passedAsArgument(String src, String id) {
Matcher call = CALL_ARGUMENTS.matcher(src);
Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(id) + "(?!\\w)");
while (call.find()) {
if (NOT_VALUE_CONSUMERS.contains(call.group(1))) {
continue;
}
if (use.matcher(call.group(2)).find()) {
return true;
}
}
return false;
}
}
/** 源码行:{@code text} 已 trim(口径同仓内既有过滤器),{@code indent} 保留原始缩进(块边界靠它收口)。 */
private record SrcLine(int indent, String text) {
}
private record Blocks(List<Block> handlers, List<String> residual) {
}
/** 剔空行、行注释、块注释起始行与以星号打头的注释续行;口径同 CompanyReadPathMenuGateTest:69-75。 */
/**
* 剔空行、行注释、块注释起始行与以星号打头的注释续行;口径同 CompanyReadPathMenuGateTest:69-75。
* 与 {@link #executableLines} 是<b>同一份</b>实现(后者只是取 {@code text}),不会出现"取样用的口径
* 与切块用的口径不一致"这种静默跳过;额外保留原始缩进,供主体收口按"与 mapping 注解同缩进的
* 单独 <code>}</code> 行"判定(第 5 条)。
*/
private static List<SrcLine> sourceLines(String text) {
List<SrcLine> out = new ArrayList<>();
for (String raw : text.split("\n", -1)) {
String trimmed = raw.trim();
if (trimmed.isEmpty() || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
continue;
}
out.add(new SrcLine(raw.length() - raw.stripLeading().length(), trimmed));
}
return out;
}
private static List<String> executableLines(String text) {
return Arrays.stream(text.split("\n", -1))
.map(String::trim)
.filter(line -> !line.isEmpty())
.filter(line -> !line.startsWith("//") && !line.startsWith("/*") && !line.startsWith("*"))
.collect(Collectors.toList());
return textsOf(sourceLines(text));
}
/** 白名单键的文件部分:相对 src/main/java、统一正斜杠,与取样路径同源,避免平台分隔符造成静默不匹配。 */
@@ -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;
}
}
@@ -0,0 +1,87 @@
package com.nanri.aiimage.modules.appearancepatent.service;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
/**
* 外观专利的进度快照是「文件构建」合成单位(LLM 批次数 + 3 个固定阶段),任务收尾在
* completeLlmFileJob 里同一瞬间连发三条进度(组装 N-2 / 上传 N-1 / 完成 N)。快照写入
* (TaskProgressSnapshotService.save)只对终态豁免 500ms 节流,所以满格那条必须带任务
* 真实状态落库——此前恒按 RUNNING 写,必被节流吞掉,看板永远停在 0/N 或 N-2/N
* (2026-10-04 生产实测)。修复:completed 满格且任务已终态时按任务状态写,
* 对齐货源查询 isTerminalFileBuildProgress。
*/
@ExtendWith(MockitoExtension.class)
class AppearancePatentSnapshotTerminalWriteTest {
private static final Long TASK_ID = 31337L;
@Mock private TaskProgressSnapshotService taskProgressSnapshotService;
@InjectMocks private AppearancePatentTaskService service;
@Test
void runningTaskKeepsWritingRunningStatus() {
save(task("RUNNING"), 3, "正在组装 xlsx");
assertSavedStatus("RUNNING");
}
@Test
void completedTaskWritesSuccessAsTerminalStatus() {
save(task("SUCCESS"), 6, "结果文件已生成");
assertSavedStatus("SUCCESS");
}
@Test
void failedTaskAtFullProgressWritesFailedAsTerminalStatus() {
save(task("FAILED"), 6, "结果文件已生成");
assertSavedStatus("FAILED");
}
/** 没跑满格就不算终态进度:失败的中间阶段照旧按 RUNNING 写,节流语义保持不变。 */
@Test
void failedTaskBelowFullProgressIsNotTerminalYet() {
save(task("FAILED"), 3, "正在组装 xlsx");
assertSavedStatus("RUNNING");
}
private void save(FileTaskEntity task, int completed, String message) {
TaskFileJobEntity job = new TaskFileJobEntity();
job.setId(1L);
job.setScopeKey("task:31337:owner:instance-a");
job.setStatus("RUNNING");
ReflectionTestUtils.invokeMethod(service, "saveFileBuildProgress",
task, job, 6, completed, message);
}
private void assertSavedStatus(String expectedStatus) {
ArgumentCaptor<String> status = ArgumentCaptor.forClass(String.class);
verify(taskProgressSnapshotService).save(eq(TASK_ID), eq(AppearancePatentTaskService.MODULE_TYPE),
status.capture(), anyInt(), anyInt(), anyInt(), anyString(), anyString(), any());
assertEquals(expectedStatus, status.getValue());
}
private FileTaskEntity task(String status) {
FileTaskEntity task = new FileTaskEntity();
task.setId(TASK_ID);
task.setModuleType(AppearancePatentTaskService.MODULE_TYPE);
task.setStatus(status);
return task;
}
}
@@ -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;
}
}
@@ -1,19 +1,42 @@
package com.nanri.aiimage.modules.imagehistory.service;
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.service.ReadScope;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.imagehistory.mapper.ImageHistoryMapper;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.imagehistory.model.entity.ImageHistoryEntity;
import com.nanri.aiimage.modules.imagehistory.model.vo.ImageHistoryListVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
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 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.when;
/** 验收反馈:生成记录数据要可清理——DELETE 清空全表并返回清理条数。 */
class ImageHistoryServiceTest {
@BeforeEach
void setUp() {
// Lambda 列名(user_id/created_at)要从实体元数据里查;纯单测没有 Spring/MyBatis 装配,
// 不初始化就会在 wrapper 上抛 "can not find lambda cache"。口径同 AdminUserListCompanyTest:47。
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ImageHistoryEntity.class);
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
}
@Test
void clearAllHistoryDeletesAndReturnsCount() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
@@ -39,4 +62,118 @@ class ImageHistoryServiceTest {
assertThat(service.clearAllHistory("admin")).isZero();
verify(historyMapper).delete(any());
}
// ---------- 公司 tab 的成员集合怎么进这条查询(Task 8 后半页) ----------
//
// 范围在 controller 里由 DataReadScope 算,service 只收算好的 List<Long> userIds:
// null = 不筛(超管没选公司,保持今天的行为),空集 = 这家公司没有成员账号(必须空页)。
@Test
@DisplayName("总数与 id 页必须拿到同一个成员集合——只改一处就是「总数对不上但没人报错」")
@SuppressWarnings("unchecked")
void memberSetGoesToBothCountAndIdPageWrappers() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
ImageHistoryService service = new ImageHistoryService(historyMapper, userMapper, new ObjectMapper());
when(historyMapper.selectCount(any())).thenReturn(7L);
when(historyMapper.selectList(any())).thenReturn(List.of());
ImageHistoryListVo vo = service.listHistory(1, 15, null, null, null, List.of(11L, 12L));
ArgumentCaptor<LambdaQueryWrapper<ImageHistoryEntity>>
countCap = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
ArgumentCaptor<LambdaQueryWrapper<ImageHistoryEntity>>
rowsCap = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(historyMapper).selectCount(countCap.capture());
verify(historyMapper).selectList(rowsCap.capture());
// 先碰一次 SqlSegment 才会铺出参数(MP 惯例,口径同 AdminUserServiceCompanySuperAdminTest:167)。
String countSql = countCap.getValue().getSqlSegment();
String rowsSql = rowsCap.getValue().getSqlSegment();
assertThat(countSql).contains("user_id IN");
assertThat(rowsSql).contains("user_id IN");
assertThat(countCap.getValue().getParamNameValuePairs().values()).containsExactlyInAnyOrder(11L, 12L);
assertThat(rowsCap.getValue().getParamNameValuePairs().values()).containsExactlyInAnyOrder(11L, 12L);
// 那条总数确实是这条页的总数(不是另算一次的别的范围)。
assertThat(vo.getTotal()).isEqualTo(7L);
}
@Test
@DisplayName("成员集为空=空页:两支 mapper 一支都不许碰,绝不把 [] 交给 wrapper(IN () 是 500)")
void emptyMemberSetReturnsEmptyPageWithoutTouchingMapper() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
ImageHistoryService service = new ImageHistoryService(historyMapper, userMapper, new ObjectMapper());
ImageHistoryListVo vo = service.listHistory(3, 20, null, null, null, List.of());
assertThat(vo.getItems()).isEmpty();
assertThat(vo.getTotal()).isZero();
assertThat(vo.getPage()).isEqualTo(3);
assertThat(vo.getPageSize()).isEqualTo(20);
verify(historyMapper, never()).selectCount(any());
verify(historyMapper, never()).selectList(any());
}
@Test
@DisplayName("不筛时传 null: wrapper 上根本不该出现 user_id IN")
@SuppressWarnings("unchecked")
void unfilteredPassesNullAndRendersNoInClause() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
ImageHistoryService service = new ImageHistoryService(historyMapper, userMapper, new ObjectMapper());
when(historyMapper.selectCount(any())).thenReturn(0L);
when(historyMapper.selectList(any())).thenReturn(List.of());
service.listHistory(1, 15, null, null, null, null);
ArgumentCaptor<LambdaQueryWrapper<ImageHistoryEntity>>
countCap = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
ArgumentCaptor<LambdaQueryWrapper<ImageHistoryEntity>>
rowsCap = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(historyMapper).selectCount(countCap.capture());
verify(historyMapper).selectList(rowsCap.capture());
assertThat(countCap.getValue().getSqlSegment()).doesNotContain("user_id IN");
assertThat(rowsCap.getValue().getSqlSegment()).doesNotContain("user_id IN");
assertThat(countCap.getValue().getParamNameValuePairs()).isEmpty();
}
@Test
@DisplayName("非超管请求别的公司:readScope 给空集,进这页只能落空页,退化成「不筛」就是越权")
void crossCompanyEmptyScopeBecomesEmptyPageNotUnfiltered() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
ImageHistoryService service = new ImageHistoryService(historyMapper, userMapper, new ObjectMapper());
// DataReadScope 的越界分支给的就是 ReadScope.users(List.of())(空集),controller 只做 userIdsOr(base)
// 之后原样传进来;这里连 base 都不给,就是「非超管 + 请求了别家」那一条。
List<Long> scoped = ReadScope.users(List.of()).userIdsOr(null);
assertThat(scoped).isEmpty();
ImageHistoryListVo vo = service.listHistory(1, 15, null, null, null, scoped);
assertThat(vo.getItems()).isEmpty();
assertThat(vo.getTotal()).isZero();
verify(historyMapper, never()).selectCount(any());
verify(historyMapper, never()).selectList(any());
}
@Test
@DisplayName("显式 user_id 与公司成员集是叠加不是替换:同一条 wrapper 上既有 = 也有 IN")
@SuppressWarnings("unchecked")
void explicitUserIdStacksWithMemberSetInsteadOfReplacingIt() {
ImageHistoryMapper historyMapper = mock(ImageHistoryMapper.class);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
ImageHistoryService service = new ImageHistoryService(historyMapper, userMapper, new ObjectMapper());
when(historyMapper.selectCount(any())).thenReturn(0L);
when(historyMapper.selectList(any())).thenReturn(List.of());
service.listHistory(1, 15, 9L, null, null, List.of(11L, 12L));
ArgumentCaptor<LambdaQueryWrapper<ImageHistoryEntity>>
cap = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(historyMapper).selectCount(cap.capture());
assertThat(cap.getValue().getSqlSegment()).contains("user_id IN");
assertThat(cap.getValue().getParamNameValuePairs().values()).contains(9L, 11L, 12L);
}
}
@@ -0,0 +1,136 @@
package com.nanri.aiimage.modules.imagevideo.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.imagevideo.mapper.ImageVideoAdminTaskMapper;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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.anyInt;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 公司 tab 的成员集合怎么进这条查询(Task 8)。
*
* <p>范围本身在 controller 里由 {@code DataReadScope} 算,service 只收算好的
* {@code List<Long> userIds}:null = 不筛(超管没选公司,今天的行为),
* 空集 = 这家公司今天没有成员账号(必须空页,绝不许退化成不筛)。</p>
*/
class ImageVideoAdminTaskServiceTest {
private final ImageVideoAdminTaskMapper mapper = mock(ImageVideoAdminTaskMapper.class);
private final ImageVideoAdminTaskService service =
new ImageVideoAdminTaskService(mapper, new ObjectMapper());
@Test
@DisplayName("超管选了公司:userId 的单值过滤之外必须多出成员集合")
@SuppressWarnings("unchecked")
void companyMembersGoToBothPageAndCountQueries() {
when(mapper.selectAdminTaskPage(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyInt()))
.thenReturn(List.of());
when(mapper.countAdminTaskPage(any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
service.page(null, null, null, null, null, null, 1, 20, List.of(11L, 12L));
// 关键:行集与总数必须拿到同一个范围。只换 page 不换 count ⇒ "总数对不上但没人报错"。
ArgumentCaptor<List<Long>> rowsCap = ArgumentCaptor.forClass((Class) List.class);
ArgumentCaptor<List<Long>> cntCap = ArgumentCaptor.forClass((Class) List.class);
verify(mapper).selectAdminTaskPage(any(), rowsCap.capture(), any(), any(), any(), any(), any(),
anyInt(), anyInt());
verify(mapper).countAdminTaskPage(any(), cntCap.capture(), any(), any(), any(), any(), any());
assertThat(rowsCap.getValue()).containsExactlyInAnyOrder(11L, 12L);
assertThat(cntCap.getValue()).containsExactlyInAnyOrder(11L, 12L);
}
@Test
@DisplayName("不筛时传 null,不是空集——空集在 mapper 那里会渲染出 IN () 语法错")
void unfilteredPassesNullNotEmptyList() {
when(mapper.selectAdminTaskPage(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyInt()))
.thenReturn(List.of());
service.page(null, null, null, null, null, null, 1, 20, null);
verify(mapper).selectAdminTaskPage(any(), isNull(), any(), any(), any(), any(), any(),
anyInt(), anyInt());
}
@Test
@DisplayName("成员集为空=空页,两支 mapper 一支都不许碰(退化成不筛就是越权)")
void emptyMemberSetShortCircuitsWithoutTouchingMapper() {
Map<String, Object> result = service.page(null, null, null, null, null, null, 3, 20, List.of());
assertThat(result)
.containsEntry("items", List.of())
.containsEntry("total", 0L)
.containsEntry("page", 3L)
.containsEntry("page_size", 20L);
verify(mapper, never()).selectAdminTaskPage(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyInt());
verify(mapper, never()).countAdminTaskPage(any(), any(), any(), any(), any(), any(), any());
}
@Test
@DisplayName("detail:行主人不在成员集里=403,真查不到行才是 404;不筛(null)时照旧放行")
void detailGatesRowOwnerAndKeepsNotFoundForMissingRow() {
when(mapper.selectAdminTaskDetail(7L)).thenReturn(videoRow(7L, 99L));
when(mapper.selectAdminTaskDetail(8L)).thenReturn(null);
assertThatThrownBy(() -> service.detail(7L, List.of(11L, 12L)))
.isInstanceOf(BusinessException.class)
.hasMessage("该任务不属于当前公司")
.extracting(e -> ((BusinessException) e).getCode())
.isEqualTo(403);
assertThatThrownBy(() -> service.detail(8L, List.of(11L)))
.isInstanceOf(BusinessException.class)
.hasMessage("视频任务不存在")
.extracting(e -> ((BusinessException) e).getCode())
.isEqualTo(404);
// 主人落在成员集里 ⇒ 读得到;集合为 null(超管没选公司)⇒ 同一条行也读得到。
assertThat(service.detail(7L, List.of(99L)).get("item")).isNotNull();
assertThat(service.detail(7L, null).get("item")).isNotNull();
}
@Test
@DisplayName("download-zip:任一行越界整单 403,不许塞进 X-Archive-Error-Count 的部分失败")
void zipRejectsWholeRequestWhenAnyRowIsOutOfScope() throws Exception {
when(mapper.selectAdminZipRows(List.of(7L, 8L)))
.thenReturn(List.of(videoRow(7L, 11L), videoRow(8L, 99L)));
List<ImageVideoAdminTaskService.VideoSelection> selections =
List.of(new ImageVideoAdminTaskService.VideoSelection(7L, 0),
new ImageVideoAdminTaskService.VideoSelection(8L, 0));
assertThatThrownBy(() -> service.buildZip(selections, List.of(11L, 12L)))
.isInstanceOf(BusinessException.class)
.hasMessage("该任务不属于当前公司")
.extracting(e -> ((BusinessException) e).getCode())
.isEqualTo(403);
// 在范围内的行照旧走"打包"语义(这里没有可下载的视频 ⇒ 记一条错误,不是 403)。
ImageVideoAdminTaskService.ZipBundle bundle =
service.buildZip(List.of(new ImageVideoAdminTaskService.VideoSelection(7L, 0)), List.of(11L));
java.nio.file.Files.deleteIfExists(bundle.file());
assertThat(bundle.fileCount()).isZero();
assertThat(bundle.errorCount()).isEqualTo(1);
}
/** 一条最小可用的任务行:user_id 是闸门唯一的判据,video_urls_json 留空好让 zip 不碰网络。 */
private Map<String, Object> videoRow(long taskId, Long ownerId) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("id", taskId);
row.put("user_id", ownerId);
row.put("video_urls_json", "[]");
return row;
}
}
@@ -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;
}
}
}
@@ -145,6 +145,21 @@ class TaskProgressSnapshotServiceThrottleTest {
verify(taskProgressSnapshotMapper, times(1)).update(isNull(), any(LambdaUpdateWrapper.class));
}
/** 终态不受节流:外观专利收尾在同一瞬间连发三条进度(组装/上传/完成),只有最后一条带终态——
* 若终态也被 500ms 窗口吞掉,快照永远停在中间阶段,看板出现「已完成 0/130、57/59」
* (2026-10-04 生产实测,模块侧修复:AppearancePatentTaskService.saveFileBuildProgress 终态带任务状态)。 */
@Test
void terminalStatusWritesLandEvenInsideTheThrottleWindow() {
when(taskProgressSnapshotMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(running());
rewindLastWrite(20581L, "SIMILAR_ASIN", 100L);
service.save(20581L, "SIMILAR_ASIN", "RUNNING", 10, 5, 1, "s1", "half", null);
verify(taskProgressSnapshotMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
service.save(20581L, "SIMILAR_ASIN", "SUCCESS", 10, 10, 0, "s1", "done", null);
verify(taskProgressSnapshotMapper, times(1)).update(isNull(), any(LambdaUpdateWrapper.class));
}
@Test
void test_task_063_progress_frontend_boundary_limit_and_overflow() {
// 上限/超限:最小更新间隔设为 0(超限值)→ 节流禁用,
@@ -374,6 +374,18 @@ class TaskCenterQueryServiceTest {
assertNull(TaskCenterQueryService.statusFilter(null));
}
/** 三态收敛(2026-10-04 用户定案:状态只留 执行中/成功/失败):成功/失败筛选必须命中
* 历史拼写(COMPLETED/ERROR)与取消,否则前端归并后的行在筛选下凭空消失。 */
@Test
void statusFilterExpandsSuccessAndFailedIntoSynonyms() {
assertEquals(TaskCenterQueryMapper.SUCCESS_STATUSES_ORDERED,
TaskCenterQueryService.statusFilter("success"));
assertEquals(List.of("SUCCESS", "COMPLETED"), TaskCenterQueryService.statusFilter(" SUCCESS "));
assertEquals(TaskCenterQueryMapper.FAILED_STATUSES_ORDERED,
TaskCenterQueryService.statusFilter("FAILED"));
assertEquals(List.of("FAILED", "ERROR", "CANCELLED"), TaskCenterQueryService.statusFilter("failed"));
}
/** 国家列:原文两种形状都要归一,取不到留空(前端画「—」),不许把 null 当国家名。 */
@Test
void countryColumnIsNormalizedFromBothJsonShapes() {
@@ -6,7 +6,6 @@ import com.nanri.aiimage.modules.notification.client.MaixiangConsoleClient.Batch
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterUserRow;
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterVariantPageVo;
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterVariantTaskVo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
@@ -31,7 +30,7 @@ import static org.mockito.Mockito.when;
/**
* 变体采集页签的 Java 侧口径:可见用户 → uid 集合(逗号拼接、排序稳定)、
* 分页归一化、uid → 账号名映射、麦象不可达/未配置时返回空页;
* 不传 status = 只看在跑(等待 0 ∪ 处理中 1 合并,历史终态不进默认口径)。
* 不传 status = 全部状态(单次直查麦象,四态与分页都由麦象完成——2026-10-05 定案)。
*/
@ExtendWith(MockitoExtension.class)
class TaskCenterVariantServiceTest {
@@ -54,11 +53,6 @@ class TaskCenterVariantServiceTest {
resMes, "{\"file_url\": \"https://oss.aishufu.top/a.xlsx\"}");
}
private static BatchTaskItem item(String taskId, String uid, int status, String resMes, LocalDateTime createTime) {
return new BatchTaskItem(taskId, "variant-collection", uid, status,
createTime, createTime, resMes, "{\"file_url\": \"https://oss.aishufu.top/a.xlsx\"}");
}
private static TaskCenterUserRow userRow(Long id, String username) {
TaskCenterUserRow row = new TaskCenterUserRow();
row.setUserId(id);
@@ -87,7 +81,7 @@ class TaskCenterVariantServiceTest {
assertEquals(1, page.getItems().get(0).getStatus());
assertEquals("处理中", page.getItems().get(0).getStatusLabel());
assertEquals("最新采集到 B0XXXXXXX 数据,已采集 12 条", page.getItems().get(0).getResMes());
assertEquals("已完成", page.getItems().get(1).getStatusLabel());
assertEquals("成功", page.getItems().get(1).getStatusLabel());
assertEquals("bob", page.getItems().get(1).getUsername());
}
@@ -113,58 +107,24 @@ class TaskCenterVariantServiceTest {
}
@Test
void superAdminWithoutStatusSeesOnlyActiveMergedFromBothStatuses() {
void superAdminWithoutStatusFetchesAllStatesInOneCall() {
when(consoleClient.configured()).thenReturn(true);
when(consoleClient.batchTasksPage(isNull(), eq(0), eq("variant-collection"), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(1, List.of(item("t-wait", "5", 0, "已添加至任务队列,等待执行"))));
when(consoleClient.batchTasksPage(isNull(), eq(1), eq("variant-collection"), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(2, List.of(item("t-run", "5", 1, "已采集 12 条"))));
when(consoleClient.batchTasksPage(isNull(), isNull(), eq("variant-collection"), eq(1), eq(20)))
.thenReturn(new BatchTaskPage(3, List.of(
item("t-wait", "5", 0, "已添加至任务队列,等待执行"),
item("t-run", "5", 1, "已采集 12 条"),
item("t-done", "5", 2, "已完成,共 30 条"))));
when(queryMapper.selectUsernames(List.of(5L))).thenReturn(List.of(userRow(5L, "ali")));
TaskCenterVariantPageVo page = service.variantTasks(superScope(), null, null, null, null);
assertEquals(3, page.getTotal(), "不传 status = 在跑(等待+处理中)之和,不再是历史全量 106");
assertEquals(2, page.getItems().size());
assertEquals(3, page.getTotal(), "不传 status = 全部状态直查麦象,total 原样透传");
assertEquals(3, page.getItems().size());
assertEquals(1, page.getPage());
assertEquals(20, page.getPageSize());
assertEquals("等待执行", page.getItems().get(0).getStatusLabel());
verify(consoleClient, never()).batchTasksPage(any(), isNull(), any(), anyInt(), anyInt());
}
@Test
void activeMergeSortsByCreateTimeDescAndSlicesPages() {
when(consoleClient.configured()).thenReturn(true);
when(consoleClient.batchTasksPage(isNull(), eq(0), any(), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(2, List.of(
item("t-old", "5", 0, "等待", LocalDateTime.of(2026, 10, 4, 1, 0)),
item("t-mid", "5", 0, "等待", LocalDateTime.of(2026, 10, 4, 2, 0)))));
when(consoleClient.batchTasksPage(isNull(), eq(1), any(), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(1, List.of(
item("t-new", "5", 1, "处理中", LocalDateTime.of(2026, 10, 4, 3, 0)))));
TaskCenterVariantPageVo first = service.variantTasks(superScope(), null, null, 1, 2);
assertEquals(List.of("t-new", "t-mid"),
first.getItems().stream().map(TaskCenterVariantTaskVo::getTaskId).toList(),
"两个状态合并后按创建时间倒序,不是先等待后处理中的拼接序");
TaskCenterVariantPageVo second = service.variantTasks(superScope(), null, null, 2, 2);
assertEquals(List.of("t-old"),
second.getItems().stream().map(TaskCenterVariantTaskVo::getTaskId).toList());
TaskCenterVariantPageVo beyond = service.variantTasks(superScope(), null, null, 3, 2);
assertEquals(0, beyond.getItems().size(), "越界页给空列表");
assertEquals(3, beyond.getTotal(), "total 不随空页归零");
}
@Test
void activeTotalFallsBackToItemCountWhenMaixiangTotalIsSentinel() {
when(consoleClient.configured()).thenReturn(true);
when(consoleClient.batchTasksPage(isNull(), eq(0), any(), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(-1, List.of(item("t-1", "5", 0, "等待"))));
when(consoleClient.batchTasksPage(isNull(), eq(1), any(), eq(1), eq(200)))
.thenReturn(new BatchTaskPage(-1, List.of()));
TaskCenterVariantPageVo page = service.variantTasks(superScope(), null, null, 1, 20);
assertEquals(1, page.getTotal(), "-1 哨兵不能把在跑数算成负数");
assertEquals("待执行", page.getItems().get(0).getStatusLabel());
assertEquals("成功", page.getItems().get(2).getStatusLabel());
verify(consoleClient).batchTasksPage(isNull(), isNull(), eq("variant-collection"), eq(1), eq(20));
}
@Test
@@ -181,19 +141,17 @@ class TaskCenterVariantServiceTest {
@Test
void nonNumericUidAndUnknownStatusDegradeGracefully() {
when(consoleClient.configured()).thenReturn(true);
when(consoleClient.batchTasksPage("5", 0, "variant-collection", 1, 200))
when(consoleClient.batchTasksPage("5", null, "variant-collection", 1, 20))
.thenReturn(new BatchTaskPage(3, List.of(
item("t-1", "collect-27475", 0, "已添加至任务队列,等待执行"),
item("t-2", "5", 9, ""))));
when(consoleClient.batchTasksPage("5", 1, "variant-collection", 1, 200))
.thenReturn(BatchTaskPage.EMPTY);
when(queryMapper.selectUsernames(List.of(5L))).thenReturn(List.of(userRow(5L, "ali")));
TaskCenterVariantPageVo page = service.variantTasks(scoped(5L), null, null, 1, 20);
assertNull(page.getItems().get(0).getUsername(), "非数字 uid 不参与账号名映射");
assertEquals("collect-27475", page.getItems().get(0).getUid());
assertEquals("等待执行", page.getItems().get(0).getStatusLabel());
assertEquals("待执行", page.getItems().get(0).getStatusLabel());
assertEquals("ali", page.getItems().get(1).getUsername());
assertEquals("未知", page.getItems().get(1).getStatusLabel(), "未识别的麦象状态码不冒充成功");
}
@@ -8,6 +8,7 @@ import org.apache.ibatis.builder.MapperBuilderAssistant;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
@@ -22,6 +23,7 @@ import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.data.redis.core.StringRedisTemplate;
@@ -477,7 +479,7 @@ class UserApiSecretServiceTest {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
var page = service.adminPage(operator, new AdminUserSecretQuery());
var page = service.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered());
assertThat(page.getItems()).hasSize(1);
var rowVo = page.getItems().get(0);
@@ -500,7 +502,7 @@ class UserApiSecretServiceTest {
when(adminGroupMapper.selectLedGroups(88L)).thenReturn(List.of());
when(adminUserMapper.selectList(any())).thenReturn(List.of());
var page = service.adminPage(operator, new AdminUserSecretQuery());
var page = service.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered());
assertThat(page.getItems()).isEmpty();
assertThat(page.getGroupOptions()).isEmpty();
@@ -526,7 +528,7 @@ class UserApiSecretServiceTest {
ref.setGroupName("一组");
when(adminGroupMapper.selectGroupNamesByUserIds(any())).thenReturn(List.of(ref));
var page = service.adminPage(operator, new AdminUserSecretQuery());
var page = service.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered());
assertThat(page.getItems()).hasSize(1);
assertThat(page.getItems().get(0).getGroups()).containsExactly("一组");
@@ -589,7 +591,7 @@ class UserApiSecretServiceTest {
when(adminUserMapper.selectBatchIds(any())).thenReturn(List.of(user, leader));
when(adminGroupMapper.selectAllGroups()).thenReturn(List.of());
var page = service.adminPage(operator, new AdminUserSecretQuery());
var page = service.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered());
assertThat(page.getItems()).hasSize(1);
assertThat(page.getItems().get(0).getGroups()).isEmpty();
@@ -607,12 +609,66 @@ class UserApiSecretServiceTest {
AdminUserSecretQuery query = new AdminUserSecretQuery();
query.setGroupId(5L);
var page = service.adminPage(operator, query);
var page = service.adminPage(operator, query, ReadScope.unfiltered());
assertThat(page.getItems()).isEmpty();
verify(adminGroupMapper).selectUserIdsByGroupId(5L);
}
@Test
@DisplayName("超管 group_id + company_id 同时给:取交集,不是后一个覆盖前一个")
void groupAndCompanyIntersect() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(12L, 13L, 99L));
List<Long> scoped = service.scopedUserIds(operator, 7L, ReadScope.users(List.of(11L, 12L, 13L)));
assertThat(scoped).containsExactlyInAnyOrder(12L, 13L);
}
@Test
@DisplayName("公司选了但交集为空:返回空页,不许退化成「不筛」(那是越权)")
void emptyIntersectionReturnsEmptyPage() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(99L));
assertThat(service.scopedUserIds(operator, 7L, ReadScope.users(List.of(11L)))).isEmpty();
// 空集必须由 adminPage 早退:交给 in(...) 会渲染成 IN () → SQL 语法错 → 500。
AdminUserSecretQuery query = new AdminUserSecretQuery();
query.setGroupId(7L);
var page = service.adminPage(operator, query, ReadScope.users(List.of(11L)));
assertThat(page.getItems()).isEmpty();
verify(mapper, never()).selectList(any());
}
@Test
@DisplayName("超管不传公司:保持今天的不筛(全局约束 2——tab 不是安全边界,不许把空公司 id 当成筛)")
void superAdminWithoutCompanyStaysUnfiltered() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
assertThat(service.scopedUserIds(operator, null, ReadScope.unfiltered())).isNull();
}
@Test
@DisplayName("主管:组长锁定 ∩ 公司成员集;越界公司的成员集是空集 ⇒ 空页,不是全量")
void leaderVisibleSetIsNarrowedByCompany() {
UserApiSecretService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of(1L, 2L, 88L));
assertThat(service.scopedUserIds(operator, null, ReadScope.users(List.of(2L, 88L))))
.containsExactlyInAnyOrder(2L, 88L);
assertThat(service.scopedUserIds(operator, null, ReadScope.users(List.of()))).isEmpty();
}
@Test
void adminClearByUserDeletesAllRowsOfUser() {
UserApiSecretService service = newService();
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
@@ -9,6 +10,7 @@ import com.nanri.aiimage.modules.shopkey.model.dto.UserGroupRef;
import com.nanri.aiimage.modules.usersecret.mapper.UserSecretUsageMapper;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretUsageQuery;
import com.nanri.aiimage.modules.usersecret.model.entity.UserSecretUsageEntity;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
@@ -114,7 +116,7 @@ class UserSecretUsageServiceTest {
ref.setGroupName("一组");
when(adminGroupMapper.selectGroupNamesByUserIds(any())).thenReturn(List.of(ref));
var page = service.adminPage(new AdminUserEntity(), new AdminUserSecretUsageQuery());
var page = service.adminPage(new AdminUserEntity(), new AdminUserSecretUsageQuery(), ReadScope.unfiltered());
assertThat(page.getTotal()).isEqualTo(2);
assertThat(page.getItems()).hasSize(2);
@@ -144,7 +146,7 @@ class UserSecretUsageServiceTest {
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of());
when(adminGroupMapper.selectLedGroups(88L)).thenReturn(List.of());
var page = service.adminPage(operator, new AdminUserSecretUsageQuery());
var page = service.adminPage(operator, new AdminUserSecretUsageQuery(), ReadScope.unfiltered());
assertThat(page.getItems()).isEmpty();
assertThat(page.getTotal()).isZero();
@@ -167,7 +169,7 @@ class UserSecretUsageServiceTest {
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
query.setGroupId(5L);
var page = service.adminPage(new AdminUserEntity(), query);
var page = service.adminPage(new AdminUserEntity(), query, ReadScope.unfiltered());
assertThat(page.getItems()).hasSize(1);
assertThat(page.getItems().get(0).getProxyCount()).isEqualTo(3);
@@ -186,9 +188,43 @@ class UserSecretUsageServiceTest {
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
query.setKeyword("不存在的人");
var page = service.adminPage(new AdminUserEntity(), query);
var page = service.adminPage(new AdminUserEntity(), query, ReadScope.unfiltered());
assertThat(page.getItems()).isEmpty();
verify(usageMapper, never()).selectList(any());
}
@Test
@DisplayName("用量统计:超管 group_id ∩ 公司成员集;交集为空时早退且不查库")
void groupAndCompanyIntersectThenEarlyReturn() {
UserSecretUsageService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(12L, 13L, 99L));
assertThat(service.scopedUserIds(operator, 7L, ReadScope.users(List.of(11L, 12L, 13L))))
.containsExactlyInAnyOrder(12L, 13L);
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(99L));
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
query.setGroupId(7L);
var page = service.adminPage(operator, query, ReadScope.users(List.of(11L)));
assertThat(page.getItems()).isEmpty();
verify(usageMapper, never()).selectList(any());
}
@Test
@DisplayName("用量统计:主管只看自己带的分组成员,公司 tab 只能再收窄不能放大")
void leaderVisibleSetIsNarrowedByCompany() {
UserSecretUsageService service = newService();
AdminUserEntity operator = new AdminUserEntity();
operator.setId(88L);
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of(1L, 2L, 88L));
assertThat(service.scopedUserIds(operator, null, ReadScope.users(List.of(2L))))
.containsExactly(2L);
assertThat(service.scopedUserIds(operator, null, ReadScope.unfiltered()))
.containsExactlyInAnyOrder(1L, 2L, 88L);
}
}
+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>
@@ -69,7 +69,7 @@
<div class="section-title">备选店铺</div>
<div v-if="!candidates.length" class="empty-candidates">暂无备选店铺,请先输入并确认</div>
<div v-else class="candidate-table-scroll">
<el-table :data="pagedCandidates" row-key="id" height="160" class="candidate-table"
<el-table ref="candidateTableRef" :data="pagedCandidates" row-key="id" height="160" class="candidate-table"
@selection-change="onSelectionChange">
<el-table-column type="selection" width="42" />
<el-table-column prop="shopName" label="店铺名" min-width="120" show-overflow-tooltip />
@@ -83,6 +83,11 @@
<el-pagination v-if="candidateTotal > candidatePageSize" class="candidate-pagination"
layout="total, prev, pager, next" :total="candidateTotal" :page-size="candidatePageSize"
v-model:current-page="candidatePage" />
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="hint">
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
<button v-if="rememberedCandidates.length" type="button" class="link-danger"
@click="clearCandidateSelectionMemory">清除勾选记忆(共 {{ rememberedCandidates.length }} 家)</button>
</div>
</div>
<template v-if="!asinModeEnabled">
@@ -214,8 +219,9 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, shallowRef, triggerRef } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef, triggerRef, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { TableInstance } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
@@ -272,6 +278,13 @@ import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError } from '@/shared/utils/task-queue-state.ts'
import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
import {
parseRememberedNames,
reconcileRememberedNames,
selectableRows,
selectionMemoryKey,
selectionNotice,
} from '@/shared/utils/candidate-selection-memory'
const ziniaoVersion = useZiniaoVersion()
@@ -304,11 +317,14 @@ const {
total: candidateTotal,
paged: pagedCandidates,
} = useTablePaging(candidates)
// 勾选记忆:按 uid + 页签存店铺名,翻页与重载后自动恢复,不发任何请求
const candidateTableRef = ref<TableInstance | null>(null)
const rememberedCandidates = ref<string[]>([])
const candidateSelectionNotice = ref('')
let restoringSelection = false
const adding = ref(false)
const matching = ref(false)
const pushing = ref(false)
const queueWorkerRunning = ref(false)
const autoQueueEnabled = ref(false)
const queuePushResult = ref('')
const queuePayloadText = ref('')
const matchAsinRowsByCountry = ref<Record<string, PriceTrackAsinParsedRow[]>>({})
@@ -437,6 +453,10 @@ function activeLoopStorageKey() {
return `price-track:active-loop:${uidForStorage()}`
}
function selectionMemoryStorageKey() {
return selectionMemoryKey(uidForStorage(), 'price-track')
}
function setStorageJson(key: string, value: unknown, shouldRemove: boolean) {
if (typeof window === 'undefined') return
try {
@@ -724,10 +744,64 @@ function syncPollingIdsWithHistory() {
}
}
function candidateNameOf(row: PriceTrackCandidateVo) {
return row.shopName || ''
}
function loadSelectionMemory() {
try {
const raw = typeof window !== 'undefined' ? window.localStorage.getItem(selectionMemoryStorageKey()) : null
rememberedCandidates.value = parseRememberedNames(raw ? JSON.parse(raw) : [])
} catch {
rememberedCandidates.value = []
}
}
function saveSelectionMemory() {
setStorageJson(selectionMemoryStorageKey(), rememberedCandidates.value, rememberedCandidates.value.length === 0)
}
async function restoreCandidateSelection() {
await nextTick()
const table = candidateTableRef.value
if (!table) return
const rows = selectableRows(pagedCandidates.value, rememberedCandidates.value, candidateNameOf)
if (!rows.length) {
candidateSelectionNotice.value = ''
return
}
// 恢复期间的 selection-change 不回写记忆:半程重算会把还没勾上的名字抹掉
restoringSelection = true
try {
for (const row of rows) table.toggleRowSelection(row, true)
} finally {
restoringSelection = false
}
candidateSelectionNotice.value = selectionNotice(rows.length)
}
function clearCandidateSelectionMemory() {
rememberedCandidates.value = []
candidateSelectionNotice.value = ''
saveSelectionMemory()
candidateTableRef.value?.clearSelection()
}
function onSelectionChange(rows: PriceTrackCandidateVo[]) {
selectedCandidates.value = rows || []
if (restoringSelection) return
rememberedCandidates.value = reconcileRememberedNames(
rememberedCandidates.value,
pagedCandidates.value.map(candidateNameOf),
(rows || []).map(candidateNameOf),
)
saveSelectionMemory()
}
watch(pagedCandidates, () => {
void restoreCandidateSelection()
})
async function confirmAdd() {
const name = shopInput.value.trim()
if (!name) {
@@ -807,9 +881,6 @@ async function runMatch() {
}
matchedItems.value = [...nextByShop.values()]
saveMatchedItemsToStorage()
if (autoQueueEnabled.value) {
void processMatchedQueue()
}
ElMessage.success(`匹配 ${batch.length} 个店铺`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '匹配失败')
@@ -1083,122 +1154,6 @@ async function waitForTaskTerminal(taskId: number) {
}
}
function nextMatchedQueueItem() {
return matchedItems.value.find((item) => item.matched)
}
async function processMatchedQueue() {
if (disposed) return
if (queueWorkerRunning.value) {
return
}
if (!hasValidMode.value) {
ElMessage.warning('请至少选择一个跟价模式')
return
}
if (asinModeEnabled.value && !asinFiles.value.length) {
ElMessage.warning('请先选择 ASIN 文件')
return
}
const api = getPywebviewApi()
if (!api?.enqueue_json) {
ElMessage.error('当前环境未启用 pywebview enqueue_json')
return
}
const matchedRows = matchedItems.value.filter((i) => i.matched)
if (!matchedRows.length) {
ElMessage.warning('无可用匹配店铺')
return
}
queueWorkerRunning.value = true
pushing.value = true
queuePayloadText.value = ''
let successCount = 0
let failedCount = 0
try {
let index = 0
while (!disposed && autoQueueEnabled.value) {
const row = nextMatchedQueueItem()
if (!row) {
break
}
index += 1
try {
let attempt = 0
const taskVo = await (async () => {
while (true) {
if (disposed) throw new Error('component disposed')
try {
return await createPriceTrackTask({
userId: 0,
statusMode: statusModeEnabled.value,
asinMode: asinModeEnabled.value,
items: [row] as unknown as Record<string, unknown>[],
asinFiles: resolveAsinRequestPaths(),
countryCodes: resolveCountryCodesForRequest(),
})
} catch (error) {
const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase()
const transient = ['无法连接到服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase()))
attempt += 1
if (!transient || attempt >= 10) throw error
queuePushResult.value = '服务暂时不可用,正在重试创建任务(' + attempt + '/10)...'
await sleep(getPollIntervalMs())
}
}
})()
taskSnapshots.value = {
...taskSnapshots.value,
[taskVo.taskId]: {
task: { id: taskVo.taskId, status: 'RUNNING' },
items: taskVo.items,
},
}
triggerRef(taskSnapshots)
taskDetails.value = {
...taskDetails.value,
[taskVo.taskId]: 'RUNNING',
}
saveTaskSnapshotsToStorage(true)
saveTaskDetailsToStorage()
const queuePayload = await buildQueuePayload(taskVo, row)
queuePayloadText.value = JSON.stringify(queuePayload, null, 2)
await enqueueCreatedTask(api, taskVo.taskId, queuePayload)
addPollingTask(taskVo.taskId)
scheduleNextPoll(true)
removeMatchedRowsLocally([row])
queuePushResult.value = '任务 ' + taskVo.taskId + ' 已提交,等待执行完成'
const finalStatus = await waitForTaskTerminal(taskVo.taskId)
if (finalStatus !== 'SUCCESS') {
failedCount += 1
queuePushResult.value = '任务 ' + taskVo.taskId + ' 执行失败,已自动继续下一条'
ElMessage.error(queuePushResult.value)
continue
}
successCount += 1
queuePushResult.value = '任务 ' + taskVo.taskId + ' 已完成'
} catch (error) {
if (disposed) break
failedCount += 1
queuePushResult.value = '第 ' + index + ' 条任务处理失败,已自动继续下一条:' + (error instanceof Error ? error.message : '未知错误')
ElMessage.error(queuePushResult.value)
removeMatchedRowsLocally([row])
continue
}
}
if (successCount > 0 || failedCount > 0) {
ElMessage.success('店铺任务启动已完成:成功 ' + successCount + ' 条,失败 ' + failedCount + ' 条')
}
} catch (e) {
if (disposed) return
queuePushResult.value = e instanceof Error ? e.message : '启动异常'
ElMessage.error(queuePushResult.value)
} finally {
queueWorkerRunning.value = false
pushing.value = false
}
}
function setLoopRun(next: PriceTrackLoopRunVo | null) {
activeLoopRun.value = next
activeLoopRunId.value = next?.id ?? null
@@ -1699,6 +1654,7 @@ onMounted(() => {
loadTaskSnapshotsFromStorage()
loadMatchedItemsFromStorage()
loadActiveLoopRunIdFromStorage()
loadSelectionMemory()
loadCandidates().catch(() => undefined)
loadCountryPreference().catch(() => undefined)
loadHistory().catch(() => undefined)
@@ -33,6 +33,7 @@
</div>
<div v-else class="candidate-table-scroll">
<el-table
ref="candidateTableRef"
:data="pagedCandidates"
row-key="id"
height="260"
@@ -67,6 +68,17 @@
:page-size="candidatePageSize"
v-model:current-page="candidatePage"
/>
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="loading-msg">
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
<button
v-if="rememberedCandidates.length"
type="button"
class="link-danger"
@click="clearCandidateSelectionMemory"
>
清除勾选记忆(共 {{ rememberedCandidates.length }} 家)
</button>
</div>
<ZiniaoVersionSetting v-model="ziniaoVersion" />
@@ -197,8 +209,9 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import type { TableInstance } from "element-plus";
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import TaskCenterPanel from "@/shared/components/tasks/TaskCenterPanel.vue";
import type { TaskItemView, TaskStatCard } from "@/shared/components/tasks/types";
@@ -239,6 +252,14 @@ import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm';
import { dispatchedPruneNotice, mergeDispatchedArchive, pruneRows } from '@/shared/utils/dispatch-row-prune';
import {
parseRememberedNames,
reconcileRememberedNames,
selectableRows,
selectionMemoryKey,
selectionNotice,
} from '@/shared/utils/candidate-selection-memory';
const MAX_TRANSIENT_ERRORS = 30;
const ziniaoVersion = useZiniaoVersion();
@@ -262,6 +283,11 @@ const {
total: candidateTotal,
paged: pagedCandidates,
} = useTablePaging(candidates)
// 勾选记忆:按 uid + 页签存店铺名,翻页与重载后自动恢复,不发任何请求
const candidateTableRef = ref<TableInstance | null>(null);
const rememberedCandidates = ref<string[]>([]);
const candidateSelectionNotice = ref("");
let restoringSelection = false;
const historyItems = ref<QueryAsinHistoryItem[]>([]);
const dashboard = ref<QueryAsinDashboardVo>({
candidateCount: 0,
@@ -275,6 +301,8 @@ const pushing = ref(false);
const queuePushResult = ref("");
const queuePayloadText = ref("");
const pendingQueue = ref<QueryAsinShopQueueItem[]>([]);
// 已派发但历史卡片的 ASIN 明细仍要靠它回退(见 fallbackQueryAsinsForShop),所以只裁匹配表、不删数据
const dispatchedArchive = ref<QueryAsinShopQueueItem[]>([]);
const activeTaskId = ref<number | null>(null);
const activeQueueItem = ref<QueryAsinShopQueueItem | null>(null);
const queueWorkerRunning = ref(false);
@@ -492,6 +520,7 @@ function fallbackQueryAsinsForShop(shopName?: string) {
activeQueueItem.value,
...pendingQueue.value,
...matchedItems.value,
...dispatchedArchive.value,
];
const exact = candidates.find((item) => (item?.shopName || "").trim() === normalizedShopName && hasQueryAsins(item));
return readQueryAsins(exact);
@@ -554,6 +583,7 @@ function saveQueueState() {
if (typeof window === "undefined") return;
const payload = {
pendingQueue: pendingQueue.value,
dispatchedArchive: dispatchedArchive.value,
activeTaskId: activeTaskId.value,
activeQueueItem: activeQueueItem.value,
};
@@ -578,14 +608,19 @@ function loadQueueState() {
if (!raw) return;
const parsed = JSON.parse(raw) as {
pendingQueue?: QueryAsinShopQueueItem[];
dispatchedArchive?: QueryAsinShopQueueItem[];
activeTaskId?: number | null;
activeQueueItem?: QueryAsinShopQueueItem | null;
};
pendingQueue.value = parsed.pendingQueue || [];
dispatchedArchive.value = Array.isArray(parsed.dispatchedArchive)
? parsed.dispatchedArchive
: [];
activeTaskId.value = parsed.activeTaskId ?? null;
activeQueueItem.value = parsed.activeQueueItem ?? null;
} catch {
pendingQueue.value = [];
dispatchedArchive.value = [];
activeTaskId.value = null;
activeQueueItem.value = null;
}
@@ -766,10 +801,79 @@ async function refreshActiveTaskProgress(taskIds?: number[]) {
}
}
function candidateNameOf(row: QueryAsinCandidateVo) {
return row.shop_name || "";
}
function selectionMemoryStorageKey() {
return selectionMemoryKey(uidForStorage(), "query-asin");
}
function loadSelectionMemory() {
try {
const raw =
typeof window === "undefined"
? null
: window.localStorage.getItem(selectionMemoryStorageKey());
rememberedCandidates.value = parseRememberedNames(raw ? JSON.parse(raw) : []);
} catch {
rememberedCandidates.value = [];
}
}
function saveSelectionMemory() {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
selectionMemoryStorageKey(),
JSON.stringify(rememberedCandidates.value),
);
} catch {
/* 配额满:记忆丢了不影响任务 */
}
}
async function restoreCandidateSelection() {
await nextTick();
const table = candidateTableRef.value;
if (!table) return;
const rows = selectableRows(pagedCandidates.value, rememberedCandidates.value, candidateNameOf);
if (!rows.length) {
candidateSelectionNotice.value = "";
return;
}
// 恢复期间的 selection-change 不回写记忆:半程重算会把还没勾上的名字抹掉
restoringSelection = true;
try {
for (const row of rows) table.toggleRowSelection(row, true);
} finally {
restoringSelection = false;
}
candidateSelectionNotice.value = selectionNotice(rows.length);
}
function clearCandidateSelectionMemory() {
rememberedCandidates.value = [];
candidateSelectionNotice.value = "";
saveSelectionMemory();
candidateTableRef.value?.clearSelection();
}
function onSelectionChange(rows: QueryAsinCandidateVo[]) {
selectedCandidates.value = rows;
if (restoringSelection) return;
rememberedCandidates.value = reconcileRememberedNames(
rememberedCandidates.value,
pagedCandidates.value.map(candidateNameOf),
rows.map(candidateNameOf),
);
saveSelectionMemory();
}
watch(pagedCandidates, () => {
void restoreCandidateSelection();
});
async function confirmAdd() {
const name = shopInput.value.trim();
if (!name) {
@@ -1052,9 +1156,13 @@ async function pushToPythonQueue() {
ElMessage.warning("请先匹配可用店铺");
return;
}
const { remaining, removed } = pruneRows(matchedItems.value, runnable, rowKeyForMatch);
matchedItems.value = remaining;
saveMatchedItems();
dispatchedArchive.value = mergeDispatchedArchive(dispatchedArchive.value, removed, rowKeyForMatch);
pendingQueue.value = mergeQueueItems(pendingQueue.value, runnable);
saveQueueState();
queuePushResult.value = `已加入 ${runnable.length} 条店铺,开始按顺序执行`;
queuePushResult.value = dispatchedPruneNotice(runnable.length, remaining.length);
await processQueue();
}
@@ -1105,6 +1213,7 @@ async function deleteTaskRecord(item: QueryAsinHistoryItem) {
}
onMounted(async () => {
loadSelectionMemory();
loadMatchedItems();
loadQueueState();
loadTaskStartTimes();
@@ -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 {

Some files were not shown because too many files have changed in this diff Show More