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) {