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