Przeglądaj źródła

数据权限逻辑统一处理

zengy 3 tygodni temu
rodzic
commit
ef2efd635d
20 zmienionych plików z 449 dodań i 112 usunięć
  1. 29 7
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/AssignmentCandidateMapperTest.java
  2. 7 6
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/WarningParticipantServiceTest.java
  3. 43 8
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/WarningScopeMapperTest.java
  4. 45 0
      pipe-network-service/zksy-common/src/main/java/com/zksy/common/utils/AccessContext.java
  5. 37 0
      pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/aspectj/AdminDataScopeAspect.java
  6. 13 4
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmReviewScopeService.java
  7. 2 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentBaseServiceImpl.java
  8. 116 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/support/CompanyEquipmentScope.java
  9. 19 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/dto/WarningAccessScope.java
  10. 7 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/mapper/WarningParticipantMapper.java
  11. 6 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/service/WarningAccessService.java
  12. 6 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/service/WarningParticipantService.java
  13. 11 2
      pipe-network-service/zksy-system/src/main/java/com/zksy/ops/service/impl/WorkOrderServiceImpl.java
  14. 17 66
      pipe-network-service/zksy-system/src/main/java/com/zksy/ops/support/OpsAssignScopeSupport.java
  15. 1 0
      pipe-network-service/zksy-system/src/main/resources/mapper/base/AlarmOperationsMapper.xml
  16. 6 0
      pipe-network-service/zksy-system/src/main/resources/mapper/warning/EarlyWarningMapper.xml
  17. 13 6
      pipe-network-service/zksy-system/src/main/resources/mapper/warning/WarningParticipantMapper.xml
  18. 35 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/mapper/MobileAlarmMapperTest.java
  19. 7 3
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmMobileServiceTest.java
  20. 29 7
      pipe-network-service/zksy-system/src/test/java/com/zksy/ops/support/CompanyEquipmentScopeTest.java

+ 29 - 7
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/AssignmentCandidateMapperTest.java

@@ -1,5 +1,6 @@
 package com.zksy.web.controller.warning;
 
+import com.zksy.base.support.CompanyEquipmentScope;
 import com.zksy.common.core.domain.entity.SysUser;
 import com.zksy.common.core.domain.entity.SysDept;
 import com.zksy.common.core.domain.entity.SysRole;
@@ -46,20 +47,41 @@ class AssignmentCandidateMapperTest {
         }
     }
 
-    @Test void warningSharedTypeBypassesDepartmentButOtherTypesKeepCompanyMatch() throws Exception {
+    private BoundSql warningCandidates(List<CompanyEquipmentScope.CompanyRule> rules) throws Exception {
         Map<String, Object> params = new HashMap<>();
         params.put("warningId", "w1"); params.put("deptId", null); params.put("keyword", null);
-        String sql = statement("mapper/warning/WarningParticipantMapper.xml",
-                "com.zksy.base.warning.mapper.WarningParticipantMapper.selectCandidates", params)
-                .getSql().replaceAll("\\s+", " ");
+        params.put("companyRules", rules);
+        return statement("mapper/warning/WarningParticipantMapper.xml",
+                "com.zksy.base.warning.mapper.WarningParticipantMapper.selectCandidates", params);
+    }
+
+    @Test void sharedManholeBelongsOnlyToDrainageCompanyAndOtherTypesKeepOwnDepartment() throws Exception {
+        BoundSql bound = warningCandidates(CompanyEquipmentScope.companyRules());
+        String sql = bound.getSql().replaceAll("\\s+", " ");
         assertTrue(sql.contains("LEFT JOIN app_user.sys_dept"));
         assertTrue(sql.contains("LEFT JOIN app_user.sys_dept parent_dept"));
         assertTrue(sql.contains("CONCAT(parent_dept.dept_name, '.', d.dept_name)"));
         assertTrue(sql.contains("d.parent_id <> 100"));
-        assertTrue(sql.contains("et.parent_id = 4 OR (d.status = '0' AND d.del_flag = '0' AND ("));
-        for (int parent = 1; parent <= 3; parent++)
-            assertTrue(sql.contains("et.parent_id = " + parent + " AND (d.dept_id = " + (100 + parent)));
         assertFalse(sql.substring(0, sql.indexOf("AND EXISTS")).contains("d.status"));
         assertTrue(sql.contains("eb.equipment_code = w.device_code"));
+        // 共享大类 4 不再无条件绕过部门限制
+        assertFalse(sql.contains("et.parent_id = 4 OR"));
+        assertTrue(sql.contains("d.status = '0' AND d.del_flag = '0' AND ("));
+
+        // 规则里 4 只绑定 102,且 101/103 各绑定自己的大类
+        List<CompanyEquipmentScope.CompanyRule> rules = CompanyEquipmentScope.companyRules();
+        assertEquals(4, rules.size());
+        assertEquals(Set.of(1, 2, 3, 4), rules.stream().map(CompanyEquipmentScope.CompanyRule::getRootTypeId).collect(java.util.stream.Collectors.toSet()));
+        assertEquals(101L, rules.stream().filter(r -> r.getRootTypeId() == 1).findFirst().orElseThrow().getCompanyDeptId());
+        assertEquals(102L, rules.stream().filter(r -> r.getRootTypeId() == 2).findFirst().orElseThrow().getCompanyDeptId());
+        assertEquals(103L, rules.stream().filter(r -> r.getRootTypeId() == 3).findFirst().orElseThrow().getCompanyDeptId());
+        assertEquals(102L, rules.stream().filter(r -> r.getRootTypeId() == 4).findFirst().orElseThrow().getCompanyDeptId());
+    }
+
+    @Test void unrestrictedCandidateQuerySkipsDepartmentRestriction() throws Exception {
+        String sql = warningCandidates(null).getSql().replaceAll("\\s+", " ");
+        assertFalse(sql.contains("d.status = '0'"));
+        assertFalse(sql.contains("et.parent_id"));
+        assertTrue(sql.contains("eb.equipment_code = w.device_code"));
     }
 }

+ 7 - 6
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/WarningParticipantServiceTest.java

