diff --git a/admin-frontend-vue/src/pages/jd/JdDatabasePage.vue b/admin-frontend-vue/src/pages/jd/JdDatabasePage.vue
index f2fc23519..49c048377 100644
--- a/admin-frontend-vue/src/pages/jd/JdDatabasePage.vue
+++ b/admin-frontend-vue/src/pages/jd/JdDatabasePage.vue
@@ -1,10 +1,12 @@
@@ -264,10 +265,6 @@ onMounted(() => {
-
-
-
-
@@ -276,6 +273,16 @@ onMounted(() => {
+
+
+
+
+
@@ -286,9 +293,6 @@ onMounted(() => {
-
@@ -314,11 +318,13 @@ onMounted(() => {
店铺 |
分组 |
商品信息 |
- 品牌 |
- 价格区间 |
总库存 |
- 商品状态 |
+ 价格 |
+ 上架时间 / 商品状态 |
+ 创建时间 |
+ 修改时间 |
同步时间 |
+ 操作 |
@@ -341,22 +347,37 @@ onMounted(() => {
货号:{{ row.itemNum || '-' }}
+
+
+ {{ row.brand || '' }} {{ row.categoryPath || '' }}
+
{{ row.skuCount }}个SKU
- {{ row.brand || '-' }} |
- {{ jdPriceRange(row) || '-' }} |
{{ row.stockTotal ?? '-' }} |
- {{ row.saleStatus || '-' }} |
+ {{ jdPriceRange(row) || '-' }} |
+
+ {{ formatDateTime(row.jdOnlineAt || '') || '-' }}
+
+ {{ row.saleStatus }}
+
+ |
+ {{ formatDateTime(row.jdCreatedAt || '') || '-' }} |
+ {{ formatDateTime(row.jdUpdatedAt || '') || '-' }} |
{{ formatDateTime(row.syncedAt || '') }} |
+
+
+
+
+ |
- | 加载中... |
+ 加载中... |
- | 暂无京东商品数据 |
+ 暂无京东商品数据 |
@@ -371,6 +392,13 @@ onMounted(() => {
:company-id="companyTab.requestCompanyId"
@close="closeDetail"
/>
+
table {
- min-width: 1180px;
+ min-width: 1500px;
+}
+/* 操作列(编辑/删除):双小按钮,放开换行不让按钮被裁。 */
+.jd-ops-cell {
+ white-space: normal;
+ text-overflow: clip;
+}
+.btn-sm {
+ min-height: 28px;
+ padding: 3px 10px;
+ font-size: 12.5px;
+ margin-right: 6px;
+}
+.btn-sm:last-child {
+ margin-right: 0;
}
.table-scroll th,
.table-scroll td {
@@ -556,6 +602,14 @@ h3 {
text-overflow: ellipsis;
white-space: nowrap;
}
+/* 首列勾选格:checkbox 的 UA 默认 margin(3px 3px 3px 4px)使其 margin-box 溢出
+ 42px 格的内容盒(42−24 padding=18px),配合上面的 overflow:hidden,Chromium 在
+ 首次渲染时会把被裁的 checkbox 碎片留在裁剪边缘,看起来像格子右边多出 ".."。
+ margin 归零后 margin-box 收进内容盒,首渲染即干净(playwright 三次冷加载已验)。 */
+.table-scroll th:first-child input,
+.table-scroll td:first-child input {
+ margin: 0;
+}
.table-scroll th {
background: #edf4fa;
color: #4e6479;
@@ -666,6 +720,31 @@ h3 {
gap: 6px;
margin-top: 2px;
}
+/* 品牌·类目行(京麦列表同款深色文字):信息 meta 是灰色,这行按京麦用主文字色。 */
+.jd-brand-cat {
+ color: #3d5368;
+ font-weight: 550;
+}
+.jd-online-cell {
+ line-height: 1.45;
+}
+/* 商品状态(京麦同款圆点):上架中绿点,其余灰点。 */
+.jd-sale-status {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ color: #24384d;
+}
+.jd-sale-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #2fb26b;
+ flex-shrink: 0;
+}
+.jd-sale-status.off .jd-sale-dot {
+ background: #9fb0c0;
+}
.jd-tag {
display: inline-flex;
align-items: center;
diff --git a/admin-frontend-vue/src/pages/jd/JdProductEditDrawer.vue b/admin-frontend-vue/src/pages/jd/JdProductEditDrawer.vue
new file mode 100644
index 000000000..a02710941
--- /dev/null
+++ b/admin-frontend-vue/src/pages/jd/JdProductEditDrawer.vue
@@ -0,0 +1,695 @@
+
+
+
+
+
+
+
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 3f1093e0a..c5da4979f 100644
--- a/admin-frontend-vue/src/pages/jd/jd-product-api.ts
+++ b/admin-frontend-vue/src/pages/jd/jd-product-api.ts
@@ -1,14 +1,12 @@
/** 京东数据库查询适配(v1.4 Phase 5):GET /api/admin/jd-products + 删除(DELETE /{id} +
* POST /batch-delete)+ 分组端点 /api/admin/jd-product-groups。
- * 只读列表+导出+删除+分组管理:公司 tab 的值由本发送口从原始入参自己下传
- * (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。 */
+ * 只读列表+删除+分组管理:公司 tab 的值由本发送口从原始入参自己下传
+ * (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。
+ * 导出发送口已随 2026-11-15 客户口径「导出也不用」从前端下线(后端 /export 端点保留)。 */
import { http } from '@/api/http'
import { errorTextOf, unwrap } from '../../api/envelope.ts'
import {
- toJdProductExportParams,
toJdProductListParams,
- type JdProductExportParams,
- type JdProductExportQuery,
type JdProductListParams,
} from './jd-product-filter.ts'
import {
@@ -28,7 +26,7 @@ export async function fetchJdProductList(
shopName: params.shopName ?? '',
productCode: params.productCode ?? '',
titleKeyword: params.titleKeyword ?? '',
- saleStatus: params.saleStatus ?? '',
+ category: params.category ?? '',
groupId: params.groupId ?? '',
syncedFrom: params.syncedFrom ?? '',
syncedTo: params.syncedTo ?? '',
@@ -52,63 +50,6 @@ export async function fetchJdProductDetail(
return parseJdProductDetail(data)
}
-export interface JdProductExportResult {
- blob: Blob
- filename: string
-}
-
-/** 从 Content-Disposition 取 filename*(UTF-8 轨,后端 DownloadHeaderUtil 双轨口径),取不到回退常量名。 */
-function exportFilenameOf(disposition: unknown): string {
- const raw = typeof disposition === 'string' ? disposition : ''
- const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(raw)
- if (star?.[1]) {
- try {
- return decodeURIComponent(star[1].trim().replace(/^"|"$/g, '')) || '京东数据库.xlsx'
- } catch {
- // 编码坏的 filename* 当作没有,走 ASCII 轨或常量名
- }
- }
- const plain = /filename="([^"]+)"/i.exec(raw)
- return plain?.[1] || '京东数据库.xlsx'
-}
-
-/** 导出当前过滤面全量明细:与列表共用同一过滤面取值口(含公司 tab),blob 下载交给页面触发保存。 */
-export async function exportJdProductList(
- params: JdProductExportParams,
-): Promise {
- const query: JdProductExportQuery = toJdProductExportParams({
- shopName: params.shopName ?? '',
- productCode: params.productCode ?? '',
- titleKeyword: params.titleKeyword ?? '',
- saleStatus: params.saleStatus ?? '',
- groupId: params.groupId ?? '',
- syncedFrom: params.syncedFrom ?? '',
- syncedTo: params.syncedTo ?? '',
- })
- if (params.companyId != null) query.company_id = params.companyId
- const response = await http.get(`${JD_PRODUCT_ENDPOINT}/export`, {
- params: query,
- responseType: 'blob',
- timeout: 120_000,
- })
- const disposition = response.headers?.['content-disposition']
- if (!disposition) {
- // 没有附件头=服务端回了业务错误信封(HTTP 200 + JSON),把 blob 文本解回错误文案抛给页面
- const blob = response.data
- let payload: unknown = null
- if (blob && typeof blob.text === 'function') {
- const text = await blob.text()
- try {
- payload = JSON.parse(text)
- } catch {
- payload = text
- }
- }
- throw new Error(errorTextOf(payload))
- }
- return { blob: response.data, filename: exportFilenameOf(disposition) }
-}
-
/** 删除回执(后端 JdProductDeleteVo):三个对象计数分开报——真删的、共用的、前缀外不敢动的。 */
export interface JdProductDeleteResult {
deleted: number
@@ -133,8 +74,39 @@ export async function deleteJdProducts(
return unwrap(data)
}
-/** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */
-export interface JdProductGroup {
+/** 编辑提交负载(PUT /api/admin/jd-products/{id} body,后端 JdProductUpdateRequest):
+ * 主字段全量提交;attrGroups/skus/deleteImageIds 可选——null=不修改该块
+ * (后端对 null 块零触碰)。 */
+export interface JdProductUpdatePayload {
+ title: string
+ brand: string | null
+ categoryPath: string | null
+ itemNum: string | null
+ priceMin: string | null
+ priceMax: string | null
+ stockTotal: number | null
+ saleStatus: string | null
+ groupId: number | null
+ attrGroups: { groupName: string; attrs: { key: string; label: string; value: string }[] }[] | null
+ skus: { skuId: string; price: string | null; stock: number | null }[] | null
+ deleteImageIds: number[] | null
+}
+
+/** 编辑保存(PUT + company_id 作 query,照 deleteJdProducts 形状):主字段保存即置
+ * 人工编辑锁(V199 manual_locked=1,后续采集不再覆盖该行);失败文案原样抛给抽屉红条。
+ * 返回刷新后的详情(与 fetchJdProductDetail 同一信封),抽屉用它回填。 */
+export async function updateJdProduct(
+ id: number,
+ payload: JdProductUpdatePayload,
+ companyId: number | null,
+): Promise> {
+ const query: Record = {}
+ if (companyId != null) query.company_id = companyId
+ const { data } = await http.put(`${JD_PRODUCT_ENDPOINT}/${id}`, payload, { params: query })
+ return parseJdProductDetail(data)
+}
+
+/** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */export interface JdProductGroup {
id: number
name: string
sortOrder: number
@@ -184,6 +156,32 @@ export async function fetchJdProductGroups(companyId: number | null): Promise {
+ const query: Record = {}
+ if (companyId != null) query.company_id = companyId
+ const { data } = await http.get(`${JD_PRODUCT_ENDPOINT}/categories`, { params: query })
+ const core = unwrap(data)
+ if (!Array.isArray(core)) return []
+ const out: JdProductCategoryOption[] = []
+ for (const raw of core) {
+ if (!raw || typeof raw !== 'object') continue
+ const record = raw as Record
+ const name = typeof record.name === 'string' ? record.name.trim() : ''
+ if (!name) continue
+ out.push({ name, productCount: numberOr(record.productCount ?? record.product_count, 0) })
+ }
+ return out
+}
+
/** 新建分组;重名等业务失败把后端中文文案抛回(页面直接展示)。 */
export async function createJdProductGroup(
payload: JdProductGroupPayload,
diff --git a/admin-frontend-vue/src/pages/jd/jd-product-filter.ts b/admin-frontend-vue/src/pages/jd/jd-product-filter.ts
index 29c37f94f..0caad6cdf 100644
--- a/admin-frontend-vue/src/pages/jd/jd-product-filter.ts
+++ b/admin-frontend-vue/src/pages/jd/jd-product-filter.ts
@@ -1,7 +1,9 @@
-/** 京东数据库页筛选纯函数(v1.4 Phase 5):店铺/商品编码/标题关键字/商品状态/分组/同步起止 + snake 分页参数。
+/** 京东数据库页筛选纯函数(v1.4 Phase 5):店铺/商品编码/标题关键字/类目/分组/同步起止 + snake 分页参数。
* 产出与后端契约 §列表 query 逐字对撞:`page`/`page_size`(默认 20、上限 100)、`shop_name`、
- * `product_code`、`title_keyword`、`sale_status`、`group_id`、`synced_from`/`synced_to`
- * (ISO yyyy-MM-dd;空白不下发)。
+ * `product_code`、`title_keyword`、`category`(京麦末级类目等值过滤,2026-11-15 增)、
+ * `group_id`、`synced_from`/`synced_to`(ISO yyyy-MM-dd;空白不下发)。
+ * 商品状态筛选与导出(2026-11-15 客户口径「这两个不要/导出也不用」)已从前端下线;
+ * 后端 `sale_status` 参数与 `/export` 端点保留(无 UI 入口),重上时从 git 历史找回取值口。
* 分页钳制(铁律 15):page < 1 归 1、上限 10_000(后端 CR-18 同值),(page-1)*page_size
* 最大 999_900,Number.MAX_SAFE_INTEGER 也不会把乘积顶出安全整数。纯逻辑,node --test 直测。
* 公司维不在这里:归一化构造器不认识 company_id(同外观专利 filter 惯例),由 api 发送口从
@@ -16,9 +18,6 @@ export const JD_PRODUCT_MAX_PAGE_SIZE = 100
/** 页码上限:与后端 MAX_PAGE(CR-18 先例,外观专利同值)对齐,两侧不漂。 */
export const JD_PRODUCT_MAX_PAGE = 10_000
-/** 商品状态值域(契约口径):筛选为简单文本输入,placeholder 提示值域。 */
-export const JD_SALE_STATUS_HINT = '上架中/已下架/审核中/草稿'
-
export interface JdProductFilterState {
/** 店铺名(模糊),空串不限。 */
shopName: string
@@ -26,8 +25,8 @@ export interface JdProductFilterState {
productCode: string
/** 标题关键字,空串不限。 */
titleKeyword: string
- /** 商品状态:上架中/已下架/审核中/草稿,空串=全部。 */
- saleStatus: string
+ /** 类目(京麦末级类目名,等值过滤;选项来自 GET /categories),空串=全部类目。 */
+ category: string
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
groupId: string
/** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */
@@ -37,7 +36,7 @@ export interface JdProductFilterState {
}
export function createJdProductFilterState(): JdProductFilterState {
- return { shopName: '', productCode: '', titleKeyword: '', saleStatus: '', groupId: '', syncedFrom: '', syncedTo: '' }
+ return { shopName: '', productCode: '', titleKeyword: '', category: '', groupId: '', syncedFrom: '', syncedTo: '' }
}
/** 是否有任一激活筛选条件。 */
@@ -45,7 +44,7 @@ export function jdProductFilterActive(state: JdProductFilterState): boolean {
if ((state.shopName || '').trim()) return true
if ((state.productCode || '').trim()) return true
if ((state.titleKeyword || '').trim()) return true
- if ((state.saleStatus || '').trim()) return true
+ if ((state.category || '').trim()) return true
if ((state.groupId || '').trim()) return true
if (validIsoDateOrUndefined(state.syncedFrom) || validIsoDateOrUndefined(state.syncedTo)) return true
return false
@@ -58,7 +57,8 @@ export interface JdProductQuery {
shop_name?: string
product_code?: string
title_keyword?: string
- sale_status?: string
+ /** 京麦末级类目等值过滤(后端 JdProductQueryService.Filter.category)。 */
+ category?: string
group_id?: number
synced_from?: string
synced_to?: string
@@ -66,19 +66,6 @@ export interface JdProductQuery {
company_id?: number
}
-/** 导出查询参数:与列表同一过滤面、无分页(全量导出由服务侧上限兜住)。 */
-export interface JdProductExportQuery {
- shop_name?: string
- product_code?: string
- title_keyword?: string
- sale_status?: string
- group_id?: number
- synced_from?: string
- synced_to?: string
- /** 公司 tab 同列表口径:白名单构造不点名,由 api 发送口下传。 */
- company_id?: number
-}
-
/** api 模块的入参:筛选态 + 分页 + 公司值(camel)。 */
export interface JdProductListParams {
page: number
@@ -86,37 +73,24 @@ export interface JdProductListParams {
shopName?: string
productCode?: string
titleKeyword?: string
- saleStatus?: string
+ category?: string
groupId?: string
syncedFrom?: string
syncedTo?: string
companyId?: number | null
}
-/** api 导出入口的入参:筛选态 + 公司值(camel,无分页)。 */
-export interface JdProductExportParams {
- shopName?: string
- productCode?: string
- titleKeyword?: string
- saleStatus?: string
- groupId?: string
- syncedFrom?: string
- syncedTo?: string
- companyId?: number | null
-}
-
-/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段);列表与导出共用这一个取值口,
- * 「导出的过滤面和页签看到的永远同源」由这条单出口保证,不出现两处各算各的。 */
-function toJdProductFilterQuery(state: JdProductFilterState): JdProductExportQuery {
- const query: JdProductExportQuery = {}
+/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段)。 */
+function toJdProductFilterQuery(state: JdProductFilterState): Omit {
+ const query: Omit = {}
const shopName = (state.shopName || '').trim()
if (shopName) query.shop_name = shopName
const productCode = (state.productCode || '').trim()
if (productCode) query.product_code = productCode
const titleKeyword = (state.titleKeyword || '').trim()
if (titleKeyword) query.title_keyword = titleKeyword
- const saleStatus = (state.saleStatus || '').trim()
- if (saleStatus) query.sale_status = saleStatus
+ const category = (state.category || '').trim()
+ if (category) query.category = category
const groupId = Number.parseInt((state.groupId || '').trim(), 10)
if (Number.isFinite(groupId) && groupId > 0) query.group_id = groupId
const syncedFrom = validIsoDateOrUndefined(state.syncedFrom)
@@ -141,8 +115,3 @@ export function toJdProductListParams(
...toJdProductFilterQuery(state),
}
}
-
-/** 过滤态 → 导出查询参数(无分页;归一规则与列表逐字同源)。 */
-export function toJdProductExportParams(state: JdProductFilterState): JdProductExportQuery {
- return toJdProductFilterQuery(state)
-}
diff --git a/admin-frontend-vue/src/pages/jd/jd-product-model.ts b/admin-frontend-vue/src/pages/jd/jd-product-model.ts
index 0d8defd00..7fa68476f 100644
--- a/admin-frontend-vue/src/pages/jd/jd-product-model.ts
+++ b/admin-frontend-vue/src/pages/jd/jd-product-model.ts
@@ -132,8 +132,10 @@ export interface JdProductAttrGroup {
attrs: JdProductAttrEntry[]
}
-/** 详情图片:images[{imageType, attrName, sortNo, url, byteSize, width, height}]。 */
+/** 详情图片:images[{id, imageType, attrName, sortNo, url, byteSize, width, height}]
+ * (id=biz_jd_product_image 行号,编辑抽屉按它提交删图;旧后端不带 id 时按缺 0 弃行口径不拦展示)。 */
export interface JdProductImage {
+ id: number
imageType: string
attrName: string
sortNo: number
@@ -207,6 +209,7 @@ function toImages(raw: unknown): JdProductImage[] {
const url = text(image.url)
if (!url) continue
out.push({
+ id: numberOrNull(image.id) ?? 0,
imageType: text(image.imageType ?? image.image_type),
attrName: text(image.attrName ?? image.attr_name),
sortNo: numberOrNull(image.sortNo ?? image.sort_no) ?? 0,
diff --git a/admin-frontend-vue/tests/company-tab-wiring.test.ts b/admin-frontend-vue/tests/company-tab-wiring.test.ts
index 81f873edc..2c2b87667 100644
--- a/admin-frontend-vue/tests/company-tab-wiring.test.ts
+++ b/admin-frontend-vue/tests/company-tab-wiring.test.ts
@@ -133,10 +133,19 @@ const SEND_POINTS: ReadonlyArray = [
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'fetchAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items 无侵权只读列表' },
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'exportAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items/export 导出(2026-11-11 客户需求「数据得导出来」,与列表共用同一过滤面)' },
// ↓ 批次 8(2026-11-14 v1.4 京东数据库):京麦店铺商品采集落库的只读镜像,归属物化在行
- // company_id 列(V193,同外观专利 V189 形状)⇒ 后端正门 readCompanyIdOrOwn。列表与导出
- // 共用同一过滤面,塞键行与外观专利逐字同行,但分属不同文件 ⇒ (文件, 整行) 各成一组。
+ // company_id 列(V193,同外观专利 V189 形状)⇒ 后端正门 readCompanyIdOrOwn。
+ // 导出发送口已随 2026-11-15 客户口径「导出也不用」从前端下线(后端 /export 端点保留,
+ // 前端发送口撤,重上时从 git 历史找回发送行再登记——同批次 7 主管两口的先例)。
{ menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /jd-products 京东数据库只读列表' },
- { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'exportJdProductList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /jd-products/export 京东数据库导出(与列表共用同一过滤面)' },
+ // ↓ 同文件其余 6 个发送口(payload 形签名,塞键行与列表口不同形):详情/删除/分组列表/
+ // 类目列表/删分组都在 2026-11-14 v1.4 就带 company_id 下传,编辑口(2026-11-15 行级编辑,
+ // PUT 保存、V199 人工编辑锁)同形状——6 处塞键行逐字同行走一组,一函数一钉对平。
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductDetail', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'GET /jd-products/{id} 详情抽屉取数' },
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'deleteJdProducts', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'DELETE /jd-products/{id} 与 POST batch-delete 删除' },
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductGroups', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'GET /jd-product-groups 分组下拉/管理列表' },
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductCategories', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'GET /jd-products/categories 类目下拉' },
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'deleteJdProductGroup', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'DELETE /jd-product-groups/{id} 删分组' },
+ { menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'updateJdProduct', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'PUT /jd-products/{id} 行级编辑保存(V199 人工编辑锁)' },
]
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
@@ -260,7 +269,7 @@ const COMPANY_ID_SOURCE_PINS: Readonly>
admin_columns: pinsFor('admin_columns'),
// 批次 7(v1.3 无侵权只读页):同样由 SEND_POINTS 现算——只有一个发送口(列表)。
admin_appearance_patent_clean_items: pinsFor('admin_appearance_patent_clean_items'),
- // 批次 8(v1.4 京东数据库):列表 + 导出两口,由 SEND_POINTS 现算。
+ // 批次 8(v1.4 京东数据库):列表一口(导出发送口 2026-11-15 随客户口径下线),由 SEND_POINTS 现算。
admin_jd_database: pinsFor('admin_jd_database'),
}
@@ -360,8 +369,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 7 + 批次 3 的 4 + 批次 4 的 1 + 批次 5 的 1 + 批次 6 的 3;
// 批次 2 原 12 条里的品牌库 1 条 + 商品类目 4 条随 2026-10-06「这两页退回全平台共享」摘掉)。
// 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
- assert.ok(SEND_POINTS.length >= 27,
- `发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 + 批次 8 v1.4 京东数据库列表/导出 2 条 = 28 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
+ assert.ok(SEND_POINTS.length >= 32,
+ `发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 + 批次 8 v1.4 京东数据库列表/详情/删除/分组/类目/删分组/编辑 7 条(导出口 2026-11-15 随客户口径下线)= 32 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
for (const p of SEND_POINTS) {
const shape = pointShape(p)
const compliant = pointCompliant(p)
@@ -393,8 +402,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
if (hit) hit.pinned += 1
else grouped.set(key, { file: p.file, line: p.line, pinned: 1 })
}
- assert.equal(grouped.size, 20,
- `发送口表按 (文件, 整行) 应聚成 20 组(28 处发送口,批次 7 的列表/导出/主管聚合/按主管删除与批次 8 的京东列表/导出逐字同行各走同一组),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
+ assert.equal(grouped.size, 21,
+ `发送口表按 (文件, 整行) 应聚成 21 组(32 处发送口,批次 7 的列表/导出/主管聚合/按主管删除、批次 8 的京东详情/删除/分组/类目/删分组/编辑逐字同行各走同一组;京东导出口 2026-11-15 随客户口径下线),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
for (const g of grouped.values()) {
const actual = occurrences(stripComments(read(g.file)), g.line)
assert.equal(g.pinned, actual,
@@ -750,14 +759,14 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
],
},
- // ↓ 批次 8(2026-11-14 v1.4 京东数据库):店铺/商品编码/标题是按行集筛的自由文本,分组选项集是
- // 公司隔离的(/jd-product-groups 带 company_id)⇒ 上一家的筛选值与 groupId 在新一家的行集/选项集
- // 里不存在,切 tab 必清且选项重取;页码回 1 同外观专利页。
+ // ↓ 批次 8(2026-11-14 v1.4 京东数据库):店铺/商品编码/标题是按行集筛的自由文本,分组/类目
+ // 选项集是公司隔离的(/jd-product-groups、/jd-products/categories 带 company_id)⇒ 上一家的
+ // 筛选值与 groupId/category 在新一家的行集/选项集里不存在,切 tab 必清且选项重取;页码回 1 同外观专利页。
{
file: 'src/pages/jd/JdDatabasePage.vue',
- token: "filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.saleStatus = ''; filter.groupId = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadGroupOptions(); void load()",
+ token: "filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.category = ''; filter.groupId = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadGroupOptions(); void loadCategoryOptions(); void load()",
why: '店铺/商品编码/标题是按行集筛的自由文本,上一家的值在新一家的行里不存在 ⇒ 切 tab 后首屏被筛成「暂无商品」,'
- + '而输入框还显示着上一家填的值;分组选项集是公司隔离的,上一家选的 groupId 在新一家的选项里不存在,'
+ + '而输入框还显示着上一家填的值;分组/类目选项集是公司隔离的,上一家选的 groupId/category 在新一家的选项里不存在,'
+ '同罪必清且选项重取;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据',
premise: [
{ file: 'src/pages/jd/jd-product-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
diff --git a/admin-frontend-vue/tests/jd-database-page.test.ts b/admin-frontend-vue/tests/jd-database-page.test.ts
index c27197726..86f1b2f8a 100644
--- a/admin-frontend-vue/tests/jd-database-page.test.ts
+++ b/admin-frontend-vue/tests/jd-database-page.test.ts
@@ -60,3 +60,16 @@ test('缺 skuId 的行弃掉、空 skus 回空数组(旧数据不渲染空表
assert.equal(parseJdProductDetail({ id: 3 }).skus.length, 0)
assert.equal(jdSkuSummary([]), '')
})
+
+/** 类目筛选(2026-11-15):京麦末级类目等值过滤,空串不下发、非空透传 category。 */
+test('类目筛选参数序列化:空串不下发、非空下发 category(等值过滤)', async () => {
+ const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } =
+ await import('../src/pages/jd/jd-product-filter.ts')
+ const empty = createJdProductFilterState()
+ assert.equal('category' in toJdProductListParams(empty, 1, 20), false, '全部类目不下发 category')
+ assert.equal(jdProductFilterActive(empty), false)
+
+ const filtered = { ...empty, category: ' 服饰内衣 ' }
+ assert.equal(toJdProductListParams(filtered, 1, 20).category, '服饰内衣', '去空白透传(等值过滤)')
+ assert.equal(jdProductFilterActive(filtered), true, '选中类目算激活筛选')
+})
diff --git a/admin-frontend-vue/tests/jd-product-group.test.ts b/admin-frontend-vue/tests/jd-product-group.test.ts
index 51bfb0c68..46b79dd16 100644
--- a/admin-frontend-vue/tests/jd-product-group.test.ts
+++ b/admin-frontend-vue/tests/jd-product-group.test.ts
@@ -6,8 +6,9 @@
*
* 覆盖:
* 1. **snake 参数形状**:toJdProductListParams 产出 `page`/`page_size`(默认 20、上限 100)、
- * `shop_name`/`product_code`/`title_keyword`/`sale_status`/`group_id`/`synced_from`/`synced_to`
+ * `shop_name`/`product_code`/`title_keyword`/`group_id`/`synced_from`/`synced_to`
* (ISO yyyy-MM-dd;空白不下发;groupId 空串→不带、有值→snake group_id);分页钳制(铁律 15)。
+ * 商品状态筛选与导出参数口已随 2026-11-15 客户口径下线,不再出现在参数面。
* 2. **详情解析**:parseJdProductDetail 解析 attrGroups/images(camel 为正 snake 容错、缺 url 弃行),
* attrGroups 解析不出时 attrJsonRaw 原文兜底;列表行解析缺 id 弃行。
*
@@ -19,7 +20,6 @@ import assert from 'node:assert/strict'
import {
JD_PRODUCT_MAX_PAGE,
createJdProductFilterState,
- toJdProductExportParams,
toJdProductListParams,
} from '../src/pages/jd/jd-product-filter.ts'
import {
@@ -35,7 +35,6 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
shopName: ' 旗舰自营店 ',
productCode: ' JD-10086 ',
titleKeyword: ' 保温杯 ',
- saleStatus: '上架中',
groupId: ' 7 ',
syncedFrom: '2026-11-01',
syncedTo: '2026-11-09',
@@ -49,7 +48,6 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
shop_name: '旗舰自营店',
product_code: 'JD-10086',
title_keyword: '保温杯',
- sale_status: '上架中',
group_id: 7,
synced_from: '2026-11-01',
synced_to: '2026-11-09',
@@ -60,21 +58,12 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
assert.deepEqual(blank, { page: 1, page_size: 20 })
assert.equal('group_id' in blank, false, 'groupId 空串不带 group_id')
const dirty = toJdProductListParams(
- { shopName: ' ', productCode: '', titleKeyword: '', saleStatus: '', groupId: 'abc', syncedFrom: '2026/11/01', syncedTo: 'not-a-date' },
+ { shopName: ' ', productCode: '', titleKeyword: '', groupId: 'abc', syncedFrom: '2026/11/01', syncedTo: 'not-a-date' },
1,
20,
)
assert.deepEqual(dirty, { page: 1, page_size: 20 }, '脏值不下发')
-
- // 导出与列表同一过滤面单出口(无分页)。
- const state = { shopName: '旗舰自营店', productCode: '', titleKeyword: '', saleStatus: '已下架', groupId: '7', syncedFrom: '2026-11-01', syncedTo: '' }
- const list = toJdProductListParams(state, 3, 20)
- const exp = toJdProductExportParams(state)
- for (const key of Object.keys(exp) as Array) {
- assert.equal((list as Record)[key], exp[key], `导出与列表的 ${key} 必须同源`)
- }
- assert.equal('page' in exp, false, '导出参数无分页')
- assert.deepEqual(exp, { shop_name: '旗舰自营店', sale_status: '已下架', group_id: 7, synced_from: '2026-11-01' })
+ assert.equal('sale_status' in full, false, '商品状态筛选已下线,参数面不再出现 sale_status')
})
test('京东列表参数——page 钳制防 (page-1)*page_size 溢出(铁律 15)', () => {
diff --git a/admin-frontend-vue/tests/mount/jd-database-page.mount.test.ts b/admin-frontend-vue/tests/mount/jd-database-page.mount.test.ts
index e70bf4ca1..dce42b7f4 100644
--- a/admin-frontend-vue/tests/mount/jd-database-page.mount.test.ts
+++ b/admin-frontend-vue/tests/mount/jd-database-page.mount.test.ts
@@ -1,9 +1,10 @@
/**
* 京东数据库页(v1.4 Phase 5)的挂载契约。
*
- * 形态:panel-box + 筛选行(店铺/商品编码/标题关键字/商品状态/分组/同步起止 date 对)+
- * 查询/导出/重置/管理分组 + 自绘明细表(点行开详情抽屉)+ OldPagination;
+ * 形态:panel-box + 筛选行(店铺/商品编码/标题关键字/分组/同步起止 date 对)+
+ * 查询/重置/管理分组 + 自绘明细表(点行开详情抽屉)+ OldPagination;
* 公司 tab 切换=清筛选重取(company-tab-wiring 同口径)。
+ * 商品状态筛选/列与导出按钮已随 2026-11-15 客户口径从前端下线(后端端点保留)。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
*
* 跑法:`npx vitest run tests/mount/jd-database-page.mount.test.ts`
@@ -22,12 +23,13 @@ const jdApi = vi.hoisted(() => ({
JD_PRODUCT_GROUP_ENDPOINT: '/api/admin/jd-product-groups',
fetchJdProductList: vi.fn(),
fetchJdProductDetail: vi.fn(),
- exportJdProductList: vi.fn(),
deleteJdProducts: vi.fn(),
fetchJdProductGroups: vi.fn(),
+ fetchJdProductCategories: vi.fn(),
createJdProductGroup: vi.fn(),
updateJdProductGroup: vi.fn(),
deleteJdProductGroup: vi.fn(),
+ updateJdProduct: vi.fn(),
}))
const confirmMock = vi.hoisted(() => vi.fn())
@@ -75,6 +77,7 @@ beforeEach(() => {
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(1)
jdApi.fetchJdProductGroups.mockResolvedValue([])
+ jdApi.fetchJdProductCategories.mockResolvedValue([])
confirmMock.mockResolvedValue(true)
})
@@ -98,34 +101,97 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
})
- it('行内容按京麦商品列表样式(2026-11-15 用户口径):勾选/店铺/分组/商品信息(图+标题+编码+货号+SKU/信息分)/品牌/价格/库存/状态/同步(9 列),类目等其余收进详情抽屉', async () => {
+ it('行列字段与顺序对齐京麦(2026-11-15 用户口径):勾选/店铺/分组/商品信息(图+标题+编码+货号+品牌·类目+SKU/信息分)/总库存/价格/上架时间·商品状态/创建/修改/同步/操作(11 列)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
- expect(cells).toHaveLength(9)
+ expect(cells).toHaveLength(11)
expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框')
- expect(cells[1].text()).toBe('旗舰自营店', '第 2 列=店铺(用户口径前置为第 1 数据列)')
- expect(cells[2].text()).toBe('甲组', '第 3 列=分组')
- // 商品信息列=京麦同款合并布局:主图+信息分+标题+商品编码+货号+SKU 标签。
+ expect(cells[1].text()).toBe('旗舰自营店', '第 2 列=店铺(admin 专属,置前)')
+ expect(cells[2].text()).toBe('甲组', '第 3 列=分组(admin 专属)')
+ // 商品信息列=京麦同款合并布局:主图+信息分+标题+商品编码+货号+品牌·类目行+SKU 标签。
const info = cells[3]
expect(info.find('.jd-thumb').exists()).toBe(true, '商品信息列含主图')
expect(info.text()).toContain('304不锈钢保温杯')
expect(info.text()).toContain('JD-1001', '商品编码并入商品信息列')
expect(info.text()).toContain('ITEM-1', '货号并入商品信息列')
+ expect(info.text()).toContain('锅宝', '品牌并入商品信息列(京麦品牌·类目行)')
+ expect(info.text()).toContain('家居 > 厨具 > 保温杯', '类目随品牌·类目行上列表(京麦同款)')
expect(info.text()).toContain('12个SKU')
expect(info.text()).toContain('信息分 81')
- expect(cells[4].text()).toBe('锅宝')
- expect(cells[5].text()).toBe('12.90 ~ 15.90', '价格区间=min ~ max')
- expect(cells[6].text()).toBe('500', '总库存列')
- expect(cells[7].text()).toBe('上架中')
- expect(cells[8].text()).not.toBe('-', '同步时间格式化展示')
- // 类目/上架时间/京东创建/修改时间仍收进详情抽屉(信息分/SKU 数 2026-11-15 起随京麦样式回列表)。
+ expect(cells[4].text()).toBe('500', '第 4 数据列=总库存(京麦第 2 列)')
+ expect(cells[5].text()).toBe('12.90 ~ 15.90', '第 5 数据列=价格(京麦第 3 列)')
+ expect(cells[6].text()).toContain('上架中', '第 6 数据列=上架时间/商品状态(京麦合并列)')
+ expect(cells[6].find('.jd-sale-dot').exists()).toBe(true, '状态带京麦同款圆点')
+ expect(cells[7].text()).not.toBe('-', '第 7 数据列=创建时间')
+ expect(cells[8].text()).not.toBe('-', '第 8 数据列=修改时间')
+ expect(cells[9].text()).not.toBe('-', '第 9 数据列=同步时间(admin 专属,置末)')
+ expect(cells[10].text()).toContain('编辑', '第 10 数据列=操作(编辑/删除)')
+ // 表头字段名与顺序与京麦一致;品牌/类目不再是独立列(收进商品信息)。
const headerText = wrapper.find('thead').text()
- for (const gone of ['类目', '上架时间', '创建时间', '修改时间']) {
- expect(headerText).not.toContain(gone, `${gone}列已收进详情抽屉,不再上列表`)
+ for (const gone of ['品牌', '类目']) {
+ expect(headerText).not.toContain(gone, `${gone}不再是独立列(京麦把它们收进商品信息)`)
+ }
+ for (const head of ['商品信息', '总库存', '价格', '上架时间 / 商品状态', '创建时间', '修改时间', '同步时间']) {
+ expect(headerText).toContain(head, `表头必须有「${head}」(京麦字段名)`)
}
expect(wrapper.find('.jd-thumb').exists()).toBe(true, '商品信息列渲染缩略图')
})
+ it('操作列删除按钮防冒泡且走确认弹窗:确认后调 deleteJdProducts,取消不动(2026-11-15 行级删除)', async () => {
+ const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
+ // beforeEach 默认 confirm=true;本例先翻回 false 验「取消不动」。
+ confirmMock.mockResolvedValue(false)
+ const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[10]
+ await opsCell.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
+ await flushPromises()
+ // 防冒泡:点删除不得顺手打开详情抽屉(抽屉的可视判据=.drawer 出现)。
+ expect(wrapper.find('.drawer').exists()).toBe(false, '删除按钮 @click.stop,点它不开详情抽屉')
+ expect(confirmMock).toHaveBeenCalledTimes(1, '删除必须过二次确认')
+ expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(0, '确认弹窗取消时不发删除请求')
+ // 确认后:deleteJdProducts 按公司 tab 下传(id, companyId)。
+ confirmMock.mockResolvedValue(true)
+ jdApi.deleteJdProducts.mockResolvedValueOnce({ deleted: 1, imagesDeleted: 0, objectsDeleted: 0, objectsKept: 0, objectsSkipped: 0 })
+ await wrapper.findAll('tbody tr')[0].findAll('td')[10].findAll('button').find((b) => b.text() === '删除')!.trigger('click')
+ await flushPromises()
+ expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1], 1)
+ })
+
+ it('操作列编辑按钮防冒泡且打开编辑抽屉(抽屉自取详情回填,2026-11-15 行级编辑)', async () => {
+ // fetchJdProductDetail 的返回已由 parseJdProductDetail 归一成 {item, attrGroups, images, skus, attrJsonRaw}。
+ jdApi.fetchJdProductDetail.mockResolvedValue({
+ item: {
+ id: 1,
+ title: '304不锈钢保温杯大容量便携',
+ brand: '锅宝',
+ categoryPath: '家居 > 厨具 > 保温杯',
+ itemNum: 'ITEM-1',
+ priceMin: '12.90',
+ priceMax: '15.90',
+ stockTotal: 500,
+ saleStatus: '上架中',
+ groupId: 7,
+ groupName: '甲组',
+ productCode: 'JD-1001',
+ shopName: '旗舰自营店',
+ },
+ attrGroups: [],
+ images: [],
+ skus: [],
+ attrJsonRaw: '',
+ })
+ const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
+ const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[10]
+ await opsCell.findAll('button').find((b) => b.text() === '编辑')!.trigger('click')
+ await flushPromises()
+ await flushPromises()
+ expect(wrapper.find('.drawer').exists()).toBe(true, '编辑抽屉打开')
+ expect(wrapper.text()).toContain('编辑商品', '抽屉标题点商品')
+ // 抽屉按 (id, companyId) 自取详情回填。
+ expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1, 1)
+ // 编辑抽屉的保存提示文案点名人工编辑锁后果(用户保存前看得见「采集不再覆盖」)。
+ expect(wrapper.text()).toContain('人工维护', '保存后果提示常驻(V199 人工编辑锁)')
+ })
+
it('商品信息列:主图无 URL 显示「无图」占位、healthScore 为空不出信息分行、skuCount 为空不出 SKU 标签', async () => {
const wrapper = await mountWith({
items: [item(1), item(2, { mainImageUrl: '', healthScore: null, skuCount: null })],
@@ -153,16 +219,15 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(wrapper.findAll('tbody tr')[0].findAll('td')[2].text()).toBe('未分组')
})
- it('筛选生效:店铺/编码/关键字/状态/分组/起止日期,查询回第一页重发', async () => {
+ it('筛选生效:店铺/编码/关键字/分组/起止日期,查询回第一页重发', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
- expect(textInputs).toHaveLength(4, '店铺+商品编码+标题关键字+商品状态四个文本筛选框')
+ expect(textInputs).toHaveLength(3, '店铺+商品编码+标题关键字三个文本筛选框(商品状态已下线)')
await textInputs[0].setValue('旗舰自营店')
await textInputs[1].setValue('JD-1001')
await textInputs[2].setValue('保温杯')
- await textInputs[3].setValue('上架中')
await wrapper.find('select').setValue('7')
const dateInputs = wrapper.findAll('input[type="date"]')
await dateInputs[0].setValue('2026-11-01')
@@ -175,13 +240,13 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
shopName: '旗舰自营店',
productCode: 'JD-1001',
titleKeyword: '保温杯',
- saleStatus: '上架中',
groupId: '7',
syncedFrom: '2026-11-01',
syncedTo: '2026-11-09',
page: 1,
companyId: 1,
})
+ expect(last).not.toHaveProperty('saleStatus', '商品状态筛选已下线,入参不再带 saleStatus')
})
it('分组下拉选中即查', async () => {
@@ -204,6 +269,29 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupId: '7', page: 1 })
})
+ it('类目下拉:选项来自 GET /categories(带商品数),选中即查回第一页', async () => {
+ jdApi.fetchJdProductCategories.mockResolvedValue([
+ { name: '服饰内衣', productCount: 120 },
+ { name: '运动户外', productCount: 8 },
+ ])
+ const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
+ expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith(1)
+
+ // 第 1 个 select = 分组(既有契约不动),类目下拉紧随其后
+ const selects = wrapper.findAll('.jd-filter-row select')
+ expect(selects).toHaveLength(2)
+ const categorySelect = selects[1]
+ const optionTexts = categorySelect.findAll('option').map((o) => o.text())
+ expect(optionTexts[0]).toBe('全部类目')
+ expect(optionTexts).toContain('服饰内衣(120)')
+
+ const callsBeforeSelect = jdApi.fetchJdProductList.mock.calls.length
+ await categorySelect.setValue('运动户外')
+ await flushPromises()
+ expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBeforeSelect + 1, '选中类目必须立刻重查')
+ expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '运动户外', page: 1 })
+ })
+
it('重置把筛选面回空并回第一页重取', async () => {
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
@@ -235,48 +323,11 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(last.page).toBe(1, '改每页条数后回第一页')
})
- it('导出=当前过滤面全量(含公司 tab 与分组),成功反馈点名落盘文件', async () => {
- const createObjectURL = vi.fn(() => 'blob:mock-url')
- const revokeObjectURL = vi.fn()
- const urlRecord = URL as unknown as Record
- Object.defineProperty(URL, 'createObjectURL', { value: createObjectURL, configurable: true, writable: true })
- Object.defineProperty(URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true, writable: true })
- const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
- jdApi.exportJdProductList.mockImplementation(() =>
- Promise.resolve({ blob: new Blob(['xlsx']), filename: '京东数据库-20261114090000.xlsx' }),
- )
-
- try {
- const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
- const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
- expect(btn, '筛选行必须有「导出」按钮').toBeTruthy()
- await btn!.trigger('click')
- await flushPromises()
- await flushPromises()
-
- expect(jdApi.exportJdProductList).toHaveBeenCalledTimes(1)
- const call = jdApi.exportJdProductList.mock.calls[0][0]
- expect(call).toMatchObject({ shopName: '', groupId: '', companyId: 1 })
- expect(createObjectURL).toHaveBeenCalledTimes(1)
- expect(clickSpy).toHaveBeenCalled()
- expect(document.body.textContent).toContain('已导出', '成功反馈点名落盘文件')
- } finally {
- Object.defineProperty(URL, 'createObjectURL', { value: undefined, configurable: true, writable: true })
- Object.defineProperty(URL, 'revokeObjectURL', { value: undefined, configurable: true, writable: true })
- clickSpy.mockRestore()
- }
- })
-
- it('导出失败把服务端业务文案弹出来,不许静默;在途标记复位', async () => {
- jdApi.exportJdProductList.mockImplementation(() => Promise.reject(new Error('京东商品共 80001 行,超过导出上限 50000 行,请缩小筛选范围后重试')))
+ it('导出按钮已下线:筛选行不再出现「导出」(2026-11-15 客户口径「导出也不用」)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
- await wrapper.findAll('button').find((b) => b.text() === '导出')!.trigger('click')
- await flushPromises()
- await flushPromises()
- expect(document.body.textContent).toContain('超过导出上限')
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
- expect(btn!.text()).toBe('导出', '失败后在途标记必须复位')
- expect((btn!.element as HTMLButtonElement).disabled).toBe(false)
+ expect(btn, '导出按钮必须已从前端移除').toBeUndefined()
+ expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1, '下线导出不影响列表首屏')
})
it('点行打开详情抽屉:按 (id, companyId) 取详情,attrGroups 分块渲染', async () => {
@@ -460,6 +511,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(last.shopName).toBe('', '切公司必须清掉上一家的店铺名')
expect(last.titleKeyword).toBe('', '切公司必须清掉上一家的标题关键字')
expect(last.groupId).toBe('', '切公司必须清掉上一家选的分组')
+ expect(last).not.toHaveProperty('category', '切公司必须清掉上一家选的类目')
expect(last.page).toBe(1)
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(2)
})
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 12e4d6906..04f5845de 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
@@ -7,13 +7,15 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.DataReadScope;
-import com.nanri.aiimage.common.support.DownloadHeaderUtil;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
+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;
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.JdProductDeleteService;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
+import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -26,31 +28,30 @@ 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;
import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 后管「京东数据库」(v1.4 Phase 5)。数据由采集回传同步落表
- * ({@code JdResultIngestService},覆盖最新):列表/详情/导出三个 GET 端点 +
+ * ({@code JdResultIngestService},覆盖最新):列表/详情两个 GET 端点 +
* 删除(单行 {@code DELETE /{id}} 与批量 {@code POST /batch-delete},用户口径
* 「后台删除数据的时候也要把桶对应的文件删除」);分组管理走
* {@code AdminJdProductGroupController}(同款鉴权闸)。
*
- * 删除是唯一会改数据的动作,语义写在 {@code JdProductDeleteService}:先删 {@code jd-products}
- * 桶内对象、全成功才删库行(SKU → 图片登记 → 商品行),被其他商品共用的图片对象保留。
+ * 写动作两个:删除(语义写在 {@code JdProductDeleteService}:先删 {@code jd-products}
+ * 桶内对象、全成功才删库行(SKU → 图片登记 → 商品行),被其他商品共用的图片对象保留)
+ * 与编辑({@code PUT /{id}},语义写在 {@code JdProductUpdateService}:主字段全量提交+可选块,
+ * 保存即置人工编辑锁 manual_locked=1,采集回传对锁定的行不再覆盖/清理,删除成功另写忽略表)。
*
* 鉴权照外观专利只读页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 →
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
@@ -60,22 +61,24 @@ import java.util.List;
* 归属物化在行 company_id 列、可见集不靠账号/分组)——超管显式传才收窄、不传全量;
* 非超管强制本公司(忽略请求传参)。{@code superAdminScopedCompanyId} 对非超管返回 null
* =按行 company_id 列查询时把整张表交给每一家(该方法 javadoc 点名的越权形状),不走那道门。
+ *
+ * 导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
+ * {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。DB 列
+ * {@code biz_jd_product.sale_status} 与详情/回传链不动。
*/
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/admin/jd-products")
-@Tag(name = "京东数据库", description = "后管只读页:京东店铺商品同步落表数据的分页查询、详情与导出,按分公司隔离。")
+@Tag(name = "京东数据库", description = "后管京东店铺商品库:分页查询、详情、编辑与删除,按分公司隔离。")
public class AdminJdProductController {
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
- private static final String XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
- /** 导出文件名时间戳(同外观专利只读页口径),中文文件名的 ASCII 回退由 DownloadHeaderUtil 兜底。 */
- private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
private final JdProductQueryService jdProductQueryService;
private final JdProductDeleteService jdProductDeleteService;
+ private final JdProductUpdateService jdProductUpdateService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@@ -92,7 +95,7 @@ public class AdminJdProductController {
@Parameter(description = "店铺名(包含匹配)") @RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
- @Parameter(description = "商品状态(上架中/已下架/审核中/草稿)") @RequestParam(name = "sale_status", required = false) String saleStatus,
+ @Parameter(description = "类目(京麦末级类目名,eq)") @RequestParam(name = "category", required = false) String category,
@Parameter(description = "分组 id") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "同步开始时间(包含,ISO datetime)")
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
@@ -106,7 +109,21 @@ public class AdminJdProductController {
// 不传全量;非超管强制本公司(忽略请求传参)。
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
return ApiResponse.success(jdProductQueryService.page(page, pageSize, scopedCompanyId, shopName,
- productCode, titleKeyword, saleStatus, groupId, syncedFrom, syncedTo));
+ productCode, titleKeyword, category, groupId, syncedFrom, syncedTo));
+ }
+
+ @GetMapping("/categories")
+ @Operation(summary = "类目筛选下拉数据源", description = "本公司已落库行 DISTINCT 的 category_path"
+ + "(京麦末级类目名)+ 行数,按类目名排序;company_id 只对站点超管生效(显式传才收窄,"
+ + "不传全量),非超管强制本公司。")
+ public ApiResponse> categories(
+ @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
+ HttpServletRequest request) {
+ RequestOperator operator = requireJdAccess(request);
+ AdminUserEntity user = operator.user();
+ // 类目下拉与列表同走 readCompanyIdOrOwn 正门:选项集永远和页签能看到的公司行集同源。
+ Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
+ return ApiResponse.success(jdProductQueryService.categories(scopedCompanyId));
}
@GetMapping("/{id}")
@@ -123,34 +140,24 @@ public class AdminJdProductController {
return ApiResponse.success(jdProductQueryService.detail(id, scopedCompanyId));
}
- @GetMapping("/export")
- @Operation(summary = "导出京东数据库 Excel", description = "与分页查询同一过滤面(店铺名/商品编码/标题关键词/"
- + "商品状态/分组/同步起止),公司隔离走同一正门:company_id 只对站点超管生效(显式传才收窄,"
- + "不传全量),非超管强制本公司。超过导出上限按业务错误拒绝。")
- public ResponseEntity export(
- @Parameter(description = "店铺名(包含匹配)") @RequestParam(name = "shop_name", required = false) String shopName,
- @Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
- @Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
- @Parameter(description = "商品状态") @RequestParam(name = "sale_status", required = false) String saleStatus,
- @Parameter(description = "分组 id") @RequestParam(name = "group_id", required = false) Long groupId,
- @Parameter(description = "同步开始时间(包含,ISO datetime)")
- @RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
- @Parameter(description = "同步结束时间(包含,ISO datetime)")
- @RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
+ @PutMapping("/{id}")
+ @Operation(summary = "编辑京东商品", description = "主字段全量提交(标题/品牌/类目/货号/价格区间/总库存/"
+ + "状态/分组),可选块缺省不动:attrGroups 重建 attr_json 的 tabs 段(其余顶层键保留)、"
+ + "skus 按 skuId 改价格库存、deleteImageIds 删图(共用对象保留)。保存即置人工编辑锁"
+ + "(manual_locked=1):采集回传对该行不再覆盖/清理。返回刷新后的详情。")
+ public ApiResponse update(
+ @Parameter(description = "商品行 id") @PathVariable("id") Long id,
+ @Valid @RequestBody JdProductUpdateRequest body,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request);
AdminUserEntity user = operator.user();
- // 导出与分页共用 readCompanyIdOrOwn 正门(同 page 的口径注释):绝不让导出绕过页签的公司隔离。
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
- byte[] bytes = jdProductQueryService.export(scopedCompanyId, shopName, productCode, titleKeyword,
- saleStatus, groupId, syncedFrom, syncedTo);
- String filename = "京东数据库-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
- return ResponseEntity.ok()
- .header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
- .contentType(MediaType.parseMediaType(XLSX_CONTENT_TYPE))
- .contentLength(bytes.length)
- .body(bytes);
+ Long updatedId = jdProductUpdateService.update(id, body, scopedCompanyId);
+ log.info("[jd-product] 编辑商品 operatorId={} companyId={} id={} title={}",
+ operator.id(), scopedCompanyId, updatedId, body.getTitle());
+ // 返回刷新后的详情(前端保存后直接回填抽屉),复用详情同一查询出口。
+ return ApiResponse.success(jdProductQueryService.detail(updatedId, scopedCompanyId));
}
@DeleteMapping("/{id}")
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductIgnoreMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductIgnoreMapper.java
new file mode 100644
index 000000000..562ec3150
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductIgnoreMapper.java
@@ -0,0 +1,16 @@
+package com.nanri.aiimage.modules.jd.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductIgnoreEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 京东商品删除忽略表(biz_jd_product_ignore,V199)数据访问口。
+ *
+ * 只走 BaseMapper wrapper(铁律 1 允许的两种形态之一,与 {@link JdProductSkuMapper}
+ * 的查询口同形状):写入口是 {@code JdProductDeleteService} 删除成功后的幂等登记,
+ * 读入口是 {@code JdResultIngestService} 按三元组回查命中集。无自定义 SQL,无 XML。
+ */
+@Mapper
+public interface JdProductIgnoreMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
index a9ca955ab..d3a2a86c4 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/mapper/JdProductMapper.java
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.jd.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
+import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -33,14 +34,14 @@ public interface JdProductMapper extends BaseMapper {
/**
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
- * (公司/店铺名/商品编码/标题关键词/商品状态/分组/同步起止,全部 SQL 侧下推,
+ * (公司/店铺名/商品编码/标题关键词/类目/分组/同步起止,全部 SQL 侧下推,
* 铁律 20)。{@code companyId}/{@code groupId} 为空或 ≤0=不过滤该面。
*/
long countProducts(@Param("companyId") Long companyId,
@Param("shopName") String shopName,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword,
- @Param("saleStatus") String saleStatus,
+ @Param("category") String category,
@Param("groupId") Long groupId,
@Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo);
@@ -73,10 +74,17 @@ public interface JdProductMapper extends BaseMapper {
@Param("shopName") String shopName,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword,
- @Param("saleStatus") String saleStatus,
+ @Param("category") String category,
@Param("groupId") Long groupId,
@Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo,
@Param("offset") long offset,
@Param("limit") int limit);
+
+ /**
+ * 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
+ * 本公司已落库行的 DISTINCT {@code category_path}(=京麦末级类目名)+ 行数。
+ * {@code companyId} 为空(超管不选公司)=跨公司全量去重。
+ */
+ List selectProductCategories(@Param("companyId") Long companyId);
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdProductUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdProductUpdateRequest.java
new file mode 100644
index 000000000..4df7be493
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdProductUpdateRequest.java
@@ -0,0 +1,116 @@
+package com.nanri.aiimage.modules.jd.model.dto;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import jakarta.validation.constraints.DecimalMin;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Size;
+import lombok.Data;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+/**
+ * 后管「编辑京东商品」请求体(PUT /api/admin/jd-products/{id},2026-11-15 用户口径)。
+ *
+ * 主字段全量提交(保存即按本请求体覆写这几个列);三个可选块缺省=不动那一面:
+ * {@code attrGroups} 缺省不动属性、{@code skus} 缺省不动 SKU 价格库存、{@code deleteImageIds}
+ * 缺省不删图。公司隔离不走 body——`company_id` 是请求参数,由
+ * {@code DataReadScope#readCompanyIdOrOwn} 统一收口(同本模块全部端点)。
+ *
+ * 编辑保存后商品行 {@code manual_locked=1}(V199 人工编辑锁):采集回传的
+ * upsert / 图片与 SKU 登记 / 覆盖清理对该行全部跳过,人工值不被京麦采集覆盖。
+ */
+@Data
+@Schema(description = "编辑京东商品请求(主字段全量提交,可选块缺省不动)")
+public class JdProductUpdateRequest {
+
+ @Schema(description = "商品标题(必填非空)")
+ @NotBlank(message = "标题不能为空")
+ @Size(max = 600, message = "标题最长 600 字")
+ private String title;
+
+ @Schema(description = "品牌名(可空)")
+ @Size(max = 128, message = "品牌最长 128 字")
+ private String brand;
+
+ @Schema(description = "类目路径(可空)")
+ @Size(max = 500, message = "类目路径最长 500 字")
+ private String categoryPath;
+
+ @Schema(description = "货号(可空)")
+ @Size(max = 128, message = "货号最长 128 字")
+ private String itemNum;
+
+ @Schema(description = "价格区间下限(可空)")
+ @DecimalMin(value = "0", message = "价格下限不能为负数")
+ private BigDecimal priceMin;
+
+ @Schema(description = "价格区间上限(可空)")
+ @DecimalMin(value = "0", message = "价格上限不能为负数")
+ private BigDecimal priceMax;
+
+ @Schema(description = "总库存(可空,非负)")
+ private Integer stockTotal;
+
+ @Schema(description = "商品状态(可空,自由文本)")
+ @Size(max = 32, message = "商品状态最长 32 字")
+ private String saleStatus;
+
+ @Schema(description = "分组 id(null=未分组;组 id 必须属于本公司)")
+ private Long groupId;
+
+ @Schema(description = "属性分组(可选块;缺省不动属性;提交时重建 attr_json 的 tabs 段,其余顶层键保留)")
+ private List attrGroups;
+
+ @Schema(description = "SKU 价格库存编辑(可选块;缺省不动;按 skuId 匹配逐行更新)")
+ private List skus;
+
+ @Schema(description = "要删除的图片登记行 id 清单(可选块;缺省不删图;共用对象保留)")
+ private List deleteImageIds;
+
+ @Data
+ @Schema(description = "属性分组(京麦 Tab 形状)")
+ public static class AttrGroupDto {
+
+ @Schema(description = "分组名(京麦 Tab 名,可空)")
+ @Size(max = 64, message = "属性分组名最长 64 字")
+ private String groupName;
+
+ @Schema(description = "属性键值对列表")
+ private List attrs;
+ }
+
+ @Data
+ @Schema(description = "属性键值对")
+ public static class AttrDto {
+
+ @Schema(description = "属性键(可空)")
+ @Size(max = 128, message = "属性键最长 128 字")
+ private String key;
+
+ @Schema(description = "属性名(可空)")
+ @Size(max = 128, message = "属性名最长 128 字")
+ private String label;
+
+ @Schema(description = "属性值(可空)")
+ @Size(max = 1000, message = "属性值最长 1000 字")
+ private String value;
+ }
+
+ @Data
+ @Schema(description = "SKU 价格库存编辑行")
+ public static class SkuEditDto {
+
+ @Schema(description = "京麦 SKU id(匹配键)")
+ @NotBlank(message = "SKU 行缺少 skuId")
+ @Size(max = 64, message = "skuId 最长 64 字")
+ private String skuId;
+
+ @Schema(description = "京东价(可空=不改)")
+ @DecimalMin(value = "0", message = "SKU 价格不能为负数")
+ private BigDecimal price;
+
+ @Schema(description = "库存(可空=不改,非负)")
+ private Integer stock;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductEntity.java
index 1debceee4..3743a8d95 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductEntity.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductEntity.java
@@ -81,4 +81,6 @@ public class JdProductEntity {
private String collectBatchId;
/** 同步时刻(INSERT 路径走列默认值,UPDATE 路径由 XML 显式刷 CURRENT_TIMESTAMP)。 */
private LocalDateTime syncedAt;
+ /** 人工编辑锁(V199):后管编辑保存置 1;采集 upsert/图片与 SKU 登记/覆盖清理对锁定的行全部跳过——人工值优先,重爬不再覆盖。 */
+ private Integer manualLocked;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductIgnoreEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductIgnoreEntity.java
new file mode 100644
index 000000000..b933587b3
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/entity/JdProductIgnoreEntity.java
@@ -0,0 +1,34 @@
+package com.nanri.aiimage.modules.jd.model.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * 京东商品删除忽略行({@code biz_jd_product_ignore},V199)。
+ *
+ * 后管删除商品成功后写入被删行的 {@code (company_id, shop_id, product_code)} 三元组;
+ * 采集回传({@code JdResultIngestService})对命中三元组的行跳过落库——防止删除后的商品
+ * 在重爬同一店铺时被当作新行重新插回来(upsert 对不存在的键走 INSERT)。
+ *
+ * 不设外键、不级联:主表行被覆盖清理级联删掉时忽略记录仍保留(忽略语义本就独立于
+ * 行存在)。唯一键 {@code uk_company_shop_code} 与主表同三元组口径,重复删除幂等。
+ */
+@Data
+@TableName("biz_jd_product_ignore")
+public class JdProductIgnoreEntity {
+
+ @TableId(type = IdType.AUTO)
+ private Long id;
+ /** 物化归属分公司(与主表 uk_company_shop_code 同口径)。 */
+ private Long companyId;
+ /** 京东店铺标识(与主表 shop_id 同形状,缺省回落 shop_name)。 */
+ private String shopId;
+ /** 京东商品编码。 */
+ private String productCode;
+ /** 写入时刻(后管删除成功时)。 */
+ private LocalDateTime createdAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductCategoryVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductCategoryVo.java
new file mode 100644
index 000000000..df5ac86ea
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductCategoryVo.java
@@ -0,0 +1,22 @@
+package com.nanri.aiimage.modules.jd.model.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+/**
+ * 京东数据库「类目」筛选下拉的一行(2026-11-15 用户口径「京麦的类目也要同步过来后台」)。
+ *
+ * 京麦列表接口只回末级类目名({@code categoryDetailVO.lastCategoryName},契约 §2.3 E3),
+ * 拿不到完整三级树 ⇒ 下拉选项按本公司已落库行的 {@code category_path}(=末级类目名)
+ * distinct 现算,{@code productCount} 是该类目行数(供界面展示「类目(N)」)。
+ */
+@Data
+@Schema(description = "京东数据库类目筛选下拉选项")
+public class JdProductCategoryVo {
+
+ @Schema(description = "类目名(京麦末级类目,即落库的 category_path)")
+ private String name;
+
+ @Schema(description = "该类目的商品行数")
+ private Long productCount;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductDetailVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductDetailVo.java
index a74f2d9b5..81ee3d0a9 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductDetailVo.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/vo/JdProductDetailVo.java
@@ -151,6 +151,9 @@ public class JdProductDetailVo {
@Schema(description = "商品图片")
public static class ImageViewVo {
+ @Schema(description = "图片登记行 id(后管编辑抽屉按它提交删图)")
+ private Long id;
+
@Schema(description = "图片档:MAIN/ATTR/DETAIL")
private String imageType;
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductDeleteService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductDeleteService.java
index 4f235403f..e8ea18a2c 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductDeleteService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductDeleteService.java
@@ -3,9 +3,11 @@ 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.file.service.oss.OssStorageService;
+import com.nanri.aiimage.modules.jd.mapper.JdProductIgnoreMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductIgnoreEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDeleteVo;
import lombok.RequiredArgsConstructor;
@@ -13,6 +15,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
+import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
@@ -53,6 +56,7 @@ public class JdProductDeleteService {
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
+ private final JdProductIgnoreMapper jdProductIgnoreMapper;
private final JdProductRowDeleteService jdProductRowDeleteService;
private final OssStorageService ossStorageService;
@@ -67,7 +71,7 @@ public class JdProductDeleteService {
/** 删除给定商品(含 SKU、图片登记行与桶内对象);见类注释的三条边界。 */
public JdProductDeleteVo delete(List requestedIds, Long scopedCompanyId) {
List ids = normalizeIds(requestedIds);
- requireScopedRows(ids, scopedCompanyId);
+ List scopedRows = requireScopedRows(ids, scopedCompanyId);
List images = imageRowsOf(ids);
Set ownedKeys = new LinkedHashSet<>();
Set foreignKeys = new LinkedHashSet<>();
@@ -89,6 +93,10 @@ public class JdProductDeleteService {
throw ex;
}
+ // V199:删除成功即登记忽略三元组——采集回传对命中行跳过落库,防止重爬把删掉的
+ // 商品当新行插回来(upsert 对不存在的键走 INSERT)。登记失败不推翻删除结果,留痕即可。
+ registerIgnoreRows(scopedRows);
+
JdProductDeleteVo vo = new JdProductDeleteVo();
vo.setDeleted(deleted);
vo.setImagesDeleted(images.size());
@@ -122,17 +130,57 @@ public class JdProductDeleteService {
return new ArrayList<>(unique);
}
- /** 归属闸:行必须都在(且都在当前公司可见面内),否则整批拒绝——不做部分删除。 */
- private void requireScopedRows(List ids, Long scopedCompanyId) {
+ /** 归属闸:行必须都在(且都在当前公司可见面内),否则整批拒绝——不做部分删除。返回归属校验通过的行(供删除成功后登记忽略三元组)。 */
+ private List requireScopedRows(List ids, Long scopedCompanyId) {
boolean scoped = scopedCompanyId != null && scopedCompanyId > 0;
List rows = jdProductMapper.selectList(new LambdaQueryWrapper()
- .select(JdProductEntity::getId)
.in(JdProductEntity::getId, ids)
.eq(scoped, JdProductEntity::getCompanyId, scopedCompanyId));
if (rows.size() != ids.size()) {
throw new BusinessException("有 " + (ids.size() - rows.size())
+ " 个商品不存在或不属于当前公司,请刷新后重试(本次未删除任何数据)");
}
+ return rows;
+ }
+
+ /**
+ * 删除成功后登记忽略三元组(V199):采集回传按 (company_id, shop_id, product_code) 跳过
+ * 命中行,防止重爬把删掉的商品重新插回来。幂等(uk 去重,重复删除同商品 no-op);
+ * shop_id/product_code 读不出键形状的行跳过并留 WARN(与采集侧 protectedKey 同一判据)。
+ * 登记失败不推翻删除结果(删除本体已完成),只留 error 日志。
+ */
+ private void registerIgnoreRows(List rows) {
+ List ignores = new ArrayList<>();
+ for (JdProductEntity row : rows) {
+ if (row.getShopId() == null || row.getShopId().isBlank()
+ || row.getProductCode() == null || row.getProductCode().isBlank()) {
+ log.warn("[{}] 行缺少 shop_id/product_code,忽略登记跳过 productId={}", LOG_TAG, row.getId());
+ continue;
+ }
+ JdProductIgnoreEntity ignore = new JdProductIgnoreEntity();
+ ignore.setCompanyId(row.getCompanyId());
+ ignore.setShopId(row.getShopId().trim());
+ ignore.setProductCode(row.getProductCode().trim());
+ ignores.add(ignore);
+ }
+ if (ignores.isEmpty()) {
+ return;
+ }
+ try {
+ for (JdProductIgnoreEntity ignore : ignores) {
+ // 幂等登记:uk_company_shop_code 冲突即重复删除,直接跳过(MP 无 insert ignore,逐条吞重复)。
+ try {
+ jdProductIgnoreMapper.insert(ignore);
+ } catch (org.springframework.dao.DuplicateKeyException alreadyIgnored) {
+ log.info("[{}] 忽略三元组已登记过(重复删除同商品,no-op) companyId={} shopId={} code={}",
+ LOG_TAG, ignore.getCompanyId(), ignore.getShopId(), ignore.getProductCode());
+ }
+ }
+ log.info("[{}] 删除忽略登记完成 rows={}", LOG_TAG, ignores.size());
+ } catch (RuntimeException ex) {
+ log.error("[{}] 删除忽略登记失败(删除本体已完成,重爬可能复活这些商品,需人工补登记) rows={}",
+ LOG_TAG, rows.size(), ex);
+ }
}
private List imageRowsOf(List ids) {
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductQueryService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductQueryService.java
index 65baa831a..2f546ef7a 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductQueryService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductQueryService.java
@@ -13,26 +13,22 @@ import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
+import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductListItemVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
-import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
- * 后管「京东数据库」只读查询(v1.4 Phase 5):分页 / 详情 / 导出。
+ * 后管「京东数据库」只读查询(v1.4 Phase 5):分页 / 详情。
*
* 分页钳制是本服务的职责(铁律 15):mapper 的 {@code offset}/{@code limit} 只收钳制后的值
* (单一出口,mapper 不做第二次换算)。钳制形状照 {@code AppearancePatentCleanItemQueryService}
@@ -49,9 +45,8 @@ import java.util.Map;
* 非该形状时不抛 500,落空 {@code attrGroups} 并把原文放进 {@code attrJsonRaw} 兜底展示。
* 主表高频列直接从 entity 映射,不走 JSON。
*
- * 导出与分页共用同一过滤面与同一条 SQL(offset=0、limit=导出上限,不另写导出查询),
- * 先 {@code countProducts} 卡 {@link #EXPORT_MAX_ROWS} 上限防内存;行集按后管页面主要字段
- * 中文列序写 xlsx(SXSSF 流式,口径同 {@code QueryAsinService.export} 的 byte[] 形状)。
+ * 导出(byte[] xlsx)已随 2026-11-15 客户口径「导出也不用」整段下线,控制器端点同窗删;
+ * {@code sale_status} 过滤参数同窗撤掉(前端筛选框下线),DB 列与详情/回传链不动。
*/
@Slf4j
@Service
@@ -62,11 +57,6 @@ public class JdProductQueryService {
private static final long MAX_PAGE = 10_000;
/** 每页条数上限(照外观专利只读页同值)。 */
private static final long MAX_PAGE_SIZE = 100;
- /** 单次导出行数上限:超限按业务错误拒(提示缩小筛选面),不把无界内存写进一次 HTTP 响应。 */
- public static final long EXPORT_MAX_ROWS = 50_000;
- /** 导出时间列的展示格式。 */
- private static final DateTimeFormatter EXPORT_DATETIME_FORMATTER =
- DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** attr_json 原始形状里的 Tab 字段名(客户端实拍契约,AC-3 保真不转写)。 */
private static final String ATTR_TAB_FIELD = "tab";
private static final String ATTR_ATTRS_FIELD = "attrs";
@@ -74,12 +64,6 @@ public class JdProductQueryService {
private static final String ATTR_LABEL_FIELD = "label";
private static final String ATTR_VALUE_FIELD = "value";
- /** 导出列序(与后管页面主要字段同序,中文列名)。 */
- private static final List EXPORT_HEADERS = List.of(
- "店铺名", "店铺ID", "商品编码", "货号", "SKU", "SKU数", "信息分", "标题", "品牌", "类目路径",
- "价格下限", "价格上限", "库存", "商品状态", "来源Tab", "上架时间", "京东创建时间",
- "京东修改时间", "属性键数", "图片数", "主图URL", "分组", "同步时间");
-
private final JdProductMapper jdProductMapper;
private final JdProductImageMapper jdProductImageMapper;
private final JdProductSkuMapper jdProductSkuMapper;
@@ -90,10 +74,10 @@ public class JdProductQueryService {
* 分页查询商品行({@code synced_at} 倒序)。
*
* 过滤面:公司(物化列 eq)、店铺名 contains、商品编码 contains、标题关键词 contains、
- * 商品状态 eq、分组 eq、同步起止(datetime 闭区间)。
+ * 类目 eq、分组 eq、同步起止(datetime 闭区间)。
*/
public JdProductPageVo page(Long page, Long pageSize, Long scopedCompanyId, String shopName,
- String productCode, String titleKeyword, String saleStatus, Long groupId,
+ String productCode, String titleKeyword, String category, Long groupId,
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
throw new BusinessException("开始时间不能晚于结束时间");
@@ -101,15 +85,15 @@ public class JdProductQueryService {
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(scopedCompanyId, shopName, productCode, titleKeyword, saleStatus, groupId,
- syncedFrom, syncedTo);
+ Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, category,
+ groupId, syncedFrom, syncedTo);
long total = jdProductMapper.countProducts(filter.companyId(), filter.shopName(), filter.productCode(),
- filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
- filter.syncedTo());
+ filter.titleKeyword(), filter.category(), filter.groupId(),
+ filter.syncedFrom(), filter.syncedTo());
List rows = total <= 0 ? List.of()
: jdProductMapper.selectProductPage(filter.companyId(), filter.shopName(), filter.productCode(),
- filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
- filter.syncedTo(), (safePage - 1) * safeSize, (int) safeSize);
+ filter.titleKeyword(), filter.category(), filter.groupId(),
+ filter.syncedFrom(), filter.syncedTo(), (safePage - 1) * safeSize, (int) safeSize);
List items = rows.stream().map(this::toListItem).toList();
fillGroupNames(items);
JdProductPageVo vo = new JdProductPageVo();
@@ -120,6 +104,16 @@ public class JdProductQueryService {
return vo;
}
+ /**
+ * 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
+ * 本公司已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3)
+ * + 各自行数,按类目名排序。公司隔离与分页同门(控制器经 {@code readCompanyIdOrOwn} 传入)。
+ */
+ public List categories(Long scopedCompanyId) {
+ Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
+ return jdProductMapper.selectProductCategories(companyId);
+ }
+
/**
* 商品详情(主字段全量 + attr_json 解析 + 已转存图片)。
*
@@ -172,49 +166,19 @@ public class JdProductQueryService {
return vo;
}
- /**
- * 导出当前过滤面全量明细为 xlsx 字节(控制器直接回 {@code ResponseEntity},
- * 口径同 {@code AppearancePatentCleanItemQueryService.export})。
- *
- * 先 count 卡 {@link #EXPORT_MAX_ROWS} 上限再取数;取数复用 {@code selectProductPage}
- * 这一条 SQL(offset=0、limit=上限),不另写导出查询——过滤面永远和分页页签同源。
- */
- public byte[] export(Long scopedCompanyId, String shopName, String productCode, String titleKeyword,
- String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
- if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
- throw new BusinessException("开始时间不能晚于结束时间");
- }
- Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, saleStatus, groupId,
- syncedFrom, syncedTo);
- long total = jdProductMapper.countProducts(filter.companyId(), filter.shopName(), filter.productCode(),
- filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
- filter.syncedTo());
- if (total > EXPORT_MAX_ROWS) {
- throw new BusinessException("京东数据库共 " + total + " 行,超过导出上限 " + EXPORT_MAX_ROWS
- + " 行,请缩小筛选范围后重试");
- }
- List rows = total <= 0 ? List.of()
- : jdProductMapper.selectProductPage(filter.companyId(), filter.shopName(), filter.productCode(),
- filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
- filter.syncedTo(), 0L, (int) EXPORT_MAX_ROWS);
- List items = rows.stream().map(this::toListItem).toList();
- fillGroupNames(items);
- return writeExportWorkbook(items);
- }
-
// ---------------------------------------------------------------- 过滤面
/** 服务侧过滤面归一:companyId/groupId ≤0 按没选处理,文本 trim 后空串归 null。 */
private record Filter(Long companyId, String shopName, String productCode, String titleKeyword,
- String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
+ String category, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
}
private static Filter filter(Long scopedCompanyId, String shopName, String productCode, String titleKeyword,
- String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
+ String category, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
return new Filter(companyId, trimToNull(shopName), trimToNull(productCode), trimToNull(titleKeyword),
- trimToNull(saleStatus), safeGroupId, syncedFrom, syncedTo);
+ trimToNull(category), safeGroupId, syncedFrom, syncedTo);
}
/** 超管不选公司(scopedCompanyId=null)=全量可见;正数=只看该公司。 */
@@ -290,6 +254,7 @@ public class JdProductQueryService {
List images = new ArrayList<>(rows.size());
for (JdProductImageEntity row : rows) {
JdProductDetailVo.ImageViewVo view = new JdProductDetailVo.ImageViewVo();
+ view.setId(row.getId());
view.setImageType(row.getImageType());
view.setAttrName(row.getAttrName());
view.setSortNo(row.getSortNo());
@@ -405,67 +370,6 @@ public class JdProductQueryService {
}
}
- // ---------------------------------------------------------------- 导出
-
- private byte[] writeExportWorkbook(List items) {
- try (SXSSFWorkbook workbook = new SXSSFWorkbook(100);
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
- Sheet sheet = workbook.createSheet("京东数据库");
- Row header = sheet.createRow(0);
- for (int c = 0; c < EXPORT_HEADERS.size(); c++) {
- header.createCell(c).setCellValue(EXPORT_HEADERS.get(c));
- }
- for (int i = 0; i < items.size(); i++) {
- writeExportRow(sheet, i + 1, items.get(i));
- }
- // 标题列放宽,其余走默认窄列;与页面列宽观感对齐即可,不追求逐像素。
- sheet.setColumnWidth(4, 46 * 256);
- workbook.write(outputStream);
- workbook.dispose();
- return outputStream.toByteArray();
- } catch (Exception ex) {
- // 落盘/序列化失败必须给可读业务错误,细节进日志(CatchSilenceRatchetTest RETHROW 形状)。
- log.warn("[jd-product] 导出 xlsx 失败 rows={} msg={}", items.size(), ex.getMessage());
- throw new BusinessException("导出京东数据库失败,请稍后重试");
- }
- }
-
- private void writeExportRow(Sheet sheet, int rowIndex, JdProductListItemVo item) {
- Row row = sheet.createRow(rowIndex);
- row.createCell(0).setCellValue(safe(item.getShopName()));
- row.createCell(1).setCellValue(safe(item.getShopId()));
- row.createCell(2).setCellValue(safe(item.getProductCode()));
- row.createCell(3).setCellValue(safe(item.getItemNum()));
- row.createCell(4).setCellValue(safe(item.getSkuId()));
- row.createCell(5).setCellValue(item.getSkuCount() == null ? "" : String.valueOf(item.getSkuCount()));
- row.createCell(6).setCellValue(item.getHealthScore() == null
- ? "" : String.valueOf(item.getHealthScore()));
- row.createCell(7).setCellValue(safe(item.getTitle()));
- row.createCell(8).setCellValue(safe(item.getBrand()));
- row.createCell(9).setCellValue(safe(item.getCategoryPath()));
- row.createCell(10).setCellValue(item.getPriceMin() == null ? "" : item.getPriceMin().toPlainString());
- row.createCell(11).setCellValue(item.getPriceMax() == null ? "" : item.getPriceMax().toPlainString());
- row.createCell(12).setCellValue(item.getStockTotal() == null ? "" : String.valueOf(item.getStockTotal()));
- row.createCell(13).setCellValue(safe(item.getSaleStatus()));
- row.createCell(14).setCellValue(safe(item.getListTab()));
- row.createCell(15).setCellValue(item.getJdOnlineAt() == null
- ? "" : EXPORT_DATETIME_FORMATTER.format(item.getJdOnlineAt()));
- row.createCell(16).setCellValue(item.getJdCreatedAt() == null
- ? "" : EXPORT_DATETIME_FORMATTER.format(item.getJdCreatedAt()));
- row.createCell(17).setCellValue(item.getJdUpdatedAt() == null
- ? "" : EXPORT_DATETIME_FORMATTER.format(item.getJdUpdatedAt()));
- row.createCell(18).setCellValue(item.getAttrCount() == null ? "" : String.valueOf(item.getAttrCount()));
- row.createCell(19).setCellValue(item.getImageCount() == null ? "" : String.valueOf(item.getImageCount()));
- row.createCell(20).setCellValue(safe(item.getMainImageUrl()));
- row.createCell(21).setCellValue(safe(item.getGroupName()));
- row.createCell(22).setCellValue(item.getSyncedAt() == null
- ? "" : EXPORT_DATETIME_FORMATTER.format(item.getSyncedAt()));
- }
-
- private static String safe(String value) {
- return value == null ? "" : value;
- }
-
private static String trimToNull(String value) {
if (value == null) {
return null;
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
new file mode 100644
index 000000000..ccbcc18f9
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdProductUpdateService.java
@@ -0,0 +1,421 @@
+package com.nanri.aiimage.modules.jd.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.common.text.UserMessages;
+import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
+import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
+import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
+import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
+import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
+import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
+import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 后管「编辑京东商品」编排(PUT /api/admin/jd-products/{id},2026-11-15 用户口径
+ * 「每条数据可以编辑,详情里的内容都可以改」)。
+ *
+ * 三条块语义:
+ *
+ * - 主字段全量提交:标题/品牌/类目/货号/价格区间/总库存/状态/分组按请求体覆写;
+ * 分组 id 归属必须与商品行同公司(防跨公司挂组)。保存即置 {@code manual_locked=1}(V199
+ * 人工编辑锁)——采集回传的 upsert / 图片与 SKU 登记 / 覆盖清理对锁定的行全部跳过,
+ * 人工值不被重爬覆盖。
+ * - 可选块缺省不动:{@code attrGroups} 缺省不动属性;提交时只重建 attr_json 的
+ * {@code tabs} 段、保留原 JSON 其它顶层键(images/productCode 等,铁律 30 形状:
+ * 不整份覆写别人的键);原文解析不出(attrJsonRaw 兜底行)则明确拒绝,不让编辑静默丢原文。
+ * {@code skus} 按 (productId, skuId) 匹配逐行改 price/stock,提交里有不存在的 skuId 按不存在拒绝。
+ * {@code deleteImageIds} 复用 {@link JdProductDeleteService} 的共用对象语义删桶对象+登记行。
+ * - 桶删除在库行之前:与 {@link JdProductDeleteService} 同纪律——对象删除不可回滚,
+ * 先删桶、任何对象删不掉整笔拒绝(此时零库行已动,可安全重试)。
+ *
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class JdProductUpdateService {
+
+ private static final String LOG_TAG = "jd-update";
+
+ /** 单次属性分组/属性行上限(防脏包一次写爆 attr_json;京麦 8 个 Tab 量级)。 */
+ private static final int MAX_ATTR_GROUPS = 64;
+ private static final int MAX_ATTRS_PER_GROUP = 200;
+ /** 单次提交 SKU 编辑行上限(京麦单商品 SKU 个位数到几十,与登记侧 200 同量级)。 */
+ private static final int MAX_SKU_EDITS = 200;
+ /** 单次删图上限(与登记链单商品图片量级同档)。 */
+ private static final int MAX_IMAGE_DELETES = 500;
+
+ private final JdProductMapper jdProductMapper;
+ private final JdProductSkuMapper jdProductSkuMapper;
+ private final JdProductImageMapper jdProductImageMapper;
+ private final JdProductGroupMapper jdProductGroupMapper;
+ private final OssStorageService ossStorageService;
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ /** 京东商品图独立桶(与 JdProductDeleteService 同源,application.yml 写死,铁律 17)。 */
+ @Value("${aiimage.jd.oss.bucket:jd-products}")
+ private String bucket;
+
+ /** 对象 key 前缀(与 JdProductDeleteService/JdProductImageIngestService 同源)。 */
+ @Value("${aiimage.jd.oss.key-prefix:jd-products/}")
+ private String keyPrefix;
+
+ /**
+ * 编辑保存,返回商品行 id(控制器用它回读刷新后的详情 VO)。
+ *
+ * 公司隔离与详情同门:行 company_id 与范围不符按不存在拒绝(不泄露越界行存在性)。
+ */
+ @Transactional(rollbackFor = Exception.class)
+ public Long update(Long id, JdProductUpdateRequest body, Long scopedCompanyId) {
+ if (id == null || id <= 0) {
+ throw new BusinessException("商品不存在");
+ }
+ JdProductEntity row = jdProductMapper.selectById(id);
+ if (row == null || !companyVisible(row.getCompanyId(), scopedCompanyId)) {
+ throw new BusinessException("商品不存在");
+ }
+ validateBody(body);
+
+ Long groupId = body.getGroupId();
+ if (groupId != null) {
+ JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
+ if (group == null || !row.getCompanyId().equals(group.getCompanyId())) {
+ throw new BusinessException("分组不存在或不属于当前公司,请刷新分组后重试");
+ }
+ }
+
+ // 可选块先算(属性重建可能拒绝),再动库行——拒绝时零库行已动。
+ String newAttrJson = null;
+ Integer newAttrCount = null;
+ if (body.getAttrGroups() != null) {
+ AttrRewrite rewrite = rebuildAttrJson(row, body.getAttrGroups());
+ newAttrJson = rewrite.json();
+ newAttrCount = rewrite.attrCount();
+ }
+
+ LambdaUpdateWrapper updater = new LambdaUpdateWrapper()
+ .eq(JdProductEntity::getId, id)
+ .set(JdProductEntity::getTitle, body.getTitle().trim())
+ .set(JdProductEntity::getBrand, trimToNull(body.getBrand()))
+ .set(JdProductEntity::getCategoryPath, trimToNull(body.getCategoryPath()))
+ .set(JdProductEntity::getItemNum, trimToNull(body.getItemNum()))
+ .set(JdProductEntity::getPriceMin, body.getPriceMin())
+ .set(JdProductEntity::getPriceMax, body.getPriceMax())
+ .set(JdProductEntity::getStockTotal, body.getStockTotal())
+ .set(JdProductEntity::getSaleStatus, trimToNull(body.getSaleStatus()))
+ .set(JdProductEntity::getGroupId, groupId)
+ // 人工编辑锁:保存即锁定,采集链路(upsert/登记/覆盖清理)此后跳过本行。
+ .set(JdProductEntity::getManualLocked, 1);
+ if (newAttrJson != null) {
+ updater.set(JdProductEntity::getAttrJson, newAttrJson);
+ updater.set(JdProductEntity::getAttrCount, newAttrCount);
+ }
+ int updated = jdProductMapper.update(null, updater);
+ if (updated <= 0) {
+ throw new BusinessException("商品不存在或已被删除,请刷新后重试");
+ }
+
+ if (body.getSkus() != null && !body.getSkus().isEmpty()) {
+ applySkuEdits(row.getId(), body.getSkus());
+ }
+ if (body.getDeleteImageIds() != null && !body.getDeleteImageIds().isEmpty()) {
+ int purged = deleteImages(row, body.getDeleteImageIds());
+ log.info("[{}] 编辑删除图片 productId={} requested={} objectsPurged={}",
+ LOG_TAG, row.getId(), body.getDeleteImageIds().size(), purged);
+ }
+ log.info("[{}] 编辑保存完成 productId={} companyId={} locked=1 attrGroups={} skuEdits={} imageDeletes={}",
+ LOG_TAG, row.getId(), row.getCompanyId(),
+ body.getAttrGroups() == null ? 0 : body.getAttrGroups().size(),
+ body.getSkus() == null ? 0 : body.getSkus().size(),
+ body.getDeleteImageIds() == null ? 0 : body.getDeleteImageIds().size());
+ return id;
+ }
+
+ // ---------- 校验 ----------
+
+ private void validateBody(JdProductUpdateRequest body) {
+ if (body.getPriceMin() != null && body.getPriceMax() != null
+ && body.getPriceMin().compareTo(body.getPriceMax()) > 0) {
+ throw new BusinessException("价格区间下限不能大于上限");
+ }
+ if (body.getStockTotal() != null && body.getStockTotal() < 0) {
+ throw new BusinessException("总库存不能为负数");
+ }
+ if (body.getAttrGroups() != null && body.getAttrGroups().size() > MAX_ATTR_GROUPS) {
+ throw new BusinessException("属性分组超过上限 " + MAX_ATTR_GROUPS + " 个,请精简后重试");
+ }
+ if (body.getAttrGroups() != null) {
+ for (JdProductUpdateRequest.AttrGroupDto group : body.getAttrGroups()) {
+ if (group == null) {
+ continue;
+ }
+ if (group.getAttrs() != null && group.getAttrs().size() > MAX_ATTRS_PER_GROUP) {
+ throw new BusinessException("单个属性分组的属性行超过上限 " + MAX_ATTRS_PER_GROUP + " 条,请精简后重试");
+ }
+ }
+ }
+ if (body.getSkus() != null && body.getSkus().size() > MAX_SKU_EDITS) {
+ throw new BusinessException("SKU 编辑行超过上限 " + MAX_SKU_EDITS + " 行,请分批保存");
+ }
+ if (body.getSkus() != null) {
+ for (JdProductUpdateRequest.SkuEditDto sku : body.getSkus()) {
+ if (sku != null && sku.getStock() != null && sku.getStock() < 0) {
+ throw new BusinessException("SKU 库存不能为负数(skuId=" + sku.getSkuId() + ")");
+ }
+ }
+ }
+ if (body.getDeleteImageIds() != null && body.getDeleteImageIds().size() > MAX_IMAGE_DELETES) {
+ throw new BusinessException("单次最多删除 " + MAX_IMAGE_DELETES + " 张图片,请分批保存");
+ }
+ }
+
+ /** 超管不选公司(scopedCompanyId=null)=全量可编辑;正数=只可编辑该公司行。 */
+ private static boolean companyVisible(Long rowCompanyId, Long scopedCompanyId) {
+ if (scopedCompanyId == null || scopedCompanyId <= 0) {
+ return true;
+ }
+ return scopedCompanyId.equals(rowCompanyId);
+ }
+
+ // ---------- 属性重建(只重建 tabs 段,其余顶层键保留) ----------
+
+ /**
+ * 由提交的 attrGroups 重建 attr_json:原 JSON 是契约形状
+ * {@code {"tabs":[…],"images":[…],"productCode":"…"}}——拷贝原 Map、只覆写 {@code tabs} 键,
+ * images/productCode 等其它顶层键原样保留(铁律 30:不整份覆写别人的键)。
+ * 原文解析不出或不是契约形状(tabs 缺失/不是数组)时按不存在拒绝——这种行的原文兜底
+ * 在详情页可见,静默重写等于丢数据。
+ */
+ private AttrRewrite rebuildAttrJson(JdProductEntity row, List groups) {
+ if (row.getAttrJson() == null || row.getAttrJson().isBlank()) {
+ // 原本就没有属性:按空 tabs 新建,不拒(首采行 attr_json 可为空)。
+ return new AttrRewrite(writeTabs(List.of(), null), countAttrs(groups));
+ }
+ Map root;
+ try {
+ Object parsed = objectMapper.readValue(row.getAttrJson(), Object.class);
+ root = parsed instanceof Map, ?> map ? asStringKeyMap(map) : null;
+ } catch (Exception ex) {
+ root = null;
+ }
+ if (root == null || !(root.get("tabs") instanceof List>)) {
+ throw new BusinessException("该商品的属性原文形状不识别(详情里以原文兜底展示),"
+ + "为防丢数据不允许在线编辑属性;请仅保存主字段");
+ }
+ return new AttrRewrite(writeTabs(groups, root), countAttrs(groups));
+ }
+
+ /** tabs 段重建:groupName→tab、attrs→[{key,label,value}];root 非 null 时其余顶层键原样保留。 */
+ private String writeTabs(List groups, Map root) {
+ List