Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0aa93759d | |||
| e175e85973 | |||
| 91cf5dfaf7 | |||
| b9b66bcb0b | |||
| 84a4bc38b5 | |||
| dea9891e19 | |||
| 7a117187b7 |
@@ -63,7 +63,9 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
|
||||
// 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列
|
||||
// (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] },
|
||||
// 京东数据库(2026-11-14 v1.4):京麦店铺商品采集落库的只读镜像,归属物化在行 company_id 列
|
||||
// (V193,同外观专利 V189 形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
// 京东数据库(2026-11-14 v1.4;2026-11-15 公共化改口径):京麦店铺商品采集落库的只读镜像,
|
||||
// 行 company_id 只剩"哪家公司客户端同步的"来源标记。数据公共(用户定案「不区分公司、属于
|
||||
// 公共的」):详情/编辑/删除/分组管理不带公司维度;留在注册表里的理由是超管的公司 tab 筛选
|
||||
// (=筛选管理员)仍作用于只读列表与类目下拉两个发送口,非超管没有这个筛选、看同一份全量。
|
||||
{ menuKey: 'admin_jd_database', apiFiles: ['src/pages/jd/jd-product-api.ts'], pageFiles: ['src/pages/jd/JdDatabasePage.vue'] },
|
||||
]
|
||||
|
||||
@@ -1,27 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东数据库页(v1.4 Phase 5):公司隔离的京东商品库,筛选行(店铺/商品编码/标题关键字/商品状态/
|
||||
* 分组/同步起止 date 对)+查询/导出/重置/管理分组 + 自绘明细表(勾选列+点行开详情抽屉)
|
||||
/** 京东数据库页(v1.4 Phase 5):公共的京东商品库(2026-11-15 用户定案「不区分公司、属于
|
||||
* 公共的」,分类同亚马逊口径全平台一份),筛选行(店铺/商品编码/标题关键字/分类/分类状态/
|
||||
* 类目/同步起止 date 对)+查询/重置/店铺分类 + 自绘明细表(勾选列+点行开详情抽屉)
|
||||
* + 删除(单行/批量,先删桶对象、全成功才删库行,确认弹窗点名数量)+ OldPagination。
|
||||
* 列表按京麦商品列表样式(2026-11-15 用户口径):店铺/分组前置为第 1/2 列;商品信息列=京麦同款
|
||||
* 公司维度只剩超管的公司 tab(=筛选管理员,非超管没有这个筛选、看到同一份公共全量);
|
||||
* 列表按京麦商品列表样式(2026-11-15 用户口径):店铺/分类前置为第 1/2 列;商品信息列=京麦同款
|
||||
* 合并布局(主图+图下信息分+标题两行+商品编码/货号+SKU 数标签,编码带一键复制);类目/上架
|
||||
* 时间/京东创建/修改时间仍收详情抽屉基本信息(B104「详情显示全部属性」口径不变)。
|
||||
* 商品状态筛选框/列与导出按钮随 2026-11-15 客户口径「这两个不要/导出也不用」从前端下线
|
||||
* (后端 sale_status 参数与 /export 端点保留;状态仍收详情抽屉)。
|
||||
* 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页);
|
||||
* 公司 tab 切换=清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、
|
||||
* 超管切公司 tab = 清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、
|
||||
* 止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来(clampJdSyncedRange 照 clampDatePair)。
|
||||
* 日期初值故意留空:同步数据是累计集,默认当天会让首屏只剩今天同步的行
|
||||
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
deleteJdProducts,
|
||||
exportJdProductList,
|
||||
fetchJdProductCategories,
|
||||
fetchJdProductGroups,
|
||||
fetchJdProductList,
|
||||
type JdProductCategoryOption,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import type { JdProductItem } from './jd-product-model.ts'
|
||||
import { jdPriceRange } from './jd-product-model.ts'
|
||||
import { createJdProductFilterState, JD_SALE_STATUS_HINT } from './jd-product-filter.ts'
|
||||
import { createJdProductFilterState } from './jd-product-filter.ts'
|
||||
import JdProductDetailDrawer from './JdProductDetailDrawer.vue'
|
||||
import JdProductEditDrawer from './JdProductEditDrawer.vue'
|
||||
import JdProductGroupDialog from './JdProductGroupDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
@@ -39,15 +45,36 @@ const rows = ref<JdProductItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
/** 导出在途锁:避免连点导出把同一份过滤面重复请求两遍。 */
|
||||
const exporting = ref(false)
|
||||
const filter = reactive(createJdProductFilterState())
|
||||
/** 分组下拉选项:公司 tab 切换时重取;选项失败不拦列表,只回空下拉(可见「全部分组」)。 */
|
||||
/** 分组下拉选项:分组全平台一份(公共),进页取一次即可;选项失败不拦列表,只回空下拉
|
||||
* (可见「全部分组」)。 */
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
/** 类目下拉选项(京麦末级类目):与当前行集同源(超管切公司 tab 时按 tab 收窄重取、
|
||||
* 普通行集全量);失败静默回空。 */
|
||||
const categoryOptions = ref<JdProductCategoryOption[]>([])
|
||||
/** 分组管理弹窗与详情抽屉。 */
|
||||
const groupDialogVisible = ref(false)
|
||||
const detailItem = ref<JdProductItem | null>(null)
|
||||
const detailVisible = ref(false)
|
||||
/** 行级编辑抽屉(2026-11-15 用户口径「每一条数据后面 需要编辑或者删除;编辑的话
|
||||
* 这里面都是可以编辑的」):删除走下面的 removeOne(同一条删除链),编辑走独立抽屉。 */
|
||||
const editItem = ref<JdProductItem | null>(null)
|
||||
const editVisible = ref(false)
|
||||
|
||||
function openEdit(item: JdProductItem): void {
|
||||
editItem.value = item
|
||||
editVisible.value = true
|
||||
}
|
||||
|
||||
function closeEdit(): void {
|
||||
editVisible.value = false
|
||||
editItem.value = null
|
||||
}
|
||||
|
||||
/** 编辑保存成功:刷新列表(该行已置人工编辑锁,标题/价格等即时可见且不再被采集覆盖)。 */
|
||||
async function onEditSaved(): Promise<void> {
|
||||
await load()
|
||||
}
|
||||
|
||||
/** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */
|
||||
function clampJdSyncedRange(): void {
|
||||
@@ -61,12 +88,21 @@ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.v
|
||||
/** 分组选项失败静默回空——分组只是筛选项,不该让它把首屏行集一起拖死。 */
|
||||
async function loadGroupOptions(): Promise<void> {
|
||||
try {
|
||||
groupOptions.value = await fetchJdProductGroups(companyTab.requestCompanyId)
|
||||
groupOptions.value = await fetchJdProductGroups()
|
||||
} catch {
|
||||
groupOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 类目选项同分组口径:失败静默回空下拉(可见「全部类目」),不拦首屏行集。 */
|
||||
async function loadCategoryOptions(): Promise<void> {
|
||||
try {
|
||||
categoryOptions.value = await fetchJdProductCategories(companyTab.requestCompanyId)
|
||||
} catch {
|
||||
categoryOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 分组管理弹窗里做过变更:分组下拉与列表都刷新(删除分组后行集的 groupName 会变)。 */
|
||||
async function onGroupChanged(): Promise<void> {
|
||||
await loadGroupOptions()
|
||||
@@ -84,8 +120,9 @@ async function load(): Promise<void> {
|
||||
shopName: filter.shopName,
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
saleStatus: filter.saleStatus,
|
||||
category: filter.category,
|
||||
groupId: filter.groupId,
|
||||
groupScope: filter.groupScope,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
@@ -103,38 +140,6 @@ async function load(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出与页签同一过滤面(含公司 tab 与分组),服务端全量出 xlsx;成功后浏览器落盘,失败弹可读文案。 */
|
||||
async function exportAll(): Promise<void> {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const result = await exportJdProductList({
|
||||
shopName: filter.shopName,
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
saleStatus: filter.saleStatus,
|
||||
groupId: filter.groupId,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
})
|
||||
const url = URL.createObjectURL(result.blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = result.filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
showAdminFeedback(`已导出 ${result.filename}`, 'success')
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : '导出失败,请稍后重试'
|
||||
showAdminFeedback(message, 'error')
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function apply(): void {
|
||||
page.value = 1
|
||||
void load()
|
||||
@@ -219,7 +224,7 @@ async function removeMany(picked: JdProductItem[], message: string): Promise<voi
|
||||
if (!ok) return
|
||||
deleting.value = true
|
||||
try {
|
||||
const receipt = await deleteJdProducts(picked.map((row) => row.id), companyTab.requestCompanyId)
|
||||
const receipt = await deleteJdProducts(picked.map((row) => row.id))
|
||||
showAdminFeedback(`已删除 ${receipt.deleted} 个商品,清理 ${receipt.objectsDeleted} 个图片文件` +
|
||||
(receipt.objectsKept ? `(${receipt.objectsKept} 个共用图片保留)` : ''), 'success')
|
||||
selectedIds.value = new Set()
|
||||
@@ -233,12 +238,14 @@ async function removeMany(picked: JdProductItem[], message: string): Promise<voi
|
||||
}
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数:店铺/编码/关键字/状态/分组是上一家选中的值,在新一家的行集里筛不出东西,
|
||||
// 必须一起清,分组选项也按新公司重取(选项集是公司隔离的)。
|
||||
watch(() => companyTab.activeId, () => { filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.saleStatus = ''; filter.groupId = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadGroupOptions(); void load() })
|
||||
// 超管切公司 tab = 重新取数:店铺/编码/关键字/类目/日期是按行集筛的自由值,在另一家的
|
||||
// 行集里筛不出东西,必须一起清(分组与分类状态全平台一份,groupId/groupScope 与公司维度
|
||||
// 正交、不清);类目选项与行集同源,按新 tab 重取;分组选项是全局的、进页取一次即可。
|
||||
watch(() => companyTab.activeId, () => { filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.category = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadCategoryOptions(); void load() })
|
||||
|
||||
onMounted(() => {
|
||||
void loadGroupOptions()
|
||||
void loadCategoryOptions()
|
||||
void load()
|
||||
})
|
||||
</script>
|
||||
@@ -248,7 +255,7 @@ onMounted(() => {
|
||||
<section class="panel-box">
|
||||
<div class="jd-panel-head">
|
||||
<h3>京东数据库</h3>
|
||||
<button class="btn btn-secondary" type="button" @click="groupDialogVisible = true">管理分组</button>
|
||||
<button class="btn btn-secondary" type="button" @click="groupDialogVisible = true">店铺分类</button>
|
||||
</div>
|
||||
|
||||
<div class="jd-filter-row">
|
||||
@@ -265,15 +272,33 @@ onMounted(() => {
|
||||
<input v-model="filter.titleKeyword" type="text" placeholder="输入标题关键字" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>商品状态</label>
|
||||
<input v-model="filter.saleStatus" type="text" :placeholder="JD_SALE_STATUS_HINT" @keyup.enter="apply" />
|
||||
<label>分类</label>
|
||||
<!-- 分类选中即查:选完立刻按该分类过滤刷新(回第一页),不必再点查询。
|
||||
(2026-11-15「分组管理」改「店铺分类」:同一 group 实体,只改界面措辞。) -->
|
||||
<select v-model="filter.groupId" @change="apply">
|
||||
<option value="">全部分类</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>分组</label>
|
||||
<!-- 分组选中即查:选完立刻按该分组过滤刷新(回第一页),不必再点查询。 -->
|
||||
<select v-model="filter.groupId" @change="apply">
|
||||
<option value="">全部分组</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
|
||||
<label>分类状态</label>
|
||||
<!-- 分类状态(2026-11-15 客户口径「查询已分类的跟未分类,分类好的可以不显示」):
|
||||
选中即查,同分组/类目口径;与上方「分类」(具体分组等值过滤)正交——
|
||||
这里只按 group_id 是否为空分档。 -->
|
||||
<select v-model="filter.groupScope" @change="apply">
|
||||
<option value="">全部</option>
|
||||
<option value="grouped">已分类</option>
|
||||
<option value="ungrouped">未分类</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>类目</label>
|
||||
<!-- 类目(京麦末级类目)选中即查:同分组口径,选完立刻按该类目过滤刷新(回第一页)。 -->
|
||||
<select v-model="filter.category" @change="apply">
|
||||
<option value="">全部类目</option>
|
||||
<option v-for="cat in categoryOptions" :key="cat.name" :value="cat.name">
|
||||
{{ cat.name }}({{ cat.productCount }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
@@ -286,9 +311,6 @@ onMounted(() => {
|
||||
</div>
|
||||
<div class="jd-filter-actions">
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
<button class="btn btn-export" type="button" :disabled="exporting" @click="exportAll">
|
||||
{{ exporting ? '导出中...' : '导出' }}
|
||||
</button>
|
||||
<button class="btn btn-secondary" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -312,13 +334,15 @@ onMounted(() => {
|
||||
<tr>
|
||||
<th style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th style="width: 130px">店铺</th>
|
||||
<th style="width: 96px">分组</th>
|
||||
<th style="width: 96px">分类</th>
|
||||
<th>商品信息</th>
|
||||
<th style="width: 90px">品牌</th>
|
||||
<th style="width: 110px">价格区间</th>
|
||||
<th style="width: 76px">总库存</th>
|
||||
<th style="width: 86px">商品状态</th>
|
||||
<th style="width: 120px">价格</th>
|
||||
<th style="width: 170px">上架时间 / 商品状态</th>
|
||||
<th style="width: 150px">创建时间</th>
|
||||
<th style="width: 150px">修改时间</th>
|
||||
<th style="width: 170px">同步时间</th>
|
||||
<th style="width: 120px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -326,7 +350,7 @@ onMounted(() => {
|
||||
<tr v-for="row in rows" :key="row.id" class="jd-row" @click="openDetail(row)">
|
||||
<td @click.stop><input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row, ($event.target as HTMLInputElement).checked)" /></td>
|
||||
<td :title="row.shopName || ''">{{ row.shopName || '-' }}</td>
|
||||
<td :title="row.groupName || ''">{{ row.groupName || '未分组' }}</td>
|
||||
<td :title="row.groupName || ''">{{ row.groupName || '未分类' }}</td>
|
||||
<td class="jd-info-cell">
|
||||
<div class="jd-info-wrap">
|
||||
<div class="jd-info-figure">
|
||||
@@ -341,22 +365,37 @@ onMounted(() => {
|
||||
<button v-if="row.productCode" class="jd-copy-btn" type="button" title="复制商品编码" @click.stop="copyText(row.productCode)">⧉</button>
|
||||
</div>
|
||||
<div class="jd-info-meta">货号:<span class="jd-info-code">{{ row.itemNum || '-' }}</span></div>
|
||||
<!-- 品牌·类目行:京麦列表同款(末级类目名紧随品牌),字段与顺序 2026-11-15 对齐京麦。 -->
|
||||
<div v-if="row.brand || row.categoryPath" class="jd-info-meta jd-brand-cat">
|
||||
<span class="jd-brand-name">{{ row.brand || '' }}</span> {{ row.categoryPath || '' }}
|
||||
</div>
|
||||
<div v-if="row.skuCount" class="jd-info-tags"><span class="jd-tag">{{ row.skuCount }}个SKU</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>{{ row.brand || '-' }}</td>
|
||||
<td>{{ jdPriceRange(row) || '-' }}</td>
|
||||
<td>{{ row.stockTotal ?? '-' }}</td>
|
||||
<td>{{ row.saleStatus || '-' }}</td>
|
||||
<td>{{ jdPriceRange(row) || '-' }}</td>
|
||||
<td class="jd-online-cell">
|
||||
<div>{{ formatDateTime(row.jdOnlineAt || '') || '-' }}</div>
|
||||
<div v-if="row.saleStatus" class="jd-sale-status" :class="{ off: row.saleStatus !== '上架中' }">
|
||||
<span class="jd-sale-dot"></span>{{ row.saleStatus }}
|
||||
</div>
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.jdCreatedAt || '') || '-' }}</td>
|
||||
<td>{{ formatDateTime(row.jdUpdatedAt || '') || '-' }}</td>
|
||||
<td>{{ formatDateTime(row.syncedAt || '') }}</td>
|
||||
<!-- 操作列(2026-11-15 用户口径):编辑/删除;@click.stop 防冒泡开详情抽屉。 -->
|
||||
<td class="jd-ops-cell" @click.stop>
|
||||
<button class="btn btn-sm" type="button" @click="openEdit(row)">编辑</button>
|
||||
<button class="btn btn-sm btn-danger" type="button" :disabled="deleting" @click="removeOne(row)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
<td colspan="11" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="9" class="empty-tip">暂无京东商品数据</td>
|
||||
<td colspan="11" class="empty-tip">暂无京东商品数据</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -368,12 +407,16 @@ onMounted(() => {
|
||||
<JdProductDetailDrawer
|
||||
:item="detailItem"
|
||||
:visible="detailVisible"
|
||||
:company-id="companyTab.requestCompanyId"
|
||||
@close="closeDetail"
|
||||
/>
|
||||
<JdProductEditDrawer
|
||||
:item="editItem"
|
||||
:visible="editVisible"
|
||||
@close="closeEdit"
|
||||
@saved="onEditSaved"
|
||||
/>
|
||||
<JdProductGroupDialog
|
||||
:visible="groupDialogVisible"
|
||||
:company-id="companyTab.requestCompanyId"
|
||||
@close="groupDialogVisible = false"
|
||||
@changed="onGroupChanged"
|
||||
/>
|
||||
@@ -415,14 +458,18 @@ h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.jd-filter-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, minmax(140px, 1fr)) auto;
|
||||
/* 可换行流式布局:固定 6 列 minmax(140px) 的网格在窄面板下最小宽超出容器,
|
||||
把查询/重置挤出面板右缘(与「管理分组」重叠)。flex-wrap 让放不下的项自然折行。 */
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.jd-filter-row .form-group {
|
||||
min-width: 0;
|
||||
flex: 1 1 160px;
|
||||
min-width: 150px;
|
||||
max-width: 260px;
|
||||
}
|
||||
.jd-filter-actions {
|
||||
display: flex;
|
||||
@@ -542,7 +589,21 @@ h3 {
|
||||
table-layout: fixed;
|
||||
}
|
||||
.jd-table-scroll > 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 +617,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 +735,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;
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东店铺分类弹窗右栏:商品人工归类面板(2026-11-15 从 JdProductGroupDialog 拆出,
|
||||
* 独立件也守可读棘轮的 800 行报警线)。范围切换(全部/未分类/当前分类)+标题关键字搜索
|
||||
* +勾选行 →「归入所选分类」/「移出分类」。归类走批量端点
|
||||
* POST /api/admin/jd-products/batch-assign-group:后端与单行编辑同口径置 manual_locked=1
|
||||
* (归类即人工干预,采集 upsert/覆盖清理不再碰该行,分类永不丢;代价是该行价格/库存随锁
|
||||
* 停更——弹窗提示语点名这个后果)。取数复用 fetchJdProductList(不带公司维度,
|
||||
* company-tab-wiring 只认两个公司维度发送口);「未分类」走 ungrouped 参数。
|
||||
* 归类目标(selectedGroup)由左栏(父件)点亮下发;弹窗壳 v-if 整树重建 ⇒ 每次打开即本件
|
||||
* 重挂载、onMounted 自取首屏行集。成功后 emit('changed') 让父件刷新分类商品数并上抛页面;
|
||||
* 业务失败把后端中文文案展示在本面板红条内。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { batchAssignJdProductGroup, fetchJdProductList } from './jd-product-api.ts'
|
||||
import type { JdProductGroup } from './jd-product-api.ts'
|
||||
import type { JdProductItem } from './jd-product-model.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 左栏点亮的分类=归类目标;null=尚未点亮(「归入」按钮置灰)。 */
|
||||
selectedGroup: JdProductGroup | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'changed'): void }>()
|
||||
|
||||
type Scope = 'all' | 'ungrouped' | 'current'
|
||||
const scope = ref<Scope>('all')
|
||||
const keyword = ref('')
|
||||
const PRODUCT_PAGE_SIZE = 20
|
||||
const products = ref<JdProductItem[]>([])
|
||||
const productTotal = ref(0)
|
||||
const productPage = ref(1)
|
||||
const productsLoading = ref(false)
|
||||
const productsError = ref('')
|
||||
/** 本页勾选集(按行 id):切范围/翻页/重取后清空,防「看不见的勾选被一起归类」。 */
|
||||
const selectedProductIds = ref<Set<number>>(new Set())
|
||||
const assigning = ref(false)
|
||||
|
||||
const selectedCount = computed(() => selectedProductIds.value.size)
|
||||
/** 归入所选分类:必须先在左侧点亮一个分类且有勾选行。 */
|
||||
const canAssign = computed(() => !!props.selectedGroup && selectedCount.value > 0 && !assigning.value)
|
||||
const canRemove = computed(() => selectedCount.value > 0 && !assigning.value)
|
||||
const allSelected = computed(() =>
|
||||
products.value.length > 0 && products.value.every((row) => selectedProductIds.value.has(row.id)))
|
||||
|
||||
async function loadProducts(): Promise<void> {
|
||||
productsLoading.value = true
|
||||
productsError.value = ''
|
||||
try {
|
||||
const result = await fetchJdProductList({
|
||||
page: productPage.value,
|
||||
pageSize: PRODUCT_PAGE_SIZE,
|
||||
titleKeyword: keyword.value.trim(),
|
||||
groupId: scope.value === 'current' && props.selectedGroup ? String(props.selectedGroup.id) : '',
|
||||
ungrouped: scope.value === 'ungrouped',
|
||||
companyId: null,
|
||||
})
|
||||
products.value = result.items
|
||||
productTotal.value = result.total
|
||||
if (result.page >= 1) productPage.value = result.page
|
||||
selectedProductIds.value = new Set()
|
||||
} catch (error) {
|
||||
productsError.value = requestErrorMessage(error) || '商品列表加载失败'
|
||||
products.value = []
|
||||
productTotal.value = 0
|
||||
selectedProductIds.value = new Set()
|
||||
} finally {
|
||||
productsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function pickScope(next: Scope): void {
|
||||
if (next === 'current' && !props.selectedGroup) return
|
||||
if (scope.value === next) return
|
||||
scope.value = next
|
||||
productPage.value = 1
|
||||
void loadProducts()
|
||||
}
|
||||
|
||||
function searchProducts(): void {
|
||||
productPage.value = 1
|
||||
void loadProducts()
|
||||
}
|
||||
|
||||
function changeProductPage(next: number): void {
|
||||
if (next < 1 || next === productPage.value) return
|
||||
productPage.value = next
|
||||
void loadProducts()
|
||||
}
|
||||
|
||||
function toggleSelect(row: JdProductItem, checked: boolean): void {
|
||||
const next = new Set(selectedProductIds.value)
|
||||
if (checked) next.add(row.id)
|
||||
else next.delete(row.id)
|
||||
selectedProductIds.value = next
|
||||
}
|
||||
|
||||
function toggleSelectAll(checked: boolean): void {
|
||||
selectedProductIds.value = checked ? new Set(products.value.map((row) => row.id)) : new Set()
|
||||
}
|
||||
|
||||
/** 勾选行 → 归入左栏点亮的分类。成功后分类商品数(父件)与右栏行集都刷新(归类过的行离开「未分类」)。 */
|
||||
async function assignToSelected(): Promise<void> {
|
||||
const target = props.selectedGroup
|
||||
if (!target || !canAssign.value) return
|
||||
assigning.value = true
|
||||
productsError.value = ''
|
||||
try {
|
||||
const updated = await batchAssignJdProductGroup([...selectedProductIds.value], target.id)
|
||||
showAdminFeedback(`已把 ${updated} 个商品归入「${target.name}」`, 'success')
|
||||
emit('changed')
|
||||
await loadProducts()
|
||||
} catch (error) {
|
||||
productsError.value = requestErrorMessage(error) || '归类失败,请稍后重试'
|
||||
} finally {
|
||||
assigning.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 勾选行 → 移出分类(group_id 置 NULL,回到未分类)。 */
|
||||
async function removeFromCategory(): Promise<void> {
|
||||
if (!canRemove.value) return
|
||||
assigning.value = true
|
||||
productsError.value = ''
|
||||
try {
|
||||
const updated = await batchAssignJdProductGroup([...selectedProductIds.value], null)
|
||||
showAdminFeedback(`已把 ${updated} 个商品移出分类`, 'success')
|
||||
emit('changed')
|
||||
await loadProducts()
|
||||
} catch (error) {
|
||||
productsError.value = requestErrorMessage(error) || '移出分类失败,请稍后重试'
|
||||
} finally {
|
||||
assigning.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 目标分类变化(左栏点亮/删除):右栏停在「当前分类」页签时随点亮对象换行集;
|
||||
// 目标被删(null)=「当前分类」没了,拉回全量页签,不留在空集页签里。
|
||||
watch(
|
||||
() => props.selectedGroup,
|
||||
(group) => {
|
||||
if (scope.value !== 'current') return
|
||||
if (group && group.id > 0) {
|
||||
productPage.value = 1
|
||||
void loadProducts()
|
||||
} else {
|
||||
scope.value = 'all'
|
||||
productPage.value = 1
|
||||
void loadProducts()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void loadProducts()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="right-pane">
|
||||
<div class="product-toolbar">
|
||||
<div class="scope-tabs">
|
||||
<button type="button" :class="{ on: scope === 'all' }" @click="pickScope('all')">全部</button>
|
||||
<button type="button" :class="{ on: scope === 'ungrouped' }" @click="pickScope('ungrouped')">未分类</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ on: scope === 'current' }"
|
||||
:disabled="!selectedGroup"
|
||||
:title="selectedGroup ? `只看「${selectedGroup.name}」下的商品` : '先在左侧点选一个分类'"
|
||||
@click="pickScope('current')"
|
||||
>当前分类</button>
|
||||
</div>
|
||||
<input v-model="keyword" type="text" class="keyword-input" placeholder="标题关键字" @keyup.enter="searchProducts" />
|
||||
<button class="btn btn-small" type="button" @click="searchProducts">查询</button>
|
||||
</div>
|
||||
<p v-if="productsError" class="pane-error">
|
||||
{{ productsError }}
|
||||
<button class="btn btn-secondary btn-mini" type="button" @click="loadProducts">重试</button>
|
||||
</p>
|
||||
|
||||
<div class="product-list">
|
||||
<table v-if="products.length">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="col-check"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th>商品信息</th>
|
||||
<th class="col-group">当前分类</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in products" :key="row.id">
|
||||
<td class="col-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="selectedProductIds.has(row.id)"
|
||||
@change="toggleSelect(row, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<div class="product-cell">
|
||||
<img v-if="row.mainImageUrl" class="product-thumb" :src="row.mainImageUrl" alt="" loading="lazy" />
|
||||
<span v-else class="product-thumb product-thumb-empty">无图</span>
|
||||
<div class="product-body">
|
||||
<div class="product-title" :title="row.title">{{ row.title || '-' }}</div>
|
||||
<div class="product-meta">商品编码:{{ row.productCode || '-' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="col-group" :title="row.groupName || ''">{{ row.groupName || '未分类' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else-if="productsLoading" class="pane-tip">加载中...</p>
|
||||
<p v-else-if="!productsError" class="pane-tip">没有符合条件的商品</p>
|
||||
</div>
|
||||
|
||||
<div class="product-footer">
|
||||
<span class="pick-summary">已勾选 {{ selectedCount }} 个商品</span>
|
||||
<div class="footer-actions">
|
||||
<button class="btn btn-small" type="button" :disabled="!canAssign" @click="assignToSelected">
|
||||
{{ assigning ? '归类中...' : selectedGroup ? `归入「${selectedGroup.name}」` : '归入所选分类' }}
|
||||
</button>
|
||||
<button class="btn btn-danger btn-small" type="button" :disabled="!canRemove" @click="removeFromCategory">移出分类</button>
|
||||
</div>
|
||||
</div>
|
||||
<OldPagination
|
||||
:total="productTotal"
|
||||
:page="productPage"
|
||||
:page-size="PRODUCT_PAGE_SIZE"
|
||||
:sizes="[PRODUCT_PAGE_SIZE]"
|
||||
:jump="false"
|
||||
@change="changeProductPage"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.right-pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 14px;
|
||||
}
|
||||
.product-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.scope-tabs {
|
||||
display: flex;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 9px;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.scope-tabs button {
|
||||
min-height: 34px;
|
||||
padding: 5px 14px;
|
||||
border: 0;
|
||||
border-right: 1px solid #e7eef5;
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.scope-tabs button:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.scope-tabs button:hover:not(:disabled):not(.on) {
|
||||
background: #edf5fb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.scope-tabs button.on {
|
||||
background: #4f78a5;
|
||||
color: #ffffff;
|
||||
}
|
||||
.scope-tabs button:disabled {
|
||||
color: #9baaba;
|
||||
background: #eef3f7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.keyword-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 36px;
|
||||
padding: 6px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.keyword-input:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.pane-error {
|
||||
margin: 0 0 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
/* 错误条右缘的重试入口:一条真能办成事的出口(重试绑页内 loadProducts,守卫 load-failure-visibility 钉)。 */
|
||||
.pane-error .btn {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pane-tip {
|
||||
margin: 10px 2px;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
}
|
||||
.product-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.product-list table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.product-list th,
|
||||
.product-list td {
|
||||
padding: 8px 12px;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.product-list th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.product-list tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.product-list tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.col-check {
|
||||
width: 42px;
|
||||
}
|
||||
.col-check input {
|
||||
margin: 0;
|
||||
}
|
||||
.col-group {
|
||||
width: 140px;
|
||||
color: #7b8a99;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.product-cell {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.product-thumb {
|
||||
flex-shrink: 0;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #f2f7fb;
|
||||
}
|
||||
.product-thumb-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.product-body {
|
||||
min-width: 0;
|
||||
}
|
||||
.product-title {
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
word-break: break-all;
|
||||
}
|
||||
.product-meta {
|
||||
margin-top: 2px;
|
||||
color: #7b8a99;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.product-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.pick-summary {
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.footer-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-left: auto;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-small {
|
||||
min-height: 34px;
|
||||
padding: 5px 13px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.btn-danger {
|
||||
background: #ffffff;
|
||||
color: #a04432;
|
||||
border-color: #e4b3a8;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: #fdf1ef;
|
||||
border-color: #d08a7b;
|
||||
}
|
||||
/* 弹窗里的分页贴右、收紧行高(页内版式在弹窗内偏大)。 */
|
||||
:deep(.old-pagination) {
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
@@ -4,7 +4,7 @@
|
||||
* 基本信息=商品全部字段(B104:列表只摆部分字段,类目/信息分/SKU 数/上架时间/京东创建/
|
||||
* 修改时间/店铺/分组都在这里看)。
|
||||
* 图片点击放大预览用自绘 modal-mask(先例:RecordsHistoryPage 的 thumb + modal-mask +
|
||||
* 原图新标签;不用 element-plus)。数据由本组件按 (id, companyId) 自取,失败条内提示可重试。 */
|
||||
* 原图新标签;不用 element-plus)。数据由本组件按 id 自取(公共库无公司维度),失败条内提示可重试。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { fetchJdProductDetail } from './jd-product-api.ts'
|
||||
import type {
|
||||
@@ -20,7 +20,6 @@ import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
const props = defineProps<{
|
||||
item: JdProductItem | null
|
||||
visible: boolean
|
||||
companyId: number | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void }>()
|
||||
@@ -82,7 +81,7 @@ async function loadDetail(): Promise<void> {
|
||||
skus.value = []
|
||||
attrJsonRaw.value = ''
|
||||
try {
|
||||
const detail = await fetchJdProductDetail(item.id, props.companyId)
|
||||
const detail = await fetchJdProductDetail(item.id)
|
||||
attrGroups.value = detail.attrGroups
|
||||
images.value = detail.images
|
||||
skus.value = detail.skus
|
||||
@@ -147,7 +146,7 @@ function dash(value: string | number | null | undefined): string {
|
||||
<div class="info-item"><dt>总库存</dt><dd>{{ dash(item?.stockTotal) }}</dd></div>
|
||||
<div class="info-item"><dt>状态</dt><dd>{{ dash(item?.saleStatus) }}</dd></div>
|
||||
<div class="info-item"><dt>店铺</dt><dd :title="item?.shopName || ''">{{ dash(item?.shopName) }}</dd></div>
|
||||
<div class="info-item"><dt>分组</dt><dd>{{ dash(item?.groupName || '未分组') }}</dd></div>
|
||||
<div class="info-item"><dt>分类</dt><dd>{{ dash(item?.groupName || '未分类') }}</dd></div>
|
||||
<div class="info-item"><dt>上架时间</dt><dd>{{ item?.jdOnlineAt ? formatDateTime(item.jdOnlineAt) : '-' }}</dd></div>
|
||||
<div class="info-item"><dt>京东创建时间</dt><dd>{{ item?.jdCreatedAt ? formatDateTime(item.jdCreatedAt) : '-' }}</dd></div>
|
||||
<div class="info-item"><dt>京东修改时间</dt><dd>{{ item?.jdUpdatedAt ? formatDateTime(item.jdUpdatedAt) : '-' }}</dd></div>
|
||||
|
||||
@@ -0,0 +1,694 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品编辑抽屉(2026-11-15 用户口径「每一条数据后面 需要编辑或者删除;编辑的话
|
||||
* 这里面都是可以编辑的」):详情抽屉的可编辑版——基本信息/属性与设置/SKU 矩阵(价格、
|
||||
* 库存)/图片(标删)四块。形状照 JdProductDetailDrawer(自绘 drawer + 分块 + attr-group
|
||||
* 表格 + image-grid,零 element-plus)。
|
||||
* 保存语义在后端 JdProductUpdateService(PUT /api/admin/jd-products/{id}):主字段全量提交
|
||||
* +可选块(attrGroups 重建 attr_json 的 tabs 段、skus 按 skuId 改价格库存、deleteImageIds
|
||||
* 删图——先删桶、共用对象保留)。保存即置人工编辑锁 manual_locked=1:后续采集不再覆盖该行,
|
||||
* 底部常驻提示点名这件事。
|
||||
* 图片只支持删除(上传/替换链路未做,BACKLOG);京东时间/信息分/商品编码只读。
|
||||
* 数据自取 fetchJdProductDetail 回填,保存成功用返回的刷新详情直接回填并 emit('saved')。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
fetchJdProductDetail,
|
||||
fetchJdProductGroups,
|
||||
updateJdProduct,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import type {
|
||||
JdProductAttrEntry,
|
||||
JdProductAttrGroup,
|
||||
JdProductImage,
|
||||
JdProductItem,
|
||||
JdProductSku,
|
||||
} from './jd-product-model.ts'
|
||||
import { jdSkuDimensions } from './jd-product-model.ts'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const props = defineProps<{
|
||||
item: JdProductItem | null
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'saved'): void }>()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const saving = ref(false)
|
||||
/** 保存失败红条(后端校验/业务文案原样展示,如价格倒挂、SKU 行不存在)。 */
|
||||
const saveError = ref('')
|
||||
|
||||
// ---------------- 草稿(基本信息 + 属性 + SKU + 删图标记) ----------------
|
||||
|
||||
interface DraftAttrGroup {
|
||||
groupName: string
|
||||
attrs: JdProductAttrEntry[]
|
||||
}
|
||||
|
||||
const form = ref({
|
||||
title: '',
|
||||
brand: '',
|
||||
categoryPath: '',
|
||||
itemNum: '',
|
||||
priceMin: '',
|
||||
priceMax: '',
|
||||
stockTotal: '' as string,
|
||||
saleStatus: '',
|
||||
groupId: '' as string,
|
||||
})
|
||||
const draftAttrGroups = ref<DraftAttrGroup[]>([])
|
||||
const draftSkus = ref<JdProductSku[]>([])
|
||||
const images = ref<JdProductImage[]>([])
|
||||
/** 标删的图片行 id(前端只标记,保存时一次提交 deleteImageIds)。 */
|
||||
const deleteImageIds = ref<Set<number>>(new Set())
|
||||
/** attr_json 解析失败(attrJsonRaw 兜底行):属性块禁用,防保存把原文形状弄丢。 */
|
||||
const attrJsonRaw = ref('')
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
|
||||
const skuDimensions = computed(() => jdSkuDimensions(draftSkus.value))
|
||||
const deletedCount = computed(() => deleteImageIds.value.size)
|
||||
const remainingImageCount = computed(() => images.value.length - deletedCount.value)
|
||||
|
||||
function skuAttrValue(sku: JdProductSku, dimension: string): string {
|
||||
return sku.saleAttrs.find((attr) => attr.name === dimension)?.value || '-'
|
||||
}
|
||||
|
||||
function toggleDeleteImage(image: JdProductImage): void {
|
||||
const next = new Set(deleteImageIds.value)
|
||||
if (next.has(image.id)) next.delete(image.id)
|
||||
else next.add(image.id)
|
||||
deleteImageIds.value = next
|
||||
}
|
||||
|
||||
function removeAttrRow(group: DraftAttrGroup, index: number): void {
|
||||
group.attrs.splice(index, 1)
|
||||
}
|
||||
|
||||
// ---------------- 取数与保存 ----------------
|
||||
|
||||
async function loadDetail(): Promise<void> {
|
||||
const item = props.item
|
||||
if (!item) return
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
saveError.value = ''
|
||||
try {
|
||||
const [detail, groups] = await Promise.all([
|
||||
fetchJdProductDetail(item.id),
|
||||
fetchJdProductGroups().catch(() => [] as JdProductGroup[]),
|
||||
])
|
||||
groupOptions.value = groups
|
||||
const row = detail.item
|
||||
form.value = {
|
||||
title: row.title,
|
||||
brand: row.brand,
|
||||
categoryPath: row.categoryPath,
|
||||
itemNum: row.itemNum,
|
||||
priceMin: row.priceMin,
|
||||
priceMax: row.priceMax,
|
||||
stockTotal: row.stockTotal === null ? '' : String(row.stockTotal),
|
||||
saleStatus: row.saleStatus,
|
||||
groupId: row.groupId === null ? '' : String(row.groupId),
|
||||
}
|
||||
// 深拷贝草稿:直接改副本,保存前才拼负载。
|
||||
draftAttrGroups.value = detail.attrGroups.map((group: JdProductAttrGroup) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({ ...attr })),
|
||||
}))
|
||||
draftSkus.value = detail.skus.map((sku) => ({ ...sku }))
|
||||
images.value = detail.images
|
||||
deleteImageIds.value = new Set()
|
||||
attrJsonRaw.value = detail.attrJsonRaw
|
||||
} catch (error) {
|
||||
loadFailure.value = requestErrorMessage(error) || '商品详情加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('close')
|
||||
}
|
||||
|
||||
/** 保存:主字段全量 + 有改动的可选块。前端先拦「标题为空」(后端 @NotBlank 同判),失败红条。 */
|
||||
async function save(): Promise<void> {
|
||||
if (!props.item || saving.value) return
|
||||
saveError.value = ''
|
||||
if (!form.value.title.trim()) {
|
||||
saveError.value = '标题不能为空'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
const detail = await updateJdProduct(props.item.id, {
|
||||
title: form.value.title.trim(),
|
||||
brand: form.value.brand.trim() || null,
|
||||
categoryPath: form.value.categoryPath.trim() || null,
|
||||
itemNum: form.value.itemNum.trim() || null,
|
||||
priceMin: form.value.priceMin.trim() || null,
|
||||
priceMax: form.value.priceMax.trim() || null,
|
||||
stockTotal: form.value.stockTotal.trim() === '' ? null : Number(form.value.stockTotal),
|
||||
saleStatus: form.value.saleStatus.trim() || null,
|
||||
groupId: form.value.groupId === '' ? null : Number(form.value.groupId),
|
||||
// 属性块:原文兜底行(解析失败)不提交,防保存把解析不出的原文形状弄丢。
|
||||
attrGroups: attrJsonRaw.value
|
||||
? null
|
||||
: draftAttrGroups.value.map((group) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({
|
||||
key: attr.key,
|
||||
label: attr.label,
|
||||
value: attr.value,
|
||||
})),
|
||||
})),
|
||||
skus: draftSkus.value.length
|
||||
? draftSkus.value.map((sku) => ({
|
||||
skuId: sku.skuId,
|
||||
price: sku.price || null,
|
||||
stock: sku.stock,
|
||||
}))
|
||||
: null,
|
||||
deleteImageIds: deleteImageIds.value.size ? [...deleteImageIds.value] : null,
|
||||
})
|
||||
// 保存成功:用返回的刷新详情直接回填(图片行集已扣掉删掉的行、计数已刷新)。
|
||||
form.value.title = detail.item.title
|
||||
form.value.brand = detail.item.brand
|
||||
form.value.categoryPath = detail.item.categoryPath
|
||||
form.value.itemNum = detail.item.itemNum
|
||||
form.value.priceMin = detail.item.priceMin
|
||||
form.value.priceMax = detail.item.priceMax
|
||||
form.value.stockTotal = detail.item.stockTotal === null ? '' : String(detail.item.stockTotal)
|
||||
form.value.saleStatus = detail.item.saleStatus
|
||||
form.value.groupId = detail.item.groupId === null ? '' : String(detail.item.groupId)
|
||||
draftAttrGroups.value = detail.attrGroups.map((group) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({ ...attr })),
|
||||
}))
|
||||
draftSkus.value = detail.skus.map((sku) => ({ ...sku }))
|
||||
images.value = detail.images
|
||||
deleteImageIds.value = new Set()
|
||||
showAdminFeedback('已保存,该商品已转为人工维护(采集不再覆盖)', 'success')
|
||||
emit('saved')
|
||||
} catch (error) {
|
||||
saveError.value = requestErrorMessage(error) || '保存失败,请稍后重试'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.item?.id] as const,
|
||||
([visible]) => {
|
||||
if (visible && props.item) void loadDetail()
|
||||
},
|
||||
)
|
||||
|
||||
function dash(value: string | number | null | undefined): string {
|
||||
const text = value === null || value === undefined ? '' : String(value).trim()
|
||||
return text || '-'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="drawer-mask" @click.self="close">
|
||||
<aside class="drawer">
|
||||
<header class="drawer-head">
|
||||
<h3>编辑商品{{ item?.productCode ? ` · ${item.productCode}` : '' }}</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="close">×</button>
|
||||
</header>
|
||||
|
||||
<div class="drawer-body">
|
||||
<div v-if="loadFailure" class="drawer-failure">
|
||||
<span>{{ loadFailure }}</span>
|
||||
<button class="btn btn-secondary" type="button" @click="loadDetail">重试</button>
|
||||
</div>
|
||||
<p v-else-if="loading" class="drawer-tip">加载中...</p>
|
||||
|
||||
<template v-else>
|
||||
<section class="detail-block">
|
||||
<h4>基本信息</h4>
|
||||
<div class="edit-grid">
|
||||
<div class="edit-item edit-item-wide">
|
||||
<label>标题</label>
|
||||
<input v-model="form.title" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>品牌</label>
|
||||
<input v-model="form.brand" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>类目</label>
|
||||
<input v-model="form.categoryPath" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>货号(系统生成=行号,可改)</label>
|
||||
<input v-model="form.itemNum" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>状态</label>
|
||||
<input v-model="form.saleStatus" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>价格下限</label>
|
||||
<input v-model="form.priceMin" type="text" inputmode="decimal" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>价格上限</label>
|
||||
<input v-model="form.priceMax" type="text" inputmode="decimal" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>总库存</label>
|
||||
<input v-model="form.stockTotal" type="text" inputmode="numeric" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>分类</label>
|
||||
<select v-model="form.groupId">
|
||||
<option value="">未分类</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">
|
||||
{{ group.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>商品编码(只读)</label>
|
||||
<input type="text" :value="dash(item?.productCode)" readonly class="readonly" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>信息分(只读)</label>
|
||||
<input type="text" :value="dash(item?.healthScore)" readonly class="readonly" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="draftAttrGroups.length" class="detail-block">
|
||||
<h4>属性与设置(键值可改,行可删)</h4>
|
||||
<div v-for="group in draftAttrGroups" :key="group.groupName" class="attr-group">
|
||||
<h5>{{ group.groupName }}</h5>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr v-for="(attr, index) in group.attrs" :key="`${attr.key}-${index}`">
|
||||
<th>{{ attr.label || attr.key || '-' }}</th>
|
||||
<td><input v-model="attr.value" type="text" class="attr-input" /></td>
|
||||
<td class="attr-remove-cell">
|
||||
<button class="attr-remove" type="button" title="删除该属性行" @click="removeAttrRow(group, index)">删</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<p v-else-if="attrJsonRaw" class="drawer-tip">属性原文解析失败(原始 JSON 兜底),属性区不可编辑以防丢失原文;可照常改基本信息。</p>
|
||||
<p v-else class="drawer-tip">暂无属性</p>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>SKU 矩阵(京东价 / 库存可改)</h4>
|
||||
<template v-if="draftSkus.length">
|
||||
<div class="sku-table-wrap">
|
||||
<table class="sku-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="dimension in skuDimensions" :key="dimension">{{ dimension }}</th>
|
||||
<th>京东价</th>
|
||||
<th>库存</th>
|
||||
<th>SKU ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="sku in draftSkus" :key="sku.skuId">
|
||||
<td v-for="dimension in skuDimensions" :key="dimension">{{ skuAttrValue(sku, dimension) }}</td>
|
||||
<td><input v-model="sku.price" type="text" inputmode="decimal" class="sku-input" /></td>
|
||||
<td>
|
||||
<input
|
||||
:value="sku.stock === null ? '' : String(sku.stock)"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
class="sku-input"
|
||||
@input="sku.stock = ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
</td>
|
||||
<td class="sku-id">{{ sku.skuId }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else class="drawer-tip">暂无 SKU 矩阵(V198 之前采集的旧行需重新采集)</p>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>图片(点「删图」标记,保存时一并删除;上传/替换暂未开放)</h4>
|
||||
<div v-if="images.length" class="image-grid">
|
||||
<div
|
||||
v-for="image in images"
|
||||
:key="`${image.id}-${image.url}`"
|
||||
class="image-cell"
|
||||
:class="{ marked: deleteImageIds.has(image.id) }"
|
||||
>
|
||||
<img :src="image.url" alt="" loading="lazy" />
|
||||
<button class="image-del" type="button" @click="toggleDeleteImage(image)">
|
||||
{{ deleteImageIds.has(image.id) ? '撤销' : '删图' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无图片</p>
|
||||
<p v-if="deletedCount" class="delete-count">已标记删除 {{ deletedCount }} 张,保存后剩余 {{ remainingImageCount }} 张</p>
|
||||
</section>
|
||||
|
||||
<div v-if="saveError" class="drawer-failure">{{ saveError }}</div>
|
||||
<p class="save-hint">保存后该商品转为人工维护,后续采集不再覆盖它的数据(含本单重爬);删除的图片文件一并从存储桶清理(共用的保留)。</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer class="drawer-foot">
|
||||
<button class="btn btn-secondary" type="button" :disabled="saving" @click="close">取消</button>
|
||||
<button class="btn" type="button" :disabled="saving || loading" @click="save">
|
||||
{{ saving ? '保存中...' : '保存' }}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2600;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.drawer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(920px, 100%);
|
||||
height: 100%;
|
||||
background: #ffffff;
|
||||
box-shadow: -18px 0 40px rgba(39, 67, 94, 0.18);
|
||||
}
|
||||
.drawer-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #dbe5ee;
|
||||
}
|
||||
.drawer-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-close {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #5b6f83;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.drawer-close:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px 20px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.drawer-foot {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
padding: 14px 20px;
|
||||
border-top: 1px solid #dbe5ee;
|
||||
background: #f8fbfd;
|
||||
}
|
||||
.drawer-tip {
|
||||
margin: 0;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.drawer-failure {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.detail-block h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
color: #4e6479;
|
||||
}
|
||||
.edit-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px 16px;
|
||||
}
|
||||
.edit-item {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
.edit-item-wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.edit-item label {
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
}
|
||||
.edit-item input,
|
||||
.edit-item select {
|
||||
min-width: 0;
|
||||
min-height: 36px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.edit-item input:focus,
|
||||
.edit-item select:focus {
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.edit-item input.readonly {
|
||||
background: #f2f7fb;
|
||||
color: #5b6f83;
|
||||
}
|
||||
.attr-group {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.attr-group h5 {
|
||||
margin: 0 0 6px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.attr-group table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.attr-group th,
|
||||
.attr-group td {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.attr-group th {
|
||||
width: 180px;
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.attr-group tr:last-child th,
|
||||
.attr-group tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.attr-input {
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 7px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.attr-input:focus {
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.attr-remove-cell {
|
||||
width: 44px;
|
||||
text-align: center;
|
||||
}
|
||||
.attr-remove {
|
||||
border: 1px solid #e4b3a8;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: #a04432;
|
||||
font-size: 12px;
|
||||
padding: 3px 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.attr-remove:hover {
|
||||
background: #fdf1ef;
|
||||
}
|
||||
.sku-table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.sku-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sku-table th,
|
||||
.sku-table td {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
text-align: left;
|
||||
color: #24384d;
|
||||
}
|
||||
.sku-table th {
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sku-table tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.sku-input {
|
||||
width: 110px;
|
||||
min-height: 32px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 7px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.sku-input:focus {
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.sku-id {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
color: #4e6479;
|
||||
}
|
||||
.image-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.image-cell {
|
||||
position: relative;
|
||||
}
|
||||
.image-cell img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 8px;
|
||||
background: #f2f7fb;
|
||||
}
|
||||
.image-cell.marked img {
|
||||
opacity: 0.35;
|
||||
outline: 2px solid #d08a7b;
|
||||
}
|
||||
.image-del {
|
||||
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;
|
||||
cursor: pointer;
|
||||
}
|
||||
.image-del:hover {
|
||||
background: #fdf1ef;
|
||||
}
|
||||
.image-cell.marked .image-del {
|
||||
border-color: #95b1cb;
|
||||
color: #5b6f83;
|
||||
}
|
||||
.delete-count {
|
||||
margin: 10px 0 0;
|
||||
color: #a04432;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.save-hint {
|
||||
margin: 0;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #cfe3f5;
|
||||
border-radius: 10px;
|
||||
background: #eef5fc;
|
||||
color: #3b6d99;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 9px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border: 1px solid #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn:not(.btn-secondary) {
|
||||
border: 1px solid #4f78a5;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
}
|
||||
.btn:not(.btn-secondary):hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品分组管理弹窗(v1.4 Phase 5):新建/改名/删除,重名等业务失败把后端返回的中文文案
|
||||
* 原样展示在弹窗内(envelope code 非 0 → errorTextOf);删除前 openAdminConfirm 二次确认;
|
||||
* 变更成功后 emit('changed'),由页面刷新分组下拉与列表。 */
|
||||
/** 京东商品「店铺分类」弹窗(2026-11-15 由「分组管理」小弹窗重做):左右分栏——左栏分类管理
|
||||
* (新建/改名/删除;分组全平台一份、措辞「分类」),右栏商品人工归类(独立件
|
||||
* JdProductAssignPane:范围切换+搜索+勾选 →「归入所选分类」/「移出分类」,批量端点
|
||||
* batch-assign-group 与单行编辑同口径置 manual_locked=1——归类即人工干预,采集不再覆盖/
|
||||
* 清理该行)。左栏点亮的分类=右栏归类目标;目标被删时右栏自动拉回全量页签。
|
||||
* 重名等业务失败把后端返回的中文文案原样展示在弹窗内(envelope code 非 0 → errorTextOf);
|
||||
* 删除分类前 openAdminConfirm 二次确认;变更成功后 emit('changed'),由页面刷新分组下拉与
|
||||
* 列表。弹窗壳 v-if 整树重建 ⇒ 每次打开即两个面板都重新拉数据,无需手动重置。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
createJdProductGroup,
|
||||
@@ -10,16 +15,18 @@ import {
|
||||
updateJdProductGroup,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import JdProductAssignPane from './JdProductAssignPane.vue'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
companyId: number | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed'): void }>()
|
||||
|
||||
// ---------------- 左栏:分类管理(分组全平台一份,界面措辞「分类」) ----------------
|
||||
|
||||
const loading = ref(false)
|
||||
const errorText = ref('')
|
||||
const groups = ref<JdProductGroup[]>([])
|
||||
@@ -27,20 +34,23 @@ const groups = ref<JdProductGroup[]>([])
|
||||
const createName = ref('')
|
||||
const createSortOrder = ref(0)
|
||||
const creating = ref(false)
|
||||
/** 改名:正在编辑的分组 id 与草稿名。 */
|
||||
/** 改名:正在编辑的分类 id 与草稿名。 */
|
||||
const editingId = ref(0)
|
||||
const editingName = ref('')
|
||||
const saving = ref(false)
|
||||
/** 左侧点亮的分类=右栏「归入所选分类」的归类目标;删除后自动清掉。 */
|
||||
const selectedGroupId = ref(0)
|
||||
|
||||
const canCreate = computed(() => createName.value.trim().length > 0 && !creating.value && !saving.value)
|
||||
const selectedGroup = computed(() => groups.value.find((group) => group.id === selectedGroupId.value) || null)
|
||||
|
||||
async function loadGroups(): Promise<void> {
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
groups.value = await fetchJdProductGroups(props.companyId)
|
||||
groups.value = await fetchJdProductGroups()
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '分组列表加载失败'
|
||||
errorText.value = requestErrorMessage(error) || '分类列表加载失败'
|
||||
groups.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -51,19 +61,24 @@ function sortGroups(list: JdProductGroup[]): JdProductGroup[] {
|
||||
return [...list].sort((a, b) => a.sortOrder - b.sortOrder || a.id - b.id)
|
||||
}
|
||||
|
||||
/** 变更后统一收口:刷新左栏商品数徽标+上抛页面(分组下拉与行集都依赖它)。 */
|
||||
async function refreshAfterChange(): Promise<void> {
|
||||
groups.value = sortGroups(await fetchJdProductGroups())
|
||||
emit('changed')
|
||||
}
|
||||
|
||||
async function submitCreate(): Promise<void> {
|
||||
const name = createName.value.trim()
|
||||
if (!name || creating.value) return
|
||||
creating.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await createJdProductGroup({ name, sortOrder: Math.floor(createSortOrder.value) || 0 }, props.companyId)
|
||||
await createJdProductGroup({ name, sortOrder: Math.floor(createSortOrder.value) || 0 })
|
||||
createName.value = ''
|
||||
createSortOrder.value = 0
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
await refreshAfterChange()
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '新建分组失败'
|
||||
errorText.value = requestErrorMessage(error) || '新建分类失败'
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
@@ -86,10 +101,9 @@ async function submitRename(group: JdProductGroup): Promise<void> {
|
||||
saving.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await updateJdProductGroup(group.id, { name, sortOrder: group.sortOrder }, props.companyId)
|
||||
await updateJdProductGroup(group.id, { name, sortOrder: group.sortOrder })
|
||||
cancelRename()
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
await refreshAfterChange()
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '改名失败'
|
||||
} finally {
|
||||
@@ -98,21 +112,31 @@ async function submitRename(group: JdProductGroup): Promise<void> {
|
||||
}
|
||||
|
||||
async function removeGroup(group: JdProductGroup): Promise<void> {
|
||||
const ok = await openAdminConfirm({ title: '删除分组', message: `确定删除分组「${group.name}」吗?删除后该组商品回到未分组。`, confirmText: '确认删除', danger: true })
|
||||
const ok = await openAdminConfirm({ title: '删除分类', message: `确定删除分类「${group.name}」吗?删除后该分类下 ${group.productCount} 个商品回到未分类。`, confirmText: '确认删除', danger: true })
|
||||
if (!ok || saving.value) return
|
||||
saving.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await deleteJdProductGroup(group.id, props.companyId)
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
await deleteJdProductGroup(group.id)
|
||||
// 删掉的是当前归类目标:清点亮,右栏自己会拉回全量页签(watch selectedGroup)。
|
||||
if (selectedGroupId.value === group.id) {
|
||||
selectedGroupId.value = 0
|
||||
}
|
||||
await refreshAfterChange()
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '删除分组失败'
|
||||
errorText.value = requestErrorMessage(error) || '删除分类失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧点亮分类=归类目标(右栏「当前分类」页签随点亮对象换行集)。 */
|
||||
function pickGroup(group: JdProductGroup): void {
|
||||
if (saving.value) return
|
||||
selectedGroupId.value = group.id
|
||||
}
|
||||
|
||||
// 打开即拉一次分类列表;右栏行集由 JdProductAssignPane 挂载时自取。
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
@@ -120,54 +144,81 @@ watch(
|
||||
cancelRename()
|
||||
createName.value = ''
|
||||
createSortOrder.value = 0
|
||||
errorText.value = ''
|
||||
selectedGroupId.value = 0
|
||||
void loadGroups()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/** 右栏归类成功:分类商品数变化+页面行集的 groupName 都要刷。 */
|
||||
function onPaneChanged(): void {
|
||||
void refreshAfterChange()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
|
||||
<div class="group-modal">
|
||||
<div class="modal-head">
|
||||
<h3>分组管理</h3>
|
||||
<h3>店铺分类</h3>
|
||||
<button class="modal-close" type="button" aria-label="关闭" @click="emit('close')">×</button>
|
||||
</div>
|
||||
|
||||
<div class="group-create">
|
||||
<input
|
||||
v-model="createName"
|
||||
type="text"
|
||||
placeholder="输入新分组名称"
|
||||
@keyup.enter="submitCreate"
|
||||
/>
|
||||
<input v-model.number="createSortOrder" type="number" class="sort-input" aria-label="排序" />
|
||||
<button class="btn" type="button" :disabled="!canCreate" @click="submitCreate">
|
||||
{{ creating ? '新建中...' : '新建分组' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="modal-tip">
|
||||
左侧管理分类并点选目标分类;右侧勾选商品后「归入所选分类」或「移出分类」。
|
||||
人工归类过的商品不再被采集自动覆盖(价格/库存等字段停更)。
|
||||
</p>
|
||||
<p v-if="errorText" class="group-error">{{ errorText }}</p>
|
||||
<p v-else-if="loading" class="group-tip">加载中...</p>
|
||||
|
||||
<ul class="group-list">
|
||||
<li v-for="group in groups" :key="group.id" class="group-row">
|
||||
<template v-if="editingId === group.id">
|
||||
<input v-model="editingName" type="text" @keyup.enter="submitRename(group)" />
|
||||
<button class="btn btn-small" type="button" :disabled="saving" @click="submitRename(group)">保存</button>
|
||||
<button class="btn btn-secondary btn-small" type="button" @click="cancelRename">取消</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="group-name" :title="group.name">{{ group.name }}</span>
|
||||
<span class="group-meta">排序 {{ group.sortOrder }} · {{ group.productCount }} 个商品</span>
|
||||
<span class="group-actions">
|
||||
<button class="btn btn-secondary btn-small" type="button" @click="startRename(group)">改名</button>
|
||||
<button class="btn btn-danger btn-small" type="button" :disabled="saving" @click="removeGroup(group)">删除</button>
|
||||
</span>
|
||||
</template>
|
||||
</li>
|
||||
<li v-if="!loading && !groups.length && !errorText" class="group-tip">暂无分组,先新建一个</li>
|
||||
</ul>
|
||||
<div class="split-body">
|
||||
<!-- 左栏:分类管理 -->
|
||||
<aside class="left-pane">
|
||||
<div class="group-create">
|
||||
<input
|
||||
v-model="createName"
|
||||
type="text"
|
||||
placeholder="输入新分类名称"
|
||||
@keyup.enter="submitCreate"
|
||||
/>
|
||||
<div class="group-create-row">
|
||||
<input v-model.number="createSortOrder" type="number" class="sort-input" aria-label="排序" />
|
||||
<button class="btn" type="button" :disabled="!canCreate" @click="submitCreate">
|
||||
{{ creating ? '新建中...' : '新建分类' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="loading" class="pane-tip">加载中...</p>
|
||||
<ul class="group-list">
|
||||
<li
|
||||
v-for="group in groups"
|
||||
:key="group.id"
|
||||
class="group-row"
|
||||
:class="{ active: selectedGroupId === group.id }"
|
||||
@click="pickGroup(group)"
|
||||
>
|
||||
<template v-if="editingId === group.id">
|
||||
<input v-model="editingName" type="text" @keyup.enter="submitRename(group)" />
|
||||
<span class="group-actions" @click.stop>
|
||||
<button class="btn btn-mini" type="button" :disabled="saving" @click="submitRename(group)">保存</button>
|
||||
<button class="btn btn-secondary btn-mini" type="button" @click="cancelRename">取消</button>
|
||||
</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="group-name" :title="group.name">{{ group.name }}</span>
|
||||
<span class="group-meta">{{ group.productCount }}</span>
|
||||
<span class="group-actions" @click.stop>
|
||||
<button class="btn btn-secondary btn-mini" type="button" @click="startRename(group)">改名</button>
|
||||
<button class="btn btn-danger btn-mini" type="button" :disabled="saving" @click="removeGroup(group)">删除</button>
|
||||
</span>
|
||||
</template>
|
||||
</li>
|
||||
<li v-if="!loading && !groups.length && !errorText" class="pane-tip">暂无分类,先新建一个</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<!-- 右栏:商品人工归类(独立件,行集/勾选/批量归类都在那里) -->
|
||||
<JdProductAssignPane :selected-group="selectedGroup" @changed="onPaneChanged" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -187,9 +238,9 @@ watch(
|
||||
.group-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(560px, 100%);
|
||||
max-height: 84vh;
|
||||
padding: 18px 20px;
|
||||
width: min(1080px, 100%);
|
||||
max-height: 86vh;
|
||||
padding: 18px 20px 20px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
@@ -222,16 +273,46 @@ watch(
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.modal-tip {
|
||||
margin: 8px 0 10px;
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.group-error {
|
||||
margin: 0 0 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
}
|
||||
.split-body {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
/* 左栏(分类管理):固定宽,独立滚动。 */
|
||||
.left-pane {
|
||||
flex: 0 0 248px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid #e7eef5;
|
||||
padding-right: 14px;
|
||||
}
|
||||
.group-create {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin: 14px 0 10px;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.group-create input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 38px;
|
||||
padding: 7px 12px;
|
||||
min-height: 36px;
|
||||
padding: 6px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
@@ -244,22 +325,12 @@ watch(
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.group-create-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.sort-input {
|
||||
flex: 0 0 88px !important;
|
||||
}
|
||||
.group-error {
|
||||
margin: 0 0 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
}
|
||||
.group-tip {
|
||||
margin: 0 0 8px;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
flex: 0 0 72px !important;
|
||||
}
|
||||
.group-list {
|
||||
flex: 1;
|
||||
@@ -273,16 +344,25 @@ watch(
|
||||
.group-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 4px;
|
||||
gap: 8px;
|
||||
padding: 8px 6px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.group-row:hover {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
/* 左侧点亮=归类目标:右侧「归入所选分类」就落在这一行。 */
|
||||
.group-row.active {
|
||||
background: #e8f1fa;
|
||||
box-shadow: inset 3px 0 0 #4f78a5;
|
||||
}
|
||||
.group-row input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 34px;
|
||||
padding: 5px 10px;
|
||||
min-height: 32px;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
font-size: 13.5px;
|
||||
@@ -298,14 +378,24 @@ watch(
|
||||
}
|
||||
.group-meta {
|
||||
flex: none;
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
min-width: 22px;
|
||||
padding: 1px 7px;
|
||||
border-radius: 9px;
|
||||
background: #eef4fa;
|
||||
color: #4e6479;
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.group-actions {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
.pane-tip {
|
||||
margin: 10px 2px;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
@@ -325,10 +415,10 @@ watch(
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-small {
|
||||
min-height: 32px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12.5px;
|
||||
.btn-mini {
|
||||
min-height: 28px;
|
||||
padding: 3px 9px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/** 京东数据库查询适配(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 护栏钉住。 */
|
||||
* 公司口径(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」):公共库只有两个
|
||||
* 公司维度出口——只读列表与类目下拉把公司 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,8 +28,9 @@ export async function fetchJdProductList(
|
||||
shopName: params.shopName ?? '',
|
||||
productCode: params.productCode ?? '',
|
||||
titleKeyword: params.titleKeyword ?? '',
|
||||
saleStatus: params.saleStatus ?? '',
|
||||
category: params.category ?? '',
|
||||
groupId: params.groupId ?? '',
|
||||
groupScope: params.groupScope ?? '',
|
||||
syncedFrom: params.syncedFrom ?? '',
|
||||
syncedTo: params.syncedTo ?? '',
|
||||
},
|
||||
@@ -37,78 +38,21 @@ export async function fetchJdProductList(
|
||||
params.pageSize,
|
||||
)
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
// 未分类范围(店铺分类弹窗「未分类」页签):与 company_id 一样由发送口直传,构造器不认识它。
|
||||
if (params.ungrouped) query.ungrouped = true
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
|
||||
return parseJdProductPage(data)
|
||||
}
|
||||
|
||||
/** 详情:GET /api/admin/jd-products/{id}(信封 data=主字段 + attrGroups + attrJsonRaw + images)。 */
|
||||
/** 详情:GET /api/admin/jd-products/{id}(信封 data=主字段 + attrGroups + attrJsonRaw + images)。
|
||||
* 公共库无公司维度,按 id 直取。 */
|
||||
export async function fetchJdProductDetail(
|
||||
id: number,
|
||||
companyId: number | null,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, { params: query })
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`)
|
||||
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<JdProductExportResult> {
|
||||
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<Blob>(`${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
|
||||
@@ -118,23 +62,49 @@ export interface JdProductDeleteResult {
|
||||
objectsSkipped: number
|
||||
}
|
||||
|
||||
/** 删除是先删桶、全成功才删库行(后端 JdProductDeleteService);失败文案原样抛给页面。 */
|
||||
/** 删除是先删桶、全成功才删库行(后端 JdProductDeleteService);失败文案原样抛给页面。
|
||||
* 公共库写侧无公司维度(2026-11-15 用户定案)。 */
|
||||
export async function deleteJdProducts(
|
||||
ids: number[],
|
||||
companyId: number | null,
|
||||
): Promise<JdProductDeleteResult> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
if (ids.length === 1) {
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_ENDPOINT}/${ids[0]}`, { params: query })
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_ENDPOINT}/${ids[0]}`)
|
||||
return unwrap<JdProductDeleteResult>(data)
|
||||
}
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-delete`, { ids }, { params: query })
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-delete`, { ids })
|
||||
return unwrap<JdProductDeleteResult>(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):主字段保存即置人工编辑锁(V199 manual_locked=1,后续采集不再覆盖该行);
|
||||
* 失败文案原样抛给抽屉红条。公共库写侧无公司维度。返回刷新后的详情(与
|
||||
* fetchJdProductDetail 同一信封),抽屉用它回填。 */
|
||||
export async function updateJdProduct(
|
||||
id: number,
|
||||
payload: JdProductUpdatePayload,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const { data } = await http.put<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, payload)
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
/** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */export interface JdProductGroup {
|
||||
id: number
|
||||
name: string
|
||||
sortOrder: number
|
||||
@@ -161,11 +131,10 @@ function numberOr(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
}
|
||||
|
||||
/** 分组下拉/管理列表;失败由页面自己兜(分组只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(companyId: number | null): Promise<JdProductGroup[]> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT, { params: query })
|
||||
/** 分组下拉/管理列表(分组 2026-11-15 起全平台一份,不带公司维度);失败由页面自己兜
|
||||
* (分组只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(): Promise<JdProductGroup[]> {
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT)
|
||||
const core = unwrap<unknown>(data)
|
||||
if (!Array.isArray(core)) return []
|
||||
const out: JdProductGroup[] = []
|
||||
@@ -184,13 +153,37 @@ export async function fetchJdProductGroups(companyId: number | null): Promise<Jd
|
||||
return out
|
||||
}
|
||||
|
||||
/** 新建分组;重名等业务失败把后端中文文案抛回(页面直接展示)。 */
|
||||
/** 类目下拉选项(GET /categories 返回 [{name, productCount}],name=京麦末级类目即
|
||||
* 落库的 category_path;等值过滤)。失败由页面自己兜(类目只是筛选项,不拦首屏行集)。 */
|
||||
export interface JdProductCategoryOption {
|
||||
name: string
|
||||
productCount: number
|
||||
}
|
||||
|
||||
export async function fetchJdProductCategories(
|
||||
companyId: number | null,
|
||||
): Promise<JdProductCategoryOption[]> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/categories`, { params: query })
|
||||
const core = unwrap<unknown>(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<string, unknown>
|
||||
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,
|
||||
companyId: number | null,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (companyId != null) body.company_id = companyId
|
||||
const { data } = await http.post<unknown>(JD_PRODUCT_GROUP_ENDPOINT, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
@@ -199,18 +192,27 @@ export async function createJdProductGroup(
|
||||
export async function updateJdProductGroup(
|
||||
id: number,
|
||||
payload: JdProductGroupPayload,
|
||||
companyId: number | null,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (companyId != null) body.company_id = companyId
|
||||
const { data } = await http.put<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
|
||||
/** 删除分组;业务失败文案同上。 */
|
||||
export async function deleteJdProductGroup(id: number, companyId: number | null): Promise<void> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`, { params: query })
|
||||
export async function deleteJdProductGroup(id: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`)
|
||||
groupDataOf<unknown>(data)
|
||||
}
|
||||
|
||||
/** 批量人工归类(店铺分类弹窗,2026-11-15):勾选商品行 → 归入指定分类或移出分类。
|
||||
* groupId 传 null=移出分类(后端把 group_id 置 NULL);返回实际更新的行数。
|
||||
* 后端与单行编辑同口径置 manual_locked=1(归类即人工干预,采集不再覆盖/清理该行)。
|
||||
* 业务失败(分类不存在等)把中文文案抛回,弹窗红条原样展示。公共库写侧无公司维度。 */
|
||||
export async function batchAssignJdProductGroup(
|
||||
ids: number[],
|
||||
groupId: number | null,
|
||||
): Promise<number> {
|
||||
const body: Record<string, unknown> = { ids, groupId }
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-assign-group`, body)
|
||||
return groupDataOf<number>(data)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
/** 京东数据库页筛选纯函数(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`、`grouped`(只看已分类,2026-11-15 客户口径「查询已分类的跟未分类,分类好的
|
||||
* 可以不显示」增)、`ungrouped`(只看未分类,页面「分类状态」档与店铺分类弹窗共用)、
|
||||
* `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 +20,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,10 +27,13 @@ export interface JdProductFilterState {
|
||||
productCode: string
|
||||
/** 标题关键字,空串不限。 */
|
||||
titleKeyword: string
|
||||
/** 商品状态:上架中/已下架/审核中/草稿,空串=全部。 */
|
||||
saleStatus: string
|
||||
/** 类目(京麦末级类目名,等值过滤;选项来自 GET /categories),空串=全部类目。 */
|
||||
category: string
|
||||
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
|
||||
groupId: string
|
||||
/** 分类状态(2026-11-15 客户口径「查询已分类的跟未分类」):''=全部、
|
||||
* 'grouped'=只看已分类(group_id 非空)、'ungrouped'=只看未分类(group_id 为空)。 */
|
||||
groupScope: '' | 'grouped' | 'ungrouped'
|
||||
/** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
syncedFrom: string
|
||||
/** 同步结束日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
@@ -37,7 +41,7 @@ export interface JdProductFilterState {
|
||||
}
|
||||
|
||||
export function createJdProductFilterState(): JdProductFilterState {
|
||||
return { shopName: '', productCode: '', titleKeyword: '', saleStatus: '', groupId: '', syncedFrom: '', syncedTo: '' }
|
||||
return { shopName: '', productCode: '', titleKeyword: '', category: '', groupId: '', groupScope: '', syncedFrom: '', syncedTo: '' }
|
||||
}
|
||||
|
||||
/** 是否有任一激活筛选条件。 */
|
||||
@@ -45,8 +49,9 @@ 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 ((state.groupScope || '').trim()) return true
|
||||
if (validIsoDateOrUndefined(state.syncedFrom) || validIsoDateOrUndefined(state.syncedTo)) return true
|
||||
return false
|
||||
}
|
||||
@@ -58,27 +63,20 @@ export interface JdProductQuery {
|
||||
shop_name?: string
|
||||
product_code?: string
|
||||
title_keyword?: string
|
||||
sale_status?: string
|
||||
/** 京麦末级类目等值过滤(后端 JdProductQueryService.Filter.category)。 */
|
||||
category?: string
|
||||
group_id?: number
|
||||
/** 未分类过滤(店铺分类弹窗「未分类」范围):true=只看 group_id 为空的行。
|
||||
* 同 group_id 一样由 api 发送口下传——构造器不认识它(弹窗的取数不走筛选态)。 */
|
||||
ungrouped?: boolean
|
||||
/** 已分类过滤(页面筛选行「分类状态」=已分类):true=只看 group_id 非空的行。 */
|
||||
grouped?: boolean
|
||||
synced_from?: string
|
||||
synced_to?: string
|
||||
/** 公司 tab:白名单构造不点名它,字段只为 api 发送口的 `query.company_id = params.companyId` 存在。 */
|
||||
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,39 +84,34 @@ export interface JdProductListParams {
|
||||
shopName?: string
|
||||
productCode?: string
|
||||
titleKeyword?: string
|
||||
saleStatus?: string
|
||||
category?: string
|
||||
groupId?: string
|
||||
/** 分类状态档(''=全部 | 'grouped' | 'ungrouped');页面筛选行传,弹窗不传。 */
|
||||
groupScope?: '' | 'grouped' | 'ungrouped'
|
||||
/** 未分类范围(true=只看未分类行);仅店铺分类弹窗右栏传,页面筛选行不用。 */
|
||||
ungrouped?: boolean
|
||||
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<JdProductQuery, 'page' | 'page_size'> {
|
||||
const query: Omit<JdProductQuery, 'page' | 'page_size'> = {}
|
||||
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
|
||||
// 分类状态档:未分类走既有 ungrouped 参数(与店铺分类弹窗同一后端谓词),
|
||||
// 已分类走 grouped;''(全部)不下发。
|
||||
if (state.groupScope === 'ungrouped') query.ungrouped = true
|
||||
if (state.groupScope === 'grouped') query.grouped = true
|
||||
const syncedFrom = validIsoDateOrUndefined(state.syncedFrom)
|
||||
if (syncedFrom) query.synced_from = syncedFrom
|
||||
const syncedTo = validIsoDateOrUndefined(state.syncedTo)
|
||||
@@ -141,8 +134,3 @@ export function toJdProductListParams(
|
||||
...toJdProductFilterQuery(state),
|
||||
}
|
||||
}
|
||||
|
||||
/** 过滤态 → 导出查询参数(无分页;归一规则与列表逐字同源)。 */
|
||||
export function toJdProductExportParams(state: JdProductFilterState): JdProductExportQuery {
|
||||
return toJdProductFilterQuery(state)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -132,11 +132,15 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
|
||||
// 500 够得着自己、够不到隔壁(对平用例逐处从真文件重算,注释过期即红)。
|
||||
{ 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。列表与导出
|
||||
// 共用同一过滤面,塞键行与外观专利逐字同行,但分属不同文件 ⇒ (文件, 整行) 各成一组。
|
||||
{ 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 京东数据库导出(与列表共用同一过滤面)' },
|
||||
// ↓ 批次 8(2026-11-14 v1.4 京东数据库;2026-11-15 公共化改口径):京麦店铺商品采集落库的
|
||||
// 只读镜像,行 company_id 只剩"哪家公司客户端同步的"来源标记。2026-11-15 用户定案
|
||||
// 「京东数据库不区分公司、属于公共的」「分组和亚马逊功能一样」⇒ 详情/编辑/删除/分组管理
|
||||
// 的 6 个 company_id 发送口整批撤下(后端写侧同窗摘掉公司谓词,重上时从 git 历史找回);
|
||||
// 留下的两个公司维度出口=只读列表与类目下拉(仅超管生效=筛选管理员,普通管理员没有
|
||||
// 这个筛选)。导出发送口已随 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 京东数据库只读列表(超管公司 tab 筛选=筛选管理员)' },
|
||||
{ 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 类目下拉(选项集与超管当前 tab 行集同源)' },
|
||||
]
|
||||
|
||||
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
|
||||
@@ -260,7 +264,7 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
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 +364,11 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
|
||||
// ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 7 + 批次 3 的 4 + 批次 4 的 1 + 批次 5 的 1 + 批次 6 的 3;
|
||||
// 批次 2 原 12 条里的品牌库 1 条 + 商品类目 4 条随 2026-10-06「这两页退回全平台共享」摘掉)。
|
||||
// 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
|
||||
// 2026-11-15 京东数据库公共化(用户定案「不区分公司、属于公共的」):批次 8 的详情/删除/
|
||||
// 分组列表/删分组/编辑 5 条 company_id 发送口随公司谓词整批撤下(后端写侧同窗摘),批次 8
|
||||
// 只剩列表/类目两条(超管筛选管理员)⇒ 32 → 27。
|
||||
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 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 + 批次 8 v1.4 京东数据库列表/类目 2 条(详情/删除/分组/删分组/编辑 5 口随 2026-11-15 公共化撤、导出口随客户口径下线)= 27 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
for (const p of SEND_POINTS) {
|
||||
const shape = pointShape(p)
|
||||
const compliant = pointCompliant(p)
|
||||
@@ -393,8 +400,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 +757,15 @@ 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 京东数据库;2026-11-15 公共化改口径):店铺/商品编码/标题是
|
||||
// 按行集筛的自由文本,类目选项集与超管当前 tab 的行集同源 ⇒ 上一家的筛选值与 category
|
||||
// 在新一家的行集/选项集里不存在,切 tab 必清且类目选项重取;页码回 1 同外观专利页。
|
||||
// 分组 2026-11-15 起全平台一份(公共),groupId 与公司维度正交——不清、选项也不随 tab 重取。
|
||||
{
|
||||
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.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadCategoryOptions(); void load()",
|
||||
why: '店铺/商品编码/标题是按行集筛的自由文本,上一家的值在新一家的行里不存在 ⇒ 切 tab 后首屏被筛成「暂无商品」,'
|
||||
+ '而输入框还显示着上一家填的值;分组选项集是公司隔离的,上一家选的 groupId 在新一家的选项里不存在,'
|
||||
+ '而输入框还显示着上一家填的值;类目选项集与超管当前 tab 的行集同源,上一家选的 category 在新一家的选项里不存在,'
|
||||
+ '同罪必清且选项重取;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据',
|
||||
premise: [
|
||||
{ file: 'src/pages/jd/jd-product-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
|
||||
|
||||
@@ -60,3 +60,36 @@ 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, '选中类目算激活筛选')
|
||||
})
|
||||
|
||||
/** 分类状态筛选(2026-11-15 客户口径「查询已分类的跟未分类,分类好的可以不显示」):
|
||||
* 全部不下发、已分类下发 grouped、未分类下发 ungrouped(与店铺分类弹窗同一后端谓词)。 */
|
||||
test('分类状态筛选参数序列化:全部不下发、已分类 grouped、未分类 ungrouped', async () => {
|
||||
const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } =
|
||||
await import('../src/pages/jd/jd-product-filter.ts')
|
||||
const empty = createJdProductFilterState()
|
||||
assert.equal('grouped' in toJdProductListParams(empty, 1, 20), false, '全部不下发 grouped')
|
||||
assert.equal('ungrouped' in toJdProductListParams(empty, 1, 20), false, '全部不下发 ungrouped')
|
||||
|
||||
const grouped = { ...empty, groupScope: 'grouped' as const }
|
||||
assert.equal(toJdProductListParams(grouped, 1, 20).grouped, true, '已分类档下发 grouped=true')
|
||||
assert.equal('ungrouped' in toJdProductListParams(grouped, 1, 20), false, '已分类档不下发 ungrouped')
|
||||
assert.equal(jdProductFilterActive(grouped), true, '选中已分类算激活筛选')
|
||||
|
||||
const ungrouped = { ...empty, groupScope: 'ungrouped' as const }
|
||||
assert.equal(toJdProductListParams(ungrouped, 1, 20).ungrouped, true, '未分类档下发 ungrouped=true')
|
||||
assert.equal('grouped' in toJdProductListParams(ungrouped, 1, 20), false, '未分类档不下发 grouped')
|
||||
assert.equal(jdProductFilterActive(ungrouped), true, '选中未分类算激活筛选')
|
||||
})
|
||||
|
||||
@@ -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<keyof typeof exp>) {
|
||||
assert.equal((list as Record<string, unknown>)[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)', () => {
|
||||
|
||||
@@ -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,14 @@ 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(),
|
||||
batchAssignJdProductGroup: vi.fn(),
|
||||
}))
|
||||
|
||||
const confirmMock = vi.hoisted(() => vi.fn())
|
||||
@@ -75,6 +78,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 +102,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 按 id 直删(公共库写侧无公司维度,2026-11-15 公共化)。
|
||||
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])
|
||||
})
|
||||
|
||||
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 自取详情回填(公共库详情无公司维度)。
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(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 })],
|
||||
@@ -148,21 +215,20 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '点复制按钮不冒泡开抽屉')
|
||||
})
|
||||
|
||||
it('分组读不到的那行展示「未分组」(不猜名字)', async () => {
|
||||
it('分类读不到的那行展示「未分类」(不猜名字;2026-11-15「分组管理」改「店铺分类」只换措辞)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[2].text()).toBe('未分组')
|
||||
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 +241,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 () => {
|
||||
@@ -190,11 +256,11 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
{ id: 8, name: '乙组', sortOrder: 1, productCount: 1 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(1)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith()
|
||||
|
||||
const groupSelect = wrapper.find('select')
|
||||
const optionTexts = groupSelect.findAll('option').map((o) => o.text())
|
||||
expect(optionTexts).toContain('全部分组')
|
||||
expect(optionTexts).toContain('全部分类')
|
||||
expect(optionTexts).toContain('甲组')
|
||||
|
||||
const callsBeforeSelect = jdApi.fetchJdProductList.mock.calls.length
|
||||
@@ -204,6 +270,47 @@ 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 = 分组(既有契约不动),第 2 个 = 分类状态(2026-11-15 增),类目下拉第 3
|
||||
const selects = wrapper.findAll('.jd-filter-row select')
|
||||
expect(selects).toHaveLength(3)
|
||||
const categorySelect = selects[2]
|
||||
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 selects = wrapper.findAll('.jd-filter-row select')
|
||||
const scopeSelect = selects[1]
|
||||
const optionTexts = scopeSelect.findAll('option').map((o) => o.text())
|
||||
expect(optionTexts).toEqual(['全部', '已分类', '未分类'])
|
||||
|
||||
// 选「已分类」= 只看 group_id 非空的行(分类好的行想单独看时用这一档)
|
||||
await scopeSelect.setValue('grouped')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupScope: 'grouped', page: 1 })
|
||||
|
||||
// 选「未分类」= 只看 group_id 为空的行(分类好的不显示)
|
||||
await scopeSelect.setValue('ungrouped')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupScope: 'ungrouped', 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,51 +342,14 @@ 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<string, unknown>
|
||||
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 () => {
|
||||
it('点行打开详情抽屉:按 id 取详情(公共库无公司维度),attrGroups 分块渲染', async () => {
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
item: item(1),
|
||||
@@ -298,7 +368,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(true)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1, 1)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('基本信息')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('规格')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('容量')
|
||||
@@ -368,7 +438,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('暂无 SKU 矩阵')
|
||||
})
|
||||
|
||||
it('删除:勾选两行点删除 → 二次确认点名数量与桶清理 → 批量端点带 (ids, companyId),成功后刷新并清勾选', async () => {
|
||||
it('删除:勾选两行点删除 → 二次确认点名数量与桶清理 → 批量端点按 id 直删(公共库无公司维度),成功后刷新并清勾选', async () => {
|
||||
jdApi.deleteJdProducts.mockResolvedValue({ deleted: 2, imagesDeleted: 18, objectsDeleted: 16, objectsKept: 2, objectsSkipped: 0 })
|
||||
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
|
||||
|
||||
@@ -388,7 +458,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(options.danger).toBe(true)
|
||||
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1, 2], 1)
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1, 2])
|
||||
expect(document.body.textContent).toContain('已删除 2 个商品')
|
||||
expect(document.body.textContent).toContain('2 个共用图片保留', '共用对象计数要透出到反馈')
|
||||
// 成功后重取列表并清勾选:工具栏按钮消失。
|
||||
@@ -420,20 +490,25 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('管理分组弹窗:打开即拉分组列表,变更后刷新分组下拉与列表', async () => {
|
||||
it('店铺分类弹窗(原「管理分组」):打开即拉分类列表与右栏商品行集,变更后刷新分类下拉与列表', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '管理分组')!.trigger('click')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '店铺分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.group-modal').exists()).toBe(true)
|
||||
// 打开弹窗 = 拉一次分组列表(第 2 次:首屏已拉过一次)
|
||||
expect(wrapper.find('.group-modal').text()).toContain('店铺分类', '弹窗标题改「店铺分类」')
|
||||
// 打开弹窗 = 拉一次分类列表(第 2 次:首屏已拉过一次;分类全平台一份、不带公司维度)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(1)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith()
|
||||
// 右栏取数复用 fetchJdProductList:不带公司维度(公共库),默认「全部」范围不带 ungrouped=true。
|
||||
const dialogCall = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(dialogCall.companyId).toBeNull()
|
||||
expect(dialogCall.ungrouped).toBe(false)
|
||||
|
||||
// 模拟分组管理里删了一个分组:emit changed → 页面刷新分组下拉与列表(回第一页)
|
||||
// 模拟分类管理里删了一个分类:emit changed → 页面刷新分类下拉与列表(回第一页)
|
||||
wrapper.findComponent(JdProductGroupDialog).vm.$emit('changed')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
@@ -441,7 +516,67 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1, companyId: 1 })
|
||||
})
|
||||
|
||||
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径)', async () => {
|
||||
it('店铺分类弹窗:左侧点亮分类→勾选商品→「归入所选分类」按(ids, 目标分类 id)调批量归类', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([
|
||||
{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 },
|
||||
{ id: 8, name: '乙组', sortOrder: 1, productCount: 0 },
|
||||
])
|
||||
jdApi.fetchJdProductList.mockImplementation(() =>
|
||||
Promise.resolve({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 }))
|
||||
const wrapper = mount(JdProductGroupDialog, { props: { visible: false }, global: { plugins: [pinia] } })
|
||||
await wrapper.setProps({ visible: true })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
// 左侧点亮「甲组」=归类目标;只点亮还没勾选时按钮仍置灰(归入=目标+勾选两者齐备)。
|
||||
const assignBtn = () => wrapper.findAll('button').find((b) => b.text().includes('归入'))
|
||||
expect(assignBtn()!.attributes('disabled')).toBeDefined()
|
||||
await wrapper.findAll('.group-row')[0].trigger('click')
|
||||
await flushPromises()
|
||||
expect(assignBtn()!.attributes('disabled')).toBeDefined()
|
||||
expect(assignBtn()!.text()).toContain('甲组', '按钮点名归类目标')
|
||||
|
||||
// 勾选两行 → 按钮点亮 → 归入「甲组」。
|
||||
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
|
||||
await boxes[0].setValue(true)
|
||||
await boxes[1].setValue(true)
|
||||
expect(assignBtn()!.attributes('disabled')).toBeUndefined()
|
||||
jdApi.batchAssignJdProductGroup.mockResolvedValue(2)
|
||||
await assignBtn()!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1, 2], 7)
|
||||
// 成功后刷新左栏分类数(商品数)与右栏行集,勾选清空。
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalled()
|
||||
expect(wrapper.findAll('tbody input[type="checkbox"]').every((b) => !(b.element as HTMLInputElement).checked).valueOf()).toBe(true)
|
||||
})
|
||||
|
||||
it('店铺分类弹窗:「未分类」页签走 ungrouped=true 取行集;「移出分类」按(ids, null)调批量归类', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
jdApi.fetchJdProductList.mockImplementation(() =>
|
||||
Promise.resolve({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 }))
|
||||
const wrapper = mount(JdProductGroupDialog, { props: { visible: false }, global: { plugins: [pinia] } })
|
||||
await wrapper.setProps({ visible: true })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
const listCallsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
await wrapper.findAll('.scope-tabs button').find((b) => b.text() === '未分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(listCallsBefore + 1, '切「未分类」必须立刻重取')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ungrouped: true, companyId: null })
|
||||
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
jdApi.batchAssignJdProductGroup.mockResolvedValue(1)
|
||||
await wrapper.findAll('button').find((b) => b.text() === '移出分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null)
|
||||
})
|
||||
|
||||
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径;分组公共不清)', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
@@ -459,9 +594,13 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(last.companyId).toBe(2)
|
||||
expect(last.shopName).toBe('', '切公司必须清掉上一家的店铺名')
|
||||
expect(last.titleKeyword).toBe('', '切公司必须清掉上一家的标题关键字')
|
||||
expect(last.groupId).toBe('', '切公司必须清掉上一家选的分组')
|
||||
expect(last.groupId).toBe('7', '分组全平台一份(公共),groupId 与公司维度正交——切 tab 不清')
|
||||
expect(last).not.toHaveProperty('category', '切公司必须清掉上一家选的类目')
|
||||
expect(last.page).toBe(1)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(2)
|
||||
// 分组选项是全局的:切 tab 不重取(首屏那一次之后就不再增长),且任何一次拉取都不带公司维度。
|
||||
for (const call of jdApi.fetchJdProductGroups.mock.calls) {
|
||||
expect(call).toEqual([], '分组选项是全局的,任何一次拉取都不带公司维度')
|
||||
}
|
||||
})
|
||||
|
||||
it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
|
||||
|
||||
+88
-68
@@ -7,13 +7,16 @@ 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.JdProductBatchAssignGroupRequest;
|
||||
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,63 +29,67 @@ 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}(同款鉴权闸)。
|
||||
*
|
||||
* <p>删除是唯一会改数据的动作,语义写在 {@code JdProductDeleteService}:先删 {@code jd-products}
|
||||
* 桶内对象、全成功才删库行(SKU → 图片登记 → 商品行),被其他商品共用的图片对象保留。</p>
|
||||
* <p>写动作两个:删除(语义写在 {@code JdProductDeleteService}:先删 {@code jd-products}
|
||||
* 桶内对象、全成功才删库行(SKU → 图片登记 → 商品行),被其他商品共用的图片对象保留)
|
||||
* 与编辑({@code PUT /{id}},语义写在 {@code JdProductUpdateService}:主字段全量提交+可选块,
|
||||
* 保存即置人工编辑锁 manual_locked=1,采集回传对锁定的行不再覆盖/清理,删除成功另写忽略表)。</p>
|
||||
*
|
||||
* <p>鉴权照外观专利只读页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 →
|
||||
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
|
||||
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。</p>
|
||||
*
|
||||
* <p>公司隔离正门是 {@code readCompanyIdOrOwn}(同外观专利只读页/店铺密钥的表形状:
|
||||
* 归属物化在行 company_id 列、可见集不靠账号/分组)——超管显式传才收窄、不传全量;
|
||||
* 非超管强制本公司(忽略请求传参)。{@code superAdminScopedCompanyId} 对非超管返回 null
|
||||
* =按行 company_id 列查询时把整张表交给每一家(该方法 javadoc 点名的越权形状),不走那道门。</p>
|
||||
* <p><b>公司口径(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」)</b>:行上的
|
||||
* company_id 只剩「哪家公司客户端同步的」来源标记,不再构成可见性边界——读侧全公共;
|
||||
* 唯一保留的公司维度是<b>站点超管</b>的公司 tab 筛选({@code superAdminScopedCompanyId}:
|
||||
* 超管显式传 company_id 才收窄,非超管传什么都不收),也就是「管理员没有这个筛选、
|
||||
* 超管可以筛选管理员」。详情与写侧(编辑/删除)没有公司维度:任何拿到本页菜单权限的
|
||||
* 管理员对全部公共行可编辑可删除(同商品类目「谁都能改」的 2026-10-06 定案形状),
|
||||
* 请求里的 company_id 传参已随公共化从写侧端点摘除。</p>
|
||||
*
|
||||
* <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
|
||||
* {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。DB 列
|
||||
* {@code biz_jd_product.sale_status} 与详情/回传链不动。</p>
|
||||
*/
|
||||
@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;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询京东数据库商品", description = "按分公司隔离分页查询同步落表的京东商品;"
|
||||
+ "company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。")
|
||||
@Operation(summary = "分页查询京东数据库商品", description = "公共库分页查询同步落表的京东商品;"
|
||||
+ "company_id 只对站点超管生效(显式传才收窄=按同步来源公司筛),非超管传什么都不收(全量)。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = JdProductPageVo.class)))
|
||||
})
|
||||
@@ -92,8 +99,12 @@ 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 = "只看未分类(group_id IS NULL,店铺分类弹窗「未分类」范围)")
|
||||
@RequestParam(name = "ungrouped", required = false) Boolean ungrouped,
|
||||
@Parameter(description = "只看已分类(group_id IS NOT NULL,页面筛选行「分类状态」档)")
|
||||
@RequestParam(name = "grouped", required = false) Boolean grouped,
|
||||
@Parameter(description = "同步开始时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
|
||||
@Parameter(description = "同步结束时间(包含,ISO datetime)")
|
||||
@@ -102,55 +113,53 @@ public class AdminJdProductController {
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 公司隔离正门是 readCompanyIdOrOwn(同外观专利只读页口径):超管显式传才收窄、
|
||||
// 不传全量;非超管强制本公司(忽略请求传参)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
// 公司维度只剩超管的公司 tab 筛选(superAdminScopedCompanyId):超管显式传才收窄,
|
||||
// 非超管传什么都不收——公共库对每一家管理员都是同一份全量。
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
return ApiResponse.success(jdProductQueryService.page(page, pageSize, scopedCompanyId, shopName,
|
||||
productCode, titleKeyword, saleStatus, groupId, syncedFrom, syncedTo));
|
||||
productCode, titleKeyword, category, groupId, ungrouped, grouped, syncedFrom, syncedTo));
|
||||
}
|
||||
|
||||
@GetMapping("/categories")
|
||||
@Operation(summary = "类目筛选下拉数据源", description = "已落库行 DISTINCT 的 category_path"
|
||||
+ "(京麦末级类目名)+ 行数,按类目名排序;company_id 只对站点超管生效(显式传才收窄="
|
||||
+ "选项集与超管当前公司 tab 的行集同源),非超管传什么都不收(全量)。")
|
||||
public ApiResponse<List<JdProductCategoryVo>> categories(
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 类目下拉与列表同走超管筛选口径:选项集永远和当前请求能看到的行集同源。
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
return ApiResponse.success(jdProductQueryService.categories(scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "商品详情", description = "主字段全量 + attr_json 属性分组(契约形状不识别时落空分组"
|
||||
+ "并把原文放 attrJsonRaw 兜底,AC-7 未识别属性不丢弃)+ 已转存图片(100% 自有域名,AC-4)。"
|
||||
+ "公司隔离与列表同门:越界 id 按不存在拒绝。")
|
||||
+ "公共库无公司维度:按 id 直取,越界 id 按不存在拒绝。")
|
||||
public ApiResponse<JdProductDetailVo> detail(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 详情同样过公司隔离正门:超管不传 company_id = 全量可见;非超管恒为本公司(服务按它收口)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
return ApiResponse.success(jdProductQueryService.detail(id, scopedCompanyId));
|
||||
requireJdAccess(request);
|
||||
return ApiResponse.success(jdProductQueryService.detail(id));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
@Operation(summary = "导出京东数据库 Excel", description = "与分页查询同一过滤面(店铺名/商品编码/标题关键词/"
|
||||
+ "商品状态/分组/同步起止),公司隔离走同一正门:company_id 只对站点超管生效(显式传才收窄,"
|
||||
+ "不传全量),非超管强制本公司。超过导出上限按业务错误拒绝。")
|
||||
public ResponseEntity<byte[]> 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,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "编辑京东商品", description = "主字段全量提交(标题/品牌/类目/货号/价格区间/总库存/"
|
||||
+ "状态/分组),可选块缺省不动:attrGroups 重建 attr_json 的 tabs 段(其余顶层键保留)、"
|
||||
+ "skus 按 skuId 改价格库存、deleteImageIds 删图(共用对象保留)。保存即置人工编辑锁"
|
||||
+ "(manual_locked=1):采集回传对该行不再覆盖/清理。返回刷新后的详情。")
|
||||
public ApiResponse<JdProductDetailVo> update(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
@Valid @RequestBody JdProductUpdateRequest body,
|
||||
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);
|
||||
log.info("[jd-product] 编辑商品 operatorId={} id={} title={}",
|
||||
operator.id(), updatedId, body.getTitle());
|
||||
// 返回刷新后的详情(前端保存后直接回填抽屉),复用详情同一查询出口。
|
||||
return ApiResponse.success(jdProductQueryService.detail(updatedId));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@@ -159,31 +168,42 @@ public class AdminJdProductController {
|
||||
+ "任何对象删不掉就整批拒绝、一行库行都不动。越界 id 按不存在拒绝。")
|
||||
public ApiResponse<JdProductDeleteVo> delete(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(List.of(id), scopedCompanyId);
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(List.of(id));
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪些行、桶里清了几个对象(同分组删除口径)。
|
||||
log.info("[jd-product] 删除商品 operatorId={} companyId={} id={} deleted={} objectsDeleted={}",
|
||||
operator.id(), scopedCompanyId, id, vo.getDeleted(), vo.getObjectsDeleted());
|
||||
log.info("[jd-product] 删除商品 operatorId={} id={} deleted={} objectsDeleted={}",
|
||||
operator.id(), id, vo.getDeleted(), vo.getObjectsDeleted());
|
||||
return ApiResponse.success(vo);
|
||||
}
|
||||
|
||||
@PostMapping("/batch-assign-group")
|
||||
@Operation(summary = "批量归类京东商品(店铺分类弹窗)", description = "勾选商品行 → 归入指定分类"
|
||||
+ "(groupId 必须真实存在)或移出分类(groupId=null,group_id 置 NULL)。与单行编辑"
|
||||
+ "同口径:归类即人工干预,落 manual_locked=1(采集 upsert/登记/覆盖清理此后跳过本行,"
|
||||
+ "分类不被重爬清理冲掉,代价是该行价格/库存随锁停更)。单次最多 200 个;id 不存在的"
|
||||
+ "行不计入更新数、不整批拒绝(弹窗行集与库行有采集刷新时间差,掉队行跳过)。")
|
||||
public ApiResponse<Integer> batchAssignGroup(
|
||||
@Valid @RequestBody JdProductBatchAssignGroupRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
int updated = jdProductUpdateService.assignGroup(body.getIds(), body.getGroupId());
|
||||
// 管理端写动作必须留痕:谁、把多少行归到哪个分类(null=移出分类)。
|
||||
log.info("[jd-product] 批量归类 operatorId={} requested={} updated={} groupId={}",
|
||||
operator.id(), body.getIds().size(), updated, body.getGroupId());
|
||||
return ApiResponse.success(updated);
|
||||
}
|
||||
|
||||
@PostMapping("/batch-delete")
|
||||
@Operation(summary = "批量删除京东商品", description = "与单行删除同一出口(先删桶对象、全成功才删库行);"
|
||||
+ "单次最多 200 个,id 里有一行不存在或不属于当前公司则整批拒绝(不做部分删除)。")
|
||||
+ "单次最多 200 个,id 里有一行不存在则整批拒绝(不做部分删除)。")
|
||||
public ApiResponse<JdProductDeleteVo> batchDelete(
|
||||
@Valid @RequestBody JdProductBatchDeleteRequest body,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(body.getIds(), scopedCompanyId);
|
||||
log.info("[jd-product] 批量删除商品 operatorId={} companyId={} requested={} deleted={} objectsDeleted={} kept={}",
|
||||
operator.id(), scopedCompanyId, body.getIds().size(), vo.getDeleted(),
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(body.getIds());
|
||||
log.info("[jd-product] 批量删除商品 operatorId={} requested={} deleted={} objectsDeleted={} kept={}",
|
||||
operator.id(), body.getIds().size(), vo.getDeleted(),
|
||||
vo.getObjectsDeleted(), vo.getObjectsKept());
|
||||
return ApiResponse.success(vo);
|
||||
}
|
||||
|
||||
+18
-35
@@ -5,7 +5,6 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.modules.jd.model.dto.JdProductGroupSaveRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
@@ -24,7 +23,6 @@ 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.util.List;
|
||||
@@ -32,19 +30,20 @@ import java.util.List;
|
||||
/**
|
||||
* 后管「京东数据库」分组管理(v1.4 Phase 5,R4):新建 / 改名 / 删除 / 下拉列表。
|
||||
*
|
||||
* <p>京东数据库专属分组(不是店铺管理的分组集):按公司隔离(唯一键
|
||||
* {@code uk_company_group_name});删除分组不删商品——商品行 {@code group_id} 置 NULL
|
||||
* (AC-8,事务两步落 {@code JdProductGroupService})。</p>
|
||||
* <p>京东数据库专属分组(不是店铺管理的分组集):<b>2026-11-15 用户定案公共化</b>——
|
||||
* 与品牌数据库(亚马逊)的分组同形状,全平台一份、不分公司(唯一键 {@code uk_group_name},
|
||||
* V200 退键);删除分组不删商品——商品行 {@code group_id} 置 NULL(AC-8,事务两步落
|
||||
* {@code JdProductGroupService})。实体上遗留的 company_id 列只是历史归属标记,读写两侧
|
||||
* 都不再引用,新行按 DEFAULT 0 落「平台公共」。</p>
|
||||
*
|
||||
* <p>鉴权与 {@code AdminJdProductController} 同款私有闸(同一 column_key/route_path):
|
||||
* 普通授权用户可读写分组(AC-9),默认仅 super_admin;公司隔离正门同样是
|
||||
* {@code readCompanyIdOrOwn}——超管显式传才收窄,非超管强制本公司。</p>
|
||||
* 普通授权用户可读写分组(AC-9),默认仅 super_admin。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@RequestMapping("/api/admin/jd-product-groups")
|
||||
@Tag(name = "京东数据库分组", description = "京东商品自定义分组管理:按公司隔离的列表/新建/改名/删除,删除不删商品(脱组)。")
|
||||
@Tag(name = "京东数据库分组", description = "京东商品自定义分组管理:全平台一份(公共库),列表/新建/改名/删除,删除不删商品(脱组)。")
|
||||
public class AdminJdProductGroupController {
|
||||
|
||||
private static final String COLUMN_KEY = "admin_jd_database";
|
||||
@@ -53,49 +52,35 @@ public class AdminJdProductGroupController {
|
||||
private final JdProductGroupService jdProductGroupService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分组列表(含组内商品数)", description = "按公司隔离返回全部分组,按 sort_order, id 升序;"
|
||||
+ "company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。"
|
||||
@Operation(summary = "分组列表(含组内商品数)", description = "全平台全部分组,按 sort_order, id 升序;"
|
||||
+ "productCount 为读侧现算列(分组下拉展示用)。")
|
||||
public ApiResponse<List<JdProductGroupVo>> list(
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
return ApiResponse.success(jdProductGroupService.list(scopedCompanyId));
|
||||
public ApiResponse<List<JdProductGroupVo>> list(HttpServletRequest request) {
|
||||
requireJdAccess(request);
|
||||
return ApiResponse.success(jdProductGroupService.list());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新建分组", description = "同公司重名按业务错误拒绝(409),不落库;"
|
||||
+ "归属公司走公司隔离正门(站点超管必须显式传 company_id)。")
|
||||
@Operation(summary = "新建分组", description = "重名按业务错误拒绝(409),不落库;公共库无公司归属。")
|
||||
public ApiResponse<Long> create(
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 超管不传 company_id 时 scopedCompanyId 为空 ⇒ 服务侧拒绝(分组必须归属一家公司)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
Long id = jdProductGroupService.create(scopedCompanyId, body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 新建分组 operatorId={} companyId={} groupId={}",
|
||||
operator.id(), scopedCompanyId, id);
|
||||
Long id = jdProductGroupService.create(body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 新建分组 operatorId={} groupId={}", operator.id(), id);
|
||||
return ApiResponse.success(id);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "分组改名/改排序", description = "越界 id(不属于本公司)按不存在拒绝;"
|
||||
+ "改成本公司已有名字按业务错误拒绝(409)。")
|
||||
@Operation(summary = "分组改名/改排序", description = "越界 id(不存在)按不存在拒绝;"
|
||||
+ "改成已有名字按业务错误拒绝(409)。")
|
||||
public ApiResponse<Boolean> rename(
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
jdProductGroupService.rename(id, scopedCompanyId, body.getName(), body.getSortOrder());
|
||||
jdProductGroupService.rename(id, body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 分组改名 operatorId={} groupId={}", operator.id(), id);
|
||||
return ApiResponse.success(Boolean.TRUE);
|
||||
}
|
||||
@@ -107,9 +92,7 @@ public class AdminJdProductGroupController {
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
int detached = jdProductGroupService.delete(id, scopedCompanyId);
|
||||
int detached = jdProductGroupService.delete(id);
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪个分组、脱组了多少商品。
|
||||
log.info("[jd-product-group] 删除分组 operatorId={} groupId={} detached={}",
|
||||
operator.id(), id, detached);
|
||||
|
||||
+16
@@ -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)数据访问口。
|
||||
*
|
||||
* <p>只走 BaseMapper wrapper(铁律 1 允许的两种形态之一,与 {@link JdProductSkuMapper}
|
||||
* 的查询口同形状):写入口是 {@code JdProductDeleteService} 删除成功后的幂等登记,
|
||||
* 读入口是 {@code JdResultIngestService} 按三元组回查命中集。无自定义 SQL,无 XML。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface JdProductIgnoreMapper extends BaseMapper<JdProductIgnoreEntity> {
|
||||
}
|
||||
+34
-4
@@ -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;
|
||||
|
||||
@@ -31,20 +32,40 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
*/
|
||||
int upsertBatch(@Param("rows") List<JdProductEntity> rows);
|
||||
|
||||
/**
|
||||
* 货号系统生成(2026-11-15 用户口径「系统自行生成货号,不用之前的货号」):
|
||||
* 本任务落库的行 {@code item_num = 行号}(全局唯一、从 1 递增;行不变货号不变,
|
||||
* 重爬命中已有行时货号稳定)。幂等:已等于行号的行不重复写;{@code manual_locked=1}
|
||||
* 的行不动(人工编辑过的人工值优先)。京东原货号只在 attr_json 属性区留档。
|
||||
*/
|
||||
int reassignItemNums(@Param("companyId") Long companyId, @Param("taskId") Long taskId);
|
||||
|
||||
/**
|
||||
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
|
||||
* (公司/店铺名/商品编码/标题关键词/商品状态/分组/同步起止,全部 SQL 侧下推,
|
||||
* 铁律 20)。{@code companyId}/{@code groupId} 为空或 ≤0=不过滤该面。
|
||||
* (公司/店铺名/商品编码/标题关键词/类目/分组/未分类/已分类/同步起止,全部 SQL 侧下推,
|
||||
* 铁律 20)。{@code companyId}/{@code groupId} 为空或 ≤0=不过滤该面;
|
||||
* {@code ungrouped=true}=只看未分类行(group_id IS NULL,店铺分类弹窗「未分类」范围);
|
||||
* {@code grouped=true}=只看已分类行(group_id IS NOT NULL,页面筛选行「分类状态」档)。
|
||||
*/
|
||||
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("ungrouped") Boolean ungrouped,
|
||||
@Param("grouped") Boolean grouped,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo);
|
||||
|
||||
/**
|
||||
* 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+
|
||||
* 名下员工,公司超管=全公司成员)计 {@code biz_jd_product} 行数。归属列
|
||||
* {@code user_id}=任务 owner(V193 物化列)。调用方保证列表非空——空集在服务侧
|
||||
* 直接按 0 处理,不进 SQL。
|
||||
*/
|
||||
long countByUserIds(@Param("userIds") List<Long> userIds);
|
||||
|
||||
/**
|
||||
* 后管只读页分页查询(synced_at 倒序)。
|
||||
*
|
||||
@@ -73,10 +94,19 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
@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("ungrouped") Boolean ungrouped,
|
||||
@Param("grouped") Boolean grouped,
|
||||
@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<JdProductCategoryVo> selectProductCategories(@Param("companyId") Long companyId);
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.nanri.aiimage.modules.jd.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 后管京东商品批量归类请求体(店铺分类弹窗,2026-11-15):勾选商品行 → 归入左侧选中分类
|
||||
* 或移出分类。公共库写侧无公司维度(2026-11-15 用户定案),body 不带 company_id——
|
||||
* 公司维度的假 tab 形状随 2026-11-15 公共化已从写侧端点整批摘除。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品批量归类请求(归入分类或移出分类)")
|
||||
public class JdProductBatchAssignGroupRequest {
|
||||
|
||||
@Schema(description = "商品行 id 清单(单次最多 200 个,与批量删除同档)")
|
||||
@NotEmpty(message = "请先选择要归类的商品")
|
||||
@Size(max = 200, message = "单次最多归类 200 个商品,请分批操作")
|
||||
private List<Long> ids;
|
||||
|
||||
@Schema(description = "目标分类 id;null=移出分类(group_id 置 NULL,商品回到未分类)")
|
||||
private Long groupId;
|
||||
}
|
||||
+116
@@ -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 用户口径)。
|
||||
*
|
||||
* <p>主字段全量提交(保存即按本请求体覆写这几个列);三个可选块缺省=不动那一面:
|
||||
* {@code attrGroups} 缺省不动属性、{@code skus} 缺省不动 SKU 价格库存、{@code deleteImageIds}
|
||||
* 缺省不删图。公司隔离不走 body——`company_id` 是请求参数,由
|
||||
* {@code DataReadScope#readCompanyIdOrOwn} 统一收口(同本模块全部端点)。</p>
|
||||
*
|
||||
* <p>编辑保存后商品行 {@code manual_locked=1}(V199 人工编辑锁):采集回传的
|
||||
* upsert / 图片与 SKU 登记 / 覆盖清理对该行全部跳过,人工值不被京麦采集覆盖。</p>
|
||||
*/
|
||||
@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<AttrGroupDto> attrGroups;
|
||||
|
||||
@Schema(description = "SKU 价格库存编辑(可选块;缺省不动;按 skuId 匹配逐行更新)")
|
||||
private List<SkuEditDto> skus;
|
||||
|
||||
@Schema(description = "要删除的图片登记行 id 清单(可选块;缺省不删图;共用对象保留)")
|
||||
private List<Long> deleteImageIds;
|
||||
|
||||
@Data
|
||||
@Schema(description = "属性分组(京麦 Tab 形状)")
|
||||
public static class AttrGroupDto {
|
||||
|
||||
@Schema(description = "分组名(京麦 Tab 名,可空)")
|
||||
@Size(max = 64, message = "属性分组名最长 64 字")
|
||||
private String groupName;
|
||||
|
||||
@Schema(description = "属性键值对列表")
|
||||
private List<AttrDto> 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;
|
||||
}
|
||||
}
|
||||
+2
@@ -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;
|
||||
}
|
||||
|
||||
+6
-5
@@ -10,9 +10,10 @@ import java.time.LocalDateTime;
|
||||
/**
|
||||
* 京东商品自定义分组({@code biz_jd_product_group},V195,v1.4)。
|
||||
*
|
||||
* <p>京东数据库专属分组(R4):按公司隔离(唯一键 {@code uk_company_group_name}),
|
||||
* 可新建/改名/删除;删除分组不删商品——商品行 {@code group_id} 置 NULL(AC-8)。
|
||||
* 简单单表 CRUD 走 BaseMapper + wrapper(SqlLayering 惯例),无 XML。</p>
|
||||
* <p>京东数据库专属分组(R4):<b>2026-11-15 起全平台一份</b>(唯一键 {@code uk_group_name},
|
||||
* V200 退掉按公司的 {@code uk_company_group_name});可新建/改名/删除;删除分组不删商品——
|
||||
* 商品行 {@code group_id} 置 NULL(AC-8)。简单单表 CRUD 走 BaseMapper + wrapper
|
||||
* (SqlLayering 惯例),无 XML。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_jd_product_group")
|
||||
@@ -20,9 +21,9 @@ public class JdProductGroupEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
/** 归属分公司(分组按公司隔离,R4)。 */
|
||||
/** 历史归属公司(V195~V199 按公司隔离时代遗留,公共化后读写两侧不再引用;新行 DEFAULT 0=平台公共)。 */
|
||||
private Long companyId;
|
||||
/** 分组名(同公司内唯一)。 */
|
||||
/** 分组名(全平台唯一)。 */
|
||||
private String name;
|
||||
/** 下拉展示顺序。 */
|
||||
private Integer sortOrder;
|
||||
|
||||
+34
@@ -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)。
|
||||
*
|
||||
* <p>后管删除商品成功后写入被删行的 {@code (company_id, shop_id, product_code)} 三元组;
|
||||
* 采集回传({@code JdResultIngestService})对命中三元组的行跳过落库——防止删除后的商品
|
||||
* 在重爬同一店铺时被当作新行重新插回来(upsert 对不存在的键走 INSERT)。</p>
|
||||
*
|
||||
* <p>不设外键、不级联:主表行被覆盖清理级联删掉时忽略记录仍保留(忽略语义本就独立于
|
||||
* 行存在)。唯一键 {@code uk_company_shop_code} 与主表同三元组口径,重复删除幂等。</p>
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
+22
@@ -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 用户口径「京麦的类目也要同步过来后台」)。
|
||||
*
|
||||
* <p>京麦列表接口只回末级类目名({@code categoryDetailVO.lastCategoryName},契约 §2.3 E3),
|
||||
* 拿不到完整三级树 ⇒ 下拉选项按本公司已落库行的 {@code category_path}(=末级类目名)
|
||||
* distinct 现算,{@code productCount} 是该类目行数(供界面展示「类目(N)」)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东数据库类目筛选下拉选项")
|
||||
public class JdProductCategoryVo {
|
||||
|
||||
@Schema(description = "类目名(京麦末级类目,即落库的 category_path)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "该类目的商品行数")
|
||||
private Long productCount;
|
||||
}
|
||||
+3
@@ -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;
|
||||
|
||||
|
||||
+63
-14
@@ -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;
|
||||
@@ -31,9 +34,12 @@ import java.util.Set;
|
||||
* {@code biz_jd_product_image} 里有没有别的商品引用它;有就保留,计入 {@code objectsKept}。</li>
|
||||
* <li><b>只删自己前缀内的 key</b>:key 不以 {@code aiimage.jd.oss.key-prefix} 开头的行只留 WARN、
|
||||
* 不动手(防早期脏数据把删除扩到别的桶前缀上),计入 {@code objectsSkipped}。</li>
|
||||
* <li><b>归属先判、整批拒绝</b>:id 里有一行不存在或不属于当前公司 ⇒ 整批不删(不做部分删除,
|
||||
* 也不泄露越界行的存在性),文案点明"本次未删除任何数据"。</li>
|
||||
* <li><b>存在先判、整批拒绝</b>:id 里有一行不存在 ⇒ 整批不删(不做部分删除),
|
||||
* 文案点明"本次未删除任何数据"。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>公共库无公司维度(2026-11-15 用户定案「京东数据库不区分公司」):删除按 id 直判存在性,
|
||||
* 不再按行 company_id 收口。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -53,6 +59,7 @@ public class JdProductDeleteService {
|
||||
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductIgnoreMapper jdProductIgnoreMapper;
|
||||
private final JdProductRowDeleteService jdProductRowDeleteService;
|
||||
private final OssStorageService ossStorageService;
|
||||
|
||||
@@ -64,10 +71,10 @@ public class JdProductDeleteService {
|
||||
@Value("${aiimage.jd.oss.key-prefix:jd-products/}")
|
||||
private String keyPrefix;
|
||||
|
||||
/** 删除给定商品(含 SKU、图片登记行与桶内对象);见类注释的三条边界。 */
|
||||
public JdProductDeleteVo delete(List<Long> requestedIds, Long scopedCompanyId) {
|
||||
/** 删除给定商品(含 SKU、图片登记行与桶内对象);见类注释的三条边界。公共库无公司维度(2026-11-15 用户定案)。 */
|
||||
public JdProductDeleteVo delete(List<Long> requestedIds) {
|
||||
List<Long> ids = normalizeIds(requestedIds);
|
||||
requireScopedRows(ids, scopedCompanyId);
|
||||
List<JdProductEntity> scopedRows = requireExistingRows(ids);
|
||||
List<JdProductImageEntity> images = imageRowsOf(ids);
|
||||
Set<String> ownedKeys = new LinkedHashSet<>();
|
||||
Set<String> foreignKeys = new LinkedHashSet<>();
|
||||
@@ -89,14 +96,18 @@ public class JdProductDeleteService {
|
||||
throw ex;
|
||||
}
|
||||
|
||||
// V199:删除成功即登记忽略三元组——采集回传对命中行跳过落库,防止重爬把删掉的
|
||||
// 商品当新行插回来(upsert 对不存在的键走 INSERT)。登记失败不推翻删除结果,留痕即可。
|
||||
registerIgnoreRows(scopedRows);
|
||||
|
||||
JdProductDeleteVo vo = new JdProductDeleteVo();
|
||||
vo.setDeleted(deleted);
|
||||
vo.setImagesDeleted(images.size());
|
||||
vo.setObjectsDeleted(purged);
|
||||
vo.setObjectsKept(ownedKeys.size() - purged);
|
||||
vo.setObjectsSkipped(foreignKeys.size());
|
||||
log.info("[{}] 删除完成 companyId={} productIds={} deleted={} images={} objectsDeleted={} kept={} skipped={}",
|
||||
LOG_TAG, scopedCompanyId, ids, deleted, images.size(), purged, vo.getObjectsKept(),
|
||||
log.info("[{}] 删除完成 productIds={} deleted={} images={} objectsDeleted={} kept={} skipped={}",
|
||||
LOG_TAG, ids, deleted, images.size(), purged, vo.getObjectsKept(),
|
||||
foreignKeys.size());
|
||||
return vo;
|
||||
}
|
||||
@@ -122,16 +133,54 @@ public class JdProductDeleteService {
|
||||
return new ArrayList<>(unique);
|
||||
}
|
||||
|
||||
/** 归属闸:行必须都在(且都在当前公司可见面内),否则整批拒绝——不做部分删除。 */
|
||||
private void requireScopedRows(List<Long> ids, Long scopedCompanyId) {
|
||||
boolean scoped = scopedCompanyId != null && scopedCompanyId > 0;
|
||||
/** 存在闸:行必须都在,否则整批拒绝——不做部分删除。返回实读到的行(供删除成功后登记忽略三元组)。 */
|
||||
private List<JdProductEntity> requireExistingRows(List<Long> ids) {
|
||||
List<JdProductEntity> rows = jdProductMapper.selectList(new LambdaQueryWrapper<JdProductEntity>()
|
||||
.select(JdProductEntity::getId)
|
||||
.in(JdProductEntity::getId, ids)
|
||||
.eq(scoped, JdProductEntity::getCompanyId, scopedCompanyId));
|
||||
.in(JdProductEntity::getId, ids));
|
||||
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<JdProductEntity> rows) {
|
||||
List<JdProductIgnoreEntity> 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+22
-38
@@ -21,17 +21,14 @@ import java.util.List;
|
||||
* <p>分组表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。
|
||||
* 业务规则:</p>
|
||||
* <ul>
|
||||
* <li><b>按公司隔离</b>:所有读写都带 {@code companyId} 面;越界 id(行不存在或
|
||||
* {@code company_id} 与传入公司不符)一律按「分组不存在」拒绝,不泄露存在性。</li>
|
||||
* <li><b>同公司重名拒绝</b>(唯一键 {@code uk_company_group_name}):先查后插给可读的
|
||||
* <li><b>全平台一份(2026-11-15 用户定案「分组和亚马逊功能一样」=与品牌数据库的
|
||||
* 全平台共享同形状)</b>:读写都不带公司维度;实体遗留的 {@code company_id} 列只是
|
||||
* V195~V199 按公司隔离时代的历史值,新行由 DEFAULT 0 落「平台公共」。</li>
|
||||
* <li><b>全局重名拒绝</b>(唯一键 {@code uk_group_name},V200 退键):先查后插给可读的
|
||||
* 409 业务错误,不拿 DB 异常撞 500;改名时排除自身再查。</li>
|
||||
* <li><b>删除两步一事务</b>(AC-8):先把该组商品 {@code biz_jd_product.group_id} 置 NULL
|
||||
* (商品不删,脱组即成「未分组」),再删分组行——同一事务,失败一起回滚。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code companyId} 由控制器经 {@code DataReadScope#readCompanyIdOrOwn} 算好传入:
|
||||
* {@code null} = 超管没选公司(rename/delete 放行、create 没有「没选公司」语义——
|
||||
* 分组必须归属一家公司,直接拒绝),正数=该公司(非超管恒为自己的公司)。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -45,10 +42,8 @@ public class JdProductGroupService {
|
||||
* {@code productCount} 用 {@code JdProductMapper} BaseMapper selectCount wrapper
|
||||
* 按 {@code group_id} 统计(分组下拉展示用)。
|
||||
*/
|
||||
public List<JdProductGroupVo> list(Long scopedCompanyId) {
|
||||
public List<JdProductGroupVo> list() {
|
||||
LambdaQueryWrapper<JdProductGroupEntity> query = new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.eq(scopedCompanyId != null && scopedCompanyId > 0,
|
||||
JdProductGroupEntity::getCompanyId, scopedCompanyId)
|
||||
.orderByAsc(JdProductGroupEntity::getSortOrder)
|
||||
.orderByAsc(JdProductGroupEntity::getId);
|
||||
List<JdProductGroupVo> items = new ArrayList<>();
|
||||
@@ -65,15 +60,11 @@ public class JdProductGroupService {
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 新建分组:同公司重名(trim 后)按 409 业务错误拒绝,不落库。 */
|
||||
public Long create(Long scopedCompanyId, String name, Integer sortOrder) {
|
||||
if (scopedCompanyId == null || scopedCompanyId <= 0) {
|
||||
throw new BusinessException(400, "创建分组必须指定公司");
|
||||
}
|
||||
/** 新建分组:重名(trim 后)按 409 业务错误拒绝,不落库;company_id 不写(DB DEFAULT 0=平台公共)。 */
|
||||
public Long create(String name, Integer sortOrder) {
|
||||
String safeName = requireName(name);
|
||||
requireNameFree(scopedCompanyId, safeName, null);
|
||||
requireNameFree(safeName, null);
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setCompanyId(scopedCompanyId);
|
||||
group.setName(safeName);
|
||||
group.setSortOrder(sortOrder == null ? 0 : sortOrder);
|
||||
jdProductGroupMapper.insert(group);
|
||||
@@ -81,10 +72,10 @@ public class JdProductGroupService {
|
||||
}
|
||||
|
||||
/** 改名/改排序:越界 id 拒绝,重名(排除自身)拒绝。 */
|
||||
public void rename(Long id, Long scopedCompanyId, String name, Integer sortOrder) {
|
||||
public void rename(Long id, String name, Integer sortOrder) {
|
||||
String safeName = requireName(name);
|
||||
JdProductGroupEntity group = requireOwnedGroup(id, scopedCompanyId);
|
||||
requireNameFree(group.getCompanyId(), safeName, group.getId());
|
||||
JdProductGroupEntity group = requireExistingGroup(id);
|
||||
requireNameFree(safeName, group.getId());
|
||||
group.setName(safeName);
|
||||
if (sortOrder != null) {
|
||||
group.setSortOrder(sortOrder);
|
||||
@@ -99,11 +90,10 @@ public class JdProductGroupService {
|
||||
* @return 实际脱组的商品行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
|
||||
*/
|
||||
@Transactional
|
||||
public int delete(Long id, Long scopedCompanyId) {
|
||||
JdProductGroupEntity group = requireOwnedGroup(id, scopedCompanyId);
|
||||
public int delete(Long id) {
|
||||
JdProductGroupEntity group = requireExistingGroup(id);
|
||||
int detached = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.set(JdProductEntity::getGroupId, null)
|
||||
.eq(JdProductEntity::getCompanyId, group.getCompanyId())
|
||||
.eq(JdProductEntity::getGroupId, group.getId()));
|
||||
jdProductGroupMapper.deleteById(group.getId());
|
||||
return detached;
|
||||
@@ -114,36 +104,30 @@ public class JdProductGroupService {
|
||||
/** 名字归一:trim 后必须非空。 */
|
||||
private static String requireName(String name) {
|
||||
if (name == null || name.trim().isEmpty()) {
|
||||
throw new BusinessException(400, "分组名不能为空");
|
||||
throw new BusinessException(400, "分类名不能为空");
|
||||
}
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 分组行归属校验:不存在 / 公司不符(越界 id)一律按「分组不存在」拒绝——
|
||||
* 越界探测拿到的与 id 不存在是同一种响应,不泄露跨公司行的存在性。
|
||||
* {@code scopedCompanyId} 为空=超管没选公司、跨公司放行。
|
||||
*/
|
||||
private JdProductGroupEntity requireOwnedGroup(Long id, Long scopedCompanyId) {
|
||||
/** 分类行存在校验:不存在一律按「分类不存在」拒绝。 */
|
||||
private JdProductGroupEntity requireExistingGroup(Long id) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("分组不存在");
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(id);
|
||||
if (group == null || (scopedCompanyId != null && scopedCompanyId > 0
|
||||
&& !scopedCompanyId.equals(group.getCompanyId()))) {
|
||||
throw new BusinessException("分组不存在");
|
||||
if (group == null) {
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
/** 同公司重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
|
||||
private void requireNameFree(Long companyId, String name, Long excludeId) {
|
||||
/** 全局重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
|
||||
private void requireNameFree(String name, Long excludeId) {
|
||||
Long count = jdProductGroupMapper.selectCount(new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.eq(JdProductGroupEntity::getCompanyId, companyId)
|
||||
.eq(JdProductGroupEntity::getName, name)
|
||||
.ne(excludeId != null, JdProductGroupEntity::getId, excludeId));
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException(409, "同公司下已存在同名分组:" + name);
|
||||
throw new BusinessException(409, "已存在同名分类:" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+47
-140
@@ -13,35 +13,32 @@ 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):分页 / 详情。
|
||||
*
|
||||
* <p>分页钳制是本服务的职责(铁律 15):mapper 的 {@code offset}/{@code limit} 只收钳制后的值
|
||||
* (单一出口,mapper 不做第二次换算)。钳制形状照 {@code AppearancePatentCleanItemQueryService}
|
||||
* 先例:{@code page} 上限 {@link #MAX_PAGE}、{@code page_size} 上限 {@link #MAX_PAGE_SIZE},
|
||||
* {@code page=Long.MAX_VALUE} 不会把乘积顶成负数生成 {@code LIMIT -N} 的 500 错。</p>
|
||||
*
|
||||
* <p><b>公司隔离</b>:{@code scopedCompanyId} 由控制器经 {@code DataReadScope#readCompanyIdOrOwn}
|
||||
* 算好传入——{@code null} = 超管没选公司、查全量;正数 = 只查该公司(非超管恒为自己的公司)。
|
||||
* 详情同样按它收口:行 {@code company_id} 与公司隔离范围不符按不存在拒绝(不泄露跨公司行的存在性)。</p>
|
||||
* <p><b>公司口径(2026-11-15 公共化)</b>:{@code scopedCompanyId} 由控制器经
|
||||
* {@code DataReadScope#superAdminScopedCompanyId} 算好传入——只有站点超管显式传 company_id
|
||||
* (公司 tab 筛选)才是正数,其余请求(含全部非超管)恒为 {@code null} = 全量;详情没有
|
||||
* 公司维度,按 id 直取。</p>
|
||||
*
|
||||
* <p><b>详情 attr_json 解析(AC-7 未识别属性不丢弃)</b>:客户端实拍契约
|
||||
* {@code {"tabs":[{"tab":"...","attrs":[{key,label,value}]}],"images":[...],"productCode":"..."}}——
|
||||
@@ -49,9 +46,8 @@ import java.util.Map;
|
||||
* 非该形状时<b>不抛 500</b>,落空 {@code attrGroups} 并把原文放进 {@code attrJsonRaw} 兜底展示。
|
||||
* 主表高频列直接从 entity 映射,不走 JSON。</p>
|
||||
*
|
||||
* <p><b>导出</b>与分页共用同一过滤面与同一条 SQL(offset=0、limit=导出上限,不另写导出查询),
|
||||
* 先 {@code countProducts} 卡 {@link #EXPORT_MAX_ROWS} 上限防内存;行集按后管页面主要字段
|
||||
* 中文列序写 xlsx(SXSSF 流式,口径同 {@code QueryAsinService.export} 的 byte[] 形状)。</p>
|
||||
* <p>导出(byte[] xlsx)已随 2026-11-15 客户口径「导出也不用」整段下线,控制器端点同窗删;
|
||||
* {@code sale_status} 过滤参数同窗撤掉(前端筛选框下线),DB 列与详情/回传链不动。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -62,11 +58,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 +65,6 @@ public class JdProductQueryService {
|
||||
private static final String ATTR_LABEL_FIELD = "label";
|
||||
private static final String ATTR_VALUE_FIELD = "value";
|
||||
|
||||
/** 导出列序(与后管页面主要字段同序,中文列名)。 */
|
||||
private static final List<String> EXPORT_HEADERS = List.of(
|
||||
"店铺名", "店铺ID", "商品编码", "货号", "SKU", "SKU数", "信息分", "标题", "品牌", "类目路径",
|
||||
"价格下限", "价格上限", "库存", "商品状态", "来源Tab", "上架时间", "京东创建时间",
|
||||
"京东修改时间", "属性键数", "图片数", "主图URL", "分组", "同步时间");
|
||||
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductSkuMapper jdProductSkuMapper;
|
||||
@@ -90,26 +75,29 @@ public class JdProductQueryService {
|
||||
* 分页查询商品行({@code synced_at} 倒序)。
|
||||
*
|
||||
* <p>过滤面:公司(物化列 eq)、店铺名 contains、商品编码 contains、标题关键词 contains、
|
||||
* 商品状态 eq、分组 eq、同步起止(datetime 闭区间)。</p>
|
||||
* 类目 eq、分组 eq、未分类(group_id IS NULL,店铺分类弹窗「未分类」范围)、
|
||||
* 已分类(group_id IS NOT NULL,页面筛选行「分类状态」档,2026-11-15 客户口径
|
||||
* 「查询已分类的跟未分类,分类好的可以不显示」)、同步起止(datetime 闭区间)。</p>
|
||||
*/
|
||||
public JdProductPageVo page(Long page, Long pageSize, Long scopedCompanyId, String shopName,
|
||||
String productCode, String titleKeyword, String saleStatus, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
String productCode, String titleKeyword, String category, Long groupId, Boolean ungrouped,
|
||||
Boolean grouped, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
}
|
||||
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
|
||||
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
|
||||
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, saleStatus, groupId,
|
||||
syncedFrom, syncedTo);
|
||||
Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, category,
|
||||
groupId, ungrouped, grouped, 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.ungrouped(),
|
||||
filter.grouped(), filter.syncedFrom(), filter.syncedTo());
|
||||
List<JdProductEntity> 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.ungrouped(),
|
||||
filter.grouped(), filter.syncedFrom(), filter.syncedTo(),
|
||||
(safePage - 1) * safeSize, (int) safeSize);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
fillGroupNames(items);
|
||||
JdProductPageVo vo = new JdProductPageVo();
|
||||
@@ -120,20 +108,30 @@ public class JdProductQueryService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
|
||||
* 已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3)
|
||||
* + 各自行数,按类目名排序。公司口径与分页同门(控制器经 {@code superAdminScopedCompanyId} 传入,
|
||||
* {@code null} = 全量公共选项集)。
|
||||
*/
|
||||
public List<JdProductCategoryVo> categories(Long scopedCompanyId) {
|
||||
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
|
||||
return jdProductMapper.selectProductCategories(companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品详情(主字段全量 + attr_json 解析 + 已转存图片)。
|
||||
*
|
||||
* <p>公司隔离与分页同门:{@code scopedCompanyId} 非空且与行 {@code company_id} 不符时按
|
||||
* 不存在拒绝——不泄露跨公司行的存在性(越界 id 探测拿到的与 id 不存在是同一种响应)。
|
||||
* attr_json 非契约形状/解析异常时不抛 500:落空 {@code attrGroups}、原文进
|
||||
* {@code attrJsonRaw} 兜底(AC-7)。</p>
|
||||
* <p>公共库无公司维度(2026-11-15 用户定案「京东数据库不区分公司」):按 id 直取,
|
||||
* 越界 id 按不存在拒绝。attr_json 非契约形状/解析异常时不抛 500:落空 {@code attrGroups}、
|
||||
* 原文进 {@code attrJsonRaw} 兜底(AC-7)。</p>
|
||||
*/
|
||||
public JdProductDetailVo detail(Long id, Long scopedCompanyId) {
|
||||
public JdProductDetailVo detail(Long id) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
JdProductEntity row = jdProductMapper.selectById(id);
|
||||
if (row == null || !companyVisible(row.getCompanyId(), scopedCompanyId)) {
|
||||
if (row == null) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
JdProductDetailVo vo = new JdProductDetailVo();
|
||||
@@ -172,57 +170,26 @@ public class JdProductQueryService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前过滤面全量明细为 xlsx 字节(控制器直接回 {@code ResponseEntity<byte[]>},
|
||||
* 口径同 {@code AppearancePatentCleanItemQueryService.export})。
|
||||
*
|
||||
* <p>先 count 卡 {@link #EXPORT_MAX_ROWS} 上限再取数;取数复用 {@code selectProductPage}
|
||||
* 这一条 SQL(offset=0、limit=上限),不另写导出查询——过滤面永远和分页页签同源。</p>
|
||||
*/
|
||||
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<JdProductEntity> 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<JdProductListItemVo> 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, Boolean ungrouped, Boolean grouped,
|
||||
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, Boolean ungrouped, Boolean grouped,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
|
||||
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
|
||||
// 未分类与其它过滤面同口径:没显式要(true)=null=不进 IS NULL 分支。
|
||||
Boolean safeUngrouped = Boolean.TRUE.equals(ungrouped) ? Boolean.TRUE : null;
|
||||
// 已分类同口径:true=只看 group_id IS NOT NULL 的行;与未分类同选时 SQL 侧两谓词相与=空集
|
||||
// (前端下拉是单选,正常到不了这个组合)。
|
||||
Boolean safeGrouped = Boolean.TRUE.equals(grouped) ? Boolean.TRUE : null;
|
||||
return new Filter(companyId, trimToNull(shopName), trimToNull(productCode), trimToNull(titleKeyword),
|
||||
trimToNull(saleStatus), safeGroupId, syncedFrom, syncedTo);
|
||||
}
|
||||
|
||||
/** 超管不选公司(scopedCompanyId=null)=全量可见;正数=只看该公司。 */
|
||||
private static boolean companyVisible(Long rowCompanyId, Long scopedCompanyId) {
|
||||
if (scopedCompanyId == null || scopedCompanyId <= 0) {
|
||||
return true;
|
||||
}
|
||||
return scopedCompanyId.equals(rowCompanyId);
|
||||
trimToNull(category), safeGroupId, safeUngrouped, safeGrouped, syncedFrom, syncedTo);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表/详情搬运
|
||||
@@ -290,6 +257,7 @@ public class JdProductQueryService {
|
||||
List<JdProductDetailVo.ImageViewVo> 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 +373,6 @@ public class JdProductQueryService {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 导出
|
||||
|
||||
private byte[] writeExportWorkbook(List<JdProductListItemVo> 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;
|
||||
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
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 用户口径
|
||||
* 「每条数据可以编辑,详情里的内容都可以改」)。
|
||||
*
|
||||
* <p>三条块语义:</p>
|
||||
* <ul>
|
||||
* <li><b>主字段全量提交</b>:标题/品牌/类目/货号/价格区间/总库存/状态/分组按请求体覆写;
|
||||
* 分组 id 必须真实存在(分组 2026-11-15 起全平台一份,无公司维度)。保存即置
|
||||
* {@code manual_locked=1}(V199 人工编辑锁)——采集回传的 upsert / 图片与 SKU 登记 /
|
||||
* 覆盖清理对锁定的行全部跳过,人工值不被重爬覆盖。</li>
|
||||
* <li><b>可选块缺省不动</b>:{@code attrGroups} 缺省不动属性;提交时只重建 attr_json 的
|
||||
* {@code tabs} 段、<b>保留原 JSON 其它顶层键</b>(images/productCode 等,铁律 30 形状:
|
||||
* 不整份覆写别人的键);原文解析不出(attrJsonRaw 兜底行)则明确拒绝,不让编辑静默丢原文。
|
||||
* {@code skus} 按 (productId, skuId) 匹配逐行改 price/stock,提交里有不存在的 skuId 按不存在拒绝。
|
||||
* {@code deleteImageIds} 复用 {@link JdProductDeleteService} 的共用对象语义删桶对象+登记行。</li>
|
||||
* <li><b>桶删除在库行之前</b>:与 {@link JdProductDeleteService} 同纪律——对象删除不可回滚,
|
||||
* 先删桶、任何对象删不掉整笔拒绝(此时零库行已动,可安全重试)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class JdProductUpdateService {
|
||||
|
||||
private static final String LOG_TAG = "jd-update";
|
||||
|
||||
/** 单次批量归类上限(与批量删除同档,防脏包一次写爆)。 */
|
||||
private static final int MAX_ASSIGN_IDS = 200;
|
||||
|
||||
/** 单次属性分组/属性行上限(防脏包一次写爆 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)。
|
||||
*
|
||||
* <p>公共库无公司维度(2026-11-15 用户定案):任何拿到本页菜单权限的管理员可编辑全部行。</p>
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long update(Long id, JdProductUpdateRequest body) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
JdProductEntity row = jdProductMapper.selectById(id);
|
||||
if (row == null) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
validateBody(body);
|
||||
|
||||
Long groupId = body.getGroupId();
|
||||
if (groupId != null) {
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
|
||||
if (group == null) {
|
||||
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<JdProductEntity> updater = new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.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;
|
||||
}
|
||||
|
||||
// ---------- 校验 ----------
|
||||
|
||||
/**
|
||||
* 批量人工归类(店铺分类弹窗,2026-11-15):勾选商品行 → 归入指定分类或移出分类。
|
||||
*
|
||||
* <p>与单行编辑同口径(用户拍板「置锁」):归类即人工干预,落 {@code manual_locked=1}——
|
||||
* 采集 upsert 本就不写 group_id,置锁后覆盖清理也不再把这些行整行删掉,分类永不丢;
|
||||
* 代价是该行的价格/库存等字段随锁停更(与编辑保存同一语义)。</p>
|
||||
*
|
||||
* <p>{@code groupId} null=移出分类(group_id 置 NULL 回到未分类);非 null 时必须真实
|
||||
* 存在(分类全平台一份,无公司维度)。只写 group_id 与锁两个列,不动其它字段——
|
||||
* 与 {@link #update} 的全量覆写不同,这是行集级轻touch。</p>
|
||||
*
|
||||
* @return 实际更新的行数(id 不存在/已被删的行不计入,不按不存在整批拒绝——
|
||||
* 弹窗行集与库行之间天然有采集刷新的时间差,掉队的行跳过即可)
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int assignGroup(List<Long> ids, Long groupId) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
throw new BusinessException("请先选择要归类的商品");
|
||||
}
|
||||
List<Long> distinctIds = ids.stream().filter(id -> id != null && id > 0).distinct().toList();
|
||||
if (distinctIds.isEmpty()) {
|
||||
throw new BusinessException("请先选择要归类的商品");
|
||||
}
|
||||
if (distinctIds.size() > MAX_ASSIGN_IDS) {
|
||||
throw new BusinessException("单次最多归类 " + MAX_ASSIGN_IDS + " 个商品,请分批操作");
|
||||
}
|
||||
if (groupId != null) {
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
|
||||
if (group == null) {
|
||||
throw new BusinessException("分类不存在,请刷新分类后重试");
|
||||
}
|
||||
}
|
||||
int updated = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.in(JdProductEntity::getId, distinctIds)
|
||||
.set(JdProductEntity::getGroupId, groupId)
|
||||
// 人工编辑锁:归类即人工干预,采集链路(upsert/登记/覆盖清理)此后跳过本行。
|
||||
.set(JdProductEntity::getManualLocked, 1));
|
||||
log.info("[{}] 批量归类 requested={} distinct={} groupId={} updated={}",
|
||||
LOG_TAG, ids.size(), distinctIds.size(), groupId, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
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 + " 张图片,请分批保存");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 属性重建(只重建 tabs 段,其余顶层键保留) ----------
|
||||
|
||||
/**
|
||||
* 由提交的 attrGroups 重建 attr_json:原 JSON 是契约形状
|
||||
* {@code {"tabs":[…],"images":[…],"productCode":"…"}}——拷贝原 Map、只覆写 {@code tabs} 键,
|
||||
* images/productCode 等其它顶层键原样保留(铁律 30:不整份覆写别人的键)。
|
||||
* 原文解析不出或不是契约形状(tabs 缺失/不是数组)时按不存在拒绝——这种行的原文兜底
|
||||
* 在详情页可见,静默重写等于丢数据。
|
||||
*/
|
||||
private AttrRewrite rebuildAttrJson(JdProductEntity row, List<JdProductUpdateRequest.AttrGroupDto> groups) {
|
||||
if (row.getAttrJson() == null || row.getAttrJson().isBlank()) {
|
||||
// 原本就没有属性:按空 tabs 新建,不拒(首采行 attr_json 可为空)。
|
||||
return new AttrRewrite(writeTabs(List.of(), null), countAttrs(groups));
|
||||
}
|
||||
Map<String, Object> 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<JdProductUpdateRequest.AttrGroupDto> groups, Map<String, Object> root) {
|
||||
List<Map<String, Object>> tabs = new ArrayList<>(groups.size());
|
||||
for (JdProductUpdateRequest.AttrGroupDto group : groups) {
|
||||
if (group == null) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> tab = new java.util.LinkedHashMap<>();
|
||||
tab.put("tab", trimToNull(group.getGroupName()));
|
||||
List<Map<String, Object>> attrs = new ArrayList<>();
|
||||
if (group.getAttrs() != null) {
|
||||
for (JdProductUpdateRequest.AttrDto attr : group.getAttrs()) {
|
||||
if (attr == null) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> pair = new java.util.LinkedHashMap<>();
|
||||
pair.put("key", trimToNull(attr.getKey()));
|
||||
pair.put("label", trimToNull(attr.getLabel()));
|
||||
pair.put("value", trimToNull(attr.getValue()));
|
||||
attrs.add(pair);
|
||||
}
|
||||
}
|
||||
tab.put("attrs", attrs);
|
||||
tabs.add(tab);
|
||||
}
|
||||
try {
|
||||
if (root == null) {
|
||||
return objectMapper.writeValueAsString(Map.of("tabs", tabs));
|
||||
}
|
||||
root.put("tabs", tabs);
|
||||
return objectMapper.writeValueAsString(root);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException ex) {
|
||||
throw new BusinessException("属性 JSON 序列化失败,请稍后重试", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static int countAttrs(List<JdProductUpdateRequest.AttrGroupDto> groups) {
|
||||
int count = 0;
|
||||
for (JdProductUpdateRequest.AttrGroupDto group : groups) {
|
||||
if (group != null && group.getAttrs() != null) {
|
||||
count += group.getAttrs().size();
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// ---------- SKU 价格库存 ----------
|
||||
|
||||
/** 按 (productId, skuId) 逐行更新 price/stock(null=不改该列);提交里有不存在的 skuId 按不存在拒绝。 */
|
||||
private void applySkuEdits(Long productId, List<JdProductUpdateRequest.SkuEditDto> skus) {
|
||||
List<JdProductSkuEntity> rows = jdProductSkuMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductSkuEntity>()
|
||||
.eq(JdProductSkuEntity::getProductId, productId));
|
||||
Map<String, JdProductSkuEntity> bySkuId = new java.util.LinkedHashMap<>();
|
||||
for (JdProductSkuEntity sku : rows) {
|
||||
if (sku.getSkuId() != null) {
|
||||
bySkuId.put(sku.getSkuId(), sku);
|
||||
}
|
||||
}
|
||||
List<String> missing = new ArrayList<>();
|
||||
int edited = 0;
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
for (JdProductUpdateRequest.SkuEditDto edit : skus) {
|
||||
if (edit == null || edit.getSkuId() == null || edit.getSkuId().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String skuId = edit.getSkuId().trim();
|
||||
if (!seen.add(skuId)) {
|
||||
continue;
|
||||
}
|
||||
JdProductSkuEntity existing = bySkuId.get(skuId);
|
||||
if (existing == null) {
|
||||
missing.add(skuId);
|
||||
continue;
|
||||
}
|
||||
LambdaUpdateWrapper<JdProductSkuEntity> updater = new LambdaUpdateWrapper<JdProductSkuEntity>()
|
||||
.eq(JdProductSkuEntity::getId, existing.getId());
|
||||
boolean touched = false;
|
||||
if (edit.getPrice() != null) {
|
||||
updater.set(JdProductSkuEntity::getPrice, edit.getPrice());
|
||||
touched = true;
|
||||
}
|
||||
if (edit.getStock() != null) {
|
||||
updater.set(JdProductSkuEntity::getStock, edit.getStock());
|
||||
touched = true;
|
||||
}
|
||||
if (touched) {
|
||||
jdProductSkuMapper.update(null, updater);
|
||||
edited++;
|
||||
}
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("有 " + missing.size() + " 个 SKU 行不存在(可能已被重新采集刷新),"
|
||||
+ "请刷新详情后重试:首个缺失 skuId=" + missing.get(0));
|
||||
}
|
||||
log.info("[{}] SKU 价格库存已更新 productId={} rows={}", LOG_TAG, productId, edited);
|
||||
}
|
||||
|
||||
// ---------- 删图(与 JdProductDeleteService 同纪律:先删桶、全成功才删行) ----------
|
||||
|
||||
/**
|
||||
* 删除给定图片登记行:逐 id 校验归属(必须挂在本商品上,否则整笔拒绝)→ 共用对象保留
|
||||
* (同 key 被其他商品引用)→ 先删桶对象(任一失败整笔拒绝、零库行已动)→ 删登记行 →
|
||||
* 按剩余行数回写 {@code image_count}。
|
||||
*/
|
||||
private int deleteImages(JdProductEntity row, List<Long> requestedIds) {
|
||||
Set<Long> ids = new LinkedHashSet<>();
|
||||
for (Long imageId : requestedIds) {
|
||||
if (imageId != null && imageId > 0) {
|
||||
ids.add(imageId);
|
||||
}
|
||||
}
|
||||
if (ids.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
List<JdProductImageEntity> imageRows = jdProductImageMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
.in(JdProductImageEntity::getId, ids)
|
||||
.eq(JdProductImageEntity::getProductId, row.getId()));
|
||||
if (imageRows.size() != ids.size()) {
|
||||
throw new BusinessException("有 " + (ids.size() - imageRows.size())
|
||||
+ " 张图片不存在或不属于该商品,请刷新后重试(本次未删除任何数据)");
|
||||
}
|
||||
// 共用性回查(同 JdProductDeleteService.sharedObjectKeys 语义,分片防 IN 计划走坏)。
|
||||
Set<String> ownedKeys = new LinkedHashSet<>();
|
||||
for (JdProductImageEntity image : imageRows) {
|
||||
String key = image.getObjectKey() == null ? "" : image.getObjectKey().trim();
|
||||
if (!key.isEmpty() && keyPrefix != null && !keyPrefix.isEmpty() && key.startsWith(keyPrefix)) {
|
||||
ownedKeys.add(key);
|
||||
}
|
||||
}
|
||||
Set<String> sharedKeys = new LinkedHashSet<>();
|
||||
List<String> all = new ArrayList<>(ownedKeys);
|
||||
final int chunkSize = 500;
|
||||
for (int from = 0; from < all.size(); from += chunkSize) {
|
||||
List<String> chunk = all.subList(from, Math.min(all.size(), from + chunkSize));
|
||||
List<JdProductImageEntity> others = jdProductImageMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
.select(JdProductImageEntity::getObjectKey)
|
||||
.in(JdProductImageEntity::getObjectKey, chunk)
|
||||
.ne(JdProductImageEntity::getProductId, row.getId()));
|
||||
for (JdProductImageEntity other : others) {
|
||||
if (other.getObjectKey() != null) {
|
||||
sharedKeys.add(other.getObjectKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
int purged = 0;
|
||||
for (String key : ownedKeys) {
|
||||
if (sharedKeys.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ossStorageService.removeObject(bucket, key);
|
||||
} catch (RuntimeException ex) {
|
||||
// 异常原文不进界面(RawExceptionMessageSinkGuard):headline 中文判人话,原文只进日志。
|
||||
throw new BusinessException(
|
||||
UserMessages.with("图片对象删除失败,本次未保存任何修改(" + key + ")", ex), ex);
|
||||
}
|
||||
purged++;
|
||||
}
|
||||
jdProductImageMapper.delete(new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
.eq(JdProductImageEntity::getProductId, row.getId())
|
||||
.in(JdProductImageEntity::getId, ids));
|
||||
// 图片数只由删除/登记两侧按表实数刷(XML UPDATE 段刻意不写它,P1-1 口径不变)。
|
||||
Long remaining = jdProductImageMapper.selectCount(
|
||||
new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
.eq(JdProductImageEntity::getProductId, row.getId()));
|
||||
jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.eq(JdProductEntity::getId, row.getId())
|
||||
.set(JdProductEntity::getImageCount, remaining.intValue()));
|
||||
return purged;
|
||||
}
|
||||
|
||||
// ---------- 公共小件 ----------
|
||||
|
||||
private static String trimToNull(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> asStringKeyMap(Map<?, ?> map) {
|
||||
Map<String, Object> result = new java.util.LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
result.put(String.valueOf(entry.getKey()), entry.getValue());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 属性重建结果:新 JSON 与属性键计数(attr_count 质量核查分母同步刷新)。 */
|
||||
private record AttrRewrite(String json, int attrCount) {
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品上架配额(2026-11-15 用户口径「限制管理员上架的商品数量,包括管理员下的员工
|
||||
* 总和不能超过配置的最大值」,默认 5000,{@code aiimage.jd.max-products-per-admin})。
|
||||
*
|
||||
* <p>计数口径=团队在京东数据库({@code biz_jd_product})占有的行数:上架功能的数据源
|
||||
* 就是京东数据库,团队占有量即「可上架量」的上游闸。归属列 {@code user_id}=任务 owner
|
||||
* (V193 物化列),uid 集由 {@link UserDataScopeSupport#resolveVisibleUserIds} 统一解析——
|
||||
* 管理员=本人+名下员工(数据权限分组成员,无分组回退 {@code created_by_id} 兜底);
|
||||
* 公司超管=全公司成员;普通账号先锚定到 {@code created_by_id} 指向的管理员再取团队集,
|
||||
* 读不到主管回退按自己计。站点超管不限额。</p>
|
||||
*
|
||||
* <p>两个出口:{@link #quotaOf} 只读快照(供上架界面展示余量);{@link #assertWithinQuota}
|
||||
* 建上架单前的配额闸,超限抛 {@link BusinessException}。上限 ≤0(0=不限)整体放行。
|
||||
* 商品上架建单入口落地时调用 {@link #assertWithinQuota}——本服务是配额原语,
|
||||
* 不自行改变任何现有链路行为。</p>
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class JdPublishQuotaService {
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final UserDataScopeSupport userDataScopeSupport;
|
||||
private final JdProductMapper jdProductMapper;
|
||||
|
||||
/** 出厂默认与 application.yml 的 aiimage.jd.max-products-per-admin 逐字相等(棘轮);包级可见供同包测试直设。 */
|
||||
@Value("${aiimage.jd.max-products-per-admin:5000}")
|
||||
long maxProductsPerAdmin = 5000L;
|
||||
|
||||
/** 配额只读快照:used=团队已占有行数,limit=配置上限(≤0=不限)。 */
|
||||
public record QuotaSnapshot(long used, long limit) {
|
||||
public boolean unlimited() {
|
||||
return limit <= 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** 团队已占用与上限的只读快照;uid 集为空(无主管且无 id)按 used=0 处理,不进 SQL。 */
|
||||
public QuotaSnapshot quotaOf(AdminUserEntity operator) {
|
||||
List<Long> userIds = teamUserIds(operator);
|
||||
long used = userIds.isEmpty() ? 0L : jdProductMapper.countByUserIds(userIds);
|
||||
return new QuotaSnapshot(used, maxProductsPerAdmin);
|
||||
}
|
||||
|
||||
/**
|
||||
* 建上架单前的配额闸:按「管理员+名下员工合计」口径判限。站点超管不限额;
|
||||
* 上限 ≤0(0=不限)放行;{@code additionalCount} 为负按 0 处理(本闸只判限不预占)。
|
||||
*/
|
||||
public void assertWithinQuota(AdminUserEntity operator, int additionalCount) {
|
||||
if (maxProductsPerAdmin <= 0) {
|
||||
return;
|
||||
}
|
||||
if (operator != null && DeviceSessionPolicy.isSuperAdmin(
|
||||
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) {
|
||||
return;
|
||||
}
|
||||
QuotaSnapshot snapshot = quotaOf(operator);
|
||||
long requested = Math.max(0, additionalCount);
|
||||
if (snapshot.used() + requested > snapshot.limit()) {
|
||||
log.warn("[jd-publish] 商品上架配额不足 operatorId={} used={} requested={} limit={}",
|
||||
operator == null ? null : operator.getId(),
|
||||
snapshot.used(), requested, snapshot.limit());
|
||||
throw new BusinessException("商品上架数量已达上限:该管理员及其名下员工当前已占用 "
|
||||
+ snapshot.used() + "/上限 " + snapshot.limit()
|
||||
+ ",请清理京东数据库商品或联系管理员调整配额后重试");
|
||||
}
|
||||
}
|
||||
|
||||
/** 普通账号锚定到其所属管理员(created_by_id);管理员/公司超管锚自己;无 id 返回空集。 */
|
||||
private List<Long> teamUserIds(AdminUserEntity operator) {
|
||||
if (operator == null || operator.getId() == null) {
|
||||
return List.of();
|
||||
}
|
||||
return userDataScopeSupport.resolveVisibleUserIds(anchorOf(operator));
|
||||
}
|
||||
|
||||
private AdminUserEntity anchorOf(AdminUserEntity operator) {
|
||||
// resolveRole 对普通账号返回 null(角色域只有 super_admin/company_super_admin/admin/null)
|
||||
if (DeviceSessionPolicy.resolveRole(
|
||||
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById()) == null
|
||||
&& operator.getCreatedById() != null) {
|
||||
AdminUserEntity admin = adminUserMapper.selectById(operator.getCreatedById());
|
||||
if (admin != null) {
|
||||
return admin;
|
||||
}
|
||||
}
|
||||
return operator;
|
||||
}
|
||||
}
|
||||
+95
-1
@@ -9,10 +9,12 @@ import com.nanri.aiimage.common.retry.CredentialFatalClassifier;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.text.UserMessages;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductIgnoreMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdCollectTaskCreateRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdIngestChunkRequest;
|
||||
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.vo.JdIngestChunkVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
@@ -31,6 +33,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 京东采集分片回传落库(v1.4 Phase 2,蓝图 §3.2 回传契约)。
|
||||
@@ -68,6 +71,7 @@ public class JdResultIngestService {
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductIgnoreMapper jdProductIgnoreMapper;
|
||||
private final TaskScopeStateMapper taskScopeStateMapper;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final JdCollectTaskService collectTaskService;
|
||||
@@ -136,7 +140,19 @@ public class JdResultIngestService {
|
||||
}
|
||||
}
|
||||
if (!rows.isEmpty()) {
|
||||
jdProductMapper.upsertBatch(rows);
|
||||
// V199 保护闸:人工编辑锁(manual_locked=1)与删除忽略表的行不落库、不登记
|
||||
// 子表——后管编辑/删除过的人工值优先,重爬不得覆盖/复活(跳过只留 WARN,不炸整批)。
|
||||
int protectedSkipped = filterProtectedRows(companyId, rows, pendingImages, pendingSkus);
|
||||
if (!rows.isEmpty()) {
|
||||
jdProductMapper.upsertBatch(rows);
|
||||
// 货号系统生成(2026-11-15 用户口径「系统自行生成货号,不用之前的货号」):
|
||||
// 行号即货号,落库后按本任务刷一次(幂等——已等于行号的行不重复写;
|
||||
// 锁定行不动)。重爬命中已有行时 UPDATE 段不覆盖 item_num,货号保持稳定。
|
||||
jdProductMapper.reassignItemNums(companyId, taskId);
|
||||
} else {
|
||||
log.info("[{}] 整批行都被人工编辑锁/删除忽略保护,本次不落库 taskId={} skipped={}",
|
||||
LOG_TAG, taskId, protectedSkipped);
|
||||
}
|
||||
}
|
||||
// Phase 4:直传完成的图片清单按 statObject 对撞落 biz_jd_product_image(登记链唯一出口
|
||||
// JdProductImageIngestService,uk_product_image 幂等)——必须在商品行落库之后执行。
|
||||
@@ -252,6 +268,84 @@ public class JdResultIngestService {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- V199 保护闸:人工编辑锁与删除忽略 ----------
|
||||
|
||||
/**
|
||||
* 把被保护行从本批落库清单里摘掉(rows 与 pendingImages/pendingSkus 三张清单按下标并行)。
|
||||
* 保护集=本公司 {@code manual_locked=1} 的行(后管编辑保存置 1,人工值优先)∪
|
||||
* {@code biz_jd_product_ignore} 命中三元组(后管删除成功登记,防重爬复活)。
|
||||
* 返回跳过行数;被跳过的行连同其图片/SKU 登记一起不落库。
|
||||
*/
|
||||
private int filterProtectedRows(Long companyId, List<JdProductEntity> rows,
|
||||
List<PendingImageRegistration> pendingImages,
|
||||
List<PendingSkuRegistration> pendingSkus) {
|
||||
Set<String> protectedKeys = loadProtectedKeys(companyId);
|
||||
if (protectedKeys.isEmpty() || rows.size() != pendingImages.size()
|
||||
|| rows.size() != pendingSkus.size()) {
|
||||
return 0;
|
||||
}
|
||||
List<JdProductEntity> keptRows = new ArrayList<>();
|
||||
List<PendingImageRegistration> keptImages = new ArrayList<>();
|
||||
List<PendingSkuRegistration> keptSkus = new ArrayList<>();
|
||||
int skipped = 0;
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
JdProductEntity row = rows.get(i);
|
||||
String key = protectedKey(row.getShopId(), row.getProductCode());
|
||||
if (key != null && protectedKeys.contains(key)) {
|
||||
skipped++;
|
||||
log.warn("[{}] 行被人工编辑锁/删除忽略保护,跳过落库 companyId={} shopId={} productCode={}",
|
||||
LOG_TAG, companyId, row.getShopId(), row.getProductCode());
|
||||
continue;
|
||||
}
|
||||
keptRows.add(row);
|
||||
keptImages.add(pendingImages.get(i));
|
||||
keptSkus.add(pendingSkus.get(i));
|
||||
}
|
||||
if (skipped > 0) {
|
||||
rows.clear();
|
||||
rows.addAll(keptRows);
|
||||
pendingImages.clear();
|
||||
pendingImages.addAll(keptImages);
|
||||
pendingSkus.clear();
|
||||
pendingSkus.addAll(keptSkus);
|
||||
log.info("[{}] 本批 {} 行命中保护集被跳过 companyId={}", LOG_TAG, skipped, companyId);
|
||||
}
|
||||
return skipped;
|
||||
}
|
||||
|
||||
/** 本公司保护键集:锁定的行(shop_id|product_code)∪ 删除忽略表命中三元组。 */
|
||||
private Set<String> loadProtectedKeys(Long companyId) {
|
||||
Set<String> keys = new java.util.LinkedHashSet<>();
|
||||
List<JdProductEntity> locked = jdProductMapper.selectList(new LambdaQueryWrapper<JdProductEntity>()
|
||||
.select(JdProductEntity::getShopId, JdProductEntity::getProductCode)
|
||||
.eq(JdProductEntity::getCompanyId, companyId)
|
||||
.eq(JdProductEntity::getManualLocked, 1));
|
||||
for (JdProductEntity row : locked) {
|
||||
String key = protectedKey(row.getShopId(), row.getProductCode());
|
||||
if (key != null) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
for (JdProductIgnoreEntity ignore : jdProductIgnoreMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductIgnoreEntity>()
|
||||
.select(JdProductIgnoreEntity::getShopId, JdProductIgnoreEntity::getProductCode)
|
||||
.eq(JdProductIgnoreEntity::getCompanyId, companyId))) {
|
||||
String key = protectedKey(ignore.getShopId(), ignore.getProductCode());
|
||||
if (key != null) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** 保护键:shop_id|product_code(两段都非空才算得出键;主表列 NOT NULL,容异常数据)。 */
|
||||
private static String protectedKey(String shopId, String productCode) {
|
||||
if (shopId == null || shopId.isBlank() || productCode == null || productCode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return shopId.trim() + "|" + productCode.trim();
|
||||
}
|
||||
|
||||
// ---------- scope 台账:断点游标合并写(铁律 30 / B84-01) ----------
|
||||
|
||||
/**
|
||||
|
||||
@@ -43,6 +43,8 @@ AIIMAGE_JD_COLLECT_IMAGE_MAX_PER_PRODUCT=200
|
||||
AIIMAGE_JD_COLLECT_STALE_MINUTES=60
|
||||
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN。
|
||||
AIIMAGE_JD_SKU_MAX_PER_PRODUCT=200
|
||||
# 商品上架配额:单个管理员(含其名下员工合计)可上架商品数上限,默认 5000,0=不限。
|
||||
AIIMAGE_JD_MAX_PRODUCTS_PER_ADMIN=5000
|
||||
# 京东采集的客户端兜底拉取白名单(v1.4 P0-1):默认值已含 JD_SHOP_COLLECT(见 application.yml)。
|
||||
# ⚠ 只有真的要覆盖整个白名单时才设 AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES——env 变量存在即生效,
|
||||
# 设成空串会把白名单清空(兜底拉取对 JD 形同关闭)。打开 AIIMAGE_CLIENT_TASK_PULL_ENABLED
|
||||
|
||||
@@ -177,6 +177,11 @@ aiimage:
|
||||
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN,
|
||||
# 防脏回传把整批撑爆。显式写在这里,不许只活在代码默认值里。
|
||||
sku-max-per-product: ${AIIMAGE_JD_SKU_MAX_PER_PRODUCT:200}
|
||||
# 商品上架配额(2026-11-15 用户口径):单个管理员(含其名下员工合计;公司超管按
|
||||
# 全公司合计)可上架的商品数上限,默认 5000;0=不限。计数源=biz_jd_product 按
|
||||
# owner uid 集计行数(上架功能的数据源就是京东数据库);站点超管不限额。
|
||||
# 校验出口=JdPublishQuotaService,商品上架建单入口落地时调用。
|
||||
max-products-per-admin: ${AIIMAGE_JD_MAX_PRODUCTS_PER_ADMIN:5000}
|
||||
# 设备日志对象存储:主机B 独立 MinIO(与业务 OSS 隔离,日志只保留 7 天)。
|
||||
# endpoint 未配置时日志上报/管理接口不可用(宁可失败也不静默落到业务桶)。
|
||||
# 桶的 7 天过期规则由运维用 mc 配置(与 retention-days 口径一致)。
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
-- 迁移 V199:京东商品人工编辑保护(行级「编辑/删除」,2026-11-15 用户口径)
|
||||
-- =============================================================
|
||||
-- 1. 变更目的:后管京东数据库列表加行级「编辑/删除」。采集回传的 upsertBatch
|
||||
-- UPDATE 段是整字段覆盖、收尾覆盖清理(purgeSupersededRows)会整行删旧数据、
|
||||
-- 重爬会把删掉的行当新行插回来——不加保护件,人工编辑/删除会在下一次采集时
|
||||
-- 被京麦值盖回/复活。本迁移补两个保护件(Expand-and-Contract,只加不改):
|
||||
--
|
||||
-- - biz_jd_product.manual_locked:人工编辑锁。后管编辑保存置 1;采集链路
|
||||
-- (upsert / 图片与 SKU 登记 / 覆盖清理)对锁定的行全部跳过——人工值优先。
|
||||
-- 单向锁(本轮不做「解锁恢复采集覆盖」)。
|
||||
-- - biz_jd_product_ignore:删除忽略表。后管删除成功后写入被删行的
|
||||
-- (company_id, shop_id, product_code) 三元组,采集回传对命中行跳过落库,
|
||||
-- 防止删除后的商品在重爬时复活。键形状与主表 uk_company_shop_code 同三元组。
|
||||
--
|
||||
-- 2. 形状口径:
|
||||
-- - manual_locked TINYINT NOT NULL DEFAULT 0:存量行全部视为「未人工编辑」,
|
||||
-- 采集链路行为不变(默认 0=不跳过)。
|
||||
-- - ignore 表不设外键、不级联:主表行被覆盖清理级联删掉时忽略记录仍保留
|
||||
-- (忽略语义本就独立于行存在)。
|
||||
-- - created_at DEFAULT CURRENT_TIMESTAMP,与 V193 synced_at 同口径。
|
||||
--
|
||||
-- 3. 数据量:ignore 表随删除操作增长,量级=人工删除次数(远小于商品行数);
|
||||
-- uk 三元组同时是采集侧过滤的查询键(按 company_id + 三元组 IN 查)。
|
||||
--
|
||||
-- 4. 可重跑性:ADD COLUMN 用「先判存在再加」的幂等形状(V195 补列先例);
|
||||
-- CREATE TABLE IF NOT EXISTS——中途失败重跑整条 no-op。
|
||||
--
|
||||
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW COLUMNS FROM biz_jd_product LIKE 'manual_locked'; -> 期望 tinyint(1) NOT NULL DEFAULT '0'
|
||||
-- SHOW CREATE TABLE biz_jd_product_ignore; -> 期望 uk_company_shop_code 唯一键
|
||||
-- 应用侧:MigrationInventoryTest 自动覆盖新迁移;JdProductUpdateServiceTest /
|
||||
-- JdResultIngestService 锁定跳过用例在 Phase 测试收口。
|
||||
--
|
||||
-- 6. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- DROP TABLE biz_jd_product_ignore;
|
||||
-- ALTER TABLE biz_jd_product DROP COLUMN manual_locked;
|
||||
-- DELETE FROM flyway_schema_history WHERE version='199';
|
||||
-- =============================================================
|
||||
|
||||
-- 幂等补列(V195 先例:information_schema 先判存在)
|
||||
SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'biz_jd_product'
|
||||
AND COLUMN_NAME = 'manual_locked');
|
||||
SET @sql = IF(@col_exists = 0,
|
||||
'ALTER TABLE biz_jd_product ADD COLUMN manual_locked TINYINT NOT NULL DEFAULT 0 COMMENT ''人工编辑锁(后管编辑保存置 1;采集 upsert/登记/覆盖清理对锁定的行全部跳过)'' AFTER synced_at',
|
||||
'SELECT ''manual_locked already exists, skip''');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_jd_product_ignore (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`company_id` BIGINT NOT NULL COMMENT '物化归属分公司(与主表 uk_company_shop_code 同口径)',
|
||||
`shop_id` VARCHAR(128) NOT NULL COMMENT '京东店铺标识(与主表 shop_id 同形状)',
|
||||
`product_code` VARCHAR(64) NOT NULL COMMENT '京东商品编码',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '写入时刻(后管删除成功时)',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_company_shop_code` (`company_id`, `shop_id`, `product_code`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='京东商品删除忽略表(后管删除成功即登记,采集回传对命中行跳过落库,防重爬复活)';
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V200__jd_product_group_shared_across_companies
|
||||
-- 需求:2026-11-15 用户定案「京东数据库不区分公司、属于公共的」「分组就是和亚马逊功能一样」
|
||||
-- 前版:V195(京东分组表按公司一套,uk_company_group_name)
|
||||
--
|
||||
-- 1. 变更目的:把「京东数据库」分组 biz_jd_product_group 的唯一键从"公司+名"退回【全平台】
|
||||
-- 键,与同批 jar 里已经摘掉公司谓词的读写侧对齐(分组挂到 AdminJdProductGroupController /
|
||||
-- JdProductGroupService,读写两侧都不再引用 company_id)。不退这一刀的后果不是"看不到",
|
||||
-- 是"写不进去":新代码的 INSERT 不带 company_id(实体字段不再赋值),旧键 (company_id, name)
|
||||
-- 在功能上"暂时还能用"——但它把第 2 家公司将来建的同名分组挡在同一行里,而这一版之后
|
||||
-- 系统里根本不存在"哪一家的分组"这个概念,键里留着公司维度就是一把没有对照物的锁。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- uk_company_group_name(company_id, name) -> uk_group_name(name)
|
||||
-- 键名复用 V151__rule_tables_shared_across_companies 的退键纪律(先加全局键、再摘公司键,
|
||||
-- 中间任一步失败时至少还有一个唯一键在守并发)。
|
||||
-- 同名组归并:V195 上线(2026-11-14)以来各公司可建同名组;退全局键前必须先归并——
|
||||
-- 每个分组名保留最小 id 一行,其余行的商品(biz_jd_product.group_id)改挂到保留行,
|
||||
-- 再删除多余组行。临时表 _v200_group_map(old_id, keep_id) 只记"要删的行"。
|
||||
-- 【company_id 列不 DROP】(V151 第 6 段同一理由):上一版 jar 的读写两侧还带着
|
||||
-- company_id(实体字段 + insert 列清单),删列与换键同批必然在混合窗口里打断旧 jar。
|
||||
-- 本版只把 DEFAULT 补上(NOT NULL DEFAULT 0):新 jar 的 INSERT 不带这一列,
|
||||
-- 靠 DEFAULT 0 落「平台公共」;历史行保留原公司号,只作"哪家客户端同步的"溯源标记。
|
||||
-- 【CompanyDefaultGuard 不登记本表】:该哨兵只盯"仍然按公司写"的表;本表自本版起
|
||||
-- 读写两侧都不分公司,喊"去摘 DEFAULT"会让人把唯一能兜住 NOT NULL 的默认值摘掉(1364)。
|
||||
--
|
||||
-- 3. 影响表与数据量:分组行数=公司数×用户自建组数(十级量级),归并扫描毫秒级;
|
||||
-- 商品侧 UPDATE 只动 group_id 指向被归并行的那部分(通常 0 行)。任何形态都在毫秒级,
|
||||
-- ADD UNIQUE 仍钉 ALGORITHM = INPLACE, LOCK = NONE,不给"顺手退化成交换锁"留机会。
|
||||
--
|
||||
-- 4. 可重跑性:归并段只在 uk_company_group_name 仍存在时执行;四条 DDL 都先查
|
||||
-- information_schema 再 PREPARE(V145 首例写法),重跑逐条 no-op。
|
||||
--
|
||||
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- ALTER TABLE biz_jd_product_group ADD UNIQUE KEY uk_company_group_name (company_id, name);
|
||||
-- ALTER TABLE biz_jd_product_group DROP INDEX uk_group_name;
|
||||
-- ALTER TABLE biz_jd_product_group MODIFY COLUMN company_id BIGINT NOT NULL
|
||||
-- COMMENT '归属分公司(分组按公司隔离,R4)';
|
||||
-- (jar 必须先回到带公司谓词的那版,否则"键按公司、代码不分公司"会让第 2 家建出
|
||||
-- 与第 1 家同键的行;归并掉的组行不可自动找回,回滚前先备份。)
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 同名组归并(只在公司键仍在时执行;每组保留最小 id) ----------
|
||||
|
||||
SET @v200_old_uk := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'uk_company_group_name');
|
||||
|
||||
CREATE TEMPORARY TABLE IF NOT EXISTS _v200_group_map (
|
||||
old_id BIGINT NOT NULL PRIMARY KEY,
|
||||
keep_id BIGINT NOT NULL
|
||||
) ENGINE = InnoDB;
|
||||
|
||||
-- 重复执行前先清空(Flyway 重跑整个文件时临时表可能已存在)。
|
||||
DELETE FROM _v200_group_map;
|
||||
|
||||
-- 每个分组名保留最小 id;其余行进归并映射。
|
||||
INSERT INTO _v200_group_map (old_id, keep_id)
|
||||
SELECT g.id, keep.first_id
|
||||
FROM biz_jd_product_group g
|
||||
JOIN (
|
||||
SELECT name, MIN(id) AS first_id
|
||||
FROM biz_jd_product_group
|
||||
GROUP BY name
|
||||
HAVING COUNT(*) > 1
|
||||
) dup ON dup.name = g.name
|
||||
JOIN (
|
||||
SELECT name, MIN(id) AS first_id
|
||||
FROM biz_jd_product_group
|
||||
GROUP BY name
|
||||
) keep ON keep.name = g.name
|
||||
WHERE g.id <> keep.first_id
|
||||
AND @v200_old_uk > 0;
|
||||
|
||||
-- 商品改挂保留组(只动指向被归并行的 group_id)。
|
||||
UPDATE biz_jd_product p
|
||||
JOIN _v200_group_map m ON p.group_id = m.old_id
|
||||
SET p.group_id = m.keep_id;
|
||||
|
||||
-- 删除被归并的组行。
|
||||
DELETE g FROM biz_jd_product_group g
|
||||
JOIN _v200_group_map m ON g.id = m.old_id;
|
||||
|
||||
DROP TEMPORARY TABLE IF EXISTS _v200_group_map;
|
||||
|
||||
-- ---------- 2. 分组表:先加全局键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'uk_group_name');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `biz_jd_product_group` ADD UNIQUE KEY `uk_group_name` (`name`), ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 3. 分组表:再摘公司键 ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'uk_company_group_name');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_jd_product_group` DROP INDEX `uk_company_group_name`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 4. 摘按公司取全量的二级索引(读侧已不按 company_id 筛) ----------
|
||||
|
||||
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND INDEX_NAME = 'idx_company');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_jd_product_group` DROP INDEX `idx_company`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 5. company_id 补 DEFAULT 0(新 INSERT 不带这一列,靠它满足 NOT NULL) ----------
|
||||
|
||||
SET @col_default := (SELECT COLUMN_DEFAULT FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND COLUMN_NAME = 'company_id');
|
||||
SET @v200_needs_default := (@col_default IS NULL OR (@col_default <> '0' AND @col_default <> 'NULL'));
|
||||
SET @sql := IF(@v200_needs_default,
|
||||
'ALTER TABLE `biz_jd_product_group` MODIFY COLUMN `company_id` BIGINT NOT NULL DEFAULT 0 COMMENT ''历史归属公司(V195~V199 按公司隔离时代遗留;2026-11-15 公共化后读写两侧不再引用,新行 0=平台公共)''',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
|
||||
--
|
||||
-- SELECT TABLE_NAME, INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
|
||||
-- FROM information_schema.STATISTICS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_jd_product_group' AND NON_UNIQUE = 0
|
||||
-- GROUP BY TABLE_NAME, INDEX_NAME;
|
||||
-- -> 期望恰好两行:PRIMARY(id)、uk_group_name(name@1);
|
||||
-- uk_company_group_name / idx_company 必须不在结果里。
|
||||
--
|
||||
-- SELECT COUNT(*) AS dup_group_names FROM (
|
||||
-- SELECT name FROM biz_jd_product_group GROUP BY name HAVING COUNT(*) > 1 LIMIT 1
|
||||
-- ) t;
|
||||
-- -> 期望 0(第 2 步 ADD UNIQUE 能建起的前提)。
|
||||
--
|
||||
-- SELECT COUNT(*) AS orphan_group_products FROM biz_jd_product p
|
||||
-- LEFT JOIN biz_jd_product_group g ON g.id = p.group_id
|
||||
-- WHERE p.group_id IS NOT NULL AND g.id IS NULL;
|
||||
-- -> 期望 0:归并后没有商品还挂着已删除的组行。
|
||||
--
|
||||
-- SHOW COLUMNS FROM biz_jd_product_group LIKE 'company_id';
|
||||
-- -> 期望 Null = NO、Default = 0。本版【故意保留列】:旧 jar 的读写两侧还引用它。
|
||||
--
|
||||
-- INSERT IGNORE 在退回全局键后(事务内跑完回滚,只插 ZZTEST 前缀):
|
||||
-- START TRANSACTION;
|
||||
-- INSERT INTO biz_jd_product_group (name) VALUES ('ZZTESTGROUP0001');
|
||||
-- INSERT INTO biz_jd_product_group (name) VALUES ('ZZTESTGROUP0001');
|
||||
-- SELECT COUNT(*) AS one_row FROM biz_jd_product_group WHERE name = 'ZZTESTGROUP0001';
|
||||
-- ROLLBACK;
|
||||
-- -> 期望 one_row = 1:同名第二次被 IGNORE 掉 = 键真的回到全平台一档,且
|
||||
-- company_id 由 DEFAULT 0 兜住(新 INSERT 不带这一列)。
|
||||
-- =============================================================
|
||||
@@ -38,7 +38,9 @@
|
||||
task_id = VALUES(task_id),
|
||||
shop_name = VALUES(shop_name),
|
||||
sku_id = VALUES(sku_id),
|
||||
item_num = VALUES(item_num),
|
||||
<!-- 货号不进 UPDATE 段(2026-11-15 用户口径「系统自行生成货号,不用之前的货号」):
|
||||
货号=行号(reassignItemNums 在落库后刷写,全局唯一、从 1 递增,行不变货号就不变),
|
||||
重爬命中已有行时不得把系统货号刷回京东原值。 -->
|
||||
sku_count = VALUES(sku_count),
|
||||
health_score = VALUES(health_score),
|
||||
title = VALUES(title),
|
||||
@@ -60,15 +62,33 @@
|
||||
synced_at = CURRENT_TIMESTAMP
|
||||
</insert>
|
||||
|
||||
<!-- 货号系统生成(2026-11-15 用户口径「我们系统自行生成货号 排序 不用之前的货号;
|
||||
从 1 开始递增或者随机数(唯一)」):行号即货号——全局唯一、从 1 递增、天然零竞争,
|
||||
行不变货号就不变(重爬命中已有行时货号稳定)。只在商品行落库后按本任务刷一次:
|
||||
新插入行的 item_num 是京东原值(暂存),刷成行号;已等于行号的行不重复写(幂等);
|
||||
manual_locked=1 的行不动(人工编辑过货号的人工值优先)。京东原货号仍在 attr_json
|
||||
的「货号」属性行留档(京麦原文随属性区同步),主字段货号一律系统形状。 -->
|
||||
<update id="reassignItemNums">
|
||||
UPDATE biz_jd_product
|
||||
SET item_num = CONVERT(id, CHAR)
|
||||
WHERE company_id = #{companyId}
|
||||
AND task_id = #{taskId}
|
||||
AND manual_locked = 0
|
||||
AND (item_num IS NULL OR item_num = '' OR item_num != CONVERT(id, CHAR))
|
||||
</update>
|
||||
|
||||
<!-- 覆盖清理候选行(重爬覆盖语义,2026-11-15):本任务成功收尾后,同一公司同一批店铺里
|
||||
不是本任务写、且所属任务已不在在飞(PENDING/RUNNING 不删——同店铺并发两单先收尾的
|
||||
单不得抹掉仍在跑的单的行,后收尾的单会在自己的收尾时清)的商品行。
|
||||
shop_id 取本任务落过的行的 DISTINCT 值(shop_id 缺省回落 shop_name,与 buildRow 同源),
|
||||
删除本体走 JdProductRowDeleteService#deleteRows(SKU/图片行级联),本查询只出 id。 -->
|
||||
删除本体走 JdProductRowDeleteService#deleteRows(SKU/图片行级联),本查询只出 id。
|
||||
V199:manual_locked=1 的行(后管人工编辑过)不进清理候选——人工值优先,重爬不得整行删掉。 -->
|
||||
<select id="selectSupersededProductIds" resultType="long">
|
||||
SELECT p.id
|
||||
FROM biz_jd_product p
|
||||
WHERE p.company_id = #{companyId}
|
||||
<!-- V199 覆盖清理候选必须排除 manual_locked=1 的行(V199 人工编辑锁) -->
|
||||
AND p.manual_locked = 0
|
||||
AND p.shop_id IN (
|
||||
SELECT DISTINCT shop_id FROM biz_jd_product
|
||||
WHERE company_id = #{companyId} AND task_id = #{taskId}
|
||||
@@ -81,15 +101,21 @@
|
||||
</select>
|
||||
|
||||
<!-- 后管只读页(Phase 5,v1.4)过滤面:公司(物化列 eq)、店铺名/商品编码/标题关键词
|
||||
(contains LIKE)、商品状态 eq、分组 eq、同步起止(datetime 闭区间)。
|
||||
(contains LIKE)、类目 eq、分组 eq、未分类(group_id IS NULL,店铺分类弹窗
|
||||
「未分类」范围)、已分类(group_id IS NOT NULL,页面筛选行「分类状态」档,
|
||||
2026-11-15 客户口径「查询已分类的跟未分类,分类好的可以不显示」)、
|
||||
同步起止(datetime 闭区间)。
|
||||
sale_status 筛选随 2026-11-15 客户口径撤掉(前端筛选框下线;列本身与详情/回传链不动)。
|
||||
全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 -->
|
||||
<sql id="productConds">
|
||||
<if test="companyId != null and companyId > 0">AND p.company_id = #{companyId}</if>
|
||||
<if test="shopName != null and shopName != ''">AND p.shop_name LIKE CONCAT('%', #{shopName}, '%')</if>
|
||||
<if test="productCode != null and productCode != ''">AND p.product_code LIKE CONCAT('%', #{productCode}, '%')</if>
|
||||
<if test="titleKeyword != null and titleKeyword != ''">AND p.title LIKE CONCAT('%', #{titleKeyword}, '%')</if>
|
||||
<if test="saleStatus != null and saleStatus != ''">AND p.sale_status = #{saleStatus}</if>
|
||||
<if test="category != null and category != ''">AND p.category_path = #{category}</if>
|
||||
<if test="groupId != null and groupId > 0">AND p.group_id = #{groupId}</if>
|
||||
<if test="ungrouped != null and ungrouped">AND p.group_id IS NULL</if>
|
||||
<if test="grouped != null and grouped">AND p.group_id IS NOT NULL</if>
|
||||
<if test="syncedFrom != null">AND p.synced_at >= #{syncedFrom}</if>
|
||||
<if test="syncedTo != null">AND p.synced_at <= #{syncedTo}</if>
|
||||
</sql>
|
||||
@@ -115,4 +141,26 @@
|
||||
ORDER BY p.synced_at DESC, p.id DESC
|
||||
LIMIT #{offset}, #{limit}
|
||||
</select>
|
||||
|
||||
<!-- 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):本公司已落库行
|
||||
的 DISTINCT category_path(=京麦末级类目名,契约 §2.3 E3)+ 行数。
|
||||
空类目行不进下拉;companyId 为空(超管不选公司=全量)时跨公司去重。 -->
|
||||
<select id="selectProductCategories" resultType="com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo">
|
||||
SELECT p.category_path AS name, COUNT(*) AS productCount
|
||||
FROM biz_jd_product p
|
||||
WHERE p.category_path IS NOT NULL AND p.category_path != ''
|
||||
<if test="companyId != null">AND p.company_id = #{companyId}</if>
|
||||
GROUP BY p.category_path
|
||||
ORDER BY p.category_path
|
||||
</select>
|
||||
|
||||
<!-- 商品上架配额计数(JdPublishQuotaService):按 owner uid 集计 biz_jd_product 行数;
|
||||
uid 集=管理员本人+名下员工(公司超管=全公司成员),由服务侧保证非空
|
||||
(空集按 0 处理,不进 SQL)。user_id=任务 owner(V193 物化归属列)。 -->
|
||||
<select id="countByUserIds" resultType="long">
|
||||
SELECT COUNT(*)
|
||||
FROM biz_jd_product
|
||||
WHERE user_id IN
|
||||
<foreach collection="userIds" item="uid" open="(" separator="," close=")">#{uid}</foreach>
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@@ -88,7 +88,10 @@ class MigratedSqlEquivalenceTest {
|
||||
// 109 → 111:v1.4 Phase 5(2026-11-14)后管只读页在 JdProductMapper 新写 2 条只读 select
|
||||
//(countProducts + selectProductPage)。注意本格是「全部 XML 的 select 总数」(不走
|
||||
// NOT_MIGRATED 豁免——豁免只作用于等价性那支),新写 select 也计入本分母。
|
||||
private static final int XML_SELECT_TOTAL = 111;
|
||||
// 111 → 112:2026-11-15 类目筛选下拉在 JdProductMapper 新写 1 条 select
|
||||
//(selectProductCategories,DISTINCT category_path +行数),从来没有注解原文可对撞,
|
||||
// 逐条点名进 NOT_MIGRATED。
|
||||
private static final int XML_SELECT_TOTAL = 113;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -195,7 +198,10 @@ class MigratedSqlEquivalenceTest {
|
||||
// 注解时代没有原文可对撞,逐条点名留痕
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 157 → 159)。
|
||||
"JdProductMapper#countProducts",
|
||||
"JdProductMapper#selectProductPage");
|
||||
"JdProductMapper#selectProductPage",
|
||||
// 2026-11-15 类目筛选下拉(京麦末级类目 distinct +行数)新写 1 条 select,
|
||||
// 同样没有注解原文可对撞,点名留痕(XML_SELECT_TOTAL 同轮 111 → 112)。
|
||||
"JdProductMapper#selectProductCategories");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -118,7 +118,13 @@ class SqlLayeringConventionTest {
|
||||
// 159 → 160:v1.4 B102 SKU 矩阵在 JdProductSkuMapper 落 1 条写侧 insert
|
||||
//(upsertBatch,uk_product_sku(product_id,sku_id),ON DUPLICATE KEY UPDATE upsert-only——
|
||||
// 与 V198 迁移同窗、商品行 upsert 之后登记),全部新写,非迁移语句。
|
||||
private static final int XML_STATEMENT_TOTAL = 160;
|
||||
// 160 → 161:2026-11-15 类目筛选下拉在 JdProductMapper 落 1 条只读 select
|
||||
//(selectProductCategories,DISTINCT category_path +行数),全部新写,非迁移语句。
|
||||
// 162 → 163:2026-11-15 货号系统生成在 JdProductMapper 落 1 条写侧 update
|
||||
//(reassignItemNums,行号即货号 item_num = CONVERT(id, CHAR),按本任务刷、锁定行排除、
|
||||
// 幂等——已等于行号的行不重复写),全部新写,非迁移语句;同笔 upsertBatch 的 UPDATE 段
|
||||
// 摘掉 item_num 覆盖(语句数不变)。
|
||||
private static final int XML_STATEMENT_TOTAL = 163;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+14
-2
@@ -1181,8 +1181,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
for (Path file : files) {
|
||||
String rel = relativeKey(file);
|
||||
if (SHARED_TABLES_MUST_STAY_UNSCOPED.stream().anyMatch(rel::startsWith)) continue;
|
||||
if (executableLines(read(file)).stream()
|
||||
.anyMatch(line -> SHARED_TABLE_TYPE_ANCHORS.stream().anyMatch(line::contains))) {
|
||||
if (executableLines(read(file)).stream().anyMatch(CompanyIdParamGoesThroughReadScopeTest::hitsSharedTableAnchor)) {
|
||||
consumers.add(rel);
|
||||
}
|
||||
}
|
||||
@@ -1190,6 +1189,19 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
return consumers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 锚命中判定:先剥掉 {@code JdProductCategoryVo} 字样再比子串。锚 {@code ProductCategory}
|
||||
* 是子串匹配,而京东商品库自己的类目下拉 VO(biz_jd_product.category_path 聚合统计,
|
||||
* 与全平台共享的商品类目表毫无关系)名字里含这个子串——2026-11-15 实录:它把整个
|
||||
* {@code AdminJdProductController} 误拖进「共享表消费者」清单,controller 里正常按公司
|
||||
* 隔离取数的 company_id 行全被判违规。剥字样而非整行排除:同一行真引用
|
||||
* {@code ProductCategoryEntity} 时照样命中,护栏意图不削弱。
|
||||
*/
|
||||
private static boolean hitsSharedTableAnchor(String line) {
|
||||
String stripped = line.replace("JdProductCategoryVo", "");
|
||||
return SHARED_TABLE_TYPE_ANCHORS.stream().anyMatch(stripped::contains);
|
||||
}
|
||||
|
||||
/**
|
||||
* 断言 C 的探针驱动器:先确认这段样本真被切成"1 支收公司 id 参数、体内写了 readScope(" 的 handler,
|
||||
* 再跑 {@link Block#scopeCatchFailure()}。切不出 handler / 不认公司参数 / 没有 readScope( 这三种
|
||||
|
||||
@@ -78,7 +78,13 @@ class CatchSilenceRatchetTest {
|
||||
// 11-15 京东 B101/B102 收口抬 616 -> 619:三枚不重抛含 log(JdProductQueryService SKU 组合解析
|
||||
// 与 JdResultIngestService 单行 SKU 跳过两枚落 LOG_ONLY、JdProductSkuIngestService.writeJson
|
||||
// 序列化是 log+return),出处与误差方向逐处见 STRICT_TOTAL 上方 11-15 段;EMPTY 一格没涨。
|
||||
static final int GIVEN_NOT_RETHROW = 620;
|
||||
// 11-15 京东行级编辑+删除忽略(V199)抬 620 -> 624:三枚逐处记名——
|
||||
// JdProductUpdateService.rebuildAttrJson 读侧解析失败落 null(拒绝出口在块外)、
|
||||
// JdProductDeleteService.registerIgnoreRows 的逐条 DuplicateKeyException 幂等跳过(log.info)
|
||||
// 与外层登记失败 log.error 不推翻删除本体(log.error);另 1 枚来自同窗另一路会话的类目下拉
|
||||
// 在飞件(本笔 diff 只有上述 3 枚 NOT_RETHROW 形状,逐文件 HEAD 对比 JD 包净增 catch=5,
|
||||
// 实测读数 624 ⇒ 差的 1 枚不在本笔文件里,随该会话自己的收尾记名)。
|
||||
static final int GIVEN_NOT_RETHROW = 624;
|
||||
static final int GIVEN_LOG_ONLY = 251;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -386,7 +392,17 @@ class CatchSilenceRatchetTest {
|
||||
// 历史行读不到店铺名时对旧建单载荷 requestJson 做 objectMapper.readValue 兜底(解析失败
|
||||
// log.warn + return null,历史行少店铺名不判死)。同批 JdCollectTaskService 的 scope 解析
|
||||
// 私有副本是**搬家**进 JdScopeStateReader(同形状 catch 一删一增对冲),不占本格。
|
||||
static final int STRICT_TOTAL = 1098;
|
||||
// 11-15 京东行级编辑+删除忽略(V199,2026-11-15 用户口径「每条数据可以编辑/删除」)抬 1098 -> 1104:
|
||||
// 净新增 6 枚——① JdProductUpdateService.rebuildAttrJson 的 attr_json 读侧解析失败先落 null
|
||||
// 再按形状不识别拒绝(块体仅赋值,NOT_RETHROW;拒绝出口在块外,不算吞);
|
||||
// ② JdProductUpdateService.writeTabs 的 attr_json 序列化失败整笔拒绝(RETHROW,可安全重试);
|
||||
// ③ JdProductUpdateService.deleteImages 的桶对象删除失败整笔拒绝(RETHROW,与删除链同纪律,
|
||||
// 异常原文走 UserMessages.with 不进界面);④⑤ JdProductDeleteService.registerIgnoreRows 的
|
||||
// 逐条 DuplicateKeyException 幂等跳过(log.info,LOG_ONLY;MP 无 insert ignore)+外层登记失败
|
||||
// log.error 不推翻删除本体(LOG_ONLY,误差方向=重爬可能复活需人工补登记,已在文案点名);
|
||||
// ⑥ JdProductDeleteService 删库行失败 log.error 后重抛(RETHROW,桶已删需人工核对,只进 total
|
||||
// 与 RETHROW 下限格)。NOT_RETHROW/LOG_ONLY 两格随之各 +3/+2(见各自常量上方 11-15 段)。
|
||||
static final int STRICT_TOTAL = 1104;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -447,7 +463,13 @@ class CatchSilenceRatchetTest {
|
||||
// 11-15 京东 B101/B102 收口上调 380 -> 382,出处见 STRICT_TOTAL 上方 11-15 段:新增 5 枚中
|
||||
// 2 枚是 RETHROW(删除链的"桶已删、库行回滚"重抛 + 对象删除失败整批拒绝)。
|
||||
// 这是下限不是上限:重抛枚数变多 = 又有两处异常被改成往外走,只许涨。
|
||||
static final int RETHROW_FLOOR = 382;
|
||||
// 11-15 再下调 382 -> 381,出处点名:2026-11-15 客户口径「导出也不用」把京东数据库导出整段下线
|
||||
// (控制器 GET /export + JdProductQueryService.export/writeExportWorkbook 一起删),
|
||||
// `JdProductQueryService.writeExportWorkbook` 的 `catch (Exception ex) → log.warn +
|
||||
// BusinessException「导出京东数据库失败,请稍后重试」`是 RETHROW 形状,随死代码一起离开树;
|
||||
// 同窗撤掉的 sale_status 筛选参数无 catch。不重抛/只 log/空体三格上限原样未动(绿即未涨),
|
||||
// 没有任何一处「异常会往外走」被改回吞掉——这是整段功能下线,不是改出口方向。
|
||||
static final int RETHROW_FLOOR = 381;
|
||||
/**
|
||||
* 10-17 抬 559 -> 561,逐处记名(两处都是新增的 fail-open 证据读写,不是把已有出口改回吞掉):
|
||||
* 1){@code TaskHeartbeatLivenessService.stamp()}:心跳证据写失败只 WARN——心跳接口不许因为
|
||||
@@ -529,7 +551,7 @@ 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 = 620;
|
||||
static final int STRICT_NOT_RETHROW = 624;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
@@ -562,8 +584,13 @@ class CatchSilenceRatchetTest {
|
||||
* 块体只有一句带 {@code [task-evidence]} 锚点的 WARN(id+reason),坏行跳过、其余照删。
|
||||
* 同日 Phase 5.1 再抬 189 -> 190:登记行落库失败后的对象回收失败只 WARN(同上锚点),
|
||||
* 主错误仍由外层转业务错误;不吞主错误。
|
||||
* 11-15 抬 196 -> 198(V199 行级编辑+删除忽略,同窗另一路会话落码、本笔跑全量时补记):
|
||||
* {@code JdProductDeleteService.registerIgnoreRows} 的逐条 DuplicateKeyException 幂等跳过
|
||||
* (块内仅一句 log.info)+外层登记失败 log.error 不推翻删除本体(块内仅一句 log.error),
|
||||
* 出处即 STRICT_TOTAL 上方 11-15 V199 段的 ④⑤——该段写明「LOG_ONLY 随之 +2」但常量漏抬,
|
||||
* 两枚都是带锚点的 fail-open(MP 无 insert ignore),不是把已有出口改回吞掉。
|
||||
*/
|
||||
static final int STRICT_LOG_ONLY = 196; // 严格口径:块内每条顶层语句都是 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 = 198; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1、11-14 v1.4 建单 scope 行 DuplicateKeyException 复用先到行 +1,见 STRICT_TOTAL 上方)
|
||||
static final int STRICT_EMPTY = 56;
|
||||
|
||||
/**
|
||||
|
||||
+184
-136
@@ -12,19 +12,18 @@ import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
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.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 jakarta.servlet.http.HttpServletRequest;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
@@ -34,7 +33,6 @@ import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
@@ -50,16 +48,19 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情/导出)与分组管理入口。
|
||||
* v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情)与分组管理入口。
|
||||
*
|
||||
* <p>结构判据(照 {@code AdminAppearancePatentCleanItemsControllerTest} 双形态):
|
||||
* 端点只读、鉴权 seam、公司隔离正门、snake 参数带默认值、SQL 只落 XML;
|
||||
* 行为样本:mock HttpServletRequest 把 company 参数交给 readCompanyIdOrOwn 并装进 200 信封、
|
||||
* 端点只读、鉴权 seam、公司口径(读侧只剩超管筛选 superAdminScopedCompanyId,公共库不走
|
||||
* readCompanyIdOrOwn)、snake 参数带默认值、SQL 只落 XML;
|
||||
* 行为样本:mock HttpServletRequest 把 company 参数交给 superAdminScopedCompanyId 并装进 200 信封、
|
||||
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
|
||||
* tabs→attrGroups 解析与非法形状兜底(AC-7)。</p>
|
||||
* tabs→attrGroups 解析与非法形状兜底(AC-7)。
|
||||
* 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p>
|
||||
*/
|
||||
class AdminJdProductControllerTest {
|
||||
|
||||
@@ -82,15 +83,20 @@ class AdminJdProductControllerTest {
|
||||
assertTrue(source.contains("/api/admin/jd-products"), "端点必须挂在 /api/admin/jd-products");
|
||||
assertTrue(source.contains("@GetMapping"), "查询端点必须落在 @GetMapping");
|
||||
assertTrue(source.contains("\"/{id}\""), "详情端点必须是 GET /{id}");
|
||||
assertTrue(source.contains("\"/export\""), "导出端点必须是 GET /export");
|
||||
// 导出端点已随 2026-11-15 客户口径「导出也不用」下线(前端导出发送口同窗撤)——反向钉住防回潜。
|
||||
assertFalse(source.contains("\"/export\""), "导出端点必须已删除,不得回潜");
|
||||
// 删除入口(用户口径「后台删除数据的时候也要把桶对应的文件删除」):DELETE /{id} 单行
|
||||
// + POST /batch-delete 批量,先删桶、全成功才删库行(JdProductDeleteService 判据另钉)。
|
||||
assertTrue(source.contains("@DeleteMapping"), "删除端点必须落在 @DeleteMapping");
|
||||
assertTrue(source.contains("\"/batch-delete\""), "批量删除端点必须是 POST /batch-delete");
|
||||
assertTrue(source.contains("@Valid"), "批量删除请求体必须过 @Valid(ids 非空)");
|
||||
// 不得有 PUT:商品行只能被采集链回传覆盖,界面改名改值都不存在。
|
||||
assertFalse(source.contains("@PutMapping"),
|
||||
"京东数据库页不得有 PUT(商品行由采集回传覆盖,分组改排序落 AdminJdProductGroupController)");
|
||||
// 批量归类端点(店铺分类弹窗,2026-11-15):POST /batch-assign-group,归入/移出分类。
|
||||
assertTrue(source.contains("\"/batch-assign-group\""),
|
||||
"批量归类端点必须是 POST /batch-assign-group(店铺分类弹窗人工归类)");
|
||||
// PUT 旧绊线(「不得有 PUT:商品行只能被采集链回传覆盖」)已随后台「编辑商品」特性放行
|
||||
// (AdminJdProductController 的 @PutMapping("/{id}",JdProductUpdateService 承接);商品行
|
||||
// 采集回传覆盖链不变,人工改名只走这条 PUT。分组改排序仍落 AdminJdProductGroupController。
|
||||
assertTrue(source.contains("@PutMapping"), "编辑商品端点必须落在 @PutMapping(\"/{id}\")");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,22 +114,25 @@ class AdminJdProductControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void 公司隔离走readCompanyIdOrOwn() throws IOException {
|
||||
void 公司口径只剩超管筛选_公共库不走readCompanyIdOrOwn() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
assertTrue(source.contains("DataReadScope"), "公司隔离唯一出口是 DataReadScope");
|
||||
assertTrue(source.contains("readCompanyIdOrOwn"),
|
||||
"读侧必须走 readCompanyIdOrOwn:超管显式传才收窄,非超管强制本公司");
|
||||
assertFalse(source.contains("superAdminScopedCompanyId"),
|
||||
"不得走 superAdminScopedCompanyId:它对非超管返回 null=按行 company_id 查询时把整张表交给每一家");
|
||||
assertTrue(source.contains("DataReadScope"), "公司维度唯一出口是 DataReadScope");
|
||||
assertTrue(source.contains("superAdminScopedCompanyId"),
|
||||
"读侧(列表/类目)必须走 superAdminScopedCompanyId:只有站点超管显式传 company_id 才收窄"
|
||||
+ "(公司 tab 筛选管理员),其余请求全量(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」)");
|
||||
assertFalse(source.contains("readCompanyIdOrOwn"),
|
||||
"不得走 readCompanyIdOrOwn:它对非超管强制本公司,公共库对每一家管理员都是同一份全量");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分页参数snake且带默认值() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
for (String param : List.of("page_size", "shop_name", "product_code", "title_keyword",
|
||||
"sale_status", "group_id", "synced_from", "synced_to", "company_id")) {
|
||||
"group_id", "ungrouped", "grouped", "synced_from", "synced_to", "company_id")) {
|
||||
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
|
||||
}
|
||||
// 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。
|
||||
assertFalse(source.contains("\"sale_status\""), "sale_status 筛选参数必须已删除,不得回潜");
|
||||
assertTrue(source.contains("PageDefaults"), "page/page_size 默认值必须取 PageDefaults"
|
||||
+ "(page_size 默认 20=PageDefaults.JD_PRODUCTS_PAGE_SIZE);"
|
||||
+ "page 钳制防 (page-1)*page_size 溢出的行为样本见查询服务钳制支(铁律 15)");
|
||||
@@ -166,13 +175,13 @@ class AdminJdProductControllerTest {
|
||||
// ===================== 行为样本 =====================
|
||||
|
||||
@Test
|
||||
void 控制器把公司参数交给readCompanyIdOrOwn并把结果装进200信封() {
|
||||
void 控制器把公司参数交给superAdminScopedCompanyId并把结果装进200信封() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), authSupport,
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
permissionMenuService, dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -180,31 +189,31 @@ class AdminJdProductControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 超管显式传 company_id=5 ⇒ 正门把 5 交出来(不传时正门给 null=全量,同一行为样本家族)。
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
|
||||
// 超管显式传 company_id=5 ⇒ 超管筛选把 5 交出来(不传时给 null=全量,同一行为样本家族)。
|
||||
when(dataReadScope.superAdminScopedCompanyId(operator, 5L)).thenReturn(5L);
|
||||
JdProductPageVo pageVo = new JdProductPageVo();
|
||||
pageVo.setItems(List.of());
|
||||
pageVo.setTotal(0L);
|
||||
pageVo.setPage(1L);
|
||||
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
|
||||
when(queryService.page(1L, 20L, 5L, null, null, null, null, null, null, null)).thenReturn(pageVo);
|
||||
when(queryService.page(1L, 20L, 5L, null, null, null, null, null, null, null, null, null)).thenReturn(pageVo);
|
||||
|
||||
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
|
||||
null, null, 5L, request);
|
||||
null, null, null, null, 5L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
|
||||
verify(queryService).page(1L, 20L, 5L, null, null, null, null, null, null, null);
|
||||
verify(dataReadScope).superAdminScopedCompanyId(operator, 5L);
|
||||
verify(queryService).page(1L, 20L, 5L, null, null, null, null, null, null, null, null, null);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
|
||||
assertEquals(pageVo, response.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 控制器详情走同一鉴权正门并回详情() {
|
||||
void 类目下拉端点走同一超管筛选口径并回选项集() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), authSupport,
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -212,45 +221,74 @@ class AdminJdProductControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 详情不收 company 参数:超管不传=全量可见;非超管由正门强制本公司(服务按返回值收口)。
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, null)).thenReturn(null);
|
||||
JdProductDetailVo detailVo = new JdProductDetailVo();
|
||||
detailVo.setId(11L);
|
||||
when(queryService.detail(11L, null)).thenReturn(detailVo);
|
||||
when(dataReadScope.superAdminScopedCompanyId(operator, 5L)).thenReturn(5L);
|
||||
JdProductCategoryVo row = new JdProductCategoryVo();
|
||||
row.setName("艺考形体服");
|
||||
row.setProductCount(85L);
|
||||
when(queryService.categories(5L)).thenReturn(List.of(row));
|
||||
|
||||
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
|
||||
ApiResponse<List<JdProductCategoryVo>> response = controller.categories(5L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, null);
|
||||
verify(queryService).detail(11L, null);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess());
|
||||
assertEquals(detailVo, response.getData());
|
||||
verify(dataReadScope).superAdminScopedCompanyId(operator, 5L);
|
||||
verify(queryService).categories(5L);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "类目下拉与列表同一鉴权正门(200 信封)");
|
||||
assertEquals("艺考形体服", response.getData().get(0).getName(), "选项=已落库行的末级类目名");
|
||||
assertEquals(85L, response.getData().get(0).getProductCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除端点走同一正门并把服务回执装进200信封() {
|
||||
void 控制器详情走同一鉴权正门并回详情且不问公司() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, authSupport, mock(PermissionMenuService.class), dataReadScope);
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
JdProductDetailVo detailVo = new JdProductDetailVo();
|
||||
detailVo.setId(11L);
|
||||
when(queryService.detail(11L)).thenReturn(detailVo);
|
||||
|
||||
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
|
||||
|
||||
// 公共库详情没有公司维度:DataReadScope 不参与(防有人把公司收口接回来)。
|
||||
verifyNoInteractions(dataReadScope);
|
||||
verify(queryService).detail(11L);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess());
|
||||
assertEquals(detailVo, response.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除端点按公共库直判存在并把服务回执装进200信封() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
|
||||
mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
|
||||
JdProductDeleteVo receipt = new JdProductDeleteVo();
|
||||
receipt.setDeleted(1);
|
||||
receipt.setObjectsDeleted(9);
|
||||
receipt.setObjectsKept(2);
|
||||
when(deleteService.delete(List.of(11L), 5L)).thenReturn(receipt);
|
||||
when(deleteService.delete(List.of(11L))).thenReturn(receipt);
|
||||
|
||||
ApiResponse<JdProductDeleteVo> response = controller.delete(11L, 5L, request);
|
||||
ApiResponse<JdProductDeleteVo> response = controller.delete(11L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
|
||||
verify(deleteService).delete(List.of(11L), 5L);
|
||||
// 公共库写侧没有公司维度:不收 company_id、DataReadScope 不参与。
|
||||
verifyNoInteractions(dataReadScope);
|
||||
verify(deleteService).delete(List.of(11L));
|
||||
assertEquals(Boolean.TRUE, response.isSuccess());
|
||||
assertEquals(9, response.getData().getObjectsDeleted());
|
||||
}
|
||||
@@ -262,31 +300,7 @@ class AdminJdProductControllerTest {
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, authSupport, mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, null)).thenReturn(5L);
|
||||
when(deleteService.delete(List.of(11L, 12L), 5L))
|
||||
.thenThrow(new BusinessException("有 1 个商品不存在或不属于当前公司,请刷新后重试(本次未删除任何数据)"));
|
||||
|
||||
JdProductBatchDeleteRequest body = new JdProductBatchDeleteRequest();
|
||||
body.setIds(List.of(11L, 12L));
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.batchDelete(body, null, request));
|
||||
assertTrue(ex.getMessage().contains("本次未删除任何数据"), "整批拒绝的语义必须到界面");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 控制器导出走同一正门并回Excel响应() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), authSupport,
|
||||
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
|
||||
mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -294,21 +308,14 @@ class AdminJdProductControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
|
||||
byte[] payload = "xlsx-bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
when(queryService.export(5L, null, null, null, null, null, null, null)).thenReturn(payload);
|
||||
when(deleteService.delete(List.of(11L, 12L)))
|
||||
.thenThrow(new BusinessException("有 1 个商品不存在,请刷新后重试(本次未删除任何数据)"));
|
||||
|
||||
ResponseEntity<byte[]> response = controller.export(null, null, null, null, null, null, null,
|
||||
5L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
|
||||
verify(queryService).export(5L, null, null, null, null, null, null, null);
|
||||
assertEquals(MediaType.parseMediaType(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
|
||||
response.getHeaders().getContentType(), "导出必须是 xlsx Content-Type");
|
||||
assertTrue(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION).contains("filename*=UTF-8''"),
|
||||
"中文文件名必须带 filename* UTF-8 轨(DownloadHeaderUtil 双轨口径)");
|
||||
assertArrayEquals(payload, response.getBody(), "响应体必须原样是服务侧产出的字节");
|
||||
JdProductBatchDeleteRequest body = new JdProductBatchDeleteRequest();
|
||||
body.setIds(List.of(11L, 12L));
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.batchDelete(body, request));
|
||||
assertTrue(ex.getMessage().contains("本次未删除任何数据"), "整批拒绝的语义必须到界面");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -317,23 +324,23 @@ class AdminJdProductControllerTest {
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
|
||||
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
|
||||
service.page(0L, null, null, null, null, null, null, null, null, null);
|
||||
service.page(0L, null, null, null, null, null, null, null, null, null, null, null);
|
||||
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
|
||||
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), offset.capture(), limit.capture());
|
||||
isNull(), isNull(), isNull(), isNull(), offset.capture(), limit.capture());
|
||||
assertEquals(0L, offset.getValue());
|
||||
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
|
||||
|
||||
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
|
||||
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null);
|
||||
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null, null, null);
|
||||
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
|
||||
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
|
||||
any(), any(), offsetMax.capture(), limitMax.capture());
|
||||
any(), any(), any(), any(), offsetMax.capture(), limitMax.capture());
|
||||
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
|
||||
assertEquals(100, limitMax.getValue());
|
||||
}
|
||||
@@ -347,14 +354,9 @@ class AdminJdProductControllerTest {
|
||||
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
|
||||
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.page(1L, 20L, null, null, null, null, null, null, from, to));
|
||||
() -> service.page(1L, 20L, null, null, null, null, null, null, null, null, from, to));
|
||||
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
|
||||
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
// 导出与分页共用同一过滤面校验(同一个拒绝时机:不碰 mapper)。
|
||||
BusinessException exportEx = assertThrows(BusinessException.class,
|
||||
() -> service.export(null, null, null, null, null, null, from, to));
|
||||
assertTrue(exportEx.getMessage().contains("开始时间不能晚于结束时间"),
|
||||
"导出端点必须同样拒绝倒挂时间,不得绕过分页页签的校验口径");
|
||||
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -363,16 +365,78 @@ class AdminJdProductControllerTest {
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
|
||||
|
||||
// 超管显式传 5 ⇒ 按公司 5 筛(收窄);groupId ≤0 按没选分组处理;文本两侧空白剥掉。
|
||||
service.page(1L, 20L, 5L, " 店铺甲 ", " SKU-1 ", " 连衣裙 ", "上架中", 0L, null, null);
|
||||
verify(mapper).countProducts(eq(5L), eq("店铺甲"), eq("SKU-1"), eq("连衣裙"), eq("上架中"),
|
||||
isNull(), isNull(), isNull());
|
||||
// 类目(京麦末级类目名)走同一过滤面:传值原样直传、空白归 null。
|
||||
service.page(1L, 20L, 5L, " 店铺甲 ", " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 0L, null, null, null, null);
|
||||
verify(mapper).countProducts(eq(5L), eq("店铺甲"), eq("SKU-1"), eq("连衣裙"),
|
||||
eq("艺考形体服"), isNull(), isNull(), isNull(), isNull(), isNull());
|
||||
// 全量(scopedCompanyId=null)⇒ companyId 不过滤。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, null, null);
|
||||
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull());
|
||||
service.page(1L, 20L, null, null, null, null, null, null, null, null, null, null);
|
||||
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull());
|
||||
|
||||
// 未分类范围(店铺分类弹窗「未分类」页签):ungrouped=true 原样下推到 SQL 侧。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, null, null, null);
|
||||
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), eq(Boolean.TRUE), isNull(), isNull(), isNull());
|
||||
// ungrouped=false / 缺省按不过滤处理(Filter 归一成 null,不进 IS NULL 分支);
|
||||
// 与②「全量」那发同形状,累计 2 次。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, Boolean.FALSE, null, null, null);
|
||||
verify(mapper, times(2)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull());
|
||||
|
||||
// 已分类档(页面筛选行「分类状态」=已分类,2026-11-15 客户口径「分类好的可以不显示」反选):
|
||||
// grouped=true 原样下推到 SQL 侧(group_id IS NOT NULL),ungrouped 不动。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, null, Boolean.TRUE, null, null);
|
||||
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), eq(Boolean.TRUE), isNull(), isNull());
|
||||
// grouped=false / 缺省同口径归一成 null(不进 IS NOT NULL 分支);与②「全量」累计 3 次。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, null, Boolean.FALSE, null, null);
|
||||
verify(mapper, times(3)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类端点走同一鉴权正门且参数透传() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), updateService, authSupport,
|
||||
mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(updateService.assignGroup(List.of(11L, 12L), 3L)).thenReturn(2);
|
||||
|
||||
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest body =
|
||||
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
|
||||
body.setIds(List.of(11L, 12L));
|
||||
body.setGroupId(3L);
|
||||
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
|
||||
|
||||
// 公共库写侧没有公司维度:不收 company_id、DataReadScope 不参与。
|
||||
verifyNoInteractions(dataReadScope);
|
||||
verify(updateService).assignGroup(List.of(11L, 12L), 3L);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
|
||||
assertEquals(2, response.getData(), "回执=实际更新的行数");
|
||||
|
||||
// 业务失败(目标分类不存在)文案原样透出,不吞。
|
||||
when(updateService.assignGroup(List.of(11L), 404L))
|
||||
.thenThrow(new BusinessException("分类不存在,请刷新分类后重试"));
|
||||
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest ghostBody =
|
||||
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
|
||||
ghostBody.setIds(List.of(11L));
|
||||
ghostBody.setGroupId(404L);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.batchAssignGroup(ghostBody, request));
|
||||
assertTrue(ex.getMessage().contains("分类不存在"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -402,7 +466,7 @@ class AdminJdProductControllerTest {
|
||||
image.setHeight(800);
|
||||
when(imageMapper.selectList(any())).thenReturn(List.of(image));
|
||||
|
||||
JdProductDetailVo vo = service.detail(11L, 5L);
|
||||
JdProductDetailVo vo = service.detail(11L);
|
||||
|
||||
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
|
||||
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
|
||||
@@ -433,7 +497,7 @@ class AdminJdProductControllerTest {
|
||||
JdProductEntity broken = productEntity(11L);
|
||||
broken.setAttrJson("{\"tabs\": [broken");
|
||||
when(mapper.selectById(11L)).thenReturn(broken);
|
||||
JdProductDetailVo brokenVo = service.detail(11L, 5L);
|
||||
JdProductDetailVo brokenVo = service.detail(11L);
|
||||
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
|
||||
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
|
||||
|
||||
@@ -441,7 +505,7 @@ class AdminJdProductControllerTest {
|
||||
JdProductEntity foreign = productEntity(11L);
|
||||
foreign.setAttrJson("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}");
|
||||
when(mapper.selectById(11L)).thenReturn(foreign);
|
||||
JdProductDetailVo foreignVo = service.detail(11L, 5L);
|
||||
JdProductDetailVo foreignVo = service.detail(11L);
|
||||
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
|
||||
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
|
||||
"未识别属性不丢弃:原文兜底透出(AC-7)");
|
||||
@@ -450,7 +514,7 @@ class AdminJdProductControllerTest {
|
||||
JdProductEntity blank = productEntity(11L);
|
||||
blank.setAttrJson(null);
|
||||
when(mapper.selectById(11L)).thenReturn(blank);
|
||||
JdProductDetailVo blankVo = service.detail(11L, 5L);
|
||||
JdProductDetailVo blankVo = service.detail(11L);
|
||||
assertTrue(blankVo.getAttrGroups().isEmpty());
|
||||
assertNull(blankVo.getAttrJsonRaw());
|
||||
}
|
||||
@@ -482,7 +546,7 @@ class AdminJdProductControllerTest {
|
||||
brokenJson.setSaleAttrsJson("[{\"name\":");
|
||||
when(skuMapper.selectList(any())).thenReturn(List.of(first, brokenJson));
|
||||
|
||||
JdProductDetailVo vo = service.detail(11L, 5L);
|
||||
JdProductDetailVo vo = service.detail(11L);
|
||||
|
||||
assertEquals(2, vo.getSkus().size(), "京麦那 12 行矩阵按入库行下发(抽屉渲染的唯一来源)");
|
||||
JdProductDetailVo.SkuVo sku = vo.getSkus().get(0);
|
||||
@@ -499,40 +563,24 @@ class AdminJdProductControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void 详情公司越界按不存在拒绝() {
|
||||
void 详情按公共库直取_缺失按不存在拒绝() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
|
||||
// 公共库(2026-11-15 用户定案):详情没有公司维度,别家公司时代的行照样可读。
|
||||
JdProductEntity row = productEntity(11L);
|
||||
row.setCompanyId(6L);
|
||||
when(mapper.selectById(11L)).thenReturn(row);
|
||||
assertNotNull(service.detail(11L));
|
||||
|
||||
// 非超管(scopedCompanyId=5):行属公司 6 ⇒ 按「商品不存在」拒绝,不泄露跨公司行的存在性。
|
||||
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, 5L));
|
||||
// 行不存在 ⇒ 按「商品不存在」拒绝。
|
||||
when(mapper.selectById(11L)).thenReturn(null);
|
||||
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L));
|
||||
assertTrue(ex.getMessage().contains("商品不存在"));
|
||||
// 超管不选公司(null)=全量可见。
|
||||
assertNotNull(service.detail(11L, null));
|
||||
// id 非法同样拒绝。
|
||||
assertThrows(BusinessException.class, () -> service.detail(0L, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 导出超上限按业务错误拒绝且不取数() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(JdProductQueryService.EXPORT_MAX_ROWS + 1);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.export(null, null, null, null, null, null, null, null));
|
||||
assertTrue(ex.getMessage().contains("超过导出上限"),
|
||||
"超上限必须给「缩小筛选范围」的可读文案,不能让用户等一次注定 OOM 的全量查询");
|
||||
verify(mapper, never()).selectProductPage(any(), any(), any(), any(), any(), any(), any(),
|
||||
any(), anyLong(), anyInt());
|
||||
assertThrows(BusinessException.class, () -> service.detail(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -548,8 +596,8 @@ class AdminJdProductControllerTest {
|
||||
grouped.setGroupId(3L);
|
||||
JdProductEntity missing = productEntity(2L);
|
||||
missing.setGroupId(99L);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
|
||||
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
|
||||
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
anyLong(), anyInt())).thenReturn(List.of(grouped, missing));
|
||||
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity group =
|
||||
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity();
|
||||
@@ -557,7 +605,7 @@ class AdminJdProductControllerTest {
|
||||
group.setName("秋冬款");
|
||||
when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group));
|
||||
|
||||
JdProductPageVo vo = service.page(1L, 20L, 5L, null, null, null, null, null, null, null);
|
||||
JdProductPageVo vo = service.page(1L, 20L, 5L, null, null, null, null, null, null, null, null, null);
|
||||
|
||||
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
|
||||
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
|
||||
|
||||
+25
-33
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
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;
|
||||
@@ -36,9 +37,10 @@ import static org.mockito.Mockito.when;
|
||||
* 京东商品删除编排判据(用户口径「后台删除数据的时候也要把桶对应的文件删除」)。
|
||||
*
|
||||
* <p>钉四件事:①<b>先删桶、全成功才删库行</b>——桶失败时库行删除出口必须零调用
|
||||
* (库行先消失就再没人知道该删哪些 key,对象成永久孤儿);②共用对象不删(同公司
|
||||
* 同内容同 key,删一个商品的图不能把别的商品搞裂图);③归属先判、越界整批拒绝
|
||||
* (不做部分删除);④前缀外的 key 不动手(只留 WARN),防脏数据把删除扩到别的桶前缀。</p>
|
||||
* (库行先消失就再没人知道该删哪些 key,对象成永久孤儿);②共用对象不删(同内容同 key,
|
||||
* 删一个商品的图不能把别的商品搞裂图);③存在先判、缺失整批拒绝(不做部分删除);
|
||||
* ④前缀外的 key 不动手(只留 WARN),防脏数据把删除扩到别的桶前缀。
|
||||
* 公共库无公司维度(2026-11-15 用户定案):删除按 id 直判存在性,不再按 company_id 收口。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdProductDeleteServiceTest {
|
||||
@@ -50,6 +52,8 @@ class JdProductDeleteServiceTest {
|
||||
@Mock
|
||||
private JdProductImageMapper jdProductImageMapper;
|
||||
@Mock
|
||||
private JdProductIgnoreMapper jdProductIgnoreMapper;
|
||||
@Mock
|
||||
private JdProductRowDeleteService jdProductRowDeleteService;
|
||||
@Mock
|
||||
private OssStorageService ossStorageService;
|
||||
@@ -63,7 +67,7 @@ class JdProductDeleteServiceTest {
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductImageEntity.class);
|
||||
service = new JdProductDeleteService(jdProductMapper, jdProductImageMapper,
|
||||
jdProductRowDeleteService, ossStorageService);
|
||||
jdProductIgnoreMapper, jdProductRowDeleteService, ossStorageService);
|
||||
ReflectionTestUtils.setField(service, "bucket", "jd-products");
|
||||
ReflectionTestUtils.setField(service, "keyPrefix", "jd-products/");
|
||||
}
|
||||
@@ -90,7 +94,7 @@ class JdProductDeleteServiceTest {
|
||||
@Test
|
||||
void 先删桶_全成功才删库行() {
|
||||
givenOwnedRows(List.of(11L));
|
||||
// selectList 依次被调:①商品归属闸 ②图片行取数 ③共用性回查(mock 不看 wrapper 条件,
|
||||
// selectList 依次被调:①商品存在闸 ②图片行取数 ③共用性回查(mock 不看 wrapper 条件,
|
||||
// 所以回查那次显式给空——没人引用这张图,才能真的删)。
|
||||
when(jdProductMapper.selectList(any())).thenReturn(List.of(productRow(11L)));
|
||||
when(jdProductImageMapper.selectList(any()))
|
||||
@@ -98,7 +102,7 @@ class JdProductDeleteServiceTest {
|
||||
.thenReturn(List.of());
|
||||
when(jdProductRowDeleteService.deleteRows(List.of(11L))).thenReturn(1);
|
||||
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L), COMPANY_ID);
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L));
|
||||
|
||||
// 顺序:removeObject 先于 deleteRows。
|
||||
var inOrder = org.mockito.Mockito.inOrder(ossStorageService, jdProductRowDeleteService);
|
||||
@@ -117,7 +121,7 @@ class JdProductDeleteServiceTest {
|
||||
doThrow(new RuntimeException("oss 5xx"))
|
||||
.when(ossStorageService).removeObject(anyString(), anyString());
|
||||
|
||||
assertThatThrownBy(() -> service.delete(List.of(11L), COMPANY_ID))
|
||||
assertThatThrownBy(() -> service.delete(List.of(11L)))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("本次未删除任何数据");
|
||||
|
||||
@@ -127,14 +131,14 @@ class JdProductDeleteServiceTest {
|
||||
@Test
|
||||
void 被其他商品共用的对象保留不删() {
|
||||
givenOwnedRows(List.of(11L));
|
||||
// selectList 依次被调:①商品归属闸 ②图片行取数 ③按 key 反查别的商品的共用性回查
|
||||
// selectList 依次被调:①商品存在闸 ②图片行取数 ③按 key 反查别的商品的共用性回查
|
||||
//(回查返回 99 号商品也引用同一 key ⇒ 保留)。
|
||||
when(jdProductImageMapper.selectList(any()))
|
||||
.thenReturn(List.of(image(11L, "jd-products/5/shared.jpg")))
|
||||
.thenReturn(List.of(image(99L, "jd-products/5/shared.jpg")));
|
||||
when(jdProductRowDeleteService.deleteRows(List.of(11L))).thenReturn(1);
|
||||
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L), COMPANY_ID);
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L));
|
||||
|
||||
verify(ossStorageService, never()).removeObject(anyString(), anyString());
|
||||
assertThat(vo.getObjectsDeleted()).isZero();
|
||||
@@ -144,17 +148,22 @@ class JdProductDeleteServiceTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void 越界或缺失的行整批拒绝_不做部分删除() {
|
||||
// 请求 2 行,归属闸只找到 1 行(另一行不存在/不属于本公司)。
|
||||
void 存在闸不分公司_缺失的行整批拒绝_不做部分删除() {
|
||||
// 公共库(2026-11-15 用户定案):存在闸 wrapper 不带 company_id 谓词,任何公司的行都可删。
|
||||
// 请求 2 行,存在闸只找到 1 行(另一行不存在)⇒ 整批拒绝。
|
||||
JdProductEntity row = new JdProductEntity();
|
||||
row.setId(11L);
|
||||
row.setCompanyId(COMPANY_ID);
|
||||
when(jdProductMapper.selectList(any(Wrapper.class))).thenReturn(List.of(row));
|
||||
|
||||
assertThatThrownBy(() -> service.delete(List.of(11L, 12L), COMPANY_ID))
|
||||
assertThatThrownBy(() -> service.delete(List.of(11L, 12L)))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("本次未删除任何数据");
|
||||
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment()).doesNotContain("company_id");
|
||||
|
||||
verify(ossStorageService, never()).removeObject(anyString(), anyString());
|
||||
verify(jdProductRowDeleteService, never()).deleteRows(any());
|
||||
}
|
||||
@@ -166,7 +175,7 @@ class JdProductDeleteServiceTest {
|
||||
image(11L, "nanri-ai-images/legacy.jpg")));
|
||||
when(jdProductRowDeleteService.deleteRows(List.of(11L))).thenReturn(1);
|
||||
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L), COMPANY_ID);
|
||||
JdProductDeleteVo vo = service.delete(List.of(11L));
|
||||
|
||||
verify(ossStorageService, never()).removeObject(anyString(), anyString());
|
||||
assertThat(vo.getObjectsSkipped()).isEqualTo(1);
|
||||
@@ -175,10 +184,10 @@ class JdProductDeleteServiceTest {
|
||||
|
||||
@Test
|
||||
void 空清单与超上限都在入口拒绝() {
|
||||
assertThatThrownBy(() -> service.delete(List.of(), COMPANY_ID))
|
||||
assertThatThrownBy(() -> service.delete(List.of()))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择");
|
||||
assertThatThrownBy(() -> service.delete(null, COMPANY_ID))
|
||||
assertThatThrownBy(() -> service.delete(null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择");
|
||||
|
||||
@@ -186,28 +195,11 @@ class JdProductDeleteServiceTest {
|
||||
for (long id = 1; id <= JdProductDeleteService.MAX_BATCH + 1; id++) {
|
||||
tooMany.add(id);
|
||||
}
|
||||
assertThatThrownBy(() -> service.delete(tooMany, COMPANY_ID))
|
||||
assertThatThrownBy(() -> service.delete(tooMany))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("200");
|
||||
|
||||
verify(jdProductMapper, times(0)).selectList(any());
|
||||
verify(jdProductRowDeleteService, never()).deleteRows(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void 非超管按本公司收口_越公司行不可见() {
|
||||
// scopedCompanyId=5:归属闸 wrapper 带 company_id=5 ⇒ 别家行查不到 ⇒ 整批拒绝。
|
||||
JdProductEntity row = new JdProductEntity();
|
||||
row.setId(11L);
|
||||
row.setCompanyId(6L);
|
||||
when(jdProductMapper.selectList(any(Wrapper.class))).thenReturn(List.of());
|
||||
|
||||
assertThatThrownBy(() -> service.delete(List.of(11L), COMPANY_ID))
|
||||
.isInstanceOf(BusinessException.class);
|
||||
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("company_id");
|
||||
}
|
||||
}
|
||||
|
||||
+51
-56
@@ -11,7 +11,7 @@ import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
@@ -35,9 +35,10 @@ import static org.mockito.Mockito.when;
|
||||
/**
|
||||
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
|
||||
*
|
||||
* <p>判据:同公司重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行
|
||||
* (事务两步,AC-8)、越公司 id 操作按不存在拒绝(不泄露存在性)、productCount
|
||||
* 读侧现算统计(分组下拉展示用)。</p>
|
||||
* <p>判据(2026-11-15 用户定案「分组和亚马逊功能一样」=全平台一份,V200 退键后的服务形状):
|
||||
* 全局重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行(事务两步,AC-8,
|
||||
* 且脱组谓词不带 company_id)、越界 id 操作按不存在拒绝、company_id 列读写两侧都不再引用
|
||||
* (新行不带公司,DB DEFAULT 0 兜底)、productCount 读侧现算统计(分组下拉展示用)。</p>
|
||||
*/
|
||||
class JdProductGroupServiceTest {
|
||||
|
||||
@@ -45,29 +46,30 @@ class JdProductGroupServiceTest {
|
||||
private final JdProductMapper productMapper = mock(JdProductMapper.class);
|
||||
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
|
||||
|
||||
@BeforeEach
|
||||
void initTableInfo() {
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
|
||||
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
JdProductEntity.class);
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
|
||||
}
|
||||
|
||||
// ===================== 新建 =====================
|
||||
|
||||
@Test
|
||||
void 新建同公司重名拒绝且不落库() {
|
||||
void 新建重名拒绝且不落库() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.create(5L, " 秋冬款 ", 2));
|
||||
() -> service.create(" 秋冬款 ", 2));
|
||||
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
|
||||
assertTrue(ex.getMessage().contains("同名分组"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500");
|
||||
assertTrue(ex.getMessage().contains("同名分类"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500(2026-11-15 起界面措辞「分类」)");
|
||||
verify(groupMapper, never()).insert(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建成功落公司归属与归一名() {
|
||||
void 新建成功落归一名与排序且不带公司() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
when(groupMapper.insert(any(JdProductGroupEntity.class))).thenAnswer(invocation -> {
|
||||
JdProductGroupEntity group = invocation.getArgument(0);
|
||||
@@ -75,25 +77,21 @@ class JdProductGroupServiceTest {
|
||||
return 1;
|
||||
});
|
||||
|
||||
Long id = service.create(5L, " 秋冬款 ", 2);
|
||||
Long id = service.create(" 秋冬款 ", 2);
|
||||
|
||||
assertEquals(9L, id);
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
JdProductGroupEntity saved = captor.getValue();
|
||||
assertEquals(5L, saved.getCompanyId(), "归属公司来自隔离正门的 scopedCompanyId,不是请求体");
|
||||
assertNull(saved.getCompanyId(), "公共库新行不带公司(实体字段不赋值,DB DEFAULT 0=平台公共)");
|
||||
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
|
||||
assertEquals(2, saved.getSortOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建缺公司或空名直接拒绝() {
|
||||
// 超管没选公司(scopedCompanyId=null)=分组没有归属公司,直接拒绝。
|
||||
BusinessException noCompany = assertThrows(BusinessException.class,
|
||||
() -> service.create(null, "秋冬款", null));
|
||||
assertEquals(400, noCompany.getCode());
|
||||
void 新建空名直接拒绝() {
|
||||
BusinessException blankName = assertThrows(BusinessException.class,
|
||||
() -> service.create(5L, " ", null));
|
||||
() -> service.create(" ", null));
|
||||
assertEquals(400, blankName.getCode());
|
||||
verifyNoInteractions(groupMapper);
|
||||
}
|
||||
@@ -102,7 +100,7 @@ class JdProductGroupServiceTest {
|
||||
void 新建排序缺省归零() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.create(5L, "默认排序", null);
|
||||
service.create("默认排序", null);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
@@ -112,34 +110,32 @@ class JdProductGroupServiceTest {
|
||||
// ===================== 改名 =====================
|
||||
|
||||
@Test
|
||||
void 改名越公司id按不存在拒绝() {
|
||||
JdProductGroupEntity group = groupEntity(1L, 6L, "别家的组");
|
||||
when(groupMapper.selectById(1L)).thenReturn(group);
|
||||
void 改名不存在按不存在拒绝() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(null);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.rename(1L, 5L, "新名字", null));
|
||||
assertTrue(ex.getMessage().contains("分组不存在"),
|
||||
"越界 id 与 id 不存在是同一种响应,不泄露跨公司行的存在性");
|
||||
() -> service.rename(1L, "新名字", null));
|
||||
assertTrue(ex.getMessage().contains("分类不存在"));
|
||||
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名重名拒绝且不落库() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.rename(1L, 5L, "已有名", 3));
|
||||
() -> service.rename(1L, "已有名", 3));
|
||||
assertEquals(409, ex.getCode());
|
||||
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名成功带归一名与排序() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, 5L, " 新名 ", 7);
|
||||
service.rename(1L, " 新名 ", 7);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
@@ -149,10 +145,10 @@ class JdProductGroupServiceTest {
|
||||
|
||||
@Test
|
||||
void 改名排序不传保持原值() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, 5L, "只改名", null);
|
||||
service.rename(1L, "只改名", null);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
@@ -163,29 +159,31 @@ class JdProductGroupServiceTest {
|
||||
|
||||
@Test
|
||||
void 删除先把商品组置NULL再删分组行() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "秋冬款"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "秋冬款"));
|
||||
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
|
||||
|
||||
int detached = service.delete(1L, 5L);
|
||||
int detached = service.delete(1L);
|
||||
|
||||
assertEquals(3, detached, "返回实际脱组的商品行数(前端拿它做反馈,不猜)");
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(productMapper).update(any(), wrapperCaptor.capture());
|
||||
// 置 NULL 语义必须落在 SET group_id=NULL(商品保留,脱组即「未分组」),且限定本公司该组。
|
||||
// 置 NULL 语义必须落在 SET group_id=NULL(商品保留,脱组即「未分组」)。
|
||||
var setValues = UpdateWrapperProbe.setValues(wrapperCaptor.getValue());
|
||||
assertTrue(setValues.containsKey("group_id") && setValues.get("group_id") == null,
|
||||
"删除分组必须把商品 group_id 置 NULL(SET group_id=NULL),不是删商品行:实得 " + setValues);
|
||||
// 公共库:脱组谓词只限定该组,不带 company_id。
|
||||
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
|
||||
assertEquals(5L, ((Number) whereEq.get("company_id")).longValue(), "脱组必须限定本公司");
|
||||
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
|
||||
assertTrue(!whereEq.containsKey("company_id"),
|
||||
"分组公共化后脱组谓词不得再带 company_id:实得 " + whereEq);
|
||||
verify(groupMapper).deleteById(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除越公司id拒绝且一个字节都不写() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 6L, "别家的组"));
|
||||
void 删除不存在拒绝且一个字节都不写() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(null);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.delete(1L, 5L));
|
||||
assertThrows(BusinessException.class, () -> service.delete(1L));
|
||||
verifyNoInteractions(productMapper);
|
||||
verify(groupMapper, never()).deleteById(anyLong());
|
||||
}
|
||||
@@ -194,22 +192,23 @@ class JdProductGroupServiceTest {
|
||||
void 删除分组不存在直接拒绝() {
|
||||
when(groupMapper.selectById(404L)).thenReturn(null);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.delete(404L, null));
|
||||
assertThrows(BusinessException.class, () -> service.delete(404L));
|
||||
verifyNoInteractions(productMapper);
|
||||
}
|
||||
|
||||
// ===================== 列表(productCount 统计) =====================
|
||||
|
||||
@Test
|
||||
void 列表按排序返回且productCount现算() {
|
||||
JdProductGroupEntity first = groupEntity(2L, 5L, "晚出厂");
|
||||
@SuppressWarnings("unchecked")
|
||||
void 列表全平台一份不带公司谓词且productCount现算() {
|
||||
JdProductGroupEntity first = groupEntity(2L, "晚出厂");
|
||||
first.setSortOrder(0);
|
||||
JdProductGroupEntity second = groupEntity(1L, 5L, "早出厂");
|
||||
JdProductGroupEntity second = groupEntity(1L, "早出厂");
|
||||
second.setSortOrder(1);
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
|
||||
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
|
||||
|
||||
List<JdProductGroupVo> items = service.list(5L);
|
||||
List<JdProductGroupVo> items = service.list();
|
||||
|
||||
assertEquals(2, items.size());
|
||||
assertEquals("晚出厂", items.get(0).getName(), "selectList 的排序由 wrapper 决定,服务不重排");
|
||||
@@ -218,24 +217,20 @@ class JdProductGroupServiceTest {
|
||||
assertEquals(1, items.get(1).getSortOrder());
|
||||
verify(productMapper, times(2)).selectCount(any());
|
||||
assertNotNull(items.get(0).getCreatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 列表超管不选公司查全量() {
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
List<JdProductGroupVo> items = service.list(null);
|
||||
|
||||
assertTrue(items.isEmpty());
|
||||
verify(groupMapper).selectList(any());
|
||||
// 公共库:列表 wrapper 不带 company_id 谓词(历史行的 company_id 只是溯源标记)。
|
||||
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(groupMapper).selectList(captor.capture());
|
||||
assertTrue(!captor.getValue().getSqlSegment().contains("company_id"),
|
||||
"分组列表不得再按公司过滤(2026-11-15 公共化):实得 " + captor.getValue().getSqlSegment());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
private static JdProductGroupEntity groupEntity(long id, long companyId, String name) {
|
||||
private static JdProductGroupEntity groupEntity(long id, String name) {
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(id);
|
||||
group.setCompanyId(companyId);
|
||||
group.setCompanyId(5L);
|
||||
group.setName(name);
|
||||
group.setSortOrder(3);
|
||||
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
|
||||
|
||||
+100
-2
@@ -7,10 +7,12 @@ import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductIgnoreMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdCollectTaskCreateRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdIngestChunkRequest;
|
||||
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.vo.JdIngestChunkVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
@@ -84,6 +86,8 @@ class JdProductSyncServiceTest {
|
||||
private JdProductSkuIngestService jdProductSkuIngestService;
|
||||
@Mock
|
||||
private JdProductRowDeleteService jdProductRowDeleteService;
|
||||
@Mock
|
||||
private JdProductIgnoreMapper jdProductIgnoreMapper;
|
||||
@Spy
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -92,8 +96,11 @@ class JdProductSyncServiceTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
// MP 条件构造器在纯单测里必须先初始化实体 TableInfo(CollectDataCredentialFatalTest 同款)
|
||||
// MP 条件构造器在纯单测里必须先初始化实体 TableInfo(CollectDataCredentialFatalTest 同款)。
|
||||
// V199 保护闸的 LambdaQueryWrapper 也吃这两个实体的 lambda cache。
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), FileTaskEntity.class);
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), JdProductEntity.class);
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), JdProductIgnoreEntity.class);
|
||||
}
|
||||
|
||||
// ---------- 夹具 ----------
|
||||
@@ -177,6 +184,9 @@ class JdProductSyncServiceTest {
|
||||
lenient().when(adminUserMapper.selectById(USER_ID)).thenReturn(owner(COMPANY_ID));
|
||||
lenient().when(collectTaskService.readCreateRequest(any(FileTaskEntity.class))).thenReturn(createRequest());
|
||||
lenient().when(collectTaskService.findScopeRow(TASK_ID)).thenReturn(scopeRow());
|
||||
// V199 保护闸:默认无锁定行、无忽略三元组(保护用例各自覆盖自己的桩)。
|
||||
lenient().when(jdProductMapper.selectList(any())).thenReturn(List.of());
|
||||
lenient().when(jdProductIgnoreMapper.selectList(any())).thenReturn(List.of());
|
||||
}
|
||||
|
||||
// ---------- 判据 ----------
|
||||
@@ -206,7 +216,7 @@ class JdProductSyncServiceTest {
|
||||
assertThat(first.getJdOnlineAt()).as("上架时间与创建时间不是同一个值(京麦后台两列)")
|
||||
.isEqualTo(LocalDateTime.of(2026, 11, 12, 15, 3, 37));
|
||||
assertThat(first.getJdUpdatedAt()).isEqualTo(LocalDateTime.of(2026, 11, 13, 14, 6, 7));
|
||||
assertThat(first.getItemNum()).as("货号(京麦列表列,≠ skuId)").isEqualTo("956597306407");
|
||||
assertThat(first.getItemNum()).as("货号:回传面暂存京麦原值,落库后由 reassignItemNums 刷成行号(系统生成)").isEqualTo("956597306407");
|
||||
assertThat(first.getSkuCount()).isEqualTo(12);
|
||||
assertThat(first.getHealthScore()).isEqualTo(81);
|
||||
assertThat(first.getAttrCount()).as("detail 键数进 attr_count").isEqualTo(2);
|
||||
@@ -215,6 +225,52 @@ class JdProductSyncServiceTest {
|
||||
assertThat(first.getImageCount()).isZero().as("Phase 2 图片只记 tempKey 待位");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 落库后货号刷写为系统生成的行号() {
|
||||
// 2026-11-15 用户口径「系统自行生成货号,不用之前的货号;从 1 开始递增(唯一)」:
|
||||
// 行号即货号——落库后按本任务刷一次(幂等,锁定行不动)。
|
||||
stubHappyPath();
|
||||
|
||||
service.submitChunk(TASK_ID, chunk(item("10036442942137", "艺考形体服女")), true);
|
||||
|
||||
verify(jdProductMapper).reassignItemNums(COMPANY_ID, TASK_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 整批被保护不落库时不刷货号() {
|
||||
stubHappyPath();
|
||||
// 保护集:唯一一行命中锁定(后管编辑过)⇒ 本批零落库 ⇒ 货号刷写也不该发生。
|
||||
JdProductEntity locked = new JdProductEntity();
|
||||
locked.setShopId("shop-001");
|
||||
locked.setProductCode("10036442942137");
|
||||
when(jdProductMapper.selectList(any())).thenReturn(List.of(locked));
|
||||
when(jdProductIgnoreMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
JdIngestChunkVo vo = service.submitChunk(TASK_ID,
|
||||
chunk(item("10036442942137", "艺考形体服女")), true);
|
||||
|
||||
assertThat(vo.getUpserted()).isZero();
|
||||
verify(jdProductMapper, never()).upsertBatch(anyList());
|
||||
verify(jdProductMapper, never()).reassignItemNums(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 货号不随重爬覆盖_系统生成为行号_绊线() throws Exception {
|
||||
// 货号=行号(reassignItemNums 落库后刷写)的三个 SQL 侧前提,改回即红:
|
||||
// ① upsertBatch 的 UPDATE 段不得覆盖 item_num(否则重爬把系统货号刷回京东原值);
|
||||
// ② 刷写语句必须按行号 SET 且排除锁定行;③ 刷写必须限定本任务(不碰历史行)。
|
||||
String xml = Files.readString(Path.of("src/main/resources/mapper/jd/JdProductMapper.xml"));
|
||||
String upsert = xml.substring(xml.indexOf("upsertBatch"), xml.indexOf("reassignItemNums"));
|
||||
assertThat(upsert)
|
||||
.as("货号不进 upsertBatch 的 UPDATE 段(2026-11-15 用户口径:系统生成货号,重爬不得刷回京东原值)")
|
||||
.doesNotContain("item_num = VALUES(item_num)");
|
||||
String reassign = xml.substring(xml.indexOf("reassignItemNums"));
|
||||
assertThat(reassign)
|
||||
.contains("item_num = CONVERT(id, CHAR)")
|
||||
.contains("manual_locked = 0")
|
||||
.contains("task_id = #{taskId}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 同一批两次提交行数不增且无delete() {
|
||||
stubHappyPath();
|
||||
@@ -392,6 +448,48 @@ class JdProductSyncServiceTest {
|
||||
.anySatisfy(json -> assertThat(json).contains("覆盖清理失败"));
|
||||
}
|
||||
|
||||
// ---------- V199 保护闸:人工编辑锁与删除忽略 ----------
|
||||
|
||||
@Test
|
||||
void 人工编辑锁与删除忽略的行跳过落库不登记子表() {
|
||||
stubHappyPath();
|
||||
// 保护集:锁定行 10036442942137(manual_locked=1,后管编辑过)+ 忽略三元组 10036442942138(后管删过)
|
||||
JdProductEntity locked = new JdProductEntity();
|
||||
locked.setShopId("shop-001");
|
||||
locked.setProductCode("10036442942137");
|
||||
when(jdProductMapper.selectList(any())).thenReturn(List.of(locked));
|
||||
JdProductIgnoreEntity ignored = new JdProductIgnoreEntity();
|
||||
ignored.setCompanyId(COMPANY_ID);
|
||||
ignored.setShopId("shop-001");
|
||||
ignored.setProductCode("10036442942138");
|
||||
when(jdProductIgnoreMapper.selectList(any())).thenReturn(List.of(ignored));
|
||||
|
||||
JdIngestChunkVo vo = service.submitChunk(TASK_ID,
|
||||
chunk(item("10036442942137", "艺考形体服女"), item("10036442942138", "艺考形体服男"),
|
||||
item("10036442942139", "艺考形体服新")), true);
|
||||
|
||||
// 命中保护集的两行连同其图片/SKU 登记一起跳过;只有第三行落库
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<JdProductEntity>> rowsCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(jdProductMapper).upsertBatch(rowsCaptor.capture());
|
||||
assertThat(rowsCaptor.getValue()).extracting(JdProductEntity::getProductCode)
|
||||
.containsExactly("10036442942139");
|
||||
verify(jdProductImageIngestService, times(1)).registerTaskImages(
|
||||
any(), eq(COMPANY_ID), eq("10036442942139"), any());
|
||||
verify(jdProductSkuIngestService, times(1)).registerTaskSkus(
|
||||
any(), eq(COMPANY_ID), eq("10036442942139"), any());
|
||||
assertThat(vo.getUpserted()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 覆盖清理SQL必须排除人工编辑锁的行_绊线() throws Exception {
|
||||
// V199:人工编辑过的行不进覆盖清理候选——重爬不得整行删掉人工值。
|
||||
String xml = Files.readString(Path.of("src/main/resources/mapper/jd/JdProductMapper.xml"));
|
||||
String purge = xml.substring(xml.indexOf("selectSupersededProductIds"));
|
||||
assertThat(purge).contains("manual_locked = 0",
|
||||
"覆盖清理候选必须排除 manual_locked=1 的行(V199 人工编辑锁)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 覆盖清理SQL必须排除在飞任务行_绊线() throws Exception {
|
||||
// 同店铺并发两单:先收尾的单不得把仍在跑(PENDING/RUNNING)的单已落的行抹掉,
|
||||
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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 org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 后管「编辑京东商品」编排判据(PUT /api/admin/jd-products/{id},2026-11-15 用户口径)。
|
||||
*
|
||||
* <p>钉六件事:①存在闸(行不存在按不存在拒绝,零写;公共库无公司维度);②主字段全量保存即置人工编辑锁
|
||||
* {@code manual_locked=1}(V199——没有这个锁,编辑会被下一次采集 upsert 覆盖回去);
|
||||
* ③分组存在校验(分组 2026-11-15 起全平台一份,挂组只认存在性);④属性重建只覆写 attr_json 的 {@code tabs} 段、
|
||||
* images/productCode 等其它顶层键原样保留(铁律 30 形状),原文形状不识别时拒绝而不是静默重写;
|
||||
* ⑤SKU 按 (productId, skuId) 匹配改价改库存,缺失 skuId 拒绝;⑥删图=先删桶、共用对象保留、
|
||||
* image_count 按表实数刷新。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdProductUpdateServiceTest {
|
||||
|
||||
private static final Long PRODUCT_ID = 42L;
|
||||
private static final Long COMPANY_ID = 5L;
|
||||
|
||||
@Mock
|
||||
private JdProductMapper jdProductMapper;
|
||||
@Mock
|
||||
private JdProductSkuMapper jdProductSkuMapper;
|
||||
@Mock
|
||||
private JdProductImageMapper jdProductImageMapper;
|
||||
@Mock
|
||||
private JdProductGroupMapper jdProductGroupMapper;
|
||||
@Mock
|
||||
private OssStorageService ossStorageService;
|
||||
|
||||
private JdProductUpdateService service;
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
// MP 条件构造器在纯单测里必须先初始化实体 TableInfo(JdProductDeleteServiceTest 同款)。
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductSkuEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductImageEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new JdProductUpdateService(jdProductMapper, jdProductSkuMapper,
|
||||
jdProductImageMapper, jdProductGroupMapper, ossStorageService);
|
||||
ReflectionTestUtils.setField(service, "bucket", "jd-products");
|
||||
ReflectionTestUtils.setField(service, "keyPrefix", "jd-products/");
|
||||
}
|
||||
|
||||
// ---------- 夹具 ----------
|
||||
|
||||
private JdProductEntity productRow() {
|
||||
JdProductEntity row = new JdProductEntity();
|
||||
row.setId(PRODUCT_ID);
|
||||
row.setCompanyId(COMPANY_ID);
|
||||
row.setShopId("shop-001");
|
||||
row.setProductCode("1003668397262");
|
||||
row.setTitle("旧标题");
|
||||
row.setAttrJson("{\"tabs\":[{\"tab\":\"商品基本信息\",\"attrs\":[{\"key\":\"brand\",\"label\":\"品牌\",\"value\":\"花屿巷\"}]}],"
|
||||
+ "\"images\":[{\"type\":\"MAIN\",\"objectKey\":\"jd-products/5/aaa.jpg\"}],\"productCode\":\"1003668397262\"}");
|
||||
return row;
|
||||
}
|
||||
|
||||
private JdProductUpdateRequest mainFieldsOnly() {
|
||||
JdProductUpdateRequest body = new JdProductUpdateRequest();
|
||||
body.setTitle(" 新标题 ");
|
||||
body.setBrand(" 新品牌 ");
|
||||
body.setGroupId(null);
|
||||
return body;
|
||||
}
|
||||
|
||||
private void givenOwnedRow() {
|
||||
when(jdProductMapper.selectById(PRODUCT_ID)).thenReturn(productRow());
|
||||
}
|
||||
|
||||
/** 取 update 落下的 SET 键值对(paramNameValuePairs),供断言新值。 */
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> capturedSetValues() {
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
|
||||
return (Map<String, Object>) ReflectionTestUtils.getField(wrapper, "paramNameValuePairs");
|
||||
}
|
||||
|
||||
// ---------- 判据 ----------
|
||||
|
||||
@Test
|
||||
void 行不存在按不存在拒绝_公共库跨公司行可编辑() {
|
||||
// 公共库(2026-11-15 用户定案):行存在即可编辑,company_id 只是同步来源标记。
|
||||
JdProductEntity otherCompany = productRow();
|
||||
otherCompany.setCompanyId(99L);
|
||||
when(jdProductMapper.selectById(PRODUCT_ID)).thenReturn(otherCompany);
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
assertThat(service.update(PRODUCT_ID, mainFieldsOnly())).isEqualTo(PRODUCT_ID);
|
||||
|
||||
// 行不存在 ⇒ 按不存在拒绝,零写。
|
||||
when(jdProductMapper.selectById(PRODUCT_ID)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, mainFieldsOnly()))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("商品不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 主字段全量保存即置人工编辑锁() {
|
||||
givenOwnedRow();
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
|
||||
Long id = service.update(PRODUCT_ID, mainFieldsOnly());
|
||||
|
||||
assertThat(id).isEqualTo(PRODUCT_ID);
|
||||
Map<String, Object> values = capturedSetValues();
|
||||
// 主字段全量提交:trim 落值(title/brand)
|
||||
assertThat(values.values()).contains("新标题", "新品牌");
|
||||
// SET 段必须带 manual_locked(V199 人工编辑锁本体)
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).update(isNull(), captor.capture());
|
||||
assertThat(((LambdaUpdateWrapper<JdProductEntity>) captor.getValue()).getSqlSet())
|
||||
.contains("manual_locked");
|
||||
// 主字段全量提交:trim 落值(title/brand)
|
||||
assertThat(values.values()).contains("新标题").contains("新品牌");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分组必须存在_公共组无公司维度() {
|
||||
givenOwnedRow();
|
||||
JdProductUpdateRequest body = mainFieldsOnly();
|
||||
body.setGroupId(7L);
|
||||
// 分组 2026-11-15 起全平台一份:别家时代建的组(company_id=99)照样能挂。
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(7L);
|
||||
group.setCompanyId(99L);
|
||||
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
assertThat(service.update(PRODUCT_ID, body)).isEqualTo(PRODUCT_ID);
|
||||
|
||||
// 分组不存在 ⇒ 拒绝且零写(2026-11-15 起界面措辞「分类」)。
|
||||
JdProductUpdateRequest ghost = mainFieldsOnly();
|
||||
ghost.setGroupId(404L);
|
||||
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, ghost))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("分类不存在");
|
||||
// update 只剩成功挂组那 1 次:ghost 分支零写点(同用例前半段已成功写过一次,不能按 never 数)。
|
||||
verify(jdProductMapper, org.mockito.Mockito.times(1)).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
// ---------- 批量归类(店铺分类弹窗,2026-11-15) ----------
|
||||
|
||||
/** 取批量归类落下的 SET 键值对(paramNameValuePairs),供断言 groupId/ids 落值。 */
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> capturedAssignValues() {
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
|
||||
return (Map<String, Object>) ReflectionTestUtils.getField(wrapper, "paramNameValuePairs");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类成功_置分类并落人工编辑锁() {
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(7L);
|
||||
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(3);
|
||||
|
||||
// 入参含重复 id:去重后 1/2/3 三行
|
||||
int updated = service.assignGroup(List.of(1L, 1L, 2L, 3L), 7L);
|
||||
|
||||
assertThat(updated).isEqualTo(3);
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
|
||||
// SET 段必须同时带 group_id 与 manual_locked(归类即人工干预:置锁后覆盖清理不再删行)
|
||||
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
|
||||
// WHERE 段(IN ids)惰性构参:先触发 getSqlSegment 再读参数表,IN 值才落进 paramNameValuePairs。
|
||||
wrapper.getSqlSegment();
|
||||
Map<String, Object> values = capturedAssignValues();
|
||||
assertThat(values.values()).contains(7L, 1L, 2L, 3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类目标分类不存在拒绝且零写() {
|
||||
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(1L, 2L), 404L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("分类不存在");
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类空清单与超上限可读拒绝() {
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(), null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择要归类的商品");
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(0L, -1L), null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择要归类的商品");
|
||||
|
||||
List<Long> tooMany = new java.util.ArrayList<>();
|
||||
for (long i = 1; i <= 201; i++) {
|
||||
tooMany.add(i);
|
||||
}
|
||||
assertThatThrownBy(() -> service.assignGroup(tooMany, null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("单次最多归类 200");
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 移出分类_groupId置空仍落人工编辑锁() {
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(2);
|
||||
|
||||
int updated = service.assignGroup(List.of(5L, 6L), null);
|
||||
|
||||
assertThat(updated).isEqualTo(2);
|
||||
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
|
||||
// groupId=null 也显式落 SET(group_id=NULL=回到未分类),锁照落。
|
||||
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
|
||||
// 移出分类没有目标组:不查分组表。
|
||||
verify(jdProductGroupMapper, never()).selectById(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 属性重建只覆写tabs段其余顶层键保留() {
|
||||
givenOwnedRow();
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
JdProductUpdateRequest body = mainFieldsOnly();
|
||||
JdProductUpdateRequest.AttrGroupDto group = new JdProductUpdateRequest.AttrGroupDto();
|
||||
group.setGroupName("商品基本信息");
|
||||
JdProductUpdateRequest.AttrDto attr = new JdProductUpdateRequest.AttrDto();
|
||||
attr.setKey("brand");
|
||||
attr.setLabel("品牌");
|
||||
attr.setValue("新品牌值");
|
||||
group.setAttrs(List.of(attr));
|
||||
body.setAttrGroups(List.of(group));
|
||||
|
||||
service.update(PRODUCT_ID, body);
|
||||
|
||||
Map<String, Object> values = capturedSetValues();
|
||||
// 新 JSON 里有重建后的 tabs(新属性值落进去了),且 images/productCode 原样保留(铁律 30)
|
||||
Object newJson = values.values().stream()
|
||||
.filter(v -> v instanceof String s && s.contains("\"tabs\""))
|
||||
.findFirst().orElseThrow();
|
||||
assertThat((String) newJson).contains("新品牌值").contains("\"images\"").contains("1003668397262");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 属性原文形状不识别时拒绝编辑防丢原文() {
|
||||
JdProductEntity row = productRow();
|
||||
row.setAttrJson("not-a-contract-shape");
|
||||
when(jdProductMapper.selectById(PRODUCT_ID)).thenReturn(row);
|
||||
JdProductUpdateRequest body = mainFieldsOnly();
|
||||
body.setAttrGroups(List.of(new JdProductUpdateRequest.AttrGroupDto()));
|
||||
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, body))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("属性原文形状不识别");
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void SKU按skuId匹配改价格库存_缺失拒绝() {
|
||||
givenOwnedRow();
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
JdProductSkuEntity sku = new JdProductSkuEntity();
|
||||
sku.setId(900L);
|
||||
sku.setProductId(PRODUCT_ID);
|
||||
sku.setSkuId("10238877506570");
|
||||
when(jdProductSkuMapper.selectList(any())).thenReturn(List.of(sku));
|
||||
|
||||
JdProductUpdateRequest body = mainFieldsOnly();
|
||||
JdProductUpdateRequest.SkuEditDto edit = new JdProductUpdateRequest.SkuEditDto();
|
||||
edit.setSkuId("10238877506570");
|
||||
edit.setPrice(new BigDecimal("199.00"));
|
||||
edit.setStock(88);
|
||||
body.setSkus(List.of(edit));
|
||||
service.update(PRODUCT_ID, body);
|
||||
|
||||
ArgumentCaptor<Wrapper<JdProductSkuEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductSkuMapper).update(isNull(), captor.capture());
|
||||
Map<String, Object> values = (Map<String, Object>) ReflectionTestUtils.getField(
|
||||
(LambdaUpdateWrapper<JdProductSkuEntity>) captor.getValue(), "paramNameValuePairs");
|
||||
assertThat(values.values()).contains(new BigDecimal("199.00"), 88);
|
||||
|
||||
// 提交里有不存在的 skuId:整笔拒绝(行可能已被重新采集刷新,让用户刷新重试)
|
||||
JdProductUpdateRequest bad = mainFieldsOnly();
|
||||
JdProductUpdateRequest.SkuEditDto ghost = new JdProductUpdateRequest.SkuEditDto();
|
||||
ghost.setSkuId("ghost-sku");
|
||||
ghost.setPrice(BigDecimal.ONE);
|
||||
bad.setSkus(List.of(ghost));
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, bad))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("SKU 行不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删图先删桶_共用对象保留_计数按表实数刷() {
|
||||
givenOwnedRow();
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
|
||||
JdProductImageEntity owned = new JdProductImageEntity();
|
||||
owned.setId(1L);
|
||||
owned.setProductId(PRODUCT_ID);
|
||||
owned.setObjectKey("jd-products/5/aaa.jpg");
|
||||
JdProductImageEntity missing = new JdProductImageEntity();
|
||||
missing.setId(2L);
|
||||
missing.setProductId(999L);
|
||||
when(jdProductImageMapper.selectList(any()))
|
||||
// ① 归属校验:两张里有一张不属于本商品 → 整笔拒绝(本次未保存任何修改)
|
||||
.thenReturn(List.of(owned))
|
||||
// ② 共用性回查:同 key 被另一商品引用 → 保留对象
|
||||
.thenReturn(List.of(new JdProductImageEntity()));
|
||||
|
||||
JdProductUpdateRequest body = mainFieldsOnly();
|
||||
body.setDeleteImageIds(List.of(1L, 2L));
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, body))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("本次未删除任何数据");
|
||||
|
||||
// 修正归属:只删 1L;同 key 被别的商品引用 ⇒ 对象保留、只删登记行、计数刷新
|
||||
JdProductUpdateRequest fixed = mainFieldsOnly();
|
||||
fixed.setDeleteImageIds(List.of(1L));
|
||||
service.update(PRODUCT_ID, fixed);
|
||||
|
||||
verify(ossStorageService, never()).removeObject(eq("jd-products"), eq("jd-products/5/aaa.jpg"));
|
||||
verify(jdProductImageMapper).delete(any(Wrapper.class));
|
||||
// update 共 3 次:两次 service.update() 的主字段各 1 次(第一次归属拒绝虽已过主字段
|
||||
// 写点,但 @Transactional 会整笔回滚,DB 层零持久化)+ 删图后的计数刷新 1 次
|
||||
verify(jdProductMapper, org.mockito.Mockito.times(3)).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 价格区间倒挂与负库存可读拒绝() {
|
||||
givenOwnedRow();
|
||||
JdProductUpdateRequest badPrice = mainFieldsOnly();
|
||||
badPrice.setPriceMin(new BigDecimal("100"));
|
||||
badPrice.setPriceMax(new BigDecimal("50"));
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, badPrice))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("价格区间下限不能大于上限");
|
||||
|
||||
JdProductUpdateRequest badStock = mainFieldsOnly();
|
||||
badStock.setStockTotal(-1);
|
||||
assertThatThrownBy(() -> service.update(PRODUCT_ID, badStock))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("总库存不能为负数");
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
verify(jdProductSkuMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
verify(jdProductSkuMapper, never()).selectList(any());
|
||||
verify(jdProductImageMapper, never()).delete(any(Wrapper.class));
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 商品上架配额(JdPublishQuotaService)行为测试:默认 5000、0=不限、普通账号锚定到
|
||||
* created_by_id 管理员并按其团队 uid 集计数、站点超管豁免、恰好等于上限的边界放行、
|
||||
* 空集按 used=0 不进 SQL。判限口径=「管理员+名下员工合计」(2026-11-15 用户口径)。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdPublishQuotaServiceTest {
|
||||
|
||||
@Mock
|
||||
private AdminUserMapper adminUserMapper;
|
||||
@Mock
|
||||
private UserDataScopeSupport userDataScopeSupport;
|
||||
@Mock
|
||||
private JdProductMapper jdProductMapper;
|
||||
|
||||
private JdPublishQuotaService newService() {
|
||||
return new JdPublishQuotaService(adminUserMapper, userDataScopeSupport, jdProductMapper);
|
||||
}
|
||||
|
||||
private AdminUserEntity admin(long id) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setRole("admin");
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 普通账号:role 为空(resolveRole 返回 null),created_by_id 指向所属管理员。 */
|
||||
private AdminUserEntity employee(long id, long adminId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setCreatedById(adminId);
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 双重载(Long/实体)消歧:lambda 参数显式标注实体形状(argThat(...))。 */
|
||||
|
||||
@Test
|
||||
void 默认上限5000_超限拒绝且文案含占用与上限() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity employee = employee(9L, 5L);
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(admin(5L));
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
|
||||
.thenReturn(List.of(5L, 9L, 10L));
|
||||
when(jdProductMapper.countByUserIds(List.of(5L, 9L, 10L))).thenReturn(4990L);
|
||||
|
||||
assertThatThrownBy(() -> service.assertWithinQuota(employee, 20))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("4990")
|
||||
.hasMessageContaining("5000")
|
||||
.hasMessageContaining("管理员");
|
||||
// 普通账号必须锚定到所属管理员(uid=5)的团队集,而不是只数自己
|
||||
verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 恰好等于上限_放行() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity operator = admin(5L);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
|
||||
.thenReturn(List.of(5L, 9L));
|
||||
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(4990L);
|
||||
|
||||
assertThatCode(() -> service.assertWithinQuota(operator, 10)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 上限为0_整体放行且不查库() {
|
||||
JdPublishQuotaService service = newService();
|
||||
service.maxProductsPerAdmin = 0L;
|
||||
|
||||
assertThatCode(() -> service.assertWithinQuota(admin(5L), 999_999)).doesNotThrowAnyException();
|
||||
verifyNoInteractions(jdProductMapper, userDataScopeSupport, adminUserMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 站点超管_豁免不限额() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity siteSuperAdmin = new AdminUserEntity();
|
||||
siteSuperAdmin.setId(1L);
|
||||
siteSuperAdmin.setRole("super_admin");
|
||||
|
||||
assertThatCode(() -> service.assertWithinQuota(siteSuperAdmin, 999_999)).doesNotThrowAnyException();
|
||||
verifyNoInteractions(jdProductMapper, userDataScopeSupport, adminUserMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 团队uid集为空_按used0处理且不进SQL() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity operator = admin(5L);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
|
||||
.thenReturn(List.of());
|
||||
|
||||
// used=0:additional=5000 恰好等于上限,放行
|
||||
assertThatCode(() -> service.assertWithinQuota(operator, 5000)).doesNotThrowAnyException();
|
||||
// additional=5001 超限,但空集不查库
|
||||
assertThatThrownBy(() -> service.assertWithinQuota(operator, 5001))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("0");
|
||||
verifyNoInteractions(jdProductMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 快照返回占用与上限() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity operator = admin(5L);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 5L)))
|
||||
.thenReturn(List.of(5L, 9L));
|
||||
when(jdProductMapper.countByUserIds(List.of(5L, 9L))).thenReturn(1234L);
|
||||
|
||||
JdPublishQuotaService.QuotaSnapshot snapshot = service.quotaOf(operator);
|
||||
assertThat(snapshot.used()).isEqualTo(1234L);
|
||||
assertThat(snapshot.limit()).isEqualTo(5000L);
|
||||
assertThat(snapshot.unlimited()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 普通账号读不到主管_回退按自己计() {
|
||||
JdPublishQuotaService service = newService();
|
||||
AdminUserEntity employee = employee(9L, 5L);
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(null);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L)))
|
||||
.thenReturn(List.of(9L));
|
||||
when(jdProductMapper.countByUserIds(List.of(9L))).thenReturn(5000L);
|
||||
|
||||
assertThatThrownBy(() -> service.assertWithinQuota(employee, 1))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("5000");
|
||||
verify(userDataScopeSupport).resolveVisibleUserIds(argThat((AdminUserEntity u) -> u != null && u.getId() == 9L));
|
||||
}
|
||||
}
|
||||
@@ -132,13 +132,6 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
|
||||
href: '/convert',
|
||||
permissionKeys: ['convert'],
|
||||
},
|
||||
{
|
||||
id: 'jd',
|
||||
name: '京东采集',
|
||||
desc: '采集京东店铺商品列表与详情全部属性,同步到后台京东数据库',
|
||||
href: '/jd-collect',
|
||||
permissionKeys: ['jd-collect', 'jd_collect'],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -287,7 +280,6 @@ export const TOOL_ICON_GRADIENTS: Record<string, string> = {
|
||||
shop: 'linear-gradient(180deg, #93C5FD, #3B82F6)',
|
||||
purchase: 'linear-gradient(180deg, #C4B5FD, #8B5CF6)',
|
||||
erp: 'linear-gradient(180deg, #F9A8D4, #EC4899)',
|
||||
jd: 'linear-gradient(180deg, #FCA5A5, #DC2626)',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -335,8 +327,6 @@ export const TOOL_ICON_SHAPES: Record<string, string> = {
|
||||
purchase: '<path d="M10 14 L34 14 L30 34 L14 34 Z"/><line x1="34" y1="14" x2="40" y2="14"/><line x1="40" y1="14" x2="38" y2="20"/><circle class="fill" cx="19" cy="39" r="3"/><circle class="fill" cx="33" cy="39" r="3"/>',
|
||||
// ERP:网格
|
||||
erp: '<rect x="8" y="8" width="32" height="32"/><line x1="24" y1="8" x2="24" y2="40"/><line x1="8" y1="24" x2="40" y2="24"/>',
|
||||
// 京东采集:商品袋
|
||||
jd: '<path d="M12 16 L36 16 L34 38 L14 38 Z"/><path d="M19 16 A 5 6 0 0 1 29 16"/><circle class="fill" cx="19" cy="26" r="2"/><circle class="fill" cx="29" cy="26" r="2"/>',
|
||||
}
|
||||
|
||||
export const TOOL_MAP: ReadonlyMap<string, ToolInfo> = new Map(
|
||||
@@ -359,7 +349,6 @@ export const TOOL_DETAILS: Readonly<Record<string, string>> = {
|
||||
qasin: '通过店小蜜导出出单 ASIN,上传后台,时不时排查是否还在店铺售卖,确保优质数据时刻在店。',
|
||||
scrape:
|
||||
'没排名、久未出单数据可优化删除;获取店铺所有数据的排名、品牌和销售情况。半个月到一个月复查一次品牌,确保数据没有被注册。',
|
||||
jd: '在本机已登录京麦的窗口里采集店铺商品(列表 + 详情全部属性 + 图片),同步到后台「京东数据库」。任务由本机客户端执行,提交后保持客户端在线。',
|
||||
}
|
||||
|
||||
export type VisibleGroup = ToolGroup & { tools: ToolInfo[] }
|
||||
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
TOOL_MAP,
|
||||
} from '../src/pages/amazon/tool-catalog.ts'
|
||||
|
||||
test('工具目录:21 个工具 id 唯一且每个都有图标与渐变配色', () => {
|
||||
test('工具目录:20 个工具 id 唯一且每个都有图标与渐变配色', () => {
|
||||
const ids = TOOL_GROUPS.flatMap((g) => g.tools.map((t) => t.id))
|
||||
assert.equal(ids.length, 21, '工具总数应为 21(前端9 + 运营10 + 后勤2;v1.4 前端组加京东采集)')
|
||||
assert.equal(ids.length, 20, '工具总数应为 20(前端8 + 运营10 + 后勤2;京东采集已撤出亚马逊目录,入口收敛到首页一级「京东」)')
|
||||
assert.equal(new Set(ids).size, ids.length, '工具 id 不应重复')
|
||||
for (const id of ids) {
|
||||
assert.ok(TOOL_ICON_SHAPES[id], `图标形状缺失: ${id}`)
|
||||
@@ -38,7 +38,7 @@ test('权限过滤:组键命中整组保留,未命中按工具权限过滤
|
||||
const frontOnly = filterGroupsByPermission(TOOL_GROUPS, ['brand_front_tools'])
|
||||
assert.equal(frontOnly.length, 1)
|
||||
assert.equal(frontOnly[0].key, 'front')
|
||||
assert.equal(frontOnly[0].tools.length, 9)
|
||||
assert.equal(frontOnly[0].tools.length, 8)
|
||||
|
||||
// 无组键时按单个工具权限过滤
|
||||
const partial = filterGroupsByPermission(TOOL_GROUPS, ['collect-data', 'publish'])
|
||||
@@ -88,3 +88,14 @@ test('工具目录:页头长描述(detail)只覆盖已知工具,且不
|
||||
assert.ok(toolsWithHref?.href, `detail 只应用于有页面的工具: ${id}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('工具目录:京东不出现在亚马逊这边(入口收敛到首页一级「京东」)', () => {
|
||||
const ids = TOOL_GROUPS.flatMap((g) => g.tools.map((t) => t.id))
|
||||
assert.ok(!ids.includes('jd'), '亚马逊工具目录不应再挂京东采集卡片')
|
||||
assert.ok(
|
||||
!TOOL_GROUPS.some((g) => g.tools.some((t) => t.name.includes('京东'))),
|
||||
'亚马逊工具目录不应出现任何京东命名的工具卡',
|
||||
)
|
||||
assert.ok(!('jd' in TOOL_ICON_GRADIENTS) && !('jd' in TOOL_ICON_SHAPES) && !('jd' in TOOL_DETAILS),
|
||||
'亚马逊目录的图标/渐变/详情表不应残留 jd 条目')
|
||||
})
|
||||
|
||||
@@ -5,14 +5,16 @@ import { join } from 'node:path'
|
||||
|
||||
/** v1.4 AC-1 用户端入口契约(蓝图 docs/ITERATION_PLAN.md §3.2 / §4 Phase 5)。
|
||||
*
|
||||
* 「京东采集」以工具台卡片 + 路由 + endpoints 组三件接入用户端(照工具台既有形状):
|
||||
* 工具卡必须声明非空 permissionKeys(用户端工具按后端 app 菜单 column_key 过滤显隐),
|
||||
* 「京东采集」以工具台卡片 + 路由 + endpoints 组三件接入用户端:
|
||||
* 2026-11-15 用户拍板——卡片不再挂在亚马逊工具台(pages/amazon/tool-catalog.ts,
|
||||
* 不含京东的绊线在 amazon-tool-catalog.test.ts),收敛到首页一级「京东」工作台
|
||||
* 自己的目录(pages/jd/tool-catalog.ts,显隐收口在工具台内部)。
|
||||
* 路由 /jd-collect,endpoints.ts 有 jdCollect 组。Pending 期整组 skip;
|
||||
* Phase 5 落地后去掉 skip 跑绿。
|
||||
*/
|
||||
|
||||
const ROUTER = join(process.cwd(), 'src', 'router', 'index.ts')
|
||||
const TOOL_CATALOG = join(process.cwd(), 'src', 'pages', 'amazon', 'tool-catalog.ts')
|
||||
const JD_TOOL_CATALOG = join(process.cwd(), 'src', 'pages', 'jd', 'tool-catalog.ts')
|
||||
const ENDPOINTS = join(process.cwd(), 'src', 'shared', 'api', 'endpoints.ts')
|
||||
|
||||
function readIfExists(path: string, what: string): string {
|
||||
@@ -25,12 +27,12 @@ test('路由注册京东采集页', () => {
|
||||
'router 缺 /jd-collect 路由')
|
||||
})
|
||||
|
||||
test('工具台卡片声明京东工具且带权限键', () => {
|
||||
const catalog = readIfExists(TOOL_CATALOG, 'tool-catalog.ts')
|
||||
assert.ok(catalog.includes('jd-collect') || catalog.includes('京东采集'),
|
||||
'TOOL_GROUPS 缺京东采集工具卡')
|
||||
assert.ok(/jd[\s\S]{0,400}permissionKeys/.test(catalog),
|
||||
'京东工具卡必须声明非空 permissionKeys(显隐按后端 app 菜单 key 过滤)')
|
||||
test('京东工作台卡片声明采集入口并指向采集页', () => {
|
||||
const catalog = readIfExists(JD_TOOL_CATALOG, 'jd/tool-catalog.ts')
|
||||
assert.ok(catalog.includes('获取店铺数据'),
|
||||
'京东工作台缺「获取店铺数据」卡')
|
||||
assert.ok(catalog.includes('/jd-collect'),
|
||||
'「获取店铺数据」卡必须带 href 指向 /jd-collect')
|
||||
})
|
||||
|
||||
test('endpoints 注册 jdCollect 端点组', () => {
|
||||
|
||||
Reference in New Issue
Block a user