feat(jd-database): v1.7 对齐原型后端半边——V214 店铺名单+合并搜索/价格区间/店铺谓词+CSV 导出

This commit is contained in:
2026-11-21 16:30:21 +08:00
parent 9eb42fe16a
commit 085c285446
21 changed files with 1313 additions and 105 deletions
@@ -7,8 +7,10 @@ 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.support.DownloadHeaderUtil;
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.JdProductExportRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDeleteVo;
@@ -31,7 +33,9 @@ import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -43,7 +47,9 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
@@ -75,10 +81,13 @@ import java.util.List;
* 「超管+管理员都可以,只有普通员工不能」,见 {@code requireJdProductWrite}),
* 写侧端点的 company_id 传参已随 2026-11-15 公共化摘除。</p>
*
* <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
* {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。店铺筛选参数
* {@code shop_name} 同日客户口径「店铺不需要」同窗撤掉(前端筛选框与列下线;DB 列
* {@code biz_jd_product.shop_name} 与详情/回传链不动)。</p>
* <p><b>v1.7(2026-11-21 对齐原型《商品数据商城》,用户拍板)</b>:恢复 CSV 导出
* {@code POST /export}(按勾选 id,读闸 requireJdAccess,UTF-8 BOM+中文表头);
* 新增合并搜索 {@code keyword}(product_code OR title,OR 语义必须后端做)、价格区间
* {@code min_price}/{@code max_price}(商品区间完全落在筛选区间内);店铺过滤
* {@code shop_name} 随「店铺名单维度完整对齐」复活——精确 eq 配合 group_id(点店铺=
* 该分类归属 ∩ 该店铺;2026-11-15「店铺不需要」撤掉的是筛选框,本次随名单维度回来,
* 旧口径注释的历史事实保留在 git)。{@code sale_status} 维持撤掉。</p>
*
* <p><b>分类并入类目(2026-11-16 用户口径「分类不要了,全部整合到类目里」)</b>:
* 分页查询的 {@code ungrouped}/{@code grouped}(分类状态档)整批撤掉;独立「分类」筛选框
@@ -94,6 +103,8 @@ public class AdminJdProductController {
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
/** 导出文件名时间戳(外观专利导出同款:分钟级,ASCII 下划线文件名由 DownloadHeaderUtil 兜)。 */
private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
private final JdProductQueryService jdProductQueryService;
private final JdProductDeleteService jdProductDeleteService;
@@ -112,12 +123,22 @@ public class AdminJdProductController {
public ApiResponse<JdProductPageVo> page(
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
@Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
@Parameter(description = "商品编码(包含匹配;旧参数保留兼容,前端单搜索框已停发)")
@RequestParam(name = "product_code", required = false) String productCode,
@Parameter(description = "标题关键词(包含匹配;旧参数保留兼容,前端单搜索框已停发)")
@RequestParam(name = "title_keyword", required = false) String titleKeyword,
@Parameter(description = "合并搜索词(v1.7 单搜索框:商品编码 OR 标题,OR 语义必须后端做)")
@RequestParam(name = "keyword", required = false) String keyword,
@Parameter(description = "类目(京麦类目名,多值 IN;2026-11-18 支持选一级/二级类目——"
+ "前端把选中节点展开为其子树全部类目名,用重复 category 参数下发,单值形状照常工作)")
@RequestParam(name = "category", required = false) List<String> categories,
@Parameter(description = "自定义分类 id(类目面板「自定义分类」选中驱动)") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "店铺名精确过滤(v1.7 随店铺名单维度复活:点店铺=该分类归属 ∩ 该店铺)")
@RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "价格下限(商品 price_min >= 该值)")
@RequestParam(name = "min_price", required = false) BigDecimal minPrice,
@Parameter(description = "价格上限(商品 price_max <= 该值)")
@RequestParam(name = "max_price", required = false) BigDecimal maxPrice,
@Parameter(description = "当前数据权限分组 id(分类列/分类筛选按它取;缺省=作用域默认分组)")
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
@Parameter(description = "同步开始时间(包含,ISO datetime)")
@@ -138,8 +159,28 @@ public class AdminJdProductController {
requireVisibleCategory(scope, groupId);
}
return ApiResponse.success(jdProductQueryService.page(page, pageSize,
productCode, titleKeyword, categories, groupId, syncedFrom, syncedTo, classified,
scopedOwnerGroupId));
keyword, productCode, titleKeyword, categories, groupId, shopName, minPrice, maxPrice,
syncedFrom, syncedTo, classified, scopedOwnerGroupId));
}
@PostMapping("/export")
@Operation(summary = "导出勾选商品 CSV(v1.7 恢复,2026-11-21 拍板「只恢复 CSV」)",
description = "按勾选 id 导出(上限 1000,超限整批拒绝不静默截断);"
+ "UTF-8 带 BOM + 中文表头(Excel 双击直开不乱码),列=商品编码/标题/价格下限/价格上限/"
+ "总库存/SKU数/信息分/品牌/货号/店铺/类目/状态/同步时间/主图。"
+ "导出属读行为:走 requireJdAccess 菜单正门,不走商品行写闸。")
public ResponseEntity<byte[]> export(
@Valid @RequestBody JdProductExportRequest body,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
byte[] bytes = jdProductQueryService.exportCsv(body.getIds());
log.info("[jd-product] 导出CSV operatorId={} requested={}", operator.id(), body.getIds().size());
String filename = "京东数据库-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".csv";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
.contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
.contentLength(bytes.length)
.body(bytes);
}
@GetMapping("/categories")
@@ -6,10 +6,13 @@ 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.JdGroupShopAddShopsRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdGroupShopRenameShopRequest;
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.JdGroupShopService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.swagger.v3.oas.annotations.Operation;
@@ -21,6 +24,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
@@ -32,7 +36,8 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后管「京东数据库」分类管理(v1.4 Phase 5,R4;V203 改按数据权限分组归属)。
* 后管「京东数据库」分类管理(v1.4 Phase 5,R4;V203 改按数据权限分组归属;
* v1.7 加分类店铺名单五条端点)。
*
* <p>归属口径(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类,
* 同组普通号只读」):一行分类属于<b>一个数据权限分组</b>({@code biz_shop_manage_group}),
@@ -40,25 +45,30 @@ import java.util.List;
* ①把请求里的 {@code owner_group_id} 收敛成「当前分组」;②写端点校验该组可写。</p>
*
* <ul>
* <li>读(列表 / 作用域):拿到本页菜单权限即可,只能看自己可见组(本组普通号也能看);</li>
* <li>写(新建/改名/删除):本组管理员、公司超管(本公司全部组)、平台超管(全部组);
* 普通号 403。</li>
* <li>读(列表 / 作用域 / 分类名单 / 可添加候选):拿到本页菜单权限即可,
* 只能看自己可见组(本组普通号也能看);</li>
* <li>写(分类新建/改名/删除;名单添加/移除/改名):本组管理员、公司超管(本公司全部组)、
* 平台超管(全部组);普通号 403。</li>
* </ul>
*
* <p>删除分类不删商品:只删该分类的归类归属行({@code biz_jd_product_group_assign}),
* 商品行留在公共库里(见 {@link JdProductGroupService#delete})。</p>
* <p>店铺名单(V214,2026-11-21 拍板「完整对齐」原型《商品数据商城》):名单挂在分类下,
* 读走 canRead(按分类归属组)、写走 canWrite——与分类本身同一道闸。名单改名只更新名单表
* (商品归类不带店铺维,无原型 assignment 同步链)。删除分类不删商品:只删该分类的归类
* 归属行({@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 = "京东商品自定义分类:按数据权限分组隔离,组内管理员可新建/改名/删除,删除不删商品(只解挂归属);分类下可挂店铺名单(v1.7)。")
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 JdGroupShopService jdGroupShopService;
private final JdCategoryScopeService jdCategoryScopeService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@@ -142,6 +152,99 @@ public class AdminJdProductGroupController {
}
}
// ---------------------------------------------------------------- 店铺名单(V214,v1.7)
@GetMapping("/{id}/shops")
@Operation(summary = "分类店铺名单", description = "该分类下的店铺名清单(shop_name 升序);"
+ "分类必须在本账号可见组内,越组 403。")
public ApiResponse<List<String>> listShops(
@Parameter(description = "分类 id") @PathVariable("id") Long id,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
requireReadableCategory(scope, jdProductGroupService.requireCategory(id).getOwnerGroupId());
return ApiResponse.success(jdGroupShopService.listShops(id));
}
@PostMapping("/{id}/shops")
@Operation(summary = "批量添加店铺到分类名单", description = "弹窗勾选候选+手输自定义项合并下发;"
+ "服务侧 trim/去空/去重/上限 100,INSERT IGNORE 幂等跳过已存在的行,"
+ "返回实际新增行数(全重复=0 不报错)。非本组管理员 403。")
public ApiResponse<Integer> addShops(
@Parameter(description = "分类 id") @PathVariable("id") Long id,
@Valid @RequestBody JdGroupShopAddShopsRequest body,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
requireWritableCategory(scope, ownerGroupId);
int added = jdGroupShopService.addShops(id, body.getShopNames(), operator.id());
log.info("[jd-group-shop] 添加店铺 operatorId={} categoryId={} requested={} added={}",
operator.id(), id, body.getShopNames().size(), added);
return ApiResponse.success(added);
}
@DeleteMapping("/{id}/shops")
@Operation(summary = "移除分类名单中的店铺", description = "删 (分类, 店铺名) 那一行名单;"
+ "该分类下不存在此店铺按业务错误拒绝。非本组管理员 403。")
public ApiResponse<Integer> removeShop(
@Parameter(description = "分类 id") @PathVariable("id") Long id,
@Parameter(description = "店铺名(精确)") @RequestParam(name = "shop_name") String shopName,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
requireWritableCategory(scope, ownerGroupId);
int deleted = jdGroupShopService.removeShop(id, shopName);
log.info("[jd-group-shop] 移除店铺 operatorId={} categoryId={} shopName={}",
operator.id(), id, shopName);
return ApiResponse.success(deleted);
}
@PatchMapping("/{id}/shops/rename")
@Operation(summary = "改名分类名单中的店铺", description = "老名必须在该分类名单里,"
+ "新名同分类查重 409;名单改名只更新名单表(商品归类不带店铺维)。非本组管理员 403。")
public ApiResponse<Boolean> renameShop(
@Parameter(description = "分类 id") @PathVariable("id") Long id,
@Valid @RequestBody JdGroupShopRenameShopRequest body,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
requireWritableCategory(scope, ownerGroupId);
jdGroupShopService.renameShop(id, body.getOldName(), body.getNewName());
log.info("[jd-group-shop] 店铺改名 operatorId={} categoryId={} old={} new={}",
operator.id(), id, body.getOldName(), body.getNewName());
return ApiResponse.success(Boolean.TRUE);
}
@GetMapping("/shops/available")
@Operation(summary = "可添加的店铺候选", description = "biz_jd_product.shop_name DISTINCT +"
+ " 关键词包含匹配 + 排除指定分类已有名单(exclude_category_id);limit ≤ 200。"
+ "商品是全平台公共的,候选同样全平台去重(不按分组收窄)。")
public ApiResponse<List<String>> availableShops(
@Parameter(description = "关键词(店铺名包含匹配)")
@RequestParam(name = "keyword", required = false) String keyword,
@Parameter(description = "排除该分类已有名单的分类 id")
@RequestParam(name = "exclude_category_id", required = false) Long excludeCategoryId,
@Parameter(description = "返回条数上限(≤200,缺省 200)")
@RequestParam(name = "limit", required = false) Integer limit,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
if (excludeCategoryId != null && excludeCategoryId > 0) {
requireReadableCategory(scope, jdProductGroupService.requireCategory(excludeCategoryId).getOwnerGroupId());
}
return ApiResponse.success(jdGroupShopService.availableShops(keyword, excludeCategoryId, limit));
}
/** 名单读闸:分类必须在本账号可见组内(同组普通号能看名单,越组 403)。 */
private void requireReadableCategory(JdCategoryScopeService.JdCategoryScope scope, Long ownerGroupId) {
if (!scope.canRead(ownerGroupId)) {
throw new BusinessException(403, "无权查看该分组的分类");
}
}
private RequestOperator requireJdAccess(HttpServletRequest request) {
AdminUserEntity operator = resolveOperator(request);
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
@@ -0,0 +1,29 @@
package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdGroupShopEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 京东数据库分类店铺名单(biz_jd_group_shop,V214)数据访问口。
*
* <p>单表 CRUD 走 BaseMapper + wrapper(SqlLayering 惯例);批量添加是唯一一条
* 自定义 SQL,落 {@code mapper/jd/JdGroupShopMapper.xml}(铁律 1)——
* {@code INSERT IGNORE} 靠唯一键 {@code uk_category_shop} 幂等跳过已存在的行,
* 返回实际新增行数(调用方拿它做「新增 N 家」的反馈,不猜)。</p>
*/
@Mapper
public interface JdGroupShopMapper extends BaseMapper<JdGroupShopEntity> {
/**
* 批量添加店铺名单(INSERT IGNORE):同名重复、与库中已有的 (categoryId, shopName)
* 撞唯一键的行一律跳过、不报错(原型 onConflictDoNothing 同语义)。
* 调用方保证名单非空、已去重——空集合不进本语句。
*/
int insertIgnoreBatch(@Param("categoryId") Long categoryId,
@Param("shopNames") List<String> shopNames,
@Param("createdBy") Long createdBy);
}
@@ -6,6 +6,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@@ -42,23 +43,34 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
/**
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
* (商品编码/标题关键词/类目/自定义分类/同步起止,全部 SQL 侧下推,铁律 20)。
* (合并搜索词/商品编码/标题关键词/类目/自定义分类/店铺/价格区间/同步起止,
* 全部 SQL 侧下推,铁律 20)。
* {@code keyword}(v1.7,2026-11-21 对齐原型合并搜索):product_code LIKE <b>OR</b>
* title LIKE——OR 语义必须后端做,前端单框停发旧两参数(旧参数保留兼容,仍 AND 生效)。
* {@code categories}(2026-11-18 一级/二级类目可选):类目名集合 IN,空/ null=不过滤;
* 选父级时由前端展开为子树类目名集合下发,单值=原 eq 形状。
* {@code shopName}(v1.7 恢复:2026-11-21 拍板「店铺名单维度完整对齐」)——
* 精确 eq,配合 {@code groupId} 组合(点店铺=该分类归属 ∩ 该店铺);
* 2026-11-15「店铺不需要」撤掉的是筛选框,本次随名单维度复活(DB 列一直在)。
* {@code minPrice}/{@code maxPrice}(v1.7 价格区间):商品区间完全落在筛选区间内
* ({@code price_min >= X AND price_max <= Y},采购直觉语义)。
* 公司维过滤已随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉
* (数据全平台公共);{@code groupId} 为空或 ≤0=不过滤该面;
* {@code ungrouped}/{@code grouped} 两档(未分类/已分类)已随同日口径
* 「分类不要了,全部整合到类目里」撤掉(独立「分类」筛选框前端下线,
* {@code groupId} 改由类目面板「自定义分类」选中驱动)。
* 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。
* {@code classified}+{@code ownerGroupId}(2026-11-17 用户口径「加个已分类和未分类的筛选」):
* 按 V203 归属表 EXISTS/NOT EXISTS 快筛分类状态,NULL=不过滤;与 11-16 撤掉的旧
* grouped/ungrouped(读已停用的 biz_jd_product.group_id 列)不是一回事。
*/
long countProducts(@Param("productCode") String productCode,
long countProducts(@Param("keyword") String keyword,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword,
@Param("categories") List<String> categories,
@Param("groupId") Long groupId,
@Param("shopName") String shopName,
@Param("minPrice") BigDecimal minPrice,
@Param("maxPrice") BigDecimal maxPrice,
@Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo,
@Param("classified") Boolean classified,
@@ -96,10 +108,14 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
* <p>{@code offset}/{@code limit} 必须是服务侧钳制后的值——page 钳制防
* {@code (page-1)*page_size} 溢出(铁律 15),mapper 不做第二次换算,避免两处各算各的。</p>
*/
List<JdProductEntity> selectProductPage(@Param("productCode") String productCode,
List<JdProductEntity> selectProductPage(@Param("keyword") String keyword,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword,
@Param("categories") List<String> categories,
@Param("groupId") Long groupId,
@Param("shopName") String shopName,
@Param("minPrice") BigDecimal minPrice,
@Param("maxPrice") BigDecimal maxPrice,
@Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo,
@Param("classified") Boolean classified,
@@ -107,6 +123,16 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
@Param("offset") long offset,
@Param("limit") int limit);
/**
* 店铺名单「可添加候选」(v1.7,添加店铺弹窗源):{@code biz_jd_product.shop_name}
* DISTINCT + like + 排除指定分类已有名单(NOT IN 下推,铁律 20),按店铺名升序。
* {@code limit} 必须是服务侧钳制后的值(≤ {@code JdGroupShopService.MAX_AVAILABLE_LIMIT}),
* mapper 不做第二次换算。
*/
List<String> selectDistinctShopNames(@Param("keyword") String keyword,
@Param("excludeNames") List<String> excludeNames,
@Param("limit") int limit);
/**
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
* 已落库行的 DISTINCT {@code category_path}(=京麦末级类目名)+ 行数,全平台公共去重
@@ -0,0 +1,20 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 分类店铺名单批量添加请求(v1.7):弹窗勾选候选 + 手输自定义项合并下发;
* 单批 ≤ {@code JdGroupShopService.MAX_ADD_SHOPS}(100),服务侧再查重去空。
*/
@Data
@Schema(description = "分类店铺名单批量添加请求")
public class JdGroupShopAddShopsRequest {
@Schema(description = "店铺名称集合(弹窗勾选+手输合并;服务侧 trim/去空/去重)")
@NotEmpty(message = "店铺名称列表不能为空")
private List<String> shopNames;
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 分类店铺名单改名请求(v1.7):同分类内改名;撞已有名按 409 业务错误拒绝。
*/
@Data
@Schema(description = "分类店铺名单改名请求")
public class JdGroupShopRenameShopRequest {
@Schema(description = "原店铺名(必须在该分类名单里)")
@NotBlank(message = "原店铺名称不能为空")
private String oldName;
@Schema(description = "新店铺名(同分类内不得与其它名单重名)")
@NotBlank(message = "新店铺名称不能为空")
private String newName;
}
@@ -0,0 +1,21 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 京东数据库商品导出请求(v1.7,2026-11-21 拍板「只恢复 CSV」导出)。
* 按<b>勾选</b>导出:前端把选中行 id 一次性提交,上限 {@code JdProductQueryService.MAX_EXPORT_IDS}
* (1000)——超限服务侧拒绝,不做静默截断(用户以为导全了、实际少导是交付事故)。
*/
@Data
@Schema(description = "京东数据库商品导出请求")
public class JdProductExportRequest {
@Schema(description = "勾选商品行 id 集合(单次最多 1000 个)")
@NotEmpty(message = "请先勾选要导出的商品")
private List<Long> ids;
}
@@ -0,0 +1,32 @@
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_group_shop},V214,v1.7)。
*
* <p>口径(2026-11-21 用户拍板「店铺名单维度完整对齐」原型《商品数据商城》):一行=
* 「分类 × 店铺名」,唯一键 {@code uk_category_shop(category_id, shop_name)} 同分类重名拒绝。
* 名单不碰 {@code biz_jd_product} 行——商品过滤走 {@code shop_name} 精确 eq 谓词
* (配合 {@code group_id} 组合:点店铺=该分类归属 ∩ 该店铺)。简单单表 CRUD 走
* BaseMapper + wrapper(SqlLayering 惯例),批量添加一条 XML(INSERT IGNORE 幂等)。</p>
*/
@Data
@TableName("biz_jd_group_shop")
public class JdGroupShopEntity {
@TableId(type = IdType.AUTO)
private Long id;
/** 分类 id(biz_jd_product_group.id)。 */
private Long categoryId;
/** 京麦店铺名(biz_jd_product.shop_name 同形状)。 */
private String shopName;
/** 操作者 user id。 */
private Long createdBy;
private LocalDateTime createdAt;
}
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 京东商品自定义分类(分类下拉/管理面,v1.4 Phase 5;V203 按数据权限分组归属)。
@@ -11,6 +12,9 @@ import java.time.LocalDateTime;
* <p>{@code productCount} 是读侧现算列(按归属表 {@code biz_jd_product_group_assign} 的
* {@code category_id} 计数)——商品是全平台公共的,同一商品在别的组里可能另挂一个分类,
* 这里只数本分类。{@code ownerGroupId} 是归属的数据权限分组 id(同组内重名唯一)。</p>
*
* <p>{@code shops}(V214,v1.7 店铺名单):该分类下的店铺名清单(读侧一次批量取,无逐行
* 查询),侧栏分类行按它渲染展开箭头与店铺行;点店铺=商品查询带 group_id+shop_name。</p>
*/
@Data
@Schema(description = "京东商品自定义分类")
@@ -31,6 +35,9 @@ public class JdProductGroupVo {
@Schema(description = "本分类下的商品数(读侧现算)")
private Long productCount;
@Schema(description = "该分类下的店铺名单(v1.7,shop_name 升序;无名单=空数组)")
private List<String> shops;
@Schema(description = "创建时刻")
private LocalDateTime createdAt;
}
@@ -0,0 +1,192 @@
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.modules.jd.mapper.JdGroupShopMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdGroupShopEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* 京东数据库分类「店铺名单」业务(V214,v1.7 对齐原型《商品数据商城》)。
*
* <p>口径(2026-11-21 用户拍板「店铺名单维度完整对齐」):名单行=「分类 × 店铺名」,
* 唯一键 {@code uk_category_shop} 同分类重名拒绝。业务规则:</p>
* <ul>
* <li><b>批量添加幂等</b>:INSERT IGNORE 跳过已存在的行(原型 onConflictDoNothing 同语义),
* 返回实际新增行数;单批 ≤ {@link #MAX_ADD_SHOPS} 家(前端弹窗勾选+手输合计)。</li>
* <li><b>改名同分类查重 409</b>:先查后改给可读的 409 业务错误,不拿 DB 唯一键异常撞 500;
* 名单改名只更新名单表本身(我们的商品归类不带店铺维,无原型 assignment 同步链)。</li>
* <li><b>可添加候选</b>:{@code biz_jd_product.shop_name} DISTINCT + like + 排除
* 指定分类已有名单(前端「添加店铺」弹窗候选源),limit ≤ {@link #MAX_AVAILABLE_LIMIT}。</li>
* <li><b>分类列表带名单</b>:{@link #listShopsByCategoryIds} 一次批量取(无逐行查询),
* {@code JdProductGroupService} 填进每行 {@code shops[]}。</li>
* </ul>
*
* <p>读写作用域(谁能看/改哪个分类的名单)不在本类——控制器按分类归属过
* {@code JdCategoryScopeService} 的 canRead/canWrite 闸(与分类改名/删除同口径)。</p>
*/
@Service
@RequiredArgsConstructor
public class JdGroupShopService {
/** 单批添加上限(弹窗勾选+手输合计)。 */
public static final int MAX_ADD_SHOPS = 100;
/** available 候选单次返回上限。 */
public static final int MAX_AVAILABLE_LIMIT = 200;
private final JdGroupShopMapper jdGroupShopMapper;
private final JdProductMapper jdProductMapper;
/** 名单(按 shop_name 升序)。 */
public List<String> listShops(Long categoryId) {
if (categoryId == null || categoryId <= 0) {
return List.of();
}
List<String> shops = new ArrayList<>();
for (JdGroupShopEntity row : jdGroupShopMapper.selectList(
new LambdaQueryWrapper<JdGroupShopEntity>()
.eq(JdGroupShopEntity::getCategoryId, categoryId)
.orderByAsc(JdGroupShopEntity::getShopName))) {
if (row.getShopName() != null && !row.getShopName().isBlank()) {
shops.add(row.getShopName());
}
}
return shops;
}
/** 多个分类的名单按 categoryId 分组(分类列表一行带 shops[];一次查询,无逐行查询)。 */
public Map<Long, List<String>> listShopsByCategoryIds(Collection<Long> categoryIds) {
List<Long> ids = categoryIds == null ? List.of()
: categoryIds.stream().filter(id -> id != null && id > 0).distinct().toList();
if (ids.isEmpty()) {
return Map.of();
}
Map<Long, List<String>> shopsByCategory = new LinkedHashMap<>();
for (JdGroupShopEntity row : jdGroupShopMapper.selectList(
new LambdaQueryWrapper<JdGroupShopEntity>()
.in(JdGroupShopEntity::getCategoryId, ids)
.orderByAsc(JdGroupShopEntity::getShopName))) {
if (row.getCategoryId() != null && row.getShopName() != null && !row.getShopName().isBlank()) {
shopsByCategory.computeIfAbsent(row.getCategoryId(), k -> new ArrayList<>()).add(row.getShopName());
}
}
return shopsByCategory;
}
/**
* 批量添加:trim/去空/去重/上限 100,INSERT IGNORE 幂等跳过已存在的行。
*
* @return 实际新增行数(全重复=0,不报错)
*/
@Transactional(rollbackFor = Exception.class)
public int addShops(Long categoryId, List<String> shopNames, Long operatorId) {
if (categoryId == null || categoryId <= 0) {
throw new BusinessException("分类不存在");
}
if (shopNames == null || shopNames.isEmpty()) {
throw new BusinessException(400, "店铺名称列表不能为空");
}
LinkedHashSet<String> uniqueNames = new LinkedHashSet<>();
for (String name : shopNames) {
if (name == null) {
continue;
}
String trimmed = name.trim();
if (!trimmed.isEmpty()) {
uniqueNames.add(trimmed);
}
}
if (uniqueNames.isEmpty()) {
throw new BusinessException(400, "有效店铺名称不能为空");
}
if (uniqueNames.size() > MAX_ADD_SHOPS) {
throw new BusinessException(400, "单次最多添加 " + MAX_ADD_SHOPS + " 家店铺");
}
// 幂等跳过的行数不单独记;谁加了几个由控制器留日志(V203 归类同口径)。
return jdGroupShopMapper.insertIgnoreBatch(categoryId, List.copyOf(uniqueNames), operatorId);
}
/**
* 移除名单中的一个店铺:删 (categoryId, shopName) 那一行。
*
* @return 删除的行数;该分类下不存在此店铺按业务错误拒绝(原型 404 同语义)
*/
public int removeShop(Long categoryId, String shopName) {
String trimmed = requireShopName(shopName, "店铺名称不能为空");
int deleted = jdGroupShopMapper.delete(new LambdaQueryWrapper<JdGroupShopEntity>()
.eq(JdGroupShopEntity::getCategoryId, categoryId)
.eq(JdGroupShopEntity::getShopName, trimmed));
if (deleted <= 0) {
throw new BusinessException("该分类下不存在此店铺:" + trimmed);
}
return deleted;
}
/**
* 改名:老名必须在该分类名单里,新名同分类查重 409(排除自身)。
* 名单改名只更新名单表本身(商品归类不带店铺维,无原型 assignment 同步链)。
*/
@Transactional(rollbackFor = Exception.class)
public void renameShop(Long categoryId, String oldName, String newName) {
String safeOld = requireShopName(oldName, "原店铺名称不能为空");
String safeNew = requireShopName(newName, "新店铺名称不能为空");
if (safeOld.equals(safeNew)) {
throw new BusinessException(400, "新店铺名称不能与原名称相同");
}
JdGroupShopEntity row = jdGroupShopMapper.selectOne(
new LambdaQueryWrapper<JdGroupShopEntity>()
.eq(JdGroupShopEntity::getCategoryId, categoryId)
.eq(JdGroupShopEntity::getShopName, safeOld)
.last("limit 1"));
if (row == null) {
throw new BusinessException("该分类下不存在此店铺:" + safeOld);
}
Long duplicate = jdGroupShopMapper.selectCount(new LambdaQueryWrapper<JdGroupShopEntity>()
.eq(JdGroupShopEntity::getCategoryId, categoryId)
.eq(JdGroupShopEntity::getShopName, safeNew)
.ne(row.getId() != null, JdGroupShopEntity::getId, row.getId()));
if (duplicate != null && duplicate > 0) {
throw new BusinessException(409, "该分类下已存在同名店铺:" + safeNew);
}
row.setShopName(safeNew);
jdGroupShopMapper.updateById(row);
}
/**
* 可添加候选(「添加店铺」弹窗源):{@code biz_jd_product.shop_name} DISTINCT +
* like + 排除指定分类已有名单。SQL 侧下推(铁律 20 同形),limit 服务侧钳制。
*/
public List<String> availableShops(String keyword, Long excludeCategoryId, Integer limit) {
int safeLimit = limit == null || limit < 1 ? MAX_AVAILABLE_LIMIT : Math.min(limit, MAX_AVAILABLE_LIMIT);
List<String> excludeNames = excludeCategoryId == null || excludeCategoryId <= 0
? List.of() : listShops(excludeCategoryId);
return jdProductMapper.selectDistinctShopNames(trimToNull(keyword), excludeNames, safeLimit);
}
// ---------------------------------------------------------------- 业务规则
private static String requireShopName(String name, String blankMessage) {
if (name == null || name.trim().isEmpty()) {
throw new BusinessException(400, blankMessage);
}
return name.trim();
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}
@@ -14,6 +14,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
@@ -38,6 +39,7 @@ public class JdProductGroupService {
private final JdProductGroupMapper jdProductGroupMapper;
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
private final JdGroupShopService jdGroupShopService;
/** 单个分组的分类全量(按 {@code sort_order, id} 升序,下拉展示顺序)。 */
public List<JdProductGroupVo> list(Long ownerGroupId) {
@@ -49,7 +51,8 @@ public class JdProductGroupService {
/**
* 多个分组的分类并集(用户端「获取店铺数据」页:一个普通号可能同时在多个组里,只读展示)。
* 空清单直接回空,不生成 {@code IN ()}。
* 空清单直接回空,不生成 {@code IN ()}。名单({@code shops[]},V214)按行集 id 一次批量取,
* 无名单的分类落空数组(侧栏不渲染展开箭头)。
*/
public List<JdProductGroupVo> listForGroups(List<Long> ownerGroupIds) {
Set<Long> safeGroupIds = new LinkedHashSet<>();
@@ -68,6 +71,8 @@ public class JdProductGroupService {
.in(JdProductGroupEntity::getOwnerGroupId, safeGroupIds)
.orderByAsc(JdProductGroupEntity::getSortOrder)
.orderByAsc(JdProductGroupEntity::getId));
Map<Long, List<String>> shopsByCategory = jdGroupShopService.listShopsByCategoryIds(
rows.stream().map(JdProductGroupEntity::getId).toList());
List<JdProductGroupVo> items = new ArrayList<>(rows.size());
for (JdProductGroupEntity category : rows) {
JdProductGroupVo vo = new JdProductGroupVo();
@@ -79,6 +84,7 @@ public class JdProductGroupService {
vo.setProductCount(jdProductGroupAssignMapper.selectCount(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.eq(JdProductGroupAssignEntity::getCategoryId, category.getId())));
vo.setShops(shopsByCategory.getOrDefault(category.getId(), List.of()));
items.add(vo);
}
return items;
@@ -23,7 +23,9 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -48,25 +50,35 @@ import java.util.Map;
* 非该形状时<b>不抛 500</b>,落空 {@code attrGroups} 并把原文放进 {@code attrJsonRaw} 兜底展示。
* 主表高频列直接从 entity 映射,不走 JSON。</p>
*
* <p>导出(byte[] xlsx)已随 2026-11-15 客户口径「导出也不用」整段下线,控制器端点同窗删;
* {@code sale_status} 过滤参数同窗撤掉(前端筛选框下线);店铺筛选参数同日客户口径
* 「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。</p>
* <p><b>v1.7(2026-11-21 对齐原型《商品数据商城》)</b>:合并搜索 {@code keyword}
* (product_code LIKE OR title LIKE,OR 语义必须后端做;旧 product_code/title_keyword 参数
* 保留兼容)、价格区间 {@code minPrice}/{@code maxPrice}(商品区间完全落在筛选区间内)、
* 店铺精确过滤 {@code shopName}(随「店铺名单维度完整对齐」复活,2026-11-15 撤掉的是筛选框);
* 每页上限放宽 100 → 1000(原型档位 50/100/200/500/1000,两侧逐字同步);恢复 CSV 导出
* {@link #exportCsv}(按勾选 id,UTF-8 BOM+中文表头,Excel 直开)。xlsx 导出维持下线。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class JdProductQueryService {
/** 页码上限(CR-18 关键词分页同值):10000 页 x 100 条 = 100 万行封顶,乘积不溢出。 */
/** 页码上限(CR-18 关键词分页同值):10000 页 x 1000 条 = 1000 万行封顶,乘积不溢出。 */
private static final long MAX_PAGE = 10_000;
/** 每页条数上限(照外观专利只读页同值)。 */
private static final long MAX_PAGE_SIZE = 100;
/**
* 每页条数上限(v1.7 放宽 100 → 1000,对齐原型档位 50/100/200/500/1000)。
* ⚠ 前端 {@code jd-product-filter.ts} 的 MAX_PAGE_SIZE 同值逐字同步(两侧契约测试都钉)。
*/
private static final long MAX_PAGE_SIZE = 1000;
/** CSV 导出单次上限(勾选行数;前端工具栏同值提示)。 */
public static final int MAX_EXPORT_IDS = 1000;
/** attr_json 原始形状里的 Tab 字段名(客户端实拍契约,AC-3 保真不转写)。 */
private static final String ATTR_TAB_FIELD = "tab";
private static final String ATTR_ATTRS_FIELD = "attrs";
private static final String ATTR_KEY_FIELD = "key";
private static final String ATTR_LABEL_FIELD = "label";
private static final String ATTR_VALUE_FIELD = "value";
/** CSV「同步时间」列格式(Excel 可读的秒级形状)。 */
private static final DateTimeFormatter SYNCED_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
@@ -78,10 +90,13 @@ public class JdProductQueryService {
/**
* 分页查询商品行({@code synced_at} 倒序)。
*
* <p>过滤面:商品编码 contains、标题关键词 contains、类目 IN(2026-11-18 起多值:
* <p>过滤面:合并搜索词 {@code keyword}(v1.7:product_code LIKE <b>OR</b> title LIKE,
* OR 语义必须后端做;旧 productCode/titleKeyword 保留兼容、仍 AND 生效)、
* 类目 IN(2026-11-18 起多值:
* 选一级/二级类目由前端展开为子树类目名集合下发,单值=原 eq 形状;空集合=不过滤该面)、
* 分组 eq(2026-11-16 起
* 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)、分类状态档
* 由类目面板「自定义分类」选中驱动)、店铺精确 eq(v1.7 随名单维度复活,配合 groupId)、
* 价格区间(v1.7:商品区间完全落在筛选区间内)、同步起止(datetime 闭区间)、分类状态档
* {@code classified}(2026-11-17 用户口径「加个已分类和未分类的筛选」:true=当前分组下
* 有分类、false=没有、null=全部;按 V203 归属表 EXISTS/NOT EXISTS 在 SQL 侧下推,
* 判据与 {@link #fillGroupNames} 填分类列的条件同形——「筛选说未分类的行,列表分类列
@@ -91,22 +106,28 @@ public class JdProductQueryService {
* 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p>
*/
public JdProductPageVo page(Long page, Long pageSize,
String productCode, String titleKeyword, List<String> categories, Long groupId,
String keyword, String productCode, String titleKeyword, List<String> categories,
Long groupId, String shopName, BigDecimal minPrice, BigDecimal maxPrice,
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified, Long ownerGroupId) {
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
throw new BusinessException("开始时间不能晚于结束时间");
}
if (minPrice != null && maxPrice != null && minPrice.compareTo(maxPrice) > 0) {
throw new BusinessException("价格区间最小值不能大于最大值");
}
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
Filter filter = filter(productCode, titleKeyword, categories,
groupId, syncedFrom, syncedTo, classified);
long total = jdProductMapper.countProducts(filter.productCode(),
filter.titleKeyword(), filter.categories(), filter.groupId(),
Filter filter = filter(keyword, productCode, titleKeyword, categories,
groupId, shopName, minPrice, maxPrice, syncedFrom, syncedTo, classified);
long total = jdProductMapper.countProducts(filter.keyword(), filter.productCode(),
filter.titleKeyword(), filter.categories(), filter.groupId(), filter.shopName(),
filter.minPrice(), filter.maxPrice(),
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId);
List<JdProductEntity> rows = total <= 0 ? List.of()
: jdProductMapper.selectProductPage(filter.productCode(),
filter.titleKeyword(), filter.categories(), filter.groupId(),
: jdProductMapper.selectProductPage(filter.keyword(),
filter.productCode(), filter.titleKeyword(), filter.categories(),
filter.groupId(), filter.shopName(), filter.minPrice(), filter.maxPrice(),
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId,
(safePage - 1) * safeSize, (int) safeSize);
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
@@ -176,6 +197,68 @@ public class JdProductQueryService {
return jdProductMapper.selectProductCategories();
}
/**
* 按勾选导出 CSV(v1.7,2026-11-21 拍板「只恢复 CSV」)。
*
* <p>形状对齐原型 downloadProducts 的 CSV 档:UTF-8 <b>带 BOM</b>(Excel 双击直开中文不乱码)、
* 中文表头、逐字段 CSV 转义(含逗号/引号/换行的标题不串列,RFC 4180)。列按
* {@code biz_jd_product} 现有字段映射(原型的拼团价/销量等商城销售字段京东采集源头没有,
* 不建空列,见蓝图 Out of Scope)。行按 id 升序(勾选集合无顺序语义,id 稳定输出便于对账)。</p>
*
* <p>上限 {@link #MAX_EXPORT_IDS}(1000):超限整批拒绝不静默截断——用户以为导全了、
* 实际少导是交付事故;空勾选同样拒绝(前端按钮置灰是第一道,这里是兜底)。</p>
*/
public byte[] exportCsv(List<Long> ids) {
if (ids == null || ids.isEmpty()) {
throw new BusinessException("请先勾选要导出的商品");
}
List<Long> uniqueIds = ids.stream().filter(id -> id != null && id > 0).distinct().toList();
if (uniqueIds.isEmpty()) {
throw new BusinessException("请先勾选要导出的商品");
}
if (uniqueIds.size() > MAX_EXPORT_IDS) {
throw new BusinessException("单次最多导出 " + MAX_EXPORT_IDS + " 个商品,请缩小勾选范围");
}
List<JdProductEntity> rows = new ArrayList<>(jdProductMapper.selectBatchIds(uniqueIds));
rows.sort(java.util.Comparator.comparing(JdProductEntity::getId,
java.util.Comparator.nullsLast(java.util.Comparator.naturalOrder())));
StringBuilder csv = new StringBuilder();
csv.append('\uFEFF');
csv.append(String.join(",", List.of("商品编码", "标题", "价格下限", "价格上限", "总库存",
"SKU数", "信息分", "品牌", "货号", "店铺", "类目", "状态", "同步时间", "主图")));
for (JdProductEntity row : rows) {
csv.append("\r\n");
csv.append(csvCell(row.getProductCode())).append(',')
.append(csvCell(row.getTitle())).append(',')
.append(csvCell(row.getPriceMin())).append(',')
.append(csvCell(row.getPriceMax())).append(',')
.append(csvCell(row.getStockTotal())).append(',')
.append(csvCell(row.getSkuCount())).append(',')
.append(csvCell(row.getHealthScore())).append(',')
.append(csvCell(row.getBrand())).append(',')
.append(csvCell(row.getItemNum())).append(',')
.append(csvCell(row.getShopName())).append(',')
.append(csvCell(row.getCategoryPath())).append(',')
.append(csvCell(row.getSaleStatus())).append(',')
.append(csvCell(row.getSyncedAt() == null ? null
: row.getSyncedAt().format(SYNCED_AT_FORMATTER))).append(',')
.append(csvCell(row.getMainImageUrl()));
}
return csv.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
/** CSV 单元格转义:含逗号/引号/换行时整体加引号、内部引号翻倍(RFC 4180)。 */
private static String csvCell(Object value) {
if (value == null) {
return "";
}
String text = String.valueOf(value);
if (text.contains(",") || text.contains("\"") || text.contains("\n") || text.contains("\r")) {
return '"' + text.replace("\"", "\"\"") + '"';
}
return text;
}
/**
* 商品详情(主字段全量 + attr_json 解析 + 已转存图片)。
*
@@ -230,15 +313,18 @@ public class JdProductQueryService {
// ---------------------------------------------------------------- 过滤面
/** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘);
* shopName/keyword 同 trim 归一(v1.7);价格区间原样直传(倒挂已在校验段拒绝);
* classified 原样直传(null=不过滤该面,2026-11-17 分类状态快筛);
* categories 逐项 trim、去空白、去重,空集合归 null=不过滤该面(2026-11-18 一级/二级类目展开)。 */
private record Filter(String productCode, String titleKeyword,
List<String> categories, Long groupId,
private record Filter(String keyword, String productCode, String titleKeyword,
List<String> categories, Long groupId, String shopName,
BigDecimal minPrice, BigDecimal maxPrice,
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
}
private static Filter filter(String productCode, String titleKeyword,
List<String> categories, Long groupId,
private static Filter filter(String keyword, String productCode, String titleKeyword,
List<String> categories, Long groupId, String shopName,
BigDecimal minPrice, BigDecimal maxPrice,
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
List<String> safeCategories = categories == null ? null : categories.stream()
@@ -246,9 +332,10 @@ public class JdProductQueryService {
.filter(java.util.Objects::nonNull)
.distinct()
.toList();
return new Filter(trimToNull(productCode), trimToNull(titleKeyword),
return new Filter(trimToNull(keyword), trimToNull(productCode), trimToNull(titleKeyword),
safeCategories == null || safeCategories.isEmpty() ? null : safeCategories,
safeGroupId, syncedFrom, syncedTo, classified);
safeGroupId, trimToNull(shopName), minPrice, maxPrice,
syncedFrom, syncedTo, classified);
}
// ---------------------------------------------------------------- 列表/详情搬运
@@ -0,0 +1,51 @@
-- =============================================================
-- 迁移 V214__jd_group_shop
-- 需求:v1.7(2026-11-21 用户拍板「店铺名单维度完整对齐」原型《商品数据商城》)——
-- 京东数据库自定义分类下挂「店铺名单」:侧栏分类行可展开店铺清单,点店铺=
-- 只看「该分类归属 ∩ 该店铺」的商品;名单可批量添加(从已落库行的
-- biz_jd_product.shop_name 去重挑选,也允许手输自定义名)、移除、改名。
-- 前版:V203(分类按数据权限分组归属 + 归类归属表)。
--
-- 1. 变更目的:名单是「分类 × 店铺名」的多对多维——一张独立名单表,不碰
-- biz_jd_product 行(店铺列已存在,商品过滤走 shop_name 精确 eq 谓词)。
-- 写权限与分类一致(本组管理员/公司超管/平台超管,JdCategoryScopeService)。
--
-- 2. 口径:
-- biz_jd_group_shop(新表)
-- uk_category_shop(category_id, shop_name) 同分类重名拒绝
-- (改名撞已有名服务层先查给 409;批量添加走 INSERT IGNORE 幂等跳过)
--
-- 3. 存量:新表零存量行;历史分类的名单为空(侧栏不渲染展开箭头)。
--
-- 4. 可重跑性:CREATE TABLE IF NOT EXISTS,重跑 no-op。
--
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
-- DROP TABLE biz_jd_group_shop;
-- (jar 必须先回到不带名单维度的版本,否则读侧会查不存在的表。)
-- =============================================================
CREATE TABLE IF NOT EXISTS `biz_jd_group_shop` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`category_id` bigint NOT NULL COMMENT '分类 id(biz_jd_product_group.id)',
`shop_name` varchar(255) NOT NULL COMMENT '京麦店铺名(biz_jd_product.shop_name 同形状,商品过滤精确 eq)',
`created_by` bigint NULL DEFAULT NULL COMMENT '操作者 user id',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_category_shop` (`category_id` ASC, `shop_name` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '京东数据库分类店铺名单(V214)' ROW_FORMAT = Dynamic;
-- =============================================================
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
--
-- SHOW CREATE TABLE biz_jd_group_shop;
-- -> 期望含 uk_category_shop(category_id, shop_name)、created_at 默认 CURRENT_TIMESTAMP。
--
-- INSERT 撞键(事务内跑完回滚,只插 ZZTEST 前缀):
-- START TRANSACTION;
-- INSERT INTO biz_jd_group_shop (category_id, shop_name) VALUES (9223372036854775806, 'ZZTEST');
-- INSERT INTO biz_jd_group_shop (category_id, shop_name) VALUES (9223372036854775806, 'ZZTEST2');
-- INSERT IGNORE INTO biz_jd_group_shop (category_id, shop_name) VALUES (9223372036854775806, 'ZZTEST');
-- SELECT ROW_COUNT() AS should_be_zero_probe;
-- ROLLBACK;
-- -> 期望第二条与前两条都成功、第三条 INSERT IGNORE 影响行数 0(唯一键生效);回滚后零残留。
-- =============================================================
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.jd.mapper.JdGroupShopMapper">
<!-- 京东数据库分类店铺名单(V214,v1.7):SQL 全部落 XML(铁律 1)。
唯一键 uk_category_shop(category_id, shop_name)=同分类重名拒绝;
批量添加用 INSERT IGNORE 幂等(撞已存在的行跳过,原型 onConflictDoNothing 同语义),
其余 CRUD 走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。 -->
<insert id="insertIgnoreBatch">
INSERT IGNORE INTO biz_jd_group_shop (category_id, shop_name, created_by)
VALUES
<foreach collection="shopNames" item="name" separator=",">
(#{categoryId}, #{name}, #{createdBy})
</foreach>
</insert>
</mapper>
@@ -120,6 +120,12 @@
同窗撤掉(前端筛选框与列下线;DB 列本身与详情/回传链不动)。
全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 -->
<sql id="productConds">
<!-- 合并搜索词(v1.7,2026-11-21 对齐原型单搜索框):product_code LIKE OR title LIKE——
OR 语义必须在这里下推(前端停发旧两参数;旧 product_code/title_keyword 参数保留
兼容,与本谓词 AND 叠加)。 -->
<if test="keyword != null and keyword != ''">
AND (p.product_code LIKE CONCAT('%', #{keyword}, '%') OR p.title LIKE CONCAT('%', #{keyword}, '%'))
</if>
<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>
<!-- 类目过滤(2026-11-18 一级/二级类目可选):单值=原 eq 形状;父级选中由前端展开为
@@ -129,6 +135,14 @@
AND p.category_path IN
<foreach collection="categories" item="cat" open="(" separator="," close=")">#{cat}</foreach>
</if>
<!-- 店铺过滤(v1.7 恢复:2026-11-21 拍板「店铺名单维度完整对齐」,点店铺=该分类归属
∩ 该店铺):精确 eq(店铺名单是全名清单,不是模糊搜索面)。2026-11-15 撤掉的是
筛选框,DB 列与名单候选查询一直在。 -->
<if test="shopName != null and shopName != ''">AND p.shop_name = #{shopName}</if>
<!-- 价格区间(v1.7 对齐原型):商品区间完全落在筛选区间内=采购直觉语义
(price_min >= X AND price_max <= Y),不是「区间有交集」。 -->
<if test="minPrice != null">AND p.price_min &gt;= #{minPrice}</if>
<if test="maxPrice != null">AND p.price_max &lt;= #{maxPrice}</if>
<if test="groupId != null and groupId &gt; 0">
AND EXISTS (
SELECT 1 FROM biz_jd_product_group_assign a
@@ -197,6 +211,22 @@
ORDER BY p.category_path
</select>
<!-- 店铺名单「可添加候选」(v1.7,添加店铺弹窗源):biz_jd_product.shop_name DISTINCT +
like + 排除指定分类已有名单(NOT IN 下推,铁律 20)。limit 是服务侧钳制后的值
(≤ JdGroupShopService.MAX_AVAILABLE_LIMIT),mapper 不做第二次换算。 -->
<select id="selectDistinctShopNames" resultType="string">
SELECT DISTINCT p.shop_name
FROM biz_jd_product p
WHERE p.shop_name IS NOT NULL AND p.shop_name != ''
<if test="keyword != null and keyword != ''">AND p.shop_name LIKE CONCAT('%', #{keyword}, '%')</if>
<if test="excludeNames != null and excludeNames.size() > 0">
AND p.shop_name NOT IN
<foreach collection="excludeNames" item="name" open="(" separator="," close=")">#{name}</foreach>
</if>
ORDER BY p.shop_name
LIMIT #{limit}
</select>
<!-- 商品上架配额计数(JdPublishQuotaService):按 owner uid 集计 biz_jd_product 行数;
uid 集=管理员本人+名下员工(公司超管=全公司成员),由服务侧保证非空
(空集按 0 处理,不进 SQL)。user_id=任务 owner(V193 物化归属列)。 -->
@@ -156,6 +156,23 @@ class JdSchemaContractTest {
assertTrue(sql.contains("迁移 V210"), "头注释必须是 `-- 迁移 V210…`(MigrationInventoryTest 口径)");
}
@Test
void V214_分类店铺名单_同分类唯一键形状() {
String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql"));
assertTrue(sql.contains("biz_jd_group_shop"), "缺名单表");
for (String column : List.of("category_id", "shop_name", "created_by", "created_at")) {
assertFalse(linesContaining(sql, "`" + column + "`").isEmpty(), "V214 缺列: " + column);
}
// 同分类重名拒绝(服务层先查给 409,DB 唯一键兜并发)。
assertTrue(sql.contains("uk_category_shop"), "同分类店铺重名唯一键缺失");
assertTrue(linesContaining(sql, "uk_category_shop").stream()
.anyMatch(line -> line.contains("category_id") && line.contains("shop_name")),
"唯一键必须是 (category_id, shop_name)");
assertTrue(linesContaining(sql, "`shop_name`").stream().anyMatch(line -> line.contains("NOT NULL")),
"shop_name 必须 NOT NULL(空店铺名没有语义,铁律 30 同形)");
assertTrue(sql.contains("迁移 V214"), "头注释必须是 `-- 迁移 V214…`(MigrationInventoryTest 口径)");
}
@Test
void 配置_独立图片桶不落默认桶() {
String appYml = read(RESOURCES.resolve("application.yml"));
@@ -13,6 +13,7 @@ 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.JdProductExportRequest;
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;
@@ -26,6 +27,7 @@ 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.JdGroupShopService;
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
@@ -35,6 +37,7 @@ import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@@ -107,8 +110,9 @@ class AdminJdProductControllerTest {
assertTrue(source.contains("/api/admin/jd-products"), "端点必须挂在 /api/admin/jd-products");
assertTrue(source.contains("@GetMapping"), "查询端点必须落在 @GetMapping");
assertTrue(source.contains("\"/{id}\""), "详情端点必须是 GET /{id}");
// 导出端点已随 2026-11-15 客户口径「导出也不用」下线(前端导出发送口同窗撤)——反向钉住防回潜。
assertFalse(source.contains("\"/export\""), "导出端点必须已删除,不得回潜");
// 导出端点 v1.7 恢复(2026-11-21 拍板「只恢复 CSV」):POST /export 按勾选 id 导出,
// 2026-11-15 的下线口径只对当年的 xlsx 形状有效(历史见 git)。
assertTrue(source.contains("\"/export\""), "导出端点必须复活(v1.7 拍板「只恢复 CSV」)");
// 删除入口(用户口径「后台删除数据的时候也要把桶对应的文件删除」):DELETE /{id} 单行
// + POST /batch-delete 批量,先删桶、全成功才删库行(JdProductDeleteService 判据另钉)。
assertTrue(source.contains("@DeleteMapping"), "删除端点必须落在 @DeleteMapping");
@@ -159,7 +163,8 @@ class AdminJdProductControllerTest {
@Test
void 分页参数snake且带默认值() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
for (String param : List.of("page_size", "product_code", "title_keyword",
for (String param : List.of("page_size", "product_code", "title_keyword", "keyword",
"shop_name", "min_price", "max_price",
"group_id", "owner_group_id", "synced_from", "synced_to")) {
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
}
@@ -169,12 +174,20 @@ class AdminJdProductControllerTest {
// 那两档读已停用的 biz_jd_product.group_id 列,语义不同,旧参数仍必须被拒收)。
assertTrue(source.contains("@RequestParam(name = \"classified\""),
"分类状态快筛参数 classified 必须在册(2026-11-17 用户口径)");
// v1.7 合并搜索(2026-11-21 对齐原型单搜索框):keyword 必须在册(OR 语义后端做)。
assertTrue(source.contains("@RequestParam(name = \"keyword\""),
"合并搜索参数 keyword 必须在册(v1.7 拍板)");
assertTrue(source.contains("@RequestParam(name = \"min_price\"")
&& source.contains("@RequestParam(name = \"max_price\""),
"价格区间参数 min_price/max_price 必须在册(v1.7 拍板)");
// company_id 参数已随 2026-11-16「删除掉公司 tab」整批摘除(读侧零公司维度支另有反向钉)。
assertFalse(source.contains("company_id"), "company_id 请求参数必须已删除,不得回潜");
// 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。
assertFalse(source.contains("\"sale_status\""), "sale_status 筛选参数必须已删除,不得回潜");
// 店铺筛选同日客户口径「店铺不需要」下线 ⇒ shop_name 参数同窗撤(反向钉住防回潜)。
assertFalse(source.contains("shop_name"), "shop_name 筛选参数必须已删除,不得回潜(店铺列/详情仍保留)");
// 店铺筛选 v1.7 复活(2026-11-21 拍板「店铺名单维度完整对齐」):精确 eq 配合 group_id;
// 2026-11-15 撤掉的是筛选框(旧口径注释的历史事实保留在 git)。
assertTrue(source.contains("@RequestParam(name = \"shop_name\""),
"店铺精确过滤参数 shop_name 必须在册(v1.7 随名单维度复活)");
assertTrue(source.contains("PageDefaults"), "page/page_size 默认值必须取 PageDefaults"
+ "(page_size 默认 20=PageDefaults.JD_PRODUCTS_PAGE_SIZE);"
+ "page 钳制防 (page-1)*page_size 溢出的行为样本见查询服务钳制支(铁律 15)");
@@ -220,11 +233,17 @@ class AdminJdProductControllerTest {
assertTrue(source.contains(seam), "分组鉴权闸缺接缝 " + seam + "(与商品页同款)");
}
// V203 起写权限不再收窄到平台超管:本组管理员 / 公司超管 / 平台超管都可写(作用域服务判)。
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping", "@PatchMapping")) {
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb);
}
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/作用域/新建/改名/删除五条路由都走同一菜单正门(写权限在作用域服务里判)");
// v1.7 店铺名单五条端点(V214):GET/POST/DELETE /{id}/shops、PATCH /{id}/shops/rename、
// GET /shops/available——读走 canRead、写走 canWrite(与分类同一道闸)。
for (String route : List.of("\"/{id}/shops\"", "\"/{id}/shops/rename\"", "\"/shops/available\"")) {
assertTrue(source.contains(route), "店铺名单端点缺失:" + route);
}
assertEquals(10, count(source, "requireJdAccess(request)"),
"列表/作用域/新建/改名/删除五条分类路由+名单五条路由,共十处同一菜单正门"
+ "(写权限在作用域服务里判)");
assertFalse(source.contains("requirePlatformSuperAdminWrite"),
"分类写权限已改由 JdCategoryScopeService 判「该组可写」,超管专属闸必须已摘除");
assertTrue(source.contains("requireWritableGroup(") && source.contains("canWrite("),
@@ -234,6 +253,11 @@ class AdminJdProductControllerTest {
assertTrue(source.contains("仅该分组的管理员可以修改它的分类"),
"非本组管理员写分类的 403 文案必须点名分组管理员");
assertTrue(source.contains("\"owner_group_id\""), "列表必须收 owner_group_id(当前分组)");
// 名单写端点必须显式过 requireWritableCategory(同分类改名/删除同一道闸,不另开门)。
assertTrue(count(source, "requireWritableCategory(scope, ownerGroupId)") >= 3,
"名单添加/移除/改名三条写路由必须逐条过 requireWritableCategory(V214)");
assertTrue(source.contains("requireReadableCategory("),
"名单读端点必须过可见组闸(canRead,同组普通号能看名单)");
}
// ===================== 写权限分档(2026-11-17:超管级+管理员可写,普通账号只读) =====================
@@ -245,8 +269,9 @@ class AdminJdProductControllerTest {
assertEquals(4, count(source, "requireJdProductWrite(request)"),
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走管理员级写闸"
+ "(归类不在此列:V203 起归本组管理员可做)");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/类目/详情/归类四条读+组内写路由,与写闸内部一处,共五处菜单权限正门");
assertEquals(6, count(source, "requireJdAccess(request)"),
"列表/类目/详情/归类四条读+组内写路由与导出,加写闸内部一处,共六处菜单权限正门"
+ "(v1.7 导出走读闸:导出属读行为,不走商品行写闸)");
assertTrue(source.contains("仅超级管理员或管理员可以编辑或删除京东数据库数据"),
"普通账号写商品的 403 文案必须点名超管与管理员(2026-11-17 口径)");
assertTrue(source.contains("operator.superAdmin()"),
@@ -289,8 +314,10 @@ class AdminJdProductControllerTest {
// 读:菜单权限命中即放行(公共库一人一份全量)。
JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of());
when(queryService.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, null, request)
when(queryService.page(1L, 20L, null, null, null, null, null, null, null, null, null, null, null, GROUP_ID))
.thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null,
null, null, null, null, null, null, request)
.isSuccess(), "普通账号有菜单权限时读必须放行(读写分档只收窄写)");
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
@@ -391,7 +418,7 @@ class AdminJdProductControllerTest {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductGroupController controller = new AdminJdProductGroupController(
groupService, scopeService, authSupport, permissionMenuService);
groupService, mock(JdGroupShopService.class), scopeService, authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
@@ -502,11 +529,13 @@ class AdminJdProductControllerTest {
when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L));
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, null, request));
() -> controller.page(1L, 20L, null, null, null, null, 8L, null, null, null,
null, null, null, null, request));
assertTrue(ex.getMessage().contains("无权查看该分组的分类"),
"跨组分类筛选必须 403 点名分组,不做空结果降级");
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any());
}
// ===================== 行为样本 =====================
@@ -534,13 +563,14 @@ class AdminJdProductControllerTest {
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, null, GROUP_ID)).thenReturn(pageVo);
when(queryService.page(1L, 20L, null, null, null, null, null, null, null, null, null, null, null, GROUP_ID))
.thenReturn(pageVo);
// 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null,
GROUP_ID, null, null, null, request);
null, null, null, null, GROUP_ID, null, null, null, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, null, null, null, null, null, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData());
}
@@ -564,12 +594,14 @@ 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, null, null, request));
() -> controller.page(1L, 20L, null, null, null, null, 7L, null, null, null,
null, 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(), any(), any());
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any());
}
@Test
@@ -688,25 +720,26 @@ class AdminJdProductControllerTest {
void 查询服务分页钳制防溢出() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), 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, null, null);
service.page(0L, null, null, null, null, null, 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(),
isNull(), isNull(), offset.capture(), limit.capture());
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), offset.capture(), limit.capture());
assertEquals(0L, offset.getValue());
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, null, null);
// page=Long.MAX_VALUE / size=5000 ⇒ 钳到 10_000 页、1000 条(v1.7 上限);乘积 9_999_000 不得变负(铁律 15)。
service.page(Long.MAX_VALUE, 5000L, null, null, null, null, null, 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(),
any(), any(), offsetMax.capture(), limitMax.capture());
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
assertEquals(100, limitMax.getValue());
any(), any(), any(), any(), any(), any(), offsetMax.capture(), limitMax.capture());
assertEquals(9_999_000L, offsetMax.getValue(), "(page-1)*page_size 最大 9_999_000,钳制后不得溢出变负");
assertEquals(1000, limitMax.getValue(), "page_size 上限已随 v1.7 放宽到 1000(对齐原型档位)");
}
@Test
@@ -716,23 +749,29 @@ class AdminJdProductControllerTest {
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, null, null));
() -> service.page(1L, 20L, null, null, null, null, null, null, null, null, from, to, null, null));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any());
}
@Test
void 查询服务过滤面原样直传且空串归null() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", List.of(" 艺考形体服 "), 7L, null, null, null, null);
verify(mapper).countProducts("SKU-1", "连衣裙", List.of("艺考形体服"), 7L, null, null, null, null);
verify(mapper).selectProductPage("SKU-1", "连衣裙", List.of("艺考形体服"), 7L, null, null, null, null, 0L, 20);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, null, " SKU-1 ", " 连衣裙 ", List.of(" 艺考形体服 "), 7L,
null, null, null, null, null, null, null);
verify(mapper).countProducts(null, "SKU-1", "连衣裙", List.of("艺考形体服"), 7L,
null, null, null, null, null, null, null);
verify(mapper).selectProductPage(null, "SKU-1", "连衣裙", List.of("艺考形体服"), 7L,
null, null, null, null, null, null, null, 0L, 20);
service.page(1L, 20L, " ", null, null, 0L, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, null, null, null, null, null, 0L, 20);
service.page(1L, 20L, null, " ", null, null, 0L, null, null, null, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null, null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, null, null, null, null, null,
null, null, null, null, 0L, 20);
}
/**
@@ -744,19 +783,21 @@ class AdminJdProductControllerTest {
void 类目多值必须逐项归一并IN下推() throws IOException {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, null, null,
service.page(1L, 20L, null, null, null,
java.util.Arrays.asList(" 女装 ", "女装", "", null, " 汉服/旗袍 "),
null, null, null, null, null);
verify(mapper).countProducts(null, null, List.of("女装", "汉服/旗袍"),
null, null, null, null, null);
verify(mapper).selectProductPage(null, null, List.of("女装", "汉服/旗袍"),
null, null, null, null, null, 0L, 20);
null, null, null, null, null, null, null, null);
verify(mapper).countProducts(null, null, null, List.of("女装", "汉服/旗袍"),
null, null, null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, List.of("女装", "汉服/旗袍"),
null, null, null, null, null, null, null, null, 0L, 20);
// 全空白/空集合=不过滤该面(与「全部类目」清选同口径,不得下发空 IN)
service.page(1L, 20L, null, null, java.util.Arrays.asList(" ", ""), null, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null, null, null);
service.page(1L, 20L, null, null, null, java.util.Arrays.asList(" ", ""),
null, null, null, null, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null, null, null, null, null, null, null);
Path xml = findJdProductMapperXml();
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
@@ -793,14 +834,19 @@ class AdminJdProductControllerTest {
// ① 服务直传:classified 与 ownerGroupId 成对进 mapper(计数与分页同一过滤面)。
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, true, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, true, GROUP_ID, 0L, 20);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, null, null, null, null, null, null, null, null, null, null,
Boolean.TRUE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, null, null, null, null, true, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, null, null,
null, null, true, GROUP_ID, 0L, 20);
service.page(1L, 20L, null, null, null, null, null, null, Boolean.FALSE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, false, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, false, GROUP_ID, 0L, 20);
service.page(1L, 20L, null, null, null, null, null, null, null, null, null, null,
Boolean.FALSE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, null, null, null, null, false, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, null, null,
null, null, false, GROUP_ID, 0L, 20);
// ③ 控制器直传:classified 原样进服务(owner_group_id 仍按作用域收敛后的值)。
JdProductQueryService queryService = mock(JdProductQueryService.class);
@@ -818,8 +864,148 @@ class AdminJdProductControllerTest {
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
controller.page(1L, 20L, null, null, null, null, null, null, null, Boolean.TRUE, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, GROUP_ID);
controller.page(1L, 20L, null, null, null, null, null, null, null, null, null, null,
null, Boolean.TRUE, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, null, null, null,
null, Boolean.TRUE, GROUP_ID);
}
/**
* v1.7(2026-11-21 对齐原型):合并搜索 keyword(product_code OR title)+ 价格区间
* min/max_price + 店铺精确过滤 shop_name 三件新过滤面——服务侧逐项归一后原样直传
* mapper(谓词在 XML 的 productConds 段,铁律 20 同形);价格倒挂按业务异常拒绝。
*/
@Test
void 合并搜索价格区间店铺过滤归一后直传且价格倒挂拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(1L);
// ① 三件新面原样直传:keyword/shopName trim 归一,价格 BigDecimal 原样。
service.page(1L, 20L, " 连衣裙 ", null, null, null, 7L, " 测试店铺 ",
new BigDecimal("100"), new BigDecimal("200"), null, null, null, null);
verify(mapper).countProducts("连衣裙", null, null, null, 7L, "测试店铺",
new BigDecimal("100"), new BigDecimal("200"), null, null, null, null);
verify(mapper).selectProductPage("连衣裙", null, null, null, 7L, "测试店铺",
new BigDecimal("100"), new BigDecimal("200"), null, null, null, null, 0L, 20);
// ② 空白 keyword/shopName 归 null(不过滤该面)。
service.page(1L, 20L, " ", null, null, null, 0L, " ", null, null, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null, null, null, null, null, null, null);
// ③ 价格倒挂按业务异常拒绝(同同步起止倒挂形状)。
BusinessException ex = assertThrows(BusinessException.class,
() -> service.page(1L, 20L, null, null, null, null, null, null,
new BigDecimal("200"), new BigDecimal("100"), null, null, null, null));
assertTrue(ex.getMessage().contains("价格区间最小值不能大于最大值"), "倒挂价格区间按业务异常拒绝");
verify(mapper, times(2)).countProducts(any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any());
}
/**
* v1.7 导出端点(2026-11-21 拍板「只恢复 CSV」):POST /export 按勾选 id 导出,
* 读闸 requireJdAccess(导出属读行为,不走商品行写闸),200 信封改
* {@code ResponseEntity<byte[]>}+Content-Disposition(外观专利导出同款形状)。
*/
@Test
void 导出CSV端点走菜单正门并把字节装进附件响应() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), 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");
byte[] csvBytes = "\uFEFF商品编码\r\nA123".getBytes(java.nio.charset.StandardCharsets.UTF_8);
when(queryService.exportCsv(List.of(11L, 12L))).thenReturn(csvBytes);
JdProductExportRequest body = new JdProductExportRequest();
body.setIds(List.of(11L, 12L));
ResponseEntity<byte[]> response = controller.export(body, request);
verify(queryService).exportCsv(List.of(11L, 12L));
assertEquals(200, response.getStatusCode().value(), "放行必须是 200 附件响应(非 ApiResponse 信封)");
assertTrue(response.getHeaders().getFirst("Content-Disposition").contains(".csv"),
"Content-Disposition 必须带 .csv 文件名(DownloadHeaderUtil 兜 ASCII 回退与 UTF-8 双名)");
assertTrue(response.getHeaders().getFirst("Content-Type").startsWith("text/csv"),
"Content-Type 必须是 text/csv(Excel 直开形状)");
assertEquals(csvBytes.length, response.getHeaders().getContentLength());
}
/** 导出超限整批拒绝(不静默截断——少导是交付事故),文案点名上限 1000。 */
@Test
void 导出勾选超上限整批拒绝() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), 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");
// 服务侧限流是真源(服务级用例另钉 1001 拒绝);这里钉控制器原样透出业务异常、不吞成 500。
when(queryService.exportCsv(any()))
.thenThrow(new BusinessException("单次最多导出 1000 个商品,请缩小勾选范围"));
java.util.List<Long> oversized = new java.util.ArrayList<>();
for (long i = 1; i <= 1001; i++) {
oversized.add(i);
}
JdProductExportRequest body = new JdProductExportRequest();
body.setIds(oversized);
BusinessException ex = assertThrows(BusinessException.class, () -> controller.export(body, request));
assertTrue(ex.getMessage().contains("1000"), "超限文案必须点名上限 1000");
}
/** 导出服务侧:BOM+中文表头+RFC 4180 转义+id 稳定排序;空/超限在服务层同样拒绝。 */
@Test
void 导出CSV带BOM中文表头转义与稳定排序() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
JdProductEntity first = productEntity(1L);
first.setTitle("测试连衣裙,带逗号\"带引号\"");
JdProductEntity second = productEntity(2L);
second.setSyncedAt(LocalDateTime.of(2026, 11, 21, 9, 30));
when(mapper.selectBatchIds(List.of(2L, 1L))).thenReturn(List.of(second, first));
byte[] bytes = service.exportCsv(List.of(2L, 1L));
String csv = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
assertTrue(csv.startsWith("\uFEFF"), "必须带 UTF-8 BOM(Excel 双击直开中文不乱码)");
assertTrue(csv.contains("商品编码,标题,价格下限,价格上限,总库存,SKU数,信息分,品牌,货号,店铺,类目,状态,同步时间,主图"),
"中文表头必须按 v1.7 列序在册");
// RFC 4180 转义:含逗号/引号的标题整体加引号、内部引号翻倍,不串列。
assertTrue(csv.contains("\"测试连衣裙,带逗号\"\"带引号\"\"\""),
"含逗号/引号的标题必须加引号且内部引号翻倍");
assertTrue(csv.contains("2026-11-21 09:30:00"), "同步时间列必须是秒级格式");
// 行按 id 升序(勾选集合无顺序语义)。
assertTrue(csv.indexOf("A123,") < csv.lastIndexOf("A123,"), "两行都在");
int firstRow = csv.indexOf("\r\n" + "A123,");
int secondRow = csv.indexOf("\r\n", firstRow + 1);
assertTrue(firstRow > 0 && secondRow > firstRow, "行分隔符存在");
// 空勾选拒绝(前端按钮置灰是第一道,这里是兜底);超上限同样拒绝(少导是交付事故)。
BusinessException empty = assertThrows(BusinessException.class, () -> service.exportCsv(List.of()));
assertTrue(empty.getMessage().contains("请先勾选"));
BusinessException invalid = assertThrows(BusinessException.class,
() -> service.exportCsv(java.util.Arrays.asList(0L, null)));
assertTrue(invalid.getMessage().contains("请先勾选"));
java.util.List<Long> oversized = new java.util.ArrayList<>();
for (long i = 1; i <= JdProductQueryService.MAX_EXPORT_IDS + 1; i++) {
oversized.add(i);
}
BusinessException over = assertThrows(BusinessException.class, () -> service.exportCsv(oversized));
assertTrue(over.getMessage().contains("1000"), "超限文案必须点名上限 1000");
}
@Test
@@ -967,9 +1153,10 @@ class AdminJdProductControllerTest {
JdProductEntity categorized = productEntity(1L);
JdProductEntity missing = productEntity(2L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(categorized, missing));
any(), any(), any(), any(), 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();
@@ -977,7 +1164,8 @@ class AdminJdProductControllerTest {
category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID);
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, null,
null, null, null, GROUP_ID);
assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行");
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)");
@@ -992,11 +1180,13 @@ class AdminJdProductControllerTest {
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(), any(), any())).thenReturn(1L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any())).thenReturn(1L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
any(), any(), any(), any(), anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, null);
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, null,
null, null, null, null);
assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)");
assertNull(vo.getItems().get(0).getGroupName());
@@ -61,9 +61,65 @@ class JdProductMapperSqlTest {
() -> "占位符数变了(companyId + taskId): " + sql);
}
/**
* v1.7(2026-11-21 对齐原型《商品数据商城》)新筛选谓词必须 SQL 侧下推(铁律 20):
* keyword=product_code LIKE <b>OR</b> title LIKE(OR 语义必须在 SQL 段,Java 侧 filter 即红)、
* 价格区间=商品区间完全落在筛选区间内(price_min &gt;= X AND price_max &lt;= Y)、
* 店铺=精确 eq(点店铺=该分类归属 ∩ 该店铺)。
*/
@Test
void v17_合并搜索价格区间店铺谓词全部下推SQL() throws Exception {
String sql = render("countProducts", Map.of(
"keyword", "连衣裙",
"productCode", "A123",
"titleKeyword", "碎花裙",
"groupId", 7L,
"shopName", "测试店铺",
"minPrice", new java.math.BigDecimal("100"),
"maxPrice", new java.math.BigDecimal("200")));
assertTrue(sql.contains("(p.product_code LIKE CONCAT('%', ?, '%') OR p.title LIKE CONCAT('%', ?, '%'))"),
() -> "keyword 必须 OR 下推在同一个括号对里(拆成 AND 或 Java 侧 filter 都算回潜): " + sql);
assertTrue(sql.contains("p.product_code LIKE CONCAT('%', ?, '%')")
&& sql.contains("p.title LIKE CONCAT('%', ?, '%')"),
() -> "旧两参数的独立 LIKE 谓词必须保留(兼容在飞前端): " + sql);
assertTrue(sql.contains("p.price_min >= ?") && sql.contains("p.price_max <= ?"),
() -> "价格区间必须是「商品区间完全落在筛选区间内」(有交集语义即改坏了口径): " + sql);
assertTrue(sql.contains("p.shop_name = ?"),
() -> "店铺过滤必须精确 eq(LIKE 模糊会把名单点选变搜索面): " + sql);
assertTrue(sql.contains("a.category_id = ?"),
() -> "自定义分类谓词必须仍在(v1.7 未动存量过滤面): " + sql);
// 空过滤面:一个新谓词都不许出现(空串/null 归一在服务侧,XML 不兜)。
String bare = render("countProducts", Map.of("offset", 0L, "limit", 20));
assertFalse(bare.contains("LIKE"), () -> "空过滤面不得残留 LIKE 谓词: " + bare);
assertFalse(bare.contains("shop_name"), () -> "空过滤面不得残留店铺谓词: " + bare);
assertFalse(bare.contains("price_min"), () -> "空过滤面不得残留价格谓词: " + bare);
}
/** 店铺名单「可添加候选」:DISTINCT + like + NOT IN 排除已有名单 + LIMIT(服务侧钳制值)。 */
@Test
void v17_店铺候选查询必须distinct下推与排除已有名单() throws Exception {
String sql = render("selectDistinctShopNames", Map.of(
"keyword", "旗",
"excludeNames", java.util.List.of("已有店A", "已有店B"),
"limit", 200));
assertTrue(sql.startsWith("SELECT DISTINCT p.shop_name FROM biz_jd_product p WHERE"),
() -> "候选源必须是 biz_jd_product.shop_name DISTINCT: " + sql);
assertTrue(sql.contains("p.shop_name LIKE CONCAT('%', ?, '%')"), () -> "关键词必须 like 下推: " + sql);
assertTrue(sql.contains("p.shop_name NOT IN ( ? , ? )"),
() -> "排除已有名单必须 NOT IN 下推(Java 侧过滤即红,铁律 20): " + sql);
assertTrue(sql.endsWith("ORDER BY p.shop_name LIMIT ?"), () -> "必须按店名升序+LIMIT 收尾: " + sql);
}
private static String render(String id) throws Exception {
return render(id, Map.of("companyId", 1L, "taskId", 34956L));
}
private static String render(String id, Map<String, Object> params) throws Exception {
MappedStatement statement = parse().getMappedStatement(NS + "." + id);
return statement.getBoundSql(Map.of("companyId", 1L, "taskId", 34956L))
return statement.getBoundSql(params)
.getSql().replaceAll("\\s+", " ").trim();
}
@@ -0,0 +1,232 @@
package com.nanri.aiimage.modules.jd.service;
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.JdGroupShopMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdGroupShopEntity;
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* v1.7(V214,2026-11-21 拍板「店铺名单维度完整对齐」原型《商品数据商城》):
* 分类店铺名单业务规则。
*
* <p>判据:批量添加 trim/去空/去重/上限 100/INSERT IGNORE 幂等(全重复=0 不报错)、
* 移除不存在按业务错误拒绝、改名同分类查重 409+老名必须存在、可添加候选
* DISTINCT+like+排除已有名单+limit 钳制 200、分类列表带名单一次批量取。
* <b>读写作用域(谁能看/改哪个分类的名单)不在本类</b>——控制器按分类归属过
* JdCategoryScopeService 的闸(与分类改名/删除同口径)。</p>
*/
class JdGroupShopServiceTest {
private static final long CATEGORY_ID = 3L;
private static final long OPERATOR_ID = 9L;
private final JdGroupShopMapper shopMapper = mock(JdGroupShopMapper.class);
private final JdProductMapper productMapper = mock(JdProductMapper.class);
private final JdGroupShopService service = new JdGroupShopService(shopMapper, productMapper);
@BeforeAll
static void initTableInfo() {
// 探针要读 Lambda wrapper 的 WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了
// (JdProductGroupServiceTest 同款)。
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, JdGroupShopEntity.class);
}
// ===================== 批量添加 =====================
@Test
void 批量添加归一去重后落INSERTIGNORE并带操作者() {
when(shopMapper.insertIgnoreBatch(anyLong(), anyList(), anyLong())).thenReturn(2);
int added = service.addShops(CATEGORY_ID,
java.util.Arrays.asList(" 测试店铺 ", "测试店铺", "", null, "绿屿街道店"), OPERATOR_ID);
assertEquals(2, added, "回执=实际新增行数(幂等跳过不计)");
verify(shopMapper).insertIgnoreBatch(CATEGORY_ID, List.of("测试店铺", "绿屿街道店"), OPERATOR_ID);
}
@Test
void 批量添加空名单与全空白直接拒绝() {
BusinessException empty = assertThrows(BusinessException.class,
() -> service.addShops(CATEGORY_ID, List.of(), OPERATOR_ID));
assertTrue(empty.getMessage().contains("店铺名称列表不能为空"));
verifyNoInteractions(shopMapper);
BusinessException blank = assertThrows(BusinessException.class,
() -> service.addShops(CATEGORY_ID, java.util.Arrays.asList(" ", "", null), OPERATOR_ID));
assertTrue(blank.getMessage().contains("有效店铺名称不能为空"));
verifyNoInteractions(shopMapper);
BusinessException ghost = assertThrows(BusinessException.class,
() -> service.addShops(0L, List.of("测试店铺"), OPERATOR_ID));
assertTrue(ghost.getMessage().contains("分类不存在"));
verifyNoInteractions(shopMapper);
}
@Test
void 批量添加超上限拒绝且不落库() {
List<String> tooMany = new java.util.ArrayList<>();
for (int i = 0; i < JdGroupShopService.MAX_ADD_SHOPS + 1; i++) {
tooMany.add("店铺" + i);
}
BusinessException ex = assertThrows(BusinessException.class,
() -> service.addShops(CATEGORY_ID, tooMany, OPERATOR_ID));
assertTrue(ex.getMessage().contains("100"), "超限文案必须点名上限 100");
verify(shopMapper, never()).insertIgnoreBatch(anyLong(), anyList(), anyLong());
}
// ===================== 移除 =====================
@Test
void 移除限定该分类该店铺且不存在按业务错误拒绝() {
when(shopMapper.delete(any())).thenReturn(1);
assertEquals(1, service.removeShop(CATEGORY_ID, " 测试店铺 "));
ArgumentCaptor<Wrapper<JdGroupShopEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(shopMapper).delete(captor.capture());
var whereEq = UpdateWrapperProbe.whereEq(captor.getValue());
assertEquals(CATEGORY_ID, ((Number) whereEq.get("category_id")).longValue(),
"移除谓词必须限定该分类(别家分类的名单不许动)");
assertEquals("测试店铺", whereEq.get("shop_name"), "移除谓词必须精确店铺名");
when(shopMapper.delete(any())).thenReturn(0);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.removeShop(CATEGORY_ID, "不存在的店"));
assertTrue(ex.getMessage().contains("该分类下不存在此店铺"), "移除 0 行=按不存在拒绝(不静默成功)");
}
// ===================== 改名 =====================
@Test
void 改名撞同分类已有名409且不落库() {
when(shopMapper.selectOne(any())).thenReturn(shopRow(11L, CATEGORY_ID, "旧名"));
when(shopMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.renameShop(CATEGORY_ID, "旧名", "已有名"));
assertEquals(409, ex.getCode(), "同分类重名=409(资源冲突语义)");
assertTrue(ex.getMessage().contains("该分类下已存在同名店铺"));
verify(shopMapper, never()).updateById(any(JdGroupShopEntity.class));
}
@Test
void 改名老名不存在拒绝与原名相同拒绝() {
when(shopMapper.selectOne(any())).thenReturn(null);
BusinessException missing = assertThrows(BusinessException.class,
() -> service.renameShop(CATEGORY_ID, "幽灵店", "新名"));
assertTrue(missing.getMessage().contains("该分类下不存在此店铺"));
verify(shopMapper, never()).updateById(any(JdGroupShopEntity.class));
BusinessException same = assertThrows(BusinessException.class,
() -> service.renameShop(CATEGORY_ID, "同名", " 同名 "));
assertTrue(same.getMessage().contains("新店铺名称不能与原名称相同"));
verifyNoInteractions(productMapper);
}
@Test
void 改名成功只更新名单表本身() {
when(shopMapper.selectOne(any())).thenReturn(shopRow(11L, CATEGORY_ID, "旧名"));
when(shopMapper.selectCount(any())).thenReturn(0L);
service.renameShop(CATEGORY_ID, "旧名", " 新名 ");
ArgumentCaptor<JdGroupShopEntity> captor = ArgumentCaptor.forClass(JdGroupShopEntity.class);
verify(shopMapper).updateById(captor.capture());
assertEquals("新名", captor.getValue().getShopName());
assertEquals(CATEGORY_ID, captor.getValue().getCategoryId(), "改名不得把分类改走");
// 无原型 assignment 同步链:商品行一次都不查(名单改名不碰 biz_jd_product)。
verifyNoInteractions(productMapper);
}
// ===================== 查询 =====================
@Test
void 名单按店名升序且空分类回空() {
when(shopMapper.selectList(any())).thenReturn(List.of(
shopRow(1L, CATEGORY_ID, "B店"), shopRow(2L, CATEGORY_ID, "A店")));
assertEquals(List.of("B店", "A店"), service.listShops(CATEGORY_ID),
"排序由 wrapper 决定,服务不重排(selectList 顺序即返回顺序)");
assertTrue(service.listShops(null).isEmpty(), "越界分类 id 回空(不查库)");
assertTrue(service.listShops(0L).isEmpty());
}
@Test
@SuppressWarnings("unchecked")
void 分类列表带名单按行集id一次批量取() {
when(shopMapper.selectList(any())).thenReturn(List.of(
shopRow(1L, CATEGORY_ID, "B店"), shopRow(2L, CATEGORY_ID, "A店")));
Map<Long, List<String>> byCategory = service.listShopsByCategoryIds(
java.util.Arrays.asList(CATEGORY_ID, CATEGORY_ID, null, 0L, 99L));
assertEquals(List.of("B店", "A店"), byCategory.get(CATEGORY_ID), "一次批量取(无逐行查询)");
assertTrue(byCategory.getOrDefault(99L, List.of()).isEmpty(), "无名单分类=空,不猜");
assertTrue(service.listShopsByCategoryIds(List.of()).isEmpty(), "空清单不生成 IN ()");
assertTrue(service.listShopsByCategoryIds(null).isEmpty());
ArgumentCaptor<Wrapper<JdGroupShopEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(shopMapper).selectList(captor.capture());
captor.getValue().getSqlSegment();
assertTrue(captor.getValue().getSqlSegment().toUpperCase().contains(" IN "),
"多分类走 IN 谓词:实得 " + captor.getValue().getSqlSegment());
}
// ===================== 可添加候选 =====================
@Test
void 可添加候选排除已有名单且limit钳制() {
when(shopMapper.selectList(any())).thenReturn(List.of(shopRow(1L, CATEGORY_ID, "已有店A")));
when(productMapper.selectDistinctShopNames("旗", List.of("已有店A"), 200))
.thenReturn(List.of("旗舷店"));
assertEquals(List.of("旗舷店"),
service.availableShops(" 旗 ", CATEGORY_ID, null), "keyword trim 后下推;limit 缺省钳到 200");
// limit 钳制:500 请求 → 200(服务侧钳,mapper 不做第二次换算)。
service.availableShops(null, CATEGORY_ID, 500);
verify(productMapper).selectDistinctShopNames(null, List.of("已有店A"), 200);
// 不带排除分类:excludeNames 空清单(不生成 NOT IN);前两轮各查过一次名单表,共两次。
when(productMapper.selectDistinctShopNames(null, List.of(), 50)).thenReturn(List.of("直接店"));
assertEquals(List.of("直接店"), service.availableShops(null, null, 50));
verify(shopMapper, times(2)).selectList(any());
}
// ---------------------------------------------------------------- 助手
private static JdGroupShopEntity shopRow(long id, long categoryId, String shopName) {
JdGroupShopEntity entity = new JdGroupShopEntity();
entity.setId(id);
entity.setCategoryId(categoryId);
entity.setShopName(shopName);
entity.setCreatedBy(OPERATOR_ID);
entity.setCreatedAt(LocalDateTime.of(2026, 11, 21, 10, 0));
return entity;
}
}
@@ -48,7 +48,10 @@ class JdProductGroupServiceTest {
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
private final JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, assignMapper);
private final com.nanri.aiimage.modules.jd.service.JdGroupShopService groupShopService =
mock(com.nanri.aiimage.modules.jd.service.JdGroupShopService.class);
private final JdProductGroupService service =
new JdProductGroupService(groupMapper, assignMapper, groupShopService);
@BeforeAll
static void initTableInfo() {
@@ -60,6 +63,11 @@ class JdProductGroupServiceTest {
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
}
/** 名单服务默认空桩(V214 列表带 shops[]:未指定时全空名单,不 NPE)。 */
private void stubNoShops() {
when(groupShopService.listShopsByCategoryIds(any())).thenReturn(java.util.Map.of());
}
// ===================== 新建 =====================
@Test
@@ -222,6 +230,7 @@ class JdProductGroupServiceTest {
@Test
@SuppressWarnings("unchecked")
void 列表按当前分组取且productCount按归属表现算() {
stubNoShops();
JdProductGroupEntity first = categoryEntity(2L, "晚出厂");
first.setSortOrder(0);
JdProductGroupEntity second = categoryEntity(1L, "早出厂");
@@ -257,10 +266,32 @@ class JdProductGroupServiceTest {
assertTrue(service.list(0L).isEmpty());
verifyNoInteractions(groupMapper);
verifyNoInteractions(assignMapper);
verifyNoInteractions(groupShopService);
}
/** V214(v1.7 店铺名单):列表行带 shops[],按行集 id 一次批量取;无名单分类落空数组。 */
@Test
void 列表行带店铺名单_一次批量取_无名单落空数组() {
JdProductGroupEntity withShops = categoryEntity(2L, "晚出厂");
withShops.setSortOrder(0);
JdProductGroupEntity withoutShops = categoryEntity(1L, "早出厂");
withoutShops.setSortOrder(1);
when(groupMapper.selectList(any())).thenReturn(List.of(withShops, withoutShops));
when(assignMapper.selectCount(any())).thenReturn(0L, 0L);
when(groupShopService.listShopsByCategoryIds(any()))
.thenReturn(java.util.Map.of(2L, java.util.List.of("B店", "A店")));
List<JdProductGroupVo> items = service.list(GROUP_ID);
assertEquals(java.util.List.of("B店", "A店"), items.get(0).getShops(),
"名单按行集 id 批量补(JdGroupShopService 一次查询,无逐行)");
assertNotNull(items.get(1).getShops(), "无名单分类的 shops 必须是空数组不是 null(前端展开箭头判据)");
assertTrue(items.get(1).getShops().isEmpty());
}
@Test
void 多组并集取分类_空清单不生成IN查询() {
stubNoShops();
JdProductGroupEntity row = categoryEntity(2L, "晚出厂");
when(groupMapper.selectList(any())).thenReturn(List.of(row));
when(assignMapper.selectCount(any())).thenReturn(0L);
@@ -141,7 +141,8 @@ class JdProductQueryServiceUserPageTest {
JdProductPageVo zero = service.pageForUser(7L, null, 0L, 5000L);
assertThat(zero.getPage()).as("页码下限钳到 1").isEqualTo(1L);
assertThat(zero.getPageSize()).as("页宽上限钳到 100").isEqualTo(100L);
assertThat(zero.getPageSize()).as("页宽上限钳到 1000(v1.7 对齐原型档位放宽,与后管只读页同出口)")
.isEqualTo(1000L);
JdProductPageVo huge = service.pageForUser(7L, null, Long.MAX_VALUE, 20L);
assertThat(huge.getPage()).as("页码上限钳到 10000(乘积不溢出,铁律 15 同形)").isEqualTo(10000L);