feat(jd): 京东店铺分类按数据权限分组隔离(V203)

用户口径:不同组不能看到跨组的分类;当前组只管理员可以编辑分类,同组普通号可以进弹窗看但不能增删;
平台超管全量可见可编辑,公司超管管本公司全部组;归类也按组隔离且不再置人工编辑锁。

数据模型:biz_jd_product_group 加 owner_group_id(NOT NULL DEFAULT 0,
uk_company_owner_name(company_id, owner_group_id, name));新增 biz_jd_product_group_assign
(product_id, owner_group_id, category_id, uk_product_owner) 承接归类,同一商品各组可各自归类;
biz_jd_product.group_id 保留但零读零写。

权限:新增 JdCategoryScopeService(GET /api/admin/jd-product-groups/scope 回可见组 + 每组 editable)
四档矩阵;分类增删改与归类走 requireWritableGroup 403;商品行写(编辑/删除)仍只平台超管。

读面:列表/筛选/详情/归类一律按 owner_group_id,分类筛选 group_id 走归属表 EXISTS 下推
(不在 Java 侧 filter);用户端 /api/jd-collect/groups 按登录用户可见组收窄。

前端:工具栏「分组」下拉(多组才渲染,单组锁定显示);店铺分类弹窗对所有有该页菜单权限的人可见,
但按 editable 隐藏新建/改名/删除/勾选/归入移出;编辑抽屉「分类」下拉下线;只读提示改为
「只读:编辑/删除仅超级管理员可用;分类由本组管理员维护」。

