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:
+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)
|
||||
|
||||
Reference in New Issue
Block a user