fix(多公司): 站点超管不替别家公司建下级账号,admin 候选与首任管理员都收在本公司

- AdminUserService:建号前两道不变式——ensureSubSuperAccountStaysWithOperatorCompany(超管只能往别家开"那家的公司超管",往下的组长/员工一律 403)+ ensureCreatorSharesCompany 提成执行体(created_by_id 与 company_id 不得分属两家,超管是唯一豁免),建号与移人共用一份,避免"另一侧照样落库"
- 列表侧 admin 候选按 companyIdFilter 过滤:全平台列 admin 就是"admin 替别家建账号"的入口
- ShopManageController 同步一处;配套 AdminUserServiceCompanyTest 9 例(本机 mvn -o test 19 例全绿,含 PublishBrandLabel/PublishWorkbook 两支)
- 前端 CreateUserDialog/GroupEditorDialog/UsersPage + 两个 model 与 types 随之收口,新增 company-user-create.test.ts 61 行用例
- 注:这批改动原为另一路会话在飞文件,按用户"所有的都提交推送"指示收口,提交前已跑其自带用例
This commit is contained in:
2026-10-09 09:11:30 +08:00
parent 39fc5d537f
commit 65b40e5cc0
11 changed files with 305 additions and 27 deletions
@@ -3,7 +3,10 @@ import { computed, reactive, ref, watch } from 'vue'
import { submitCreateUser } from './user-create-adapter'
import {
createEmptyCreateUserForm,
defaultRoleChoice,
mayCarryOwnExpiry,
resolveRoleChoices,
type CreatableUserRole,
type CreateUserForm,
type CreateUserFormErrors,
validateCreateUserForm,
@@ -17,10 +20,14 @@ const props = defineProps<{
operatorSuper?: boolean
/** 操作者角色(company_super_admin 也能建管理员/普通账号)。 */
operatorRole?: string | null
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示)。 */
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示,已按当前公司 tab 收窄)。 */
adminOptions?: Array<{ id: number; username: string }>
/** 公司候选(站点超管创建公司超级管理员时必选)。 */
companyOptions?: Array<{ id: number; companyName: string }>
/** 操作者自己那家公司(会话 current-user.companyId)。 */
operatorCompanyId?: number | null
/** 当前公司 tab:这次建号落在哪家,就决定能建哪些角色。 */
activeCompanyId?: number | null
}>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
@@ -30,29 +37,40 @@ const busy = ref(false)
/** 角色下拉:站点超管可选公司超管/管理员/普通账号;公司超管只可选管理员/普通账号;
* 管理员不显示角色选择(后端强制 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 ROLE_LABELS: Record<CreatableUserRole, string> = {
company_super_admin: '公司超级管理员',
admin: '管理员',
normal: '普通账号',
}
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'),
/** 可选角色集合的唯一来源是 user-create-model 那个纯函数(后端有同一口径的一条 403)。 */
const allowedRoles = computed<CreatableUserRole[]>(() =>
resolveRoleChoices(props.operatorSuper === true, props.operatorCompanyId, props.activeCompanyId),
)
const roleChoices = computed(() => allowedRoles.value.map((value) => ({ value, label: ROLE_LABELS[value] })))
/** 只有管理员/公司超管有「自己的到期时间」;普通账号跟随上级级联,不给它入口。 */
const expiryEditable = computed(() => mayCarryOwnExpiry(form.role))
// 公司 tab 收窄了可选角色时,把残留的旧选择收敛回合法项(并清掉上一家的所属管理员):
// 留着它,用户看到的是一个已经不给选的选项,提交会被后端 403 打回。
watch(allowedRoles, (roles) => {
if (roles.includes(form.role)) return
form.role = defaultRoleChoice(roles)
form.createdBy = null
})
watch(
() => props.modelValue,
(open) => {
if (!open) return
form.username = ''
form.password = ''
form.role = 'normal'
form.role = defaultRoleChoice(allowedRoles.value)
form.columnIds = []
form.createdBy = null
form.expiresAt = ''
form.companyId = null
// 预填当前 tab:跨公司时角色本来就只剩公司超管,而那一例必须带公司
form.companyId = props.activeCompanyId ?? null
errors.username = undefined
errors.password = undefined
errors.companyId = undefined
@@ -55,7 +55,10 @@ watch(
async function loadCandidates(): Promise<void> {
try {
// 对齐 admin.js loadUserOptions:page=1&page_size=999 全量拉取,避免归属过滤漏人。
const page = await fetchUserList({ page: 1, pageSize: 999 })
// company_id 必带:不带时后端对站点超管返回全平台账号,别家公司的人就会出现在本公司分组的候选里。
// 取的是**组长自己那家**(当前登录用户),不是公司 tab——新建时组长就是操作者本人,
// 按 tab 取人会在超管停在别家 tab 时列出那家的人,保存时被后端"只能添加组长本公司的账号"打回。
const page = await fetchUserList({ page: 1, pageSize: 999, companyId: session.user?.companyId ?? null })
users.value = page.items
} catch (error) {
showAdminFeedback(actionableErrorText(error), 'error')
@@ -30,6 +30,9 @@ const total = ref(0)
const admins = ref<Array<{ id: number; username: string }>>([])
/** 公司候选(仅供建号弹窗的「公司超级管理员」下拉使用,2026-10-05 唯一豁免)。 */
const companyOptions = ref<Array<{ id: number; companyName: string }>>([])
/** 操作者自己那家公司(会话里的 current-user.companyId):建号弹窗据此判断当前 tab 是不是自己家。
* 与 GroupEditorDialog 取的是同一个源——两处各取一份会靠约定对齐。 */
const operatorCompanyId = computed<number | null>(() => session.user?.companyId ?? null)
const filters = reactive<UserFilterState>(createUserFilterState())
const isSuperAdmin = computed(() => session.isSuperAdmin)
const operatorRole = computed(() => session.user?.role ?? null)
@@ -258,6 +261,8 @@ onMounted(() => {
:operator-role="operatorRole"
:admin-options="admins"
:company-options="companyOptions"
:operator-company-id="operatorCompanyId"
:active-company-id="companyTab.requestCompanyId"
@created="loadUsers"
/>
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" :company-id="companyTab.requestCompanyId" @updated="loadUsers" />
@@ -1,5 +1,6 @@
/** 数据权限分组列表模型(任务 59;module 13 task 253 扩展编辑能力):解析 VO + 摘要 + 提交载荷。 */
import { unwrap } from '../../api/envelope.ts'
import { isSuperAdminRole, roleKind } from '../../types/admin.ts'
export interface ShopGroupItem {
id: number
@@ -101,10 +102,20 @@ export interface GroupMemberCandidateUser {
}
/**
* 组员候选过滤(对齐 admin.js:3020-3028):
* 超管(站点与公司两档)永不进组员候选——它是那家公司的最高账号,不属于任何分组。
* 与后端 `ShopManageGroupService#resolveMembers` 抛的「超级管理员不属于任何分组」同一口径。
*/
export function isGroupIneligibleRole(role: string | null | undefined): boolean {
const kind = roleKind(role)
return kind === 'super_admin' || kind === 'company_super_admin'
}
/**
* 组员候选过滤(对齐 admin.js:3020-3028,2026-10-07 收口):
* - 组长本人永不进候选;
* - 超管可选全部用户(不论角色/归属);
* - 非超管仅可选"组长(创建人)名下"的普通账号。
* - 超管(站点/公司)永不进候选;
* - 超管操作者可选本公司全部账号(公司维度由请求的 company_id 收窄,不在这里再判一次);
* - 其余操作者仅可选"组长(创建人)名下"的普通账号。
*/
export function eligibleGroupMembers(
users: GroupMemberCandidateUser[],
@@ -112,9 +123,10 @@ export function eligibleGroupMembers(
operatorRole: string,
): GroupMemberCandidateUser[] {
const leaderKey = leaderUserId != null && leaderUserId > 0 ? String(leaderUserId) : ''
const isSuper = (operatorRole || '').toLowerCase() === 'super_admin'
const isSuper = isSuperAdminRole(operatorRole)
return users.filter((u) => {
if (String(u.id) === leaderKey) return false
if (isGroupIneligibleRole(u.role)) return false
if (isSuper) return true
return (
(u.role || '').toLowerCase() === 'normal' &&
@@ -57,6 +57,43 @@ export function normalizeCreateRole(role: string | null | undefined): CreatableU
return 'normal'
}
/**
* 目标公司是否不是操作者自己那家。任一侧未知时按「不算跨家」处理——未知不是证据,
* 拿它当证据会把管理员/普通账号的选项从自己家公司面前也收走。
*/
export function isCrossCompanyTarget(
operatorCompanyId: number | null | undefined,
targetCompanyId: number | null | undefined,
): boolean {
return operatorCompanyId != null && targetCompanyId != null && operatorCompanyId !== targetCompanyId
}
/**
* 建号弹窗的可选角色(2026-10-07 口径):站点超管停在别家公司 tab 上时,只剩「给那家开一个
* 公司超级管理员」;组长与普通账号由那家自己的公司超管开设。
*
* 与后端 `AdminUserService#ensureSubSuperAccountStaysWithOperatorCompany` 同一口径,两端各写
* 一遍的前提是这两处永远一起改——所以这里做成纯函数,用例直接喂三种角色×两种公司组合。
*/
export function resolveRoleChoices(
operatorSuper: boolean,
operatorCompanyId: number | null | undefined,
targetCompanyId: number | null | undefined,
): CreatableUserRole[] {
if (!operatorSuper) return ['admin', 'normal']
if (isCrossCompanyTarget(operatorCompanyId, targetCompanyId)) return ['company_super_admin']
return ['company_super_admin', 'admin', 'normal']
}
/**
* 弹窗默认选中的角色:普通账号优先——那是历史默认值,也是用得最多的一档。
* 只有 tab 收窄到不给选普通账号时(跨家公司)才退到唯一合法项,否则超管一进弹窗就落在
* 「公司超级管理员」上,点一次创建就多出一个超管账号。
*/
export function defaultRoleChoice(choices: CreatableUserRole[]): CreatableUserRole {
return choices.includes('normal') ? 'normal' : choices[0]
}
/**
* 可携带「自己的到期时间」的角色,与后端 AdminUserService#mayCarryOwnExpiry 逐字对齐
* (normal-account-no-own-expiry.test.ts 钉两端集合相等)。普通账号的停用只由上级
+2
View File
@@ -10,6 +10,8 @@ export interface AdminUser {
/** 1 为管理员标志位;role 为空时可据此推断角色。 */
isAdmin?: boolean
createdById?: number | null
/** 操作者自己那家公司(/api/admin/current-user 带回):分组候选要按组长公司取人,不能用当前 tab。 */
companyId?: number | null
creatorUsername?: string
createdAt?: string
updatedAt?: string
@@ -15,12 +15,20 @@ const USERS = [
{ id: 4, username: '别人员工', role: 'normal', createdById: 9 },
{ id: 5, username: '另一个管理员', role: 'admin', createdById: null },
{ id: 6, username: '超管本人', role: 'super_admin', createdById: null },
{ id: 7, username: '别家公司超管', role: 'company_super_admin', createdById: null },
]
test('align_group_eligible_super_admin_sees_all_except_leader', () => {
// 超管:候选 = 全部用户(除组长本人),不区分归属。
test('align_group_eligible_super_admin_sees_all_except_leader_and_super_roles', () => {
// 站点超管操作者:候选 = 全部账号(除组长本人),但超管两档永不入组(2026-10-07 收口)。
// 以前这里 return true 放行一切,别的公司的 company_super_admin 会被拉进本公司分组当组员。
const result = eligibleGroupMembers(USERS, 1, 'super_admin')
assert.deepEqual(result.map((u) => u.id), [2, 3, 4, 5, 6])
assert.deepEqual(result.map((u) => u.id), [2, 3, 4, 5])
})
test('align_group_eligible_excludes_both_super_admin_flavours_for_non_super_too', () => {
// 非超管分支本来就只放 normal,两档超管同样进不来——反向钉住「收紧不许只落在一侧」。
const result = eligibleGroupMembers(USERS, null, 'company_super_admin')
assert.deepEqual(result.map((u) => u.id), [])
})
test('align_group_eligible_non_super_only_own_normal_employees', () => {
@@ -62,7 +70,25 @@ test('align_group_editor_dialog_ui_wiring', () => {
assert.match(dialog, /当前登录用户/, '新建时组长只读显示当前登录用户')
assert.match(dialog, /eligibleGroupMembers/, '组员候选走归属过滤')
assert.match(dialog, /groupMemberCandidateHint/, '候选提示文案走对齐逻辑')
assert.match(dialog, /companyId:\s*session\.user\?\.companyId \?\? null/,
'候选必须按组长(新建时=当前登录用户)那家取人:不带时后端对站点超管返回全平台账号,别家公司的人会进到这家的候选里')
assert.doesNotMatch(dialog, /companyTab/, '分组候选不能按公司 tab 取人——超管停在别家 tab 时会列出那家的人,保存必被后端打回')
const page = readSource('src/pages/account/GroupsPage.vue')
assert.match(page, /创建时间/, '列表补创建时间列')
assert.doesNotMatch(page, /slice\(0,\s*10\)/, '组员 chips 全量渲染不再收 +N')
})
test('align_group_backend_gate_super_never_joins_and_leader_shares_company', () => {
// 界面收窄只是少踩一次;这两条 403 才是出口。锚在调用点与抛出语句,不锚注释。
const java = readSource(
'../backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java',
)
assert.match(java, /"超级管理员不属于任何分组"/)
assert.match(java, /if \(siteSuper \|\| "company_super_admin"\.equals\(memberRole\)\)/,
'站点超管走 DeviceSessionPolicy 唯一出口,公司超管比 resolveRole 的结果——都不在本文件里写 super_admin 字面量')
assert.match(java, /if \(leaderCompanyId != null && !leaderCompanyId\.equals\(user\.getCompanyId\(\)\)\)/,
'组员必须与组长同公司(分组表没有 company_id 列,归属只能从组长推)')
assert.match(java, /ensureLeaderSharesOperatorCompany\(createdById, operatorId\);/, '新建:组长必须与操作者同公司')
assert.match(java, /ensureLeaderSharesOperatorCompany\(resolveGroupLeaderUserId\(entity\), normalizedOperatorId\);/,
'改删:站点超管也按组长公司收窄,不能只靠"读侧藏起来"')
})
@@ -3,6 +3,9 @@ import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import {
createEmptyCreateUserForm,
defaultRoleChoice,
isCrossCompanyTarget,
resolveRoleChoices,
toCreateUserRequest,
validateCreateUserForm,
} from '../src/pages/account/user-create-model.ts'
@@ -89,6 +92,64 @@ test('建号模型源码:公司口径只对「公司超管」这一例放行',
* 同理"停用后不能再用于新建账号"也不成立了——requireActive 只在显式传 company_id 时才走,
* 而页面现在一律不传(接口直连的老调用方仍受它保护,那条由上一用例盯着)。
*/
test('跨公司 tab 只给「开一家公司超管」这一个选项(2026-10-07 收口)', () => {
// isCrossCompanyTarget:未知不是证据。任一侧拿不到都按「不算跨家」,否则自己家公司也会被收走选项。
assert.equal(isCrossCompanyTarget(1, 2), true)
assert.equal(isCrossCompanyTarget(1, 1), false)
assert.equal(isCrossCompanyTarget(null, 2), false, '操作者公司未知时不能凭空判成跨家')
assert.equal(isCrossCompanyTarget(1, null), false, '没选公司 tab 时同理')
assert.equal(isCrossCompanyTarget(undefined, 2), false)
// 站点超管:本公司 tab 三档全开,别家 tab 只剩公司超管。
assert.deepEqual(resolveRoleChoices(true, 1, 1), ['company_super_admin', 'admin', 'normal'])
assert.deepEqual(resolveRoleChoices(true, 1, 7), ['company_super_admin'])
assert.deepEqual(resolveRoleChoices(true, 1, null), ['company_super_admin', 'admin', 'normal'],
'tab 未知退回"不加戏":宁可让后端 403 拦,不能把自己家的管理员/普通账号藏掉')
// 非超管(公司超管 / 组长):公司维度根本不进请求体,跨家无从谈起 ⇒ 与 tab 无关。
assert.deepEqual(resolveRoleChoices(false, 1, 7), ['admin', 'normal'])
assert.deepEqual(resolveRoleChoices(false, 1, 1), ['admin', 'normal'])
// 默认值:normal 能选时必须是 normal——以前一打开弹窗就是 normal,
// 改成"首个合法项"会让超管一进弹窗就落在公司超级管理员上,点一次就多一个超管。
assert.equal(defaultRoleChoice(['company_super_admin', 'admin', 'normal']), 'normal')
assert.equal(defaultRoleChoice(['admin', 'normal']), 'normal')
assert.equal(defaultRoleChoice(['company_super_admin']), 'company_super_admin')
})
test('弹窗与后端同口径:角色候选来自纯函数,且后端真的有一条 403', () => {
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
assert.match(dialog, /resolveRoleChoices\(props\.operatorSuper === true, props\.operatorCompanyId, props\.activeCompanyId\)/,
'角色候选必须走 user-create-model 的纯函数,不能在组件里再写一遍 if')
assert.match(dialog, /defaultRoleChoice\(allowedRoles\.value\)/, '打开弹窗的默认角色走同一条归一')
assert.match(dialog, /watch\(allowedRoles, \(roles\) => \{[\s\S]*?form\.role = defaultRoleChoice\(roles\)[\s\S]*?form\.createdBy = null/,
'tab 换了要把残留的旧角色和所属管理员一起收掉,否则提交会被后端打回')
const page = readSource('src/pages/account/UsersPage.vue')
assert.match(page, /:operator-company-id="operatorCompanyId"/, '操作者公司 id 要传给弹窗')
assert.match(page, /:active-company-id="companyTab\.requestCompanyId"/, '当前 tab 公司要传给弹窗')
assert.match(page, /session\.user\?\.companyId/, '操作者公司 id 取自会话(与分组弹窗同一个源)')
// current-user 必须继续带回 companyId:弹窗的跨家判断只有这一个数据源,摘掉它就恒为 false。
const consoleJava = readSource(
'../backend-java/src/main/java/com/nanri/aiimage/modules/admin/controller/AdminConsoleController.java',
)
assert.match(consoleJava, /item\.put\("companyId", operator\.getCompanyId\(\)\)/,
'GET /api/admin/current-user 要带回操作者公司 id')
// 后端那条 403 才是唯一防线:前端只是让它少踩一次。锚在"被调用"而不是"方法存在"——
// 只锚方法名,删掉调用点这条用例照样绿。
const java = readSource(
'../backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java',
)
assert.match(java, /ensureSubSuperAccountStaysWithOperatorCompany\(role, currentUser, wantRole, targetCompanyId\);/)
assert.match(java, /if \(!"super_admin"\.equals\(operatorRole\) \|\| "company_super_admin"\.equals\(wantRole\)\) \{/)
assert.match(java, /只能在本公司名下创建管理员和普通账号/)
// 所属管理员候选也必须按当前 tab 收窄:截图里那个下拉列出了别家公司的组长。
assert.match(java, /\.eq\(AdminUserEntity::getRole, "admin"\)\s*\.eq\(companyIdFilter != null, AdminUserEntity::getCompanyId, companyIdFilter\)/,
'admins 候选要带 company_id 过滤,且只在传了 company_id 时生效')
})
test('「公司管理」引导文案说的是自动继承,并写清公司超管这一例外', () => {
const guide = OPERATION_GUIDES.admin_companies.text
assert.match(guide, /操作者自己所在的公司/, '要写清归属的真实口径:落在操作者本公司')
@@ -124,9 +124,11 @@ public class AdminUserService {
Map<Long, String> companyMap = loadCompanyNameMap(rows);
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap, companyMap)).toList();
// 候选只给当前公司 tab 的组长:全平台列 admin 就是「admin 替别家建账号」的入口(2026-10-07 收口)。
List<AdminBriefVo> admins = "super_admin".equals(role)
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
.eq(companyIdFilter != null, AdminUserEntity::getCompanyId, companyIdFilter)
.orderByAsc(AdminUserEntity::getId)).stream()
.map(u -> new AdminBriefVo(u.getId(), u.getUsername()))
.toList()
@@ -174,6 +176,9 @@ public class AdminUserService {
throw new BusinessException("密码至少6个字符");
}
Long targetCompanyId = resolveTargetCompanyId(role, currentUser, request.getCompanyId());
ensureSubSuperAccountStaysWithOperatorCompany(role, currentUser, wantRole, targetCompanyId);
Long wantCreatedBy;
if ("admin".equals(wantRole) || "company_super_admin".equals(wantRole)) {
// 组长/公司超管的创建人就是操作者本人:公司超管不能替别的主管“认领”管理员
@@ -183,6 +188,7 @@ public class AdminUserService {
if (wantCreatedBy == null) {
AdminUserEntity firstAdmin = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getRole, "admin")
.eq(AdminUserEntity::getCompanyId, targetCompanyId)
.orderByAsc(AdminUserEntity::getId)
.last("LIMIT 1"));
wantCreatedBy = firstAdmin != null ? firstAdmin.getId() : currentUser.getId();
@@ -190,6 +196,12 @@ public class AdminUserService {
} else {
wantCreatedBy = currentUser.getId();
}
// 创建人是操作者本人时它的公司已知:非超管那条分支上 targetCompanyId 就是操作者公司,
// 超管自己则是下面这条不变式唯一豁免的对象。两种情况都不必再查一次库。
if (!currentUser.getId().equals(wantCreatedBy)) {
ensureCreatorSharesCompany(wantCreatedBy, targetCompanyId,
"所属管理员不存在,无法确认与账号同公司", "所属管理员与账号不在同一家公司");
}
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)
|| "company_super_admin".equals(wantRole)) ? 1 : 0;
@@ -199,7 +211,7 @@ public class AdminUserService {
entity.setIsAdmin(isAdmin);
entity.setRole(wantRole);
entity.setCreatedById(wantCreatedBy);
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
entity.setCompanyId(targetCompanyId);
entity.setExpiresAt(parseExpiresAt(request.getExpiresAt()));
try {
adminUserMapper.insert(entity);
@@ -269,6 +281,9 @@ public class AdminUserService {
*
* <p>永远返回一个具体值并写进实体:列 DEFAULT 1 只为发布期的旧 jar 存在(§8.2),
* 新代码不靠它,否则第二家公司开通后每个未传公司的建号都会被静默塞进厦门米椿花。</p>
*
* <p>"超管可指定任意公司"只对<b>公司超管</b>那一档成立,组长/员工另有一道
* {@link #ensureSubSuperAccountStaysWithOperatorCompany} 收在操作者本公司。</p>
*/
private Long resolveTargetCompanyId(String operatorRole, AdminUserEntity operator, Long requestedCompanyId) {
if (!"super_admin".equals(operatorRole)) {
@@ -284,6 +299,25 @@ public class AdminUserService {
return requestedCompanyId;
}
/**
* 站点超管不替其他公司建「超管以下」的账号(组长 / 普通员工)——2026-10-07 定案。
*
* <p>超管在别家公司名下能开的只有一级:那家自己的公司超级管理员。往下的层级由该公司超管
* 自己搭。这条不做进代码的话,唯一防线是"前端建号请求里不带 company_id"——而 {@code users}
* 的 {@code created_by_id} 与 {@code company_id} 一旦分别来自两家公司,二期那 77 处按账号过滤的
* 出口就全错位了(同一形态见 {@link #ensureCreatorSharesCompany})。</p>
*/
private void ensureSubSuperAccountStaysWithOperatorCompany(String operatorRole, AdminUserEntity operator,
String wantRole, Long targetCompanyId) {
if (!"super_admin".equals(operatorRole) || "company_super_admin".equals(wantRole)) {
return;
}
if (!targetCompanyId.equals(operator.getCompanyId())) {
throw new BusinessException(403,
"只能在本公司名下创建管理员和普通账号;其他公司请先建该公司的超级管理员,由它开设下级账号");
}
}
/**
* 移人(设计文档 §2.2):返回要把账号移去的公司 id,返回 null 表示「这次没动公司」。
*
@@ -309,19 +343,31 @@ public class AdminUserService {
* "同公司"和"同一人"两套口径就会交叉,越权只能逐出口重新补。</p>
*/
private void ensureCreatorSharesCompany(AdminUserEntity target, Long newCompanyId) {
Long createdById = target.getCreatedById();
ensureCreatorSharesCompany(target.getCreatedById(), newCompanyId,
"该账号的创建人已不存在,无法确认同公司,不能移入其他公司",
"只能把账号移到其创建人所在的公司");
}
/**
* 归属不变式的执行体:{@code created_by_id} 指向的账号必须与 {@code companyId} 那家同属一家,
* 除非创建人是站点超管(它是平台自己的身份,本来就不属于任何一家)。
*
* <p>建号与移人共用这一份:两边各写一遍的话,"挂名挂到别家"只会在一侧被挡下,而另一侧照样落库。</p>
*/
private void ensureCreatorSharesCompany(Long createdById, Long companyId, String missingCreatorMessage,
String deniedMessage) {
if (createdById == null) {
return;
}
AdminUserEntity creator = adminUserMapper.selectById(createdById);
if (creator == null) {
throw new BusinessException(403, "该账号的创建人已不存在,无法确认同公司,不能移入其他公司");
throw new BusinessException(403, missingCreatorMessage);
}
if ("super_admin".equals(creator.getRole())) {
if (DeviceSessionPolicy.isSuperAdmin(creator.getRole(), creator.getIsAdmin(), creator.getCreatedById())) {
return;
}
if (!newCompanyId.equals(creator.getCompanyId())) {
throw new BusinessException(403, "只能把账号移到其创建人所在的公司");
if (!companyId.equals(creator.getCompanyId())) {
throw new BusinessException(403, deniedMessage);
}
}
@@ -134,6 +134,7 @@ public class ShopManageController {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
if (isSuper(operator)) {
// 公司 tab 只收窄可见集;list() 内按组长两列(created_by_id / user_id)认归属。
List<Long> memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null);
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds));
}
@@ -13,6 +13,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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;
@@ -55,10 +57,10 @@ class AdminUserServiceCompanyTest {
}
@Test
void superAdminPlacesNewUserInSpecifiedCompany() {
void superAdminPlacesNewCompanySuperAdminInSpecifiedCompany() {
AdminUserEntity operator = operator(1L, "super_admin", 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
AdminUserCreateRequest request = request(7L);
AdminUserCreateRequest request = request("company_super_admin", 7L);
service.createUser(operator, request);
@@ -66,6 +68,56 @@ class AdminUserServiceCompanyTest {
verify(companyService).requireActive(7L);
}
@Test
void superAdminCannotOpenSubSuperAccountForAnotherCompany() {
// 2026-10-07 定案:admin 不替别家建组长/员工,那家由它自己的公司超管往下搭。
AdminUserEntity operator = operator(1L, "super_admin", 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
for (String subSuperRole : List.of("normal", "admin")) {
assertThatThrownBy(() -> service.createUser(operator, request(subSuperRole, 7L)))
.as("角色 %s 属于「超管以下」,不许落在别家公司名下", subSuperRole)
.isInstanceOfSatisfying(BusinessException.class, ex -> {
assertThat(ex.getCode()).isEqualTo(403);
assertThat(ex.getMessage()).contains("超级管理员");
});
}
verify(userMapper, never()).insert(any(AdminUserEntity.class));
}
@Test
void createdByIdMustBelongToTheSameCompanyAsTheNewAccount() {
AdminUserEntity operator = operator(1L, "super_admin", 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(50L)).thenReturn(creator(50L, "admin", 7L));
AdminUserCreateRequest request = request("normal", null);
request.setCreatedById(50L);
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOfSatisfying(BusinessException.class, ex -> {
assertThat(ex.getCode()).isEqualTo(403);
assertThat(ex.getMessage()).contains("同一家公司");
});
// 挂名挂到别家时一行都不许落库:落了就等于凭空造出一条跨公司的归属链,二期补不回来
verify(userMapper, never()).insert(any(AdminUserEntity.class));
}
@Test
void createdByIdFromTheSameCompanyIsAccepted() {
AdminUserEntity operator = operator(1L, "super_admin", 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(51L)).thenReturn(creator(51L, "admin", 1L));
AdminUserCreateRequest request = request("normal", null);
request.setCreatedById(51L);
service.createUser(operator, request);
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
verify(userMapper).insert(captor.capture());
assertThat(captor.getValue().getCreatedById()).isEqualTo(51L);
assertThat(captor.getValue().getCompanyId()).isEqualTo(1L);
}
@Test
void superAdminWithoutCompanyFallsBackToItsOwnCompany() {
// 操作者所属公司故意取 3:实现里写死 1(照抄列 DEFAULT)必须被这条抓到
@@ -124,14 +176,29 @@ class AdminUserServiceCompanyTest {
}
private AdminUserCreateRequest request(Long companyId) {
return request("normal", companyId);
}
private AdminUserCreateRequest request(String role, Long companyId) {
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("created-user");
request.setPassword("secret1");
request.setRole("normal");
request.setRole(role);
request.setCompanyId(companyId);
return request;
}
/** 被当作「所属管理员」挂名的账号:role=admin,落在 companyId 那家。 */
private AdminUserEntity creator(Long id, String role, Long companyId) {
AdminUserEntity creator = new AdminUserEntity();
creator.setId(id);
creator.setUsername("creator-" + id);
creator.setRole(role);
creator.setIsAdmin(1);
creator.setCompanyId(companyId);
return creator;
}
private AdminUserEntity operator(Long id, String role, Long companyId) {
AdminUserEntity operator = new AdminUserEntity();
operator.setId(id);