验证:后端 mvn -o test 整量 5610 例 0 失败 19 skip;后管 npx vue-tsc 绿 / node --test 1919 绿 /
vitest 132 绿;用户端 vue-tsc 绿;python scripts/_push_gate.py --fast overall=pass。
迁移实跑与真机页面验收留发版窗口(本机无 MySQL/OSS);V203 需与另一路 V202 同窗口发布。
This commit is contained in:
2026-11-16 21:09:44 +08:00
parent e621deea58
commit 61ab844e5d
39 changed files with 2330 additions and 627 deletions
@@ -85,6 +85,24 @@ public final class DeviceSessionPolicy {
return isSuper(resolveRole(role, isAdmin, createdById));
}
/**
* 是否<b>公司超级管理员</b>(本公司最高账号,数据只看本公司)。
*
* <p>为什么收这一处:这条比较在 src/main 里已有 22 处手抄({@code AdminUserService} 14、
* {@code PermissionMenuService} 4、去重/分组/到期停任务/看板各 1)。京东数据库分类按
* 「公司 → 数据权限分组」两级隔离(V203)需要它,新写点再手抄一份就是第 23 处,故先在这里
* 收一个出口;<b>不改既有调用方</b>——要把那 22 处收进来,得连「业务数据面同权、管理动作收窄」
* 那条定案一起落(见本类 {@link #COMPANY_SUPER_ADMIN} 注释)。</p>
*/
public static boolean isCompanySuperAdmin(String resolvedRole) {
return COMPANY_SUPER_ADMIN.equals(resolvedRole);
}
/** {@link #isCompanySuperAdmin(String)} 的原始字段版本(自行 resolve 角色)。 */
public static boolean isCompanySuperAdmin(String role, Integer isAdmin, Long createdById) {
return isCompanySuperAdmin(resolveRole(role, isAdmin, createdById));
}
/** 从 JWT claims 中提取签名的设备号;缺失返回空串。 */
public static String claimDeviceId(Claims claims) {
Object raw = claims == null ? null : claims.get("deviceId");
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest;
@@ -13,7 +14,9 @@ import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDeleteVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
@@ -93,6 +96,8 @@ public class AdminJdProductController {
private final JdProductQueryService jdProductQueryService;
private final JdProductDeleteService jdProductDeleteService;
private final JdProductUpdateService jdProductUpdateService;
private final JdProductGroupService jdProductGroupService;
private final JdCategoryScopeService jdCategoryScopeService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@@ -109,17 +114,24 @@ public class AdminJdProductController {
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
@Parameter(description = "类目(京麦末级类目名,eq)") @RequestParam(name = "category", required = false) String category,
@Parameter(description = "自定义分类 id(类目面板「自定义分类」选中驱动)") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "当前数据权限分组 id(分类列/分类筛选按它取;缺省=作用域默认分组)")
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
@Parameter(description = "同步开始时间(包含,ISO datetime)")
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
@Parameter(description = "同步结束时间(包含,ISO datetime)")
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
HttpServletRequest request) {
requireJdAccess(request);
RequestOperator operator = requireJdAccess(request);
if (request.getParameter("grouped") != null || request.getParameter("ungrouped") != null) {
throw new BusinessException("页面版本已更新,请刷新页面后重新查询");
}
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long scopedOwnerGroupId = jdCategoryScopeService.readGroupOrNull(scope, ownerGroupId);
if (groupId != null && groupId > 0) {
requireVisibleCategory(scope, groupId);
}
return ApiResponse.success(jdProductQueryService.page(page, pageSize,
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo));
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, scopedOwnerGroupId));
}
@GetMapping("/categories")
@@ -137,15 +149,20 @@ public class AdminJdProductController {
+ "公共库无公司维度:按 id 直取,越界 id 按不存在拒绝。")
public ApiResponse<JdProductDetailVo> detail(
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
@Parameter(description = "当前数据权限分组 id(分类字段按它取)")
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
HttpServletRequest request) {
requireJdAccess(request);
return ApiResponse.success(jdProductQueryService.detail(id));
RequestOperator operator = requireJdAccess(request);
Long scopedOwnerGroupId = jdCategoryScopeService.readGroupOrNull(
jdCategoryScopeService.resolve(operator.user()), ownerGroupId);
return ApiResponse.success(jdProductQueryService.detail(id, scopedOwnerGroupId));
}
@PutMapping("/{id}")
@Operation(summary = "编辑京东商品", description = "主字段全量提交(标题/品牌/类目/货号/价格区间/总库存/"
+ "状态/分组),可选块缺省不动:attrGroups 重建 attr_json 的 tabs 段(其余顶层键保留)、"
+ "skus 按 skuId 改价格库存、deleteImageIds 删图(共用对象保留)。保存即置人工编辑锁"
@Operation(summary = "编辑京东商品", description = "主字段全量提交(标题/品牌/类目/货号/价格区间/总库存/状态),"
+ "可选块缺省不动:attrGroups 重建 attr_json 的 tabs 段(其余顶层键保留)、"
+ "skus 按 skuId 改价格库存、deleteImageIds 删图(共用对象保留)。分类不在编辑面"
+ "(按数据权限分组隔离,走「店铺分类」弹窗归类)。保存即置人工编辑锁"
+ "(manual_locked=1):采集回传对该行不再覆盖/清理。返回刷新后的详情。")
public ApiResponse<JdProductDetailVo> update(
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
@@ -156,7 +173,7 @@ public class AdminJdProductController {
log.info("[jd-product] 编辑商品 operatorId={} id={} title={}",
operator.id(), updatedId, body.getTitle());
// 返回刷新后的详情(前端保存后直接回填抽屉),复用详情同一查询出口。
return ApiResponse.success(jdProductQueryService.detail(updatedId));
return ApiResponse.success(jdProductQueryService.detail(updatedId, null));
}
@PostMapping(value = "/{id}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@@ -180,7 +197,7 @@ public class AdminJdProductController {
log.info("[jd-product] 上传图片 operatorId={} id={} replaceImageId={} imageType={}",
operator.id(), updatedId, replaceImageId, imageType);
// 返回刷新后的详情(前端上传后直接回填抽屉图片区),复用详情同一查询出口。
return ApiResponse.success(jdProductQueryService.detail(updatedId));
return ApiResponse.success(jdProductQueryService.detail(updatedId, null));
}
@DeleteMapping("/{id}")
@@ -199,19 +216,23 @@ public class AdminJdProductController {
}
@PostMapping("/batch-assign-group")
@Operation(summary = "批量归类京东商品(店铺分类弹窗)", description = "勾选商品行 → 归入指定分类"
+ "(groupId 必须真实存在)或移出分类(groupId=null,group_id 置 NULL)。与单行编辑"
+ "同口径:归类即人工干预,落 manual_locked=1(采集 upsert/登记/覆盖清理此后跳过本行,"
+ "分类不被重爬清理冲掉,代价是该行价格/库存随锁停更)。单次最多 200 个;id 不存在的"
+ "行不计入更新数、不整批拒绝(弹窗行集与库行有采集刷新时间差,掉队行跳过)。")
@Operation(summary = "批量归类京东商品(店铺分类弹窗)", description = "勾选商品行 → 归入当前数据权限分组的"
+ "某个分类(groupId 必须真实存在且属于该分组)或移出分类(groupId=null,删本组归属行)。"
+ "归类写 biz_jd_product_group_assign 的 (product_id, owner_group_id) 一行——同一商品各组"
+ "可各自归类;<b>不再置人工编辑锁</b>(分类不在商品行上,采集刷新冲不掉它,锁只会让"
+ "共享行的价格/库存对所有组停更)。写权限=本组管理员/公司超管/平台超管。"
+ "单次最多 200 个;id 不存在的行不计入、不整批拒绝(弹窗行集与库行有采集刷新时间差)。")
public ApiResponse<Integer> batchAssignGroup(
@Valid @RequestBody JdProductBatchAssignGroupRequest body,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
int updated = jdProductUpdateService.assignGroup(body.getIds(), body.getGroupId());
// 管理端写动作必须留痕:谁、把多少行归到哪个分类(null=移出分类)。
log.info("[jd-product] 批量归类 operatorId={} requested={} updated={} groupId={}",
operator.id(), body.getIds().size(), updated, body.getGroupId());
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
ShopManageGroupEntity target = jdCategoryScopeService.requireWritableGroup(scope, body.getOwnerGroupId());
int updated = jdProductUpdateService.assignGroup(target.getId(), target.getCompanyId(),
body.getIds(), body.getGroupId(), operator.id());
// 管理端写动作必须留痕:谁、把多少行归到哪个组的哪个分类(null=移出分类)。
log.info("[jd-product] 批量归类 operatorId={} ownerGroupId={} requested={} updated={} groupId={}",
operator.id(), target.getId(), body.getIds().size(), updated, body.getGroupId());
return ApiResponse.success(updated);
}
@@ -263,6 +284,17 @@ public class AdminJdProductController {
return operator;
}
/**
* 分类筛选面的越权闸:请求里的 {@code group_id} 必须是本账号可见组下的分类,
* 否则 403(分类按数据权限分组隔离,V203;不认识的 id 直接拒,不做"空结果"降级)。
*/
private void requireVisibleCategory(JdCategoryScopeService.JdCategoryScope scope, Long categoryId) {
Long ownerGroupId = jdProductGroupService.requireCategory(categoryId).getOwnerGroupId();
if (!scope.canRead(ownerGroupId)) {
throw new BusinessException(403, "无权查看该分组的分类");
}
}
private AdminUserEntity resolveOperator(HttpServletRequest request) {
try {
return adminAuthSupport.requireUser(request);
@@ -3,10 +3,13 @@ package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.swagger.v3.oas.annotations.Operation;
@@ -23,84 +26,122 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后管「京东数据库」分组管理(v1.4 Phase 5,R4):新建 / 改名 / 删除 / 下拉列表。
* 后管「京东数据库」分类管理(v1.4 Phase 5,R4;V203 改按数据权限分组归属)。
*
* <p>京东数据库专属分组(不是店铺管理的分组集):<b>2026-11-15 用户定案公共化</b>——
* 与品牌数据库(亚马逊)的分组同形状,全平台一份、不分公司(唯一键 {@code uk_group_name},
* V200 退键);删除分组不删商品——商品行 {@code group_id} 置 NULL(AC-8,事务两步落
* {@code JdProductGroupService})。实体上遗留的 company_id 列只是历史归属标记,读写两侧
* 都不再引用,新行按 DEFAULT 0 落「平台公共」。</p>
* <p>归属口径(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类,
* 同组普通号只读」):一行分类属于<b>一个数据权限分组</b>({@code biz_shop_manage_group}),
* 公司→组两级隔离。作用域由 {@link JdCategoryScopeService} 解析,本控制器只做两件事:
* ①把请求里的 {@code owner_group_id} 收敛成「当前分组」;②写端点校验该组可写。</p>
*
* <p>鉴权与 {@code AdminJdProductController} 同款私有闸(同一 column_key/route_path):
* 列表按菜单权限放行;<b>写(新建/改名/删除)2026-11-16 起收窄到平台超管</b>(用户口径
* 「京东数据库只有超管有编辑删除权限」——分类是全平台一份的公共数据,普通授权用户只看不写),
* 默认仅 super_admin。</p>
* <ul>
* <li>读(列表 / 作用域):拿到本页菜单权限即可,只能看自己可见组(本组普通号也能看);</li>
* <li>写(新建/改名/删除):本组管理员、公司超管(本公司全部组)、平台超管(全部组);
* 普通号 403。</li>
* </ul>
*
* <p>删除分类不删商品:只删该分类的归类归属行({@code biz_jd_product_group_assign}),
* 商品行留在公共库里(见 {@link JdProductGroupService#delete})。</p>
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/admin/jd-product-groups")
@Tag(name = "京东数据库分组", description = "京东商品自定义分组管理:全平台一份(公共库),列表/新建/改名/删除,删除不删商品(脱组)。")
@Tag(name = "京东数据库分类", description = "京东商品自定义分类:按数据权限分组隔离,组内管理员可新建/改名/删除,删除不删商品(只解挂归属)。")
public class AdminJdProductGroupController {
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
private final JdProductGroupService jdProductGroupService;
private final JdCategoryScopeService jdCategoryScopeService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@GetMapping
@Operation(summary = "分组列表(含组内商品数)", description = "全平台全部分组,按 sort_order, id 升序;"
+ "productCount 为读侧现算列(分组下拉展示用)。")
public ApiResponse<List<JdProductGroupVo>> list(HttpServletRequest request) {
requireJdAccess(request);
return ApiResponse.success(jdProductGroupService.list());
@Operation(summary = "分类列表(含分类下商品数)", description = "按「当前分组」返回分类,"
+ "按 sort_order, id 升序;owner_group_id 缺省=作用域默认分组(可见组第一项)。"
+ "一个可见组都没有时返回空列表(普通号也能读)。")
public ApiResponse<List<JdProductGroupVo>> list(
@Parameter(description = "数据权限分组 id(缺省=默认分组)")
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
return ApiResponse.success(jdProductGroupService.list(
jdCategoryScopeService.readGroupOrNull(scope, ownerGroupId)));
}
@GetMapping("/scope")
@Operation(summary = "分类作用域(分组下拉 + 可写标记)", description = "本账号可见的数据权限分组清单"
+ "(平台超管=全部公司全部组、公司超管=本公司、管理员/普通号=自己带的组+自己所属组的组长)"
+ "与每组是否可写;前端用它渲染「分组」下拉并按 editable 隐藏分类写入口。")
public ApiResponse<JdCategoryScopeVo> scope(HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
return ApiResponse.success(jdCategoryScopeService.scopeVo(operator.user()));
}
@PostMapping
@Operation(summary = "新建分组", description = "重名按业务错误拒绝(409),不落库;公共库无公司归属。")
@Operation(summary = "新建分类", description = "归属当前分组(ownerGroupId 缺省=自己带的那个组);"
+ "同一分组内重名按 409 业务错误拒绝,不落库。")
public ApiResponse<Long> create(
@Valid @RequestBody JdProductGroupSaveRequest body,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
Long id = jdProductGroupService.create(body.getName(), body.getSortOrder());
log.info("[jd-product-group] 新建分组 operatorId={} groupId={}", operator.id(), id);
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
ShopManageGroupEntity target = jdCategoryScopeService.requireWritableGroup(scope, body.getOwnerGroupId());
Long id = jdProductGroupService.create(target.getId(), target.getCompanyId(),
body.getName(), body.getSortOrder());
log.info("[jd-product-group] 新建分类 operatorId={} ownerGroupId={} categoryId={}",
operator.id(), target.getId(), id);
return ApiResponse.success(id);
}
@PutMapping("/{id}")
@Operation(summary = "分组改名/改排序", description = "越界 id(不存在)按不存在拒绝;"
+ "改成已有名字按业务错误拒绝(409)。")
@Operation(summary = "分类改名/改排序", description = "越界 id(不存在)按不存在拒绝;"
+ "改成本组已有名字按业务错误拒绝(409);非本组管理员 403。")
public ApiResponse<Boolean> rename(
@Parameter(description = "分组 id") @PathVariable("id") Long id,
@Parameter(description = "分类 id") @PathVariable("id") Long id,
@Valid @RequestBody JdProductGroupSaveRequest body,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
requireWritableCategory(scope, ownerGroupId);
jdProductGroupService.rename(id, body.getName(), body.getSortOrder());
log.info("[jd-product-group] 分组改名 operatorId={} groupId={}", operator.id(), id);
log.info("[jd-product-group] 分类改名 operatorId={} ownerGroupId={} categoryId={}",
operator.id(), ownerGroupId, id);
return ApiResponse.success(Boolean.TRUE);
}
@DeleteMapping("/{id}")
@Operation(summary = "删除分组", description = "删除分组不删商品(AC-8):先同事务把该组商品 "
+ "group_id 置 NULL 再删分组行;返回实际脱组的商品行数。越界 id 按不存在拒绝。")
@Operation(summary = "删除分类", description = "只删该分类的归类归属行(商品保留在公共库,"
+ "回到该组的未分类);返回实际解挂的归属行数。非本组管理员 403。")
public ApiResponse<Integer> delete(
@Parameter(description = "分组 id") @PathVariable("id") Long id,
@Parameter(description = "分类 id") @PathVariable("id") Long id,
HttpServletRequest request) {
RequestOperator operator = requirePlatformSuperAdminWrite(request);
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
requireWritableCategory(scope, ownerGroupId);
int detached = jdProductGroupService.delete(id);
// 管理端破坏性动作必须留痕:谁、删了哪个分组、脱组了多少商品。
log.info("[jd-product-group] 删除分组 operatorId={} groupId={} detached={}",
operator.id(), id, detached);
// 管理端破坏性动作必须留痕:谁、删了哪个分类、解挂了多少商品归属。
log.info("[jd-product-group] 删除分类 operatorId={} ownerGroupId={} categoryId={} detached={}",
operator.id(), ownerGroupId, id, detached);
return ApiResponse.success(detached);
}
private void requireWritableCategory(JdCategoryScopeService.JdCategoryScope scope, Long ownerGroupId) {
if (!scope.canWrite(ownerGroupId)) {
throw new BusinessException(403, "仅该分组的管理员可以修改它的分类");
}
}
private RequestOperator requireJdAccess(HttpServletRequest request) {
AdminUserEntity operator = resolveOperator(request);
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
@@ -113,21 +154,6 @@ public class AdminJdProductGroupController {
return new RequestOperator(operator.getId(), superAdmin, operator);
}
/**
* 写端点(新建/改名/删除)的越权闸:在菜单权限之上再要求平台超管,判据与
* {@code AdminJdProductController#requirePlatformSuperAdminWrite} 逐字同源
* (读列表仍按菜单权限放行)。
*/
private RequestOperator requirePlatformSuperAdminWrite(HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
if (!operator.superAdmin()) {
log.warn("[jd-product-group] 非平台超管写操作被拒 operatorId={} role={}",
operator.id(), adminAuthSupport.currentRole(operator.user()));
throw new BusinessException(403, "仅平台超级管理员可以修改京东数据库分类");
}
return operator;
}
private AdminUserEntity resolveOperator(HttpServletRequest request) {
try {
return adminAuthSupport.requireUser(request);
@@ -14,6 +14,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskVo;
import com.nanri.aiimage.modules.jd.model.vo.JdIngestChunkVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdCollectBoardService;
import com.nanri.aiimage.modules.jd.service.JdCollectTaskService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
@@ -63,6 +64,7 @@ public class JdCollectController {
private final JdResultIngestService ingestService;
private final JdProductQueryService jdProductQueryService;
private final JdProductGroupService jdProductGroupService;
private final JdCategoryScopeService jdCategoryScopeService;
private final TaskHeartbeatService taskHeartbeatService;
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
private final TaskProgressOwnershipSupport progressOwnershipSupport;
@@ -82,13 +84,14 @@ public class JdCollectController {
@GetMapping("/groups")
@Operation(summary = "店铺分类列表(用户侧只读)", description = "2026-11-16 客户口径「管理员弄了多少"
+ "店铺分类 普通账户都能看到」:「获取店铺数据」页把管理员在后管京东数据库建的分类展示出来"
+ "(含组内商品数),普通账号登录即可见。与后管分组管理同一条读出口(JdProductGroupService.list,"
+ "分组 2026-11-15 起全平台一份、无公司维度);只读不写——分类的增删改仍只在后管。"
+ "「商品上架」未落地(jd-publish 占位),上架界面落地时消费同一端点。")
+ "(含分类下商品数)。<b>V203 起按数据权限分组隔离</b>:只返回当前登录用户可见组"
+ "(自己所属组的组长带的组)的分类,别组的一律不下发——这正是「不同组不能看到跨组的分类」。"
+ "只读不写——分类的增删改仍只在后管(本组管理员)。")
public ApiResponse<List<JdProductGroupVo>> groups(HttpServletRequest httpRequest) {
// 登录用户即可读(公共库口径):解析不出会话身份就 401(fail-closed,与 categories 同口径)。
adminAuthSupport.requireOwnershipUserId(httpRequest, null);
return ApiResponse.success(jdProductGroupService.list());
// 登录用户即可读:解析不出会话身份就 401(fail-closed,与建单同口径)。
Long userId = adminAuthSupport.requireOwnershipUserId(httpRequest, null);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolveByUserId(userId);
return ApiResponse.success(jdProductGroupService.listForGroups(scope.visibleGroupIds()));
}
@GetMapping("/dashboard")
@@ -0,0 +1,16 @@
package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 京东商品按组归类归属({@code biz_jd_product_group_assign},V203)数据访问口。
*
* <p>全部走 BaseMapper + wrapper(铁律 1 允许的两种形态之一,与 {@code JdProductGroupMapper}
* 同形状,无 XML):读=按 {@code owner_group_id} 批量取一组的归属、按 {@code category_id} 计数;
* 写=存在则改挂、不存在则插入(唯一键 {@code uk_product_owner}),移出分类走 delete。</p>
*/
@Mapper
public interface JdProductGroupAssignMapper extends BaseMapper<JdProductGroupAssignEntity> {
}
@@ -8,9 +8,11 @@ import lombok.Data;
import java.util.List;
/**
* 后管京东商品批量归类请求体(店铺分类弹窗,2026-11-15):勾选商品行 → 归入左侧选中分类
* 或移出分类。公共库写侧无公司维度(2026-11-15 用户定案),body 不带 company_id——
* 公司维度的假 tab 形状随 2026-11-15 公共化已从写侧端点整批摘除。
* 后管京东商品批量归类请求体(店铺分类弹窗,2026-11-15;V203 改按组隔离)。
*
* <p>归类归属 = {@code ownerGroupId}(当前「分组」下拉选中的<b>数据权限分组</b>):
* 同一商品各组可各自归类,写进 {@code biz_jd_product_group_assign} 的
* {@code (product_id, owner_group_id)} 一行。服务端校验该组可写、分类属于该组。</p>
*/
@Data
@Schema(description = "京东商品批量归类请求(归入分类或移出分类)")
@@ -21,6 +23,9 @@ public class JdProductBatchAssignGroupRequest {
@Size(max = 200, message = "单次最多归类 200 个商品,请分批操作")
private List<Long> ids;
@Schema(description = "目标分类 id;null=移出分类(group_id 置 NULL,商品回到未分类)")
@Schema(description = "目标分类 id;null=移出分类(本组归属行删除,商品在本组回到未分类)")
private Long groupId;
@Schema(description = "当前数据权限分组 id(缺省=操作者自己带的组)")
private Long ownerGroupId;
}
@@ -4,16 +4,22 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 京东商品分组新建/改名请求体(v1.4 Phase 5)。归属公司不走 body:由控制器经
* {@code DataReadScope#readCompanyIdOrOwn} 的公司隔离正门算出,客户端伪造无效。
* 京东商品分类新建/改名请求体(v1.4 Phase 5;V203 加归属分组)。
*
* <p>新建时 {@code ownerGroupId} 是<b>目标数据权限分组</b>(缺省=操作者自己带的那个组;
* 能看多组的人由前端「分组」下拉传);服务端按作用域校验可写,客户端伪造无效。
* 改名/删除不带它——归属以库里那一行为准。</p>
*/
@Data
@Schema(description = "京东商品分组保存请求")
@Schema(description = "京东商品分类保存请求")
public class JdProductGroupSaveRequest {
@Schema(description = "分组名(同公司内唯一)")
@Schema(description = "分类名(同一分组内唯一)")
private String name;
@Schema(description = "下拉展示顺序(新建缺省 0;改名不传保持原值)")
private Integer sortOrder;
@Schema(description = "新建时的目标数据权限分组 id(缺省=操作者自己带的组)")
private Long ownerGroupId;
}
@@ -56,8 +56,9 @@ public class JdProductUpdateRequest {
@Size(max = 32, message = "商品状态最长 32 字")
private String saleStatus;
@Schema(description = "分组 id(null=未分组;组 id 必须属于本公司)")
private Long groupId;
// 分类(groupId)【V203 起不在编辑面】:分类按数据权限分组隔离、归属存
// biz_jd_product_group_assign,编辑抽屉不再写商品行的 group_id(走「店铺分类」弹窗归类)。
// 旧前端仍带 groupId 时由 Jackson 忽略(未知字段不报错),不会静默写错列。
@Schema(description = "属性分组(可选块;缺省不动属性;提交时重建 attr_json 的 tabs 段,其余顶层键保留)")
private List<AttrGroupDto> attrGroups;
@@ -0,0 +1,40 @@
package com.nanri.aiimage.modules.jd.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 京东商品按组归类归属({@code biz_jd_product_group_assign},V203)。
*
* <p>为什么单独一张表:京东数据库的商品行是全平台公共的(2026-11-15 定案),而分类从
* 2026-11-16 起按数据权限分组隔离(「同一商品各组可各自归类」)。商品行上的单值
* {@code group_id} 放不下"每组一份归属",故按 {@code (product_id, owner_group_id)} 建唯一键——
* 一个商品在同一组里最多挂一个分类,不同组互不干扰。</p>
*
* <p>本表不参与采集回传的覆盖保护:归类不再置 {@code manual_locked}(分类不再写进商品行,
* 采集刷新也冲不掉它),共享商品的价格/库存照旧随采集更新。</p>
*/
@Data
@TableName("biz_jd_product_group_assign")
public class JdProductGroupAssignEntity {
@TableId(type = IdType.AUTO)
private Long id;
/** 商品行 id(biz_jd_product.id)。 */
private Long productId;
/** 归属数据权限分组 id(biz_shop_manage_group.id)。 */
private Long ownerGroupId;
/** 分类 id(biz_jd_product_group.id)。 */
private Long categoryId;
/** 归属公司(分组所属公司,读侧快速过滤)。 */
private Long companyId;
/** 操作者 user id(管理端破坏性动作留痕用,可为空)。 */
private Long createdBy;
private LocalDateTime createdAt;
/** 改挂分类/刷新时刻(列 ON UPDATE CURRENT_TIMESTAMP)。 */
private LocalDateTime updatedAt;
}
@@ -8,12 +8,13 @@ import lombok.Data;
import java.time.LocalDateTime;
/**
* 京东商品自定义分组({@code biz_jd_product_group},V195,v1.4)。
* 京东商品自定义分类({@code biz_jd_product_group},V195,v1.4;V203 改按数据权限分组归属)。
*
* <p>京东数据库专属分组(R4):<b>2026-11-15 起全平台一份</b>(唯一键 {@code uk_group_name},
* V200 退掉按公司的 {@code uk_company_group_name});可新建/改名/删除;删除分组不删商品——
* 商品行 {@code group_id} 置 NULL(AC-8)。简单单表 CRUD 走 BaseMapper + wrapper
* (SqlLayering 惯例),无 XML。</p>
* <p>归属口径(2026-11-16 用户口径「不同组不能看到跨组的分类」):一行属于<b>一个数据权限分组</b>
* ({@code owner_group_id} → {@code biz_shop_manage_group.id}),唯一键
* {@code uk_company_owner_name(company_id, owner_group_id, name)}(同组内重名拒绝,不同组可同名)。
* 删除分类不删商品——只删该组的归类归属行({@code biz_jd_product_group_assign})。
* 简单单表 CRUD 走 BaseMapper + wrapper(SqlLayering 惯例),无 XML。</p>
*/
@Data
@TableName("biz_jd_product_group")
@@ -21,9 +22,14 @@ public class JdProductGroupEntity {
@TableId(type = IdType.AUTO)
private Long id;
/** 历史归属公司(V195~V199 按公司隔离时代遗留,公共化后读写两侧不再引用;新行 DEFAULT 0=平台公共)。 */
/** 归属公司(=所属数据权限分组的公司;V200 时代的历史行为 0,读侧不可见)。 */
private Long companyId;
/** 分组名(全平台唯一)。 */
/**
* 归属数据权限分组 id(V203):分类只对本组管理员可写、本组成员可读;
* 0 = 2026-11-15 公共化时代的历史行,任何读取面都不会返回它。
*/
private Long ownerGroupId;
/** 分类名(同一公司同一分组内唯一)。 */
private String name;
/** 下拉展示顺序。 */
private Integer sortOrder;
@@ -0,0 +1,31 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 「分组」下拉的一项=一个数据权限分组({@code biz_shop_manage_group})。
*
* <p>{@code editable} 是本账号对该组分类的写权限(能建/改名/删除分类、能把商品归入该组分类);
* 组内普通号拿到的是 {@code false}(弹窗可看不可改)。</p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "京东数据库分类的可选分组")
public class JdCategoryGroupOptionVo {
@Schema(description = "数据权限分组 id")
private Long id;
@Schema(description = "分组名")
private String name;
@Schema(description = "展示名(跨公司时带公司名,前端不解析公司字段)")
private String label;
@Schema(description = "本账号对该组分类可写(建/改名/删除/归类)")
private boolean editable;
}
@@ -0,0 +1,28 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 京东数据库分类的「当前分组」作用域(GET /api/admin/jd-product-groups/scope)。
*
* <p>给后管页面两个东西:①「分组」下拉的选项(能看多个组的人才需要切);②本账号对每个组
* 能不能建/改/删分类({@code editable})。分类与归类都只按这个作用域读写(V203)。</p>
*
* <p><b>不下发公司字段</b>:`admin-frontend-vue` 的 `company-tab-wiring` 反向扫描禁止
* `jd-product-api.ts` / `JdDatabasePage.vue` 出现 `company_id|companyId` 记号,
* 跨公司场景的组名由后端拼进 {@code label}(如「某某公司 / 一组」)。</p>
*/
@Data
@Schema(description = "京东数据库分类作用域(分组下拉 + 可写标记)")
public class JdCategoryScopeVo {
@Schema(description = "是否平台超管(全部公司全部组可读可写)")
private boolean platformSuperAdmin;
@Schema(description = "默认分组 id(可见组的第一项;无可见组时为空)")
private Long defaultGroupId;
@Schema(description = "当前账号可见的分组(按组名排序)")
private java.util.List<JdCategoryGroupOptionVo> groups;
}
@@ -98,9 +98,12 @@ public class JdProductDetailVo {
@Schema(description = "已转存图片数")
private Integer imageCount;
@Schema(description = "自定义分组 id(未挂组为空)")
@Schema(description = "自定义分类 id(当前分组下未归类为空)")
private Long groupId;
@Schema(description = "自定义分类名(当前分组那一行归属;未归类或读不到为空)")
private String groupName;
@Schema(description = "本次采集批次号")
private String collectBatchId;
@@ -6,25 +6,29 @@ import lombok.Data;
import java.time.LocalDateTime;
/**
* 京东商品自定义分组(分组下拉/管理面,v1.4 Phase 5)。
* 京东商品自定义分类(分类下拉/管理面,v1.4 Phase 5;V203 按数据权限分组归属)。
*
* <p>{@code productCount} 是读侧现算列({@code JdProductMapper} BaseMapper selectCount
* wrapper 按 {@code group_id} 统计,分组下拉展示用)。</p>
* <p>{@code productCount} 是读侧现算列(按归属表 {@code biz_jd_product_group_assign} 的
* {@code category_id} 计数)——商品是全平台公共的,同一商品在别的组里可能另挂一个分类,
* 这里只数本分类。{@code ownerGroupId} 是归属的数据权限分组 id(同组内重名唯一)。</p>
*/
@Data
@Schema(description = "京东商品自定义分组")
@Schema(description = "京东商品自定义分类")
public class JdProductGroupVo {
@Schema(description = "分组 id")
@Schema(description = "分类 id")
private Long id;
@Schema(description = "分组名(同公司内唯一)")
@Schema(description = "分类名(同一分组内唯一)")
private String name;
@Schema(description = "归属数据权限分组 id")
private Long ownerGroupId;
@Schema(description = "下拉展示顺序")
private Integer sortOrder;
@Schema(description = "组内商品数(读侧现算)")
@Schema(description = "本分类下的商品数(读侧现算)")
private Long productCount;
@Schema(description = "创建时刻")
@@ -0,0 +1,271 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 京东数据库分类的「当前分组」作用域解析(V203,2026-11-16 用户口径)。
*
* <p>口径:「组」=公司内的<b>数据权限分组</b>({@code biz_shop_manage_group}),公司→组两级隔离。
* 四档:</p>
* <ul>
* <li><b>平台超管</b>:全部公司全部组可读可写;</li>
* <li><b>公司超管</b>:本公司全部组可读可写(与「公司超管看本公司全部成员」同源);</li>
* <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长;可写=自己带的组;</li>
* <li><b>普通号</b>:可见同上,可写空(能开弹窗看,不能增删改分类、不能归类)。</li>
* </ul>
*
* <p>平台超管判定走 {@link DataReadScope#isPlatformSuperAdmin}({@code isSuper} 的唯一包装),
* 不新增 {@code DeviceSessionPolicy.isSuper(...)} 调用点——那条字面量调用点由
* {@code SuperAdminPredicateSingleOutletTest} 钉死在 22 处。公司超管判定用
* {@link DeviceSessionPolicy#isCompanySuperAdmin(String)}(本笔新收的出口)。</p>
*
* <p>解析结果不带任何公司字段给前端:跨公司的组名由 {@link #scopeVo} 拼进 {@code label},
* 因为 `admin-frontend-vue` 禁止 JD 两个文件出现 `company_id|companyId` 记号。</p>
*/
@Service
@RequiredArgsConstructor
public class JdCategoryScopeService {
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
private final AdminUserMapper adminUserMapper;
private final ShopManageGroupMapper shopManageGroupMapper;
private final CompanyMapper companyMapper;
/** 管理端作用域(会话身份已由调用方的菜单闸解析过)。 */
public JdCategoryScope resolve(AdminUserEntity operator) {
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
throw new BusinessException(403, "无权访问京东数据库");
}
return build(operator);
}
/**
* 按 user id 解析作用域(用户端「获取店铺数据」页的分类列表用:那里的身份是登录用户 id,
* 不是后台会话;解析不出账号按空作用域处理,调用方拿空列表而不是 500)。
*/
public JdCategoryScope resolveByUserId(Long userId) {
if (userId == null || userId <= 0) {
return JdCategoryScope.empty();
}
AdminUserEntity user = adminUserMapper.selectById(userId);
if (user == null || user.getId() == null || user.getId() <= 0) {
return JdCategoryScope.empty();
}
return build(user);
}
/** 前端「分组」下拉 + 可写标记(不带公司字段,跨公司组名拼进 label)。 */
public JdCategoryScopeVo scopeVo(AdminUserEntity operator) {
return voOf(resolve(operator));
}
public JdCategoryScopeVo voOf(JdCategoryScope scope) {
JdCategoryScopeVo vo = new JdCategoryScopeVo();
vo.setPlatformSuperAdmin(scope.platformSuperAdmin());
vo.setDefaultGroupId(scope.defaultGroupId());
vo.setGroups(scope.groups());
return vo;
}
// ---------------------------------------------------------------- 入参收敛(读/写各一道)
/**
* 读侧「当前分组」:请求带了就用请求的(必须可见),没带就用默认(可见组第一项)。
* 一个可见组都没有时返回 {@code null}——页面照常可用(商品是全平台公共的,只是分类列全空),
* 弹窗按空列表提示「还没有数据权限分组」,不把整页打成 403。
*/
public Long readGroupOrNull(JdCategoryScope scope, Long requestedGroupId) {
Long target = requestedGroupId != null && requestedGroupId > 0
? requestedGroupId : scope.defaultGroupId();
if (target == null) {
return null;
}
if (!scope.canRead(target)) {
throw new BusinessException(403, "无权查看该分组的分类");
}
return target;
}
/**
* 写侧「当前分组」:请求带了就用请求的;没带时若只有一个可写组就用它,否则拒绝(要求先选组)。
*
* @return 目标数据权限分组(带 company_id,建分类时落归属公司)
*/
public ShopManageGroupEntity requireWritableGroup(JdCategoryScope scope, Long requestedGroupId) {
Long target = requestedGroupId != null && requestedGroupId > 0
? requestedGroupId : defaultWritableGroupId(scope);
if (target == null) {
throw new BusinessException(403, scope.writableGroupIds().isEmpty()
? "你还没有可管理的数据权限分组" : "请先选择要管理的分组");
}
if (!scope.canWrite(target)) {
throw new BusinessException(403, "仅该分组的管理员可以修改它的分类");
}
ShopManageGroupEntity group = shopManageGroupMapper.selectById(target);
if (group == null || group.getId() == null) {
throw new BusinessException("分组不存在,请刷新后重试");
}
return group;
}
private static Long defaultWritableGroupId(JdCategoryScope scope) {
if (scope.writableGroupIds().size() == 1) {
return scope.writableGroupIds().get(0);
}
Long first = scope.defaultGroupId();
return first != null && scope.canWrite(first) ? first : null;
}
// ---------------------------------------------------------------- 解析
private JdCategoryScope build(AdminUserEntity user) {
String role = adminAuthSupport.currentRole(user);
Map<Long, ShopManageGroupEntity> visible = new LinkedHashMap<>();
Set<Long> writable = new LinkedHashSet<>();
if (dataReadScope.isPlatformSuperAdmin(user)) {
collect(visible, shopManageGroupMapper.selectAllGroups());
writable.addAll(visible.keySet());
return assemble(true, user.getCompanyId(), visible, writable);
}
if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
Long companyId = user.getCompanyId();
if (companyId != null && companyId > 0) {
collect(visible, companyGroups(companyId));
writable.addAll(visible.keySet());
}
return assemble(false, companyId, visible, writable);
}
// 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。
List<ShopManageGroupEntity> led = ledGroups(user.getId());
collect(visible, led);
if ("admin".equals(role)) {
for (ShopManageGroupEntity group : led) {
if (group.getId() != null) {
writable.add(group.getId());
}
}
}
if (user.getCreatedById() != null && user.getCreatedById() > 0) {
collect(visible, ledGroups(user.getCreatedById()));
}
List<Long> memberOfLeaders = shopManageGroupMapper.selectLeaderIdsByMemberUserId(user.getId());
if (memberOfLeaders != null) {
for (Long leaderId : memberOfLeaders) {
collect(visible, ledGroups(leaderId));
}
}
return assemble(false, user.getCompanyId(), visible, writable);
}
private List<ShopManageGroupEntity> companyGroups(Long companyId) {
return shopManageGroupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
.eq(ShopManageGroupEntity::getCompanyId, companyId)
.orderByAsc(ShopManageGroupEntity::getGroupName)
.orderByAsc(ShopManageGroupEntity::getId));
}
private List<ShopManageGroupEntity> ledGroups(Long userId) {
if (userId == null || userId <= 0) {
return List.of();
}
List<ShopManageGroupEntity> rows = shopManageGroupMapper.selectLedGroups(userId);
return rows == null ? List.of() : rows;
}
private static void collect(Map<Long, ShopManageGroupEntity> target, List<ShopManageGroupEntity> rows) {
if (rows == null) {
return;
}
for (ShopManageGroupEntity row : rows) {
if (row != null && row.getId() != null && row.getId() > 0) {
target.putIfAbsent(row.getId(), row);
}
}
}
private JdCategoryScope assemble(boolean platformSuperAdmin, Long companyId,
Map<Long, ShopManageGroupEntity> visible, Set<Long> writable) {
Map<Long, String> companyNames = platformSuperAdmin ? companyNames(visible.values()) : Map.of();
List<JdCategoryGroupOptionVo> options = new ArrayList<>(visible.size());
for (ShopManageGroupEntity group : visible.values()) {
String groupName = group.getGroupName() == null ? "" : group.getGroupName().trim();
String label = groupName;
if (platformSuperAdmin) {
String companyName = companyNames.get(group.getCompanyId());
label = companyName == null || companyName.isBlank()
? groupName : companyName + " / " + groupName;
}
options.add(new JdCategoryGroupOptionVo(group.getId(), groupName, label,
writable.contains(group.getId())));
}
return new JdCategoryScope(platformSuperAdmin, companyId,
List.copyOf(visible.keySet()), List.copyOf(writable), List.copyOf(options));
}
/** 平台超管跨公司时给组名补公司前缀(一次批量取,不逐行查询)。 */
private Map<Long, String> companyNames(java.util.Collection<ShopManageGroupEntity> groups) {
Set<Long> companyIds = new LinkedHashSet<>();
for (ShopManageGroupEntity group : groups) {
if (group.getCompanyId() != null && group.getCompanyId() > 0) {
companyIds.add(group.getCompanyId());
}
}
if (companyIds.isEmpty()) {
return Map.of();
}
Map<Long, String> names = new LinkedHashMap<>();
for (CompanyEntity company : companyMapper.selectBatchIds(companyIds)) {
if (company.getId() != null && company.getCompanyName() != null) {
names.put(company.getId(), company.getCompanyName());
}
}
return names;
}
/**
* 解析结果(只读快照)。{@code groups} 已按组名排序并带 {@code editable};列表读侧直接用
* {@link #visibleGroupIds()}、写侧用 {@link #writableGroupIds()}。
*/
public record JdCategoryScope(boolean platformSuperAdmin, Long companyId,
List<Long> visibleGroupIds, List<Long> writableGroupIds,
List<JdCategoryGroupOptionVo> groups) {
public static JdCategoryScope empty() {
return new JdCategoryScope(false, null, List.of(), List.of(), List.of());
}
public boolean canRead(Long groupId) {
return groupId != null && groupId > 0 && visibleGroupIds.contains(groupId);
}
public boolean canWrite(Long groupId) {
return groupId != null && groupId > 0 && writableGroupIds.contains(groupId);
}
public Long defaultGroupId() {
return groups.isEmpty() ? null : groups.get(0).getId();
}
}
}
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
@@ -16,6 +17,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskItemVo;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
@@ -59,6 +61,7 @@ public class JdCollectBoardService {
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
private final JdProductSkuMapper jdProductSkuMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
private final ObjectMapper objectMapper;
/** 查询当前用户的面板总览(运行中/成功/失败三档计数,已结束=成功+失败)。 */
@@ -279,9 +282,10 @@ public class JdCollectBoardService {
}
/**
* 删除任务(铁律 32 数据面):京东数据库三表按 {@code task_id} 清 + scope 行 + 任务主行。
* 删除任务(铁律 32 数据面):京东数据库四表按 {@code task_id}/商品 id 清 + scope 行 + 任务主行。
* 事务内只做 DB 删除;京东采集没有 OSS 载荷/任务缓存需要 afterCommit 清理。
* 删行顺序照 {@code JdProductRowDeleteService#deleteRows}:先 sku/image 子行再主行。
* 删行顺序照 {@code JdProductRowDeleteService#deleteRows}:先归类归属/sku/image 子行再主行
* (V203 加入 {@code biz_jd_product_group_assign},按商品 id 清所有组的归属)。
*/
@Transactional
public void deleteTask(Long taskId, Long userId) {
@@ -296,6 +300,8 @@ public class JdCollectBoardService {
.eq(JdProductEntity::getTaskId, taskId))
.stream().map(JdProductEntity::getId).toList();
if (!productIds.isEmpty()) {
jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.in(JdProductGroupAssignEntity::getProductId, productIds));
jdProductSkuMapper.delete(new LambdaQueryWrapper<JdProductSkuEntity>()
.in(JdProductSkuEntity::getProductId, productIds));
jdProductImageMapper.delete(new LambdaQueryWrapper<JdProductImageEntity>()
@@ -1,11 +1,10 @@
package com.nanri.aiimage.modules.jd.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.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import lombok.RequiredArgsConstructor;
@@ -13,21 +12,24 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 京东商品自定义分组业务(v1.4 Phase 5,R4):下拉列表 / 新建 / 改名 / 删除。
* 京东商品自定义分类业务(v1.4 Phase 5,R4;V203 改按数据权限分组归属)。
*
* <p>分组表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。
* 业务规则:</p>
* <p>分类表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。业务规则:</p>
* <ul>
* <li><b>全平台一份(2026-11-15 用户定案「分组和亚马逊功能一样」=与品牌数据库的
* 全平台共享同形状)</b>:读写都不带公司维度;实体遗留的 {@code company_id} 列只是
* V195~V199 按公司隔离时代的历史值,新行由 DEFAULT 0 落「平台公共」。</li>
* <li><b>全局重名拒绝</b>(唯一键 {@code uk_group_name},V200 退键):先查后插给可读的
* 409 业务错误,不拿 DB 异常撞 500;改名时排除自身再查。</li>
* <li><b>删除两步一事务</b>(AC-8):先把该组商品 {@code biz_jd_product.group_id} 置 NULL
* (商品不删,脱组即成「未分组」),再删分组行——同一事务,失败一起回滚。</li>
* <li><b>归属一个数据权限分组</b>(2026-11-16 用户口径「不同组不能看到跨组的分类」):
* {@code owner_group_id} → {@code biz_shop_manage_group.id};读写范围由
* {@link JdCategoryScopeService} 解析,本服务只做「按给定组取/写」。</li>
* <li><b>同组重名拒绝</b>(唯一键 {@code uk_company_owner_name},V203):先查后插给可读的
* 409 业务错误,不拿 DB 异常撞 500;改名时排除自身再查。不同组可同名。</li>
* <li><b>删除分类不删商品</b>:只删该分类的归类归属行
* ({@code biz_jd_product_group_assign},同一事务),商品行留在公共库里。</li>
* <li><b>商品数现算</b>:{@code productCount} 按归属表 {@code category_id} 计数——商品是全平台公共的,
* 同一商品在别的组里可能另挂一个分类,这里只数本分类。</li>
* </ul>
*/
@Service
@@ -35,67 +37,105 @@ import java.util.List;
public class JdProductGroupService {
private final JdProductGroupMapper jdProductGroupMapper;
private final JdProductMapper jdProductMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
/** 单个分组的分类全量(按 {@code sort_order, id} 升序,下拉展示顺序)。 */
public List<JdProductGroupVo> list(Long ownerGroupId) {
if (ownerGroupId == null || ownerGroupId <= 0) {
return List.of();
}
return listForGroups(List.of(ownerGroupId));
}
/**
* 分组全量(按 {@code sort_order, id} 升序,下拉展示顺序);
* {@code productCount} 用 {@code JdProductMapper} BaseMapper selectCount wrapper
* 按 {@code group_id} 统计(分组下拉展示用)。
* 多个分组的分类并集(用户端「获取店铺数据」页:一个普通号可能同时在多个组里,只读展示)。
* 空清单直接回空,不生成 {@code IN ()}。
*/
public List<JdProductGroupVo> list() {
LambdaQueryWrapper<JdProductGroupEntity> query = new LambdaQueryWrapper<JdProductGroupEntity>()
.orderByAsc(JdProductGroupEntity::getSortOrder)
.orderByAsc(JdProductGroupEntity::getId);
List<JdProductGroupVo> items = new ArrayList<>();
for (JdProductGroupEntity group : jdProductGroupMapper.selectList(query)) {
public List<JdProductGroupVo> listForGroups(List<Long> ownerGroupIds) {
Set<Long> safeGroupIds = new LinkedHashSet<>();
if (ownerGroupIds != null) {
for (Long id : ownerGroupIds) {
if (id != null && id > 0) {
safeGroupIds.add(id);
}
}
}
if (safeGroupIds.isEmpty()) {
return List.of();
}
List<JdProductGroupEntity> rows = jdProductGroupMapper.selectList(
new LambdaQueryWrapper<JdProductGroupEntity>()
.in(JdProductGroupEntity::getOwnerGroupId, safeGroupIds)
.orderByAsc(JdProductGroupEntity::getSortOrder)
.orderByAsc(JdProductGroupEntity::getId));
List<JdProductGroupVo> items = new ArrayList<>(rows.size());
for (JdProductGroupEntity category : rows) {
JdProductGroupVo vo = new JdProductGroupVo();
vo.setId(group.getId());
vo.setName(group.getName());
vo.setSortOrder(group.getSortOrder());
vo.setCreatedAt(group.getCreatedAt());
vo.setProductCount(jdProductMapper.selectCount(
new LambdaQueryWrapper<JdProductEntity>().eq(JdProductEntity::getGroupId, group.getId())));
vo.setId(category.getId());
vo.setName(category.getName());
vo.setSortOrder(category.getSortOrder());
vo.setOwnerGroupId(category.getOwnerGroupId());
vo.setCreatedAt(category.getCreatedAt());
vo.setProductCount(jdProductGroupAssignMapper.selectCount(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.eq(JdProductGroupAssignEntity::getCategoryId, category.getId())));
items.add(vo);
}
return items;
}
/** 新建分组:重名(trim 后)按 409 业务错误拒绝,不落库;company_id 不写(DB DEFAULT 0=平台公共)。 */
public Long create(String name, Integer sortOrder) {
String safeName = requireName(name);
requireNameFree(safeName, null);
JdProductGroupEntity group = new JdProductGroupEntity();
group.setName(safeName);
group.setSortOrder(sortOrder == null ? 0 : sortOrder);
jdProductGroupMapper.insert(group);
return group.getId();
/** 分类行存在校验(调用方拿它校验归属/写权限)。不存在一律按「分类不存在」拒绝。 */
public JdProductGroupEntity requireCategory(Long id) {
if (id == null || id <= 0) {
throw new BusinessException("分类不存在");
}
JdProductGroupEntity category = jdProductGroupMapper.selectById(id);
if (category == null) {
throw new BusinessException("分类不存在");
}
return category;
}
/** 改名/改排序:越界 id 拒绝,重名(排除自身)拒绝。 */
/** 新建分类:归属分组与公司由调用方(控制器)按作用域算好传入;同组重名 409。 */
public Long create(Long ownerGroupId, Long companyId, String name, Integer sortOrder) {
if (ownerGroupId == null || ownerGroupId <= 0) {
throw new BusinessException(400, "请先选择分组再新建分类");
}
String safeName = requireName(name);
requireNameFree(companyId, ownerGroupId, safeName, null);
JdProductGroupEntity category = new JdProductGroupEntity();
category.setCompanyId(companyId == null || companyId <= 0 ? 0L : companyId);
category.setOwnerGroupId(ownerGroupId);
category.setName(safeName);
category.setSortOrder(sortOrder == null ? 0 : sortOrder);
jdProductGroupMapper.insert(category);
return category.getId();
}
/** 改名/改排序:归属由调用方校验过;重名(同组、排除自身)拒绝。 */
public void rename(Long id, String name, Integer sortOrder) {
String safeName = requireName(name);
JdProductGroupEntity group = requireExistingGroup(id);
requireNameFree(safeName, group.getId());
group.setName(safeName);
JdProductGroupEntity category = requireCategory(id);
requireNameFree(category.getCompanyId(), category.getOwnerGroupId(), safeName, category.getId());
category.setName(safeName);
if (sortOrder != null) {
group.setSortOrder(sortOrder);
category.setSortOrder(sortOrder);
}
jdProductGroupMapper.updateById(group);
jdProductGroupMapper.updateById(category);
}
/**
* 删除分组(事务两步,AC-8):先把该组商品 {@code group_id} 置 NULL(商品保留,
* 脱组即「未分组」),再删分组行。越界 id 拒绝。
* 删除分类(同一事务):先删该分类的归类归属行(商品保留在公共库),再删分类行。
*
* @return 实际脱组的商品行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
* @return 实际解挂的归属行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
*/
@Transactional
@Transactional(rollbackFor = Exception.class)
public int delete(Long id) {
JdProductGroupEntity group = requireExistingGroup(id);
int detached = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
.set(JdProductEntity::getGroupId, null)
.eq(JdProductEntity::getGroupId, group.getId()));
jdProductGroupMapper.deleteById(group.getId());
JdProductGroupEntity category = requireCategory(id);
int detached = jdProductGroupAssignMapper.delete(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.eq(JdProductGroupAssignEntity::getCategoryId, category.getId()));
jdProductGroupMapper.deleteById(category.getId());
return detached;
}
@@ -109,25 +149,15 @@ public class JdProductGroupService {
return name.trim();
}
/** 分类行存在校验:不存在一律按「分类不存在」拒绝。 */
private JdProductGroupEntity requireExistingGroup(Long id) {
if (id == null || id <= 0) {
throw new BusinessException("分类不存在");
}
JdProductGroupEntity group = jdProductGroupMapper.selectById(id);
if (group == null) {
throw new BusinessException("分类不存在");
}
return group;
}
/** 全局重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
private void requireNameFree(String name, Long excludeId) {
/** 同组重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
private void requireNameFree(Long companyId, Long ownerGroupId, String name, Long excludeId) {
Long count = jdProductGroupMapper.selectCount(new LambdaQueryWrapper<JdProductGroupEntity>()
.eq(JdProductGroupEntity::getName, name)
.eq(JdProductGroupEntity::getOwnerGroupId, ownerGroupId)
.eq(JdProductGroupEntity::getCompanyId, companyId == null ? 0L : companyId)
.ne(excludeId != null, JdProductGroupEntity::getId, excludeId));
if (count != null && count > 0) {
throw new BusinessException(409, "已存在同名分类:" + name);
throw new BusinessException(409, "本组已存在同名分类:" + name);
}
}
}
@@ -5,11 +5,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
@@ -70,6 +72,7 @@ public class JdProductQueryService {
private final JdProductImageMapper jdProductImageMapper;
private final JdProductSkuMapper jdProductSkuMapper;
private final JdProductGroupMapper jdProductGroupMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
private final ObjectMapper objectMapper = new ObjectMapper();
/**
@@ -83,7 +86,7 @@ public class JdProductQueryService {
*/
public JdProductPageVo page(Long page, Long pageSize,
String productCode, String titleKeyword, String category, Long groupId,
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
LocalDateTime syncedFrom, LocalDateTime syncedTo, Long ownerGroupId) {
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
throw new BusinessException("开始时间不能晚于结束时间");
}
@@ -101,7 +104,7 @@ public class JdProductQueryService {
filter.syncedFrom(), filter.syncedTo(),
(safePage - 1) * safeSize, (int) safeSize);
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
fillGroupNames(items);
fillGroupNames(items, ownerGroupId);
JdProductPageVo vo = new JdProductPageVo();
vo.setItems(items);
vo.setTotal(total);
@@ -127,7 +130,7 @@ public class JdProductQueryService {
* 越界 id 按不存在拒绝。attr_json 非契约形状/解析异常时不抛 500:落空 {@code attrGroups}、
* 原文进 {@code attrJsonRaw} 兜底(AC-7)。</p>
*/
public JdProductDetailVo detail(Long id) {
public JdProductDetailVo detail(Long id, Long ownerGroupId) {
if (id == null || id <= 0) {
throw new BusinessException("商品不存在");
}
@@ -162,7 +165,7 @@ public class JdProductQueryService {
vo.setDetailUrl(row.getDetailUrl());
vo.setAttrCount(row.getAttrCount());
vo.setImageCount(row.getImageCount());
vo.setGroupId(row.getGroupId());
fillCategory(vo, row.getId(), ownerGroupId);
vo.setCollectBatchId(row.getCollectBatchId());
vo.setSyncedAt(row.getSyncedAt());
parseAttrGroups(vo, row.getAttrJson());
@@ -189,7 +192,7 @@ public class JdProductQueryService {
// ---------------------------------------------------------------- 列表/详情搬运
/** 行值原样搬运(读侧不加工),groupName 由 {@link #fillGroupNames} 批量补齐。 */
/** 行值原样搬运(读侧不加工),分类 id/名由 {@link #fillGroupNames} 批量补。 */
private JdProductListItemVo toListItem(JdProductEntity row) {
JdProductListItemVo vo = new JdProductListItemVo();
vo.setId(row.getId());
@@ -214,34 +217,81 @@ public class JdProductQueryService {
vo.setMainImageUrl(row.getMainImageUrl());
vo.setAttrCount(row.getAttrCount());
vo.setImageCount(row.getImageCount());
vo.setGroupId(row.getGroupId());
vo.setSyncedAt(row.getSyncedAt());
return vo;
}
/** 批量补分组名:行集的 group_id 一次取齐(一次查询,无逐行查询);读不到的分组不猜名字。 */
private void fillGroupNames(List<JdProductListItemVo> items) {
List<Long> groupIds = items.stream()
.map(JdProductListItemVo::getGroupId)
/**
* 批量补「当前分组」的分类:行集商品 id 一次取齐本组归属
* ({@code biz_jd_product_group_assign} 的 {@code owner_group_id} 那一行),再批量取分类名。
* 读不到的分类不猜名字(可能刚被别的会话删掉);没有分组上下文时分类列一律空(未分类)。
*/
private void fillGroupNames(List<JdProductListItemVo> items, Long ownerGroupId) {
if (items.isEmpty() || ownerGroupId == null || ownerGroupId <= 0) {
return;
}
List<Long> productIds = items.stream()
.map(JdProductListItemVo::getId)
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (groupIds.isEmpty()) {
if (productIds.isEmpty()) {
return;
}
Map<Long, String> namesById = new LinkedHashMap<>();
for (JdProductGroupEntity group : jdProductGroupMapper.selectBatchIds(groupIds)) {
if (group.getId() != null && group.getName() != null && !group.getName().isBlank()) {
namesById.put(group.getId(), group.getName());
Map<Long, Long> categoryByProduct = new LinkedHashMap<>();
for (JdProductGroupAssignEntity assign : jdProductGroupAssignMapper.selectList(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.in(JdProductGroupAssignEntity::getProductId, productIds)
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId))) {
if (assign.getProductId() != null && assign.getCategoryId() != null) {
categoryByProduct.put(assign.getProductId(), assign.getCategoryId());
}
}
if (categoryByProduct.isEmpty()) {
return;
}
Map<Long, String> namesById = categoryNames(categoryByProduct.values());
for (JdProductListItemVo item : items) {
if (item.getGroupId() != null) {
item.setGroupName(namesById.get(item.getGroupId()));
Long categoryId = categoryByProduct.get(item.getId());
if (categoryId != null) {
item.setGroupId(categoryId);
item.setGroupName(namesById.get(categoryId));
}
}
}
/** 详情侧的单行分类:与列表同一出口同一口径(当前分组那一行归属)。 */
private void fillCategory(JdProductDetailVo vo, Long productId, Long ownerGroupId) {
if (productId == null || ownerGroupId == null || ownerGroupId <= 0) {
return;
}
JdProductGroupAssignEntity assign = jdProductGroupAssignMapper.selectOne(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.eq(JdProductGroupAssignEntity::getProductId, productId)
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId)
.last("limit 1"));
if (assign == null || assign.getCategoryId() == null) {
return;
}
vo.setGroupId(assign.getCategoryId());
vo.setGroupName(categoryNames(List.of(assign.getCategoryId())).get(assign.getCategoryId()));
}
/** 分类 id → 名字(一次批量取;读不到的不猜)。 */
private Map<Long, String> categoryNames(java.util.Collection<Long> categoryIds) {
List<Long> ids = categoryIds.stream().filter(id -> id != null && id > 0).distinct().toList();
if (ids.isEmpty()) {
return Map.of();
}
Map<Long, String> namesById = new LinkedHashMap<>();
for (JdProductGroupEntity category : jdProductGroupMapper.selectBatchIds(ids)) {
if (category.getId() != null && category.getName() != null && !category.getName().isBlank()) {
namesById.put(category.getId(), category.getName());
}
}
return namesById;
}
/** 已转存图片:按档内排序号、id 稳定升序(详情抽屉分区展示顺序)。 */
private List<JdProductDetailVo.ImageViewVo> loadImages(Long productId) {
List<JdProductImageEntity> rows = jdProductImageMapper.selectList(
@@ -1,9 +1,11 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
import lombok.RequiredArgsConstructor;
@@ -20,9 +22,10 @@ import java.util.List;
* ({@link JdProductDeleteService} 先删桶、全成功才调本类)。若把三次 delete 与 S3 调用塞进
* 同一个事务,S3 通一次网就多占一次行锁,而且事务回滚也救不回已经删掉的对象。</p>
*
* <p>删除顺序固定 {@code SKU → 图片行 → 商品行}:三张表都按 {@code product_id} 关联、没有外键,
* 先删子行不会因为"主行先没"而留下查不到的孤儿;反过来则会。SQL 全走 BaseMapper wrapper
* (铁律 1 允许的两种形态之一,与 {@link JdProductGroupService} 同形状)。</p>
* <p>删除顺序固定 {@code 归类归属 → SKU → 图片行 → 商品行}:四张表都按 {@code product_id} 关联、
* 没有外键,先删子行不会因为"主行先没"而留下查不到的孤儿;反过来则会。归类归属
* ({@code biz_jd_product_group_assign},V203)按组各一行,删商品行时一次性清掉所有组的归属。
* SQL 全走 BaseMapper wrapper(铁律 1 允许的两种形态之一,与 {@link JdProductGroupService} 同形状)。</p>
*/
@Service
@RequiredArgsConstructor
@@ -32,6 +35,7 @@ public class JdProductRowDeleteService {
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
private final JdProductSkuMapper jdProductSkuMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
/**
* 删除给定商品行的 SKU / 图片登记 / 商品行,返回商品行删除条数。
@@ -44,6 +48,8 @@ public class JdProductRowDeleteService {
if (ids == null || ids.isEmpty()) {
throw new IllegalArgumentException("删除商品行必须给出非空 id 清单");
}
jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.in(JdProductGroupAssignEntity::getProductId, ids));
jdProductSkuMapper.delete(new LambdaQueryWrapper<JdProductSkuEntity>()
.in(JdProductSkuEntity::getProductId, ids));
jdProductImageMapper.delete(new LambdaQueryWrapper<JdProductImageEntity>()
@@ -6,12 +6,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.text.UserMessages;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
@@ -26,6 +28,7 @@ import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -38,8 +41,9 @@ import java.util.Set;
*
* <p>三条块语义:</p>
* <ul>
* <li><b>主字段全量提交</b>:标题/品牌/类目/货号/价格区间/总库存/状态/分组按请求体覆写;
* 分组 id 必须真实存在(分组 2026-11-15 起全平台一份,无公司维度)。保存即置
* <li><b>主字段全量提交</b>:标题/品牌/类目/货号/价格区间/总库存/状态按请求体覆写;
* <b>分类不在编辑面</b>(V203:分类按数据权限分组隔离、归属存独立表,只能走「店铺分类」
* 弹窗归类,编辑抽屉不再写商品行的 {@code group_id})。保存即置
* {@code manual_locked=1}(V199 人工编辑锁)——采集回传的 upsert / 图片与 SKU 登记 /
* 覆盖清理对锁定的行全部跳过,人工值不被重爬覆盖。</li>
* <li><b>可选块缺省不动</b>:{@code attrGroups} 缺省不动属性;提交时只重建 attr_json 的
@@ -92,6 +96,7 @@ public class JdProductUpdateService {
private final JdProductSkuMapper jdProductSkuMapper;
private final JdProductImageMapper jdProductImageMapper;
private final JdProductGroupMapper jdProductGroupMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
private final OssStorageService ossStorageService;
private final ObjectMapper objectMapper = new ObjectMapper();
@@ -119,14 +124,6 @@ public class JdProductUpdateService {
}
validateBody(body);
Long groupId = body.getGroupId();
if (groupId != null) {
JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
if (group == null) {
throw new BusinessException("分类不存在,请刷新分类后重试");
}
}
// 可选块先算(属性重建可能拒绝),再动库行——拒绝时零库行已动。
String newAttrJson = null;
Integer newAttrCount = null;
@@ -146,7 +143,6 @@ public class JdProductUpdateService {
.set(JdProductEntity::getPriceMax, body.getPriceMax())
.set(JdProductEntity::getStockTotal, body.getStockTotal())
.set(JdProductEntity::getSaleStatus, trimToNull(body.getSaleStatus()))
.set(JdProductEntity::getGroupId, groupId)
// 人工编辑锁:保存即锁定,采集链路(upsert/登记/覆盖清理)此后跳过本行。
.set(JdProductEntity::getManualLocked, 1);
if (newAttrJson != null) {
@@ -177,21 +173,23 @@ public class JdProductUpdateService {
// ---------- 校验 ----------
/**
* 批量人工归类(店铺分类弹窗,2026-11-15):勾选商品行 → 归入指定分类或移出分类。
* 批量人工归类(店铺分类弹窗,2026-11-15;V203 改按数据权限分组隔离)。
*
* <p>与单行编辑同口径(用户拍板「置锁」):归类即人工干预,落 {@code manual_locked=1}——
* 采集 upsert 本就不写 group_id,置锁后覆盖清理也不再把这些行整行删掉,分类永不丢;
* 代价是该行的价格/库存等字段随锁停更(与编辑保存同一语义)。</p>
* <p>归类归属写进 {@code biz_jd_product_group_assign}({@code (product_id, owner_group_id)} 唯一):
* 商品行是全平台公共的,同一个商品在 A 组和 B 组可以各自归类,互不挤占。
* {@code categoryId} null=移出分类(删本组这一行归属,商品在本组回到未分类)。</p>
*
* <p>{@code groupId} null=移出分类(group_id 置 NULL 回到未分类);非 null 时必须真实
* 存在(分类全平台一份,无公司维度)。只写 group_id 与锁两个列,不动其它字段——
* 与 {@link #update} 的全量覆写不同,这是行集级轻touch。</p>
* <p><b>不再置人工编辑锁</b>(2026-11-16 用户口径):分类不在商品行上,采集回传的
* upsert/覆盖清理冲不掉它,置锁只会让这个共享商品的价格/库存对所有组都停更。</p>
*
* @return 实际更新的行数(id 不存在/已被删的行不计入,不按不存在整批拒绝——
* @return 实际写入/变更的归属行数(id 不存在/已被删的行不计入,不按不存在整批拒绝——
* 弹窗行集与库行之间天然有采集刷新的时间差,掉队的行跳过即可)
*/
@Transactional(rollbackFor = Exception.class)
public int assignGroup(List<Long> ids, Long groupId) {
public int assignGroup(Long ownerGroupId, Long companyId, List<Long> ids, Long categoryId, Long operatorId) {
if (ownerGroupId == null || ownerGroupId <= 0) {
throw new BusinessException(403, "请先选择分组再归类");
}
if (ids == null || ids.isEmpty()) {
throw new BusinessException("请先选择要归类的商品");
}
@@ -202,20 +200,55 @@ public class JdProductUpdateService {
if (distinctIds.size() > MAX_ASSIGN_IDS) {
throw new BusinessException("单次最多归类 " + MAX_ASSIGN_IDS + " 个商品,请分批操作");
}
if (groupId != null) {
JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
if (group == null) {
if (categoryId != null) {
JdProductGroupEntity category = jdProductGroupMapper.selectById(categoryId);
if (category == null) {
throw new BusinessException("分类不存在,请刷新分类后重试");
}
if (!ownerGroupId.equals(category.getOwnerGroupId())) {
throw new BusinessException(403, "该分类不属于当前分组,请刷新后重试");
}
}
int updated = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
.in(JdProductEntity::getId, distinctIds)
.set(JdProductEntity::getGroupId, groupId)
// 人工编辑锁:归类即人工干预,采集链路(upsert/登记/覆盖清理)此后跳过本行。
.set(JdProductEntity::getManualLocked, 1));
log.info("[{}] 批量归类 requested={} distinct={} groupId={} updated={}",
LOG_TAG, ids.size(), distinctIds.size(), groupId, updated);
return updated;
Map<Long, Long> categoryIdByProduct = new LinkedHashMap<>();
for (JdProductGroupAssignEntity assign : jdProductGroupAssignMapper.selectList(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.in(JdProductGroupAssignEntity::getProductId, distinctIds)
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId))) {
if (assign.getProductId() != null) {
categoryIdByProduct.put(assign.getProductId(), assign.getCategoryId());
}
}
if (categoryId == null) {
int removed = jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.in(JdProductGroupAssignEntity::getProductId, distinctIds)
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId));
log.info("[{}] 移出分类 ownerGroupId={} requested={} removed={}",
LOG_TAG, ownerGroupId, distinctIds.size(), removed);
return removed;
}
int written = 0;
for (Long productId : distinctIds) {
Long existingCategoryId = categoryIdByProduct.get(productId);
if (existingCategoryId == null) {
JdProductGroupAssignEntity assign = new JdProductGroupAssignEntity();
assign.setProductId(productId);
assign.setOwnerGroupId(ownerGroupId);
assign.setCategoryId(categoryId);
assign.setCompanyId(companyId == null || companyId <= 0 ? 0L : companyId);
assign.setCreatedBy(operatorId);
written += jdProductGroupAssignMapper.insert(assign);
} else if (!categoryId.equals(existingCategoryId)) {
written += jdProductGroupAssignMapper.update(null,
new LambdaUpdateWrapper<JdProductGroupAssignEntity>()
.eq(JdProductGroupAssignEntity::getProductId, productId)
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId)
.set(JdProductGroupAssignEntity::getCategoryId, categoryId)
.set(JdProductGroupAssignEntity::getCreatedBy, operatorId));
}
}
log.info("[{}] 批量归类 ownerGroupId={} requested={} distinct={} categoryId={} written={}",
LOG_TAG, ownerGroupId, ids.size(), distinctIds.size(), categoryId, written);
return written;
}
private void validateBody(JdProductUpdateRequest body) {
@@ -0,0 +1,122 @@
-- =============================================================
-- 迁移 V203__jd_product_group_owner_group
-- 需求:2026-11-16 用户口径「京东数据库分类不同组不能看到跨组的分类,当前组只管理员可以编辑,
-- 同组普通号只读;归类也按组隔离」——「组」=公司内的数据权限分组
-- (biz_shop_manage_group),即 公司 → 组 两级隔离。
-- 前版:V195(分组表按公司一套,uk_company_group_name)→ V200(退成全平台一份 uk_group_name)
-- → V201(清空旧分类与商品归属,商品保留)
--
-- 1. 变更目的:分类从「全平台一份」改成「归属某个数据权限分组」。只加一个归属列不够——
-- 商品归类也必须按组隔离(同一商品各组可各自归类),而 biz_jd_product.group_id 是单值列,
-- 放不下"每组一份归属",故新增归属表 biz_jd_product_group_assign。
-- biz_jd_product.group_id 列【不删】:V201 已把它整列置 NULL,本版起读写两侧都不再引用;
-- 删列与换代码同批会在混合窗口里打断旧 jar(同 V200 第 2 段、V151 第 6 段纪律)。
--
-- 2. 口径:
-- biz_jd_product_group + owner_group_id BIGINT NOT NULL DEFAULT 0
-- uk_group_name(name) -> uk_company_owner_name(company_id, owner_group_id, name)
-- biz_jd_product_group_assign(新表)
-- uk_product_owner(product_id, owner_group_id) 一组一商品最多一个分类
-- idx_category(category_id) 分类商品数现算 / 删分类级联
-- idx_owner_group 按组取一组归属
--
-- 3. 存量:owner_group_id DEFAULT 0 =「V200 全平台一份时代」的历史行。V201 已把分类与商品归属
-- 清空(2026-11-16 上线),预期本表 0 行、最多少量手工重建行;这些行不删、也不出现在任何
-- 读取面(读侧只按真实分组 id 过滤)。要保留它们须人工回填归属,见文末回滚/恢复段。
--
-- 4. 可重跑性:两条列/键 DDL 与建表都先查 information_schema 再 PREPARE,重跑逐条 no-op。
-- 先加新唯一键、再摘旧键(同 V151/V200 纪律:中间任一步失败时至少有一个唯一键在守并发)。
--
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
-- ALTER TABLE biz_jd_product_group ADD UNIQUE KEY uk_group_name (name);
-- ALTER TABLE biz_jd_product_group DROP INDEX uk_company_owner_name;
-- ALTER TABLE biz_jd_product_group DROP COLUMN owner_group_id;
-- DROP TABLE biz_jd_product_group_assign;
-- (jar 必须先回到"分类全平台一份"的那版,否则读侧会按不存在的列过滤。)
--
-- 6. 历史行恢复(可选,人工执行;确认目标组 id 与公司 id 后再跑):
-- UPDATE biz_jd_product_group SET owner_group_id = <组id>, company_id = <公司id>
-- WHERE owner_group_id = 0 AND name = '<分类名>';
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 分类表:加归属数据权限分组列 ----------
SET @v203_owner_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND COLUMN_NAME = 'owner_group_id');
SET @sql := IF(@v203_owner_col = 0,
'ALTER TABLE `biz_jd_product_group` ADD COLUMN `owner_group_id` BIGINT NOT NULL DEFAULT 0 COMMENT ''归属数据权限分组(biz_shop_manage_group.id);0=2026-11-15 公共化时代的历史行,读侧不可见;V203'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 分类表:先加「公司+组+名」唯一键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'uk_company_owner_name');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `biz_jd_product_group` ADD UNIQUE KEY `uk_company_owner_name` (`company_id`, `owner_group_id`, `name`), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 3. 分类表:再摘全平台唯一键(同组才拒绝重名,不同组可同名) ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'uk_group_name');
SET @sql := IF(@idx_exists > 0,
'ALTER TABLE `biz_jd_product_group` DROP INDEX `uk_group_name`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 4. 归类归属表(按组一份;同一商品各组可各自归类) ----------
CREATE TABLE IF NOT EXISTS `biz_jd_product_group_assign` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`product_id` bigint NOT NULL COMMENT '商品行 id(biz_jd_product.id)',
`owner_group_id` bigint NOT NULL COMMENT '归属数据权限分组(biz_shop_manage_group.id)',
`category_id` bigint NOT NULL COMMENT '分类 id(biz_jd_product_group.id)',
`company_id` bigint NOT NULL DEFAULT 0 COMMENT '归属公司(分组所属公司,读侧快速过滤)',
`created_by` bigint NULL DEFAULT NULL COMMENT '操作者 user id',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_product_owner` (`product_id` ASC, `owner_group_id` ASC) USING BTREE,
INDEX `idx_category` (`category_id` ASC) USING BTREE,
INDEX `idx_owner_group` (`owner_group_id` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '京东商品按组归类归属(V203)' ROW_FORMAT = Dynamic;
-- =============================================================
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
--
-- SHOW COLUMNS FROM biz_jd_product_group LIKE 'owner_group_id';
-- -> 期望 Null = NO、Default = 0。
--
-- SELECT INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
-- FROM information_schema.STATISTICS
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_jd_product_group' AND NON_UNIQUE = 0
-- GROUP BY INDEX_NAME;
-- -> 期望 PRIMARY(id)、uk_company_owner_name(company_id@1,owner_group_id@2,name@3);
-- uk_group_name 必须不在结果里。
--
-- SHOW CREATE TABLE biz_jd_product_group_assign;
-- -> 期望含 uk_product_owner、idx_category、idx_owner_group。
--
-- SELECT COUNT(*) AS legacy_rows FROM biz_jd_product_group WHERE owner_group_id = 0;
-- -> 记录读数(V201 已清空,预期 0;>0 的行迁移后不可见,按头注释第 6 段人工回填)。
--
-- INSERT 撞键(事务内跑完回滚,只插 ZZTEST 前缀):
-- START TRANSACTION;
-- INSERT INTO biz_jd_product_group_assign (product_id, owner_group_id, category_id)
-- VALUES (9223372036854775806, 9223372036854775805, 9223372036854775804);
-- INSERT INTO biz_jd_product_group_assign (product_id, owner_group_id, category_id)
-- VALUES (9223372036854775806, 9223372036854775805, 9223372036854775803);
-- SELECT ROW_COUNT() AS should_be_dup_error_probe;
-- ROLLBACK;
-- -> 期望第二条报 Duplicate entry(uk_product_owner 生效);回滚后零残留。
-- =============================================================
@@ -101,9 +101,12 @@
</select>
<!-- 后管只读页(Phase 5,v1.4)过滤面:商品编码/标题关键词(contains LIKE)、类目 eq、
分组 eq(2026-11-16 起由类目面板「自定义分类」选中驱动,独立「分类」筛选框与
自定义分类 eq(2026-11-16 起由类目面板「自定义分类」选中驱动,独立「分类」筛选框与
「分类状态」档随同日口径「分类不要了,全部整合到类目里」撤掉:ungrouped/grouped
两参数与谓词同窗删除)、同步起止(datetime 闭区间)。
group_id 过滤【V203 起按组隔离】:分类归属在 biz_jd_product_group_assign 的
(product_id, owner_group_id) 一行上,商品行自己的 group_id 列已停用(V201 清空),
故改 EXISTS 子查询;分类 id 自带归属组,不必再传 owner 维(行内谓词仍只这一处)。
公司维过滤随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉(数据全平台公共;
行 company_id 列仍是同步来源标记,不构成可见性边界)。
sale_status 筛选随 2026-11-15 客户口径撤掉;店铺名过滤同日客户口径「店铺不需要」
@@ -113,7 +116,12 @@
<if test="productCode != null and productCode != ''">AND p.product_code LIKE CONCAT('%', #{productCode}, '%')</if>
<if test="titleKeyword != null and titleKeyword != ''">AND p.title LIKE CONCAT('%', #{titleKeyword}, '%')</if>
<if test="category != null and category != ''">AND p.category_path = #{category}</if>
<if test="groupId != null and groupId &gt; 0">AND p.group_id = #{groupId}</if>
<if test="groupId != null and groupId &gt; 0">
AND EXISTS (
SELECT 1 FROM biz_jd_product_group_assign a
WHERE a.product_id = p.id AND a.category_id = #{groupId}
)
</if>
<if test="syncedFrom != null">AND p.synced_at &gt;= #{syncedFrom}</if>
<if test="syncedTo != null">AND p.synced_at &lt;= #{syncedTo}</if>
</sql>
@@ -126,14 +134,16 @@
</select>
<!-- 只读页分页查询(synced_at 倒序)。
group_name 不在此联表:读侧按行集 group_id 批量取分组名补齐(一次查询,无逐行查询)。 -->
group_name 不在此联表:读侧按「当前数据权限分组」批量取归属
(biz_jd_product_group_assign,V203)再补分类名(一次查询,无逐行查询)。
p.group_id 列已随 V203 停用(分类改按组归属),不再投影。 -->
<select id="selectProductPage" resultType="com.nanri.aiimage.modules.jd.model.entity.JdProductEntity">
SELECT p.id, p.company_id, p.user_id, p.task_id, p.shop_id, p.shop_name, p.product_code, p.sku_id,
p.item_num, p.sku_count, p.health_score,
p.title, p.brand, p.brand_id, p.category_path, p.price_min, p.price_max, p.stock_total,
p.sale_status, p.list_tab, p.jd_created_at, p.jd_online_at, p.jd_updated_at,
p.main_image_url, p.detail_url,
p.attr_json, p.attr_count, p.image_count, p.group_id, p.collect_batch_id, p.synced_at
p.attr_json, p.attr_count, p.image_count, p.collect_batch_id, p.synced_at
FROM biz_jd_product p
WHERE 1=1 <include refid="productConds"/>
ORDER BY p.synced_at DESC, p.id DESC
@@ -80,6 +80,31 @@ class JdSchemaContractTest {
assertFalse(sql.contains("user_column_permission"), "菜单迁移不得插授权行(默认仅 super_admin,V190 惯例)");
}
@Test
void V203_分类按数据权限分组归属_归属列与归属表形状() {
String sql = read(DB_DIR.resolve("V203__jd_product_group_owner_group.sql"));
assertTrue(sql.contains("biz_jd_product_group"), "缺分类表");
// 归属列:NOT NULL DEFAULT 0(0=历史公共行,读侧不可见;显式默认值避免存量行 NULL 撞唯一键)。
assertTrue(linesContaining(sql, "`owner_group_id`").stream()
.anyMatch(line -> line.contains("NOT NULL") && line.contains("DEFAULT 0")),
"owner_group_id 必须 NOT NULL DEFAULT 0(铁律 30:缺件沿用前值,NULL 会让唯一键失效)");
// 唯一键三件套:同公司同组内重名拒绝、不同组可同名。
assertTrue(sql.contains("uk_company_owner_name"), "同公司同组重名唯一键缺失");
assertTrue(linesContaining(sql, "uk_company_owner_name").stream()
.anyMatch(line -> line.contains("company_id") && line.contains("owner_group_id")
&& line.contains("name")),
"唯一键必须是 (company_id, owner_group_id, name)");
// 一组一商品一行:同一商品各组可各自归类。
assertTrue(sql.contains("biz_jd_product_group_assign"), "缺归类归属表");
assertTrue(sql.contains("uk_product_owner"), "一组一商品唯一键缺失(uk_product_owner)");
for (String column : List.of("product_id", "owner_group_id", "category_id", "company_id", "created_by")) {
assertFalse(linesContaining(sql, "`" + column + "`").isEmpty(), "V203 归属表缺列: " + column);
}
// 可重跑:两次迁移之间不会因为列/键已存在而炸(information_schema 守卫)。
assertTrue(sql.contains("information_schema"), "必须带 information_schema 幂等守卫(可重跑)");
assertTrue(sql.contains("迁移 V203"), "头注释必须是 `-- 迁移 V203…`(MigrationInventoryTest 口径)");
}
@Test
void 配置_独立图片桶不落默认桶() {
String appYml = read(RESOURCES.resolve("application.yml"));
@@ -4,20 +4,28 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDeleteVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
@@ -25,7 +33,6 @@ import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Mapper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.web.multipart.MultipartFile;
@@ -66,6 +73,13 @@ import static org.mockito.Mockito.when;
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
* tabs→attrGroups 解析与非法形状兜底(AC-7)。
* 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p>
*
* <p><b>V203 分类按数据权限分组隔离(2026-11-16 用户口径)</b>:分类归属存
* {@code biz_jd_product_group_assign} 的 (product_id, owner_group_id) 一行,读面靠
* {@code owner_group_id} 取「当前分组」的分类(缺省=作用域默认分组),归类的写权限
* 由 {@link JdCategoryScopeService} 判「该组可写」——商品行编辑/删除仍只平台超管。
* 本类把作用域服务整体 mock 掉(四档角色矩阵在 {@code JdCategoryScopeServiceTest} 里钉),
* 只钉控制器怎么用它、以及拒绝语义不被吞。</p>
*/
class AdminJdProductControllerTest {
@@ -79,6 +93,10 @@ class AdminJdProductControllerTest {
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
/** 用例里的「当前分组」:数据权限分组 10,归属公司 5。 */
private static final long GROUP_ID = 10L;
private static final long COMPANY_ID = 5L;
// ===================== 结构判据 =====================
@Test
@@ -102,6 +120,9 @@ class AdminJdProductControllerTest {
// (AdminJdProductController 的 @PutMapping("/{id}",JdProductUpdateService 承接);商品行
// 采集回传覆盖链不变,人工改名只走这条 PUT。分组改排序仍落 AdminJdProductGroupController。
assertTrue(source.contains("@PutMapping"), "编辑商品端点必须落在 @PutMapping(\"/{id}\")");
// V203:读面「当前分组」一律走 owner_group_id(不叫 company_id——前端 company-tab 绊线钉住)。
assertTrue(source.contains("\"owner_group_id\""),
"分页/详情必须收 owner_group_id(当前数据权限分组)");
}
@Test
@@ -138,7 +159,7 @@ class AdminJdProductControllerTest {
void 分页参数snake且带默认值() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
for (String param : List.of("page_size", "product_code", "title_keyword",
"group_id", "synced_from", "synced_to")) {
"group_id", "owner_group_id", "synced_from", "synced_to")) {
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
}
assertFalse(source.contains("@RequestParam(name = \"ungrouped\""));
@@ -166,7 +187,13 @@ class AdminJdProductControllerTest {
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
assertTrue(xmlText.contains("countProducts"), "XML 必须有 countProducts(只读页总数)");
assertTrue(xmlText.contains("selectProductPage"), "XML 必须有 selectProductPage(只读页分页)");
assertTrue(xmlText.contains("AND p.group_id = #{groupId}"), "自定义分类必须下推 SQL");
// V203:分类归属在 biz_jd_product_group_assign(一组一商品一行),过滤必须下推成 EXISTS 子查询。
assertTrue(xmlText.contains("FROM biz_jd_product_group_assign"),
"自定义分类必须下推 SQL(V203 归属表 EXISTS 子查询)");
assertTrue(xmlText.contains("a.product_id = p.id") && xmlText.contains("a.category_id = #{groupId}"),
"EXISTS 子查询必须同时按商品与分类关联");
assertFalse(xmlText.contains("p.group_id = #{groupId}"),
"商品行 group_id 列已随 V203 停用(分类按组归属),不得回潜");
assertFalse(xmlText.contains("ungrouped"));
assertFalse(xmlText.contains("grouped"));
assertEquals(2, xmlText.split("<include refid=\"productConds\"", -1).length - 1,
@@ -187,29 +214,34 @@ class AdminJdProductControllerTest {
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
assertTrue(source.contains(seam), "分组鉴权闸缺接缝 " + seam + "(与商品页同款)");
}
// 读列表按菜单权限放行,写(新建/改名/删除)2026-11-16 起收窄到平台超管(用户口径
// 「京东数据库只有超管有编辑删除权限」;AC-9「普通授权用户可读写分组」已被该口径推翻)。
// V203 起写权限不再收窄到平台超管:本组管理员 / 公司超管 / 平台超管都可写(作用域服务判)。
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb);
}
assertEquals(3, count(source, "requirePlatformSuperAdminWrite(request)"),
"分组列表外的三个写端点都必须走超管写闸");
assertEquals(2, count(source, "requireJdAccess(request)"),
"分组列表与写闸内部各走一处菜单权限正门");
assertTrue(source.contains("仅平台超级管理员可以修改京东数据库分类"),
"非超管写分类的 403 文案必须点名平台超管");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/作用域/新建/改名/删除五条路由都走同一菜单正门(写权限在作用域服务里判)");
assertFalse(source.contains("requirePlatformSuperAdminWrite"),
"分类写权限已改由 JdCategoryScopeService 判「该组可写」,超管专属闸必须已摘除");
assertTrue(source.contains("requireWritableGroup(") && source.contains("canWrite("),
"新建走 requireWritableGroup,改名/删除走 canWrite 归属校验");
assertTrue(source.contains("/scope") && source.contains("scopeVo("),
"必须提供 GET /scope 给前端渲染「分组」下拉与可写标记");
assertTrue(source.contains("仅该分组的管理员可以修改它的分类"),
"非本组管理员写分类的 403 文案必须点名分组管理员");
assertTrue(source.contains("\"owner_group_id\""), "列表必须收 owner_group_id(当前分组)");
}
// ===================== 写权限分档(2026-11-16) =====================
// ===================== 写权限分档(2026-11-16 / V203) =====================
/** 写端点越权闸的结构判据:五条写路由逐条走 requirePlatformSuperAdminWrite,读三条仍走菜单正门。 */
/** 写端点越权闸的结构判据:商品行四条写路由走超管闸,读三条走菜单正门。 */
@Test
void 商品页读写权限分档_写端点逐条走超管闸() throws IOException {
void 商品页读写权限分档_商品行写端点逐条走超管闸() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
assertEquals(5, count(source, "requirePlatformSuperAdminWrite(request)"),
"编辑/上传图片/单行删除/批量归类/批量删除五条写路由必须逐条走超管写闸");
assertEquals(4, count(source, "requireJdAccess(request)"),
"列表/类目/详情三条读路由与写闸内部共四处菜单权限正门");
assertEquals(4, count(source, "requirePlatformSuperAdminWrite(request)"),
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走超管写闸"
+ "(归类不在此列:V203 起归本组管理员可做)");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/类目/详情/归类四条读+组内写路由,与超管写闸内部一处,共五处菜单权限正门");
assertTrue(source.contains("仅平台超级管理员可以编辑或删除京东数据库数据"),
"非超管写商品的 403 文案必须点名平台超管");
assertTrue(source.contains("operator.superAdmin()"),
@@ -217,35 +249,41 @@ class AdminJdProductControllerTest {
}
@Test
void 非超管有菜单权限时读放行_写一律403且不触服务() {
void 非超管有菜单权限时读放行_商品行写一律403且不触服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, updateService, authSupport, permissionMenuService);
queryService, deleteService, updateService, groupService, scopeService,
authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
operator.setUsername("company-admin");
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、写仍拒。
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、商品行写仍拒。
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
grant.setRoutePath(ROUTE_PATH);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
// 读:菜单权限命中即放行(公共库一人一份全量)。
JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of());
when(queryService.page(1L, 20L, null, null, null, null, null, null)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, request).isSuccess(),
"非超管有菜单权限时读必须放行(读写分档只收窄写)");
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, request)
.isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)");
// 写:五条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
JdProductUpdateRequest updateBody = new JdProductUpdateRequest();
updateBody.setTitle("标题");
BusinessException updateEx = assertThrows(BusinessException.class,
@@ -262,14 +300,6 @@ class AdminJdProductControllerTest {
() -> controller.batchDelete(batchBody, request));
assertTrue(batchEx.getMessage().contains("仅平台超级管理员"));
JdProductBatchAssignGroupRequest assignBody = new JdProductBatchAssignGroupRequest();
assignBody.setIds(List.of(11L));
assignBody.setGroupId(3L);
BusinessException assignEx = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(assignBody, request));
assertTrue(assignEx.getMessage().contains("仅平台超级管理员"),
"批量归类会置人工编辑锁=写动作,必须同闸");
BusinessException uploadEx = assertThrows(BusinessException.class,
() -> controller.uploadImage(11L, mock(MultipartFile.class), "MAIN", null, null, request));
assertTrue(uploadEx.getMessage().contains("仅平台超级管理员"),
@@ -277,17 +307,18 @@ class AdminJdProductControllerTest {
verify(updateService, never()).update(any(), any());
verify(updateService, never()).uploadImage(any(), any(), any(), any(), any());
verify(updateService, never()).assignGroup(any(), any());
verify(updateService, never()).assignGroup(any(), any(), any(), any(), any());
verify(deleteService, never()).delete(any());
}
@Test
void 非超管有菜单权限时分组写一律403_读列表仍放行() {
void 不可写组的分组写一律403且不触服务() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductGroupController controller = new AdminJdProductGroupController(
groupService, authSupport, permissionMenuService);
groupService, scopeService, authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
@@ -297,57 +328,146 @@ class AdminJdProductControllerTest {
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
when(groupService.list()).thenReturn(List.of());
// 普通号:组可见但不可写(四档矩阵在 JdCategoryScopeServiceTest 里钉,这里只钉控制器接线)。
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
when(groupService.list(GROUP_ID)).thenReturn(List.of());
when(groupService.requireCategory(7L)).thenReturn(category(7L, GROUP_ID));
// 真实作用域服务对「可见但不可写」的组回 403;mock 掉它只验控制器不吞、不触业务服务。
when(scopeService.requireWritableGroup(any(), any()))
.thenThrow(new BusinessException(403, "仅该分组的管理员可以修改它的分类"));
assertEquals(Boolean.TRUE, controller.list(request).isSuccess(),
"分类列表是读端点,菜单权限命中即放行(筛选下拉要能用)");
assertEquals(Boolean.TRUE, controller.list(null, request).isSuccess(),
"分类列表是读端点,菜单权限命中即放行(同组普通号也能开弹窗看)");
JdProductGroupSaveRequest saveBody = new JdProductGroupSaveRequest();
saveBody.setName("新分类");
saveBody.setSortOrder(0);
BusinessException createEx = assertThrows(BusinessException.class,
() -> controller.create(saveBody, request));
assertTrue(createEx.getMessage().contains("仅平台超级管理员"));
assertTrue(createEx.getMessage().contains("仅该分组的管理员"),
"新建成分类的 403 文案必须点名分组管理员");
// 改名/删除:控制器自己按分类归属判 canWrite(作用域不可写 ⇒ 403,业务服务不被调到)。
BusinessException renameEx = assertThrows(BusinessException.class,
() -> controller.rename(7L, saveBody, request));
assertTrue(renameEx.getMessage().contains("仅平台超级管理员"));
assertTrue(renameEx.getMessage().contains("仅该分组的管理员"));
BusinessException deleteEx = assertThrows(BusinessException.class,
() -> controller.delete(7L, request));
assertTrue(deleteEx.getMessage().contains("仅平台超级管理员"));
assertTrue(deleteEx.getMessage().contains("仅该分组的管理员"));
verify(groupService, never()).create(any(), any());
verify(groupService, never()).create(any(), any(), any(), any());
verify(groupService, never()).rename(any(), any(), any());
verify(groupService, never()).delete(any());
}
@Test
void 本组管理员可归类本组_组内写权限不再只归平台超管() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), updateService, groupService,
scopeService, authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 组长(admin,非平台超管):拿到菜单权限即可归类自己带的组。
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.requireWritableGroup(any(), any())).thenReturn(shopGroup(GROUP_ID, COMPANY_ID));
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L)).thenReturn(2);
JdProductBatchAssignGroupRequest body = new JdProductBatchAssignGroupRequest();
body.setIds(List.of(11L, 12L));
body.setGroupId(3L);
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
verify(updateService).assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L);
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
assertEquals(2, response.getData(), "回执=实际写入的归属行数");
// 业务失败(目标分类不属于当前分组)文案原样透出,不吞。
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L), 404L, 9L))
.thenThrow(new BusinessException(403, "该分类不属于当前分组,请刷新后重试"));
JdProductBatchAssignGroupRequest ghostBody = new JdProductBatchAssignGroupRequest();
ghostBody.setIds(List.of(11L));
ghostBody.setGroupId(404L);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(ghostBody, request));
assertTrue(ex.getMessage().contains("不属于当前分组"));
}
@Test
void 分类筛选越组请求403且不触查询服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
// 分类 8 属于别组(ownerGroupId=20):按「当前分组」不可见 ⇒ 403,不放成空结果。
when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L));
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, request));
assertTrue(ex.getMessage().contains("无权查看该分组的分类"),
"跨组分类筛选必须 403 点名分组,不做空结果降级");
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
// ===================== 行为样本 =====================
@Test
void 控制器列表走requireJdAccess正门并把查询结果装进200信封() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
permissionMenuService);
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, GROUP_ID)).thenReturn(GROUP_ID);
JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of());
pageVo.setTotal(0L);
pageVo.setPage(1L);
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
when(queryService.page(1L, 20L, null, null, null, null, null, null)).thenReturn(pageVo);
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
// 2026-11-16 起请求面没有 company_id:任何授权身份看到的都是同一份全量。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
null, request);
// 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null,
GROUP_ID, null, null, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData());
}
@@ -355,10 +475,12 @@ class AdminJdProductControllerTest {
@Test
void 旧分类筛选参数明确拒绝并提示刷新() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
authSupport, mock(PermissionMenuService.class));
mock(JdProductGroupService.class), scopeService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
@@ -369,12 +491,12 @@ class AdminJdProductControllerTest {
for (String value : List.of("true", "false", "")) {
when(request.getParameter(name)).thenReturn(value);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, request));
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, null, request));
assertTrue(ex.getMessage().contains("刷新页面"));
when(request.getParameter(name)).thenReturn(null);
}
}
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any());
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -382,7 +504,8 @@ class AdminJdProductControllerTest {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -406,9 +529,11 @@ class AdminJdProductControllerTest {
@Test
void 控制器详情走同一鉴权正门并回详情且不问公司() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), scopeService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -416,14 +541,18 @@ class AdminJdProductControllerTest {
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
JdProductDetailVo detailVo = new JdProductDetailVo();
detailVo.setId(11L);
when(queryService.detail(11L)).thenReturn(detailVo);
when(queryService.detail(11L, GROUP_ID)).thenReturn(detailVo);
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
ApiResponse<JdProductDetailVo> response = controller.detail(11L, null, request);
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除)。
verify(queryService).detail(11L);
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除);
// 分类字段按「当前分组」取(V203)。
verify(queryService).detail(11L, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess());
assertEquals(detailVo, response.getData());
}
@@ -434,7 +563,8 @@ class AdminJdProductControllerTest {
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
queryService, deleteService, mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -462,7 +592,8 @@ class AdminJdProductControllerTest {
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
queryService, deleteService, mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -483,13 +614,11 @@ class AdminJdProductControllerTest {
@Test
void 查询服务分页钳制防溢出() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
service.page(0L, null, null, null, null, null, null, null);
service.page(0L, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
@@ -498,7 +627,7 @@ class AdminJdProductControllerTest {
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null);
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
@@ -510,13 +639,11 @@ class AdminJdProductControllerTest {
@Test
void 查询服务同步起止倒挂拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.page(1L, 20L, null, null, null, null, from, to));
() -> service.page(1L, 20L, null, null, null, null, from, to, null));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any());
}
@@ -524,65 +651,22 @@ class AdminJdProductControllerTest {
@Test
void 查询服务过滤面原样直传且空串归null() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null);
verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null);
verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, 0L, 20);
service.page(1L, 20L, " ", null, null, 0L, null, null);
service.page(1L, 20L, " ", null, null, 0L, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, null, null, null, 0L, 20);
}
@Test
void 批量归类端点走同一鉴权正门且参数透传() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), updateService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(updateService.assignGroup(List.of(11L, 12L), 3L)).thenReturn(2);
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest body =
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
body.setIds(List.of(11L, 12L));
body.setGroupId(3L);
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
// 公共库写侧没有公司维度(结构判据支反向钉 company_id/DataReadScope 不得回流)。
verify(updateService).assignGroup(List.of(11L, 12L), 3L);
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
assertEquals(2, response.getData(), "回执=实际更新的行数");
// 业务失败(目标分类不存在)文案原样透出,不吞。
when(updateService.assignGroup(List.of(11L), 404L))
.thenThrow(new BusinessException("分类不存在,请刷新分类后重试"));
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest ghostBody =
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
ghostBody.setIds(List.of(11L));
ghostBody.setGroupId(404L);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(ghostBody, request));
assertTrue(ex.getMessage().contains("分类不存在"));
}
@Test
void 详情解析attr_json的tabs映射成attrGroups() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductImageMapper imageMapper = mock(JdProductImageMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, imageMapper,
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper, imageMapper);
JdProductEntity row = productEntity(11L);
// 客户端实拍契约:tabs[{tab, attrs[{key,label,value}]}];value 允许数字型 JSON 值(转字符串)。
@@ -603,7 +687,7 @@ class AdminJdProductControllerTest {
image.setHeight(800);
when(imageMapper.selectList(any())).thenReturn(List.of(image));
JdProductDetailVo vo = service.detail(11L);
JdProductDetailVo vo = service.detail(11L, null);
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
@@ -626,15 +710,13 @@ class AdminJdProductControllerTest {
@Test
void 详情非法attr_json落空分组且原文兜底不抛500() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
// 形状一:非法 JSON(解析异常)。
JdProductEntity broken = productEntity(11L);
broken.setAttrJson("{\"tabs\": [broken");
when(mapper.selectById(11L)).thenReturn(broken);
JdProductDetailVo brokenVo = service.detail(11L);
JdProductDetailVo brokenVo = service.detail(11L, null);
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
@@ -642,7 +724,7 @@ class AdminJdProductControllerTest {
JdProductEntity foreign = productEntity(11L);
foreign.setAttrJson("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}");
when(mapper.selectById(11L)).thenReturn(foreign);
JdProductDetailVo foreignVo = service.detail(11L);
JdProductDetailVo foreignVo = service.detail(11L, null);
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
"未识别属性不丢弃:原文兜底透出(AC-7)");
@@ -651,7 +733,7 @@ class AdminJdProductControllerTest {
JdProductEntity blank = productEntity(11L);
blank.setAttrJson(null);
when(mapper.selectById(11L)).thenReturn(blank);
JdProductDetailVo blankVo = service.detail(11L);
JdProductDetailVo blankVo = service.detail(11L, null);
assertTrue(blankVo.getAttrGroups().isEmpty());
assertNull(blankVo.getAttrJsonRaw());
}
@@ -659,11 +741,8 @@ class AdminJdProductControllerTest {
@Test
void 详情下发SKU矩阵_销售属性JSON解析成键值对() {
JdProductMapper mapper = mock(JdProductMapper.class);
com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper skuMapper =
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper,
mock(JdProductImageMapper.class), skuMapper,
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductSkuMapper skuMapper = mock(JdProductSkuMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class), skuMapper);
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
@@ -683,7 +762,7 @@ class AdminJdProductControllerTest {
brokenJson.setSaleAttrsJson("[{\"name\":");
when(skuMapper.selectList(any())).thenReturn(List.of(first, brokenJson));
JdProductDetailVo vo = service.detail(11L);
JdProductDetailVo vo = service.detail(11L, null);
assertEquals(2, vo.getSkus().size(), "京麦那 12 行矩阵按入库行下发(抽屉渲染的唯一来源)");
JdProductDetailVo.SkuVo sku = vo.getSkus().get(0);
@@ -702,55 +781,158 @@ class AdminJdProductControllerTest {
@Test
void 详情按公共库直取_缺失按不存在拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
// 公共库(2026-11-15 用户定案):详情没有公司维度,别家公司时代的行照样可读。
JdProductEntity row = productEntity(11L);
row.setCompanyId(6L);
when(mapper.selectById(11L)).thenReturn(row);
assertNotNull(service.detail(11L));
assertNotNull(service.detail(11L, null));
// 行不存在 ⇒ 按「商品不存在」拒绝。
when(mapper.selectById(11L)).thenReturn(null);
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L));
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, null));
assertTrue(ex.getMessage().contains("商品不存在"));
// id 非法同样拒绝。
assertThrows(BusinessException.class, () -> service.detail(0L));
assertThrows(BusinessException.class, () -> service.detail(0L, null));
}
@Test
void 列表行分组名批量补齐且读不到不猜() {
void 列表行分类名按当前分组批量补齐且读不到不猜() {
JdProductMapper mapper = mock(JdProductMapper.class);
com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper groupMapper =
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
groupMapper);
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
JdProductEntity grouped = productEntity(1L);
grouped.setGroupId(3L);
JdProductEntity categorized = productEntity(1L);
JdProductEntity missing = productEntity(2L);
missing.setGroupId(99L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(grouped, missing));
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity group =
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity();
group.setId(3L);
group.setName("秋冬款");
when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group));
anyLong(), anyInt())).thenReturn(List.of(categorized, missing));
when(assignMapper.selectList(any())).thenReturn(List.of(
assign(1L, GROUP_ID, 3L), assign(2L, GROUP_ID, 99L)));
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(3L);
category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null);
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
verify(groupMapper, times(1)).selectBatchIds(any());
assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行");
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分类已删=不猜名字(铁律 30),前端展示 -");
verify(assignMapper, times(1)).selectList(any());
verify(categoryMapper, times(1)).selectBatchIds(any());
}
@Test
void 列表无当前分组时分类列全空且不发归属查询() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), mock(JdProductGroupMapper.class), assignMapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null);
assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)");
assertNull(vo.getItems().get(0).getGroupName());
verify(assignMapper, never()).selectList(any());
}
@Test
void 详情分类按当前分组取_别的组归类不可见() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
// 本组(10)没归类:detail 的 selectOne 回 null ⇒ 分类字段空。
when(assignMapper.selectOne(any())).thenReturn(null);
JdProductDetailVo untouched = service.detail(11L, GROUP_ID);
assertNull(untouched.getGroupId(), "本组没归类=未分类,不拿别组的归属顶上");
assertNull(untouched.getGroupName());
// 本组归类到 3:取到分类名。
when(assignMapper.selectOne(any())).thenReturn(assign(11L, GROUP_ID, 3L));
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(3L);
category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductDetailVo categorized = service.detail(11L, GROUP_ID);
assertEquals(3L, categorized.getGroupId());
assertEquals("秋冬款", categorized.getGroupName());
}
// ---------------------------------------------------------------- 助手
/** 查询服务夹具:默认四个从属 mapper 全 mock,只有 assign mapper 可注入。 */
private static JdProductQueryService queryService(JdProductMapper mapper) {
return queryService(mapper, mock(JdProductImageMapper.class), mock(JdProductSkuMapper.class),
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper) {
return queryService(mapper, imageMapper, mock(JdProductSkuMapper.class),
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
JdProductSkuMapper skuMapper) {
return queryService(mapper, imageMapper, skuMapper,
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
JdProductSkuMapper skuMapper, JdProductGroupMapper categoryMapper,
JdProductGroupAssignMapper assignMapper) {
return new JdProductQueryService(mapper, imageMapper, skuMapper, categoryMapper, assignMapper);
}
/** 可写作用域(组长/公司超管/平台超管同形:可见组=可写组)。 */
private static JdCategoryScopeService.JdCategoryScope writableScope(long groupId, long companyId) {
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
List.of(groupId), List.of(groupId),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", true)));
}
/** 只读作用域(组内普通号:可见不可写)。 */
private static JdCategoryScopeService.JdCategoryScope readOnlyScope(long groupId, long companyId) {
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
List.of(groupId), List.of(),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
}
private static ShopManageGroupEntity shopGroup(long id, long companyId) {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
group.setCompanyId(companyId);
group.setGroupName("默认组");
return group;
}
private static JdProductGroupEntity category(long id, long ownerGroupId) {
JdProductGroupEntity entity = new JdProductGroupEntity();
entity.setId(id);
entity.setOwnerGroupId(ownerGroupId);
entity.setCompanyId(COMPANY_ID);
entity.setName("分类-" + id);
return entity;
}
private static JdProductGroupAssignEntity assign(long productId, long ownerGroupId, long categoryId) {
JdProductGroupAssignEntity entity = new JdProductGroupAssignEntity();
entity.setProductId(productId);
entity.setOwnerGroupId(ownerGroupId);
entity.setCategoryId(categoryId);
return entity;
}
/** 列表/详情用例共用的商品行夹具:归属公司 5,主字段齐备便于按字段对撞。 */
private static JdProductEntity productEntity(long id) {
JdProductEntity entity = new JdProductEntity();
@@ -2,7 +2,9 @@ package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdCollectBoardService;
import com.nanri.aiimage.modules.jd.service.JdCollectTaskService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
@@ -32,30 +34,38 @@ import static org.mockito.Mockito.when;
* 用户侧「店铺分类」只读端点(2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」)。
*
* <p>「获取店铺数据」页把管理员在后管京东数据库建的分类展示给普通账号:GET /api/jd-collect/groups,
* 与 categories 端点同形(登录用户即可读、fail-closed 401;分组全平台一份、无公司维度)。
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。结构判据(照
* {@code AdminJdProductControllerTest} 双形态的第一半)+行为样本(200 信封装 list、鉴权先过)。</p>
* 与 categories 端点同形(登录用户即可读、fail-closed 401)。
* <b>V203 起按数据权限分组隔离</b>:只下发登录用户<b>可见组</b>的分类(「不同组不能看到跨组的分类」),
* 收窄由 {@code JdCategoryScopeService.resolveByUserId} 出,本端点不自己判角色。
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。</p>
*/
class JdCollectGroupsEndpointTest {
private static final Path CONTROLLER = Path.of("").toAbsolutePath()
.resolve("src/main/java/com/nanri/aiimage/modules/jd/controller/JdCollectController.java");
private static final long USER_ID = 1L;
private static final long GROUP_ID = 10L;
@Test
void 结构判据_groups端点只读且复用分组服务公共口径() throws IOException {
void 结构判据_groups端点只读且按可见组收窄() throws IOException {
assertTrue(Files.exists(CONTROLLER), "控制器必须落在 " + CONTROLLER);
String source = Files.readString(CONTROLLER);
assertTrue(source.contains("@GetMapping(\"/groups\")"),
"用户侧分类列表必须是 GET /groups(categories 同形)");
assertTrue(source.contains("jdProductGroupService.list()"),
"必须复用 JdProductGroupService.list()(与后管分组管理同一条读出口,不另造查询)");
assertTrue(source.contains("jdCategoryScopeService.resolveByUserId(userId)"),
"可见组必须由 JdCategoryScopeService 按登录用户解析(端点不自己判角色)");
assertTrue(source.contains("jdProductGroupService.listForGroups(scope.visibleGroupIds())"),
"必须按可见组取分类(listForGroups),不得退回 list() 全量下发"
+ "——否则普通号仍能看到别组的分类");
assertTrue(source.contains("adminAuthSupport.requireOwnershipUserId(httpRequest, null)"),
"登录用户即可读但必须 fail-closed:解析不出会话身份就 401(与 categories 同口径)");
}
@Test
void 行为样本_鉴权先过且200信封装分组全量() {
void 行为样本_鉴权先过且200信封只装可见组的分类() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
JdCollectController controller = new JdCollectController(
mock(JdCollectTaskService.class),
@@ -63,6 +73,7 @@ class JdCollectGroupsEndpointTest {
mock(JdResultIngestService.class),
mock(JdProductQueryService.class),
groupService,
scopeService,
mock(TaskHeartbeatService.class),
mock(TaskHeartbeatPositionService.class),
mock(TaskProgressOwnershipSupport.class),
@@ -72,9 +83,11 @@ class JdCollectGroupsEndpointTest {
JdProductGroupVo vo = new JdProductGroupVo();
vo.setId(7L);
vo.setName("ASSS");
vo.setOwnerGroupId(GROUP_ID);
vo.setProductCount(20L);
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(1L);
when(groupService.list()).thenReturn(List.of(vo));
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
when(scopeService.resolveByUserId(USER_ID)).thenReturn(scope(GROUP_ID));
when(groupService.listForGroups(List.of(GROUP_ID))).thenReturn(List.of(vo));
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
@@ -83,9 +96,44 @@ class JdCollectGroupsEndpointTest {
assertNotNull(response.getData());
assertEquals(1, response.getData().size());
assertEquals("ASSS", response.getData().get(0).getName());
assertEquals(GROUP_ID, response.getData().get(0).getOwnerGroupId());
assertEquals(20L, response.getData().get(0).getProductCount());
// 鉴权闸先行:解析不出会话身份就 401,读不到任何数据。
verify(authSupport).requireOwnershipUserId(same(request), isNull());
verify(groupService).list();
verify(scopeService).resolveByUserId(USER_ID);
verify(groupService).listForGroups(List.of(GROUP_ID));
}
@Test
void 行为样本_不属于任何分组时下发空列表() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
JdCollectController controller = new JdCollectController(
mock(JdCollectTaskService.class),
mock(JdCollectBoardService.class),
mock(JdResultIngestService.class),
mock(JdProductQueryService.class),
groupService,
scopeService,
mock(TaskHeartbeatService.class),
mock(TaskHeartbeatPositionService.class),
mock(TaskProgressOwnershipSupport.class),
authSupport);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
when(scopeService.resolveByUserId(USER_ID)).thenReturn(JdCategoryScopeService.JdCategoryScope.empty());
when(groupService.listForGroups(List.of())).thenReturn(List.of());
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
assertTrue(response.isSuccess());
assertTrue(response.getData().isEmpty(), "一个可见组都没有 ⇒ 空列表(不降级成全平台分类)");
verify(groupService).listForGroups(List.of());
}
private static JdCategoryScopeService.JdCategoryScope scope(long groupId) {
return new JdCategoryScopeService.JdCategoryScope(false, 5L, List.of(groupId), List.of(),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
}
}
@@ -0,0 +1,272 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。
*
* <p>四档矩阵:平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
* 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读;
* 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。
* 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、
* 写侧在「无可写组 / 多可写组未选 / 该组不可写 / 组行不存在」四种形状下的文案。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdCategoryScopeServiceTest {
private static final long USER_ID = 9L;
private static final long COMPANY_ID = 5L;
@Mock
private AdminAuthSupport adminAuthSupport;
@Mock
private DataReadScope dataReadScope;
@Mock
private AdminUserMapper adminUserMapper;
@Mock
private ShopManageGroupMapper shopManageGroupMapper;
@Mock
private CompanyMapper companyMapper;
@InjectMocks
private JdCategoryScopeService service;
// ---------------------------------------------------------------- 四档矩阵
@Test
void 平台超管_可见并可写全部公司全部组且组名带公司前缀() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
group(10L, 1L, "A组"), group(20L, 2L, "B组")));
CompanyEntity first = new CompanyEntity();
first.setId(1L);
first.setCompanyName("甲公司");
CompanyEntity second = new CompanyEntity();
second.setId(2L);
second.setCompanyName("乙公司");
when(companyMapper.selectBatchIds(any())).thenReturn(List.of(first, second));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.platformSuperAdmin()).isTrue();
assertThat(scope.visibleGroupIds()).containsExactly(10L, 20L);
assertThat(scope.writableGroupIds()).containsExactly(10L, 20L);
assertThat(scope.defaultGroupId()).isEqualTo(10L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("甲公司 / A组", "乙公司 / B组");
assertThat(scope.groups()).allMatch(JdCategoryGroupOptionVo::isEditable);
assertThat(scope.canRead(20L)).isTrue();
assertThat(scope.canWrite(20L)).isTrue();
}
@Test
void 公司超管_本公司全部组可读可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("company_super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectList(any())).thenReturn(List.of(
group(10L, COMPANY_ID, "A组"), group(11L, COMPANY_ID, "B组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.platformSuperAdmin()).isFalse();
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
assertThat(scope.writableGroupIds()).containsExactly(10L, 11L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("A组", "B组");
// 公司超管的公司维只用来取组,不随 scope 下发公司字段给前端(label 里已拼好)。
verify(companyMapper, never()).selectBatchIds(any());
}
@Test
void 组长_自己带的组可写_自己所属组的组长带的分组只读() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "自己的组")));
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(11L, COMPANY_ID, "上司的组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
assertThat(scope.writableGroupIds()).containsExactly(10L);
assertThat(scope.canRead(11L)).isTrue();
assertThat(scope.canWrite(11L)).isFalse();
}
@Test
void 普通号_可见同组长但零可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L);
assertThat(scope.writableGroupIds()).isEmpty();
assertThat(scope.groups()).singleElement()
.satisfies(option -> assertThat(option.isEditable()).isFalse());
}
@Test
void 不属于任何分组的账号_空作用域不报错() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).isEmpty();
assertThat(scope.defaultGroupId()).isNull();
assertThat(scope.groups()).isEmpty();
}
// ---------------------------------------------------------------- 入参收敛
@Test
void 读侧_缺省取默认分组且不可见组403() {
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(), List.of(10L, 11L));
assertThat(service.readGroupOrNull(scope, null)).isEqualTo(10L);
assertThat(service.readGroupOrNull(scope, 11L)).isEqualTo(11L);
assertThatThrownBy(() -> service.readGroupOrNull(scope, 20L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("无权查看该分组的分类");
// 空作用域:页面照常可用(商品全平台公共),分类列全空,不打 403。
assertThat(service.readGroupOrNull(JdCategoryScopeService.JdCategoryScope.empty(), null)).isNull();
}
@Test
void 写侧_无可写组拒绝_缺省收敛到当前分组() {
JdCategoryScopeService.JdCategoryScope readOnly = scope(List.of(10L), List.of(), List.of(10L));
assertThatThrownBy(() -> service.requireWritableGroup(readOnly, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("你还没有可管理的数据权限分组");
// 两个可写组 + 没带 ownerGroupId ⇒ 落到「当前分组」(下拉默认第一项=组名序首个)。
JdCategoryScopeService.JdCategoryScope twoGroups = scope(List.of(10L, 11L), List.of(10L, 11L),
List.of(10L, 11L));
when(shopManageGroupMapper.selectById(10L)).thenReturn(group(10L, COMPANY_ID, "A组"));
assertThat(service.requireWritableGroup(twoGroups, null).getId()).isEqualTo(10L);
// 明确选另一个也照办。
when(shopManageGroupMapper.selectById(11L)).thenReturn(group(11L, COMPANY_ID, "B组"));
assertThat(service.requireWritableGroup(twoGroups, 11L).getId()).isEqualTo(11L);
}
@Test
void 写侧_当前分组不可写且没指定时要求先选组() {
// 可见组的第一项(默认分组 10)是只读的上司组,可写的是 11/12 两个 ⇒ 不带 ownerGroupId 不能瞎猜。
// (只有一个可写组时不用选——组长那一档直接用它,见上一条用例。)
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L, 12L), List.of(11L, 12L),
List.of(10L, 11L, 12L));
assertThatThrownBy(() -> service.requireWritableGroup(scope, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要管理的分组");
}
@Test
void 写侧_不可写组与组行不存在分别拒绝() {
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(10L),
List.of(10L, 11L));
assertThatThrownBy(() -> service.requireWritableGroup(scope, 11L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("仅该分组的管理员可以修改它的分类");
// 作用域认为可写但组行已被删:明确拒绝(不静默落 0 号组)。
when(shopManageGroupMapper.selectById(10L)).thenReturn(null);
assertThatThrownBy(() -> service.requireWritableGroup(scope, 10L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分组不存在");
}
// ---------------------------------------------------------------- 用户端 / scope 回执
@Test
void 按uid解析_账号不存在按空作用域() {
when(adminUserMapper.selectById(USER_ID)).thenReturn(null);
assertThat(service.resolveByUserId(USER_ID).visibleGroupIds()).isEmpty();
assertThat(service.resolveByUserId(null).visibleGroupIds()).isEmpty();
assertThat(service.resolveByUserId(0L).visibleGroupIds()).isEmpty();
// null/0 直接回空,只有正数 uid 才查账号表。
verify(adminUserMapper, org.mockito.Mockito.times(1)).selectById(anyLong());
}
@Test
void scope回执_带平台超管标记与每组可写标记() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
JdCategoryScopeVo vo = service.scopeVo(operator);
assertThat(vo.isPlatformSuperAdmin()).isFalse();
assertThat(vo.getDefaultGroupId()).isEqualTo(10L);
assertThat(vo.getGroups()).singleElement().satisfies(option -> {
assertThat(option.getId()).isEqualTo(10L);
assertThat(option.getName()).isEqualTo("A组");
assertThat(option.isEditable()).isTrue();
});
}
// ---------------------------------------------------------------- 助手
private static AdminUserEntity user(long id, long companyId) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setCompanyId(companyId);
return user;
}
private static ShopManageGroupEntity group(long id, long companyId, String name) {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
group.setCompanyId(companyId);
group.setGroupName(name);
return group;
}
/** 直接构作用域(跳过解析):可见组 / 可写组 / 下拉项三者按入参给。 */
private static JdCategoryScopeService.JdCategoryScope scope(List<Long> visible, List<Long> writable,
List<Long> optionGroupIds) {
List<JdCategoryGroupOptionVo> options = optionGroupIds.stream()
.map(id -> new JdCategoryGroupOptionVo(id, "组" + id, "组" + id, writable.contains(id)))
.toList();
return new JdCategoryScopeService.JdCategoryScope(false, COMPANY_ID, visible, writable, options);
}
}
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
@@ -50,6 +51,8 @@ class JdCollectBoardServiceTest {
private JdProductImageMapper jdProductImageMapper;
@Mock
private JdProductSkuMapper jdProductSkuMapper;
@Mock
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
@Spy
private ObjectMapper objectMapper = new ObjectMapper();
@@ -73,6 +76,8 @@ class JdCollectBoardServiceTest {
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity.class);
}
private FileTaskEntity task(long id, long userId, String status) {
@@ -171,6 +176,7 @@ class JdCollectBoardServiceTest {
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务不存在");
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).delete(any());
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
}
@@ -187,7 +193,8 @@ class JdCollectBoardServiceTest {
service.deleteTask(88L, 7L);
// sku/image 子行 → 主行 → scope → 任务行,五次删除一次不落
// 归类归属(V203)→ sku/image 子行 → 主行 → scope → 任务行,六次删除一次不落
verify(jdProductGroupAssignMapper, times(1)).delete(any());
verify(jdProductSkuMapper, times(1)).delete(any());
verify(jdProductImageMapper, times(1)).delete(any());
verify(jdProductMapper, times(1)).delete(any());
@@ -4,9 +4,10 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
@@ -20,7 +21,6 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -33,78 +33,105 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
* v1.4 Phase 5(R4/AC-8)+V203:京东商品自定义分类业务规则(按数据权限分组归属)。
*
* <p>判据(2026-11-15 用户定案「分组和亚马逊功能一样」=全平台一份,V200 退键后的服务形状):
* 全局重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行(事务两步,AC-8,
* 且脱组谓词不带 company_id)、越界 id 操作按不存在拒绝、company_id 列读写两侧都不再引用
* (新行不带公司,DB DEFAULT 0 兜底)、productCount 读侧现算统计(分组下拉展示用)。</p>
* <p>判据(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类」):
* 分类归属一个数据权限分组({@code owner_group_id}),<b>同组内</b>重名拒绝(409,不同组可同名)、
* 删除只解挂归属行({@code biz_jd_product_group_assign})不删商品、商品数按归属表
* {@code category_id} 现算、越界 id 按不存在拒绝。<b>作用域(谁能读/写哪个组)不在本类</b>——
* 那是 {@code JdCategoryScopeServiceTest} 的事,本类只钉「按给定组取/写」的语义。</p>
*/
class JdProductGroupServiceTest {
private static final long GROUP_ID = 10L;
private static final long COMPANY_ID = 5L;
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
private final JdProductMapper productMapper = mock(JdProductMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
private final JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, assignMapper);
@BeforeAll
static void initTableInfo() {
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
// 探针要读 Lambda wrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
}
// ===================== 新建 =====================
@Test
void 新建重名拒绝且不落库() {
void 新建同组重名拒绝且不落库() {
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.create(" 秋冬款 ", 2));
() -> service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2));
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
assertTrue(ex.getMessage().contains("同名分类"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500(2026-11-15 起界面措辞「分类」)");
assertTrue(ex.getMessage().contains("本组已存在同名分类"),
"重名必须给可读文案并点名「本组」,不拿 DB 唯一键异常撞 500");
verify(groupMapper, never()).insert(any(JdProductGroupEntity.class));
}
@Test
void 新建成功落归一名与排序且不带公司() {
void 新建成功落归属分组与公司() {
when(groupMapper.selectCount(any())).thenReturn(0L);
when(groupMapper.insert(any(JdProductGroupEntity.class))).thenAnswer(invocation -> {
JdProductGroupEntity group = invocation.getArgument(0);
group.setId(9L);
JdProductGroupEntity category = invocation.getArgument(0);
category.setId(9L);
return 1;
});
Long id = service.create(" 秋冬款 ", 2);
Long id = service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2);
assertEquals(9L, id);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
JdProductGroupEntity saved = captor.getValue();
assertNull(saved.getCompanyId(), "公共库新行不带公司(实体字段不赋值,DB DEFAULT 0=平台公共)");
assertEquals(GROUP_ID, saved.getOwnerGroupId(), "必须落在当前数据权限分组上(跨组不可见)");
assertEquals(COMPANY_ID, saved.getCompanyId(), "公司随组落(唯一键 uk_company_owner_name 的左段)");
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
assertEquals(2, saved.getSortOrder());
// 重名查询必须是「同公司 + 同组」口径:不同公司/不同组可同名。
ArgumentCaptor<Wrapper<JdProductGroupEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectCount(wrapperCaptor.capture());
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
assertEquals(GROUP_ID, ((Number) whereEq.get("owner_group_id")).longValue(),
"重名查询必须钉 owner_group_id(同组才冲突)");
assertEquals(COMPANY_ID, ((Number) whereEq.get("company_id")).longValue(),
"重名查询必须钉 company_id(唯一键左段)");
}
@Test
void 新建无分组直接拒绝() {
BusinessException ex = assertThrows(BusinessException.class,
() -> service.create(null, COMPANY_ID, "秋冬款", null));
assertEquals(400, ex.getCode());
assertTrue(ex.getMessage().contains("请先选择分组再新建分类"));
verifyNoInteractions(groupMapper);
}
@Test
void 新建空名直接拒绝() {
BusinessException blankName = assertThrows(BusinessException.class,
() -> service.create(" ", null));
() -> service.create(GROUP_ID, COMPANY_ID, " ", null));
assertEquals(400, blankName.getCode());
verifyNoInteractions(groupMapper);
}
@Test
void 新建排序缺省归零() {
void 新建排序缺省归零且公司缺省按0() {
when(groupMapper.selectCount(any())).thenReturn(0L);
service.create("默认排序", null);
service.create(GROUP_ID, null, "默认排序", null);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
assertEquals(0, captor.getValue().getSortOrder(), "sortOrder 缺省 0(下拉按 sort_order, id 升序)");
assertEquals(0L, captor.getValue().getCompanyId(),
"公司为空按 0 落(唯一键非空列;组本身取自可写组,正常不会为空)");
}
// ===================== 改名 =====================
@@ -121,7 +148,7 @@ class JdProductGroupServiceTest {
@Test
void 改名重名拒绝且不落库() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
@@ -132,7 +159,7 @@ class JdProductGroupServiceTest {
@Test
void 改名成功带归一名与排序() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, " 新名 ", 7);
@@ -141,11 +168,13 @@ class JdProductGroupServiceTest {
verify(groupMapper).updateById(captor.capture());
assertEquals("新名", captor.getValue().getName());
assertEquals(7, captor.getValue().getSortOrder());
assertEquals(GROUP_ID, captor.getValue().getOwnerGroupId(),
"改名不得把归属组改走(沿用原行的 owner_group_id 查重名)");
}
@Test
void 改名排序不传保持原值() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, "只改名", null);
@@ -155,27 +184,21 @@ class JdProductGroupServiceTest {
assertEquals(3, captor.getValue().getSortOrder(), "sortOrder 不传=保持原值(改名不改排序)");
}
// ===================== 删除(AC-8 事务两步) =====================
// ===================== 删除(只解挂归属,不删商品) =====================
@Test
void 删除先把商品组置NULL再删分组行() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "秋冬款"));
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
void 删除只解挂归属行再删分类行_商品一个不删() {
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "秋冬款"));
when(assignMapper.delete(any())).thenReturn(3);
int detached = service.delete(1L);
assertEquals(3, detached, "返回实际脱组的商品行数(前端拿它做反馈,不猜)");
ArgumentCaptor<Wrapper<JdProductEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productMapper).update(any(), wrapperCaptor.capture());
// 置 NULL 语义必须落在 SET group_id=NULL(商品保留,脱组即「未分组」)。
var setValues = UpdateWrapperProbe.setValues(wrapperCaptor.getValue());
assertTrue(setValues.containsKey("group_id") && setValues.get("group_id") == null,
"删除分组必须把商品 group_id 置 NULL(SET group_id=NULL),不是删商品行:实得 " + setValues);
// 公共库:脱组谓词只限定该组,不带 company_id。
assertEquals(3, detached, "返回实际解挂的商品归属行数(前端拿它做反馈,不猜)");
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(assignMapper).delete(wrapperCaptor.capture());
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
assertTrue(!whereEq.containsKey("company_id"),
"分组公共化后脱组谓词不得再带 company_id:实得 " + whereEq);
assertEquals(1L, ((Number) whereEq.get("category_id")).longValue(),
"解挂谓词必须限定该分类(商品保留在公共库,回到未分类)");
verify(groupMapper).deleteById(1L);
}
@@ -184,56 +207,115 @@ class JdProductGroupServiceTest {
when(groupMapper.selectById(1L)).thenReturn(null);
assertThrows(BusinessException.class, () -> service.delete(1L));
verifyNoInteractions(productMapper);
verifyNoInteractions(assignMapper);
verify(groupMapper, never()).deleteById(anyLong());
}
@Test
void 删除分组不存在直接拒绝() {
when(groupMapper.selectById(404L)).thenReturn(null);
void 删除越界id直接拒绝() {
assertThrows(BusinessException.class, () -> service.delete(404L));
verifyNoInteractions(productMapper);
verifyNoInteractions(assignMapper);
}
// ===================== 列表(productCount 统计) =====================
// ===================== 列表(按组取 + productCount 统计) =====================
@Test
@SuppressWarnings("unchecked")
void 列表全平台一份不带公司谓词且productCount现算() {
JdProductGroupEntity first = groupEntity(2L, "晚出厂");
void 列表按当前分组取且productCount按归属表现算() {
JdProductGroupEntity first = categoryEntity(2L, "晚出厂");
first.setSortOrder(0);
JdProductGroupEntity second = groupEntity(1L, "早出厂");
JdProductGroupEntity second = categoryEntity(1L, "早出厂");
second.setSortOrder(1);
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
when(assignMapper.selectCount(any())).thenReturn(12L, 0L);
List<JdProductGroupVo> items = service.list();
List<JdProductGroupVo> items = service.list(GROUP_ID);
assertEquals(2, items.size());
assertEquals("晚出厂", items.get(0).getName(), "selectList 的排序由 wrapper 决定,服务不重排");
assertEquals(12L, items.get(0).getProductCount(), "productCount 用 JdProductMapper selectCount 现算");
assertEquals(0L, items.get(1).getProductCount(), "空组也是 0,不是 null(下拉展示口径)");
assertEquals(GROUP_ID, items.get(0).getOwnerGroupId(), "归属组随行下发(前端按它锁分组)");
assertEquals(12L, items.get(0).getProductCount(),
"productCount 按归属表 category_id 现算(同一商品可在别组另归一类,这里只数本分类)");
assertEquals(0L, items.get(1).getProductCount(), "空分类也是 0,不是 null(下拉展示口径)");
assertEquals(1, items.get(1).getSortOrder());
verify(productMapper, times(2)).selectCount(any());
verify(assignMapper, times(2)).selectCount(any());
assertNotNull(items.get(0).getCreatedAt());
// 公共库:列表 wrapper 不带 company_id 谓词(历史行的 company_id 只是溯源标记)。
// 按组取:wrapper 钉 owner_group_id(.in 谓词,取值从参数表取证),且不再按 company_id 过滤。
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectList(captor.capture());
assertTrue(!captor.getValue().getSqlSegment().contains("company_id"),
"分组列表不得再按公司过滤(2026-11-15 公共化):实得 " + captor.getValue().getSqlSegment());
assertEquals(List.of(GROUP_ID), inParams(captor.getValue()),
"列表必须只取当前分组的分类(跨组不可见)");
assertTrue(!captor.getValue().getSqlSegment().toLowerCase().contains("company"),
"列表不再按公司过滤(同一公司的组已由 owner_group_id 区分):实得 "
+ captor.getValue().getSqlSegment());
}
@Test
void 列表无分组上下文回空且不查库() {
assertTrue(service.list(null).isEmpty(), "没有当前分组=空列表(页面分类列全空,不打 403)");
assertTrue(service.list(0L).isEmpty());
verifyNoInteractions(groupMapper);
verifyNoInteractions(assignMapper);
}
@Test
void 多组并集取分类_空清单不生成IN查询() {
JdProductGroupEntity row = categoryEntity(2L, "晚出厂");
when(groupMapper.selectList(any())).thenReturn(List.of(row));
when(assignMapper.selectCount(any())).thenReturn(0L);
List<JdProductGroupVo> items = service.listForGroups(java.util.Arrays.asList(10L, 11L, 10L, null, 0L));
assertEquals(1, items.size(), "用户端一个普通号可能同时在多个组里:并集只读展示");
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectList(captor.capture());
String segment = captor.getValue().getSqlSegment();
assertTrue(segment.toUpperCase().contains(" IN "), "多组走 IN 谓词:实得 " + segment);
// 参数表是 HashMap,序不可依赖:按集合语义断言。
java.util.List<Object> inValues = inParams(captor.getValue());
assertEquals(2, inValues.size(), "10/11/10/null/0 ⇒ 去重去脏后只剩两个有效组:实得 " + inValues);
assertTrue(inValues.containsAll(List.of(10L, 11L)), "只留 10、11:实得 " + inValues);
assertTrue(service.listForGroups(List.of()).isEmpty(), "空清单直接回空,不生成 IN ()");
assertTrue(service.listForGroups(null).isEmpty());
}
// ---------------------------------------------------------------- 助手
private static JdProductGroupEntity groupEntity(long id, String name) {
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(id);
group.setCompanyId(5L);
group.setName(name);
group.setSortOrder(3);
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
return group;
private static JdProductGroupEntity categoryEntity(long id, String name) {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(id);
category.setOwnerGroupId(GROUP_ID);
category.setCompanyId(COMPANY_ID);
category.setName(name);
category.setSortOrder(3);
category.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
return category;
}
/**
* wrapper 参数表里的字面值(IN 集合按元素展开成多个 paramNameValuePairs 条目;
* 若某版 MP 把整个集合塞一个条目,这里按集合展开——两种形状都认)。
*
* <p>MP 的 SQL 段与参数表都是惰性构建:必须先触发 {@code getSqlSegment()},否则
* {@code paramNameValuePairs} 还是空表(原测试里那条「先触发再读」的注释同源)。</p>
*/
private static List<Object> inParams(Wrapper<?> wrapper) {
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
abstractWrapper.getSqlSegment();
}
List<Object> out = new java.util.ArrayList<>();
for (Object value : UpdateWrapperProbe.paramNameValuePairs(wrapper).values()) {
if (value == null) {
continue;
}
if (value instanceof java.util.Collection<?> collection) {
out.addAll(collection);
} else {
out.add(value);
}
}
return out;
}
}
@@ -6,12 +6,14 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
@@ -64,6 +66,8 @@ class JdProductUpdateServiceTest {
@Mock
private JdProductGroupMapper jdProductGroupMapper;
@Mock
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
@Mock
private OssStorageService ossStorageService;
private JdProductUpdateService service;
@@ -76,12 +80,13 @@ class JdProductUpdateServiceTest {
TableInfoHelper.initTableInfo(assistant, JdProductSkuEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductImageEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
}
@BeforeEach
void setUp() {
service = new JdProductUpdateService(jdProductMapper, jdProductSkuMapper,
jdProductImageMapper, jdProductGroupMapper, ossStorageService);
jdProductImageMapper, jdProductGroupMapper, jdProductGroupAssignMapper, ossStorageService);
ReflectionTestUtils.setField(service, "bucket", "jd-products");
ReflectionTestUtils.setField(service, "keyPrefix", "jd-products/");
}
@@ -104,7 +109,6 @@ class JdProductUpdateServiceTest {
JdProductUpdateRequest body = new JdProductUpdateRequest();
body.setTitle(" 新标题 ");
body.setBrand(" 新品牌 ");
body.setGroupId(null);
return body;
}
@@ -160,78 +164,133 @@ class JdProductUpdateServiceTest {
}
@Test
void 分组必须存在_公共组无公司维度() {
void 编辑不再写分组列_分类只走弹窗归类() {
givenOwnedRow();
JdProductUpdateRequest body = mainFieldsOnly();
body.setGroupId(7L);
// 分组 2026-11-15 起全平台一份:别家时代建的组(company_id=99)照样能挂。
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(7L);
group.setCompanyId(99L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
assertThat(service.update(PRODUCT_ID, body)).isEqualTo(PRODUCT_ID);
// 分组不存在 ⇒ 拒绝且零写(2026-11-15 起界面措辞「分类」)。
JdProductUpdateRequest ghost = mainFieldsOnly();
ghost.setGroupId(404L);
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
assertThatThrownBy(() -> service.update(PRODUCT_ID, ghost))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分类不存在");
// update 只剩成功挂组那 1 次:ghost 分支零写点(同用例前半段已成功写过一次,不能按 never 数)。
verify(jdProductMapper, org.mockito.Mockito.times(1)).update(isNull(), any(Wrapper.class));
}
service.update(PRODUCT_ID, mainFieldsOnly());
// ---------- 批量归类(店铺分类弹窗,2026-11-15) ----------
/** 取批量归类落下的 SET 键值对(paramNameValuePairs),供断言 groupId/ids 落值。 */
@SuppressWarnings("unchecked")
private Map<String, Object> capturedAssignValues() {
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
return (Map<String, Object>) ReflectionTestUtils.getField(wrapper, "paramNameValuePairs");
String sqlSet = ((LambdaUpdateWrapper<JdProductEntity>) captor.getValue()).getSqlSet();
// V203:分类不在编辑面(归属在 biz_jd_product_group_assign 的按组行上,
// 商品行的 group_id 列已停用),编辑保存一个字都不许往那一列写。
assertThat(sqlSet).doesNotContain("group_id");
// 也不再去查分类表(旧「分组必须存在」校验已随分类移出编辑面撤掉)。
verify(jdProductGroupMapper, never()).selectById(any());
}
// ---------- 批量归类(店铺分类弹窗;V203 起按组写归属表,不置锁) ----------
/** 归属表插入行的夹具校验:一次 insert 一行 (product_id, owner_group_id)。 */
private java.util.List<JdProductGroupAssignEntity> capturedAssignInserts() {
ArgumentCaptor<JdProductGroupAssignEntity> captor =
ArgumentCaptor.forClass(JdProductGroupAssignEntity.class);
verify(jdProductGroupAssignMapper, org.mockito.Mockito.atLeastOnce()).insert(captor.capture());
return captor.getAllValues();
}
@Test
void 批量归类成功_置分类并落人工编辑锁() {
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(7L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(3);
void 批量归类写归属表_一组一商品一行且不置人工锁() {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(7L);
category.setOwnerGroupId(10L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of());
when(jdProductGroupAssignMapper.insert(any(JdProductGroupAssignEntity.class))).thenReturn(1);
// 入参含重复 id:去重后 1/2/3 三行
int updated = service.assignGroup(List.of(1L, 1L, 2L, 3L), 7L);
// 入参含重复 id:去重后 1/2 两行
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L, 1L, 2L), 7L, 99L);
assertThat(updated).isEqualTo(3);
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
// SET 段必须同时带 group_id 与 manual_locked(归类即人工干预:置锁后覆盖清理不再删行)
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
// WHERE 段(IN ids)惰性构参:先触发 getSqlSegment 再读参数表,IN 值才落进 paramNameValuePairs。
wrapper.getSqlSegment();
Map<String, Object> values = capturedAssignValues();
assertThat(values.values()).contains(7L, 1L, 2L, 3L);
assertThat(written).isEqualTo(2);
java.util.List<JdProductGroupAssignEntity> inserted = capturedAssignInserts();
assertThat(inserted).hasSize(2);
assertThat(inserted.get(0).getProductId()).isEqualTo(1L);
assertThat(inserted.get(0).getOwnerGroupId()).isEqualTo(10L);
assertThat(inserted.get(0).getCategoryId()).isEqualTo(7L);
assertThat(inserted.get(0).getCompanyId()).isEqualTo(COMPANY_ID);
assertThat(inserted.get(0).getCreatedBy()).isEqualTo(99L);
assertThat(inserted.get(1).getProductId()).isEqualTo(2L);
// 归类不再置人工编辑锁(2026-11-16 用户拍板):商品行一个字节都不写,
// 锁只会让共享行的价格/库存对所有组停更(分类不在商品行上,采集冲不掉它)。
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
verify(jdProductGroupAssignMapper, never()).update(any(), any());
}
@Test
void 批量归类目标分类不存在拒绝且零写() {
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
void 批量归类换组改归属行不新增() {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(7L);
category.setOwnerGroupId(10L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
JdProductGroupAssignEntity existing = new JdProductGroupAssignEntity();
existing.setProductId(1L);
existing.setOwnerGroupId(10L);
existing.setCategoryId(3L);
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of(existing));
when(jdProductGroupAssignMapper.update(any(), any())).thenReturn(1);
assertThatThrownBy(() -> service.assignGroup(List.of(1L, 2L), 404L))
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L), 7L, 99L);
assertThat(written).isEqualTo(1);
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductGroupAssignMapper).update(isNull(), captor.capture());
assertThat(com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(captor.getValue()))
.containsEntry("category_id", 7L);
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
}
@Test
void 批量归类目标分类不存在或跨组拒绝且零写() {
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L, 2L), 404L, 99L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分类不存在");
// 分类存在于别的组(ownerGroupId=20)⇒ 403,不许跨组归类。
JdProductGroupEntity foreign = new JdProductGroupEntity();
foreign.setId(8L);
foreign.setOwnerGroupId(20L);
when(jdProductGroupMapper.selectById(8L)).thenReturn(foreign);
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L), 8L, 99L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("该分类不属于当前分组");
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductGroupAssignMapper, never()).update(any(), any());
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 批量归类空清单与超上限可读拒绝() {
assertThatThrownBy(() -> service.assignGroup(List.of(), null))
void 移出分类_删本组归属行且商品行不动() {
when(jdProductGroupAssignMapper.delete(any())).thenReturn(2);
int removed = service.assignGroup(10L, COMPANY_ID, List.of(5L, 6L), null, 99L);
assertThat(removed).isEqualTo(2);
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductGroupAssignMapper).delete(captor.capture());
var whereEq = com.nanri.aiimage.testutil.UpdateWrapperProbe.whereEq(captor.getValue());
assertThat(((Number) whereEq.get("owner_group_id")).longValue()).isEqualTo(10L);
// 只删本组、只删勾选行:IN 集合按元素落参数表(MP 逐个 formatParam),取值逐一取证。
assertThat(captor.getValue().getSqlSegment().toUpperCase()).contains(" IN ");
java.util.List<Object> params = new java.util.ArrayList<>(
com.nanri.aiimage.testutil.UpdateWrapperProbe
.paramNameValuePairs(captor.getValue()).values());
assertThat(params).contains(10L).contains(5L).contains(6L);
// 移出分类不查分类表、不写商品行。
verify(jdProductGroupMapper, never()).selectById(any());
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 批量归类空清单超上限与无当前分组可读拒绝() {
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要归类的商品");
assertThatThrownBy(() -> service.assignGroup(List.of(0L, -1L), null))
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(0L, -1L), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要归类的商品");
@@ -239,28 +298,19 @@ class JdProductUpdateServiceTest {
for (long i = 1; i <= 201; i++) {
tooMany.add(i);
}
assertThatThrownBy(() -> service.assignGroup(tooMany, null))
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, tooMany, null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("单次最多归类 200");
// 没有「当前分组」就没有归属可写:403 点名先选组(V203)。
assertThatThrownBy(() -> service.assignGroup(null, COMPANY_ID, List.of(1L), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择分组再归类");
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 移出分类_groupId置空仍落人工编辑锁() {
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(2);
int updated = service.assignGroup(List.of(5L, 6L), null);
assertThat(updated).isEqualTo(2);
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
// groupId=null 也显式落 SET(group_id=NULL=回到未分类),锁照落。
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
// 移出分类没有目标组:不查分组表。
verify(jdProductGroupMapper, never()).selectById(any());
}
@Test
void 属性重建只覆写tabs段其余顶层键保留() {
givenOwnedRow();