feat(公司tab): 日志管理列表按 uid 成员集筛,麦象行走 OR 不被筛掉

生产只读取证(2026-10-05 15:1x,主机 A 业务库只读):device_log_file COUNT(*)=1028,
GROUP BY source = client 831 / maixiang 197 ⇒ 客户端占多数 ⇒ 这页留在批次 1、照声明
companyScoped(若麦象占多数,公司 tab 只会筛掉小半边,就该把这页摘出清单)。

22 行 source='client' 且 uid IS NULL 的匿名客户端日志的处置:选了公司后接受它们从
每一个 tab 里消失(条件定成 (source='maixiang' OR uid IN (成员集)),不加 uid IS NULL
那条腿)。理由是那 197 行麦象能进每一个 tab,是因为它是平台自己的采集机(基础设施),
而这 22 行只是「没登录的桌面端」——一家没有归属的行在每一家各冒充一份,既错归属也让
「这家有多少日志」这个数失去意义;tab 只是超管的视图过滤器(这页 9 个端点全在
requireSuperAdmin 之后,无非超管调用方),全量仍可由不带 company_id 的请求拿到
(readScope(operator, null) ⇒ unfiltered ⇒ memberUids=null ⇒ 一条条件都不叠)。
代价与定案写进 DeviceLogServiceTest 的 @DisplayName
「定案:那 22 行 source=client 且 uid IS NULL 的匿名客户端日志——选了公司就接受它们消失」。

