feat(admin): 账号域三页平台分侧+京东上架额度收口(V206/V207)

This commit is contained in:
2026-11-17 03:29:33 +08:00
parent 764eeb2914
commit 5c7a310ee7
58 changed files with 2796 additions and 1455 deletions
@@ -48,6 +48,15 @@ public class AdminUserEntity {
*/
@TableField(value = "updated_at", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
private LocalDateTime updatedAt;
@TableField("jd_publish_quota")
private Integer jdPublishQuota;
/**
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
* 用户管理页的显示与筛选,不影响登录与功能权限。存量 DEFAULT 'amazon',京东侧
* 数据由使用者在编辑弹窗里翻档。
*/
@TableField("platform")
private String platform;
private String machine;
/**
* 会话世代(V172 新增):登录/登出各 +1,JWT 的 epoch claim 必须与它相等。
@@ -22,6 +22,11 @@ public class ShopManageGroupEntity {
private Long userId;
@TableField("created_by_id")
private Long createdById;
/**
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
* 分组管理页的显示与筛选;存量 DEFAULT 'amazon',京东侧由使用者在编辑弹窗里翻档。
*/
private String platform;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,51 @@
package com.nanri.aiimage.common.service;
import com.nanri.aiimage.common.exception.BusinessException;
/**
* 账号域「所属平台」(V206)取值口径的唯一出处。取值字面量与 admin-frontend-vue 的
* {@code PlatformTabId} 同源:{@code amazon | jd}。
*
* <p>语义边界:平台只作用于后管「用户管理 / 分组管理 / 公司管理」三个页面的显示与筛选,
* 不影响登录、用户端功能、任务权限与 DataReadScope。存量行 DEFAULT 'amazon',京东侧数据
* 由使用者在编辑弹窗里自己翻档(不做数据驱动的自动归类)。</p>
*/
public final class AdminPlatformScope {
public static final String AMAZON = "amazon";
public static final String JD = "jd";
private AdminPlatformScope() {
}
/**
* 新建侧归一:null/空白按 {@code amazon}(与列 DEFAULT 同口径);给了就只认合法值,
* 非法值 400——静默归一会把"手滑打错"变成"悄悄归进亚马逊侧"。
*/
public static String normalizeOrCreate(String raw) {
String value = raw == null ? "" : raw.trim();
if (value.isEmpty()) {
return AMAZON;
}
return requireLegal(value);
}
/**
* 更新侧归一:null/空白=本次不动(返回 null,调用方跳过该列);给了就只认合法值,
* 非法值 400。{@code PUT} 只带部分字段的既有形状(如 setUserDisabled)不会把平台冲掉。
*/
public static String normalizeOrNull(String raw) {
String value = raw == null ? "" : raw.trim();
if (value.isEmpty()) {
return null;
}
return requireLegal(value);
}
private static String requireLegal(String value) {
if (AMAZON.equals(value) || JD.equals(value)) {
return value;
}
throw new BusinessException(400, "所属平台只支持 amazon 或 jd");
}
}
@@ -41,11 +41,13 @@ public class AdminUserController {
@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 = "company_id", required = false) Long companyId) {
@RequestParam(name = "company_id", required = false) Long companyId,
@RequestParam(name = "platform", required = false) String platform) {
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, companyId);
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role,
companyId, platform);
return ApiResponse.success(vo);
}
@@ -11,6 +11,10 @@ public class AdminUserCreateRequest {
private String role;
private Long createdById;
private Long companyId;
/**
* 所属平台(V206):amazon|jd;null/空白按 'amazon'(与列 DEFAULT 同口径)。
*/
private String platform;
/**
* 到期时间(V146):支持 yyyy-MM-dd / yyyy-MM-dd HH:mm / yyyy-MM-dd HH:mm:ss。
* 空/不传 = 永不过期;super_admin 目标不存在本字段语义(超管建不出超管)。
@@ -6,6 +6,12 @@ import java.util.List;
@Data
public class AdminUserUpdateRequest {
private Integer jdPublishQuota;
/**
* 所属平台(V206):null=不动;给了就只认 amazon|jd(非法值 400)。只改后管
* 用户管理页的归属展示,不影响登录与功能权限。
*/
private String platform;
private String password;
private String role;
private List<Long> columnIds;
@@ -5,6 +5,11 @@ import lombok.Data;
@Data
public class AdminUserItemVo {
@JsonProperty("jd_publish_quota")
private Integer jdPublishQuota;
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
@JsonProperty("platform")
private String platform;
private Long id;
private String username;
@JsonProperty("is_admin")
@@ -10,6 +10,7 @@ import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminPlatformScope;
import com.nanri.aiimage.modules.admin.util.PinyinAbbrUtil;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
@@ -54,6 +55,17 @@ public class AdminUserService {
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
String username, Long createdById, String roleFilter,
Long companyIdFilter) {
return listUsers(currentUser, page, pageSize, username, createdById, roleFilter, companyIdFilter, null);
}
/**
* 带平台过滤的分页用户列表(V206):platformFilter 非空白时只返回该平台的账号
* (amazon|jd,非法值 400),后管「用户管理」页按当前平台 tab 传参;null/空白=不过滤,
* 用户选择器等旧调用方口径不变。
*/
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
String username, Long createdById, String roleFilter,
Long companyIdFilter, String platformFilter) {
String role = adminAuthSupport.currentRole(currentUser);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
@@ -71,6 +83,11 @@ public class AdminUserService {
Long filterCreatedBy = "super_admin".equals(role) ? createdById : null;
LambdaQueryWrapper<AdminUserEntity> query = new LambdaQueryWrapper<>();
String platformFilterValue = AdminPlatformScope.normalizeOrNull(platformFilter);
if (platformFilterValue != null) {
// 平台过滤对三档可见范围(超管/公司超管/组长)统一生效:count 与取页共用同一 wrapper
query.eq(AdminUserEntity::getPlatform, platformFilterValue);
}
String roleFilterValue = roleFilter == null ? "" : roleFilter.trim();
if (!roleFilterValue.isEmpty()) {
query.eq(AdminUserEntity::getRole, roleFilterValue);
@@ -211,6 +228,7 @@ public class AdminUserService {
entity.setRole(wantRole);
entity.setCreatedById(wantCreatedBy);
entity.setCompanyId(targetCompanyId);
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
entity.setExpiresAt(parseExpiresAt(request.getExpiresAt()));
try {
adminUserMapper.insert(entity);
@@ -379,13 +397,18 @@ public class AdminUserService {
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
String password = request.getPassword();
String wantRole = request.getRole() == null ? null : request.getRole().trim();
// 平台只在显式给出时落(null/空白=不动):PUT 只带 disabled 的既有形状不能把平台冲掉;
// 非法值在这里直接 400,不等后面的 dirty 判定
String platformUpdate = AdminPlatformScope.normalizeOrNull(request.getPlatform());
if ((password == null || password.isEmpty())
&& (wantRole == null || wantRole.isEmpty())
&& request.getColumnIds() == null
&& request.getCompanyId() == null
&& request.getExpiresAt() == null
&& request.getDisabled() == null) {
&& request.getDisabled() == null
&& request.getJdPublishQuota() == null
&& platformUpdate == null) {
throw new BusinessException("请提供要修改的内容");
}
// 不许停自己:现有的角色闸(admin 只动自建普通账号 / 公司超管与超管目标互斥)已经
@@ -440,6 +463,18 @@ public class AdminUserService {
throw new BusinessException(400, NORMAL_ACCOUNT_EXPIRY_MESSAGE);
}
if (request.getJdPublishQuota() != null) {
if (!"super_admin".equals(role) && !"company_super_admin".equals(role)) {
throw new BusinessException(403, "无权修改京东上架额度");
}
if (!"admin".equals(roleAfter) && !"company_super_admin".equals(roleAfter)) {
throw new BusinessException(400, "只能为管理员设置京东上架额度");
}
if (request.getJdPublishQuota() < 0) {
throw new BusinessException(400, "京东上架额度不能为负数");
}
}
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
if (moveCompanyId != null) {
@@ -449,6 +484,14 @@ public class AdminUserService {
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
.eq(AdminUserEntity::getId, uid);
boolean dirty = false;
if (request.getJdPublishQuota() != null) {
update.set(AdminUserEntity::getJdPublishQuota, request.getJdPublishQuota());
dirty = true;
}
if (platformUpdate != null) {
update.set(AdminUserEntity::getPlatform, platformUpdate);
dirty = true;
}
if (moveCompanyId != null) {
update.set(AdminUserEntity::getCompanyId, moveCompanyId);
dirty = true;
@@ -635,11 +678,13 @@ public class AdminUserService {
vo.setCompanyId(companyId);
// 账号挂着公司表里查不到的 id(脏数据/回滚残留)时留空串,前端显示 '-',整页不能因此 500
vo.setCompanyName(companyId == null ? "" : companyMap.getOrDefault(companyId, ""));
vo.setPlatform(entity.getPlatform());
LocalDateTime createdAt = entity.getCreatedAt();
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
LocalDateTime updatedAt = entity.getUpdatedAt();
vo.setUpdatedAt(updatedAt == null ? "" : updatedAt.format(CREATED_AT_FORMATTER));
// 到期时间:null(永不过期)与空字符串在列表里都要有明确渲染,前端按空串判"永不过期"
vo.setJdPublishQuota(entity.getJdPublishQuota());
vo.setExpiresAt(entity.getExpiresAt() == null ? "" : entity.getExpiresAt().format(CREATED_AT_FORMATTER));
// 停用时刻(V155):null=未停用,前端按此渲染「已停用」徽标
vo.setDisabledAt(entity.getDisabledAt() == null ? null : entity.getDisabledAt().format(CREATED_AT_FORMATTER));
@@ -43,6 +43,12 @@ public class LoginUserEntity {
*/
@TableField("disabled_at")
private LocalDateTime disabledAt;
/**
* 所属平台(V206 新增):与 {@code AdminUserEntity.platform} 同列,amazon|jd。
* 改一处必须同改两处(UsersCompanyIdMappingTest 钉住)。
*/
@TableField("platform")
private String platform;
/**
* 会话世代(V172 新增):登录/登出各 +1,JWT 的 epoch claim 必须与它相等。
* 与 {@code AdminUserEntity.sessionEpoch} 同列,改一处必须同改两处。
@@ -7,6 +7,7 @@ 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.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
@@ -16,6 +17,7 @@ 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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@@ -35,9 +37,12 @@ public class CompanyController {
@GetMapping("/companies")
@Operation(summary = "公司目录:仅超级管理员可读,非超管一律 403")
public ApiResponse<List<CompanyVo>> listCompanies(HttpServletRequest request) {
public ApiResponse<List<CompanyVo>> listCompanies(
HttpServletRequest request,
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤")
@RequestParam(name = "platform", required = false) String platform) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
List<CompanyVo> items = companyService.listVisible(operator).stream().map(CompanyVo::from).toList();
List<CompanyVo> items = companyService.listVisible(operator, platform).stream().map(CompanyVo::from).toList();
return ApiResponse.success(items);
}
@@ -14,4 +14,8 @@ public class CompanySaveRequest {
/** 1=启用 0=停用;null 按启用(与 company.status 的 DEFAULT 1 一致)。 */
private Integer status;
private String remark;
/**
* 所属平台(V206):新建 null/空白按 'amazon';编辑 null=不动,给了就只认 amazon|jd。
*/
private String platform;
}
@@ -22,6 +22,11 @@ public class CompanyEntity {
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */
private Integer status;
private String remark;
/**
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
* 公司管理页的显示与筛选;存量 DEFAULT 'amazon',京东侧由使用者在编辑弹窗里翻档。
*/
private String platform;
@TableField("created_at")
private LocalDateTime createdAt;
@TableField("updated_at")
@@ -20,6 +20,9 @@ public class CompanyVo {
private String companyName;
private Integer status;
private String remark;
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
@JsonProperty("platform")
private String platform;
@JsonProperty("created_at")
private String createdAt;
@JsonProperty("updated_at")
@@ -31,6 +34,7 @@ public class CompanyVo {
vo.setCompanyName(entity.getCompanyName());
vo.setStatus(entity.getStatus());
vo.setRemark(entity.getRemark());
vo.setPlatform(entity.getPlatform());
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
return vo;
@@ -5,6 +5,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.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.entity.CompanyEntity;
@@ -59,6 +60,14 @@ public class CompanyService {
* 角色不会被"忘了授权"打穿,所以这里用 {@link #ensureSuperAdmin} 与写入口共用同一个出口。</p>
*/
public List<CompanyEntity> listVisible(AdminUserEntity operator) {
return listVisible(operator, null);
}
/**
* 带平台过滤的公司目录(V206):platform 非空白时只返回该平台的公司(amazon|jd,非法值 400),
* 后管「公司管理」页按当前平台 tab 传参;null/空白=不过滤,旧调用方口径不变。
*/
public List<CompanyEntity> listVisible(AdminUserEntity operator, String platform) {
String role = adminAuthSupport.currentRole(operator);
if (role == null) {
throw new BusinessException(403, "需要管理员权限");
@@ -66,8 +75,13 @@ public class CompanyService {
// 读写都只超管(spec §2 的 A 类):判角色、不判菜单授权——
// 12:3x 已经证明"把可见性挂在 user_column_permission 上"会因一笔授权没发而全员 403。
ensureSuperAdmin(operator);
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
.orderByAsc(CompanyEntity::getId));
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<>();
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
if (platformValue != null) {
query.eq(CompanyEntity::getPlatform, platformValue);
}
query.orderByAsc(CompanyEntity::getId);
return companyMapper.selectList(query);
}
/**
@@ -127,6 +141,7 @@ public class CompanyService {
entity.setCompanyName(companyName);
entity.setStatus(status);
entity.setRemark(remark);
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
companyMapper.insert(entity);
permissionMenuService.copyTreeFromTemplate(entity.getId(), operator.getCompanyId());
return entity;
@@ -142,12 +157,17 @@ public class CompanyService {
String companyName = requireValidName(request.getCompanyName());
int status = resolveStatus(request.getStatus());
String remark = normalizeRemark(request.getRemark());
// 平台只在显式给出时落(null/空白=不动),与 users 的 PUT 同口径
String platform = AdminPlatformScope.normalizeOrNull(request.getPlatform());
// 排除自己:只改备注时名字没变,不排除就会把合法编辑判成重名
ensureNameAvailable(companyName, id);
company.setCompanyName(companyName);
company.setStatus(status);
company.setRemark(remark);
if (platform != null) {
company.setPlatform(platform);
}
companyMapper.updateById(company);
return company;
}
@@ -8,14 +8,13 @@ import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 商品上架配额(2026-11-15 用户口径「限制管理员上架的商品数量,包括管理员下的员工
* 总和不能超过配置的最大值」,默认 5000,{@code aiimage.jd.max-products-per-admin})。
* 总和不能超过管理员账号设置的最大值」,默认 5000。
*
* <p>计数口径=团队在京东数据库({@code biz_jd_product})占有的行数:上架功能的数据源
* 就是京东数据库,团队占有量即「可上架量」的上游闸。归属列 {@code user_id}=任务 owner
@@ -38,9 +37,7 @@ public class JdPublishQuotaService {
private final UserDataScopeSupport userDataScopeSupport;
private final JdProductMapper jdProductMapper;
/** 出厂默认与 application.yml 的 aiimage.jd.max-products-per-admin 逐字相等(棘轮);包级可见供同包测试直设。 */
@Value("${aiimage.jd.max-products-per-admin:5000}")
long maxProductsPerAdmin = 5000L;
private static final long DEFAULT_QUOTA = 5000L;
/** 配额只读快照:used=团队已占有行数,limit=配置上限(≤0=不限)。 */
public record QuotaSnapshot(long used, long limit) {
@@ -51,9 +48,13 @@ public class JdPublishQuotaService {
/** 团队已占用与上限的只读快照;uid 集为空(无主管且无 id)按 used=0 处理,不进 SQL。 */
public QuotaSnapshot quotaOf(AdminUserEntity operator) {
List<Long> userIds = teamUserIds(operator);
AdminUserEntity anchor = operator == null ? null : anchorOf(operator);
List<Long> userIds = anchor == null || anchor.getId() == null ? List.of()
: userDataScopeSupport.resolveVisibleUserIds(anchor);
long used = userIds.isEmpty() ? 0L : jdProductMapper.countByUserIds(userIds);
return new QuotaSnapshot(used, maxProductsPerAdmin);
long limit = anchor == null || anchor.getJdPublishQuota() == null
? DEFAULT_QUOTA : anchor.getJdPublishQuota();
return new QuotaSnapshot(used, limit);
}
/**
@@ -61,14 +62,14 @@ public class JdPublishQuotaService {
* 上限 ≤0(0=不限)放行;{@code additionalCount} 为负按 0 处理(本闸只判限不预占)。
*/
public void assertWithinQuota(AdminUserEntity operator, int additionalCount) {
if (maxProductsPerAdmin <= 0) {
return;
}
if (operator != null && DeviceSessionPolicy.isSuperAdmin(
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) {
return;
}
QuotaSnapshot snapshot = quotaOf(operator);
if (snapshot.unlimited()) {
return;
}
long requested = Math.max(0, additionalCount);
if (snapshot.used() + requested > snapshot.limit()) {
log.warn("[jd-publish] 商品上架配额不足 operatorId={} used={} requested={} limit={}",
@@ -80,14 +81,6 @@ public class JdPublishQuotaService {
}
}
/** 普通账号锚定到其所属管理员(created_by_id);管理员/公司超管锚自己;无 id 返回空集。 */
private List<Long> teamUserIds(AdminUserEntity operator) {
if (operator == null || operator.getId() == null) {
return List.of();
}
return userDataScopeSupport.resolveVisibleUserIds(anchorOf(operator));
}
private AdminUserEntity anchorOf(AdminUserEntity operator) {
// resolveRole 对普通账号返回 null(角色域只有 super_admin/company_super_admin/admin/null)
if (DeviceSessionPolicy.resolveRole(
@@ -131,15 +131,16 @@ public class ShopManageController {
public ApiResponse<java.util.List<ShopManageGroupItemVo>> listGroups(
HttpServletRequest request,
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤") @RequestParam(required = false) String platform) {
AdminUserEntity operator = requireOperator(request);
if (isSuper(operator)) {
// 公司 tab 只收窄可见集;list() 内按组长两列(created_by_id / user_id)认归属。
List<Long> memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null);
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds));
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds, platform));
}
Long operatorId = operator.getId();
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false));
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false, platform));
}
@PostMapping("/groups")
@@ -20,4 +20,7 @@ public class ShopManageGroupCreateRequest {
@Schema(description = "创建人用户ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "创建人不能为空")
private Long createdById;
@Schema(description = "所属平台(V206):amazon|jd;空白按 'amazon'")
private String platform;
}
@@ -15,4 +15,7 @@ public class ShopManageGroupUpdateRequest {
@Schema(description = "组员用户ID列表")
private List<Long> memberUserIds;
@Schema(description = "所属平台(V206):null=不动;给了就只认 amazon|jd")
private String platform;
}
@@ -9,6 +9,8 @@ import java.util.List;
public class ShopManageGroupItemVo {
private Long id;
private String groupName;
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
private String platform;
private Long leaderUserId;
private String leaderUsername;
private List<Long> memberUserIds;
@@ -8,6 +8,7 @@ import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
import com.nanri.aiimage.modules.shopkey.spi.GroupDeletionGuardPort;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminPlatformScope;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
@@ -52,8 +53,20 @@ public class ShopManageGroupService {
}
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds) {
return list(createdById, companyMemberIds, null);
}
/**
* 带平台过滤的分组列表(V206):platform 非空白时只返回该平台的分组(amazon|jd,非法值 400),
* 后管「分组管理」页按当前平台 tab 传参;null/空白=不过滤,旧调用方口径不变。
*/
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds, String platform) {
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
.orderByAsc(ShopManageGroupEntity::getId);
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
if (platformValue != null) {
qw.eq(ShopManageGroupEntity::getPlatform, platformValue);
}
if (createdById != null && createdById > 0) {
// 这两条原本是平铺的 .eq(...).or(...):MP 的 normal 段按顺序拼 AND/OR,MySQL 里 AND 优先,
// 外面再叠一条公司条件时 created_by_id = ? 那半边会整块逃出筛选(多放行、不报错)⇒ 必须收进 and()。
@@ -77,16 +90,26 @@ public class ShopManageGroupService {
}
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin) {
return listAccessible(operatorId, superAdmin, null);
}
/** 带平台过滤的可见分组列表(V206):platform 非空白时只返回该平台的分组,null/空白=不过滤。 */
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin, String platform) {
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
if (superAdmin) {
return list();
return list(null, null, platformValue);
}
Set<Long> groupIds = listAccessibleGroupIds(operatorId, false);
if (groupIds.isEmpty()) {
return List.of();
}
return toVoList(groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
.in(ShopManageGroupEntity::getId, groupIds)
.orderByAsc(ShopManageGroupEntity::getId)));
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
.in(ShopManageGroupEntity::getId, groupIds);
if (platformValue != null) {
qw.eq(ShopManageGroupEntity::getPlatform, platformValue);
}
qw.orderByAsc(ShopManageGroupEntity::getId);
return toVoList(groupMapper.selectList(qw));
}
public Set<Long> listAccessibleGroupIds(Long operatorId, boolean superAdmin) {
@@ -179,6 +202,7 @@ public class ShopManageGroupService {
entity.setGroupName(groupName);
entity.setCreatedById(createdById);
entity.setCompanyId(companyId);
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
groupMapper.insert(entity);
replaceMembers(entity.getId(), request.getMemberUserIds(), createdById, operatorId, superAdmin);
return toVo(getById(entity.getId()));
@@ -197,6 +221,11 @@ public class ShopManageGroupService {
entity.setGroupName(groupName);
entity.setCompanyId(companyId);
// 平台只在显式给出时落(null/空白=不动),与 users/company 的 PUT 同口径
String platformUpdate = AdminPlatformScope.normalizeOrNull(request.getPlatform());
if (platformUpdate != null) {
entity.setPlatform(platformUpdate);
}
groupMapper.updateById(entity);
// 组长取 resolveGroupLeaderUserId 而不是 created_by_id:生产有 2 个分组只有 user_id
// (见 listCompanyGroupIds 的注释),只认 created_by_id 会让那 2 个分组绕过组员的公司校验。
@@ -488,6 +517,7 @@ public class ShopManageGroupService {
ShopManageGroupItemVo vo = new ShopManageGroupItemVo();
vo.setId(entity.getId());
vo.setGroupName(entity.getGroupName());
vo.setPlatform(entity.getPlatform());
Long leaderUserId = resolveGroupLeaderUserId(entity);
vo.setLeaderUserId(leaderUserId);
AdminUserEntity leaderUser = leaderUserId == null ? null : userById.get(leaderUserId);
@@ -177,11 +177,6 @@ aiimage:
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN,
# 防脏回传把整批撑爆。显式写在这里,不许只活在代码默认值里。
sku-max-per-product: ${AIIMAGE_JD_SKU_MAX_PER_PRODUCT:200}
# 商品上架配额(2026-11-15 用户口径):单个管理员(含其名下员工合计;公司超管按
# 全公司合计)可上架的商品数上限,默认 5000;0=不限。计数源=biz_jd_product 按
# owner uid 集计行数(上架功能的数据源就是京东数据库);站点超管不限额。
# 校验出口=JdPublishQuotaService,商品上架建单入口落地时调用。
max-products-per-admin: ${AIIMAGE_JD_MAX_PRODUCTS_PER_ADMIN:5000}
# 设备日志对象存储:主机B 独立 MinIO(与业务 OSS 隔离,日志只保留 7 天)。
# endpoint 未配置时日志上报/管理接口不可用(宁可失败也不静默落到业务桶)。
# 桶的 7 天过期规则由运维用 mc 配置(与 retention-days 口径一致)。
@@ -0,0 +1,82 @@
-- =============================================================
-- 迁移 V206__admin_account_platform
-- 需求:2026-11-17 用户口径「用户管理/分组管理/公司管理亚马逊这边也要有」+
-- 「京东是也有,但是数据都是新的,别把亚马逊的带过来」——后管三类账号域数据
-- (users / company / biz_shop_manage_group)从全系统共用一份改成按平台(amazon/jd)
-- 各管各的:后管在哪个平台 tab 下就只看/管那个平台的账号、分组、公司。
-- 前版:V153(分组表挂 company_id)→ V202 待改号件(jd_publish_quota,另一窗在飞,见下)
--
-- 1. 变更目的:三张表各加一个「所属平台」标记列。存量一律 DEFAULT 'amazon'(亚马逊业务
-- 一直在用这套账号;京东侧新录的数据由使用者在编辑弹窗里自己翻成 'jd',本迁移不做
-- 数据驱动的自动归类——按引用猜归属会错分)。平台语义只作用于后管三个管理页的
-- 显示与筛选:登录、用户端功能、任务权限、DataReadScope 全部不动。
--
-- 2. 号段协调(重要,写给并行的 jd_publish_quota 窗):V202 号已随 764eeb29 永久退役
-- (RETIRED_HOLES),那个待入库的 V202__users_jd_publish_quota.sql 按 AGENTS.md 铁律 33
-- 必须改号 V206+ 才能入库;本笔先占 V206,改号件请取 V207 及以上——若改号撞到 V206
-- 会触发 MigrationInventoryTest 的重复版本断言(同 V148 先例:宁可测试红,不把撞号
-- 留到 Flyway 运行期)。
--
-- 3. 口径:
-- users + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
-- company + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
-- biz_shop_manage_group + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
-- 取值字面量与 admin-frontend-vue 的 PlatformTabId 同源:'amazon' | 'jd'。
-- users 是双映射表(AdminUserEntity + LoginUserEntity),实体两侧同加,UsersCompanyIdMappingTest 钉住。
--
-- 4. 可重跑性:三条列 DDL 都先查 information_schema 再 PREPARE,重跑逐条 no-op;
-- ADD COLUMN ... DEFAULT 走 ALGORITHM = INSTANT(users 行数大,不锁表)。
--
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
-- ALTER TABLE users DROP COLUMN platform;
-- ALTER TABLE company DROP COLUMN platform;
-- ALTER TABLE biz_shop_manage_group DROP COLUMN platform;
-- (jar 必须先回到"无平台维度"的那版,否则实体按不存在的列 select 会 500。)
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. users:所属平台(双映射实体同改) ----------
SET @v206_users_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'users' AND COLUMN_NAME = 'platform');
SET @sql := IF(@v206_users_col = 0,
'ALTER TABLE `users` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管用户管理页的显示与筛选'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. company:所属平台 ----------
SET @v206_company_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'company' AND COLUMN_NAME = 'platform');
SET @sql := IF(@v206_company_col = 0,
'ALTER TABLE `company` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管公司管理页的显示与筛选'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 3. biz_shop_manage_group:所属平台 ----------
SET @v206_group_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_manage_group' AND COLUMN_NAME = 'platform');
SET @sql := IF(@v206_group_col = 0,
'ALTER TABLE `biz_shop_manage_group` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管分组管理页的显示与筛选'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- =============================================================
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
--
-- SHOW COLUMNS FROM users LIKE 'platform';
-- SHOW COLUMNS FROM company LIKE 'platform';
-- SHOW COLUMNS FROM biz_shop_manage_group LIKE 'platform';
-- -> 三条都期望 Null = NO、Default = 'amazon'、Type = varchar(16)。
--
-- SELECT platform, COUNT(*) FROM users GROUP BY platform;
-- -> 迁移后只有 'amazon' 一档(存量全归亚马逊,京东侧由使用者在界面翻档)。
-- =============================================================
@@ -0,0 +1,5 @@
-- 迁移 V207:逐管理员设置京东上架额度;0 表示不限。已有账号保留原默认额度。
-- 号段协调(2026-11-17):原 V202 号已被 V203/V204/V205 按序越过(764eeb29 把 202 登记
-- RETIRED_HOLES),按其明文要求改号入库;V206 被同窗 admin_account_platform(三表平台列)占用,
-- 故本件取 V207。改号只动文件名与头注释,ALTER 语句一个字节未变(可重入:加列前查重)。
ALTER TABLE users ADD COLUMN jd_publish_quota INT NOT NULL DEFAULT 5000;
@@ -93,7 +93,9 @@ class MigrationInventoryTest {
* V204(aff6c88a)与 V205(任务证据下线,71b19e4f)随 2026-11-17 发版窗越过 202 落库。
* Flyway 未开 out-of-order ⇒ 该路径入库前必须把文件改名到 V206+(RELEASE_LEDGER 2026-11-16
* 22:2x 段的顺序债登记);把新迁移写回 202 会让已过 205 的环境启动期报
* "resolved migration not applied" 失败。与 132/133 同属"只能永久保留、不能回填"。</p>
* "resolved migration not applied" 失败。与 132/133 同属"只能永久保留、不能回填"。
* 2026-11-17 已改号 {@code V207__users_jd_publish_quota.sql} 入库(V206 被同窗
* admin_account_platform 三表平台列占用,account-platform 提交);202 号自此彻底空置。</p>
*
* <p>共同后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。</p>
*/
@@ -0,0 +1,544 @@
package com.nanri.aiimage.modules.admin.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.AdminPlatformScope;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
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.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
import com.nanri.aiimage.modules.shopkey.mapper.SkipPriceAsinMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
import com.nanri.aiimage.modules.shopkey.spi.GroupDeletionGuardPort;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
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.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 账号域「所属平台」(V206,2026-11-17 用户口径「亚马逊这边也要有;京东的数据是新的,
* 别把亚马逊的带过来」):users / company / biz_shop_manage_group 三张表各带 platform 列
* (amazon|jd),后管三个管理页按平台 tab 过滤、新建默认当前平台、编辑只显式翻档。
*
* <p>判据钉四条形状:①列表过滤真的进 SQL 条件(打在 wrapper 参数上,不是打在返回值——
* 返回空也可能是别的条件写反);②新建缺省落 'amazon'(与列 DEFAULT 同口径);③编辑只在
* 显式给出时落(PUT 只带 disabled 的既有形状不得把平台冲掉);④非法值 400,不许静默归档。</p>
*/
class AdminAccountPlatformScopeTest {
private AdminUserMapper userMapper;
private AdminAuthSupport authSupport;
private PermissionMenuService permissionService;
private CompanyService companyService;
private AdminUserService userService;
private CompanyMapper companyMapper;
private CompanyService standaloneCompanyService;
private ShopManageGroupMapper groupMapper;
private ShopManageGroupMemberMapper groupMemberMapper;
private CompanyScopeSupport companyScope;
private AdminUserMapper groupAdminUserMapper;
private ShopManageGroupService groupService;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class);
userMapper = mock(AdminUserMapper.class);
authSupport = mock(AdminAuthSupport.class);
permissionService = mock(PermissionMenuService.class);
companyService = mock(CompanyService.class);
userService = new AdminUserService(userMapper, mock(WerkzeugPasswordEncoder.class), authSupport,
permissionService, mock(UserSecretCleanupPort.class), companyService);
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
companyMapper = mock(CompanyMapper.class);
standaloneCompanyService = new CompanyService(companyMapper, authSupport,
mock(PermissionMenuService.class));
when(companyMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
when(companyMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
groupMapper = mock(ShopManageGroupMapper.class);
groupMemberMapper = mock(ShopManageGroupMemberMapper.class);
companyScope = mock(CompanyScopeSupport.class);
groupAdminUserMapper = mock(AdminUserMapper.class);
groupService = new ShopManageGroupService(groupMapper, groupMemberMapper,
List.of(mock(GroupDeletionGuardPort.class)), mock(ShopManageMapper.class),
mock(QueryAsinMapper.class), mock(SkipPriceAsinMapper.class),
groupAdminUserMapper, companyScope);
when(groupMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
when(groupMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
when(groupMemberMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(5L);
}
// ---------------------------------------------------------------- 用户列表过滤
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void userListPlatformFilterBecomesAQueryCondition() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
userService.listUsers(operator, 1, 10, null, null, null, null, "jd");
LambdaQueryWrapper<AdminUserEntity> query = capturedUserCountQuery();
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值(同 AdminUserListCompanyTest 的断言顺序)
assertThat(query.getSqlSegment()).contains("platform");
assertThat(query.getParamNameValuePairs()).containsValue("jd");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void userListWithoutPlatformAddsNoCondition() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
// 8 参重载传 null 与旧 7 参口径完全一致:不带平台时查询条件一个都没有
userService.listUsers(operator, 1, 10, null, null, null, null, null);
assertThat(capturedUserCountQuery().getParamNameValuePairs()).isEmpty();
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void userListRejectsIllegalPlatformValue() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
assertThatThrownBy(() -> userService.listUsers(operator, 1, 10, null, null, null, null, "taobao"))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("所属平台");
}
// ---------------------------------------------------------------- 用户新建/编辑落库
@Test
void createUserWithoutPlatformFallsBackToAmazon() {
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
AtomicReference<AdminUserEntity> inserted = captureUserInsert();
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("京东客服");
request.setPassword("123456");
request.setRole("normal");
userService.createUser(operator, request);
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
}
@Test
void createUserWithExplicitJdPlatformStoresJd() {
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
AtomicReference<AdminUserEntity> inserted = captureUserInsert();
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("京东客服");
request.setPassword("123456");
request.setRole("normal");
request.setPlatform("jd");
userService.createUser(operator, request);
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
@Test
void createUserRejectsIllegalPlatformValue() {
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("京东客服");
request.setPassword("123456");
request.setRole("normal");
request.setPlatform("taobao");
assertThatThrownBy(() -> userService.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("所属平台");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void updateUserWithPlatformOnlyStillAppliesIt() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
when(userMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setPlatform("jd");
userService.updateUser(operator, 11L, request);
LambdaUpdateWrapper<AdminUserEntity> update = capturedUserUpdate();
assertThat(update.getSqlSet()).contains("platform");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void disabledOnlyUpdateDoesNotTouchPlatform() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
when(userMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setDisabled(true);
userService.updateUser(operator, 11L, request);
LambdaUpdateWrapper<AdminUserEntity> update = capturedUserUpdate();
assertThat(update.getSqlSet()).contains("disabled_at");
assertThat(update.getSqlSet()).doesNotContain("platform");
}
@Test
void updateUserRejectsIllegalPlatformValue() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setPlatform("taobao");
assertThatThrownBy(() -> userService.updateUser(operator, 11L, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("所属平台");
}
// ---------------------------------------------------------------- 公司目录过滤与落库
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void companyListPlatformFilterBecomesAQueryCondition() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
standaloneCompanyService.listVisible(operator, "jd");
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(companyMapper).selectList(captor.capture());
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值
assertThat(captor.getValue().getSqlSegment()).contains("platform");
assertThat(captor.getValue().getParamNameValuePairs()).containsValue("jd");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void companyListWithoutPlatformAddsNoCondition() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
standaloneCompanyService.listVisible(operator);
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(companyMapper).selectList(captor.capture());
assertThat(captor.getValue().getParamNameValuePairs()).isEmpty();
}
@Test
void createCompanyWithoutPlatformFallsBackToAmazon() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
AtomicReference<CompanyEntity> inserted = captureCompanyInsert();
CompanySaveRequest request = new CompanySaveRequest();
request.setCompanyName("京东事业部");
standaloneCompanyService.create(operator, request);
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
}
@Test
void updateCompanyKeepsPlatformWhenRequestOmitsIt() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
CompanyEntity existing = companyRow(2L, "京东事业部");
existing.setPlatform(AdminPlatformScope.JD);
when(companyMapper.selectById(2L)).thenReturn(existing);
when(companyMapper.updateById(any(CompanyEntity.class))).thenReturn(1);
CompanySaveRequest request = new CompanySaveRequest();
request.setCompanyName("京东事业部");
CompanyEntity saved = standaloneCompanyService.update(operator, 2L, request);
assertThat(saved.getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
@Test
void updateCompanyWithExplicitPlatformReassignsIt() {
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
CompanyEntity existing = companyRow(2L, "老公司");
existing.setPlatform(AdminPlatformScope.AMAZON);
when(companyMapper.selectById(2L)).thenReturn(existing);
when(companyMapper.updateById(any(CompanyEntity.class))).thenReturn(1);
CompanySaveRequest request = new CompanySaveRequest();
request.setCompanyName("老公司");
request.setPlatform("jd");
CompanyEntity saved = standaloneCompanyService.update(operator, 2L, request);
assertThat(saved.getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
// ---------------------------------------------------------------- 分组列表过滤与落库
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void groupListPlatformFilterBecomesAQueryCondition() {
groupService.list(null, null, "jd");
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(groupMapper).selectList(captor.capture());
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值
assertThat(captor.getValue().getSqlSegment()).contains("platform");
assertThat(captor.getValue().getParamNameValuePairs()).containsValue("jd");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void groupListWithoutPlatformAddsNoCondition() {
groupService.list(null, null);
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(groupMapper).selectList(captor.capture());
assertThat(captor.getValue().getParamNameValuePairs()).isEmpty();
}
@Test
void groupListRejectsIllegalPlatformValue() {
assertThatThrownBy(() -> groupService.list(null, null, "taobao"))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("所属平台");
}
@Test
void createGroupWithExplicitPlatformStoresJd() {
stubGroupInsertCapturing();
AdminUserEntity leader = operator(2L, "admin", 5L);
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator);
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
request.setGroupName("京东采集组");
request.setCreatedById(2L);
request.setPlatform("jd");
groupService.create(request, 1L, true);
assertThat(groupInsertCaptor.get().getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
@Test
void createGroupWithoutPlatformFallsBackToAmazon() {
stubGroupInsertCapturing();
AdminUserEntity leader = operator(2L, "admin", 5L);
AdminUserEntity operator = operator(1L, "super_admin", 5L);
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator);
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
request.setGroupName("亚马逊采集组");
request.setCreatedById(2L);
groupService.create(request, 1L, true);
assertThat(groupInsertCaptor.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
}
@Test
void updateGroupKeepsPlatformWhenRequestOmitsIt() {
ShopManageGroupEntity existing = groupRow(9L, "采集组");
existing.setPlatform(AdminPlatformScope.JD);
when(groupMapper.selectById(9L)).thenReturn(existing);
AdminUserEntity leader = operator(2L, "admin", 5L);
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
// validateManageAccess(超管档)还要按操作者再查一次公司:漏桩会让 requireCompanyId
// 拿到 null 账号、any(AdminUserEntity.class) 匹配不上 null ⇒ 组长/操作者公司判不一致
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator(1L, "super_admin", 5L));
when(groupMapper.updateById(any(ShopManageGroupEntity.class))).thenReturn(1);
when(groupAdminUserMapper.selectBatchIds(any())).thenReturn(List.of());
ShopManageGroupUpdateRequest request = new ShopManageGroupUpdateRequest();
request.setGroupName("采集组");
groupService.update(9L, 1L, true, request);
ArgumentCaptor<ShopManageGroupEntity> captor = ArgumentCaptor.forClass(ShopManageGroupEntity.class);
verify(groupMapper).updateById(captor.capture());
assertThat(captor.getValue().getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
@Test
void updateGroupWithExplicitPlatformReassignsIt() {
ShopManageGroupEntity existing = groupRow(9L, "采集组");
existing.setPlatform(AdminPlatformScope.AMAZON);
when(groupMapper.selectById(9L)).thenReturn(existing);
AdminUserEntity leader = operator(2L, "admin", 5L);
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
// 同上:validateManageAccess(超管档)按操作者再查一次公司
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator(1L, "super_admin", 5L));
when(groupMapper.updateById(any(ShopManageGroupEntity.class))).thenReturn(1);
when(groupAdminUserMapper.selectBatchIds(any())).thenReturn(List.of());
ShopManageGroupUpdateRequest request = new ShopManageGroupUpdateRequest();
request.setGroupName("采集组");
request.setPlatform("jd");
groupService.update(9L, 1L, true, request);
ArgumentCaptor<ShopManageGroupEntity> captor = ArgumentCaptor.forClass(ShopManageGroupEntity.class);
verify(groupMapper).updateById(captor.capture());
assertThat(captor.getValue().getPlatform()).isEqualTo(AdminPlatformScope.JD);
}
// ---------------------------------------------------------------- 取值出口自身
@Test
void normalizeOrCreateTrimsAndDefaultsBlankToAmazon() {
assertThat(AdminPlatformScope.normalizeOrCreate(null)).isEqualTo(AdminPlatformScope.AMAZON);
assertThat(AdminPlatformScope.normalizeOrCreate(" ")).isEqualTo(AdminPlatformScope.AMAZON);
assertThat(AdminPlatformScope.normalizeOrCreate(" jd ")).isEqualTo(AdminPlatformScope.JD);
assertThatThrownBy(() -> AdminPlatformScope.normalizeOrCreate(" taobao "))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("所属平台");
}
// ---------------------------------------------------------------- 夹具
private final AtomicReference<AdminUserEntity> userInsertCaptor = new AtomicReference<>();
private final AtomicReference<CompanyEntity> companyInsertCaptor = new AtomicReference<>();
private final AtomicReference<ShopManageGroupEntity> groupInsertCaptor = new AtomicReference<>();
private AtomicReference<AdminUserEntity> captureUserInsert() {
when(userMapper.insert(any(AdminUserEntity.class))).thenAnswer(inv -> {
AdminUserEntity entity = inv.getArgument(0);
entity.setId(99L);
userInsertCaptor.set(entity);
return 1;
});
return userInsertCaptor;
}
private AtomicReference<CompanyEntity> captureCompanyInsert() {
when(companyMapper.insert(any(CompanyEntity.class))).thenAnswer(inv -> {
CompanyEntity entity = inv.getArgument(0);
entity.setId(99L);
companyInsertCaptor.set(entity);
return 1;
});
return companyInsertCaptor;
}
private void stubGroupInsertCapturing() {
when(groupMapper.insert(any(ShopManageGroupEntity.class))).thenAnswer(inv -> {
ShopManageGroupEntity entity = inv.getArgument(0);
entity.setId(9L);
groupInsertCaptor.set(entity);
return 1;
});
// create() 末尾 toVo(getById(id)) 会按新 id 回读同一行
when(groupMapper.selectById(any())).thenAnswer(inv -> groupInsertCaptor.get());
}
@SuppressWarnings({"unchecked", "rawtypes"})
private LambdaQueryWrapper<AdminUserEntity> capturedUserCountQuery() {
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(userMapper).selectCount(captor.capture());
return captor.getValue();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private LambdaUpdateWrapper<AdminUserEntity> capturedUserUpdate() {
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass((Class) LambdaUpdateWrapper.class);
verify(userMapper).update(any(), captor.capture());
return captor.getValue();
}
private AdminUserEntity operator(Long id, String role, Long companyId) {
AdminUserEntity entity = new AdminUserEntity();
entity.setId(id);
entity.setUsername("op" + id);
entity.setRole(role);
entity.setIsAdmin("normal".equals(role) ? 0 : 1);
entity.setCompanyId(companyId);
return entity;
}
private AdminUserEntity target(Long id, String role) {
AdminUserEntity entity = new AdminUserEntity();
entity.setId(id);
entity.setUsername("u" + id);
entity.setRole(role);
entity.setIsAdmin("normal".equals(role) ? 0 : 1);
entity.setCompanyId(5L);
entity.setCreatedById(1L);
return entity;
}
private CompanyEntity companyRow(Long id, String name) {
CompanyEntity entity = new CompanyEntity();
entity.setId(id);
entity.setCompanyName(name);
entity.setStatus(CompanyService.STATUS_ACTIVE);
return entity;
}
private ShopManageGroupEntity groupRow(Long id, String name) {
ShopManageGroupEntity entity = new ShopManageGroupEntity();
entity.setId(id);
entity.setGroupName(name);
entity.setCreatedById(2L);
entity.setCompanyId(5L);
return entity;
}
}
@@ -60,6 +60,25 @@ class AdminUserServiceCompanySuperAdminTest {
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
}
@Test
void 京东额度允许零并拒绝负数和普通账号() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(10L, "admin", 1L, 1L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(10L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setJdPublishQuota(0);
service.updateUser(operator, 10L, request);
verify(userMapper).update(any(), any());
request.setJdPublishQuota(-1);
assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
.isInstanceOf(BusinessException.class).hasMessageContaining("不能为负数");
request.setJdPublishQuota(1);
target.setRole("normal");
assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
.isInstanceOf(BusinessException.class).hasMessageContaining("只能为管理员");
}
// ---------- 建号 ----------
@Test
@@ -57,7 +57,7 @@ class CompanyControllerEndpointTest {
body.setRemark("二期");
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
when(companyService.listVisible(operator)).thenReturn(List.of(company(1L, "厦门米椿花")));
when(companyService.listVisible(operator, null)).thenReturn(List.of(company(1L, "厦门米椿花")));
when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富"));
when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技"));
}
@@ -73,13 +73,13 @@ class CompanyControllerEndpointTest {
@Test
@DisplayName("每个端点先鉴权再进 service,顺序不能反")
void everyEndpointAuthenticatesBeforeTouchingTheDirectory() {
controller.listCompanies(request);
controller.listCompanies(request, null);
controller.createCompany(request, body);
controller.updateCompany(request, 2L, body);
InOrder order = inOrder(adminAuthSupport, companyService);
order.verify(adminAuthSupport).requireAdminOrInternal(request);
order.verify(companyService).listVisible(operator);
order.verify(companyService).listVisible(operator, null);
order.verify(adminAuthSupport).requireAdminOrInternal(request);
order.verify(companyService).create(operator, body);
order.verify(adminAuthSupport).requireAdminOrInternal(request);
@@ -108,7 +108,7 @@ class CompanyControllerEndpointTest {
@Test
@DisplayName("列表回包是 CompanyVo 而不是实体:实体字段是 camelCase,前端解析不到公司名")
void listReturnsVoItemsNotEntities() {
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request);
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request, null);
assertThat(response.getData()).hasSize(1);
assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花");
@@ -88,10 +88,12 @@ class JdPublishQuotaServiceTest {
@Test
void 上限为0_整体放行且不查库() {
JdPublishQuotaService service = newService();
service.maxProductsPerAdmin = 0L;
assertThatCode(() -> service.assertWithinQuota(admin(5L), 999_999)).doesNotThrowAnyException();
verifyNoInteractions(jdProductMapper, userDataScopeSupport, adminUserMapper);
AdminUserEntity operator = admin(5L);
operator.setJdPublishQuota(0);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of());
assertThatCode(() -> service.assertWithinQuota(operator, 999_999)).doesNotThrowAnyException();
verifyNoInteractions(jdProductMapper, adminUserMapper);
}
@Test
@@ -135,6 +137,19 @@ class JdPublishQuotaServiceTest {
assertThat(snapshot.unlimited()).isFalse();
}
@Test
void 员工使用所属管理员的独立额度() {
JdPublishQuotaService service = newService();
AdminUserEntity manager = admin(5L);
manager.setJdPublishQuota(12);
when(adminUserMapper.selectById(5L)).thenReturn(manager);
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
.thenReturn(List.of(5L, 9L));
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(12L);
assertThatThrownBy(() -> service.assertWithinQuota(employee(9L, 5L), 1))
.isInstanceOf(BusinessException.class).hasMessageContaining("12");
}
@Test
void 普通账号读不到主管_回退按自己计() {
JdPublishQuotaService service = newService();