@@ -33,7 +33,7 @@ class WarningParticipantServiceTest {
     }
 
     @Test void rolesUseSeparatePermissionsAndSupportWildcard() {
-        when(mapper.selectCandidates("w1", null, null)).thenReturn(Arrays.asList(person(2), person(3), person(4), person(5)));
+        when(mapper.selectCandidates(eq("w1"), isNull(), isNull(), any())).thenReturn(Arrays.asList(person(2), person(3), person(4), person(5)));
         when(menus.selectMenuPermsByUserId(2L)).thenReturn(Set.of("warning:warning:handle"));
         when(menus.selectMenuPermsByUserId(3L)).thenReturn(Set.of("warning:warning:audit"));
         when(menus.selectMenuPermsByUserId(4L)).thenReturn(Set.of("warning:warning:*"));
@@ -45,7 +45,7 @@ class WarningParticipantServiceTest {
 
     @Test void filterPermissionsBeforePaginationSoEligibleUsersAreNotLost() {
         List<WarningParticipant> users = LongStream.rangeClosed(2, 131).mapToObj(this::person).collect(Collectors.toList());
-        when(mapper.selectCandidates("w1", null, null)).thenReturn(users);
+        when(mapper.selectCandidates(eq("w1"), isNull(), isNull(), any())).thenReturn(users);
         for (WarningParticipant user : users) when(menus.selectMenuPermsByUserId(user.getUserId()))
                 .thenReturn(user.getUserId() % 2 == 0 ? Set.of("warning:warning:audit") : Set.of("warning:warning:handle"));
         var page = service.users("w1", "reviewer", 2, 20, null, null);
@@ -55,22 +55,23 @@ class WarningParticipantServiceTest {
     }
 
     @Test void publishRechecksPermissionsAfterUserWasSelected() {
-        when(mapper.selectCandidates("w1", null, "user3")).thenReturn(List.of(person(3)));
+        when(mapper.selectCandidates(eq("w1"), isNull(), eq("user3"), any())).thenReturn(List.of(person(3)));
         when(menus.selectMenuPermsByUserId(3L)).thenReturn(Set.of("warning:warning:audit"), Collections.emptySet());
         assertDoesNotThrow(() -> service.requireCandidate("w1", "reviewer", "user3"));
         assertThrows(ServiceException.class, () -> service.requireCandidate("w1", "reviewer", "user3"));
     }
 
     @Test void usersOutsideDeviceCompanyCannotBeAssignedEvenWhenTheyHavePermission() {
-        when(mapper.selectCandidates("w1", null, "user3")).thenReturn(Collections.emptyList());
+        when(mapper.selectCandidates(eq("w1"), isNull(), eq("user3"), any())).thenReturn(Collections.emptyList());
         assertThrows(ServiceException.class, () -> service.requireCandidate("w1", "reviewer", "user3"));
         verifyNoInteractions(menus);
     }
 
-    @Test void sharedDeviceCandidateNeedsPermissionButDoesNotNeedDepartment() {
+    /** 部门约束在 SQL 层(共享大类 4 只归 102),Service 层只负责权限过滤。 */
+    @Test void candidateStillNeedsPermissionRegardlessOfDepartment() {
         WarningParticipant candidate = person(3);
         candidate.setDeptId(null);
-        when(mapper.selectCandidates("shared", null, "user3")).thenReturn(List.of(candidate));
+        when(mapper.selectCandidates(eq("shared"), isNull(), eq("user3"), any())).thenReturn(List.of(candidate));
         when(menus.selectMenuPermsByUserId(3L)).thenReturn(Set.of("warning:warning:audit"));
         assertDoesNotThrow(() -> service.requireCandidate("shared", "reviewer", "user3"));
         assertThrows(ServiceException.class, () -> service.requireCandidate("shared", "handler", "user3"));

+ 43 - 8
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/warning/WarningScopeMapperTest.java

@@ -24,7 +24,7 @@ class WarningScopeMapperTest {
             new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
         }
         Map<String, Object> params = new HashMap<>(extra);
-        params.put("scope", new WarningAccessScope("current", true, true, true, parentTypes));
+        params.put("scope", WarningAccessScope.restricted("current", true, true, true, parentTypes));
         params.putIfAbsent("q", Collections.emptyMap());
         params.putIfAbsent("releaseOrder", false);
         params.putIfAbsent("pendingOnly", false);
@@ -47,18 +47,53 @@ class WarningScopeMapperTest {
         }
     }
 
-    @Test void missingCompanyOnlyAllowsExplicitSharedDeviceAssignees() throws Exception {
+    @Test void missingCompanyFailsClosedWithoutSharedDeviceException() throws Exception {
         for (String query : List.of("selectMobileWarnings", "countVisibleWarning", "countCompanyDevice")) {
             String sql = sql(statement(query, Collections.emptySet(), Collections.emptyMap()));
-            if (query.equals("countCompanyDevice")) assertTrue(sql.contains("AND 1 = 0"));
-            else {
-                assertTrue(sql.contains("1 = 0 OR (et.parent_id = 4 AND (w.handler = ? OR w.reviewer = ?))"));
-                assertTrue(sql.contains("eb.equipment_code = w.device_code"));
-            }
-            assertFalse(sql.contains("IN ( )"));
+            assertTrue(sql.contains("1 = 0"), query);
+            assertFalse(sql.contains("et.parent_id = 4"), query);
+            assertFalse(sql.contains("IN ( )"), query);
         }
     }
 
+    @Test void drainageCompanyKeepsSharedDeviceAssigneeException() throws Exception {
+        String sql = sql(statement("selectMobileWarnings", Set.of(2, 4), Collections.emptyMap()));
+        assertTrue(sql.contains("OR (et.parent_id = 4 AND (w.handler = ? OR w.reviewer = ?))"));
+        assertTrue(sql.contains("et.parent_id IN"));
+    }
+
+    @Test void waterAndGasCompaniesHaveNoSharedDeviceException() throws Exception {
+        for (Set<Integer> types : List.of(Set.of(1), Set.of(3))) {
+            String sql = sql(statement("selectMobileWarnings", types, Collections.emptyMap()));
+            assertFalse(sql.contains("et.parent_id = 4 AND"), String.valueOf(types));
+        }
+    }
+
+    @Test void unrestrictedScopeSkipsAllVisibilityFilters() throws Exception {
+        Configuration configuration = new Configuration();
+        String resource = "mapper/warning/EarlyWarningMapper.xml";
+        try (InputStream input = Resources.getResourceAsStream(resource)) {
+            new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
+        }
+        for (String query : List.of("selectWarningList", "searchWarnings", "selectMobileWarnings", "selectMyTasks",
+                "countVisibleWarning", "selectProcessingWarnings", "selectCompletedWarnings", "selectVisibleArchives")) {
+            Map<String, Object> params = new HashMap<>();
+            params.put("scope", WarningAccessScope.unrestricted("admin"));
+            params.putIfAbsent("q", Collections.emptyMap());
+            params.putIfAbsent("releaseOrder", false);
+            params.putIfAbsent("pendingOnly", false);
+            String text = sql(configuration.getMappedStatement(NS + query).getBoundSql(params));
+            assertFalse(text.contains("eb.equipment_code = w.device_code"), query);
+            assertFalse(text.contains("et.parent_id IN"), query);
+        }
+        Map<String, Object> deviceParams = new HashMap<>();
+        deviceParams.put("scope", WarningAccessScope.unrestricted("admin"));
+        deviceParams.put("deviceCode", "any");
+        String deviceSql = sql(configuration.getMappedStatement(NS + "countCompanyDevice").getBoundSql(deviceParams));
+        assertFalse(deviceSql.contains("1 = 0"));
+        assertFalse(deviceSql.contains("et.parent_id IN"));
+    }
+
     @Test void pcAndMobileTodoUseSameAssigneePermissionStateRulesWithoutRequiringTodoRows() throws Exception {
         String pc = sql(statement("selectMyTasks", Set.of(2, 4), Map.of("q", Map.of("todoType", "TODO"))));
         String mobile = sql(statement("selectMobileWarnings", Set.of(2, 4), Map.of("pendingOnly", true)));

+ 45 - 0
pipe-network-service/zksy-common/src/main/java/com/zksy/common/utils/AccessContext.java

@@ -0,0 +1,45 @@
+package com.zksy.common.utils;
+
+/**
+ * 数据范围统一入口:超级管理员看全部数据。
+ *
+ * <p>判据始终与 {@code SysUser.isAdmin()} /
+ * {@code SecurityUtils.isAdmin(Long)} 一致,即 {@code userId == 1L}。
+ * HTTP 请求由框架的 {@code AdminDataScopeAspect} 在入口一次性打标;非 HTTP 调用
+ * (定时任务、内部服务、单元测试)自动回退到 Spring Security 上下文判定,
+ * 保证所有调用链口径一致。</p>
+ *
+ * <p>业务侧只需读取 {@link #isUnrestricted()},不再散落 {@code if (isAdmin)} 判断。</p>
+ */
+public final class AccessContext {
+
+    private static final ThreadLocal<Boolean> UNRESTRICTED = new ThreadLocal<>();
+
+    private AccessContext() {
+    }
+
+    /** 当前登录用户是否为超级管理员(唯一判据 userId == 1L)。 */
+    public static boolean isAdmin() {
+        try {
+            return SecurityUtils.isAdmin(SecurityUtils.getUserId());
+        } catch (Exception ignored) {
+            return false;
+        }
+    }
+
+    /** 当前调用链是否不受数据范围限制(超级管理员看全部数据)。 */
+    public static boolean isUnrestricted() {
+        Boolean marked = UNRESTRICTED.get();
+        return marked != null ? marked : isAdmin();
+    }
+
+    /** 由切面在请求入口标记,业务代码不要调用。 */
+    public static void markUnrestricted() {
+        UNRESTRICTED.set(Boolean.TRUE);
+    }
+
+    /** 由切面在请求出口清理,避免线程复用污染数据范围。 */
+    public static void clear() {
+        UNRESTRICTED.remove();
+    }
+}

+ 37 - 0
pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/aspectj/AdminDataScopeAspect.java

@@ -0,0 +1,37 @@
+package com.zksy.framework.aspectj;
+
+import com.zksy.common.utils.AccessContext;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+/**
+ * 集中声明「超级管理员看全部数据」的切片。
+ *
+ * <p>在请求进入 Controller 时判定一次超管并打标,各业务的数据范围构造点统一读取
+ * {@link AccessContext#isUnrestricted()} 自行短路,避免在每个 Service 里重复写
+ * {@code if (isAdmin) return ...}。后续若要放宽到其它角色/范围,只需改这一处。</p>
+ *
+ * <p>{@code finally} 必须清理 ThreadLocal,防止线程池复用导致范围放大。</p>
+ */
+@Aspect
+@Component
+@Order(Ordered.HIGHEST_PRECEDENCE)
+public class AdminDataScopeAspect {
+
+    @Around("execution(* com.zksy..controller..*.*(..))")
+    public Object markAdminScope(ProceedingJoinPoint point) throws Throwable {
+        if (!AccessContext.isAdmin()) {
+            return point.proceed();
+        }
+        AccessContext.markUnrestricted();
+        try {
+            return point.proceed();
+        } finally {
+            AccessContext.clear();
+        }
+    }
+}

+ 13 - 4
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmReviewScopeService.java

@@ -9,6 +9,7 @@ import com.zksy.base.enums.EquipmentTypeEnum;
 import com.zksy.base.mapper.EquipmentTypeMapper;
 import com.zksy.common.core.domain.entity.SysMenu;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.common.utils.SecurityUtils;
 import com.zksy.system.service.ISysMenuService;
 import com.zksy.ops.support.OpsAssignScopeSupport;
@@ -26,16 +27,24 @@ public class AlarmReviewScopeService {
     private final ISysMenuService menuService;
     private final OpsAssignScopeSupport companyScope;
 
-    /** 移动端匹配用户所属公司的设备类型直接子级,并包含所有共享窨井设备类型(父类 4)。 */
+    /**
+     * 移动端按公司设备大类取直接子级。
+     * 大类范围(含「仅 102 可见共享窨井 4」及「超管看全部」)统一由
+     * {@link com.zksy.base.support.CompanyEquipmentScope} 决定。
+     */
     public List<Integer> resolveMobile(MobileAlarmQuery query) {
+        if (AccessContext.isUnrestricted() && query.getRootTypeId() == null) {
+            return typeMapper.selectList(null).stream()
+                    .map(EquipmentType::getId).filter(Objects::nonNull)
+                    .distinct().collect(Collectors.toList());
+        }
         Set<Integer> roots = companyScope.currentCompanyEquipmentRootTypeIds();
         if (query.getRootTypeId() != null) {
             if (!roots.contains(query.getRootTypeId())) throw new ServiceException("无权访问该公司的故障数据");
             roots = Collections.singleton(query.getRootTypeId());
         }
         if (roots.isEmpty()) return Collections.emptyList();
-        final Set<Integer> allowed = new LinkedHashSet<>(roots);
-        allowed.add(4);
+        final Set<Integer> allowed = roots;
         return typeMapper.selectList(null).stream()
                 .filter(type -> allowed.contains(type.getParentId()) && type.getId() != null)
                 .map(EquipmentType::getId).distinct().collect(Collectors.toList());
@@ -58,7 +67,7 @@ public class AlarmReviewScopeService {
         Integer rootTypeId = query.getRootTypeId();
         EquipmentTypeEnum root = rootTypeId == null ? null : EquipmentTypeEnum.getById(rootTypeId);
         if (rootTypeId != null && (root == null || !root.isRoot())) throw new ServiceException("无效的设备大类");
-        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
+        if (!AccessContext.isUnrestricted()) {
             boolean allowed = menuService.selectMenuList(SecurityUtils.getUserId()).stream()
                     .anyMatch(menu -> matches(menu, query, components));
             if (!allowed) throw new AccessDeniedException("无权访问当前子系统的报警数据");

+ 2 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentBaseServiceImpl.java

@@ -25,6 +25,7 @@ import com.zksy.base.manhole.mapper.ManholeDataMapper;
 import com.zksy.base.mapper.*;
 import com.zksy.base.service.EquipmentBaseService;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.manhole.dto.in.EquipmentCountByTypeInDTO;
 import com.zksy.manhole.dto.in.EquipmentExportInDTO;
 import com.zksy.manhole.dto.in.ManholeDevicePageInDTO;
@@ -236,6 +237,7 @@ public class EquipmentBaseServiceImpl extends ServiceImpl<EquipmentBaseMapper, E
     }
 
     private boolean isTypeInAuthorizedRoots(EquipmentType type, Set<Integer> authorizedRoots) {
+        if (AccessContext.isUnrestricted()) return true;
         return type != null && authorizedRoots != null && authorizedRoots.contains(type.getParentId());
     }
 

+ 116 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/support/CompanyEquipmentScope.java

@@ -0,0 +1,116 @@
+package com.zksy.base.support;
+
+import com.zksy.common.utils.AccessContext;
+import lombok.Value;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 公司部门与设备大类的统一映射,供移动端报警、设备台账、工单、预警的数据范围共用。
+ *
+ * <p>规则:部门 101 供水 → 大类 1,102 排水 → 大类 2,103 燃气 → 大类 3;
+ * 共享窨井大类 4 只归属排水公司(102),101 / 103 只能看各自公司的大类。
+ * 超级管理员使用 {@link #all()} 取得全部大类。</p>
+ *
+ * <p>此前「任意公司都追加 4」的逻辑分散在 {@code OpsAssignScopeSupport} 与
+ * {@code AlarmReviewScopeService} 两处,现统一收敛到本类。</p>
+ */
+public final class CompanyEquipmentScope {
+
+    public static final long DEPT_WATER_SUPPLY = 101L;
+    public static final long DEPT_DRAINAGE = 102L;
+    public static final long DEPT_GAS = 103L;
+
+    public static final int ROOT_WATER_SUPPLY = 1;
+    public static final int ROOT_DRAINAGE = 2;
+    public static final int ROOT_GAS = 3;
+    public static final int ROOT_SHARED_MANHOLE = 4;
+
+    /** 共享窨井大类仅对排水公司开放。 */
+    public static final long SHARED_MANHOLE_DEPT_ID = DEPT_DRAINAGE;
+
+    private static final Map<Long, Integer> COMPANY_ROOT_TYPE = new LinkedHashMap<>();
+    private static final Set<Integer> ALL_ROOT_TYPE_IDS;
+    private static final List<CompanyRule> COMPANY_RULES;
+
+    static {
+        COMPANY_ROOT_TYPE.put(DEPT_WATER_SUPPLY, ROOT_WATER_SUPPLY);
+        COMPANY_ROOT_TYPE.put(DEPT_DRAINAGE, ROOT_DRAINAGE);
+        COMPANY_ROOT_TYPE.put(DEPT_GAS, ROOT_GAS);
+        Set<Integer> all = new LinkedHashSet<>(COMPANY_ROOT_TYPE.values());
+        all.add(ROOT_SHARED_MANHOLE);
+        ALL_ROOT_TYPE_IDS = Collections.unmodifiableSet(all);
+        COMPANY_RULES = Collections.unmodifiableList(Arrays.asList(
+                new CompanyRule(ROOT_WATER_SUPPLY, DEPT_WATER_SUPPLY),
+                new CompanyRule(ROOT_DRAINAGE, DEPT_DRAINAGE),
+                new CompanyRule(ROOT_GAS, DEPT_GAS),
+                // 共享窨井只归排水公司,101 / 103 不再无条件放行人选
+                new CompanyRule(ROOT_SHARED_MANHOLE, SHARED_MANHOLE_DEPT_ID)));
+    }
+
+    /** 设备大类 → 归属公司部门,供候选人等 SQL 直接遍历,避免 XML 硬编码部门号。 */
+    @Value
+    public static class CompanyRule {
+        Integer rootTypeId;
+        Long companyDeptId;
+    }
+
+    public static List<CompanyRule> companyRules() {
+        return COMPANY_RULES;
+    }
+
+    private CompanyEquipmentScope() {
+    }
+
+    /**
+     * 部门路径(部门自身 + ancestors)→ 可见设备大类。
+     * 只有路径包含 102 时才追加共享窨井大类 4;101 / 103 只返回各自大类。
+     */
+    public static Set<Integer> resolve(Set<Long> deptPathIds) {
+        if (deptPathIds == null || deptPathIds.isEmpty()) {
+            return Collections.emptySet();
+        }
+        Set<Integer> roots = new LinkedHashSet<>();
+        COMPANY_ROOT_TYPE.forEach((deptId, rootTypeId) -> {
+            if (deptPathIds.contains(deptId)) {
+                roots.add(rootTypeId);
+            }
+        });
+        if (deptPathIds.contains(SHARED_MANHOLE_DEPT_ID)) {
+            roots.add(ROOT_SHARED_MANHOLE);
+        }
+        return roots;
+    }
+
+    /** 超级管理员可见的全部设备大类(1/2/3 + 共享 4)。 */
+    public static Set<Integer> all() {
+        return ALL_ROOT_TYPE_IDS;
+    }
+
+    /**
+     * 当前调用链的可见设备大类:超管看全部,其余按部门路径解析。
+     * 所有移动端/预警数据范围入口统一调用此方法。
+     */
+    public static Set<Integer> current(Set<Long> deptPathIds) {
+        return AccessContext.isUnrestricted() ? all() : resolve(deptPathIds);
+    }
+
+    /** 设备大类反推归属公司部门 ID;共享窨井 4 归 102,未知大类返回 null。 */
+    public static Long companyDeptId(int rootTypeId) {
+        return COMPANY_RULES.stream()
+                .filter(rule -> rule.getRootTypeId() == rootTypeId)
+                .map(CompanyRule::getCompanyDeptId)
+                .findFirst()
+                .orElse(null);
+    }
+
+    public static boolean isSharedManhole(Integer rootTypeId) {
+        return rootTypeId != null && rootTypeId == ROOT_SHARED_MANHOLE;
+    }
+}

+ 19 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/dto/WarningAccessScope.java

@@ -1,6 +1,8 @@
 package com.zksy.base.warning.dto;
 
+import com.zksy.base.support.CompanyEquipmentScope;
 import lombok.Value;
+
 import java.util.Set;
 
 /** 两端共用的预警可见范围,只由登录上下文构造。 */
@@ -11,4 +13,21 @@ public class WarningAccessScope {
     boolean canHandle;
     boolean canAudit;
     Set<Integer> parentTypeIds;
+    /** 超级管理员:看全部数据,跳过所有可见性过滤。 */
+    boolean all;
+
+    public static WarningAccessScope restricted(String username, boolean canPublish, boolean canHandle,
+                                                boolean canAudit, Set<Integer> parentTypeIds) {
+        return new WarningAccessScope(username, canPublish, canHandle, canAudit, parentTypeIds, false);
+    }
+
+    /** 超级管理员:看全部数据。 */
+    public static WarningAccessScope unrestricted(String username) {
+        return new WarningAccessScope(username, true, true, true, CompanyEquipmentScope.all(), true);
+    }
+
+    /** 共享窨井例外是否生效:仅排水公司(含大类 4)或超管可见。 */
+    public boolean isSharedManholeVisible() {
+        return parentTypeIds != null && parentTypeIds.contains(CompanyEquipmentScope.ROOT_SHARED_MANHOLE);
+    }
 }

+ 7 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/mapper/WarningParticipantMapper.java

@@ -1,12 +1,18 @@
 package com.zksy.base.warning.mapper;
 
+import com.zksy.base.support.CompanyEquipmentScope;
 import com.zksy.base.warning.domain.WarningParticipant;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
+
 import java.util.List;
 
 @Mapper
 public interface WarningParticipantMapper {
+    /**
+     * @param companyRules 设备大类→归属公司部门规则;传 null 表示不做部门限制(超管看全部)。
+     */
     List<WarningParticipant> selectCandidates(@Param("warningId") String warningId,
-            @Param("deptId") Long deptId, @Param("keyword") String keyword);
+            @Param("deptId") Long deptId, @Param("keyword") String keyword,
+            @Param("companyRules") List<CompanyEquipmentScope.CompanyRule> companyRules);
 }

+ 6 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/service/WarningAccessService.java

@@ -3,6 +3,7 @@ package com.zksy.base.warning.service;
 import com.zksy.base.warning.dto.WarningAccessScope;
 import com.zksy.base.warning.mapper.EarlyWarningMapper;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.common.utils.SecurityUtils;
 import com.zksy.ops.support.OpsAssignScopeSupport;
 import lombok.RequiredArgsConstructor;
@@ -15,7 +16,11 @@ public class WarningAccessService {
     private final OpsAssignScopeSupport companyScope;
 
     public WarningAccessScope current() {
-        return new WarningAccessScope(SecurityUtils.getUsername(),
+        String username = SecurityUtils.getUsername();
+        if (AccessContext.isUnrestricted()) {
+            return WarningAccessScope.unrestricted(username);
+        }
+        return WarningAccessScope.restricted(username,
                 SecurityUtils.hasPermi("warning:warning:publish"),
                 SecurityUtils.hasPermi("warning:warning:handle"),
                 SecurityUtils.hasPermi("warning:warning:audit"),

+ 6 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/base/warning/service/WarningParticipantService.java

@@ -2,11 +2,13 @@ package com.zksy.base.warning.service;
 
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.zksy.base.support.CompanyEquipmentScope;
 import com.zksy.base.warning.domain.WarningParticipant;
 import com.zksy.base.warning.mapper.WarningParticipantMapper;
 import com.zksy.common.core.domain.TreeSelect;
 import com.zksy.common.core.domain.entity.SysDept;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.system.mapper.SysDeptMapper;
 import com.zksy.system.service.ISysDeptService;
 import com.zksy.system.service.ISysMenuService;
@@ -72,8 +74,11 @@ public class WarningParticipantService {
             keyword = keyword.trim();
             if (keyword.length() > 100) throw new ServiceException("搜索关键字不能超过100个字符");
         }
+        // 超管看全部数据,普通用户按设备大类归属公司部门;规则由 CompanyEquipmentScope 统一提供。
+        List<CompanyEquipmentScope.CompanyRule> rules = AccessContext.isUnrestricted()
+                ? null : CompanyEquipmentScope.companyRules();
         // 按实际权限(含通配权限)过滤后分页,避免页内过滤漏人;不走用户管理 @DataScope。
-        return participantMapper.selectCandidates(warningId, deptId, keyword).stream()
+        return participantMapper.selectCandidates(warningId, deptId, keyword, rules).stream()
                 .filter(user -> hasPermission(user.getUserId(), permission)).collect(Collectors.toList());
     }
 

+ 11 - 2
pipe-network-service/zksy-system/src/main/java/com/zksy/ops/service/impl/WorkOrderServiceImpl.java

@@ -9,6 +9,8 @@ import com.zksy.base.domain.EquipmentType;
 import com.zksy.base.domain.HazardHiddenAccount;
 import com.zksy.base.alarm.domain.AlarmData;
 import com.zksy.base.alarm.service.AlarmDataService;
+import com.zksy.base.support.CompanyEquipmentScope;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.ops.domain.WorkOrder;
 import com.zksy.ops.domain.WorkOrderLog;
 import com.zksy.ops.domain.vo.WorkOrderLogVO;
@@ -811,6 +813,9 @@ public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder
      * 工单进入派单后,统一按创建人、责任人、核验人控制可见范围。</p>
      */
     private void applyMobileScope(LambdaQueryWrapper<WorkOrder> wrapper, Long userId, boolean pending) {
+        if (AccessContext.isUnrestricted()) {
+            return;
+        }
         String companySql = currentCompanyEquipmentSql();
         int hasDispatch = SecurityUtils.hasPermi(PERM_DISPATCH) ? 1 : 0;
         if (pending) {
@@ -854,6 +859,7 @@ public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder
     }
 
     private boolean isDeviceInCurrentCompany(String deviceId) {
+        if (AccessContext.isUnrestricted()) return true;
         if (StringUtils.isEmpty(deviceId)) return true;
         EquipmentBase equipment = equipmentBaseMapper.selectById(deviceId);
         if (equipment == null || equipment.getEquipmentTypeId() == null) return false;
@@ -874,8 +880,11 @@ public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder
         EquipmentType type = device == null || device.getEquipmentTypeId() == null ? null
                 : equipmentTypeMapper.selectById(device.getEquipmentTypeId());
         Integer parent = type == null ? null : type.getParentId();
-        if (Objects.equals(parent, 4)) return null;
-        if (parent != null && parent >= 1 && parent <= 3) return 100L + parent;
+        if (CompanyEquipmentScope.isSharedManhole(parent)) return null;
+        if (parent != null) {
+            Long deptId = CompanyEquipmentScope.companyDeptId(parent);
+            if (deptId != null) return deptId;
+        }
         throw new ServiceException("工单关联设备或设备类型无效,无法选择人员");
     }
 

+ 17 - 66
pipe-network-service/zksy-system/src/main/java/com/zksy/ops/support/OpsAssignScopeSupport.java

@@ -1,9 +1,10 @@
 package com.zksy.ops.support;
 
-import com.zksy.common.core.domain.TreeSelect;
+import com.zksy.base.support.CompanyEquipmentScope;
 import com.zksy.common.core.domain.entity.SysDept;
 import com.zksy.common.core.domain.entity.SysUser;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.common.utils.SecurityUtils;
 import com.zksy.common.utils.StringUtils;
 import com.zksy.system.service.ISysDeptService;
@@ -12,7 +13,10 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.*;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 
 /**
@@ -58,11 +62,10 @@ public class OpsAssignScopeSupport {
     }
 
     /**
-     * 当前登录用户是否为超级管理员
+     * 当前调用链是否不受数据范围限制(超级管理员看全部数据)。
      */
     public boolean isAdmin() {
-        Long userId = currentUserId();
-        return userId != null && SecurityUtils.isAdmin(userId);
+        return AccessContext.isUnrestricted();
     }
 
     /**
@@ -110,50 +113,6 @@ public class OpsAssignScopeSupport {
         return allowed;
     }
 
-    /**
-     * 获取可指派部门树:当前登录用户所属部门及其全部子部门
-     */
-    public List<TreeSelect> assignableDeptTree() {
-        Set<Long> scope = scopeDeptIds();
-        List<SysDept> allDepts = deptService.selectDeptList(new SysDept());
-        if (allDepts == null || allDepts.isEmpty()) {
-            return Collections.emptyList();
-        }
-        if (scope == null) {
-            return deptService.buildDeptTreeSelect(allDepts);
-        }
-        if (scope.isEmpty()) {
-            return Collections.emptyList();
-        }
-        List<SysDept> scoped = allDepts.stream()
-                .filter(dept -> dept.getDeptId() != null && scope.contains(dept.getDeptId()))
-                .collect(Collectors.toList());
-        return deptService.buildDeptTreeSelect(scoped);
-    }
-
-    /**
-     * 查询可指派用户:仅返回指定部门(须在可指派部门范围内)的人员
-     */
-    public List<SysUser> assignableUsers(Long deptId) {
-        Set<Long> scope = scopeDeptIds();
-        if (scope == null) {
-            SysUser query = new SysUser();
-            if (deptId != null) {
-                query.setDeptId(deptId);
-            }
-            return userService.selectUserList(query);
-        }
-        if (scope.isEmpty()) {
-            return new ArrayList<>();
-        }
-        Long targetDeptId = (deptId == null || !scope.contains(deptId)) ? currentDeptId() : deptId;
-        if (targetDeptId == null || !scope.contains(targetDeptId)) {
-            throw new ServiceException("无权限获取该部门人员");
-        }
-        SysUser query = new SysUser();
-        query.setDeptId(targetDeptId);
-        return userService.selectUserList(query);
-    }
 
     /**
      * 查询当前用户可指派范围内的全部人员。
@@ -169,9 +128,7 @@ public class OpsAssignScopeSupport {
         if (scope.isEmpty()) {
             return Collections.emptyList();
         }
-        return users.stream()
-                .filter(user -> user.getDeptId() != null && scope.contains(user.getDeptId()))
-                .collect(Collectors.toList());
+        return users.stream().filter(user -> user.getDeptId() != null && scope.contains(user.getDeptId())).collect(Collectors.toList());
     }
 
     /**
@@ -198,26 +155,20 @@ public class OpsAssignScopeSupport {
     }
 
     /**
-     * 当前用户所属公司的设备父类型范围(含共享窨井类型)。
+     * 当前调用链可见的设备大类(含共享窨井,仅排水公司 102 可见;超管看全部)。
      *
-     * <p>部门路径包含 101/102/103 时分别代表供水/排水/燃气公司;窨井类型(4)
-     * 是三家公司共享的设备范围。
-     * 空集合表示当前部门不属于上述任一公司。</p>
+     * <p>映射规则统一由 {@link CompanyEquipmentScope} 维护,空集合表示当前部门
+     * 不属于任一公司。</p>
      */
     public Set<Integer> currentCompanyEquipmentParentTypeIds() {
-        Set<Integer> result = currentCompanyEquipmentRootTypeIds();
-        if (!result.isEmpty()) result.add(4);
-        return result;
+        return CompanyEquipmentScope.current(currentDeptPathIds());
     }
 
-    /** 当前用户所属公司的根设备类型范围,不包含共享窨井类型。 */
+    /**
+     * 当前调用链可见的设备大类(与公司范围口径一致,保留方法名兼容既有调用方)。
+     */
     public Set<Integer> currentCompanyEquipmentRootTypeIds() {
-        Set<Long> deptPath = currentDeptPathIds();
-        Set<Integer> result = new HashSet<>();
-        if (deptPath.contains(101L)) result.add(1);
-        if (deptPath.contains(102L)) result.add(2);
-        if (deptPath.contains(103L)) result.add(3);
-        return result;
+        return currentCompanyEquipmentParentTypeIds();
     }
 
     /**

+ 1 - 0
pipe-network-service/zksy-system/src/main/resources/mapper/base/AlarmOperationsMapper.xml

@@ -8,6 +8,7 @@
         LEFT JOIN LATERAL (SELECT b.* FROM app_user.equipment_base b
             WHERE b.equipment_code = a.device_code
             ORDER BY b.equipment_id LIMIT 1) e ON true
+        LEFT JOIN app_user.equipment_type t ON t.id = e.equipment_type_id
         LEFT JOIN LATERAL (SELECT s.alarm_status FROM app_user.equipment_status s
             WHERE s.equipment_id = e.equipment_id AND s.del_flag = '0'
             ORDER BY s.status_update_time DESC NULLS LAST, s.status_id DESC LIMIT 1) st ON true

+ 6 - 0
pipe-network-service/zksy-system/src/main/resources/mapper/warning/EarlyWarningMapper.xml

@@ -964,6 +964,7 @@
     </select>
 
     <sql id="WarningVisibility">
+        <if test="!scope.all">
         AND (
             w.create_by = #{scope.username}
             OR w.publisher = #{scope.username}
@@ -987,9 +988,12 @@
               </when>
               <otherwise>1 = 0</otherwise>
               </choose>
+              <if test="scope.sharedManholeVisible">
               OR (et.parent_id = 4 AND (w.handler = #{scope.username} OR w.reviewer = #{scope.username}))
+              </if>
               )
         )
+        </if>
     </sql>
 
     <sql id="WarningPending">
@@ -1056,6 +1060,7 @@
         SELECT COUNT(1) FROM app_user.equipment_base eb
         INNER JOIN app_user.equipment_type et ON et.id = eb.equipment_type_id
         WHERE eb.equipment_code = #{deviceCode}
+        <if test="!scope.all">
         <choose>
             <when test="scope.parentTypeIds != null and !scope.parentTypeIds.isEmpty()">
                 AND et.parent_id IN
@@ -1065,6 +1070,7 @@
             </when>
             <otherwise>AND 1 = 0</otherwise>
         </choose>
+        </if>
     </select>
 
     <select id="selectVisibleArchives" resultType="com.zksy.base.warning.domain.WarningArchive">

+ 13 - 6
pipe-network-service/zksy-system/src/main/resources/mapper/warning/WarningParticipantMapper.xml

@@ -1,6 +1,11 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.zksy.base.warning.mapper.WarningParticipantMapper">
+    <!--
+      候选人可见范围:设备大类 → 归属公司部门,规则由 CompanyEquipmentScope.companyRules() 统一提供。
+      101/102/103 为同级公司部门;共享窨井大类 4 只归排水公司 102。
+      companyRules 传 null 表示超管看全部,不附加部门限制。
+    -->
     <select id="selectCandidates" resultType="com.zksy.base.warning.domain.WarningParticipant">
         SELECT u.user_id, u.user_name, u.nick_name, u.dept_id,
                CASE
@@ -19,14 +24,16 @@
             JOIN app_user.equipment_base eb ON eb.equipment_code = w.device_code
             JOIN app_user.equipment_type et ON et.id = eb.equipment_type_id
             WHERE w.warning_id = #{warningId}
+            <if test="companyRules != null and !companyRules.isEmpty()">
+              AND d.status = '0' AND d.del_flag = '0'
               AND (
-                et.parent_id = 4
-                OR (d.status = '0' AND d.del_flag = '0' AND (
-                  (et.parent_id = 1 AND (d.dept_id = 101 OR POSITION(',101,' IN CONCAT(',', d.ancestors, ',')) &gt; 0))
-                  OR (et.parent_id = 2 AND (d.dept_id = 102 OR POSITION(',102,' IN CONCAT(',', d.ancestors, ',')) &gt; 0))
-                  OR (et.parent_id = 3 AND (d.dept_id = 103 OR POSITION(',103,' IN CONCAT(',', d.ancestors, ',')) &gt; 0))
-                ))
+                <foreach collection="companyRules" item="rule" separator=" OR ">
+                (et.parent_id = #{rule.rootTypeId}
+                 AND (d.dept_id = #{rule.companyDeptId}
+                      OR POSITION(CONCAT(',', #{rule.companyDeptId}, ',') IN CONCAT(',', d.ancestors, ',')) &gt; 0))
+                </foreach>
               )
+            </if>
           )
         <if test="deptId != null">
           AND (d.dept_id = #{deptId}

+ 35 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/mapper/MobileAlarmMapperTest.java

@@ -56,4 +56,39 @@ class MobileAlarmMapperTest {
                 .getBoundSql(params).getSql().replaceAll("\\s+", " ");
         assertTrue(filteredSql.contains("a.alarm_status = ?"), filteredSql);
     }
+
+    @Test void mobileQueriesDeclareEveryAliasUsedBySharedColumns() throws Exception {
+        MybatisConfiguration config = new MybatisConfiguration();
+        for (String name : Arrays.asList("AlarmReviewMapper", "AlarmOperationsMapper")) {
+            try (InputStream xml = getClass().getResourceAsStream("/mapper/base/" + name + ".xml")) {
+                new XMLMapperBuilder(xml, config, name, config.getSqlFragments()).parse();
+            }
+        }
+        Map<String,Object> params = new HashMap<>();
+        params.put("query", new AlarmQuery());
+        params.put("typeIds", Collections.singletonList(11));
+        params.put("id", "a1");
+        params.put("unhandled", 0);
+        Map<String,String> requiredJoins = new LinkedHashMap<>();
+        requiredJoins.put("a", "FROM app_user.alarm_data a");
+        requiredJoins.put("e", ") e ON true");
+        requiredJoins.put("t", "LEFT JOIN app_user.equipment_type t ON t.id = e.equipment_type_id");
+        requiredJoins.put("st", ") st ON true");
+        requiredJoins.put("w", "app_user.work_order w");
+        requiredJoins.put("u", "app_user.sys_user u");
+        List<String> statements = Arrays.asList(
+                AlarmOperationsMapper.class.getName()+".selectMobilePage",
+                AlarmOperationsMapper.class.getName()+".selectMobileDetail",
+                AlarmReviewMapper.class.getName()+".selectMobileDetail",
+                AlarmOperationsMapper.class.getName()+".selectPage");
+        for (String statement : statements) {
+            String sql = config.getMappedStatement(statement).getBoundSql(params).getSql().replaceAll("\\s+", " ");
+            assertTrue(sql.contains("t.type_name AS equipment_type_name"), statement + ": " + sql);
+            for (Map.Entry<String,String> join : requiredJoins.entrySet()) {
+                assertTrue(sql.contains(join.getValue()), statement + " 缺少别名 " + join.getKey() + ": " + sql);
+            }
+            assertTrue(sql.indexOf(") e ON true") < sql.indexOf("app_user.equipment_type t"),
+                    statement + " 类型表 JOIN 必须位于设备子查询之后: " + sql);
+        }
+    }
 }

+ 7 - 3
pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmMobileServiceTest.java

@@ -41,11 +41,15 @@ class AlarmMobileServiceTest {
     }
 
     @ParameterizedTest @ValueSource(ints = {1, 2, 3})
-    void scopeIncludesCompanyChildrenAndSharedManholeChildren(int root) {
-        when(company.currentCompanyEquipmentRootTypeIds()).thenReturn(Collections.singleton(root));
+    void onlyDrainageCompanyScopeIncludesSharedManholeChildren(int root) {
+        Set<Integer> roots = root == 2 ? new LinkedHashSet<>(Arrays.asList(2, 4)) : Collections.singleton(root);
+        when(company.currentCompanyEquipmentRootTypeIds()).thenReturn(roots);
         when(types.selectList(null)).thenReturn(Arrays.asList(type(1,0), type(2,0), type(3,0), type(4,0),
                 type(11,1), type(21,2), type(31,3), type(41,4), type(111,11)));
-        assertEquals(new HashSet<>(Arrays.asList(root * 10 + 1, 41)), new HashSet<>(scope.resolveMobile(new MobileAlarmQuery())));
+        Set<Integer> expected = root == 2
+                ? new HashSet<>(Arrays.asList(root * 10 + 1, 41))
+                : Collections.singleton(root * 10 + 1);
+        assertEquals(expected, new HashSet<>(scope.resolveMobile(new MobileAlarmQuery())));
     }
     @Test void forgedRootBlocksEveryEntryBeforeReadingOrWriting() {
         when(company.currentCompanyEquipmentRootTypeIds()).thenReturn(Collections.singleton(1));

+ 29 - 7
pipe-network-service/zksy-system/src/test/java/com/zksy/ops/support/CompanyEquipmentScopeTest.java

@@ -1,8 +1,10 @@
 package com.zksy.ops.support;
 
+import com.zksy.base.support.CompanyEquipmentScope;
 import com.zksy.common.core.domain.entity.SysDept;
 import com.zksy.common.core.domain.entity.SysUser;
 import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.common.utils.AccessContext;
 import com.zksy.system.service.ISysDeptService;
 import org.junit.jupiter.api.*;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -16,7 +18,7 @@ class CompanyEquipmentScopeTest {
     private final ISysDeptService depts = mock(ISysDeptService.class);
     private final OpsAssignScopeSupport scope = new OpsAssignScopeSupport();
     @BeforeEach void setup() { ReflectionTestUtils.setField(scope, "deptService", depts); }
-    @AfterEach void cleanup() { SecurityContextHolder.clearContext(); }
+    @AfterEach void cleanup() { SecurityContextHolder.clearContext(); AccessContext.clear(); }
     private void login(long userId, long deptId, String ancestors) {
         SysUser user = new SysUser(); user.setUserId(userId); user.setDeptId(deptId);
         LoginUser login = new LoginUser(userId, deptId, user, Collections.emptySet());
@@ -24,22 +26,42 @@ class CompanyEquipmentScopeTest {
         SysDept dept = new SysDept(); dept.setDeptId(deptId); dept.setAncestors(ancestors);
         when(depts.selectDeptById(deptId)).thenReturn(dept);
     }
-    @Test void companyDepartmentItselfMapsToExactRootWithoutSharedType() {
+
+    @Test void onlyDrainageCompanySeesSharedManholeType() {
+        assertEquals(Collections.singleton(1), CompanyEquipmentScope.resolve(Set.of(101L)));
+        assertEquals(Set.of(2, 4), CompanyEquipmentScope.resolve(Set.of(102L)));
+        assertEquals(Collections.singleton(3), CompanyEquipmentScope.resolve(Set.of(103L)));
+        assertTrue(CompanyEquipmentScope.resolve(Collections.emptySet()).isEmpty());
+    }
+
+    @Test void companyRulesAndReverseLookupUseSameMapping() {
+        assertEquals(101L, CompanyEquipmentScope.companyDeptId(1));
+        assertEquals(102L, CompanyEquipmentScope.companyDeptId(2));
+        assertEquals(103L, CompanyEquipmentScope.companyDeptId(3));
+        assertEquals(102L, CompanyEquipmentScope.companyDeptId(4));
+        assertNull(CompanyEquipmentScope.companyDeptId(9));
+        assertEquals(4, CompanyEquipmentScope.companyRules().size());
+    }
+
+    @Test void companyDepartmentItselfMapsToExactRoot() {
         for (int company = 101; company <= 103; company++) {
             login(42, company, "0,100");
-            assertEquals(Collections.singleton(company - 100), scope.currentCompanyEquipmentRootTypeIds());
+            assertEquals(CompanyEquipmentScope.resolve(Set.of((long) company)),
+                    scope.currentCompanyEquipmentRootTypeIds());
         }
     }
+
     @Test void descendantDepartmentUsesExactAncestorIds() {
         login(42, 201, "0,100, 102 ,invalid");
-        assertEquals(Collections.singleton(2), scope.currentCompanyEquipmentRootTypeIds());
+        assertEquals(Set.of(2, 4), scope.currentCompanyEquipmentRootTypeIds());
         login(42, 201, "0,100,1101,1102,1103");
         assertTrue(scope.currentCompanyEquipmentRootTypeIds().isEmpty());
     }
-    @Test void administratorStillUsesOwnCompanyAndHasNoGlobalBypass() {
+
+    @Test void administratorSeesAllCompanyTypes() {
         login(1, 201, "0,100,103");
-        assertEquals(Collections.singleton(3), scope.currentCompanyEquipmentRootTypeIds());
+        assertEquals(Set.of(1, 2, 3, 4), scope.currentCompanyEquipmentRootTypeIds());
         login(1, 100, "0");
-        assertTrue(scope.currentCompanyEquipmentRootTypeIds().isEmpty());
+        assertEquals(Set.of(1, 2, 3, 4), scope.currentCompanyEquipmentParentTypeIds());
     }
 }