Compare commits
6 Commits
5aab38cfa9
...
cac5b8ae7d
| Author | SHA1 | Date | |
|---|---|---|---|
| cac5b8ae7d | |||
| 7067d5380d | |||
| 61ab844e5d | |||
| e621deea58 | |||
| 61c361222d | |||
| 8413cd335e |
@@ -1,11 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东公共商品库:支持店铺分类和京麦类目组合筛选,分类管理在弹窗中完成。 */
|
||||
/** 京东公共商品库:支持店铺分类和京麦类目组合筛选,分类管理在弹窗中完成。
|
||||
* V203(2026-11-16 用户口径):分类按「数据权限分组」隔离——不同组看不到彼此的分类,
|
||||
* 组管理员可建/改/删分类并归类,同组普通号可开弹窗看但只读;平台超管全量可见可编辑;
|
||||
* 能看多组的人用工具栏「分组」下拉切换当前组(只有一组时锁定显示)。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import {
|
||||
deleteJdProducts,
|
||||
fetchJdCategoryScope,
|
||||
fetchJdProductCategories,
|
||||
fetchJdProductGroups,
|
||||
fetchJdProductList,
|
||||
type JdCategoryGroupOption,
|
||||
type JdProductCategoryOption,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
@@ -21,8 +26,14 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
|
||||
/** 写权限口径(2026-11-16 用户口径):商品行写(编辑/删除/勾选批量删)只对平台超级管理员渲染;
|
||||
* 分类写(建/改名/删除、归类)由 scope 的每组 editable 决定(本组管理员/公司超管/平台超管)。 */
|
||||
const session = useAdminSessionStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<JdProductItem[]>([])
|
||||
@@ -30,8 +41,12 @@ const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const filter = reactive(createJdProductFilterState())
|
||||
/** 分组下拉选项:分组全平台一份(公共),进页取一次即可;选项失败不拦列表,只回空下拉
|
||||
* (可见「全部分组」)。 */
|
||||
/** 分类作用域(V203):可见分组 + 每组可写标记。失败静默回空作用域(分类列全空但商品照常)。 */
|
||||
const categoryScope = ref<JdCategoryGroupOption[]>([])
|
||||
const scopeDefaultGroupId = ref(0)
|
||||
/** 当前分组(数据权限分组 id):分类列/分类筛选/分类管理的共同作用域。 */
|
||||
const ownerGroupId = ref(0)
|
||||
/** 当前分组的分类下拉选项(按 ownerGroupId 取,切组即换)。 */
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
/** 类目下拉选项(京麦末级类目):与当前行集同源(公共库全量);失败静默回空。 */
|
||||
const categoryOptions = ref<JdProductCategoryOption[]>([])
|
||||
@@ -43,6 +58,15 @@ const groupDialogVisible = ref(false)
|
||||
const editItem = ref<JdProductItem | null>(null)
|
||||
const editVisible = ref(false)
|
||||
|
||||
/** 当前分组的下拉项(带 editable)——分类写入口与「店铺分类」弹窗的可管理档都读它。 */
|
||||
const currentGroupOption = computed<JdCategoryGroupOption | null>(() =>
|
||||
categoryScope.value.find((group) => group.id === ownerGroupId.value) || null)
|
||||
const currentGroupName = computed(() => currentGroupOption.value?.name || '')
|
||||
/** 分类可管理(建/改名/删除/归类):本组管理员、公司超管、平台超管(后端 scope 判)。 */
|
||||
const canManageCategories = computed(() => currentGroupOption.value?.editable === true)
|
||||
/** 分组下拉只在能看多组时才渲染;只有一组(含无可见组)时按锁定态展示。 */
|
||||
const canSwitchGroup = computed(() => categoryScope.value.length > 1)
|
||||
|
||||
function openEdit(item: JdProductItem): void {
|
||||
editItem.value = item
|
||||
editVisible.value = true
|
||||
@@ -67,10 +91,26 @@ function clampJdSyncedRange(): void {
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
/** 分组选项失败静默回空——分组只是筛选项,不该让它把首屏行集一起拖死。 */
|
||||
/** 作用域 → 分组列表 → 该组分类:失败一律静默降级(分类只是筛选/归类面,不拦首屏行集)。 */
|
||||
async function loadCategoryScope(): Promise<void> {
|
||||
try {
|
||||
const scope = await fetchJdCategoryScope()
|
||||
categoryScope.value = scope.groups
|
||||
scopeDefaultGroupId.value = scope.defaultGroupId ?? 0
|
||||
} catch {
|
||||
categoryScope.value = []
|
||||
scopeDefaultGroupId.value = 0
|
||||
}
|
||||
// 当前分组:保留用户已选(仍可见时),否则回默认(可见组第一项)。
|
||||
const keep = categoryScope.value.some((group) => group.id === ownerGroupId.value)
|
||||
if (!keep) ownerGroupId.value = scopeDefaultGroupId.value
|
||||
await loadGroupOptions()
|
||||
}
|
||||
|
||||
/** 当前分组的分类选项:按 ownerGroupId 取(跨组不可见);失败静默回空下拉。 */
|
||||
async function loadGroupOptions(): Promise<void> {
|
||||
try {
|
||||
groupOptions.value = await fetchJdProductGroups()
|
||||
groupOptions.value = await fetchJdProductGroups(ownerGroupId.value)
|
||||
} catch {
|
||||
groupOptions.value = []
|
||||
}
|
||||
@@ -85,7 +125,17 @@ async function loadCategoryOptions(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 分组管理弹窗里做过变更:分组下拉与列表都刷新(删除分组后行集的 groupName 会变)。 */
|
||||
/** 切换「分组」下拉:分类筛选(属于上一组的分类)清空,分类选项换成本组,回第一页重取。 */
|
||||
async function changeOwnerGroup(next: number): Promise<void> {
|
||||
if (next === ownerGroupId.value) return
|
||||
ownerGroupId.value = next
|
||||
filter.groupId = ''
|
||||
await loadGroupOptions()
|
||||
page.value = 1
|
||||
await load()
|
||||
}
|
||||
|
||||
/** 分类弹窗里做过变更:分类下拉与列表都刷新(删除分类后行集的 groupName 会变)。 */
|
||||
async function onGroupChanged(deletedGroupId?: number): Promise<void> {
|
||||
if (deletedGroupId && filter.groupId === String(deletedGroupId)) filter.groupId = ''
|
||||
await loadGroupOptions()
|
||||
@@ -104,6 +154,7 @@ async function load(): Promise<void> {
|
||||
titleKeyword: filter.titleKeyword,
|
||||
category: filter.category,
|
||||
groupId: filter.groupId,
|
||||
ownerGroupId: ownerGroupId.value,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
})
|
||||
@@ -225,10 +276,12 @@ async function removeMany(picked: JdProductItem[], message: string): Promise<voi
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadGroupOptions()
|
||||
onMounted(async () => {
|
||||
// 先解析作用域再取列表:首屏的 owner_group_id 必须与分类下拉同一个组(铁律 30 同形——
|
||||
// 不要先发一条不带 owner_group_id 的列表请求再补,两次请求会落在不同默认组上)。
|
||||
await loadCategoryScope()
|
||||
void loadCategoryOptions()
|
||||
void load()
|
||||
await load()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -276,13 +329,29 @@ onMounted(() => {
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="jd-toolbar">
|
||||
<span class="jd-summary">共 {{ total }} 条京东商品</span>
|
||||
<!-- 当前分组(V203):能看多组的人(平台超管/公司超管)用下拉切换;只有一组时锁定显示组名。
|
||||
分组是分类列/分类筛选/分类管理的作用域,不是筛选条件 ⇒ 「重置」不清它。 -->
|
||||
<select
|
||||
v-if="canSwitchGroup"
|
||||
:value="ownerGroupId"
|
||||
aria-label="当前分组"
|
||||
@change="changeOwnerGroup(Number(($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option v-for="group in categoryScope" :key="group.id" :value="group.id">{{ group.label }}</option>
|
||||
</select>
|
||||
<span v-else-if="currentGroupName" class="jd-group-locked" title="你的数据权限内只有这一个分组">分组:{{ currentGroupName }}</span>
|
||||
<!-- 商品行写只对平台超管;分类写由当前分组 editable 决定(本组管理员/公司超管/平台超管)。
|
||||
非超管看到只读提示,但「店铺分类」弹窗照常可开(同组普通号只读查看)。 -->
|
||||
<span v-if="!isSuperAdmin" class="jd-readonly-tip">只读:编辑/删除仅超级管理员可用;分类由本组管理员维护</span>
|
||||
<button class="btn btn-secondary" type="button" @click="groupDialogVisible = true">店铺分类</button>
|
||||
<select v-model="filter.groupId" aria-label="筛选店铺分类" @change="apply">
|
||||
<option value="">全部分类</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
|
||||
</select>
|
||||
<!-- 批量删除 2026-11-16 客户口径「不要勾选后才显示」:常显,勾选 0 时置灰。 -->
|
||||
<!-- 批量删除 2026-11-16 客户口径「不要勾选后才显示」:常显,勾选 0 时置灰。
|
||||
同日写权限收窄到超管:非超管整颗按钮不渲染(勾选列同窗隐藏)。 -->
|
||||
<button
|
||||
v-if="isSuperAdmin"
|
||||
class="btn btn-danger jd-delete-btn"
|
||||
type="button"
|
||||
:disabled="deleting || !selectedCount"
|
||||
@@ -295,21 +364,21 @@ onMounted(() => {
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th v-if="isSuperAdmin" style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th style="width: 92px">分类</th>
|
||||
<th style="width: 520px">商品信息</th>
|
||||
<th style="width: 76px">总库存</th>
|
||||
<th style="width: 120px">价格</th>
|
||||
<!-- 同步时间收尾(创建/修改两列 2026-11-16 客户口径「不要」下线,仍收详情抽屉);
|
||||
操作列 2026-11-16「操作放最后一列」口径置末。 -->
|
||||
操作列 2026-11-16「操作放最后一列」口径置末;同日写权限收窄到超管 ⇒ 非超管不渲染。 -->
|
||||
<th style="width: 170px">同步时间</th>
|
||||
<th style="width: 138px">操作</th>
|
||||
<th v-if="isSuperAdmin" style="width: 138px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<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 v-if="isSuperAdmin" @click.stop><input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row, ($event.target as HTMLInputElement).checked)" /></td>
|
||||
<td :title="row.groupName || ''">{{ row.groupName || '未分类' }}</td>
|
||||
<td class="jd-info-cell">
|
||||
<div class="jd-info-wrap">
|
||||
@@ -337,18 +406,19 @@ onMounted(() => {
|
||||
<td>{{ jdPriceRange(row) || '-' }}</td>
|
||||
<td>{{ formatDateTime(row.syncedAt || '') }}</td>
|
||||
<!-- 操作列(2026-11-15 用户口径):编辑/删除;@click.stop 防冒泡开详情抽屉。
|
||||
2026-11-16「操作放最后一列」口径置末;「上架时间 / 商品状态」列同日整列下线。 -->
|
||||
<td class="jd-ops-cell" @click.stop>
|
||||
2026-11-16「操作放最后一列」口径置末;「上架时间 / 商品状态」列同日整列下线;
|
||||
同日写权限收窄到超管 ⇒ 非超管不渲染该列。 -->
|
||||
<td v-if="isSuperAdmin" 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="7" class="empty-tip">加载中...</td>
|
||||
<td :colspan="isSuperAdmin ? 7 : 5" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="7" class="empty-tip">暂无京东商品数据</td>
|
||||
<td :colspan="isSuperAdmin ? 7 : 5" class="empty-tip">暂无京东商品数据</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -357,7 +427,16 @@ onMounted(() => {
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<JdProductGroupDialog :visible="groupDialogVisible" :category-options="categoryOptions" @close="groupDialogVisible = false" @changed="onGroupChanged" />
|
||||
<JdProductGroupDialog
|
||||
:visible="groupDialogVisible"
|
||||
:category-options="categoryOptions"
|
||||
:owner-group-id="ownerGroupId"
|
||||
:owner-group-name="currentGroupName"
|
||||
:can-manage="canManageCategories"
|
||||
:can-assign="canManageCategories"
|
||||
@close="groupDialogVisible = false"
|
||||
@changed="onGroupChanged"
|
||||
/>
|
||||
<JdProductDetailDrawer
|
||||
:item="detailItem"
|
||||
:visible="detailVisible"
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/** 店铺分类弹窗右栏:按京麦类目和标题筛选商品,勾选后归入左侧目标或移出分类。
|
||||
* 两种操作都会设置人工编辑锁,弹窗提示采集不再覆盖以及价格、库存停更。 */
|
||||
* V203(2026-11-16 用户口径):归类写「本组」的归属行(biz_jd_product_group_assign,
|
||||
* 一组一商品一行),行集与归入/移出都带当前分组 ownerGroupId,同一商品在其他组可另归一类;
|
||||
* 归类不再置人工编辑锁(采集照常更新价格/库存)。`canAssign=false`(同组普通号只读)
|
||||
* 时勾选列与底部两个写按钮都不渲染,只留行集浏览。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import JdCategoryCascader from './JdCategoryCascader.vue'
|
||||
import { batchAssignJdProductGroup, fetchJdProductList } from './jd-product-api.ts'
|
||||
@@ -15,6 +18,10 @@ const props = defineProps<{
|
||||
selectedGroup: JdProductGroup | null
|
||||
categoryOptions: JdProductCategoryOption[]
|
||||
refreshVersion: number
|
||||
/** 当前数据权限分组:行集的分类列与归类落点都以它为作用域。 */
|
||||
ownerGroupId: number
|
||||
/** 本账号可归类(本组管理员/公司超管/平台超管);false=只读浏览。 */
|
||||
canAssign: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'changed'): void }>()
|
||||
@@ -34,8 +41,9 @@ const assigning = ref(false)
|
||||
const selectedCount = computed(() => selectedProductIds.value.size)
|
||||
/** 归入所选分类:必须先在左侧点亮一个分类且有勾选行。 */
|
||||
const removableIds = computed(() => products.value.filter(row => selectedProductIds.value.has(row.id) && row.groupId != null && row.groupId > 0).map(row => row.id))
|
||||
const canAssign = computed(() => !!props.selectedGroup && selectedCount.value > 0 && !assigning.value && !productsLoading.value)
|
||||
const canRemove = computed(() => removableIds.value.length > 0 && !assigning.value && !productsLoading.value)
|
||||
/** 可提交「归入」(props.canAssign 是权限,这里的名字避开与 prop 同名)。 */
|
||||
const canSubmitAssign = computed(() => props.canAssign && !!props.selectedGroup && selectedCount.value > 0 && !assigning.value && !productsLoading.value)
|
||||
const canRemove = computed(() => props.canAssign && removableIds.value.length > 0 && !assigning.value && !productsLoading.value)
|
||||
const allSelected = computed(() =>
|
||||
products.value.length > 0 && products.value.every((row) => selectedProductIds.value.has(row.id)))
|
||||
|
||||
@@ -51,6 +59,7 @@ async function loadProducts(): Promise<void> {
|
||||
pageSize: PRODUCT_PAGE_SIZE,
|
||||
titleKeyword: keyword.value.trim(),
|
||||
category: category.value,
|
||||
ownerGroupId: props.ownerGroupId,
|
||||
})
|
||||
if (request !== requestVersion) return
|
||||
products.value = result.items
|
||||
@@ -98,14 +107,15 @@ 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
|
||||
if (!target || !canSubmitAssign.value) return
|
||||
assigning.value = true
|
||||
productsError.value = ''
|
||||
try {
|
||||
const updated = await batchAssignJdProductGroup([...selectedProductIds.value], target.id)
|
||||
const updated = await batchAssignJdProductGroup([...selectedProductIds.value], target.id, props.ownerGroupId)
|
||||
showAdminFeedback(`已把 ${updated} 个商品归入「${target.name}」`, 'success')
|
||||
emit('changed')
|
||||
await loadProducts()
|
||||
@@ -116,13 +126,13 @@ async function assignToSelected(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 勾选行 → 移出分类(group_id 置 NULL,回到未分类)。 */
|
||||
/** 勾选行 → 移出本组分类(删本组归属行,商品回到未分类;别组的归类不受影响)。 */
|
||||
async function removeFromCategory(): Promise<void> {
|
||||
if (!canRemove.value) return
|
||||
assigning.value = true
|
||||
productsError.value = ''
|
||||
try {
|
||||
const updated = await batchAssignJdProductGroup(removableIds.value, null)
|
||||
const updated = await batchAssignJdProductGroup(removableIds.value, null, props.ownerGroupId)
|
||||
showAdminFeedback(`已把 ${updated} 个商品移出分类`, 'success')
|
||||
emit('changed')
|
||||
await loadProducts()
|
||||
@@ -154,14 +164,14 @@ onMounted(() => {
|
||||
<table v-if="products.length">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="col-check"><input type="checkbox" :disabled="productsLoading || assigning" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th v-if="canAssign" class="col-check"><input type="checkbox" :disabled="productsLoading || assigning" :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">
|
||||
<td v-if="canAssign" class="col-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
:disabled="productsLoading || assigning"
|
||||
@@ -187,10 +197,10 @@ onMounted(() => {
|
||||
<p v-else-if="!productsError" class="pane-tip">没有符合条件的商品</p>
|
||||
</div>
|
||||
|
||||
<div class="product-footer">
|
||||
<div v-if="canAssign" class="product-footer">
|
||||
<span class="pick-summary">已勾选 {{ selectedCount }} 个商品</span>
|
||||
<div class="footer-actions">
|
||||
<button class="btn btn-small" type="button" :disabled="!canAssign" @click="assignToSelected">
|
||||
<button class="btn btn-small" type="button" :disabled="!canSubmitAssign" @click="assignToSelected">
|
||||
{{ assigning ? '归类中...' : selectedGroup ? `归入「${selectedGroup.name}」` : '归入所选分类' }}
|
||||
</button>
|
||||
<button class="btn btn-danger btn-small" type="button" :disabled="!canRemove" @click="removeFromCategory">移出分类</button>
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
* +可选块(attrGroups 重建 attr_json 的 tabs 段、skus 按 skuId 改价格库存、deleteImageIds
|
||||
* 删图——先删桶、共用对象保留)。保存即置人工编辑锁 manual_locked=1:后续采集不再覆盖该行,
|
||||
* 底部常驻提示点名这件事。
|
||||
* V203(2026-11-16):分类<b>不在本抽屉编辑</b>(分类按数据权限分组隔离,归属存
|
||||
* biz_jd_product_group_assign,归类只走「店铺分类」弹窗)——原「分类」下拉与 groupId 负载已下线,
|
||||
* 避免写遗留的 biz_jd_product.group_id 列造成「界面改了、列表分组没变」。
|
||||
* 图片区拆在 JdProductImageManager 子组件(2026-11-16:× 右上角标删+替换/新增本地图,
|
||||
* B109-01 落地;标删集合经 update:deleteIds 上抛进保存负载,上传立即生效由子组件自理)。
|
||||
* 京东时间/信息分/商品编码只读。
|
||||
@@ -14,9 +17,7 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
fetchJdProductDetail,
|
||||
fetchJdProductGroups,
|
||||
updateJdProduct,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import JdProductImageManager from './JdProductImageManager.vue'
|
||||
import type {
|
||||
@@ -59,7 +60,6 @@ const form = ref({
|
||||
priceMax: '',
|
||||
stockTotal: '' as string,
|
||||
saleStatus: '',
|
||||
groupId: '' as string,
|
||||
})
|
||||
const draftAttrGroups = ref<DraftAttrGroup[]>([])
|
||||
const draftSkus = ref<JdProductSku[]>([])
|
||||
@@ -68,7 +68,6 @@ const images = ref<JdProductImage[]>([])
|
||||
const managerDeleteIds = ref<number[]>([])
|
||||
/** attr_json 解析失败(attrJsonRaw 兜底行):属性块禁用,防保存把原文形状弄丢。 */
|
||||
const attrJsonRaw = ref('')
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
|
||||
const skuDimensions = computed(() => jdSkuDimensions(draftSkus.value))
|
||||
|
||||
@@ -89,11 +88,7 @@ async function loadDetail(): Promise<void> {
|
||||
loadFailure.value = ''
|
||||
saveError.value = ''
|
||||
try {
|
||||
const [detail, groups] = await Promise.all([
|
||||
fetchJdProductDetail(item.id),
|
||||
fetchJdProductGroups().catch(() => [] as JdProductGroup[]),
|
||||
])
|
||||
groupOptions.value = groups
|
||||
const detail = await fetchJdProductDetail(item.id)
|
||||
const row = detail.item
|
||||
form.value = {
|
||||
title: row.title,
|
||||
@@ -104,7 +99,6 @@ async function loadDetail(): Promise<void> {
|
||||
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) => ({
|
||||
@@ -145,7 +139,6 @@ async function save(): Promise<void> {
|
||||
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
|
||||
@@ -175,7 +168,6 @@ async function save(): Promise<void> {
|
||||
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 })),
|
||||
@@ -256,15 +248,6 @@ function dash(value: string | number | null | undefined): string {
|
||||
<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" />
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
/** 店铺分类弹窗:左侧管理分类和选择归类目标,右侧按京麦类目筛选商品并批量归类。
|
||||
* 人工归类会设置编辑锁,采集不再覆盖商品;变更后通知页面刷新。 */
|
||||
/** 店铺分类弹窗:左侧管理当前分组的分类并选择归类目标,右侧按京麦类目筛选商品并批量归类。
|
||||
* V203(2026-11-16 用户口径):分类按「数据权限分组」隔离——弹窗只显示当前分组的分类;
|
||||
* `canManage=false`(同组普通号)可打开看,但新建行、改名/删除按钮与归类入口都不渲染;
|
||||
* 归类写归属表(biz_jd_product_group_assign),不置人工编辑锁(采集照常更新商品行)。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
createJdProductGroup,
|
||||
@@ -17,11 +19,18 @@ import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
categoryOptions: JdProductCategoryOption[]
|
||||
/** 当前数据权限分组(分类的归属与可见范围);0=没有可管理/可见的组。 */
|
||||
ownerGroupId: number
|
||||
ownerGroupName: string
|
||||
/** 本账号对当前分组分类可写(建/改名/删除);缺省 false=只读查看。 */
|
||||
canManage: boolean
|
||||
/** 可归类(本组管理员/公司超管/平台超管);与 canManage 同源,但分开传便于后续细分。 */
|
||||
canAssign: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed', deletedGroupId?: number): void }>()
|
||||
|
||||
// ---------------- 左栏:分类管理(分组全平台一份,界面措辞「分类」) ----------------
|
||||
// ---------------- 左栏:分类管理(当前分组一份,界面措辞「分类」) ----------------
|
||||
|
||||
const loading = ref(false)
|
||||
const errorText = ref('')
|
||||
@@ -37,14 +46,27 @@ const paneRefreshVersion = ref(0)
|
||||
/** 左侧点亮的分类=右栏「归入所选分类」的归类目标;删除后自动清掉。 */
|
||||
const selectedGroupId = ref(0)
|
||||
|
||||
const canCreate = computed(() => createName.value.trim().length > 0 && !creating.value && !saving.value)
|
||||
const canCreate = computed(() => props.canManage && createName.value.trim().length > 0 && !creating.value && !saving.value)
|
||||
const selectedGroup = computed(() => groups.value.find((group) => group.id === selectedGroupId.value) || null)
|
||||
/** 标题带当前分组名(跨组同名分类靠它区分)。 */
|
||||
const dialogTitle = computed(() => props.ownerGroupName ? `店铺分类 · ${props.ownerGroupName}` : '店铺分类')
|
||||
/** 空列表文案分三种:不属于任何组 / 本组还没分类(可管理)/ 本组还没分类(只读)。 */
|
||||
const emptyListText = computed(() => {
|
||||
if (props.ownerGroupId <= 0) return '你还不属于任何数据权限分组'
|
||||
return props.canManage ? '本组暂无分类,先新建一个' : '本组暂无分类'
|
||||
})
|
||||
|
||||
async function loadGroups(): Promise<void> {
|
||||
if (props.ownerGroupId <= 0) {
|
||||
groups.value = []
|
||||
loading.value = false
|
||||
errorText.value = ''
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
groups.value = await fetchJdProductGroups()
|
||||
groups.value = await fetchJdProductGroups(props.ownerGroupId)
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '分类列表加载失败'
|
||||
groups.value = []
|
||||
@@ -62,7 +84,7 @@ async function refreshAfterChange(deletedGroupId?: number, refreshPane = false):
|
||||
emit('changed', deletedGroupId)
|
||||
if (refreshPane) paneRefreshVersion.value++
|
||||
try {
|
||||
groups.value = sortGroups(await fetchJdProductGroups())
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.ownerGroupId))
|
||||
} catch (error) {
|
||||
errorText.value = `操作已成功,分类列表刷新失败:${requestErrorMessage(error) || '请重试'}`
|
||||
}
|
||||
@@ -70,11 +92,11 @@ async function refreshAfterChange(deletedGroupId?: number, refreshPane = false):
|
||||
|
||||
async function submitCreate(): Promise<void> {
|
||||
const name = createName.value.trim()
|
||||
if (!name || creating.value) return
|
||||
if (!name || creating.value || !props.canManage) return
|
||||
creating.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await createJdProductGroup({ name, sortOrder: 0 })
|
||||
await createJdProductGroup({ name, sortOrder: 0, ownerGroupId: props.ownerGroupId })
|
||||
createName.value = ''
|
||||
await refreshAfterChange()
|
||||
} catch (error) {
|
||||
@@ -132,9 +154,9 @@ async function removeGroup(group: JdProductGroup): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧点亮分类作为右栏归类目标。 */
|
||||
/** 左侧点亮分类作为右栏归类目标(只读账号没有归类入口,点亮无意义 ⇒ 直接不响应)。 */
|
||||
function pickGroup(group: JdProductGroup): void {
|
||||
if (saving.value) return
|
||||
if (saving.value || !props.canAssign) return
|
||||
selectedGroupId.value = group.id
|
||||
}
|
||||
|
||||
@@ -162,19 +184,19 @@ function onPaneChanged(): void {
|
||||
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
|
||||
<div class="group-modal">
|
||||
<div class="modal-head">
|
||||
<h3>店铺分类</h3>
|
||||
<h3>{{ dialogTitle }}</h3>
|
||||
<button class="modal-close" type="button" aria-label="关闭" @click="emit('close')">×</button>
|
||||
</div>
|
||||
<p class="modal-tip">
|
||||
左侧管理分类并点选目标分类;右侧勾选商品后「归入所选分类」或「移出分类」。
|
||||
人工归类过的商品不再被采集自动覆盖(价格/库存等字段停更)。
|
||||
<template v-if="canAssign">左侧管理本组分类并点选目标分类;右侧勾选商品后「归入所选分类」或「移出分类」。归类只记在分类归属上,不影响采集对价格/库存的更新。</template>
|
||||
<template v-else>左侧是本组分类(只读);分类的新建/改名/删除与商品归类由本组管理员操作。</template>
|
||||
</p>
|
||||
<p v-if="errorText" class="group-error">{{ errorText }}</p>
|
||||
|
||||
<div class="split-body">
|
||||
<!-- 左栏:分类管理 -->
|
||||
<!-- 左栏:分类管理(只读账号不渲染新建行,改名/删除按钮逐行隐藏) -->
|
||||
<aside class="left-pane">
|
||||
<div class="group-create">
|
||||
<div v-if="canManage" class="group-create">
|
||||
<input
|
||||
v-model="createName"
|
||||
type="text"
|
||||
@@ -211,18 +233,25 @@ function onPaneChanged(): void {
|
||||
<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>
|
||||
<span v-if="canManage" 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>
|
||||
<li v-if="!loading && !groups.length && !errorText" class="pane-tip">{{ emptyListText }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<!-- 右栏:商品人工归类(独立件,行集/勾选/批量归类都在那里) -->
|
||||
<JdProductAssignPane :selected-group="selectedGroup" :category-options="categoryOptions" :refresh-version="paneRefreshVersion" @changed="onPaneChanged" />
|
||||
<!-- 右栏:商品人工归类(独立件,行集/勾选/批量归类都在那里;只读账号不含写入口) -->
|
||||
<JdProductAssignPane
|
||||
:selected-group="selectedGroup"
|
||||
:category-options="categoryOptions"
|
||||
:refresh-version="paneRefreshVersion"
|
||||
:owner-group-id="ownerGroupId"
|
||||
:can-assign="canAssign"
|
||||
@changed="onPaneChanged"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -128,11 +128,43 @@ h3 {
|
||||
.jd-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
gap: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
/* 工具栏右侧两个批量按钮:推右的 margin 由移除分类带,删除跟排。 */
|
||||
.jd-remove-btn {
|
||||
/* 工具栏里的下拉与按钮统一 42px 外壳(2026-11-16 用户口径「样式要统一」):
|
||||
这一行此前只有 .btn 有壳,两个原生 <select> 落成 28px 灰框、字号也不跟,
|
||||
与旁边按钮同排时高矮不齐。数值与 .form-group select / .btn 同一套(42px 高、
|
||||
9px 圆角、#cbd9e6 描边、#f8fbfd 底),箭头用内联 SVG 自绘,避免各浏览器原生
|
||||
箭头粗细不一(appearance:none 后必须补 padding-right 给箭头留位)。 */
|
||||
.jd-toolbar select {
|
||||
min-height: 42px;
|
||||
max-width: 220px;
|
||||
padding: 0 34px 0 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background-color: #f8fbfd;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1.5 6 6.5 11 1.5' fill='none' stroke='%235b6f83' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 12px center;
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
color: #24384d;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.jd-toolbar select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.jd-toolbar select:focus {
|
||||
background-color: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
/* 危险动作(删除勾选)推到行尾:留在「店铺分类/分类筛选」旁边会被读成同一组动作。 */
|
||||
.jd-delete-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
/* 危险动作(删除勾选):与全站 .btn-danger 同形——实心红渐变+白字。
|
||||
@@ -150,6 +182,26 @@ h3 {
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 非超管只读提示(2026-11-16 写权限收窄):紧跟汇总的一句话,不冒充可点按钮。 */
|
||||
.jd-readonly-tip {
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 只有一个可见分组时锁定的组名(不可切):做成与下拉同高的静态芯片,
|
||||
这样"一组锁定"和"多组下拉"两种形态占位一致,页面不跳。 */
|
||||
.jd-group-locked {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 42px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 9px;
|
||||
background: #f1f6fb;
|
||||
color: #4e6479;
|
||||
font-size: 13.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
|
||||
@@ -34,17 +34,22 @@ export async function fetchJdProductList(
|
||||
},
|
||||
params.page,
|
||||
params.pageSize,
|
||||
params.ownerGroupId ?? null,
|
||||
)
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
|
||||
return parseJdProductPage(data)
|
||||
}
|
||||
|
||||
/** 详情:GET /api/admin/jd-products/{id}(信封 data=主字段 + attrGroups + attrJsonRaw + images)。
|
||||
* 公共库无公司维度,按 id 直取。 */
|
||||
* 公共库无公司维度,按 id 直取;分类字段按「当前分组」(owner_group_id)取(V203)。 */
|
||||
export async function fetchJdProductDetail(
|
||||
id: number,
|
||||
ownerGroupId?: number | null,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`)
|
||||
const params = typeof ownerGroupId === 'number' && ownerGroupId > 0
|
||||
? { owner_group_id: ownerGroupId }
|
||||
: undefined
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, { params })
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
@@ -72,7 +77,8 @@ export async function deleteJdProducts(
|
||||
|
||||
/** 编辑提交负载(PUT /api/admin/jd-products/{id} body,后端 JdProductUpdateRequest):
|
||||
* 主字段全量提交;attrGroups/skus/deleteImageIds 可选——null=不修改该块
|
||||
* (后端对 null 块零触碰)。 */
|
||||
* (后端对 null 块零触碰)。分类不在本负载里(V203:分类按数据权限分组归属存
|
||||
* biz_jd_product_group_assign,编辑面不写 group_id,归类只走「店铺分类」弹窗)。 */
|
||||
export interface JdProductUpdatePayload {
|
||||
title: string
|
||||
brand: string | null
|
||||
@@ -82,7 +88,6 @@ export interface JdProductUpdatePayload {
|
||||
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
|
||||
@@ -129,17 +134,37 @@ export async function uploadJdProductImage(
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
/** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */export interface JdProductGroup {
|
||||
/** 分组行(GET 列表返回:[{id,name,ownerGroupId,sortOrder,productCount}])。 */
|
||||
export interface JdProductGroup {
|
||||
id: number
|
||||
name: string
|
||||
ownerGroupId: number
|
||||
sortOrder: number
|
||||
productCount: number
|
||||
}
|
||||
|
||||
/** 分组管理的写入负载(POST / PUT body:{name, sortOrder})。 */
|
||||
/** 分组管理的写入负载(POST / PUT body:{name, sortOrder, ownerGroupId?})。 */
|
||||
export interface JdProductGroupPayload {
|
||||
name: string
|
||||
sortOrder: number
|
||||
/** 新建时归属的数据权限分组(缺省=操作者自己带的组,后端 requireWritableGroup 收敛)。 */
|
||||
ownerGroupId?: number | null
|
||||
}
|
||||
|
||||
/** 「当前分组」下拉的一项(GET /scope 的 groups[],V203):editable=本账号对该组分类可写
|
||||
* (建/改名/删除/归类)。跨公司的组名由后端拼进 label,前端不解析公司字段。 */
|
||||
export interface JdCategoryGroupOption {
|
||||
id: number
|
||||
name: string
|
||||
label: string
|
||||
editable: boolean
|
||||
}
|
||||
|
||||
/** 分类作用域回执(GET /api/admin/jd-product-groups/scope):分组下拉 + 平台超管标记。 */
|
||||
export interface JdCategoryScope {
|
||||
platformSuperAdmin: boolean
|
||||
defaultGroupId: number | null
|
||||
groups: JdCategoryGroupOption[]
|
||||
}
|
||||
|
||||
/** 分组信封是 `{code, message, data}` 三段式:code 非 0 =业务失败,message 是中文文案
|
||||
@@ -156,10 +181,13 @@ function numberOr(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
}
|
||||
|
||||
/** 分组下拉/管理列表(分组 2026-11-15 起全平台一份,不带公司维度);失败由页面自己兜
|
||||
* (分组只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(): Promise<JdProductGroup[]> {
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT)
|
||||
/** 分组下拉/管理列表:按「当前分组」(owner_group_id)取该组的分类(V203,跨组不可见);
|
||||
* 缺省=后端按作用域默认分组取。失败由页面自己兜(分类只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(ownerGroupId?: number | null): Promise<JdProductGroup[]> {
|
||||
const params = typeof ownerGroupId === 'number' && ownerGroupId > 0
|
||||
? { owner_group_id: ownerGroupId }
|
||||
: undefined
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT, { params })
|
||||
const core = unwrap<unknown>(data)
|
||||
if (!Array.isArray(core)) return []
|
||||
const out: JdProductGroup[] = []
|
||||
@@ -171,6 +199,7 @@ export async function fetchJdProductGroups(): Promise<JdProductGroup[]> {
|
||||
out.push({
|
||||
id,
|
||||
name: typeof record.name === 'string' ? record.name.trim() : '',
|
||||
ownerGroupId: numberOr(record.ownerGroupId ?? record.owner_group_id, 0),
|
||||
sortOrder: numberOr(record.sortOrder ?? record.sort_order, 0),
|
||||
productCount: numberOr(record.productCount ?? record.product_count, 0),
|
||||
})
|
||||
@@ -178,6 +207,35 @@ export async function fetchJdProductGroups(): Promise<JdProductGroup[]> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** 分类作用域(GET /scope):本账号可见的数据权限分组 + 每组可写标记。
|
||||
* 页面用它渲染「分组」下拉、按 editable 渲染分类写入口;失败由页面自己兜(回空作用域=
|
||||
* 分类列全空、弹窗提示不属于任何分组,但商品列表照常可用)。 */
|
||||
export async function fetchJdCategoryScope(): Promise<JdCategoryScope> {
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/scope`)
|
||||
const core = groupDataOf<unknown>(data)
|
||||
const record = core && typeof core === 'object' ? (core as Record<string, unknown>) : {}
|
||||
const rawGroups = Array.isArray(record.groups) ? record.groups : []
|
||||
const groups: JdCategoryGroupOption[] = []
|
||||
for (const raw of rawGroups) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const row = raw as Record<string, unknown>
|
||||
const id = numberOr(row.id, 0)
|
||||
if (id <= 0) continue
|
||||
const name = typeof row.name === 'string' ? row.name.trim() : ''
|
||||
groups.push({
|
||||
id,
|
||||
name,
|
||||
label: typeof row.label === 'string' && row.label.trim() ? row.label.trim() : name,
|
||||
editable: row.editable === true,
|
||||
})
|
||||
}
|
||||
return {
|
||||
platformSuperAdmin: record.platformSuperAdmin === true || record.platform_super_admin === true,
|
||||
defaultGroupId: numberOr(record.defaultGroupId ?? record.default_group_id, 0) || null,
|
||||
groups,
|
||||
}
|
||||
}
|
||||
|
||||
/** 类目下拉选项(GET /categories 返回 [{name, productCount}],name=京麦末级类目即
|
||||
* 落库的 category_path;等值过滤)。失败由页面自己兜(类目只是筛选项,不拦首屏行集)。 */
|
||||
export interface JdProductCategoryOption {
|
||||
@@ -200,11 +258,15 @@ export async function fetchJdProductCategories(): Promise<JdProductCategoryOptio
|
||||
return out
|
||||
}
|
||||
|
||||
/** 新建分组(公共库无公司维度);重名等业务失败把后端中文文案抛回(页面直接展示)。 */
|
||||
/** 新建分类(归属当前分组,V203):ownerGroupId 缺省=后端取操作者自己带的组;
|
||||
* 同一分组内重名等业务失败把后端中文文案抛回(页面直接展示)。 */
|
||||
export async function createJdProductGroup(
|
||||
payload: JdProductGroupPayload,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (typeof payload.ownerGroupId === 'number' && payload.ownerGroupId > 0) {
|
||||
body.ownerGroupId = payload.ownerGroupId
|
||||
}
|
||||
const { data } = await http.post<unknown>(JD_PRODUCT_GROUP_ENDPOINT, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
@@ -226,15 +288,17 @@ export async function deleteJdProductGroup(id: number): Promise<void> {
|
||||
}
|
||||
|
||||
/** 批量人工归类(店铺分类弹窗 2026-11-15 + 京东数据库页工具栏「移除分类」2026-11-16):
|
||||
* 勾选商品行 → 归入指定分类或移出分类。
|
||||
* groupId 传 null=移出分类(后端把 group_id 置 NULL);返回实际更新的行数。
|
||||
* 后端与单行编辑同口径置 manual_locked=1(归类即人工干预,采集不再覆盖/清理该行)。
|
||||
* 业务失败(分类不存在等)把中文文案抛回,弹窗红条原样展示。公共库写侧无公司维度。 */
|
||||
* 勾选商品行 → 归入当前分组(ownerGroupId)的指定分类或移出分类(V203:归属写
|
||||
* biz_jd_product_group_assign 的 (product_id, owner_group_id) 一行,同一商品各组可各自归类)。
|
||||
* groupId 传 null=移出本组分类;返回实际写入/解挂的归属行数。
|
||||
* 归类<b>不再置人工编辑锁</b>(2026-11-16 用户拍板):分类不在商品行上,采集冲不掉它。
|
||||
* 业务失败(分类不存在/不属于当前分组)把中文文案抛回,弹窗红条原样展示。 */
|
||||
export async function batchAssignJdProductGroup(
|
||||
ids: number[],
|
||||
groupId: number | null,
|
||||
ownerGroupId: number,
|
||||
): Promise<number> {
|
||||
const body: Record<string, unknown> = { ids, groupId }
|
||||
const body: Record<string, unknown> = { ids, groupId, ownerGroupId }
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-assign-group`, body)
|
||||
return groupDataOf<number>(data)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** 京东数据库页筛选纯函数(v1.4 Phase 5):商品编码/标题关键字/类目/分组/分类状态/同步起止 + snake 分页参数。
|
||||
/** 京东数据库页筛选纯函数(v1.4 Phase 5):商品编码/标题关键字/类目/分组/同步起止 + snake 分页参数。
|
||||
* 产出与后端契约 §列表 query 逐字对撞:`page`/`page_size`(默认 20、上限 100)、
|
||||
* `product_code`、`title_keyword`、`category`(京麦末级类目等值过滤,2026-11-15 增)、
|
||||
* `group_id`、
|
||||
* `group_id`(当前分组下的分类 id)、`owner_group_id`(当前数据权限分组,V203)、
|
||||
* `synced_from`/`synced_to`(ISO yyyy-MM-dd;空白不下发)。
|
||||
* 商品状态筛选与导出(2026-11-15 客户口径「这两个不要/导出也不用」)已从前端下线;
|
||||
* 店铺筛选同日客户口径「店铺不需要」从前端下线(后端 shop_name 参数同窗撤,DB 列与详情不动)。
|
||||
@@ -57,12 +57,15 @@ export interface JdProductQuery {
|
||||
title_keyword?: string
|
||||
/** 京麦末级类目等值过滤(后端 JdProductQueryService.Filter.category)。 */
|
||||
category?: string
|
||||
/** 自定义分类 id(当前分组下的一个分类;V203 起按归属表 EXISTS 过滤)。 */
|
||||
group_id?: number
|
||||
/** 当前数据权限分组 id(分类列/分类筛选都按它取;V203「不同组不能看到跨组的分类」)。 */
|
||||
owner_group_id?: number
|
||||
synced_from?: string
|
||||
synced_to?: string
|
||||
}
|
||||
|
||||
/** api 模块的入参:筛选态 + 分页(公共库无公司维度)。 */
|
||||
/** api 模块的入参:筛选态 + 分页 + 当前分组(公共库无公司维度)。 */
|
||||
export interface JdProductListParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
@@ -70,6 +73,8 @@ export interface JdProductListParams {
|
||||
titleKeyword?: string
|
||||
category?: string
|
||||
groupId?: string
|
||||
/** 当前分组(数据权限分组 id):分类列/分类筛选的作用域,非筛选条件(重置不清它)。 */
|
||||
ownerGroupId?: number | null
|
||||
syncedFrom?: string
|
||||
syncedTo?: string
|
||||
}
|
||||
@@ -92,18 +97,25 @@ function toJdProductFilterQuery(state: JdProductFilterState): Omit<JdProductQuer
|
||||
return query
|
||||
}
|
||||
|
||||
/** 过滤态 + 分页 → 列表查询参数;空白/非法日期不下发,分页钳制在此单出口(不含公司维)。 */
|
||||
/** 过滤态 + 分页 → 列表查询参数;空白/非法日期不下发,分页钳制在此单出口(不含公司维)。
|
||||
* {@code ownerGroupId} 是「当前分组」(分类列/分类筛选作用域,V203),不是筛选条件:
|
||||
* >0 时下发 `owner_group_id`,缺省/0 不下发=后端按作用域默认分组取。 */
|
||||
export function toJdProductListParams(
|
||||
state: JdProductFilterState,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
ownerGroupId?: number | null,
|
||||
): JdProductQuery {
|
||||
const safePage = Math.min(Math.max(Math.floor(page) || 1, 1), JD_PRODUCT_MAX_PAGE)
|
||||
const rawSize = Math.floor(pageSize) || JD_PRODUCT_PAGE_SIZE
|
||||
const safeSize = Math.min(Math.max(rawSize, 1), JD_PRODUCT_MAX_PAGE_SIZE)
|
||||
return {
|
||||
const query: JdProductQuery = {
|
||||
page: safePage,
|
||||
page_size: safeSize,
|
||||
...toJdProductFilterQuery(state),
|
||||
}
|
||||
if (typeof ownerGroupId === 'number' && Number.isFinite(ownerGroupId) && ownerGroupId > 0) {
|
||||
query.owner_group_id = Math.floor(ownerGroupId)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
*
|
||||
* 覆盖:
|
||||
* 1. **snake 参数形状**:toJdProductListParams 产出 `page`/`page_size`(默认 20、上限 100)、
|
||||
* `product_code`/`title_keyword`/`group_id`/`synced_from`/`synced_to`
|
||||
* (ISO yyyy-MM-dd;空白不下发;groupId 空串→不带、有值→snake group_id);分页钳制(铁律 15)。
|
||||
* `product_code`/`title_keyword`/`group_id`/`owner_group_id`/`synced_from`/`synced_to`
|
||||
* (ISO yyyy-MM-dd;空白不下发;groupId 空串→不带、有值→snake group_id;ownerGroupId>0 才带、
|
||||
* 0/null/NaN 一律不带=后端按作用域默认分组取,V203);分页钳制(铁律 15)。
|
||||
* 商品状态筛选与导出参数口已随 2026-11-15 客户口径下线,不再出现在参数面;
|
||||
* 店铺筛选同日客户口径「店铺不需要」下线(shop_name 也不在参数面)。
|
||||
* 2. **详情解析**:parseJdProductDetail 解析 attrGroups/images(camel 为正 snake 容错、缺 url 弃行),
|
||||
@@ -59,6 +60,8 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
|
||||
},
|
||||
2,
|
||||
20,
|
||||
// V203 第 4 参=当前数据权限分组(分类列/分类筛选的作用域,不是筛选条件)。
|
||||
11,
|
||||
)
|
||||
assert.deepEqual(full, {
|
||||
page: 2,
|
||||
@@ -66,6 +69,7 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
|
||||
product_code: 'JD-10086',
|
||||
title_keyword: '保温杯',
|
||||
group_id: 7,
|
||||
owner_group_id: 11,
|
||||
synced_from: '2026-11-01',
|
||||
synced_to: '2026-11-09',
|
||||
})
|
||||
@@ -75,6 +79,7 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
|
||||
const blank = toJdProductListParams(createJdProductFilterState(), 1, 20)
|
||||
assert.deepEqual(blank, { page: 1, page_size: 20 })
|
||||
assert.equal('group_id' in blank, false, 'groupId 空串不带 group_id')
|
||||
assert.equal('owner_group_id' in blank, false, '没传当前分组就不带 owner_group_id(后端按作用域默认组取)')
|
||||
const dirty = toJdProductListParams(
|
||||
{ productCode: '', titleKeyword: '', groupId: 'abc', syncedFrom: '2026/11/01', syncedTo: 'not-a-date' },
|
||||
1,
|
||||
@@ -82,6 +87,11 @@ test('京东列表参数——snake 形状:groupId 空→不带、有值→gro
|
||||
)
|
||||
assert.deepEqual(dirty, { page: 1, page_size: 20 }, '脏值不下发')
|
||||
assert.equal('sale_status' in full, false, '商品状态筛选已下线,参数面不再出现 sale_status')
|
||||
// 当前分组非法值(0/NaN/null)一律不下发:0 是「不属于任何组」的哨兵,不能当组 id 发出去。
|
||||
for (const bad of [0, null, undefined, Number.NaN]) {
|
||||
assert.equal('owner_group_id' in toJdProductListParams(createJdProductFilterState(), 1, 20, bad), false,
|
||||
`ownerGroupId=${String(bad)} 不得下发 owner_group_id`)
|
||||
}
|
||||
})
|
||||
|
||||
test('京东列表参数——page 钳制防 (page-1)*page_size 溢出(铁律 15)', () => {
|
||||
|
||||
@@ -27,6 +27,7 @@ const jdApi = vi.hoisted(() => ({
|
||||
fetchJdProductDetail: vi.fn(),
|
||||
deleteJdProducts: vi.fn(),
|
||||
fetchJdProductGroups: vi.fn(),
|
||||
fetchJdCategoryScope: vi.fn(),
|
||||
fetchJdProductCategories: vi.fn(),
|
||||
createJdProductGroup: vi.fn(),
|
||||
updateJdProductGroup: vi.fn(),
|
||||
@@ -75,11 +76,24 @@ function item(id: number, over: Record<string, unknown> = {}) {
|
||||
|
||||
let pinia: Pinia
|
||||
|
||||
/** 分组 id 常量:默认作用域就这一个可见且可写的组(组长档形状),分类与行集都按它取。 */
|
||||
const GROUP_A = 11
|
||||
|
||||
/** 分类作用域夹具(GET /scope 的归一形状):单组默认场景。 */
|
||||
function singleGroupScope(editable = true) {
|
||||
return {
|
||||
platformSuperAdmin: false,
|
||||
defaultGroupId: GROUP_A,
|
||||
groups: [{ id: GROUP_A, name: '甲组', label: '甲组', editable }],
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope())
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([])
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([])
|
||||
confirmMock.mockResolvedValue(true)
|
||||
@@ -121,7 +135,9 @@ describe('店铺分类弹窗', () => {
|
||||
await wrapper.findAll('button').find(b => b.text() === '店铺分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.group-modal')
|
||||
expect(modal.text()).toContain('价格/库存等字段停更')
|
||||
expect(modal.text()).toContain('不影响采集对价格/库存的更新', 'V203 归类不再置人工编辑锁,文案不得再说「停更」')
|
||||
expect(modal.text()).not.toContain('停更', '旧「价格/库存等字段停更」口径已废(归类不再置锁)')
|
||||
expect(modal.text()).toContain('甲组', '标题带当前分组名(跨组同名分类靠它区分)')
|
||||
expect(modal.find('.scope-tabs').exists()).toBe(false)
|
||||
await modal.get('.group-row').trigger('click')
|
||||
await modal.get('.cat-trigger').trigger('click')
|
||||
@@ -133,11 +149,12 @@ describe('店铺分类弹窗', () => {
|
||||
await modal.get('tbody input[type="checkbox"]').setValue(true)
|
||||
await modal.findAll('button').find(b => b.text().includes('归入「甲组」'))!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], 7)
|
||||
// 归类落点是「本组」的归属行:第三个参数必须是当前分组(V203 一组一商品一行)。
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], 7, GROUP_A)
|
||||
await modal.get('tbody input[type="checkbox"]').setValue(true)
|
||||
await modal.findAll('button').find(b => b.text() === '移出分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null)
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null, GROUP_A)
|
||||
await modal.get('.modal-close').trigger('click')
|
||||
expect(wrapper.find('.group-modal').exists()).toBe(false)
|
||||
wrapper.unmount()
|
||||
@@ -200,7 +217,7 @@ describe('店铺分类弹窗', () => {
|
||||
await modal.get('thead input').setValue(true)
|
||||
await modal.findAll('button').find(b => b.text() === '移出分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null)
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null, GROUP_A)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
@@ -249,7 +266,8 @@ describe('店铺分类弹窗', () => {
|
||||
await modal.get('.group-create input').setValue('新分类')
|
||||
await modal.get('.create-icon-btn').trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.createJdProductGroup).toHaveBeenCalledWith({ name: '新分类', sortOrder: 0 })
|
||||
// 新建落当前分组的归属(V203 跨组不可见:不带 ownerGroupId 会落到后端默认组)。
|
||||
expect(jdApi.createJdProductGroup).toHaveBeenCalledWith({ name: '新分类', sortOrder: 0, ownerGroupId: GROUP_A })
|
||||
await modal.findAll('button').find(b => b.text() === '改名')!.trigger('click')
|
||||
await modal.get('.group-row input').setValue('改名后')
|
||||
await modal.findAll('button').find(b => b.text() === '保存')!.trigger('click')
|
||||
@@ -728,3 +746,136 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(failed.find('.load-failure-bar').text()).toContain('京东商品列表加载失败')
|
||||
})
|
||||
})
|
||||
|
||||
/** 写权限分档(2026-11-16 用户口径):
|
||||
* 商品行写(编辑/删除/勾选批量删)只对平台超管渲染;
|
||||
* 分类写由 scope 的每组 editable 决定(本组管理员/公司超管/平台超管)——同组普通号
|
||||
* 能打开「店铺分类」弹窗看(用户原话「可以进弹窗里看 但是不能添加删除分类」),
|
||||
* 但新建/改名/删除与归类入口都不渲染,后端同口径 403 兜底。 */
|
||||
describe('京东数据库写权限分档(商品行写=平台超管;分类写=本组 editable)', () => {
|
||||
it('非超管只读:无勾选列、无操作列、无删除勾选;列表/筛选/详情照常,弹窗可看不可改', async () => {
|
||||
useAdminSessionStore().user = { id: 2, username: 'ops', role: 'admin' }
|
||||
// 同组普通号:可见但不可写(editable=false)。
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(false))
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({ item: item(1), attrGroups: [], images: [], skus: [], attrJsonRaw: '' }),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
|
||||
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(0, '非超管不渲染勾选列(勾选只为批量删除服务)')
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false, '批量删除按钮不渲染')
|
||||
expect(wrapper.find('thead').text()).not.toContain('操作', '操作列(编辑/删除)不渲染')
|
||||
expect(wrapper.text()).toContain('只读:编辑/删除仅超级管理员可用;分类由本组管理员维护', '只读提示必须看得见并区分两类写权限')
|
||||
|
||||
// 读面不受影响:筛选下拉、列表行、点行开详情都还在。
|
||||
expect(wrapper.get('[aria-label="筛选店铺分类"]').exists()).toBe(true, '分类筛选是读面,保留')
|
||||
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
|
||||
expect(cells).toHaveLength(5, '非超管列表 5 列:分类/商品信息/总库存/价格/同步时间')
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(true, '点行仍可开只读详情抽屉')
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
|
||||
await wrapper.find('.drawer-mask').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
// 「店铺分类」弹窗对所有有本页菜单权限的人可见(可以进弹窗里看)……
|
||||
const dialogButton = wrapper.findAll('button').find((b) => b.text() === '店铺分类')
|
||||
expect(dialogButton, '同组普通号也能打开分类弹窗(只读查看)').toBeTruthy()
|
||||
await dialogButton!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.group-modal')
|
||||
expect(modal.text()).toContain('本组分类(只读)', '弹窗文案点名只读')
|
||||
expect(modal.text()).toContain('甲组', '看得到本组分类')
|
||||
// ……但没有建/改/删与归类入口(用户原话「不能添加删除分类」)。
|
||||
expect(modal.find('.group-create').exists()).toBe(false, '只读账号不渲染新建输入行')
|
||||
expect(modal.findAll('button').some((b) => b.text() === '改名')).toBe(false, '无改名入口')
|
||||
expect(modal.findAll('button').some((b) => b.text() === '删除')).toBe(false, '无删除入口')
|
||||
expect(modal.find('tbody input[type="checkbox"]').exists()).toBe(false, '右栏无勾选列(没有归类写入口)')
|
||||
expect(modal.findAll('button').some((b) => b.text().includes('归入') || b.text() === '移出分类')).toBe(false,
|
||||
'无归入/移出入口')
|
||||
expect(jdApi.batchAssignJdProductGroup).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('超管保留全部写入口(勾选列+操作列+删除勾选+店铺分类),且不显示只读提示', async () => {
|
||||
// beforeEach 默认 super_admin;这里显式再钉一次,防默认值漂移把这条闸门变成恒绿。
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
|
||||
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(1)
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(7)
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
|
||||
expect(wrapper.findAll('button').some((b) => b.text() === '店铺分类')).toBe(true)
|
||||
expect(wrapper.text()).not.toContain('只读:')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('本组管理员(非平台超管):商品行仍只读,但分类弹窗有建/改/删与归类入口', async () => {
|
||||
useAdminSessionStore().user = { id: 3, username: 'leader', role: 'admin' }
|
||||
// 组长档形状:可见组可写 ⇒ editable=true,商品行写仍按 isSuperAdmin 判(不受 editable 影响)。
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(true))
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(0, '组管理员也不动商品行(编辑/删除只归平台超管)')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '店铺分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.group-modal')
|
||||
expect(modal.find('.group-create').exists()).toBe(true, '本组管理员能新建分类')
|
||||
expect(modal.findAll('button').some((b) => b.text() === '删除')).toBe(true, '能删除分类')
|
||||
expect(modal.find('tbody input[type="checkbox"]').exists()).toBe(true, '能勾选商品归类')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
/** 分组作用域(V203):不同组看不到彼此的分类;能看多组的人用「分组」下拉切换。 */
|
||||
describe('京东数据库分类按数据权限分组隔离(V203)', () => {
|
||||
it('多组可见:工具栏出「分组」下拉,切换后分类下拉与列表一并用新组取', async () => {
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue({
|
||||
platformSuperAdmin: true,
|
||||
defaultGroupId: 11,
|
||||
groups: [
|
||||
{ id: 11, name: 'A组', label: '甲公司 / A组', editable: true },
|
||||
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: true },
|
||||
],
|
||||
})
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
// 首屏就按默认组取(不是先不带 ownerGroupId 再补一次)。
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(11)
|
||||
expect(jdApi.fetchJdProductList.mock.calls[0][0]).toMatchObject({ ownerGroupId: 11 })
|
||||
|
||||
const picker = wrapper.get('[aria-label="当前分组"]')
|
||||
expect(picker.findAll('option').map((o) => o.text())).toEqual(['甲公司 / A组', '甲公司 / B组'],
|
||||
'跨公司组名由后端拼进 label,前端不解析公司字段')
|
||||
|
||||
await picker.setValue('12')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(12)
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ownerGroupId: 12, page: 1 },
|
||||
'切组后列表按新组重取并回第一页')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('只有一组:不出下拉(锁定显示组名),分类与行集仍按该组取', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false, '单组不渲染切换下拉')
|
||||
expect(wrapper.get('.jd-group-locked').text()).toBe('分组:甲组')
|
||||
expect(jdApi.fetchJdProductList.mock.calls[0][0]).toMatchObject({ ownerGroupId: GROUP_A })
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('不属于任何数据权限分组:分类全空、不给切换,弹窗直说「你还不属于任何数据权限分组」', async () => {
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue({ platformSuperAdmin: false, defaultGroupId: null, groups: [] })
|
||||
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false)
|
||||
expect(wrapper.find('.jd-group-locked').exists()).toBe(false, '没有分组就没有可锁定的组名')
|
||||
expect(wrapper.find('[aria-label="筛选店铺分类"]').text()).toContain('全部分类', '分类筛选只剩「全部分类」')
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[1].text()).toBe('未分类')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '店铺分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('.group-modal').text()).toContain('你还不属于任何数据权限分组')
|
||||
expect(jdApi.batchAssignJdProductGroup).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -85,6 +85,24 @@ public final class DeviceSessionPolicy {
|
||||
return isSuper(resolveRole(role, isAdmin, createdById));
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否<b>公司超级管理员</b>(本公司最高账号,数据只看本公司)。
|
||||
*
|
||||
* <p>为什么收这一处:这条比较在 src/main 里已有 22 处手抄({@code AdminUserService} 14、
|
||||
* {@code PermissionMenuService} 4、去重/分组/到期停任务/看板各 1)。京东数据库分类按
|
||||
* 「公司 → 数据权限分组」两级隔离(V203)需要它,新写点再手抄一份就是第 23 处,故先在这里
|
||||
* 收一个出口;<b>不改既有调用方</b>——要把那 22 处收进来,得连「业务数据面同权、管理动作收窄」
|
||||
* 那条定案一起落(见本类 {@link #COMPANY_SUPER_ADMIN} 注释)。</p>
|
||||
*/
|
||||
public static boolean isCompanySuperAdmin(String resolvedRole) {
|
||||
return COMPANY_SUPER_ADMIN.equals(resolvedRole);
|
||||
}
|
||||
|
||||
/** {@link #isCompanySuperAdmin(String)} 的原始字段版本(自行 resolve 角色)。 */
|
||||
public static boolean isCompanySuperAdmin(String role, Integer isAdmin, Long createdById) {
|
||||
return isCompanySuperAdmin(resolveRole(role, isAdmin, createdById));
|
||||
}
|
||||
|
||||
/** 从 JWT claims 中提取签名的设备号;缺失返回空串。 */
|
||||
public static String claimDeviceId(Claims claims) {
|
||||
Object raw = claims == null ? null : claims.get("deviceId");
|
||||
|
||||
+1
-1
@@ -800,7 +800,7 @@ public class AppearancePatentLlmClient {
|
||||
recordSecretUsage();
|
||||
Map<String, Object> body = buildChatBody(model, system, userText, images, responseFormat);
|
||||
String host = resolveHost();
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.5-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.1-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
String requestModel = LlmChannel.modelForHost(host, model);
|
||||
body.put("model", requestModel);
|
||||
// 思考参数按渠道补:贞贞把 thinking 写在模型名里,龙抬头要显式传(复刻现网的 thinking-medium)
|
||||
|
||||
+82
-25
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest;
|
||||
@@ -13,7 +14,9 @@ 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.JdCategoryScopeService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
@@ -57,15 +60,18 @@ import java.util.List;
|
||||
*
|
||||
* <p>鉴权照外观专利只读页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 →
|
||||
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
|
||||
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。</p>
|
||||
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。
|
||||
* <b>2026-11-16 起读/写分档</b>:读(列表/类目/详情)按上面的菜单口径放行;写(编辑/上传图片/
|
||||
* 删除/批量删除/批量归类)在菜单口径之上再要求平台超管,非超管一律 403(前端同窗隐藏写入口)。</p>
|
||||
*
|
||||
* <p><b>公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」)</b>:读侧零公司
|
||||
* 维度——company_id 请求参数与 {@code superAdminScopedCompanyId} 谓词已随公共化收尾整批
|
||||
* 摘除(2026-11-15 定案「京东数据库不区分公司、属于公共的」的最后一截),行上的 company_id
|
||||
* 只剩「哪家公司客户端同步的」来源标记,不构成可见性边界;每个拿到本页菜单权限的管理员
|
||||
* (含站点超管)看到同一份全量公共库。详情与写侧(编辑/删除)同样没有公司维度:
|
||||
* 对全部公共行可编辑可删除(同商品类目「谁都能改」的 2026-10-06 定案形状),写侧端点的
|
||||
* company_id 传参已随 2026-11-15 公共化摘除。</p>
|
||||
* 对全部公共行可编辑可删除,但<b>写动作只对平台超管开放</b>(2026-11-16 用户口径
|
||||
* 「京东数据库只有超管有编辑删除权限」,见 {@code requirePlatformSuperAdminWrite}),
|
||||
* 写侧端点的 company_id 传参已随 2026-11-15 公共化摘除。</p>
|
||||
*
|
||||
* <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
|
||||
* {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。店铺筛选参数
|
||||
@@ -90,6 +96,8 @@ public class AdminJdProductController {
|
||||
private final JdProductQueryService jdProductQueryService;
|
||||
private final JdProductDeleteService jdProductDeleteService;
|
||||
private final JdProductUpdateService jdProductUpdateService;
|
||||
private final JdProductGroupService jdProductGroupService;
|
||||
private final JdCategoryScopeService jdCategoryScopeService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
|
||||
@@ -106,17 +114,24 @@ public class AdminJdProductController {
|
||||
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
|
||||
@Parameter(description = "类目(京麦末级类目名,eq)") @RequestParam(name = "category", required = false) String category,
|
||||
@Parameter(description = "自定义分类 id(类目面板「自定义分类」选中驱动)") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "当前数据权限分组 id(分类列/分类筛选按它取;缺省=作用域默认分组)")
|
||||
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
|
||||
@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,
|
||||
HttpServletRequest request) {
|
||||
requireJdAccess(request);
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
if (request.getParameter("grouped") != null || request.getParameter("ungrouped") != null) {
|
||||
throw new BusinessException("页面版本已更新,请刷新页面后重新查询");
|
||||
}
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
Long scopedOwnerGroupId = jdCategoryScopeService.readGroupOrNull(scope, ownerGroupId);
|
||||
if (groupId != null && groupId > 0) {
|
||||
requireVisibleCategory(scope, groupId);
|
||||
}
|
||||
return ApiResponse.success(jdProductQueryService.page(page, pageSize,
|
||||
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo));
|
||||
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, scopedOwnerGroupId));
|
||||
}
|
||||
|
||||
@GetMapping("/categories")
|
||||
@@ -134,26 +149,31 @@ public class AdminJdProductController {
|
||||
+ "公共库无公司维度:按 id 直取,越界 id 按不存在拒绝。")
|
||||
public ApiResponse<JdProductDetailVo> detail(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
@Parameter(description = "当前数据权限分组 id(分类字段按它取)")
|
||||
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
|
||||
HttpServletRequest request) {
|
||||
requireJdAccess(request);
|
||||
return ApiResponse.success(jdProductQueryService.detail(id));
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
Long scopedOwnerGroupId = jdCategoryScopeService.readGroupOrNull(
|
||||
jdCategoryScopeService.resolve(operator.user()), ownerGroupId);
|
||||
return ApiResponse.success(jdProductQueryService.detail(id, scopedOwnerGroupId));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "编辑京东商品", description = "主字段全量提交(标题/品牌/类目/货号/价格区间/总库存/"
|
||||
+ "状态/分组),可选块缺省不动:attrGroups 重建 attr_json 的 tabs 段(其余顶层键保留)、"
|
||||
+ "skus 按 skuId 改价格库存、deleteImageIds 删图(共用对象保留)。保存即置人工编辑锁"
|
||||
@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);
|
||||
RequestOperator operator = requirePlatformSuperAdminWrite(request);
|
||||
Long updatedId = jdProductUpdateService.update(id, body);
|
||||
log.info("[jd-product] 编辑商品 operatorId={} id={} title={}",
|
||||
operator.id(), updatedId, body.getTitle());
|
||||
// 返回刷新后的详情(前端保存后直接回填抽屉),复用详情同一查询出口。
|
||||
return ApiResponse.success(jdProductQueryService.detail(updatedId));
|
||||
return ApiResponse.success(jdProductQueryService.detail(updatedId, null));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/{id}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@@ -172,12 +192,12 @@ public class AdminJdProductController {
|
||||
@Parameter(description = "替换目标图片登记行 id(缺省=新增)")
|
||||
@RequestParam(value = "replace_image_id", required = false) Long replaceImageId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
RequestOperator operator = requirePlatformSuperAdminWrite(request);
|
||||
Long updatedId = jdProductUpdateService.uploadImage(id, file, imageType, attrName, replaceImageId);
|
||||
log.info("[jd-product] 上传图片 operatorId={} id={} replaceImageId={} imageType={}",
|
||||
operator.id(), updatedId, replaceImageId, imageType);
|
||||
// 返回刷新后的详情(前端上传后直接回填抽屉图片区),复用详情同一查询出口。
|
||||
return ApiResponse.success(jdProductQueryService.detail(updatedId));
|
||||
return ApiResponse.success(jdProductQueryService.detail(updatedId, null));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@@ -187,7 +207,7 @@ public class AdminJdProductController {
|
||||
public ApiResponse<JdProductDeleteVo> delete(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
RequestOperator operator = requirePlatformSuperAdminWrite(request);
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(List.of(id));
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪些行、桶里清了几个对象(同分组删除口径)。
|
||||
log.info("[jd-product] 删除商品 operatorId={} id={} deleted={} objectsDeleted={}",
|
||||
@@ -196,19 +216,23 @@ public class AdminJdProductController {
|
||||
}
|
||||
|
||||
@PostMapping("/batch-assign-group")
|
||||
@Operation(summary = "批量归类京东商品(店铺分类弹窗)", description = "勾选商品行 → 归入指定分类"
|
||||
+ "(groupId 必须真实存在)或移出分类(groupId=null,group_id 置 NULL)。与单行编辑"
|
||||
+ "同口径:归类即人工干预,落 manual_locked=1(采集 upsert/登记/覆盖清理此后跳过本行,"
|
||||
+ "分类不被重爬清理冲掉,代价是该行价格/库存随锁停更)。单次最多 200 个;id 不存在的"
|
||||
+ "行不计入更新数、不整批拒绝(弹窗行集与库行有采集刷新时间差,掉队行跳过)。")
|
||||
@Operation(summary = "批量归类京东商品(店铺分类弹窗)", description = "勾选商品行 → 归入当前数据权限分组的"
|
||||
+ "某个分类(groupId 必须真实存在且属于该分组)或移出分类(groupId=null,删本组归属行)。"
|
||||
+ "归类写 biz_jd_product_group_assign 的 (product_id, owner_group_id) 一行——同一商品各组"
|
||||
+ "可各自归类;<b>不再置人工编辑锁</b>(分类不在商品行上,采集刷新冲不掉它,锁只会让"
|
||||
+ "共享行的价格/库存对所有组停更)。写权限=本组管理员/公司超管/平台超管。"
|
||||
+ "单次最多 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());
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
ShopManageGroupEntity target = jdCategoryScopeService.requireWritableGroup(scope, body.getOwnerGroupId());
|
||||
int updated = jdProductUpdateService.assignGroup(target.getId(), target.getCompanyId(),
|
||||
body.getIds(), body.getGroupId(), operator.id());
|
||||
// 管理端写动作必须留痕:谁、把多少行归到哪个组的哪个分类(null=移出分类)。
|
||||
log.info("[jd-product] 批量归类 operatorId={} ownerGroupId={} requested={} updated={} groupId={}",
|
||||
operator.id(), target.getId(), body.getIds().size(), updated, body.getGroupId());
|
||||
return ApiResponse.success(updated);
|
||||
}
|
||||
|
||||
@@ -218,7 +242,7 @@ public class AdminJdProductController {
|
||||
public ApiResponse<JdProductDeleteVo> batchDelete(
|
||||
@Valid @RequestBody JdProductBatchDeleteRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
RequestOperator operator = requirePlatformSuperAdminWrite(request);
|
||||
JdProductDeleteVo vo = jdProductDeleteService.delete(body.getIds());
|
||||
log.info("[jd-product] 批量删除商品 operatorId={} requested={} deleted={} objectsDeleted={} kept={}",
|
||||
operator.id(), body.getIds().size(), vo.getDeleted(),
|
||||
@@ -238,6 +262,39 @@ public class AdminJdProductController {
|
||||
return new RequestOperator(operator.getId(), superAdmin, operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写端点的越权闸(2026-11-16 用户口径「京东数据库只有超管有编辑删除权限」)。
|
||||
*
|
||||
* <p>读保持菜单权限口径(拿到 {@code admin_jd_database} 列权限的管理员可见同一份公共库),
|
||||
* 写(编辑 / 上传图片 / 单行删除 / 批量删除 / 批量归类)收窄到<b>平台超级管理员</b>:
|
||||
* 与 {@code BrandGatingController#requirePlatformSuperAdmin}、
|
||||
* {@code AdminDeviceLogController#requireSuperAdmin} 同一判据(
|
||||
* {@code DeviceSessionPolicy#isSuper} 只认站点 super_admin,公司超管不在内)。</p>
|
||||
*
|
||||
* <p>写动作会置人工编辑锁({@code manual_locked=1})并物理删除桶内图片,属影响全平台公共
|
||||
* 数据的动作,故不随读权限下放;非超管拿到 403 时前端已不渲染这些入口,本闸是兜底。</p>
|
||||
*/
|
||||
private RequestOperator requirePlatformSuperAdminWrite(HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
if (!operator.superAdmin()) {
|
||||
log.warn("[jd-product] 非平台超管写操作被拒 operatorId={} role={}",
|
||||
operator.id(), adminAuthSupport.currentRole(operator.user()));
|
||||
throw new BusinessException(403, "仅平台超级管理员可以编辑或删除京东数据库数据");
|
||||
}
|
||||
return operator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分类筛选面的越权闸:请求里的 {@code group_id} 必须是本账号可见组下的分类,
|
||||
* 否则 403(分类按数据权限分组隔离,V203;不认识的 id 直接拒,不做"空结果"降级)。
|
||||
*/
|
||||
private void requireVisibleCategory(JdCategoryScopeService.JdCategoryScope scope, Long categoryId) {
|
||||
Long ownerGroupId = jdProductGroupService.requireCategory(categoryId).getOwnerGroupId();
|
||||
if (!scope.canRead(ownerGroupId)) {
|
||||
throw new BusinessException(403, "无权查看该分组的分类");
|
||||
}
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveOperator(HttpServletRequest request) {
|
||||
try {
|
||||
return adminAuthSupport.requireUser(request);
|
||||
|
||||
+70
-27
@@ -3,10 +3,13 @@ package com.nanri.aiimage.modules.jd.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -23,82 +26,122 @@ 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;
|
||||
|
||||
/**
|
||||
* 后管「京东数据库」分组管理(v1.4 Phase 5,R4):新建 / 改名 / 删除 / 下拉列表。
|
||||
* 后管「京东数据库」分类管理(v1.4 Phase 5,R4;V203 改按数据权限分组归属)。
|
||||
*
|
||||
* <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>归属口径(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类,
|
||||
* 同组普通号只读」):一行分类属于<b>一个数据权限分组</b>({@code biz_shop_manage_group}),
|
||||
* 公司→组两级隔离。作用域由 {@link JdCategoryScopeService} 解析,本控制器只做两件事:
|
||||
* ①把请求里的 {@code owner_group_id} 收敛成「当前分组」;②写端点校验该组可写。</p>
|
||||
*
|
||||
* <p>鉴权与 {@code AdminJdProductController} 同款私有闸(同一 column_key/route_path):
|
||||
* 普通授权用户可读写分组(AC-9),默认仅 super_admin。</p>
|
||||
* <ul>
|
||||
* <li>读(列表 / 作用域):拿到本页菜单权限即可,只能看自己可见组(本组普通号也能看);</li>
|
||||
* <li>写(新建/改名/删除):本组管理员、公司超管(本公司全部组)、平台超管(全部组);
|
||||
* 普通号 403。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>删除分类不删商品:只删该分类的归类归属行({@code biz_jd_product_group_assign}),
|
||||
* 商品行留在公共库里(见 {@link JdProductGroupService#delete})。</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";
|
||||
private static final String ROUTE_PATH = "jd-center/database";
|
||||
|
||||
private final JdProductGroupService jdProductGroupService;
|
||||
private final JdCategoryScopeService jdCategoryScopeService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分组列表(含组内商品数)", description = "全平台全部分组,按 sort_order, id 升序;"
|
||||
+ "productCount 为读侧现算列(分组下拉展示用)。")
|
||||
public ApiResponse<List<JdProductGroupVo>> list(HttpServletRequest request) {
|
||||
requireJdAccess(request);
|
||||
return ApiResponse.success(jdProductGroupService.list());
|
||||
@Operation(summary = "分类列表(含分类下商品数)", description = "按「当前分组」返回分类,"
|
||||
+ "按 sort_order, id 升序;owner_group_id 缺省=作用域默认分组(可见组第一项)。"
|
||||
+ "一个可见组都没有时返回空列表(普通号也能读)。")
|
||||
public ApiResponse<List<JdProductGroupVo>> list(
|
||||
@Parameter(description = "数据权限分组 id(缺省=默认分组)")
|
||||
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
return ApiResponse.success(jdProductGroupService.list(
|
||||
jdCategoryScopeService.readGroupOrNull(scope, ownerGroupId)));
|
||||
}
|
||||
|
||||
@GetMapping("/scope")
|
||||
@Operation(summary = "分类作用域(分组下拉 + 可写标记)", description = "本账号可见的数据权限分组清单"
|
||||
+ "(平台超管=全部公司全部组、公司超管=本公司、管理员/普通号=自己带的组+自己所属组的组长)"
|
||||
+ "与每组是否可写;前端用它渲染「分组」下拉并按 editable 隐藏分类写入口。")
|
||||
public ApiResponse<JdCategoryScopeVo> scope(HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
return ApiResponse.success(jdCategoryScopeService.scopeVo(operator.user()));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新建分组", description = "重名按业务错误拒绝(409),不落库;公共库无公司归属。")
|
||||
@Operation(summary = "新建分类", description = "归属当前分组(ownerGroupId 缺省=自己带的那个组);"
|
||||
+ "同一分组内重名按 409 业务错误拒绝,不落库。")
|
||||
public ApiResponse<Long> create(
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
Long id = jdProductGroupService.create(body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 新建分组 operatorId={} groupId={}", operator.id(), id);
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
ShopManageGroupEntity target = jdCategoryScopeService.requireWritableGroup(scope, body.getOwnerGroupId());
|
||||
Long id = jdProductGroupService.create(target.getId(), target.getCompanyId(),
|
||||
body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 新建分类 operatorId={} ownerGroupId={} categoryId={}",
|
||||
operator.id(), target.getId(), id);
|
||||
return ApiResponse.success(id);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "分组改名/改排序", description = "越界 id(不存在)按不存在拒绝;"
|
||||
+ "改成已有名字按业务错误拒绝(409)。")
|
||||
@Operation(summary = "分类改名/改排序", description = "越界 id(不存在)按不存在拒绝;"
|
||||
+ "改成本组已有名字按业务错误拒绝(409);非本组管理员 403。")
|
||||
public ApiResponse<Boolean> rename(
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
@Parameter(description = "分类 id") @PathVariable("id") Long id,
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
|
||||
requireWritableCategory(scope, ownerGroupId);
|
||||
jdProductGroupService.rename(id, body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 分组改名 operatorId={} groupId={}", operator.id(), id);
|
||||
log.info("[jd-product-group] 分类改名 operatorId={} ownerGroupId={} categoryId={}",
|
||||
operator.id(), ownerGroupId, id);
|
||||
return ApiResponse.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除分组", description = "删除分组不删商品(AC-8):先同事务把该组商品 "
|
||||
+ "group_id 置 NULL 再删分组行;返回实际脱组的商品行数。越界 id 按不存在拒绝。")
|
||||
@Operation(summary = "删除分类", description = "只删该分类的归类归属行(商品保留在公共库,"
|
||||
+ "回到该组的未分类);返回实际解挂的归属行数。非本组管理员 403。")
|
||||
public ApiResponse<Integer> delete(
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
@Parameter(description = "分类 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolve(operator.user());
|
||||
Long ownerGroupId = jdProductGroupService.requireCategory(id).getOwnerGroupId();
|
||||
requireWritableCategory(scope, ownerGroupId);
|
||||
int detached = jdProductGroupService.delete(id);
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪个分组、脱组了多少商品。
|
||||
log.info("[jd-product-group] 删除分组 operatorId={} groupId={} detached={}",
|
||||
operator.id(), id, detached);
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪个分类、解挂了多少商品归属。
|
||||
log.info("[jd-product-group] 删除分类 operatorId={} ownerGroupId={} categoryId={} detached={}",
|
||||
operator.id(), ownerGroupId, id, detached);
|
||||
return ApiResponse.success(detached);
|
||||
}
|
||||
|
||||
private void requireWritableCategory(JdCategoryScopeService.JdCategoryScope scope, Long ownerGroupId) {
|
||||
if (!scope.canWrite(ownerGroupId)) {
|
||||
throw new BusinessException(403, "仅该分组的管理员可以修改它的分类");
|
||||
}
|
||||
}
|
||||
|
||||
private RequestOperator requireJdAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = resolveOperator(request);
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
|
||||
+9
-6
@@ -14,6 +14,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdIngestChunkVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCollectBoardService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCollectTaskService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
@@ -63,6 +64,7 @@ public class JdCollectController {
|
||||
private final JdResultIngestService ingestService;
|
||||
private final JdProductQueryService jdProductQueryService;
|
||||
private final JdProductGroupService jdProductGroupService;
|
||||
private final JdCategoryScopeService jdCategoryScopeService;
|
||||
private final TaskHeartbeatService taskHeartbeatService;
|
||||
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
|
||||
private final TaskProgressOwnershipSupport progressOwnershipSupport;
|
||||
@@ -82,13 +84,14 @@ public class JdCollectController {
|
||||
@GetMapping("/groups")
|
||||
@Operation(summary = "店铺分类列表(用户侧只读)", description = "2026-11-16 客户口径「管理员弄了多少"
|
||||
+ "店铺分类 普通账户都能看到」:「获取店铺数据」页把管理员在后管京东数据库建的分类展示出来"
|
||||
+ "(含组内商品数),普通账号登录即可见。与后管分组管理同一条读出口(JdProductGroupService.list,"
|
||||
+ "分组 2026-11-15 起全平台一份、无公司维度);只读不写——分类的增删改仍只在后管。"
|
||||
+ "「商品上架」未落地(jd-publish 占位),上架界面落地时消费同一端点。")
|
||||
+ "(含分类下商品数)。<b>V203 起按数据权限分组隔离</b>:只返回当前登录用户可见组"
|
||||
+ "(自己所属组的组长带的组)的分类,别组的一律不下发——这正是「不同组不能看到跨组的分类」。"
|
||||
+ "只读不写——分类的增删改仍只在后管(本组管理员)。")
|
||||
public ApiResponse<List<JdProductGroupVo>> groups(HttpServletRequest httpRequest) {
|
||||
// 登录用户即可读(公共库口径):解析不出会话身份就 401(fail-closed,与 categories 同口径)。
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, null);
|
||||
return ApiResponse.success(jdProductGroupService.list());
|
||||
// 登录用户即可读:解析不出会话身份就 401(fail-closed,与建单同口径)。
|
||||
Long userId = adminAuthSupport.requireOwnershipUserId(httpRequest, null);
|
||||
JdCategoryScopeService.JdCategoryScope scope = jdCategoryScopeService.resolveByUserId(userId);
|
||||
return ApiResponse.success(jdProductGroupService.listForGroups(scope.visibleGroupIds()));
|
||||
}
|
||||
|
||||
@GetMapping("/dashboard")
|
||||
|
||||
+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.JdProductGroupAssignEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 京东商品按组归类归属({@code biz_jd_product_group_assign},V203)数据访问口。
|
||||
*
|
||||
* <p>全部走 BaseMapper + wrapper(铁律 1 允许的两种形态之一,与 {@code JdProductGroupMapper}
|
||||
* 同形状,无 XML):读=按 {@code owner_group_id} 批量取一组的归属、按 {@code category_id} 计数;
|
||||
* 写=存在则改挂、不存在则插入(唯一键 {@code uk_product_owner}),移出分类走 delete。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface JdProductGroupAssignMapper extends BaseMapper<JdProductGroupAssignEntity> {
|
||||
}
|
||||
+19
@@ -31,6 +31,25 @@ public class JdCollectTaskCreateRequest {
|
||||
* 要采集的京麦末级类目名(多选,客户端按行 {@code categoryPath} 等值过滤,只对命中商品
|
||||
* 开详情采集);null/空=全店采集。服务端建单口归一化(trim/去空/去重)后写进
|
||||
* {@code request_json},与派发载荷、客户端过滤同源。
|
||||
*
|
||||
* @deprecated 2026-11-16 建单页类目级联已下线(客户口径「类目不需要只要分类」),UI 不再
|
||||
* 产生该值;字段保留只为兼容已发版页面的历史行/在途任务(重试链从 request_json 回读)。
|
||||
*/
|
||||
@Deprecated
|
||||
private List<String> categoryPaths;
|
||||
|
||||
/**
|
||||
* 要采集的京麦「店内分类」名(2026-11-16 取证后新增,客户口径「选京麦的内部分类去采集」):
|
||||
* 多选 {@code ShopCategoryReadViewService.getShopCategoryList} 的 {@code label};客户端按行
|
||||
* {@code shopCategorys/shopCategoryPath/groupId} 等值过滤(任一键命中即命中)。null/空=全店采集。
|
||||
* 服务端建单口归一化后写进 {@code request_json},与派发载荷、客户端过滤三处同键。
|
||||
*/
|
||||
private List<String> shopCategoryNames;
|
||||
|
||||
/**
|
||||
* 要采集的京麦「店内分类」id(与 {@link #shopCategoryNames} 同一多选的 {@code value} 集)。
|
||||
* 行级 {@code shopCategorys} 填充形状未取证(可能是 id 数组也可能是对象),双键同发任一
|
||||
* 命中即命中;null/空=无 id 维度过滤。
|
||||
*/
|
||||
private List<String> shopCategoryIds;
|
||||
}
|
||||
|
||||
+9
-4
@@ -8,9 +8,11 @@ import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 后管京东商品批量归类请求体(店铺分类弹窗,2026-11-15):勾选商品行 → 归入左侧选中分类
|
||||
* 或移出分类。公共库写侧无公司维度(2026-11-15 用户定案),body 不带 company_id——
|
||||
* 公司维度的假 tab 形状随 2026-11-15 公共化已从写侧端点整批摘除。
|
||||
* 后管京东商品批量归类请求体(店铺分类弹窗,2026-11-15;V203 改按组隔离)。
|
||||
*
|
||||
* <p>归类归属 = {@code ownerGroupId}(当前「分组」下拉选中的<b>数据权限分组</b>):
|
||||
* 同一商品各组可各自归类,写进 {@code biz_jd_product_group_assign} 的
|
||||
* {@code (product_id, owner_group_id)} 一行。服务端校验该组可写、分类属于该组。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品批量归类请求(归入分类或移出分类)")
|
||||
@@ -21,6 +23,9 @@ public class JdProductBatchAssignGroupRequest {
|
||||
@Size(max = 200, message = "单次最多归类 200 个商品,请分批操作")
|
||||
private List<Long> ids;
|
||||
|
||||
@Schema(description = "目标分类 id;null=移出分类(group_id 置 NULL,商品回到未分类)")
|
||||
@Schema(description = "目标分类 id;null=移出分类(本组归属行删除,商品在本组回到未分类)")
|
||||
private Long groupId;
|
||||
|
||||
@Schema(description = "当前数据权限分组 id(缺省=操作者自己带的组)")
|
||||
private Long ownerGroupId;
|
||||
}
|
||||
|
||||
+10
-4
@@ -4,16 +4,22 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 京东商品分组新建/改名请求体(v1.4 Phase 5)。归属公司不走 body:由控制器经
|
||||
* {@code DataReadScope#readCompanyIdOrOwn} 的公司隔离正门算出,客户端伪造无效。
|
||||
* 京东商品分类新建/改名请求体(v1.4 Phase 5;V203 加归属分组)。
|
||||
*
|
||||
* <p>新建时 {@code ownerGroupId} 是<b>目标数据权限分组</b>(缺省=操作者自己带的那个组;
|
||||
* 能看多组的人由前端「分组」下拉传);服务端按作用域校验可写,客户端伪造无效。
|
||||
* 改名/删除不带它——归属以库里那一行为准。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品分组保存请求")
|
||||
@Schema(description = "京东商品分类保存请求")
|
||||
public class JdProductGroupSaveRequest {
|
||||
|
||||
@Schema(description = "分组名(同公司内唯一)")
|
||||
@Schema(description = "分类名(同一分组内唯一)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "下拉展示顺序(新建缺省 0;改名不传保持原值)")
|
||||
private Integer sortOrder;
|
||||
|
||||
@Schema(description = "新建时的目标数据权限分组 id(缺省=操作者自己带的组)")
|
||||
private Long ownerGroupId;
|
||||
}
|
||||
|
||||
+3
-2
@@ -56,8 +56,9 @@ public class JdProductUpdateRequest {
|
||||
@Size(max = 32, message = "商品状态最长 32 字")
|
||||
private String saleStatus;
|
||||
|
||||
@Schema(description = "分组 id(null=未分组;组 id 必须属于本公司)")
|
||||
private Long groupId;
|
||||
// 分类(groupId)【V203 起不在编辑面】:分类按数据权限分组隔离、归属存
|
||||
// biz_jd_product_group_assign,编辑抽屉不再写商品行的 group_id(走「店铺分类」弹窗归类)。
|
||||
// 旧前端仍带 groupId 时由 Jackson 忽略(未知字段不报错),不会静默写错列。
|
||||
|
||||
@Schema(description = "属性分组(可选块;缺省不动属性;提交时重建 attr_json 的 tabs 段,其余顶层键保留)")
|
||||
private List<AttrGroupDto> attrGroups;
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
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_group_assign},V203)。
|
||||
*
|
||||
* <p>为什么单独一张表:京东数据库的商品行是全平台公共的(2026-11-15 定案),而分类从
|
||||
* 2026-11-16 起按数据权限分组隔离(「同一商品各组可各自归类」)。商品行上的单值
|
||||
* {@code group_id} 放不下"每组一份归属",故按 {@code (product_id, owner_group_id)} 建唯一键——
|
||||
* 一个商品在同一组里最多挂一个分类,不同组互不干扰。</p>
|
||||
*
|
||||
* <p>本表不参与采集回传的覆盖保护:归类不再置 {@code manual_locked}(分类不再写进商品行,
|
||||
* 采集刷新也冲不掉它),共享商品的价格/库存照旧随采集更新。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_jd_product_group_assign")
|
||||
public class JdProductGroupAssignEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
/** 商品行 id(biz_jd_product.id)。 */
|
||||
private Long productId;
|
||||
/** 归属数据权限分组 id(biz_shop_manage_group.id)。 */
|
||||
private Long ownerGroupId;
|
||||
/** 分类 id(biz_jd_product_group.id)。 */
|
||||
private Long categoryId;
|
||||
/** 归属公司(分组所属公司,读侧快速过滤)。 */
|
||||
private Long companyId;
|
||||
/** 操作者 user id(管理端破坏性动作留痕用,可为空)。 */
|
||||
private Long createdBy;
|
||||
private LocalDateTime createdAt;
|
||||
/** 改挂分类/刷新时刻(列 ON UPDATE CURRENT_TIMESTAMP)。 */
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+13
-7
@@ -8,12 +8,13 @@ import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 京东商品自定义分组({@code biz_jd_product_group},V195,v1.4)。
|
||||
* 京东商品自定义分类({@code biz_jd_product_group},V195,v1.4;V203 改按数据权限分组归属)。
|
||||
*
|
||||
* <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>
|
||||
* <p>归属口径(2026-11-16 用户口径「不同组不能看到跨组的分类」):一行属于<b>一个数据权限分组</b>
|
||||
* ({@code owner_group_id} → {@code biz_shop_manage_group.id}),唯一键
|
||||
* {@code uk_company_owner_name(company_id, owner_group_id, name)}(同组内重名拒绝,不同组可同名)。
|
||||
* 删除分类不删商品——只删该组的归类归属行({@code biz_jd_product_group_assign})。
|
||||
* 简单单表 CRUD 走 BaseMapper + wrapper(SqlLayering 惯例),无 XML。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_jd_product_group")
|
||||
@@ -21,9 +22,14 @@ public class JdProductGroupEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
/** 历史归属公司(V195~V199 按公司隔离时代遗留,公共化后读写两侧不再引用;新行 DEFAULT 0=平台公共)。 */
|
||||
/** 归属公司(=所属数据权限分组的公司;V200 时代的历史行为 0,读侧不可见)。 */
|
||||
private Long companyId;
|
||||
/** 分组名(全平台唯一)。 */
|
||||
/**
|
||||
* 归属数据权限分组 id(V203):分类只对本组管理员可写、本组成员可读;
|
||||
* 0 = 2026-11-15 公共化时代的历史行,任何读取面都不会返回它。
|
||||
*/
|
||||
private Long ownerGroupId;
|
||||
/** 分类名(同一公司同一分组内唯一)。 */
|
||||
private String name;
|
||||
/** 下拉展示顺序。 */
|
||||
private Integer sortOrder;
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 「分组」下拉的一项=一个数据权限分组({@code biz_shop_manage_group})。
|
||||
*
|
||||
* <p>{@code editable} 是本账号对该组分类的写权限(能建/改名/删除分类、能把商品归入该组分类);
|
||||
* 组内普通号拿到的是 {@code false}(弹窗可看不可改)。</p>
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "京东数据库分类的可选分组")
|
||||
public class JdCategoryGroupOptionVo {
|
||||
|
||||
@Schema(description = "数据权限分组 id")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "分组名")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "展示名(跨公司时带公司名,前端不解析公司字段)")
|
||||
private String label;
|
||||
|
||||
@Schema(description = "本账号对该组分类可写(建/改名/删除/归类)")
|
||||
private boolean editable;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 京东数据库分类的「当前分组」作用域(GET /api/admin/jd-product-groups/scope)。
|
||||
*
|
||||
* <p>给后管页面两个东西:①「分组」下拉的选项(能看多个组的人才需要切);②本账号对每个组
|
||||
* 能不能建/改/删分类({@code editable})。分类与归类都只按这个作用域读写(V203)。</p>
|
||||
*
|
||||
* <p><b>不下发公司字段</b>:`admin-frontend-vue` 的 `company-tab-wiring` 反向扫描禁止
|
||||
* `jd-product-api.ts` / `JdDatabasePage.vue` 出现 `company_id|companyId` 记号,
|
||||
* 跨公司场景的组名由后端拼进 {@code label}(如「某某公司 / 一组」)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东数据库分类作用域(分组下拉 + 可写标记)")
|
||||
public class JdCategoryScopeVo {
|
||||
|
||||
@Schema(description = "是否平台超管(全部公司全部组可读可写)")
|
||||
private boolean platformSuperAdmin;
|
||||
|
||||
@Schema(description = "默认分组 id(可见组的第一项;无可见组时为空)")
|
||||
private Long defaultGroupId;
|
||||
|
||||
@Schema(description = "当前账号可见的分组(按组名排序)")
|
||||
private java.util.List<JdCategoryGroupOptionVo> groups;
|
||||
}
|
||||
+9
-1
@@ -43,9 +43,17 @@ public class JdCollectHistoryItemVo {
|
||||
private List<String> listTabs;
|
||||
|
||||
@Schema(description = "建单时选择的采集类目(京麦末级类目名多选;空=全店采集)。"
|
||||
+ "「继续/重试」从历史行重建推送载荷时同源带回")
|
||||
+ "「继续/重试」从历史行重建推送载荷时同源带回。2026-11-16 建单页类目级联下线,"
|
||||
+ "仅历史行/在途任务兼容")
|
||||
private List<String> categoryPaths;
|
||||
|
||||
@Schema(description = "建单时选择的京麦店内分类名(多选;空=全店采集)。"
|
||||
+ "「继续/重试」从历史行重建推送载荷时同源带回")
|
||||
private List<String> shopCategoryNames;
|
||||
|
||||
@Schema(description = "建单时选择的京麦店内分类 id(与 shopCategoryNames 同一多选的 value 集)")
|
||||
private List<String> shopCategoryIds;
|
||||
|
||||
@Schema(description = "已落京东数据库的商品行数(biz_jd_product 按 task_id 计数)", example = "1407")
|
||||
private Integer rowCount;
|
||||
|
||||
|
||||
+4
-1
@@ -98,9 +98,12 @@ public class JdProductDetailVo {
|
||||
@Schema(description = "已转存图片数")
|
||||
private Integer imageCount;
|
||||
|
||||
@Schema(description = "自定义分组 id(未挂组为空)")
|
||||
@Schema(description = "自定义分类 id(当前分组下未归类为空)")
|
||||
private Long groupId;
|
||||
|
||||
@Schema(description = "自定义分类名(当前分组那一行归属;未归类或读不到为空)")
|
||||
private String groupName;
|
||||
|
||||
@Schema(description = "本次采集批次号")
|
||||
private String collectBatchId;
|
||||
|
||||
|
||||
+11
-7
@@ -6,25 +6,29 @@ import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 京东商品自定义分组(分组下拉/管理面,v1.4 Phase 5)。
|
||||
* 京东商品自定义分类(分类下拉/管理面,v1.4 Phase 5;V203 按数据权限分组归属)。
|
||||
*
|
||||
* <p>{@code productCount} 是读侧现算列({@code JdProductMapper} BaseMapper selectCount
|
||||
* wrapper 按 {@code group_id} 统计,分组下拉展示用)。</p>
|
||||
* <p>{@code productCount} 是读侧现算列(按归属表 {@code biz_jd_product_group_assign} 的
|
||||
* {@code category_id} 计数)——商品是全平台公共的,同一商品在别的组里可能另挂一个分类,
|
||||
* 这里只数本分类。{@code ownerGroupId} 是归属的数据权限分组 id(同组内重名唯一)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品自定义分组")
|
||||
@Schema(description = "京东商品自定义分类")
|
||||
public class JdProductGroupVo {
|
||||
|
||||
@Schema(description = "分组 id")
|
||||
@Schema(description = "分类 id")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "分组名(同公司内唯一)")
|
||||
@Schema(description = "分类名(同一分组内唯一)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "归属数据权限分组 id")
|
||||
private Long ownerGroupId;
|
||||
|
||||
@Schema(description = "下拉展示顺序")
|
||||
private Integer sortOrder;
|
||||
|
||||
@Schema(description = "组内商品数(读侧现算)")
|
||||
@Schema(description = "本分类下的商品数(读侧现算)")
|
||||
private Long productCount;
|
||||
|
||||
@Schema(description = "创建时刻")
|
||||
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
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.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
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.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 京东数据库分类的「当前分组」作用域解析(V203,2026-11-16 用户口径)。
|
||||
*
|
||||
* <p>口径:「组」=公司内的<b>数据权限分组</b>({@code biz_shop_manage_group}),公司→组两级隔离。
|
||||
* 四档:</p>
|
||||
* <ul>
|
||||
* <li><b>平台超管</b>:全部公司全部组可读可写;</li>
|
||||
* <li><b>公司超管</b>:本公司全部组可读可写(与「公司超管看本公司全部成员」同源);</li>
|
||||
* <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长;可写=自己带的组;</li>
|
||||
* <li><b>普通号</b>:可见同上,可写空(能开弹窗看,不能增删改分类、不能归类)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>平台超管判定走 {@link DataReadScope#isPlatformSuperAdmin}({@code isSuper} 的唯一包装),
|
||||
* 不新增 {@code DeviceSessionPolicy.isSuper(...)} 调用点——那条字面量调用点由
|
||||
* {@code SuperAdminPredicateSingleOutletTest} 钉死在 22 处。公司超管判定用
|
||||
* {@link DeviceSessionPolicy#isCompanySuperAdmin(String)}(本笔新收的出口)。</p>
|
||||
*
|
||||
* <p>解析结果不带任何公司字段给前端:跨公司的组名由 {@link #scopeVo} 拼进 {@code label},
|
||||
* 因为 `admin-frontend-vue` 禁止 JD 两个文件出现 `company_id|companyId` 记号。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class JdCategoryScopeService {
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final DataReadScope dataReadScope;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final CompanyMapper companyMapper;
|
||||
|
||||
/** 管理端作用域(会话身份已由调用方的菜单闸解析过)。 */
|
||||
public JdCategoryScope resolve(AdminUserEntity operator) {
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
throw new BusinessException(403, "无权访问京东数据库");
|
||||
}
|
||||
return build(operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 user id 解析作用域(用户端「获取店铺数据」页的分类列表用:那里的身份是登录用户 id,
|
||||
* 不是后台会话;解析不出账号按空作用域处理,调用方拿空列表而不是 500)。
|
||||
*/
|
||||
public JdCategoryScope resolveByUserId(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return JdCategoryScope.empty();
|
||||
}
|
||||
AdminUserEntity user = adminUserMapper.selectById(userId);
|
||||
if (user == null || user.getId() == null || user.getId() <= 0) {
|
||||
return JdCategoryScope.empty();
|
||||
}
|
||||
return build(user);
|
||||
}
|
||||
|
||||
/** 前端「分组」下拉 + 可写标记(不带公司字段,跨公司组名拼进 label)。 */
|
||||
public JdCategoryScopeVo scopeVo(AdminUserEntity operator) {
|
||||
return voOf(resolve(operator));
|
||||
}
|
||||
|
||||
public JdCategoryScopeVo voOf(JdCategoryScope scope) {
|
||||
JdCategoryScopeVo vo = new JdCategoryScopeVo();
|
||||
vo.setPlatformSuperAdmin(scope.platformSuperAdmin());
|
||||
vo.setDefaultGroupId(scope.defaultGroupId());
|
||||
vo.setGroups(scope.groups());
|
||||
return vo;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 入参收敛(读/写各一道)
|
||||
|
||||
/**
|
||||
* 读侧「当前分组」:请求带了就用请求的(必须可见),没带就用默认(可见组第一项)。
|
||||
* 一个可见组都没有时返回 {@code null}——页面照常可用(商品是全平台公共的,只是分类列全空),
|
||||
* 弹窗按空列表提示「还没有数据权限分组」,不把整页打成 403。
|
||||
*/
|
||||
public Long readGroupOrNull(JdCategoryScope scope, Long requestedGroupId) {
|
||||
Long target = requestedGroupId != null && requestedGroupId > 0
|
||||
? requestedGroupId : scope.defaultGroupId();
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
if (!scope.canRead(target)) {
|
||||
throw new BusinessException(403, "无权查看该分组的分类");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写侧「当前分组」:请求带了就用请求的;没带时若只有一个可写组就用它,否则拒绝(要求先选组)。
|
||||
*
|
||||
* @return 目标数据权限分组(带 company_id,建分类时落归属公司)
|
||||
*/
|
||||
public ShopManageGroupEntity requireWritableGroup(JdCategoryScope scope, Long requestedGroupId) {
|
||||
Long target = requestedGroupId != null && requestedGroupId > 0
|
||||
? requestedGroupId : defaultWritableGroupId(scope);
|
||||
if (target == null) {
|
||||
throw new BusinessException(403, scope.writableGroupIds().isEmpty()
|
||||
? "你还没有可管理的数据权限分组" : "请先选择要管理的分组");
|
||||
}
|
||||
if (!scope.canWrite(target)) {
|
||||
throw new BusinessException(403, "仅该分组的管理员可以修改它的分类");
|
||||
}
|
||||
ShopManageGroupEntity group = shopManageGroupMapper.selectById(target);
|
||||
if (group == null || group.getId() == null) {
|
||||
throw new BusinessException("分组不存在,请刷新后重试");
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
private static Long defaultWritableGroupId(JdCategoryScope scope) {
|
||||
if (scope.writableGroupIds().size() == 1) {
|
||||
return scope.writableGroupIds().get(0);
|
||||
}
|
||||
Long first = scope.defaultGroupId();
|
||||
return first != null && scope.canWrite(first) ? first : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 解析
|
||||
|
||||
private JdCategoryScope build(AdminUserEntity user) {
|
||||
String role = adminAuthSupport.currentRole(user);
|
||||
Map<Long, ShopManageGroupEntity> visible = new LinkedHashMap<>();
|
||||
Set<Long> writable = new LinkedHashSet<>();
|
||||
if (dataReadScope.isPlatformSuperAdmin(user)) {
|
||||
collect(visible, shopManageGroupMapper.selectAllGroups());
|
||||
writable.addAll(visible.keySet());
|
||||
return assemble(true, user.getCompanyId(), visible, writable);
|
||||
}
|
||||
if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
|
||||
Long companyId = user.getCompanyId();
|
||||
if (companyId != null && companyId > 0) {
|
||||
collect(visible, companyGroups(companyId));
|
||||
writable.addAll(visible.keySet());
|
||||
}
|
||||
return assemble(false, companyId, visible, writable);
|
||||
}
|
||||
// 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。
|
||||
List<ShopManageGroupEntity> led = ledGroups(user.getId());
|
||||
collect(visible, led);
|
||||
if ("admin".equals(role)) {
|
||||
for (ShopManageGroupEntity group : led) {
|
||||
if (group.getId() != null) {
|
||||
writable.add(group.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (user.getCreatedById() != null && user.getCreatedById() > 0) {
|
||||
collect(visible, ledGroups(user.getCreatedById()));
|
||||
}
|
||||
List<Long> memberOfLeaders = shopManageGroupMapper.selectLeaderIdsByMemberUserId(user.getId());
|
||||
if (memberOfLeaders != null) {
|
||||
for (Long leaderId : memberOfLeaders) {
|
||||
collect(visible, ledGroups(leaderId));
|
||||
}
|
||||
}
|
||||
return assemble(false, user.getCompanyId(), visible, writable);
|
||||
}
|
||||
|
||||
private List<ShopManageGroupEntity> companyGroups(Long companyId) {
|
||||
return shopManageGroupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.eq(ShopManageGroupEntity::getCompanyId, companyId)
|
||||
.orderByAsc(ShopManageGroupEntity::getGroupName)
|
||||
.orderByAsc(ShopManageGroupEntity::getId));
|
||||
}
|
||||
|
||||
private List<ShopManageGroupEntity> ledGroups(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return List.of();
|
||||
}
|
||||
List<ShopManageGroupEntity> rows = shopManageGroupMapper.selectLedGroups(userId);
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
private static void collect(Map<Long, ShopManageGroupEntity> target, List<ShopManageGroupEntity> rows) {
|
||||
if (rows == null) {
|
||||
return;
|
||||
}
|
||||
for (ShopManageGroupEntity row : rows) {
|
||||
if (row != null && row.getId() != null && row.getId() > 0) {
|
||||
target.putIfAbsent(row.getId(), row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private JdCategoryScope assemble(boolean platformSuperAdmin, Long companyId,
|
||||
Map<Long, ShopManageGroupEntity> visible, Set<Long> writable) {
|
||||
Map<Long, String> companyNames = platformSuperAdmin ? companyNames(visible.values()) : Map.of();
|
||||
List<JdCategoryGroupOptionVo> options = new ArrayList<>(visible.size());
|
||||
for (ShopManageGroupEntity group : visible.values()) {
|
||||
String groupName = group.getGroupName() == null ? "" : group.getGroupName().trim();
|
||||
String label = groupName;
|
||||
if (platformSuperAdmin) {
|
||||
// 归属公司可为 NULL(V153 口径:组长账号已不存在、归属无从追溯),而 companyNames()
|
||||
// 在「一个公司 id 都取不到」时返回的是 Map.of()——对不可变空 Map 调 get(null) 会抛
|
||||
// NullPointerException(2026-11-16 22:00 线上实录:全空归属时整个京东数据库 500,
|
||||
// 列表/分类/scope 三端点同时挂)。故先判空再取,取不到就只显示组名。
|
||||
Long groupCompanyId = group.getCompanyId();
|
||||
String companyName = groupCompanyId == null || groupCompanyId <= 0
|
||||
? null : companyNames.get(groupCompanyId);
|
||||
label = companyName == null || companyName.isBlank()
|
||||
? groupName : companyName + " / " + groupName;
|
||||
}
|
||||
options.add(new JdCategoryGroupOptionVo(group.getId(), groupName, label,
|
||||
writable.contains(group.getId())));
|
||||
}
|
||||
return new JdCategoryScope(platformSuperAdmin, companyId,
|
||||
List.copyOf(visible.keySet()), List.copyOf(writable), List.copyOf(options));
|
||||
}
|
||||
|
||||
/** 平台超管跨公司时给组名补公司前缀(一次批量取,不逐行查询)。 */
|
||||
private Map<Long, String> companyNames(java.util.Collection<ShopManageGroupEntity> groups) {
|
||||
Set<Long> companyIds = new LinkedHashSet<>();
|
||||
for (ShopManageGroupEntity group : groups) {
|
||||
if (group.getCompanyId() != null && group.getCompanyId() > 0) {
|
||||
companyIds.add(group.getCompanyId());
|
||||
}
|
||||
}
|
||||
if (companyIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, String> names = new LinkedHashMap<>();
|
||||
for (CompanyEntity company : companyMapper.selectBatchIds(companyIds)) {
|
||||
if (company.getId() != null && company.getCompanyName() != null) {
|
||||
names.put(company.getId(), company.getCompanyName());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析结果(只读快照)。{@code groups} 已按组名排序并带 {@code editable};列表读侧直接用
|
||||
* {@link #visibleGroupIds()}、写侧用 {@link #writableGroupIds()}。
|
||||
*/
|
||||
public record JdCategoryScope(boolean platformSuperAdmin, Long companyId,
|
||||
List<Long> visibleGroupIds, List<Long> writableGroupIds,
|
||||
List<JdCategoryGroupOptionVo> groups) {
|
||||
|
||||
public static JdCategoryScope empty() {
|
||||
return new JdCategoryScope(false, null, List.of(), List.of(), List.of());
|
||||
}
|
||||
|
||||
public boolean canRead(Long groupId) {
|
||||
return groupId != null && groupId > 0 && visibleGroupIds.contains(groupId);
|
||||
}
|
||||
|
||||
public boolean canWrite(Long groupId) {
|
||||
return groupId != null && groupId > 0 && writableGroupIds.contains(groupId);
|
||||
}
|
||||
|
||||
public Long defaultGroupId() {
|
||||
return groups.isEmpty() ? null : groups.get(0).getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
|
||||
@@ -16,6 +17,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskBatchVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskDetailVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCollectTaskItemVo;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
@@ -59,6 +61,7 @@ public class JdCollectBoardService {
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductSkuMapper jdProductSkuMapper;
|
||||
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/** 查询当前用户的面板总览(运行中/成功/失败三档计数,已结束=成功+失败)。 */
|
||||
@@ -165,6 +168,9 @@ public class JdCollectBoardService {
|
||||
// 类目随建单载荷同源带回:重试/继续时页面从历史行重建推送载荷,缺了它
|
||||
// 客户端会按全店采集跑(兜底拉取路径读 request_json 不受影响)。
|
||||
item.setCategoryPaths(request.getCategoryPaths());
|
||||
// 店内分类双键同源带回(2026-11-16):label 与 id 都带,客户端任一键命中即命中。
|
||||
item.setShopCategoryNames(request.getShopCategoryNames());
|
||||
item.setShopCategoryIds(request.getShopCategoryIds());
|
||||
}
|
||||
item.setRowCount(rowCount == null ? 0 : rowCount);
|
||||
fillProgress(item, task, scope);
|
||||
@@ -276,9 +282,10 @@ public class JdCollectBoardService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除任务(铁律 32 数据面):京东数据库三表按 {@code task_id} 清 + scope 行 + 任务主行。
|
||||
* 删除任务(铁律 32 数据面):京东数据库四表按 {@code task_id}/商品 id 清 + scope 行 + 任务主行。
|
||||
* 事务内只做 DB 删除;京东采集没有 OSS 载荷/任务缓存需要 afterCommit 清理。
|
||||
* 删行顺序照 {@code JdProductRowDeleteService#deleteRows}:先 sku/image 子行再主行。
|
||||
* 删行顺序照 {@code JdProductRowDeleteService#deleteRows}:先归类归属/sku/image 子行再主行
|
||||
* (V203 加入 {@code biz_jd_product_group_assign},按商品 id 清所有组的归属)。
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteTask(Long taskId, Long userId) {
|
||||
@@ -293,6 +300,8 @@ public class JdCollectBoardService {
|
||||
.eq(JdProductEntity::getTaskId, taskId))
|
||||
.stream().map(JdProductEntity::getId).toList();
|
||||
if (!productIds.isEmpty()) {
|
||||
jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.in(JdProductGroupAssignEntity::getProductId, productIds));
|
||||
jdProductSkuMapper.delete(new LambdaQueryWrapper<JdProductSkuEntity>()
|
||||
.in(JdProductSkuEntity::getProductId, productIds));
|
||||
jdProductImageMapper.delete(new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
|
||||
+13
-10
@@ -156,36 +156,39 @@ public class JdCollectTaskService {
|
||||
if (request.getMaxProducts() != null && request.getMaxProducts() < 0) {
|
||||
throw new BusinessException("采集范围上限不能为负数");
|
||||
}
|
||||
// 类目归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源),
|
||||
// 类目/分类归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源),
|
||||
// 派发载荷与客户端过滤都从这里读,不再各归各的。
|
||||
request.setCategoryPaths(normalizeCategoryPaths(request.getCategoryPaths()));
|
||||
request.setCategoryPaths(normalizeStringSelection(request.getCategoryPaths(), "采集类目"));
|
||||
request.setShopCategoryNames(normalizeStringSelection(request.getShopCategoryNames(), "采集分类"));
|
||||
request.setShopCategoryIds(normalizeStringSelection(request.getShopCategoryIds(), "采集分类ID"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 类目多选归一化:trim/去空/保序去重;全空白归 null(=不过滤,全店采集)。
|
||||
* 多选值归一化:trim/去空/保序去重;全空白归 null(=不过滤,全店采集)。
|
||||
* 超限当场点名拒绝(建单口必须拦注定失败的输入),不静默截断。
|
||||
* {@code label} 进拒绝文案(类目/分类两条链共用同一上限常量)。
|
||||
*/
|
||||
private List<String> normalizeCategoryPaths(List<String> categoryPaths) {
|
||||
if (categoryPaths == null || categoryPaths.isEmpty()) {
|
||||
private List<String> normalizeStringSelection(List<String> raw, String label) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Set<String> normalized = new java.util.LinkedHashSet<>();
|
||||
for (String raw : categoryPaths) {
|
||||
if (raw == null) {
|
||||
for (String item : raw) {
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
String path = raw.trim();
|
||||
String path = item.trim();
|
||||
if (path.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (path.length() > MAX_CATEGORY_PATH_LENGTH) {
|
||||
throw new BusinessException("采集类目名过长(上限 " + MAX_CATEGORY_PATH_LENGTH
|
||||
throw new BusinessException(label + "名过长(上限 " + MAX_CATEGORY_PATH_LENGTH
|
||||
+ " 字): " + path.substring(0, 50) + "…");
|
||||
}
|
||||
normalized.add(path);
|
||||
}
|
||||
if (normalized.size() > MAX_CATEGORY_PATHS) {
|
||||
throw new BusinessException("采集类目最多选 " + MAX_CATEGORY_PATHS + " 个,当前 "
|
||||
throw new BusinessException(label + "最多选 " + MAX_CATEGORY_PATHS + " 个,当前 "
|
||||
+ normalized.size() + " 个");
|
||||
}
|
||||
return normalized.isEmpty() ? null : List.copyOf(normalized);
|
||||
|
||||
+98
-68
@@ -1,11 +1,10 @@
|
||||
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.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
|
||||
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.JdProductGroupAssignEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -13,21 +12,24 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 京东商品自定义分组业务(v1.4 Phase 5,R4):下拉列表 / 新建 / 改名 / 删除。
|
||||
* 京东商品自定义分类业务(v1.4 Phase 5,R4;V203 改按数据权限分组归属)。
|
||||
*
|
||||
* <p>分组表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。
|
||||
* 业务规则:</p>
|
||||
* <p>分类表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。业务规则:</p>
|
||||
* <ul>
|
||||
* <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>
|
||||
* <li><b>归属一个数据权限分组</b>(2026-11-16 用户口径「不同组不能看到跨组的分类」):
|
||||
* {@code owner_group_id} → {@code biz_shop_manage_group.id};读写范围由
|
||||
* {@link JdCategoryScopeService} 解析,本服务只做「按给定组取/写」。</li>
|
||||
* <li><b>同组重名拒绝</b>(唯一键 {@code uk_company_owner_name},V203):先查后插给可读的
|
||||
* 409 业务错误,不拿 DB 异常撞 500;改名时排除自身再查。不同组可同名。</li>
|
||||
* <li><b>删除分类不删商品</b>:只删该分类的归类归属行
|
||||
* ({@code biz_jd_product_group_assign},同一事务),商品行留在公共库里。</li>
|
||||
* <li><b>商品数现算</b>:{@code productCount} 按归属表 {@code category_id} 计数——商品是全平台公共的,
|
||||
* 同一商品在别的组里可能另挂一个分类,这里只数本分类。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
@@ -35,67 +37,105 @@ import java.util.List;
|
||||
public class JdProductGroupService {
|
||||
|
||||
private final JdProductGroupMapper jdProductGroupMapper;
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
|
||||
/** 单个分组的分类全量(按 {@code sort_order, id} 升序,下拉展示顺序)。 */
|
||||
public List<JdProductGroupVo> list(Long ownerGroupId) {
|
||||
if (ownerGroupId == null || ownerGroupId <= 0) {
|
||||
return List.of();
|
||||
}
|
||||
return listForGroups(List.of(ownerGroupId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 分组全量(按 {@code sort_order, id} 升序,下拉展示顺序);
|
||||
* {@code productCount} 用 {@code JdProductMapper} BaseMapper selectCount wrapper
|
||||
* 按 {@code group_id} 统计(分组下拉展示用)。
|
||||
* 多个分组的分类并集(用户端「获取店铺数据」页:一个普通号可能同时在多个组里,只读展示)。
|
||||
* 空清单直接回空,不生成 {@code IN ()}。
|
||||
*/
|
||||
public List<JdProductGroupVo> list() {
|
||||
LambdaQueryWrapper<JdProductGroupEntity> query = new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.orderByAsc(JdProductGroupEntity::getSortOrder)
|
||||
.orderByAsc(JdProductGroupEntity::getId);
|
||||
List<JdProductGroupVo> items = new ArrayList<>();
|
||||
for (JdProductGroupEntity group : jdProductGroupMapper.selectList(query)) {
|
||||
public List<JdProductGroupVo> listForGroups(List<Long> ownerGroupIds) {
|
||||
Set<Long> safeGroupIds = new LinkedHashSet<>();
|
||||
if (ownerGroupIds != null) {
|
||||
for (Long id : ownerGroupIds) {
|
||||
if (id != null && id > 0) {
|
||||
safeGroupIds.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (safeGroupIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<JdProductGroupEntity> rows = jdProductGroupMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.in(JdProductGroupEntity::getOwnerGroupId, safeGroupIds)
|
||||
.orderByAsc(JdProductGroupEntity::getSortOrder)
|
||||
.orderByAsc(JdProductGroupEntity::getId));
|
||||
List<JdProductGroupVo> items = new ArrayList<>(rows.size());
|
||||
for (JdProductGroupEntity category : rows) {
|
||||
JdProductGroupVo vo = new JdProductGroupVo();
|
||||
vo.setId(group.getId());
|
||||
vo.setName(group.getName());
|
||||
vo.setSortOrder(group.getSortOrder());
|
||||
vo.setCreatedAt(group.getCreatedAt());
|
||||
vo.setProductCount(jdProductMapper.selectCount(
|
||||
new LambdaQueryWrapper<JdProductEntity>().eq(JdProductEntity::getGroupId, group.getId())));
|
||||
vo.setId(category.getId());
|
||||
vo.setName(category.getName());
|
||||
vo.setSortOrder(category.getSortOrder());
|
||||
vo.setOwnerGroupId(category.getOwnerGroupId());
|
||||
vo.setCreatedAt(category.getCreatedAt());
|
||||
vo.setProductCount(jdProductGroupAssignMapper.selectCount(
|
||||
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.eq(JdProductGroupAssignEntity::getCategoryId, category.getId())));
|
||||
items.add(vo);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 新建分组:重名(trim 后)按 409 业务错误拒绝,不落库;company_id 不写(DB DEFAULT 0=平台公共)。 */
|
||||
public Long create(String name, Integer sortOrder) {
|
||||
String safeName = requireName(name);
|
||||
requireNameFree(safeName, null);
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setName(safeName);
|
||||
group.setSortOrder(sortOrder == null ? 0 : sortOrder);
|
||||
jdProductGroupMapper.insert(group);
|
||||
return group.getId();
|
||||
/** 分类行存在校验(调用方拿它校验归属/写权限)。不存在一律按「分类不存在」拒绝。 */
|
||||
public JdProductGroupEntity requireCategory(Long id) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
JdProductGroupEntity category = jdProductGroupMapper.selectById(id);
|
||||
if (category == null) {
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
return category;
|
||||
}
|
||||
|
||||
/** 改名/改排序:越界 id 拒绝,重名(排除自身)拒绝。 */
|
||||
/** 新建分类:归属分组与公司由调用方(控制器)按作用域算好传入;同组重名 409。 */
|
||||
public Long create(Long ownerGroupId, Long companyId, String name, Integer sortOrder) {
|
||||
if (ownerGroupId == null || ownerGroupId <= 0) {
|
||||
throw new BusinessException(400, "请先选择分组再新建分类");
|
||||
}
|
||||
String safeName = requireName(name);
|
||||
requireNameFree(companyId, ownerGroupId, safeName, null);
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setCompanyId(companyId == null || companyId <= 0 ? 0L : companyId);
|
||||
category.setOwnerGroupId(ownerGroupId);
|
||||
category.setName(safeName);
|
||||
category.setSortOrder(sortOrder == null ? 0 : sortOrder);
|
||||
jdProductGroupMapper.insert(category);
|
||||
return category.getId();
|
||||
}
|
||||
|
||||
/** 改名/改排序:归属由调用方校验过;重名(同组、排除自身)拒绝。 */
|
||||
public void rename(Long id, String name, Integer sortOrder) {
|
||||
String safeName = requireName(name);
|
||||
JdProductGroupEntity group = requireExistingGroup(id);
|
||||
requireNameFree(safeName, group.getId());
|
||||
group.setName(safeName);
|
||||
JdProductGroupEntity category = requireCategory(id);
|
||||
requireNameFree(category.getCompanyId(), category.getOwnerGroupId(), safeName, category.getId());
|
||||
category.setName(safeName);
|
||||
if (sortOrder != null) {
|
||||
group.setSortOrder(sortOrder);
|
||||
category.setSortOrder(sortOrder);
|
||||
}
|
||||
jdProductGroupMapper.updateById(group);
|
||||
jdProductGroupMapper.updateById(category);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除分组(事务两步,AC-8):先把该组商品 {@code group_id} 置 NULL(商品保留,
|
||||
* 脱组即「未分组」),再删分组行。越界 id 拒绝。
|
||||
* 删除分类(同一事务):先删该分类的归类归属行(商品保留在公共库),再删分类行。
|
||||
*
|
||||
* @return 实际脱组的商品行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
|
||||
* @return 实际解挂的归属行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
|
||||
*/
|
||||
@Transactional
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int delete(Long id) {
|
||||
JdProductGroupEntity group = requireExistingGroup(id);
|
||||
int detached = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.set(JdProductEntity::getGroupId, null)
|
||||
.eq(JdProductEntity::getGroupId, group.getId()));
|
||||
jdProductGroupMapper.deleteById(group.getId());
|
||||
JdProductGroupEntity category = requireCategory(id);
|
||||
int detached = jdProductGroupAssignMapper.delete(
|
||||
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.eq(JdProductGroupAssignEntity::getCategoryId, category.getId()));
|
||||
jdProductGroupMapper.deleteById(category.getId());
|
||||
return detached;
|
||||
}
|
||||
|
||||
@@ -109,25 +149,15 @@ public class JdProductGroupService {
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
/** 分类行存在校验:不存在一律按「分类不存在」拒绝。 */
|
||||
private JdProductGroupEntity requireExistingGroup(Long id) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(id);
|
||||
if (group == null) {
|
||||
throw new BusinessException("分类不存在");
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
/** 全局重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
|
||||
private void requireNameFree(String name, Long excludeId) {
|
||||
/** 同组重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
|
||||
private void requireNameFree(Long companyId, Long ownerGroupId, String name, Long excludeId) {
|
||||
Long count = jdProductGroupMapper.selectCount(new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.eq(JdProductGroupEntity::getName, name)
|
||||
.eq(JdProductGroupEntity::getOwnerGroupId, ownerGroupId)
|
||||
.eq(JdProductGroupEntity::getCompanyId, companyId == null ? 0L : companyId)
|
||||
.ne(excludeId != null, JdProductGroupEntity::getId, excludeId));
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException(409, "已存在同名分类:" + name);
|
||||
throw new BusinessException(409, "本组已存在同名分类:" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+67
-17
@@ -5,11 +5,13 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
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.entity.JdProductEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
|
||||
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;
|
||||
@@ -70,6 +72,7 @@ public class JdProductQueryService {
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductSkuMapper jdProductSkuMapper;
|
||||
private final JdProductGroupMapper jdProductGroupMapper;
|
||||
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
@@ -83,7 +86,7 @@ public class JdProductQueryService {
|
||||
*/
|
||||
public JdProductPageVo page(Long page, Long pageSize,
|
||||
String productCode, String titleKeyword, String category, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Long ownerGroupId) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
}
|
||||
@@ -101,7 +104,7 @@ public class JdProductQueryService {
|
||||
filter.syncedFrom(), filter.syncedTo(),
|
||||
(safePage - 1) * safeSize, (int) safeSize);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
fillGroupNames(items);
|
||||
fillGroupNames(items, ownerGroupId);
|
||||
JdProductPageVo vo = new JdProductPageVo();
|
||||
vo.setItems(items);
|
||||
vo.setTotal(total);
|
||||
@@ -127,7 +130,7 @@ public class JdProductQueryService {
|
||||
* 越界 id 按不存在拒绝。attr_json 非契约形状/解析异常时不抛 500:落空 {@code attrGroups}、
|
||||
* 原文进 {@code attrJsonRaw} 兜底(AC-7)。</p>
|
||||
*/
|
||||
public JdProductDetailVo detail(Long id) {
|
||||
public JdProductDetailVo detail(Long id, Long ownerGroupId) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
@@ -162,7 +165,7 @@ public class JdProductQueryService {
|
||||
vo.setDetailUrl(row.getDetailUrl());
|
||||
vo.setAttrCount(row.getAttrCount());
|
||||
vo.setImageCount(row.getImageCount());
|
||||
vo.setGroupId(row.getGroupId());
|
||||
fillCategory(vo, row.getId(), ownerGroupId);
|
||||
vo.setCollectBatchId(row.getCollectBatchId());
|
||||
vo.setSyncedAt(row.getSyncedAt());
|
||||
parseAttrGroups(vo, row.getAttrJson());
|
||||
@@ -189,7 +192,7 @@ public class JdProductQueryService {
|
||||
|
||||
// ---------------------------------------------------------------- 列表/详情搬运
|
||||
|
||||
/** 行值原样搬运(读侧不加工),groupName 由 {@link #fillGroupNames} 批量补齐。 */
|
||||
/** 行值原样搬运(读侧不加工),分类 id/名由 {@link #fillGroupNames} 批量补。 */
|
||||
private JdProductListItemVo toListItem(JdProductEntity row) {
|
||||
JdProductListItemVo vo = new JdProductListItemVo();
|
||||
vo.setId(row.getId());
|
||||
@@ -214,34 +217,81 @@ public class JdProductQueryService {
|
||||
vo.setMainImageUrl(row.getMainImageUrl());
|
||||
vo.setAttrCount(row.getAttrCount());
|
||||
vo.setImageCount(row.getImageCount());
|
||||
vo.setGroupId(row.getGroupId());
|
||||
vo.setSyncedAt(row.getSyncedAt());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 批量补分组名:行集的 group_id 一次取齐(一次查询,无逐行查询);读不到的分组不猜名字。 */
|
||||
private void fillGroupNames(List<JdProductListItemVo> items) {
|
||||
List<Long> groupIds = items.stream()
|
||||
.map(JdProductListItemVo::getGroupId)
|
||||
/**
|
||||
* 批量补「当前分组」的分类:行集商品 id 一次取齐本组归属
|
||||
* ({@code biz_jd_product_group_assign} 的 {@code owner_group_id} 那一行),再批量取分类名。
|
||||
* 读不到的分类不猜名字(可能刚被别的会话删掉);没有分组上下文时分类列一律空(未分类)。
|
||||
*/
|
||||
private void fillGroupNames(List<JdProductListItemVo> items, Long ownerGroupId) {
|
||||
if (items.isEmpty() || ownerGroupId == null || ownerGroupId <= 0) {
|
||||
return;
|
||||
}
|
||||
List<Long> productIds = items.stream()
|
||||
.map(JdProductListItemVo::getId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (groupIds.isEmpty()) {
|
||||
if (productIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<Long, String> namesById = new LinkedHashMap<>();
|
||||
for (JdProductGroupEntity group : jdProductGroupMapper.selectBatchIds(groupIds)) {
|
||||
if (group.getId() != null && group.getName() != null && !group.getName().isBlank()) {
|
||||
namesById.put(group.getId(), group.getName());
|
||||
Map<Long, Long> categoryByProduct = new LinkedHashMap<>();
|
||||
for (JdProductGroupAssignEntity assign : jdProductGroupAssignMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.in(JdProductGroupAssignEntity::getProductId, productIds)
|
||||
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId))) {
|
||||
if (assign.getProductId() != null && assign.getCategoryId() != null) {
|
||||
categoryByProduct.put(assign.getProductId(), assign.getCategoryId());
|
||||
}
|
||||
}
|
||||
if (categoryByProduct.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<Long, String> namesById = categoryNames(categoryByProduct.values());
|
||||
for (JdProductListItemVo item : items) {
|
||||
if (item.getGroupId() != null) {
|
||||
item.setGroupName(namesById.get(item.getGroupId()));
|
||||
Long categoryId = categoryByProduct.get(item.getId());
|
||||
if (categoryId != null) {
|
||||
item.setGroupId(categoryId);
|
||||
item.setGroupName(namesById.get(categoryId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 详情侧的单行分类:与列表同一出口同一口径(当前分组那一行归属)。 */
|
||||
private void fillCategory(JdProductDetailVo vo, Long productId, Long ownerGroupId) {
|
||||
if (productId == null || ownerGroupId == null || ownerGroupId <= 0) {
|
||||
return;
|
||||
}
|
||||
JdProductGroupAssignEntity assign = jdProductGroupAssignMapper.selectOne(
|
||||
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.eq(JdProductGroupAssignEntity::getProductId, productId)
|
||||
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId)
|
||||
.last("limit 1"));
|
||||
if (assign == null || assign.getCategoryId() == null) {
|
||||
return;
|
||||
}
|
||||
vo.setGroupId(assign.getCategoryId());
|
||||
vo.setGroupName(categoryNames(List.of(assign.getCategoryId())).get(assign.getCategoryId()));
|
||||
}
|
||||
|
||||
/** 分类 id → 名字(一次批量取;读不到的不猜)。 */
|
||||
private Map<Long, String> categoryNames(java.util.Collection<Long> categoryIds) {
|
||||
List<Long> ids = categoryIds.stream().filter(id -> id != null && id > 0).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, String> namesById = new LinkedHashMap<>();
|
||||
for (JdProductGroupEntity category : jdProductGroupMapper.selectBatchIds(ids)) {
|
||||
if (category.getId() != null && category.getName() != null && !category.getName().isBlank()) {
|
||||
namesById.put(category.getId(), category.getName());
|
||||
}
|
||||
}
|
||||
return namesById;
|
||||
}
|
||||
|
||||
/** 已转存图片:按档内排序号、id 稳定升序(详情抽屉分区展示顺序)。 */
|
||||
private List<JdProductDetailVo.ImageViewVo> loadImages(Long productId) {
|
||||
List<JdProductImageEntity> rows = jdProductImageMapper.selectList(
|
||||
|
||||
+9
-3
@@ -1,9 +1,11 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
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.entity.JdProductGroupAssignEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -20,9 +22,10 @@ import java.util.List;
|
||||
* ({@link JdProductDeleteService} 先删桶、全成功才调本类)。若把三次 delete 与 S3 调用塞进
|
||||
* 同一个事务,S3 通一次网就多占一次行锁,而且事务回滚也救不回已经删掉的对象。</p>
|
||||
*
|
||||
* <p>删除顺序固定 {@code SKU → 图片行 → 商品行}:三张表都按 {@code product_id} 关联、没有外键,
|
||||
* 先删子行不会因为"主行先没"而留下查不到的孤儿;反过来则会。SQL 全走 BaseMapper wrapper
|
||||
* (铁律 1 允许的两种形态之一,与 {@link JdProductGroupService} 同形状)。</p>
|
||||
* <p>删除顺序固定 {@code 归类归属 → SKU → 图片行 → 商品行}:四张表都按 {@code product_id} 关联、
|
||||
* 没有外键,先删子行不会因为"主行先没"而留下查不到的孤儿;反过来则会。归类归属
|
||||
* ({@code biz_jd_product_group_assign},V203)按组各一行,删商品行时一次性清掉所有组的归属。
|
||||
* SQL 全走 BaseMapper wrapper(铁律 1 允许的两种形态之一,与 {@link JdProductGroupService} 同形状)。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -32,6 +35,7 @@ public class JdProductRowDeleteService {
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductSkuMapper jdProductSkuMapper;
|
||||
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
|
||||
/**
|
||||
* 删除给定商品行的 SKU / 图片登记 / 商品行,返回商品行删除条数。
|
||||
@@ -44,6 +48,8 @@ public class JdProductRowDeleteService {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
throw new IllegalArgumentException("删除商品行必须给出非空 id 清单");
|
||||
}
|
||||
jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.in(JdProductGroupAssignEntity::getProductId, ids));
|
||||
jdProductSkuMapper.delete(new LambdaQueryWrapper<JdProductSkuEntity>()
|
||||
.in(JdProductSkuEntity::getProductId, ids));
|
||||
jdProductImageMapper.delete(new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
|
||||
+64
-31
@@ -6,12 +6,14 @@ 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.JdProductGroupAssignMapper;
|
||||
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.JdProductGroupAssignEntity;
|
||||
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;
|
||||
@@ -26,6 +28,7 @@ import java.math.BigDecimal;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -38,8 +41,9 @@ import java.util.Set;
|
||||
*
|
||||
* <p>三条块语义:</p>
|
||||
* <ul>
|
||||
* <li><b>主字段全量提交</b>:标题/品牌/类目/货号/价格区间/总库存/状态/分组按请求体覆写;
|
||||
* 分组 id 必须真实存在(分组 2026-11-15 起全平台一份,无公司维度)。保存即置
|
||||
* <li><b>主字段全量提交</b>:标题/品牌/类目/货号/价格区间/总库存/状态按请求体覆写;
|
||||
* <b>分类不在编辑面</b>(V203:分类按数据权限分组隔离、归属存独立表,只能走「店铺分类」
|
||||
* 弹窗归类,编辑抽屉不再写商品行的 {@code group_id})。保存即置
|
||||
* {@code manual_locked=1}(V199 人工编辑锁)——采集回传的 upsert / 图片与 SKU 登记 /
|
||||
* 覆盖清理对锁定的行全部跳过,人工值不被重爬覆盖。</li>
|
||||
* <li><b>可选块缺省不动</b>:{@code attrGroups} 缺省不动属性;提交时只重建 attr_json 的
|
||||
@@ -92,6 +96,7 @@ public class JdProductUpdateService {
|
||||
private final JdProductSkuMapper jdProductSkuMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductGroupMapper jdProductGroupMapper;
|
||||
private final JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
private final OssStorageService ossStorageService;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -119,14 +124,6 @@ public class JdProductUpdateService {
|
||||
}
|
||||
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;
|
||||
@@ -146,7 +143,6 @@ public class JdProductUpdateService {
|
||||
.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) {
|
||||
@@ -177,21 +173,23 @@ public class JdProductUpdateService {
|
||||
// ---------- 校验 ----------
|
||||
|
||||
/**
|
||||
* 批量人工归类(店铺分类弹窗,2026-11-15):勾选商品行 → 归入指定分类或移出分类。
|
||||
* 批量人工归类(店铺分类弹窗,2026-11-15;V203 改按数据权限分组隔离)。
|
||||
*
|
||||
* <p>与单行编辑同口径(用户拍板「置锁」):归类即人工干预,落 {@code manual_locked=1}——
|
||||
* 采集 upsert 本就不写 group_id,置锁后覆盖清理也不再把这些行整行删掉,分类永不丢;
|
||||
* 代价是该行的价格/库存等字段随锁停更(与编辑保存同一语义)。</p>
|
||||
* <p>归类归属写进 {@code biz_jd_product_group_assign}({@code (product_id, owner_group_id)} 唯一):
|
||||
* 商品行是全平台公共的,同一个商品在 A 组和 B 组可以各自归类,互不挤占。
|
||||
* {@code categoryId} null=移出分类(删本组这一行归属,商品在本组回到未分类)。</p>
|
||||
*
|
||||
* <p>{@code groupId} null=移出分类(group_id 置 NULL 回到未分类);非 null 时必须真实
|
||||
* 存在(分类全平台一份,无公司维度)。只写 group_id 与锁两个列,不动其它字段——
|
||||
* 与 {@link #update} 的全量覆写不同,这是行集级轻touch。</p>
|
||||
* <p><b>不再置人工编辑锁</b>(2026-11-16 用户口径):分类不在商品行上,采集回传的
|
||||
* upsert/覆盖清理冲不掉它,置锁只会让这个共享商品的价格/库存对所有组都停更。</p>
|
||||
*
|
||||
* @return 实际更新的行数(id 不存在/已被删的行不计入,不按不存在整批拒绝——
|
||||
* @return 实际写入/变更的归属行数(id 不存在/已被删的行不计入,不按不存在整批拒绝——
|
||||
* 弹窗行集与库行之间天然有采集刷新的时间差,掉队的行跳过即可)
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int assignGroup(List<Long> ids, Long groupId) {
|
||||
public int assignGroup(Long ownerGroupId, Long companyId, List<Long> ids, Long categoryId, Long operatorId) {
|
||||
if (ownerGroupId == null || ownerGroupId <= 0) {
|
||||
throw new BusinessException(403, "请先选择分组再归类");
|
||||
}
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
throw new BusinessException("请先选择要归类的商品");
|
||||
}
|
||||
@@ -202,20 +200,55 @@ public class JdProductUpdateService {
|
||||
if (distinctIds.size() > MAX_ASSIGN_IDS) {
|
||||
throw new BusinessException("单次最多归类 " + MAX_ASSIGN_IDS + " 个商品,请分批操作");
|
||||
}
|
||||
if (groupId != null) {
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(groupId);
|
||||
if (group == null) {
|
||||
if (categoryId != null) {
|
||||
JdProductGroupEntity category = jdProductGroupMapper.selectById(categoryId);
|
||||
if (category == null) {
|
||||
throw new BusinessException("分类不存在,请刷新分类后重试");
|
||||
}
|
||||
if (!ownerGroupId.equals(category.getOwnerGroupId())) {
|
||||
throw new BusinessException(403, "该分类不属于当前分组,请刷新后重试");
|
||||
}
|
||||
}
|
||||
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;
|
||||
Map<Long, Long> categoryIdByProduct = new LinkedHashMap<>();
|
||||
for (JdProductGroupAssignEntity assign : jdProductGroupAssignMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.in(JdProductGroupAssignEntity::getProductId, distinctIds)
|
||||
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId))) {
|
||||
if (assign.getProductId() != null) {
|
||||
categoryIdByProduct.put(assign.getProductId(), assign.getCategoryId());
|
||||
}
|
||||
}
|
||||
if (categoryId == null) {
|
||||
int removed = jdProductGroupAssignMapper.delete(new LambdaQueryWrapper<JdProductGroupAssignEntity>()
|
||||
.in(JdProductGroupAssignEntity::getProductId, distinctIds)
|
||||
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId));
|
||||
log.info("[{}] 移出分类 ownerGroupId={} requested={} removed={}",
|
||||
LOG_TAG, ownerGroupId, distinctIds.size(), removed);
|
||||
return removed;
|
||||
}
|
||||
int written = 0;
|
||||
for (Long productId : distinctIds) {
|
||||
Long existingCategoryId = categoryIdByProduct.get(productId);
|
||||
if (existingCategoryId == null) {
|
||||
JdProductGroupAssignEntity assign = new JdProductGroupAssignEntity();
|
||||
assign.setProductId(productId);
|
||||
assign.setOwnerGroupId(ownerGroupId);
|
||||
assign.setCategoryId(categoryId);
|
||||
assign.setCompanyId(companyId == null || companyId <= 0 ? 0L : companyId);
|
||||
assign.setCreatedBy(operatorId);
|
||||
written += jdProductGroupAssignMapper.insert(assign);
|
||||
} else if (!categoryId.equals(existingCategoryId)) {
|
||||
written += jdProductGroupAssignMapper.update(null,
|
||||
new LambdaUpdateWrapper<JdProductGroupAssignEntity>()
|
||||
.eq(JdProductGroupAssignEntity::getProductId, productId)
|
||||
.eq(JdProductGroupAssignEntity::getOwnerGroupId, ownerGroupId)
|
||||
.set(JdProductGroupAssignEntity::getCategoryId, categoryId)
|
||||
.set(JdProductGroupAssignEntity::getCreatedBy, operatorId));
|
||||
}
|
||||
}
|
||||
log.info("[{}] 批量归类 ownerGroupId={} requested={} distinct={} categoryId={} written={}",
|
||||
LOG_TAG, ownerGroupId, ids.size(), distinctIds.size(), categoryId, written);
|
||||
return written;
|
||||
}
|
||||
|
||||
private void validateBody(JdProductUpdateRequest body) {
|
||||
|
||||
+13
-5
@@ -17,9 +17,10 @@ import java.util.Map;
|
||||
* <p>页面推送缺失(只建单没推送 / 推送前关页面 / 纯浏览器打开)时任务会停在 PENDING,
|
||||
* {@code TaskClientPullService} 认领后由本实现组装可直接入队的载荷。{@code data} 的键集
|
||||
* 与客户端 {@code jd_base.process_task} 的读取契约同键({@code taskId / shopName /
|
||||
* listTabs / maxProducts / categoryPaths},{@code QUEUE_TYPE} 与客户端
|
||||
* {@code amazon.jd.jd_base.QUEUE_TYPE} 同值 {@code jd-shop-collect-run})——两处任意一处
|
||||
* 漂移,兜底拉下来的任务客户端不识别(categoryPaths 客户端读不到=不过滤,全店采集)。</p>
|
||||
* listTabs / maxProducts / categoryPaths / shopCategoryNames / shopCategoryIds},
|
||||
* {@code QUEUE_TYPE} 与客户端 {@code amazon.jd.jd_base.QUEUE_TYPE} 同值
|
||||
* {@code jd-shop-collect-run})——两处任意一处漂移,兜底拉下来的任务客户端不识别
|
||||
* (categoryPaths/shopCategory* 客户端读不到=不过滤,全店采集)。</p>
|
||||
*
|
||||
* <p>shopName/listTabs/maxProducts 从建单载荷({@code request_json})回读,与页面推送
|
||||
* 同源;载荷解析失败按 SPI 语义返回 null(调用方会把任务标失败并回写原因),不静默出空载荷。</p>
|
||||
@@ -50,9 +51,16 @@ public class JdTaskPullSpiImpl implements ClientTaskPullSpi {
|
||||
// 缺省放空列表(不是 null):键集稳定,客户端读空集合=不过滤,语义与缺键一致。
|
||||
data.put("categoryPaths", create.getCategoryPaths() == null
|
||||
? List.of() : create.getCategoryPaths());
|
||||
log.info("[jd-collect] 兜底载荷已组装 taskId={} shopName={} tabs={} categories={}",
|
||||
// 店内分类双键(2026-11-16):label 与 value(id) 同发,行级填充形状未取证(可能是
|
||||
// id 数组也可能是对象),客户端任一键命中即命中——只发一个键会让另一形状全空。
|
||||
data.put("shopCategoryNames", create.getShopCategoryNames() == null
|
||||
? List.of() : create.getShopCategoryNames());
|
||||
data.put("shopCategoryIds", create.getShopCategoryIds() == null
|
||||
? List.of() : create.getShopCategoryIds());
|
||||
log.info("[jd-collect] 兜底载荷已组装 taskId={} shopName={} tabs={} categories={} shopCategories={}",
|
||||
task.getId(), create.getShopName(), create.getListTabs(),
|
||||
create.getCategoryPaths() == null ? 0 : create.getCategoryPaths().size());
|
||||
create.getCategoryPaths() == null ? 0 : create.getCategoryPaths().size(),
|
||||
create.getShopCategoryNames() == null ? 0 : create.getShopCategoryNames().size());
|
||||
return Map.of("type", QUEUE_TYPE, "data", data);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -188,7 +188,7 @@ public class SimilarAsinLlmClient {
|
||||
recordSecretUsage();
|
||||
Map<String, Object> body = buildChatBody(model, system, userText, images, responseFormat);
|
||||
String host = resolveHost();
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.5-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.1-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
String requestModel = LlmChannel.modelForHost(host, model);
|
||||
body.put("model", requestModel);
|
||||
// 思考参数按渠道补:贞贞把 thinking 写在模型名里,龙抬头要显式传(复刻现网的 thinking-medium)
|
||||
|
||||
+1
-1
@@ -542,7 +542,7 @@ public class UserApiSecretCheckService {
|
||||
private CheckOutcome probeOnce(UserSecretModule module, String plainApiKey, String proxyUrl, boolean viaProxy,
|
||||
String channel) {
|
||||
String host = module.resolveLlmHost(appearancePatentProperties, similarAsinProperties, channel);
|
||||
// 检测也要按渠道换模型名:龙抬头那边叫 gm-3.5-flash-lite,发贞贞的名字会 404/model_not_found,
|
||||
// 检测也要按渠道换模型名:龙抬头那边叫 gm-3.1-flash-lite,发贞贞的名字会 404/model_not_found,
|
||||
// 用户会误以为自己的密钥坏了
|
||||
String model = LlmChannel.modelForHost(host, userSecretProperties.getCheckModel());
|
||||
String url = joinUrl(host, "/v1/chat/completions");
|
||||
|
||||
+3
-2
@@ -14,7 +14,7 @@ import java.util.Locale;
|
||||
public enum LlmChannel {
|
||||
|
||||
LONGTAITOU("longtaitou", "龙抬头", "https://longtaitou.token6688.com",
|
||||
"gm-3.5-flash-lite", true, "medium"),
|
||||
"gm-3.1-flash-lite", true, "medium"),
|
||||
T8STAR("t8star", "贞贞", "https://ai.t8star.org", null, false, null);
|
||||
|
||||
/** 新建配置的默认渠道(2026-10-30 用户拍板:默认仍是贞贞,龙抬头手动切)。 */
|
||||
@@ -28,7 +28,8 @@ public enum LlmChannel {
|
||||
*
|
||||
* <p>两家中转的模型目录不同名:本系统业务配置写的是贞贞的
|
||||
* {@code gemini-3.1-flash-lite-preview-thinking-medium} 等,龙抬头那边统一叫
|
||||
* {@code gm-3.5-flash-lite}(2026-11-09 用户指定:龙抬头切 3.5,贞贞仍留 3.1)。
|
||||
* {@code gm-3.1-flash-lite}(2026-11-16 用户拍板:龙抬头从 3.5 改回 3.1 lite,
|
||||
* 2026-11-09 曾切到 {@code gm-3.5-flash-lite};贞贞始终 3.1 不变)。
|
||||
* 不映射直接切渠道会 model_not_found。</p>
|
||||
*/
|
||||
private final String defaultModel;
|
||||
|
||||
@@ -43,8 +43,6 @@ 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
|
||||
@@ -131,7 +129,7 @@ AIIMAGE_USER_SECRET_ADMIN_BALANCE_DEADLINE_MILLIS=10000
|
||||
# 以上 LLM 主机/模型是「贞贞」渠道的默认值(历史口径)。
|
||||
# 2026-10-29 起用户密钥可按人选择渠道(龙抬头 / 贞贞,默认贞贞,可手动切龙抬头):
|
||||
# - 渠道主机写死在 UserSecretModule/LlmChannel 里,不读本段;
|
||||
# - 手动切到龙抬头渠道后,模型 id 统一映射为 gm-3.5-flash-lite(2026-11-09 起,贞贞仍走 3.1),并显式补
|
||||
# - 手动切到龙抬头渠道后,模型 id 统一映射为 gm-3.1-flash-lite(2026-11-16 起,贞贞仍走 3.1),并显式补
|
||||
# enable_thinking=true + thinking_budget=medium(贞贞把 thinking 写在模型名里;
|
||||
# 不补这一对就等于给外观专利/货源查询降档。检测链路刻意不思考,只验连通);
|
||||
# - 用户没配密钥或迁移前遗留行没有 channel 时,才会回落到本段配置。
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V203__jd_product_group_owner_group
|
||||
-- 需求:2026-11-16 用户口径「京东数据库分类不同组不能看到跨组的分类,当前组只管理员可以编辑,
|
||||
-- 同组普通号只读;归类也按组隔离」——「组」=公司内的数据权限分组
|
||||
-- (biz_shop_manage_group),即 公司 → 组 两级隔离。
|
||||
-- 前版:V195(分组表按公司一套,uk_company_group_name)→ V200(退成全平台一份 uk_group_name)
|
||||
-- → V201(清空旧分类与商品归属,商品保留)
|
||||
--
|
||||
-- 1. 变更目的:分类从「全平台一份」改成「归属某个数据权限分组」。只加一个归属列不够——
|
||||
-- 商品归类也必须按组隔离(同一商品各组可各自归类),而 biz_jd_product.group_id 是单值列,
|
||||
-- 放不下"每组一份归属",故新增归属表 biz_jd_product_group_assign。
|
||||
-- biz_jd_product.group_id 列【不删】:V201 已把它整列置 NULL,本版起读写两侧都不再引用;
|
||||
-- 删列与换代码同批会在混合窗口里打断旧 jar(同 V200 第 2 段、V151 第 6 段纪律)。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- biz_jd_product_group + owner_group_id BIGINT NOT NULL DEFAULT 0
|
||||
-- uk_group_name(name) -> uk_company_owner_name(company_id, owner_group_id, name)
|
||||
-- biz_jd_product_group_assign(新表)
|
||||
-- uk_product_owner(product_id, owner_group_id) 一组一商品最多一个分类
|
||||
-- idx_category(category_id) 分类商品数现算 / 删分类级联
|
||||
-- idx_owner_group 按组取一组归属
|
||||
--
|
||||
-- 3. 存量:owner_group_id DEFAULT 0 =「V200 全平台一份时代」的历史行。V201 已把分类与商品归属
|
||||
-- 清空(2026-11-16 上线),预期本表 0 行、最多少量手工重建行;这些行不删、也不出现在任何
|
||||
-- 读取面(读侧只按真实分组 id 过滤)。要保留它们须人工回填归属,见文末回滚/恢复段。
|
||||
--
|
||||
-- 4. 可重跑性:两条列/键 DDL 与建表都先查 information_schema 再 PREPARE,重跑逐条 no-op。
|
||||
-- 先加新唯一键、再摘旧键(同 V151/V200 纪律:中间任一步失败时至少有一个唯一键在守并发)。
|
||||
--
|
||||
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- ALTER TABLE biz_jd_product_group ADD UNIQUE KEY uk_group_name (name);
|
||||
-- ALTER TABLE biz_jd_product_group DROP INDEX uk_company_owner_name;
|
||||
-- ALTER TABLE biz_jd_product_group DROP COLUMN owner_group_id;
|
||||
-- DROP TABLE biz_jd_product_group_assign;
|
||||
-- (jar 必须先回到"分类全平台一份"的那版,否则读侧会按不存在的列过滤。)
|
||||
--
|
||||
-- 6. 历史行恢复(可选,人工执行;确认目标组 id 与公司 id 后再跑):
|
||||
-- UPDATE biz_jd_product_group SET owner_group_id = <组id>, company_id = <公司id>
|
||||
-- WHERE owner_group_id = 0 AND name = '<分类名>';
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. 分类表:加归属数据权限分组列 ----------
|
||||
|
||||
SET @v203_owner_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_jd_product_group' AND COLUMN_NAME = 'owner_group_id');
|
||||
SET @sql := IF(@v203_owner_col = 0,
|
||||
'ALTER TABLE `biz_jd_product_group` ADD COLUMN `owner_group_id` BIGINT NOT NULL DEFAULT 0 COMMENT ''归属数据权限分组(biz_shop_manage_group.id);0=2026-11-15 公共化时代的历史行,读侧不可见;V203'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 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_company_owner_name');
|
||||
SET @sql := IF(@idx_exists = 0,
|
||||
'ALTER TABLE `biz_jd_product_group` ADD UNIQUE KEY `uk_company_owner_name` (`company_id`, `owner_group_id`, `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_group_name');
|
||||
SET @sql := IF(@idx_exists > 0,
|
||||
'ALTER TABLE `biz_jd_product_group` DROP INDEX `uk_group_name`, ALGORITHM = INPLACE, LOCK = NONE',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 4. 归类归属表(按组一份;同一商品各组可各自归类) ----------
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `biz_jd_product_group_assign` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`product_id` bigint NOT NULL COMMENT '商品行 id(biz_jd_product.id)',
|
||||
`owner_group_id` bigint NOT NULL COMMENT '归属数据权限分组(biz_shop_manage_group.id)',
|
||||
`category_id` bigint NOT NULL COMMENT '分类 id(biz_jd_product_group.id)',
|
||||
`company_id` bigint NOT NULL DEFAULT 0 COMMENT '归属公司(分组所属公司,读侧快速过滤)',
|
||||
`created_by` bigint NULL DEFAULT NULL COMMENT '操作者 user id',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_product_owner` (`product_id` ASC, `owner_group_id` ASC) USING BTREE,
|
||||
INDEX `idx_category` (`category_id` ASC) USING BTREE,
|
||||
INDEX `idx_owner_group` (`owner_group_id` ASC) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '京东商品按组归类归属(V203)' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
|
||||
--
|
||||
-- SHOW COLUMNS FROM biz_jd_product_group LIKE 'owner_group_id';
|
||||
-- -> 期望 Null = NO、Default = 0。
|
||||
--
|
||||
-- SELECT 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 INDEX_NAME;
|
||||
-- -> 期望 PRIMARY(id)、uk_company_owner_name(company_id@1,owner_group_id@2,name@3);
|
||||
-- uk_group_name 必须不在结果里。
|
||||
--
|
||||
-- SHOW CREATE TABLE biz_jd_product_group_assign;
|
||||
-- -> 期望含 uk_product_owner、idx_category、idx_owner_group。
|
||||
--
|
||||
-- SELECT COUNT(*) AS legacy_rows FROM biz_jd_product_group WHERE owner_group_id = 0;
|
||||
-- -> 记录读数(V201 已清空,预期 0;>0 的行迁移后不可见,按头注释第 6 段人工回填)。
|
||||
--
|
||||
-- INSERT 撞键(事务内跑完回滚,只插 ZZTEST 前缀):
|
||||
-- START TRANSACTION;
|
||||
-- INSERT INTO biz_jd_product_group_assign (product_id, owner_group_id, category_id)
|
||||
-- VALUES (9223372036854775806, 9223372036854775805, 9223372036854775804);
|
||||
-- INSERT INTO biz_jd_product_group_assign (product_id, owner_group_id, category_id)
|
||||
-- VALUES (9223372036854775806, 9223372036854775805, 9223372036854775803);
|
||||
-- SELECT ROW_COUNT() AS should_be_dup_error_probe;
|
||||
-- ROLLBACK;
|
||||
-- -> 期望第二条报 Duplicate entry(uk_product_owner 生效);回滚后零残留。
|
||||
-- =============================================================
|
||||
@@ -101,9 +101,12 @@
|
||||
</select>
|
||||
|
||||
<!-- 后管只读页(Phase 5,v1.4)过滤面:商品编码/标题关键词(contains LIKE)、类目 eq、
|
||||
分组 eq(2026-11-16 起由类目面板「自定义分类」选中驱动,独立「分类」筛选框与
|
||||
自定义分类 eq(2026-11-16 起由类目面板「自定义分类」选中驱动,独立「分类」筛选框与
|
||||
「分类状态」档随同日口径「分类不要了,全部整合到类目里」撤掉:ungrouped/grouped
|
||||
两参数与谓词同窗删除)、同步起止(datetime 闭区间)。
|
||||
group_id 过滤【V203 起按组隔离】:分类归属在 biz_jd_product_group_assign 的
|
||||
(product_id, owner_group_id) 一行上,商品行自己的 group_id 列已停用(V201 清空),
|
||||
故改 EXISTS 子查询;分类 id 自带归属组,不必再传 owner 维(行内谓词仍只这一处)。
|
||||
公司维过滤随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉(数据全平台公共;
|
||||
行 company_id 列仍是同步来源标记,不构成可见性边界)。
|
||||
sale_status 筛选随 2026-11-15 客户口径撤掉;店铺名过滤同日客户口径「店铺不需要」
|
||||
@@ -113,7 +116,12 @@
|
||||
<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="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="groupId != null and groupId > 0">
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_jd_product_group_assign a
|
||||
WHERE a.product_id = p.id AND a.category_id = #{groupId}
|
||||
)
|
||||
</if>
|
||||
<if test="syncedFrom != null">AND p.synced_at >= #{syncedFrom}</if>
|
||||
<if test="syncedTo != null">AND p.synced_at <= #{syncedTo}</if>
|
||||
</sql>
|
||||
@@ -126,14 +134,16 @@
|
||||
</select>
|
||||
|
||||
<!-- 只读页分页查询(synced_at 倒序)。
|
||||
group_name 不在此联表:读侧按行集 group_id 批量取分组名补齐(一次查询,无逐行查询)。 -->
|
||||
group_name 不在此联表:读侧按「当前数据权限分组」批量取归属
|
||||
(biz_jd_product_group_assign,V203)再补分类名(一次查询,无逐行查询)。
|
||||
p.group_id 列已随 V203 停用(分类改按组归属),不再投影。 -->
|
||||
<select id="selectProductPage" resultType="com.nanri.aiimage.modules.jd.model.entity.JdProductEntity">
|
||||
SELECT p.id, p.company_id, p.user_id, p.task_id, p.shop_id, p.shop_name, p.product_code, p.sku_id,
|
||||
p.item_num, p.sku_count, p.health_score,
|
||||
p.title, p.brand, p.brand_id, p.category_path, p.price_min, p.price_max, p.stock_total,
|
||||
p.sale_status, p.list_tab, p.jd_created_at, p.jd_online_at, p.jd_updated_at,
|
||||
p.main_image_url, p.detail_url,
|
||||
p.attr_json, p.attr_count, p.image_count, p.group_id, p.collect_batch_id, p.synced_at
|
||||
p.attr_json, p.attr_count, p.image_count, p.collect_batch_id, p.synced_at
|
||||
FROM biz_jd_product p
|
||||
WHERE 1=1 <include refid="productConds"/>
|
||||
ORDER BY p.synced_at DESC, p.id DESC
|
||||
|
||||
@@ -80,6 +80,31 @@ class JdSchemaContractTest {
|
||||
assertFalse(sql.contains("user_column_permission"), "菜单迁移不得插授权行(默认仅 super_admin,V190 惯例)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void V203_分类按数据权限分组归属_归属列与归属表形状() {
|
||||
String sql = read(DB_DIR.resolve("V203__jd_product_group_owner_group.sql"));
|
||||
assertTrue(sql.contains("biz_jd_product_group"), "缺分类表");
|
||||
// 归属列:NOT NULL DEFAULT 0(0=历史公共行,读侧不可见;显式默认值避免存量行 NULL 撞唯一键)。
|
||||
assertTrue(linesContaining(sql, "`owner_group_id`").stream()
|
||||
.anyMatch(line -> line.contains("NOT NULL") && line.contains("DEFAULT 0")),
|
||||
"owner_group_id 必须 NOT NULL DEFAULT 0(铁律 30:缺件沿用前值,NULL 会让唯一键失效)");
|
||||
// 唯一键三件套:同公司同组内重名拒绝、不同组可同名。
|
||||
assertTrue(sql.contains("uk_company_owner_name"), "同公司同组重名唯一键缺失");
|
||||
assertTrue(linesContaining(sql, "uk_company_owner_name").stream()
|
||||
.anyMatch(line -> line.contains("company_id") && line.contains("owner_group_id")
|
||||
&& line.contains("name")),
|
||||
"唯一键必须是 (company_id, owner_group_id, name)");
|
||||
// 一组一商品一行:同一商品各组可各自归类。
|
||||
assertTrue(sql.contains("biz_jd_product_group_assign"), "缺归类归属表");
|
||||
assertTrue(sql.contains("uk_product_owner"), "一组一商品唯一键缺失(uk_product_owner)");
|
||||
for (String column : List.of("product_id", "owner_group_id", "category_id", "company_id", "created_by")) {
|
||||
assertFalse(linesContaining(sql, "`" + column + "`").isEmpty(), "V203 归属表缺列: " + column);
|
||||
}
|
||||
// 可重跑:两次迁移之间不会因为列/键已存在而炸(information_schema 守卫)。
|
||||
assertTrue(sql.contains("information_schema"), "必须带 information_schema 幂等守卫(可重跑)");
|
||||
assertTrue(sql.contains("迁移 V203"), "头注释必须是 `-- 迁移 V203…`(MigrationInventoryTest 口径)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 配置_独立图片桶不落默认桶() {
|
||||
String appYml = read(RESOURCES.resolve("application.yml"));
|
||||
|
||||
+443
-119
@@ -4,25 +4,38 @@ import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
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.JdProductBatchAssignGroupRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
|
||||
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.JdProductGroupAssignEntity;
|
||||
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.JdCategoryGroupOptionVo;
|
||||
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.JdCategoryScopeService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
|
||||
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
|
||||
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.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
@@ -60,6 +73,13 @@ import static org.mockito.Mockito.when;
|
||||
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
|
||||
* tabs→attrGroups 解析与非法形状兜底(AC-7)。
|
||||
* 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p>
|
||||
*
|
||||
* <p><b>V203 分类按数据权限分组隔离(2026-11-16 用户口径)</b>:分类归属存
|
||||
* {@code biz_jd_product_group_assign} 的 (product_id, owner_group_id) 一行,读面靠
|
||||
* {@code owner_group_id} 取「当前分组」的分类(缺省=作用域默认分组),归类的写权限
|
||||
* 由 {@link JdCategoryScopeService} 判「该组可写」——商品行编辑/删除仍只平台超管。
|
||||
* 本类把作用域服务整体 mock 掉(四档角色矩阵在 {@code JdCategoryScopeServiceTest} 里钉),
|
||||
* 只钉控制器怎么用它、以及拒绝语义不被吞。</p>
|
||||
*/
|
||||
class AdminJdProductControllerTest {
|
||||
|
||||
@@ -73,6 +93,10 @@ class AdminJdProductControllerTest {
|
||||
private static final String COLUMN_KEY = "admin_jd_database";
|
||||
private static final String ROUTE_PATH = "jd-center/database";
|
||||
|
||||
/** 用例里的「当前分组」:数据权限分组 10,归属公司 5。 */
|
||||
private static final long GROUP_ID = 10L;
|
||||
private static final long COMPANY_ID = 5L;
|
||||
|
||||
// ===================== 结构判据 =====================
|
||||
|
||||
@Test
|
||||
@@ -96,6 +120,9 @@ class AdminJdProductControllerTest {
|
||||
// (AdminJdProductController 的 @PutMapping("/{id}",JdProductUpdateService 承接);商品行
|
||||
// 采集回传覆盖链不变,人工改名只走这条 PUT。分组改排序仍落 AdminJdProductGroupController。
|
||||
assertTrue(source.contains("@PutMapping"), "编辑商品端点必须落在 @PutMapping(\"/{id}\")");
|
||||
// V203:读面「当前分组」一律走 owner_group_id(不叫 company_id——前端 company-tab 绊线钉住)。
|
||||
assertTrue(source.contains("\"owner_group_id\""),
|
||||
"分页/详情必须收 owner_group_id(当前数据权限分组)");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,7 +159,7 @@ class AdminJdProductControllerTest {
|
||||
void 分页参数snake且带默认值() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
for (String param : List.of("page_size", "product_code", "title_keyword",
|
||||
"group_id", "synced_from", "synced_to")) {
|
||||
"group_id", "owner_group_id", "synced_from", "synced_to")) {
|
||||
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
|
||||
}
|
||||
assertFalse(source.contains("@RequestParam(name = \"ungrouped\""));
|
||||
@@ -160,7 +187,13 @@ class AdminJdProductControllerTest {
|
||||
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
|
||||
assertTrue(xmlText.contains("countProducts"), "XML 必须有 countProducts(只读页总数)");
|
||||
assertTrue(xmlText.contains("selectProductPage"), "XML 必须有 selectProductPage(只读页分页)");
|
||||
assertTrue(xmlText.contains("AND p.group_id = #{groupId}"), "自定义分类必须下推 SQL");
|
||||
// V203:分类归属在 biz_jd_product_group_assign(一组一商品一行),过滤必须下推成 EXISTS 子查询。
|
||||
assertTrue(xmlText.contains("FROM biz_jd_product_group_assign"),
|
||||
"自定义分类必须下推 SQL(V203 归属表 EXISTS 子查询)");
|
||||
assertTrue(xmlText.contains("a.product_id = p.id") && xmlText.contains("a.category_id = #{groupId}"),
|
||||
"EXISTS 子查询必须同时按商品与分类关联");
|
||||
assertFalse(xmlText.contains("p.group_id = #{groupId}"),
|
||||
"商品行 group_id 列已随 V203 停用(分类按组归属),不得回潜");
|
||||
assertFalse(xmlText.contains("ungrouped"));
|
||||
assertFalse(xmlText.contains("grouped"));
|
||||
assertEquals(2, xmlText.split("<include refid=\"productConds\"", -1).length - 1,
|
||||
@@ -174,17 +207,233 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 分组控制器与同款鉴权闸就位() throws IOException {
|
||||
assertTrue(Files.exists(GROUP_CONTROLLER),
|
||||
"分组控制器必须落在 " + GROUP_CONTROLLER + "(AC-9:普通授权用户可读写分组)");
|
||||
"分组控制器必须落在 " + GROUP_CONTROLLER);
|
||||
String source = stripComments(Files.readString(GROUP_CONTROLLER));
|
||||
assertTrue(source.contains("/api/admin/jd-product-groups"), "分组端点必须挂在 /api/admin/jd-product-groups");
|
||||
for (String seam : List.of("requireUser", "X-Internal-Token", "isSuper",
|
||||
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
|
||||
assertTrue(source.contains(seam), "分组鉴权闸缺接缝 " + seam + "(与商品页同款)");
|
||||
}
|
||||
// 普通(非超管)授权用户可读写分组:菜单双匹配那道闸在两个控制器上逐字同源。
|
||||
// V203 起写权限不再收窄到平台超管:本组管理员 / 公司超管 / 平台超管都可写(作用域服务判)。
|
||||
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
|
||||
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb + "(AC-9)");
|
||||
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb);
|
||||
}
|
||||
assertEquals(5, count(source, "requireJdAccess(request)"),
|
||||
"列表/作用域/新建/改名/删除五条路由都走同一菜单正门(写权限在作用域服务里判)");
|
||||
assertFalse(source.contains("requirePlatformSuperAdminWrite"),
|
||||
"分类写权限已改由 JdCategoryScopeService 判「该组可写」,超管专属闸必须已摘除");
|
||||
assertTrue(source.contains("requireWritableGroup(") && source.contains("canWrite("),
|
||||
"新建走 requireWritableGroup,改名/删除走 canWrite 归属校验");
|
||||
assertTrue(source.contains("/scope") && source.contains("scopeVo("),
|
||||
"必须提供 GET /scope 给前端渲染「分组」下拉与可写标记");
|
||||
assertTrue(source.contains("仅该分组的管理员可以修改它的分类"),
|
||||
"非本组管理员写分类的 403 文案必须点名分组管理员");
|
||||
assertTrue(source.contains("\"owner_group_id\""), "列表必须收 owner_group_id(当前分组)");
|
||||
}
|
||||
|
||||
// ===================== 写权限分档(2026-11-16 / V203) =====================
|
||||
|
||||
/** 写端点越权闸的结构判据:商品行四条写路由走超管闸,读三条走菜单正门。 */
|
||||
@Test
|
||||
void 商品页读写权限分档_商品行写端点逐条走超管闸() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
assertEquals(4, count(source, "requirePlatformSuperAdminWrite(request)"),
|
||||
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走超管写闸"
|
||||
+ "(归类不在此列:V203 起归本组管理员可做)");
|
||||
assertEquals(5, count(source, "requireJdAccess(request)"),
|
||||
"列表/类目/详情/归类四条读+组内写路由,与超管写闸内部一处,共五处菜单权限正门");
|
||||
assertTrue(source.contains("仅平台超级管理员可以编辑或删除京东数据库数据"),
|
||||
"非超管写商品的 403 文案必须点名平台超管");
|
||||
assertTrue(source.contains("operator.superAdmin()"),
|
||||
"写闸必须在菜单口径之上再判 superAdmin(只放行站点超管,公司超管不在内)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非超管有菜单权限时读放行_商品行写一律403且不触服务() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
|
||||
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, updateService, groupService, scopeService,
|
||||
authSupport, permissionMenuService);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(9L);
|
||||
operator.setUsername("company-admin");
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、商品行写仍拒。
|
||||
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||
PermissionMenuItemVo grant = new PermissionMenuItemVo();
|
||||
grant.setColumnKey(COLUMN_KEY);
|
||||
grant.setRoutePath(ROUTE_PATH);
|
||||
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
|
||||
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
|
||||
|
||||
// 读:菜单权限命中即放行(公共库一人一份全量)。
|
||||
JdProductPageVo pageVo = new JdProductPageVo();
|
||||
pageVo.setItems(List.of());
|
||||
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
|
||||
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, request)
|
||||
.isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)");
|
||||
|
||||
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
|
||||
JdProductUpdateRequest updateBody = new JdProductUpdateRequest();
|
||||
updateBody.setTitle("标题");
|
||||
BusinessException updateEx = assertThrows(BusinessException.class,
|
||||
() -> controller.update(11L, updateBody, request));
|
||||
assertTrue(updateEx.getMessage().contains("仅平台超级管理员"), "编辑被拒文案点名平台超管");
|
||||
|
||||
BusinessException deleteEx = assertThrows(BusinessException.class,
|
||||
() -> controller.delete(11L, request));
|
||||
assertTrue(deleteEx.getMessage().contains("仅平台超级管理员"));
|
||||
|
||||
JdProductBatchDeleteRequest batchBody = new JdProductBatchDeleteRequest();
|
||||
batchBody.setIds(List.of(11L, 12L));
|
||||
BusinessException batchEx = assertThrows(BusinessException.class,
|
||||
() -> controller.batchDelete(batchBody, request));
|
||||
assertTrue(batchEx.getMessage().contains("仅平台超级管理员"));
|
||||
|
||||
BusinessException uploadEx = assertThrows(BusinessException.class,
|
||||
() -> controller.uploadImage(11L, mock(MultipartFile.class), "MAIN", null, null, request));
|
||||
assertTrue(uploadEx.getMessage().contains("仅平台超级管理员"),
|
||||
"上传/替换图片改桶内对象=写动作,必须同闸");
|
||||
|
||||
verify(updateService, never()).update(any(), any());
|
||||
verify(updateService, never()).uploadImage(any(), any(), any(), any(), any());
|
||||
verify(updateService, never()).assignGroup(any(), any(), any(), any(), any());
|
||||
verify(deleteService, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 不可写组的分组写一律403且不触服务() {
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
AdminJdProductGroupController controller = new AdminJdProductGroupController(
|
||||
groupService, scopeService, authSupport, permissionMenuService);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(9L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||
PermissionMenuItemVo grant = new PermissionMenuItemVo();
|
||||
grant.setColumnKey(COLUMN_KEY);
|
||||
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
|
||||
// 普通号:组可见但不可写(四档矩阵在 JdCategoryScopeServiceTest 里钉,这里只钉控制器接线)。
|
||||
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
|
||||
when(groupService.list(GROUP_ID)).thenReturn(List.of());
|
||||
when(groupService.requireCategory(7L)).thenReturn(category(7L, GROUP_ID));
|
||||
// 真实作用域服务对「可见但不可写」的组回 403;mock 掉它只验控制器不吞、不触业务服务。
|
||||
when(scopeService.requireWritableGroup(any(), any()))
|
||||
.thenThrow(new BusinessException(403, "仅该分组的管理员可以修改它的分类"));
|
||||
|
||||
assertEquals(Boolean.TRUE, controller.list(null, request).isSuccess(),
|
||||
"分类列表是读端点,菜单权限命中即放行(同组普通号也能开弹窗看)");
|
||||
|
||||
JdProductGroupSaveRequest saveBody = new JdProductGroupSaveRequest();
|
||||
saveBody.setName("新分类");
|
||||
saveBody.setSortOrder(0);
|
||||
BusinessException createEx = assertThrows(BusinessException.class,
|
||||
() -> controller.create(saveBody, request));
|
||||
assertTrue(createEx.getMessage().contains("仅该分组的管理员"),
|
||||
"新建成分类的 403 文案必须点名分组管理员");
|
||||
// 改名/删除:控制器自己按分类归属判 canWrite(作用域不可写 ⇒ 403,业务服务不被调到)。
|
||||
BusinessException renameEx = assertThrows(BusinessException.class,
|
||||
() -> controller.rename(7L, saveBody, request));
|
||||
assertTrue(renameEx.getMessage().contains("仅该分组的管理员"));
|
||||
BusinessException deleteEx = assertThrows(BusinessException.class,
|
||||
() -> controller.delete(7L, request));
|
||||
assertTrue(deleteEx.getMessage().contains("仅该分组的管理员"));
|
||||
|
||||
verify(groupService, never()).create(any(), any(), any(), any());
|
||||
verify(groupService, never()).rename(any(), any(), any());
|
||||
verify(groupService, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 本组管理员可归类本组_组内写权限不再只归平台超管() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), updateService, groupService,
|
||||
scopeService, authSupport, permissionMenuService);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(9L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
// 组长(admin,非平台超管):拿到菜单权限即可归类自己带的组。
|
||||
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||
PermissionMenuItemVo grant = new PermissionMenuItemVo();
|
||||
grant.setColumnKey(COLUMN_KEY);
|
||||
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
|
||||
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.requireWritableGroup(any(), any())).thenReturn(shopGroup(GROUP_ID, COMPANY_ID));
|
||||
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L)).thenReturn(2);
|
||||
|
||||
JdProductBatchAssignGroupRequest body = new JdProductBatchAssignGroupRequest();
|
||||
body.setIds(List.of(11L, 12L));
|
||||
body.setGroupId(3L);
|
||||
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
|
||||
|
||||
verify(updateService).assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
|
||||
assertEquals(2, response.getData(), "回执=实际写入的归属行数");
|
||||
|
||||
// 业务失败(目标分类不属于当前分组)文案原样透出,不吞。
|
||||
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L), 404L, 9L))
|
||||
.thenThrow(new BusinessException(403, "该分类不属于当前分组,请刷新后重试"));
|
||||
JdProductBatchAssignGroupRequest ghostBody = new JdProductBatchAssignGroupRequest();
|
||||
ghostBody.setIds(List.of(11L));
|
||||
ghostBody.setGroupId(404L);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.batchAssignGroup(ghostBody, request));
|
||||
assertTrue(ex.getMessage().contains("不属于当前分组"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分类筛选越组请求403且不触查询服务() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
|
||||
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
|
||||
|
||||
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");
|
||||
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
|
||||
// 分类 8 属于别组(ownerGroupId=20):按「当前分组」不可见 ⇒ 403,不放成空结果。
|
||||
when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L));
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, request));
|
||||
assertTrue(ex.getMessage().contains("无权查看该分组的分类"),
|
||||
"跨组分类筛选必须 403 点名分组,不做空结果降级");
|
||||
|
||||
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
// ===================== 行为样本 =====================
|
||||
@@ -192,29 +441,33 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 控制器列表走requireJdAccess正门并把查询结果装进200信封() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
permissionMenuService);
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
|
||||
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
|
||||
|
||||
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");
|
||||
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.readGroupOrNull(scope, GROUP_ID)).thenReturn(GROUP_ID);
|
||||
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, null, null, null, null, null, null)).thenReturn(pageVo);
|
||||
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
|
||||
|
||||
// 2026-11-16 起请求面没有 company_id:任何授权身份看到的都是同一份全量。
|
||||
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
|
||||
null, request);
|
||||
// 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。
|
||||
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null,
|
||||
GROUP_ID, null, null, request);
|
||||
|
||||
verify(queryService).page(1L, 20L, null, null, null, null, null, null);
|
||||
verify(queryService).page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
|
||||
assertEquals(pageVo, response.getData());
|
||||
}
|
||||
@@ -222,10 +475,12 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 旧分类筛选参数明确拒绝并提示刷新() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
|
||||
authSupport, mock(PermissionMenuService.class));
|
||||
mock(JdProductGroupService.class), scopeService, authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
@@ -236,12 +491,12 @@ class AdminJdProductControllerTest {
|
||||
for (String value : List.of("true", "false", "")) {
|
||||
when(request.getParameter(name)).thenReturn(value);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, request));
|
||||
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, null, request));
|
||||
assertTrue(ex.getMessage().contains("刷新页面"));
|
||||
when(request.getParameter(name)).thenReturn(null);
|
||||
}
|
||||
}
|
||||
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -249,7 +504,8 @@ class AdminJdProductControllerTest {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
|
||||
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -273,9 +529,11 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 控制器详情走同一鉴权正门并回详情且不问公司() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
|
||||
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
|
||||
mock(JdProductGroupService.class), scopeService, authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -283,14 +541,18 @@ class AdminJdProductControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
|
||||
when(scopeService.resolve(operator)).thenReturn(scope);
|
||||
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
|
||||
JdProductDetailVo detailVo = new JdProductDetailVo();
|
||||
detailVo.setId(11L);
|
||||
when(queryService.detail(11L)).thenReturn(detailVo);
|
||||
when(queryService.detail(11L, GROUP_ID)).thenReturn(detailVo);
|
||||
|
||||
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
|
||||
ApiResponse<JdProductDetailVo> response = controller.detail(11L, null, request);
|
||||
|
||||
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除)。
|
||||
verify(queryService).detail(11L);
|
||||
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除);
|
||||
// 分类字段按「当前分组」取(V203)。
|
||||
verify(queryService).detail(11L, GROUP_ID);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess());
|
||||
assertEquals(detailVo, response.getData());
|
||||
}
|
||||
@@ -301,7 +563,8 @@ class AdminJdProductControllerTest {
|
||||
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
|
||||
queryService, deleteService, mock(JdProductUpdateService.class),
|
||||
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -329,7 +592,8 @@ class AdminJdProductControllerTest {
|
||||
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
|
||||
queryService, deleteService, mock(JdProductUpdateService.class),
|
||||
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
@@ -350,13 +614,11 @@ class AdminJdProductControllerTest {
|
||||
@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));
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
when(mapper.countProducts(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);
|
||||
service.page(0L, 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(),
|
||||
@@ -365,7 +627,7 @@ class AdminJdProductControllerTest {
|
||||
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);
|
||||
service.page(Long.MAX_VALUE, 500L, 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(),
|
||||
@@ -377,13 +639,11 @@ class AdminJdProductControllerTest {
|
||||
@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));
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
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, from, to));
|
||||
() -> service.page(1L, 20L, null, null, null, null, from, to, null));
|
||||
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
|
||||
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
@@ -391,65 +651,22 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 查询服务过滤面原样直传且空串归null() {
|
||||
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));
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null);
|
||||
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null);
|
||||
verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null);
|
||||
verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, 0L, 20);
|
||||
|
||||
service.page(1L, 20L, " ", null, null, 0L, null, null);
|
||||
service.page(1L, 20L, " ", null, null, 0L, null, null, null);
|
||||
verify(mapper).countProducts(null, null, null, null, null, null);
|
||||
verify(mapper).selectProductPage(null, null, null, null, null, null, 0L, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类端点走同一鉴权正门且参数透传() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, mock(JdProductDeleteService.class), updateService, authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
|
||||
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 不得回流)。
|
||||
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
|
||||
void 详情解析attr_json的tabs映射成attrGroups() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductImageMapper imageMapper = mock(JdProductImageMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, imageMapper,
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
JdProductQueryService service = queryService(mapper, imageMapper);
|
||||
|
||||
JdProductEntity row = productEntity(11L);
|
||||
// 客户端实拍契约:tabs[{tab, attrs[{key,label,value}]}];value 允许数字型 JSON 值(转字符串)。
|
||||
@@ -470,7 +687,7 @@ class AdminJdProductControllerTest {
|
||||
image.setHeight(800);
|
||||
when(imageMapper.selectList(any())).thenReturn(List.of(image));
|
||||
|
||||
JdProductDetailVo vo = service.detail(11L);
|
||||
JdProductDetailVo vo = service.detail(11L, null);
|
||||
|
||||
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
|
||||
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
|
||||
@@ -493,15 +710,13 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 详情非法attr_json落空分组且原文兜底不抛500() {
|
||||
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));
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
|
||||
// 形状一:非法 JSON(解析异常)。
|
||||
JdProductEntity broken = productEntity(11L);
|
||||
broken.setAttrJson("{\"tabs\": [broken");
|
||||
when(mapper.selectById(11L)).thenReturn(broken);
|
||||
JdProductDetailVo brokenVo = service.detail(11L);
|
||||
JdProductDetailVo brokenVo = service.detail(11L, null);
|
||||
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
|
||||
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
|
||||
|
||||
@@ -509,7 +724,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);
|
||||
JdProductDetailVo foreignVo = service.detail(11L, null);
|
||||
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
|
||||
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
|
||||
"未识别属性不丢弃:原文兜底透出(AC-7)");
|
||||
@@ -518,7 +733,7 @@ class AdminJdProductControllerTest {
|
||||
JdProductEntity blank = productEntity(11L);
|
||||
blank.setAttrJson(null);
|
||||
when(mapper.selectById(11L)).thenReturn(blank);
|
||||
JdProductDetailVo blankVo = service.detail(11L);
|
||||
JdProductDetailVo blankVo = service.detail(11L, null);
|
||||
assertTrue(blankVo.getAttrGroups().isEmpty());
|
||||
assertNull(blankVo.getAttrJsonRaw());
|
||||
}
|
||||
@@ -526,11 +741,8 @@ class AdminJdProductControllerTest {
|
||||
@Test
|
||||
void 详情下发SKU矩阵_销售属性JSON解析成键值对() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper skuMapper =
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper,
|
||||
mock(JdProductImageMapper.class), skuMapper,
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
JdProductSkuMapper skuMapper = mock(JdProductSkuMapper.class);
|
||||
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class), skuMapper);
|
||||
|
||||
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
|
||||
|
||||
@@ -550,7 +762,7 @@ class AdminJdProductControllerTest {
|
||||
brokenJson.setSaleAttrsJson("[{\"name\":");
|
||||
when(skuMapper.selectList(any())).thenReturn(List.of(first, brokenJson));
|
||||
|
||||
JdProductDetailVo vo = service.detail(11L);
|
||||
JdProductDetailVo vo = service.detail(11L, null);
|
||||
|
||||
assertEquals(2, vo.getSkus().size(), "京麦那 12 行矩阵按入库行下发(抽屉渲染的唯一来源)");
|
||||
JdProductDetailVo.SkuVo sku = vo.getSkus().get(0);
|
||||
@@ -569,55 +781,158 @@ class AdminJdProductControllerTest {
|
||||
@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));
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
|
||||
// 公共库(2026-11-15 用户定案):详情没有公司维度,别家公司时代的行照样可读。
|
||||
JdProductEntity row = productEntity(11L);
|
||||
row.setCompanyId(6L);
|
||||
when(mapper.selectById(11L)).thenReturn(row);
|
||||
assertNotNull(service.detail(11L));
|
||||
assertNotNull(service.detail(11L, null));
|
||||
|
||||
// 行不存在 ⇒ 按「商品不存在」拒绝。
|
||||
when(mapper.selectById(11L)).thenReturn(null);
|
||||
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L));
|
||||
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, null));
|
||||
assertTrue(ex.getMessage().contains("商品不存在"));
|
||||
// id 非法同样拒绝。
|
||||
assertThrows(BusinessException.class, () -> service.detail(0L));
|
||||
assertThrows(BusinessException.class, () -> service.detail(0L, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 列表行分组名批量补齐且读不到不猜() {
|
||||
void 列表行分类名按当前分组批量补齐且读不到不猜() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper groupMapper =
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
|
||||
groupMapper);
|
||||
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
|
||||
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
|
||||
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
|
||||
|
||||
JdProductEntity grouped = productEntity(1L);
|
||||
grouped.setGroupId(3L);
|
||||
JdProductEntity categorized = productEntity(1L);
|
||||
JdProductEntity missing = productEntity(2L);
|
||||
missing.setGroupId(99L);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(2L);
|
||||
when(mapper.selectProductPage(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();
|
||||
group.setId(3L);
|
||||
group.setName("秋冬款");
|
||||
when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group));
|
||||
anyLong(), anyInt())).thenReturn(List.of(categorized, missing));
|
||||
when(assignMapper.selectList(any())).thenReturn(List.of(
|
||||
assign(1L, GROUP_ID, 3L), assign(2L, GROUP_ID, 99L)));
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setId(3L);
|
||||
category.setName("秋冬款");
|
||||
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
|
||||
|
||||
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null);
|
||||
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
|
||||
|
||||
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
|
||||
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
|
||||
verify(groupMapper, times(1)).selectBatchIds(any());
|
||||
assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行");
|
||||
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)");
|
||||
assertNull(vo.getItems().get(1).getGroupName(), "分类已删=不猜名字(铁律 30),前端展示 -");
|
||||
verify(assignMapper, times(1)).selectList(any());
|
||||
verify(categoryMapper, times(1)).selectBatchIds(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 列表无当前分组时分类列全空且不发归属查询() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
|
||||
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(JdProductSkuMapper.class), mock(JdProductGroupMapper.class), assignMapper);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(),
|
||||
anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
|
||||
|
||||
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null);
|
||||
|
||||
assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)");
|
||||
assertNull(vo.getItems().get(0).getGroupName());
|
||||
verify(assignMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 详情分类按当前分组取_别的组归类不可见() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
|
||||
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
|
||||
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
|
||||
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
|
||||
|
||||
// 本组(10)没归类:detail 的 selectOne 回 null ⇒ 分类字段空。
|
||||
when(assignMapper.selectOne(any())).thenReturn(null);
|
||||
JdProductDetailVo untouched = service.detail(11L, GROUP_ID);
|
||||
assertNull(untouched.getGroupId(), "本组没归类=未分类,不拿别组的归属顶上");
|
||||
assertNull(untouched.getGroupName());
|
||||
|
||||
// 本组归类到 3:取到分类名。
|
||||
when(assignMapper.selectOne(any())).thenReturn(assign(11L, GROUP_ID, 3L));
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setId(3L);
|
||||
category.setName("秋冬款");
|
||||
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
|
||||
JdProductDetailVo categorized = service.detail(11L, GROUP_ID);
|
||||
assertEquals(3L, categorized.getGroupId());
|
||||
assertEquals("秋冬款", categorized.getGroupName());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
/** 查询服务夹具:默认四个从属 mapper 全 mock,只有 assign mapper 可注入。 */
|
||||
private static JdProductQueryService queryService(JdProductMapper mapper) {
|
||||
return queryService(mapper, mock(JdProductImageMapper.class), mock(JdProductSkuMapper.class),
|
||||
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
|
||||
}
|
||||
|
||||
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper) {
|
||||
return queryService(mapper, imageMapper, mock(JdProductSkuMapper.class),
|
||||
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
|
||||
}
|
||||
|
||||
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
|
||||
JdProductSkuMapper skuMapper) {
|
||||
return queryService(mapper, imageMapper, skuMapper,
|
||||
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
|
||||
}
|
||||
|
||||
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
|
||||
JdProductSkuMapper skuMapper, JdProductGroupMapper categoryMapper,
|
||||
JdProductGroupAssignMapper assignMapper) {
|
||||
return new JdProductQueryService(mapper, imageMapper, skuMapper, categoryMapper, assignMapper);
|
||||
}
|
||||
|
||||
/** 可写作用域(组长/公司超管/平台超管同形:可见组=可写组)。 */
|
||||
private static JdCategoryScopeService.JdCategoryScope writableScope(long groupId, long companyId) {
|
||||
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
|
||||
List.of(groupId), List.of(groupId),
|
||||
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", true)));
|
||||
}
|
||||
|
||||
/** 只读作用域(组内普通号:可见不可写)。 */
|
||||
private static JdCategoryScopeService.JdCategoryScope readOnlyScope(long groupId, long companyId) {
|
||||
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
|
||||
List.of(groupId), List.of(),
|
||||
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
|
||||
}
|
||||
|
||||
private static ShopManageGroupEntity shopGroup(long id, long companyId) {
|
||||
ShopManageGroupEntity group = new ShopManageGroupEntity();
|
||||
group.setId(id);
|
||||
group.setCompanyId(companyId);
|
||||
group.setGroupName("默认组");
|
||||
return group;
|
||||
}
|
||||
|
||||
private static JdProductGroupEntity category(long id, long ownerGroupId) {
|
||||
JdProductGroupEntity entity = new JdProductGroupEntity();
|
||||
entity.setId(id);
|
||||
entity.setOwnerGroupId(ownerGroupId);
|
||||
entity.setCompanyId(COMPANY_ID);
|
||||
entity.setName("分类-" + id);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static JdProductGroupAssignEntity assign(long productId, long ownerGroupId, long categoryId) {
|
||||
JdProductGroupAssignEntity entity = new JdProductGroupAssignEntity();
|
||||
entity.setProductId(productId);
|
||||
entity.setOwnerGroupId(ownerGroupId);
|
||||
entity.setCategoryId(categoryId);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 列表/详情用例共用的商品行夹具:归属公司 5,主字段齐备便于按字段对撞。 */
|
||||
private static JdProductEntity productEntity(long id) {
|
||||
JdProductEntity entity = new JdProductEntity();
|
||||
@@ -661,4 +976,13 @@ class AdminJdProductControllerTest {
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** 判据里的出现次数(逐字匹配,非正则)。 */
|
||||
private static int count(String text, String needle) {
|
||||
int n = 0;
|
||||
for (int i = text.indexOf(needle); i >= 0; i = text.indexOf(needle, i + needle.length())) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
+58
-10
@@ -2,7 +2,9 @@ package com.nanri.aiimage.modules.jd.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCollectBoardService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdCollectTaskService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
@@ -32,30 +34,38 @@ import static org.mockito.Mockito.when;
|
||||
* 用户侧「店铺分类」只读端点(2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」)。
|
||||
*
|
||||
* <p>「获取店铺数据」页把管理员在后管京东数据库建的分类展示给普通账号:GET /api/jd-collect/groups,
|
||||
* 与 categories 端点同形(登录用户即可读、fail-closed 401;分组全平台一份、无公司维度)。
|
||||
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。结构判据(照
|
||||
* {@code AdminJdProductControllerTest} 双形态的第一半)+行为样本(200 信封装 list、鉴权先过)。</p>
|
||||
* 与 categories 端点同形(登录用户即可读、fail-closed 401)。
|
||||
* <b>V203 起按数据权限分组隔离</b>:只下发登录用户<b>可见组</b>的分类(「不同组不能看到跨组的分类」),
|
||||
* 收窄由 {@code JdCategoryScopeService.resolveByUserId} 出,本端点不自己判角色。
|
||||
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。</p>
|
||||
*/
|
||||
class JdCollectGroupsEndpointTest {
|
||||
|
||||
private static final Path CONTROLLER = Path.of("").toAbsolutePath()
|
||||
.resolve("src/main/java/com/nanri/aiimage/modules/jd/controller/JdCollectController.java");
|
||||
|
||||
private static final long USER_ID = 1L;
|
||||
private static final long GROUP_ID = 10L;
|
||||
|
||||
@Test
|
||||
void 结构判据_groups端点只读且复用分组服务公共口径() throws IOException {
|
||||
void 结构判据_groups端点只读且按可见组收窄() throws IOException {
|
||||
assertTrue(Files.exists(CONTROLLER), "控制器必须落在 " + CONTROLLER);
|
||||
String source = Files.readString(CONTROLLER);
|
||||
assertTrue(source.contains("@GetMapping(\"/groups\")"),
|
||||
"用户侧分类列表必须是 GET /groups(categories 同形)");
|
||||
assertTrue(source.contains("jdProductGroupService.list()"),
|
||||
"必须复用 JdProductGroupService.list()(与后管分组管理同一条读出口,不另造查询)");
|
||||
assertTrue(source.contains("jdCategoryScopeService.resolveByUserId(userId)"),
|
||||
"可见组必须由 JdCategoryScopeService 按登录用户解析(端点不自己判角色)");
|
||||
assertTrue(source.contains("jdProductGroupService.listForGroups(scope.visibleGroupIds())"),
|
||||
"必须按可见组取分类(listForGroups),不得退回 list() 全量下发"
|
||||
+ "——否则普通号仍能看到别组的分类");
|
||||
assertTrue(source.contains("adminAuthSupport.requireOwnershipUserId(httpRequest, null)"),
|
||||
"登录用户即可读但必须 fail-closed:解析不出会话身份就 401(与 categories 同口径)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 行为样本_鉴权先过且200信封装分组全量() {
|
||||
void 行为样本_鉴权先过且200信封只装可见组的分类() {
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
JdCollectController controller = new JdCollectController(
|
||||
mock(JdCollectTaskService.class),
|
||||
@@ -63,6 +73,7 @@ class JdCollectGroupsEndpointTest {
|
||||
mock(JdResultIngestService.class),
|
||||
mock(JdProductQueryService.class),
|
||||
groupService,
|
||||
scopeService,
|
||||
mock(TaskHeartbeatService.class),
|
||||
mock(TaskHeartbeatPositionService.class),
|
||||
mock(TaskProgressOwnershipSupport.class),
|
||||
@@ -72,9 +83,11 @@ class JdCollectGroupsEndpointTest {
|
||||
JdProductGroupVo vo = new JdProductGroupVo();
|
||||
vo.setId(7L);
|
||||
vo.setName("ASSS");
|
||||
vo.setOwnerGroupId(GROUP_ID);
|
||||
vo.setProductCount(20L);
|
||||
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(1L);
|
||||
when(groupService.list()).thenReturn(List.of(vo));
|
||||
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
|
||||
when(scopeService.resolveByUserId(USER_ID)).thenReturn(scope(GROUP_ID));
|
||||
when(groupService.listForGroups(List.of(GROUP_ID))).thenReturn(List.of(vo));
|
||||
|
||||
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
|
||||
|
||||
@@ -83,9 +96,44 @@ class JdCollectGroupsEndpointTest {
|
||||
assertNotNull(response.getData());
|
||||
assertEquals(1, response.getData().size());
|
||||
assertEquals("ASSS", response.getData().get(0).getName());
|
||||
assertEquals(GROUP_ID, response.getData().get(0).getOwnerGroupId());
|
||||
assertEquals(20L, response.getData().get(0).getProductCount());
|
||||
// 鉴权闸先行:解析不出会话身份就 401,读不到任何数据。
|
||||
verify(authSupport).requireOwnershipUserId(same(request), isNull());
|
||||
verify(groupService).list();
|
||||
verify(scopeService).resolveByUserId(USER_ID);
|
||||
verify(groupService).listForGroups(List.of(GROUP_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 行为样本_不属于任何分组时下发空列表() {
|
||||
JdProductGroupService groupService = mock(JdProductGroupService.class);
|
||||
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
JdCollectController controller = new JdCollectController(
|
||||
mock(JdCollectTaskService.class),
|
||||
mock(JdCollectBoardService.class),
|
||||
mock(JdResultIngestService.class),
|
||||
mock(JdProductQueryService.class),
|
||||
groupService,
|
||||
scopeService,
|
||||
mock(TaskHeartbeatService.class),
|
||||
mock(TaskHeartbeatPositionService.class),
|
||||
mock(TaskProgressOwnershipSupport.class),
|
||||
authSupport);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
|
||||
when(scopeService.resolveByUserId(USER_ID)).thenReturn(JdCategoryScopeService.JdCategoryScope.empty());
|
||||
when(groupService.listForGroups(List.of())).thenReturn(List.of());
|
||||
|
||||
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
|
||||
|
||||
assertTrue(response.isSuccess());
|
||||
assertTrue(response.getData().isEmpty(), "一个可见组都没有 ⇒ 空列表(不降级成全平台分类)");
|
||||
verify(groupService).listForGroups(List.of());
|
||||
}
|
||||
|
||||
private static JdCategoryScopeService.JdCategoryScope scope(long groupId) {
|
||||
return new JdCategoryScopeService.JdCategoryScope(false, 5L, List.of(groupId), List.of(),
|
||||
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
|
||||
}
|
||||
}
|
||||
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
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.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
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.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。
|
||||
*
|
||||
* <p>四档矩阵:平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
|
||||
* 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读;
|
||||
* 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。
|
||||
* 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、
|
||||
* 写侧在「无可写组 / 多可写组未选 / 该组不可写 / 组行不存在」四种形状下的文案。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdCategoryScopeServiceTest {
|
||||
|
||||
private static final long USER_ID = 9L;
|
||||
private static final long COMPANY_ID = 5L;
|
||||
|
||||
@Mock
|
||||
private AdminAuthSupport adminAuthSupport;
|
||||
@Mock
|
||||
private DataReadScope dataReadScope;
|
||||
@Mock
|
||||
private AdminUserMapper adminUserMapper;
|
||||
@Mock
|
||||
private ShopManageGroupMapper shopManageGroupMapper;
|
||||
@Mock
|
||||
private CompanyMapper companyMapper;
|
||||
|
||||
@InjectMocks
|
||||
private JdCategoryScopeService service;
|
||||
|
||||
// ---------------------------------------------------------------- 四档矩阵
|
||||
|
||||
@Test
|
||||
void 平台超管_可见并可写全部公司全部组且组名带公司前缀() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
|
||||
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
|
||||
group(10L, 1L, "A组"), group(20L, 2L, "B组")));
|
||||
CompanyEntity first = new CompanyEntity();
|
||||
first.setId(1L);
|
||||
first.setCompanyName("甲公司");
|
||||
CompanyEntity second = new CompanyEntity();
|
||||
second.setId(2L);
|
||||
second.setCompanyName("乙公司");
|
||||
when(companyMapper.selectBatchIds(any())).thenReturn(List.of(first, second));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.platformSuperAdmin()).isTrue();
|
||||
assertThat(scope.visibleGroupIds()).containsExactly(10L, 20L);
|
||||
assertThat(scope.writableGroupIds()).containsExactly(10L, 20L);
|
||||
assertThat(scope.defaultGroupId()).isEqualTo(10L);
|
||||
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
|
||||
.containsExactly("甲公司 / A组", "乙公司 / B组");
|
||||
assertThat(scope.groups()).allMatch(JdCategoryGroupOptionVo::isEditable);
|
||||
assertThat(scope.canRead(20L)).isTrue();
|
||||
assertThat(scope.canWrite(20L)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 公司超管_本公司全部组可读可写() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
|
||||
when(shopManageGroupMapper.selectList(any())).thenReturn(List.of(
|
||||
group(10L, COMPANY_ID, "A组"), group(11L, COMPANY_ID, "B组")));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.platformSuperAdmin()).isFalse();
|
||||
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
|
||||
assertThat(scope.writableGroupIds()).containsExactly(10L, 11L);
|
||||
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
|
||||
.containsExactly("A组", "B组");
|
||||
// 公司超管的公司维只用来取组,不随 scope 下发公司字段给前端(label 里已拼好)。
|
||||
verify(companyMapper, never()).selectBatchIds(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 组长_自己带的组可写_自己所属组的组长带的分组只读() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
|
||||
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "自己的组")));
|
||||
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
|
||||
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(11L, COMPANY_ID, "上司的组")));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
|
||||
assertThat(scope.writableGroupIds()).containsExactly(10L);
|
||||
assertThat(scope.canRead(11L)).isTrue();
|
||||
assertThat(scope.canWrite(11L)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 普通号_可见同组长但零可写() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
|
||||
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
|
||||
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
|
||||
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.visibleGroupIds()).containsExactly(10L);
|
||||
assertThat(scope.writableGroupIds()).isEmpty();
|
||||
assertThat(scope.groups()).singleElement()
|
||||
.satisfies(option -> assertThat(option.isEditable()).isFalse());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 不属于任何分组的账号_空作用域不报错() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
|
||||
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
|
||||
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.visibleGroupIds()).isEmpty();
|
||||
assertThat(scope.defaultGroupId()).isNull();
|
||||
assertThat(scope.groups()).isEmpty();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 入参收敛
|
||||
|
||||
@Test
|
||||
void 读侧_缺省取默认分组且不可见组403() {
|
||||
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(), List.of(10L, 11L));
|
||||
|
||||
assertThat(service.readGroupOrNull(scope, null)).isEqualTo(10L);
|
||||
assertThat(service.readGroupOrNull(scope, 11L)).isEqualTo(11L);
|
||||
assertThatThrownBy(() -> service.readGroupOrNull(scope, 20L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("无权查看该分组的分类");
|
||||
// 空作用域:页面照常可用(商品全平台公共),分类列全空,不打 403。
|
||||
assertThat(service.readGroupOrNull(JdCategoryScopeService.JdCategoryScope.empty(), null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 写侧_无可写组拒绝_缺省收敛到当前分组() {
|
||||
JdCategoryScopeService.JdCategoryScope readOnly = scope(List.of(10L), List.of(), List.of(10L));
|
||||
assertThatThrownBy(() -> service.requireWritableGroup(readOnly, null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("你还没有可管理的数据权限分组");
|
||||
|
||||
// 两个可写组 + 没带 ownerGroupId ⇒ 落到「当前分组」(下拉默认第一项=组名序首个)。
|
||||
JdCategoryScopeService.JdCategoryScope twoGroups = scope(List.of(10L, 11L), List.of(10L, 11L),
|
||||
List.of(10L, 11L));
|
||||
when(shopManageGroupMapper.selectById(10L)).thenReturn(group(10L, COMPANY_ID, "A组"));
|
||||
assertThat(service.requireWritableGroup(twoGroups, null).getId()).isEqualTo(10L);
|
||||
// 明确选另一个也照办。
|
||||
when(shopManageGroupMapper.selectById(11L)).thenReturn(group(11L, COMPANY_ID, "B组"));
|
||||
assertThat(service.requireWritableGroup(twoGroups, 11L).getId()).isEqualTo(11L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 写侧_当前分组不可写且没指定时要求先选组() {
|
||||
// 可见组的第一项(默认分组 10)是只读的上司组,可写的是 11/12 两个 ⇒ 不带 ownerGroupId 不能瞎猜。
|
||||
// (只有一个可写组时不用选——组长那一档直接用它,见上一条用例。)
|
||||
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L, 12L), List.of(11L, 12L),
|
||||
List.of(10L, 11L, 12L));
|
||||
assertThatThrownBy(() -> service.requireWritableGroup(scope, null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择要管理的分组");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 写侧_不可写组与组行不存在分别拒绝() {
|
||||
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(10L),
|
||||
List.of(10L, 11L));
|
||||
assertThatThrownBy(() -> service.requireWritableGroup(scope, 11L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("仅该分组的管理员可以修改它的分类");
|
||||
|
||||
// 作用域认为可写但组行已被删:明确拒绝(不静默落 0 号组)。
|
||||
when(shopManageGroupMapper.selectById(10L)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.requireWritableGroup(scope, 10L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("分组不存在");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 用户端 / scope 回执
|
||||
|
||||
@Test
|
||||
void 按uid解析_账号不存在按空作用域() {
|
||||
when(adminUserMapper.selectById(USER_ID)).thenReturn(null);
|
||||
|
||||
assertThat(service.resolveByUserId(USER_ID).visibleGroupIds()).isEmpty();
|
||||
assertThat(service.resolveByUserId(null).visibleGroupIds()).isEmpty();
|
||||
assertThat(service.resolveByUserId(0L).visibleGroupIds()).isEmpty();
|
||||
// null/0 直接回空,只有正数 uid 才查账号表。
|
||||
verify(adminUserMapper, org.mockito.Mockito.times(1)).selectById(anyLong());
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台超管 + 全部组的归属公司都是 NULL(V153 留下的存量形状:组长账号已不存在)。
|
||||
*
|
||||
* <p>2026-11-16 22:00 线上实录:这种数据的整页 500——{@code companyNames()} 在「一个公司 id
|
||||
* 都取不到」时返回 {@code Map.of()},`Map.of().get(null)` 抛 NullPointerException,
|
||||
* 列表/分类/scope 三个端点同时挂。判据:不炸、组名不加前缀、也不去查公司表。</p>
|
||||
*/
|
||||
@Test
|
||||
void 平台超管_组归属公司全为NULL时不炸且组名不带前缀() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
|
||||
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
|
||||
groupWithoutCompany(10L, "A组"), groupWithoutCompany(11L, "B组")));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
|
||||
assertThat(scope.writableGroupIds()).containsExactly(10L, 11L);
|
||||
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
|
||||
.containsExactly("A组", "B组");
|
||||
verify(companyMapper, never()).selectBatchIds(any());
|
||||
}
|
||||
|
||||
/** 部分组没归属公司(NULL)、部分有:有归属的带公司前缀,没归属的只显示组名。 */
|
||||
@Test
|
||||
void 平台超管_组归属公司部分为NULL时只给有归属的加前缀() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
|
||||
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
|
||||
group(10L, 1L, "A组"), groupWithoutCompany(11L, "B组")));
|
||||
CompanyEntity company = new CompanyEntity();
|
||||
company.setId(1L);
|
||||
company.setCompanyName("甲公司");
|
||||
when(companyMapper.selectBatchIds(any())).thenReturn(List.of(company));
|
||||
|
||||
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
|
||||
|
||||
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
|
||||
.containsExactly("甲公司 / A组", "B组");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scope回执_带平台超管标记与每组可写标记() {
|
||||
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
|
||||
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
|
||||
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
|
||||
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
|
||||
|
||||
JdCategoryScopeVo vo = service.scopeVo(operator);
|
||||
|
||||
assertThat(vo.isPlatformSuperAdmin()).isFalse();
|
||||
assertThat(vo.getDefaultGroupId()).isEqualTo(10L);
|
||||
assertThat(vo.getGroups()).singleElement().satisfies(option -> {
|
||||
assertThat(option.getId()).isEqualTo(10L);
|
||||
assertThat(option.getName()).isEqualTo("A组");
|
||||
assertThat(option.isEditable()).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
private static AdminUserEntity user(long id, long companyId) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setCompanyId(companyId);
|
||||
return user;
|
||||
}
|
||||
|
||||
private static ShopManageGroupEntity group(long id, long companyId, String name) {
|
||||
ShopManageGroupEntity group = new ShopManageGroupEntity();
|
||||
group.setId(id);
|
||||
group.setCompanyId(companyId);
|
||||
group.setGroupName(name);
|
||||
return group;
|
||||
}
|
||||
|
||||
/** 归属公司为 NULL 的组(V153 口径:组长账号已不存在,归属无从追溯)。 */
|
||||
private static ShopManageGroupEntity groupWithoutCompany(long id, String name) {
|
||||
ShopManageGroupEntity group = new ShopManageGroupEntity();
|
||||
group.setId(id);
|
||||
group.setGroupName(name);
|
||||
return group;
|
||||
}
|
||||
|
||||
/** 直接构作用域(跳过解析):可见组 / 可写组 / 下拉项三者按入参给。 */
|
||||
private static JdCategoryScopeService.JdCategoryScope scope(List<Long> visible, List<Long> writable,
|
||||
List<Long> optionGroupIds) {
|
||||
List<JdCategoryGroupOptionVo> options = optionGroupIds.stream()
|
||||
.map(id -> new JdCategoryGroupOptionVo(id, "组" + id, "组" + id, writable.contains(id)))
|
||||
.toList();
|
||||
return new JdCategoryScopeService.JdCategoryScope(false, COMPANY_ID, visible, writable, options);
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
|
||||
@@ -50,6 +51,8 @@ class JdCollectBoardServiceTest {
|
||||
private JdProductImageMapper jdProductImageMapper;
|
||||
@Mock
|
||||
private JdProductSkuMapper jdProductSkuMapper;
|
||||
@Mock
|
||||
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
@Spy
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -73,6 +76,8 @@ class JdCollectBoardServiceTest {
|
||||
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class);
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity.class);
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity.class);
|
||||
}
|
||||
|
||||
private FileTaskEntity task(long id, long userId, String status) {
|
||||
@@ -171,6 +176,7 @@ class JdCollectBoardServiceTest {
|
||||
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务不存在");
|
||||
verify(jdProductGroupAssignMapper, never()).delete(any());
|
||||
verify(jdProductMapper, never()).delete(any());
|
||||
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
|
||||
}
|
||||
@@ -187,7 +193,8 @@ class JdCollectBoardServiceTest {
|
||||
|
||||
service.deleteTask(88L, 7L);
|
||||
|
||||
// sku/image 子行 → 主行 → scope → 任务行,五次删除一次不落
|
||||
// 归类归属(V203)→ sku/image 子行 → 主行 → scope → 任务行,六次删除一次不落
|
||||
verify(jdProductGroupAssignMapper, times(1)).delete(any());
|
||||
verify(jdProductSkuMapper, times(1)).delete(any());
|
||||
verify(jdProductImageMapper, times(1)).delete(any());
|
||||
verify(jdProductMapper, times(1)).delete(any());
|
||||
|
||||
+61
@@ -162,4 +162,65 @@ class JdCollectTaskServiceTest {
|
||||
assertThat(stored.getCategoryPaths())
|
||||
.as("全空白类目归 null=全店采集(既有行为,不因新参数收紧)").isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 店内分类双键归一化后落requestJson() throws Exception {
|
||||
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
|
||||
invocation.getArgument(0, FileTaskEntity.class).setId(33893L);
|
||||
return 1;
|
||||
});
|
||||
JdCollectTaskCreateRequest request = validRequest();
|
||||
// 2026-11-16 店内分类双键(label + value/id):与类目同一归一化出口(trim/去空/保序去重)。
|
||||
request.setShopCategoryNames(new java.util.ArrayList<>(java.util.Arrays.asList(
|
||||
" 工作制服 ", "拉丁舞服", "工作制服", " ")));
|
||||
request.setShopCategoryIds(new java.util.ArrayList<>(java.util.Arrays.asList(
|
||||
" 1024347567 ", "1024347572", "1024347567")));
|
||||
|
||||
service.createTask(request, "device-abc");
|
||||
|
||||
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
|
||||
verify(fileTaskMapper).insert(taskCaptor.capture());
|
||||
JdCollectTaskCreateRequest stored = new ObjectMapper().readValue(
|
||||
taskCaptor.getValue().getRequestJson(), JdCollectTaskCreateRequest.class);
|
||||
assertThat(stored.getShopCategoryNames())
|
||||
.as("request_json 里的店内分类名=归一化后的值(铁律 27a 同源)")
|
||||
.containsExactly("工作制服", "拉丁舞服");
|
||||
assertThat(stored.getShopCategoryIds()).containsExactly("1024347567", "1024347572");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 店内分类全空白视为不过滤() throws Exception {
|
||||
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
|
||||
invocation.getArgument(0, FileTaskEntity.class).setId(33894L);
|
||||
return 1;
|
||||
});
|
||||
JdCollectTaskCreateRequest request = validRequest();
|
||||
request.setShopCategoryNames(new java.util.ArrayList<>(java.util.Arrays.asList(" ", "")));
|
||||
request.setShopCategoryIds(new java.util.ArrayList<>(java.util.Arrays.asList(" ", "")));
|
||||
|
||||
service.createTask(request, "device-abc");
|
||||
|
||||
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
|
||||
verify(fileTaskMapper).insert(taskCaptor.capture());
|
||||
JdCollectTaskCreateRequest stored = new ObjectMapper().readValue(
|
||||
taskCaptor.getValue().getRequestJson(), JdCollectTaskCreateRequest.class);
|
||||
assertThat(stored.getShopCategoryNames())
|
||||
.as("全空白分类归 null=全店采集(与类目同口径)").isNull();
|
||||
assertThat(stored.getShopCategoryIds()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 超过店内分类上限建单被拒并点名() {
|
||||
JdCollectTaskCreateRequest request = validRequest();
|
||||
java.util.List<String> tooMany = new java.util.ArrayList<>();
|
||||
for (int i = 0; i < 51; i++) {
|
||||
tooMany.add("分类" + i);
|
||||
}
|
||||
request.setShopCategoryNames(tooMany);
|
||||
|
||||
assertThatThrownBy(() -> service.createTask(request, null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("采集分类最多选 50 个");
|
||||
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
|
||||
}
|
||||
}
|
||||
|
||||
+146
-64
@@ -4,9 +4,10 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
|
||||
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.JdProductGroupAssignEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
|
||||
@@ -20,7 +21,6 @@ import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -33,78 +33,105 @@ import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
|
||||
* v1.4 Phase 5(R4/AC-8)+V203:京东商品自定义分类业务规则(按数据权限分组归属)。
|
||||
*
|
||||
* <p>判据(2026-11-15 用户定案「分组和亚马逊功能一样」=全平台一份,V200 退键后的服务形状):
|
||||
* 全局重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行(事务两步,AC-8,
|
||||
* 且脱组谓词不带 company_id)、越界 id 操作按不存在拒绝、company_id 列读写两侧都不再引用
|
||||
* (新行不带公司,DB DEFAULT 0 兜底)、productCount 读侧现算统计(分组下拉展示用)。</p>
|
||||
* <p>判据(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类」):
|
||||
* 分类归属一个数据权限分组({@code owner_group_id}),<b>同组内</b>重名拒绝(409,不同组可同名)、
|
||||
* 删除只解挂归属行({@code biz_jd_product_group_assign})不删商品、商品数按归属表
|
||||
* {@code category_id} 现算、越界 id 按不存在拒绝。<b>作用域(谁能读/写哪个组)不在本类</b>——
|
||||
* 那是 {@code JdCategoryScopeServiceTest} 的事,本类只钉「按给定组取/写」的语义。</p>
|
||||
*/
|
||||
class JdProductGroupServiceTest {
|
||||
|
||||
private static final long GROUP_ID = 10L;
|
||||
private static final long COMPANY_ID = 5L;
|
||||
|
||||
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
|
||||
private final JdProductMapper productMapper = mock(JdProductMapper.class);
|
||||
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
|
||||
private final JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
|
||||
private final JdProductGroupService service = new JdProductGroupService(groupMapper, assignMapper);
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
|
||||
// 探针要读 Lambda wrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
|
||||
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
|
||||
}
|
||||
|
||||
// ===================== 新建 =====================
|
||||
|
||||
@Test
|
||||
void 新建重名拒绝且不落库() {
|
||||
void 新建同组重名拒绝且不落库() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.create(" 秋冬款 ", 2));
|
||||
() -> service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2));
|
||||
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
|
||||
assertTrue(ex.getMessage().contains("同名分类"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500(2026-11-15 起界面措辞「分类」)");
|
||||
assertTrue(ex.getMessage().contains("本组已存在同名分类"),
|
||||
"重名必须给可读文案并点名「本组」,不拿 DB 唯一键异常撞 500");
|
||||
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);
|
||||
group.setId(9L);
|
||||
JdProductGroupEntity category = invocation.getArgument(0);
|
||||
category.setId(9L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
Long id = service.create(" 秋冬款 ", 2);
|
||||
Long id = service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2);
|
||||
|
||||
assertEquals(9L, id);
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
JdProductGroupEntity saved = captor.getValue();
|
||||
assertNull(saved.getCompanyId(), "公共库新行不带公司(实体字段不赋值,DB DEFAULT 0=平台公共)");
|
||||
assertEquals(GROUP_ID, saved.getOwnerGroupId(), "必须落在当前数据权限分组上(跨组不可见)");
|
||||
assertEquals(COMPANY_ID, saved.getCompanyId(), "公司随组落(唯一键 uk_company_owner_name 的左段)");
|
||||
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
|
||||
assertEquals(2, saved.getSortOrder());
|
||||
|
||||
// 重名查询必须是「同公司 + 同组」口径:不同公司/不同组可同名。
|
||||
ArgumentCaptor<Wrapper<JdProductGroupEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(groupMapper).selectCount(wrapperCaptor.capture());
|
||||
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
|
||||
assertEquals(GROUP_ID, ((Number) whereEq.get("owner_group_id")).longValue(),
|
||||
"重名查询必须钉 owner_group_id(同组才冲突)");
|
||||
assertEquals(COMPANY_ID, ((Number) whereEq.get("company_id")).longValue(),
|
||||
"重名查询必须钉 company_id(唯一键左段)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建无分组直接拒绝() {
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.create(null, COMPANY_ID, "秋冬款", null));
|
||||
assertEquals(400, ex.getCode());
|
||||
assertTrue(ex.getMessage().contains("请先选择分组再新建分类"));
|
||||
verifyNoInteractions(groupMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建空名直接拒绝() {
|
||||
BusinessException blankName = assertThrows(BusinessException.class,
|
||||
() -> service.create(" ", null));
|
||||
() -> service.create(GROUP_ID, COMPANY_ID, " ", null));
|
||||
assertEquals(400, blankName.getCode());
|
||||
verifyNoInteractions(groupMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建排序缺省归零() {
|
||||
void 新建排序缺省归零且公司缺省按0() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.create("默认排序", null);
|
||||
service.create(GROUP_ID, null, "默认排序", null);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
assertEquals(0, captor.getValue().getSortOrder(), "sortOrder 缺省 0(下拉按 sort_order, id 升序)");
|
||||
assertEquals(0L, captor.getValue().getCompanyId(),
|
||||
"公司为空按 0 落(唯一键非空列;组本身取自可写组,正常不会为空)");
|
||||
}
|
||||
|
||||
// ===================== 改名 =====================
|
||||
@@ -121,7 +148,7 @@ class JdProductGroupServiceTest {
|
||||
|
||||
@Test
|
||||
void 改名重名拒绝且不落库() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
@@ -132,7 +159,7 @@ class JdProductGroupServiceTest {
|
||||
|
||||
@Test
|
||||
void 改名成功带归一名与排序() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, " 新名 ", 7);
|
||||
@@ -141,11 +168,13 @@ class JdProductGroupServiceTest {
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
assertEquals("新名", captor.getValue().getName());
|
||||
assertEquals(7, captor.getValue().getSortOrder());
|
||||
assertEquals(GROUP_ID, captor.getValue().getOwnerGroupId(),
|
||||
"改名不得把归属组改走(沿用原行的 owner_group_id 查重名)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名排序不传保持原值() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
|
||||
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, "只改名", null);
|
||||
@@ -155,27 +184,21 @@ class JdProductGroupServiceTest {
|
||||
assertEquals(3, captor.getValue().getSortOrder(), "sortOrder 不传=保持原值(改名不改排序)");
|
||||
}
|
||||
|
||||
// ===================== 删除(AC-8 事务两步) =====================
|
||||
// ===================== 删除(只解挂归属,不删商品) =====================
|
||||
|
||||
@Test
|
||||
void 删除先把商品组置NULL再删分组行() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "秋冬款"));
|
||||
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
|
||||
void 删除只解挂归属行再删分类行_商品一个不删() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "秋冬款"));
|
||||
when(assignMapper.delete(any())).thenReturn(3);
|
||||
|
||||
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(商品保留,脱组即「未分组」)。
|
||||
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。
|
||||
assertEquals(3, detached, "返回实际解挂的商品归属行数(前端拿它做反馈,不猜)");
|
||||
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(assignMapper).delete(wrapperCaptor.capture());
|
||||
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
|
||||
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
|
||||
assertTrue(!whereEq.containsKey("company_id"),
|
||||
"分组公共化后脱组谓词不得再带 company_id:实得 " + whereEq);
|
||||
assertEquals(1L, ((Number) whereEq.get("category_id")).longValue(),
|
||||
"解挂谓词必须限定该分类(商品保留在公共库,回到未分类)");
|
||||
verify(groupMapper).deleteById(1L);
|
||||
}
|
||||
|
||||
@@ -184,56 +207,115 @@ class JdProductGroupServiceTest {
|
||||
when(groupMapper.selectById(1L)).thenReturn(null);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.delete(1L));
|
||||
verifyNoInteractions(productMapper);
|
||||
verifyNoInteractions(assignMapper);
|
||||
verify(groupMapper, never()).deleteById(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除分组不存在直接拒绝() {
|
||||
when(groupMapper.selectById(404L)).thenReturn(null);
|
||||
|
||||
void 删除越界id直接拒绝() {
|
||||
assertThrows(BusinessException.class, () -> service.delete(404L));
|
||||
verifyNoInteractions(productMapper);
|
||||
verifyNoInteractions(assignMapper);
|
||||
}
|
||||
|
||||
// ===================== 列表(productCount 统计) =====================
|
||||
// ===================== 列表(按组取 + productCount 统计) =====================
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void 列表全平台一份不带公司谓词且productCount现算() {
|
||||
JdProductGroupEntity first = groupEntity(2L, "晚出厂");
|
||||
void 列表按当前分组取且productCount按归属表现算() {
|
||||
JdProductGroupEntity first = categoryEntity(2L, "晚出厂");
|
||||
first.setSortOrder(0);
|
||||
JdProductGroupEntity second = groupEntity(1L, "早出厂");
|
||||
JdProductGroupEntity second = categoryEntity(1L, "早出厂");
|
||||
second.setSortOrder(1);
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
|
||||
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
|
||||
when(assignMapper.selectCount(any())).thenReturn(12L, 0L);
|
||||
|
||||
List<JdProductGroupVo> items = service.list();
|
||||
List<JdProductGroupVo> items = service.list(GROUP_ID);
|
||||
|
||||
assertEquals(2, items.size());
|
||||
assertEquals("晚出厂", items.get(0).getName(), "selectList 的排序由 wrapper 决定,服务不重排");
|
||||
assertEquals(12L, items.get(0).getProductCount(), "productCount 用 JdProductMapper selectCount 现算");
|
||||
assertEquals(0L, items.get(1).getProductCount(), "空组也是 0,不是 null(下拉展示口径)");
|
||||
assertEquals(GROUP_ID, items.get(0).getOwnerGroupId(), "归属组随行下发(前端按它锁分组)");
|
||||
assertEquals(12L, items.get(0).getProductCount(),
|
||||
"productCount 按归属表 category_id 现算(同一商品可在别组另归一类,这里只数本分类)");
|
||||
assertEquals(0L, items.get(1).getProductCount(), "空分类也是 0,不是 null(下拉展示口径)");
|
||||
assertEquals(1, items.get(1).getSortOrder());
|
||||
verify(productMapper, times(2)).selectCount(any());
|
||||
verify(assignMapper, times(2)).selectCount(any());
|
||||
assertNotNull(items.get(0).getCreatedAt());
|
||||
|
||||
// 公共库:列表 wrapper 不带 company_id 谓词(历史行的 company_id 只是溯源标记)。
|
||||
// 按组取:wrapper 钉 owner_group_id(.in 谓词,取值从参数表取证),且不再按 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());
|
||||
assertEquals(List.of(GROUP_ID), inParams(captor.getValue()),
|
||||
"列表必须只取当前分组的分类(跨组不可见)");
|
||||
assertTrue(!captor.getValue().getSqlSegment().toLowerCase().contains("company"),
|
||||
"列表不再按公司过滤(同一公司的组已由 owner_group_id 区分):实得 "
|
||||
+ captor.getValue().getSqlSegment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 列表无分组上下文回空且不查库() {
|
||||
assertTrue(service.list(null).isEmpty(), "没有当前分组=空列表(页面分类列全空,不打 403)");
|
||||
assertTrue(service.list(0L).isEmpty());
|
||||
verifyNoInteractions(groupMapper);
|
||||
verifyNoInteractions(assignMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 多组并集取分类_空清单不生成IN查询() {
|
||||
JdProductGroupEntity row = categoryEntity(2L, "晚出厂");
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of(row));
|
||||
when(assignMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
List<JdProductGroupVo> items = service.listForGroups(java.util.Arrays.asList(10L, 11L, 10L, null, 0L));
|
||||
|
||||
assertEquals(1, items.size(), "用户端一个普通号可能同时在多个组里:并集只读展示");
|
||||
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(groupMapper).selectList(captor.capture());
|
||||
String segment = captor.getValue().getSqlSegment();
|
||||
assertTrue(segment.toUpperCase().contains(" IN "), "多组走 IN 谓词:实得 " + segment);
|
||||
// 参数表是 HashMap,序不可依赖:按集合语义断言。
|
||||
java.util.List<Object> inValues = inParams(captor.getValue());
|
||||
assertEquals(2, inValues.size(), "10/11/10/null/0 ⇒ 去重去脏后只剩两个有效组:实得 " + inValues);
|
||||
assertTrue(inValues.containsAll(List.of(10L, 11L)), "只留 10、11:实得 " + inValues);
|
||||
|
||||
assertTrue(service.listForGroups(List.of()).isEmpty(), "空清单直接回空,不生成 IN ()");
|
||||
assertTrue(service.listForGroups(null).isEmpty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
private static JdProductGroupEntity groupEntity(long id, String name) {
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(id);
|
||||
group.setCompanyId(5L);
|
||||
group.setName(name);
|
||||
group.setSortOrder(3);
|
||||
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
|
||||
return group;
|
||||
private static JdProductGroupEntity categoryEntity(long id, String name) {
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setId(id);
|
||||
category.setOwnerGroupId(GROUP_ID);
|
||||
category.setCompanyId(COMPANY_ID);
|
||||
category.setName(name);
|
||||
category.setSortOrder(3);
|
||||
category.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
|
||||
return category;
|
||||
}
|
||||
|
||||
/**
|
||||
* wrapper 参数表里的字面值(IN 集合按元素展开成多个 paramNameValuePairs 条目;
|
||||
* 若某版 MP 把整个集合塞一个条目,这里按集合展开——两种形状都认)。
|
||||
*
|
||||
* <p>MP 的 SQL 段与参数表都是惰性构建:必须先触发 {@code getSqlSegment()},否则
|
||||
* {@code paramNameValuePairs} 还是空表(原测试里那条「先触发再读」的注释同源)。</p>
|
||||
*/
|
||||
private static List<Object> inParams(Wrapper<?> wrapper) {
|
||||
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
|
||||
abstractWrapper.getSqlSegment();
|
||||
}
|
||||
List<Object> out = new java.util.ArrayList<>();
|
||||
for (Object value : UpdateWrapperProbe.paramNameValuePairs(wrapper).values()) {
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
if (value instanceof java.util.Collection<?> collection) {
|
||||
out.addAll(collection);
|
||||
} else {
|
||||
out.add(value);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
+118
-68
@@ -6,12 +6,14 @@ 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.JdProductGroupAssignMapper;
|
||||
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.JdProductGroupAssignEntity;
|
||||
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;
|
||||
@@ -64,6 +66,8 @@ class JdProductUpdateServiceTest {
|
||||
@Mock
|
||||
private JdProductGroupMapper jdProductGroupMapper;
|
||||
@Mock
|
||||
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
@Mock
|
||||
private OssStorageService ossStorageService;
|
||||
|
||||
private JdProductUpdateService service;
|
||||
@@ -76,12 +80,13 @@ class JdProductUpdateServiceTest {
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductSkuEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductImageEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new JdProductUpdateService(jdProductMapper, jdProductSkuMapper,
|
||||
jdProductImageMapper, jdProductGroupMapper, ossStorageService);
|
||||
jdProductImageMapper, jdProductGroupMapper, jdProductGroupAssignMapper, ossStorageService);
|
||||
ReflectionTestUtils.setField(service, "bucket", "jd-products");
|
||||
ReflectionTestUtils.setField(service, "keyPrefix", "jd-products/");
|
||||
}
|
||||
@@ -104,7 +109,6 @@ class JdProductUpdateServiceTest {
|
||||
JdProductUpdateRequest body = new JdProductUpdateRequest();
|
||||
body.setTitle(" 新标题 ");
|
||||
body.setBrand(" 新品牌 ");
|
||||
body.setGroupId(null);
|
||||
return body;
|
||||
}
|
||||
|
||||
@@ -160,78 +164,133 @@ class JdProductUpdateServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分组必须存在_公共组无公司维度() {
|
||||
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));
|
||||
}
|
||||
service.update(PRODUCT_ID, mainFieldsOnly());
|
||||
|
||||
// ---------- 批量归类(店铺分类弹窗,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");
|
||||
String sqlSet = ((LambdaUpdateWrapper<JdProductEntity>) captor.getValue()).getSqlSet();
|
||||
// V203:分类不在编辑面(归属在 biz_jd_product_group_assign 的按组行上,
|
||||
// 商品行的 group_id 列已停用),编辑保存一个字都不许往那一列写。
|
||||
assertThat(sqlSet).doesNotContain("group_id");
|
||||
// 也不再去查分类表(旧「分组必须存在」校验已随分类移出编辑面撤掉)。
|
||||
verify(jdProductGroupMapper, never()).selectById(any());
|
||||
}
|
||||
|
||||
// ---------- 批量归类(店铺分类弹窗;V203 起按组写归属表,不置锁) ----------
|
||||
|
||||
/** 归属表插入行的夹具校验:一次 insert 一行 (product_id, owner_group_id)。 */
|
||||
private java.util.List<JdProductGroupAssignEntity> capturedAssignInserts() {
|
||||
ArgumentCaptor<JdProductGroupAssignEntity> captor =
|
||||
ArgumentCaptor.forClass(JdProductGroupAssignEntity.class);
|
||||
verify(jdProductGroupAssignMapper, org.mockito.Mockito.atLeastOnce()).insert(captor.capture());
|
||||
return captor.getAllValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类成功_置分类并落人工编辑锁() {
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(7L);
|
||||
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
|
||||
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(3);
|
||||
void 批量归类写归属表_一组一商品一行且不置人工锁() {
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setId(7L);
|
||||
category.setOwnerGroupId(10L);
|
||||
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
|
||||
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of());
|
||||
when(jdProductGroupAssignMapper.insert(any(JdProductGroupAssignEntity.class))).thenReturn(1);
|
||||
|
||||
// 入参含重复 id:去重后 1/2/3 三行
|
||||
int updated = service.assignGroup(List.of(1L, 1L, 2L, 3L), 7L);
|
||||
// 入参含重复 id:去重后 1/2 两行
|
||||
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L, 1L, 2L), 7L, 99L);
|
||||
|
||||
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);
|
||||
assertThat(written).isEqualTo(2);
|
||||
java.util.List<JdProductGroupAssignEntity> inserted = capturedAssignInserts();
|
||||
assertThat(inserted).hasSize(2);
|
||||
assertThat(inserted.get(0).getProductId()).isEqualTo(1L);
|
||||
assertThat(inserted.get(0).getOwnerGroupId()).isEqualTo(10L);
|
||||
assertThat(inserted.get(0).getCategoryId()).isEqualTo(7L);
|
||||
assertThat(inserted.get(0).getCompanyId()).isEqualTo(COMPANY_ID);
|
||||
assertThat(inserted.get(0).getCreatedBy()).isEqualTo(99L);
|
||||
assertThat(inserted.get(1).getProductId()).isEqualTo(2L);
|
||||
// 归类不再置人工编辑锁(2026-11-16 用户拍板):商品行一个字节都不写,
|
||||
// 锁只会让共享行的价格/库存对所有组停更(分类不在商品行上,采集冲不掉它)。
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
verify(jdProductGroupAssignMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类目标分类不存在拒绝且零写() {
|
||||
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
|
||||
void 批量归类换组改归属行不新增() {
|
||||
JdProductGroupEntity category = new JdProductGroupEntity();
|
||||
category.setId(7L);
|
||||
category.setOwnerGroupId(10L);
|
||||
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
|
||||
JdProductGroupAssignEntity existing = new JdProductGroupAssignEntity();
|
||||
existing.setProductId(1L);
|
||||
existing.setOwnerGroupId(10L);
|
||||
existing.setCategoryId(3L);
|
||||
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of(existing));
|
||||
when(jdProductGroupAssignMapper.update(any(), any())).thenReturn(1);
|
||||
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(1L, 2L), 404L))
|
||||
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L), 7L, 99L);
|
||||
|
||||
assertThat(written).isEqualTo(1);
|
||||
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductGroupAssignMapper).update(isNull(), captor.capture());
|
||||
assertThat(com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(captor.getValue()))
|
||||
.containsEntry("category_id", 7L);
|
||||
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类目标分类不存在或跨组拒绝且零写() {
|
||||
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L, 2L), 404L, 99L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("分类不存在");
|
||||
|
||||
// 分类存在于别的组(ownerGroupId=20)⇒ 403,不许跨组归类。
|
||||
JdProductGroupEntity foreign = new JdProductGroupEntity();
|
||||
foreign.setId(8L);
|
||||
foreign.setOwnerGroupId(20L);
|
||||
when(jdProductGroupMapper.selectById(8L)).thenReturn(foreign);
|
||||
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L), 8L, 99L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("该分类不属于当前分组");
|
||||
|
||||
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
|
||||
verify(jdProductGroupAssignMapper, never()).update(any(), any());
|
||||
verify(jdProductGroupAssignMapper, never()).delete(any());
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类空清单与超上限可读拒绝() {
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(), null))
|
||||
void 移出分类_删本组归属行且商品行不动() {
|
||||
when(jdProductGroupAssignMapper.delete(any())).thenReturn(2);
|
||||
|
||||
int removed = service.assignGroup(10L, COMPANY_ID, List.of(5L, 6L), null, 99L);
|
||||
|
||||
assertThat(removed).isEqualTo(2);
|
||||
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(jdProductGroupAssignMapper).delete(captor.capture());
|
||||
var whereEq = com.nanri.aiimage.testutil.UpdateWrapperProbe.whereEq(captor.getValue());
|
||||
assertThat(((Number) whereEq.get("owner_group_id")).longValue()).isEqualTo(10L);
|
||||
// 只删本组、只删勾选行:IN 集合按元素落参数表(MP 逐个 formatParam),取值逐一取证。
|
||||
assertThat(captor.getValue().getSqlSegment().toUpperCase()).contains(" IN ");
|
||||
java.util.List<Object> params = new java.util.ArrayList<>(
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe
|
||||
.paramNameValuePairs(captor.getValue()).values());
|
||||
assertThat(params).contains(10L).contains(5L).contains(6L);
|
||||
// 移出分类不查分类表、不写商品行。
|
||||
verify(jdProductGroupMapper, never()).selectById(any());
|
||||
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
|
||||
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量归类空清单超上限与无当前分组可读拒绝() {
|
||||
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(), null, 1L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择要归类的商品");
|
||||
assertThatThrownBy(() -> service.assignGroup(List.of(0L, -1L), null))
|
||||
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(0L, -1L), null, 1L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择要归类的商品");
|
||||
|
||||
@@ -239,28 +298,19 @@ class JdProductUpdateServiceTest {
|
||||
for (long i = 1; i <= 201; i++) {
|
||||
tooMany.add(i);
|
||||
}
|
||||
assertThatThrownBy(() -> service.assignGroup(tooMany, null))
|
||||
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, tooMany, null, 1L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("单次最多归类 200");
|
||||
|
||||
// 没有「当前分组」就没有归属可写:403 点名先选组(V203)。
|
||||
assertThatThrownBy(() -> service.assignGroup(null, COMPANY_ID, List.of(1L), null, 1L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("请先选择分组再归类");
|
||||
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
|
||||
verify(jdProductGroupAssignMapper, never()).delete(any());
|
||||
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();
|
||||
|
||||
+34
-3
@@ -71,10 +71,16 @@ class JdTaskPullSpiImplTest {
|
||||
assertThat(data.get("categoryPaths"))
|
||||
.as("建单没选类目时派空列表(键集稳定,客户端读空=不过滤全店采集)")
|
||||
.isEqualTo(List.of());
|
||||
// 客户端 process_task 只读这五键:多键无害,缺键即空跑——所以逐键钉
|
||||
assertThat(data.get("shopCategoryNames"))
|
||||
.as("建单没选店内分类时派空列表(2026-11-16 双键契约,同 categoryPaths 口径)")
|
||||
.isEqualTo(List.of());
|
||||
assertThat(data.get("shopCategoryIds")).isEqualTo(List.of());
|
||||
// 客户端 process_task 只读这七键:多键无害,缺键即空跑——所以逐键钉
|
||||
assertThat(data.keySet())
|
||||
.as("data 键集与客户端 jd_base.process_task 读取契约同键(taskId/shopName/listTabs/maxProducts/categoryPaths)")
|
||||
.containsExactlyInAnyOrder("taskId", "shopName", "listTabs", "maxProducts", "categoryPaths");
|
||||
.as("data 键集与客户端 jd_base.process_task 读取契约同键(taskId/shopName/listTabs/"
|
||||
+ "maxProducts/categoryPaths/shopCategoryNames/shopCategoryIds)")
|
||||
.containsExactlyInAnyOrder("taskId", "shopName", "listTabs", "maxProducts",
|
||||
"categoryPaths", "shopCategoryNames", "shopCategoryIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,6 +103,31 @@ class JdTaskPullSpiImplTest {
|
||||
.isEqualTo(List.of("女装", "男装"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 店内分类双键随载荷透传客户端() throws Exception {
|
||||
FileTaskEntity withShopCategories = task();
|
||||
withShopCategories.setRequestJson("{\"userId\":7,\"shopName\":\"测试旗舰店\","
|
||||
+ "\"listTabs\":[\"ONSALE\"],\"maxProducts\":0,"
|
||||
+ "\"shopCategoryNames\":[\"工作制服\",\"拉丁舞服\"],"
|
||||
+ "\"shopCategoryIds\":[\"1024347567\",\"1024347572\"]}");
|
||||
when(collectTaskService.readCreateRequest(any(FileTaskEntity.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
FileTaskEntity t = invocation.getArgument(0);
|
||||
return new ObjectMapper().readValue(t.getRequestJson(), JdCollectTaskCreateRequest.class);
|
||||
});
|
||||
|
||||
Map<String, Object> payload = spi.buildQueuePayload(withShopCategories);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) payload.get("data");
|
||||
assertThat(data.get("shopCategoryNames"))
|
||||
.as("店内分类 label 原样透传(客户端按行 shopCategorys/shopCategoryPath 等值过滤)")
|
||||
.isEqualTo(List.of("工作制服", "拉丁舞服"));
|
||||
assertThat(data.get("shopCategoryIds"))
|
||||
.as("店内分类 id 原样透传(行级填充形状未取证,双键同发任一命中即命中)")
|
||||
.isEqualTo(List.of("1024347567", "1024347572"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 建单载荷缺失按SPI语义返回异常路径而非空载荷() {
|
||||
FileTaskEntity broken = task();
|
||||
|
||||
+4
-3
@@ -15,7 +15,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
* 密钥「货源」维度:LLM 渠道(龙抬头/贞贞)与代理供应商(青果/极客)的归一化、默认值、主机与模型映射。
|
||||
*
|
||||
* <p>口径来源(2026-10-29 用户拍板):新建默认龙抬头 + 青果;存量由迁移 V180 回填贞贞/极客;
|
||||
* 龙抬头的模型 id 统一用 {@code gm-3.5-flash-lite}(2026-11-09 由 3.1 切到 3.5,贞贞不变)。</p>
|
||||
* 龙抬头的模型 id 统一用 {@code gm-3.1-flash-lite}(2026-11-16 用户拍板从 3.5 改回 3.1 lite;
|
||||
* 2026-11-09 曾切 3.5;贞贞不变)。</p>
|
||||
*/
|
||||
class LlmChannelProxyProviderTest {
|
||||
|
||||
@@ -39,7 +40,7 @@ class LlmChannelProxyProviderTest {
|
||||
void longtaitouUsesItsOwnModelId() {
|
||||
// 贞贞的模型名在龙抬头那边不存在,切渠道必须换 id,否则 model_not_found
|
||||
assertThat(LlmChannel.LONGTAITOU.modelFor("gemini-3.1-flash-lite-preview-thinking-medium"))
|
||||
.isEqualTo("gm-3.5-flash-lite");
|
||||
.isEqualTo("gm-3.1-flash-lite");
|
||||
// 贞贞保持配置里的模型名原样
|
||||
assertThat(LlmChannel.T8STAR.modelFor("gemini-3.1-flash-lite-preview-thinking-medium"))
|
||||
.isEqualTo("gemini-3.1-flash-lite-preview-thinking-medium");
|
||||
@@ -48,7 +49,7 @@ class LlmChannelProxyProviderTest {
|
||||
@Test
|
||||
void modelMappingFollowsRequestHost() {
|
||||
assertThat(LlmChannel.modelForHost("https://longtaitou.token6688.com", "any-model"))
|
||||
.isEqualTo("gm-3.5-flash-lite");
|
||||
.isEqualTo("gm-3.1-flash-lite");
|
||||
assertThat(LlmChannel.modelForHost("https://ai.t8star.org", "any-model")).isEqualTo("any-model");
|
||||
assertThat(LlmChannel.modelForHost(null, "any-model")).isEqualTo("any-model");
|
||||
assertThat(LlmChannel.modelForHost("https://unknown.example.com", "any-model")).isEqualTo("any-model");
|
||||
|
||||
@@ -1,458 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 建单页「采集类目」多选级联面板(2026-11-16 客户口径「京麦类目是这些 我们后台的现在
|
||||
* 的不对」+「你直接爬」→ 树数据换成京麦授权类目真树,见 ./jd-category-tree.ts 头注释
|
||||
* 的取证来源与边界;面板形状与后管筛选面板同款,两处差异:① **多选**——末级行点击=
|
||||
* toggle(方点 checkbox),「全部类目」行=清空,触发框显示「已选 N 个类目」;
|
||||
* ② 触发框配色按本页暗色主题适配(面板本体仍是白底弹层)。
|
||||
*
|
||||
* 交互(京麦真机同款,2026-11-16 面板逐级点开取证):面板按点亮路径动态出栏——第一栏
|
||||
* 一级(3 个)、后续栏=点亮节点的 children(最深 4 栏);**非末级行点击=下钻**、
|
||||
* **末级行(children 空)点击=toggle 勾选**(随建单走 categoryPaths → 客户端按
|
||||
* categoryPath 等值过滤)。搜索框搜树内全部末级(行 title 带全路径);树外命中(已
|
||||
* 落库但京麦类目体系变更后的历史名)从 options 兜底段选。面板是 fixed 浮层(窄触发框
|
||||
* 不撑文档横向滚动),打开瞬间按触发框实际位置定位。零依赖自绘,无 element 依赖。 */
|
||||
import { computed, ref } from 'vue'
|
||||
import {
|
||||
jdCategoryChildren,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
type JdCategoryNode,
|
||||
} from './jd-category-tree.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 已落库末级类目全集(/api/jd-collect/categories 现算)——只作**树外兜底**(搜索无
|
||||
* 树内命中时列出「已落库类目(树外历史)」段),不再默认铺第三栏。 */
|
||||
options?: { name: string; productCount: number }[]
|
||||
/** 当前选中的末级类目名列表;空数组 = 全部类目(全店采集)。 */
|
||||
modelValue: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'change', value: string[]): void }>()
|
||||
|
||||
const open = ref(false)
|
||||
/** 已下钻的节点名路径(非末级行点击推进)。 */
|
||||
const activePath = ref<string[]>([])
|
||||
const searchText = ref('')
|
||||
/** 触发框元素:打开面板瞬间按它的实际位置给浮层定位(fixed 不撑文档横向滚动)。 */
|
||||
const triggerRef = ref<HTMLElement | null>(null)
|
||||
/** 面板浮层定位(fixed 的 top/left,px 字符串)。 */
|
||||
const panelPos = ref({ top: '0px', left: '0px' })
|
||||
|
||||
const roots = jdCategoryRoots()
|
||||
/** 树内全部末级名集合(判定 options 哪些是「树外历史」)。 */
|
||||
const treeLeafNames = new Set(
|
||||
jdCategorySearchLeaves('').map((leaf) => leaf.name),
|
||||
)
|
||||
|
||||
/** 面板各栏内容:第 0 栏一级,第 i+1 栏=点亮路径前 i+1 个的 children(栏数随路径动态 1~4)。 */
|
||||
const columns = computed<JdCategoryNode[][]>(() => {
|
||||
const cols: JdCategoryNode[][] = [roots]
|
||||
for (let i = 0; i < activePath.value.length; i++) {
|
||||
const children = jdCategoryChildren(activePath.value.slice(0, i + 1))
|
||||
if (!children.length) break
|
||||
cols.push(children)
|
||||
}
|
||||
return cols
|
||||
})
|
||||
|
||||
/** 搜索激活=搜索词非空:面板切换成扁平末级结果列表。 */
|
||||
const searching = computed(() => searchText.value.trim().length > 0)
|
||||
|
||||
/** 树内命中末级(名称或路径段命中)。 */
|
||||
const searchLeaves = computed(() =>
|
||||
searching.value ? jdCategorySearchLeaves(searchText.value) : [],
|
||||
)
|
||||
|
||||
/** 树外兜底:options 里不在树名集的行按搜索词过滤(历史行仍可勾选过滤)。 */
|
||||
const fallbackOptions = computed(() => {
|
||||
if (!searching.value) return []
|
||||
const keyword = searchText.value.trim().toLowerCase()
|
||||
return (props.options ?? [])
|
||||
.filter((option) => !treeLeafNames.has(option.name))
|
||||
.filter((option) => option.name.toLowerCase().includes(keyword))
|
||||
})
|
||||
|
||||
/** 触发框文案:空=全店采集;一个=类目名;多个=已选 N 个类目(title 列全名)。 */
|
||||
const triggerText = computed(() => {
|
||||
const picked = props.modelValue
|
||||
if (!picked.length) return '全部类目(全店采集)'
|
||||
if (picked.length === 1) return picked[0]
|
||||
return `已选 ${picked.length} 个类目`
|
||||
})
|
||||
|
||||
function toggle(): void {
|
||||
if (open.value) {
|
||||
close()
|
||||
return
|
||||
}
|
||||
activePath.value = []
|
||||
searchText.value = ''
|
||||
// 面板是 fixed 浮层:打开瞬间按触发框实际位置定位;测试环境无真实布局时 rect 全 0,
|
||||
// top/left 落在视口原点即可。
|
||||
const rect = triggerRef.value?.getBoundingClientRect()
|
||||
if (rect) {
|
||||
const width = Math.min(652, Math.max(320, window.innerWidth - 24))
|
||||
panelPos.value = {
|
||||
top: `${Math.round(rect.bottom + 4)}px`,
|
||||
left: `${Math.round(Math.max(8, Math.min(rect.left, window.innerWidth - width - 8)))}px`,
|
||||
}
|
||||
}
|
||||
open.value = true
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
open.value = false
|
||||
activePath.value = []
|
||||
}
|
||||
|
||||
/** 非末级行点击=下钻;末级行点击=toggle 勾选(多选,不收面板,连续勾多个)。 */
|
||||
function pick(node: JdCategoryNode, depth: number): void {
|
||||
if (node.children && node.children.length) {
|
||||
activePath.value = [...activePath.value.slice(0, depth), node.name]
|
||||
return
|
||||
}
|
||||
toggleLeaf(node.name)
|
||||
}
|
||||
|
||||
function clearAll(): void {
|
||||
emit('change', [])
|
||||
close()
|
||||
}
|
||||
|
||||
/** 叶子勾选/取消(同名跨支叶子是同一个过滤值,选中态共享)。 */
|
||||
function toggleLeaf(name: string): void {
|
||||
const picked = props.modelValue.includes(name)
|
||||
? props.modelValue.filter((item) => item !== name)
|
||||
: [...props.modelValue, name]
|
||||
emit('change', picked)
|
||||
}
|
||||
|
||||
/** 搜索结果行点击=toggle 勾选(不收面板,连续勾多个)。 */
|
||||
function pickName(name: string): void {
|
||||
toggleLeaf(name)
|
||||
}
|
||||
|
||||
function clear(): void {
|
||||
emit('change', [])
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="cat-cascader">
|
||||
<button
|
||||
ref="triggerRef"
|
||||
class="cat-trigger"
|
||||
type="button"
|
||||
:class="{ open, filled: modelValue.length > 0 }"
|
||||
:title="modelValue.length ? modelValue.join('、') : '不选类目=全店采集'"
|
||||
@click="toggle"
|
||||
>
|
||||
<span class="cat-trigger-text">{{ triggerText }}</span>
|
||||
<span
|
||||
v-if="modelValue.length"
|
||||
class="cat-clear"
|
||||
role="button"
|
||||
aria-label="清除类目"
|
||||
@click.stop="clear"
|
||||
>×</span>
|
||||
<span class="cat-chevron" aria-hidden="true"></span>
|
||||
</button>
|
||||
|
||||
<!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 -->
|
||||
<div v-if="open" class="cat-mask" @click="close"></div>
|
||||
<div v-if="open" class="cat-panel" :style="panelPos">
|
||||
<!-- 搜索态:树内末级命中+树外兜底段(扁平列表,行 title 带全路径)。 -->
|
||||
<template v-if="searching">
|
||||
<div class="cat-col cat-col-search">
|
||||
<template v-if="searchLeaves.length || fallbackOptions.length">
|
||||
<div
|
||||
v-for="leaf in searchLeaves"
|
||||
:key="`tree-${leaf.path.join('/')}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue.includes(leaf.name) }"
|
||||
:title="leaf.path.join(' > ')"
|
||||
@click="pickName(leaf.name)"
|
||||
>
|
||||
<span
|
||||
class="cat-dot cat-dot-check"
|
||||
:class="{ on: modelValue.includes(leaf.name) }"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
<span class="cat-name">{{ leaf.name }}</span>
|
||||
<span class="cat-path">{{ leaf.path.slice(0, -1).join(' › ') }}</span>
|
||||
</div>
|
||||
<div v-if="fallbackOptions.length" class="cat-seg">已落库类目(树外历史)</div>
|
||||
<div
|
||||
v-for="option in fallbackOptions"
|
||||
:key="`db-${option.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue.includes(option.name) }"
|
||||
:title="option.name"
|
||||
@click="pickName(option.name)"
|
||||
>
|
||||
<span
|
||||
class="cat-dot cat-dot-check"
|
||||
:class="{ on: modelValue.includes(option.name) }"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
<span class="cat-name">{{ option.name }}</span>
|
||||
<span class="cat-count">{{ option.productCount }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="cat-empty">未找到类目</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 下钻态:逐级动态栏;首栏顶部搜索框+「全部类目」行=清空。 -->
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="(col, depth) in columns"
|
||||
:key="depth"
|
||||
class="cat-col"
|
||||
>
|
||||
<div v-if="depth === 0" class="cat-search-row">
|
||||
<input
|
||||
v-model="searchText"
|
||||
type="text"
|
||||
class="cat-search"
|
||||
placeholder="搜索类目"
|
||||
@click.stop
|
||||
/>
|
||||
</div>
|
||||
<div v-if="depth === 0" class="cat-row cat-row-all" :class="{ active: !modelValue.length }" @click="clearAll">
|
||||
<span class="cat-dot" :class="{ on: !modelValue.length }" aria-hidden="true"></span>
|
||||
<span class="cat-name">全部类目(全店采集)</span>
|
||||
</div>
|
||||
<div
|
||||
v-for="node in col"
|
||||
:key="`${depth}-${node.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: activePath[depth] === node.name || (depth === 0 && modelValue.includes(node.name)) }"
|
||||
:title="node.name"
|
||||
@click="pick(node, depth)"
|
||||
>
|
||||
<span
|
||||
v-if="!node.children || !node.children.length"
|
||||
class="cat-dot cat-dot-check"
|
||||
:class="{ on: modelValue.includes(node.name) }"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
<span v-else class="cat-dot" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ node.name }}</span>
|
||||
<span v-if="node.children && node.children.length" class="cat-arrow" aria-hidden="true">›</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.cat-cascader {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 触发框按建单页暗色主题适配(后管筛选框是浅色页,这里页面底 #1a1f2e)。 */
|
||||
.cat-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 8px;
|
||||
background: #232b3d;
|
||||
color: #f5f8fc;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: border-color 160ms ease, background 160ms ease;
|
||||
}
|
||||
.cat-trigger:hover {
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.cat-trigger.open {
|
||||
background: #2b3447;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.cat-trigger-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.cat-trigger:not(.filled) .cat-trigger-text {
|
||||
color: #a0acbe;
|
||||
}
|
||||
.cat-clear {
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
background: #3e4a62;
|
||||
color: #c8d2e2;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
}
|
||||
.cat-clear:hover {
|
||||
background: #52627e;
|
||||
color: #f5f8fc;
|
||||
}
|
||||
/* 下拉箭头:CSS 三角(京麦同款向下 chevron,展开翻向上)。 */
|
||||
.cat-chevron {
|
||||
flex: none;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 5px solid transparent;
|
||||
border-right: 5px solid transparent;
|
||||
border-top: 6px solid #7b8a99;
|
||||
transition: transform 160ms ease;
|
||||
}
|
||||
.cat-trigger.open .cat-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.cat-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2550;
|
||||
}
|
||||
.cat-panel {
|
||||
/* fixed 浮层:位置由 toggle() 按触发框实际位置写 :style(top/left)。
|
||||
* 宽度随栏数自适应(200/栏 + 搜索态 300),cap 652 不撑文档横向滚动条。 */
|
||||
position: fixed;
|
||||
max-width: min(860px, calc(100vw - 16px));
|
||||
z-index: 2560;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 16px 44px rgba(0, 0, 0, 0.35);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cat-col {
|
||||
width: 200px;
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
padding: 6px 0;
|
||||
border-right: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-col:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.cat-col-search {
|
||||
width: 300px;
|
||||
}
|
||||
/* 行=京麦同款:圆点 + 名称 + 右箭头;hover 浅蓝底。 */
|
||||
.cat-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13.5px;
|
||||
color: #24384d;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cat-row:hover,
|
||||
.cat-row.active {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.cat-row.active {
|
||||
color: #2f5d8b;
|
||||
font-weight: 550;
|
||||
}
|
||||
.cat-dot {
|
||||
flex: none;
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 1px solid #c0ccda;
|
||||
border-radius: 50%;
|
||||
background: #ffffff;
|
||||
}
|
||||
/* 导航圆点(非末级)=纯形状;末级=方点 checkbox。 */
|
||||
.cat-dot-check {
|
||||
border-radius: 3px;
|
||||
}
|
||||
.cat-dot-check.on {
|
||||
background: #3b82c4;
|
||||
position: relative;
|
||||
}
|
||||
.cat-dot-check.on::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 3px;
|
||||
top: 0.5px;
|
||||
width: 5px;
|
||||
height: 9px;
|
||||
border: solid #ffffff;
|
||||
border-width: 0 2px 2px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.cat-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 搜索态行尾的路径灰字(同名跨支时定位用)。 */
|
||||
.cat-path {
|
||||
flex: none;
|
||||
max-width: 110px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #9fb0c0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cat-arrow {
|
||||
flex: none;
|
||||
color: #9fb0c0;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
}
|
||||
.cat-count {
|
||||
flex: none;
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cat-seg {
|
||||
padding: 8px 12px 4px;
|
||||
color: #8293a5;
|
||||
font-size: 11.5px;
|
||||
border-top: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-search-row {
|
||||
padding: 4px 8px 6px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-search {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.cat-search:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.cat-empty {
|
||||
padding: 16px 12px;
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -7,14 +7,10 @@ import {
|
||||
activateJdCollectTask,
|
||||
createJdCollectTask,
|
||||
deleteJdCollectTask,
|
||||
fetchJdCollectCategories,
|
||||
fetchJdCollectDashboard,
|
||||
fetchJdCollectGroups,
|
||||
fetchJdCollectHistory,
|
||||
fetchJdCollectTaskProgressBatch,
|
||||
interruptJdCollectTask,
|
||||
type JdCollectCategoryVo,
|
||||
type JdCollectGroupVo,
|
||||
type JdCollectHistoryItemVo,
|
||||
type JdListTab,
|
||||
} from '@/shared/api/types/modules/jd-collect'
|
||||
@@ -25,14 +21,16 @@ import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { useLiveTaskBoard } from '@/shared/composables/useLiveTaskBoard'
|
||||
import NotificationBell from '@/shared/components/NotificationBell.vue'
|
||||
import JdCategoryCascader from './JdCategoryCascader.vue'
|
||||
import { JD_SHOP_CATEGORY_SNAPSHOT, type JdShopCategory } from './jd-shop-category.ts'
|
||||
|
||||
/** 京东「获取店铺数据」(v1.5):一键建单 → 推送本机客户端 → 右侧任务面板实时进度。
|
||||
*
|
||||
* 四个真源与四条边界(照 v1.4 已落地的采集契约与外观专利任务面板骨架,不另造流程):
|
||||
* 1. 建单走后端 `/api/jd-collect/tasks`(通道恒 LOCAL,服务端落 PENDING);可选多选采集
|
||||
* 类目(京麦末级类目名,`categoryPaths`)——空=全店采集,选中值随建单进 request_json、
|
||||
* 随推送/兜底拉取进客户端,客户端按行 categoryPath 等值过滤(三处同键契约);
|
||||
* 分类(京麦「店内分类」快照,`shopCategoryNames`/`shopCategoryIds` 双键)——空=全店
|
||||
* 采集,选中值随建单进 request_json、随推送/兜底拉取进客户端,客户端按行
|
||||
* shopCategorys/shopCategoryPath/groupId 等值过滤、任一键命中即命中(三处同键契约;
|
||||
* 2026-11-16 类目级联按客户口径「类目不需要只要分类」下线,categoryPaths 仅历史行兼容);
|
||||
* 2. 建单成功把 `jd-shop-collect-run` 载荷推进本机客户端队列——只建单不推送会让任务
|
||||
* 卡在 PENDING 等兜底拉取(v1.4 Phase 6.1 P0-1 的教训);推送失败不回滚建单;
|
||||
* 3. 进度只读服务端:任务状态 + 合并写游标里的 itemsReceived/total。`total` 缺失时
|
||||
@@ -40,8 +38,9 @@ import JdCategoryCascader from './JdCategoryCascader.vue'
|
||||
* 4. 失败/中断任务「重试/继续」走通用原位复位(铁律 26,保留已收分片与断点游标),
|
||||
* 复位后页面重新激活并推队列——同一份输入不再多出好几行结果。
|
||||
*
|
||||
* 2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」:左面板加只读「店铺分类」
|
||||
* 块(GET /api/jd-collect/groups,管理员在后管京东数据库维护);「商品上架」落地后消费同一端点。
|
||||
* 2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」落点改为本多选块:
|
||||
* 客户的参照系是京麦后台的「店内分类」(getShopCategoryList 快照),不再是后管平台分组
|
||||
* (平台分组接口从本页下线,分组数据面归京东数据库与商品上架)。
|
||||
*/
|
||||
|
||||
/** 页面不再让用户填店铺名:店铺名称由客户端从京麦后台读,建单先按此占位记录。 */
|
||||
@@ -56,46 +55,31 @@ const submitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const successMessage = ref('')
|
||||
|
||||
// ---- 采集类目(可选,多选;空=全店采集)----
|
||||
/** 选项集=公共库已落库 category_path 全集(/api/jd-collect/categories 现算)。
|
||||
* 拉取失败不阻塞建单(不选类目=全店采集),只把空态文案打出来。 */
|
||||
const categoryOptions = ref<JdCollectCategoryVo[]>([])
|
||||
const categoryOptionsLoaded = ref(false)
|
||||
const selectedCategories = ref<string[]>([])
|
||||
// ---- 采集分类(可选,多选;空=全店采集)----
|
||||
/** 选项集=京麦「店内分类」快照(getShopCategoryList,2026-11-16 真机取证 9 个;
|
||||
* 京麦侧改分类后按取证路重抓,见 jd-shop-category.ts 头注释——快照不会自动过期告警)。 */
|
||||
const shopCategoryOptions = JD_SHOP_CATEGORY_SNAPSHOT
|
||||
const selectedShopCategories = ref<JdShopCategory[]>([])
|
||||
|
||||
async function loadCategoryOptions() {
|
||||
if (categoryOptionsLoaded.value) return
|
||||
try {
|
||||
categoryOptions.value = await fetchJdCollectCategories()
|
||||
} catch (err) {
|
||||
// 选项是锦上添花:拉不到就保持空态文案,不把「全店采集」这条主路堵死。
|
||||
// 静默 catch 棘轮口径:console + ElMessage(界面上看得见),不算静默。
|
||||
console.error('[jd-collect] 类目选项拉取失败', err)
|
||||
ElMessage.warning('类目选项加载失败,本次可先不选类目(全店采集)')
|
||||
} finally {
|
||||
categoryOptionsLoaded.value = true
|
||||
}
|
||||
function toggleShopCategory(category: JdShopCategory) {
|
||||
const hit = selectedShopCategories.value.find((item) => item.value === category.value)
|
||||
selectedShopCategories.value = hit
|
||||
? selectedShopCategories.value.filter((item) => item.value !== category.value)
|
||||
: [...selectedShopCategories.value, category]
|
||||
}
|
||||
|
||||
function clearShopCategories() {
|
||||
selectedShopCategories.value = []
|
||||
}
|
||||
|
||||
/** 建单/推送载荷的选中值:label 与 id 双键同发(行级填充形状未取证,任一键命中即命中)。 */
|
||||
const selectedShopCategoryNames = computed(() => selectedShopCategories.value.map((item) => item.label))
|
||||
const selectedShopCategoryIds = computed(() => selectedShopCategories.value.map((item) => item.value))
|
||||
|
||||
function uidForStorage() {
|
||||
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
|
||||
}
|
||||
|
||||
// ---- 店铺分类(管理员在后管「京东数据库」维护,本页只读展示;2026-11-16 客户口径
|
||||
// 「管理员弄了多少店铺分类 普通账户都能看到」——普通账号在「获取店铺数据」页就能看到
|
||||
// 分类全集与各组商品数。分类的增删改仍只在后管;「商品上架」落地后消费同一端点。)----
|
||||
const groupList = ref<JdCollectGroupVo[]>([])
|
||||
|
||||
async function loadGroups() {
|
||||
try {
|
||||
groupList.value = await fetchJdCollectGroups()
|
||||
} catch (err) {
|
||||
// 分类只是展示项:拉不到就保持空态文案,不把采集主路堵死(同 loadCategoryOptions 口径)。
|
||||
console.error('[jd-collect] 店铺分类拉取失败', err)
|
||||
ElMessage.warning('店铺分类加载失败,不影响采集')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 实时任务面板(与外观专利共用 useLiveTaskBoard 骨架;京东无结果文件,无下载层)----
|
||||
const board = useLiveTaskBoard<JdCollectHistoryItemVo>({
|
||||
scope: 'jd-collect',
|
||||
@@ -267,7 +251,7 @@ async function retryTaskRecord(item: JdCollectHistoryItemVo | null | undefined)
|
||||
if (!activateError) {
|
||||
await pushToClientQueue(taskId, item?.shopName || DEFAULT_SHOP_NAME,
|
||||
(item?.listTabs?.length ? item.listTabs : DEFAULT_TABS) as JdListTab[],
|
||||
item?.categoryPaths ?? [])
|
||||
item?.shopCategoryNames ?? [], item?.shopCategoryIds ?? [])
|
||||
}
|
||||
board.addPollingTask(taskId)
|
||||
await refreshBoard()
|
||||
@@ -306,13 +290,14 @@ async function activateTask(id: number): Promise<string | null> {
|
||||
}
|
||||
|
||||
/** 建单成功后推送本机队列;返回 null 表示环境无队列能力(浏览器预览),返回 string 表示失败原因。
|
||||
* categoryPaths 是建单时选的采集类目(重试/继续从历史行同源带回)——推送载荷与建单请求体、
|
||||
* 客户端兜底拉取(request_json)三处同键,缺一处客户端就按全店采集跑。 */
|
||||
* shopCategoryNames/Ids 是建单时选的京麦店内分类(重试/继续从历史行同源带回)——推送载荷
|
||||
* 与建单请求体、客户端兜底拉取(request_json)三处同键,缺一处客户端就按全店采集跑。 */
|
||||
async function pushToClientQueue(
|
||||
id: number,
|
||||
shop: string,
|
||||
tabs: JdListTab[],
|
||||
categoryPaths: string[] = [],
|
||||
shopCategoryNames: string[] = [],
|
||||
shopCategoryIds: string[] = [],
|
||||
): Promise<string | null> {
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.enqueue_json) {
|
||||
@@ -321,7 +306,7 @@ async function pushToClientQueue(
|
||||
const payload = {
|
||||
type: 'jd-shop-collect-run',
|
||||
ts: Date.now(),
|
||||
data: { taskId: id, shopName: shop, listTabs: tabs, maxProducts: 0, categoryPaths },
|
||||
data: { taskId: id, shopName: shop, listTabs: tabs, maxProducts: 0, shopCategoryNames, shopCategoryIds },
|
||||
}
|
||||
const pushResult = await api.enqueue_json(payload)
|
||||
if (pushResult?.success) {
|
||||
@@ -343,9 +328,10 @@ async function startCollect() {
|
||||
submitting.value = true
|
||||
const shop = DEFAULT_SHOP_NAME
|
||||
const tabs = DEFAULT_TABS
|
||||
const categories = [...selectedCategories.value]
|
||||
const shopNames = [...selectedShopCategoryNames.value]
|
||||
const shopIds = [...selectedShopCategoryIds.value]
|
||||
try {
|
||||
const vo = await createJdCollectTask(shop, tabs, 0, categories)
|
||||
const vo = await createJdCollectTask(shop, tabs, 0, [], shopNames, shopIds)
|
||||
board.addPollingTask(vo.taskId)
|
||||
let pushNote = ''
|
||||
const activateError = await activateTask(vo.taskId)
|
||||
@@ -355,7 +341,7 @@ async function startCollect() {
|
||||
pushNote = activateError
|
||||
} else {
|
||||
try {
|
||||
const pushError = await pushToClientQueue(vo.taskId, shop, tabs, categories)
|
||||
const pushError = await pushToClientQueue(vo.taskId, shop, tabs, shopNames, shopIds)
|
||||
if (pushError) pushNote = pushError
|
||||
} catch (pushErr) {
|
||||
// 推送自身异常不回滚建单:任务可由服务端兜底拉取认领。
|
||||
@@ -366,8 +352,8 @@ async function startCollect() {
|
||||
if (pushNote) {
|
||||
errorMessage.value = pushNote
|
||||
} else {
|
||||
successMessage.value = categories.length
|
||||
? `任务已创建(只采 ${categories.length} 个类目)并推送给本机客户端,进度显示在右侧任务区`
|
||||
successMessage.value = shopNames.length
|
||||
? `任务已创建(只采 ${shopNames.length} 个分类)并推送给本机客户端,进度显示在右侧任务区`
|
||||
: '任务已创建并推送给本机客户端,进度显示在右侧任务区'
|
||||
}
|
||||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||||
@@ -385,8 +371,6 @@ onMounted(async () => {
|
||||
await Promise.all([
|
||||
board.loadDashboard().catch(() => undefined),
|
||||
board.loadHistory().catch(() => undefined),
|
||||
loadCategoryOptions(),
|
||||
loadGroups(),
|
||||
])
|
||||
board.seedRunningTasksFromHistory()
|
||||
board.seedPendingFileTasksFromHistory()
|
||||
@@ -428,34 +412,29 @@ onUnmounted(() => {
|
||||
<main class="jd-body">
|
||||
<aside class="left-panel">
|
||||
<div class="category-block">
|
||||
<span class="category-label">采集类目(可选,多选)</span>
|
||||
<JdCategoryCascader
|
||||
v-model="selectedCategories"
|
||||
:options="categoryOptions"
|
||||
@change="selectedCategories = $event"
|
||||
/>
|
||||
<span class="category-label">采集分类(可选,多选)</span>
|
||||
<ul class="shop-cat-list">
|
||||
<li v-for="category in shopCategoryOptions" :key="category.value">
|
||||
<label class="shop-cat-item" :title="`${category.label}(id ${category.value})`">
|
||||
<input type="checkbox" class="shop-cat-check"
|
||||
:checked="selectedShopCategories.some((item) => item.value === category.value)"
|
||||
@change="toggleShopCategory(category)" />
|
||||
<span class="shop-cat-name">{{ category.label }}</span>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="category-hint">
|
||||
{{ selectedCategories.length
|
||||
? `只采选中 ${selectedCategories.length} 个类目的商品;清空恢复全店采集。`
|
||||
: '不选=全店采集。类目树与京麦后台一致(按店铺授权类目逐级下钻到末级)。' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="category-block">
|
||||
<span class="category-label">自定义分类</span>
|
||||
<p v-if="groupList.length" class="group-chips">
|
||||
<span v-for="group in groupList" :key="group.id" class="group-chip"
|
||||
:title="`${group.name}:${group.productCount} 个商品`">
|
||||
{{ group.name }}({{ group.productCount }})
|
||||
</span>
|
||||
</p>
|
||||
<p v-else class="category-hint">
|
||||
后台还没建自定义分类;管理员可在「京东数据库」的类目面板中新建自定义分类,建好后会显示在这里。
|
||||
{{ selectedShopCategories.length
|
||||
? `只采选中 ${selectedShopCategories.length} 个分类的商品;`
|
||||
: '不选=全店采集。' }}
|
||||
分类是京麦后台「店内分类」(2026-11-16 快照);商品要先在京麦挂上分类才会被选中。
|
||||
<button v-if="selectedShopCategories.length" class="shop-cat-clear" type="button"
|
||||
@click="clearShopCategories">清空</button>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button class="collect-btn" type="button" :disabled="isRunning" @click="startCollect">
|
||||
{{ isRunning ? '获取中…' : (selectedCategories.length ? `获取选中类目数据` : '一键获取店铺数据') }}
|
||||
{{ isRunning ? '获取中…' : (selectedShopCategories.length ? `获取选中分类数据` : '一键获取店铺数据') }}
|
||||
</button>
|
||||
|
||||
<p class="collect-hint">
|
||||
@@ -523,7 +502,9 @@ onUnmounted(() => {
|
||||
border-bottom: 1px solid #3e4a62;
|
||||
}
|
||||
|
||||
.home-back {
|
||||
/* 首页返回与工具台返回按钮同款样式,合并声明 */
|
||||
.home-back,
|
||||
.tool-head__back {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -538,7 +519,8 @@ onUnmounted(() => {
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.home-back:hover {
|
||||
.home-back:hover,
|
||||
.tool-head__back:hover {
|
||||
background: #2b3447;
|
||||
color: #f5f8fc;
|
||||
}
|
||||
@@ -608,26 +590,6 @@ onUnmounted(() => {
|
||||
background: #1a1f2e;
|
||||
}
|
||||
|
||||
.tool-head__back {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 14px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 6px;
|
||||
color: #c8d2e2;
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tool-head__back:hover {
|
||||
background: #2b3447;
|
||||
color: #f5f8fc;
|
||||
}
|
||||
|
||||
.tool-head__title {
|
||||
flex-shrink: 0;
|
||||
color: #f5f8fc;
|
||||
@@ -705,26 +667,59 @@ onUnmounted(() => {
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 店铺分类只读块(2026-11-16 客户口径):label 复用 category-label,chips 深色卡片同色系。 */
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
/* 采集分类多选块(2026-11-16 京麦店内分类快照):label 复用 category-label,
|
||||
* 列表项按暗色主题复选行样式(快照是纯前端数据,无加载失败分支)。 */
|
||||
.shop-cat-list {
|
||||
margin: 8px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
.shop-cat-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 10px;
|
||||
gap: 8px;
|
||||
padding: 5px 10px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 6px;
|
||||
background: #232b3d;
|
||||
color: #c8d2e2;
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.shop-cat-item:hover {
|
||||
border-color: #5a6b8c;
|
||||
}
|
||||
|
||||
.shop-cat-check {
|
||||
accent-color: #e1251b;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-cat-name {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.shop-cat-clear {
|
||||
margin-left: 6px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: #6ea8ff;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.shop-cat-clear:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.collect-btn:hover:not(:disabled) {
|
||||
filter: brightness(1.1);
|
||||
transform: translateY(-1px);
|
||||
@@ -762,7 +757,6 @@ onUnmounted(() => {
|
||||
|
||||
/* 行内动作按钮:与外观专利 Tab 同色系(中断琥珀/重试绿/删除红),钉死 12px 字号 */
|
||||
.btn-delete, .btn-retry, .btn-interrupt { border: none; cursor: pointer; border-radius: 6px; font-size: 12px; }
|
||||
.download { padding: 6px 10px; color: #c8d2e2; background: rgba(52, 152, 219, .18); }
|
||||
.btn-delete { padding: 6px 10px; color: #ff8f8f; background: rgba(231, 76, 60, .12); }
|
||||
.btn-retry { padding: 6px 10px; color: #7fd1a0; background: rgba(39, 174, 96, .14); }
|
||||
.btn-interrupt { padding: 6px 10px; color: #f0b35e; background: rgba(240, 179, 94, .12); }
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,41 @@
|
||||
/** 京麦「店内分类」快照——建单页采集分类多选的选项集(2026-11-16 真机取证)。
|
||||
*
|
||||
* 数据来源(唯一正本):京麦商品列表页首屏自发的
|
||||
* `dsm.product.manage.ShopCategoryReadViewService.getShopCategoryList`
|
||||
* (响应 `data.shopCategoryList[]` = `{parent:"0", orderNo, children:[], label, value}`;
|
||||
* 2026-11-16 本机 Chrome 19899/chrome_data_jd profile 真机抓包,原始响应与取证脚本存
|
||||
* D:/tmp/jd_group_probe/)。label=店内分类名,value=分类 id;扁平单层(parent 恒 0、
|
||||
* children 恒空),本店 9 个,按 orderNo 排序。
|
||||
*
|
||||
* 口径与边界(先说清,防止后人当它错改):
|
||||
* - 这是**京麦侧**的店内分类(商家在京麦后台维护),不是后管「京东数据库」的平台分组
|
||||
* (那是 biz_jd_product_group,两套概念,2026-11-16 客户口径「选京麦的内部分类去采集」
|
||||
* 指的是这一套);
|
||||
* - 行级过滤键:列表行 `shopCategorys/shopCategoryPath/groupId`(取证见客户端
|
||||
* `app_client/amazon/jd/jd_base.py::_filter_by_shop_category`);**填充形状未取证**
|
||||
* (450 行采样全空——采样店铺还没给商品挂分类),所以建单把 label 与 value 双键同发
|
||||
* (shopCategoryNames + shopCategoryIds),客户端任一键命中即命中;
|
||||
* - ⚠ 采样店铺(花屿巷)当前 0/450 商品挂了店内分类:选任何分类采集都是 0 行命中
|
||||
* (客户端零命中时打 WARNING 校准点),商家在京麦把商品挂上分类后本功能才真正生效;
|
||||
* - 京麦侧改分类(增删改名)后按原取证路重抓替换本数据(快照不会自动过期告警)。
|
||||
*
|
||||
* 纯数据,node --test 直测。后管若要用,复制同形文件(两前端没有共享包)。 */
|
||||
|
||||
/** 店内分类项:label=分类名(行级等值词),value=分类 id(取证留档 + id 形状对冲)。 */
|
||||
export interface JdShopCategory {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/** 京麦店内分类快照(2026-11-16 取证,getShopCategoryList 按 orderNo 原序)。 */
|
||||
export const JD_SHOP_CATEGORY_SNAPSHOT: JdShopCategory[] = [
|
||||
{ label: '工作制服', value: '1024347567' },
|
||||
{ label: '礼服/演出服', value: '1024347568' },
|
||||
{ label: '女士演出服/民族服装', value: '1024347569' },
|
||||
{ label: '特殊服装', value: '1024347570' },
|
||||
{ label: '睡衣/家居服', value: '1024347571' },
|
||||
{ label: '拉丁舞服', value: '1024347572' },
|
||||
{ label: '服饰配件', value: '1024347573' },
|
||||
{ label: '男士卫衣', value: '1024347574' },
|
||||
{ label: '其他', value: '1024347575' },
|
||||
]
|
||||
@@ -70,6 +70,10 @@ export interface JdCollectCategoryVo {
|
||||
/**
|
||||
* 类目选项集(建单页多选面板第三栏)。公共库口径:从未采集过的店铺/新类目不在集内
|
||||
* (先全店采集一次即有),拉取失败不阻塞建单——不选类目=全店采集。
|
||||
*
|
||||
* @deprecated 2026-11-16 建单页类目级联下线(客户口径「类目不需要只要分类」,换京麦
|
||||
* 店内分类多选,见 pages/jd/jd-shop-category.ts);本函数与 /api/jd-collect/categories
|
||||
* 端点保留给数据面(endpoints 冻结快照仍登记),建单页不再消费。
|
||||
*/
|
||||
export function fetchJdCollectCategories() {
|
||||
return unwrapJavaResponse(
|
||||
@@ -82,7 +86,8 @@ export function fetchJdCollectCategories() {
|
||||
|
||||
/** 店铺分类行(GET /api/jd-collect/groups:管理员在后管京东数据库建的分类+组内商品数)。
|
||||
* 2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」:只读展示,分类的
|
||||
* 增删改仍只在后管;分组 2026-11-15 起全平台一份,无公司维度。 */
|
||||
* 增删改仍只在后管。⚠ V203(2026-11-16「不同组不能看到跨组的分类」):该端点已按登录用户
|
||||
* <b>可见的数据权限分组</b>收窄——只回自己组的分类(不再全平台一份),不属于任何组的账号拿到空列表。 */
|
||||
export interface JdCollectGroupVo {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -90,7 +95,12 @@ export interface JdCollectGroupVo {
|
||||
productCount: number;
|
||||
}
|
||||
|
||||
/** 店铺分类只读列表(「获取店铺数据」页展示;「商品上架」落地后消费同一端点)。 */
|
||||
/**
|
||||
* 店铺分类只读列表(「获取店铺数据」页展示;「商品上架」落地后消费同一端点)。
|
||||
*
|
||||
* @deprecated 2026-11-16 建单页的平台分组只读 chips 下线(同上:采集范围换京麦店内分类,
|
||||
* 平台分组与采集范围是两套概念);分组数据面归后管京东数据库与商品上架,本函数保留。
|
||||
*/
|
||||
export function fetchJdCollectGroups() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdCollectGroupVo[]>>(
|
||||
@@ -105,6 +115,8 @@ export function createJdCollectTask(
|
||||
listTabs: JdListTab[],
|
||||
maxProducts = 0,
|
||||
categoryPaths: string[] = [],
|
||||
shopCategoryNames: string[] = [],
|
||||
shopCategoryIds: string[] = [],
|
||||
) {
|
||||
return unwrapJavaResponse(post<JavaApiResponse<JdCollectTaskVo>, Record<string, unknown>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.create),
|
||||
@@ -118,9 +130,13 @@ export function createJdCollectTask(
|
||||
shopName,
|
||||
listTabs,
|
||||
maxProducts,
|
||||
// 京麦末级类目名多选;空数组=全店采集(后端归一化后进 request_json,客户端按
|
||||
// categoryPath 等值过滤——三处同键契约见 JdTaskPullSpiImplTest / jd_base.process_task)。
|
||||
// 京麦末级类目名多选(2026-11-16 起建单页不再产生值,字段仅兼容保留);空数组=全店采集。
|
||||
categoryPaths,
|
||||
// 京麦「店内分类」多选(2026-11-16 取证后新增,getShopCategoryList 的 label/value 对):
|
||||
// label 与 id 双键同发——行级 shopCategorys 填充形状未取证,客户端任一键命中即命中。
|
||||
// 空数组=全店采集;三处同键契约见 JdTaskPullSpiImplTest / jd_base._read_shop_category_filter。
|
||||
shopCategoryNames,
|
||||
shopCategoryIds,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -153,8 +169,12 @@ export interface JdCollectHistoryItemVo {
|
||||
errorMessage?: string;
|
||||
shopName?: string;
|
||||
listTabs?: string[];
|
||||
/** 建单时选的采集类目(京麦末级类目名多选;空=全店采集)。重试/继续重建推送载荷时同源带回 */
|
||||
/** 建单时选的采集类目(京麦末级类目名多选;空=全店采集)。2026-11-16 起 UI 不再产生值,仅历史行兼容。重试/继续重建推送载荷时同源带回 */
|
||||
categoryPaths?: string[];
|
||||
/** 建单时选的京麦店内分类名(多选;空=全店采集)。重试/继续重建推送载荷时同源带回 */
|
||||
shopCategoryNames?: string[];
|
||||
/** 建单时选的京麦店内分类 id(与 shopCategoryNames 同一多选的 value 集) */
|
||||
shopCategoryIds?: string[];
|
||||
/** 已落京东数据库的商品行数 */
|
||||
rowCount?: number;
|
||||
itemsReceived?: number;
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
JD_CATEGORY_TREE,
|
||||
jdCategoryChildren,
|
||||
jdCategoryLeaves,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
} from '../src/pages/jd/jd-category-tree.ts'
|
||||
|
||||
/** 京麦授权类目真树(2026-11-16 真机取证 getVenderLicenseCategory 快照;与后管
|
||||
* admin-frontend-vue 侧同数据两份正本,改树两边同轮同步)。判据钉的是取证读数:
|
||||
* 3 个一级 / 250 个末级 / 最深 4 级 / 5 个同名跨支——改树先对取证数据(京麦面板
|
||||
* 或 getVenderLicenseCategory 重抓),不得手改数字凑测试。 */
|
||||
test('树形状=京麦授权类目真机读数:3 个一级、250 个末级、最深 4 级', () => {
|
||||
const roots = jdCategoryRoots()
|
||||
assert.deepEqual(
|
||||
roots.map((node) => node.name),
|
||||
['服饰内衣', '母婴', '运动户外'],
|
||||
'一级就 3 个(京麦面板 2026-11-16 真机:该店铺授权经营类目,不得加回京东公开全量)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
roots.map((node) => node.value),
|
||||
['1315', '1319', '1318'],
|
||||
'一级类目 id 与取证响应逐字同',
|
||||
)
|
||||
const leaves = jdCategoryLeaves()
|
||||
assert.equal(leaves.length, 250, '末级节点 250 个(取证读数)')
|
||||
const maxDepth = Math.max(...leaves.map((leaf) => leaf.path.length))
|
||||
assert.equal(maxDepth, 4, '树最深 4 级')
|
||||
})
|
||||
|
||||
test('服饰内衣二级与京麦面板逐字同源;逐级下钻到真机样本叶', () => {
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣']).map((node) => node.name),
|
||||
['服饰配件', '内衣', '女装', '男装', '定制服装/工装'],
|
||||
'服饰内衣二级 5 个(京麦面板逐字)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣', '服饰配件']).map((node) => node.name),
|
||||
['腰带/腰链', '耳罩/耳包', '领带/领结/领带夹', '男士丝巾/围巾', '女士丝巾/围巾/披肩', '鸭舌帽',
|
||||
'礼帽', '手套', '围巾/手套/帽子套装', '毛线帽', '遮阳帽', '棒球帽', '渔夫帽'],
|
||||
'服饰配件三级 13 个(京麦面板 2026-11-16 截图逐字前 6 +取证快照全量)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣', '服饰配件', '腰带/腰链']),
|
||||
[],
|
||||
'三级叶子 children 空(末级,可选中)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['不存在的一级']),
|
||||
[],
|
||||
'未知路径回落空子级(面板该栏缺省)',
|
||||
)
|
||||
})
|
||||
|
||||
test('落库末级名真机样本都在树内(category_path 等值过滤成立的前提)', () => {
|
||||
const names = new Set(jdCategoryLeaves().map((leaf) => leaf.name))
|
||||
for (const sample of ['艺考形体服', '啦啦队服', '拉丁舞服']) {
|
||||
assert.ok(names.has(sample), `真机样本「${sample}」必须是树内末级(契约 E3 口径)`)
|
||||
}
|
||||
const yikao = jdCategoryLeaves().find((leaf) => leaf.name === '艺考形体服')
|
||||
assert.ok(yikao, '艺考形体服在树内')
|
||||
assert.equal(yikao!.path.length, 3, '艺考形体服是 level 3 节点(取证读数)')
|
||||
})
|
||||
|
||||
test('同名跨支叶子如实登记:4 组重名(同名行等值过滤一起命中,B112-05 口径)', () => {
|
||||
const counts = new Map<string, number>()
|
||||
for (const leaf of jdCategoryLeaves()) {
|
||||
counts.set(leaf.name, (counts.get(leaf.name) ?? 0) + 1)
|
||||
}
|
||||
const dups = [...counts.entries()].filter(([, count]) => count > 1)
|
||||
assert.deepEqual(
|
||||
dups.map(([name]) => name).sort(),
|
||||
['唐装', '吊带/背心', '短裤', '赠品'].sort(),
|
||||
'重名集与取证读数逐字同(改树后这里红=重名集变了,须复核登记)。注:「汉服」两处节点中'
|
||||
+ '一处带四级子级是非叶(点它会下钻),不构成末级重名。',
|
||||
)
|
||||
})
|
||||
|
||||
test('搜索:按名称或路径段命中末级;空词返回全量', () => {
|
||||
assert.equal(jdCategorySearchLeaves('').length, 250, '空词=全量末级')
|
||||
const byName = jdCategorySearchLeaves('艺考')
|
||||
assert.equal(byName.length, 1)
|
||||
assert.equal(byName[0]!.name, '艺考形体服')
|
||||
const byPath = jdCategorySearchLeaves('服饰配件')
|
||||
assert.ok(byPath.length >= 12, '按路径段命中服饰配件全部末级')
|
||||
assert.ok(byPath.every((leaf) => leaf.path.includes('服饰配件')))
|
||||
assert.deepEqual(jdCategorySearchLeaves('不存在词xyz'), [])
|
||||
})
|
||||
|
||||
test('树数据快照不可空、value 全非空(取证 id 留档完整)', () => {
|
||||
assert.ok(JD_CATEGORY_TREE.length > 0)
|
||||
for (const leaf of jdCategoryLeaves()) {
|
||||
assert.ok(leaf.value, `叶子 ${leaf.name} 必须带京麦类目 id`)
|
||||
}
|
||||
})
|
||||
@@ -40,40 +40,44 @@ test('endpoints 注册 jdCollect 端点组', () => {
|
||||
'endpoints.ts 缺 jdCollect 端点组(建单/心跳/回传三件)')
|
||||
})
|
||||
|
||||
/** 2026-11-16 用户口径「客户端前端也要同步加上京东类目」:建单页多选末级类目随链下发。
|
||||
* 三处同键契约(建单请求体 / 推送载荷 / 历史行带回)缺一处,客户端就按全店采集跑。 */
|
||||
test('endpoints 注册采集类目 categories 下拉端点', () => {
|
||||
/** 2026-11-16 建单页采集范围换成京麦「店内分类」多选(客户口径「类目不需要只要分类」
|
||||
* 「选京麦的内部分类去采集」+「做成多选的」)。三处同键契约(建单请求体 / 推送载荷 /
|
||||
* 历史行带回)缺一处,客户端就按全店采集跑。 */
|
||||
test('endpoints 注册采集类目 categories 端点(数据面保留)', () => {
|
||||
const endpoints = readIfExists(ENDPOINTS, 'endpoints.ts')
|
||||
assert.ok(endpoints.includes("categories: '/api/jd-collect/categories'"),
|
||||
'endpoints.ts jdCollect 组缺 categories(建单页类目多选面板的选项源)')
|
||||
'endpoints.ts jdCollect 组仍须登记 categories(冻结快照口径;建单页 UI 已下线,仅数据面保留)')
|
||||
})
|
||||
|
||||
/** 2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」:普通账号在
|
||||
* 「获取店铺数据」页就能看到管理员在后管京东数据库建的分类全集与各组商品数;
|
||||
* 本页只读——分类的增删改仍只在后管。「商品上架」落地后消费同一端点。 */
|
||||
test('endpoints 注册店铺分类 groups 只读端点,页面加载并只读展示', () => {
|
||||
/** 2026-11-16 口径修订:客户参照系是京麦后台的「店内分类」,平台分组 chips 从本页下线
|
||||
* (分组数据面归后管京东数据库与商品上架,端点与 fetch 函数保留)。 */
|
||||
test('分类多选来自京麦店内分类快照,平台分组从本页下线', () => {
|
||||
const endpoints = readIfExists(ENDPOINTS, 'endpoints.ts')
|
||||
assert.ok(endpoints.includes("groups: '/api/jd-collect/groups'"),
|
||||
'endpoints.ts jdCollect 组缺 groups(店铺分类只读列表的选项源)')
|
||||
'endpoints.ts jdCollect 组仍须登记 groups(冻结快照口径;建单页 UI 已下线,仅数据面保留)')
|
||||
|
||||
const api = readIfExists(
|
||||
join(process.cwd(), 'src', 'shared', 'api', 'types', 'modules', 'jd-collect.ts'),
|
||||
'jd-collect.ts',
|
||||
)
|
||||
assert.ok(api.includes('export function fetchJdCollectGroups'),
|
||||
'jd-collect.ts 缺 fetchJdCollectGroups(页面取分类列表的发送口)')
|
||||
'jd-collect.ts 保留 fetchJdCollectGroups(上架/数据面消费,非建单页)')
|
||||
|
||||
const page = readIfExists(
|
||||
join(process.cwd(), 'src', 'pages', 'jd', 'JdCollectTab.vue'),
|
||||
'JdCollectTab.vue',
|
||||
)
|
||||
assert.ok(page.includes('fetchJdCollectGroups'),
|
||||
'JdCollectTab.vue 必须调 fetchJdCollectGroups(普通账号在这里看到管理员建的分类)')
|
||||
assert.ok(page.includes('自定义分类</span>'),
|
||||
'JdCollectTab.vue 必须以「自定义分类」展示分类块')
|
||||
assert.ok(page.includes('JD_SHOP_CATEGORY_SNAPSHOT'),
|
||||
'JdCollectTab.vue 必须消费京麦店内分类快照(jd-shop-category.ts)作采集分类多选选项')
|
||||
assert.ok(page.includes('采集分类(可选,多选)'),
|
||||
'JdCollectTab.vue 必须以「采集分类(可选,多选)」展示分类块')
|
||||
assert.ok(!page.includes('JdCategoryCascader'),
|
||||
'JdCollectTab.vue 不得再引用类目级联(2026-11-16 客户口径「类目不需要」)')
|
||||
assert.ok(!page.includes('fetchJdCollectGroups'),
|
||||
'JdCollectTab.vue 不得再消费平台分组接口(两套「分类」并存必混)')
|
||||
})
|
||||
|
||||
test('建单请求体与推送载荷都带 categoryPaths', () => {
|
||||
test('建单请求体与推送载荷都带店内分类双键', () => {
|
||||
const api = readIfExists(
|
||||
join(process.cwd(), 'src', 'shared', 'api', 'types', 'modules', 'jd-collect.ts'),
|
||||
'jd-collect.ts',
|
||||
@@ -82,20 +86,20 @@ test('建单请求体与推送载荷都带 categoryPaths', () => {
|
||||
const apiEnd = api.indexOf('export interface JdCollectDashboardVo')
|
||||
assert.ok(apiStart > 0 && apiEnd > apiStart, 'jd-collect.ts 缺 createJdCollectTask')
|
||||
const apiBody = api.slice(apiStart, apiEnd)
|
||||
assert.ok(apiBody.includes('categoryPaths'),
|
||||
'createJdCollectTask 请求体必须带 categoryPaths(空数组=全店采集)')
|
||||
assert.ok(apiBody.includes('shopCategoryNames') && apiBody.includes('shopCategoryIds'),
|
||||
'createJdCollectTask 请求体必须带店内分类双键(label+id 同发:行级填充形状未取证,任一键命中即命中)')
|
||||
|
||||
const page = readIfExists(
|
||||
join(process.cwd(), 'src', 'pages', 'jd', 'JdCollectTab.vue'),
|
||||
'JdCollectTab.vue',
|
||||
)
|
||||
assert.ok(page.includes('maxProducts: 0, categoryPaths }'),
|
||||
'推送载荷 data 必须带 categoryPaths(与后端 JdTaskPullSpiImplTest 键集断言同键)')
|
||||
assert.ok(page.includes('createJdCollectTask(shop, tabs, 0, categories)'),
|
||||
'startCollect 建单必须把选中的类目传给 createJdCollectTask')
|
||||
assert.ok(page.includes('maxProducts: 0, shopCategoryNames, shopCategoryIds }'),
|
||||
'推送载荷 data 必须带店内分类双键(与后端 JdTaskPullSpiImplTest 键集断言同键)')
|
||||
assert.ok(page.includes('createJdCollectTask(shop, tabs, 0, [], shopNames, shopIds)'),
|
||||
'startCollect 建单必须把选中的分类(names+ids)传给 createJdCollectTask')
|
||||
})
|
||||
|
||||
test('重试/继续从历史行同源带回 categoryPaths', () => {
|
||||
test('重试/继续从历史行同源带回店内分类双键', () => {
|
||||
const page = readIfExists(
|
||||
join(process.cwd(), 'src', 'pages', 'jd', 'JdCollectTab.vue'),
|
||||
'JdCollectTab.vue',
|
||||
@@ -103,8 +107,8 @@ test('重试/继续从历史行同源带回 categoryPaths', () => {
|
||||
const startAt = page.indexOf('async function retryTaskRecord')
|
||||
assert.ok(startAt > 0, 'JdCollectTab.vue 缺 retryTaskRecord')
|
||||
const body = page.slice(startAt, page.indexOf('/** 手动刷新'))
|
||||
assert.ok(body.includes('item?.categoryPaths ?? []'),
|
||||
'重试/继续重建推送载荷必须从历史行带回 categoryPaths(后端 history VO 同源字段),缺了客户端会按全店采集跑')
|
||||
assert.ok(body.includes('item?.shopCategoryNames ?? []') && body.includes('item?.shopCategoryIds ?? []'),
|
||||
'重试/继续重建推送载荷必须从历史行带回店内分类双键(后端 history VO 同源字段),缺了客户端会按全店采集跑')
|
||||
})
|
||||
|
||||
/** 2026-11-14 真机实录:建单请求体写成 `user_id` 时后端回一句「user_id 不合法」直接拒,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** 京麦「店内分类」快照契约(2026-11-16 真机取证,建单页采集分类多选的选项集)。
|
||||
*
|
||||
* 快照是纯前端静态数据(getShopCategoryList 的 label/value 对,扁平单层)。判据钉四件:
|
||||
* ① 快照非空且形状齐(label/value 都非空字符串);② label 不重复(多选以 label 下发,
|
||||
* 重名会让客户端过滤语义歧义);③ 取证出处注释在位(后人按原路重抓,防止当它错改);
|
||||
* ④ 建单页消费快照(对手面 jd-collect-tab.test.ts 的发送口断言)。 */
|
||||
|
||||
const SNAPSHOT = join(process.cwd(), 'src', 'pages', 'jd', 'jd-shop-category.ts')
|
||||
|
||||
function readIfExists(path: string, what: string): string {
|
||||
assert.ok(existsSync(path), `${what} 尚未落地:${path}`)
|
||||
return readFileSync(path, 'utf8')
|
||||
}
|
||||
|
||||
test('店内分类快照非空且每项 label/value 齐全', async () => {
|
||||
const mod = await import('../src/pages/jd/jd-shop-category.ts')
|
||||
const { JD_SHOP_CATEGORY_SNAPSHOT } = mod as {
|
||||
JD_SHOP_CATEGORY_SNAPSHOT: { label: string; value: string }[]
|
||||
}
|
||||
assert.ok(Array.isArray(JD_SHOP_CATEGORY_SNAPSHOT) && JD_SHOP_CATEGORY_SNAPSHOT.length > 0,
|
||||
'快照不得为空(2026-11-16 取证 9 个)')
|
||||
for (const item of JD_SHOP_CATEGORY_SNAPSHOT) {
|
||||
assert.ok(typeof item.label === 'string' && item.label.trim().length > 0,
|
||||
`label 必须是非空字符串: ${JSON.stringify(item)}`)
|
||||
assert.ok(typeof item.value === 'string' && item.value.trim().length > 0,
|
||||
`value(京麦分类 id)必须是非空字符串: ${JSON.stringify(item)}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('快照 label 不重复(多选按 label 下发,重名会让过滤语义歧义)', async () => {
|
||||
const mod = await import('../src/pages/jd/jd-shop-category.ts')
|
||||
const { JD_SHOP_CATEGORY_SNAPSHOT } = mod as {
|
||||
JD_SHOP_CATEGORY_SNAPSHOT: { label: string }[]
|
||||
}
|
||||
const labels = JD_SHOP_CATEGORY_SNAPSHOT.map((item) => item.label)
|
||||
assert.equal(new Set(labels).size, labels.length,
|
||||
`label 有重复: ${labels.join(', ')}`)
|
||||
})
|
||||
|
||||
test('取证出处与边界注释在位(防后人当它错改)', () => {
|
||||
const body = readIfExists(SNAPSHOT, 'jd-shop-category.ts')
|
||||
assert.ok(body.includes('getShopCategoryList'),
|
||||
'快照文件必须写明数据来源接口(ShopCategoryReadViewService.getShopCategoryList)')
|
||||
assert.ok(body.includes('2026-11-16'), '快照文件必须带取证日期')
|
||||
assert.ok(body.includes('shopCategorys') || body.includes('shopCategoryPath'),
|
||||
'快照文件必须写明行级过滤键(shopCategorys/shopCategoryPath/groupId)')
|
||||
assert.ok(body.includes('0/450') || body.includes('没给商品挂分类'),
|
||||
'快照文件必须写明「采样店铺 0 商品挂分类」的现状边界(选分类=0 行命中是已知形状)')
|
||||
})
|
||||
@@ -151,8 +151,8 @@ describe('获取店铺数据:一键采集 + 任务面板', () => {
|
||||
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledTimes(1)
|
||||
// 店铺名留空 → 按「京麦后台」占位(客户端从京麦后台现读真实店铺名落库);
|
||||
// 不选类目=空数组(全店采集,后端归一化为 null 进 request_json)
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [])
|
||||
// 不选分类=双键空数组(全店采集,后端归一化为 null 进 request_json)
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [], [], [])
|
||||
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
|
||||
expect(api.enqueue).toHaveBeenCalledTimes(1)
|
||||
const payload = api.enqueue.mock.calls[0][0]
|
||||
@@ -162,7 +162,8 @@ describe('获取店铺数据:一键采集 + 任务面板', () => {
|
||||
shopName: '京麦后台',
|
||||
listTabs: ['ONSALE', 'OFFSALE'],
|
||||
maxProducts: 0,
|
||||
categoryPaths: [],
|
||||
shopCategoryNames: [],
|
||||
shopCategoryIds: [],
|
||||
})
|
||||
// 轮询已启动:批量进度端点拿到任务 88
|
||||
expect(api.fetchJdCollectTaskProgressBatch).toHaveBeenCalled()
|
||||
@@ -283,75 +284,54 @@ describe('获取店铺数据:一键采集 + 任务面板', () => {
|
||||
expect(w.find('.feedback.error').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('勾选类目后建单:categoryPaths 随建单请求体与推送载荷同链下发', async () => {
|
||||
// 2026-11-16 用户口径「客户端前端也要同步加上京东类目」+「你直接爬」:面板换京麦
|
||||
// 授权类目真树(逐级下钻、末级勾选)——下钻 运动户外 → 舞蹈体操鞋服/装备(客户
|
||||
// 舞蹈服类目在京麦归运动户外支)→ 勾末级「艺考形体服」后建单请求体与推送载荷都要
|
||||
// 带 ['艺考形体服'](客户端按行 categoryPath 等值过滤的源头;mock 类目用树内真实
|
||||
// 末级名,贴合落库形状)。
|
||||
api.fetchJdCollectCategories.mockResolvedValue([
|
||||
{ name: '艺考形体服', productCount: 5 },
|
||||
{ name: '啦啦队服', productCount: 3 },
|
||||
])
|
||||
it('勾选分类后建单:店内分类双键随建单请求体与推送载荷同链下发', async () => {
|
||||
// 2026-11-16 客户口径「类目不需要只要分类」「选京麦的内部分类去采集」+「做成多选的」:
|
||||
// 选项集=京麦「店内分类」快照(jd-shop-category.ts,getShopCategoryList 取证 9 个),
|
||||
// checkbox 多选;建单请求体与推送载荷带 label+id 双键(行级填充形状未取证,客户端
|
||||
// 任一键命中即命中)——mock 选中项用快照真实行(拉丁舞服/1024347572),贴合下发形状。
|
||||
const w = await mountPage()
|
||||
|
||||
await w.find('.cat-trigger').trigger('click')
|
||||
await w.findAll('.cat-col')[0].findAll('.cat-row').find((row) => row.text().includes('运动户外'))!.trigger('click')
|
||||
let cols = w.findAll('.cat-col')
|
||||
expect(cols).toHaveLength(2, '点亮一级后第二栏出现(真树下钻)')
|
||||
await cols[1].findAll('.cat-row').find((row) => row.text().includes('舞蹈体操鞋服/装备'))!.trigger('click')
|
||||
cols = w.findAll('.cat-col')
|
||||
expect(cols).toHaveLength(3, '二级非末级:第三栏出末级子级')
|
||||
const leafRow = cols[2].findAll('.cat-row').find((row) => row.text().includes('艺考形体服'))
|
||||
expect(leafRow, '第三栏必须渲染出该支的末级(艺考形体服)').toBeTruthy()
|
||||
await leafRow!.trigger('click')
|
||||
const rows = w.findAll('.shop-cat-item')
|
||||
expect(rows.length).toBeGreaterThan(0, '分类多选列表必须渲染快照选项')
|
||||
const latinRow = rows.find((row) => row.text().includes('拉丁舞服'))
|
||||
expect(latinRow, '快照里必须有「拉丁舞服」').toBeTruthy()
|
||||
await latinRow!.find('input').setValue(true)
|
||||
const uniformRow = rows.find((row) => row.text().includes('工作制服'))
|
||||
await uniformRow!.find('input').setValue(true)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.cat-trigger-text').text()).toBe('艺考形体服', '单选勾选后触发框显示类目名')
|
||||
await w.find('.cat-mask').trigger('click')
|
||||
await startCollect(w)
|
||||
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, ['艺考形体服'])
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [],
|
||||
['拉丁舞服', '工作制服'], ['1024347572', '1024347567'])
|
||||
const payload = api.enqueue.mock.calls[0][0]
|
||||
expect(payload.data).toEqual({
|
||||
taskId: 88,
|
||||
shopName: '京麦后台',
|
||||
listTabs: ['ONSALE', 'OFFSALE'],
|
||||
maxProducts: 0,
|
||||
categoryPaths: ['艺考形体服'],
|
||||
shopCategoryNames: ['拉丁舞服', '工作制服'],
|
||||
shopCategoryIds: ['1024347572', '1024347567'],
|
||||
})
|
||||
})
|
||||
|
||||
it('店铺分类只读块:页面加载即拉取并把管理员建的分类与商品数展示出来', async () => {
|
||||
// 2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」:普通账号在
|
||||
// 「获取店铺数据」页就能看到后管京东数据库建的分类全集;本页只读,不提供增删改。
|
||||
api.fetchJdCollectGroups.mockResolvedValue([
|
||||
{ id: 1, name: 'ASSS', sortOrder: 0, productCount: 20 },
|
||||
{ id: 2, name: '家居日用', sortOrder: 1, productCount: 7 },
|
||||
])
|
||||
it('采集分类块:快照选项全量渲染并可取消勾选(清空恢复全店采集)', async () => {
|
||||
const w = await mountPage()
|
||||
|
||||
expect(api.fetchJdCollectGroups).toHaveBeenCalledTimes(1)
|
||||
const block = w.findAll('.category-block').find((el) => el.text().includes('自定义分类'))
|
||||
expect(block, '必须有「自定义分类」展示块').toBeTruthy()
|
||||
expect(block!.text()).toContain('自定义分类')
|
||||
const chips = block!.findAll('.group-chip')
|
||||
expect(chips.length).toBe(2)
|
||||
expect(chips[0].text()).toContain('ASSS(20)')
|
||||
expect(chips[1].text()).toContain('家居日用(7)')
|
||||
expect(chips[0].attributes('title')).toContain('ASSS:20 个商品')
|
||||
})
|
||||
const block = w.findAll('.category-block').find((el) => el.text().includes('采集分类'))
|
||||
expect(block, '必须有「采集分类(可选,多选)」块').toBeTruthy()
|
||||
expect(block!.text()).toContain('采集分类(可选,多选)')
|
||||
// 快照 9 项全渲染(客户端「能看见管理员/商家建的分类」口径落点就在这)
|
||||
expect(block!.findAll('.shop-cat-item').length).toBe(9)
|
||||
expect(block!.text()).toContain('不选=全店采集')
|
||||
|
||||
it('后台还没建分类:只读块落空态提示,采集主路照常', async () => {
|
||||
const w = await mountPage()
|
||||
|
||||
const block = w.findAll('.category-block').find((el) => el.text().includes('自定义分类'))
|
||||
expect(block, '空态也要有「自定义分类」块(不能整块消失让用户以为没这功能)').toBeTruthy()
|
||||
expect(block!.text()).toContain('后台还没建自定义分类')
|
||||
expect(block!.text()).toContain('管理员可在「京东数据库」的类目面板中新建自定义分类')
|
||||
expect(block!.text()).not.toContain('京东数据库 → 店铺分类')
|
||||
expect(block!.find('.group-chip').exists()).toBe(false)
|
||||
// 拉取失败只 warning、不影响建单主路(catch 口径见 catch-silence-ratchet 319)
|
||||
expect(w.find('.collect-btn').exists()).toBe(true)
|
||||
const first = block!.findAll('.shop-cat-item')[0]
|
||||
await first.find('input').setValue(true)
|
||||
await flushPromises()
|
||||
expect(block!.text()).toContain('只采选中 1 个分类的商品')
|
||||
expect(block!.find('.shop-cat-clear').exists()).toBe(true, '选中后出「清空」')
|
||||
await block!.find('.shop-cat-clear').trigger('click')
|
||||
await flushPromises()
|
||||
expect(block!.text()).toContain('不选=全店采集')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user