feat(jd): 编辑抽屉图片区(×右上角+替换/新增本地图)+详情抽屉改京麦左图右信息布局(B109-01 落地)

This commit is contained in:
2026-11-16 02:20:17 +08:00
parent dca5d6f554
commit 2a4598216a
9 changed files with 952 additions and 51 deletions
@@ -29,6 +29,7 @@ import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -38,6 +39,7 @@ 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 org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;
@@ -162,6 +164,30 @@ public class AdminJdProductController {
return ApiResponse.success(jdProductQueryService.detail(updatedId));
}
@PostMapping(value = "/{id}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上传/替换商品图片", description = "multipart 后端中转(管理面低频单张,不走采集端"
+ " presign 直传链):objectKey 由服务端按上传字节 SHA-256 内容寻址生成(铁律 32 同形,前端"
+ "不自造 key);replace_image_id 有值=替换该登记行(档位继承原行,旧对象共用保留),缺省="
+ "新增(image_type=MAIN/ATTR/DETAIL,ATTR 必须带 attr_name)。上传/替换即置人工编辑锁"
+ "(manual_locked=1)并按表实数刷 image_count/main_image_url。返回刷新后的详情。")
public ApiResponse<JdProductDetailVo> uploadImage(
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
@Parameter(description = "图片文件(jpg/png/webp/gif,≤10MB)") @RequestParam("file") MultipartFile file,
@Parameter(description = "新增时的分区:MAIN/ATTR/DETAIL(替换时忽略、继承原行档位)")
@RequestParam(value = "image_type", required = false) String imageType,
@Parameter(description = "ATTR 分区的属性名(新增 ATTR 时必填)")
@RequestParam(value = "attr_name", required = false) String attrName,
@Parameter(description = "替换目标图片登记行 id(缺省=新增)")
@RequestParam(value = "replace_image_id", required = false) Long replaceImageId,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
Long updatedId = jdProductUpdateService.uploadImage(id, file, imageType, attrName, replaceImageId);
log.info("[jd-product] 上传图片 operatorId={} id={} replaceImageId={} imageType={}",
operator.id(), updatedId, replaceImageId, imageType);
// 返回刷新后的详情(前端上传后直接回填抽屉图片区),复用详情同一查询出口。
return ApiResponse.success(jdProductQueryService.detail(updatedId));
}
@DeleteMapping("/{id}")
@Operation(summary = "删除单个京东商品", description = "先删 jd-products 桶内该商品的图片对象、"
+ "全部成功后才删库行(SKU → 图片登记 → 商品行);被其他商品共用的图片对象保留。"
@@ -20,11 +20,15 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -65,6 +69,25 @@ public class JdProductUpdateService {
/** 单次删图上限(与登记链单商品图片量级同档)。 */
private static final int MAX_IMAGE_DELETES = 500;
// ---------- 图片上传/替换(POST /{id}/images,2026-11-16 客户口径「删除做打叉 icon 放图右上角,
// 支持编辑替换本地的图」;B109-01 上传链路欠账落地) ----------
/** 图片档词表(与 JdProductImageIngestService.V194 image_type 同词表;管理面明确拒绝不静默归 MAIN)。 */
private static final Set<String> UPLOAD_IMAGE_TYPES = Set.of("MAIN", "ATTR", "DETAIL");
/** 管理面上传接受的 MIME(与登记链 MIME_EXTENSIONS 同词表)。 */
private static final Set<String> UPLOAD_MIME_TYPES = Set.of("image/jpeg", "image/png", "image/webp", "image/gif");
/** MIME → 对象扩展名(与 JdProductImageIngestService 同映射)。 */
private static final Map<String, String> UPLOAD_MIME_EXTENSIONS = Map.of(
"image/jpeg", ".jpg",
"image/png", ".png",
"image/webp", ".webp",
"image/gif", ".gif");
/** 管理面单张图片上限(商品图 KB~MB 量级;multipart 全局上限 2GB 与本闸无关,业务闸自己收紧)。 */
private static final long MAX_UPLOAD_BYTES = 10L * 1024 * 1024;
private final JdProductMapper jdProductMapper;
private final JdProductSkuMapper jdProductSkuMapper;
private final JdProductImageMapper jdProductImageMapper;
@@ -433,6 +456,203 @@ public class JdProductUpdateService {
return purged;
}
// ---------- 图片上传/替换(B109-01 落地,2026-11-16 客户口径) ----------
/**
* 后管上传/替换商品图片(multipart 后端中转:管理面低频单张操作,不走采集端 presign 直传链)。
*
* <p>数据面三件事(铁律 32 同形):① 独立桶 {@code jd-products};② objectKey 由服务端
* 内容寻址生成(对上传字节算 SHA-256 拼 key,前端不自造 key);③ 落库字节数就是上传
* 字节本身(中转模式服务端持有字节,无「登记与对象对撞」窗口)。</p>
*
* <ul>
* <li><b>替换</b>({@code replaceImageId} 有值):原行必须挂在本商品上;档位
* (imageType/attrName/sortNo)继承原行——用户换的是「这一格」的图,不改分区。
* 新对象落桶 → 原行更新指向 → 旧对象共用回查后删桶(被其他商品引用则保留,
* 同 {@link #deleteImages} 语义);删旧对象失败只记 WARN 不拒绝——行已指向新 key,
* 残留只是存储垃圾,为它把用户已成功的替换整笔回滚(新桶对象成孤儿)不划算。</li>
* <li><b>新增</b>:imageType 必须在词表内(明确拒绝,不静默归 MAIN),ATTR 必须带
* attrName;sortNo 同区内 max+1。</li>
* <li><b>置锁</b>:上传/替换即 {@code manual_locked=1}(与编辑保存/归类同口径)——
* 采集 upsert/覆盖清理此后跳过本行,人工图不被重爬冲掉。</li>
* <li><b>投影刷新</b>:image_count 与 main_image_url 按表实数刷
* (与 JdProductImageIngestService.refreshProductImageProjection 同形状)。</li>
* </ul>
*
* @return 商品行 id(控制器用它回读刷新后的详情 VO)
*/
@Transactional(rollbackFor = Exception.class)
public Long uploadImage(Long id, MultipartFile file, String imageType, String attrName, Long replaceImageId) {
if (id == null || id <= 0) {
throw new BusinessException("商品不存在");
}
JdProductEntity row = jdProductMapper.selectById(id);
if (row == null) {
throw new BusinessException("商品不存在");
}
if (file == null || file.isEmpty()) {
throw new BusinessException("请选择要上传的图片文件");
}
if (file.getSize() > MAX_UPLOAD_BYTES) {
throw new BusinessException("单张图片不能超过 10MB");
}
String contentType = file.getContentType() == null ? "" : file.getContentType().trim().toLowerCase(Locale.ROOT);
if (!UPLOAD_MIME_TYPES.contains(contentType)) {
throw new BusinessException("只支持 jpg / png / webp / gif 图片");
}
byte[] bytes;
try {
bytes = file.getBytes();
} catch (java.io.IOException ex) {
throw new BusinessException("读取上传图片失败,请重试");
}
String sha256 = sha256Hex(bytes);
JdProductImageEntity target;
String oldKey = null;
if (replaceImageId != null) {
target = jdProductImageMapper.selectOne(new LambdaQueryWrapper<JdProductImageEntity>()
.eq(JdProductImageEntity::getId, replaceImageId)
.eq(JdProductImageEntity::getProductId, row.getId()));
if (target == null) {
throw new BusinessException("要替换的图片不存在或不属于该商品,请刷新后重试");
}
oldKey = target.getObjectKey();
} else {
String normalizedType = imageType == null ? "" : imageType.trim().toUpperCase(Locale.ROOT);
if (!UPLOAD_IMAGE_TYPES.contains(normalizedType)) {
throw new BusinessException("图片分区只支持 主图 / 属性图 / 详情图");
}
String normalizedAttr = trimToNull(attrName);
if ("ATTR".equals(normalizedType) && normalizedAttr == null) {
throw new BusinessException("属性图必须带属性名");
}
target = new JdProductImageEntity();
target.setProductId(row.getId());
target.setCompanyId(row.getCompanyId());
target.setImageType(normalizedType);
target.setAttrName("ATTR".equals(normalizedType) ? normalizedAttr : null);
target.setSortNo(nextUploadSortNo(row.getId(), normalizedType));
}
// objectKey 服务端内容寻址生成;同内容对象已在桶里时跳过重传(与登记链 presign 命中既有对象同形)。
String objectKey = buildUploadObjectKey(row.getCompanyId(), sha256, contentType);
long existingSize = ossStorageService.objectSize(bucket, objectKey);
if (existingSize < 0) {
try {
ossStorageService.uploadBytes(bucket, objectKey, bytes, contentType);
} catch (RuntimeException ex) {
throw new BusinessException(
UserMessages.with("图片上传存储失败,请稍后重试", ex), ex);
}
}
target.setObjectKey(objectKey);
target.setUrl(ossStorageService.getBucketObjectUrl(bucket, objectKey));
target.setByteSize((long) bytes.length);
target.setSha256(sha256);
target.setWidth(null);
target.setHeight(null);
if (replaceImageId != null) {
jdProductImageMapper.updateById(target);
} else {
jdProductImageMapper.insert(target);
}
if (oldKey != null) {
purgeReplacedObject(row.getId(), oldKey);
}
// 人工干预置锁(与编辑保存/归类同口径):采集 upsert/覆盖清理此后跳过本行。
jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
.eq(JdProductEntity::getId, row.getId())
.set(JdProductEntity::getManualLocked, 1));
refreshImageProjection(row.getId());
log.info("[{}] 图片上传完成 productId={} companyId={} replace={} imageType={} objectKey={} bytes={} locked=1",
LOG_TAG, row.getId(), row.getCompanyId(), replaceImageId != null,
target.getImageType(), objectKey, bytes.length);
return row.getId();
}
/** 替换后旧对象清理:共用(同 key 被其他商品引用)或前缀外不删;删除失败只记 WARN
* 不拒绝——行已指向新 key,残留只是存储垃圾,不值得为它回滚整笔替换。 */
private void purgeReplacedObject(Long productId, String oldKey) {
String key = oldKey == null ? "" : oldKey.trim();
if (key.isEmpty() || keyPrefix == null || keyPrefix.isEmpty() || !key.startsWith(keyPrefix)) {
return;
}
Long shared = jdProductImageMapper.selectCount(new LambdaQueryWrapper<JdProductImageEntity>()
.eq(JdProductImageEntity::getObjectKey, key)
.ne(JdProductImageEntity::getProductId, productId));
if (shared != null && shared > 0) {
return;
}
try {
ossStorageService.removeObject(bucket, key);
} catch (RuntimeException ex) {
log.warn("[{}] 替换后旧对象清理失败(行已指向新 key,仅存储垃圾)productId={} key={} err={}",
LOG_TAG, productId, key, ex.getMessage());
}
}
/** 新增图排序号:同 (productId, imageType) 区内 max+1(同区追加,不扰动采集登记的既有排序)。 */
private Integer nextUploadSortNo(Long productId, String imageType) {
List<JdProductImageEntity> rows = jdProductImageMapper.selectList(
new LambdaQueryWrapper<JdProductImageEntity>()
.select(JdProductImageEntity::getSortNo)
.eq(JdProductImageEntity::getProductId, productId)
.eq(JdProductImageEntity::getImageType, imageType));
int max = 0;
if (rows != null) {
for (JdProductImageEntity existing : rows) {
if (existing.getSortNo() != null && existing.getSortNo() > max) {
max = existing.getSortNo();
}
}
}
return max + 1;
}
/** 内容寻址 objectKey(与 JdProductImageIngestService.buildObjectKey 同形状;companyId 缺省 0 段)。 */
private String buildUploadObjectKey(Long companyId, String sha256, String contentType) {
String ext = UPLOAD_MIME_EXTENSIONS.getOrDefault(contentType, ".bin");
return keyPrefix + (companyId == null ? 0L : companyId) + "/" + sha256 + ext;
}
/** 上传/替换后把图片投影刷成表实数:image_count + main_image_url
* (与 JdProductImageIngestService.refreshProductImageProjection 同形状,B98-01 口径)。 */
private void refreshImageProjection(Long productId) {
Long total = jdProductImageMapper.selectCount(new LambdaQueryWrapper<JdProductImageEntity>()
.eq(JdProductImageEntity::getProductId, productId));
String mainImageUrl = null;
List<JdProductImageEntity> mains = jdProductImageMapper.selectList(
new LambdaQueryWrapper<JdProductImageEntity>()
.eq(JdProductImageEntity::getProductId, productId)
.eq(JdProductImageEntity::getImageType, "MAIN")
.orderByAsc(JdProductImageEntity::getSortNo)
.orderByAsc(JdProductImageEntity::getId)
.last("limit 1"));
if (mains != null && !mains.isEmpty()) {
mainImageUrl = mains.get(0).getUrl();
}
jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
.eq(JdProductEntity::getId, productId)
.set(JdProductEntity::getImageCount, total == null ? 0 : total.intValue())
.set(JdProductEntity::getMainImageUrl, mainImageUrl));
}
/** 上传字节 SHA-256 十六进制小写(内容寻址 key 用)。 */
private static String sha256Hex(byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
StringBuilder out = new StringBuilder(64);
for (byte b : digest.digest(bytes)) {
out.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
}
return out.toString();
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("SHA-256 摘要算法不可用", ex);
}
}
// ---------- 公共小件 ----------
private static String trimToNull(String value) {
@@ -84,7 +84,9 @@ class CatchSilenceRatchetTest {
// 与外层登记失败 log.error 不推翻删除本体(log.error);另 1 枚来自同窗另一路会话的类目下拉
// 在飞件(本笔 diff 只有上述 3 枚 NOT_RETHROW 形状,逐文件 HEAD 对比 JD 包净增 catch=5,
// 实测读数 624 ⇒ 差的 1 枚不在本笔文件里,随该会话自己的收尾记名)。
static final int GIVEN_NOT_RETHROW = 624;
// 11-16 京东编辑抽屉图片上传/替换抬 624 -> 625:purgeReplacedObject 旧对象清理失败
// log.warn 不抛一枚(行已指向新 key,残留只是存储垃圾),出处见 STRICT_TOTAL 上方 11-16 段。
static final int GIVEN_NOT_RETHROW = 625;
static final int GIVEN_LOG_ONLY = 251;
static final int GIVEN_EMPTY = 56;
@@ -402,7 +404,14 @@ class CatchSilenceRatchetTest {
// log.error 不推翻删除本体(LOG_ONLY,误差方向=重爬可能复活需人工补登记,已在文案点名);
// ⑥ JdProductDeleteService 删库行失败 log.error 后重抛(RETHROW,桶已删需人工核对,只进 total
// 与 RETHROW 下限格)。NOT_RETHROW/LOG_ONLY 两格随之各 +3/+2(见各自常量上方 11-15 段)。
static final int STRICT_TOTAL = 1104;
// 11-16 京东编辑抽屉图片上传/替换(POST /{id}/images,2026-11-16 客户口径「× 右上角+替换本地图」,
// B109-01 落地)抬 1104 -> 1107,净新增 3 枚——① JdProductUpdateService.uploadImage 读上传字节
// `catch IOException` → BusinessException「读取上传图片失败,请重试」(RETHROW,multipart 读取
// 失败不裸 500);② 同方法 uploadBytes `catch RuntimeException` → UserMessages.with 包 BusinessException
// (RETHROW,与 deleteImages 同纪律:异常原文不进界面、整笔拒绝可安全重试);
// ③ JdProductUpdateService.purgeReplacedObject 的旧对象清理失败 log.warn 不抛(LOG_ONLY,块内仅
// 一句 log)——替换行已指向新 key,残留只是存储垃圾,为它回滚用户已成功的替换不划算。
static final int STRICT_TOTAL = 1107;
/**
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
@@ -469,7 +478,10 @@ class CatchSilenceRatchetTest {
// BusinessException「导出京东数据库失败,请稍后重试」`是 RETHROW 形状,随死代码一起离开树;
// 同窗撤掉的 sale_status 筛选参数无 catch。不重抛/只 log/空体三格上限原样未动(绿即未涨),
// 没有任何一处「异常会往外走」被改回吞掉——这是整段功能下线,不是改出口方向。
static final int RETHROW_FLOOR = 381;
// 11-16 再上调 381 -> 383,出处见 STRICT_TOTAL 上方 11-16 段:京东编辑抽屉图片上传/替换
// 新增 2 枚 RETHROW(multipart 读字节失败 → BusinessException;uploadBytes 存储失败整笔拒绝)。
// 这是下限不是上限:重抛枚数变多 = 又有两处异常被改成往外走,只许涨。
static final int RETHROW_FLOOR = 383;
/**
* 10-17 抬 559 -> 561,逐处记名(两处都是新增的 fail-open 证据读写,不是把已有出口改回吞掉):
* 1){@code TaskHeartbeatLivenessService.stamp()}:心跳证据写失败只 WARN——心跳接口不许因为
@@ -551,7 +563,9 @@ class CatchSilenceRatchetTest {
// 11-15 京东 B101/B102 收口:严格口径实测 616 -> 619(三枚不重抛含 log:两枚落 LOG_ONLY、
// 一枚 log+return,出处见 STRICT_TOTAL 上方 11-15 段)。
// 11-15 京东任务面板改版 619 -> 620:JdCollectBoardService 旧建单载荷解析兜底一枚(见 STRICT_TOTAL 上方)。
static final int STRICT_NOT_RETHROW = 624;
// 11-16 图片上传/替换 624 -> 625:purgeReplacedObject 旧对象清理 WARN 一枚(LOG_ONLY 连带
// 占本格额度——本格含 LOG_ONLY 口径,出处见 STRICT_TOTAL 上方 11-16 段)。
static final int STRICT_NOT_RETHROW = 625;
/**
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
@@ -589,8 +603,10 @@ class CatchSilenceRatchetTest {
* (块内仅一句 log.info)+外层登记失败 log.error 不推翻删除本体(块内仅一句 log.error),
* 出处即 STRICT_TOTAL 上方 11-15 V199 段的 ④⑤——该段写明「LOG_ONLY 随之 +2」但常量漏抬,
* 两枚都是带锚点的 fail-open(MP 无 insert ignore),不是把已有出口改回吞掉。
* 11-16 抬 198 -> 199:{@code JdProductUpdateService.purgeReplacedObject} 替换后旧对象清理
* 失败只 WARN(行已指向新 key,残留只是存储垃圾),出处即 STRICT_TOTAL 上方 11-16 段的 ③。
*/
static final int STRICT_LOG_ONLY = 198; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1、11-14 v1.4 建单 scope 行 DuplicateKeyException 复用先到行 +1,见 STRICT_TOTAL 上方)
static final int STRICT_LOG_ONLY = 199; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1、11-14 v1.4 建单 scope 行 DuplicateKeyException 复用先到行 +1、11-16 图片替换旧对象清理 +1,见 STRICT_TOTAL 上方)
static final int STRICT_EMPTY = 56;
/**
@@ -389,4 +389,142 @@ class JdProductUpdateServiceTest {
verify(jdProductSkuMapper, never()).selectList(any());
verify(jdProductImageMapper, never()).delete(any(Wrapper.class));
}
// ---------- 图片上传/替换(POST /{id}/images,2026-11-16 客户口径,B109-01 落地) ----------
private org.springframework.mock.web.MockMultipartFile pngFile(byte[] content) {
return new org.springframework.mock.web.MockMultipartFile("file", "替换.png", "image/png", content);
}
private static String sha256Of(byte[] bytes) throws Exception {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
StringBuilder out = new StringBuilder(64);
for (byte b : digest.digest(bytes)) {
out.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
}
return out.toString();
}
@Test
void 新增主图_objectKey服务端内容寻址生成_同内容命中既有对象不重传_置锁并刷投影() throws Exception {
givenOwnedRow();
byte[] content = {1, 2, 3, 4};
String key = "jd-products/5/" + sha256Of(content) + ".png";
// 同区既有 sortNo=3 → 新增行 sortNo=4;同内容对象已在桶里(objectSize≥0)→ 不重传
JdProductImageEntity existing = new JdProductImageEntity();
existing.setSortNo(3);
when(jdProductImageMapper.selectList(any())).thenReturn(List.of(existing));
when(ossStorageService.objectSize("jd-products", key)).thenReturn((long) content.length);
when(ossStorageService.getBucketObjectUrl("jd-products", key)).thenReturn("https://oss.example/" + key);
when(jdProductImageMapper.insert(any(JdProductImageEntity.class))).thenReturn(1);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
service.uploadImage(PRODUCT_ID, pngFile(content), "MAIN", null, null);
ArgumentCaptor<JdProductImageEntity> rowCaptor = ArgumentCaptor.forClass(JdProductImageEntity.class);
verify(jdProductImageMapper).insert(rowCaptor.capture());
JdProductImageEntity inserted = rowCaptor.getValue();
assertThat(inserted.getObjectKey()).isEqualTo(key);
assertThat(inserted.getImageType()).isEqualTo("MAIN");
assertThat(inserted.getSha256()).isEqualTo(sha256Of(content));
assertThat(inserted.getByteSize()).isEqualTo((long) content.length);
assertThat(inserted.getSortNo()).isEqualTo(4);
assertThat(inserted.getUrl()).contains(key);
verify(ossStorageService, never()).uploadBytes(any(), any(), any(), any());
// 置锁+投影刷新=两次 update:第 1 笔 SET 带 manual_locked(人工锁本体),
// 第 2 笔 SET 带 image_count/main_image_url(B98-01 投影形状)。
verify(jdProductMapper, org.mockito.Mockito.times(2)).update(isNull(), any(Wrapper.class));
ArgumentCaptor<Wrapper<JdProductEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
org.mockito.Mockito.verify(jdProductMapper, org.mockito.Mockito.times(2))
.update(isNull(), wrapperCaptor.capture());
String lockSqlSet = ((LambdaUpdateWrapper<JdProductEntity>) wrapperCaptor.getAllValues().get(0)).getSqlSet();
String projectionSqlSet = ((LambdaUpdateWrapper<JdProductEntity>) wrapperCaptor.getAllValues().get(1)).getSqlSet();
assertThat(lockSqlSet).contains("manual_locked");
assertThat(projectionSqlSet).contains("image_count").contains("main_image_url");
}
@Test
void 替换图片_档位继承原行_新对象落桶_旧对象非共用即删_共用保留() throws Exception {
givenOwnedRow();
byte[] content = {9, 8, 7};
String newKey = "jd-products/5/" + sha256Of(content) + ".png";
JdProductImageEntity original = new JdProductImageEntity();
original.setId(7L);
original.setProductId(PRODUCT_ID);
original.setImageType("DETAIL");
original.setAttrName(null);
original.setSortNo(2);
original.setObjectKey("jd-products/5/old.jpg");
original.setUrl("https://oss.example/jd-products/5/old.jpg");
when(jdProductImageMapper.selectOne(any())).thenReturn(original);
when(ossStorageService.objectSize("jd-products", newKey)).thenReturn(-1L);
when(ossStorageService.getBucketObjectUrl("jd-products", newKey)).thenReturn("https://oss.example/" + newKey);
// 共用回查:没有其他商品引用旧 key → 删桶
when(jdProductImageMapper.selectCount(any())).thenReturn(0L);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
service.uploadImage(PRODUCT_ID, pngFile(content), null, null, 7L);
verify(ossStorageService).uploadBytes(eq("jd-products"), eq(newKey), any(), eq("image/png"));
ArgumentCaptor<JdProductImageEntity> rowCaptor = ArgumentCaptor.forClass(JdProductImageEntity.class);
verify(jdProductImageMapper).updateById(rowCaptor.capture());
JdProductImageEntity updated = rowCaptor.getValue();
assertThat(updated.getId()).isEqualTo(7L);
assertThat(updated.getObjectKey()).isEqualTo(newKey);
assertThat(updated.getImageType()).isEqualTo("DETAIL");
assertThat(updated.getSortNo()).isEqualTo(2);
verify(ossStorageService).removeObject("jd-products", "jd-products/5/old.jpg");
}
@Test
void 替换图片_旧对象被其他商品引用则保留() throws Exception {
givenOwnedRow();
byte[] content = {5, 5};
JdProductImageEntity original = new JdProductImageEntity();
original.setId(7L);
original.setProductId(PRODUCT_ID);
original.setImageType("MAIN");
original.setObjectKey("jd-products/5/shared.jpg");
when(jdProductImageMapper.selectOne(any())).thenReturn(original);
when(ossStorageService.objectSize(any(), any())).thenReturn(-1L);
when(ossStorageService.getBucketObjectUrl(any(), any())).thenReturn("https://oss.example/x");
when(jdProductImageMapper.selectCount(any())).thenReturn(1L);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
service.uploadImage(PRODUCT_ID, pngFile(content), null, null, 7L);
verify(ossStorageService, never()).removeObject(eq("jd-products"), eq("jd-products/5/shared.jpg"));
}
@Test
void 替换目标不属于本商品_明确拒绝() {
givenOwnedRow();
when(jdProductImageMapper.selectOne(any())).thenReturn(null);
assertThatThrownBy(() -> service.uploadImage(PRODUCT_ID, pngFile(new byte[]{1}), null, null, 99L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("不属于该商品");
verify(ossStorageService, never()).uploadBytes(any(), any(), any(), any());
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 新增ATTR缺属性名与类型词表外_MIME不支持_空文件_全部明确拒绝() {
givenOwnedRow();
assertThatThrownBy(() -> service.uploadImage(PRODUCT_ID, pngFile(new byte[]{1}), "ATTR", " ", null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("属性图必须带属性名");
assertThatThrownBy(() -> service.uploadImage(PRODUCT_ID, pngFile(new byte[]{1}), "COVER", null, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("主图 / 属性图 / 详情图");
assertThatThrownBy(() -> service.uploadImage(PRODUCT_ID,
new org.springframework.mock.web.MockMultipartFile("file", "a.gif", "image/bmp", new byte[]{1}),
"MAIN", null, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只支持 jpg / png / webp / gif");
assertThatThrownBy(() -> service.uploadImage(PRODUCT_ID, pngFile(new byte[]{}), "MAIN", null, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请选择要上传的图片文件");
verify(jdProductImageMapper, never()).insert(any(JdProductImageEntity.class));
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
}
@@ -91,8 +91,14 @@ class TaskFailureCategoryGuardrailTest {
* (TaskScopeStateEntity 无 ALWAYS 字段,且写前经合并读回,铁律 30)。三处传入实体都不带
* ALWAYS 家族列(ALWAYS 只在 PriceTrackLoopRun/ShopKey/SkipPriceAsin/FileTask 四实体),
* 审过无抹列风险后登记基线。
*
* <p>162 → 163:2026-11-16 京东编辑抽屉图片上传/替换(POST /{id}/images,B109-01 落地)
* 新增一处——{@code JdProductUpdateService.uploadImage} 替换分支对原登记行
* {@code jdProductImageMapper.updateById(target)}(JdProductImageEntity 无 ALWAYS 字段;
* target 是 selectOne 读回的新鲜行,替换语义本就是全字段覆写 objectKey/url/byteSize/sha256,
* 不涉抹列风险)。审过后登记基线。
*/
private static final int REGISTERED_UPDATE_BY_ID_SITES = 162;
private static final int REGISTERED_UPDATE_BY_ID_SITES = 163;
@Test
void 任务失败文案写点必须同笔写分类列() {