fix(客户10-08): 分组名收到同公司唯一、去重按分组写不再 403、登录态失效前端会真退出
付费客户「先锋-团队」一次报的四件事,根因各自独立,这一版一起收: 1) 去重数据汇总「新增导入」选自己公司的分组提交必 403。DedupeTotalDataService .resolveAccessScope 给 company_super_admin 时只开了 wholeCompany 那一支、groupIds 留空集,而写侧闸门 resolveWritableGroup / ensureImportTaskAccess 只认 allUsers 与 groupIds——读侧宽、写侧窄,表现就是「下拉选得到、提交就 403」,且 403 是 HTTP 状态 不是中文文案,前端只能显示 Request failed with status code 403。改为同一口径把本公司的 分组 id 一起带上(src/main/.../DedupeTotalDataService.java:86,104,112 + 注释)。 2) 「暂无分组」与「分组名称已存在」是同一行的两面:老「先锋」的组长 uid=1188 已被删, 分组 id=33 成了孤儿行,仍占着全平台唯一的组名;而 list() 只按 created_by_id 筛, 这一行被每一个公司的 tab 静默排除(生产 13 个分组里 2 个组长只落在旧列 user_id 上)。 V153 给 biz_shop_manage_group 加 company_id(建组按组长定死、改名按组长当前公司纠回, 顺手治「移人」造成的落值漂移),唯一键换成 uk_company_group_name(company_id, group_name), 先 ADD 后 DROP。校验收窄到本公司,文案也从「分组名称已存在」改成「本公司内已存在同名分组」。 MySQL 唯一索引里 NULL 互不相异 ⇒ 迁移上线后 (NULL,'先锋') 不挡 (3,'先锋'), 客户当场就能建组,不需要先清那两行孤儿数据。 3) 删号/凭证过期后「软件还能用、没有强制退出」:前端 http 拦截器只认业务码 4011(互踢), JWT 过期或被拒返回的 401 一路静默,页面停在原处。新增 handleSessionExpired(), 401 与「code/status=401」都清本地登录态并跳 /login?expired=1;匿名 401 不收口 (那是常态噪声,且没登录态可清)。403 仍不触发下线——那是权限缺口,不能说成登录坏了。 4) 互踢(客户要「支持同时登录」)走配置不改码:AIIMAGE_AUTH_SINGLE_DEVICE_ENABLED=false, 开关只有 3 个消费点、OFF 支已有用例钉着。这里只把公司超管的角色串收成 DeviceSessionPolicy.COMPANY_SUPER_ADMIN,并记下它 src/main 仍有 22 处手抄比较 (SuperAdminPredicateSingleOutletTest 那支绊线只管 super_admin,别以为它也在守这一串)。 ⚠ 本提交带着并行会话 10-07 那批分组公司归属校验一起上线(ShopManageGroupService 的 ensureLeaderSharesOperatorCompany / resolveMembers 公司校验等,约 58 行):HEAD 里这个类 连 companyScope 字段都没有,我的写侧代码压在同一处,逐 hunk 拆不出「纯本批」的一版, 拆出来的也编不过。他那支 ShopManageGroupCompanyScopeTest(5 例)一并收了,否则这 58 行进仓 却没有用例。他的 ShopKey*/AdminUserService/admin-frontend-vue 账号页那批一个字没动,仍在 工作树里等他自己发。 验证:mvn -o clean test 全量在 detached worktree(HEAD + 本批白名单)跑;定向 8 支类 61 例 0 红; shopkey+dedupe 整包 130 例 0 红;本批判据变异自证 6/6 被杀(每轮还原后与注入前哈希逐字节一致); 前端 node --test 21 例 0 红、变异 3/3。回滚:jar 单独回退即可,V153 的手术式回滚见 backend-java/docs/rollback-V153-shop-manage-group-company-id.sql(不要 DROP COLUMN,它是资产)。
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
# Flyway 迁移盘点(task-193)
|
||||
|
||||
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
|
||||
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步;2026-10-05 23:0x 随 V147 同步;2026-10-06 随 V148 同步(并把 V145/V146/V147 从"待发版"挪进"已应用");2026-10-06 随 V149 同步(菜单树按公司一套;V148 仍未上线,故 V149 与它同批);2026-10-06 随 V150/V151 同步,并删掉未上线的 V148(该号就此退役,见下);2026-10-07 随 V152 同步(并把 V149/V150/V151 从"待发版"挪进"已应用"——10-06 17:32 只读实查,success 全 1)。
|
||||
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步;2026-10-05 23:0x 随 V147 同步;2026-10-06 随 V148 同步(并把 V145/V146/V147 从"待发版"挪进"已应用");2026-10-06 随 V149 同步(菜单树按公司一套;V148 仍未上线,故 V149 与它同批);2026-10-06 随 V150/V151 同步,并删掉未上线的 V148(该号就此退役,见下);2026-10-07 随 V152 同步(并把 V149/V150/V151 从"待发版"挪进"已应用"——10-06 17:32 只读实查,success 全 1);2026-10-08 随 V153 同步(分组名收窄到同公司唯一;表侧只 13 行,写侧代码与本版必须同批)。
|
||||
|
||||
## 概览
|
||||
|
||||
- 版本化迁移文件数:**150**(`src/main/resources/db/V*.sql`,其中整数版本 149 个 + 小版本 V25_1)
|
||||
- 整数版本范围:**V1..V152**,其中 V132/V133/V148 为已退役空号(见下),其余连续
|
||||
- 版本化迁移文件数:**151**(`src/main/resources/db/V*.sql`,其中整数版本 150 个 + 小版本 V25_1)
|
||||
- 整数版本范围:**V1..V153**,其中 V132/V133/V148 为已退役空号(见下),其余连续
|
||||
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
|
||||
- 最新版本:**V152__columns_shop_key_company_id_drop_default.sql**(上一版 **V151__rule_tables_shared_across_companies.sql**,再上一版 **V150__shop_key_company_scope.sql**)
|
||||
- 待下一次 jar 发版执行:**V152**(摘 `columns` 与 `biz_shop_key` 的 DEFAULT;V149/V150/V151 已于 10-06 17:32 应用,见下)
|
||||
- 最新版本:**V153__shop_manage_group_company_id.sql**(上一版 **V152__columns_shop_key_company_id_drop_default.sql**,再上一版 **V151__rule_tables_shared_across_companies.sql**)
|
||||
- 待下一次 jar 发版执行:**V152、V153**(V152 摘 `columns` 与 `biz_shop_key` 的 DEFAULT;V153 给分组表加 `company_id` 并把分组名从"全平台唯一"收窄成"同公司唯一",**写侧代码必须同批**,两个方向单独发都不行——见 V153 头注释第 6 段;V149/V150/V151 已于 10-06 17:32 应用,见下)
|
||||
- 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)**、`V145__brand_dedupe_company_scope.sql`(10-05 13:01)、`V146__users_expires_at_admin_expiry.sql`(10-05 13:01)、**`V147__product_category_company_scope.sql`(10-06 11:03)**、`V149__permission_menu_company_tree.sql` / `V150__shop_key_company_scope.sql` / `V151__rule_tables_shared_across_companies.sql`(三条均为 10-06 17:32)
|
||||
- 末段 `flyway_schema_history` 为 2026-10-07 主机A 只读实查(`success` 全 1,最大整数版本 151),不是从 jar 版本推的
|
||||
- 重复版本:无
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
`V148__product_category_builtin_owned_by_company.sql`(把 18 行内置类目的归属从共享哨兵 0 改成厦门米椿花 1)从未上线,2026-10-06 控制方点名「商品类目做成共享的,不区分」⇒ 它的口径被 V151 整体推翻,文件连同 `ProductCategoryMigrationV148Test`、`docs/rollback-V148-product-category-builtin-shared.sql` 一起删除。它与 132/133 的区别要写清:**把新迁移编号写回 148 在 Flyway 语义上是可行的**(生产最大值仍是 147,不存在 out-of-order),这里禁它是共树并发的护栏——148 与 149/150 是同一工作区里另一路会话此刻正在引用的号,被删的 `V148` 文件可能被再次写出,而同号两个文件会让 Flyway 启动期报 "Found more than one migration with version 148" ⇒ 两台 java 同时起不来。宁可让 `integerVersionsSequentialFromOne` 的红字出现在测试里,也不把撞号留到运行期发现。因此这三个号都在 `MigrationInventoryTest.RETIRED_HOLES` 里登记。
|
||||
|
||||
后续新增迁移从 **V153** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红;也不要回填上面那三个洞)。原先挂在 V149 名下的"摘 DEFAULT"待办,`columns` 那条已与 `biz_shop_key` 合并成 **V152** 发出(V150 头注释第 6 段要求"合并成一版发出";发布前的只读取证:`columns` 154 行按公司 52/51/51、`biz_shop_key` 16 行全 company_id=1 且无 NULL,两列 COLUMN_DEFAULT 都是 1)。摘 DEFAULT 这一族现在只剩一条:
|
||||
后续新增迁移从 **V154** 起取号(V153 已被 `shop_manage_group_company_id` 占用:分组名从全平台唯一收窄到同公司唯一,回滚见 `docs/rollback-V153-shop-manage-group-company-id.sql`。只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红;也不要回填上面那三个洞)。原先挂在 V149 名下的"摘 DEFAULT"待办,`columns` 那条已与 `biz_shop_key` 合并成 **V152** 发出(V150 头注释第 6 段要求"合并成一版发出";发布前的只读取证:`columns` 154 行按公司 52/51/51、`biz_shop_key` 16 行全 company_id=1 且无 NULL,两列 COLUMN_DEFAULT 都是 1)。摘 DEFAULT 这一族现在只剩一条:
|
||||
|
||||
- `ALTER TABLE biz_dedupe_total_data ALTER COLUMN company_id DROP DEFAULT;` —— 前提:写侧显式落列的修复(`insertBatchIgnore` 的列清单补 `company_id` + 实体加字段)**先上线并验证真实导入**。历史上它的导入不算这一列、全靠 `DEFAULT 1` 兜底,先摘=每次导入 1364;修复已落码、尚未出厂,按"先上线并验过写入 → 才谈摘"的顺序排下一版。
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
-- 回滚 V153(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
|
||||
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
|
||||
-- 在没有人工执行的情况下自己发生。)
|
||||
--
|
||||
-- 顺序:停两台应用 → 执行本脚本 → DELETE FROM flyway_schema_history WHERE version='153'
|
||||
-- → 回滚 jar → 起应用。
|
||||
-- 漏掉"删历史行"那步,将来重装带 V153 的 jar 时 Flyway 判定"已应用"直接跳过重建,
|
||||
-- 而 Java 侧实体照常读写 company_id ⇒ 运行期 Unknown column。
|
||||
--
|
||||
-- 【回滚的前提比加迁移重】名字退回"全平台唯一"之前必须先消掉跨公司同名,
|
||||
-- 否则第 1 段末尾那条 ADD UNIQUE KEY 直接 1062 失败,而失败发生在停了两台之后。
|
||||
--
|
||||
-- ---------- 0. 预检:有没有跨公司同名(必须先跑,出任何一行都不能直接回滚) ----------
|
||||
-- SELECT g.`group_name`, COUNT(DISTINCT g.`company_id`) AS companies
|
||||
-- FROM `biz_shop_manage_group` g
|
||||
-- GROUP BY g.`group_name`
|
||||
-- HAVING companies > 1;
|
||||
-- -> 0 行:可以走第 1 段。
|
||||
-- -> 有行:先由业务把重名的分组改名(保留一份),再回来跑第 1 段。这一份脚本【不自动改名】,
|
||||
-- 因为"改哪一个"是业务判断,不是工程判断。
|
||||
--
|
||||
-- 另外单独看一眼 NULL 归属的行(组长账号已删的孤儿分组):
|
||||
-- SELECT `id`, `group_name` FROM `biz_shop_manage_group` WHERE `company_id` IS NULL;
|
||||
-- -> (NULL, name) 在全局键下与任何同名行都冲突,第 1 段会连带把它们一起钉住。
|
||||
-- 这些行本来就在所有公司的列表里不可见,回滚前一并改名或清掉更干净。
|
||||
--
|
||||
-- ---------- 1. 唯一键退回全局(先 ADD 旧键,后 DROP 新键:中间始终有一把在守并发) ----------
|
||||
-- ALTER TABLE `biz_shop_manage_group` ADD UNIQUE KEY `uk_group_name` (`group_name`),
|
||||
-- ALGORITHM = INPLACE, LOCK = NONE;
|
||||
-- ALTER TABLE `biz_shop_manage_group` DROP INDEX `uk_company_group_name`,
|
||||
-- ALGORITHM = INPLACE, LOCK = NONE;
|
||||
--
|
||||
-- ---------- 2. 列【不要删】:它是资产,删了就回不来 ----------
|
||||
-- company_id 存的是"组长账号在哪一家",而账号会被硬删(users 无软删列)——
|
||||
-- 今天删掉这一列,明天那些组长的账号一删,归属就永久无从追溯(这正是 V153 第 1 段
|
||||
-- 拒绝给孤儿行硬塞公司号的同一个理由)。列留着对旧 jar 是惰性的:
|
||||
-- 旧 ShopManageGroupEntity 没有 companyId 字段,MyBatis-Plus 的 insert 列清单不含它,
|
||||
-- 而这一列是 NULL DEFAULT NULL ⇒ 旧 jar 插入的行该列读作 NULL,与新代码
|
||||
-- "推不出归属就报错"的口径一致,不会静默归到某一家。
|
||||
-- ALTER TABLE `biz_shop_manage_group` DROP COLUMN `company_id`; -- 想清楚再解开这行
|
||||
--
|
||||
-- ---------- 3. 只回滚 jar(默认档) ----------
|
||||
-- 保留列与 uk_company_group_name,只把 jar 退回不带 companyId 的版本:
|
||||
-- 旧 jar 建分组时该列一律落成 NULL ⇒ 之后每一行新分组都变成"归属无从追溯",
|
||||
-- 且它们彼此可以重名(NULL 在唯一索引里互不等价)。这个形状能跑,但会把隔离一寸寸磨掉,
|
||||
-- 所以只作为"新代码有缺陷、需要立刻止血"时的临时档,停的时间不能过夜。
|
||||
+3
@@ -15,6 +15,9 @@ public class ShopManageGroupEntity {
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String groupName;
|
||||
/** 归属公司(V153):写入时由组长账号推导;NULL = 组长账号已不存在、归属无从追溯。 */
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
@TableField("user_id")
|
||||
private Long userId;
|
||||
@TableField("created_by_id")
|
||||
|
||||
+10
-2
@@ -25,16 +25,24 @@ public final class DeviceSessionPolicy {
|
||||
/** {@code super_admin} 的字面量在 src/main 只允许出现在这一处;比较口径见 {@link #isSuper(String)}。 */
|
||||
public static final String SUPER_ADMIN = "super_admin";
|
||||
|
||||
/**
|
||||
* 公司超管的角色串。与 {@link #SUPER_ADMIN} 不同,它在 src/main 里还有 <b>22 处手抄比较</b>
|
||||
* (6 个文件:AdminUserService 14、PermissionMenuService 4、去重/分组/到期停任务/看板各 1;
|
||||
* {@code SuperAdminPredicateSingleOutletTest} 那支绊线只管 super_admin)。
|
||||
* 要收成一处,得连「业务数据面同权、管理动作不同」那条定案一起落,别只搬字面量。
|
||||
*/
|
||||
public static final String COMPANY_SUPER_ADMIN = "company_super_admin";
|
||||
|
||||
/** 计算用户管理角色:super_admin / company_super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
|
||||
public static String resolveRole(String role, Integer isAdmin, Long createdById) {
|
||||
String storedRole = role == null ? "" : role.trim().toLowerCase();
|
||||
if (SUPER_ADMIN.equals(storedRole)) {
|
||||
return SUPER_ADMIN;
|
||||
}
|
||||
if ("company_super_admin".equals(storedRole)) {
|
||||
if (COMPANY_SUPER_ADMIN.equals(storedRole)) {
|
||||
// 公司超级管理员(2026-10-05):单家公司内的最高账号,数据只看本公司,由站点
|
||||
// super_admin 创建。必须先于 is_admin 兼容推断返回,否则会被顶成站点超管。
|
||||
return "company_super_admin";
|
||||
return COMPANY_SUPER_ADMIN;
|
||||
}
|
||||
if ("admin".equals(storedRole)) {
|
||||
return "admin";
|
||||
|
||||
+9
-1
@@ -21,6 +21,7 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -82,6 +83,7 @@ public class DedupeTotalDataService {
|
||||
private final DedupeTotalDataMapper dedupeTotalDataMapper;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final ShopManageGroupService shopManageGroupService;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
@@ -99,6 +101,7 @@ public class DedupeTotalDataService {
|
||||
public DedupeTotalDataService(DedupeTotalDataMapper dedupeTotalDataMapper,
|
||||
AdminUserMapper adminUserMapper,
|
||||
ShopManageGroupMapper shopManageGroupMapper,
|
||||
ShopManageGroupService shopManageGroupService,
|
||||
CompanyScopeSupport companyScopeSupport,
|
||||
PlatformTransactionManager transactionManager,
|
||||
org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate,
|
||||
@@ -106,6 +109,7 @@ public class DedupeTotalDataService {
|
||||
this.dedupeTotalDataMapper = dedupeTotalDataMapper;
|
||||
this.adminUserMapper = adminUserMapper;
|
||||
this.shopManageGroupMapper = shopManageGroupMapper;
|
||||
this.shopManageGroupService = shopManageGroupService;
|
||||
this.companyScopeSupport = companyScopeSupport;
|
||||
this.transactionManager = transactionManager;
|
||||
this.importProgressMap = progressStore("aiimage:dedupe:import:progress", stringRedisTemplate, objectMapper);
|
||||
@@ -1233,7 +1237,11 @@ public class DedupeTotalDataService {
|
||||
companyUserIds.add(memberId);
|
||||
}
|
||||
}
|
||||
return new AccessScope(false, Set.of(), Set.copyOf(companyUserIds), true);
|
||||
// groupIds 必须一起给:写侧闸门(resolveAccessibleGroup / ensureImportTaskAccess)只认
|
||||
// allUsers 与 groupIds 两样,读侧才走 wholeCompany 那一支。这里留空集的表现是
|
||||
// 「下拉选得到自己公司的分组、提交必 403」,而 403 是 HTTP 状态不是中文文案。
|
||||
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(List.copyOf(companyUserIds));
|
||||
return new AccessScope(false, companyGroupIds, Set.copyOf(companyUserIds), true);
|
||||
}
|
||||
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
|
||||
+83
-8
@@ -7,6 +7,8 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
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.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.SkipPriceAsinMapper;
|
||||
@@ -43,6 +45,7 @@ public class ShopManageGroupService {
|
||||
private final QueryAsinMapper queryAsinMapper;
|
||||
private final SkipPriceAsinMapper skipPriceAsinMapper;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final CompanyScopeSupport companyScope;
|
||||
|
||||
public List<ShopManageGroupItemVo> list() {
|
||||
return list(null, null);
|
||||
@@ -61,8 +64,13 @@ public class ShopManageGroupService {
|
||||
if (companyMemberIds.isEmpty()) {
|
||||
qw.eq(ShopManageGroupEntity::getId, -1L);
|
||||
} else {
|
||||
// 同样自成一组:上面那支 and() 里已经混着 OR,这条若平铺下去,AND 优先只会作用在 OR 的右半边。
|
||||
qw.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds));
|
||||
// 两列一起认,与 listCompanyGroupIds 同一口径:生产 13 个分组里 2 个(组长只落在
|
||||
// 旧列 user_id 上)只按 created_by_id 筛会被每一个公司 tab 静默删掉——不报错、不 403,
|
||||
// 表现是"切到本公司,分组凭空少一半,而它们下面挂着几万行数据"。
|
||||
// 仍要自成一组:上面那支 and() 里已经混着 OR,这条若平铺下去,AND 优先只会作用在
|
||||
// OR 的右半边。
|
||||
qw.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds)
|
||||
.or(x -> x.in(ShopManageGroupEntity::getUserId, companyMemberIds)));
|
||||
}
|
||||
}
|
||||
return toVoList(groupMapper.selectList(qw));
|
||||
@@ -159,12 +167,18 @@ public class ShopManageGroupService {
|
||||
public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request, Long operatorId, boolean superAdmin) {
|
||||
Long createdById = normalizePositiveId(request.getCreatedById(), "创建人不能为空");
|
||||
validateLeaderOperator(createdById, operatorId, superAdmin);
|
||||
ensureLeaderSharesOperatorCompany(createdById, operatorId);
|
||||
String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空");
|
||||
ensureGroupNameUnique(groupName, null);
|
||||
// 归属在写侧一次定死:分组的公司就是组长的公司(同 listCompanyGroupIds 的推导口径),
|
||||
// 而 V153 之后"名字在哪家范围内唯一"就看这一列。取不到公司必须抛而不是留 NULL——
|
||||
// NULL 会让这一行落进"孤儿"那一档,从此谁的公司 tab 都排不到它。
|
||||
Long companyId = companyScope.requireCompanyId(adminUserMapper.selectById(createdById));
|
||||
ensureGroupNameUnique(groupName, null, companyId);
|
||||
|
||||
ShopManageGroupEntity entity = new ShopManageGroupEntity();
|
||||
entity.setGroupName(groupName);
|
||||
entity.setCreatedById(createdById);
|
||||
entity.setCompanyId(companyId);
|
||||
groupMapper.insert(entity);
|
||||
replaceMembers(entity.getId(), request.getMemberUserIds(), createdById, operatorId, superAdmin);
|
||||
return toVo(getById(entity.getId()));
|
||||
@@ -174,11 +188,20 @@ public class ShopManageGroupService {
|
||||
public ShopManageGroupItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageGroupUpdateRequest request) {
|
||||
ShopManageGroupEntity entity = getManageableById(id, operatorId, superAdmin);
|
||||
String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空");
|
||||
ensureGroupNameUnique(groupName, id);
|
||||
// 每次改名都按组长当前公司重算并回写:账号可以被「移人」挪到别家公司,而移人不会来更新
|
||||
// 这张表 ⇒ 落值会漂。在这里顺手纠回来,比另立一个漂移哨兵便宜。
|
||||
// 组长推不出账号时 requireCompanyId 直接抛:孤儿分组本来就过不了上面的管理门。
|
||||
Long companyId = companyScope.requireCompanyId(
|
||||
adminUserMapper.selectById(resolveGroupLeaderUserId(entity)));
|
||||
ensureGroupNameUnique(groupName, id, companyId);
|
||||
|
||||
entity.setGroupName(groupName);
|
||||
entity.setCompanyId(companyId);
|
||||
groupMapper.updateById(entity);
|
||||
replaceMembers(entity.getId(), request.getMemberUserIds(), entity.getCreatedById(), operatorId, superAdmin);
|
||||
// 组长取 resolveGroupLeaderUserId 而不是 created_by_id:生产有 2 个分组只有 user_id
|
||||
// (见 listCompanyGroupIds 的注释),只认 created_by_id 会让那 2 个分组绕过组员的公司校验。
|
||||
replaceMembers(entity.getId(), request.getMemberUserIds(), resolveGroupLeaderUserId(entity),
|
||||
operatorId, superAdmin);
|
||||
return toVo(getById(id));
|
||||
}
|
||||
|
||||
@@ -229,15 +252,32 @@ public class ShopManageGroupService {
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void ensureGroupNameUnique(String groupName, Long excludeId) {
|
||||
/**
|
||||
* 分组名<b>同一家公司内</b>唯一(V153 之前是全平台唯一,2026-10-08 定档改窄)。
|
||||
*
|
||||
* <p>依据是 {@code company_id} 这一列,而库级唯一键 {@code uk_company_group_name
|
||||
* (company_id, group_name)} 与这里必须同口径:Java 少筛一次的表现是"报错了但库里其实允许",
|
||||
* 多筛一次则是"这里放行、INSERT 撞 1062 变成 500"。</p>
|
||||
*
|
||||
* <p>报错只说"本公司内已存在",不报出别的公司有没有同名——那既是跨租户信息,
|
||||
* 也不是调用方能处理的事。</p>
|
||||
*/
|
||||
private void ensureGroupNameUnique(String groupName, Long excludeId, Long companyId) {
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> query = new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.eq(ShopManageGroupEntity::getGroupName, groupName);
|
||||
// NULL 归属(组长账号已删的孤儿行)只能按 IS NULL 比:eq(col, null) 渲染成
|
||||
// company_id = NULL,MySQL 里恒不成立 ⇒ 校验永远查不到占用者,等于把这条校验整支删掉。
|
||||
if (companyId == null) {
|
||||
query.isNull(ShopManageGroupEntity::getCompanyId);
|
||||
} else {
|
||||
query.eq(ShopManageGroupEntity::getCompanyId, companyId);
|
||||
}
|
||||
if (excludeId != null) {
|
||||
query.ne(ShopManageGroupEntity::getId, excludeId);
|
||||
}
|
||||
Long count = groupMapper.selectCount(query);
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException("分组名称已存在");
|
||||
throw new BusinessException("本公司内已存在同名分组,请换一个名称");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,10 +292,12 @@ public class ShopManageGroupService {
|
||||
}
|
||||
|
||||
private void validateManageAccess(ShopManageGroupEntity entity, Long operatorId, boolean superAdmin) {
|
||||
Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空");
|
||||
if (superAdmin) {
|
||||
// 站点超管也按组长公司收窄:读侧已经按公司 tab 收窄了,写侧不收窄等于「列表里藏起来的分组仍然能改删」。
|
||||
ensureLeaderSharesOperatorCompany(resolveGroupLeaderUserId(entity), normalizedOperatorId);
|
||||
return;
|
||||
}
|
||||
Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空");
|
||||
boolean leaderBySelf = entity.getCreatedById() != null && entity.getCreatedById().equals(normalizedOperatorId);
|
||||
boolean legacyLeaderBySelf = entity.getUserId() != null && entity.getUserId().equals(normalizedOperatorId);
|
||||
if (!leaderBySelf && !legacyLeaderBySelf) {
|
||||
@@ -263,6 +305,23 @@ public class ShopManageGroupService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组长必须与操作者同一家公司——站点超管因此不能替别家公司开分组(2026-10-07,与建号那条同口径)。
|
||||
*
|
||||
* <p>分组表没有 {@code company_id} 列,归属只能从组长账号推(同 {@link #listCompanyGroupIds});
|
||||
* 推不出来时必须报错而不是放行:把"没有组长"读成"不限公司",等于给所有无主分组开了一个越权口子。</p>
|
||||
*/
|
||||
private void ensureLeaderSharesOperatorCompany(Long leaderId, Long operatorId) {
|
||||
if (leaderId == null || leaderId <= 0) {
|
||||
throw new BusinessException("该分组没有组长账号,无法确认所属公司");
|
||||
}
|
||||
Long leaderCompanyId = companyScope.requireCompanyId(adminUserMapper.selectById(leaderId));
|
||||
Long operatorCompanyId = companyScope.requireCompanyId(adminUserMapper.selectById(operatorId));
|
||||
if (!leaderCompanyId.equals(operatorCompanyId)) {
|
||||
throw new BusinessException("只能维护本公司的分组:组长必须与操作者同一家公司");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateLeaderOperator(Long leaderId, Long operatorId, boolean superAdmin) {
|
||||
if (superAdmin) {
|
||||
return;
|
||||
@@ -304,6 +363,10 @@ public class ShopManageGroupService {
|
||||
AdminUserEntity operatorUser = operatorId == null ? null : adminUserMapper.selectById(operatorId);
|
||||
boolean operatorCanBindAllNormals = superAdmin
|
||||
|| (operatorUser != null && "admin".equalsIgnoreCase(normalizeBlank(operatorUser.getUsername())));
|
||||
// 组长的公司 = 这个分组的公司(分组表没有 company_id 列,见 listCompanyGroupIds 的注释)
|
||||
Long leaderCompanyId = leaderId == null || leaderId <= 0
|
||||
? null
|
||||
: companyScope.requireCompanyId(adminUserMapper.selectById(leaderId));
|
||||
LinkedHashSet<Long> uniqueIds = new LinkedHashSet<>();
|
||||
for (Long memberUserId : memberUserIds) {
|
||||
uniqueIds.add(normalizePositiveId(memberUserId, "组员用户不能为空"));
|
||||
@@ -330,6 +393,18 @@ public class ShopManageGroupService {
|
||||
if (leaderId != null && leaderId.equals(user.getId())) {
|
||||
throw new BusinessException("组长不能作为组员重复加入分组");
|
||||
}
|
||||
// 超管(站点与公司两档)永不入组:它是那家公司的最高账号,进了组就等于把自己
|
||||
// 关进某个组长的可见范围里。此前超管操作者能绕过这条,把别家公司的人(含别家超管)拉进分组。
|
||||
boolean siteSuper = DeviceSessionPolicy.isSuperAdmin(
|
||||
user.getRole(), user.getIsAdmin(), user.getCreatedById());
|
||||
String memberRole = DeviceSessionPolicy.resolveRole(
|
||||
user.getRole(), user.getIsAdmin(), user.getCreatedById());
|
||||
if (siteSuper || "company_super_admin".equals(memberRole)) {
|
||||
throw new BusinessException("超级管理员不属于任何分组");
|
||||
}
|
||||
if (leaderCompanyId != null && !leaderCompanyId.equals(user.getCompanyId())) {
|
||||
throw new BusinessException("只能添加组长本公司的账号");
|
||||
}
|
||||
if (!superAdmin && !"normal".equals(normalizeBlank(user.getRole()))) {
|
||||
throw new BusinessException("只能绑定普通员工账号");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V153__shop_manage_group_company_id
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 需求:2026-10-08 客户「先锋-团队」定档「分组名同公司唯一就行」
|
||||
--
|
||||
-- 1. 变更目的:把「数据权限分组」的名称唯一性从**全平台**收窄到**同一家公司内**。
|
||||
-- 现状是 V12 建表时的 `UNIQUE KEY uk_group_name (group_name)`(全局),而分组列表按
|
||||
-- "本人是组长/组员"收窄 —— 两把尺子不同,2026-10-08 现网表现为同一屏「暂无分组」+
|
||||
-- 「分组名称已存在」:占着「先锋」这个名字的是 id=33 那行,它的组长账号 uid=1188 已被
|
||||
-- 硬删(users 无软删列),所以它在任何公司的列表里都不出现,却仍然全局占名。
|
||||
-- 收窄之后同一家人人可复用常见人名,别家同名不再互相挡路。
|
||||
--
|
||||
-- 为什么本文件不"顺手"把那两行孤儿分组改成谁的 company_id:孤儿推不出归属,
|
||||
-- 硬塞一个公司号就是"归属失真且不报错"(CompanyScopeSupport 类注释点名的形态)。
|
||||
-- 所以这一列【可空】,NULL 的语义就是「组长账号已不存在,归属无从追溯」。
|
||||
-- 副作用是好的:MySQL 唯一索引里 NULL 彼此不等价 ⇒ (NULL,'先锋') 不挡 (3,'先锋'),
|
||||
-- **迁移跑完客户立刻就能建「先锋」**,不需要先动那两行数据。
|
||||
--
|
||||
-- 2. 影响表与数据量:只有 `biz_shop_manage_group`,全表 **13 行**(2026-10-08 只读实查)。
|
||||
-- · 加列:末位、INSTANT,不重建表;
|
||||
-- · 回填:11 行能推出 company_id(组长账号在 users 里),2 行(id=33、id=34)留 NULL;
|
||||
-- · 唯一键:先 ADD `uk_company_group_name (company_id, group_name)` 再 DROP `uk_group_name`
|
||||
-- (顺序照 V145 第 3 段:中间任一步失败都至少还有一个唯一键在守并发)。
|
||||
-- 不碰 biz_shop_manage_group_member / biz_shop_manage / biz_query_asin / 任何业务数据表。
|
||||
--
|
||||
-- 3. 锁表风险:极低。13 行的表,加列走 ALGORITHM = INSTANT,两条索引变更走
|
||||
-- ALGORITHM = INPLACE, LOCK = NONE。回填 UPDATE 由本表自己驱动(13 行全扫),
|
||||
-- 不 JOIN 大表、不加 AFTER、不写 MODIFY COLUMN ... NOT NULL(重建表会按当时的列默认值
|
||||
-- 物化历史行 —— V144/V150 同款禁令,且这里根本没有可物化的默认值)。
|
||||
-- 全部语句先查 information_schema 再 PREPARE(MySQL 8.4.8 无 ADD COLUMN IF NOT EXISTS,
|
||||
-- 写法首例见 V143/V145),重跑是 no-op。
|
||||
--
|
||||
-- 4. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW COLUMNS FROM `biz_shop_manage_group` LIKE 'company_id';
|
||||
-- -> 期望 Null = YES,Default = NULL
|
||||
-- SHOW INDEX FROM `biz_shop_manage_group`;
|
||||
-- -> 期望有 uk_company_group_name(company_id, group_name) 两列,且【没有】uk_group_name
|
||||
-- SELECT COUNT(*) AS total, COUNT(company_id) AS filled
|
||||
-- FROM `biz_shop_manage_group`;
|
||||
-- -> 期望 total=13、filled=11(两行 NULL 是组长已删的孤儿,见第 5 段)
|
||||
-- SELECT g.`id`, g.`group_name`, g.`company_id`, u.`company_id` AS leader_company
|
||||
-- FROM `biz_shop_manage_group` g
|
||||
-- LEFT JOIN `users` u ON u.`id` = COALESCE(g.`created_by_id`, g.`user_id`)
|
||||
-- WHERE NOT (g.`company_id` <=> u.`company_id`);
|
||||
-- -> 期望只剩 id=33、id=34 两行(其余每一行的落值必须等于组长账号的公司)
|
||||
--
|
||||
-- 5. 回滚步骤:docs/rollback-V153-shop-manage-group-company-id.sql
|
||||
-- (回滚是"名字退回全平台唯一",不是"删列"——列里已写入的归属是资产,删了就回不来。)
|
||||
-- 注意:回滚前必须先手工消掉跨公司同名,否则 ADD uk_group_name 会直接 1062 失败。
|
||||
--
|
||||
-- 6. 上线窗口:随下一次 jar 发版执行(两台必须同版,Flyway 只在先到的一台上跑)。
|
||||
-- 业务低峰即可:13 行的表,没有需要等的长事务。
|
||||
-- 写侧代码(create/update 显式落 company_id、重名校验按公司筛)与本版【同批】上线:
|
||||
-- 只上迁移不上代码,表现是"新行 company_id 全 NULL",隔离等于没做;
|
||||
-- 只上代码不上迁移,表现是新代码撞库级 uk_group_name ⇒ 500。两个方向都不许单独发。
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 加列(末位 + INSTANT;可空,NULL = 归属无从追溯) ----------
|
||||
|
||||
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_manage_group' AND COLUMN_NAME = 'company_id');
|
||||
SET @sql := IF(@col_exists = 0,
|
||||
'ALTER TABLE `biz_shop_manage_group` ADD COLUMN `company_id` bigint NULL DEFAULT NULL COMMENT ''归属公司(company.id):写入时由组长账号推导;NULL=组长账号已不存在、归属无从追溯;V153'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 2. 回填:组长账号(新列 created_by_id 优先、旧列 user_id 兜底)的公司 ----------
|
||||
-- 两列一起认是这张表既定的口径(生产 13 行里 2 行的组长只落在旧列 user_id 上,
|
||||
-- 只认 created_by_id 会把它们当成"无组长"从而留 NULL,而它们其实有明确归属)。
|
||||
-- 驱动方向:本表 13 行全扫,按 users 主键点查,不碰 users 的索引选择。
|
||||
|
||||
UPDATE `biz_shop_manage_group` g
|
||||
JOIN `users` u ON u.`id` = COALESCE(g.`created_by_id`, g.`user_id`)
|
||||
SET g.`company_id` = u.`company_id`
|
||||
WHERE g.`company_id` IS NULL
|
||||
AND u.`company_id` IS NOT NULL;
|
||||
|
||||
-- ---------- 3. 唯一键按公司放宽(先 ADD 后 DROP,理由见头注释第 2 段) ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_manage_group'
|
||||
AND INDEX_NAME = 'uk_company_group_name');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `biz_shop_manage_group` ADD UNIQUE KEY `uk_company_group_name` (`company_id`, `group_name`), ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_manage_group'
|
||||
AND INDEX_NAME = 'uk_group_name');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_shop_manage_group` DROP INDEX `uk_group_name`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
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.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.dedupe.mapper.DedupeTotalDataMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 公司超级管理员在「按分组读写去重总数据」这条链上的闸门(2026-10-08 客户现网报 403)。
|
||||
*
|
||||
* <p>客户账号 uid=1206(company_id=3)自己建了分组 id=36,后台下拉能选到它,点「上传并导入」
|
||||
* 得到的是 axios 那句 {@code Request failed with status code 403}——因为写侧闸门
|
||||
* {@code resolveAccessibleGroup} 只认 {@code allUsers} 与 {@code groupIds},而公司超管那一支
|
||||
* {@code AccessScope} 过去只填了 {@code userIds + wholeCompany}(读侧用),groupIds 是空集。
|
||||
* 读侧有 {@code wholeCompany} 兜着所以列表是好的,两边不对称就是"看得到、动不了"。</p>
|
||||
*
|
||||
* <p>断言打在闸门的行为上(抛不抛)而不是打在集合内容上:把 {@code resolveAccessScope} 里补
|
||||
* groupIds 那一行删掉,前两条用例必须一红一松手;把 {@code listCompanyGroupIds} 换成"不筛公司"
|
||||
* 则第三条必须红——这两向都红才说明这一行真的在执行口径,而不是恰好没被走到。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DedupeTotalDataCompanySuperAdminGroupAccessTest {
|
||||
|
||||
private static final long OPERATOR_ID = 1206L;
|
||||
private static final long OWN_COMPANY_ID = 3L;
|
||||
private static final long OWN_COMPANY_GROUP_ID = 36L;
|
||||
private static final long OTHER_COMPANY_GROUP_ID = 33L;
|
||||
|
||||
@Mock
|
||||
private DedupeTotalDataMapper dedupeTotalDataMapper;
|
||||
@Mock
|
||||
private AdminUserMapper adminUserMapper;
|
||||
@Mock
|
||||
private ShopManageGroupMapper shopManageGroupMapper;
|
||||
@Mock
|
||||
private ShopManageGroupService shopManageGroupService;
|
||||
@Mock
|
||||
private CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
@InjectMocks
|
||||
private DedupeTotalDataService service;
|
||||
|
||||
private void stubCompanySuperAdmin() {
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(OPERATOR_ID);
|
||||
operator.setUsername("u1206");
|
||||
operator.setRole("company_super_admin");
|
||||
operator.setIsAdmin(1);
|
||||
operator.setCompanyId(OWN_COMPANY_ID);
|
||||
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operator);
|
||||
when(companyScopeSupport.memberUserIds(OWN_COMPANY_ID)).thenReturn(List.of(OPERATOR_ID));
|
||||
}
|
||||
|
||||
private void stubGroup(Long groupId) {
|
||||
ShopManageGroupEntity group = new ShopManageGroupEntity();
|
||||
group.setId(groupId);
|
||||
group.setGroupName("g" + groupId);
|
||||
when(shopManageGroupMapper.selectById(groupId)).thenReturn(group);
|
||||
}
|
||||
|
||||
private ShopManageGroupEntity resolveWritableGroup(Long groupId) {
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(OPERATOR_ID);
|
||||
operator.setRole("company_super_admin");
|
||||
operator.setCompanyId(OWN_COMPANY_ID);
|
||||
return ReflectionTestUtils.invokeMethod(service, "resolveWritableGroup", groupId, operator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("公司超管写本公司名下的分组:闸门放行(修复前这里必 403)")
|
||||
void companySuperAdminWritesGroupOfOwnCompany() {
|
||||
stubCompanySuperAdmin();
|
||||
stubGroup(OWN_COMPANY_GROUP_ID);
|
||||
when(shopManageGroupService.listCompanyGroupIds(List.of(OPERATOR_ID)))
|
||||
.thenReturn(Set.of(OWN_COMPANY_GROUP_ID));
|
||||
|
||||
assertThat(resolveWritableGroup(OWN_COMPANY_GROUP_ID).getId()).isEqualTo(OWN_COMPANY_GROUP_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("公司超管查导入任务进度走同一把尺子:不再报「无权查看该导入任务」")
|
||||
void importTaskAccessUsesSameRuler() {
|
||||
stubCompanySuperAdmin();
|
||||
when(shopManageGroupService.listCompanyGroupIds(List.of(OPERATOR_ID)))
|
||||
.thenReturn(Set.of(OWN_COMPANY_GROUP_ID));
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "ensureImportTaskAccess", OWN_COMPANY_GROUP_ID,
|
||||
ReflectionTestUtils.invokeMethod(service, "resolveAccessScope", OPERATOR_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("别家公司的分组仍然 403:补 groupIds 不等于把闸门放开成全平台")
|
||||
void groupOfAnotherCompanyStillForbidden() {
|
||||
stubCompanySuperAdmin();
|
||||
stubGroup(OTHER_COMPANY_GROUP_ID);
|
||||
// 组长不在本公司成员集里 ⇒ listCompanyGroupIds 不会返回它
|
||||
when(shopManageGroupService.listCompanyGroupIds(List.of(OPERATOR_ID))).thenReturn(Set.of());
|
||||
|
||||
assertThatThrownBy(() -> resolveWritableGroup(OTHER_COMPANY_GROUP_ID))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, ex -> {
|
||||
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(ex.getReason()).isEqualTo("无权操作该分组数据");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("分组 id 缺失仍走中文业务错误,不被公司维度兜成放行")
|
||||
void missingGroupStillRejectedBeforeScope() {
|
||||
assertThatThrownBy(() -> resolveWritableGroup(0L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessage("请选择分组");
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package com.nanri.aiimage.modules.shopkey.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.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupMemberEntity;
|
||||
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.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
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.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 分组名的唯一性范围(V153 起:同一家公司内唯一,2026-10-08 定档)。
|
||||
*
|
||||
* <p>要防的是两种"错了不报错"的形状:</p>
|
||||
* <ol>
|
||||
* <li><b>写侧漏落 company_id</b>:这一列是 NULL 的分组会被所有公司的 tab 排除在外,
|
||||
* 而 MyBatis-Plus 对 null 字段直接不出现在 INSERT 列清单里 ⇒ 静默落库成 NULL。
|
||||
* 所以断言打在<b>送进 insert/updateById 的那个实体</b>上,不是打在方法没抛异常上。</li>
|
||||
* <li><b>校验用 eq(col, null) 而不是 isNull</b>:{@code company_id = NULL} 在 MySQL 里恒不成立,
|
||||
* 于是"查占用者"永远查不到,这条校验整支形同删掉——而它长得像在工作。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>SQL 片段字面量取自媒体实跑(脱敏后逐字),不是推理;{@code paramNameValuePairs} 必须在
|
||||
* {@code getSqlSegment()} 求值<b>之后</b>再读,否则断的是一个空 map。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class ShopManageGroupCompanyNameUniquenessTest {
|
||||
|
||||
private static final Long LEADER_ID = 1206L;
|
||||
private static final Long OPERATOR_ID = 1206L;
|
||||
private static final Long COMPANY_ID = 3L;
|
||||
private static final Long OTHER_COMPANY_ID = 1L;
|
||||
|
||||
private ShopManageGroupMapper groupMapper;
|
||||
private ShopManageGroupMemberMapper memberMapper;
|
||||
private AdminUserMapper userMapper;
|
||||
private CompanyScopeSupport companyScope;
|
||||
private ShopManageGroupService service;
|
||||
|
||||
@Mock
|
||||
private com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper shopManageMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
ShopManageGroupEntity.class);
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
ShopManageGroupMemberEntity.class);
|
||||
groupMapper = org.mockito.Mockito.mock(ShopManageGroupMapper.class);
|
||||
memberMapper = org.mockito.Mockito.mock(ShopManageGroupMemberMapper.class);
|
||||
userMapper = org.mockito.Mockito.mock(AdminUserMapper.class);
|
||||
companyScope = org.mockito.Mockito.mock(CompanyScopeSupport.class);
|
||||
service = new ShopManageGroupService(groupMapper, memberMapper, List.of(), shopManageMapper,
|
||||
null, null, userMapper, companyScope);
|
||||
// 打桩照 CompanyScopeSupport 的真实语义来:取不到公司就抛,而不是把 null 传下去。
|
||||
// 上一版这里直接回传 getCompanyId(),结果 null 一路走到别人的 equals 里 NPE,
|
||||
// 测出来的是"桩不像真实现",不是被测代码的缺陷。
|
||||
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenAnswer(invocation -> {
|
||||
AdminUserEntity account = invocation.getArgument(0);
|
||||
if (account == null || account.getCompanyId() == null || account.getCompanyId() <= 0) {
|
||||
throw new BusinessException("归属账号不存在或没有所属公司");
|
||||
}
|
||||
return account.getCompanyId();
|
||||
});
|
||||
}
|
||||
|
||||
private AdminUserEntity user(Long id, String role, Long companyId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setUsername("u" + id);
|
||||
user.setRole(role);
|
||||
user.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
user.setCompanyId(companyId);
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 脱敏:MP 在 segment 里只放 {@code #{ew.paramNameValuePairs.MPGENVALn}} 占位,值单独断。 */
|
||||
private static String masked(String segment) {
|
||||
String sql = segment.replaceAll("#\\{ew\\.paramNameValuePairs\\.MPGENVAL\\d+}", "?");
|
||||
assertThat(sql).as("脱敏必须把每个 MP 占位符都换成 ?").doesNotContain("MPGENVAL").doesNotContain("#{");
|
||||
return sql;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private LambdaQueryWrapper<ShopManageGroupEntity> captureCountQuery() {
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(groupMapper).selectCount(captor.capture());
|
||||
return (LambdaQueryWrapper<ShopManageGroupEntity>) captor.getValue();
|
||||
}
|
||||
|
||||
private void stubEmptyNameSlot() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
}
|
||||
|
||||
// ---------- 1. 校验查询必须带公司谓词 ----------
|
||||
|
||||
@Test
|
||||
@DisplayName("重名校验:按公司筛,实测渲染逐字比对")
|
||||
void duplicateCheckIsScopedByCompany() {
|
||||
stubEmptyNameSlot();
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "ensureGroupNameUnique", "先锋", null, COMPANY_ID);
|
||||
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> query = captureCountQuery();
|
||||
String sql = masked(query.getSqlSegment());
|
||||
assertThat(sql).as("名字与公司两条腿都必须 AND 在一起")
|
||||
.isEqualTo("(group_name = ? AND company_id = ?)");
|
||||
// 先求值 segment 再读 pairs,否则断的是空 map。绑定顺序由 MP 决定,不假设它跟片段同序。
|
||||
assertThat(query.getParamNameValuePairs().values())
|
||||
.containsExactlyInAnyOrder("先锋", COMPANY_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("重名校验:归属为 NULL 时必须走 IS NULL,不能渲染成 company_id = NULL(恒不成立=校验形同删掉)")
|
||||
void nullCompanyUsesIsNullNotEqualsNull() {
|
||||
stubEmptyNameSlot();
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "ensureGroupNameUnique", "先锋", null, null);
|
||||
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> query = captureCountQuery();
|
||||
String sql = masked(query.getSqlSegment());
|
||||
assertThat(sql).as("NULL 归属要按 IS NULL 比,而不是绑一个 null 进去")
|
||||
.isEqualTo("(group_name = ? AND company_id IS NULL)");
|
||||
assertThat(sql).as("绝不允许出现 company_id = ? 且绑定值是 null 的形状")
|
||||
.doesNotContain("company_id = ?");
|
||||
assertThat(query.getParamNameValuePairs().values()).containsExactly("先锋");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("重名校验:本公司内已存在才报,且文案不说\"全平台\"(V153 之后那句是假话)")
|
||||
void messageSpeaksCompanyScopeOnly() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
assertThatThrownBy(() -> ReflectionTestUtils.invokeMethod(
|
||||
service, "ensureGroupNameUnique", "先锋", 36L, COMPANY_ID))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("本公司")
|
||||
.hasMessageNotContaining("全平台");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("重名校验:编辑自己时把自己排除在外(否则任何一次改名都自撞)")
|
||||
void updateExcludesOwnRow() {
|
||||
stubEmptyNameSlot();
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "ensureGroupNameUnique", "先锋", 36L, COMPANY_ID);
|
||||
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> query = captureCountQuery();
|
||||
assertThat(masked(query.getSqlSegment()))
|
||||
.isEqualTo("(group_name = ? AND company_id = ? AND id <> ?)");
|
||||
assertThat(query.getParamNameValuePairs().values())
|
||||
.containsExactlyInAnyOrder("先锋", COMPANY_ID, 36L);
|
||||
}
|
||||
|
||||
// ---------- 2. 写侧必须把 company_id 落进去 ----------
|
||||
|
||||
@Test
|
||||
@DisplayName("建组:INSERT 的实体带 company_id(从组长账号推),漏落就会静默造出孤儿行")
|
||||
void createPersistsCompanyFromLeader() {
|
||||
stubEmptyNameSlot();
|
||||
when(userMapper.selectById(LEADER_ID)).thenReturn(user(LEADER_ID, "company_super_admin", COMPANY_ID));
|
||||
AtomicReference<ShopManageGroupEntity> inserted = new AtomicReference<>();
|
||||
when(groupMapper.insert(any(ShopManageGroupEntity.class))).thenAnswer(invocation -> {
|
||||
ShopManageGroupEntity entity = invocation.getArgument(0);
|
||||
// 真库里 insert 后主键由自增回填,create() 末尾会 selectById(id) 再回显。
|
||||
// 桩不填 id 的话 toVoList 拿 null 去查成员,测到的是桩不像真实现。
|
||||
entity.setId(36L);
|
||||
inserted.set(entity);
|
||||
return 1;
|
||||
});
|
||||
when(groupMapper.selectById(any())).thenAnswer(invocation -> inserted.get());
|
||||
// toVoList 会按组长/组员 id 批量取账号回显用户名,桩不给就 NPE 在回显上,
|
||||
// 而这条用例要断的是"送进 insert 的那个实体带没带 company_id"。
|
||||
when(userMapper.selectBatchIds(any()))
|
||||
.thenReturn(List.of(user(LEADER_ID, "company_super_admin", COMPANY_ID)));
|
||||
|
||||
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
|
||||
request.setGroupName("先锋");
|
||||
request.setCreatedById(LEADER_ID);
|
||||
request.setMemberUserIds(List.of());
|
||||
service.create(request, OPERATOR_ID, false);
|
||||
|
||||
assertThat(inserted.get().getCompanyId()).as("归属必须随建组一次定死").isEqualTo(COMPANY_ID);
|
||||
assertThat(inserted.get().getGroupName()).isEqualTo("先锋");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("建组:组长账号没有公司 ⇒ 抛,不允许落成 NULL 继续写")
|
||||
void createRejectsLeaderWithoutCompany() {
|
||||
when(userMapper.selectById(LEADER_ID)).thenReturn(user(LEADER_ID, "company_super_admin", null));
|
||||
|
||||
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
|
||||
request.setGroupName("先锋");
|
||||
request.setCreatedById(LEADER_ID);
|
||||
request.setMemberUserIds(List.of());
|
||||
|
||||
assertThatThrownBy(() -> service.create(request, OPERATOR_ID, false))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
verify(groupMapper, org.mockito.Mockito.never()).insert(any(ShopManageGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("改名:按组长当前公司回写,组长被移去别家时这一列跟着纠回来(落值漂移的自愈点)")
|
||||
void renameRewritesCompanyFromCurrentLeader() {
|
||||
stubEmptyNameSlot();
|
||||
ShopManageGroupEntity stored = new ShopManageGroupEntity();
|
||||
stored.setId(36L);
|
||||
stored.setGroupName("先锋1");
|
||||
stored.setCreatedById(LEADER_ID);
|
||||
stored.setCompanyId(OTHER_COMPANY_ID); // 落值还是老公司 —— 模拟"移人"之后
|
||||
when(groupMapper.selectById(36L)).thenReturn(stored);
|
||||
when(userMapper.selectById(LEADER_ID)).thenReturn(user(LEADER_ID, "company_super_admin", COMPANY_ID));
|
||||
AtomicReference<ShopManageGroupEntity> updated = new AtomicReference<>();
|
||||
when(groupMapper.updateById(any(ShopManageGroupEntity.class))).thenAnswer(invocation -> {
|
||||
updated.set(invocation.getArgument(0));
|
||||
return 1;
|
||||
});
|
||||
|
||||
ShopManageGroupUpdateRequest request = new ShopManageGroupUpdateRequest();
|
||||
request.setGroupName("先锋");
|
||||
request.setMemberUserIds(List.of());
|
||||
service.update(36L, OPERATOR_ID, false, request);
|
||||
|
||||
assertThat(updated.get().getCompanyId()).as("改名必须顺手把归属纠回组长当前公司").isEqualTo(COMPANY_ID);
|
||||
assertThat(updated.get().getGroupName()).isEqualTo("先锋");
|
||||
// 校验查询用的是纠回来之后的公司,不是那一列的旧值(改名场景自带 id <> 自己)
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> check = captureCountQuery();
|
||||
String sql = masked(check.getSqlSegment());
|
||||
assertThat(sql).isEqualTo("(group_name = ? AND company_id = ? AND id <> ?)");
|
||||
assertThat(check.getParamNameValuePairs().values()).contains(COMPANY_ID);
|
||||
assertThat(check.getParamNameValuePairs().values()).doesNotContain(OTHER_COMPANY_ID);
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package com.nanri.aiimage.modules.shopkey.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.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.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupMemberEntity;
|
||||
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.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* 分组的归属边界(2026-10-07 定案):与建号那条同一口径——站点超管不替其他公司管分组,
|
||||
* 而超管(站点与公司两档)不属于任何分组。
|
||||
*
|
||||
* <p>分组表没有 {@code company_id} 列,归属只能从组长账号推,所以这里的断言全部打在
|
||||
* 「组长/组员的 company_id 有没有被真的比过」上,而不是打在角色字符串上:把
|
||||
* {@code ensureLeaderSharesOperatorCompany} 那一行删掉,四条用例必须同时松手。</p>
|
||||
*/
|
||||
class ShopManageGroupCompanyScopeTest {
|
||||
|
||||
private ShopManageGroupMapper groupMapper;
|
||||
private ShopManageGroupMemberMapper memberMapper;
|
||||
private AdminUserMapper userMapper;
|
||||
private CompanyScopeSupport companyScope;
|
||||
private ShopManageGroupService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
ShopManageGroupEntity.class);
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
ShopManageGroupMemberEntity.class);
|
||||
groupMapper = mock(ShopManageGroupMapper.class);
|
||||
memberMapper = mock(ShopManageGroupMemberMapper.class);
|
||||
userMapper = mock(AdminUserMapper.class);
|
||||
companyScope = mock(CompanyScopeSupport.class);
|
||||
service = new ShopManageGroupService(groupMapper, memberMapper, List.of(), null, null, null,
|
||||
userMapper, companyScope);
|
||||
// 真实实现就是「取账号自己的 company_id,取不到就抛」,这里按同一语义打桩而不是逐个用例喂值
|
||||
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenAnswer(invocation ->
|
||||
invocation.getArgument(0, AdminUserEntity.class).getCompanyId());
|
||||
}
|
||||
|
||||
private AdminUserEntity user(Long id, String role, Long companyId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setUsername("u" + id);
|
||||
user.setRole(role);
|
||||
user.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
user.setCompanyId(companyId);
|
||||
return user;
|
||||
}
|
||||
|
||||
private ShopManageGroupCreateRequest request(Long leaderId, List<Long> memberIds) {
|
||||
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
|
||||
request.setGroupName("g-" + leaderId + "-" + memberIds);
|
||||
request.setCreatedById(leaderId);
|
||||
request.setMemberUserIds(memberIds);
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("建组:站点超管不能替别家公司建分组——组长是别家的人就挡下,且一行不写")
|
||||
void superAdminCannotCreateGroupForAnotherCompany() {
|
||||
when(userMapper.selectById(1L)).thenReturn(user(1L, "super_admin", 1L));
|
||||
when(userMapper.selectById(50L)).thenReturn(user(50L, "admin", 7L));
|
||||
|
||||
assertThatThrownBy(() -> service.create(request(50L, List.of()), 1L, true))
|
||||
.isInstanceOfSatisfying(BusinessException.class, ex ->
|
||||
assertThat(ex.getMessage()).contains("本公司"));
|
||||
verify(groupMapper, never()).insert(any(ShopManageGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("组员:公司超管永不入组,站点超管操作者也绕不过这一条")
|
||||
void companySuperAdminNeverBecomesMember() {
|
||||
when(userMapper.selectById(1L)).thenReturn(user(1L, "super_admin", 1L));
|
||||
when(userMapper.selectById(50L)).thenReturn(user(50L, "admin", 1L));
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(user(60L, "company_super_admin", 1L)));
|
||||
|
||||
assertThatThrownBy(() -> service.create(request(50L, List.of(60L)), 1L, true))
|
||||
.isInstanceOfSatisfying(BusinessException.class, ex ->
|
||||
assertThat(ex.getMessage()).isEqualTo("超级管理员不属于任何分组"));
|
||||
verify(memberMapper, never()).insert(any(ShopManageGroupMemberEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("组员:站点超管账号同样不得入组(老实现只在非超管分支才查这一条)")
|
||||
void siteSuperAdminNeverBecomesMember() {
|
||||
when(userMapper.selectById(1L)).thenReturn(user(1L, "super_admin", 1L));
|
||||
when(userMapper.selectById(50L)).thenReturn(user(50L, "admin", 1L));
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(user(61L, "super_admin", 1L)));
|
||||
|
||||
assertThatThrownBy(() -> service.create(request(50L, List.of(61L)), 1L, true))
|
||||
.isInstanceOfSatisfying(BusinessException.class, ex ->
|
||||
assertThat(ex.getMessage()).isEqualTo("超级管理员不属于任何分组"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("组员:别家公司的普通账号不能拉进本公司分组(超管操作者以前能)")
|
||||
void memberMustShareLeaderCompany() {
|
||||
when(userMapper.selectById(1L)).thenReturn(user(1L, "super_admin", 1L));
|
||||
when(userMapper.selectById(50L)).thenReturn(user(50L, "admin", 1L));
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(user(62L, "normal", 7L)));
|
||||
|
||||
assertThatThrownBy(() -> service.create(request(50L, List.of(62L)), 1L, true))
|
||||
.isInstanceOfSatisfying(BusinessException.class, ex ->
|
||||
assertThat(ex.getMessage()).contains("本公司"));
|
||||
verify(memberMapper, never()).insert(any(ShopManageGroupMemberEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("正样本配对:本公司组长 + 本公司普通员工照常落库——上面四条 never 只有这条成立才有东西可反证")
|
||||
void sameCompanyLeaderAndMemberAreSaved() {
|
||||
when(userMapper.selectById(1L)).thenReturn(user(1L, "super_admin", 1L));
|
||||
when(userMapper.selectById(50L)).thenReturn(user(50L, "admin", 1L));
|
||||
when(userMapper.selectBatchIds(any())).thenReturn(List.of(user(63L, "normal", 1L)));
|
||||
when(groupMapper.insert(any(ShopManageGroupEntity.class))).thenAnswer(invocation -> {
|
||||
invocation.getArgument(0, ShopManageGroupEntity.class).setId(9L);
|
||||
return 1;
|
||||
});
|
||||
ShopManageGroupEntity saved = new ShopManageGroupEntity();
|
||||
saved.setId(9L);
|
||||
saved.setGroupName("saved");
|
||||
saved.setCreatedById(50L);
|
||||
when(groupMapper.selectById(9L)).thenReturn(saved);
|
||||
|
||||
service.create(request(50L, List.of(63L)), 1L, true);
|
||||
|
||||
ArgumentCaptor<ShopManageGroupMemberEntity> captor =
|
||||
ArgumentCaptor.forClass(ShopManageGroupMemberEntity.class);
|
||||
verify(memberMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getUserId()).isEqualTo(63L);
|
||||
assertThat(captor.getValue().getGroupId()).isEqualTo(9L);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -47,9 +47,11 @@ import static org.mockito.Mockito.when;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ShopManageGroupServiceTest {
|
||||
|
||||
/** 实跑(MP 3.5.7,TableInfo 手工初始化)打出来的 {@code list(5L, List.of(11L))} 脱敏整串:每个字符都取自媒体,不是推测。 */
|
||||
/** 实跑(MP 3.5.7,TableInfo 手工初始化)打出来的 {@code list(5L, List.of(11L))} 脱敏整串:每个字符都取自媒体,不是推测。
|
||||
* 2026-10-08:公司那一腿从 {@code created_by_id IN (?)} 长成两列一起认(生产 13 个分组里 2 个的组长
|
||||
* 只落在旧列 user_id 上,单列筛会把它们从每一个公司 tab 里静默删掉),与 {@code listCompanyGroupIds} 对齐。 */
|
||||
private static final String OR_GROUP_MASKED =
|
||||
"((created_by_id = ? OR (user_id = ?)) AND (created_by_id IN (?))) ORDER BY id ASC";
|
||||
"((created_by_id = ? OR (user_id = ?)) AND (created_by_id IN (?) OR (user_id IN (?)))) ORDER BY id ASC";
|
||||
|
||||
/** M2(I-1 点名的那个形状)实测渲染出来的样子:OR 的左半边逃出括号组。整串比对对它必红。 */
|
||||
private static final String FLAT_OR_MASKED =
|
||||
@@ -110,8 +112,8 @@ class ShopManageGroupServiceTest {
|
||||
assertThat(sql).contains(" OR ").contains(" IN (");
|
||||
|
||||
assertThat(q.getParamNameValuePairs().values())
|
||||
.as("三个占位符 = created_by_id / user_id / 公司成员集各一个绑定")
|
||||
.hasSize(3)
|
||||
.as("四个占位符 = created_by_id / user_id 各一个绑定 + 公司成员集两列各一个绑定")
|
||||
.hasSize(4)
|
||||
.contains(5L, 11L);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user