Compare commits

...

4 Commits

Author SHA1 Message Date
huangzd1997 de743399ec feat(账号到期): 普通账号不再带自己的到期时间,入口与接口一起收窄
口径(2026-10-05 用户定):到期时间只需要设在管理员/公司超管身上,普通账号的停用
由上级级联决定(组长 + 创建人 + 本公司公司超管,见 AccountExpiryService)。
此前这条只存在于约定里,任何调用方都能给普通账号写 expires_at。

- 后端 AdminUserService:建号/编辑两道 400(绕过界面直接打接口传值就拒),
  把管理员改成普通账号时同批把 expires_at 置 null;判据 mayCarryOwnExpiry
  = admin|company_super_admin。
- 前端:user-create-model 导出同名判据(一支跨端用例逐字钉两端集合相等),
  toCreateUserRequest 对 normal 不下发;toEditUserUpdateRequest 按"改完之后
  的角色"决定,不能带就发空串=清空,公司超管目标因请求不带 role 而保留原值;
  两个对话框的「到期时间」项加 v-if="expiryEditable"。
- 用例:后端新增 4 支(含一条「普通账号仍可传空串清除」控制组,14 例绿);
  前端新增 9 支;旧 company-user-create 那条编码旧口径的断言改 role=admin。
2026-10-05 17:00:18 +08:00
huangzd1997 950e838ea7 test(公司tab): 补分组 wrapper 用例,反向钉改绑到参数绑定本身
评审两处咬不住的地方:分组侧 list() 那条 created_by_id=? OR user_id=? 被公司条件
平铺时,MySQL 的 AND 优先会让前半个 OR 整块逃出筛选(多放行、接口照样 200),而这
一Shape 全仓没有用例捕;读入口的反向钉只断 contains("company_id"),而 @Operation
的描述里就写着这个词,删掉绑定也不会红。

顺带删掉没人调的 list(Long) 重载,并把"空成员集"两支落到 id=-1 哨兵上(IN () 是
MySQL 语法错,退化成不加条件则是把全量放出来)。
2026-10-05 16:57:32 +08:00
huangzd1997 db91394837 feat(公司tab): 店铺管理与数据权限分组按成员集筛, 凭据按 id 补读闸门
Task 11: ShopManageController.page / listGroups 接 DataReadScope.readScope,
把 company_id 算出的成员集当参数传给 service(controller 层收口, service 手上
只有 operatorId+布尔); ShopManageGroupService.list 增加 companyMemberIds 腿。

凭据 getCredentialById 的闸门用与 page() 同形的尺子(created_by_id IN creators
OR group_id IN groups),不是账号集合 —— 后者表达不了分组那一腿, 会把列表看得见
的行读凭据时 403 掉, 那是把正当访问静默删掉。

新增 testutil/SourceScan 供源码扫描式护栏取文(找不到方法必须抛, 不许返回空串恒绿)。

