feat(菜单权限): 每家公司一套菜单树(V149)+ 公司 tab 只在注册表页渲染
本批两件事,加上随本批一起入仓的并行会话在制品: 一、菜单权限按公司隔离(批次 6) - V149 给 columns 加 company_id:先可空加列(末位、ALGORITHM=INSTANT)→ 回填公司 1 → MODIFY 收紧 NOT NULL;三段式缺一即撞 1048。同时建 (company_id, column_key) 复合键、 把公司 2 的 16 笔授权按 column_key 改指向它自己的副本,三类 menu_type 全复制, admin_companies 作为角色内生闸门行不复制(D3)。 - 第三道归属门 PermissionMenuService.resolveScopeCompanyId:站点超管可带 company_id 读写任意公司,非超管锁本公司、越界 403。它注册进 CompanyIdParamGoesThroughReadScopeTest 的 SCOPE_DOORS,四条判据与 readScope / readCompanyIdOrOwn 共用——护栏在代码出口,不靠清单。 - 旁路种子 PermissionMenuSchemaInitializer 只种公司 1:31 段种子逐条钉公司, 按 column_key 点查的 14 段全部带 company_id,否则摘了 DEFAULT 就是跨公司串写。 - CompanyService.create 同一次写入里给新公司复制模板树(D4)。 二、公司 tab 收口(批次 b) tab 条挂在壳层,对 22 页全画;改为按正列表 companyTabAppliesTo(menuKey) 判定, 只有注册表页渲染。护栏钉在用户看见的那个出口。 三、并行会话在制品(控制方「全部提交」,未单独拆分——见下) - V150 店铺密钥 biz_shop_key 按公司(readCompanyIdOrOwn + writeCompanyId 两道门) - V151 品牌库/商品类目推翻为全平台共享:只退唯一键、company_id DEFAULT 保留为 NOT NULL 承重约束(摘了每条 1364);删掉 ProductCategoryControllerCompanyScopeTest 那支"按公司隔离"的旧护栏,readCompanyId 方法一并移除 - invalidasin 字段与外观专利合批的连带改动 为什么不拆笔:后端 3891 例 / 0 红、前端 1731 例 / 0 红这两个读数是"合起来的树"的读数, 拆成多笔会让每一笔落到从未一起验过的组合上,而这一版要直接上两台。 回滚脚本在 backend-java/docs/rollback-V149/V150/V151-*.sql,不放进 Flyway 扫描路径。 设计记录:docs/ops/menu-company-tree-design-2026-10-06.md
This commit is contained in:
@@ -41,37 +41,21 @@ public class DataReadScope {
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属已经**物化成 company_id 列**的表(品牌库 biz_invalid_asin_data)用的谓词出口:
|
||||
* 返回要筛的公司 id,null = 不筛。
|
||||
* 归属物化成 {@code company_id} 列、<b>且可见集不靠账号/分组</b>的表用的谓词出口。
|
||||
*
|
||||
* <p>这些表不能走 {@link #readScope} 的账号集合:2026-10-05 生产只读取证,品牌库 14,801 行里
|
||||
* {@code uploader_user_id} 非空的有 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,
|
||||
* V145 补的列一直是空的),按账号筛等于把全部历史从每一个公司 tab 里静默删掉。
|
||||
* 而 {@code company_id} 那一列虽然是被 DEFAULT 1 盖上去的,对历史却是诚实的:
|
||||
* 第 2 家公司 10-04 14:55 才开通,它名下账号历史任务 0 条、去重库上传 0 行,
|
||||
* 所以「建号之前存在的行都归第 1 家」是可证的事实,不是猜。</p>
|
||||
* <p>今天的消费者是「店铺密钥」{@code biz_shop_key}(V150 起每公司一套)。
|
||||
* <b>品牌库与商品类目不走这里</b>:控制方 2026-10-06 点名这两页"做成所有公司共享的,不区分",
|
||||
* 它们的 {@code company_id} 列只剩 V145/V147 留下的历史值,读写两侧都不引用
|
||||
* (唯一键退回全局见 {@code V151__rule_tables_shared_across_companies.sql})。
|
||||
* 谁要给它们再接一个公司开关,得先推翻那一条定案。</p>
|
||||
*
|
||||
* <p>非超管返回 null(不筛):他们的可见集本来就锁在自己的分组上,叠一层公司会把
|
||||
* 「靠分组可见」的行整批删掉(同 {@code ShopManageController} 的口径)。
|
||||
* 超管的 company_id 是视图开关不是安全边界(spec §4),所以这里不需要再校验它属于谁。</p>
|
||||
*/
|
||||
public Long readCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
|
||||
if (!SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))) {
|
||||
return null;
|
||||
}
|
||||
return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 第三道门:归属物化成 {@code company_id} 列、<b>且可见集不靠账号/分组</b>的表(商品类目)。
|
||||
* <p>"不靠账号/分组"是这一道门存在的理由:可见集若无账号/分组谓词兜住,返回 null 等于
|
||||
* 把整张表交给每一家(2026-10-06 逐节点复验实测:公司 2 的 admin 读该页得 412 行,
|
||||
* 其中 394 行是公司 1 的资产)。若某页的可见集本来就锁在自己的分组/账号上,走
|
||||
* {@link #readScope} 即可,非超管在这里再叠一层公司会把那些行整批删掉。</p>
|
||||
*
|
||||
* <p>与 {@link #readCompanyId} 只差非超管那一支。差别不是省事,是那张表没有可以保护的东西:
|
||||
* 品牌库的"非超管不筛"靠的是账号/分组谓词兜住可见集,而 {@code biz_product_category}
|
||||
* 连账号列都没有(V147 才加的 {@code company_id})。返回 null 在这里等于把整棵树交给每一家——
|
||||
* 2026-10-06 逐节点复验实测:公司 2 的 admin 读该页得 412 行,其中 394 行是公司 1 的自建类目。</p>
|
||||
*
|
||||
* <p>非超管<b>钉在本公司</b>而不是"带别家就返回空":类目树里没有"空树"这个可用视图——
|
||||
* 内置节点(哨兵 0)在任何公司视图里都必须在,否则那一家装不上任何自建子级。
|
||||
* <p>非超管<b>钉在本公司</b>而不是"带别家就返回空":返回空是一个<b>可用视图</b>而不是错误,
|
||||
* 而 {@code create} 的 {@code parentId = null} / 空清单让那一家能从零自建。
|
||||
* 请求里带什么都不算,与 {@code readScope} 非超管分支同一口径(tab 不是安全边界)。</p>
|
||||
*/
|
||||
public Long readCompanyIdOrOwn(AdminUserEntity operator, Long requestedCompanyId) {
|
||||
@@ -85,8 +69,11 @@ public class DataReadScope {
|
||||
* 写侧的行级归属闸门要的值:{@code null} = 平台超管不限,其余账号一律是自己那一家。
|
||||
*
|
||||
* <p>读侧收窄而写侧不收窄,等于"藏起来的行仍然能删"——那是静默删除,不是隔离。
|
||||
* 返回值直接交给 service 与<b>行自己的</b> {@code company_id} 比(不是与 tab 比:
|
||||
* 内置行归哨兵 0,任何公司账号都不该改得动它)。</p>
|
||||
* 返回值直接交给 service 与<b>行自己的</b> {@code company_id} 比(不是与 tab 比)。
|
||||
* 今天的消费者与 {@link #readCompanyIdOrOwn} 同一批(店铺密钥)。
|
||||
* <b>商品类目已经不走这里</b>:那页的 {@code assertRowWritable}(含按 {@code is_builtin}
|
||||
* 拦内置节点的那一刀)随 2026-10-06「类目全平台共享、谁都能改整棵树」的定案一起删掉了,
|
||||
* 内置节点现在对任何管理员可改可删——这是控制方点名的口径,不是漏改。</p>
|
||||
*/
|
||||
public Long writeCompanyId(AdminUserEntity operator) {
|
||||
return SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))
|
||||
|
||||
+6
-1
@@ -7,6 +7,7 @@ import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentSheetBuilder;
|
||||
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext;
|
||||
@@ -1064,7 +1065,11 @@ public class AppearancePatentLlmClient {
|
||||
return NO_INFRINGEMENT;
|
||||
}
|
||||
if (isBrandQueryFailed(titleRisk)) {
|
||||
return BRAND_QUERY_FAILED;
|
||||
// 外观已经判出「无侵权」时别把它整格盖掉:这一行缺的只是商标那一维,
|
||||
// 结论要说「外观无侵权·商标待复核」,用户才不会把已判出的外观结论读成"整单没检测"。
|
||||
return isNoInfringement(appearanceRisk)
|
||||
? "外观" + normalize(appearanceRisk) + AppearancePatentSheetBuilder.PENDING_REVIEW_SUFFIX
|
||||
: BRAND_QUERY_FAILED;
|
||||
}
|
||||
return firstNonBlank(fallbackConclusion, "");
|
||||
}
|
||||
|
||||
+12
@@ -51,6 +51,13 @@ public final class AppearancePatentSheetBuilder {
|
||||
*/
|
||||
public static final String NO_RESULT_TEXT = "未取得检测结果";
|
||||
|
||||
/**
|
||||
* 结论列上「外观已判定、商标那一维没核上」的标记。
|
||||
* <p>放在这里而不是客户端里:结论是这里写的、状态列也是这里判的,
|
||||
* 两处共用一个字面量才不会各写各的(历史上「结论写着查询失败、状态写着成功」就是这么来的)。
|
||||
*/
|
||||
public static final String PENDING_REVIEW_SUFFIX = "·商标待复核";
|
||||
|
||||
private static final String NO_RESULT_REASON = NO_RESULT_TEXT + ":该行没有返回判定,重新运行任务可补检";
|
||||
|
||||
public static void buildResultSheet(Workbook workbook, List<AppearancePatentParsedRowVo> rows,
|
||||
@@ -261,12 +268,17 @@ public final class AppearancePatentSheetBuilder {
|
||||
* 两者都含「侵权」二字;而「商标查询失败」(品牌检测上游查询失败)、「外观识别异常」、
|
||||
* LLM 技术性失败、空白都表示这一行没得出完整结论,一律判「失败」。
|
||||
* 历史缺陷:曾按「结论非空即成功」,于是结论列写着"商标查询失败"、状态列却写"成功"。
|
||||
* 带 {@link #PENDING_REVIEW_SUFFIX} 的结论含「侵权」二字,必须排在字面判定之前判掉,
|
||||
* 否则「外观无侵权·商标待复核」会被读成成功。
|
||||
*/
|
||||
public static String resolveResultStatus(String conclusion) {
|
||||
String normalized = conclusion == null ? "" : conclusion.trim();
|
||||
if (normalized.isBlank() || isTechnicalLlmFailure(normalized)) {
|
||||
return "失败";
|
||||
}
|
||||
if (normalized.contains(PENDING_REVIEW_SUFFIX)) {
|
||||
return "失败";
|
||||
}
|
||||
return normalized.contains("侵权") ? "成功" : "失败";
|
||||
}
|
||||
|
||||
|
||||
+6
-21
@@ -1,6 +1,5 @@
|
||||
package com.nanri.aiimage.modules.collectdata.util;
|
||||
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
|
||||
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity;
|
||||
@@ -16,52 +15,39 @@ import java.util.regex.Pattern;
|
||||
/**
|
||||
* invalid ASIN 批量写入器:把不合规 ASIN 行按批次批量 INSERT IGNORE 写入
|
||||
* biz_invalid_asin_data,替代逐行 insert + 捕获唯一键异常的旧路径。
|
||||
* 幂等由唯一键 (company_id, data_value, brand) + INSERT IGNORE 语义保证;批量失败时
|
||||
* 幂等由唯一键 (data_value, brand) + INSERT IGNORE 语义保证;批量失败时
|
||||
* 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。
|
||||
* 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。
|
||||
*
|
||||
* <p>归属(company_id + uploader_user_id)由调用方给任务发起账号,本类负责推公司:
|
||||
* 此前实体与 INSERT 列清单都不带这两列,V145 补的 company_id 全靠 DEFAULT 1 盖,
|
||||
* 于是第 2 家公司跑货源产生的行会被记成第 1 家,且事后分不开。</p>
|
||||
* <p>这一张黑名单是<b>全平台共享的,不按公司区分</b>(控制方 2026-10-06 定案)。
|
||||
* {@code uploader_user_id} 只记"哪个账号采出来的",推不出账号也照写:
|
||||
* 少一条黑名单 = 下次同样的品牌再买一次代理,而归属记不上不影响任何人看数据。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CollectDataInvalidAsinBatchWriter {
|
||||
|
||||
/** 巡检可 grep 的标记:账号已不存在、推不出公司,这批 rejected 品牌整批不写。 */
|
||||
static final String OWNER_UNRESOLVED_MARKER = "INVALID_ASIN_OWNER_UNRESOLVED";
|
||||
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
|
||||
private final InvalidAsinDataMapper invalidAsinDataMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
private final int batchSize;
|
||||
|
||||
public CollectDataInvalidAsinBatchWriter(InvalidAsinDataMapper invalidAsinDataMapper,
|
||||
CompanyScopeSupport companyScopeSupport,
|
||||
@Value("${aiimage.collect-data.invalid-asin-batch-size:100}") int batchSize) {
|
||||
this.invalidAsinDataMapper = invalidAsinDataMapper;
|
||||
this.companyScopeSupport = companyScopeSupport;
|
||||
this.batchSize = Math.max(1, batchSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。
|
||||
*
|
||||
* @param uploaderUserId 任务发起账号(biz_file_task.user_id);推不出公司时整批不写并打
|
||||
* {@link #OWNER_UNRESOLVED_MARKER}——宁可少记一条黑名单,
|
||||
* 也不把行盖成别家公司(那会让另一家的正常品牌被静默过滤)
|
||||
* @param uploaderUserId 任务发起账号(biz_file_task.user_id);可为 null(账号已删),
|
||||
* 只影响这一列记不记得上,不影响写不写得进
|
||||
*/
|
||||
public int writeBatch(List<CollectDataResultRowVo> rows, Long uploaderUserId) {
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
Long companyId = companyScopeSupport.companyIdOrNull(uploaderUserId);
|
||||
if (companyId == null) {
|
||||
log.warn("{} 无法按账号推出处置公司,本批不写入无效品牌表 rows={} userId={}",
|
||||
OWNER_UNRESOLVED_MARKER, rows.size(), uploaderUserId);
|
||||
return 0;
|
||||
}
|
||||
int written = 0;
|
||||
for (int start = 0; start < rows.size(); start += batchSize) {
|
||||
int end = Math.min(start + batchSize, rows.size());
|
||||
@@ -70,7 +56,6 @@ public class CollectDataInvalidAsinBatchWriter {
|
||||
for (CollectDataResultRowVo row : batch) {
|
||||
InvalidAsinDataEntity entity = toEntity(row);
|
||||
if (entity != null) {
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setUploaderUserId(uploaderUserId);
|
||||
entities.add(entity);
|
||||
}
|
||||
|
||||
+23
-5
@@ -24,6 +24,10 @@ import java.util.Map;
|
||||
* 所以这里探的是【清单】而不是单个列名。清单与探针 SQL 的 IN 列表由 {@code CompanyDefaultGuardTest}
|
||||
* 双向钉同源:只钉"清单里的都在 SQL 里"会漏掉"SQL 里有、清单漏了"那一半,而那一半才是静默的形状。</p>
|
||||
*
|
||||
* <p>清单也会随口径<b>缩短</b>:{@code biz_invalid_asin_data} 与 {@code biz_product_category}
|
||||
* 已按 2026-10-06「这两页全平台共享」的定案一起摘掉,理由见 {@link #WATCHED_TABLES}——
|
||||
* 对一张不再分公司写行的表喊"去摘 DEFAULT",会把一个无人报错的遗留列变成一次真故障(1364)。</p>
|
||||
*
|
||||
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
|
||||
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
|
||||
*/
|
||||
@@ -41,17 +45,31 @@ public class CompanyDefaultGuard {
|
||||
/**
|
||||
* 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条——
|
||||
* 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。
|
||||
* V147 的 {@code biz_product_category} 是第四条:它的 DEFAULT 1 同样只为同批旧 jar 存在,
|
||||
* 摘除动作与上面三张同形(一条元数据操作,禁 MODIFY)。
|
||||
*
|
||||
* <p><b>登记表里只能放"仍然按公司写"的表</b>,这一条比上一句更容易踩。
|
||||
* {@code biz_invalid_asin_data}(V145)与 {@code biz_product_category}(V147)已经在
|
||||
* 2026-10-06「品牌数据库/商品类目做成所有公司共享」的定案里一并摘掉:它们的 {@code company_id}
|
||||
* 现在没有任何读写路径引用,靠 {@code DEFAULT 1} 满足 {@code NOT NULL}。此时喊
|
||||
* {@code COMPANY_DEFAULT_STILL_PRESENT} 并让人去执行本类给出的 {@code DROP DEFAULT},
|
||||
* 后果不是"修好了"而是每一次写入报 1364——品牌库那条还会被
|
||||
* {@code CollectDataInvalidAsinBatchWriter} 吞成 warn ⇒ 接口成功而黑名单静默少一批。
|
||||
* 这两列的 DEFAULT 由下一版的 {@code DROP COLUMN} 一并带走(见 docs/migration-inventory.md)。</p>
|
||||
*
|
||||
* <p>V147 的 {@code biz_product_category} 曾是第三条、V150 的 {@code biz_shop_key} 是第五条:
|
||||
* 加它们时用的是同一条理由,摘它们时也必须是同一条理由——"这张表还分公司吗"是唯一判据。</p>
|
||||
*
|
||||
* <p>V149 的 {@code columns} 方向相反,是【加进来】的一条:菜单树如今真的按公司写(每家公司一套),
|
||||
* 它的 {@code DEFAULT 1} 只为同批的旧 jar 存在(旧实体没有 companyId,insert 整列跳过会报 1364)。
|
||||
* 新 jar 的每个建/改菜单出口都显式落公司,此后留着默认值的后果是"忘了传公司的行静默归第 1 家",
|
||||
* 与上面那两条"没人读的列"不同 —— 判据仍是同一句:这张表还分公司吗。</p>
|
||||
*/
|
||||
static final List<String> WATCHED_TABLES = List.of(
|
||||
"users", "biz_invalid_asin_data", "biz_dedupe_total_data", "biz_product_category");
|
||||
"users", "biz_dedupe_total_data", "biz_shop_key", "columns");
|
||||
|
||||
private static final String COLUMN_DEFAULT_SQL = """
|
||||
SELECT TABLE_NAME, COLUMN_DEFAULT FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME = 'company_id'
|
||||
AND TABLE_NAME IN ('users', 'biz_invalid_asin_data', 'biz_dedupe_total_data',
|
||||
'biz_product_category')
|
||||
AND TABLE_NAME IN ('users', 'biz_dedupe_total_data', 'biz_shop_key', 'columns')
|
||||
""";
|
||||
|
||||
private final CompanyMapper companyMapper;
|
||||
|
||||
+12
-1
@@ -7,8 +7,10 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -31,6 +33,7 @@ public class CompanyService {
|
||||
|
||||
private final CompanyMapper companyMapper;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
|
||||
/** 建号指定的公司必须真实存在且启用:否则账号挂在查不到的公司上,按公司筛选时整体失明。 */
|
||||
public CompanyEntity requireActive(Long companyId) {
|
||||
@@ -104,7 +107,14 @@ public class CompanyService {
|
||||
return company.getCompanyName();
|
||||
}
|
||||
|
||||
/** 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。 */
|
||||
/**
|
||||
* 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。
|
||||
*
|
||||
* <p>事务包住两件事:插公司行 + 给它复制一套菜单树。每家公司一棵树之后,零菜单行的租户
|
||||
* 表现是"那家账号侧边栏全空"且不报错,所以建树不能留成上线后的人工动作;
|
||||
* 复制失败必须连公司行一起回滚,不留半成品。</p>
|
||||
*/
|
||||
@Transactional
|
||||
public CompanyEntity create(AdminUserEntity operator, CompanySaveRequest request) {
|
||||
ensureSuperAdmin(operator);
|
||||
String companyName = requireValidName(request.getCompanyName());
|
||||
@@ -117,6 +127,7 @@ public class CompanyService {
|
||||
entity.setStatus(status);
|
||||
entity.setRemark(remark);
|
||||
companyMapper.insert(entity);
|
||||
permissionMenuService.copyTreeFromTemplate(entity.getId(), operator.getCompanyId());
|
||||
return entity;
|
||||
}
|
||||
|
||||
|
||||
+8
-14
@@ -3,7 +3,6 @@ package com.nanri.aiimage.modules.invalidasin.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataItemVo;
|
||||
@@ -39,7 +38,7 @@ import java.security.MessageDigest;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin/invalid-asin-data")
|
||||
@Tag(name = "不符合ASIN数据", description = "维护不符合ASIN数据列表,支持增删改查。")
|
||||
@Tag(name = "品牌数据库", description = "维护品牌数据库(不符合规则的 ASIN / 品牌)列表,支持增删改查。全平台共享,不按公司区分。")
|
||||
public class InvalidAsinDataController {
|
||||
|
||||
private static final String INVALID_ASIN_DATA_COLUMN_KEY = "admin_invalid_asin_data";
|
||||
@@ -50,10 +49,9 @@ public class InvalidAsinDataController {
|
||||
private final InvalidAsinDataService invalidAsinDataService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询不符合ASIN数据", description = "分页查询不符合ASIN数据,支持按 ASIN/品牌 模糊搜索。")
|
||||
@Operation(summary = "分页查询品牌数据库", description = "分页查询品牌数据库(全平台共享,不按公司区分),支持按 ASIN/品牌 模糊搜索。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataPageVo.class)))
|
||||
})
|
||||
@@ -64,18 +62,14 @@ public class InvalidAsinDataController {
|
||||
@Parameter(description = "ASIN 模糊搜索") @RequestParam(name = "data_value", required = false) String dataValue,
|
||||
@Parameter(description = "品牌模糊搜索") @RequestParam(name = "brand", required = false) String brand,
|
||||
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireInvalidAsinDataAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);
|
||||
return ApiResponse.success(invalidAsinDataService.page(
|
||||
page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin(),
|
||||
scopedCompanyId));
|
||||
page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin()));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新增不符合ASIN数据", description = "新增一条不符合ASIN数据。")
|
||||
@Operation(summary = "新增品牌数据库记录", description = "新增一条品牌数据库记录(全平台共享)。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复")
|
||||
@@ -89,7 +83,7 @@ public class InvalidAsinDataController {
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "更新不符合ASIN数据", description = "按 ID 更新一条不符合ASIN数据。")
|
||||
@Operation(summary = "更新品牌数据库记录", description = "按 ID 更新一条品牌数据库记录。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复"),
|
||||
@@ -105,7 +99,7 @@ public class InvalidAsinDataController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除不符合ASIN数据", description = "按 ID 删除一条不符合ASIN数据。")
|
||||
@Operation(summary = "删除品牌数据库记录", description = "按 ID 删除一条品牌数据库记录。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "数据不存在")
|
||||
@@ -127,7 +121,7 @@ public class InvalidAsinDataController {
|
||||
if (!superAdmin && !hasInvalidAsinDataPermission(operator)) {
|
||||
throw new BusinessException(403, "无权访问品牌数据库");
|
||||
}
|
||||
return new RequestOperator(operator.getId(), superAdmin, operator);
|
||||
return new RequestOperator(operator.getId(), superAdmin);
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveOperator(HttpServletRequest request) {
|
||||
@@ -170,7 +164,7 @@ public class InvalidAsinDataController {
|
||||
|
||||
|
||||
|
||||
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
|
||||
private record RequestOperator(Long id, boolean superAdmin) {
|
||||
}
|
||||
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||
|
||||
+10
-6
@@ -12,22 +12,26 @@ import java.util.List;
|
||||
public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> {
|
||||
|
||||
/**
|
||||
* 批量 INSERT IGNORE:命中唯一键 (company_id, data_value, brand) 的重复行静默跳过,幂等。
|
||||
* 批量 INSERT IGNORE:命中唯一键 (data_value, brand) 的重复行静默跳过,幂等。
|
||||
* created_at/updated_at 不显式写入:依赖列的 DEFAULT CURRENT_TIMESTAMP。
|
||||
* 显式传 null 会绕过默认值,在宽松 SQL 模式下落为 '0000-00-00 00:00:00',
|
||||
* 随后在 NO_ZERO_DATE 模式(生产已启用)下读取即报 Zero date value prohibited。
|
||||
*
|
||||
* <p>company_id 与 uploader_user_id 由调用方填好:company_id 是 NOT NULL,
|
||||
* 这一列显式传 null 不会走 DEFAULT 1,而是直接报错(上面 created_at 那段说的正是这类列的
|
||||
* "宽松模式才静默"),所以归属推不出来时调用方必须整批不写,而不是塞 null 进来。</p>
|
||||
* <p>列清单里<b>没有</b> company_id:品牌数据库全平台共享,归属不参与幂等(控制方 2026-10-06 定案)。
|
||||
* 库里那一列带 {@code DEFAULT 1} 且仍 NOT NULL,所以省略它安全;反过来<b>显式传 null 会直接报错</b>
|
||||
* (上面 created_at 那段说的正是这类列的"宽松模式才静默")。</p>
|
||||
*
|
||||
* <p>uploader_user_id 可空,jdbcType 必须写:任务账号已被删时这一列就是 null,
|
||||
* 不告诉 MyBatis 类型它会抛 "Error setting null parameter",而调用方把异常吞成 log.warn,
|
||||
* 于是整批黑名单静默丢掉。</p>
|
||||
*/
|
||||
@Insert("""
|
||||
<script>
|
||||
INSERT IGNORE INTO biz_invalid_asin_data
|
||||
(data_value, brand, record_source, company_id, uploader_user_id)
|
||||
(data_value, brand, record_source, uploader_user_id)
|
||||
VALUES
|
||||
<foreach collection="rows" item="row" separator=",">
|
||||
(#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.companyId}, #{row.uploaderUserId})
|
||||
(#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.uploaderUserId,jdbcType=BIGINT})
|
||||
</foreach>
|
||||
</script>
|
||||
""")
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "不符合ASIN数据新增请求")
|
||||
@Schema(description = "品牌数据库新增请求")
|
||||
public class InvalidAsinDataCreateRequest {
|
||||
|
||||
@NotBlank(message = "ASIN 不能为空")
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "不符合ASIN数据更新请求")
|
||||
@Schema(description = "品牌数据库更新请求")
|
||||
public class InvalidAsinDataUpdateRequest {
|
||||
|
||||
@NotBlank(message = "ASIN 不能为空")
|
||||
|
||||
+12
-4
@@ -9,6 +9,16 @@ import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 品牌数据库(不符合 ASIN / 品牌黑名单)——<b>全平台共享,不按公司区分</b>(控制方 2026-10-06 定案)。
|
||||
*
|
||||
* <p>所以这里<b>不声明</b> {@code company_id} 字段。库里那一列(V145 加的,带 {@code DEFAULT 1})
|
||||
* 暂时还在,但没有任何读写路径引用它:不声明字段 ⇒ SELECT 列清单与 INSERT 都不含它 ⇒ 新 jar 配旧库
|
||||
* (列还在)不会报错。摘列必须等两台都跑上这一版,否则旧 jar 带着这一列来 INSERT/SELECT 会撞
|
||||
* {@code Unknown column},而批量写入器把异常吞成 log.warn——那是静默丢黑名单行。
|
||||
* 唯一键退回全局见 {@code V151__rule_tables_shared_across_companies.sql};<b>摘列本身不在 V151 里</b>
|
||||
* (V151 只退键),它是下一版的待办,取号与理由见 {@code docs/migration-inventory.md}。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_invalid_asin_data")
|
||||
public class InvalidAsinDataEntity {
|
||||
@@ -19,11 +29,9 @@ public class InvalidAsinDataEntity {
|
||||
private String brand;
|
||||
private Long groupId;
|
||||
/**
|
||||
* 归属公司(company.id)。列由 V145 物化,但**实体与批量 INSERT 的列清单此前都没带它**,
|
||||
* 所以 2026-10-05 生产只读取证 14,801 行全是被 DEFAULT 1 盖出来的。写入侧从本版本起显式盖章。
|
||||
* 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。
|
||||
* 这一列只记"谁加的",不参与任何筛选——品牌数据库全平台共享,见类注释。
|
||||
*/
|
||||
private Long companyId;
|
||||
/** 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。 */
|
||||
private Long uploaderUserId;
|
||||
private String recordSource;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Schema(description = "不符合ASIN数据项")
|
||||
@Schema(description = "品牌数据库数据项")
|
||||
public class InvalidAsinDataItemVo {
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "不符合ASIN数据分页结果")
|
||||
@Schema(description = "品牌数据库分页结果")
|
||||
public class InvalidAsinDataPageVo {
|
||||
|
||||
@Schema(description = "列表")
|
||||
|
||||
+10
-15
@@ -2,7 +2,6 @@ package com.nanri.aiimage.modules.invalidasin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
|
||||
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
|
||||
@@ -31,10 +30,9 @@ public class InvalidAsinDataService {
|
||||
|
||||
private final InvalidAsinDataMapper invalidAsinDataMapper;
|
||||
private final ShopManageGroupService shopManageGroupService;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand,
|
||||
Long groupId, Long operatorId, boolean superAdmin, Long companyFilterId) {
|
||||
Long groupId, Long operatorId, boolean superAdmin) {
|
||||
long safePage = Math.max(page, 1);
|
||||
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
|
||||
String safeKeyword = keyword == null ? "" : keyword.trim();
|
||||
@@ -48,9 +46,6 @@ public class InvalidAsinDataService {
|
||||
.like(!safeDataValue.isEmpty(), InvalidAsinDataEntity::getDataValue, safeDataValue)
|
||||
.like(!safeBrand.isEmpty(), InvalidAsinDataEntity::getBrand, safeBrand)
|
||||
.orderByDesc(InvalidAsinDataEntity::getId);
|
||||
if (companyFilterId != null) {
|
||||
query.eq(InvalidAsinDataEntity::getCompanyId, companyFilterId);
|
||||
}
|
||||
if (!superAdmin) {
|
||||
Long fixedGroupId = resolveFixedAccessibleGroupId(operatorId);
|
||||
if (fixedGroupId == null) {
|
||||
@@ -85,16 +80,13 @@ public class InvalidAsinDataService {
|
||||
@Transactional
|
||||
public InvalidAsinDataItemVo create(InvalidAsinDataCreateRequest request, Long operatorId, boolean superAdmin) {
|
||||
ShopManageGroupEntity group = resolveManualWriteGroup(request.getGroupId(), operatorId, superAdmin);
|
||||
// 归属从操作者会话推导,不读请求里的公司:超管在哪个 tab 下建都归他自己那家公司(一期定案口径)。
|
||||
Long companyId = companyScopeSupport.requireCompanyId(operatorId);
|
||||
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
|
||||
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
|
||||
ensureUnique(dataValue, null, companyId);
|
||||
ensureUnique(dataValue, null);
|
||||
InvalidAsinDataEntity entity = new InvalidAsinDataEntity();
|
||||
entity.setDataValue(dataValue);
|
||||
entity.setBrand(brand);
|
||||
entity.setGroupId(group.getId());
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setUploaderUserId(operatorId);
|
||||
entity.setRecordSource(RECORD_SOURCE_MANUAL);
|
||||
invalidAsinDataMapper.insert(entity);
|
||||
@@ -114,7 +106,7 @@ public class InvalidAsinDataService {
|
||||
}
|
||||
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
|
||||
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
|
||||
ensureUnique(dataValue, id, entity.getCompanyId());
|
||||
ensureUnique(dataValue, id);
|
||||
entity.setDataValue(dataValue);
|
||||
entity.setBrand(brand);
|
||||
String groupName = "";
|
||||
@@ -153,12 +145,15 @@ public class InvalidAsinDataService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用层的重复预检必须与 V145 放宽后的唯一键同宽——(company_id, data_value, brand)。
|
||||
* 少了公司这一维,第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。
|
||||
* 全平台一份黑名单:同一条 ASIN 只要已经被任何一家录过,第二家再录就报「ASIN 已存在」。
|
||||
*
|
||||
* <p>预检比 {@code data_value} 一个字段,而库里唯一键是 {@code (data_value, brand)} ——预检更严,
|
||||
* 这是改造前就有的口径(同一 ASIN 换品牌重录在页面上看不出区别)。V145 一度给这里叠过公司维度,
|
||||
* 2026-10-06 控制方定案"品牌数据库不区分公司"后摘回全局。<b>不许再把公司加回来</b>:
|
||||
* 那会让同一条 ASIN 在共享列表里长出两行,而这一页没有任何地方告诉操作员它们分属两家。</p>
|
||||
*/
|
||||
private void ensureUnique(String dataValue, Long excludeId, Long companyId) {
|
||||
private void ensureUnique(String dataValue, Long excludeId) {
|
||||
LambdaQueryWrapper<InvalidAsinDataEntity> query = new LambdaQueryWrapper<InvalidAsinDataEntity>()
|
||||
.eq(companyId != null, InvalidAsinDataEntity::getCompanyId, companyId)
|
||||
.eq(InvalidAsinDataEntity::getDataValue, dataValue)
|
||||
.last("LIMIT 1");
|
||||
InvalidAsinDataEntity exists = invalidAsinDataMapper.selectOne(query);
|
||||
|
||||
+39
-12
@@ -53,17 +53,29 @@ public class PermissionMenuController {
|
||||
public ApiResponse<List<PermissionMenuItemVo>> listMenus(HttpServletRequest request,
|
||||
@Parameter(description = "菜单类型: app/admin") @RequestParam(required = false) String menuType,
|
||||
@Parameter(description = "授权树语义: true 时非超管只返回自己可授予的菜单")
|
||||
@RequestParam(required = false, defaultValue = "false") boolean grantableOnly) {
|
||||
@RequestParam(required = false, defaultValue = "false") boolean grantableOnly,
|
||||
@Parameter(description = "公司 ID:仅站点超管可指定,缺省取操作者本公司")
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
// 传入操作者:授权树据此只下发(并把范围外节点标成不可勾选)操作者有权授予的菜单
|
||||
return ApiResponse.success(permissionMenuService.list(requireAdmin(request), menuType, grantableOnly));
|
||||
AdminUserEntity operator = requireAdmin(request);
|
||||
// 归属判据只有一条(读写共用):先在这里过一遍,别家公司的 company_id 在取任何数之前就被 403 拒掉,
|
||||
// 传下去的是定下来那一家,而不是 tab 原文。service 内部还会再判一次(幂等),控制器不重算口径。
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
return ApiResponse.success(permissionMenuService.list(
|
||||
operator, menuType, grantableOnly, scopeCompanyId));
|
||||
}
|
||||
|
||||
@PostMapping("/permission-menus")
|
||||
@Operation(summary = "新增菜单权限项")
|
||||
public ApiResponse<PermissionMenuItemVo> createMenu(HttpServletRequest httpRequest,
|
||||
@Valid @RequestBody PermissionMenuCreateRequest request) {
|
||||
@Valid @RequestBody PermissionMenuCreateRequest request,
|
||||
@Parameter(description = "建到哪家公司的树:仅站点超管可指定")
|
||||
@RequestParam(name = "company_id", required = false)
|
||||
Long companyId) {
|
||||
AdminUserEntity operator = requireAdmin(httpRequest);
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
return ApiResponse.success("创建成功", permissionMenuService.create(
|
||||
requireAdmin(httpRequest), request));
|
||||
operator, scopeCompanyId, request));
|
||||
}
|
||||
|
||||
@PutMapping("/permission-menus/{id}")
|
||||
@@ -86,7 +98,7 @@ public class PermissionMenuController {
|
||||
@Operation(summary = "同级菜单拖拽排序")
|
||||
public ApiResponse<Void> reorderColumns(HttpServletRequest httpRequest,
|
||||
@RequestBody(required = false) Map<String, Object> body) {
|
||||
requireAdmin(httpRequest);
|
||||
AdminUserEntity operator = requireAdmin(httpRequest);
|
||||
Object raw = body == null ? null
|
||||
: (body.get("ordered_ids") != null ? body.get("ordered_ids") : body.get("orderedIds"));
|
||||
if (!(raw instanceof List<?> list)) {
|
||||
@@ -104,7 +116,8 @@ public class PermissionMenuController {
|
||||
}
|
||||
}
|
||||
}
|
||||
permissionMenuService.reorder(ids);
|
||||
// 带上操作者:重排会写兄弟集的 sort_order,每家公司一棵树之后必须先确认锚点行属于他
|
||||
permissionMenuService.reorder(operator, ids);
|
||||
return ApiResponse.success("排序已保存", null);
|
||||
}
|
||||
|
||||
@@ -142,34 +155,48 @@ public class PermissionMenuController {
|
||||
@GetMapping("/image-video-task-permissions")
|
||||
@Operation(summary = "查询视频任务数据权限用户")
|
||||
public ApiResponse<List<ImageVideoDataPermissionUserVo>> listImageVideoDataPermissionUsers(
|
||||
HttpServletRequest request) {
|
||||
return ApiResponse.success(permissionMenuService.listImageVideoDataPermissionUsers(requireAdmin(request)));
|
||||
HttpServletRequest request,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireAdmin(request);
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
return ApiResponse.success(permissionMenuService.listImageVideoDataPermissionUsers(
|
||||
operator, scopeCompanyId));
|
||||
}
|
||||
|
||||
@PutMapping("/image-video-task-permissions")
|
||||
@Operation(summary = "更新视频任务数据权限用户")
|
||||
public ApiResponse<Integer> updateImageVideoDataPermissionUsers(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) {
|
||||
AdminUserEntity operator = requireAdmin(request);
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
int grantedCount = permissionMenuService.updateImageVideoDataPermissionUsers(
|
||||
requireAdmin(request), body == null ? List.of() : body.getUserIds());
|
||||
operator, scopeCompanyId, body == null ? List.of() : body.getUserIds());
|
||||
return ApiResponse.success("视频任务权限已更新", grantedCount);
|
||||
}
|
||||
|
||||
@GetMapping("/shop-data-crawl-task-permissions")
|
||||
@Operation(summary = "查询店铺数据任务数据权限用户")
|
||||
public ApiResponse<List<ImageVideoDataPermissionUserVo>> listShopDataCrawlDataPermissionUsers(
|
||||
HttpServletRequest request) {
|
||||
return ApiResponse.success(permissionMenuService.listShopDataCrawlDataPermissionUsers(requireAdmin(request)));
|
||||
HttpServletRequest request,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireAdmin(request);
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
return ApiResponse.success(permissionMenuService.listShopDataCrawlDataPermissionUsers(
|
||||
operator, scopeCompanyId));
|
||||
}
|
||||
|
||||
@PutMapping("/shop-data-crawl-task-permissions")
|
||||
@Operation(summary = "更新店铺数据任务数据权限用户")
|
||||
public ApiResponse<Integer> updateShopDataCrawlDataPermissionUsers(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) {
|
||||
AdminUserEntity operator = requireAdmin(request);
|
||||
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
|
||||
int grantedCount = permissionMenuService.updateShopDataCrawlDataPermissionUsers(
|
||||
requireAdmin(request), body == null ? List.of() : body.getUserIds());
|
||||
operator, scopeCompanyId, body == null ? List.of() : body.getUserIds());
|
||||
return ApiResponse.success("店铺数据任务权限已更新", grantedCount);
|
||||
}
|
||||
|
||||
|
||||
+9
@@ -22,6 +22,15 @@ public class PermissionMenuEntity {
|
||||
private String menuType;
|
||||
private String routePath;
|
||||
private Integer sortOrder;
|
||||
/**
|
||||
* 归属公司(V149):菜单字典从"全平台一棵树"改成"每家公司一套树",
|
||||
* {@code column_key} 与 {@code (menu_type, route_path)} 都只在本公司内唯一。
|
||||
*
|
||||
* <p>写侧一律显式赋值({@code PermissionMenuService} 的 create/update 从操作者或目标行推导),
|
||||
* 不许依赖列上那条临时的 {@code DEFAULT 1}:V149 留 DEFAULT 只为让同批的旧 jar 不报 1364,
|
||||
* 下一版就摘掉;一旦有出口忘了赋值,DEFAULT 会把别家的菜单静默塞进厦门米椿花。</p>
|
||||
*/
|
||||
private Long companyId;
|
||||
private LocalDateTime createdAt;
|
||||
/**
|
||||
* 更新时间(V131 新增):由数据库维护(DEFAULT CURRENT_TIMESTAMP + ON UPDATE CURRENT_TIMESTAMP)。
|
||||
|
||||
+58
-35
@@ -11,6 +11,19 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* 菜单字典的建表/种子旁路(生产默认关,见 application.yml 的 aiimage.permission-schema-init.enabled)。
|
||||
*
|
||||
* <p>V149 之后它只维护<b>公司 1 那棵平台默认树</b>:每一条种子语句的 INSERT 列清单都显式写
|
||||
* {@code company_id = 1},判存守卫、认父 JOIN、按 key 的 UPDATE 也一律带 {@code company_id = 1}——
|
||||
* 因为 column_key 如今只在单家公司内唯一,一条裸 {@code WHERE column_key = ...} 在这张表上
|
||||
* 就是"把每一家的同名行都改一遍"(把别家副本的 parent 拍平、或把授权发给别家的行 id)。
|
||||
* 显式写公司还有一层作用:这条通道不再依赖列上那条 {@code DEFAULT 1},
|
||||
* 于是 V152 起摘掉它({@code ALTER TABLE columns ALTER COLUMN company_id DROP DEFAULT})
|
||||
* 不会让这里的建号变成 1364 被 {@code executeQuietly} 吞成"一声不响少一套菜单"。
|
||||
* 别家公司的树不由这里插行——存量公司归 V149 的复制段,新建公司归
|
||||
* {@code PermissionMenuService.copyTreeFromTemplate}({@code CompanyService.create} 同事务调用)。</p>
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@@ -92,17 +105,26 @@ public class PermissionMenuSchemaInitializer {
|
||||
name VARCHAR(128) NOT NULL COMMENT '菜单标题',
|
||||
column_key VARCHAR(64) NOT NULL COMMENT '菜单唯一标识',
|
||||
parent_id INT NULL COMMENT '直接父菜单 ID',
|
||||
company_id BIGINT NOT NULL DEFAULT 1 COMMENT '归属公司:每家公司一套菜单树',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_column_key (column_key)
|
||||
UNIQUE KEY uk_company_column_key (company_id, column_key)
|
||||
)
|
||||
""");
|
||||
executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key");
|
||||
executeQuietly("ALTER TABLE columns ADD COLUMN parent_id INT NULL COMMENT '直接父菜单 ID' AFTER id");
|
||||
executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type");
|
||||
executeQuietly("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path");
|
||||
executeQuietly("ALTER TABLE columns ADD COLUMN company_id BIGINT NULL COMMENT '归属公司:每家公司一套菜单树'");
|
||||
executeQuietly("UPDATE columns SET company_id = 1 WHERE company_id IS NULL");
|
||||
executeQuietly("ALTER TABLE columns MODIFY COLUMN company_id BIGINT NOT NULL DEFAULT 1 COMMENT '归属公司:每家公司一套菜单树'");
|
||||
executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''");
|
||||
executeQuietly("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0");
|
||||
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_menu_type_route_path (menu_type, route_path)");
|
||||
// 两条全局唯一键在"每家公司一套树"之后会把别家同名菜单挡成"标识已存在"。
|
||||
// 先加复合键、再摘旧键(与 V149 第 4/5 段同一顺序:任一步失败都至少还剩一条键守并发)。
|
||||
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_company_column_key (company_id, column_key)");
|
||||
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_company_menu_type_route_path (company_id, menu_type, route_path)");
|
||||
executeQuietly("ALTER TABLE columns DROP INDEX uk_column_key");
|
||||
executeQuietly("ALTER TABLE columns DROP INDEX uk_menu_type_route_path");
|
||||
ensureDefaultAdminGroups();
|
||||
ensureDefaultAdminMenus();
|
||||
boolean shopDataCrawlDataPermissionCreated = ensureShopDataCrawlAdminDefaults();
|
||||
@@ -126,10 +148,10 @@ public class PermissionMenuSchemaInitializer {
|
||||
private void ensureDefaultAdminGroups() {
|
||||
for (DefaultAdminGroup group : DEFAULT_ADMIN_GROUPS) {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, parent_id, sort_order)
|
||||
SELECT '%s', '%s', 'admin', '%s', NULL, %d
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, parent_id, sort_order)
|
||||
SELECT 1, '%s', '%s', 'admin', '%s', NULL, %d
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = '%s'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
|
||||
)
|
||||
""".formatted(group.name(), group.columnKey(), group.routePath(), group.sortOrder(), group.columnKey()));
|
||||
}
|
||||
@@ -138,21 +160,21 @@ public class PermissionMenuSchemaInitializer {
|
||||
private void ensureDefaultAdminMenus() {
|
||||
for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT '%s', '%s', 'admin', '%s', %d, parent.id
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT 1, '%s', '%s', 'admin', '%s', %d, parent.id
|
||||
FROM columns parent
|
||||
WHERE parent.column_key = '%s'
|
||||
WHERE parent.company_id = 1 AND parent.column_key = '%s'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = '%s'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
|
||||
)
|
||||
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(),
|
||||
menu.parentKey(), menu.columnKey()));
|
||||
executeQuietly("""
|
||||
UPDATE columns child
|
||||
JOIN columns parent ON parent.column_key = '%s'
|
||||
JOIN columns parent ON parent.company_id = 1 AND parent.column_key = '%s'
|
||||
SET child.name = '%s', child.sort_order = %d,
|
||||
child.parent_id = COALESCE(child.parent_id, parent.id)
|
||||
WHERE child.column_key = '%s'
|
||||
WHERE child.company_id = 1 AND child.column_key = '%s'
|
||||
""".formatted(menu.parentKey(), menu.name(), menu.sortOrder(), menu.columnKey()));
|
||||
}
|
||||
}
|
||||
@@ -160,16 +182,16 @@ public class PermissionMenuSchemaInitializer {
|
||||
private void ensureDefaultAppMenus() {
|
||||
for (DefaultAppMenu menu : DEFAULT_APP_MENUS) {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT '%s', '%s', 'app', '%s', %d
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT 1, '%s', '%s', 'app', '%s', %d
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = '%s'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
|
||||
)
|
||||
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), menu.columnKey()));
|
||||
executeQuietly("""
|
||||
UPDATE columns
|
||||
SET sort_order = %d, route_path = '%s', menu_type = 'app', parent_id = NULL
|
||||
WHERE column_key = '%s'
|
||||
WHERE company_id = 1 AND column_key = '%s'
|
||||
""".formatted(menu.sortOrder(), menu.routePath(), menu.columnKey()));
|
||||
}
|
||||
}
|
||||
@@ -177,55 +199,55 @@ public class PermissionMenuSchemaInitializer {
|
||||
private void ensureDefaultAppChildMenus() {
|
||||
// Older migrations used underscore keys for a few app pages. Normalize
|
||||
// them once so the frontend item key and permission key stay aligned.
|
||||
executeQuietly("UPDATE columns SET column_key = 'collect-data' WHERE column_key = 'collect_data'");
|
||||
executeQuietly("UPDATE columns SET column_key = 'appearance-patent' WHERE column_key = 'appearance_patent'");
|
||||
executeQuietly("UPDATE columns SET column_key = 'similar-asin' WHERE column_key = 'similar_asin'");
|
||||
executeQuietly("UPDATE columns SET column_key = 'collect-data' WHERE company_id = 1 AND column_key = 'collect_data'");
|
||||
executeQuietly("UPDATE columns SET column_key = 'appearance-patent' WHERE company_id = 1 AND column_key = 'appearance_patent'");
|
||||
executeQuietly("UPDATE columns SET column_key = 'similar-asin' WHERE company_id = 1 AND column_key = 'similar_asin'");
|
||||
|
||||
for (DefaultAppChildMenu menu : DEFAULT_APP_CHILD_MENUS) {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT '%s', '%s', 'app', '%s', %d, parent.id
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT 1, '%s', '%s', 'app', '%s', %d, parent.id
|
||||
FROM columns parent
|
||||
WHERE parent.column_key = '%s'
|
||||
WHERE parent.company_id = 1 AND parent.column_key = '%s'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM columns existing WHERE existing.column_key = '%s'
|
||||
SELECT 1 FROM columns existing WHERE existing.company_id = 1 AND existing.column_key = '%s'
|
||||
)
|
||||
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(),
|
||||
menu.parentKey(), menu.columnKey()));
|
||||
executeQuietly("""
|
||||
UPDATE columns child
|
||||
JOIN columns parent ON parent.column_key = '%s'
|
||||
JOIN columns parent ON parent.company_id = 1 AND parent.column_key = '%s'
|
||||
SET child.name = '%s', child.menu_type = 'app', child.route_path = '%s',
|
||||
child.sort_order = %d, child.parent_id = parent.id
|
||||
WHERE child.column_key = '%s'
|
||||
WHERE child.company_id = 1 AND child.column_key = '%s'
|
||||
""".formatted(menu.parentKey(), menu.name(), menu.routePath(), menu.sortOrder(), menu.columnKey()));
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureInternalDataPermissions() {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT '视频任务数据查看', 'admin_image_video_task_data', 'internal', 'image-video-task-data', 0
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT 1, '视频任务数据查看', 'admin_image_video_task_data', 'internal', 'image-video-task-data', 0
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = 'admin_image_video_task_data'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_image_video_task_data'
|
||||
)
|
||||
""");
|
||||
}
|
||||
|
||||
private boolean ensureShopDataCrawlAdminDefaults() {
|
||||
executeQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT '店铺数据记录', 'admin_shop_data_crawl_tasks', 'admin', 'shop-data-crawl-tasks', 82,
|
||||
(SELECT id FROM columns WHERE column_key = 'admin_group_shop' LIMIT 1)
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
|
||||
SELECT 1, '店铺数据记录', 'admin_shop_data_crawl_tasks', 'admin', 'shop-data-crawl-tasks', 82,
|
||||
(SELECT id FROM columns WHERE company_id = 1 AND column_key = 'admin_group_shop' LIMIT 1)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = 'admin_shop_data_crawl_tasks'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_shop_data_crawl_tasks'
|
||||
)
|
||||
""");
|
||||
return executeUpdateQuietly("""
|
||||
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT '店铺数据任务数据查看', 'admin_shop_data_crawl_task_data', 'internal', 'shop-data-crawl-task-data', 0
|
||||
INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
|
||||
SELECT 1, '店铺数据任务数据查看', 'admin_shop_data_crawl_task_data', 'internal', 'shop-data-crawl-task-data', 0
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM columns WHERE column_key = 'admin_shop_data_crawl_task_data'
|
||||
SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_shop_data_crawl_task_data'
|
||||
)
|
||||
""") > 0;
|
||||
}
|
||||
@@ -236,7 +258,8 @@ public class PermissionMenuSchemaInitializer {
|
||||
SELECT old_perm.user_id, data_col.id
|
||||
FROM user_column_permission old_perm
|
||||
INNER JOIN columns old_col ON old_col.id = old_perm.column_id
|
||||
INNER JOIN columns data_col ON data_col.column_key = 'admin_shop_data_crawl_task_data'
|
||||
INNER JOIN columns data_col ON data_col.company_id = old_col.company_id
|
||||
AND data_col.column_key = 'admin_shop_data_crawl_task_data'
|
||||
LEFT JOIN user_column_permission existing
|
||||
ON existing.user_id = old_perm.user_id
|
||||
AND existing.column_id = data_col.id
|
||||
|
||||
+332
-66
@@ -79,9 +79,24 @@ public class PermissionMenuService {
|
||||
* 一旦可勾,「勾父覆盖全部后代」就会把树上未展示的范围外菜单一起授出去。
|
||||
* 保存侧必须配套按操作者范围替换,见
|
||||
* {@link #updateUserColumnPermissions(AdminUserEntity, Long, UserColumnPermissionUpdateRequest, String, boolean)}。
|
||||
* @param requestedCompanyId V149 目录页的公司 tab:站点超管可指定任意公司的树;非超管传别家 403,
|
||||
* 不传就锁本公司。缺省值不是"全公司"——每家公司一套树之后,跨公司的目录混在一起
|
||||
* 等于让 {@code column_key} 在同一个响应里出现两次,前端按 key 建树会直接长错。
|
||||
*/
|
||||
public List<PermissionMenuItemVo> list(AdminUserEntity operator, String menuType,
|
||||
boolean grantableOnly, Long requestedCompanyId) {
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
return listAt(companyId, operator, menuType, grantableOnly);
|
||||
}
|
||||
|
||||
public List<PermissionMenuItemVo> list(AdminUserEntity operator, String menuType, boolean grantableOnly) {
|
||||
List<PermissionMenuEntity> menus = loadMenus(menuType);
|
||||
return list(operator, menuType, grantableOnly, null);
|
||||
}
|
||||
|
||||
/** 目录/授权树的唯一出口:{@code companyId} 为非空时只取那一棵树的行,null 仅留给无操作者的内部调用。 */
|
||||
private List<PermissionMenuItemVo> listAt(Long companyId, AdminUserEntity operator,
|
||||
String menuType, boolean grantableOnly) {
|
||||
List<PermissionMenuEntity> menus = loadMenus(companyId, menuType);
|
||||
Set<Long> grantableIds = resolveGrantableMenuIds(operator);
|
||||
List<PermissionMenuEntity> visibleMenus = menus;
|
||||
if (grantableOnly && grantableIds != null) {
|
||||
@@ -109,13 +124,68 @@ public class PermissionMenuService {
|
||||
/**
|
||||
* 操作者可授予的菜单 id 全集(自身直接授权 + 其后代)。
|
||||
*
|
||||
* <p>V149 之后按<b>操作者本公司</b>那棵树展开:授权只会指向本公司的行(迁移第 9 段与
|
||||
* 闸门 3 保证),拿全平台目录去展开等于把别家同名菜单的 id 也算进"可授予",
|
||||
* 那是"范围收窄只做在界面上"的同一类事故。</p>
|
||||
*
|
||||
* @return null 表示不限制(超管或无操作者)
|
||||
*/
|
||||
private Set<Long> resolveGrantableMenuIds(AdminUserEntity operator) {
|
||||
if (operator == null || operator.getId() == null || isSuperAdmin(operator)) {
|
||||
return null;
|
||||
}
|
||||
return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(operator.getId())), loadMenus(null));
|
||||
return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(operator.getId())),
|
||||
loadMenus(operator.getCompanyId(), null));
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属公司的统一判据(设计文档 §2 D2):不传就锁操作者本公司;站点超管可以显式指定
|
||||
* 任意一家(他今天就在替两家公司共 133 只账号配权限),非超管传别家一律 403。
|
||||
*
|
||||
* <p>读侧与写侧共用这一个方法:分成两个迟早漂移成「读能看别家、写挡不住」或反过来,
|
||||
* 而那正是 09-13「权限自己没掉」那一族事故的形状。</p>
|
||||
*
|
||||
* <p>{@code null} 只可能来自「没有操作者」的历史内部调用与单测夹具,此时不下公司条件、
|
||||
* 退回换列之前的全量目录语义;生产上 {@code users.company_id} 是 NOT NULL,
|
||||
* 真出现无归属账号由列上的约束喊,不在这里编一个默认公司。</p>
|
||||
*
|
||||
* <p>公开是为了让控制器在收 {@code company_id} 参数的当场就走这道门(把返回值往下传),
|
||||
* 而不是把裸参数扔进来再靠本类内部兜——{@code CompanyIdParamGoesThroughReadScopeTest}
|
||||
* 认的就是这条出口,控制器少接一次就等于"tab 传了但没人用"。</p>
|
||||
*/
|
||||
public Long resolveScopeCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
|
||||
if (requestedCompanyId != null && requestedCompanyId <= 0) {
|
||||
throw new BusinessException("company_id 无效");
|
||||
}
|
||||
if (operator == null || operator.getId() == null) {
|
||||
return requestedCompanyId;
|
||||
}
|
||||
Long operatorCompanyId = operator.getCompanyId();
|
||||
if (requestedCompanyId == null) {
|
||||
return operatorCompanyId;
|
||||
}
|
||||
if (requestedCompanyId.equals(operatorCompanyId) || isSuperAdmin(operator)) {
|
||||
return requestedCompanyId;
|
||||
}
|
||||
throw new BusinessException(403, "无权读写其他公司的菜单");
|
||||
}
|
||||
|
||||
/**
|
||||
* 写侧闸门(§5):非超管只能动<b>本公司那棵树</b>里的行。
|
||||
*
|
||||
* <p>补这道闸门之前 {@link #ensureAdminOperatorIfPresent} 只判 isAdmin,等于任何管理员
|
||||
* 都能改整张字典;每家公司一棵树之后,跨公司改一行会把别家的菜单搬进自己树里
|
||||
* ({@code column_key} 在两家之间不再全局唯一,只有 id 认得出它属于谁)。
|
||||
* 菜单字典是租户配置,改坏它比跨公司读数据更糟——那家所有账号的权限页一起坏。</p>
|
||||
*/
|
||||
private void ensureMenuWritable(AdminUserEntity operator, PermissionMenuEntity menu) {
|
||||
if (operator == null || isSuperAdmin(operator)) {
|
||||
return;
|
||||
}
|
||||
Long menuCompanyId = menu == null ? null : menu.getCompanyId();
|
||||
if (!Objects.equals(menuCompanyId, operator.getCompanyId())) {
|
||||
throw new BusinessException(403, "无权修改其他公司的菜单");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,13 +209,25 @@ public class PermissionMenuService {
|
||||
|
||||
@Transactional
|
||||
public PermissionMenuItemVo create(PermissionMenuCreateRequest request) {
|
||||
return create(null, request);
|
||||
return create(null, null, request);
|
||||
}
|
||||
|
||||
/** Controller-facing variant; the caller may pass the authenticated admin. */
|
||||
@Transactional
|
||||
public PermissionMenuItemVo create(AdminUserEntity operator, PermissionMenuCreateRequest request) {
|
||||
return create(operator, null, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增菜单。归属公司由 {@code requestedCompanyId} 决定,缺省取操作者本公司(设计文档 §5):
|
||||
* 站点超管可以替别家建菜单(今天就是他一人在给 133 只账号配权限),非超管只能在自已公司建,
|
||||
* 传别家 403。<b>绝不靠列上的 DEFAULT 1 兜归属</b>——那等于把别家的菜单静默塞进厦门米椿花。
|
||||
*/
|
||||
@Transactional
|
||||
public PermissionMenuItemVo create(AdminUserEntity operator, Long requestedCompanyId,
|
||||
PermissionMenuCreateRequest request) {
|
||||
ensureAdminOperatorIfPresent(operator);
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
if (request == null) {
|
||||
throw new BusinessException("菜单参数不能为空");
|
||||
}
|
||||
@@ -161,9 +243,9 @@ public class PermissionMenuService {
|
||||
routePath = generateRoutePath(columnKey);
|
||||
}
|
||||
Long parentId = normalizeParentId(request.getParentId());
|
||||
ensureParentValid(parentId, null, menuType);
|
||||
ensureUniqueColumnKey(columnKey, null);
|
||||
ensureUniqueRoutePath(menuType, routePath, null);
|
||||
ensureParentValid(companyId, parentId, null, menuType);
|
||||
ensureUniqueColumnKey(companyId, columnKey, null);
|
||||
ensureUniqueRoutePath(companyId, menuType, routePath, null);
|
||||
|
||||
PermissionMenuEntity entity = new PermissionMenuEntity();
|
||||
entity.setName(name);
|
||||
@@ -171,7 +253,8 @@ public class PermissionMenuService {
|
||||
entity.setParentId(parentId);
|
||||
entity.setMenuType(menuType);
|
||||
entity.setRoutePath(routePath);
|
||||
entity.setSortOrder(resolveSortOrder(menuType, request.getSortOrder(), null));
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setSortOrder(resolveSortOrder(companyId, menuType, request.getSortOrder(), null));
|
||||
permissionMenuMapper.insert(entity);
|
||||
return toItemVo(getMenuById(entity.getId()));
|
||||
}
|
||||
@@ -186,6 +269,10 @@ public class PermissionMenuService {
|
||||
public PermissionMenuItemVo update(AdminUserEntity operator, Long id, PermissionMenuUpdateRequest request) {
|
||||
ensureAdminOperatorIfPresent(operator);
|
||||
PermissionMenuEntity entity = getMenuById(id);
|
||||
// 归属不接收请求参数:改哪棵树由<b>这一行自己属于谁</b>决定,编辑动作只能把行留在原公司。
|
||||
// 让载荷带 company_id 等于开一条"把别家的菜单搬进自己树"的旁路。
|
||||
ensureMenuWritable(operator, entity);
|
||||
Long companyId = entity.getCompanyId();
|
||||
if (request == null) {
|
||||
throw new BusinessException("菜单参数不能为空");
|
||||
}
|
||||
@@ -201,17 +288,17 @@ public class PermissionMenuService {
|
||||
routePath = entity.getRoutePath();
|
||||
}
|
||||
Long parentId = normalizeParentId(request.getParentId());
|
||||
ensureParentValid(parentId, id, menuType);
|
||||
ensureParentValid(companyId, parentId, id, menuType);
|
||||
ensureMenuTypeChangeAllowed(entity, menuType);
|
||||
ensureUniqueColumnKey(columnKey, id);
|
||||
ensureUniqueRoutePath(menuType, routePath, id);
|
||||
ensureUniqueColumnKey(companyId, columnKey, id);
|
||||
ensureUniqueRoutePath(companyId, menuType, routePath, id);
|
||||
|
||||
entity.setName(name);
|
||||
entity.setColumnKey(columnKey);
|
||||
entity.setParentId(parentId);
|
||||
entity.setMenuType(menuType);
|
||||
entity.setRoutePath(routePath);
|
||||
entity.setSortOrder(resolveSortOrder(menuType, request.getSortOrder(), id));
|
||||
entity.setSortOrder(resolveSortOrder(companyId, menuType, request.getSortOrder(), id));
|
||||
permissionMenuMapper.updateById(entity);
|
||||
return toItemVo(getMenuById(id));
|
||||
}
|
||||
@@ -229,6 +316,7 @@ public class PermissionMenuService {
|
||||
public void delete(AdminUserEntity operator, Long id) {
|
||||
ensureAdminOperatorIfPresent(operator);
|
||||
PermissionMenuEntity entity = getMenuById(id);
|
||||
ensureMenuWritable(operator, entity);
|
||||
Long childCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(PermissionMenuEntity::getParentId, entity.getId()));
|
||||
if (childCount != null && childCount > 0) {
|
||||
@@ -243,9 +331,12 @@ public class PermissionMenuService {
|
||||
/**
|
||||
* 同级菜单拖拽重排:orderedIds 为同一父级下按新顺序排列的菜单 ID 列表。
|
||||
* 不在列表中的兄弟节点保持原相对顺序追加在末尾,重排块锚定在原最小 sort_order,避免跨级穿插。
|
||||
*
|
||||
* <p>兄弟集必须按<b>锚点行的公司</b>筛:每家公司一棵树之后,"同级"这个概念本身就带公司口径,
|
||||
* 混进别家的同名分组会让重排把两棵树的 sort_order 交织在一起(表现为两排同名菜单穿插)。</p>
|
||||
*/
|
||||
@Transactional
|
||||
public void reorder(List<Long> orderedIds) {
|
||||
public void reorder(AdminUserEntity operator, List<Long> orderedIds) {
|
||||
if (orderedIds == null || orderedIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -257,9 +348,13 @@ public class PermissionMenuService {
|
||||
if (anchor == null) {
|
||||
throw new BusinessException("菜单不存在");
|
||||
}
|
||||
ensureAdminOperatorIfPresent(operator);
|
||||
ensureMenuWritable(operator, anchor);
|
||||
Long companyId = anchor.getCompanyId();
|
||||
Long parentId = anchor.getParentId();
|
||||
String menuType = anchor.getMenuType();
|
||||
List<PermissionMenuEntity> siblings = permissionMenuMapper.selectList(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(PermissionMenuEntity::getMenuType, menuType)
|
||||
.eq(PermissionMenuEntity::getParentId, parentId)
|
||||
.orderByAsc(PermissionMenuEntity::getSortOrder)
|
||||
@@ -288,6 +383,88 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给新公司复制一套模板菜单树(父子指向按 {@code column_key} 重映射),与 V149 第 6/7 段同一语义:
|
||||
* 那一版补的是<b>当时已经存在</b>的公司,这一版补的是之后新建的公司。
|
||||
*
|
||||
* <p>没有它,「公司管理 -> 新增公司」就造出一个零菜单行的租户:那家的账号登录后台侧边栏全空、
|
||||
* 授权树一个勾都没有,而且全程不报错。这正是本次要消灭的那类静默失效,
|
||||
* 所以建树必须是建号公司的同一次写入,不能留成"上线后再手工跑一遍 V149 的复制段"。</p>
|
||||
*
|
||||
* <p>两趟写:第一趟只管插(父先留空,避开插入顺序),第二趟按 key 把父指向落到本公司新行上
|
||||
* ——与 V149 第 7 段同形,两级三层都成立。幂等:目标公司已有的 key 原样保留,重跑只补差集。</p>
|
||||
*
|
||||
* @param companyId 目标(新)公司
|
||||
* @param templateCompanyId 模板树所属公司,由调用方给操作者本公司,这里不编默认值
|
||||
* @return 本次新插入的行数
|
||||
*/
|
||||
@Transactional
|
||||
public int copyTreeFromTemplate(Long companyId, Long templateCompanyId) {
|
||||
if (companyId == null || companyId <= 0) {
|
||||
throw new BusinessException("目标公司 id 不能为空");
|
||||
}
|
||||
if (templateCompanyId == null || templateCompanyId <= 0) {
|
||||
throw new BusinessException("当前账号没有所属公司,无法为新公司复制菜单树");
|
||||
}
|
||||
if (companyId.equals(templateCompanyId)) {
|
||||
return 0;
|
||||
}
|
||||
// 角色内在闸门那几行不进副本(D3):它在任何别家的树里都不该存在,
|
||||
// 连行都没有就没人能勾它,比"有一行但看不见"更干净。
|
||||
List<PermissionMenuEntity> template = loadRawMenus(templateCompanyId, null).stream()
|
||||
.filter(menu -> menu.getId() != null && menu.getColumnKey() != null)
|
||||
.filter(menu -> !SUPER_ADMIN_ONLY_KEYS.contains(menu.getColumnKey()))
|
||||
.toList();
|
||||
if (template.isEmpty()) {
|
||||
throw new BusinessException("模板公司没有可复制的菜单树");
|
||||
}
|
||||
Map<String, PermissionMenuEntity> targetByKey = new HashMap<>();
|
||||
for (PermissionMenuEntity menu : loadRawMenus(companyId, null)) {
|
||||
if (menu.getColumnKey() != null) {
|
||||
targetByKey.put(menu.getColumnKey(), menu);
|
||||
}
|
||||
}
|
||||
Map<Long, PermissionMenuEntity> templateById = new HashMap<>();
|
||||
template.forEach(menu -> templateById.put(menu.getId(), menu));
|
||||
int inserted = 0;
|
||||
for (PermissionMenuEntity source : template) {
|
||||
if (targetByKey.containsKey(source.getColumnKey())) {
|
||||
continue;
|
||||
}
|
||||
PermissionMenuEntity copy = new PermissionMenuEntity();
|
||||
copy.setCompanyId(companyId);
|
||||
copy.setName(source.getName());
|
||||
copy.setColumnKey(source.getColumnKey());
|
||||
copy.setMenuType(source.getMenuType());
|
||||
copy.setRoutePath(source.getRoutePath());
|
||||
copy.setSortOrder(source.getSortOrder());
|
||||
copy.setParentId(null);
|
||||
permissionMenuMapper.insert(copy);
|
||||
targetByKey.put(copy.getColumnKey(), copy);
|
||||
inserted++;
|
||||
}
|
||||
for (PermissionMenuEntity source : template) {
|
||||
PermissionMenuEntity child = targetByKey.get(source.getColumnKey());
|
||||
PermissionMenuEntity templateParent = templateById.get(source.getParentId());
|
||||
if (child == null || child.getId() == null || templateParent == null) {
|
||||
continue;
|
||||
}
|
||||
PermissionMenuEntity parent = targetByKey.get(templateParent.getColumnKey());
|
||||
if (parent == null || parent.getId() == null || parent.getId().equals(child.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (!Objects.equals(child.getParentId(), parent.getId())) {
|
||||
permissionMenuMapper.update(null, new LambdaUpdateWrapper<PermissionMenuEntity>()
|
||||
.eq(PermissionMenuEntity::getId, child.getId())
|
||||
.set(PermissionMenuEntity::getParentId, parent.getId()));
|
||||
child.setParentId(parent.getId());
|
||||
}
|
||||
}
|
||||
log.info("[menu-tree-copy] 新公司菜单树已建 companyId={} template={} rows={}",
|
||||
companyId, templateCompanyId, inserted);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
/** Returns only persisted direct grant IDs (never recursively expanded). */
|
||||
public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) {
|
||||
return getUserColumnIds(null, userId, menuType);
|
||||
@@ -314,7 +491,9 @@ public class PermissionMenuService {
|
||||
AdminUserEntity user = getUserById(userId);
|
||||
ensureTargetAccessible(operator, user);
|
||||
|
||||
List<PermissionMenuEntity> menus = loadMenus(menuType);
|
||||
// 回填集按<b>目标账号所属公司</b>的那棵树取:授权弹窗里勾的是"这个账号家"的菜单行 id,
|
||||
// 操作者是谁都不该改变这一点(超管替德阳配权限时勾出公司 1 的行 id,就是跨公司授权)。
|
||||
List<PermissionMenuEntity> menus = loadMenus(user.getCompanyId(), menuType);
|
||||
Map<Long, PermissionMenuEntity> menuMap = menus.stream()
|
||||
.filter(menu -> menu.getId() != null)
|
||||
.collect(Collectors.toMap(PermissionMenuEntity::getId, Function.identity(), (left, right) -> left));
|
||||
@@ -351,7 +530,7 @@ public class PermissionMenuService {
|
||||
boolean includeAncestorGroups) {
|
||||
AdminUserEntity user = getUserById(userId);
|
||||
ensureTargetAccessible(operator, user);
|
||||
List<PermissionMenuEntity> menus = loadMenus(menuType);
|
||||
List<PermissionMenuEntity> menus = loadMenus(user.getCompanyId(), menuType);
|
||||
if (isSuperAdmin(user)) {
|
||||
return toItemVos(menus, menus);
|
||||
}
|
||||
@@ -387,7 +566,12 @@ public class PermissionMenuService {
|
||||
if (isSuperAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
List<PermissionMenuEntity> menus = loadMenus(target.getMenuType());
|
||||
// 跨公司的 column_id 一律判「无权限」:本账号的直接授权里出现别家的行,只可能是载荷被
|
||||
// 拼错(或前端缓存了换键之前的旧 id)。方向是拒绝,不是放行——放宽等于让别家的行 id 生效。
|
||||
if (!Objects.equals(target.getCompanyId(), user.getCompanyId())) {
|
||||
return false;
|
||||
}
|
||||
List<PermissionMenuEntity> menus = loadMenus(target.getCompanyId(), target.getMenuType());
|
||||
return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(userId)), menus)
|
||||
.contains(columnId);
|
||||
}
|
||||
@@ -397,26 +581,40 @@ public class PermissionMenuService {
|
||||
*
|
||||
* <p>权限页此前一律 `selectList(new LambdaQueryWrapper<>())` 整表拉回,而 admin_user
|
||||
* 含密码哈希等敏感列,每次打开权限页都把全表(含哈希)读进内存(2026-09-15 优化)。
|
||||
* 判定用 role/is_admin/created_by_id,展示用 id/username。
|
||||
* 判定用 role/is_admin/created_by_id,展示用 id/username,按公司筛用 company_id
|
||||
* (V149:数据权限行分属各棵树,用户列表必须同一家,否则「勾了人、写到别家的行」
|
||||
* 会静默落空——页面照旧显示已授权,账号却永远拿不到那份数据)。
|
||||
*/
|
||||
private LambdaQueryWrapper<AdminUserEntity> grantableUserQuery() {
|
||||
private LambdaQueryWrapper<AdminUserEntity> grantableUserQuery(Long companyId) {
|
||||
return new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.select(AdminUserEntity::getId,
|
||||
AdminUserEntity::getUsername,
|
||||
AdminUserEntity::getRole,
|
||||
AdminUserEntity::getIsAdmin,
|
||||
AdminUserEntity::getCreatedById);
|
||||
AdminUserEntity::getCreatedById,
|
||||
AdminUserEntity::getCompanyId)
|
||||
.eq(companyId != null, AdminUserEntity::getCompanyId, companyId);
|
||||
}
|
||||
|
||||
public List<ImageVideoDataPermissionUserVo> listImageVideoDataPermissionUsers(AdminUserEntity operator) {
|
||||
return listImageVideoDataPermissionUsers(operator, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 「视频任务数据查看」这一项内部数据权限的分公司读口:超管切到哪家公司就解析那棵树的行,
|
||||
* 用户列表同步按那一家筛({@link #grantableUserQuery(Long)})。
|
||||
*/
|
||||
public List<ImageVideoDataPermissionUserVo> listImageVideoDataPermissionUsers(AdminUserEntity operator,
|
||||
Long requestedCompanyId) {
|
||||
ensureSuperAdminOperator(operator);
|
||||
PermissionMenuEntity dataPermission = requireImageVideoDataPermission();
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(companyId);
|
||||
Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId())
|
||||
.stream()
|
||||
.map(UserColumnPermissionEntity::getUserId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.collect(Collectors.toSet());
|
||||
return adminUserMapper.selectList(grantableUserQuery()
|
||||
return adminUserMapper.selectList(grantableUserQuery(companyId)
|
||||
.orderByAsc(AdminUserEntity::getUsername)
|
||||
.orderByAsc(AdminUserEntity::getId))
|
||||
.stream()
|
||||
@@ -427,10 +625,22 @@ public class PermissionMenuService {
|
||||
|
||||
@Transactional
|
||||
public int updateImageVideoDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) {
|
||||
return updateImageVideoDataPermissionUsers(operator, null, userIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 整分区替换本公司的那一条内部数据权限授权。别家的账号 id 会落进
|
||||
* 「contains unknown or non-grantable user」——用户列表已经按公司筛过,
|
||||
* 这不是新报错,是既有的那条从严判定现在有了公司口径。
|
||||
*/
|
||||
@Transactional
|
||||
public int updateImageVideoDataPermissionUsers(AdminUserEntity operator, Long requestedCompanyId,
|
||||
List<Long> userIds) {
|
||||
ensureSuperAdminOperator(operator);
|
||||
PermissionMenuEntity dataPermission = requireImageVideoDataPermission();
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(companyId);
|
||||
List<Long> requestedIds = normalizeColumnIds(userIds);
|
||||
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery());
|
||||
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery(companyId));
|
||||
Map<Long, AdminUserEntity> grantableUsers = users.stream()
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
@@ -448,15 +658,22 @@ public class PermissionMenuService {
|
||||
}
|
||||
|
||||
public List<ImageVideoDataPermissionUserVo> listShopDataCrawlDataPermissionUsers(AdminUserEntity operator) {
|
||||
return listShopDataCrawlDataPermissionUsers(operator, null);
|
||||
}
|
||||
|
||||
/** 与视频任务那一路同口径:内部数据权限行与用户列表必须解析到同一家公司。 */
|
||||
public List<ImageVideoDataPermissionUserVo> listShopDataCrawlDataPermissionUsers(AdminUserEntity operator,
|
||||
Long requestedCompanyId) {
|
||||
ensureSuperAdminOperator(operator, "店铺数据任务");
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
PermissionMenuEntity dataPermission = requireDataPermission(
|
||||
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId())
|
||||
.stream()
|
||||
.map(UserColumnPermissionEntity::getUserId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.collect(Collectors.toSet());
|
||||
return adminUserMapper.selectList(grantableUserQuery()
|
||||
return adminUserMapper.selectList(grantableUserQuery(companyId)
|
||||
.orderByAsc(AdminUserEntity::getUsername)
|
||||
.orderByAsc(AdminUserEntity::getId))
|
||||
.stream()
|
||||
@@ -467,11 +684,18 @@ public class PermissionMenuService {
|
||||
|
||||
@Transactional
|
||||
public int updateShopDataCrawlDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) {
|
||||
return updateShopDataCrawlDataPermissionUsers(operator, null, userIds);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public int updateShopDataCrawlDataPermissionUsers(AdminUserEntity operator, Long requestedCompanyId,
|
||||
List<Long> userIds) {
|
||||
ensureSuperAdminOperator(operator, "店铺数据任务");
|
||||
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
|
||||
PermissionMenuEntity dataPermission = requireDataPermission(
|
||||
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
List<Long> requestedIds = normalizeColumnIds(userIds);
|
||||
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery());
|
||||
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery(companyId));
|
||||
Map<Long, AdminUserEntity> grantableUsers = users.stream()
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
@@ -505,12 +729,15 @@ public class PermissionMenuService {
|
||||
if (isSuperAdmin(operator)) {
|
||||
return;
|
||||
}
|
||||
// 三行都按操作者本公司解析:换键之后同一个 key 每家公司各一行,
|
||||
// 少带条件就是 LIMIT 1 跨公司借位(§4 里最危险的那处静默失效)。
|
||||
Long companyId = operator.getCompanyId();
|
||||
PermissionMenuEntity taskMenu = requireDataPermission(
|
||||
"admin_shop_data_crawl_tasks", "店铺数据任务管理菜单");
|
||||
companyId, "admin_shop_data_crawl_tasks", "店铺数据任务管理菜单");
|
||||
PermissionMenuEntity duplicateCheckMenu = requireDataPermission(
|
||||
"admin_shop_data_duplicate_check", "店铺数据重复检查菜单");
|
||||
companyId, "admin_shop_data_duplicate_check", "店铺数据重复检查菜单");
|
||||
PermissionMenuEntity dataPermission = requireDataPermission(
|
||||
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
|
||||
boolean hasShopDataMenu = hasEffectiveColumnPermission(operator.getId(), taskMenu.getId())
|
||||
|| hasEffectiveColumnPermission(operator.getId(), duplicateCheckMenu.getId());
|
||||
if (!hasShopDataMenu || !hasEffectiveColumnPermission(operator.getId(), dataPermission.getId())) {
|
||||
@@ -532,7 +759,8 @@ public class PermissionMenuService {
|
||||
if (isSuperAdmin(operator)) {
|
||||
return;
|
||||
}
|
||||
PermissionMenuEntity menu = requireDataPermission("admin_task_center", "客户端任务管理菜单");
|
||||
PermissionMenuEntity menu = requireDataPermission(
|
||||
operator.getCompanyId(), "admin_task_center", "客户端任务管理菜单");
|
||||
if (!hasEffectiveColumnPermission(operator.getId(), menu.getId())) {
|
||||
throw new BusinessException(403, "无权查看客户端任务管理");
|
||||
}
|
||||
@@ -549,7 +777,7 @@ public class PermissionMenuService {
|
||||
if (isSuperAdmin(operator)) {
|
||||
return true;
|
||||
}
|
||||
List<PermissionMenuEntity> menus = loadMenus(MENU_TYPE_ADMIN);
|
||||
List<PermissionMenuEntity> menus = loadMenus(operator.getCompanyId(), MENU_TYPE_ADMIN);
|
||||
List<Long> wantedIds = menus.stream()
|
||||
.filter(menu -> menu.getColumnKey() != null && columnKeys.contains(menu.getColumnKey()))
|
||||
.map(PermissionMenuEntity::getId)
|
||||
@@ -606,8 +834,11 @@ public class PermissionMenuService {
|
||||
AdminUserEntity target = getUserById(userId);
|
||||
ensureTargetAccessible(operator, target);
|
||||
List<Long> requestedIds = request == null ? List.of() : normalizeColumnIds(request.getColumnIds());
|
||||
// 整条链的归属口径 = 目标账号<b>自己那棵树</b>(不是操作者的):超管替德阳配权限时,
|
||||
// 勾选与落库都必须指向德阳的菜单行 id,否则写进去的授权在本公司的树上认不出来。
|
||||
Long targetCompanyId = target.getCompanyId();
|
||||
// 出口 3(提交授权):超管专属项在这里被剥掉,越权校验与落库都看不到它(剥而不拒)。
|
||||
requestedIds = stripSuperAdminOnlyGrantIds(requestedIds, operator);
|
||||
requestedIds = stripSuperAdminOnlyGrantIds(requestedIds, operator, targetCompanyId);
|
||||
String normalizedType = menuType == null || menuType.isBlank()
|
||||
? null
|
||||
: normalizeMenuTypeRequired(menuType);
|
||||
@@ -616,13 +847,14 @@ public class PermissionMenuService {
|
||||
if (normalizedType == null) {
|
||||
if (!requestedIds.isEmpty()) {
|
||||
Long validCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(PermissionMenuEntity::getCompanyId, targetCompanyId)
|
||||
.in(PermissionMenuEntity::getId, requestedIds));
|
||||
if (validCount == null || validCount != requestedIds.size()) {
|
||||
throw new BusinessException("存在无效的菜单权限项");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
scopedMenuIds.addAll(loadMenus(normalizedType).stream()
|
||||
scopedMenuIds.addAll(loadMenus(targetCompanyId, normalizedType).stream()
|
||||
.map(PermissionMenuEntity::getId)
|
||||
.filter(Objects::nonNull)
|
||||
.toList());
|
||||
@@ -633,9 +865,9 @@ public class PermissionMenuService {
|
||||
|
||||
Set<Long> protectedIds = new LinkedHashSet<>();
|
||||
if (normalizedType == null) {
|
||||
PermissionMenuEntity imageVideoDataPermission = findImageVideoDataPermission();
|
||||
PermissionMenuEntity imageVideoDataPermission = findImageVideoDataPermission(targetCompanyId);
|
||||
PermissionMenuEntity shopDataCrawlDataPermission =
|
||||
findDataPermission(SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
|
||||
findDataPermission(targetCompanyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
|
||||
if (imageVideoDataPermission != null && imageVideoDataPermission.getId() != null) {
|
||||
protectedIds.add(imageVideoDataPermission.getId());
|
||||
}
|
||||
@@ -686,7 +918,8 @@ public class PermissionMenuService {
|
||||
userColumnPermissionMapper.insert(entity);
|
||||
}
|
||||
if (MENU_TYPE_ADMIN.equals(normalizedType)) {
|
||||
autoGrantShopDataDataPermission(userId, finalGrantIds, loadMenus(MENU_TYPE_ADMIN));
|
||||
autoGrantShopDataDataPermission(userId, finalGrantIds,
|
||||
loadMenus(targetCompanyId, MENU_TYPE_ADMIN), targetCompanyId);
|
||||
}
|
||||
|
||||
// 目标管理员的权限被回收后,其直接创建的员工若仍持有超出范围的
|
||||
@@ -712,13 +945,13 @@ public class PermissionMenuService {
|
||||
* 只增不删:数据授权的回收仍走超管专用的「数据范围授权」UI。
|
||||
*/
|
||||
private void autoGrantShopDataDataPermission(Long userId, Set<Long> directGrantIds,
|
||||
List<PermissionMenuEntity> adminMenus) {
|
||||
List<PermissionMenuEntity> adminMenus, Long companyId) {
|
||||
if (directGrantIds.isEmpty() || adminMenus.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
PermissionMenuEntity taskMenu = findDataPermission("admin_shop_data_crawl_tasks");
|
||||
PermissionMenuEntity duplicateCheckMenu = findDataPermission("admin_shop_data_duplicate_check");
|
||||
PermissionMenuEntity dataPermission = findDataPermission(SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
|
||||
PermissionMenuEntity taskMenu = findDataPermission(companyId, "admin_shop_data_crawl_tasks");
|
||||
PermissionMenuEntity duplicateCheckMenu = findDataPermission(companyId, "admin_shop_data_duplicate_check");
|
||||
PermissionMenuEntity dataPermission = findDataPermission(companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
|
||||
if (dataPermission == null || dataPermission.getId() == null) {
|
||||
return;
|
||||
}
|
||||
@@ -755,12 +988,16 @@ public class PermissionMenuService {
|
||||
if (target == null || target.getId() == null || isSuperAdmin(target)) {
|
||||
return;
|
||||
}
|
||||
Long companyId = target.getCompanyId();
|
||||
Set<Long> targetEffectiveIds = expandDescendantIds(
|
||||
new LinkedHashSet<>(loadDirectColumnIds(target.getId())), loadMenus(null));
|
||||
// 只用到 id:不要为一次级联清理把整表(含密码哈希)拉回
|
||||
new LinkedHashSet<>(loadDirectColumnIds(target.getId())), loadMenus(companyId, null));
|
||||
// 只用到 id:不要为一次级联清理把整表(含密码哈希)拉回。
|
||||
// 下属集要同时按公司筛:这段是批量删除,一旦 created_by 出现跨公司的脏数据,
|
||||
// "越权"判定就会拿 A 家的有效集去删 B 家员工的授权——删多隔离比删少更贵。
|
||||
List<AdminUserEntity> subordinates = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.select(AdminUserEntity::getId)
|
||||
.eq(AdminUserEntity::getCreatedById, target.getId()));
|
||||
.eq(AdminUserEntity::getCreatedById, target.getId())
|
||||
.eq(companyId != null, AdminUserEntity::getCompanyId, companyId));
|
||||
for (AdminUserEntity subordinate : subordinates) {
|
||||
Long subordinateId = subordinate.getId();
|
||||
if (subordinateId == null || subordinateId.equals(target.getId())) {
|
||||
@@ -782,8 +1019,14 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
private List<PermissionMenuEntity> loadMenus(String menuType) {
|
||||
List<PermissionMenuEntity> rows = loadRawMenus(menuType);
|
||||
/**
|
||||
* 目录取数的唯一出口(§4):{@code companyId} 非空时只返回那一棵树的行。
|
||||
* 授权树、有效菜单、可授予全集、越权判定都从这里取数,所以公司收窄改这一处就够一片。
|
||||
*
|
||||
* @param companyId null 只来自「无操作者 / 无归属」的历史与测试路径,此时退回全量目录
|
||||
*/
|
||||
private List<PermissionMenuEntity> loadMenus(Long companyId, String menuType) {
|
||||
List<PermissionMenuEntity> rows = loadRawMenus(companyId, menuType);
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
@@ -794,13 +1037,14 @@ public class PermissionMenuService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches every menu (optionally scoped to one type) in insertion order.
|
||||
* Sorting happens in {@link #loadMenus(String)} and only for hierarchies
|
||||
* Fetches every menu (optionally scoped to one company and one type) in insertion order.
|
||||
* Sorting happens in {@link #loadMenus(Long, String)} and only for hierarchies
|
||||
* that actually need one, keeping raw SQL and comparator semantics in sync.
|
||||
*/
|
||||
private List<PermissionMenuEntity> loadRawMenus(String menuType) {
|
||||
private List<PermissionMenuEntity> loadRawMenus(Long companyId, String menuType) {
|
||||
String normalizedType = normalizeMenuType(menuType);
|
||||
LambdaQueryWrapper<PermissionMenuEntity> query = new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(normalizedType != null, PermissionMenuEntity::getMenuType, normalizedType)
|
||||
.orderByAsc(PermissionMenuEntity::getSortOrder)
|
||||
.orderByAsc(PermissionMenuEntity::getId);
|
||||
@@ -1006,11 +1250,12 @@ public class PermissionMenuService {
|
||||
* 唯一例外是超管且 menuType 为空的「整树替换」分支:{@code deleteByUserId} 先清空目标整个
|
||||
* 分区再按提交重插,被剥的这条按既有语义就不会回来——那是该分支本来就有的行为,不是剥离引入的。
|
||||
*/
|
||||
private List<Long> stripSuperAdminOnlyGrantIds(List<Long> requestedIds, AdminUserEntity operator) {
|
||||
private List<Long> stripSuperAdminOnlyGrantIds(List<Long> requestedIds, AdminUserEntity operator,
|
||||
Long companyId) {
|
||||
if (requestedIds.isEmpty()) {
|
||||
return requestedIds;
|
||||
}
|
||||
Set<Long> restricted = superAdminOnlyMenuIds();
|
||||
Set<Long> restricted = superAdminOnlyMenuIds(companyId);
|
||||
if (restricted.isEmpty()) {
|
||||
return requestedIds;
|
||||
}
|
||||
@@ -1029,8 +1274,12 @@ public class PermissionMenuService {
|
||||
* <p>一次全量目录查询折出来,绝不按 id 逐条点查:保存权限这个入口上 N 次点查会被日志放大,
|
||||
* 而 {@code findDataPermission} 每次都是一个 {@code selectOne}。</p>
|
||||
*/
|
||||
private Set<Long> superAdminOnlyMenuIds() {
|
||||
return loadMenus(null).stream()
|
||||
/**
|
||||
* <p>V149 之后这行闸门菜单只存在于公司 1 的树里(§2 D3:副本不复制它),所以别家公司
|
||||
* 拿到的是空集——那里的提交里本来就不可能有它,剥离逻辑照常走完,不多一条分支。</p>
|
||||
*/
|
||||
private Set<Long> superAdminOnlyMenuIds(Long companyId) {
|
||||
return loadMenus(companyId, null).stream()
|
||||
.filter(menu -> SUPER_ADMIN_ONLY_KEYS.contains(menu.getColumnKey()))
|
||||
.map(PermissionMenuEntity::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
@@ -1073,12 +1322,12 @@ public class PermissionMenuService {
|
||||
return !Integer.valueOf(1).equals(user.getIsAdmin());
|
||||
}
|
||||
|
||||
private PermissionMenuEntity findImageVideoDataPermission() {
|
||||
return findDataPermission(IMAGE_VIDEO_DATA_PERMISSION_KEY);
|
||||
private PermissionMenuEntity findImageVideoDataPermission(Long companyId) {
|
||||
return findDataPermission(companyId, IMAGE_VIDEO_DATA_PERMISSION_KEY);
|
||||
}
|
||||
|
||||
private PermissionMenuEntity requireImageVideoDataPermission() {
|
||||
PermissionMenuEntity permission = findImageVideoDataPermission();
|
||||
private PermissionMenuEntity requireImageVideoDataPermission(Long companyId) {
|
||||
PermissionMenuEntity permission = findImageVideoDataPermission(companyId);
|
||||
if (permission == null || permission.getId() == null) {
|
||||
throw new BusinessException("视频任务数据权限尚未初始化");
|
||||
}
|
||||
@@ -1099,14 +1348,20 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
private PermissionMenuEntity findDataPermission(String columnKey) {
|
||||
/**
|
||||
* 按 key 点查一行菜单。<b>必须带公司</b>:V149 之后同一个 key 在每家公司各有一行,
|
||||
* 少了这个条件就是 {@code LIMIT 1} 跨公司借位——拿到别家的行 id 再往本账号身上写一条
|
||||
* 本公司树里认不出的授权,页面显示"已授权"、权限却永远不生效,且不报任何错。
|
||||
*/
|
||||
private PermissionMenuEntity findDataPermission(Long companyId, String columnKey) {
|
||||
return permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(PermissionMenuEntity::getColumnKey, columnKey)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private PermissionMenuEntity requireDataPermission(String columnKey, String displayName) {
|
||||
PermissionMenuEntity permission = findDataPermission(columnKey);
|
||||
private PermissionMenuEntity requireDataPermission(Long companyId, String columnKey, String displayName) {
|
||||
PermissionMenuEntity permission = findDataPermission(companyId, columnKey);
|
||||
if (permission == null || permission.getId() == null) {
|
||||
throw new BusinessException(displayName + "权限尚未初始化");
|
||||
}
|
||||
@@ -1126,7 +1381,7 @@ public class PermissionMenuService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
private void ensureParentValid(Long parentId, Long currentId, String menuType) {
|
||||
private void ensureParentValid(Long companyId, Long parentId, Long currentId, String menuType) {
|
||||
if (parentId == null) {
|
||||
return;
|
||||
}
|
||||
@@ -1151,6 +1406,11 @@ public class PermissionMenuService {
|
||||
if (currentId != null && currentId.equals(cursor.getId())) {
|
||||
throw new BusinessException("父级菜单不能选择自己的子级");
|
||||
}
|
||||
// fk_columns_parent_id 只保证父行存在,挡不住跨公司挂父(§3.6),同公司判定只能做在这里。
|
||||
// 整条祖先链都判:一个同公司的父、上面挂着别家的分组,落库后这行在两棵树里都渲染不出。
|
||||
if (companyId != null && !companyId.equals(cursor.getCompanyId())) {
|
||||
throw new BusinessException("父级菜单必须与当前菜单属于同一公司");
|
||||
}
|
||||
Long ancestorId = cursor.getParentId();
|
||||
if (ancestorId == null) {
|
||||
break;
|
||||
@@ -1173,8 +1433,10 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureUniqueColumnKey(String columnKey, Long excludeId) {
|
||||
/** 查重范围 = 本公司(与 {@code uk_company_column_key} 同一条键)。不加条件会拿别家的副本误报"已存在"。 */
|
||||
private void ensureUniqueColumnKey(Long companyId, String columnKey, Long excludeId) {
|
||||
PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(PermissionMenuEntity::getColumnKey, columnKey)
|
||||
.last("LIMIT 1"));
|
||||
if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) {
|
||||
@@ -1182,8 +1444,10 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureUniqueRoutePath(String menuType, String routePath, Long excludeId) {
|
||||
/** 同上,对应 {@code uk_company_menu_type_route_path}。 */
|
||||
private void ensureUniqueRoutePath(Long companyId, String menuType, String routePath, Long excludeId) {
|
||||
PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(PermissionMenuEntity::getMenuType, menuType)
|
||||
.eq(PermissionMenuEntity::getRoutePath, routePath)
|
||||
.last("LIMIT 1"));
|
||||
@@ -1297,7 +1561,7 @@ public class PermissionMenuService {
|
||||
}
|
||||
|
||||
private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity) {
|
||||
return toItemVos(List.of(entity), loadMenus(entity.getMenuType())).getFirst();
|
||||
return toItemVos(List.of(entity), loadMenus(entity.getCompanyId(), entity.getMenuType())).getFirst();
|
||||
}
|
||||
|
||||
private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity,
|
||||
@@ -1333,14 +1597,16 @@ public class PermissionMenuService {
|
||||
/**
|
||||
* Resolves the default sort order when none is supplied, scoped to the
|
||||
* menu's own type (parent takes precedence, then hierarchy ancestors).
|
||||
* The DB query mirrors {@link #loadMenus(String)} ordering so the last row
|
||||
* is the true tail of the type's ordering.
|
||||
* The DB query mirrors {@link #loadMenus(Long, String)} ordering so the last row
|
||||
* is the true tail of the type's ordering, and the same company the new row lands in
|
||||
* (两棵树的 sort_order 各排各的,跨公司取 MAX 会让两排同名菜单交织)。
|
||||
*/
|
||||
private Integer resolveSortOrder(String menuType, Integer sortOrder, Long excludeId) {
|
||||
private Integer resolveSortOrder(Long companyId, String menuType, Integer sortOrder, Long excludeId) {
|
||||
if (sortOrder != null) {
|
||||
return sortOrder;
|
||||
}
|
||||
PermissionMenuEntity tail = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
|
||||
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
|
||||
.eq(PermissionMenuEntity::getMenuType, normalizeMenuType(menuType))
|
||||
.ne(excludeId != null, PermissionMenuEntity::getId, excludeId)
|
||||
.orderByDesc(PermissionMenuEntity::getSortOrder)
|
||||
|
||||
+19
-35
@@ -1,8 +1,6 @@
|
||||
package com.nanri.aiimage.modules.productcategory.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
|
||||
@@ -10,7 +8,6 @@ import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryItemVo;
|
||||
import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo;
|
||||
import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService;
|
||||
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 jakarta.validation.Valid;
|
||||
@@ -34,24 +31,21 @@ import java.time.format.DateTimeFormatter;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin")
|
||||
@Tag(name = "商品类目管理", description = "维护商品类目树")
|
||||
@Tag(name = "商品类目管理", description = "维护商品类目树(全平台共享,不按公司区分)")
|
||||
public class ProductCategoryController {
|
||||
|
||||
private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
|
||||
|
||||
private final ProductCategoryService productCategoryService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping("/product-categories")
|
||||
@Operation(summary = "查询商品类目树")
|
||||
public ApiResponse<ProductCategoryListVo> list(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(productCategoryService.list(keyword, scopedCompanyId));
|
||||
@RequestParam(value = "keyword", required = false) String keyword) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success(productCategoryService.list(keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/product-categories/children")
|
||||
@@ -60,11 +54,9 @@ public class ProductCategoryController {
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "parent_id", required = false) Long parentId,
|
||||
@RequestParam(value = "page", defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize, scopedCompanyId));
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/product-categories/search")
|
||||
@@ -73,22 +65,18 @@ public class ProductCategoryController {
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@RequestParam(value = "page", defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize, scopedCompanyId));
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/product-categories/export")
|
||||
@Operation(summary = "导出商品类目")
|
||||
public ResponseEntity<byte[]> export(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
byte[] bytes = productCategoryService.export(keyword, scopedCompanyId);
|
||||
@RequestParam(value = "keyword", required = false) String keyword) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
byte[] bytes = productCategoryService.export(keyword);
|
||||
String filename = "product-categories-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
|
||||
@@ -102,10 +90,8 @@ public class ProductCategoryController {
|
||||
public ApiResponse<ProductCategoryItemVo> create(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody ProductCategorySaveRequest body) {
|
||||
// 归属只从会话推(请求体一律不带 company_id):service 里 requireCompanyId 取不到就抛,
|
||||
// 不让 V147 的 DEFAULT 1 静默兜住。
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("创建成功", productCategoryService.create(body, operator.getId()));
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("创建成功", productCategoryService.create(body));
|
||||
}
|
||||
|
||||
@PutMapping("/product-category/{id}")
|
||||
@@ -114,10 +100,8 @@ public class ProductCategoryController {
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody ProductCategorySaveRequest body) {
|
||||
// 写侧闸门与读侧同源:读已经收窄到本公司,写不收窄就是"藏起来的行照样能删"。
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("保存成功",
|
||||
productCategoryService.update(id, body, dataReadScope.writeCompanyId(operator)));
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("保存成功", productCategoryService.update(id, body));
|
||||
}
|
||||
|
||||
@DeleteMapping("/product-category/{id}")
|
||||
@@ -125,8 +109,8 @@ public class ProductCategoryController {
|
||||
public ApiResponse<Void> delete(
|
||||
HttpServletRequest request,
|
||||
@PathVariable Long id) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
productCategoryService.delete(id, dataReadScope.writeCompanyId(operator));
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
productCategoryService.delete(id);
|
||||
return ApiResponse.success("删除成功", null);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-8
@@ -7,20 +7,19 @@ import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 商品类目——<b>全平台共享的一棵树,不按公司区分</b>(控制方 2026-10-06 定案)。
|
||||
*
|
||||
* <p>所以这里<b>不声明</b> {@code company_id} 字段。库里那一列(V147 加的,带临时 {@code DEFAULT 1})
|
||||
* 暂时还在,但没有任何读写路径引用它:不声明字段 ⇒ MyBatis-Plus 的 SELECT 列清单与 INSERT 都不含它
|
||||
* ⇒ 新 jar 配旧库(列还在)不会报错,摘列则必须等两台都跑上这一版(见 migration-inventory 的下一版待办)。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_product_category")
|
||||
public class ProductCategoryEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
/**
|
||||
* 归属公司(V147)。{@code 0} = 平台内置共享节点(不是 company 表里的行),其余是那一家的自建节点。
|
||||
*
|
||||
* <p>写侧必须显式盖章:这一列在 V147 里带着<b>临时</b>的 {@code DEFAULT 1}(旧 jar 的实体没这字段),
|
||||
* 漏传不会报错、会被静默塞进厦门米椿花。{@code ProductCategoryService.create} 因此走
|
||||
* {@code CompanyScopeSupport.requireCompanyId}(取不到就抛),不依赖这一默认值。</p>
|
||||
*/
|
||||
private Long companyId;
|
||||
private Long parentId;
|
||||
private String name;
|
||||
private String categoryKey;
|
||||
|
||||
+88
-159
@@ -4,7 +4,6 @@ import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper;
|
||||
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
|
||||
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
|
||||
@@ -28,6 +27,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -35,109 +35,71 @@ public class ProductCategoryService {
|
||||
|
||||
private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
/**
|
||||
* 内置节点的哨兵归属(V147 回填):它不是公司表里的行,而是"所有公司都看得见、谁都不拥有"的那半棵树。
|
||||
*
|
||||
* <p>取 0 是因为 {@code company.id} 从 1 起自增,而 {@code CompanyScopeSupport.requireCompanyId}
|
||||
* 对 {@code <= 0} 直接抛 ⇒ 没有任何账号会被登记成 0 号公司,这个值和真实公司永不撞。</p>
|
||||
*/
|
||||
static final long SHARED_BUILTIN_COMPANY_ID = 0L;
|
||||
|
||||
private final ProductCategoryMapper productCategoryMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
/**
|
||||
* 全平台类目树——<b>不按公司筛,且不许改成按公司筛</b>。
|
||||
* 全平台一棵树——<b>不按公司筛,且不许改成按公司筛</b>(控制方 2026-10-06 定案:商品类目共享、不区分)。
|
||||
*
|
||||
* <p>唯一的消费者是货源/外观的类目归类({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。
|
||||
* 那一侧按公司切会同时改两件事:候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。
|
||||
* 后台的公司 tab 走 {@link #list(String, Long)},两件事别混。</p>
|
||||
* <p>两个消费者共用它:后台这一页,以及货源/外观的类目归类
|
||||
* ({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。后者若按公司切会同时改两件事:
|
||||
* 候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。</p>
|
||||
*/
|
||||
public ProductCategoryListVo list() {
|
||||
return list(null);
|
||||
}
|
||||
|
||||
/** 不筛公司(超管没选 tab 时的口径,与改造前一致)。 */
|
||||
public ProductCategoryListVo list(String keyword) {
|
||||
return list(keyword, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param companyId 要收窄到的公司;null = 不筛。内置节点({@value #SHARED_BUILTIN_COMPANY_ID})
|
||||
* 在任何公司的视图里都可见,否则第 2 家的类目树会是空的、连一个自建根都挂不上。
|
||||
*/
|
||||
public ProductCategoryListVo list(String keyword, Long companyId) {
|
||||
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(applyCompanyScope(
|
||||
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.orderByAsc(ProductCategoryEntity::getParentId)
|
||||
.orderByAsc(ProductCategoryEntity::getSortOrder)
|
||||
.orderByAsc(ProductCategoryEntity::getId),
|
||||
companyId));
|
||||
.orderByAsc(ProductCategoryEntity::getId));
|
||||
rows = filterRowsByKeyword(rows, keyword);
|
||||
return buildListVo(rows);
|
||||
}
|
||||
|
||||
public ProductCategoryListVo children(Long parentId, long page, long pageSize) {
|
||||
return children(parentId, page, pageSize, null);
|
||||
}
|
||||
|
||||
public ProductCategoryListVo children(Long parentId, long page, long pageSize, Long companyId) {
|
||||
long safePage = Math.max(page, 1);
|
||||
long safePageSize = normalizePageSize(pageSize);
|
||||
Long normalizedParentId = normalizeParentId(parentId);
|
||||
LambdaQueryWrapper<ProductCategoryEntity> countQuery = applyCompanyScope(new LambdaQueryWrapper<>(), companyId);
|
||||
LambdaQueryWrapper<ProductCategoryEntity> countQuery = new LambdaQueryWrapper<>();
|
||||
applyParentFilter(countQuery, normalizedParentId);
|
||||
Long total = productCategoryMapper.selectCount(countQuery);
|
||||
|
||||
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = applyCompanyScope(
|
||||
new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.orderByAsc(ProductCategoryEntity::getSortOrder)
|
||||
.orderByAsc(ProductCategoryEntity::getId),
|
||||
companyId)
|
||||
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.orderByAsc(ProductCategoryEntity::getSortOrder)
|
||||
.orderByAsc(ProductCategoryEntity::getId)
|
||||
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize);
|
||||
applyParentFilter(pageQuery, normalizedParentId);
|
||||
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(pageQuery);
|
||||
return buildPageVo(rows, total, safePage, safePageSize, companyId);
|
||||
return buildPageVo(rows, total, safePage, safePageSize);
|
||||
}
|
||||
|
||||
public ProductCategoryListVo search(String keyword, long page, long pageSize) {
|
||||
return search(keyword, page, pageSize, null);
|
||||
}
|
||||
|
||||
public ProductCategoryListVo search(String keyword, long page, long pageSize, Long companyId) {
|
||||
String normalized = normalizeSearchKeyword(keyword);
|
||||
if (normalized.isBlank()) {
|
||||
return emptyPageVo(Math.max(page, 1), normalizePageSize(pageSize));
|
||||
}
|
||||
long safePage = Math.max(page, 1);
|
||||
long safePageSize = normalizePageSize(pageSize);
|
||||
Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized, companyId));
|
||||
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized, companyId)
|
||||
Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized));
|
||||
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized)
|
||||
.orderByAsc(ProductCategoryEntity::getParentId)
|
||||
.orderByAsc(ProductCategoryEntity::getSortOrder)
|
||||
.orderByAsc(ProductCategoryEntity::getId)
|
||||
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));
|
||||
return buildSearchPageVo(rows, total, safePage, safePageSize, companyId);
|
||||
return buildSearchPageVo(rows, total, safePage, safePageSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属由<b>操作者会话</b>推导(请求体/查询参数一律不带 company_id):漏了这一句,新类目就会被
|
||||
* V147 的 {@code DEFAULT 1} 静默塞进厦门米椿花——那是"归属失真且不报错",而 {@code requireCompanyId}
|
||||
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载:留着它等于留着一个
|
||||
* "调用方忘了传也照样绿"的出口。
|
||||
*
|
||||
* @param operatorId 操作者账号 id
|
||||
*/
|
||||
/** 新建的类目落进全平台共享的那一棵树:谁建的都不记归属,只保证同级不重名。 */
|
||||
@Transactional
|
||||
public ProductCategoryItemVo create(ProductCategorySaveRequest request, Long operatorId) {
|
||||
public ProductCategoryItemVo create(ProductCategorySaveRequest request) {
|
||||
String name = normalizeRequired(request.getName(), "类目名称不能为空");
|
||||
Long parentId = normalizeParentId(request.getParentId());
|
||||
Long companyId = companyScopeSupport.requireCompanyId(operatorId);
|
||||
ensureParentVisible(parentId, null, companyId);
|
||||
ensureSiblingNameUnique(parentId, name, null, companyId);
|
||||
ensureParentVisible(parentId, null);
|
||||
ensureSiblingNameUnique(parentId, name, null);
|
||||
|
||||
ProductCategoryEntity entity = new ProductCategoryEntity();
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setParentId(parentId);
|
||||
entity.setName(name);
|
||||
entity.setCategoryKey(generateCategoryKey(parentId, name));
|
||||
@@ -148,22 +110,13 @@ public class ProductCategoryService {
|
||||
return findItem(entity.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param writableCompanyId 行归属闸门({@code DataReadScope.writeCompanyId} 给):
|
||||
* {@code null} = 平台超管不限,否则只能动这一家自己的行。
|
||||
* 读侧收窄而写侧不收窄="藏起来的行仍然能删",那是静默删除不是隔离。
|
||||
*/
|
||||
@Transactional
|
||||
public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request, Long writableCompanyId) {
|
||||
public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request) {
|
||||
ProductCategoryEntity entity = getById(id);
|
||||
assertRowWritable(entity, writableCompanyId);
|
||||
String name = normalizeRequired(request.getName(), "类目名称不能为空");
|
||||
Long parentId = normalizeParentId(request.getParentId());
|
||||
// 改行时"生效公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家,
|
||||
// 换父级时不能把行挪到可见集外的节点下面(那会让它从原本看得见它的 tab 里消失)。
|
||||
Long companyId = entity.getCompanyId();
|
||||
ensureParentVisible(parentId, id, companyId);
|
||||
ensureSiblingNameUnique(parentId, name, id, companyId);
|
||||
ensureParentVisible(parentId, id);
|
||||
ensureSiblingNameUnique(parentId, name, id);
|
||||
|
||||
entity.setParentId(parentId);
|
||||
entity.setName(name);
|
||||
@@ -174,9 +127,8 @@ public class ProductCategoryService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(Long id, Long writableCompanyId) {
|
||||
public void delete(Long id) {
|
||||
ProductCategoryEntity entity = getById(id);
|
||||
assertRowWritable(entity, writableCompanyId);
|
||||
Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.eq(ProductCategoryEntity::getParentId, entity.getId()));
|
||||
if (childCount != null && childCount > 0) {
|
||||
@@ -185,29 +137,13 @@ public class ProductCategoryService {
|
||||
productCategoryMapper.deleteById(entity.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 行归属闸门。走 {@code assertSameCompany} 而不是在这里比一次:它对本仓所有"按公司写"的闸门
|
||||
* 是唯一一份判定,两处各写就会有一处先漂。
|
||||
*
|
||||
* <p>内置节点(哨兵 0)在这一支里必然被拒——{@code 0 != 任何真实公司 id},
|
||||
* 而"公司账号能改/删平台内置类目"正是这一页最容易出事的一刀:改了它,
|
||||
* 所有公司的类目树与货源归类的候选表同一天跟着变。</p>
|
||||
*/
|
||||
private void assertRowWritable(ProductCategoryEntity row, Long writableCompanyId) {
|
||||
if (writableCompanyId == null) {
|
||||
return;
|
||||
}
|
||||
companyScopeSupport.assertSameCompany(writableCompanyId, row.getCompanyId(),
|
||||
"无权修改该类目:内置类目或别家公司的类目不在本公司的写范围内");
|
||||
}
|
||||
|
||||
private ProductCategoryItemVo findItem(Long id) {
|
||||
ProductCategoryEntity entity = getById(id);
|
||||
Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.eq(ProductCategoryEntity::getParentId, entity.getId()));
|
||||
ProductCategoryItemVo item = toItemVo(entity, childCount == null ? 0 : childCount.intValue());
|
||||
item.setLevel(resolveLevel(entity));
|
||||
item.setPath(resolvePath(entity));
|
||||
item.setLevel(resolveLevel(entity, productCategoryMapper::selectById));
|
||||
item.setPath(resolvePath(entity, productCategoryMapper::selectById));
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -236,10 +172,16 @@ public class ProductCategoryService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
|
||||
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
|
||||
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
|
||||
Map<Long, Integer> childCountById = buildChildCountById(rows);
|
||||
Map<Long, ProductCategoryEntity> ancestors = loadAncestorIndex(rows);
|
||||
List<ProductCategoryItemVo> items = rows.stream()
|
||||
.map(row -> toItemVo(row, childCountById.getOrDefault(row.getId(), 0)))
|
||||
.map(row -> {
|
||||
ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0));
|
||||
item.setLevel(resolveLevel(row, ancestors::get));
|
||||
item.setPath(resolvePath(row, ancestors::get));
|
||||
return item;
|
||||
})
|
||||
.toList();
|
||||
ProductCategoryListVo vo = new ProductCategoryListVo();
|
||||
vo.setItems(items);
|
||||
@@ -251,13 +193,9 @@ public class ProductCategoryService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 导出的行集合必须与页面列表同源:都走 {@link #list(String, Long)},否则"tab 里看不见但导出里有"就是第二个真相源。 */
|
||||
/** 导出的行集合必须与页面列表同源:都走 {@link #list(String)},否则"页面里没有但导出里有"就是第二个真相源。 */
|
||||
public byte[] export(String keyword) {
|
||||
return export(keyword, null);
|
||||
}
|
||||
|
||||
public byte[] export(String keyword, Long companyId) {
|
||||
ProductCategoryListVo list = list(keyword, companyId);
|
||||
ProductCategoryListVo list = list(keyword);
|
||||
List<ProductCategoryItemVo> rows = list.getItems() == null ? List.of() : list.getItems();
|
||||
Map<Long, String> nameById = buildExportNameById(rows);
|
||||
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100);
|
||||
@@ -276,13 +214,13 @@ public class ProductCategoryService {
|
||||
}
|
||||
}
|
||||
|
||||
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
|
||||
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
|
||||
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
|
||||
Map<Long, Integer> childCountById = buildChildCountById(rows);
|
||||
List<ProductCategoryItemVo> items = rows.stream()
|
||||
.map(row -> {
|
||||
ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0));
|
||||
item.setLevel(resolveLevel(row));
|
||||
item.setPath(resolvePath(row));
|
||||
item.setLevel(resolveLevel(row, productCategoryMapper::selectById));
|
||||
item.setPath(resolvePath(row, productCategoryMapper::selectById));
|
||||
return item;
|
||||
})
|
||||
.toList();
|
||||
@@ -383,12 +321,8 @@ public class ProductCategoryService {
|
||||
return time == null ? "" : time.format(EXPORT_TIME_FORMATTER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表页的「子类目数」徽章走的是<b>全表聚合</b>(不是内存里那批行),所以它必须和公司视图同源:
|
||||
* 不加这一段,第 1 家的父节点上会显示"3 个子类目"而 tab 里只列得出一两个——
|
||||
* 数字来自别人的公司,点开却是自己的树。
|
||||
*/
|
||||
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows, Long companyId) {
|
||||
/** 列表页的「子类目数」徽章走全表聚合(不是内存里那批行)——整棵树共享,聚合也就没有"别家的数"这一说。 */
|
||||
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows) {
|
||||
Map<Long, Integer> childCountById = new HashMap<>();
|
||||
if (rows.isEmpty()) {
|
||||
return childCountById;
|
||||
@@ -396,9 +330,6 @@ public class ProductCategoryService {
|
||||
QueryWrapper<ProductCategoryEntity> countQuery = new QueryWrapper<ProductCategoryEntity>()
|
||||
.select("parent_id", "count(*) AS child_count")
|
||||
.isNotNull("parent_id");
|
||||
if (companyId != null) {
|
||||
countQuery.in("company_id", visibleCompanyIds(companyId));
|
||||
}
|
||||
List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(countQuery.groupBy("parent_id"));
|
||||
for (Map<String, Object> countRow : countRows) {
|
||||
Object parentId = countRow.get("parent_id");
|
||||
@@ -420,39 +351,19 @@ public class ProductCategoryService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 关键字命中三条列任一即算命中,但<b>整条 OR 必须包起来再 AND 公司</b>:MyBatis-Plus 的
|
||||
* {@code or()} 只改"下一个连接符",直接在这串后面 {@code .in(company_id, ...)} 会拼成
|
||||
* {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND company_id IN ...)} —— SQL 里 AND 结合更紧,
|
||||
* 结果前两条列命中的行<b>不受公司约束</b>,这一页的筛选就成了假的(且不报错)。
|
||||
* 关键字命中三条列任一即算命中,整条 OR 必须包起来:MyBatis-Plus 的 {@code or()} 只改
|
||||
* "下一个连接符",直接在这串后面再 AND 别的条件会拼成
|
||||
* {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND ...)} —— SQL 里 AND 结合更紧,
|
||||
* 前两条列命中的行不受那个条件约束(且不报错)。
|
||||
*/
|
||||
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword, Long companyId) {
|
||||
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword) {
|
||||
return new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.and(group -> group
|
||||
.like(ProductCategoryEntity::getName, keyword)
|
||||
.or()
|
||||
.like(ProductCategoryEntity::getCategoryKey, keyword)
|
||||
.or()
|
||||
.like(ProductCategoryEntity::getDescription, keyword));
|
||||
return applyCompanyScope(query, companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司视图的唯一落点:null = 不筛(超管没选 tab、非超管、以及 {@link #list()} 那棵给 LLM 的全局树);
|
||||
* 否则 {@code company_id IN (0, X)} —— 哨兵 0 那批内置节点在任何公司视图里都必须在,
|
||||
* 不然第 2 家的类目页是一棵空树,它自建不出任何子级(父级只能挂在这批上面)。
|
||||
*/
|
||||
private LambdaQueryWrapper<ProductCategoryEntity> applyCompanyScope(
|
||||
LambdaQueryWrapper<ProductCategoryEntity> query, Long companyId) {
|
||||
if (companyId != null) {
|
||||
query.in(ProductCategoryEntity::getCompanyId, visibleCompanyIds(companyId));
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private List<Long> visibleCompanyIds(Long companyId) {
|
||||
return companyId == SHARED_BUILTIN_COMPANY_ID
|
||||
? List.of(SHARED_BUILTIN_COMPANY_ID)
|
||||
: List.of(SHARED_BUILTIN_COMPANY_ID, companyId);
|
||||
}
|
||||
|
||||
private List<ProductCategoryEntity> filterRowsByKeyword(List<ProductCategoryEntity> rows, String keyword) {
|
||||
@@ -570,12 +481,43 @@ public class ProductCategoryService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
private int resolveLevel(ProductCategoryEntity entity) {
|
||||
/**
|
||||
* 一次分页里所有行的父链索引:按层批量取,最多 depth 次 {@code selectBatchIds}。
|
||||
*
|
||||
* <p>「层级路径」这一列在懒加载通路上曾经是恒空的——{@code /children} 走
|
||||
* {@link #buildPageVo},它过去只填 {@link #toItemVo}、不设 {@code level}/{@code path},
|
||||
* 于是前端 {@code path || name} 回退成类目名,那一列画的是「类目」列的副本。补上它就要走父链,
|
||||
* 而一页最多 100 行、每行按层点查一次,形状是 N+1;这张表只有 412 行所以今天量不出来,
|
||||
* 但按行按层点查这个形状不该留在这里。</p>
|
||||
*/
|
||||
private Map<Long, ProductCategoryEntity> loadAncestorIndex(List<ProductCategoryEntity> rows) {
|
||||
Map<Long, ProductCategoryEntity> index = new HashMap<>();
|
||||
Set<Long> pending = new HashSet<>();
|
||||
for (ProductCategoryEntity row : rows) {
|
||||
if (row.getParentId() != null) {
|
||||
pending.add(row.getParentId());
|
||||
}
|
||||
}
|
||||
while (!pending.isEmpty()) {
|
||||
List<Long> ids = List.copyOf(pending);
|
||||
pending.clear();
|
||||
for (ProductCategoryEntity parent : productCategoryMapper.selectBatchIds(ids)) {
|
||||
if (index.put(parent.getId(), parent) == null
|
||||
&& parent.getParentId() != null
|
||||
&& !index.containsKey(parent.getParentId())) {
|
||||
pending.add(parent.getParentId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private int resolveLevel(ProductCategoryEntity entity, Function<Long, ProductCategoryEntity> lookup) {
|
||||
int level = 0;
|
||||
ProductCategoryEntity cursor = entity;
|
||||
Set<Long> visited = new HashSet<>();
|
||||
while (cursor != null && cursor.getParentId() != null && visited.add(cursor.getId())) {
|
||||
ProductCategoryEntity parent = productCategoryMapper.selectById(cursor.getParentId());
|
||||
ProductCategoryEntity parent = lookup.apply(cursor.getParentId());
|
||||
if (parent == null) {
|
||||
break;
|
||||
}
|
||||
@@ -585,13 +527,13 @@ public class ProductCategoryService {
|
||||
return level;
|
||||
}
|
||||
|
||||
private String resolvePath(ProductCategoryEntity entity) {
|
||||
private String resolvePath(ProductCategoryEntity entity, Function<Long, ProductCategoryEntity> lookup) {
|
||||
List<String> names = new ArrayList<>();
|
||||
ProductCategoryEntity cursor = entity;
|
||||
Set<Long> visited = new HashSet<>();
|
||||
while (cursor != null && cursor.getId() != null && visited.add(cursor.getId())) {
|
||||
names.add(cursor.getName());
|
||||
cursor = cursor.getParentId() == null ? null : productCategoryMapper.selectById(cursor.getParentId());
|
||||
cursor = cursor.getParentId() == null ? null : lookup.apply(cursor.getParentId());
|
||||
}
|
||||
List<String> ordered = new ArrayList<>();
|
||||
for (int i = names.size() - 1; i >= 0; i--) {
|
||||
@@ -608,14 +550,8 @@ public class ProductCategoryService {
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 父级必须"存在且在这一公司的可见集里"。
|
||||
*
|
||||
* <p>只查存在性是不够的:把行的 parent_id 指到别家公司的节点上,这一行就从原本看得见它的
|
||||
* tab 里消失(读侧按父级子树裁),而 {@code parent_id} 没有外键、库里一声不响。
|
||||
* companyId 为 null 时不校验——那是改造前/内部调用的口径,不是"允许跨公司挂"。</p>
|
||||
*/
|
||||
private void ensureParentVisible(Long parentId, Long currentId, Long companyId) {
|
||||
/** 父级必须存在,且不能把自己挂到自己的子级下面({@code parent_id} 没有外键,库里一声不响)。 */
|
||||
private void ensureParentVisible(Long parentId, Long currentId) {
|
||||
if (parentId == null) {
|
||||
return;
|
||||
}
|
||||
@@ -626,9 +562,6 @@ public class ProductCategoryService {
|
||||
if (parent == null) {
|
||||
throw new BusinessException("父级类目不存在");
|
||||
}
|
||||
if (companyId != null && !visibleCompanyIds(companyId).contains(parent.getCompanyId())) {
|
||||
throw new BusinessException(403, "父级类目不属于当前公司");
|
||||
}
|
||||
Set<Long> visited = new HashSet<>();
|
||||
Long cursor = parent.getParentId();
|
||||
while (cursor != null) {
|
||||
@@ -644,16 +577,12 @@ public class ProductCategoryService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 同级重名检查的范围 = 这一家的<b>可见集</b>(自建 + 内置),不是只查自建。
|
||||
*
|
||||
* <p>只查自建会让第 2 家在内置父级"护肤品"下建出一个也叫"面霜"的节点,和内置的那个
|
||||
* 同层同名——页面上一排两个"面霜",而货源归类按名字回填时不知道落到哪一个。
|
||||
* 反过来,跨家的同名要放行:那正是 {@code uk_company_category_key} 换掉全平台唯一键要解决的问题。</p>
|
||||
* 同级重名检查的范围 = <b>全平台那一棵树</b>:同层同名必须拦,否则页面上一排两个"面霜",
|
||||
* 货源归类按名字回填时不知道落到哪一个。
|
||||
*/
|
||||
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId, Long companyId) {
|
||||
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId) {
|
||||
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
|
||||
.eq(ProductCategoryEntity::getName, name);
|
||||
applyCompanyScope(query, companyId);
|
||||
if (parentId == null) {
|
||||
query.isNull(ProductCategoryEntity::getParentId);
|
||||
} else {
|
||||
|
||||
+27
-16
@@ -1,7 +1,9 @@
|
||||
package com.nanri.aiimage.modules.shopkey.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo;
|
||||
@@ -34,22 +36,27 @@ public class ShopKeyController {
|
||||
|
||||
private final ShopKeyService shopKeyService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。")
|
||||
@Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。company_id 只收窄可见集、不放大:"
|
||||
+ "超管按 tab 指定的公司读,非超管一律锁本公司(越界公司为空页)。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class)))
|
||||
})
|
||||
public ApiResponse<ShopKeyPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success(shopKeyService.page(page, pageSize));
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪)")
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(shopKeyService.page(page, pageSize, scopedCompanyId));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。")
|
||||
@Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。归属由操作者会话推导,请求体不带 company_id。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法")
|
||||
@@ -57,51 +64,55 @@ public class ShopKeyController {
|
||||
public ApiResponse<ShopKeyItemVo> create(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody ShopKeyCreateRequest body) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("创建成功", shopKeyService.create(body));
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("创建成功", shopKeyService.create(body, operator.getId()));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "更新店铺密钥", description = "按 ID 更新一条店铺密钥记录。")
|
||||
@Operation(summary = "更新店铺密钥", description = "按 ID 更新一条店铺密钥记录。别家公司的密钥不在本公司的写范围内。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
|
||||
})
|
||||
public ApiResponse<ShopKeyItemVo> update(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "主键ID", required = true) @PathVariable Long id,
|
||||
@Valid @RequestBody ShopKeyUpdateRequest body) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("更新成功", shopKeyService.update(id, body));
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("更新成功", shopKeyService.update(id, body, dataReadScope.writeCompanyId(operator)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除店铺密钥", description = "按 ID 删除一条店铺密钥记录。")
|
||||
@Operation(summary = "删除店铺密钥", description = "按 ID 删除一条店铺密钥记录。别家公司的密钥不在本公司的写范围内。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
|
||||
})
|
||||
public ApiResponse<Void> delete(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "主键ID", required = true) @PathVariable Long id) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
shopKeyService.delete(id);
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
shopKeyService.delete(id, dataReadScope.writeCompanyId(operator));
|
||||
return ApiResponse.success("删除成功", null);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/check-whitelist")
|
||||
@Operation(summary = "手动检测 IP 白名单",
|
||||
description = "绕过缓存真实请求一次紫鸟接口,重置自动重试次数。"
|
||||
+ "白名单放行需紫鸟公司侧授权,自动重试达上限后会停止重试,授权后可用此接口重新验证。")
|
||||
+ "白名单放行需紫鸟公司侧授权,自动重试达上限后会停止重试,授权后可用此接口重新验证。"
|
||||
+ "别家公司的密钥同样不能替它发起出网检测。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "检测完成", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
|
||||
})
|
||||
public ApiResponse<ShopKeyItemVo> checkWhitelist(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "主键ID", required = true) @PathVariable Long id) {
|
||||
adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("检测完成", shopKeyService.checkWhitelist(id));
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
return ApiResponse.success("检测完成", shopKeyService.checkWhitelist(id, dataReadScope.writeCompanyId(operator)));
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -15,6 +15,8 @@ public class ShopKeyEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
/** 归属公司(company.id)。V150 加的列,历史行的值来自当时的列默认值 1,本表无账号列故事后不可反推。 */
|
||||
private Long companyId;
|
||||
private String remarkName;
|
||||
private String ziniaoAccountName;
|
||||
private String ziniaoToken;
|
||||
|
||||
+8
@@ -15,6 +15,14 @@ import java.util.List;
|
||||
/**
|
||||
* shop_key 表对紫鸟侧的只读/回写适配器:把紫鸟需要的字段暴露给 ziniao 模块,
|
||||
* 使 ziniao 不再直接引用 shopkey 的 Mapper 与 Entity(打破模块循环依赖)。
|
||||
*
|
||||
* <p><b>这里的 listAll/count 恒为全平台,刻意不跟着 V150 的 company_id 收窄。</b>
|
||||
* 它的消费者是店铺索引刷新({@code ZiniaoShopIndexService},游标 scopeKey 就是 "global")
|
||||
* 和令牌轮询({@code ZiniaoAuthService#getScanApiKeys})——那是<b>运行时令牌池</b>,
|
||||
* 一个后台定时任务没有"当前公司"这个上下文,也没有可以筛的目标:按公司筛它,
|
||||
* 等于让第二家公司的紫鸟店铺永远进不了索引,而这一页的隔离要收窄的是
|
||||
* <b>谁能看见/改动这把握在紫鸟那边的令牌</b>(管理面),不是"这把令牌替谁出网"(用量面)。
|
||||
* 想要用量面也隔离,得先给索引刷新建每公司一份的游标与索引行,那是另一期工程。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
|
||||
+67
-14
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.service;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
|
||||
@@ -36,12 +37,17 @@ public class ShopKeyService {
|
||||
private final ZiniaoShopIndexService ziniaoShopIndexService;
|
||||
private final ZiniaoApiKeyProvider ziniaoApiKeyProvider;
|
||||
private final ZiniaoAuthService ziniaoAuthService;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
public ShopKeyPageVo page(long page, long pageSize) {
|
||||
/**
|
||||
* @param companyId 读范围公司:由 {@code DataReadScope.readCompanyIdOrOwn} 判定后传下来,
|
||||
* {@code null} 只可能来自平台超管「不筛」的判定,调用方不许在这里补默认值。
|
||||
*/
|
||||
public ShopKeyPageVo page(long page, long pageSize, Long companyId) {
|
||||
long safePage = Math.max(page, 1);
|
||||
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
|
||||
LambdaQueryWrapper<ShopKeyEntity> query = new LambdaQueryWrapper<ShopKeyEntity>()
|
||||
.orderByDesc(ShopKeyEntity::getId);
|
||||
LambdaQueryWrapper<ShopKeyEntity> query = applyCompanyScope(
|
||||
new LambdaQueryWrapper<ShopKeyEntity>().orderByDesc(ShopKeyEntity::getId), companyId);
|
||||
Long total = shopKeyMapper.selectCount(query);
|
||||
List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize))
|
||||
.stream()
|
||||
@@ -55,13 +61,19 @@ public class ShopKeyService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属由<b>操作者会话</b>推导(请求体一律不带 company_id):漏了这一句,新密钥就会被 V150 的
|
||||
* {@code DEFAULT 1} 静默塞进第 1 家——那是"归属失真且不报错",而 {@code requireCompanyId}
|
||||
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载。
|
||||
*/
|
||||
@Transactional
|
||||
public ShopKeyItemVo create(ShopKeyCreateRequest request) {
|
||||
public ShopKeyItemVo create(ShopKeyCreateRequest request, Long operatorId) {
|
||||
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
|
||||
String ziniaoToken = normalizeToken(request.getZiniaoToken());
|
||||
String ziniaoTokenHash = hashToken(ziniaoToken);
|
||||
ensureTokenAvailable(ziniaoTokenHash, null);
|
||||
ShopKeyEntity entity = new ShopKeyEntity();
|
||||
entity.setCompanyId(companyScopeSupport.requireCompanyId(operatorId));
|
||||
entity.setRemarkName(normalizeOptional(request.getRemarkName()));
|
||||
entity.setZiniaoAccountName(ziniaoAccountName);
|
||||
entity.setZiniaoToken(ziniaoToken);
|
||||
@@ -72,12 +84,12 @@ public class ShopKeyService {
|
||||
insertOrThrowDuplicateToken(entity);
|
||||
ziniaoApiKeyProvider.invalidateProxyUrlCache();
|
||||
triggerShopIndexRefresh();
|
||||
return toItemVo(getById(entity.getId()));
|
||||
return toItemVo(loadRow(entity.getId()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request) {
|
||||
ShopKeyEntity entity = getById(id);
|
||||
public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request, Long writableCompanyId) {
|
||||
ShopKeyEntity entity = getById(id, writableCompanyId);
|
||||
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
|
||||
String ziniaoToken = normalizeToken(request.getZiniaoToken());
|
||||
String ziniaoTokenHash = hashToken(ziniaoToken);
|
||||
@@ -105,12 +117,12 @@ public class ShopKeyService {
|
||||
updateOrThrowDuplicateToken(entity);
|
||||
ziniaoApiKeyProvider.invalidateProxyUrlCache();
|
||||
triggerShopIndexRefresh();
|
||||
return toItemVo(getById(id));
|
||||
return toItemVo(getById(id, writableCompanyId));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
ShopKeyEntity entity = getById(id);
|
||||
public void delete(Long id, Long writableCompanyId) {
|
||||
ShopKeyEntity entity = getById(id, writableCompanyId);
|
||||
shopKeyMapper.deleteById(entity.getId());
|
||||
ziniaoApiKeyProvider.invalidateProxyUrlCache();
|
||||
triggerShopIndexRefresh();
|
||||
@@ -125,8 +137,8 @@ public class ShopKeyService {
|
||||
* 挂在事务上等于把连接池的连接按上游 RTT 扣住,多次点击即可耗尽池——这正是本仓
|
||||
* 「事务内含外部 IO」要避免的形态。
|
||||
*/
|
||||
public ShopKeyItemVo checkWhitelist(Long id) {
|
||||
ShopKeyEntity entity = getById(id);
|
||||
public ShopKeyItemVo checkWhitelist(Long id, Long writableCompanyId) {
|
||||
ShopKeyEntity entity = getById(id, writableCompanyId);
|
||||
ziniaoApiKeyProvider.invalidateProxyUrlCache();
|
||||
try {
|
||||
ziniaoAuthService.probeApiKeyUpstream(entity.getZiniaoToken());
|
||||
@@ -145,7 +157,7 @@ public class ShopKeyService {
|
||||
id, entity.getZiniaoAccountName(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
return toItemVo(getById(id));
|
||||
return toItemVo(getById(id, writableCompanyId));
|
||||
}
|
||||
|
||||
private void updateWhitelistState(Long id, String status, String message, int failCount) {
|
||||
@@ -157,7 +169,18 @@ public class ShopKeyService {
|
||||
.set(ShopKeyEntity::getIpWhitelistFailCount, failCount));
|
||||
}
|
||||
|
||||
private ShopKeyEntity getById(Long id) {
|
||||
private ShopKeyEntity getById(Long id, Long writableCompanyId) {
|
||||
ShopKeyEntity entity = loadRow(id);
|
||||
assertRowWritable(entity, writableCompanyId);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 不带归属闸门的裸读取:只给两条已经由别的方式确定范围的路径用——
|
||||
* {@code create} 刚写完自己那一行(归属是它自己落的),以及 {@link #getById} 的内部复用。
|
||||
* 其余入口一律走 {@link #getById(Long, Long)},别在这里加"顺手读一行"的口子。
|
||||
*/
|
||||
private ShopKeyEntity loadRow(Long id) {
|
||||
ShopKeyEntity entity = shopKeyMapper.selectById(id);
|
||||
if (entity == null) {
|
||||
throw new BusinessException("店铺密钥不存在");
|
||||
@@ -165,6 +188,30 @@ public class ShopKeyService {
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级归属闸门:{@code null} = 平台超管不限。读侧已经收窄而写侧不收窄,等于"藏起来的密钥照样能改能删"。
|
||||
* 比较的是<b>行自己的</b> {@code company_id},不是 tab 的值。
|
||||
*/
|
||||
private void assertRowWritable(ShopKeyEntity row, Long writableCompanyId) {
|
||||
if (writableCompanyId == null) {
|
||||
return;
|
||||
}
|
||||
companyScopeSupport.assertSameCompany(writableCompanyId, row.getCompanyId(),
|
||||
"无权操作该密钥:别家公司的紫鸟令牌不在本公司的写范围内");
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司读范围:{@code null} 侧(平台超管「不筛」)原样不加条件。
|
||||
* <b>不许在它上面补一个默认公司</b>——那会让超管切到第 2 家时看到的还是第 1 家的令牌。
|
||||
*/
|
||||
private LambdaQueryWrapper<ShopKeyEntity> applyCompanyScope(
|
||||
LambdaQueryWrapper<ShopKeyEntity> query, Long companyId) {
|
||||
if (companyId != null) {
|
||||
query.eq(ShopKeyEntity::getCompanyId, companyId);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private String normalizeRequired(String value, String message) {
|
||||
String normalized = value == null ? "" : value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
@@ -248,6 +295,12 @@ public class ShopKeyService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 令牌查重<b>跨公司全局</b>做,不按 {@code companyId} 收窄——这与 V150 刻意不动
|
||||
* {@code uk_ziniao_token_hash} 是同一条决定的两面:同一个紫鸟令牌在两家公司各存一行,
|
||||
* 物理上是同一把握在紫鸟那边的账号被登记两次,而 {@code ZiniaoApiKeyProvider} 按令牌聚合,
|
||||
* 两行会并成一条、代理地址与白名单失败次数互相顶掉。数据库那把唯一键也根本不允许它发生。
|
||||
*/
|
||||
private void ensureTokenAvailable(String tokenHash, Long currentId) {
|
||||
ShopKeyEntity existing = shopKeyMapper.selectOne(new LambdaQueryWrapper<ShopKeyEntity>()
|
||||
.eq(ShopKeyEntity::getZiniaoTokenHash, tokenHash)
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V149__permission_menu_company_tree
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 设计:crawler-plugin/docs/ops/menu-company-tree-design-2026-10-06.md
|
||||
-- 需求:2026-10-06「菜单权限也加字段来区分,现在的默认归到 admin 下」,控制方选「每家公司一套菜单树」
|
||||
--
|
||||
-- 1. 变更目的:把 columns 从"全平台一棵菜单字典"改成"每家公司一套树",并把存量全部归厦门米椿花(id=1)。
|
||||
-- 今天这张表一个归属列都没有,两条唯一键都是全平台口径:
|
||||
-- - uk_column_key(column_key) ⇒ 第 2 家公司连"和别家同名"的菜单都建不出来(不是看不到,是建不出);
|
||||
-- - uk_menu_type_route_path(menu_type, route_path) ⇒ 同上,路径也不允许复用;
|
||||
-- 而读侧 findDataPermission 这类"按 column_key 点查 + LIMIT 1"(PermissionMenuService:1102)在换键后
|
||||
-- 会在同名的多行里借位拿到别家的行——所以这一版必须"加列 + 换键 + 复制 + 重指授权"同批做完,
|
||||
-- 只做加列等于把静默串扰装进生产。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- - 存量 52 行一律归公司 1(厦门米椿花)= 控制方说的"默认归到 admin 下"。
|
||||
-- - 三种 menu_type 全复制(admin 26 / app 24 / internal 2):客户端账号同样分属两家公司,
|
||||
-- 只复制 admin 会留半棵共享树,app 侧的权限键集合还是全平台一份。
|
||||
-- - 【唯一例外】admin_companies(id 109)不复制:它是角色内在闸门
|
||||
-- (Java 的 SUPER_ADMIN_ONLY_KEYS / 前端 SUPER_ADMIN_ONLY_MENU_KEYS 同一值),本来就"非超管看不见、
|
||||
-- 谁也授不出去",别家的树里没有这行比"有一行但被三道出口剪掉"更干净。
|
||||
-- - 公司 2 那 16 笔授权按 column_key 重指向本公司副本。不留成人工动作:否则德阳的 2 只账号
|
||||
-- 一上线就掉光菜单,"隐藏"就变成了静默删除。
|
||||
-- - 复制对 company 表里【所有】id<>1 的公司做(含 status=0 的停用公司):一行菜单不构成任何成本,
|
||||
-- 而"启用一家公司还要先补树"会让启用动作多一个能被忘掉的步骤。
|
||||
--
|
||||
-- 3. 影响表与数据量(2026-10-06 主机A 业务库只读实查,不是估的):
|
||||
-- columns = 52 行(admin 26:id 4..109|app 24:id 1..96|internal 2:id 69、95)
|
||||
-- company = 2 家(1 厦门米椿花、2 德阳)⇒ 复制段新增 51 行/家,本批共 +51 行
|
||||
-- user_column_permission = 784 笔 / 133 账号(公司1 131人768笔|公司2 2人16笔)⇒ 重指段最多改 16 行
|
||||
-- 同 column_key 重复行 = 0 ⇒ 新唯一键是旧键的严格放宽,换键不会因重复失败
|
||||
-- users / company / 其余业务表 0 改动
|
||||
--
|
||||
-- 4. 锁表风险:低。52 行的字典表,任何形态的 DDL 都在毫秒级;两条加唯一键仍按规矩钉
|
||||
-- ALGORITHM = INPLACE, LOCK = NONE。唯一的 COPY 是第 3 段那条 MODIFY ... NOT NULL(52 行,V143 同形)。
|
||||
-- 加列一律走【末位追加】(不写 AFTER):非末位加列能不能 INSTANT 取决于生产 MySQL 的小版本,
|
||||
-- 把这一条押在版本语义上,代价是发版窗口里第 1 段直接报 1846;而这一列的位置没有任何语义(读写都按列名)。
|
||||
-- 不碰 biz_task_file_job 等锁热点表。索引字节预算(utf8mb4 + DYNAMIC,上限 3072):
|
||||
-- uk_company_column_key = 8 + 64*4 = 264
|
||||
-- uk_company_menu_type_route_path = 8 + 20*4 + 255*4 = 1108
|
||||
-- 【不加 idx_columns_company】两条新唯一键的最左前缀就是 company_id,52 行的表再单开列索引
|
||||
-- 就是 V139 那轮清理掉的冗余索引形状。
|
||||
--
|
||||
-- 5. 换键顺序:先 ADD 新键,再 DROP 旧键,最后才插副本。倒过来写下的话第 6 段会撞 1062
|
||||
-- (旧键 uk_column_key 还在全局口径上守着一家一份)。中间任一步失败都至少还有一个唯一键在守并发。
|
||||
--
|
||||
-- 6. 回滚步骤:人工补丁 backend-java/docs/rollback-V149-permission-menu-company.sql(在 Flyway 扫描路径之外,
|
||||
-- 不写成 V150——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
|
||||
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=149 行 → 回滚 jar → 起应用。
|
||||
--
|
||||
-- 7. 上线窗口:随 jar 双节点同窗口发布(迁移在首台启动期执行,第二台见"已应用"即跳过),
|
||||
-- 金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。窗口内旧 jar 的后果清单见设计文档 §7,
|
||||
-- 三条都是"难看/保守拒绝",不是跨公司放行。
|
||||
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 PermissionMenuEntity 没有 companyId 字段,
|
||||
-- MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364,打到旧节点的"新增菜单"会全失败。
|
||||
-- 摘除动作与前四张表同一版做(下一版一条元数据操作 ALTER TABLE `columns` ALTER COLUMN company_id DROP DEFAULT,
|
||||
-- 与 biz_product_category 那条一起;禁写成 MODIFY,重建会按当时的列默认值物化历史行),
|
||||
-- 在摘掉之前由启动期 CompanyDefaultGuard 盯住(WATCHED_TABLES 已加 columns),
|
||||
-- 巡检按 COMPANY_DEFAULT_STILL_PRESENT 这条 ASCII 签名 grep——"漏摘"由代码喊,不靠人记得。
|
||||
--
|
||||
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在换键或复制段失败,前面的加列与回填已落库;
|
||||
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以每条 DDL
|
||||
-- 都先查 information_schema 再 PREPARE,回填 UPDATE 带 company_id IS NULL 限定,复制段带 NOT EXISTS 守卫,
|
||||
-- 重映射段带 parent_id IS NULL 限定,重指段带"行还挂在别家"限定 ⇒ 重跑逐条是 no-op。
|
||||
-- 末了四道自检闸门(临时表 must_be_zero NOT NULL,V143 那个"让约束替我喊"的家族):残留不为 0 就抛 1048
|
||||
-- 让迁移失败,而不是留一棵静默分叉的树——尤其闸门 1,它专防"NOT EXISTS 守卫把该插的行挡掉"这种
|
||||
-- 一声不响少一整家树的形状(PermissionMenuSchemaInitializer 那批裸 column_key 守卫就是同一形态)。
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 加列(末位 + INSTANT,先可空:第 2 段的回填才有行可写) ----------
|
||||
|
||||
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND COLUMN_NAME = 'company_id');
|
||||
SET @sql := IF(@col_exists = 0,
|
||||
'ALTER TABLE `columns` ADD COLUMN `company_id` bigint NULL COMMENT ''归属公司(company.id):每家公司一套菜单树;V149'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 2. 存量 52 行全部归厦门米椿花 ----------
|
||||
-- WHERE 限定 NULL ⇒ 重跑是 no-op,也不会覆盖任何人工指定过公司的行。
|
||||
|
||||
UPDATE `columns` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||
|
||||
-- ---------- 3. 收成 NOT NULL(这一句同时是回填自检闸门) ----------
|
||||
-- 第 2 段若漏掉任何一行,这里抛 1048 让迁移失败:NULL 意味着这一行在任何公司的树上都不出现,
|
||||
-- 而按 key 点查会把它当"没有这个菜单"。DEFAULT 1 的临时性与摘除时机见头部第 7 段。
|
||||
-- 这里的 MODIFY 是【建列时】定形状(52 行,毫秒级 COPY);摘 DEFAULT 那一版禁写 MODIFY,两者不是一回事。
|
||||
|
||||
ALTER TABLE `columns`
|
||||
MODIFY COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT '归属公司(company.id):每家公司一套菜单树;V149(DEFAULT 1 待下一版摘除)';
|
||||
|
||||
-- ---------- 4. 两条唯一键按公司放宽:先 ADD 新键 ----------
|
||||
-- 新键是旧键的严格放宽(旧键全平台唯一 ⇒ 新键必唯一),所以这两步不可能因重复而失败。
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_company_column_key');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_company_column_key` (`company_id`, `column_key`), 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 = 'columns'
|
||||
AND INDEX_NAME = 'uk_company_menu_type_route_path');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_company_menu_type_route_path` (`company_id`, `menu_type`, `route_path`), ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 5. 再 DROP 旧键(顺序不能反,见头部第 5 段) ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_column_key');
|
||||
SET @sql := IF(@idx_exists = 1,
|
||||
'ALTER TABLE `columns` DROP INDEX `uk_column_key`, 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 = 'columns' AND INDEX_NAME = 'uk_menu_type_route_path');
|
||||
SET @sql := IF(@idx_exists = 1,
|
||||
'ALTER TABLE `columns` DROP INDEX `uk_menu_type_route_path`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 6. 给 id<>1 的公司复制整棵树(parent_id 先留 NULL,第 7 段按 key 重映射) ----------
|
||||
-- 驱动集是「company 全表 × 公司 1 的字典行」,不是硬编码公司 2:第三家公司开通时不用再改迁移。
|
||||
-- 父指向不能照抄源行的 parent_id——那是全局 id,会跨公司挂到厦门米椿花的分组上;而外键
|
||||
-- fk_columns_parent_id 只保证父行【存在】,挡不住挂到别家,所以这里宁可先留 NULL 再按 key 认父。
|
||||
|
||||
INSERT INTO `columns` (`company_id`, `name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `created_at`)
|
||||
SELECT co.id, src.name, src.column_key, src.menu_type, src.route_path, src.sort_order, NULL, src.created_at
|
||||
FROM `company` co
|
||||
JOIN `columns` src ON src.company_id = 1
|
||||
WHERE co.id <> 1
|
||||
AND src.column_key <> 'admin_companies'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `columns` cp
|
||||
WHERE cp.company_id = co.id AND cp.column_key = src.column_key
|
||||
);
|
||||
|
||||
-- ---------- 7. 副本认父:沿 (company_id, column_key) 把父指向换成同公司副本 ----------
|
||||
-- 与插入顺序无关(源行父指向先落 NULL,join 命中才写),重跑时已认过父的行 parent_id 非 NULL ⇒ no-op;
|
||||
-- 源行本身是根的行 join 不到 sp ⇒ 一行不动,永久保持 NULL。
|
||||
|
||||
UPDATE `columns` copy
|
||||
JOIN `columns` src ON src.company_id = 1 AND src.column_key = copy.column_key
|
||||
JOIN `columns` sp ON sp.id = src.parent_id
|
||||
JOIN `columns` pcopy ON pcopy.company_id = copy.company_id AND pcopy.column_key = sp.column_key
|
||||
SET copy.parent_id = pcopy.id
|
||||
WHERE copy.company_id <> 1
|
||||
AND copy.parent_id IS NULL;
|
||||
|
||||
-- ---------- 8. 先把"源行 + 副本"并存的重复授权摘掉(今天 0 行,为 repair 重跑准备) ----------
|
||||
-- 第 9 段是把指针从源行改到副本,若某账号同时挂着这两笔,改完会撞 PK (user_id, column_id) 报 1062。
|
||||
-- 删副本那一侧、留源行那一侧给第 9 段去重指 ⇒ 结果只有一笔且指向本公司行。
|
||||
|
||||
DELETE dup FROM `user_column_permission` dup
|
||||
JOIN `users` u ON u.id = dup.user_id
|
||||
JOIN `columns` copy ON copy.id = dup.column_id AND copy.company_id = u.company_id
|
||||
JOIN `columns` src ON src.id <> copy.id AND src.column_key = copy.column_key AND src.company_id = 1
|
||||
JOIN `user_column_permission` old ON old.user_id = dup.user_id AND old.column_id = src.id
|
||||
WHERE u.company_id <> 1;
|
||||
|
||||
-- ---------- 9. 存量授权重指向本公司副本(控制方 D1 定案:不留人工动作) ----------
|
||||
-- 驱动条件"行还挂在公司 1 而账号不属于公司 1"⇒ 重跑时第 9 段一行都选不出来,是 no-op。
|
||||
-- 按 column_key 认行而不是按 id 猜:这正是"每家公司一套树"之后唯一还站得住的对应关系。
|
||||
|
||||
UPDATE `user_column_permission` g
|
||||
JOIN `users` u ON u.id = g.user_id
|
||||
JOIN `columns` src ON src.id = g.column_id AND src.company_id = 1
|
||||
JOIN `columns` copy ON copy.company_id = u.company_id AND copy.column_key = src.column_key
|
||||
SET g.column_id = copy.id
|
||||
WHERE u.company_id <> 1;
|
||||
|
||||
-- ---------- 10. 四道自检闸门:不为 0 就抛 1048(列 must_be_zero NOT NULL) ----------
|
||||
|
||||
CREATE TEMPORARY TABLE IF NOT EXISTS `_v149_gate` (`must_be_zero` INT NOT NULL);
|
||||
|
||||
-- 闸门 1:每一家公司的树都必须和公司 1 一样齐(除角色内在闸门那一行)。
|
||||
-- 这一道专防复制段被 NOT EXISTS 守卫"一声不响少一整家树"——少树的后果不是报错,
|
||||
-- 是那家公司的账号有效菜单为空、侧边栏空白,而按 key 点查会判成"这个菜单不存在"。
|
||||
INSERT INTO `_v149_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM `company` co
|
||||
JOIN `columns` src ON src.company_id = 1 AND src.column_key <> 'admin_companies'
|
||||
LEFT JOIN `columns` cp ON cp.company_id = co.id AND cp.column_key = src.column_key
|
||||
WHERE co.id <> 1 AND cp.id IS NULL;
|
||||
|
||||
-- 闸门 2:父指向绝不跨公司(第 7 段没认上父、或源行本来就挂着别家父时会不为 0)。
|
||||
INSERT INTO `_v149_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT c.id
|
||||
FROM `columns` c
|
||||
JOIN `columns` p ON p.id = c.parent_id
|
||||
WHERE c.company_id <> p.company_id
|
||||
) bad;
|
||||
|
||||
-- 闸门 3:授权绝不指向别家的行(第 9 段漏一行,那家公司就 permanently 少一个菜单)。
|
||||
INSERT INTO `_v149_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT g.user_id
|
||||
FROM `user_column_permission` g
|
||||
JOIN `users` u ON u.id = g.user_id
|
||||
JOIN `columns` c ON c.id = g.column_id
|
||||
WHERE c.company_id <> u.company_id
|
||||
) bad;
|
||||
|
||||
-- 闸门 4:company_id 不为 NULL。第 3 段的 MODIFY 已经挡过一次,这一道是给
|
||||
-- "有人在 V149 之后手工插过不带公司的行"留的复验位——重跑整个文件时它才会响。
|
||||
INSERT INTO `_v149_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (SELECT id FROM `columns` WHERE `company_id` IS NULL OR `company_id` <= 0) bad;
|
||||
|
||||
DROP TEMPORARY TABLE `_v149_gate`;
|
||||
|
||||
-- ---------- 验证(上线后人工只读复跑,不进迁移) ----------
|
||||
-- ① 各家行数应相等且 = 公司 1 的 52 - 1 = 51:
|
||||
-- SELECT company_id, menu_type, COUNT(*) FROM columns GROUP BY company_id, menu_type;
|
||||
-- ② 跨公司授权残留 0:
|
||||
-- SELECT COUNT(*) FROM user_column_permission g JOIN users u ON u.id=g.user_id
|
||||
-- JOIN columns c ON c.id=g.column_id WHERE c.company_id <> u.company_id;
|
||||
-- ③ 两条旧键已摘、两条新键在:
|
||||
-- SELECT INDEX_NAME, GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX), NON_UNIQUE
|
||||
-- FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='columns'
|
||||
-- GROUP BY INDEX_NAME, NON_UNIQUE;
|
||||
@@ -0,0 +1,122 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V150__shop_key_company_scope
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 需求:2026-10-06「店铺密钥管理的数据按照公司区分」
|
||||
-- 口径参照:V147__product_category_company_scope.sql(同为"表里一个归属列都没有"的那一类)
|
||||
--
|
||||
-- 1. 变更目的:把「店铺密钥管理」biz_shop_key 从"全平台共享的一池紫鸟令牌"改成"每公司一池"。
|
||||
-- 现状是这张表零归属列(列全集见 V5 + V76 + V82 + V89 + V114,共 12 列,没有 company_id,
|
||||
-- 也没有任何账号/分组列),而 ShopKeyService.page() 的 LambdaQueryWrapper 除 orderByDesc(id)
|
||||
-- 之外没有任何 where ⇒ 拿到 admin_shop_keys 这个菜单的任意管理员,读的是同一份全表,
|
||||
-- 且 ShopKeyItemVo 把 ziniaoToken 原文整列返回、页面把它挂在 title 属性上(悬停即得全文)。
|
||||
-- 所以这一页今天漏的不是"多看几行",是**别家公司的紫鸟令牌原文**。
|
||||
--
|
||||
-- 2. 影响表与数据量:只动 biz_shop_key 一张表,只加一列。
|
||||
-- 【行数今天没有实查,这一条不许当成已知】本仓的口径是"上线前有人实跑一遍验证 SQL",
|
||||
-- 取证命令(主机A 业务库只读):
|
||||
-- SELECT COUNT(*) AS total,
|
||||
-- SUM(created_at >= '2026-10-04 14:55:00') AS after_company_2_opened
|
||||
-- FROM biz_shop_key;
|
||||
-- 为什么必须是 14:55 这个时刻:第二家公司(company.id=2)是 10-04 14:55 开通的(V145 头注释 2 段),
|
||||
-- 而这一页的写侧闸门是随本批 jar 才装上的 ⇒ **从 14:55 到本次发布之间,第 2 家管理员建的密钥
|
||||
-- 会落在 DEFAULT 1 上,归进厦门米椿花,事后无从反推**(这张表没有账号列,V145 给品牌库补
|
||||
-- uploader_user_id 的那个锚点在这里补不出来:历史行的"由谁产生"根本没记过)。
|
||||
-- 这一段的处置与 V145 一致:不猜、不编,把窗口压短(本批尽快上线),并让
|
||||
-- after_company_2_opened 在迁移前跑一次——它是非 0 时必须在发布说明里点名"这些行的归属不可追回"。
|
||||
--
|
||||
-- 3. 锁表风险:低。
|
||||
-- ADD COLUMN 走 ALGORITHM = INSTANT 且【不加 AFTER】:非末位列加列在 InnoDB 里要重建聚簇记录,
|
||||
-- 钉死 INSTANT 之后,万一某个前提不成立,MySQL 直接报 1846 而不是悄悄退化成 COPY——
|
||||
-- 宁可迁移失败走 repair 重跑,也不要一次没人预期的整表重建(首例 V145 第 3 段)。
|
||||
-- 全文【没有一条 UPDATE】:历史行的 1 由加列时记录的默认值给出,不需要回填,
|
||||
-- 所以也就没有 V145 那条"派生值哨兵"要防的写回缺口——但摘 DEFAULT 时仍要重跑验证 SQL 第 2 条,
|
||||
-- 理由见第 6 段。
|
||||
-- 不碰 users / company / biz_shop_manage / biz_task_file_job。
|
||||
--
|
||||
-- 4. 唯一键【刻意不动】:uk_ziniao_token_hash(V89:20)保持全平台唯一。
|
||||
-- 【为什么不学 V145/V147 把它按公司放宽】那两个键管的是"同一张表里两家公司都要有名字叫 X 的行"
|
||||
-- (同名类、同名 ASIN 规则),把它们按公司放宽是隔离的前提;而这里的键管的是**一把握在紫鸟那边的
|
||||
-- 令牌字符串**本身:同一个令牌在两家公司各存一行,物理上是同一个紫鸟账号被登记了两次,
|
||||
-- 白名单状态、代理地址、连续失败次数会各自漂移,而 ZiniaoApiKeyProvider.listApiKeyAccounts()
|
||||
-- 是按令牌聚合的(LinkedHashMap 以 token 为键),两行会并成一条 ApiKeyAccount、
|
||||
-- resolveProxyUrl 取"第一个非空代理"、resolveIpWhitelistFailCount 取 max ⇒ 一家改了代理,
|
||||
-- 另一家的出口跟着变。这不是"看不到",是"两行互相顶掉成一行",保持全局唯一才是对的。
|
||||
-- 【代价,写清】第 2 家管理员提交一把第 1 家已经登记过的令牌,会拿到"紫鸟令牌已存在,不能重复维护"。
|
||||
-- 这句报错确实说出了"别家有这一条",但能撞出这句话的前提是他已经握着这把握在紫鸟那边的令牌原文,
|
||||
-- 保密性在那一刻已经没有了 ⇒ 不构成跨租户泄露。
|
||||
--
|
||||
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V150-shop-key-company.sql(在 Flyway 扫描路径之外,
|
||||
-- 不写成 V151——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
|
||||
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=150 行 → 回滚 jar → 起应用。
|
||||
--
|
||||
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
|
||||
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 ShopKeyEntity 没有 companyId 字段,
|
||||
-- MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364(旧 jar 的 create 会当场 500,
|
||||
-- 不像 V145 那样被 catch 成 log.warn 静默丢——但"新增密钥这一页在混合窗口里坏掉"同样不可接受)。
|
||||
-- 摘除动作与前三张同形,是一条纯元数据操作:
|
||||
-- ALTER TABLE biz_shop_key ALTER COLUMN company_id DROP DEFAULT;
|
||||
-- 【禁写成 MODIFY COLUMN ... NOT NULL】——那会重建表,而重建时"历史上没有这一列的行"会按
|
||||
-- 【当时】的列默认值物化:默认刚被摘掉,历史归属就没了依据。本迁移没有写回历史行(第 3 段),
|
||||
-- 所以摘 DEFAULT 之前必须先重跑下面第 2 条验证 SQL 确认 company_id 全 = 1。
|
||||
-- 在摘掉之前,启动期 CompanyDefaultGuard 的 WATCHED_TABLES 与探针 SQL 的 IN 列表已把本表一并登记
|
||||
-- (公司数 > 1 且这一列还带 DEFAULT 就打 COMPANY_DEFAULT_STILL_PRESENT,巡检按这条 ASCII 签名 grep
|
||||
-- ⇒ "漏摘"由代码喊,不靠人记得)。
|
||||
-- 【下一笔的取号】本表这条与 docs/migration-inventory.md 里那条同形待办(`columns` 的 DROP DEFAULT,
|
||||
-- 原先挂在 V149 名下,现登记在「后续新增迁移从 V152 起取号」那一段)应合并成一版发出:
|
||||
-- 两条都是纯元数据、前提各自独立,任一前提没成立就单独顺延,不要把待办拆散成两个理由。
|
||||
-- 【不要再往里加 biz_product_category / biz_invalid_asin_data】那两张表的 DEFAULT 由"待摘"改成
|
||||
-- "必须保留"(10-06 复验后改成共享口径,V151 的 INSERT 列清单不含 company_id,靠 DEFAULT 满足 NOT NULL;
|
||||
-- 此时执行 DROP DEFAULT 会让每一次新建报 1364)。它们真正消失的时点是下一版直接 DROP COLUMN。
|
||||
--
|
||||
-- 【可重跑性】MySQL 的 DDL 不进事务。按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条
|
||||
-- 语句重跑整个文件,所以加列先查 information_schema 再 PREPARE。写法首例见 V143 全文件、V145 的加列段。
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 加列(末位 + INSTANT) ----------
|
||||
|
||||
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_key' AND COLUMN_NAME = 'company_id');
|
||||
SET @sql := IF(@col_exists = 0,
|
||||
'ALTER TABLE `biz_shop_key` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT ''归属公司(company.id):本表无账号列,历史行由本默认值给出,不可反推;V150'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 2. 本迁移刻意不做的事 ----------
|
||||
-- · 不加二级索引:biz_shop_key 是"一个紫鸟账号一行"量级的小表,读路径 WHERE company_id = ? 的
|
||||
-- 选择性再高也扫不出可感知的差别,而 uk_ziniao_token_hash 之外再挂一个单列索引就是 V139 那轮
|
||||
-- 清理掉的冗余索引形状。真有慢日志再单独立项(本库的瓶颈是锁不是索引)。
|
||||
-- · 不加 created_by_id:V145 给品牌库补 uploader_user_id 的理由是"归属只能靠账号反推",
|
||||
-- 而本表的归属从本版本起由 ShopKeyService.create 显式落 company_id,反推这条路用不上;
|
||||
-- 留一列没有消费者的审计位,只是给下一次"要不要用它"的争论留个口子。
|
||||
-- · 不动 uk_ziniao_token_hash(理由见头注释第 4 段)。
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行,不许只看启动日志的 Successfully applied)
|
||||
-- SHOW COLUMNS FROM `biz_shop_key` LIKE 'company_id';
|
||||
-- -> 期望 Null = NO,Default = 1(混合窗口要求带 DEFAULT;摘 DEFAULT 的那一版之后 Default 必须变 NULL)
|
||||
--
|
||||
-- SELECT COUNT(*) AS total, SUM(company_id IS NULL) AS null_company,
|
||||
-- SUM(company_id NOT IN (1)) AS not_company_1
|
||||
-- FROM `biz_shop_key`;
|
||||
-- -> 期望 null_company = 0;not_company_1 = 0 表示历史行确实全在第 1 家
|
||||
-- -> 【派生值哨兵】本迁移没有写回历史行,这里的 1 全部来自加列时记录的默认值。
|
||||
-- 摘 DEFAULT 的那笔迁移必须【重跑这一条】:一旦某次表重建按"摘掉之后的默认值"物化历史行,
|
||||
-- not_company_1 会立刻跳出来。
|
||||
-- -> 与迁移前那次取证对齐:total 必须等于迁移前的 total(INSTANT 加列不该改变行数)。
|
||||
--
|
||||
-- SELECT TABLE_NAME, INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
|
||||
-- FROM information_schema.STATISTICS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_shop_key' AND NON_UNIQUE = 0
|
||||
-- GROUP BY TABLE_NAME, INDEX_NAME;
|
||||
-- -> 期望恰好两行:PRIMARY(id) 与 uk_ziniao_token_hash(ziniao_token_hash);
|
||||
-- 这一条是"第 4 段确实没动唯一键"的证据,不是"应该没动"的信念
|
||||
--
|
||||
-- SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_shop_key'
|
||||
-- AND COLUMN_NAME = 'company_id' AND COLUMN_DEFAULT IS NOT NULL;
|
||||
-- -> 本版本发布后期望 1(DEFAULT 1 还在,由 CompanyDefaultGuard 喊);摘 DEFAULT 的那一版之后必须变 0
|
||||
-- =============================================================
|
||||
@@ -0,0 +1,181 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V151__rule_tables_shared_across_companies
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 需求:2026-10-06 控制方点名「品牌数据库做成所有公司共享的,不区分了」「商品类目也都是做成共享的,不区分」
|
||||
-- 前版:V145(品牌库+去重库按公司一套)、V147(商品类目按公司一棵树)——本文件只退这两张表的唯一键
|
||||
--
|
||||
-- 1. 变更目的:把「品牌数据库」biz_invalid_asin_data 与「商品类目」biz_product_category 的
|
||||
-- 唯一键从"公司+值"退回【全平台】键,与同一批 jar 里已经摘掉公司谓词的读写侧对齐。
|
||||
-- 不退这一刀的后果不是"看不到",是"写不进去":新代码的 INSERT 列清单已不含 company_id,
|
||||
-- 严格模式下这一列由 DEFAULT 1 兜住,所以旧键 (company_id, ...) 在功能上"暂时还能用"——
|
||||
-- 但它把第 2 家公司将来手工建的同名类目/手工加的同名品牌挡在同一行里,
|
||||
-- 而这一版之后系统里根本不存在"哪一家"这个概念,键里留着公司维度就是一把没有对照物的锁。
|
||||
--
|
||||
-- 2. 口径:两张表都退回 V145/V147 之前的形状,键名也复用当时的名字,让"回滚到 V94/V50 时代"
|
||||
-- 这件事在 SHOW INDEX 里一眼可辨:
|
||||
-- biz_invalid_asin_data uk_company_value_brand(company_id,data_value,brand(191))
|
||||
-- -> uk_data_value_brand(data_value,brand(191))
|
||||
-- biz_product_category uk_company_category_key(company_id,category_key)
|
||||
-- -> uk_product_category_key(category_key)
|
||||
-- 【biz_dedupe_total_data 不动】:「去重数据汇总」仍是每公司一套(控制方点名"本次只改品牌数据库"),
|
||||
-- 它的 uk_company_data_value 与哨兵登记都保持原样。
|
||||
--
|
||||
-- 3. 影响表与数据量(2026-10-06 主机A 业务库只读实查,不是估的):
|
||||
-- biz_invalid_asin_data = 15,056 行,SUM(company_id <> 1) = 0
|
||||
-- biz_product_category = 412 行(内置 18 = company_id 0、自定义 394 = company_id 1)
|
||||
-- 按 category_key 分组的重复组 = 0 组
|
||||
-- V147 上线(10-06 11:03)后的新写入 = 0 行
|
||||
-- 【两张表能退键的理由不一样,别混着抄】
|
||||
-- 品牌库:现行唯一键的第一列在库里恒为 1 ⇒ 目标键 (data_value, brand 前 191 字符)
|
||||
-- 与现行键判的是同一件事,所以只要这个前提还在,ADD UNIQUE 就不可能撞 1062。
|
||||
-- 文末「验证」段要证的前提只有一条:SUM(company_id <> 1) 仍然是 0(10-06 实查是 0)。
|
||||
-- 类目表:归属有两档(0 与 1),同一个 category_key 理论上可以一档一行,现行键拦不住,
|
||||
-- 所以"重复组 = 0"必须实测,「验证」段那条 GROUP BY 是承重的、不是走过场。
|
||||
-- ⇒ 这两条预检在发版前都要【重跑】:10-06 的数字是快照,不是恒真。
|
||||
-- company / users / columns 与其余业务表一律不动。
|
||||
--
|
||||
-- 4. 锁表风险:低,但两表的形态不同,分开说。
|
||||
-- biz_invalid_asin_data 15,056 行 / 约 4.5 MB:建 uk_data_value_brand 要扫描并排序全表,
|
||||
-- 钉 ALGORITHM = INPLACE, LOCK = NONE ⇒ 建索引期间并发 DML 可以进(同 V145 第 3 段的做法)。
|
||||
-- biz_product_category 412 行:任何形态都在毫秒级,仍然钉同一对子句,不给"顺手退化成交换锁"留机会。
|
||||
-- DROP INDEX 只吃一下元数据锁。
|
||||
-- 两条 ADD UNIQUE 都排在对应的 DROP 之前:中间任一步失败时【至少还有一个唯一键在守并发】,
|
||||
-- 而失败的表象是 Flyway 迁移报错、应用起不来,不是"键没了、重复行静默进库"。
|
||||
-- 索引字节预算(utf8mb4 + DYNAMIC,上限 3072):
|
||||
-- uk_data_value_brand = 128*4 + 191*4 = 1276
|
||||
-- uk_product_category_key = 128*4 = 512
|
||||
-- 【不用前缀索引迁就长度】(V135:6-9 的结论照搬):data_value 走全列、只有 brand 因为是 TEXT
|
||||
-- 才必须带 (191),这与 V94 原键完全同形,退回去不改变任何一列的判重宽度。
|
||||
-- 不碰 biz_task_file_job 等锁热点表。
|
||||
--
|
||||
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V151-rule-tables-shared.sql
|
||||
-- (在 Flyway 扫描路径之外,不写成 V152——版本化回滚等于让"决定回滚"这件事在没有人工执行
|
||||
-- 的情况下自己发生)。回滚方向是把两把公司键加回来:今天两张表的 company_id 只有一个值
|
||||
-- (品牌库全是 1、类目是 0/1 两档),所以回滚不会撞 1062;但 jar 必须先回到带公司谓词的那版,
|
||||
-- 否则"键按公司、代码不分公司"会让第 2 家建出与第 1 家同键的行。
|
||||
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=151 行 → 回滚 jar → 起应用。
|
||||
--
|
||||
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
|
||||
-- 【为什么本文件不 DROP COLUMN,尽管控制方要的是"删掉 company_id 列"】
|
||||
-- 线上那版 jar 的读写两侧都带着 company_id:InvalidAsinDataMapper 的 INSERT 列清单点名这一列,
|
||||
-- ProductCategoryEntity 带 companyId 字段(MyBatis-Plus 的 SELECT 列清单也含它)。
|
||||
-- 这两句合起来的后果是"删列与换键同批"必然在混合窗口里打断旧 jar——而且打断得很难看:
|
||||
-- 旧 jar 的 INSERT ... (company_id, ...) -> 1054 Unknown column,而
|
||||
-- CollectDataInvalidAsinBatchWriter 把批量写失败 catch 成 log.warn 后跳过整批,接口照样返回成功
|
||||
-- ⇒ 品牌黑名单静默少一批(这正是 V145 头注释为 DEFAULT 写下的那条禁令的反方向:
|
||||
-- 一次迁移只解决一个可回滚的理由,别把"能静默丢数"的那一刀和换键捆在一起)。
|
||||
-- 所以拆两步:本文件退键(旧 jar 配新库仍然全绿——键只是变严,数据本来就不冲突),
|
||||
-- 下一版(两台同版确认后)再出
|
||||
-- ALTER TABLE biz_invalid_asin_data DROP COLUMN company_id;
|
||||
-- ALTER TABLE biz_product_category DROP COLUMN company_id;
|
||||
-- 并同步把 CompanyDefaultGuard 的清单再清一遍。uploader_user_id 保留:它是"由谁产生"的审计锚点,
|
||||
-- 与归属公司无关,摘了就把 10-05 起 AUTO 行的来源信息一起删掉。
|
||||
-- 【DEFAULT 1 在本版之后从"待摘"变成"必须保留",这点必须写清,否则会有人照哨兵的提示去摘它】
|
||||
-- 新 jar 的 INSERT 不带 company_id,靠 DEFAULT 1 满足 NOT NULL;此时执行
|
||||
-- ALTER TABLE ... ALTER COLUMN company_id DROP DEFAULT 会让每一次写入报 1364(品牌库那条
|
||||
-- 同样被 writer 吞成 warn ⇒ 静默丢数)。因此本版把这两张表从 WATCHED_TABLES 与探针 SQL 的
|
||||
-- IN 列表里同时摘掉(清单与 SQL 由 CompanyDefaultGuardTest 双向钉同源),"摘 DEFAULT"这条
|
||||
-- 待办由"改天要执行"改成"等 DROP COLUMN 那一版一起消失"。
|
||||
-- biz_dedupe_total_data 与 biz_shop_key 不在此列:它们仍然按公司写,DEFAULT 仍是要摘的。
|
||||
--
|
||||
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在 DROP 段失败,前面的 ADD 已落库;
|
||||
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以四条 DDL
|
||||
-- 都先查 information_schema 再 PREPARE。写法首例见 V145 的加列/换键段、V147 全文件。
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 品牌数据库:先加全局键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_invalid_asin_data' AND INDEX_NAME = 'uk_data_value_brand');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `biz_invalid_asin_data` ADD UNIQUE KEY `uk_data_value_brand` (`data_value`, `brand`(191)), ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 2. 品牌数据库:再摘公司键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_invalid_asin_data' AND INDEX_NAME = 'uk_company_value_brand');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_invalid_asin_data` DROP INDEX `uk_company_value_brand`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 3. 商品类目:先加全局键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_product_category_key');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `biz_product_category` ADD UNIQUE KEY `uk_product_category_key` (`category_key`), ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 4. 商品类目:再摘公司键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_company_category_key');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_product_category` DROP INDEX `uk_company_category_key`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 5. 本迁移刻意不做的事 ----------
|
||||
-- · 不 DROP COLUMN、不 DROP DEFAULT:理由见第 6 段(旧 jar 会撞 1054/1364,且失败被 writer 吞成 warn)。
|
||||
-- · 不动 biz_dedupe_total_data:去重库仍每公司一套。
|
||||
-- · 不加二级索引:两张表读侧已不按公司筛,company_id 的选择性在本版之后没有消费者,索引只是维护成本。
|
||||
-- · 不回填 group_id:14,000+ 行 AUTO 的 group_id 为 NULL 是既成事实,非超管的可见集仍由
|
||||
-- record_source = 'MANUAL' AND group_id = 固定组 这条谓词决定(与 V145/V151 无关,本文件不碰读侧)。
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
|
||||
--
|
||||
-- SELECT TABLE_NAME, INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
|
||||
-- FROM information_schema.STATISTICS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE()
|
||||
-- AND TABLE_NAME IN ('biz_invalid_asin_data','biz_product_category','biz_dedupe_total_data')
|
||||
-- AND NON_UNIQUE = 0
|
||||
-- GROUP BY TABLE_NAME, INDEX_NAME;
|
||||
-- -> 期望恰好六行:PRIMARY(id) x3,加
|
||||
-- biz_invalid_asin_data.uk_data_value_brand(data_value@1,brand@2)
|
||||
-- biz_product_category.uk_product_category_key(category_key@1)
|
||||
-- biz_dedupe_total_data.uk_company_data_value(company_id@1,data_value@2) <- 这条【必须还在】
|
||||
-- -> uk_company_value_brand / uk_company_category_key 必须【不】在结果里;
|
||||
-- uk_company_data_value 若在结果里【消失】了,说明本文件误伤了去重库。
|
||||
--
|
||||
-- SELECT COUNT(*) AS dup_brand_rows FROM (
|
||||
-- SELECT data_value FROM biz_invalid_asin_data
|
||||
-- GROUP BY data_value, LEFT(brand, 191) HAVING COUNT(*) > 1 LIMIT 1
|
||||
-- ) t;
|
||||
-- SELECT COUNT(*) AS dup_category_keys FROM (
|
||||
-- SELECT category_key FROM biz_product_category GROUP BY category_key HAVING COUNT(*) > 1 LIMIT 1
|
||||
-- ) t;
|
||||
-- -> 两条都期望 0(本文件能建起严格键的前提)。发版前【重跑】这两条:10-06 的 0 组是快照。
|
||||
--
|
||||
-- SELECT COUNT(*) AS total FROM biz_invalid_asin_data;
|
||||
-- SELECT COUNT(*) AS total, SUM(is_builtin = 1) AS builtin FROM biz_product_category;
|
||||
-- -> 期望与迁移前一致(15,056 上下、412 / 18):本文件只换键,不增删行。
|
||||
--
|
||||
-- INSERT IGNORE 在退回全局键后(事务内跑完回滚,只插 ZZTEST 前缀):
|
||||
-- START TRANSACTION;
|
||||
-- INSERT INTO `biz_invalid_asin_data` (data_value, brand, record_source) VALUES ('ZZTESTKEY000001', 'zztestbrand', 'MANUAL');
|
||||
-- INSERT INTO `biz_invalid_asin_data` (data_value, brand, record_source) VALUES ('ZZTESTKEY000001', 'zztestbrand', 'MANUAL');
|
||||
-- SELECT COUNT(*) AS one_row FROM `biz_invalid_asin_data` WHERE data_value = 'ZZTESTKEY000001';
|
||||
-- ROLLBACK;
|
||||
-- -> 期望 one_row = 1:同名值第二次被 IGNORE 掉 = 键真的回到全平台一档。
|
||||
-- 第二次也进去(=2)说明新键没建成,第 1 段被跳过了。
|
||||
--
|
||||
-- SHOW COLUMNS FROM `biz_invalid_asin_data` LIKE 'company_id';
|
||||
-- SHOW COLUMNS FROM `biz_product_category` LIKE 'company_id';
|
||||
-- -> 期望两条都仍是 Null = NO、Default = 1。本版【故意留着】:新 jar 的 INSERT 靠它满足 NOT NULL。
|
||||
-- 它们变成"列不存在"的那一版才是 DROP DEFAULT 该一起消失的时候。
|
||||
-- =============================================================
|
||||
Reference in New Issue
Block a user