From 2a4598216a8416983f01b32ebb37d294eea38bd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Mon, 16 Nov 2026 02:20:17 +0800 Subject: [PATCH] =?UTF-8?q?feat(jd):=20=E7=BC=96=E8=BE=91=E6=8A=BD?= =?UTF-8?q?=E5=B1=89=E5=9B=BE=E7=89=87=E5=8C=BA=EF=BC=88=C3=97=E5=8F=B3?= =?UTF-8?q?=E4=B8=8A=E8=A7=92=EF=BC=8B=E6=9B=BF=E6=8D=A2/=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=9C=AC=E5=9C=B0=E5=9B=BE=EF=BC=89=EF=BC=8B=E8=AF=A6?= =?UTF-8?q?=E6=83=85=E6=8A=BD=E5=B1=89=E6=94=B9=E4=BA=AC=E9=BA=A6=E5=B7=A6?= =?UTF-8?q?=E5=9B=BE=E5=8F=B3=E4=BF=A1=E6=81=AF=E5=B8=83=E5=B1=80=EF=BC=88?= =?UTF-8?q?B109-01=20=E8=90=BD=E5=9C=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/pages/jd/JdProductDetailDrawer.vue | 173 ++++++++++++-- .../src/pages/jd/JdProductEditDrawer.vue | 208 +++++++++++++++-- .../src/pages/jd/jd-product-api.ts | 30 +++ .../mount/jd-edit-drawer-images.mount.test.ts | 174 ++++++++++++++ .../controller/AdminJdProductController.java | 26 +++ .../jd/service/JdProductUpdateService.java | 220 ++++++++++++++++++ .../config/CatchSilenceRatchetTest.java | 26 ++- .../service/JdProductUpdateServiceTest.java | 138 +++++++++++ .../TaskFailureCategoryGuardrailTest.java | 8 +- 9 files changed, 952 insertions(+), 51 deletions(-) create mode 100644 admin-frontend-vue/tests/mount/jd-edit-drawer-images.mount.test.ts diff --git a/admin-frontend-vue/src/pages/jd/JdProductDetailDrawer.vue b/admin-frontend-vue/src/pages/jd/JdProductDetailDrawer.vue index 57fa47b42..3401c1e38 100644 --- a/admin-frontend-vue/src/pages/jd/JdProductDetailDrawer.vue +++ b/admin-frontend-vue/src/pages/jd/JdProductDetailDrawer.vue @@ -41,6 +41,15 @@ function skuAttrValue(sku: JdProductSku, dimension: string): string { /** 图片三区:MAIN / ATTR / DETAIL;未知类型归 DETAIL 之外的「其他」,不丢。 */ const mainImages = computed(() => images.value.filter((image) => image.imageType === 'MAIN')) + +/** 顶部画廊(2026-11-16 客户口径「详情页样式和京麦商品详情一样」=左图右信息): + * 左侧主图大图+缩略图切换(MAIN 档),右侧关键信息。 */ +const galleryImages = computed(() => mainImages.value) +const activeImageUrl = ref('') + +function switchGallery(image: JdProductImage): void { + activeImageUrl.value = image.url +} const attrImageGroups = computed(() => { const buckets = new Map() for (const image of images.value) { @@ -86,6 +95,7 @@ async function loadDetail(): Promise { images.value = detail.images skus.value = detail.skus attrJsonRaw.value = detail.attrJsonRaw + activeImageUrl.value = detail.images.find((image) => image.imageType === 'MAIN')?.url || '' if (!detail.attrGroups.length && detail.attrJsonRaw) { // 结构化解析失败但原文在:兜底展示原文,不静默吞 loadFailure.value = '' @@ -102,6 +112,7 @@ watch( ([visible]) => { previewVisible.value = false previewUrl.value = '' + activeImageUrl.value = '' if (visible && props.item) void loadDetail() }, ) @@ -128,30 +139,56 @@ function dash(value: string | number | null | undefined): string {

加载中...

@@ -604,6 +684,33 @@ function dash(value: string | number | null | undefined): string { font-size: 12px; color: #4e6479; } +.image-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.image-head h4 { + margin: 0; +} +.btn-add-image { + min-height: 30px; + padding: 4px 12px; + border: 1px solid #95b1cb; + border-radius: 8px; + background: #ffffff; + color: #2f5d8b; + font-size: 12.5px; + cursor: pointer; + white-space: nowrap; +} +.btn-add-image:hover { + background: #edf5fb; +} +.btn-add-image:disabled { + opacity: 0.55; + cursor: not-allowed; +} .image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); @@ -621,28 +728,83 @@ function dash(value: string | number | null | undefined): string { border-radius: 8px; background: #f2f7fb; } -.image-cell.marked img { +.image-cell img.dimmed { opacity: 0.35; +} +.image-cell.marked img { outline: 2px solid #d08a7b; } -.image-del { +/* 右上角 × 删除标记(京麦样式):hover 格子时出现;已标删常显。 */ +.image-x { position: absolute; - right: 6px; - bottom: 6px; - border: 1px solid #e4b3a8; - border-radius: 6px; - background: rgba(255, 255, 255, 0.92); - color: #a04432; - font-size: 12px; - padding: 3px 8px; + top: 4px; + right: 4px; + display: none; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + border: none; + border-radius: 50%; + background: rgba(38, 50, 63, 0.72); + color: #ffffff; + font-size: 15px; + line-height: 1; cursor: pointer; } -.image-del:hover { - background: #fdf1ef; +.image-cell:hover .image-x, +.image-cell.marked .image-x { + display: flex; } -.image-cell.marked .image-del { - border-color: #95b1cb; - color: #5b6f83; +.image-x:hover { + background: #a04432; +} +/* 标删态:整格遮罩可点撤销。 */ +.image-marked-mask { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 6px; + border: none; + border-radius: 8px; + background: rgba(160, 68, 50, 0.32); + color: #ffffff; + font-size: 12px; + line-height: 1.5; + cursor: pointer; +} +.image-marked-mask:hover { + background: rgba(160, 68, 50, 0.5); +} +/* hover 底部替换条(京麦替换入口);上传中常显。 */ +.image-replace { + position: absolute; + left: 0; + right: 0; + bottom: 0; + display: none; + align-items: center; + justify-content: center; + min-height: 26px; + border: none; + border-radius: 0 0 8px 8px; + background: rgba(38, 50, 63, 0.72); + color: #ffffff; + font-size: 12px; + cursor: pointer; +} +.image-cell:hover .image-replace { + display: flex; +} +.image-cell .image-replace:disabled { + display: flex; + background: rgba(38, 50, 63, 0.55); + cursor: wait; +} +.image-replace:hover { + background: #2f5d8b; } .delete-count { margin: 10px 0 0; diff --git a/admin-frontend-vue/src/pages/jd/jd-product-api.ts b/admin-frontend-vue/src/pages/jd/jd-product-api.ts index 1cc7845e8..83323b8ec 100644 --- a/admin-frontend-vue/src/pages/jd/jd-product-api.ts +++ b/admin-frontend-vue/src/pages/jd/jd-product-api.ts @@ -103,6 +103,36 @@ export async function updateJdProduct( return parseJdProductDetail(data) } +/** 图片上传参数(POST /{id}/images multipart):replaceImageId 有值=替换该登记行 + * (后端继承原行档位,imageType/attrName 忽略);缺省=新增(imageType=MAIN/DETAIL, + * ATTR 需带 attrName)。objectKey 由服务端按上传字节 sha256 内容寻址生成(铁律 32), + * 前端不自造 key。返回刷新后的详情(与 fetchJdProductDetail 同一信封)。 */ +export interface JdProductImageUploadParams { + replaceImageId?: number + imageType?: 'MAIN' | 'ATTR' | 'DETAIL' + attrName?: string +} + +/** 上传/替换商品图片(multipart 后端中转):上传/替换即生效(服务端立即落库并置 + * 人工编辑锁),与「删图保存时批量生效」不同。失败文案原样抛给抽屉。 */ +export async function uploadJdProductImage( + id: number, + file: File, + params: JdProductImageUploadParams, +): Promise> { + const body = new FormData() + body.append('file', file) + if (params.replaceImageId != null) { + body.append('replace_image_id', String(params.replaceImageId)) + } + if (params.imageType) body.append('image_type', params.imageType) + if (params.attrName) body.append('attr_name', params.attrName) + const { data } = await http.post(`${JD_PRODUCT_ENDPOINT}/${id}/images`, body, { + headers: { 'Content-Type': 'multipart/form-data' }, + }) + return parseJdProductDetail(data) +} + /** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */export interface JdProductGroup { id: number name: string diff --git a/admin-frontend-vue/tests/mount/jd-edit-drawer-images.mount.test.ts b/admin-frontend-vue/tests/mount/jd-edit-drawer-images.mount.test.ts new file mode 100644 index 000000000..45c0371d4 --- /dev/null +++ b/admin-frontend-vue/tests/mount/jd-edit-drawer-images.mount.test.ts @@ -0,0 +1,174 @@ +/** + * 京东商品编辑抽屉「图片区」(2026-11-16 客户口径「删除做成打叉的 icon 放图右上角, + * 也要支持编辑替换本地的图」+替换+新增,B109-01 落地)的挂载契约。 + * + * 形态:× 右上角标删(保存时一并删除,遮罩可点撤销);hover 替换条(multipart 立即生效); + * 「+ 新增主图」入口(imageType=MAIN)。objectKey 服务端内容寻址生成——前端只传文件。 + * 跑法:`npx vitest run tests/mount/jd-edit-drawer-images.mount.test.ts` + */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' + +import JdProductEditDrawer from '@/pages/jd/JdProductEditDrawer.vue' + +const jdApi = vi.hoisted(() => ({ + JD_PRODUCT_ENDPOINT: '/api/admin/jd-products', + JD_PRODUCT_GROUP_ENDPOINT: '/api/admin/jd-product-groups', + fetchJdProductList: vi.fn(), + fetchJdProductDetail: vi.fn(), + deleteJdProducts: vi.fn(), + fetchJdProductGroups: vi.fn(), + fetchJdProductCategories: vi.fn(), + createJdProductGroup: vi.fn(), + updateJdProductGroup: vi.fn(), + deleteJdProductGroup: vi.fn(), + updateJdProduct: vi.fn(), + uploadJdProductImage: vi.fn(), + batchAssignJdProductGroup: vi.fn(), +})) + +const feedbackMock = vi.hoisted(() => vi.fn()) + +vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi) +vi.mock('@/components/admin-feedback-ui', () => ({ showAdminFeedback: feedbackMock })) + +const ITEM = { + id: 9, + shopId: 3, + shopName: '旗舰自营店', + productCode: 'JD-1009', + skuId: 'SKU-9', + itemNum: 'ITEM-9', + skuCount: 12, + healthScore: 81, + title: '304不锈钢保温杯大容量便携', + brand: '锅宝', + categoryPath: '家居 > 厨具 > 保温杯', + priceMin: '12.9', + priceMax: '15.9', + stockTotal: 500, + saleStatus: '上架中', + listTab: 'search', + jdCreatedAt: '2026-11-07 18:49:47', + jdOnlineAt: '2026-11-12 15:03:37', + jdUpdatedAt: '2026-11-13 14:06:07', + mainImageUrl: 'https://img.example/main-9.jpg', + attrCount: 0, + imageCount: 2, + groupId: null, + groupName: '', + syncedAt: '2026-11-12 09:00:00', +} + +function image(id: number, imageType: string, url: string) { + return { id, imageType, attrName: null, sortNo: id, url, byteSize: 1024, width: null, height: null } +} + +function detailPayload(images: ReturnType[]) { + return { item: ITEM, attrGroups: [], images, skus: [], attrJsonRaw: '' } +} + +beforeEach(() => { + vi.clearAllMocks() + jdApi.fetchJdProductGroups.mockResolvedValue([]) +}) + +async function mountWith(images: ReturnType[]): Promise> { + jdApi.fetchJdProductDetail.mockResolvedValue(detailPayload(images)) + // 抽屉的加载 watch 非 immediate(真实页面里由「点编辑」把 visible 翻真触发): + // 先挂 false 再 setProps 翻真,与生产触发时序同形。 + const wrapper = mount(JdProductEditDrawer, { + props: { item: null as typeof ITEM | null, visible: false }, + }) + await wrapper.setProps({ item: ITEM, visible: true }) + await flushPromises() + await flushPromises() + return wrapper +} + +/** 把夹具文件塞进隐藏 file input 并触发 change。 */ +async function chooseFile(wrapper: VueWrapper, name = 'a.png'): Promise { + const input = wrapper.find('input[type="file"]') + const file = new File(['x'], name, { type: 'image/png' }) + Object.defineProperty(input.element, 'files', { value: [file] }) + await input.trigger('change') + await flushPromises() + await flushPromises() + return file +} + +describe('京东商品编辑抽屉图片区(×右上角+替换+新增,B109-01)', () => { + it('挂载回填图片区:每格右上角有 × 标记、hover 替换条存在、新增按钮存在(上传/替换暂未开放的旧文案下线)', async () => { + const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'DETAIL', 'https://img.example/b.jpg')]) + const cells = wrapper.findAll('.image-cell') + expect(cells).toHaveLength(2) + expect(cells[0].find('.image-x').exists()).toBe(true, '右上角 × 删除标记') + expect(cells[0].find('.image-replace').exists()).toBe(true, 'hover 替换条') + expect(cells[0].find('.image-marked-mask').exists()).toBe(false, '未标删时无遮罩') + const addBtn = wrapper.find('.btn-add-image') + expect(addBtn.exists()).toBe(true) + expect(addBtn.text()).toContain('新增主图') + expect(wrapper.find('h4').text()).not.toContain('暂未开放', '「上传/替换暂未开放」旧文案下线') + }) + + it('点 × 标记删除(保存时一并删除):遮罩出现、计数文案更新;再点撤销恢复', async () => { + const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'MAIN', 'https://img.example/b.jpg')]) + await wrapper.find('.image-cell .image-x').trigger('click') + let cell = wrapper.findAll('.image-cell')[0] + expect(cell.classes()).toContain('marked') + expect(cell.find('.image-marked-mask').exists()).toBe(true) + expect(wrapper.find('.delete-count').text()).toContain('已标记删除 1 张') + + await cell.find('.image-marked-mask').trigger('click') + cell = wrapper.findAll('.image-cell')[0] + expect(cell.classes()).not.toContain('marked') + expect(wrapper.find('.delete-count').exists()).toBe(false) + expect(jdApi.uploadJdProductImage).not.toHaveBeenCalled() + }) + + it('hover 替换条选本地图:uploadJdProductImage 带 replaceImageId 调用,立即生效回填新 url 并置 saved', async () => { + const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')]) + const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {}) + await wrapper.find('.image-cell .image-replace').trigger('click') + expect(clickSpy).toHaveBeenCalled() + + jdApi.uploadJdProductImage.mockResolvedValue(detailPayload([image(11, 'MAIN', 'https://img.example/replaced.jpg')])) + const file = await chooseFile(wrapper, 'b.png') + expect(jdApi.uploadJdProductImage).toHaveBeenCalledTimes(1) + expect(jdApi.uploadJdProductImage.mock.calls[0][0]).toBe(9) + expect(jdApi.uploadJdProductImage.mock.calls[0][1]).toBe(file) + expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ replaceImageId: 11 }) + expect(wrapper.findAll('.image-cell')[0].find('img').attributes('src')).toBe('https://img.example/replaced.jpg') + expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已替换'), 'success') + expect(wrapper.emitted('saved')).toBeTruthy() + clickSpy.mockRestore() + }) + + it('「+ 新增主图」入口:uploadJdProductImage 带 imageType=MAIN(objectKey 由服务端生成,前端不自造)', async () => { + const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')]) + const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {}) + await wrapper.find('.btn-add-image').trigger('click') + expect(clickSpy).toHaveBeenCalled() + + jdApi.uploadJdProductImage.mockResolvedValue(detailPayload([ + image(11, 'MAIN', 'https://img.example/a.jpg'), + image(13, 'MAIN', 'https://img.example/new.jpg'), + ])) + await chooseFile(wrapper, 'c.png') + expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ imageType: 'MAIN' }) + expect(wrapper.findAll('.image-cell')).toHaveLength(2) + expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已新增'), 'success') + clickSpy.mockRestore() + }) + + it('上传失败:红条出现(requestErrorMessage 对非信封异常回通用文案)、图片区不回填', async () => { + const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')]) + vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {}) + await wrapper.find('.btn-add-image').trigger('click') + jdApi.uploadJdProductImage.mockRejectedValue(new Error('单张图片不能超过 10MB')) + await chooseFile(wrapper, 'big.png') + expect(wrapper.find('.drawer-failure').exists()).toBe(true, '失败红条出现') + expect(wrapper.findAll('.image-cell')).toHaveLength(1, '失败不回填') + vi.restoreAllMocks() + }) +}) diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/AdminJdProductController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/AdminJdProductController.java index cd72a961e..b8c767604 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/AdminJdProductController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/AdminJdProductController.java @@ -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 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 → 图片登记 → 商品行);被其他商品共用的图片对象保留。" diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateService.java index 8b8fe197e..8581ce011 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateService.java @@ -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 UPLOAD_IMAGE_TYPES = Set.of("MAIN", "ATTR", "DETAIL"); + + /** 管理面上传接受的 MIME(与登记链 MIME_EXTENSIONS 同词表)。 */ + private static final Set UPLOAD_MIME_TYPES = Set.of("image/jpeg", "image/png", "image/webp", "image/gif"); + + /** MIME → 对象扩展名(与 JdProductImageIngestService 同映射)。 */ + private static final Map 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 直传链)。 + * + *

数据面三件事(铁律 32 同形):① 独立桶 {@code jd-products};② objectKey 由服务端 + * 内容寻址生成(对上传字节算 SHA-256 拼 key,前端不自造 key);③ 落库字节数就是上传 + * 字节本身(中转模式服务端持有字节,无「登记与对象对撞」窗口)。

+ * + *
    + *
  • 替换({@code replaceImageId} 有值):原行必须挂在本商品上;档位 + * (imageType/attrName/sortNo)继承原行——用户换的是「这一格」的图,不改分区。 + * 新对象落桶 → 原行更新指向 → 旧对象共用回查后删桶(被其他商品引用则保留, + * 同 {@link #deleteImages} 语义);删旧对象失败只记 WARN 不拒绝——行已指向新 key, + * 残留只是存储垃圾,为它把用户已成功的替换整笔回滚(新桶对象成孤儿)不划算。
  • + *
  • 新增:imageType 必须在词表内(明确拒绝,不静默归 MAIN),ATTR 必须带 + * attrName;sortNo 同区内 max+1。
  • + *
  • 置锁:上传/替换即 {@code manual_locked=1}(与编辑保存/归类同口径)—— + * 采集 upsert/覆盖清理此后跳过本行,人工图不被重爬冲掉。
  • + *
  • 投影刷新:image_count 与 main_image_url 按表实数刷 + * (与 JdProductImageIngestService.refreshProductImageProjection 同形状)。
  • + *
+ * + * @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() + .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() + .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() + .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 rows = jdProductImageMapper.selectList( + new LambdaQueryWrapper() + .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() + .eq(JdProductImageEntity::getProductId, productId)); + String mainImageUrl = null; + List mains = jdProductImageMapper.selectList( + new LambdaQueryWrapper() + .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() + .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) { diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java index 8e94718b8..73bf40763 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java @@ -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; /** diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateServiceTest.java index 80df9d279..d682ca245 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateServiceTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateServiceTest.java @@ -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 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> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class); + org.mockito.Mockito.verify(jdProductMapper, org.mockito.Mockito.times(2)) + .update(isNull(), wrapperCaptor.capture()); + String lockSqlSet = ((LambdaUpdateWrapper) wrapperCaptor.getAllValues().get(0)).getSqlSet(); + String projectionSqlSet = ((LambdaUpdateWrapper) 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 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)); + } } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/task/service/TaskFailureCategoryGuardrailTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/task/service/TaskFailureCategoryGuardrailTest.java index 5920458b8..8b30d6566 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/task/service/TaskFailureCategoryGuardrailTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/task/service/TaskFailureCategoryGuardrailTest.java @@ -91,8 +91,14 @@ class TaskFailureCategoryGuardrailTest { * (TaskScopeStateEntity 无 ALWAYS 字段,且写前经合并读回,铁律 30)。三处传入实体都不带 * ALWAYS 家族列(ALWAYS 只在 PriceTrackLoopRun/ShopKey/SkipPriceAsin/FileTask 四实体), * 审过无抹列风险后登记基线。 + * + *

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 任务失败文案写点必须同笔写分类列() {