前端两页接 tab: companyId 取 companyTab.requestCompanyId, 并 watch activeId 重载;
G1 登记表给 admin_shop_manage 钉两条发送点(白名单 builder 故意不收 companyId)。
写侧入口一律不收 company_id, 由 ShopManageServiceTest 逐方法反向钉住。
2026-10-05 16:25:24 +08:00
huangzd1997 3793850552 docs(公司tab): 订正 Task 13 凭据验收口径(按会话收窄而非随 tab),并抄入 Task 12 Step 0 的生产只读实测 2026-10-05 14:53:31 +08:00
22 changed files with 789 additions and 52 deletions
@@ -3,6 +3,7 @@ import { computed, reactive, ref, watch } from 'vue'
import { submitCreateUser } from './user-create-adapter'
import {
createEmptyCreateUserForm,
mayCarryOwnExpiry,
type CreateUserForm,
type CreateUserFormErrors,
validateCreateUserForm,
@@ -38,6 +39,8 @@ const canChooseRole = computed(() => props.operatorSuper || props.operatorRole =
const roleChoices = computed(() =>
props.operatorSuper ? ROLE_CHOICES : ROLE_CHOICES.filter((opt) => opt.value !== 'company_super_admin'),
)
/** 只有管理员/公司超管有「自己的到期时间」;普通账号跟随上级级联,不给它入口。 */
const expiryEditable = computed(() => mayCarryOwnExpiry(form.role))
watch(
() => props.modelValue,
@@ -140,7 +143,7 @@ async function create(): Promise<void> {
/>
</el-select>
</el-form-item>
<el-form-item label="到期时间(留空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-form-item v-if="expiryEditable" label="到期时间(留空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-date-picker
v-model="form.expiresAt"
type="datetime"
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import type { AdminUser } from '@/types/admin'
import { mayCarryOwnExpiry } from './user-create-model'
import { fillEditUserForm, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model'
import { submitEditUser } from './user-edit-adapter'
import { loadUserMenuAuth } from './user-menu-auth-api'
@@ -19,6 +20,11 @@ const loadingAuth = ref(false)
const authReady = ref(false)
/** 公司超管目标:角色单选隐藏(请求体也不带 role),只允许改密码/到期时间/菜单。 */
const targetIsCompanySuperAdmin = computed(() => (props.user?.role || '').trim().toLowerCase() === 'company_super_admin')
/** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改;
* 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */
const expiryEditable = computed(() =>
mayCarryOwnExpiry(targetIsCompanySuperAdmin.value ? 'company_super_admin' : form.role),
)
watch(
() => props.modelValue,
@@ -112,7 +118,7 @@ async function save(): Promise<void> {
<el-form-item v-if="targetIsCompanySuperAdmin" label="角色">
<el-input model-value="公司超级管理员" readonly />
</el-form-item>
<el-form-item label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-form-item v-if="expiryEditable" label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
<el-date-picker
v-model="form.expiresAt"
type="datetime"
@@ -2,9 +2,10 @@
import { formatDateTime } from '@/utils/datetime'
/** 分组管理页 · 像素复刻旧版 admin.html panel-group-manage(自绘:顶部数据权限分组摘要 chips + 分组列表表格 + 新建分组;全量无分页同旧版)。
* script 逻辑沿用现有 Vue 实现;编辑器保留现有组件。 */
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { openAdminConfirm } from '@/components/admin-confirm'
import { deleteShopGroup, fetchShopGroups } from './shop-group-api'
import type { ShopGroupItem } from './shop-group-model'
@@ -12,6 +13,7 @@ import GroupEditorDialog from './GroupEditorDialog.vue'
import OldPagination from '@/components/OldPagination.vue'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
const loading = ref(false)
const rows = ref<ShopGroupItem[]>([])
const editorVisible = ref(false)
@@ -46,7 +48,7 @@ function canEditOf(group: ShopGroupItem): boolean {
async function loadGroups() {
loading.value = true
try {
rows.value = await fetchShopGroups()
rows.value = await fetchShopGroups(companyTab.requestCompanyId)
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '数据权限分组加载失败')
} finally {
@@ -54,6 +56,9 @@ async function loadGroups() {
}
}
// 切公司 = 重新取数(G1 的 pageFiles 断言盯着这一条)。
watch(() => companyTab.activeId, () => void loadGroups())
function openCreate() {
editingGroup.value = null
editorVisible.value = true
@@ -11,8 +11,8 @@ import {
export const SHOP_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups'
export async function fetchShopGroups(): Promise<ShopGroupItem[]> {
const { data } = await http.get<unknown>(SHOP_GROUPS_ENDPOINT)
export async function fetchShopGroups(companyId?: number | null): Promise<ShopGroupItem[]> {
const { data } = await http.get<unknown>(SHOP_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })
return parseShopGroupList(data)
}
@@ -57,6 +57,17 @@ export function normalizeCreateRole(role: string | null | undefined): CreatableU
return 'normal'
}
/**
* 可携带「自己的到期时间」的角色,与后端 AdminUserService#mayCarryOwnExpiry 逐字对齐
* (normal-account-no-own-expiry.test.ts 钉两端集合相等)。普通账号的停用只由上级
* (组长/公司超管)级联决定,给它单独设到期时间既没入口也没语义。
*/
export const EXPIRY_OWNABLE_ROLES: ReadonlyArray<string> = ['admin', 'company_super_admin']
export function mayCarryOwnExpiry(role: string | null | undefined): boolean {
return EXPIRY_OWNABLE_ROLES.includes((role || '').trim().toLowerCase())
}
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填;公司超管必须选公司);返回逐字段错误。 */
export function validateCreateUserForm(form: CreateUserForm): {
valid: boolean
@@ -88,6 +99,9 @@ export function validateCreateUserForm(form: CreateUserForm): {
* <p>company_id 仅在 role=company_super_admin 且显式选择时下发(见 CreateUserPayload 注释);
* 其余角色不带——归属由后端 `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司,
* 想给别的公司建普通账号,得用那个公司自己的管理员登录,不是在这里改请求体。</p>
*
* <p>expiresAt 只对可带到期时间的角色下发:普通账号的停用走上级级联,
* 带了会被后端 400 打回(界面已隐藏该输入项,这里是「表单残留值」的兜底)。</p>
*/
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
const role = normalizeCreateRole(form.role)
@@ -100,9 +114,10 @@ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
if (payload.role === 'normal' && form.createdBy != null) {
payload.createdById = form.createdBy
}
if (form.expiresAt && String(form.expiresAt).trim()) {
if (mayCarryOwnExpiry(role) && form.expiresAt && String(form.expiresAt).trim()) {
payload.expiresAt = String(form.expiresAt).trim()
}
if (role === 'company_super_admin' && form.companyId != null) {
payload.companyId = form.companyId
}
@@ -1,6 +1,6 @@
/** 编辑用户表单回填模型(任务 47):从用户行回填可编辑表单,镜像 Java AdminUserUpdateRequest。 */
import type { AdminUser } from '../../types/admin'
import { CREATE_PASSWORD_MIN_LEN } from './user-create-model.ts'
import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts'
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
export type EditUserRole = 'normal' | 'admin'
@@ -90,20 +90,29 @@ export function validateEditUserForm(form: EditUserForm): { valid: boolean; erro
return { valid: Object.keys(errors).length === 0, errors }
}
/** 编辑表单 → 更新请求体:站点超管拒绝、空密码不下发、columnIds 拷贝不共享引用。 */
/**
* 编辑表单 → 更新请求体:站点超管拒绝、空密码不下发、columnIds 拷贝不共享引用。
*
* <p>expiresAt 按「改完之后的角色」决定:目标角色不能带自己的到期时间时发空串=清空
* (后端 400 闸门只拦「有值」,空串走既有的清除分支)。公司超管目标不带 role,
* 它的 roleAfter 就是 company_super_admin,续费那条空串不会被误当成清空。</p>
*/
export function toEditUserUpdateRequest(form: EditUserForm): EditUserUpdateRequest {
const originalRole = (form.originalRole || '').trim().toLowerCase()
if (originalRole === 'super_admin') {
throw new Error('不能修改超级管理员')
}
const request: EditUserUpdateRequest = {
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 keepsRole = originalRole !== 'company_super_admin'
const nextRole: EditUserRole = form.role === 'admin' ? 'admin' : 'normal'
const roleAfter = keepsRole ? nextRole : originalRole
const request: EditUserUpdateRequest = {
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
expiresAt: mayCarryOwnExpiry(roleAfter) ? (form.expiresAt || '').trim() : '',
}
if (keepsRole) {
request.role = nextRole
}
const password = form.password || ''
if (password) request.password = password
@@ -2,9 +2,10 @@
import { formatDateTime } from '@/utils/datetime'
/** 店铺管理页 · 像素复刻旧版 admin.html panel-shop-manage(自绘:面板头+新增店铺、筛选、密码列 ******+眼睛实时读明文、旧式表格/分页、原生 confirm 删除)。
* script 逻辑沿用现有 Vue 实现(凭证明文 dialog/编辑弹窗/分组筛选)。 */
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import {
deleteShopManage,
fetchShopCredential,
@@ -18,6 +19,7 @@ import type { ShopCredential, ShopGroupOption, ShopSummary } from './shop-dto.ts
import OldPagination from '@/components/OldPagination.vue'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin)
const loading = ref(false)
@@ -75,7 +77,7 @@ async function togglePassword(row: ShopSummary) {
async function loadGroups() {
try {
groups.value = await fetchShopManageGroups()
groups.value = await fetchShopManageGroups(companyTab.requestCompanyId)
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '分组加载失败')
}
@@ -89,6 +91,7 @@ async function load() {
pageSize: pageSize.value,
groupId: filter.groupId,
shopName: filter.shopName.trim() || undefined,
companyId: companyTab.requestCompanyId,
})
rows.value = result.items
total.value = result.total
@@ -100,6 +103,10 @@ async function load() {
}
}
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 必须一起清掉:上一家选中的分组在新一家根本不存在,留着会把切 tab 后的首屏筛成空列表。
watch(() => companyTab.activeId, () => { filter.groupId = null; void loadGroups(); void load() })
function apply() {
page.value = 1
load()
@@ -93,6 +93,8 @@ export interface ShopManageListParams {
pageSize: number
groupId?: number | null
shopName?: string
/** 公司 tab 的值;normalizeShopListParams 不点名它,只有 api 层能从原始 params 读到。 */
companyId?: number | null
}
export interface ShopKeyPageQuery {
@@ -105,6 +107,8 @@ export interface ShopManagePageQuery {
pageSize: number
groupId?: number
shopName?: string
/** 下划线形:与后端 @RequestParam(name = "company_id") 逐字对齐。 */
company_id?: number
}
function finiteInt(value: unknown): number | null {
@@ -24,15 +24,21 @@ export const SHOP_MANAGE_ENDPOINT = '/api/admin/shop-manages'
export async function fetchShopManageList(params: Partial<ShopManageListParams> = {}): Promise<ShopPageResult> {
const normalized = normalizeShopListParams(params)
const { data } = await http.get<unknown>(SHOP_MANAGE_ENDPOINT, { params: toShopManagePageQuery(normalized) })
// normalizeShopListParams 与 toShopManagePageQuery 都是白名单构造(不点名 companyId),
// 所以公司值只能从原始 params 读:写成 normalized.companyId 是 TS 绿、运行时恒 undefined。
const query = toShopManagePageQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(SHOP_MANAGE_ENDPOINT, { params: query })
return parseShopManagePage(data)
}
export const SHOP_MANAGE_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups'
/** 加载店铺分组下拉选项(超级管理员取全部,普通管理员由后端限定可访问分组)。 */
export async function fetchShopManageGroups(): Promise<ShopGroupOption[]> {
const { data } = await http.get<unknown>(SHOP_MANAGE_GROUPS_ENDPOINT)
/** 分组下拉:打的是与分组管理页同一个 GET /groups,所以它也必须跟着公司 tab 收窄,
* 否则店铺列表窄了、下拉里还选得到别家的组。 */
export async function fetchShopManageGroups(companyId?: number | null): Promise<ShopGroupOption[]> {
const { data } = await http.get<unknown>(SHOP_MANAGE_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })
return parseShopManageGroups(data)
}
@@ -70,10 +70,27 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
{ file: 'src/api/device-logs.ts', shape: null, note: 'Task 12 未接线(已在缺口清单里)' },
],
admin_group_manage: [
{ file: 'src/pages/account/shop-group-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' },
{
file: 'src/pages/account/shop-group-api.ts',
// fetchShopGroups(companyId?: number | null):唯一发送口,右侧必须是它自己的形参。
shape: /company_id\s*:\s*companyId\b/,
note: 'null 由 axios 跳过 ⇒ 非超管不发 company_id,后端按会话裁剪',
},
],
admin_shop_manage: [
{ file: 'src/pages/shop/shop-manage-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' },
{
file: 'src/pages/shop/shop-manage-api.ts',
// fetchShopManageList(params):toShopManagePageQuery 是白名单构造 ⇒ 公司值只许从原始 params 读。
shape: /company_id\s*=\s*params\.companyId\b/,
note: '写成 normalized.companyId 会 TS 绿、运行时恒 undefined(Task 8 复评 I-2 那个洞)',
},
{
file: 'src/pages/shop/shop-manage-api.ts',
// 第二个发送口 fetchShopManageGroups(companyId):同一个 GET /groups,与分组管理页共用这一形。
// 两条各管一处取值口,不许合成一条 alternation —— 那等于把判据放松回「文件里出现过就行」。
shape: /company_id\s*:\s*companyId\b/,
note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组',
},
],
}
@@ -63,9 +63,11 @@ test('请求体:admin/normal 一律不带 companyId;公司超管必须带且
'没选公司就不许带(校验层会先拦住,这里兜底不静默)')
})
test('到期时间:空串不下发,有值随请求体走', () => {
test('到期时间:空串不下发,管理员有值随请求体走', () => {
assert.equal('expiresAt' in toCreateUserRequest(form()), false, '留空 = 永不过期,不下发')
assert.equal(toCreateUserRequest(form({ expiresAt: '2026-12-31 23:59:59' })).expiresAt,
// 2026-10-05 收窄后到期时间只能设在管理员/公司超管身上(普通账号那条见
// normal-account-no-own-expiry.test.ts),所以这条要角色=管理员才成立。
assert.equal(toCreateUserRequest(form({ role: 'admin', expiresAt: '2026-12-31 23:59:59' })).expiresAt,
'2026-12-31 23:59:59')
})
@@ -0,0 +1,128 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import {
createEmptyCreateUserForm,
EXPIRY_OWNABLE_ROLES,
mayCarryOwnExpiry,
toCreateUserRequest,
} from '../src/pages/account/user-create-model.ts'
import {
fillEditUserForm,
toEditUserUpdateRequest,
} from '../src/pages/account/user-edit-model.ts'
/**
* 「普通账号不带自己的到期时间」(2026-10-05 定案)。
*
* 需求口径:到期时间只需要设在管理员/公司超管身上,普通账号的停用由上级级联决定
* (组长 + 创建人 + 本公司公司超管,见 AccountExpiryService.computeEffective)。
* 后端已把这条做进出口(AdminUserService 两处 400 闸门 + 降级即清空),本文件钉前端侧:
* 1) 建号时角色是 normal,表单里就算残留了到期值也不许下发(下发即被后端 400 打回);
* 2) 编辑时把管理员改成普通账号,要顺带把到期时间发成「清空」而不是原值——
* 这条是用户明确选定的行为(自动清空),不是顺手抹掉;
* 3) 公司超管目标(表单 role 恒归一成 normal)不许被上面两条误清。
*/
function createForm(overrides: Record<string, unknown> = {}) {
return {
...createEmptyCreateUserForm(),
username: 'zhangsan',
password: 'secret123',
...overrides,
}
}
function editForm(overrides: Record<string, unknown> = {}) {
return {
uid: 9,
username: 'team-lead',
password: '',
role: 'admin',
columnIds: [],
originalRole: 'admin',
expiresAt: '2026-12-31 23:59:00',
...overrides,
}
}
// ---------- 建号 ----------
test('create_normal_does_not_send_expiry_even_when_form_still_holds_it', () => {
const payload = toCreateUserRequest(createForm({ role: 'normal', expiresAt: '2026-12-31 23:59:00' }))
assert.equal(payload.role, 'normal')
assert.ok(!('expiresAt' in payload), `普通账号不许带 expiresAt,实际 payload=${JSON.stringify(payload)}`)
})
test('create_admin_still_sends_expiry', () => {
const payload = toCreateUserRequest(createForm({ role: 'admin', expiresAt: '2026-12-31 23:59:00' }))
assert.equal(payload.expiresAt, '2026-12-31 23:59:00', '管理员必须还能设到期时间')
})
test('create_company_super_admin_still_sends_expiry', () => {
const payload = toCreateUserRequest(
createForm({ role: 'company_super_admin', expiresAt: '2026-12-31 23:59:00', companyId: 2 }),
)
assert.equal(payload.expiresAt, '2026-12-31 23:59:00')
assert.equal(payload.companyId, 2)
})
// ---------- 编辑 ----------
test('edit_demoting_admin_to_normal_sends_expiry_clear', () => {
const request = toEditUserUpdateRequest(editForm({ role: 'normal' }))
assert.equal(request.role, 'normal')
assert.equal(request.expiresAt, '', '降级为普通账号要发「清空」,不能把旧到期时间发给后端换 400')
})
test('edit_company_super_admin_target_keeps_its_expiry', () => {
// 公司超管目标:表单 role 被 editRoleOf 归一成 normal,但绝不能被当成"降级"误清。
const request = toEditUserUpdateRequest(
editForm({ originalRole: 'company_super_admin', role: 'normal', expiresAt: '2026-12-31 23:59:00' }),
)
assert.ok(!('role' in request), '公司超管目标不带 role')
assert.equal(request.expiresAt, '2026-12-31 23:59:00', '续费入口就是改这个值,不许被清空逻辑吞掉')
})
test('edit_normal_target_sends_no_expiry_even_if_row_had_one', () => {
// 存量兜底:库里若有"普通账号带到期时间"的行,编辑保存时按清空处理(后端同口径)。
const request = toEditUserUpdateRequest(
editForm({ originalRole: 'normal', role: 'normal', expiresAt: '2026-12-31 23:59:00' }),
)
assert.equal(request.expiresAt, '')
})
test('edit_fill_from_row_keeps_expiry_for_admin', () => {
const form = fillEditUserForm({ id: 9, username: 'lead', role: 'admin', expiresAt: '2026-12-31 23:59' } as never)
assert.equal(form.expiresAt, '2026-12-31 23:59:00', '回填补秒位这条不能坏')
})
// ---------- 跨端对齐 ----------
test('frontend_and_backend_agree_on_which_roles_carry_expiry', () => {
assert.deepEqual(
['admin', 'company_super_admin', 'normal', 'super_admin', ''].map(mayCarryOwnExpiry),
[true, true, false, false, false],
)
const java = readSource('../backend-java/src/main/java/com/nanri/aiimage/modules/admin/service/AdminUserService.java')
const body = java.match(/private static boolean mayCarryOwnExpiry\(String resolvedRole\) \{([\s\S]*?)\n \}/)
assert.ok(body, '后端必须仍有 mayCarryOwnExpiry 这个方法(前端对齐的是它,不是别处)')
const javaRoles = [...body[1].matchAll(/"([a-z_]+)"\.equals\(resolvedRole\)/g)].map((m) => m[1]).sort()
assert.deepEqual(javaRoles, ['admin', 'company_super_admin'], '后端那份判据必须还是这两个角色')
assert.deepEqual([...EXPIRY_OWNABLE_ROLES].sort(), javaRoles, '两端可带到期时间的角色集合必须逐字相等')
})
// ---------- 界面出口(源码钉,防"那一行被删")----------
test('expiry_input_hidden_for_normal_in_both_dialogs', () => {
for (const rel of [
'src/pages/account/CreateUserDialog.vue',
'src/pages/account/EditUserDialog.vue',
]) {
const source = readSource(rel)
const item = source.match(/<el-form-item[^>]*label="到期时间[^"]*"[^>]*>/)
assert.ok(item, `${rel} 必须有「到期时间」表单项`)
assert.match(item[0], /v-if=/, `${rel} 的到期时间项必须带角色条件,不能对所有角色都渲染`)
assert.match(item[0], /mayCarryOwnExpiry|expiryEditable/, `${rel} 的角色条件要用同一个可到期角色判据`)
}
})
@@ -9,6 +9,7 @@ import com.nanri.aiimage.modules.admin.model.vo.AdminBriefVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.modules.admin.util.PinyinAbbrUtil;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
@@ -40,6 +41,10 @@ public class AdminUserService {
private static final DateTimeFormatter CREATED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
/** 普通账号不该带自己的到期时间(2026-10-05 定案):它的停用一律由上级账号级联决定。 */
private static final String NORMAL_ACCOUNT_EXPIRY_MESSAGE =
"普通账号不需要设置到期时间,其停用跟随上级账号(组长/公司超管)级联";
private final AdminUserMapper adminUserMapper;
private final WerkzeugPasswordEncoder passwordEncoder;
private final AdminAuthSupport adminAuthSupport;
@@ -156,6 +161,9 @@ public class AdminUserService {
// 公司超管是「某一家公司的最高账号」,只能由站点超管开设,谁都不能自己造一级
throw new BusinessException(403, "只有超级管理员可以创建公司超级管理员");
}
if (!mayCarryOwnExpiry(wantRole) && hasExpiryValue(request.getExpiresAt())) {
throw new BusinessException(400, NORMAL_ACCOUNT_EXPIRY_MESSAGE);
}
if (username.isEmpty() || password.isEmpty()) {
throw new BusinessException("用户名和密码不能为空");
}
@@ -216,6 +224,16 @@ public class AdminUserService {
return wantRole;
}
/** 哪些角色需要自己带 expires_at:管理员与公司超管;normal 与 super_admin 都不带(超管永不适用)。 */
private static boolean mayCarryOwnExpiry(String resolvedRole) {
return "admin".equals(resolvedRole) || "company_super_admin".equals(resolvedRole);
}
/** 请求里"给了到期时间":非 null 且非空白。空串是清除指令(恢复永不过期),不算给值。 */
private static boolean hasExpiryValue(String raw) {
return raw != null && !raw.trim().isEmpty();
}
/**
* 解析请求里的到期时间:null/空白 = null(永不过期);支持 yyyy-MM-dd、
* yyyy-MM-dd HH:mm、yyyy-MM-dd HH:mm:ss 与 ISO(yyyy-MM-ddTHH:mm)。
@@ -362,6 +380,15 @@ public class AdminUserService {
}
}
// 到期时间只能设在管理员/公司超管身上(普通账号跟随上级级联)。wantRole 为空表示本次不改角色,
// 所以判"改完之后"的角色:非空 storedRole 时 resolveRole 不看 is_admin,推断链不会被带偏。
String roleAfter = DeviceSessionPolicy.resolveRole(
wantRole == null || wantRole.isEmpty() ? target.getRole() : wantRole,
target.getIsAdmin(), target.getCreatedById());
if (!mayCarryOwnExpiry(roleAfter) && hasExpiryValue(request.getExpiresAt())) {
throw new BusinessException(400, NORMAL_ACCOUNT_EXPIRY_MESSAGE);
}
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
if (moveCompanyId != null) {
@@ -395,6 +422,15 @@ public class AdminUserService {
request.getExpiresAt().trim().isEmpty() ? null : parseExpiresAt(request.getExpiresAt()));
dirty = true;
}
String roleBefore = DeviceSessionPolicy.resolveRole(target.getRole(), target.getIsAdmin(),
target.getCreatedById());
if (request.getExpiresAt() == null && mayCarryOwnExpiry(roleBefore) && !mayCarryOwnExpiry(roleAfter)
&& target.getExpiresAt() != null) {
// 角色被降级成普通账号:同一次更新里摘掉它自己的到期时间,之后由上级级联决定它何时停。
// 只在"真的发生降级"时清,改密码之类的无关编辑不许顺手抹掉历史值。
update.set(AdminUserEntity::getExpiresAt, null);
dirty = true;
}
if (dirty) {
adminUserMapper.update(null, update);
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
@@ -35,6 +36,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequiredArgsConstructor
@@ -45,6 +48,7 @@ public class ShopManageController {
private final ShopManageService shopManageService;
private final ShopManageGroupService shopManageGroupService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
/** 解析当前操作者(JWT 或内部令牌通道),数据范围一律以该身份为准,不信任调用方传入的 operatorId/superAdmin。 */
private AdminUserEntity requireOperator(HttpServletRequest request) {
@@ -56,7 +60,8 @@ public class ShopManageController {
}
@GetMapping
@Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选")
@Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选;"
+ "company_id 只收窄可见集、不放大,跨公司查看仅超管")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(
responseCode = "200",
@@ -68,15 +73,16 @@ public class ShopManageController {
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
@Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId,
@Parameter(description = "店铺名称") @RequestParam(required = false) String shopName) {
@Parameter(description = "店铺名称") @RequestParam(required = false) String shopName,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
return ApiResponse.success(shopManageService.page(
page,
pageSize,
groupId,
shopName,
operator.getId(),
isSuper(operator)));
Long operatorId = operator.getId();
boolean superAdmin = isSuper(operator);
// 公司 tab 只对超管收窄:非超管的可见集里含「靠分组可见」的行,而分组行没有账号列可推公司,
// 给它叠 created_by_id IN (成员) 会把那批行从每一个 tab 里静默删掉(不报错、不 403)。
List<Long> memberIds = superAdmin ? dataReadScope.readScope(operator, companyId).userIdsOr(null) : null;
ShopManagePageVo vo = shopManageService.page(page, pageSize, groupId, shopName, operatorId, superAdmin, memberIds);
return ApiResponse.success(vo);
}
@PostMapping
@@ -111,15 +117,19 @@ public class ShopManageController {
}
@GetMapping("/groups")
@Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部")
@Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部;"
+ "company_id 只收窄可见集、不放大,跨公司查看仅超管")
public ApiResponse<java.util.List<ShopManageGroupItemVo>> listGroups(
HttpServletRequest request,
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById) {
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
if (isSuper(operator)) {
return ApiResponse.success(shopManageGroupService.list(createdById));
List<Long> memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null);
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds));
}
return ApiResponse.success(shopManageGroupService.listAccessible(operator.getId(), false));
Long operatorId = operator.getId();
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false));
}
@PostMapping("/groups")
@@ -175,10 +185,8 @@ public class ShopManageController {
public ApiResponse<ShopManageCredentialVo> adminCredential(
HttpServletRequest request,
@Parameter(description = "店铺主键 ID") @PathVariable Long id) {
requireOperator(request);
// 2026-09 修复:此前忽略路径 id、改用请求参数 shop_name 查询,
// 会出现「路径声明的店铺」与「实际读取凭据的店铺」不一致
return ApiResponse.success(shopManageService.getCredentialById(id));
AdminUserEntity operator = requireOperator(request);
return ApiResponse.success(shopManageService.getCredentialById(id, operator.getId(), isSuper(operator)));
}
}
@@ -45,14 +45,27 @@ public class ShopManageGroupService {
private final AdminUserMapper adminUserMapper;
public List<ShopManageGroupItemVo> list() {
return list(null);
return list(null, null);
}
public List<ShopManageGroupItemVo> list(Long createdById) {
return toVoList(groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
.eq(createdById != null && createdById > 0, ShopManageGroupEntity::getCreatedById, createdById)
.or(createdById != null && createdById > 0, wrapper -> wrapper.eq(ShopManageGroupEntity::getUserId, createdById))
.orderByAsc(ShopManageGroupEntity::getId)));
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds) {
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
.orderByAsc(ShopManageGroupEntity::getId);
if (createdById != null && createdById > 0) {
// 这两条原本是平铺的 .eq(...).or(...):MP 的 normal 段按顺序拼 AND/OR,MySQL 里 AND 优先,
// 外面再叠一条公司条件时 created_by_id = ? 那半边会整块逃出筛选(多放行、不报错)⇒ 必须收进 and()。
qw.and(w -> w.eq(ShopManageGroupEntity::getCreatedById, createdById)
.or(x -> x.eq(ShopManageGroupEntity::getUserId, createdById)));
}
if (companyMemberIds != null) {
if (companyMemberIds.isEmpty()) {
qw.eq(ShopManageGroupEntity::getId, -1L);
} else {
// 同样自成一组:上面那支 and() 里已经混着 OR,这条若平铺下去,AND 优先只会作用在 OR 的右半边。
qw.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds));
}
}
return toVoList(groupMapper.selectList(qw));
}
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin) {
@@ -28,7 +28,8 @@ public class ShopManageService {
private final ShopCredentialCryptoService shopCredentialCryptoService;
private final ZiniaoShopIndexRefreshTrigger ziniaoShopIndexRefreshTrigger;
public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, boolean superAdmin) {
public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId,
boolean superAdmin, List<Long> companyMemberIds) {
long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
String safeShopName = shopName == null ? "" : shopName.trim();
@@ -60,6 +61,16 @@ public class ShopManageService {
}
}
// companyMemberIds 由 controller 算好传进来(service 手上只有 operatorId + 一个布尔,
// 而 readScope 要 AdminUserEntity)。null = 不筛,与"超管没选公司"的今天逐字一致。
if (companyMemberIds != null) {
if (companyMemberIds.isEmpty()) {
query.eq(ShopManageEntity::getId, -1L);
} else {
query.in(ShopManageEntity::getCreatedById, companyMemberIds);
}
}
Long total = shopManageMapper.selectCount(query);
List<ShopManageEntity> rows = shopManageMapper
.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));
@@ -152,7 +163,7 @@ public class ShopManageService {
* <p>管理端 {@code GET /{id}/credential} 此前忽略路径里的 id、改用 shop_name 查询——
* 路径声明的对象与实际读取的对象可能不一致(同名的第一条被读写,审计日志却记成另一个 id)。
*/
public ShopManageCredentialVo getCredentialById(Long id) {
public ShopManageCredentialVo getCredentialById(Long id, Long operatorId, boolean superAdmin) {
if (id == null || id <= 0) {
throw new BusinessException("店铺 ID 不合法");
}
@@ -160,6 +171,18 @@ public class ShopManageService {
if (entity == null) {
throw new BusinessException("店铺不存在");
}
// 尺子必须与 page() 那一条同形:created_by_id IN creators OR group_id IN groups。
// 账号集合表达不了分组那一腿(店铺建在我可访问的分组里、创建人却不在我的账号集),
// 拿它当闸门会把列表看得见的行读凭据时 403 掉——那是把正当访问静默删掉。
if (!superAdmin) {
Set<Long> creators = shopManageGroupService.listAccessibleCreatorUserIds(operatorId, false);
Set<Long> groups = shopManageGroupService.listAccessibleGroupIds(operatorId, false);
boolean visible = (entity.getCreatedById() != null && creators.contains(entity.getCreatedById()))
|| (entity.getGroupId() != null && groups.contains(entity.getGroupId()));
if (!visible) {
throw new BusinessException(403, "无权查看该店铺的凭据");
}
}
return toCredentialVo(entity);
}
@@ -22,11 +22,13 @@ import org.mockito.ArgumentCaptor;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -236,6 +238,86 @@ class AdminUserServiceCompanySuperAdminTest {
.hasMessageContaining("只有超级管理员可以删除公司超级管理员");
}
// ---------- 普通账号不带自身到期(2026-10-05 定案:到期只设在管理员/公司超管身上)----------
@Test
void createRejectsExpiryOnNormalAccount() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("staff-1");
request.setPassword("secret1");
request.setRole("normal");
request.setCreatedById(7L);
request.setExpiresAt("2026-12-31 23:59");
when(authSupport.currentRole(operator)).thenReturn("super_admin");
BusinessException ex = catchThrowableOfType(() -> service.createUser(operator, request),
BusinessException.class);
assertThat(ex).isNotNull();
assertThat(ex.getCode()).isEqualTo(400);
assertThat(ex.getMessage()).contains("普通账号");
verify(userMapper, never()).insert(any(AdminUserEntity.class));
}
@Test
void updateRejectsExpiryOnNormalTarget() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "normal", 1L, 7L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setExpiresAt("2026-12-31 23:59");
BusinessException ex = catchThrowableOfType(() -> service.updateUser(operator, 9L, request),
BusinessException.class);
assertThat(ex).isNotNull();
assertThat(ex.getCode()).isEqualTo(400);
verify(userMapper, never()).update(any(), any());
}
@Test
void demotingAdminToNormalClearsOwnExpiry() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "admin", 1L, 1L);
target.setExpiresAt(LocalDateTime.of(2026, 12, 31, 23, 59));
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setRole("normal");
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");
// 清的是 null,不是把原时间照抄回去
assertThat(captor.getValue().getParamNameValuePairs().values())
.noneMatch(value -> value instanceof LocalDateTime);
}
/** 控制用例:收掉入口不许顺手把「清空」也禁掉——空串仍要能把历史值摘成永不过期。 */
@Test
void normalTargetCanStillClearExpiryWithBlankValue() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "normal", 1L, 7L);
target.setExpiresAt(LocalDateTime.of(2026, 12, 31, 23, 59));
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");
}
// ---------- helpers ----------
private static AdminUserEntity user(Long id, String role, Long companyId, Long createdById) {
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.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.security.AdminAuthSupport;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo;
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
@@ -30,10 +31,11 @@ class ShopManageCredentialAuthTest {
private final ShopManageService shopManageService = mock(ShopManageService.class);
private final ShopManageGroupService shopManageGroupService = mock(ShopManageGroupService.class);
private final AdminAuthSupport adminAuthSupport = mock(AdminAuthSupport.class);
private final DataReadScope dataReadScope = mock(DataReadScope.class);
private final HttpServletRequest request = mock(HttpServletRequest.class);
private ShopManageController newController() {
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport);
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport, dataReadScope);
}
@Test
@@ -0,0 +1,111 @@
package com.nanri.aiimage.modules.shopkey.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.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Task 11 分组侧(计划 Step 1 点名的新建文件):{@code ShopManageGroupService.list} 叠公司条件时,
* 既有那条 {@code created_by_id = ? OR user_id = ?} 必须整块留在括号里。
*
* <p>这是本任务唯一一处「错了不报错、只是多放行」的形状:MP 的 normal 段按顺序拼 AND/OR,而 MySQL 里
* AND 优先 ⇒ 平铺成 {@code created_by_id = ? OR user_id = ? AND created_by_id IN (...)} 时,第一个
* {@code created_by_id = ?} 整块逃出公司筛选,别家的分组照样列出来,接口还是 200。</p>
*
* <p>断言口径与 {@code ShopManageServiceTest} 同一条:<b>结构</b>(括号、OR、IN)从
* {@code getSqlSegment()} 读,<b>值</b>从 {@code getParamNameValuePairs()} 读——MP 在 segment 里只放
* {@code #{ew.paramNameValuePairs.MPGENVALn}} 占位,写 {@code segment.contains("11")} 是恒假断言。
* 反向钉(没给成员集不许叠条件)与它的正样本写在同一支用例里,两支护一支持平。</p>
*/
@ExtendWith(MockitoExtension.class)
class ShopManageGroupServiceTest {
@Mock
private ShopManageGroupMapper groupMapper;
/** 只给 groupMapper 打桩;其余构造参数留 null——本文件三支用例都只走 list() 的第一段查询。 */
@InjectMocks
private ShopManageGroupService groupService;
/** getSqlSegment() 解析 lambda 靠 TableInfo 缓存,单测没有 Spring 容器建它,不初始化就抛 "can not find lambda cache"。 */
@BeforeEach
void initTableInfo() {
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private List<LambdaQueryWrapper<ShopManageGroupEntity>> captureAll(int expectedInvocations) {
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(groupMapper, times(expectedInvocations)).selectList(captor.capture());
// captor 是 raw 的(ArgumentCaptor 对泛型参数只能按原始类型捕),这里过 raw List 而不是逐个 cast。
return (List) captor.getAllValues();
}
@Test
@DisplayName("分组:list 叠公司必须把既有那条平铺 OR 整个套进括号(否则 created_by_id=? 那半边逃出筛选)")
void groupListWrapsTheOrBeforeNarrowing() {
when(groupMapper.selectList(any())).thenReturn(List.of());
groupService.list(5L, List.of(11L));
LambdaQueryWrapper<ShopManageGroupEntity> q = captureAll(1).get(0);
String segment = q.getSqlSegment();
assertThat(segment).as("OR 组必须被 and() 包住").contains("(created_by_id").contains(" OR ");
assertThat(segment.lastIndexOf("AND ("))
.as("公司条件必须自成一组,不能与 OR 平铺")
.isGreaterThan(segment.indexOf("created_by_id"));
assertThat(q.getParamNameValuePairs().values()).contains(11L);
}
@Test
@DisplayName("分组:成员集为空 ⇒ 走 id = -1 恒空,绝不渲染 IN ()(MySQL 语法错)")
void groupListEmptyMemberSetUsesSentinel() {
when(groupMapper.selectList(any())).thenReturn(List.of());
groupService.list(5L, List.of());
LambdaQueryWrapper<ShopManageGroupEntity> q = captureAll(1).get(0);
assertThat(q.getSqlSegment()).doesNotContain("IN (");
assertThat(q.getParamNameValuePairs().values())
.as("空集必须落到恒不命中的哨兵 id 上,而不是退化成「不加条件」= 看全量")
.contains(-1L);
}
@Test
@DisplayName("分组:只有给了成员集才叠公司条件——正反两向写在同一支用例里,反向钉不许独自成立")
void companyLegAppearsOnlyWhenMemberSetGiven() {
when(groupMapper.selectList(any())).thenReturn(List.of());
groupService.list(null, null);
groupService.list(null, List.of(11L, 12L));
List<LambdaQueryWrapper<ShopManageGroupEntity>> both = captureAll(2);
LambdaQueryWrapper<ShopManageGroupEntity> unfiltered = both.get(0);
LambdaQueryWrapper<ShopManageGroupEntity> narrowed = both.get(1);
assertThat(unfiltered.getSqlSegment()).doesNotContain("IN (");
assertThat(unfiltered.getParamNameValuePairs().values()).doesNotContain(11L, 12L);
// 正样本:上一支的 doesNotContain 只有在这一支真的会渲染 IN 时才有意义。
assertThat(narrowed.getSqlSegment()).contains("IN (");
assertThat(narrowed.getParamNameValuePairs().values()).contains(11L, 12L);
}
}
@@ -1,19 +1,34 @@
package com.nanri.aiimage.modules.shopkey.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.exception.BusinessException;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity;
import com.nanri.aiimage.testutil.SourceScan;
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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -29,6 +44,13 @@ class ShopManageServiceTest {
@InjectMocks
private ShopManageService service;
/** getSqlSegment() 解析 lambda 靠 TableInfo 缓存,单测没有 Spring 容器去建它,不初始化就抛 "can not find lambda cache"。 */
@BeforeEach
void initTableInfo() {
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageEntity.class);
}
@Test
void requireShopByNameReturnsManagedShop() {
ShopManageEntity entity = new ShopManageEntity();
@@ -47,4 +69,96 @@ class ShopManageServiceTest {
assertEquals("后台店铺管理中未找到店铺:缺失店铺,请先添加店铺信息", exception.getMessage());
}
@Test
@DisplayName("读:超管选了公司 ⇒ created_by_id 落进成员集;非超管不叠这一条")
void superAdminPageNarrowsToCompanyMembers() {
when(shopManageMapper.selectCount(any())).thenReturn(1L);
when(shopManageMapper.selectList(any())).thenReturn(List.of());
service.page(1L, 15L, null, null, 1L, true, List.of(11L, 12L));
ArgumentCaptor<LambdaQueryWrapper<ShopManageEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(shopManageMapper).selectCount(captor.capture());
// 值在 paramNameValuePairs 里,segment 里只有 MPGENVAL 占位 ⇒ 结构从 segment 读、值从 pairs 读。
assertThat(captor.getValue().getSqlSegment()).contains("created_by_id").contains("IN (");
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(11L, 12L);
}
@Test
@DisplayName("读:超管选了一家没有成员的公司 ⇒ 走 id = -1 恒空,不许退化成不加条件")
void superAdminPageWithEmptyMemberSetStaysEmpty() {
when(shopManageMapper.selectCount(any())).thenReturn(0L);
service.page(1L, 15L, null, null, 1L, true, List.of());
ArgumentCaptor<LambdaQueryWrapper<ShopManageEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(shopManageMapper).selectCount(captor.capture());
assertThat(captor.getValue().getSqlSegment())
.as("空集渲染 IN () 是 MySQL 语法错;退化成不加条件则是把全量放出来")
.doesNotContain("IN (");
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(-1L);
}
@Test
@DisplayName("凭据:非超管读「创建人不认识、分组也不认识」的行 ⇒ 403(§6.1 列表筛了按 id 照读)")
void credentialByIdRejectsRowOutsideBothVisibleSets() {
when(shopManageMapper.selectById(77L)).thenReturn(shop(77L, 999L, 7L));
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L, 12L));
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of());
assertThatThrownBy(() -> service.getCredentialById(77L, 2L, false))
.isInstanceOf(BusinessException.class)
.hasFieldOrPropertyWithValue("code", 403);
}
@Test
@DisplayName("凭据:店铺建在可访问分组里、创建人却不在我的账号集 ⇒ 必须 200(闸门用列表那把尺子,不是账号集合)")
void credentialByIdKeepsGroupVisibleRowsReadable() {
when(shopManageMapper.selectById(78L)).thenReturn(shop(78L, 999L, 5L));
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L));
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of(5L));
// 这一支是防误伤的正样本:把它删掉,下一轮"改成按账号集合卡"就没有任何尺子看得见。
assertThatCode(() -> service.getCredentialById(78L, 2L, false)).doesNotThrowAnyException();
}
@Test
@DisplayName("凭据:超管不查可见集(今天不筛、tab 也不是安全边界;删掉短路就红在 403)")
void credentialByIdStaysUnfilteredForSuperAdmin() {
when(shopManageMapper.selectById(79L)).thenReturn(shop(79L, 999L, 7L));
assertThatCode(() -> service.getCredentialById(79L, 1L, true)).doesNotThrowAnyException();
}
private static ShopManageEntity shop(long id, Long createdById, Long groupId) {
ShopManageEntity entity = new ShopManageEntity();
entity.setId(id);
entity.setCreatedById(createdById);
entity.setGroupId(groupId);
return entity;
}
@Test
@DisplayName("写:店铺与分组的写入口一律不收 company_id——归属不从界面注入(§6.2,未批的界面暴露)")
void writeEntryPointsCarryNoCompanyId() {
String text = SourceScan.sourceText("ShopManageController.java");
// 必须逐方法体判:page 这个读入口这轮就要加 company_id,全文 doesNotContain 会被自己弄红。
for (String writer : List.of("create", "update", "delete", "createGroup", "updateGroup", "deleteGroup")) {
assertThat(SourceScan.methodBody(text, writer))
.as("写入口「" + writer + "」一旦出现 company_id,等于把公司维度端回界面(未批)")
.doesNotContain("company_id")
.doesNotContain("companyId");
}
// 取样自检必须钉「绑定」本身:methodBody 含注解,而 @Operation 的文案里就写着 company_id,
// 只断 contains("company_id") 会在参数被删掉后照样绿——删掉绑定后 G2 的 A/B 两支也都不再触发。
assertThat(SourceScan.methodBody(text, "page"))
.as("page 的 company_id 绑定一旦消失,这一整页的 tab 就成了装饰品,且没有任何尺子会红")
.contains("@RequestParam(name = \"company_id\"");
assertThat(SourceScan.methodBody(text, "listGroups"))
.as("listGroups 同样钉在自己的注解上,不是文件里另一处的字面量")
.contains("@RequestParam(name = \"company_id\"");
}
}
@@ -0,0 +1,144 @@
package com.nanri.aiimage.testutil;
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.stream.Collectors;
import java.util.stream.Stream;
/** 源码扫描式护栏的取文助手。<b>路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的
* moduleRoot()/mainSources() 两支</b>——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/,
* 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */
public final class SourceScan {
private SourceScan() {
}
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
* ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事,
* 别指望复用它的——那个是 private。 */
public static String sourceText(String fileName) {
return mainSources().stream()
.filter(p -> p.getFileName().toString().equals(fileName))
.findFirst()
.map(SourceScan::read)
.orElseThrow(() -> new IllegalStateException(
"src/main/java 下找不到 " + fileName + " —— 文件改名/挪目录了,护栏要红在这里"));
}
/** 大括号配平切出「某个方法」的源码:<b>从它的签名行往前一直含到注解</b>,到方法收尾的 `}` 为止。
*
* <p>两条它必须自己防住的坑,都写在用例里过:</p>
* <ul>
* <li><b>名字必须是完整词</b>:{@code delete} 是 {@code deleteGroup} 的前缀。用 {@code indexOf(name)}
* 会先撞上那个更长的方法 ⇒ "切出来的是隔壁",而断言仍然绿。所以下面用 {@code (?<![A-Za-z0-9_])} 卡左边界,
* 并且要求紧跟 {@code (}(构造器/局部变量名同前缀也不算方法)。</li>
* <li><b>找不到必须抛</b>,不许返回空串:返回 "" 的话 {@code doesNotContain("company_id")} 恒真,
* 反向钉会因为方法被改名而悄悄失效(memory「字符串断言必须排他、解析断言必须可匹配」)。
* 配套要求:每个用它的反向钉都要带一条"该做的确实做了"的取样自检。</li>
* </ul>
*/
public static String methodBody(String source, String methodName) {
var matcher = java.util.regex.Pattern
.compile("(?<![A-Za-z0-9_])" + java.util.regex.Pattern.quote(methodName) + "\\s*\\(")
.matcher(source);
while (matcher.find()) {
int open = matcher.end() - 1;
int signatureStart = findSignatureStart(source, matcher.start());
int bodyEnd = matchBraces(source, nextBrace(source, open));
if (bodyEnd < 0) {
continue;
}
return source.substring(signatureStart, bodyEnd + 1);
}
throw new AssertionError("源码里没有方法「" + methodName + "」——它被改名或删掉了。"
+ "反向钉宁可红在这里,也不许因为切不到方法而恒绿。");
}
/** 从签名的左括号往前退到上一条 `{`/`}`/`;` 之后,再退回到第一行注解的起始(注解属于这个方法,必须含进来)。 */
private static int findSignatureStart(String source, int nameStart) {
int boundary = 0;
for (int i = nameStart; i-- > 0; ) {
char c = source.charAt(i);
if (c == '{' || c == '}' || c == ';') {
boundary = i + 1;
break;
}
}
String head = source.substring(boundary, nameStart);
int firstMeaningful = head.length();
for (String raw : head.split("\n", -1)) {
if (!raw.isBlank()) {
firstMeaningful = head.indexOf(raw.stripLeading());
break;
}
}
return boundary + firstMeaningful;
}
private static int nextBrace(String source, int from) {
for (int i = from; i < source.length(); i++) {
if (source.charAt(i) == '{') {
return i;
}
if (source.charAt(i) == ';') {
return -1; // 抽象方法/接口声明,不是我们要切的东西
}
}
return -1;
}
/** 朴素配平:源码里的 `{` 与 `}` 若出现在字符串字面量里会算错。本仓库 controller 没有这种写法,
* 但这条限制必须写在脸上——将来有人往方法体里塞一段带花括号的字符串,这个助手会悄悄切短。 */
private static int matchBraces(String source, int open) {
if (open < 0) {
return -1;
}
int depth = 0;
for (int i = open; i < source.length(); i++) {
char c = source.charAt(i);
if (c == '{') {
depth++;
} else if (c == '}') {
if (--depth == 0) {
return i;
}
}
}
return -1;
}
private static List<Path> mainSources() {
Path root = moduleRoot().resolve("src/main/java");
try (Stream<Path> walk = Files.walk(root)) {
return walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.collect(Collectors.toList());
} catch (IOException e) {
// 定位不到必须抛,不许静默返回空表:返回空 ⇒ sourceText 那支护栏扫不到任何文件而恒绿。
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
}
}
private static Path moduleRoot() {
Path here = Path.of("").toAbsolutePath();
if (Files.isDirectory(here.resolve("src/main/java"))) {
return here;
}
Path nested = here.resolve("backend-java");
if (Files.isDirectory(nested.resolve("src/main/java"))) {
return nested;
}
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
}
private static String read(Path file) {
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
}
+4 -2
View File
@@ -2419,6 +2419,8 @@ SELECT source, COUNT(*) FROM device_log_file GROUP BY source;
- 客户端占多数 ⇒ 留在批次 1,Step 1 起往下做。
- 结果抄进本任务的提交信息。**"0 命中"或只出一个 source 时先怀疑抓错表**:配一个 `SELECT COUNT(*) FROM device_log_file` 做非零对照(memory「grep -v 过滤器连 stdout 一起吞、0 命中≠没有」)。
✅ **已实跑(2026-10-05 15:1x,主机 A 业务库只读,非零对照齐全)**:`COUNT(*)` = **1028**;`GROUP BY source` = `client` **831** / `maixiang` **197**(831+197=1028,与对照逐数相符)⇒ **客户端占多数 ⇒ 这页留在批次 1,`companyScoped` 照声明,Step 1 起往下做**。另有一条本任务要用:`WHERE uid IS NULL GROUP BY source` = `client` **22** / `maixiang` **197** ⇒ 那 22 行是"有 source=client 但没有账号可归属"的一族,`(maixiang OR uid IN (成员集))` 那个形状照样会把它们抹掉 ⇒ Step 1 的用例要替它们说句话(放行还是接受消失,二选一写进附B,不许沉默)。
- [ ] **Step 1: 写失败的测试(这条测试的价值全在"麦象行不许消失")**
```java
@@ -2625,8 +2627,8 @@ git diff --name-only e42b37c1..<本批次构建的commit> -- backend-java/src/ma
- **建号**:超管切到第 2 家 tab 建一个账号 → 查库确认新账号 `company_id` 是**1**(超管自己那家),没跟着 tab 走 —— 这是设计(`AdminUserService.resolveTargetCompanyId`,spec §6.3)。
- **店铺**:⚠️ **这页的预期完全不同**。店铺的 `created_by_id` 来自请求体(Task 11 Step 4 那条更正),所以"新建店铺的归属跟着 tab 走吗"这个问题问错了。要验的是两件事:① 负责人选超管自己 ⇒ `created_by_id=超管`、这家账号所属公司为 1;② 负责人选 `users.id=1193` ⇒ 店铺**就归第 2 家**(今天已经能做,本轮没改它)。**别把 ② 报成"tab 生效了"**,那是负责人字段生效,与 tab 无关。
- 两条都要再验一次"切 tab 不改变上述任何一条"。测完删掉测试行(只交付命令,用户执行)。
5. **凭据读出口随 tab 收窄**(Task 11 Step 3(d) 的账,这条 `mvn test` 验不到):超管切到第 2 家 tab → 从 Network 里取一个**第 1 家**店铺的 id 直接请求 `GET /api/admin/shop-manages/<id>/credential` → **403**,不是 200 + 明文密码。反向再验一次:不切 tab(或切回第 1 家)同一请求必须 200,否则就是闸门写死成了"非当前 tab 全禁"。
6. **麦象日志不消失**(Task 12 的账):切任意公司 tab,日志管理里 `source=maixiang` 的行必须还在。
5. **凭据读出口按会话收窄**(Task 11 Step 3(d) 的账,这条 `mvn test` 验不到)。⚠️ **2026-10-05 执行时订正原预期**:原写「超管切到第 2 家 tab → 按 id 请求 ⇒ 403」,实现做出来是**另一件事**,而那一件才是 §6.1 要的。理由:`adminCredential` 若靠调用方自己带 `company_id` 才收窄,**不带参数的请求就绕过闸门**——而按 id 读明文密码的越权面,越权的人本来就不会替你把 tab 的公司 id 带上;那等于"只拦老实人"的装饰,落进 memory「护栏要做进代码出口」的反面。本仓已有的范形是 Task 8 的 `AdminImageVideoTaskController.detail/download-zip`:私有 `scopeOf(operator)` = `readScope(operator, null)` ⇒ **超管不筛(tab 不是安全边界,Constraint 2),非超管与内部令牌按其可见成员集收窄**。⇒ 这条验收改成两读:① 用一个**主管**账号(不是超管)从 Network 里取一个不属于它可见集的店铺 id 请求 `GET /api/admin/shop-manages/<id>/credential` → **403**,不是 200 + 明文密码;② 超管在**任意 tab** 下同一请求必须 **200**——若这里红了,说明闸门被写死成"非当前 tab 全禁",那是回归不是收紧。③ 顺手确认这条**没有**波及 `GET /credential?shopName=`(4.0.44 客户端与 Python 自动化走的那条,本轮刻意不动)。
6. **麦象日志不消失**(Task 12 的账):切任意公司 tab,日志管理里 `source=maixiang` 的行必须还在。⚠️ 生产只读实测(10-05,`device_log_file` 共 1028 行):`client` 831 / `maixiang` 197,**但 `client` 里有 22 行 `uid IS NULL`**(22/831=2.6%)——这 22 行按「`source='maixiang' OR uid IN (成员集)`」的形状仍会被筛掉,Task 12 要么给它一条同族的"无法归属"放行腿,要么在附B 里明写这 22 行在各 tab 下消失是设计。
7. **保存权限不炸**(Task 4 的账):给一个历史带 `admin_companies` 授权的账号保存一次权限 → 成功 + 日志 `GRANT_SUPER_ADMIN_ONLY_STRIPPED`。
8. **文案这三眼看**(§9.3 / §5 的账,`node --test` 只能验"字符串在不在",验不到"读的人怎么理解"):①超管在任意一页看到引导条那句"超级管理员可用页面上方的公司 tab 切换公司"时,tab 条**确实在它上方**(Task 7 Step 4 挂的是 `</el-breadcrumb>` 与 `<OperationGuide />` 之间,顺序反了这句话就指错了方向);②引导条被收起过的人看不见这句——找一个 `localStorage.shufuAdminGuideCollapsed='1'` 的浏览器确认这不是硬伤,并在运维手册里说明这句的位置;③非超管账号读同一句时不会去找那个他根本不会有的控件(这句以"超级管理员"开头就是为这一步,若真读着别扭,改法是加 `isSuperAdmin` 分支而不是改回祈使句)。
- [ ] **Step 4: 更新两份文档 + 清掉我自己留下的临时件**