接线口径:controller 收 @RequestParam(name = "company_id", required = false) 并在 handler
体内算 dataReadScope.readScope(...).userIdsOr(null) 当实参交给 service(G2 断言 C 认的形状);
条件加在 wrapperBuilder 闭包内部,selectCount 与 selectList 共用同一把尺子;空成员集退化
成 eq(source,'maixiang') 而不是不叠条件;content/download/delete/devices 与三个写端点刻意
不收 company_id,由两支 SourceScan 用例钉住。
This commit is contained in:
2026-10-05 17:20:57 +08:00
parent 66f9178557
commit c772a07fbe
6 changed files with 233 additions and 15 deletions
@@ -64,6 +64,8 @@ export interface DeviceLogQuery {
endDate?: string
page: number
pageSize: number
/** 超管选中的公司 tab;null/undefined=不发这个参数,后端按「不筛」出全量(非超管恒不发)。 */
companyId?: number | null
}
/** 分页查询日志文件列表:GET /api/admin/device-logs/files */
@@ -73,6 +75,9 @@ export async function fetchDeviceLogFiles(params: DeviceLogQuery): Promise<Devic
if (params.uid) query.uid = params.uid
if (params.startDate) query.startDate = params.startDate
if (params.endDate) query.endDate = params.endDate
// 公司值由页面组件(companyTab.requestCompanyId)传进来,本模块不读 Pinia store。
// query 是这里逐字段点名的白名单构造 ⇒ 右半边只许取原始 params。
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get('/api/admin/device-logs/files', { params: query })
return unwrap<DeviceLogPage>(data)
}
@@ -2,10 +2,11 @@
/** 日志管理页:桌面客户端 / 麦象采集机上报的日志浏览(仅超管)。
* 支持来源/用户/日期筛选,尾部内容查看(自动滚到底、可向前加载更早内容)、
* 完整下载、删除;「采集配置」可调全量/精选模式(全局默认 + 终端覆盖)。 */
import { computed, nextTick, onMounted, ref } from 'vue'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import OldPagination from '@/components/OldPagination.vue'
import { ElMessage } from 'element-plus'
import { formatDateTime, todayDateInput } from '@/utils/datetime'
import { useCompanyTabStore } from '@/stores/company-tab'
import { fetchHistoryUserOptions } from './history-api.ts'
import type { HistoryUserOption } from './history-user-option.ts'
import {
@@ -49,6 +50,8 @@ function formatBytes(bytes: number | null | undefined): string {
return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unitIndex]}`
}
const companyTab = useCompanyTabStore()
const loading = ref(false)
const rows = ref<DeviceLogFileRow[]>([])
const total = ref(0)
@@ -74,6 +77,7 @@ async function load() {
endDate: endDate.value || undefined,
page: page.value,
pageSize: pageSize.value,
companyId: companyTab.requestCompanyId,
})
rows.value = result?.items || []
total.value = Number(result?.total || 0)
@@ -85,6 +89,10 @@ async function load() {
}
}
// 切公司 = 重新取数(形状同店铺管理页):只有列表这一个取数口按公司收窄,
// 内容/下载/删除/终端下拉都不带 company_id,所以这里只需重跑 load()。
watch(() => companyTab.activeId, () => void load())
async function loadUserOptions() {
usersLoading.value = true
try {
@@ -67,7 +67,12 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
},
],
admin_device_logs: [
{ file: 'src/api/device-logs.ts', shape: null, note: 'Task 12 未接线(已在缺口清单里)' },
{
file: 'src/api/device-logs.ts',
// fetchDeviceLogFiles(params: DeviceLogQuery):唯一入参对象是 params,query 由本函数逐字段从零构造。
shape: /company_id\s*=\s*params\.companyId\b/,
note: 'query 是白名单构造(只点名 page/pageSize/source/uid/startDate/endDate),公司值只许取原始 params 的 companyId——取自任何中间/归一化对象都是 TS 绿、运行时恒 undefined',
},
],
admin_group_manage: [
{
@@ -4,6 +4,7 @@ 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.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.devicelog.model.entity.DeviceLogConfigEntity;
import com.nanri.aiimage.modules.devicelog.model.entity.DeviceLogFileEntity;
import com.nanri.aiimage.modules.devicelog.model.vo.DeviceLogContentVo;
@@ -48,11 +49,14 @@ public class AdminDeviceLogController {
private final DeviceLogService deviceLogService;
private final DeviceLogConfigService deviceLogConfigService;
private final AdminAuthSupport adminAuthSupport;
/** 公司 tab 的唯一读范围出口(spec §7):只有 {@link #files} 用它,理由见 {@link #requireSuperAdmin}。 */
private final DataReadScope dataReadScope;
@GetMapping("/files")
@Operation(summary = "日志文件分页列表",
description = "source=client/maixiang;uid 按上报用户精确过滤(未登录/采集机的行 uid 为空,不匹配任何 uid);"
+ "日期为闭区间(早于保留窗口自动收紧)。")
+ "日期为闭区间(早于保留窗口自动收紧);"
+ "company_id 只收窄到该公司成员的 uid,麦象采集机的行(uid 恒空)照常出现,不传=不筛。")
public ApiResponse<DeviceLogPageVo> files(
HttpServletRequest request,
@Parameter(description = "来源") @RequestParam(required = false) String source,
@@ -62,9 +66,14 @@ public class AdminDeviceLogController {
@Parameter(description = "结束日期(含)") @RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@RequestParam(defaultValue = "1") Long page,
@RequestParam(defaultValue = "20") Long pageSize) {
requireSuperAdmin(request);
return ApiResponse.success(deviceLogService.page(source, uid, startDate, endDate, page, pageSize));
@RequestParam(defaultValue = "20") Long pageSize,
@Parameter(description = "公司 ID(超管 tab;不传=不筛)")
@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireSuperAdmin(request);
// 只有列表按公司收窄:成员集为空 = 这家一个账号都没有,service 那侧退化成「只看麦象」。
List<Long> memberUids = dataReadScope.readScope(operator, companyId).userIdsOr(null);
return ApiResponse.success(
deviceLogService.page(source, uid, startDate, endDate, page, pageSize, memberUids));
}
@GetMapping("/content")
@@ -148,13 +157,18 @@ public class AdminDeviceLogController {
/**
* 日志可能含账号/代理等敏感信息,这里比常规后台更严:仅超管(requireAdmin 不含)。
*
* <p>返回操作者是为了让唯一的列表端点算公司成员集;其余端点按 fileId / 配置主键工作,
* 不收 company_id(这页没有超管之外的调用方,按 id 再判一次公司只会误伤 uid 为空的麦象日志)。
* 需要把范围补进按 id 的读出口时,照 {@code AdminImageVideoTaskController} 的 scopeOf 那一样写。</p>
*/
private void requireSuperAdmin(HttpServletRequest request) {
private AdminUserEntity requireSuperAdmin(HttpServletRequest request) {
AdminUserEntity user = adminAuthSupport.requireAdmin(request);
if (!"super_admin".equals(adminAuthSupport.currentRole(user))) {
log.warn("[device-log] 非超管访问日志管理被拒 userId={} username={}",
user.getId(), user.getUsername());
throw new BusinessException(403, "仅超级管理员可访问日志管理");
}
return user;
}
}
@@ -159,8 +159,15 @@ public class DeviceLogService {
// ---------------------------------------------------------------- 查询
/**
* 列表查询。
*
* @param memberUids 公司 tab 收窄到的成员账号集(由 {@code DataReadScope.readScope} 在 controller
* 里算好传进来,service 不自己判权限)。{@code null} = 不筛(超管没选公司,行为与
* 上线前逐字一致);非 null 的空集 = 这家一个成员都没有,只剩麦象采集机的基础设施日志。
*/
public DeviceLogPageVo page(String source, Long uid, LocalDate startDate, LocalDate endDate,
Long pageParam, Long pageSizeParam) {
Long pageParam, Long pageSizeParam, List<Long> memberUids) {
int retentionDays = properties.retentionDaysOrDefault();
LocalDate minDate = LocalDate.now().minusDays(retentionDays - 1L);
LocalDate from = startDate == null || startDate.isBefore(minDate) ? minDate : startDate;
@@ -176,6 +183,18 @@ public class DeviceLogService {
if (uid != null) {
qw.eq(DeviceLogFileEntity::getUid, uid);
}
// memberUids:超管选了公司才非 null。麦象上报的行 uid 恒为 NULL,
// 叠等值会把跟价机的日志从每个 tab 里抹掉(spec §9.2),所以它必须走 OR 那半边。
// 必须加在这个闭包里:selectCount 与 selectList 共用这一个 Function,加在外面任何一侧
// 都会得到"total 与行集不同宽 = 分页错位",而且不报错。
if (memberUids != null) {
if (memberUids.isEmpty()) {
qw.eq(DeviceLogFileEntity::getSource, "maixiang");
} else {
qw.and(w -> w.eq(DeviceLogFileEntity::getSource, "maixiang")
.or(o -> o.in(DeviceLogFileEntity::getUid, memberUids)));
}
}
qw.ge(DeviceLogFileEntity::getLogDate, from);
if (endDate != null) {
qw.le(DeviceLogFileEntity::getLogDate, endDate);
@@ -204,8 +223,9 @@ public class DeviceLogService {
vo.setPage(safePage);
vo.setPageSize(safeSize);
vo.setRetentionDays(retentionDays);
log.info("[device-log] 列表查询 source={} uid={} 起={} 止={} page={} size={} 命中={}",
source, uid, from, endDate, safePage, safeSize, total);
log.info("[device-log] 列表查询 source={} uid={} 起={} 止={} page={} size={} 成员集={} 命中={}",
source, uid, from, endDate, safePage, safeSize,
memberUids == null ? "不筛" : memberUids.size(), total);
return vo;
}
@@ -11,8 +11,10 @@ import com.nanri.aiimage.modules.devicelog.mapper.DeviceLogFileMapper;
import com.nanri.aiimage.modules.devicelog.model.entity.DeviceLogFileEntity;
import com.nanri.aiimage.modules.devicelog.model.vo.DeviceLogContentVo;
import com.nanri.aiimage.modules.devicelog.storage.DeviceLogStorageService;
import com.nanri.aiimage.testutil.SourceScan;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -191,9 +193,9 @@ class DeviceLogServiceTest {
/** 捕获 page() 传给 selectCount 的查询条件(计数与列表走同一条 wrapper 构造)。 */
@SuppressWarnings("rawtypes")
private AbstractWrapper capturePageWrapper(String source, Long uid) {
private AbstractWrapper capturePageWrapper(String source, Long uid, List<Long> memberUids) {
when(mapper.selectCount(any())).thenReturn(0L);
service().page(source, uid, null, null, 1L, 15L);
service().page(source, uid, null, null, 1L, 15L, memberUids);
ArgumentCaptor<Wrapper> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(mapper).selectCount(captor.capture());
return (AbstractWrapper) captor.getValue();
@@ -201,7 +203,7 @@ class DeviceLogServiceTest {
@Test
void pageFiltersByUidExactly() {
AbstractWrapper wrapper = capturePageWrapper(null, 7L);
AbstractWrapper wrapper = capturePageWrapper(null, 7L, null);
assertThat(wrapper.getSqlSegment()).contains("uid =");
assertThat(wrapper.getParamNameValuePairs().values()).contains(7L);
}
@@ -209,14 +211,178 @@ class DeviceLogServiceTest {
@Test
void pageWithoutUidKeepsAnonymousReportersVisible() {
// 未登录的桌面端与麦象采集机 uid 为空:不指定用户时它们必须仍在结果里
assertThat(capturePageWrapper(null, null).getSqlSegment()).doesNotContain("uid");
assertThat(capturePageWrapper(null, null, null).getSqlSegment()).doesNotContain("uid");
}
/** 契约:列表筛选已改为用户维度,设备名/设备ID/文件名的模糊匹配不再存在于查询路径。 */
@Test
void pageNoLongerMatchesDeviceOrFileNameFuzzily() {
String sql = capturePageWrapper("client", 7L).getSqlSegment();
String sql = capturePageWrapper("client", 7L, null).getSqlSegment();
assertThat(sql).contains("source =");
assertThat(sql).doesNotContain("device_name", "device_id", "file_name");
}
// ------------------------------------------------------ 公司 tab(Task 12)成员集筛选
/**
* 捕 selectCount 那支 wrapper。计数支**一定**被打到,列表支只在 total != 0 时才打
* (DeviceLogService 里那个三元),所以凡是要看条件的用例都从这一支取,
* 或者先把 selectCount 桩成 1L 再捕两支。
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private AbstractWrapper<?, ?, ?> capturedCount() {
ArgumentCaptor<Wrapper> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(mapper).selectCount(captor.capture());
return (AbstractWrapper<?, ?, ?>) captor.getValue();
}
/** 捕 selectList 那支(配套用例必须把 selectCount 桩成非 0,否则这一支压根不会被调用)。 */
@SuppressWarnings({"rawtypes", "unchecked"})
private AbstractWrapper<?, ?, ?> capturedList() {
ArgumentCaptor<Wrapper> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(mapper).selectList(captor.capture());
return (AbstractWrapper<?, ?, ?>) captor.getValue();
}
@Test
@DisplayName("选了公司:客户端行按成员集筛,麦象行照常出现(uid 恒 NULL,叠等值就整类消失)")
void maixiangRowsSurviveCompanyFilter() {
when(mapper.selectCount(any())).thenReturn(1L);
when(mapper.selectList(any())).thenReturn(List.of(row(1024L, 2)));
service().page(null, null, null, null, 1L, 20L, List.of(11L, 12L));
AbstractWrapper<?, ?, ?> q = capturedCount();
assertThat(q.getSqlSegment())
.as("必须是 (source = ? OR uid IN (...)) 一整组,括号丢了就等于把麦象筛掉")
.contains(" OR ").contains("IN (");
// 值落在 paramNameValuePairs 里,不在 getSqlSegment() 里——别写成 segment.contains("maixiang"),
// MP 渲染的是 #{ew.paramNameValuePairs.MPGENVAL1},那条断言恒假。
assertThat(q.getParamNameValuePairs().values()).contains("maixiang", 11L, 12L);
}
@Test
@DisplayName("成员集为空:退化成只看麦象,不许渲染 IN () 打炸 SQL")
void emptyMemberSetFallsBackToMaixiangOnly() {
when(mapper.selectCount(any())).thenReturn(0L);
service().page(null, null, null, null, 1L, 20L, List.of());
AbstractWrapper<?, ?, ?> q = capturedCount();
// 订正 brief:MP 3.5.x 的 paramNameValuePairs 是**惰性**填的——addCondition 把
// `() -> formatParam(null, val)` 塞进 ISqlSegment lambda,只有 segment 被求值过一次,
// pairs 里才落值。先读 pairs 会拿到空 map(实跑红过一次),所以结构断言在前。
String sql = q.getSqlSegment();
// 只用 contains/doesNotContain:page 里还有 log_date >= ? 那条必带参数,
// 写 containsExactly(...) 会因为多一个 LocalDate 而恒红。
assertThat(sql).as("空集不许渲染出 IN (),MySQL 直接语法错").doesNotContain("IN (");
assertThat(q.getParamNameValuePairs().values())
.as("空集走 in() 会渲染出 IN (),MySQL 直接语法错;这里必须只看 maixiang")
.contains("maixiang")
.doesNotContain(11L);
}
@Test
@DisplayName("null = 不筛,保持今天的行为(超管没选公司时与上线前逐字一致)")
void nullMemberSetKeepsOldBehaviour() {
when(mapper.selectCount(any())).thenReturn(0L);
service().page("client", 7L, null, null, 1L, 20L, null);
AbstractWrapper<?, ?, ?> q = capturedCount();
assertThat(q.getSqlSegment()).doesNotContain(" OR ");
assertThat(q.getParamNameValuePairs().values()).doesNotContain("maixiang");
assertThat(q.getParamNameValuePairs().values()).contains("client", 7L);
}
@Test
@DisplayName("计数支与列表支必须同宽:total 与行集不一致就是分页错位")
void countAndListShareTheSameCondition() {
when(mapper.selectCount(any())).thenReturn(1L);
when(mapper.selectList(any())).thenReturn(List.of(row(1024L, 2)));
service().page(null, null, null, null, 1L, 20L, List.of(11L));
AbstractWrapper<?, ?, ?> count = capturedCount();
AbstractWrapper<?, ?, ?> list = capturedList();
// 两支的 segment 必须先各求值一次:paramNameValuePairs 是惰性填的(见上一条用例的订正),
// 不读 segment 就比 pairs 会是「两个空 map 相等」那种恒真断言——钉不住任何东西。
String countSql = count.getSqlSegment();
String listSql = list.getSqlSegment();
assertThat(countSql).as("取样非空自检:条件真进了计数支").contains(" OR ").contains("IN (");
// 列表支 = 计数支条件 + 排序 + limit;排序与 limit 不新增条件段 ⇒ 前缀逐字相同。
assertThat(listSql).as("行集那支的条件段必须与计数支逐字一致").startsWith(countSql);
// 比 paramNameValuePairs 而不是 getSqlSegment():列表那支在 builder 外面又叠了
// orderByDesc(lastUploadAt)+orderByDesc(id)+last("limit o,s")(DeviceLogService.java:190-193),
// 两支的 segment 天生就不相等 ⇒ 断 isEqualTo(getSqlSegment()) 会红在排序上,而不是红在条件上。
// 条件同宽的正确锚点是"参数绑定序列逐字相同"——排序与 limit 不往 pairs 里塞值。
assertThat(list.getParamNameValuePairs())
.as("total 与行集按不同条件算出来的 = 页码跳空/重复行")
.isEqualTo(count.getParamNameValuePairs());
}
@Test
@DisplayName("成员集与公司 tab 之外的既有条件叠得起来:嵌套 and 不许把 MPGENVAL 键撞成同一个值")
void companyFilterStacksWithSourceFilterWithoutCollidingOnParamKeys() {
when(mapper.selectCount(any())).thenReturn(0L);
service().page("client", null, null, null, 1L, 20L, List.of(11L, 12L));
AbstractWrapper<?, ?, ?> q = capturedCount();
// 正向取样自检:外层 source 等值 + OR 分组 + 成员集 IN + 必带的 log_date 四条都在。
assertThat(q.getSqlSegment())
.contains("source =").contains(" OR ").contains("IN (").contains("log_date >=");
// 嵌套 wrapper 若复用父级的 MPGENVAL 序号,'client' 会被 'maixiang' 就地覆盖 ⇒ 筛出来
// 是「来源=maixiang」的行却写着 source=client,且不报错。四个值同时在 pairs 里才算各占各的键。
assertThat(q.getParamNameValuePairs().values()).contains("client", "maixiang", 11L, 12L);
}
@Test
@DisplayName("定案:那 22 行 source=client 且 uid IS NULL 的匿名客户端日志——选了公司就接受它们消失,不加 IS NULL 那条腿")
void anonymousClientRowsFallOutOfEveryCompanyTabByDecision() {
when(mapper.selectCount(any())).thenReturn(1L);
when(mapper.selectList(any())).thenReturn(List.of(row(1024L, 2)));
service().page(null, null, null, null, 1L, 20L, List.of(11L, 12L));
AbstractWrapper<?, ?, ?> q = capturedCount();
// 反向钉的配对自检(全局约束 15):这一支确实生成了 OR 分组与成员集,
// 下面的 doesNotContain 才是「定案不加第三条腿」的证据,而不是「什么都没生成所以看不见」。
assertThat(q.getSqlSegment()).contains(" OR ").contains("IN (");
assertThat(q.getParamNameValuePairs().values()).contains("maixiang", 11L, 12L);
// 定案(2026-10-05 生产只读实测:1028 行里 client 831 / maixiang 197,其中 uid IS NULL 的是
// client 22 + maixiang 197):条件写成 (source='maixiang' OR uid IN (成员集)),
// 于是那 22 行「有客户端来源、却没有账号可归属」的行在任何一个公司 tab 下都不出现。
// 取舍:另一条腿 (uid IS NULL) 会把它们塞进**每一家**的 tab——一家没归属的行不该在每家各冒充一份,
// 那既是错的归属、也会让「这家有多少日志」这个数没法用;而 tab 只是超管的视图过滤器
// (这页 9 个端点全在 requireSuperAdmin 之后),全量仍可由不带 company_id 的请求拿到
// (readScope(operator, null) ⇒ unfiltered ⇒ memberUids=null ⇒ 一条条件都不叠)。
assertThat(q.getSqlSegment()).doesNotContain("IS NULL");
}
@Test
@DisplayName("按 fileId 的端点与 devices 刻意不收 company_id:这页无超管外调用方,收了只会误伤麦象日志")
void singleFileEndpointsStayUnscoped() {
String text = SourceScan.sourceText("AdminDeviceLogController.java");
assertThat(SourceScan.methodBody(text, "content")).doesNotContain("dataReadScope");
assertThat(SourceScan.methodBody(text, "download")).doesNotContain("dataReadScope");
assertThat(SourceScan.methodBody(text, "delete")).doesNotContain("dataReadScope");
assertThat(SourceScan.methodBody(text, "devices")).doesNotContain("dataReadScope");
assertThat(SourceScan.methodBody(text, "files")).contains("dataReadScope"); // 取样非空自检
}
@Test
@DisplayName("写端点与配置端点也不收 company_id:归属不从界面注入(spec §6.2)")
void configWriteEndpointsCarryNoCompanyId() {
String text = SourceScan.sourceText("AdminDeviceLogController.java");
for (String writer : List.of("updateGlobal", "updateDevice", "deleteOverride", "delete")) {
assertThat(SourceScan.methodBody(text, writer))
.as("写入口「" + writer + "」一旦出现公司参数,就等于把公司维度端回界面(未批)")
.doesNotContain("company_id")
.doesNotContain("companyId");
}
// 反向钉的配对自检:唯一的读端点确实收了 company_id,切块与判据都不是空跑。
assertThat(SourceScan.methodBody(text, "files")).contains("company_id").contains("companyId");
}
}