feat(admin): 批量删除并入筛选行省一整行+公司管理加删除/批量删除(2026-11-23 用户口径)
- BatchDeleteActions margin-left:auto 右对齐、不再独占一行,14 页迁入各自筛选/工具行(Users/Groups/Menus/UserSecrets/QueryAsin/AsinInvalid/SkipPrice/DedupeRegistry/ProductCategory/DeviceLogs/DigitalHuman/ShopManage/ShopKeys/BrandGating);主按钮沿用全局 34px 同高,align-batch-toolbar-inline.test.ts 钉形状防回归
- 公司删除:DELETE /api/admin/companies/{id}(仅超管,名下有账号拒并带数量),只收公司行+columns 菜单树(PermissionMenuService.deleteTreeByCompany 与 copyTreeFromTemplate 对称),业务数据不级联;列表 VO 带 user_count 供前端置灰勾选/删除按钮;批量删除按用户管理同形走前端逐条循环
- CompaniesPage 加勾选列+行删除按钮(ops-cell 补 flex-wrap 过 ops-cell-must-wrap),删除后 refreshCompanyDirectory 同步 tab 条
- 测试:CompanyServiceDeleteTest 6+PermissionMenuServiceDeleteTreeTest 2+CompanyVoTest user_count 契约+CompanyControllerEndpointTest 翻转 exposesNoDeleteEndpoint→点名 DELETE 端点+CompanyReadPathMenuGateTest ensureSuperAdmin 3→4(delete 入册)+company-directory/row-buttons 补例;source-pin 基线重生成(265 文件/1859 例)
- 验证:admin-vue vue-tsc rc=0、node --test 1976 全绿、vitest mount 247 全绿;backend test-compile rc=0、Company*/PermissionMenu*/跨切守卫点名全绿(CatchSilenceRatchet 红因=另一路在飞件 JdPublishFillAiService 3 个 catch,归属京东窗不代抬)
This commit is contained in:
+17
-3
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
@@ -21,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 公司目录(设计文档 §2.3)。可见范围与写入边界都在 CompanyService 里判,
|
||||
@@ -29,7 +31,7 @@ import java.util.List;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin")
|
||||
@Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名与启停")
|
||||
@Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名、启停与删除")
|
||||
public class CompanyController {
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
@@ -42,7 +44,11 @@ public class CompanyController {
|
||||
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤")
|
||||
@RequestParam(name = "platform", required = false) String platform) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
List<CompanyVo> items = companyService.listVisible(operator, platform).stream().map(CompanyVo::from).toList();
|
||||
// 一次分组查询带出各公司在册账号数:前端据此把「名下还有账号」的公司勾选框置灰(2026-11-23)。
|
||||
Map<Long, Long> userCounts = companyService.userCountByCompany();
|
||||
List<CompanyVo> items = companyService.listVisible(operator, platform).stream()
|
||||
.map(company -> CompanyVo.from(company, userCounts.getOrDefault(company.getId(), 0L)))
|
||||
.toList();
|
||||
return ApiResponse.success(items);
|
||||
}
|
||||
|
||||
@@ -53,7 +59,6 @@ public class CompanyController {
|
||||
return ApiResponse.success("公司创建成功", CompanyVo.from(companyService.create(operator, body)));
|
||||
}
|
||||
|
||||
/** 没有 DELETE:账号挂着的公司删不掉,停用(status=0)就是终态。 */
|
||||
@PutMapping("/companies/{id}")
|
||||
@Operation(summary = "改名与启停(仅超级管理员)")
|
||||
public ApiResponse<CompanyVo> updateCompany(HttpServletRequest request,
|
||||
@@ -62,4 +67,13 @@ public class CompanyController {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("更新成功", CompanyVo.from(companyService.update(operator, id, body)));
|
||||
}
|
||||
|
||||
/** 删除(2026-11-23):只收公司行+该公司菜单树,名下有账号的公司删不得(CompanyService 兜底校验)。 */
|
||||
@DeleteMapping("/companies/{id}")
|
||||
@Operation(summary = "删除公司(仅超级管理员,名下有账号则拒绝)")
|
||||
public ApiResponse<Void> deleteCompany(HttpServletRequest request, @PathVariable Long id) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
companyService.delete(operator, id);
|
||||
return ApiResponse.success("删除成功", null);
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -1,9 +1,26 @@
|
||||
package com.nanri.aiimage.modules.company.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanyUserCountRow;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface CompanyMapper extends BaseMapper<CompanyEntity> {
|
||||
|
||||
/**
|
||||
* 每家公司在册账号数(users.company_id 分组计数,SQL 收口在 Mapper 层)。
|
||||
* 停用账号也算在册——它们仍挂在公司上,删了公司一样把人挂在查不到的租户名下。
|
||||
* 公司行是硬删(无软删位),users 侧同样硬删,所以这里不用再过滤删除标记。
|
||||
*/
|
||||
@Select("SELECT company_id AS companyId, COUNT(*) AS userCount FROM users GROUP BY company_id")
|
||||
List<CompanyUserCountRow> selectUserCountByCompany();
|
||||
|
||||
/** 单家公司在册账号数:CompanyService.delete 的「有账号不能删」闸门用(权威校验,前端那份只是展示提示)。 */
|
||||
@Select("SELECT COUNT(*) FROM users WHERE company_id = #{companyId}")
|
||||
Long selectUserCountByCompanyId(@Param("companyId") Long companyId);
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.nanri.aiimage.modules.company.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 每家公司在册账号数(CompanyMapper.selectUserCountByCompany 的行形状)。
|
||||
* 公司管理列表用它标出"名下还有账号、删不得"的公司(2026-11-23 用户拍板:有账号不能删)。
|
||||
*/
|
||||
@Data
|
||||
public class CompanyUserCountRow {
|
||||
|
||||
private Long companyId;
|
||||
private Long userCount;
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ public class CompanyEntity {
|
||||
private Long id;
|
||||
@TableField("company_name")
|
||||
private String companyName;
|
||||
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */
|
||||
/** 1=启用 0=停用。停用≠删除:删除是独立显式入口(DELETE /api/admin/companies/{id}),名下有账号的公司删不得。 */
|
||||
private Integer status;
|
||||
private String remark;
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.company.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import lombok.Data;
|
||||
@@ -27,8 +28,19 @@ public class CompanyVo {
|
||||
private String createdAt;
|
||||
@JsonProperty("updated_at")
|
||||
private String updatedAt;
|
||||
/**
|
||||
* 在册账号数(2026-11-23):仅公司目录列表下发,供前端标出「名下还有账号、删不得」的公司;
|
||||
* create/update 回包不带(null 不序列化,旧键集形状不变)。
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@JsonProperty("user_count")
|
||||
private Long userCount;
|
||||
|
||||
public static CompanyVo from(CompanyEntity entity) {
|
||||
return from(entity, null);
|
||||
}
|
||||
|
||||
public static CompanyVo from(CompanyEntity entity, Long userCount) {
|
||||
CompanyVo vo = new CompanyVo();
|
||||
vo.setId(entity.getId());
|
||||
vo.setCompanyName(entity.getCompanyName());
|
||||
@@ -37,6 +49,7 @@ public class CompanyVo {
|
||||
vo.setPlatform(entity.getPlatform());
|
||||
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
|
||||
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
|
||||
vo.setUserCount(userCount);
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
|
||||
+43
-1
@@ -8,9 +8,11 @@ import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.AdminPlatformScope;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanyUserCountRow;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -20,7 +22,9 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CompanyService {
|
||||
@@ -84,6 +88,18 @@ public class CompanyService {
|
||||
return companyMapper.selectList(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 各公司在册账号数(id → count,一次分组查询,别逐行 COUNT 凑 N+1)。
|
||||
* 公司管理列表据此标出「名下还有账号、删不得」的公司;没有账号的公司不在 Map 里,
|
||||
* 调用方用 {@code getOrDefault(id, 0L)} 归零。
|
||||
*/
|
||||
public Map<Long, Long> userCountByCompany() {
|
||||
return companyMapper.selectUserCountByCompany().stream()
|
||||
.filter(row -> row.getCompanyId() != null)
|
||||
.collect(Collectors.toMap(CompanyUserCountRow::getCompanyId,
|
||||
row -> row.getUserCount() == null ? 0L : row.getUserCount()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 id 批量补公司名(§2.3 账号列表、§2.4 登录态都用它,别写成逐行查的 N+1)。
|
||||
*
|
||||
@@ -147,7 +163,7 @@ public class CompanyService {
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 改名 + 启停一起改;不提供删除,账号挂着的公司删不掉。 */
|
||||
/** 改名 + 启停一起改;删除是独立入口 {@link #delete}(名下有账号的公司删不得)。 */
|
||||
public CompanyEntity update(AdminUserEntity operator, Long id, CompanySaveRequest request) {
|
||||
ensureSuperAdmin(operator);
|
||||
CompanyEntity company = companyMapper.selectById(id);
|
||||
@@ -172,6 +188,32 @@ public class CompanyService {
|
||||
return company;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除公司(2026-11-23 用户拍板「有账号不能删」):只收公司行 + 该公司的菜单权限树
|
||||
* (columns,与建号时 {@code copyTreeFromTemplate} 种下的对称),业务数据一律不级联。
|
||||
*
|
||||
* <p>店铺分组/店铺密钥/去重数据/京东与外观专利等表里的 {@code company_id} 行是历史数据,
|
||||
* 留着无害:company id 自增不复用,唯一键都带 company_id,不存在新公司撞旧数据;
|
||||
* 这与京东删除任务不级联清数据库表是同一条铁律(删除只收显式说的那部分)。</p>
|
||||
*
|
||||
* <p>事务包住两件事:删菜单树 + 删公司行,任一失败一起回滚,不留「行没了树还在」的半成品。</p>
|
||||
*/
|
||||
@Transactional
|
||||
public void delete(AdminUserEntity operator, Long id) {
|
||||
ensureSuperAdmin(operator);
|
||||
CompanyEntity company = companyMapper.selectById(id);
|
||||
if (company == null) {
|
||||
throw new BusinessException("公司不存在");
|
||||
}
|
||||
Long userCount = companyMapper.selectUserCountByCompanyId(id);
|
||||
if (userCount != null && userCount > 0) {
|
||||
throw new BusinessException("该公司名下还有 " + userCount + " 个账号,请先删除或转移后再删除公司");
|
||||
}
|
||||
permissionMenuService.deleteTreeByCompany(id);
|
||||
companyMapper.deleteById(id);
|
||||
log.info("[company] 公司已删除 companyId={} name={}", id, company.getCompanyName());
|
||||
}
|
||||
|
||||
/** uk_company_name 只能兜底并发,不能当校验用:撞索引抛的是"用户名已存在"这类看不懂的文案。 */
|
||||
private void ensureNameAvailable(String companyName, Long excludeId) {
|
||||
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<CompanyEntity>()
|
||||
|
||||
+22
@@ -467,6 +467,28 @@ public class PermissionMenuService {
|
||||
return inserted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除某公司的整棵菜单树(columns 表按 company_id 清行),与 {@link #copyTreeFromTemplate}
|
||||
* 对称:建号时种下的树,删号时收走,不留孤儿行。
|
||||
*
|
||||
* <p>调用方(CompanyService.delete)必须先确认该公司名下已无账号——树是公司私有配置,
|
||||
* 没有账号引用它才允许整棵删;这里不再重复判账号数(判了就要反向依赖 admin 模块,
|
||||
* 事务边界由调用方的 @Transactional 兜住,删树失败连公司行一起回滚)。</p>
|
||||
*
|
||||
* @return 本次删除的菜单行数(写日志与测试断言用)
|
||||
*/
|
||||
@Transactional
|
||||
public int deleteTreeByCompany(Long companyId) {
|
||||
if (companyId == null || companyId <= 0) {
|
||||
throw new BusinessException("公司 id 不能为空");
|
||||
}
|
||||
int deleted = permissionMenuMapper.delete(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(PermissionMenuEntity::getCompanyId, companyId));
|
||||
log.info("[menu-tree-delete] 公司菜单树已删 companyId={} rows={}", companyId, deleted);
|
||||
invalidateMenuTreeCache();
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** Returns only persisted direct grant IDs (never recursively expanded). */
|
||||
public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) {
|
||||
return getUserColumnIds(null, userId, menuType);
|
||||
|
||||
+27
-7
@@ -20,6 +20,7 @@ import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -30,8 +31,9 @@ import static org.mockito.Mockito.when;
|
||||
/**
|
||||
* 公司目录端点的对外契约(设计文档 §2.3)。
|
||||
*
|
||||
* <p>钉的是 admin-frontend-vue/src/api/companies.ts 实际会打的三个地址,以及"先鉴权、
|
||||
* 再碰目录"的顺序。路径写错时前端只会拿到空列表、不报错,所以只能由用例盯着。</p>
|
||||
* <p>钉的是 admin-frontend-vue/src/api/companies.ts 实际会打的地址(含 2026-11-23 新增的
|
||||
* 删除口),以及"先鉴权、再碰目录"的顺序。路径写错时前端只会拿到空列表、不报错,
|
||||
* 所以只能由用例盯着。</p>
|
||||
*/
|
||||
class CompanyControllerEndpointTest {
|
||||
|
||||
@@ -58,6 +60,7 @@ class CompanyControllerEndpointTest {
|
||||
|
||||
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
|
||||
when(companyService.listVisible(operator, null)).thenReturn(List.of(company(1L, "厦门米椿花")));
|
||||
when(companyService.userCountByCompany()).thenReturn(Map.of(1L, 3L));
|
||||
when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富"));
|
||||
when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技"));
|
||||
}
|
||||
@@ -76,6 +79,7 @@ class CompanyControllerEndpointTest {
|
||||
controller.listCompanies(request, null);
|
||||
controller.createCompany(request, body);
|
||||
controller.updateCompany(request, 2L, body);
|
||||
controller.deleteCompany(request, 2L);
|
||||
|
||||
InOrder order = inOrder(adminAuthSupport, companyService);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
@@ -84,6 +88,8 @@ class CompanyControllerEndpointTest {
|
||||
order.verify(companyService).create(operator, body);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
order.verify(companyService).update(operator, 2L, body);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
order.verify(companyService).delete(operator, 2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,16 +99,22 @@ class CompanyControllerEndpointTest {
|
||||
assertThat(pathsOf("listCompanies")).contains("/companies");
|
||||
assertThat(pathsOf("createCompany")).contains("/companies");
|
||||
assertThat(pathsOf("updateCompany")).contains("/companies/{id}");
|
||||
assertThat(pathsOf("deleteCompany")).contains("/companies/{id}");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("不提供删除公司的端点:账号挂着的公司删不掉,只能停用")
|
||||
void exposesNoDeleteEndpoint() {
|
||||
@DisplayName("删除端点在册(2026-11-23 起):只许挂在 /companies/{id} 上")
|
||||
void exposesDeleteEndpointForCompanyRemoval() {
|
||||
Method deleteMethod = null;
|
||||
for (Method method : CompanyController.class.getDeclaredMethods()) {
|
||||
assertThat(AnnotatedElementUtils.findMergedAnnotation(method, DeleteMapping.class))
|
||||
.as("方法 %s 不该是 DELETE", method.getName())
|
||||
.isNull();
|
||||
if (method.getName().equals("deleteCompany")) {
|
||||
deleteMethod = method;
|
||||
}
|
||||
}
|
||||
assertThat(deleteMethod).as("CompanyController 必须有 deleteCompany 端点").isNotNull();
|
||||
DeleteMapping mapping = AnnotatedElementUtils.findMergedAnnotation(deleteMethod, DeleteMapping.class);
|
||||
assertThat(mapping).as("deleteCompany 必须是 @DeleteMapping").isNotNull();
|
||||
assertThat(mapping.path()).contains("/companies/{id}");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,6 +126,14 @@ class CompanyControllerEndpointTest {
|
||||
assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("列表带出在册账号数:Map 缺了这家就归 0,前端把非零的公司勾选框置灰")
|
||||
void listCarriesUserCountForTheDeleteGuard() {
|
||||
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request, null);
|
||||
|
||||
assertThat(response.getData().get(0).getUserCount()).isEqualTo(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("新建/改名把落库后的那一条回给前端,省一次重新拉列表")
|
||||
void writeEndpointsReturnTheSavedCompany() {
|
||||
|
||||
+24
@@ -42,4 +42,28 @@ class CompanyVoTest {
|
||||
// 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined
|
||||
assertThat(json.get("updated_at")).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("在册账号数只在列表回包带(from(entity, count)),create/update 回包不带该键")
|
||||
void carriesUserCountOnlyWhenGiven() throws Exception {
|
||||
CompanyEntity entity = new CompanyEntity();
|
||||
entity.setId(2L);
|
||||
entity.setCompanyName("福州数富");
|
||||
entity.setStatus(1);
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
Map<String, Object> listed = mapper.readValue(
|
||||
mapper.writeValueAsString(CompanyVo.from(entity, 5L)),
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
Map<String, Object> saved = mapper.readValue(
|
||||
mapper.writeValueAsString(CompanyVo.from(entity)),
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
|
||||
// 列表带 user_count:前端 CompaniesPage 据此把「名下还有账号」的公司勾选框置灰(2026-11-23)
|
||||
assertThat(listed.get("user_count")).isEqualTo(5);
|
||||
// create/update 回包键集保持旧形状(NON_NULL:null 不序列化),前端解析器不吃惊
|
||||
assertThat(saved.keySet()).doesNotContain("user_count");
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -48,9 +48,10 @@ class CompanyReadPathMenuGateTest {
|
||||
List<String> guards = executableLines(text).stream()
|
||||
.filter(line -> line.contains("ensureSuperAdmin(operator);"))
|
||||
.collect(Collectors.toList());
|
||||
// 2026-11-23 追加 delete(删公司):写路径从三处变四处,每一处都必须还挂着同一道超管闸
|
||||
assertThat(guards)
|
||||
.as("create / update / listVisible 三处的超管闸门 must 保留")
|
||||
.hasSize(3);
|
||||
.as("create / update / listVisible / delete 四处的超管闸门 must 保留")
|
||||
.hasSize(4);
|
||||
}
|
||||
|
||||
/** 取样集非空自检:扫描一旦 0 命中,上面几条就恒绿,等于没护栏。 */
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package com.nanri.aiimage.modules.company.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanyUserCountRow;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.anyLong;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 删除公司的守卫链(2026-11-23 用户拍板「名下有账号不能删」)。
|
||||
*
|
||||
* <p>删除只收两样:公司行 + 该公司的菜单权限树(与建号时 copyTreeFromTemplate 对称);
|
||||
* 业务数据(店铺分组/密钥/去重/京东/外观专利等 company_id 行)一律不级联——
|
||||
* 与京东删除任务不级联清数据库是同一条铁律。有账号的公司必须先删/转账号,这里再兜一道权威校验,
|
||||
* 前端那份 user_count 置灰只是展示提示,不能当权限边界。</p>
|
||||
*/
|
||||
class CompanyServiceDeleteTest {
|
||||
|
||||
private CompanyMapper companyMapper;
|
||||
private AdminAuthSupport adminAuthSupport;
|
||||
private PermissionMenuService permissionMenuService;
|
||||
private CompanyService companyService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// LambdaQueryWrapper 的列名解析依赖 TableInfo 缓存,单测没有 Spring 上下文,手工钉一次。
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
|
||||
companyMapper = mock(CompanyMapper.class);
|
||||
adminAuthSupport = mock(AdminAuthSupport.class);
|
||||
permissionMenuService = mock(PermissionMenuService.class);
|
||||
companyService = new CompanyService(companyMapper, adminAuthSupport, permissionMenuService);
|
||||
}
|
||||
|
||||
private AdminUserEntity operator(String role, Long companyId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(100L);
|
||||
user.setUsername("op");
|
||||
user.setRole(role);
|
||||
user.setCompanyId(companyId);
|
||||
when(adminAuthSupport.currentRole(user)).thenReturn(role);
|
||||
return user;
|
||||
}
|
||||
|
||||
private CompanyEntity company(long id, String name, int status) {
|
||||
CompanyEntity entity = new CompanyEntity();
|
||||
entity.setId(id);
|
||||
entity.setCompanyName(name);
|
||||
entity.setStatus(status);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("删除公司仅超管:公司内管理员也删不得")
|
||||
void companyAdminCannotDelete() {
|
||||
assertThatThrownBy(() -> companyService.delete(operator("admin", 2L), 1L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("超级管理员");
|
||||
verify(companyMapper, never()).deleteById(anyLong());
|
||||
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("删一家不存在的公司按失败处理,不许静默通过")
|
||||
void deleteRejectsUnknownCompany() {
|
||||
when(companyMapper.selectById(9L)).thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> companyService.delete(operator("super_admin", 1L), 9L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("不存在");
|
||||
verify(companyMapper, never()).deleteById(anyLong());
|
||||
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("名下还有账号的公司删不得:文案带账号数,树和行都不许动")
|
||||
void deleteRejectsCompanyThatStillHasUsers() {
|
||||
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
|
||||
when(companyMapper.selectUserCountByCompanyId(2L)).thenReturn(5L);
|
||||
|
||||
assertThatThrownBy(() -> companyService.delete(operator("super_admin", 1L), 2L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("5 个账号");
|
||||
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
|
||||
verify(companyMapper, never()).deleteById(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("零账号的公司才可删:先删该公司菜单树、再删公司行,同一事务两步走")
|
||||
void deleteRemovesMenuTreeThenCompanyRow() {
|
||||
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
|
||||
when(companyMapper.selectUserCountByCompanyId(2L)).thenReturn(0L);
|
||||
when(permissionMenuService.deleteTreeByCompany(2L)).thenReturn(21);
|
||||
|
||||
companyService.delete(operator("super_admin", 1L), 2L);
|
||||
|
||||
InOrder order = inOrder(permissionMenuService, companyMapper);
|
||||
order.verify(permissionMenuService).deleteTreeByCompany(2L);
|
||||
order.verify(companyMapper).deleteById(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("删除入口必须是 @Transactional:删树失败要连公司行一起回滚,不留半成品")
|
||||
void deleteIsTransactionalSoTreeAndRowRollBackTogether() throws Exception {
|
||||
assertThat(CompanyService.class
|
||||
.getMethod("delete", AdminUserEntity.class, Long.class)
|
||||
.isAnnotationPresent(Transactional.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("userCountByCompany 一次分组查询出全量,行缺 companyId 时安全跳过")
|
||||
void userCountByCompanyAggregatesInOneQuery() {
|
||||
CompanyUserCountRow row = new CompanyUserCountRow();
|
||||
row.setCompanyId(3L);
|
||||
row.setUserCount(7L);
|
||||
CompanyUserCountRow broken = new CompanyUserCountRow();
|
||||
broken.setCompanyId(null);
|
||||
when(companyMapper.selectUserCountByCompany()).thenReturn(List.of(row, broken));
|
||||
|
||||
Map<Long, Long> counts = companyService.userCountByCompany();
|
||||
|
||||
assertThat(counts).containsOnlyKeys(3L);
|
||||
assertThat(counts.get(3L)).isEqualTo(7L);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.nanri.aiimage.modules.permission.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.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.modules.permission.mapper.PermissionMenuMapper;
|
||||
import com.nanri.aiimage.modules.permission.mapper.UserColumnPermissionMapper;
|
||||
import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link PermissionMenuService#deleteTreeByCompany(Long)} 的单测:删号公司时按 company_id
|
||||
* 整棵收走菜单树(与 copyTreeFromTemplate 对称)。账号数守卫在 CompanyService.delete 那一层,
|
||||
* 这里只钉「按公司收行」这件事本身。
|
||||
*/
|
||||
class PermissionMenuServiceDeleteTreeTest {
|
||||
|
||||
private PermissionMenuMapper menuMapper;
|
||||
private UserColumnPermissionMapper permissionMapper;
|
||||
private AdminUserMapper userMapper;
|
||||
private PermissionMenuService service;
|
||||
|
||||
@BeforeAll
|
||||
static void initMybatisPlusTableInfo() {
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, PermissionMenuEntity.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
menuMapper = mock(PermissionMenuMapper.class);
|
||||
permissionMapper = mock(UserColumnPermissionMapper.class);
|
||||
userMapper = mock(AdminUserMapper.class);
|
||||
service = new PermissionMenuService(menuMapper, permissionMapper, userMapper);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private LambdaQueryWrapper<PermissionMenuEntity> capturedDelete() {
|
||||
ArgumentCaptor<LambdaQueryWrapper<PermissionMenuEntity>> captor =
|
||||
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(menuMapper).delete(captor.capture());
|
||||
// MP 的参数要渲染一次 sqlSegment 才落进 paramNameValuePairs
|
||||
assertThat(captor.getValue().getSqlSegment()).isNotNull();
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("按 company_id 整棵删:条件带目标公司的 id,回删掉的行数")
|
||||
void deletesEveryMenuRowOfTheTargetCompany() {
|
||||
when(menuMapper.delete(any())).thenReturn(21);
|
||||
|
||||
int deleted = service.deleteTreeByCompany(7L);
|
||||
|
||||
assertThat(deleted).isEqualTo(21);
|
||||
LambdaQueryWrapper<PermissionMenuEntity> query = capturedDelete();
|
||||
assertThat(query.getParamNameValuePairs()).containsValue(7L);
|
||||
// 只按归属收行,不按类型/父级再切:每家公司一棵树,一次清干净
|
||||
assertThat(query.getSqlSegment()).doesNotContain("menu_type");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("公司 id 空或非法直接拒,不许退化成清全表")
|
||||
void rejectsBlankOrInvalidCompanyId() {
|
||||
assertThatThrownBy(() -> service.deleteTreeByCompany(null))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
assertThatThrownBy(() -> service.deleteTreeByCompany(0L))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
verify(menuMapper, never()).delete(any());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user