feat(多公司): 第二批 —— 登录带出公司身份、移人仅超管、启动期 DEFAULT 哨兵、列表公司列
company 模块落地(目录读写收窄 + 菜单闸门),并把公司维度接进四个已有出口:
- 登录/current-user 回包带 companyId/companyName,且取名失败不得挡住登录;
- 移人仅超管,且校验「创建人同公司或为超管」不变式(二期免改 77 处过滤点的前提);
- users.company_id 的 DEFAULT 由启动期哨兵盯着,多公司已上线仍未摘则打
COMPANY_DEFAULT_STILL_PRESENT(ASCII 标记串,供 docker logs grep);
- 账号列表加 company_id/company_name 与可选按公司筛选:超管可筛任意公司,
公司内 admin 传别家公司视为无结果(不报错也不越权)。
39 例护栏,29 条变异自证(首轮 25/28 咬死,两条存活都是用例侧的洞:
namesByIds 被 mock 掉所以内部去重从未被证明、contains("公司") 分不清闸门与
不变式;修补后 4/4 KILLED)。业务表零 DDL、零回填。
This commit is contained in:
@@ -23,6 +23,9 @@ public class AdminUserEntity {
|
||||
private String role;
|
||||
@TableField("created_by_id")
|
||||
private Long createdById;
|
||||
/** 所属公司(company.id,V143 新增)。列 NOT NULL,建号必须显式写,见 AdminUserService#createUser。 */
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
/**
|
||||
|
||||
+6
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.admin.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import com.nanri.aiimage.modules.permission.service.support.AdminMenuTreeBuilder;
|
||||
@@ -36,6 +37,7 @@ public class AdminConsoleController {
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final CompanyService companyService;
|
||||
|
||||
@GetMapping("/")
|
||||
@Operation(summary = "根路径跳管理后台", hidden = true)
|
||||
@@ -69,6 +71,10 @@ public class AdminConsoleController {
|
||||
item.put("id", operator.getId());
|
||||
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
|
||||
item.put("role", adminAuthSupport.currentRole(operator));
|
||||
// 键名固定 camelCase:session.ts 把 item 原样当 AdminUser 用,没有字段映射层,
|
||||
// 拼错只会让顶栏静默少一行字(前端 || '' 兜底),不会报错。
|
||||
item.put("companyId", operator.getCompanyId());
|
||||
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
|
||||
return ApiResponse.success(Map.of("item", item));
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -39,11 +39,12 @@ public class AdminUserController {
|
||||
@RequestParam(name = "search", required = false) String search,
|
||||
@RequestParam(name = "created_by_id", required = false) Long createdById,
|
||||
@RequestParam(name = "admin_id", required = false) Long adminId,
|
||||
@RequestParam(name = "role", required = false) String role) {
|
||||
@RequestParam(name = "role", required = false) String role,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
|
||||
String kw = (username == null || username.isBlank()) ? search : username;
|
||||
Long filterCreatedBy = createdById != null ? createdById : adminId;
|
||||
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role);
|
||||
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role, companyId);
|
||||
return ApiResponse.success(vo);
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -10,5 +10,6 @@ public class AdminUserCreateRequest {
|
||||
private String password;
|
||||
private String role;
|
||||
private Long createdById;
|
||||
private Long companyId;
|
||||
private List<Long> columnIds;
|
||||
}
|
||||
|
||||
+2
@@ -9,4 +9,6 @@ public class AdminUserUpdateRequest {
|
||||
private String password;
|
||||
private String role;
|
||||
private List<Long> columnIds;
|
||||
/** 移人目标公司(V143 §2.2,仅超管可用);null 或与账号现公司相同都表示「不动」。 */
|
||||
private Long companyId;
|
||||
}
|
||||
|
||||
+4
@@ -12,6 +12,10 @@ public class AdminUserItemVo {
|
||||
private String role;
|
||||
@JsonProperty("created_by_id")
|
||||
private Long createdById;
|
||||
@JsonProperty("company_id")
|
||||
private Long companyId;
|
||||
@JsonProperty("company_name")
|
||||
private String companyName;
|
||||
@JsonProperty("creator_username")
|
||||
private String creatorUsername;
|
||||
@JsonProperty("created_at")
|
||||
|
||||
+124
-5
@@ -14,6 +14,7 @@ import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -44,9 +45,11 @@ public class AdminUserService {
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final UserSecretCleanupPort userSecretCleanupPort;
|
||||
private final CompanyService companyService;
|
||||
|
||||
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
|
||||
String username, Long createdById, String roleFilter) {
|
||||
String username, Long createdById, String roleFilter,
|
||||
Long companyIdFilter) {
|
||||
String role = adminAuthSupport.currentRole(currentUser);
|
||||
if (role == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
@@ -68,13 +71,24 @@ public class AdminUserService {
|
||||
if (!roleFilterValue.isEmpty()) {
|
||||
query.eq(AdminUserEntity::getRole, roleFilterValue);
|
||||
}
|
||||
if ("super_admin".equals(role)) {
|
||||
boolean isSuperAdmin = "super_admin".equals(role);
|
||||
if (companyIdFilter != null && !isSuperAdmin) {
|
||||
// 公司内管理员:筛自己公司 = 不加条件(他的可见范围本来就只有本公司),
|
||||
// 筛别家公司 = 直接空页。这里故意不报错也不越权(设计文档 §2.3)。
|
||||
if (!companyIdFilter.equals(currentUser.getCompanyId())) {
|
||||
return emptyListVo(currentUser, role, safePage, safeSize);
|
||||
}
|
||||
}
|
||||
if (isSuperAdmin) {
|
||||
if (!kw.isEmpty()) {
|
||||
query.like(AdminUserEntity::getUsername, kw);
|
||||
}
|
||||
if (filterCreatedBy != null) {
|
||||
query.eq(AdminUserEntity::getCreatedById, filterCreatedBy);
|
||||
}
|
||||
if (companyIdFilter != null) {
|
||||
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
|
||||
}
|
||||
} else {
|
||||
Long adminId = currentUser.getId();
|
||||
query.and(w -> w
|
||||
@@ -94,8 +108,9 @@ public class AdminUserService {
|
||||
List<AdminUserEntity> rows = adminUserMapper.selectList(query);
|
||||
|
||||
Map<Long, String> creatorMap = loadCreatorMap(rows);
|
||||
Map<Long, String> companyMap = loadCompanyNameMap(rows);
|
||||
|
||||
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap)).toList();
|
||||
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap, companyMap)).toList();
|
||||
List<AdminBriefVo> admins = "super_admin".equals(role)
|
||||
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.eq(AdminUserEntity::getRole, "admin")
|
||||
@@ -166,6 +181,7 @@ public class AdminUserService {
|
||||
entity.setIsAdmin(isAdmin);
|
||||
entity.setRole(wantRole);
|
||||
entity.setCreatedById(wantCreatedBy);
|
||||
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
|
||||
try {
|
||||
adminUserMapper.insert(entity);
|
||||
} catch (DuplicateKeyException e) {
|
||||
@@ -175,6 +191,68 @@ public class AdminUserService {
|
||||
return entity.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 建号落哪家公司(设计文档 §2.2,与 createdById 同构):超管可指定任意启用中的公司,
|
||||
* 其余角色只能落自己所属公司——显式传别家即 403,不静默改写。
|
||||
*
|
||||
* <p>永远返回一个具体值并写进实体:列 DEFAULT 1 只为发布期的旧 jar 存在(§8.2),
|
||||
* 新代码不靠它,否则第二家公司开通后每个未传公司的建号都会被静默塞进厦门米椿花。</p>
|
||||
*/
|
||||
private Long resolveTargetCompanyId(String operatorRole, AdminUserEntity operator, Long requestedCompanyId) {
|
||||
if (!"super_admin".equals(operatorRole)) {
|
||||
if (requestedCompanyId != null && !requestedCompanyId.equals(operator.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能在本公司名下创建账号");
|
||||
}
|
||||
return operator.getCompanyId();
|
||||
}
|
||||
if (requestedCompanyId == null) {
|
||||
return operator.getCompanyId();
|
||||
}
|
||||
companyService.requireActive(requestedCompanyId);
|
||||
return requestedCompanyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移人(设计文档 §2.2):返回要把账号移去的公司 id,返回 null 表示「这次没动公司」。
|
||||
*
|
||||
* <p>只有超管能移;传的正好是账号现属公司按"没动"处理(跟建号那条同构,别把幂等请求判成越权)。
|
||||
* 公司内 admin 传别家一律 403,不静默改写——静默改写会让操作者以为移成功了。</p>
|
||||
*/
|
||||
private Long resolveCompanyMove(String operatorRole, AdminUserEntity target, Long requestedCompanyId) {
|
||||
if (requestedCompanyId == null || requestedCompanyId.equals(target.getCompanyId())) {
|
||||
return null;
|
||||
}
|
||||
if (!"super_admin".equals(operatorRole)) {
|
||||
throw new BusinessException(403, "只有超级管理员可以把账号移到其他公司");
|
||||
}
|
||||
companyService.requireActive(requestedCompanyId);
|
||||
return requestedCompanyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移人之后的不变式:账号的 {@code created_by_id} 必须与它同一家公司,除非创建人是超管。
|
||||
*
|
||||
* <p>这条是二期不回改 77 处 {@code eq(getUserId, userId)} 过滤点的前提(§7.2):数据按账号归属,
|
||||
* 而公司内 admin 的可编辑范围判的是 {@code created_by_id}。一旦允许把账号移进一家它创建人不在的公司,
|
||||
* "同公司"和"同一人"两套口径就会交叉,越权只能逐出口重新补。</p>
|
||||
*/
|
||||
private void ensureCreatorSharesCompany(AdminUserEntity target, Long newCompanyId) {
|
||||
Long createdById = target.getCreatedById();
|
||||
if (createdById == null) {
|
||||
return;
|
||||
}
|
||||
AdminUserEntity creator = adminUserMapper.selectById(createdById);
|
||||
if (creator == null) {
|
||||
throw new BusinessException(403, "该账号的创建人已不存在,无法确认同公司,不能移入其他公司");
|
||||
}
|
||||
if ("super_admin".equals(creator.getRole())) {
|
||||
return;
|
||||
}
|
||||
if (!newCompanyId.equals(creator.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能把账号移到其创建人所在的公司");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateUser(AdminUserEntity currentUser, Long uid, AdminUserUpdateRequest request) {
|
||||
String role = adminAuthSupport.currentRole(currentUser);
|
||||
@@ -187,7 +265,8 @@ public class AdminUserService {
|
||||
|
||||
if ((password == null || password.isEmpty())
|
||||
&& (wantRole == null || wantRole.isEmpty())
|
||||
&& request.getColumnIds() == null) {
|
||||
&& request.getColumnIds() == null
|
||||
&& request.getCompanyId() == null) {
|
||||
throw new BusinessException("请提供要修改的内容");
|
||||
}
|
||||
|
||||
@@ -214,9 +293,19 @@ public class AdminUserService {
|
||||
}
|
||||
}
|
||||
|
||||
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
|
||||
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
|
||||
if (moveCompanyId != null) {
|
||||
ensureCreatorSharesCompany(target, moveCompanyId);
|
||||
}
|
||||
|
||||
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
|
||||
.eq(AdminUserEntity::getId, uid);
|
||||
boolean dirty = false;
|
||||
if (moveCompanyId != null) {
|
||||
update.set(AdminUserEntity::getCompanyId, moveCompanyId);
|
||||
dirty = true;
|
||||
}
|
||||
if (password != null && !password.isEmpty()) {
|
||||
if (password.length() < 6) {
|
||||
throw new BusinessException("密码至少6个字符");
|
||||
@@ -307,6 +396,31 @@ public class AdminUserService {
|
||||
log.info("[admin-user] 用户已删除 uid={} 级联清理密钥行={}", uid, secretRows);
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCompanyNameMap(List<AdminUserEntity> rows) {
|
||||
Set<Long> companyIds = new LinkedHashSet<>();
|
||||
for (AdminUserEntity r : rows) {
|
||||
if (r.getCompanyId() != null) {
|
||||
companyIds.add(r.getCompanyId());
|
||||
}
|
||||
}
|
||||
// 空页不去查公司表;一次批量查而不是每行一次(一行一次就是 N+1)
|
||||
return companyIds.isEmpty() ? Map.of() : companyService.namesByIds(companyIds);
|
||||
}
|
||||
|
||||
/** 公司内管理员筛了别家公司:返回一个"这一页什么都没有"的正常响应,不报错、也不去碰表。 */
|
||||
private AdminUserListVo emptyListVo(AdminUserEntity currentUser, String role, int page, int pageSize) {
|
||||
AdminUserListVo vo = new AdminUserListVo();
|
||||
vo.setItems(List.of());
|
||||
vo.setTotal(0L);
|
||||
vo.setPage(page);
|
||||
vo.setPageSize(pageSize);
|
||||
vo.setCurrentUserRole(role);
|
||||
vo.setCurrentUserId(currentUser.getId());
|
||||
vo.setCurrentUserUsername(currentUser.getUsername() == null ? "" : currentUser.getUsername());
|
||||
vo.setAdmins(List.of());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCreatorMap(List<AdminUserEntity> rows) {
|
||||
Set<Long> creatorIds = new LinkedHashSet<>();
|
||||
for (AdminUserEntity r : rows) {
|
||||
@@ -326,7 +440,8 @@ public class AdminUserService {
|
||||
return map;
|
||||
}
|
||||
|
||||
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap) {
|
||||
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap,
|
||||
Map<Long, String> companyMap) {
|
||||
AdminUserItemVo vo = new AdminUserItemVo();
|
||||
vo.setId(entity.getId());
|
||||
vo.setUsername(entity.getUsername());
|
||||
@@ -336,6 +451,10 @@ public class AdminUserService {
|
||||
// 不可变 Map(Map.of) 的 getOrDefault 不允许 null key:createdById 为 null 时直接空串。
|
||||
Long creatorId = entity.getCreatedById();
|
||||
vo.setCreatorUsername(creatorId == null ? "" : creatorMap.getOrDefault(creatorId, ""));
|
||||
Long companyId = entity.getCompanyId();
|
||||
vo.setCompanyId(companyId);
|
||||
// 账号挂着公司表里查不到的 id(脏数据/回滚残留)时留空串,前端显示 '-',整页不能因此 500
|
||||
vo.setCompanyName(companyId == null ? "" : companyMap.getOrDefault(companyId, ""));
|
||||
LocalDateTime createdAt = entity.getCreatedAt();
|
||||
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
|
||||
LocalDateTime updatedAt = entity.getUpdatedAt();
|
||||
|
||||
+8
@@ -21,4 +21,12 @@ public class LoginUserEntity {
|
||||
private String role;
|
||||
@TableField("created_by_id")
|
||||
private Long createdById;
|
||||
/**
|
||||
* 所属公司(V143 新增,company.id)。
|
||||
*
|
||||
* <p>本类与 {@code AdminUserEntity} 都映射 {@code users}:给 users 加列必须同改两处,
|
||||
* 漏一处就是半边链路(登录 vs 后台用户管理)读不到公司。由 UsersCompanyIdMappingTest 钉住。</p>
|
||||
*/
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@ public class LoginResultVo {
|
||||
private String username;
|
||||
private String role;
|
||||
private Boolean isAdmin;
|
||||
/** 所属公司 id(V143);账号没有公司归属时为 null。 */
|
||||
private Long companyId;
|
||||
/** 所属公司名,只显示用;查不到公司一律空串,绝不拿它当登录条件。 */
|
||||
private String companyName;
|
||||
private String deviceId;
|
||||
private String token;
|
||||
private Long expiresIn;
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -33,6 +34,7 @@ public class AuthService {
|
||||
private final JwtService jwtService;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final AuthProperties authProperties;
|
||||
private final CompanyService companyService;
|
||||
|
||||
/**
|
||||
* 登录失败计数与锁定(2026-09 全维度审查补):生产是公网域名,此前无任何失败限制
|
||||
@@ -180,6 +182,9 @@ public class AuthService {
|
||||
vo.setUsername(user.getUsername());
|
||||
vo.setRole(user.getRole());
|
||||
vo.setIsAdmin(isAdmin);
|
||||
// 公司身份只做显示:nameOrEmpty 查不到就空串,登录不因此被打回
|
||||
vo.setCompanyId(user.getCompanyId());
|
||||
vo.setCompanyName(companyService.nameOrEmpty(user.getCompanyId()));
|
||||
vo.setDeviceId(deviceId);
|
||||
vo.setToken(token);
|
||||
vo.setExpiresIn(jwtService.ttlSeconds());
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.nanri.aiimage.modules.company.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.vo.CompanyVo;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 公司目录(设计文档 §2.3)。可见范围与写入边界都在 CompanyService 里判,
|
||||
* 这里只负责"先解析出操作者"——鉴权必须在调 service 之前,不能靠 service 兜。
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin")
|
||||
@Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名与启停")
|
||||
public class CompanyController {
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final CompanyService companyService;
|
||||
|
||||
@GetMapping("/companies")
|
||||
@Operation(summary = "公司目录:超管看全部,公司内管理员只看到自己公司")
|
||||
public ApiResponse<List<CompanyVo>> listCompanies(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
List<CompanyVo> items = companyService.listVisible(operator).stream().map(CompanyVo::from).toList();
|
||||
return ApiResponse.success(items);
|
||||
}
|
||||
|
||||
@PostMapping("/companies")
|
||||
@Operation(summary = "新增公司(仅超级管理员)")
|
||||
public ApiResponse<CompanyVo> createCompany(HttpServletRequest request, @RequestBody CompanySaveRequest body) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("公司创建成功", CompanyVo.from(companyService.create(operator, body)));
|
||||
}
|
||||
|
||||
/** 没有 DELETE:账号挂着的公司删不掉,停用(status=0)就是终态。 */
|
||||
@PutMapping("/companies/{id}")
|
||||
@Operation(summary = "改名与启停(仅超级管理员)")
|
||||
public ApiResponse<CompanyVo> updateCompany(HttpServletRequest request,
|
||||
@PathVariable Long id,
|
||||
@RequestBody CompanySaveRequest body) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("更新成功", CompanyVo.from(companyService.update(operator, id, body)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.nanri.aiimage.modules.company.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface CompanyMapper extends BaseMapper<CompanyEntity> {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.nanri.aiimage.modules.company.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 新建/编辑公司的请求体(前端 companies-dto.ts#toCompanyPayload 的 camelCase 对齐)。
|
||||
*
|
||||
* <p>校验刻意放在 service 而不是 {@code @Valid} 注解上:一期只有这一个写入口,
|
||||
* 而"名称非空 + 长度 = 列宽"这两条要和 company 表定义同源维护。</p>
|
||||
*/
|
||||
@Data
|
||||
public class CompanySaveRequest {
|
||||
private String companyName;
|
||||
/** 1=启用 0=停用;null 按启用(与 company.status 的 DEFAULT 1 一致)。 */
|
||||
private Integer status;
|
||||
private String remark;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.nanri.aiimage.modules.company.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司(租户)主表实体(V143)。与紫鸟语义的 `biz_shop_manage`/`biz_publish_file.company_name` 无关。
|
||||
*/
|
||||
@Data
|
||||
@TableName("company")
|
||||
public class CompanyEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
@TableField("company_name")
|
||||
private String companyName;
|
||||
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */
|
||||
private Integer status;
|
||||
private String remark;
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
@TableField("updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.nanri.aiimage.modules.company.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 公司目录条目。线上字段名是 snake_case,与 admin-frontend-vue/src/api/companies-model.ts 的
|
||||
* 读法一致(实体是 camelCase,直接序列化实体前端解析不到 company_name)。
|
||||
*/
|
||||
@Data
|
||||
public class CompanyVo {
|
||||
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
private Long id;
|
||||
@JsonProperty("company_name")
|
||||
private String companyName;
|
||||
private Integer status;
|
||||
private String remark;
|
||||
@JsonProperty("created_at")
|
||||
private String createdAt;
|
||||
@JsonProperty("updated_at")
|
||||
private String updatedAt;
|
||||
|
||||
public static CompanyVo from(CompanyEntity entity) {
|
||||
CompanyVo vo = new CompanyVo();
|
||||
vo.setId(entity.getId());
|
||||
vo.setCompanyName(entity.getCompanyName());
|
||||
vo.setStatus(entity.getStatus());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
|
||||
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.nanri.aiimage.modules.company.service;
|
||||
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 「半套发布」哨兵(设计文档 §6.3):第二家公司已经开通,但 {@code users.company_id} 还带着
|
||||
* {@code DEFAULT 1}——启动期打 ERROR。
|
||||
*
|
||||
* <p>这个组合不会报错、不会丢数据,只会让每个没显式传公司的建号被静默塞进默认那家(§8.2 里
|
||||
* DEFAULT 存在的唯一理由已经过去了)。正因为它安静,所以由代码来喊,而不是靠人记得。</p>
|
||||
*
|
||||
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
|
||||
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class CompanyDefaultGuard {
|
||||
|
||||
/** 巡检签名用:出现即代表"多家公司已上线但 DEFAULT 未摘"。 */
|
||||
public static final String ALARM = "COMPANY_DEFAULT_STILL_PRESENT";
|
||||
|
||||
/** 巡检签名用:哨兵自己没跑成(例如没有 information_schema 读权限),不能当成"检查过了"。 */
|
||||
public static final String PROBE_FAILED = "COMPANY_DEFAULT_PROBE_FAILED";
|
||||
|
||||
private static final String COLUMN_DEFAULT_SQL = """
|
||||
SELECT COLUMN_DEFAULT FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'company_id'
|
||||
""";
|
||||
|
||||
private final CompanyMapper companyMapper;
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void checkOnStartup() {
|
||||
check();
|
||||
}
|
||||
|
||||
void check() {
|
||||
long companies;
|
||||
String columnDefault;
|
||||
try {
|
||||
companies = countCompanies();
|
||||
if (companies <= 1) {
|
||||
// 一期只有一家公司:DEFAULT 是混合版本窗口的兜底,此时它是正确的,不该喊
|
||||
return;
|
||||
}
|
||||
columnDefault = jdbcTemplate.queryForObject(COLUMN_DEFAULT_SQL, String.class);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[company] {} 哨兵没能确认 users.company_id 的 DEFAULT,请手工核查:{}",
|
||||
PROBE_FAILED, ex.getMessage());
|
||||
return;
|
||||
}
|
||||
if (columnDefault == null || columnDefault.isBlank()) {
|
||||
return;
|
||||
}
|
||||
log.error("[company] {} 已有 {} 家公司,但 users.company_id 仍带 DEFAULT={}:"
|
||||
+ "不传公司的建号会被静默塞进默认那家。请执行 "
|
||||
+ "ALTER TABLE users ALTER COLUMN company_id DROP DEFAULT",
|
||||
ALARM, companies, columnDefault);
|
||||
}
|
||||
|
||||
private long countCompanies() {
|
||||
Long count = companyMapper.selectCount(null);
|
||||
return count == null ? 0L : count;
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
package com.nanri.aiimage.modules.company.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
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.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CompanyService {
|
||||
|
||||
/** company.status:1=启用,0=停用(V143 列注释同口径)。 */
|
||||
public static final int STATUS_ACTIVE = 1;
|
||||
public static final int STATUS_DISABLED = 0;
|
||||
|
||||
/** 后台「公司管理」菜单的 column_key(V143 插入 columns 表那一行的值)。 */
|
||||
public static final String MENU_KEY = "admin_companies";
|
||||
|
||||
/** 列宽取自 V143:company_name varchar(128)、remark varchar(255)。超长先进校验,别让 MySQL 报 1406 变 500。 */
|
||||
private static final int NAME_MAX_LENGTH = 128;
|
||||
private static final int REMARK_MAX_LENGTH = 255;
|
||||
|
||||
private final CompanyMapper companyMapper;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
|
||||
/** 建号指定的公司必须真实存在且启用:否则账号挂在查不到的公司上,按公司筛选时整体失明。 */
|
||||
public CompanyEntity requireActive(Long companyId) {
|
||||
CompanyEntity company = companyMapper.selectById(companyId);
|
||||
if (company == null) {
|
||||
throw new BusinessException("公司不存在");
|
||||
}
|
||||
if (company.getStatus() == null || company.getStatus() != STATUS_ACTIVE) {
|
||||
throw new BusinessException("公司已停用");
|
||||
}
|
||||
return company;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司目录(设计文档 §2.3):超管看全部,公司内管理员只看自己那一家。
|
||||
*
|
||||
* <p>读口径必须和写口径一起收窄——只把写拦成超管、列表仍返回全部公司,等于把别家公司的
|
||||
* 名字泄露给本公司管理员。管理员没有公司归属时是拒绝,不是"那就不过滤"。</p>
|
||||
*/
|
||||
public List<CompanyEntity> listVisible(AdminUserEntity operator) {
|
||||
ensureCompanyMenu(operator);
|
||||
String role = adminAuthSupport.currentRole(operator);
|
||||
if (role == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
if ("super_admin".equals(role)) {
|
||||
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
|
||||
.orderByAsc(CompanyEntity::getId));
|
||||
}
|
||||
Long ownCompanyId = operator.getCompanyId();
|
||||
if (ownCompanyId == null) {
|
||||
throw new BusinessException(403, "当前账号没有所属公司,无法查看公司目录");
|
||||
}
|
||||
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
|
||||
.eq(CompanyEntity::getId, ownCompanyId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 id 批量补公司名(§2.3 账号列表、§2.4 登录态都用它,别写成逐行查的 N+1)。
|
||||
*
|
||||
* <p><b>这个方法不做权限判断</b>:它只是把调用方已经拿在手里的那些 id 换成名字,
|
||||
* 谁能看到哪些行由调用方的查询范围决定(同 {@code AdminUserService.loadCreatorMap} 的口径)。
|
||||
* 要给前端列公司目录请走 {@link #listVisible},它才带收窄与菜单闸门。</p>
|
||||
*/
|
||||
public Map<Long, String> namesByIds(Collection<Long> companyIds) {
|
||||
if (companyIds == null || companyIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<Long> ids = new ArrayList<>(new LinkedHashSet<>(companyIds));
|
||||
List<CompanyEntity> rows = companyMapper.selectList(
|
||||
new LambdaQueryWrapper<CompanyEntity>().in(CompanyEntity::getId, ids));
|
||||
Map<Long, String> nameById = new HashMap<>(rows.size() * 2);
|
||||
for (CompanyEntity row : rows) {
|
||||
nameById.put(row.getId(), row.getCompanyName() == null ? "" : row.getCompanyName());
|
||||
}
|
||||
return nameById;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个公司的显示名(设计文档 §2.4):查不到就回空串,绝不为难调用方。
|
||||
*
|
||||
* <p>每次登录都会走这里一次,所以它不是校验入口——用 {@link #requireActive} 的话,
|
||||
* 停用一家公司等于把它名下所有账号锁在门外。</p>
|
||||
*/
|
||||
public String nameOrEmpty(Long companyId) {
|
||||
if (companyId == null) {
|
||||
return "";
|
||||
}
|
||||
CompanyEntity company = companyMapper.selectById(companyId);
|
||||
if (company == null || company.getCompanyName() == null) {
|
||||
return "";
|
||||
}
|
||||
return company.getCompanyName();
|
||||
}
|
||||
|
||||
/** 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。 */
|
||||
public CompanyEntity create(AdminUserEntity operator, CompanySaveRequest request) {
|
||||
ensureSuperAdmin(operator);
|
||||
String companyName = requireValidName(request.getCompanyName());
|
||||
int status = resolveStatus(request.getStatus());
|
||||
String remark = normalizeRemark(request.getRemark());
|
||||
ensureNameAvailable(companyName, null);
|
||||
|
||||
CompanyEntity entity = new CompanyEntity();
|
||||
entity.setCompanyName(companyName);
|
||||
entity.setStatus(status);
|
||||
entity.setRemark(remark);
|
||||
companyMapper.insert(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 改名 + 启停一起改;不提供删除,账号挂着的公司删不掉。 */
|
||||
public CompanyEntity update(AdminUserEntity operator, Long id, CompanySaveRequest request) {
|
||||
ensureSuperAdmin(operator);
|
||||
CompanyEntity company = companyMapper.selectById(id);
|
||||
if (company == null) {
|
||||
throw new BusinessException("公司不存在");
|
||||
}
|
||||
String companyName = requireValidName(request.getCompanyName());
|
||||
int status = resolveStatus(request.getStatus());
|
||||
String remark = normalizeRemark(request.getRemark());
|
||||
// 排除自己:只改备注时名字没变,不排除就会把合法编辑判成重名
|
||||
ensureNameAvailable(companyName, id);
|
||||
|
||||
company.setCompanyName(companyName);
|
||||
company.setStatus(status);
|
||||
company.setRemark(remark);
|
||||
companyMapper.updateById(company);
|
||||
return company;
|
||||
}
|
||||
|
||||
/** uk_company_name 只能兜底并发,不能当校验用:撞索引抛的是"用户名已存在"这类看不懂的文案。 */
|
||||
private void ensureNameAvailable(String companyName, Long excludeId) {
|
||||
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<CompanyEntity>()
|
||||
.eq(CompanyEntity::getCompanyName, companyName);
|
||||
if (excludeId != null) {
|
||||
query.ne(CompanyEntity::getId, excludeId);
|
||||
}
|
||||
Long matched = companyMapper.selectCount(query);
|
||||
if (matched != null && matched > 0) {
|
||||
throw new BusinessException("公司名称已存在");
|
||||
}
|
||||
}
|
||||
|
||||
private String requireValidName(String rawCompanyName) {
|
||||
String companyName = rawCompanyName == null ? "" : rawCompanyName.trim();
|
||||
if (companyName.isEmpty()) {
|
||||
throw new BusinessException("公司名称不能为空");
|
||||
}
|
||||
if (companyName.length() > NAME_MAX_LENGTH) {
|
||||
throw new BusinessException("公司名称长度不能超过 " + NAME_MAX_LENGTH + " 个字符");
|
||||
}
|
||||
return companyName;
|
||||
}
|
||||
|
||||
private int resolveStatus(Integer status) {
|
||||
if (status == null) {
|
||||
return STATUS_ACTIVE;
|
||||
}
|
||||
if (status != STATUS_ACTIVE && status != STATUS_DISABLED) {
|
||||
throw new BusinessException("公司状态只能是 1(启用)或 0(停用)");
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
/** 空备注归一成 null:列本身可空,写空串会让后台表格里"无"和"空"两种值混在一起。 */
|
||||
private String normalizeRemark(String rawRemark) {
|
||||
if (rawRemark == null) {
|
||||
return null;
|
||||
}
|
||||
String remark = rawRemark.trim();
|
||||
if (remark.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (remark.length() > REMARK_MAX_LENGTH) {
|
||||
throw new BusinessException("备注长度不能超过 " + REMARK_MAX_LENGTH + " 个字符");
|
||||
}
|
||||
return remark;
|
||||
}
|
||||
|
||||
private void ensureCompanyMenu(AdminUserEntity operator) {
|
||||
if (!permissionMenuService.hasAnyAdminMenu(operator, List.of(MENU_KEY))) {
|
||||
throw new BusinessException(403, "无权访问公司管理模块");
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureSuperAdmin(AdminUserEntity operator) {
|
||||
if (!"super_admin".equals(adminAuthSupport.currentRole(operator))) {
|
||||
throw new BusinessException(403, "只有超级管理员可以新增或修改公司");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user