feat(phase-5): 后管京东数据库接口与页面+用户端采集入口——v1.4 Phase 5
This commit is contained in:
@@ -63,4 +63,7 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
|
||||
// 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列
|
||||
// (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] },
|
||||
// 京东数据库(2026-11-14 v1.4):京麦店铺商品采集落库的只读镜像,归属物化在行 company_id 列
|
||||
// (V193,同外观专利 V189 形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
{ menuKey: 'admin_jd_database', apiFiles: ['src/pages/jd/jd-product-api.ts'], pageFiles: ['src/pages/jd/JdDatabasePage.vue'] },
|
||||
]
|
||||
|
||||
@@ -125,6 +125,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '本页只读:出表成功后「结论=无侵权」的明细自动同步到这里,按分公司隔离分页展示;支持任务号/ASIN/国家/同步日期筛选,下载原表请到任务中心取结果文件。',
|
||||
steps: ['筛选记录', '核对结论明细', '到任务中心下载原表'],
|
||||
},
|
||||
admin_jd_database: {
|
||||
text: '本页只读:客户端采集的京东店铺商品自动同步到这里(同店铺同商品只保留最新一次),按分公司隔离分页展示;点行查看全部属性与图片,可用自定义分组归档商品。',
|
||||
steps: ['筛选商品记录', '查看属性与图片明细', '按分组归档管理'],
|
||||
},
|
||||
}
|
||||
|
||||
/** 全部有独立/兜底提示的后台业务菜单 key。 */
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东数据库页(v1.4 Phase 5):公司隔离的京东商品库,筛选行(店铺/商品编码/标题关键字/商品状态/
|
||||
* 分组/同步起止 date 对)+查询/导出/重置/管理分组 + 自绘明细表(点行开详情抽屉)+ OldPagination。
|
||||
* 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页);
|
||||
* 公司 tab 切换=清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、
|
||||
* 止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来(clampJdSyncedRange 照 clampDatePair)。
|
||||
* 日期初值故意留空:同步数据是累计集,默认当天会让首屏只剩今天同步的行
|
||||
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
exportJdProductList,
|
||||
fetchJdProductGroups,
|
||||
fetchJdProductList,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import type { JdProductItem } from './jd-product-model.ts'
|
||||
import { jdPriceRange } from './jd-product-model.ts'
|
||||
import { createJdProductFilterState, JD_SALE_STATUS_HINT } from './jd-product-filter.ts'
|
||||
import JdProductDetailDrawer from './JdProductDetailDrawer.vue'
|
||||
import JdProductGroupDialog from './JdProductGroupDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
|
||||
const companyTab = useCompanyTabStore()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<JdProductItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
/** 导出在途锁:避免连点导出把同一份过滤面重复请求两遍。 */
|
||||
const exporting = ref(false)
|
||||
const filter = reactive(createJdProductFilterState())
|
||||
/** 分组下拉选项:公司 tab 切换时重取;选项失败不拦列表,只回空下拉(可见「全部分组」)。 */
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
/** 分组管理弹窗与详情抽屉。 */
|
||||
const groupDialogVisible = ref(false)
|
||||
const detailItem = ref<JdProductItem | null>(null)
|
||||
const detailVisible = ref(false)
|
||||
|
||||
/** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */
|
||||
function clampJdSyncedRange(): void {
|
||||
const [s, e] = orderedPair(filter.syncedFrom, filter.syncedTo)
|
||||
filter.syncedFrom = s
|
||||
filter.syncedTo = e
|
||||
}
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
/** 分组选项失败静默回空——分组只是筛选项,不该让它把首屏行集一起拖死。 */
|
||||
async function loadGroupOptions(): Promise<void> {
|
||||
try {
|
||||
groupOptions.value = await fetchJdProductGroups(companyTab.requestCompanyId)
|
||||
} catch {
|
||||
groupOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 分组管理弹窗里做过变更:分组下拉与列表都刷新(删除分组后行集的 groupName 会变)。 */
|
||||
async function onGroupChanged(): Promise<void> {
|
||||
await loadGroupOptions()
|
||||
page.value = 1
|
||||
await load()
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchJdProductList({
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
shopName: filter.shopName,
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
saleStatus: filter.saleStatus,
|
||||
groupId: filter.groupId,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
})
|
||||
rows.value = result.items
|
||||
total.value = result.total
|
||||
if (result.page >= 1) page.value = result.page
|
||||
} catch (error) {
|
||||
loadFailure.value = loadFailureMessage(error, '京东商品列表加载失败')
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出与页签同一过滤面(含公司 tab 与分组),服务端全量出 xlsx;成功后浏览器落盘,失败弹可读文案。 */
|
||||
async function exportAll(): Promise<void> {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const result = await exportJdProductList({
|
||||
shopName: filter.shopName,
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
saleStatus: filter.saleStatus,
|
||||
groupId: filter.groupId,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
})
|
||||
const url = URL.createObjectURL(result.blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = result.filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
showAdminFeedback(`已导出 ${result.filename}`, 'success')
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : '导出失败,请稍后重试'
|
||||
showAdminFeedback(message, 'error')
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function apply(): void {
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
/** 重置:筛选面回出厂空态,回第一页重取。 */
|
||||
function reset(): void {
|
||||
Object.assign(filter, createJdProductFilterState())
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function changePage(next: number): void {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
void load()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function openDetail(item: JdProductItem): void {
|
||||
detailItem.value = item
|
||||
detailVisible.value = true
|
||||
}
|
||||
|
||||
function closeDetail(): void {
|
||||
detailVisible.value = false
|
||||
detailItem.value = null
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数:店铺/编码/关键字/状态/分组是上一家选中的值,在新一家的行集里筛不出东西,
|
||||
// 必须一起清,分组选项也按新公司重取(选项集是公司隔离的)。
|
||||
watch(() => companyTab.activeId, () => { filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.saleStatus = ''; filter.groupId = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadGroupOptions(); void load() })
|
||||
|
||||
onMounted(() => {
|
||||
void loadGroupOptions()
|
||||
void load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="jd-database-view">
|
||||
<section class="panel-box">
|
||||
<div class="jd-panel-head">
|
||||
<h3>京东数据库</h3>
|
||||
<button class="btn btn-secondary" type="button" @click="groupDialogVisible = true">管理分组</button>
|
||||
</div>
|
||||
|
||||
<div class="jd-filter-row">
|
||||
<div class="form-group">
|
||||
<label>店铺</label>
|
||||
<input v-model="filter.shopName" type="text" placeholder="输入店铺名" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>商品编码</label>
|
||||
<input v-model="filter.productCode" type="text" placeholder="输入商品编码" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>标题关键字</label>
|
||||
<input v-model="filter.titleKeyword" type="text" placeholder="输入标题关键字" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>商品状态</label>
|
||||
<input v-model="filter.saleStatus" type="text" :placeholder="JD_SALE_STATUS_HINT" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>分组</label>
|
||||
<!-- 分组选中即查:选完立刻按该分组过滤刷新(回第一页),不必再点查询。 -->
|
||||
<select v-model="filter.groupId" @change="apply">
|
||||
<option value="">全部分组</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>同步开始日期</label>
|
||||
<input v-model="filter.syncedFrom" type="date" :max="filter.syncedTo" @change="clampJdSyncedRange" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>同步结束日期</label>
|
||||
<input v-model="filter.syncedTo" type="date" :min="filter.syncedFrom" @change="clampJdSyncedRange" />
|
||||
</div>
|
||||
<div class="jd-filter-actions">
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
<button class="btn btn-export" type="button" :disabled="exporting" @click="exportAll">
|
||||
{{ exporting ? '导出中...' : '导出' }}
|
||||
</button>
|
||||
<button class="btn btn-secondary" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="jd-toolbar">
|
||||
<span class="jd-summary">共 {{ total }} 条京东商品</span>
|
||||
</div>
|
||||
<div class="table-scroll jd-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 76px">主图</th>
|
||||
<th style="width: 120px">店铺</th>
|
||||
<th style="width: 110px">商品编码</th>
|
||||
<th>标题</th>
|
||||
<th style="width: 90px">品牌</th>
|
||||
<th style="width: 110px">价格区间</th>
|
||||
<th style="width: 64px">库存</th>
|
||||
<th style="width: 80px">状态</th>
|
||||
<th style="width: 100px">分组</th>
|
||||
<th style="width: 170px">京东更新时间</th>
|
||||
<th style="width: 170px">同步时间</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>
|
||||
<img v-if="row.mainImageUrl" class="jd-thumb" :src="row.mainImageUrl" alt="" loading="lazy" />
|
||||
<span v-else class="empty-mini">无图</span>
|
||||
</td>
|
||||
<td :title="row.shopName || ''">{{ row.shopName || '-' }}</td>
|
||||
<td class="mono-cell">{{ row.productCode || '-' }}</td>
|
||||
<td class="title-cell" :title="row.title">{{ row.title || '-' }}</td>
|
||||
<td>{{ row.brand || '-' }}</td>
|
||||
<td>{{ jdPriceRange(row) || '-' }}</td>
|
||||
<td>{{ row.stockTotal ?? '-' }}</td>
|
||||
<td>{{ row.saleStatus || '-' }}</td>
|
||||
<td :title="row.groupName || ''">{{ row.groupName || '未分组' }}</td>
|
||||
<td>{{ formatDateTime(row.jdUpdatedAt || '') }}</td>
|
||||
<td>{{ formatDateTime(row.syncedAt || '') }}</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="11" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="11" class="empty-tip">暂无京东商品数据</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<JdProductDetailDrawer
|
||||
:item="detailItem"
|
||||
:visible="detailVisible"
|
||||
:company-id="companyTab.requestCompanyId"
|
||||
@close="closeDetail"
|
||||
/>
|
||||
<JdProductGroupDialog
|
||||
:visible="groupDialogVisible"
|
||||
:company-id="companyTab.requestCompanyId"
|
||||
@close="groupDialogVisible = false"
|
||||
@changed="onGroupChanged"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻「外观专利数据库」页样式(panel-box + 自绘表格 + 旧式分页),表头多一列「京东更新时间」。 */
|
||||
.jd-database-view {
|
||||
font-family: inherit;
|
||||
color: var(--c-text, #24384d);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0 0 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.jd-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.jd-panel-head h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.jd-filter-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, minmax(140px, 1fr)) auto;
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.jd-filter-row .form-group {
|
||||
min-width: 0;
|
||||
}
|
||||
.jd-filter-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.form-group input[type="date"] {
|
||||
color-scheme: light;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.jd-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.jd-summary {
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.jd-table-scroll > table {
|
||||
min-width: 1260px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
/* 点行开详情抽屉:行级 hover 已有底色反馈,光标再点一下提示可点。 */
|
||||
.jd-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
.jd-thumb {
|
||||
display: block;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #f2f7fb;
|
||||
}
|
||||
.empty-mini {
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.mono-cell {
|
||||
font-family: "Cascadia Mono", "SF Mono", Consolas, "Courier New", monospace;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.title-cell {
|
||||
max-width: 260px;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,463 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品详情抽屉(v1.4 Phase 5):点行打开,展示基本信息 + attrGroups 分块表格 +
|
||||
* 图片网格(MAIN/ATTR/DETAIL 三区,attr 图按 attrName 归并)。
|
||||
* 图片点击放大预览用自绘 modal-mask(先例:RecordsHistoryPage 的 thumb + modal-mask +
|
||||
* 原图新标签;不用 element-plus)。数据由本组件按 (id, companyId) 自取,失败条内提示可重试。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { fetchJdProductDetail } from './jd-product-api.ts'
|
||||
import type { JdProductImage, JdProductItem, JdProductAttrGroup } from './jd-product-model.ts'
|
||||
import { jdPriceRange } from './jd-product-model.ts'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
item: JdProductItem | null
|
||||
visible: boolean
|
||||
companyId: number | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void }>()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const attrGroups = ref<JdProductAttrGroup[]>([])
|
||||
const images = ref<JdProductImage[]>([])
|
||||
const attrJsonRaw = ref('')
|
||||
|
||||
/** 图片三区:MAIN / ATTR / DETAIL;未知类型归 DETAIL 之外的「其他」,不丢。 */
|
||||
const mainImages = computed(() => images.value.filter((image) => image.imageType === 'MAIN'))
|
||||
const attrImageGroups = computed(() => {
|
||||
const buckets = new Map<string, JdProductImage[]>()
|
||||
for (const image of images.value) {
|
||||
if (image.imageType !== 'ATTR') continue
|
||||
const key = image.attrName || '属性图'
|
||||
const bucket = buckets.get(key)
|
||||
if (bucket) bucket.push(image)
|
||||
else buckets.set(key, [image])
|
||||
}
|
||||
return [...buckets.entries()].map(([attrName, list]) => ({ attrName, list }))
|
||||
})
|
||||
const detailImages = computed(() => images.value.filter((image) => image.imageType === 'DETAIL'))
|
||||
const otherImages = computed(() =>
|
||||
images.value.filter((image) => image.imageType !== 'MAIN' && image.imageType !== 'ATTR' && image.imageType !== 'DETAIL'),
|
||||
)
|
||||
|
||||
/** 放大预览:点缩略图弹自绘 modal-mask,原图可新标签打开。 */
|
||||
const previewVisible = ref(false)
|
||||
const previewUrl = ref('')
|
||||
|
||||
function openPreview(url: string): void {
|
||||
previewUrl.value = url
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
previewVisible.value = false
|
||||
emit('close')
|
||||
}
|
||||
|
||||
async function loadDetail(): Promise<void> {
|
||||
const item = props.item
|
||||
if (!item) return
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
attrGroups.value = []
|
||||
images.value = []
|
||||
attrJsonRaw.value = ''
|
||||
try {
|
||||
const detail = await fetchJdProductDetail(item.id, props.companyId)
|
||||
attrGroups.value = detail.attrGroups
|
||||
images.value = detail.images
|
||||
attrJsonRaw.value = detail.attrJsonRaw
|
||||
if (!detail.attrGroups.length && detail.attrJsonRaw) {
|
||||
// 结构化解析失败但原文在:兜底展示原文,不静默吞
|
||||
loadFailure.value = ''
|
||||
}
|
||||
} catch (error) {
|
||||
loadFailure.value = requestErrorMessage(error) || '商品详情加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.item?.id] as const,
|
||||
([visible]) => {
|
||||
previewVisible.value = false
|
||||
previewUrl.value = ''
|
||||
if (visible && props.item) void loadDetail()
|
||||
},
|
||||
)
|
||||
|
||||
function dash(value: string | number | null | undefined): string {
|
||||
const text = value === null || value === undefined ? '' : String(value).trim()
|
||||
return text || '-'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="drawer-mask" @click.self="close">
|
||||
<aside class="drawer">
|
||||
<header class="drawer-head">
|
||||
<h3>商品详情{{ item?.productCode ? ` · ${item.productCode}` : '' }}</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="close">×</button>
|
||||
</header>
|
||||
|
||||
<div class="drawer-body">
|
||||
<div v-if="loadFailure" class="drawer-failure">
|
||||
<span>{{ loadFailure }}</span>
|
||||
<button class="btn btn-secondary" type="button" @click="loadDetail">重试</button>
|
||||
</div>
|
||||
<p v-else-if="loading" class="drawer-tip">加载中...</p>
|
||||
|
||||
<template v-else>
|
||||
<section class="detail-block">
|
||||
<h4>基本信息</h4>
|
||||
<dl class="info-grid">
|
||||
<div class="info-item info-item-wide">
|
||||
<dt>标题</dt>
|
||||
<dd :title="item?.title || ''">{{ dash(item?.title) }}</dd>
|
||||
</div>
|
||||
<div class="info-item"><dt>品牌</dt><dd>{{ dash(item?.brand) }}</dd></div>
|
||||
<div class="info-item"><dt>类目</dt><dd :title="item?.categoryPath || ''">{{ dash(item?.categoryPath) }}</dd></div>
|
||||
<div class="info-item"><dt>货号</dt><dd>{{ dash(item?.productCode) }}</dd></div>
|
||||
<div class="info-item"><dt>价格区间</dt><dd>{{ dash(jdPriceRange(item ?? { priceMin: '', priceMax: '' })) }}</dd></div>
|
||||
<div class="info-item"><dt>库存</dt><dd>{{ dash(item?.stockTotal) }}</dd></div>
|
||||
<div class="info-item"><dt>状态</dt><dd>{{ dash(item?.saleStatus) }}</dd></div>
|
||||
<div class="info-item"><dt>京东创建时间</dt><dd>{{ formatDateTime(item?.jdUpdatedAt || '') }}</dd></div>
|
||||
<div class="info-item"><dt>同步时间</dt><dd>{{ formatDateTime(item?.syncedAt || '') }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="attrGroups.length" class="detail-block">
|
||||
<h4>属性</h4>
|
||||
<div v-for="group in attrGroups" :key="group.groupName" class="attr-group">
|
||||
<h5>{{ group.groupName }}</h5>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr v-for="(attr, index) in group.attrs" :key="`${attr.key}-${index}`">
|
||||
<th>{{ attr.label || attr.key || '-' }}</th>
|
||||
<td>{{ attr.value || '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<section v-else-if="attrJsonRaw" class="detail-block">
|
||||
<h4>属性(原始 JSON)</h4>
|
||||
<pre class="attr-raw">{{ attrJsonRaw }}</pre>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>主图</h4>
|
||||
<div v-if="mainImages.length" class="image-grid">
|
||||
<img
|
||||
v-for="image in mainImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无主图</p>
|
||||
</section>
|
||||
|
||||
<section v-for="bucket in attrImageGroups" :key="bucket.attrName" class="detail-block">
|
||||
<h4>属性图 · {{ bucket.attrName }}</h4>
|
||||
<div class="image-grid">
|
||||
<img
|
||||
v-for="image in bucket.list"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>详情图</h4>
|
||||
<div v-if="detailImages.length" class="image-grid">
|
||||
<img
|
||||
v-for="image in detailImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无详情图</p>
|
||||
</section>
|
||||
|
||||
<section v-if="otherImages.length" class="detail-block">
|
||||
<h4>其他图</h4>
|
||||
<div class="image-grid">
|
||||
<img
|
||||
v-for="image in otherImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div v-if="previewVisible" class="modal-mask" @click.self="previewVisible = false">
|
||||
<div class="preview-modal">
|
||||
<div class="preview-head">
|
||||
<h3>图片预览</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="previewVisible = false">×</button>
|
||||
</div>
|
||||
<img class="preview-image" :src="previewUrl" alt="" />
|
||||
<div class="preview-foot">
|
||||
<a :href="previewUrl" target="_blank" rel="noopener">新标签打开原图</a>
|
||||
<button class="btn btn-secondary" type="button" @click="previewVisible = false">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2600;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.drawer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(760px, 100%);
|
||||
height: 100%;
|
||||
background: #ffffff;
|
||||
box-shadow: -18px 0 40px rgba(39, 67, 94, 0.18);
|
||||
}
|
||||
.drawer-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #dbe5ee;
|
||||
}
|
||||
.drawer-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-close {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #5b6f83;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.drawer-close:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px 20px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.drawer-tip {
|
||||
margin: 0;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.drawer-failure {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.detail-block h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
color: #4e6479;
|
||||
}
|
||||
.info-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
.info-item {
|
||||
min-width: 0;
|
||||
}
|
||||
.info-item-wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.info-item dt {
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.info-item dd {
|
||||
margin: 0;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.attr-group {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.attr-group h5 {
|
||||
margin: 0 0 6px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.attr-group table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.attr-group th,
|
||||
.attr-group td {
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.attr-group th {
|
||||
width: 180px;
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.attr-group tr:last-child th,
|
||||
.attr-group tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.attr-raw {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.image-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.image-grid img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 8px;
|
||||
background: #f2f7fb;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.preview-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(880px, 100%);
|
||||
max-height: 88vh;
|
||||
padding: 16px 20px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
}
|
||||
.preview-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.preview-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
color: #24384d;
|
||||
}
|
||||
.preview-image {
|
||||
display: block;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
max-height: 68vh;
|
||||
margin: 12px 0;
|
||||
object-fit: contain;
|
||||
background: #f2f7fb;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.preview-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.preview-foot a {
|
||||
color: #2f5d8b;
|
||||
font-size: 13px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 9px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border: 1px solid #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,352 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品分组管理弹窗(v1.4 Phase 5):新建/改名/删除,重名等业务失败把后端返回的中文文案
|
||||
* 原样展示在弹窗内(envelope code 非 0 → errorTextOf);删除前 openAdminConfirm 二次确认;
|
||||
* 变更成功后 emit('changed'),由页面刷新分组下拉与列表。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
createJdProductGroup,
|
||||
deleteJdProductGroup,
|
||||
fetchJdProductGroups,
|
||||
updateJdProductGroup,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
companyId: number | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed'): void }>()
|
||||
|
||||
const loading = ref(false)
|
||||
const errorText = ref('')
|
||||
const groups = ref<JdProductGroup[]>([])
|
||||
/** 新建:名称 + 排序。 */
|
||||
const createName = ref('')
|
||||
const createSortOrder = ref(0)
|
||||
const creating = ref(false)
|
||||
/** 改名:正在编辑的分组 id 与草稿名。 */
|
||||
const editingId = ref(0)
|
||||
const editingName = ref('')
|
||||
const saving = ref(false)
|
||||
|
||||
const canCreate = computed(() => createName.value.trim().length > 0 && !creating.value && !saving.value)
|
||||
|
||||
async function loadGroups(): Promise<void> {
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
groups.value = await fetchJdProductGroups(props.companyId)
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '分组列表加载失败'
|
||||
groups.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function sortGroups(list: JdProductGroup[]): JdProductGroup[] {
|
||||
return [...list].sort((a, b) => a.sortOrder - b.sortOrder || a.id - b.id)
|
||||
}
|
||||
|
||||
async function submitCreate(): Promise<void> {
|
||||
const name = createName.value.trim()
|
||||
if (!name || creating.value) return
|
||||
creating.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await createJdProductGroup({ name, sortOrder: Math.floor(createSortOrder.value) || 0 }, props.companyId)
|
||||
createName.value = ''
|
||||
createSortOrder.value = 0
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '新建分组失败'
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startRename(group: JdProductGroup): void {
|
||||
editingId.value = group.id
|
||||
editingName.value = group.name
|
||||
errorText.value = ''
|
||||
}
|
||||
|
||||
function cancelRename(): void {
|
||||
editingId.value = 0
|
||||
editingName.value = ''
|
||||
}
|
||||
|
||||
async function submitRename(group: JdProductGroup): Promise<void> {
|
||||
const name = editingName.value.trim()
|
||||
if (!name || saving.value) return
|
||||
saving.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await updateJdProductGroup(group.id, { name, sortOrder: group.sortOrder }, props.companyId)
|
||||
cancelRename()
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '改名失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeGroup(group: JdProductGroup): Promise<void> {
|
||||
const ok = await openAdminConfirm({ title: '删除分组', message: `确定删除分组「${group.name}」吗?删除后该组商品回到未分组。`, confirmText: '确认删除', danger: true })
|
||||
if (!ok || saving.value) return
|
||||
saving.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
await deleteJdProductGroup(group.id, props.companyId)
|
||||
groups.value = sortGroups(await fetchJdProductGroups(props.companyId))
|
||||
emit('changed')
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '删除分组失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
cancelRename()
|
||||
createName.value = ''
|
||||
createSortOrder.value = 0
|
||||
void loadGroups()
|
||||
}
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
|
||||
<div class="group-modal">
|
||||
<div class="modal-head">
|
||||
<h3>分组管理</h3>
|
||||
<button class="modal-close" type="button" aria-label="关闭" @click="emit('close')">×</button>
|
||||
</div>
|
||||
|
||||
<div class="group-create">
|
||||
<input
|
||||
v-model="createName"
|
||||
type="text"
|
||||
placeholder="输入新分组名称"
|
||||
@keyup.enter="submitCreate"
|
||||
/>
|
||||
<input v-model.number="createSortOrder" type="number" class="sort-input" aria-label="排序" />
|
||||
<button class="btn" type="button" :disabled="!canCreate" @click="submitCreate">
|
||||
{{ creating ? '新建中...' : '新建分组' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="errorText" class="group-error">{{ errorText }}</p>
|
||||
<p v-else-if="loading" class="group-tip">加载中...</p>
|
||||
|
||||
<ul class="group-list">
|
||||
<li v-for="group in groups" :key="group.id" class="group-row">
|
||||
<template v-if="editingId === group.id">
|
||||
<input v-model="editingName" type="text" @keyup.enter="submitRename(group)" />
|
||||
<button class="btn btn-small" type="button" :disabled="saving" @click="submitRename(group)">保存</button>
|
||||
<button class="btn btn-secondary btn-small" type="button" @click="cancelRename">取消</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="group-name" :title="group.name">{{ group.name }}</span>
|
||||
<span class="group-meta">排序 {{ group.sortOrder }} · {{ group.productCount }} 个商品</span>
|
||||
<span class="group-actions">
|
||||
<button class="btn btn-secondary btn-small" type="button" @click="startRename(group)">改名</button>
|
||||
<button class="btn btn-danger btn-small" type="button" :disabled="saving" @click="removeGroup(group)">删除</button>
|
||||
</span>
|
||||
</template>
|
||||
</li>
|
||||
<li v-if="!loading && !groups.length && !errorText" class="group-tip">暂无分组,先新建一个</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2800;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.group-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(560px, 100%);
|
||||
max-height: 84vh;
|
||||
padding: 18px 20px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
}
|
||||
.modal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.modal-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
}
|
||||
.modal-close {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #5b6f83;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.modal-close:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.group-create {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin: 14px 0 10px;
|
||||
}
|
||||
.group-create input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 38px;
|
||||
padding: 7px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.group-create input:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.sort-input {
|
||||
flex: 0 0 88px !important;
|
||||
}
|
||||
.group-error {
|
||||
margin: 0 0 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
}
|
||||
.group-tip {
|
||||
margin: 0 0 8px;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
}
|
||||
.group-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
border-top: 1px solid #e7eef5;
|
||||
}
|
||||
.group-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 4px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.group-row input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 34px;
|
||||
padding: 5px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
}
|
||||
.group-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #24384d;
|
||||
}
|
||||
.group-meta {
|
||||
flex: none;
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.group-actions {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-small {
|
||||
min-height: 32px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn-danger {
|
||||
background: #ffffff;
|
||||
color: #a04432;
|
||||
border-color: #e4b3a8;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: #fdf1ef;
|
||||
border-color: #d08a7b;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,191 @@
|
||||
/** 京东数据库查询适配(v1.4 Phase 5):GET /api/admin/jd-products + 分组端点 /api/admin/jd-product-groups。
|
||||
* 只读列表+导出+分组管理:公司 tab 的值由本发送口从原始入参自己下传
|
||||
* (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。 */
|
||||
import { http } from '@/api/http'
|
||||
import { errorTextOf, unwrap } from '../../api/envelope.ts'
|
||||
import {
|
||||
toJdProductExportParams,
|
||||
toJdProductListParams,
|
||||
type JdProductExportParams,
|
||||
type JdProductExportQuery,
|
||||
type JdProductListParams,
|
||||
} from './jd-product-filter.ts'
|
||||
import {
|
||||
parseJdProductDetail,
|
||||
parseJdProductPage,
|
||||
type JdProductPageResult,
|
||||
} from './jd-product-model.ts'
|
||||
|
||||
export const JD_PRODUCT_ENDPOINT = '/api/admin/jd-products'
|
||||
export const JD_PRODUCT_GROUP_ENDPOINT = '/api/admin/jd-product-groups'
|
||||
|
||||
export async function fetchJdProductList(
|
||||
params: JdProductListParams,
|
||||
): Promise<JdProductPageResult> {
|
||||
const query = toJdProductListParams(
|
||||
{
|
||||
shopName: params.shopName ?? '',
|
||||
productCode: params.productCode ?? '',
|
||||
titleKeyword: params.titleKeyword ?? '',
|
||||
saleStatus: params.saleStatus ?? '',
|
||||
groupId: params.groupId ?? '',
|
||||
syncedFrom: params.syncedFrom ?? '',
|
||||
syncedTo: params.syncedTo ?? '',
|
||||
},
|
||||
params.page,
|
||||
params.pageSize,
|
||||
)
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
|
||||
return parseJdProductPage(data)
|
||||
}
|
||||
|
||||
/** 详情:GET /api/admin/jd-products/{id}(信封 data=主字段 + attrGroups + attrJsonRaw + images)。 */
|
||||
export async function fetchJdProductDetail(
|
||||
id: number,
|
||||
companyId: number | null,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, { params: query })
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
export interface JdProductExportResult {
|
||||
blob: Blob
|
||||
filename: string
|
||||
}
|
||||
|
||||
/** 从 Content-Disposition 取 filename*(UTF-8 轨,后端 DownloadHeaderUtil 双轨口径),取不到回退常量名。 */
|
||||
function exportFilenameOf(disposition: unknown): string {
|
||||
const raw = typeof disposition === 'string' ? disposition : ''
|
||||
const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(raw)
|
||||
if (star?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(star[1].trim().replace(/^"|"$/g, '')) || '京东数据库.xlsx'
|
||||
} catch {
|
||||
// 编码坏的 filename* 当作没有,走 ASCII 轨或常量名
|
||||
}
|
||||
}
|
||||
const plain = /filename="([^"]+)"/i.exec(raw)
|
||||
return plain?.[1] || '京东数据库.xlsx'
|
||||
}
|
||||
|
||||
/** 导出当前过滤面全量明细:与列表共用同一过滤面取值口(含公司 tab),blob 下载交给页面触发保存。 */
|
||||
export async function exportJdProductList(
|
||||
params: JdProductExportParams,
|
||||
): Promise<JdProductExportResult> {
|
||||
const query: JdProductExportQuery = toJdProductExportParams({
|
||||
shopName: params.shopName ?? '',
|
||||
productCode: params.productCode ?? '',
|
||||
titleKeyword: params.titleKeyword ?? '',
|
||||
saleStatus: params.saleStatus ?? '',
|
||||
groupId: params.groupId ?? '',
|
||||
syncedFrom: params.syncedFrom ?? '',
|
||||
syncedTo: params.syncedTo ?? '',
|
||||
})
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const response = await http.get<Blob>(`${JD_PRODUCT_ENDPOINT}/export`, {
|
||||
params: query,
|
||||
responseType: 'blob',
|
||||
timeout: 120_000,
|
||||
})
|
||||
const disposition = response.headers?.['content-disposition']
|
||||
if (!disposition) {
|
||||
// 没有附件头=服务端回了业务错误信封(HTTP 200 + JSON),把 blob 文本解回错误文案抛给页面
|
||||
const blob = response.data
|
||||
let payload: unknown = null
|
||||
if (blob && typeof blob.text === 'function') {
|
||||
const text = await blob.text()
|
||||
try {
|
||||
payload = JSON.parse(text)
|
||||
} catch {
|
||||
payload = text
|
||||
}
|
||||
}
|
||||
throw new Error(errorTextOf(payload))
|
||||
}
|
||||
return { blob: response.data, filename: exportFilenameOf(disposition) }
|
||||
}
|
||||
|
||||
/** 分组行(GET 列表返回:[{id,name,sortOrder,productCount}])。 */
|
||||
export interface JdProductGroup {
|
||||
id: number
|
||||
name: string
|
||||
sortOrder: number
|
||||
productCount: number
|
||||
}
|
||||
|
||||
/** 分组管理的写入负载(POST / PUT body:{name, sortOrder})。 */
|
||||
export interface JdProductGroupPayload {
|
||||
name: string
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
/** 分组信封是 `{code, message, data}` 三段式:code 非 0 =业务失败,message 是中文文案
|
||||
* (重名等),用 errorTextOf 取出来抛给界面展示(unwrap 只认 success=false,不认 code)。 */
|
||||
function groupDataOf<T>(payload: unknown): T {
|
||||
const record = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : null
|
||||
if (record && typeof record.code === 'number' && record.code !== 0) {
|
||||
throw new Error(errorTextOf(payload))
|
||||
}
|
||||
return unwrap<T>(payload)
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
}
|
||||
|
||||
/** 分组下拉/管理列表;失败由页面自己兜(分组只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(companyId: number | null): Promise<JdProductGroup[]> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT, { params: query })
|
||||
const core = unwrap<unknown>(data)
|
||||
if (!Array.isArray(core)) return []
|
||||
const out: JdProductGroup[] = []
|
||||
for (const raw of core) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOr(record.id, 0)
|
||||
if (id <= 0) continue
|
||||
out.push({
|
||||
id,
|
||||
name: typeof record.name === 'string' ? record.name.trim() : '',
|
||||
sortOrder: numberOr(record.sortOrder ?? record.sort_order, 0),
|
||||
productCount: numberOr(record.productCount ?? record.product_count, 0),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 新建分组;重名等业务失败把后端中文文案抛回(页面直接展示)。 */
|
||||
export async function createJdProductGroup(
|
||||
payload: JdProductGroupPayload,
|
||||
companyId: number | null,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (companyId != null) body.company_id = companyId
|
||||
const { data } = await http.post<unknown>(JD_PRODUCT_GROUP_ENDPOINT, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
|
||||
/** 改名/改排序;业务失败文案同上。 */
|
||||
export async function updateJdProductGroup(
|
||||
id: number,
|
||||
payload: JdProductGroupPayload,
|
||||
companyId: number | null,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (companyId != null) body.company_id = companyId
|
||||
const { data } = await http.put<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
|
||||
/** 删除分组;业务失败文案同上。 */
|
||||
export async function deleteJdProductGroup(id: number, companyId: number | null): Promise<void> {
|
||||
const query: Record<string, number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`, { params: query })
|
||||
groupDataOf<unknown>(data)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/** 京东数据库页筛选纯函数(v1.4 Phase 5):店铺/商品编码/标题关键字/商品状态/分组/同步起止 + snake 分页参数。
|
||||
* 产出与后端契约 §列表 query 逐字对撞:`page`/`page_size`(默认 20、上限 100)、`shop_name`、
|
||||
* `product_code`、`title_keyword`、`sale_status`、`group_id`、`synced_from`/`synced_to`
|
||||
* (ISO yyyy-MM-dd;空白不下发)。
|
||||
* 分页钳制(铁律 15):page < 1 归 1、上限 10_000(后端 CR-18 同值),(page-1)*page_size
|
||||
* 最大 999_900,Number.MAX_SAFE_INTEGER 也不会把乘积顶出安全整数。纯逻辑,node --test 直测。
|
||||
* 公司维不在这里:归一化构造器不认识 company_id(同外观专利 filter 惯例),由 api 发送口从
|
||||
* 原始入参自己下传——取值口由 company-tab-wiring 护栏的发送行钉看守。
|
||||
* 日期默认空字符串:同步台账是累计数据,默认当天会让首屏只剩今天同步的行
|
||||
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
|
||||
import { validIsoDateOrUndefined } from '../asin/asin-filter.ts'
|
||||
|
||||
/** 每页条数默认 20(v1.4 §3.4),上限 100。 */
|
||||
export const JD_PRODUCT_PAGE_SIZE = 20
|
||||
export const JD_PRODUCT_MAX_PAGE_SIZE = 100
|
||||
/** 页码上限:与后端 MAX_PAGE(CR-18 先例,外观专利同值)对齐,两侧不漂。 */
|
||||
export const JD_PRODUCT_MAX_PAGE = 10_000
|
||||
|
||||
/** 商品状态值域(契约口径):筛选为简单文本输入,placeholder 提示值域。 */
|
||||
export const JD_SALE_STATUS_HINT = '上架中/已下架/审核中/草稿'
|
||||
|
||||
export interface JdProductFilterState {
|
||||
/** 店铺名(模糊),空串不限。 */
|
||||
shopName: string
|
||||
/** 商品编码,空串不限。 */
|
||||
productCode: string
|
||||
/** 标题关键字,空串不限。 */
|
||||
titleKeyword: string
|
||||
/** 商品状态:上架中/已下架/审核中/草稿,空串=全部。 */
|
||||
saleStatus: string
|
||||
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
|
||||
groupId: string
|
||||
/** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
syncedFrom: string
|
||||
/** 同步结束日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
syncedTo: string
|
||||
}
|
||||
|
||||
export function createJdProductFilterState(): JdProductFilterState {
|
||||
return { shopName: '', productCode: '', titleKeyword: '', saleStatus: '', groupId: '', syncedFrom: '', syncedTo: '' }
|
||||
}
|
||||
|
||||
/** 是否有任一激活筛选条件。 */
|
||||
export function jdProductFilterActive(state: JdProductFilterState): boolean {
|
||||
if ((state.shopName || '').trim()) return true
|
||||
if ((state.productCode || '').trim()) return true
|
||||
if ((state.titleKeyword || '').trim()) return true
|
||||
if ((state.saleStatus || '').trim()) return true
|
||||
if ((state.groupId || '').trim()) return true
|
||||
if (validIsoDateOrUndefined(state.syncedFrom) || validIsoDateOrUndefined(state.syncedTo)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** 序列化到后端的列表查询参数(snake_case,仅下发非空字段)。 */
|
||||
export interface JdProductQuery {
|
||||
page: number
|
||||
page_size: number
|
||||
shop_name?: string
|
||||
product_code?: string
|
||||
title_keyword?: string
|
||||
sale_status?: string
|
||||
group_id?: number
|
||||
synced_from?: string
|
||||
synced_to?: string
|
||||
/** 公司 tab:白名单构造不点名它,字段只为 api 发送口的 `query.company_id = params.companyId` 存在。 */
|
||||
company_id?: number
|
||||
}
|
||||
|
||||
/** 导出查询参数:与列表同一过滤面、无分页(全量导出由服务侧上限兜住)。 */
|
||||
export interface JdProductExportQuery {
|
||||
shop_name?: string
|
||||
product_code?: string
|
||||
title_keyword?: string
|
||||
sale_status?: string
|
||||
group_id?: number
|
||||
synced_from?: string
|
||||
synced_to?: string
|
||||
/** 公司 tab 同列表口径:白名单构造不点名,由 api 发送口下传。 */
|
||||
company_id?: number
|
||||
}
|
||||
|
||||
/** api 模块的入参:筛选态 + 分页 + 公司值(camel)。 */
|
||||
export interface JdProductListParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
shopName?: string
|
||||
productCode?: string
|
||||
titleKeyword?: string
|
||||
saleStatus?: string
|
||||
groupId?: string
|
||||
syncedFrom?: string
|
||||
syncedTo?: string
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
/** api 导出入口的入参:筛选态 + 公司值(camel,无分页)。 */
|
||||
export interface JdProductExportParams {
|
||||
shopName?: string
|
||||
productCode?: string
|
||||
titleKeyword?: string
|
||||
saleStatus?: string
|
||||
groupId?: string
|
||||
syncedFrom?: string
|
||||
syncedTo?: string
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段);列表与导出共用这一个取值口,
|
||||
* 「导出的过滤面和页签看到的永远同源」由这条单出口保证,不出现两处各算各的。 */
|
||||
function toJdProductFilterQuery(state: JdProductFilterState): JdProductExportQuery {
|
||||
const query: JdProductExportQuery = {}
|
||||
const shopName = (state.shopName || '').trim()
|
||||
if (shopName) query.shop_name = shopName
|
||||
const productCode = (state.productCode || '').trim()
|
||||
if (productCode) query.product_code = productCode
|
||||
const titleKeyword = (state.titleKeyword || '').trim()
|
||||
if (titleKeyword) query.title_keyword = titleKeyword
|
||||
const saleStatus = (state.saleStatus || '').trim()
|
||||
if (saleStatus) query.sale_status = saleStatus
|
||||
const groupId = Number.parseInt((state.groupId || '').trim(), 10)
|
||||
if (Number.isFinite(groupId) && groupId > 0) query.group_id = groupId
|
||||
const syncedFrom = validIsoDateOrUndefined(state.syncedFrom)
|
||||
if (syncedFrom) query.synced_from = syncedFrom
|
||||
const syncedTo = validIsoDateOrUndefined(state.syncedTo)
|
||||
if (syncedTo) query.synced_to = syncedTo
|
||||
return query
|
||||
}
|
||||
|
||||
/** 过滤态 + 分页 → 列表查询参数;空白/非法日期不下发,分页钳制在此单出口(不含公司维)。 */
|
||||
export function toJdProductListParams(
|
||||
state: JdProductFilterState,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
): 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 {
|
||||
page: safePage,
|
||||
page_size: safeSize,
|
||||
...toJdProductFilterQuery(state),
|
||||
}
|
||||
}
|
||||
|
||||
/** 过滤态 → 导出查询参数(无分页;归一规则与列表逐字同源)。 */
|
||||
export function toJdProductExportParams(state: JdProductFilterState): JdProductExportQuery {
|
||||
return toJdProductFilterQuery(state)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
/** 京东数据库列表查询模型(v1.4 Phase 5):解析 JdProductPageVo(camel),纯逻辑零依赖。
|
||||
* camel 为正、snake 容错(与外观专利/去重页模型同形),缺 id 弃行。
|
||||
* 纯函数、无框架依赖(envelope 只借纯 unwrap),node --test 可直测。 */
|
||||
import { unwrap } from '../../api/envelope.ts'
|
||||
|
||||
/** 京东商品列表行(后端 JdProductItemVo,camel 为正)。 */
|
||||
export interface JdProductItem {
|
||||
id: number
|
||||
shopId: number | null
|
||||
shopName: string
|
||||
productCode: string
|
||||
skuId: string
|
||||
title: string
|
||||
brand: string
|
||||
categoryPath: string
|
||||
priceMin: string
|
||||
priceMax: string
|
||||
stockTotal: number | null
|
||||
/** 上架中/已下架/审核中/草稿。 */
|
||||
saleStatus: string
|
||||
listTab: string
|
||||
jdUpdatedAt: string
|
||||
mainImageUrl: string
|
||||
attrCount: number | null
|
||||
imageCount: number | null
|
||||
groupId: number | null
|
||||
groupName: string
|
||||
syncedAt?: string
|
||||
}
|
||||
|
||||
export interface JdProductPageResult {
|
||||
items: JdProductItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 前端首屏默认容量(与 filter 侧 JD_PRODUCT_PAGE_SIZE 同值 20)。 */
|
||||
export const JD_PRODUCT_DEFAULT_SIZE = 20
|
||||
|
||||
export function emptyJdProductPage(): JdProductPageResult {
|
||||
return { items: [], total: 0, page: 1, pageSize: JD_PRODUCT_DEFAULT_SIZE }
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 价格区间展示:min/max 都空为 -,只空一侧给单值。 */
|
||||
export function jdPriceRange(item: Pick<JdProductItem, 'priceMin' | 'priceMax'>): string {
|
||||
const min = (item.priceMin || '').trim()
|
||||
const max = (item.priceMax || '').trim()
|
||||
if (min && max) return min === max ? min : `${min} ~ ${max}`
|
||||
return min || max || ''
|
||||
}
|
||||
|
||||
/** 解析单行;缺 id 视为无效。camel 为正、snake 容错。 */
|
||||
export function toJdProductItem(raw: unknown): JdProductItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOrNull(record.id)
|
||||
if (id === null) return null
|
||||
return {
|
||||
id,
|
||||
shopId: numberOrNull(record.shopId ?? record.shop_id),
|
||||
shopName: text(record.shopName ?? record.shop_name),
|
||||
productCode: text(record.productCode ?? record.product_code),
|
||||
skuId: text(record.skuId ?? record.sku_id),
|
||||
title: text(record.title),
|
||||
brand: text(record.brand),
|
||||
categoryPath: text(record.categoryPath ?? record.category_path),
|
||||
priceMin: text(record.priceMin ?? record.price_min),
|
||||
priceMax: text(record.priceMax ?? record.price_max),
|
||||
stockTotal: numberOrNull(record.stockTotal ?? record.stock_total),
|
||||
saleStatus: text(record.saleStatus ?? record.sale_status),
|
||||
listTab: text(record.listTab ?? record.list_tab),
|
||||
jdUpdatedAt: text(record.jdUpdatedAt ?? record.jd_updated_at),
|
||||
mainImageUrl: text(record.mainImageUrl ?? record.main_image_url),
|
||||
attrCount: numberOrNull(record.attrCount ?? record.attr_count),
|
||||
imageCount: numberOrNull(record.imageCount ?? record.image_count),
|
||||
groupId: numberOrNull(record.groupId ?? record.group_id),
|
||||
groupName: text(record.groupName ?? record.group_name),
|
||||
syncedAt: text(record.syncedAt ?? record.synced_at) || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化分页负载(信封或已解包 VO)为前端结果;缺省字段回默认。 */
|
||||
export function parseJdProductPage(payload: unknown): JdProductPageResult {
|
||||
const out = emptyJdProductPage()
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object') return out
|
||||
const record = core as Record<string, unknown>
|
||||
if (Array.isArray(record.items)) {
|
||||
out.items = record.items
|
||||
.map((raw) => toJdProductItem(raw))
|
||||
.filter((item): item is JdProductItem => item !== null)
|
||||
}
|
||||
if (typeof record.total === 'number') out.total = Math.floor(record.total)
|
||||
if (typeof record.page === 'number' && record.page >= 1) out.page = Math.floor(record.page)
|
||||
const rawSize = record.pageSize ?? record.page_size
|
||||
if (typeof rawSize === 'number' && rawSize >= 1) out.pageSize = Math.floor(rawSize)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 详情属性块:attrGroups[{groupName, attrs:[{key,label,value}]}]。 */
|
||||
export interface JdProductAttrEntry {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface JdProductAttrGroup {
|
||||
groupName: string
|
||||
attrs: JdProductAttrEntry[]
|
||||
}
|
||||
|
||||
/** 详情图片:images[{imageType, attrName, sortNo, url, byteSize, width, height}]。 */
|
||||
export interface JdProductImage {
|
||||
imageType: string
|
||||
attrName: string
|
||||
sortNo: number
|
||||
url: string
|
||||
byteSize: number | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
}
|
||||
|
||||
export interface JdProductDetail {
|
||||
item: JdProductItem
|
||||
attrGroups: JdProductAttrGroup[]
|
||||
images: JdProductImage[]
|
||||
/** attrGroups 解析失败时的原始 JSON 兜底(界面原样展示,不静默吞)。 */
|
||||
attrJsonRaw: string
|
||||
}
|
||||
|
||||
/** 归一化 attrGroups(camel/snake 同级容错),非法项跳过、块名缺省归「属性」。 */
|
||||
function toAttrGroups(raw: unknown): JdProductAttrGroup[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: JdProductAttrGroup[] = []
|
||||
for (const groupRaw of raw) {
|
||||
if (!groupRaw || typeof groupRaw !== 'object') continue
|
||||
const group = groupRaw as Record<string, unknown>
|
||||
const groupName = text(group.groupName ?? group.group_name) || '属性'
|
||||
const attrsRaw = group.attrs
|
||||
if (!Array.isArray(attrsRaw)) continue
|
||||
const attrs: JdProductAttrEntry[] = []
|
||||
for (const attrRaw of attrsRaw) {
|
||||
if (!attrRaw || typeof attrRaw !== 'object') continue
|
||||
const attr = attrRaw as Record<string, unknown>
|
||||
attrs.push({
|
||||
key: text(attr.key),
|
||||
label: text(attr.label),
|
||||
value: text(attr.value),
|
||||
})
|
||||
}
|
||||
out.push({ groupName, attrs })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 归一化 images;缺 url 弃行(界面没有可展示/可打开的目标),sortNo 缺省 0。 */
|
||||
function toImages(raw: unknown): JdProductImage[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: JdProductImage[] = []
|
||||
for (const imageRaw of raw) {
|
||||
if (!imageRaw || typeof imageRaw !== 'object') continue
|
||||
const image = imageRaw as Record<string, unknown>
|
||||
const url = text(image.url)
|
||||
if (!url) continue
|
||||
out.push({
|
||||
imageType: text(image.imageType ?? image.image_type),
|
||||
attrName: text(image.attrName ?? image.attr_name),
|
||||
sortNo: numberOrNull(image.sortNo ?? image.sort_no) ?? 0,
|
||||
url,
|
||||
byteSize: numberOrNull(image.byteSize ?? image.byte_size),
|
||||
width: numberOrNull(image.width),
|
||||
height: numberOrNull(image.height),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 解析详情负载(信封或已解包 VO);attrGroups 解析不出时回 attrJsonRaw 原文兜底。 */
|
||||
export function parseJdProductDetail(payload: unknown): JdProductDetail {
|
||||
const core = unwrap<unknown>(payload)
|
||||
const record = core && typeof core === 'object' ? (core as Record<string, unknown>) : {}
|
||||
const item = toJdProductItem(record) ?? {
|
||||
id: 0,
|
||||
shopId: null,
|
||||
shopName: '',
|
||||
productCode: '',
|
||||
skuId: '',
|
||||
title: '',
|
||||
brand: '',
|
||||
categoryPath: '',
|
||||
priceMin: '',
|
||||
priceMax: '',
|
||||
stockTotal: null,
|
||||
saleStatus: '',
|
||||
listTab: '',
|
||||
jdUpdatedAt: '',
|
||||
mainImageUrl: '',
|
||||
attrCount: null,
|
||||
imageCount: null,
|
||||
groupId: null,
|
||||
groupName: '',
|
||||
}
|
||||
const attrGroups = toAttrGroups(record.attrGroups ?? record.attr_groups)
|
||||
const attrJsonRaw = typeof record.attrJsonRaw === 'string'
|
||||
? record.attrJsonRaw
|
||||
: typeof record.attr_json_raw === 'string' ? record.attr_json_raw : ''
|
||||
return {
|
||||
item,
|
||||
attrGroups,
|
||||
images: toImages(record.images),
|
||||
attrJsonRaw,
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') },
|
||||
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') },
|
||||
{ path: 'patent-center/clean-items', menuKey: 'admin_appearance_patent_clean_items', title: '外观专利数据库', companyScoped: true, load: () => import('@/pages/patent/AppearancePatentCleanItemsPage.vue') },
|
||||
{ path: 'jd-center/database', menuKey: 'admin_jd_database', title: '京东数据库', companyScoped: true, load: () => import('@/pages/jd/JdDatabasePage.vue') },
|
||||
]
|
||||
|
||||
export function routeOf(page: AdminPageDef): RouteRecordRaw {
|
||||
|
||||
@@ -15,6 +15,8 @@ const BRAND_GATING_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src',
|
||||
'V174__restore_admin_brand_gating_menu.sql')
|
||||
const KEYWORD_USAGE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
|
||||
'V175__move_gating_and_add_keyword_usage_menu.sql')
|
||||
const JD_DATABASE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
|
||||
'V196__jd_database_menu.sql')
|
||||
|
||||
interface MigrationMenu {
|
||||
name: string
|
||||
@@ -95,3 +97,24 @@ test('V175 新增的关键词使用记录菜单 key 必须在路由注册表登
|
||||
assert.ok(sql.includes('SET col.`parent_id` = grp.`id`'), 'V175 必须把品牌Gating库迁到店铺管理组')
|
||||
assert.ok(sql.includes('col.`sort_order` = 85'), '品牌Gating库排序应为 85')
|
||||
})
|
||||
|
||||
test('V196 新增的京东数据库菜单 key 必须在路由注册表登记', () => {
|
||||
const sql = readFileSync(JD_DATABASE_MIGRATION, 'utf8')
|
||||
const menus = menusInsertedBy(sql)
|
||||
const insertCount = (sql.match(/INSERT INTO `columns`/g) || []).length
|
||||
assert.ok(menus.length > 0, 'V196 应当插入后台菜单,一条都没解析出来说明正则失效')
|
||||
assert.equal(menus.length, insertCount, `解析到 ${menus.length} 条,但迁移有 ${insertCount} 条 INSERT INTO columns`)
|
||||
|
||||
const menu = menus.find((item) => item.columnKey === 'admin_jd_database')
|
||||
assert.ok(menu, 'V196 必须插入 admin_jd_database 菜单')
|
||||
const page = adminPages.find((item) => item.menuKey === 'admin_jd_database')
|
||||
assert.ok(page, 'routes.ts 必须有 admin_jd_database 页面,否则菜单点进去 404')
|
||||
assert.equal(page.path, menu.routePath, '库里的 route_path 应与注册表路径一致')
|
||||
assert.equal(page.title, menu.name, '页面标题应与菜单名一致')
|
||||
assert.equal(page.companyScoped, true, '京东数据库按公司 tab 取数')
|
||||
|
||||
// 每公司一套树(公司 1 模板行 + 其余公司复制),挂数据管理组、排序 68(V190 外观专利占 67)。
|
||||
assert.ok(sql.includes("grp.`column_key` = 'admin_group_data'"), 'V196 必须把京东数据库挂到数据管理组')
|
||||
assert.ok(/'京东数据库', 'admin_jd_database', 'admin', 'jd-center\/database', 68/.test(sql), '京东数据库排序应为 68')
|
||||
assert.ok(!sql.includes('user_column_permission'), 'V196 不得预插授权行(默认仅超管可见)')
|
||||
})
|
||||
|
||||
@@ -132,6 +132,11 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
|
||||
// 500 够得着自己、够不到隔壁(对平用例逐处从真文件重算,注释过期即红)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'fetchAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items 无侵权只读列表' },
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'exportAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items/export 导出(2026-11-11 客户需求「数据得导出来」,与列表共用同一过滤面)' },
|
||||
// ↓ 批次 8(2026-11-14 v1.4 京东数据库):京麦店铺商品采集落库的只读镜像,归属物化在行
|
||||
// company_id 列(V193,同外观专利 V189 形状)⇒ 后端正门 readCompanyIdOrOwn。列表与导出
|
||||
// 共用同一过滤面,塞键行与外观专利逐字同行,但分属不同文件 ⇒ (文件, 整行) 各成一组。
|
||||
{ menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /jd-products 京东数据库只读列表' },
|
||||
{ menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'exportJdProductList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /jd-products/export 京东数据库导出(与列表共用同一过滤面)' },
|
||||
]
|
||||
|
||||
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
|
||||
@@ -255,6 +260,8 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
admin_columns: pinsFor('admin_columns'),
|
||||
// 批次 7(v1.3 无侵权只读页):同样由 SEND_POINTS 现算——只有一个发送口(列表)。
|
||||
admin_appearance_patent_clean_items: pinsFor('admin_appearance_patent_clean_items'),
|
||||
// 批次 8(v1.4 京东数据库):列表 + 导出两口,由 SEND_POINTS 现算。
|
||||
admin_jd_database: pinsFor('admin_jd_database'),
|
||||
}
|
||||
|
||||
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
|
||||
@@ -353,8 +360,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
|
||||
// ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 7 + 批次 3 的 4 + 批次 4 的 1 + 批次 5 的 1 + 批次 6 的 3;
|
||||
// 批次 2 原 12 条里的品牌库 1 条 + 商品类目 4 条随 2026-10-06「这两页退回全平台共享」摘掉)。
|
||||
// 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
|
||||
assert.ok(SEND_POINTS.length >= 21,
|
||||
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 = 26 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
assert.ok(SEND_POINTS.length >= 27,
|
||||
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 + 批次 8 v1.4 京东数据库列表/导出 2 条 = 28 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
for (const p of SEND_POINTS) {
|
||||
const shape = pointShape(p)
|
||||
const compliant = pointCompliant(p)
|
||||
@@ -386,8 +393,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
|
||||
if (hit) hit.pinned += 1
|
||||
else grouped.set(key, { file: p.file, line: p.line, pinned: 1 })
|
||||
}
|
||||
assert.equal(grouped.size, 19,
|
||||
`发送口表按 (文件, 整行) 应聚成 19 组(26 处发送口,批次 7 的列表/导出/主管聚合/按主管删除逐字同行走同一组),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
|
||||
assert.equal(grouped.size, 20,
|
||||
`发送口表按 (文件, 整行) 应聚成 20 组(28 处发送口,批次 7 的列表/导出/主管聚合/按主管删除与批次 8 的京东列表/导出逐字同行各走同一组),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
|
||||
for (const g of grouped.values()) {
|
||||
const actual = occurrences(stripComments(read(g.file)), g.line)
|
||||
assert.equal(g.pinned, actual,
|
||||
@@ -743,6 +750,19 @@ const WATCH_BODY_PINS: ReadonlyArray<{
|
||||
{ file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
|
||||
],
|
||||
},
|
||||
// ↓ 批次 8(2026-11-14 v1.4 京东数据库):店铺/商品编码/标题是按行集筛的自由文本,分组选项集是
|
||||
// 公司隔离的(/jd-product-groups 带 company_id)⇒ 上一家的筛选值与 groupId 在新一家的行集/选项集
|
||||
// 里不存在,切 tab 必清且选项重取;页码回 1 同外观专利页。
|
||||
{
|
||||
file: 'src/pages/jd/JdDatabasePage.vue',
|
||||
token: "filter.shopName = ''; filter.productCode = ''; filter.titleKeyword = ''; filter.saleStatus = ''; filter.groupId = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadGroupOptions(); void load()",
|
||||
why: '店铺/商品编码/标题是按行集筛的自由文本,上一家的值在新一家的行里不存在 ⇒ 切 tab 后首屏被筛成「暂无商品」,'
|
||||
+ '而输入框还显示着上一家填的值;分组选项集是公司隔离的,上一家选的 groupId 在新一家的选项里不存在,'
|
||||
+ '同罪必清且选项重取;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据',
|
||||
premise: [
|
||||
{ file: 'src/pages/jd/jd-product-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */
|
||||
@@ -751,9 +771,9 @@ function watchStatement(source: string): string | null {
|
||||
return m ? m[0] : null
|
||||
}
|
||||
|
||||
test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页 + 批次 7 一页)', () => {
|
||||
assert.ok(WATCH_BODY_PINS.length >= 10,
|
||||
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页共 11 对)`
|
||||
test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页 + 批次 7 一页 + 批次 8 一页)', () => {
|
||||
assert.ok(WATCH_BODY_PINS.length >= 11,
|
||||
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页 + 批次 8 v1.4 京东数据库页共 12 对)`
|
||||
+ '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守')
|
||||
const pinnedFiles = new Set(WATCH_BODY_PINS.map((pin) => pin.file))
|
||||
for (const pin of WATCH_BODY_PINS) {
|
||||
|
||||
@@ -37,6 +37,9 @@ const EXEMPT = new Set([
|
||||
// 2026-11-10(v1.3):外观专利无侵权数据页与去重库同形状——出表成功自动同步的累计台账,
|
||||
// 默认当天会让首屏只剩今天同步的行,历史同步行整批"消失"。
|
||||
'src/pages/patent/AppearancePatentCleanItemsPage.vue',
|
||||
// 2026-11-14(v1.4 Phase 5):京东数据库页与外观专利页同形状——京东商品同步落库的累计台账,
|
||||
// 默认当天会让首屏只剩今天同步的行(页面注释与 filter 工厂同口径留空)。
|
||||
'src/pages/jd/JdDatabasePage.vue',
|
||||
// 2026-10-05(V146):两处是「到期时间」表单字段而非列表筛选——留空 = 永不过期,
|
||||
// 是有业务语义的默认值,绝不能默认当天(默认当天等于建号即过期)。
|
||||
'src/pages/account/CreateUserDialog.vue',
|
||||
|
||||
@@ -231,11 +231,11 @@ test('orderedPair 只在两端都有值且倒挂时交换', () => {
|
||||
})
|
||||
|
||||
test('分母硬钉:四面控件实例数与成对数(扫描失明即红)', () => {
|
||||
assert.equal(adminCtrls.length, 21, '后管实例数变了,先复算普查再改这里(v1.3 外观专利无侵权数据页再落一对起止=2 实例)')
|
||||
assert.equal(adminCtrls.length, 23, '后管实例数变了,先复算普查再改这里(v1.4 京东数据库页同步时间起止再落一对=2 实例)')
|
||||
assert.equal(userCtrls.length, 2, '用户端实例数变了')
|
||||
assert.equal(finCtrls.length, 30, '财务系统实例数变了')
|
||||
assert.equal(mxCtrls.length, 4, '麦象实例数变了')
|
||||
assert.equal(pairCount(adminCtrls), 9, '后管成对区间应为 9(v1.3 外观专利无侵权数据页再落一对)')
|
||||
assert.equal(pairCount(adminCtrls), 10, '后管成对区间应为 10(v1.4 京东数据库页同步时间起止再落一对)')
|
||||
assert.equal(pairCount(finCtrls), 11, '财务系统成对区间应为 11')
|
||||
assert.equal(pairCount(mxCtrls), 2, '麦象成对区间应为 2')
|
||||
assert.equal(pairCount(userCtrls), 0, '用户端出现成对区间说明新加了两个单只控件')
|
||||
|
||||
@@ -15,7 +15,7 @@ import { adminPages } from '../src/router/routes.ts'
|
||||
const MENU_KEY = 'admin_jd_database'
|
||||
const ROUTE = 'jd-center/database'
|
||||
|
||||
test('routes 注册表出现京东数据库页面且公司隔离', { skip: 'Pending Phase 5: 京东数据库页面落地后激活' }, () => {
|
||||
test('routes 注册表出现京东数据库页面且公司隔离', () => {
|
||||
const page = adminPages.find((item) => item.menuKey === MENU_KEY)
|
||||
assert.ok(page, `routes.ts 缺 menuKey=${MENU_KEY} 的注册行`)
|
||||
assert.equal(page.path, ROUTE, 'route_path 必须与 V196 菜单一侧一致')
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* 京东数据库页纯逻辑契约(v1.4 Phase 5)—— node --test 直跑(纯函数零依赖)。
|
||||
*
|
||||
* 不用 readFileSync/readSource/globSync 读点:source-pin-ratchet 对台账外新文件带读点即红,
|
||||
* 本文件只 import 被测纯函数。
|
||||
*
|
||||
* 覆盖:
|
||||
* 1. **snake 参数形状**:toJdProductListParams 产出 `page`/`page_size`(默认 20、上限 100)、
|
||||
* `shop_name`/`product_code`/`title_keyword`/`sale_status`/`group_id`/`synced_from`/`synced_to`
|
||||
* (ISO yyyy-MM-dd;空白不下发;groupId 空串→不带、有值→snake group_id);分页钳制(铁律 15)。
|
||||
* 2. **详情解析**:parseJdProductDetail 解析 attrGroups/images(camel 为正 snake 容错、缺 url 弃行),
|
||||
* attrGroups 解析不出时 attrJsonRaw 原文兜底;列表行解析缺 id 弃行。
|
||||
*
|
||||
* 跑法:`node --test tests/jd-product-group.test.ts`
|
||||
*/
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
JD_PRODUCT_MAX_PAGE,
|
||||
createJdProductFilterState,
|
||||
toJdProductExportParams,
|
||||
toJdProductListParams,
|
||||
} from '../src/pages/jd/jd-product-filter.ts'
|
||||
import {
|
||||
jdPriceRange,
|
||||
parseJdProductDetail,
|
||||
parseJdProductPage,
|
||||
toJdProductItem,
|
||||
} from '../src/pages/jd/jd-product-model.ts'
|
||||
|
||||
test('京东列表参数——snake 形状:groupId 空→不带、有值→group_id,日期空白/非法不下发', () => {
|
||||
const full = toJdProductListParams(
|
||||
{
|
||||
shopName: ' 旗舰自营店 ',
|
||||
productCode: ' JD-10086 ',
|
||||
titleKeyword: ' 保温杯 ',
|
||||
saleStatus: '上架中',
|
||||
groupId: ' 7 ',
|
||||
syncedFrom: '2026-11-01',
|
||||
syncedTo: '2026-11-09',
|
||||
},
|
||||
2,
|
||||
20,
|
||||
)
|
||||
assert.deepEqual(full, {
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
shop_name: '旗舰自营店',
|
||||
product_code: 'JD-10086',
|
||||
title_keyword: '保温杯',
|
||||
sale_status: '上架中',
|
||||
group_id: 7,
|
||||
synced_from: '2026-11-01',
|
||||
synced_to: '2026-11-09',
|
||||
})
|
||||
|
||||
// 全空态只有分页两项;脏值(非数字分组、非法日期)同罪不下发。
|
||||
const blank = toJdProductListParams(createJdProductFilterState(), 1, 20)
|
||||
assert.deepEqual(blank, { page: 1, page_size: 20 })
|
||||
assert.equal('group_id' in blank, false, 'groupId 空串不带 group_id')
|
||||
const dirty = toJdProductListParams(
|
||||
{ shopName: ' ', productCode: '', titleKeyword: '', saleStatus: '', groupId: 'abc', syncedFrom: '2026/11/01', syncedTo: 'not-a-date' },
|
||||
1,
|
||||
20,
|
||||
)
|
||||
assert.deepEqual(dirty, { page: 1, page_size: 20 }, '脏值不下发')
|
||||
|
||||
// 导出与列表同一过滤面单出口(无分页)。
|
||||
const state = { shopName: '旗舰自营店', productCode: '', titleKeyword: '', saleStatus: '已下架', groupId: '7', syncedFrom: '2026-11-01', syncedTo: '' }
|
||||
const list = toJdProductListParams(state, 3, 20)
|
||||
const exp = toJdProductExportParams(state)
|
||||
for (const key of Object.keys(exp) as Array<keyof typeof exp>) {
|
||||
assert.equal((list as Record<string, unknown>)[key], exp[key], `导出与列表的 ${key} 必须同源`)
|
||||
}
|
||||
assert.equal('page' in exp, false, '导出参数无分页')
|
||||
assert.deepEqual(exp, { shop_name: '旗舰自营店', sale_status: '已下架', group_id: 7, synced_from: '2026-11-01' })
|
||||
})
|
||||
|
||||
test('京东列表参数——page 钳制防 (page-1)*page_size 溢出(铁律 15)', () => {
|
||||
const low = toJdProductListParams(createJdProductFilterState(), 0, 0)
|
||||
assert.equal(low.page, 1, 'page<1 归 1')
|
||||
assert.equal(low.page_size, 20, 'page_size 非法回默认 20')
|
||||
const big = toJdProductListParams(createJdProductFilterState(), 3, 500)
|
||||
assert.equal(big.page_size, 100, 'page_size 上限 100')
|
||||
|
||||
const extreme = toJdProductListParams(createJdProductFilterState(), Number.MAX_SAFE_INTEGER, 100)
|
||||
assert.equal(extreme.page, JD_PRODUCT_MAX_PAGE)
|
||||
const offset = (extreme.page - 1) * extreme.page_size
|
||||
assert.equal(Number.isSafeInteger(offset), true, `(page-1)*page_size=${offset} 必须留在安全整数域`)
|
||||
assert.equal(offset, 999_900)
|
||||
})
|
||||
|
||||
test('详情解析——attrGroups/images 结构化解析(snake 容错、缺 url 弃行)', () => {
|
||||
const detail = parseJdProductDetail({
|
||||
code: 0,
|
||||
message: 'ok',
|
||||
data: {
|
||||
id: 42,
|
||||
title: '304不锈钢保温杯',
|
||||
sale_status: '上架中',
|
||||
attrGroups: [
|
||||
{
|
||||
groupName: '规格',
|
||||
attrs: [
|
||||
{ key: 'capacity', label: '容量', value: '500ml' },
|
||||
{ key: 'material', label: '', value: '304不锈钢' },
|
||||
],
|
||||
},
|
||||
{ group_name: '其他', attrs: [{ key: 'color', label: '颜色', value: '白色' }] },
|
||||
],
|
||||
images: [
|
||||
{ imageType: 'MAIN', attrName: '', sortNo: 1, url: 'https://img.example/main.jpg', width: 800, height: 800 },
|
||||
{ image_type: 'ATTR', attrName: '白色', sortNo: 2, url: 'https://img.example/white.jpg' },
|
||||
{ imageType: 'ATTR', attrName: '', sortNo: 3, url: 'https://img.example/attr2.jpg' },
|
||||
{ imageType: 'DETAIL', sortNo: 4, url: '' }, // 缺 url 弃行
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
assert.equal(detail.item.id, 42)
|
||||
assert.equal(detail.item.title, '304不锈钢保温杯')
|
||||
assert.equal(detail.item.saleStatus, '上架中', 'snake 容错')
|
||||
assert.equal(detail.attrGroups.length, 2, '两个属性块')
|
||||
assert.equal(detail.attrGroups[0].groupName, '规格')
|
||||
assert.equal(detail.attrGroups[0].attrs[0].label, '容量')
|
||||
assert.equal(detail.attrGroups[1].groupName, '其他', 'group_name snake 容错')
|
||||
assert.equal(detail.images.length, 3, '缺 url 的 DETAIL 图弃行')
|
||||
assert.equal(detail.images[1].imageType, 'ATTR', 'image_type snake 容错')
|
||||
assert.equal(detail.images[1].attrName, '白色')
|
||||
assert.equal(detail.images[1].sortNo, 2)
|
||||
assert.equal(detail.images[2].attrName, '', 'attrName 缺省空串')
|
||||
assert.equal(detail.attrJsonRaw, '', '结构化解析成功时不需要原文兜底')
|
||||
})
|
||||
|
||||
test('详情解析——attrGroups 缺失时 attrJsonRaw 原文兜底;信封外裸负载同口径', () => {
|
||||
const raw = '{"规格":{"容量":"500ml"}}'
|
||||
const detail = parseJdProductDetail({ id: 7, attrJsonRaw: raw })
|
||||
assert.equal(detail.item.id, 7)
|
||||
assert.deepEqual(detail.attrGroups, [], 'attrGroups 解析不出为空')
|
||||
assert.equal(detail.attrJsonRaw, raw, '原文兜底字段原样透传(界面展示,不静默吞)')
|
||||
assert.deepEqual(detail.images, [])
|
||||
|
||||
// 非法负载不抛:整包垃圾回空详情(id 0),attrJsonRaw 留空。
|
||||
const junk = parseJdProductDetail('not-an-object')
|
||||
assert.equal(junk.item.id, 0)
|
||||
assert.equal(junk.attrJsonRaw, '')
|
||||
})
|
||||
|
||||
test('列表行解析——camel 为正 snake 容错、缺 id 弃行、价格区间拼装', () => {
|
||||
const page = parseJdProductPage({
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
shopId: 3,
|
||||
shopName: '旗舰自营店',
|
||||
productCode: 'JD-10086',
|
||||
priceMin: '12.90',
|
||||
priceMax: '15.90',
|
||||
stockTotal: 500,
|
||||
saleStatus: '上架中',
|
||||
groupId: 7,
|
||||
groupName: '甲组',
|
||||
syncedAt: '2026-11-12 09:00:00',
|
||||
},
|
||||
{ id: 'not-a-number', title: '缺 id 弃行' },
|
||||
{ shop_name: 'snake 行也缺 id,弃' },
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
},
|
||||
})
|
||||
assert.equal(page.items.length, 1, '三条原始行里两条缺有效 id,只留 1 行')
|
||||
const row = page.items[0]
|
||||
assert.equal(row.shopName, '旗舰自营店')
|
||||
assert.equal(row.groupId, 7)
|
||||
assert.equal(row.groupName, '甲组')
|
||||
assert.equal(jdPriceRange(row), '12.90 ~ 15.90', 'min/max 都有给区间')
|
||||
assert.equal(jdPriceRange({ priceMin: '12.90', priceMax: '' }), '12.90', '只空一侧给单值')
|
||||
assert.equal(jdPriceRange({ priceMin: '', priceMax: '' }), '', '全空为空串(界面展示 -)')
|
||||
|
||||
// snake 行同口径 + 缺省回默认。
|
||||
const snakePage = parseJdProductPage({ data: { items: [{ id: 9, shop_name: 'B店', main_image_url: 'https://img/x.jpg' }], total: 1, page: 2, page_size: 5 } })
|
||||
const snakeRow = toJdProductItem({ id: 9, shop_name: 'B店', main_image_url: 'https://img/x.jpg' })
|
||||
assert.equal(snakeRow?.mainImageUrl, 'https://img/x.jpg')
|
||||
assert.equal(snakePage.pageSize, 5)
|
||||
})
|
||||
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* 京东数据库页(v1.4 Phase 5)的挂载契约。
|
||||
*
|
||||
* 形态:panel-box + 筛选行(店铺/商品编码/标题关键字/商品状态/分组/同步起止 date 对)+
|
||||
* 查询/导出/重置/管理分组 + 自绘明细表(点行开详情抽屉)+ OldPagination;
|
||||
* 公司 tab 切换=清筛选重取(company-tab-wiring 同口径)。
|
||||
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/jd-database-page.mount.test.ts`
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia, type Pinia } from 'pinia'
|
||||
|
||||
import JdDatabasePage from '@/pages/jd/JdDatabasePage.vue'
|
||||
import JdProductGroupDialog from '@/pages/jd/JdProductGroupDialog.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
|
||||
const jdApi = vi.hoisted(() => ({
|
||||
JD_PRODUCT_ENDPOINT: '/api/admin/jd-products',
|
||||
JD_PRODUCT_GROUP_ENDPOINT: '/api/admin/jd-product-groups',
|
||||
fetchJdProductList: vi.fn(),
|
||||
fetchJdProductDetail: vi.fn(),
|
||||
exportJdProductList: vi.fn(),
|
||||
fetchJdProductGroups: vi.fn(),
|
||||
createJdProductGroup: vi.fn(),
|
||||
updateJdProductGroup: vi.fn(),
|
||||
deleteJdProductGroup: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
|
||||
|
||||
function item(id: number, over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
shopId: 3,
|
||||
shopName: '旗舰自营店',
|
||||
productCode: `JD-100${id}`,
|
||||
skuId: `SKU-${id}`,
|
||||
title: '304不锈钢保温杯大容量便携',
|
||||
brand: '锅宝',
|
||||
categoryPath: '家居 > 厨具 > 保温杯',
|
||||
priceMin: '12.90',
|
||||
priceMax: '15.90',
|
||||
stockTotal: 500,
|
||||
saleStatus: '上架中',
|
||||
listTab: 'search',
|
||||
jdUpdatedAt: '2026-11-10 08:30:00',
|
||||
mainImageUrl: `https://img.example/main-${id}.jpg`,
|
||||
attrCount: 6,
|
||||
imageCount: 9,
|
||||
groupId: 7,
|
||||
groupName: '甲组',
|
||||
syncedAt: '2026-11-12 09:00:00',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
let pinia: Pinia
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
useCompanyTabStore().setActiveId(1)
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([])
|
||||
})
|
||||
|
||||
async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
|
||||
jdApi.fetchJdProductList.mockImplementation(() => Promise.resolve(payload))
|
||||
const wrapper = mount(JdDatabasePage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
it('挂载后按首屏分页参数取列表(pageSize 默认 20、带公司 tab),行数=本页条数', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 })
|
||||
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1)
|
||||
const firstCall = jdApi.fetchJdProductList.mock.calls[0][0]
|
||||
expect(firstCall.page).toBe(1)
|
||||
expect(firstCall.pageSize).toBe(20)
|
||||
expect(firstCall.companyId).toBe(1)
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(3)
|
||||
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
|
||||
})
|
||||
|
||||
it('行内容=主图/店铺/商品编码/标题/品牌/价格区间/库存/状态/分组/京东更新时间/同步时间(11 列)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
|
||||
expect(cells).toHaveLength(11)
|
||||
expect(cells[1].text()).toBe('旗舰自营店')
|
||||
expect(cells[2].text()).toBe('JD-1001')
|
||||
expect(cells[3].text()).toContain('304不锈钢保温杯')
|
||||
expect(cells[4].text()).toBe('锅宝')
|
||||
expect(cells[5].text()).toBe('12.90 ~ 15.90', '价格区间=min ~ max')
|
||||
expect(cells[6].text()).toBe('500')
|
||||
expect(cells[7].text()).toBe('上架中')
|
||||
expect(cells[8].text()).toBe('甲组')
|
||||
expect(cells[9].text()).not.toBe('-', '京东更新时间格式化展示')
|
||||
expect(cells[10].text()).not.toBe('-', '同步时间格式化展示')
|
||||
expect(wrapper.find('.jd-thumb').exists()).toBe(true, '主图列渲染缩略图')
|
||||
})
|
||||
|
||||
it('分组读不到的那行展示「未分组」(不猜名字)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[8].text()).toBe('未分组')
|
||||
})
|
||||
|
||||
it('筛选生效:店铺/编码/关键字/状态/分组/起止日期,查询回第一页重发', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
expect(textInputs).toHaveLength(4, '店铺+商品编码+标题关键字+商品状态四个文本筛选框')
|
||||
await textInputs[0].setValue('旗舰自营店')
|
||||
await textInputs[1].setValue('JD-1001')
|
||||
await textInputs[2].setValue('保温杯')
|
||||
await textInputs[3].setValue('上架中')
|
||||
await wrapper.find('select').setValue('7')
|
||||
const dateInputs = wrapper.findAll('input[type="date"]')
|
||||
await dateInputs[0].setValue('2026-11-01')
|
||||
await dateInputs[1].setValue('2026-11-09')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({
|
||||
shopName: '旗舰自营店',
|
||||
productCode: 'JD-1001',
|
||||
titleKeyword: '保温杯',
|
||||
saleStatus: '上架中',
|
||||
groupId: '7',
|
||||
syncedFrom: '2026-11-01',
|
||||
syncedTo: '2026-11-09',
|
||||
page: 1,
|
||||
companyId: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('分组下拉选中即查', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([
|
||||
{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 },
|
||||
{ id: 8, name: '乙组', sortOrder: 1, productCount: 1 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(1)
|
||||
|
||||
const groupSelect = wrapper.find('select')
|
||||
const optionTexts = groupSelect.findAll('option').map((o) => o.text())
|
||||
expect(optionTexts).toContain('全部分组')
|
||||
expect(optionTexts).toContain('甲组')
|
||||
|
||||
const callsBeforeSelect = jdApi.fetchJdProductList.mock.calls.length
|
||||
await groupSelect.setValue('7')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBeforeSelect + 1, '选中分组必须立刻重查')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupId: '7', page: 1 })
|
||||
})
|
||||
|
||||
it('重置把筛选面回空并回第一页重取', async () => {
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
await textInputs[0].setValue('旗舰自营店')
|
||||
await textInputs[2].setValue('保温杯')
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({ shopName: '', titleKeyword: '', page: 1 }, '重置后筛选全空、回第一页')
|
||||
})
|
||||
|
||||
it('翻页与改每页条数都重发请求,改条数回第一页', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 42, page: 2, pageSize: 20 })
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(2)
|
||||
expect(jdApi.fetchJdProductList.mock.calls[1][0].page).toBe(3)
|
||||
|
||||
const sizeSelect = wrapper.find('.page-size-select')
|
||||
await sizeSelect.setValue('50')
|
||||
await flushPromises()
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last.pageSize).toBe(50)
|
||||
expect(last.page).toBe(1, '改每页条数后回第一页')
|
||||
})
|
||||
|
||||
it('导出=当前过滤面全量(含公司 tab 与分组),成功反馈点名落盘文件', async () => {
|
||||
const createObjectURL = vi.fn(() => 'blob:mock-url')
|
||||
const revokeObjectURL = vi.fn()
|
||||
const urlRecord = URL as unknown as Record<string, unknown>
|
||||
Object.defineProperty(URL, 'createObjectURL', { value: createObjectURL, configurable: true, writable: true })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true, writable: true })
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
jdApi.exportJdProductList.mockImplementation(() =>
|
||||
Promise.resolve({ blob: new Blob(['xlsx']), filename: '京东数据库-20261114090000.xlsx' }),
|
||||
)
|
||||
|
||||
try {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(btn, '筛选行必须有「导出」按钮').toBeTruthy()
|
||||
await btn!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(jdApi.exportJdProductList).toHaveBeenCalledTimes(1)
|
||||
const call = jdApi.exportJdProductList.mock.calls[0][0]
|
||||
expect(call).toMatchObject({ shopName: '', groupId: '', companyId: 1 })
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1)
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('已导出', '成功反馈点名落盘文件')
|
||||
} finally {
|
||||
Object.defineProperty(URL, 'createObjectURL', { value: undefined, configurable: true, writable: true })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { value: undefined, configurable: true, writable: true })
|
||||
clickSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('导出失败把服务端业务文案弹出来,不许静默;在途标记复位', async () => {
|
||||
jdApi.exportJdProductList.mockImplementation(() => Promise.reject(new Error('京东商品共 80001 行,超过导出上限 50000 行,请缩小筛选范围后重试')))
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('button').find((b) => b.text() === '导出')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).toContain('超过导出上限')
|
||||
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(btn!.text()).toBe('导出', '失败后在途标记必须复位')
|
||||
expect((btn!.element as HTMLButtonElement).disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('点行打开详情抽屉:按 (id, companyId) 取详情,attrGroups 分块渲染', async () => {
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
item: item(1),
|
||||
attrGroups: [{ groupName: '规格', attrs: [{ key: 'capacity', label: '容量', value: '500ml' }] }],
|
||||
images: [{ imageType: 'MAIN', attrName: '', sortNo: 1, url: 'https://img.example/main-1.jpg', byteSize: null, width: 800, height: 800 }],
|
||||
attrJsonRaw: '',
|
||||
}),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '初始不显示抽屉')
|
||||
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(true)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1, 1)
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('基本信息')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('规格')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('容量')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('500ml')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('主图')
|
||||
})
|
||||
|
||||
it('管理分组弹窗:打开即拉分组列表,变更后刷新分组下拉与列表', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '管理分组')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.group-modal').exists()).toBe(true)
|
||||
// 打开弹窗 = 拉一次分组列表(第 2 次:首屏已拉过一次)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(1)
|
||||
|
||||
// 模拟分组管理里删了一个分组:emit changed → 页面刷新分组下拉与列表(回第一页)
|
||||
wrapper.findComponent(JdProductGroupDialog).vm.$emit('changed')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1, companyId: 1 })
|
||||
})
|
||||
|
||||
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径)', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
await textInputs[0].setValue('旗舰自营店')
|
||||
await textInputs[2].setValue('保温杯')
|
||||
await wrapper.find('select').setValue('7')
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
|
||||
useCompanyTabStore().setActiveId(2)
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last.companyId).toBe(2)
|
||||
expect(last.shopName).toBe('', '切公司必须清掉上一家的店铺名')
|
||||
expect(last.titleKeyword).toBe('', '切公司必须清掉上一家的标题关键字')
|
||||
expect(last.groupId).toBe('', '切公司必须清掉上一家选的分组')
|
||||
expect(last.page).toBe(1)
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(2)
|
||||
})
|
||||
|
||||
it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
|
||||
const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
const tip = empty.find('.empty-tip')
|
||||
expect(tip.exists()).toBe(true)
|
||||
expect(tip.text()).toContain('暂无京东商品数据')
|
||||
empty.unmount()
|
||||
|
||||
jdApi.fetchJdProductList.mockRejectedValue(new Error('上游 502'))
|
||||
const failed = mount(JdDatabasePage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(failed.find('.load-failure-bar').exists()).toBe(true)
|
||||
expect(failed.find('.load-failure-bar').text()).toContain('京东商品列表加载失败')
|
||||
})
|
||||
})
|
||||
@@ -56,6 +56,15 @@ public final class PageDefaults {
|
||||
/** {@link #ADMIN_LIST_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int ADMIN_LIST_PAGE_SIZE_INT = 20;
|
||||
|
||||
/**
|
||||
* 京东数据库后管只读页默认容量 = 20(v1.4 Phase 5,蓝图 §3.2「page_size 默认 20、上限 100」;
|
||||
* 上限钳制在 {@code JdProductQueryService},不在注解上)。
|
||||
*/
|
||||
public static final String JD_PRODUCTS_PAGE_SIZE = "20";
|
||||
|
||||
/** {@link #JD_PRODUCTS_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int JD_PRODUCTS_PAGE_SIZE_INT = 20;
|
||||
|
||||
/** 上架/采集类任务历史列表默认容量 = 50。现存 2 处 {@code page_size}(collect-data、publish)。 */
|
||||
public static final String TASK_LIST_PAGE_SIZE = "50";
|
||||
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.nanri.aiimage.modules.jd.controller;
|
||||
|
||||
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.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.common.support.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 后管「京东数据库」只读页(v1.4 Phase 5)。数据由采集回传同步落表
|
||||
* ({@code JdResultIngestService},覆盖最新),本页只读——列表/详情/导出三个 GET 端点,
|
||||
* 不出表、不改商品行、无导入;分组管理走 {@code AdminJdProductGroupController}(同款鉴权闸)。
|
||||
*
|
||||
* <p>鉴权照外观专利只读页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 →
|
||||
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
|
||||
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。</p>
|
||||
*
|
||||
* <p>公司隔离正门是 {@code readCompanyIdOrOwn}(同外观专利只读页/店铺密钥的表形状:
|
||||
* 归属物化在行 company_id 列、可见集不靠账号/分组)——超管显式传才收窄、不传全量;
|
||||
* 非超管强制本公司(忽略请求传参)。{@code superAdminScopedCompanyId} 对非超管返回 null
|
||||
* =按行 company_id 列查询时把整张表交给每一家(该方法 javadoc 点名的越权形状),不走那道门。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@RequestMapping("/api/admin/jd-products")
|
||||
@Tag(name = "京东数据库", description = "后管只读页:京东店铺商品同步落表数据的分页查询、详情与导出,按分公司隔离。")
|
||||
public class AdminJdProductController {
|
||||
|
||||
private static final String COLUMN_KEY = "admin_jd_database";
|
||||
private static final String ROUTE_PATH = "jd-center/database";
|
||||
private static final String XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
/** 导出文件名时间戳(同外观专利只读页口径),中文文件名的 ASCII 回退由 DownloadHeaderUtil 兜底。 */
|
||||
private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
|
||||
|
||||
private final JdProductQueryService jdProductQueryService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询京东数据库商品", description = "按分公司隔离分页查询同步落表的京东商品;"
|
||||
+ "company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = JdProductPageVo.class)))
|
||||
})
|
||||
public ApiResponse<JdProductPageVo> page(
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "店铺名(包含匹配)") @RequestParam(name = "shop_name", required = false) String shopName,
|
||||
@Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
|
||||
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
|
||||
@Parameter(description = "商品状态(上架中/已下架/审核中/草稿)") @RequestParam(name = "sale_status", required = false) String saleStatus,
|
||||
@Parameter(description = "分组 id") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "同步开始时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
|
||||
@Parameter(description = "同步结束时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 公司隔离正门是 readCompanyIdOrOwn(同外观专利只读页口径):超管显式传才收窄、
|
||||
// 不传全量;非超管强制本公司(忽略请求传参)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
return ApiResponse.success(jdProductQueryService.page(page, pageSize, scopedCompanyId, shopName,
|
||||
productCode, titleKeyword, saleStatus, groupId, syncedFrom, syncedTo));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "商品详情", description = "主字段全量 + attr_json 属性分组(契约形状不识别时落空分组"
|
||||
+ "并把原文放 attrJsonRaw 兜底,AC-7 未识别属性不丢弃)+ 已转存图片(100% 自有域名,AC-4)。"
|
||||
+ "公司隔离与列表同门:越界 id 按不存在拒绝。")
|
||||
public ApiResponse<JdProductDetailVo> detail(
|
||||
@Parameter(description = "商品行 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 详情同样过公司隔离正门:超管不传 company_id = 全量可见;非超管恒为本公司(服务按它收口)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
return ApiResponse.success(jdProductQueryService.detail(id, scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
@Operation(summary = "导出京东数据库 Excel", description = "与分页查询同一过滤面(店铺名/商品编码/标题关键词/"
|
||||
+ "商品状态/分组/同步起止),公司隔离走同一正门:company_id 只对站点超管生效(显式传才收窄,"
|
||||
+ "不传全量),非超管强制本公司。超过导出上限按业务错误拒绝。")
|
||||
public ResponseEntity<byte[]> export(
|
||||
@Parameter(description = "店铺名(包含匹配)") @RequestParam(name = "shop_name", required = false) String shopName,
|
||||
@Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
|
||||
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
|
||||
@Parameter(description = "商品状态") @RequestParam(name = "sale_status", required = false) String saleStatus,
|
||||
@Parameter(description = "分组 id") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "同步开始时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
|
||||
@Parameter(description = "同步结束时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 导出与分页共用 readCompanyIdOrOwn 正门(同 page 的口径注释):绝不让导出绕过页签的公司隔离。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
byte[] bytes = jdProductQueryService.export(scopedCompanyId, shopName, productCode, titleKeyword,
|
||||
saleStatus, groupId, syncedFrom, syncedTo);
|
||||
String filename = "京东数据库-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
|
||||
.contentType(MediaType.parseMediaType(XLSX_CONTENT_TYPE))
|
||||
.contentLength(bytes.length)
|
||||
.body(bytes);
|
||||
}
|
||||
|
||||
private RequestOperator requireJdAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = resolveOperator(request);
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
throw new BusinessException(403, "无权访问京东数据库");
|
||||
}
|
||||
boolean superAdmin = DeviceSessionPolicy.isSuper(adminAuthSupport.currentRole(operator));
|
||||
if (!superAdmin && !hasJdPermission(operator)) {
|
||||
throw new BusinessException(403, "无权访问京东数据库");
|
||||
}
|
||||
return new RequestOperator(operator.getId(), superAdmin, operator);
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveOperator(HttpServletRequest request) {
|
||||
try {
|
||||
return adminAuthSupport.requireUser(request);
|
||||
} catch (BusinessException authFailure) {
|
||||
AdminUserEntity internalOperator = resolveInternalOperator(request);
|
||||
if (internalOperator != null) {
|
||||
return internalOperator;
|
||||
}
|
||||
throw authFailure;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasJdPermission(AdminUserEntity operator) {
|
||||
return permissionMenuService.getUserColumnPermissions(operator.getId(), "admin")
|
||||
.stream()
|
||||
.anyMatch(item -> COLUMN_KEY.equals(item.getColumnKey())
|
||||
|| ROUTE_PATH.equals(item.getRoutePath()));
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
|
||||
if (!isTrustedInternalRequest(request.getHeader("X-Internal-Token"))) {
|
||||
return null;
|
||||
}
|
||||
String rawOperatorId = request.getParameter("operatorId");
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
rawOperatorId = request.getParameter("operator_id");
|
||||
}
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return permissionMenuService.requireUserOperator(Long.parseLong(rawOperatorId.trim()));
|
||||
} catch (NumberFormatException | BusinessException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
|
||||
}
|
||||
|
||||
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
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.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 后管「京东数据库」分组管理(v1.4 Phase 5,R4):新建 / 改名 / 删除 / 下拉列表。
|
||||
*
|
||||
* <p>京东数据库专属分组(不是店铺管理的分组集):按公司隔离(唯一键
|
||||
* {@code uk_company_group_name});删除分组不删商品——商品行 {@code group_id} 置 NULL
|
||||
* (AC-8,事务两步落 {@code JdProductGroupService})。</p>
|
||||
*
|
||||
* <p>鉴权与 {@code AdminJdProductController} 同款私有闸(同一 column_key/route_path):
|
||||
* 普通授权用户可读写分组(AC-9),默认仅 super_admin;公司隔离正门同样是
|
||||
* {@code readCompanyIdOrOwn}——超管显式传才收窄,非超管强制本公司。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@RequestMapping("/api/admin/jd-product-groups")
|
||||
@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 AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分组列表(含组内商品数)", description = "按公司隔离返回全部分组,按 sort_order, id 升序;"
|
||||
+ "company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。"
|
||||
+ "productCount 为读侧现算列(分组下拉展示用)。")
|
||||
public ApiResponse<List<JdProductGroupVo>> list(
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
return ApiResponse.success(jdProductGroupService.list(scopedCompanyId));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新建分组", description = "同公司重名按业务错误拒绝(409),不落库;"
|
||||
+ "归属公司走公司隔离正门(站点超管必须显式传 company_id)。")
|
||||
public ApiResponse<Long> create(
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 超管不传 company_id 时 scopedCompanyId 为空 ⇒ 服务侧拒绝(分组必须归属一家公司)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
Long id = jdProductGroupService.create(scopedCompanyId, body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 新建分组 operatorId={} companyId={} groupId={}",
|
||||
operator.id(), scopedCompanyId, id);
|
||||
return ApiResponse.success(id);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "分组改名/改排序", description = "越界 id(不属于本公司)按不存在拒绝;"
|
||||
+ "改成本公司已有名字按业务错误拒绝(409)。")
|
||||
public ApiResponse<Boolean> rename(
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
@Valid @RequestBody JdProductGroupSaveRequest body,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
jdProductGroupService.rename(id, scopedCompanyId, body.getName(), body.getSortOrder());
|
||||
log.info("[jd-product-group] 分组改名 operatorId={} groupId={}", operator.id(), id);
|
||||
return ApiResponse.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除分组", description = "删除分组不删商品(AC-8):先同事务把该组商品 "
|
||||
+ "group_id 置 NULL 再删分组行;返回实际脱组的商品行数。越界 id 按不存在拒绝。")
|
||||
public ApiResponse<Integer> delete(
|
||||
@Parameter(description = "分组 id") @PathVariable("id") Long id,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
|
||||
int detached = jdProductGroupService.delete(id, scopedCompanyId);
|
||||
// 管理端破坏性动作必须留痕:谁、删了哪个分组、脱组了多少商品。
|
||||
log.info("[jd-product-group] 删除分组 operatorId={} groupId={} detached={}",
|
||||
operator.id(), id, detached);
|
||||
return ApiResponse.success(detached);
|
||||
}
|
||||
|
||||
private RequestOperator requireJdAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = resolveOperator(request);
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
throw new BusinessException(403, "无权访问京东数据库");
|
||||
}
|
||||
boolean superAdmin = DeviceSessionPolicy.isSuper(adminAuthSupport.currentRole(operator));
|
||||
if (!superAdmin && !hasJdPermission(operator)) {
|
||||
throw new BusinessException(403, "无权访问京东数据库");
|
||||
}
|
||||
return new RequestOperator(operator.getId(), superAdmin, operator);
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveOperator(HttpServletRequest request) {
|
||||
try {
|
||||
return adminAuthSupport.requireUser(request);
|
||||
} catch (BusinessException authFailure) {
|
||||
AdminUserEntity internalOperator = resolveInternalOperator(request);
|
||||
if (internalOperator != null) {
|
||||
return internalOperator;
|
||||
}
|
||||
throw authFailure;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasJdPermission(AdminUserEntity operator) {
|
||||
return permissionMenuService.getUserColumnPermissions(operator.getId(), "admin")
|
||||
.stream()
|
||||
.anyMatch(item -> COLUMN_KEY.equals(item.getColumnKey())
|
||||
|| ROUTE_PATH.equals(item.getRoutePath()));
|
||||
}
|
||||
|
||||
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
|
||||
if (!isTrustedInternalRequest(request.getHeader("X-Internal-Token"))) {
|
||||
return null;
|
||||
}
|
||||
String rawOperatorId = request.getParameter("operatorId");
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
rawOperatorId = request.getParameter("operator_id");
|
||||
}
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return permissionMenuService.requireUserOperator(Long.parseLong(rawOperatorId.trim()));
|
||||
} catch (NumberFormatException | BusinessException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
|
||||
}
|
||||
|
||||
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||
}
|
||||
}
|
||||
+33
-1
@@ -5,6 +5,7 @@ import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -28,5 +29,36 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
* AppearancePatentCleanItemMapper#upsertBatch 同形)。唯一键四元组自身
|
||||
* (company_id/shop_id/product_code)不出现在 UPDATE 段——不随更新漂移。</p>
|
||||
*/
|
||||
int upsertBatch(@Param("rows") List<JdProductEntity> rows);
|
||||
int upsertBatch(@Param("rows") List<JdProductEntity> rows);
|
||||
|
||||
/**
|
||||
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
|
||||
* (公司/店铺名/商品编码/标题关键词/商品状态/分组/同步起止,全部 SQL 侧下推,
|
||||
* 铁律 20)。{@code companyId}/{@code groupId} 为空或 ≤0=不过滤该面。
|
||||
*/
|
||||
long countProducts(@Param("companyId") Long companyId,
|
||||
@Param("shopName") String shopName,
|
||||
@Param("productCode") String productCode,
|
||||
@Param("titleKeyword") String titleKeyword,
|
||||
@Param("saleStatus") String saleStatus,
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo);
|
||||
|
||||
/**
|
||||
* 后管只读页分页查询(synced_at 倒序)。
|
||||
*
|
||||
* <p>{@code offset}/{@code limit} 必须是服务侧钳制后的值——page 钳制防
|
||||
* {@code (page-1)*page_size} 溢出(铁律 15),mapper 不做第二次换算,避免两处各算各的。</p>
|
||||
*/
|
||||
List<JdProductEntity> selectProductPage(@Param("companyId") Long companyId,
|
||||
@Param("shopName") String shopName,
|
||||
@Param("productCode") String productCode,
|
||||
@Param("titleKeyword") String titleKeyword,
|
||||
@Param("saleStatus") String saleStatus,
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo,
|
||||
@Param("offset") long offset,
|
||||
@Param("limit") int limit);
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.nanri.aiimage.modules.jd.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 京东商品分组新建/改名请求体(v1.4 Phase 5)。归属公司不走 body:由控制器经
|
||||
* {@code DataReadScope#readCompanyIdOrOwn} 的公司隔离正门算出,客户端伪造无效。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品分组保存请求")
|
||||
public class JdProductGroupSaveRequest {
|
||||
|
||||
@Schema(description = "分组名(同公司内唯一)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "下拉展示顺序(新建缺省 0;改名不传保持原值)")
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 京东数据库商品详情(后管只读页抽屉,v1.4 Phase 5)。
|
||||
*
|
||||
* <p>主字段从 {@code biz_jd_product} 全量搬运;属性区来自 {@code attr_json} 的
|
||||
* {@code tabs} 数组(客户端实拍契约:{@code {"tabs":[{"tab":"...","attrs":[{key,label,value}]}],
|
||||
* "images":[...],"productCode":"..."}})——解析<b>必须健壮</b>:attr_json 为空/非法/非该形状
|
||||
* 时不抛 500,落空 {@code attrGroups} 并把原文放进 {@link #attrJsonRaw} 兜底展示
|
||||
* (AC-7 未识别属性不丢弃)。图片区来自 {@code biz_jd_product_image}(100% 自有域名,AC-4)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东数据库商品详情")
|
||||
public class JdProductDetailVo {
|
||||
|
||||
@Schema(description = "商品行 id")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "物化归属分公司")
|
||||
private Long companyId;
|
||||
|
||||
@Schema(description = "来源任务 id(biz_file_task.id)")
|
||||
private Long taskId;
|
||||
|
||||
@Schema(description = "京东店铺标识")
|
||||
private String shopId;
|
||||
|
||||
@Schema(description = "京麦店铺名")
|
||||
private String shopName;
|
||||
|
||||
@Schema(description = "京东商品编码")
|
||||
private String productCode;
|
||||
|
||||
@Schema(description = "京东 SKU/货号")
|
||||
private String skuId;
|
||||
|
||||
@Schema(description = "商品标题")
|
||||
private String title;
|
||||
|
||||
@Schema(description = "品牌")
|
||||
private String brand;
|
||||
|
||||
@Schema(description = "品牌 id")
|
||||
private String brandId;
|
||||
|
||||
@Schema(description = "类目路径(京麦原始形状)")
|
||||
private String categoryPath;
|
||||
|
||||
@Schema(description = "价格区间下限")
|
||||
private BigDecimal priceMin;
|
||||
|
||||
@Schema(description = "价格区间上限")
|
||||
private BigDecimal priceMax;
|
||||
|
||||
@Schema(description = "库存合计")
|
||||
private Integer stockTotal;
|
||||
|
||||
@Schema(description = "商品状态原值")
|
||||
private String saleStatus;
|
||||
|
||||
@Schema(description = "采集来源 Tab(ONSALE/OFFSALE)")
|
||||
private String listTab;
|
||||
|
||||
@Schema(description = "京东侧创建时间")
|
||||
private LocalDateTime jdCreatedAt;
|
||||
|
||||
@Schema(description = "京东侧修改时间")
|
||||
private LocalDateTime jdUpdatedAt;
|
||||
|
||||
@Schema(description = "自有桶主图 URL")
|
||||
private String mainImageUrl;
|
||||
|
||||
@Schema(description = "京东详情页 URL(仅作溯源)")
|
||||
private String detailUrl;
|
||||
|
||||
@Schema(description = "属性键数量(质量核查分母)")
|
||||
private Integer attrCount;
|
||||
|
||||
@Schema(description = "已转存图片数")
|
||||
private Integer imageCount;
|
||||
|
||||
@Schema(description = "自定义分组 id(未挂组为空)")
|
||||
private Long groupId;
|
||||
|
||||
@Schema(description = "本次采集批次号")
|
||||
private String collectBatchId;
|
||||
|
||||
@Schema(description = "同步时刻")
|
||||
private LocalDateTime syncedAt;
|
||||
|
||||
@Schema(description = "属性分组(attr_json 的 tabs 数组映射;形状不识别时为空列表)")
|
||||
private List<AttrGroupVo> attrGroups;
|
||||
|
||||
@Schema(description = "attr_json 原文兜底(仅当解析失败/形状不识别时下发,AC-7 未识别属性不丢弃)")
|
||||
private String attrJsonRaw;
|
||||
|
||||
@Schema(description = "已转存图片(自有域名 URL)")
|
||||
private List<ImageViewVo> images;
|
||||
|
||||
/** attr_json 的一个 Tab:{@code {"tab":"商品基本信息","attrs":[...]}}。 */
|
||||
@Data
|
||||
@Schema(description = "属性分组(一个 Tab 一组)")
|
||||
public static class AttrGroupVo {
|
||||
|
||||
@Schema(description = "分组名(京东侧 Tab 名)")
|
||||
private String groupName;
|
||||
|
||||
@Schema(description = "属性键值对")
|
||||
private List<AttrVo> attrs;
|
||||
}
|
||||
|
||||
/** attr_json 的一个属性三元组:{@code {"key":"...","label":"...","value":...}}。 */
|
||||
@Data
|
||||
@Schema(description = "属性键值对")
|
||||
public static class AttrVo {
|
||||
|
||||
@Schema(description = "属性键(京东原始 key)")
|
||||
private String key;
|
||||
|
||||
@Schema(description = "属性展示名(京东原始 label)")
|
||||
private String label;
|
||||
|
||||
@Schema(description = "属性值(任意 JSON 值,读侧转字符串)")
|
||||
private String value;
|
||||
}
|
||||
|
||||
/** 一张已转存图片(biz_jd_product_image 行的读侧投影)。 */
|
||||
@Data
|
||||
@Schema(description = "商品图片")
|
||||
public static class ImageViewVo {
|
||||
|
||||
@Schema(description = "图片档:MAIN/ATTR/DETAIL")
|
||||
private String imageType;
|
||||
|
||||
@Schema(description = "销售属性名(ATTR 档专用)")
|
||||
private String attrName;
|
||||
|
||||
@Schema(description = "同档内排序")
|
||||
private Integer sortNo;
|
||||
|
||||
@Schema(description = "自有域名回读 URL")
|
||||
private String url;
|
||||
|
||||
@Schema(description = "对象字节数")
|
||||
private Long byteSize;
|
||||
|
||||
@Schema(description = "图片宽(像素,可空)")
|
||||
private Integer width;
|
||||
|
||||
@Schema(description = "图片高(像素,可空)")
|
||||
private Integer height;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 京东商品自定义分组(分组下拉/管理面,v1.4 Phase 5)。
|
||||
*
|
||||
* <p>{@code productCount} 是读侧现算列({@code JdProductMapper} BaseMapper selectCount
|
||||
* wrapper 按 {@code group_id} 统计,分组下拉展示用)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东商品自定义分组")
|
||||
public class JdProductGroupVo {
|
||||
|
||||
@Schema(description = "分组 id")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "分组名(同公司内唯一)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "下拉展示顺序")
|
||||
private Integer sortOrder;
|
||||
|
||||
@Schema(description = "组内商品数(读侧现算)")
|
||||
private Long productCount;
|
||||
|
||||
@Schema(description = "创建时刻")
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 京东数据库列表行(后管只读页,v1.4 Phase 5)。
|
||||
*
|
||||
* <p>行值从 {@code biz_jd_product} 原样搬运(读侧不加工);{@code groupName} 是唯一的
|
||||
* 读侧加工列(按 {@code group_id} 批量取分组名补齐,分组已删/未挂组为 null)。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东数据库列表行")
|
||||
public class JdProductListItemVo {
|
||||
|
||||
@Schema(description = "商品行 id")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "京麦店铺名")
|
||||
private String shopName;
|
||||
|
||||
@Schema(description = "京东店铺标识")
|
||||
private String shopId;
|
||||
|
||||
@Schema(description = "京东商品编码")
|
||||
private String productCode;
|
||||
|
||||
@Schema(description = "京东 SKU/货号")
|
||||
private String skuId;
|
||||
|
||||
@Schema(description = "商品标题")
|
||||
private String title;
|
||||
|
||||
@Schema(description = "品牌")
|
||||
private String brand;
|
||||
|
||||
@Schema(description = "类目路径(京麦原始形状,A > B > C)")
|
||||
private String categoryPath;
|
||||
|
||||
@Schema(description = "价格区间下限")
|
||||
private BigDecimal priceMin;
|
||||
|
||||
@Schema(description = "价格区间上限")
|
||||
private BigDecimal priceMax;
|
||||
|
||||
@Schema(description = "库存合计")
|
||||
private Integer stockTotal;
|
||||
|
||||
@Schema(description = "商品状态原值(上架中/已下架/审核中/草稿)")
|
||||
private String saleStatus;
|
||||
|
||||
@Schema(description = "采集来源 Tab(ONSALE/OFFSALE)")
|
||||
private String listTab;
|
||||
|
||||
@Schema(description = "京东侧修改时间")
|
||||
private LocalDateTime jdUpdatedAt;
|
||||
|
||||
@Schema(description = "自有桶主图 URL(京东原图域名不落库,AC-4)")
|
||||
private String mainImageUrl;
|
||||
|
||||
@Schema(description = "属性键数量(质量核查分母)")
|
||||
private Integer attrCount;
|
||||
|
||||
@Schema(description = "已转存图片数")
|
||||
private Integer imageCount;
|
||||
|
||||
@Schema(description = "自定义分组 id(未挂组为空)")
|
||||
private Long groupId;
|
||||
|
||||
@Schema(description = "分组名(读侧批量补齐;未挂组/分组已删为空)")
|
||||
private String groupName;
|
||||
|
||||
@Schema(description = "同步时刻")
|
||||
private LocalDateTime syncedAt;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.nanri.aiimage.modules.jd.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 京东数据库分页结果(后管只读页,v1.4 Phase 5;照 {@code AppearancePatentCleanItemPageVo}
|
||||
* 手拼形状——本表量级先走 OFFSET 分页,不做 keyset 游标)。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "京东数据库分页结果")
|
||||
public class JdProductPageVo {
|
||||
|
||||
@Schema(description = "列表")
|
||||
private List<JdProductListItemVo> items;
|
||||
|
||||
@Schema(description = "总数")
|
||||
private Long total;
|
||||
|
||||
@Schema(description = "页码")
|
||||
private Long page;
|
||||
|
||||
@Schema(description = "每页数量")
|
||||
private Long pageSize;
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
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.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.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 京东商品自定义分组业务(v1.4 Phase 5,R4):下拉列表 / 新建 / 改名 / 删除。
|
||||
*
|
||||
* <p>分组表是简单单表,CRUD 全走 BaseMapper + wrapper(SqlLayering 惯例,无 XML)。
|
||||
* 业务规则:</p>
|
||||
* <ul>
|
||||
* <li><b>按公司隔离</b>:所有读写都带 {@code companyId} 面;越界 id(行不存在或
|
||||
* {@code company_id} 与传入公司不符)一律按「分组不存在」拒绝,不泄露存在性。</li>
|
||||
* <li><b>同公司重名拒绝</b>(唯一键 {@code uk_company_group_name}):先查后插给可读的
|
||||
* 409 业务错误,不拿 DB 异常撞 500;改名时排除自身再查。</li>
|
||||
* <li><b>删除两步一事务</b>(AC-8):先把该组商品 {@code biz_jd_product.group_id} 置 NULL
|
||||
* (商品不删,脱组即成「未分组」),再删分组行——同一事务,失败一起回滚。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code companyId} 由控制器经 {@code DataReadScope#readCompanyIdOrOwn} 算好传入:
|
||||
* {@code null} = 超管没选公司(rename/delete 放行、create 没有「没选公司」语义——
|
||||
* 分组必须归属一家公司,直接拒绝),正数=该公司(非超管恒为自己的公司)。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class JdProductGroupService {
|
||||
|
||||
private final JdProductGroupMapper jdProductGroupMapper;
|
||||
private final JdProductMapper jdProductMapper;
|
||||
|
||||
/**
|
||||
* 分组全量(按 {@code sort_order, id} 升序,下拉展示顺序);
|
||||
* {@code productCount} 用 {@code JdProductMapper} BaseMapper selectCount wrapper
|
||||
* 按 {@code group_id} 统计(分组下拉展示用)。
|
||||
*/
|
||||
public List<JdProductGroupVo> list(Long scopedCompanyId) {
|
||||
LambdaQueryWrapper<JdProductGroupEntity> query = new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.eq(scopedCompanyId != null && scopedCompanyId > 0,
|
||||
JdProductGroupEntity::getCompanyId, scopedCompanyId)
|
||||
.orderByAsc(JdProductGroupEntity::getSortOrder)
|
||||
.orderByAsc(JdProductGroupEntity::getId);
|
||||
List<JdProductGroupVo> items = new ArrayList<>();
|
||||
for (JdProductGroupEntity group : jdProductGroupMapper.selectList(query)) {
|
||||
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())));
|
||||
items.add(vo);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 新建分组:同公司重名(trim 后)按 409 业务错误拒绝,不落库。 */
|
||||
public Long create(Long scopedCompanyId, String name, Integer sortOrder) {
|
||||
if (scopedCompanyId == null || scopedCompanyId <= 0) {
|
||||
throw new BusinessException(400, "创建分组必须指定公司");
|
||||
}
|
||||
String safeName = requireName(name);
|
||||
requireNameFree(scopedCompanyId, safeName, null);
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setCompanyId(scopedCompanyId);
|
||||
group.setName(safeName);
|
||||
group.setSortOrder(sortOrder == null ? 0 : sortOrder);
|
||||
jdProductGroupMapper.insert(group);
|
||||
return group.getId();
|
||||
}
|
||||
|
||||
/** 改名/改排序:越界 id 拒绝,重名(排除自身)拒绝。 */
|
||||
public void rename(Long id, Long scopedCompanyId, String name, Integer sortOrder) {
|
||||
String safeName = requireName(name);
|
||||
JdProductGroupEntity group = requireOwnedGroup(id, scopedCompanyId);
|
||||
requireNameFree(group.getCompanyId(), safeName, group.getId());
|
||||
group.setName(safeName);
|
||||
if (sortOrder != null) {
|
||||
group.setSortOrder(sortOrder);
|
||||
}
|
||||
jdProductGroupMapper.updateById(group);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除分组(事务两步,AC-8):先把该组商品 {@code group_id} 置 NULL(商品保留,
|
||||
* 脱组即「未分组」),再删分组行。越界 id 拒绝。
|
||||
*
|
||||
* @return 实际脱组的商品行数(前端拿它做「已解挂 N 个商品」的反馈,不猜)
|
||||
*/
|
||||
@Transactional
|
||||
public int delete(Long id, Long scopedCompanyId) {
|
||||
JdProductGroupEntity group = requireOwnedGroup(id, scopedCompanyId);
|
||||
int detached = jdProductMapper.update(null, new LambdaUpdateWrapper<JdProductEntity>()
|
||||
.set(JdProductEntity::getGroupId, null)
|
||||
.eq(JdProductEntity::getCompanyId, group.getCompanyId())
|
||||
.eq(JdProductEntity::getGroupId, group.getId()));
|
||||
jdProductGroupMapper.deleteById(group.getId());
|
||||
return detached;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 业务规则
|
||||
|
||||
/** 名字归一:trim 后必须非空。 */
|
||||
private static String requireName(String name) {
|
||||
if (name == null || name.trim().isEmpty()) {
|
||||
throw new BusinessException(400, "分组名不能为空");
|
||||
}
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 分组行归属校验:不存在 / 公司不符(越界 id)一律按「分组不存在」拒绝——
|
||||
* 越界探测拿到的与 id 不存在是同一种响应,不泄露跨公司行的存在性。
|
||||
* {@code scopedCompanyId} 为空=超管没选公司、跨公司放行。
|
||||
*/
|
||||
private JdProductGroupEntity requireOwnedGroup(Long id, Long scopedCompanyId) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("分组不存在");
|
||||
}
|
||||
JdProductGroupEntity group = jdProductGroupMapper.selectById(id);
|
||||
if (group == null || (scopedCompanyId != null && scopedCompanyId > 0
|
||||
&& !scopedCompanyId.equals(group.getCompanyId()))) {
|
||||
throw new BusinessException("分组不存在");
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
/** 同公司重名拒绝(409):{@code excludeId} 非空=改名时排除自身。 */
|
||||
private void requireNameFree(Long companyId, String name, Long excludeId) {
|
||||
Long count = jdProductGroupMapper.selectCount(new LambdaQueryWrapper<JdProductGroupEntity>()
|
||||
.eq(JdProductGroupEntity::getCompanyId, companyId)
|
||||
.eq(JdProductGroupEntity::getName, name)
|
||||
.ne(excludeId != null, JdProductGroupEntity::getId, excludeId));
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException(409, "同公司下已存在同名分组:" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
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.JdProductGroupMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductListItemVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 后管「京东数据库」只读查询(v1.4 Phase 5):分页 / 详情 / 导出。
|
||||
*
|
||||
* <p>分页钳制是本服务的职责(铁律 15):mapper 的 {@code offset}/{@code limit} 只收钳制后的值
|
||||
* (单一出口,mapper 不做第二次换算)。钳制形状照 {@code AppearancePatentCleanItemQueryService}
|
||||
* 先例:{@code page} 上限 {@link #MAX_PAGE}、{@code page_size} 上限 {@link #MAX_PAGE_SIZE},
|
||||
* {@code page=Long.MAX_VALUE} 不会把乘积顶成负数生成 {@code LIMIT -N} 的 500 错。</p>
|
||||
*
|
||||
* <p><b>公司隔离</b>:{@code scopedCompanyId} 由控制器经 {@code DataReadScope#readCompanyIdOrOwn}
|
||||
* 算好传入——{@code null} = 超管没选公司、查全量;正数 = 只查该公司(非超管恒为自己的公司)。
|
||||
* 详情同样按它收口:行 {@code company_id} 与公司隔离范围不符按不存在拒绝(不泄露跨公司行的存在性)。</p>
|
||||
*
|
||||
* <p><b>详情 attr_json 解析(AC-7 未识别属性不丢弃)</b>:客户端实拍契约
|
||||
* {@code {"tabs":[{"tab":"...","attrs":[{key,label,value}]}],"images":[...],"productCode":"..."}}——
|
||||
* {@code tabs} 数组映射成 {@code attrGroups}(groupName=tab 字段);attr_json 为空/非法 JSON/
|
||||
* 非该形状时<b>不抛 500</b>,落空 {@code attrGroups} 并把原文放进 {@code attrJsonRaw} 兜底展示。
|
||||
* 主表高频列直接从 entity 映射,不走 JSON。</p>
|
||||
*
|
||||
* <p><b>导出</b>与分页共用同一过滤面与同一条 SQL(offset=0、limit=导出上限,不另写导出查询),
|
||||
* 先 {@code countProducts} 卡 {@link #EXPORT_MAX_ROWS} 上限防内存;行集按后管页面主要字段
|
||||
* 中文列序写 xlsx(SXSSF 流式,口径同 {@code QueryAsinService.export} 的 byte[] 形状)。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class JdProductQueryService {
|
||||
|
||||
/** 页码上限(CR-18 关键词分页同值):10000 页 x 100 条 = 100 万行封顶,乘积不溢出。 */
|
||||
private static final long MAX_PAGE = 10_000;
|
||||
/** 每页条数上限(照外观专利只读页同值)。 */
|
||||
private static final long MAX_PAGE_SIZE = 100;
|
||||
/** 单次导出行数上限:超限按业务错误拒(提示缩小筛选面),不把无界内存写进一次 HTTP 响应。 */
|
||||
public static final long EXPORT_MAX_ROWS = 50_000;
|
||||
/** 导出时间列的展示格式。 */
|
||||
private static final DateTimeFormatter EXPORT_DATETIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
/** attr_json 原始形状里的 Tab 字段名(客户端实拍契约,AC-3 保真不转写)。 */
|
||||
private static final String ATTR_TAB_FIELD = "tab";
|
||||
private static final String ATTR_ATTRS_FIELD = "attrs";
|
||||
private static final String ATTR_KEY_FIELD = "key";
|
||||
private static final String ATTR_LABEL_FIELD = "label";
|
||||
private static final String ATTR_VALUE_FIELD = "value";
|
||||
|
||||
/** 导出列序(与后管页面主要字段同序,中文列名)。 */
|
||||
private static final List<String> EXPORT_HEADERS = List.of(
|
||||
"店铺名", "店铺ID", "商品编码", "SKU", "标题", "品牌", "类目路径",
|
||||
"价格下限", "价格上限", "库存", "商品状态", "来源Tab",
|
||||
"京东更新时间", "属性键数", "图片数", "分组", "同步时间");
|
||||
|
||||
private final JdProductMapper jdProductMapper;
|
||||
private final JdProductImageMapper jdProductImageMapper;
|
||||
private final JdProductGroupMapper jdProductGroupMapper;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* 分页查询商品行({@code synced_at} 倒序)。
|
||||
*
|
||||
* <p>过滤面:公司(物化列 eq)、店铺名 contains、商品编码 contains、标题关键词 contains、
|
||||
* 商品状态 eq、分组 eq、同步起止(datetime 闭区间)。</p>
|
||||
*/
|
||||
public JdProductPageVo page(Long page, Long pageSize, Long scopedCompanyId, String shopName,
|
||||
String productCode, String titleKeyword, String saleStatus, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
}
|
||||
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
|
||||
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
|
||||
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, saleStatus, groupId,
|
||||
syncedFrom, syncedTo);
|
||||
long total = jdProductMapper.countProducts(filter.companyId(), filter.shopName(), filter.productCode(),
|
||||
filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
|
||||
filter.syncedTo());
|
||||
List<JdProductEntity> rows = total <= 0 ? List.of()
|
||||
: jdProductMapper.selectProductPage(filter.companyId(), filter.shopName(), filter.productCode(),
|
||||
filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
|
||||
filter.syncedTo(), (safePage - 1) * safeSize, (int) safeSize);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
fillGroupNames(items);
|
||||
JdProductPageVo vo = new JdProductPageVo();
|
||||
vo.setItems(items);
|
||||
vo.setTotal(total);
|
||||
vo.setPage(safePage);
|
||||
vo.setPageSize(safeSize);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品详情(主字段全量 + attr_json 解析 + 已转存图片)。
|
||||
*
|
||||
* <p>公司隔离与分页同门:{@code scopedCompanyId} 非空且与行 {@code company_id} 不符时按
|
||||
* 不存在拒绝——不泄露跨公司行的存在性(越界 id 探测拿到的与 id 不存在是同一种响应)。
|
||||
* attr_json 非契约形状/解析异常时不抛 500:落空 {@code attrGroups}、原文进
|
||||
* {@code attrJsonRaw} 兜底(AC-7)。</p>
|
||||
*/
|
||||
public JdProductDetailVo detail(Long id, Long scopedCompanyId) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
JdProductEntity row = jdProductMapper.selectById(id);
|
||||
if (row == null || !companyVisible(row.getCompanyId(), scopedCompanyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
JdProductDetailVo vo = new JdProductDetailVo();
|
||||
vo.setId(row.getId());
|
||||
vo.setCompanyId(row.getCompanyId());
|
||||
vo.setTaskId(row.getTaskId());
|
||||
vo.setShopId(row.getShopId());
|
||||
vo.setShopName(row.getShopName());
|
||||
vo.setProductCode(row.getProductCode());
|
||||
vo.setSkuId(row.getSkuId());
|
||||
vo.setTitle(row.getTitle());
|
||||
vo.setBrand(row.getBrand());
|
||||
vo.setBrandId(row.getBrandId());
|
||||
vo.setCategoryPath(row.getCategoryPath());
|
||||
vo.setPriceMin(row.getPriceMin());
|
||||
vo.setPriceMax(row.getPriceMax());
|
||||
vo.setStockTotal(row.getStockTotal());
|
||||
vo.setSaleStatus(row.getSaleStatus());
|
||||
vo.setListTab(row.getListTab());
|
||||
vo.setJdCreatedAt(row.getJdCreatedAt());
|
||||
vo.setJdUpdatedAt(row.getJdUpdatedAt());
|
||||
vo.setMainImageUrl(row.getMainImageUrl());
|
||||
vo.setDetailUrl(row.getDetailUrl());
|
||||
vo.setAttrCount(row.getAttrCount());
|
||||
vo.setImageCount(row.getImageCount());
|
||||
vo.setGroupId(row.getGroupId());
|
||||
vo.setCollectBatchId(row.getCollectBatchId());
|
||||
vo.setSyncedAt(row.getSyncedAt());
|
||||
parseAttrGroups(vo, row.getAttrJson());
|
||||
vo.setImages(loadImages(row.getId()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前过滤面全量明细为 xlsx 字节(控制器直接回 {@code ResponseEntity<byte[]>},
|
||||
* 口径同 {@code AppearancePatentCleanItemQueryService.export})。
|
||||
*
|
||||
* <p>先 count 卡 {@link #EXPORT_MAX_ROWS} 上限再取数;取数复用 {@code selectProductPage}
|
||||
* 这一条 SQL(offset=0、limit=上限),不另写导出查询——过滤面永远和分页页签同源。</p>
|
||||
*/
|
||||
public byte[] export(Long scopedCompanyId, String shopName, String productCode, String titleKeyword,
|
||||
String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
}
|
||||
Filter filter = filter(scopedCompanyId, shopName, productCode, titleKeyword, saleStatus, groupId,
|
||||
syncedFrom, syncedTo);
|
||||
long total = jdProductMapper.countProducts(filter.companyId(), filter.shopName(), filter.productCode(),
|
||||
filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
|
||||
filter.syncedTo());
|
||||
if (total > EXPORT_MAX_ROWS) {
|
||||
throw new BusinessException("京东数据库共 " + total + " 行,超过导出上限 " + EXPORT_MAX_ROWS
|
||||
+ " 行,请缩小筛选范围后重试");
|
||||
}
|
||||
List<JdProductEntity> rows = total <= 0 ? List.of()
|
||||
: jdProductMapper.selectProductPage(filter.companyId(), filter.shopName(), filter.productCode(),
|
||||
filter.titleKeyword(), filter.saleStatus(), filter.groupId(), filter.syncedFrom(),
|
||||
filter.syncedTo(), 0L, (int) EXPORT_MAX_ROWS);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
fillGroupNames(items);
|
||||
return writeExportWorkbook(items);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 过滤面
|
||||
|
||||
/** 服务侧过滤面归一:companyId/groupId ≤0 按没选处理,文本 trim 后空串归 null。 */
|
||||
private record Filter(Long companyId, String shopName, String productCode, String titleKeyword,
|
||||
String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
}
|
||||
|
||||
private static Filter filter(Long scopedCompanyId, String shopName, String productCode, String titleKeyword,
|
||||
String saleStatus, Long groupId, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
|
||||
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
|
||||
return new Filter(companyId, trimToNull(shopName), trimToNull(productCode), trimToNull(titleKeyword),
|
||||
trimToNull(saleStatus), safeGroupId, syncedFrom, syncedTo);
|
||||
}
|
||||
|
||||
/** 超管不选公司(scopedCompanyId=null)=全量可见;正数=只看该公司。 */
|
||||
private static boolean companyVisible(Long rowCompanyId, Long scopedCompanyId) {
|
||||
if (scopedCompanyId == null || scopedCompanyId <= 0) {
|
||||
return true;
|
||||
}
|
||||
return scopedCompanyId.equals(rowCompanyId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表/详情搬运
|
||||
|
||||
/** 行值原样搬运(读侧不加工),groupName 由 {@link #fillGroupNames} 批量补齐。 */
|
||||
private JdProductListItemVo toListItem(JdProductEntity row) {
|
||||
JdProductListItemVo vo = new JdProductListItemVo();
|
||||
vo.setId(row.getId());
|
||||
vo.setShopName(row.getShopName());
|
||||
vo.setShopId(row.getShopId());
|
||||
vo.setProductCode(row.getProductCode());
|
||||
vo.setSkuId(row.getSkuId());
|
||||
vo.setTitle(row.getTitle());
|
||||
vo.setBrand(row.getBrand());
|
||||
vo.setCategoryPath(row.getCategoryPath());
|
||||
vo.setPriceMin(row.getPriceMin());
|
||||
vo.setPriceMax(row.getPriceMax());
|
||||
vo.setStockTotal(row.getStockTotal());
|
||||
vo.setSaleStatus(row.getSaleStatus());
|
||||
vo.setListTab(row.getListTab());
|
||||
vo.setJdUpdatedAt(row.getJdUpdatedAt());
|
||||
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)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (groupIds.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());
|
||||
}
|
||||
}
|
||||
for (JdProductListItemVo item : items) {
|
||||
if (item.getGroupId() != null) {
|
||||
item.setGroupName(namesById.get(item.getGroupId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 已转存图片:按档内排序号、id 稳定升序(详情抽屉分区展示顺序)。 */
|
||||
private List<JdProductDetailVo.ImageViewVo> loadImages(Long productId) {
|
||||
List<JdProductImageEntity> rows = jdProductImageMapper.selectList(
|
||||
new LambdaQueryWrapper<JdProductImageEntity>()
|
||||
.eq(JdProductImageEntity::getProductId, productId)
|
||||
.orderByAsc(JdProductImageEntity::getSortNo)
|
||||
.orderByAsc(JdProductImageEntity::getId));
|
||||
List<JdProductDetailVo.ImageViewVo> images = new ArrayList<>(rows.size());
|
||||
for (JdProductImageEntity row : rows) {
|
||||
JdProductDetailVo.ImageViewVo view = new JdProductDetailVo.ImageViewVo();
|
||||
view.setImageType(row.getImageType());
|
||||
view.setAttrName(row.getAttrName());
|
||||
view.setSortNo(row.getSortNo());
|
||||
view.setUrl(row.getUrl());
|
||||
view.setByteSize(row.getByteSize());
|
||||
view.setWidth(row.getWidth());
|
||||
view.setHeight(row.getHeight());
|
||||
images.add(view);
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- attr_json 解析
|
||||
|
||||
/**
|
||||
* attr_json → attrGroups。契约形状 {@code {"tabs":[{"tab":..,"attrs":[..]}]}};
|
||||
* 为空/非法 JSON/形状不识别一律落空列表并把原文放进 {@code attrJsonRaw}(不抛 500,AC-7)。
|
||||
*/
|
||||
private void parseAttrGroups(JdProductDetailVo vo, String attrJson) {
|
||||
vo.setAttrGroups(List.of());
|
||||
if (attrJson == null || attrJson.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(attrJson);
|
||||
JsonNode tabs = root == null ? null : root.get("tabs");
|
||||
if (tabs == null || !tabs.isArray() || tabs.isEmpty()) {
|
||||
vo.setAttrJsonRaw(attrJson);
|
||||
return;
|
||||
}
|
||||
List<JdProductDetailVo.AttrGroupVo> groups = new ArrayList<>();
|
||||
for (JsonNode tabNode : tabs) {
|
||||
JsonNode tab = tabNode.get(ATTR_TAB_FIELD);
|
||||
JsonNode attrs = tabNode.get(ATTR_ATTRS_FIELD);
|
||||
if (attrs == null || !attrs.isArray()) {
|
||||
// 该 Tab 没有 attrs 数组=形状不识别的那部分:不丢原文,整段落 attrJsonRaw 兜底
|
||||
vo.setAttrJsonRaw(attrJson);
|
||||
continue;
|
||||
}
|
||||
JdProductDetailVo.AttrGroupVo group = new JdProductDetailVo.AttrGroupVo();
|
||||
group.setGroupName(tab == null || tab.isNull() ? null : tab.asText());
|
||||
List<JdProductDetailVo.AttrVo> attrList = new ArrayList<>();
|
||||
for (JsonNode attrNode : attrs) {
|
||||
JdProductDetailVo.AttrVo attr = new JdProductDetailVo.AttrVo();
|
||||
JsonNode key = attrNode.get(ATTR_KEY_FIELD);
|
||||
JsonNode label = attrNode.get(ATTR_LABEL_FIELD);
|
||||
JsonNode value = attrNode.get(ATTR_VALUE_FIELD);
|
||||
attr.setKey(key == null || key.isNull() ? null : key.asText());
|
||||
attr.setLabel(label == null || label.isNull() ? null : label.asText());
|
||||
attr.setValue(value == null || value.isNull() ? null : value.asText());
|
||||
attrList.add(attr);
|
||||
}
|
||||
group.setAttrs(attrList);
|
||||
groups.add(group);
|
||||
}
|
||||
vo.setAttrGroups(groups);
|
||||
} catch (Exception ex) {
|
||||
// 解析异常按未识别形状兜底:原文透出,绝不把详情页打成 500(AC-7)
|
||||
log.warn("[jd-product] attr_json 解析失败 productId={} msg={}", vo.getId(), ex.getMessage());
|
||||
vo.setAttrGroups(List.of());
|
||||
vo.setAttrJsonRaw(attrJson);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 导出
|
||||
|
||||
private byte[] writeExportWorkbook(List<JdProductListItemVo> items) {
|
||||
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
|
||||
Sheet sheet = workbook.createSheet("京东数据库");
|
||||
Row header = sheet.createRow(0);
|
||||
for (int c = 0; c < EXPORT_HEADERS.size(); c++) {
|
||||
header.createCell(c).setCellValue(EXPORT_HEADERS.get(c));
|
||||
}
|
||||
for (int i = 0; i < items.size(); i++) {
|
||||
writeExportRow(sheet, i + 1, items.get(i));
|
||||
}
|
||||
// 标题列放宽,其余走默认窄列;与页面列宽观感对齐即可,不追求逐像素。
|
||||
sheet.setColumnWidth(4, 46 * 256);
|
||||
workbook.write(outputStream);
|
||||
workbook.dispose();
|
||||
return outputStream.toByteArray();
|
||||
} catch (Exception ex) {
|
||||
// 落盘/序列化失败必须给可读业务错误,细节进日志(CatchSilenceRatchetTest RETHROW 形状)。
|
||||
log.warn("[jd-product] 导出 xlsx 失败 rows={} msg={}", items.size(), ex.getMessage());
|
||||
throw new BusinessException("导出京东数据库失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
private void writeExportRow(Sheet sheet, int rowIndex, JdProductListItemVo item) {
|
||||
Row row = sheet.createRow(rowIndex);
|
||||
row.createCell(0).setCellValue(safe(item.getShopName()));
|
||||
row.createCell(1).setCellValue(safe(item.getShopId()));
|
||||
row.createCell(2).setCellValue(safe(item.getProductCode()));
|
||||
row.createCell(3).setCellValue(safe(item.getSkuId()));
|
||||
row.createCell(4).setCellValue(safe(item.getTitle()));
|
||||
row.createCell(5).setCellValue(safe(item.getBrand()));
|
||||
row.createCell(6).setCellValue(safe(item.getCategoryPath()));
|
||||
row.createCell(7).setCellValue(item.getPriceMin() == null ? "" : item.getPriceMin().toPlainString());
|
||||
row.createCell(8).setCellValue(item.getPriceMax() == null ? "" : item.getPriceMax().toPlainString());
|
||||
row.createCell(9).setCellValue(item.getStockTotal() == null ? "" : String.valueOf(item.getStockTotal()));
|
||||
row.createCell(10).setCellValue(safe(item.getSaleStatus()));
|
||||
row.createCell(11).setCellValue(safe(item.getListTab()));
|
||||
row.createCell(12).setCellValue(item.getJdUpdatedAt() == null
|
||||
? "" : EXPORT_DATETIME_FORMATTER.format(item.getJdUpdatedAt()));
|
||||
row.createCell(13).setCellValue(item.getAttrCount() == null ? "" : String.valueOf(item.getAttrCount()));
|
||||
row.createCell(14).setCellValue(item.getImageCount() == null ? "" : String.valueOf(item.getImageCount()));
|
||||
row.createCell(15).setCellValue(safe(item.getGroupName()));
|
||||
row.createCell(16).setCellValue(item.getSyncedAt() == null
|
||||
? "" : EXPORT_DATETIME_FORMATTER.format(item.getSyncedAt()));
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static String trimToNull(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,40 @@
|
||||
attr_count = VALUES(attr_count),
|
||||
image_count = VALUES(image_count),
|
||||
collect_batch_id = VALUES(collect_batch_id),
|
||||
synced_at = CURRENT_TIMESTAMP
|
||||
synced_at = CURRENT_TIMESTAMP
|
||||
</insert>
|
||||
|
||||
<!-- 后管只读页(Phase 5,v1.4)过滤面:公司(物化列 eq)、店铺名/商品编码/标题关键词
|
||||
(contains LIKE)、商品状态 eq、分组 eq、同步起止(datetime 闭区间)。
|
||||
全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 -->
|
||||
<sql id="productConds">
|
||||
<if test="companyId != null and companyId > 0">AND p.company_id = #{companyId}</if>
|
||||
<if test="shopName != null and shopName != ''">AND p.shop_name LIKE CONCAT('%', #{shopName}, '%')</if>
|
||||
<if test="productCode != null and productCode != ''">AND p.product_code LIKE CONCAT('%', #{productCode}, '%')</if>
|
||||
<if test="titleKeyword != null and titleKeyword != ''">AND p.title LIKE CONCAT('%', #{titleKeyword}, '%')</if>
|
||||
<if test="saleStatus != null and saleStatus != ''">AND p.sale_status = #{saleStatus}</if>
|
||||
<if test="groupId != null and groupId > 0">AND p.group_id = #{groupId}</if>
|
||||
<if test="syncedFrom != null">AND p.synced_at >= #{syncedFrom}</if>
|
||||
<if test="syncedTo != null">AND p.synced_at <= #{syncedTo}</if>
|
||||
</sql>
|
||||
|
||||
<!-- 只读页总数(与 selectProductPage 同一过滤面)。 -->
|
||||
<select id="countProducts" resultType="long">
|
||||
SELECT COUNT(*)
|
||||
FROM biz_jd_product p
|
||||
WHERE 1=1 <include refid="productConds"/>
|
||||
</select>
|
||||
|
||||
<!-- 只读页分页查询(synced_at 倒序)。
|
||||
group_name 不在此联表:读侧按行集 group_id 批量取分组名补齐(一次查询,无逐行查询)。 -->
|
||||
<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.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_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
|
||||
FROM biz_jd_product p
|
||||
WHERE 1=1 <include refid="productConds"/>
|
||||
ORDER BY p.synced_at DESC, p.id DESC
|
||||
LIMIT #{offset}, #{limit}
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@@ -85,7 +85,10 @@ class MigratedSqlEquivalenceTest {
|
||||
// 105 → 109:2026-11-11「按主管划分」同一 mapper 再落 4 条 select(主管聚合 count/page
|
||||
// +按主管导出 count/page),同样从来没有注解原文可对撞,逐条点名
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 151 → 155)。
|
||||
private static final int XML_SELECT_TOTAL = 109;
|
||||
// 109 → 111:v1.4 Phase 5(2026-11-14)后管只读页在 JdProductMapper 新写 2 条只读 select
|
||||
//(countProducts + selectProductPage)。注意本格是「全部 XML 的 select 总数」(不走
|
||||
// NOT_MIGRATED 豁免——豁免只作用于等价性那支),新写 select 也计入本分母。
|
||||
private static final int XML_SELECT_TOTAL = 111;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -186,7 +189,13 @@ class MigratedSqlEquivalenceTest {
|
||||
// uk_product_image),注解时代没有原文可对撞,逐条点名留痕
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 155 → 157)。
|
||||
"JdProductMapper#upsertBatch",
|
||||
"JdProductImageMapper#upsertBatch");
|
||||
"JdProductImageMapper#upsertBatch",
|
||||
// v1.4 Phase 5(2026-11-14):后管只读页在 JdProductMapper 新写 2 条只读 select
|
||||
//(countProducts + selectProductPage,同一过滤面、offset/limit 由服务钳制后传参),
|
||||
// 注解时代没有原文可对撞,逐条点名留痕
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 157 → 159)。
|
||||
"JdProductMapper#countProducts",
|
||||
"JdProductMapper#selectProductPage");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -112,7 +112,10 @@ class SqlLayeringConventionTest {
|
||||
// JdProductMapper#upsertBatch(覆盖最新,uk_company_shop_code)+
|
||||
// JdProductImageMapper#upsertBatch(图片登记,uk_product_image),全部新写,
|
||||
// 同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 不动:无 select)。
|
||||
private static final int XML_STATEMENT_TOTAL = 157;
|
||||
// 157 → 159:v1.4 Phase 5 后管只读页在 JdProductMapper 落 2 条只读 select
|
||||
//(countProducts + selectProductPage,同过滤面、offset/limit 由服务钳制后传参),
|
||||
// 同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 不动)。
|
||||
private static final int XML_STATEMENT_TOTAL = 159;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+17
-11
@@ -65,6 +65,9 @@ class PageDefaultsLedgerTest {
|
||||
// 与明细列表端点同参数名同默认值(按出站点计数、不去重)
|
||||
"AdminAppearancePatentCleanItemsController.java#page=FIRST_PAGE",
|
||||
"AdminAppearancePatentCleanItemsController.java#page_size=CLEAN_ITEMS_PAGE_SIZE",
|
||||
// v1.4 Phase 5(2026-11-14):京东数据库后管只读页分页出站点(page/page_size 默认 20)
|
||||
"AdminJdProductController.java#page=FIRST_PAGE",
|
||||
"AdminJdProductController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
|
||||
"AppearancePatentController.java#limit=DEFAULT_RESULT_LIMIT",
|
||||
"CollectDataController.java#page=FIRST_PAGE",
|
||||
"CollectDataController.java#page_size=TASK_LIST_PAGE_SIZE",
|
||||
@@ -115,11 +118,12 @@ class PageDefaultsLedgerTest {
|
||||
List<String> constants = actual.stream().filter(s -> !s.contains("LITERAL")).sorted().toList();
|
||||
|
||||
assertThat(constants)
|
||||
.as("58 处分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
+ "(56→58:2026-11-11 /supervisors 主管聚合卡片页的 page/page_size 两处出站点)")
|
||||
.as("60 处分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
+ "(58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
|
||||
+ " page/page_size 两处出站点)")
|
||||
.isEqualTo(LEDGER.stream().sorted().toList());
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 58 处
|
||||
assertThat(constants).hasSize(58);
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 60 处
|
||||
assertThat(constants).hasSize(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,13 +138,14 @@ class PageDefaultsLedgerTest {
|
||||
void oneSemanticCannotGrowASecondDefault() {
|
||||
List<String> actual = sites();
|
||||
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
|
||||
.as("页码口径只有一套:全部从 1 起(25→26:2026-11-11 /supervisors 主管聚合卡片页也是分页出站点)")
|
||||
.isEqualTo(26);
|
||||
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点)")
|
||||
.isEqualTo(27);
|
||||
assertThat(distinctConstants(actual, "page_size"))
|
||||
.as("page_size 的默认容量集合:10/15/20/50/1000 五种各自登记,新来第六种要红"
|
||||
+ "(10 是 v1.3 无侵权只读页,蓝图 §3.2 拍板、与前端 OldPagination 首屏同值)")
|
||||
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
|
||||
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
|
||||
.containsExactlyInAnyOrder("USER_LIST_PAGE_SIZE", "ADMIN_LIST_PAGE_SIZE",
|
||||
"TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE", "CLEAN_ITEMS_PAGE_SIZE");
|
||||
"TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE", "CLEAN_ITEMS_PAGE_SIZE",
|
||||
"JD_PRODUCTS_PAGE_SIZE");
|
||||
// 同一个语义有两种拼写(@RequestParam(name = "page_size") 与 camelCase 的 pageSize),
|
||||
// 而两种拼写实际用到的常量本来就不同。原来把同一个四项清单套在两种拼写上,
|
||||
// 红的是台账写法而不是有人新增了默认值——2026-10-10 出包前对平这一条。
|
||||
@@ -151,10 +156,10 @@ class PageDefaultsLedgerTest {
|
||||
bothSpellings.addAll(distinctConstants(actual, "page_size"));
|
||||
bothSpellings.addAll(distinctConstants(actual, "pageSize"));
|
||||
assertThat(bothSpellings)
|
||||
.as("两种拼写合起来仍只许那五种容量:谁长出第六种,这里就红")
|
||||
.as("两种拼写合起来仍只许那几把容量:谁长出第七种,这里就红")
|
||||
.containsExactlyInAnyOrderElementsOf(java.util.List.of("USER_LIST_PAGE_SIZE",
|
||||
"ADMIN_LIST_PAGE_SIZE", "TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE",
|
||||
"CLEAN_ITEMS_PAGE_SIZE"));
|
||||
"CLEAN_ITEMS_PAGE_SIZE", "JD_PRODUCTS_PAGE_SIZE"));
|
||||
assertThat(distinctConstants(actual, "limit"))
|
||||
.as("limit 是「本次最多返回几条」,不许和 page_size 混用同一批常量")
|
||||
.containsExactlyInAnyOrder("DEFAULT_RESULT_LIMIT", "ADMIN_SCAN_LIMIT");
|
||||
@@ -186,6 +191,7 @@ class PageDefaultsLedgerTest {
|
||||
assertPair(PageDefaults.FULL_EXPORT_PAGE_SIZE, PageDefaults.FULL_EXPORT_PAGE_SIZE_INT);
|
||||
assertPair(PageDefaults.DEFAULT_RESULT_LIMIT, PageDefaults.DEFAULT_RESULT_LIMIT_INT);
|
||||
assertPair(PageDefaults.ADMIN_SCAN_LIMIT, PageDefaults.ADMIN_SCAN_LIMIT_INT);
|
||||
assertPair(PageDefaults.JD_PRODUCTS_PAGE_SIZE, PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -69,7 +69,11 @@ class CatchSilenceRatchetTest {
|
||||
// LOG_ONLY 与 EMPTY 一格没涨(逐处记名见 STRICT_TOTAL 上方注释)——改的是"查不到"怎么表达,不是把它藏起来。
|
||||
// 11-10 v1.3 外观专利无侵权同步链抬 608 -> 611:三枚不重抛(同步服务两枚+控制器内部令牌回退一枚),
|
||||
// 逐处记名见 STRICT_TOTAL 上方注释;LOG_ONLY 宽口径格 251 没动(宽口径实测已落到 193,离上限很远)。
|
||||
static final int GIVEN_NOT_RETHROW = 611;
|
||||
// 11-14 v1.4 京东数据库抬 611 -> 615:三枚不重抛(Phase 5 后管两处 resolveInternalOperator 返回 null
|
||||
// + parseAttrGroups 的 attr_json 兜底;Phase 2/4 的 7 枚全是 RETHROW、Phase 2 的 scope 行
|
||||
// DuplicateKeyException 是 LOG_ONLY,都不占本格),逐处记名见 STRICT_TOTAL 上方注释;
|
||||
// LOG_ONLY 宽口径格 251 没动(宽口径实测 194,离上限很远)。
|
||||
static final int GIVEN_NOT_RETHROW = 615;
|
||||
static final int GIVEN_LOG_ONLY = 251;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -324,7 +328,31 @@ class CatchSilenceRatchetTest {
|
||||
// 本格与 NOT_RETHROW/LOG_ONLY/EMPTY 都不动)。误差方向:导出请求的 IO 失败必须给用户
|
||||
// 可读业务错误而不是 500 裸堆栈;反向对照——改成往外抛 IOException=前端拿到 Spring 兜底文案,
|
||||
// 改成吞掉返回空字节=用户拿到 0 字节 xlsx 还以为导出成功(比报错更贵)。
|
||||
static final int STRICT_TOTAL = 1074;
|
||||
// 11-14 v1.4 京东数据库抬 1074 -> 1090,十六枚逐处记名(Phase 2 采集域 7 枚与 Phase 4 通用化
|
||||
// 3 枚随各自 commit 落码、当时未进点名册,Phase 5 收尾跑全量时由本棘轮一次性抓出,此处并册):
|
||||
// 【Phase 4 通用化预签名,3 枚全 RETHROW】`OssStorageService.presignObjectUpload` /
|
||||
// `objectSize`(ErrorResponseException 非 404 分支 + Exception 兜底,共 2 枚):全部转
|
||||
// `storageFailure`——预签名/对撞失败必须给可读业务错误,静默 return null 会让客户端拿
|
||||
// null uploadUrl 直传炸得更深。
|
||||
// 【Phase 2 采集域,7 枚】`JdCollectTaskService`:① 建单载荷序列化 `catch Exception` →
|
||||
// BusinessException(RETHROW);② scope 行 `catch DuplicateKeyException` → log.info 复用
|
||||
// 先到行(LOG_ONLY +1,并发建单幂等语义,不吞成败);③④ `readCreateRequest` 的
|
||||
// `catch BusinessException → throw ex` + `catch Exception → BusinessException`(RETHROW,
|
||||
// 载荷损坏按异常拒绝回传不静默兜)。`JdResultIngestService`:⑤⑥ `parseState`/`writeJson`
|
||||
// → BusinessException(RETHROW,台账损坏显形);⑦ `toSummary` `catch IllegalArgumentException`
|
||||
// → BusinessException 带字段消息(RETHROW)。
|
||||
// 【Phase 5 后管,6 枚】① `AdminJdProductController.resolveOperator` 与 ②
|
||||
// `AdminJdProductGroupController.resolveOperator`:`catch BusinessException` ⇒ 先试内部令牌
|
||||
// 回退,回退失败把原鉴权异常原样重抛(RETHROW +2)。③④ 同两文件的
|
||||
// `resolveInternalOperator`:`catch NumberFormatException | BusinessException` ⇒ 返回 null ⇒
|
||||
// 上层把原 401/403 原样抛回(NOT_RETHROW +2)。⑤ `JdProductQueryService.parseAttrGroups`:
|
||||
// attr_json 解析 `catch Exception` ⇒ log.warn 带 productId + 空分组 + 原文透 attrJsonRaw
|
||||
// 兜底(AC-7 未识别属性不丢弃;NOT_RETHROW +1)。反向对照:改成往外抛=一条脏 attr_json
|
||||
// 让整行详情 500;改成静默空分组不带原文=用户看到的属性被悄悄吞掉。⑥
|
||||
// `JdProductQueryService.writeExportWorkbook`:SXSSF 落盘 `catch Exception` →
|
||||
// BusinessException「导出京东数据库失败,请稍后重试」(RETHROW +1,与 11-11 外观专利导出同款)。
|
||||
// 本批复核办法:单跑实测 total 1090、notRethrow 614、logOnly 194、empty 56(EMPTY 一格没涨)。
|
||||
static final int STRICT_TOTAL = 1090;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -453,7 +481,12 @@ class CatchSilenceRatchetTest {
|
||||
// 11-05 密钥余额三面:五枚 NOT_RETHROW(1065->1069 那批),严格口径实测 603 -> 608;
|
||||
// 上一格 604 是**上限**而实测量一直低它一枚,这次新增把那一枚额度用掉又超上去——逐处见 STRICT_TOTAL 上方。
|
||||
// 11-10 v1.3 同步链:严格口径实测 608 -> 611(三枚不重抛),出处见 STRICT_TOTAL 上方注释。
|
||||
static final int STRICT_NOT_RETHROW = 611;
|
||||
// 11-14 v1.4 京东数据库后管:严格口径实测 611 -> 614(三枚不重抛:两处 resolveInternalOperator
|
||||
// 返回 null + parseAttrGroups 的 attr_json 兜底),出处见 STRICT_TOTAL 上方注释。
|
||||
// 本格含 LOG_ONLY(incl 口径):同批 Phase 2 建单 scope 行那枚 DuplicateKeyException 复用
|
||||
// 先到行把 LOG_ONLY 抬 193 -> 194 时连带占本格一枚额度 ⇒ 614 -> 615(出处同 STRICT_TOTAL
|
||||
// 上方注释;这是本格**含 LOG_ONLY** 口径的连带,不是又一枚新的不重抛)。
|
||||
static final int STRICT_NOT_RETHROW = 615;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
@@ -487,7 +520,7 @@ class CatchSilenceRatchetTest {
|
||||
* 同日 Phase 5.1 再抬 189 -> 190:登记行落库失败后的对象回收失败只 WARN(同上锚点),
|
||||
* 主错误仍由外层转业务错误;不吞主错误。
|
||||
*/
|
||||
static final int STRICT_LOG_ONLY = 193; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1,见 STRICT_TOTAL 上方)
|
||||
static final int STRICT_LOG_ONLY = 194; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1、11-14 v1.4 建单 scope 行 DuplicateKeyException 复用先到行 +1,见 STRICT_TOTAL 上方)
|
||||
static final int STRICT_EMPTY = 56;
|
||||
|
||||
/**
|
||||
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
package com.nanri.aiimage.modules.jd.controller;
|
||||
|
||||
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.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
|
||||
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.JdProductQueryService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情/导出)与分组管理入口。
|
||||
*
|
||||
* <p>结构判据(照 {@code AdminAppearancePatentCleanItemsControllerTest} 双形态):
|
||||
* 端点只读、鉴权 seam、公司隔离正门、snake 参数带默认值、SQL 只落 XML;
|
||||
* 行为样本:mock HttpServletRequest 把 company 参数交给 readCompanyIdOrOwn 并装进 200 信封、
|
||||
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
|
||||
* tabs→attrGroups 解析与非法形状兜底(AC-7)。</p>
|
||||
*/
|
||||
class AdminJdProductControllerTest {
|
||||
|
||||
private static final Path MODULE = Path.of("").toAbsolutePath();
|
||||
private static final Path MAIN = MODULE.resolve("src/main/java/com/nanri/aiimage");
|
||||
private static final Path CONTROLLER =
|
||||
MAIN.resolve("modules/jd/controller/AdminJdProductController.java");
|
||||
private static final Path GROUP_CONTROLLER =
|
||||
MAIN.resolve("modules/jd/controller/AdminJdProductGroupController.java");
|
||||
private static final Path MAPPER = MAIN.resolve("modules/jd/mapper/JdProductMapper.java");
|
||||
private static final String COLUMN_KEY = "admin_jd_database";
|
||||
private static final String ROUTE_PATH = "jd-center/database";
|
||||
|
||||
// ===================== 结构判据 =====================
|
||||
|
||||
@Test
|
||||
void 控制器与只读端点就位() throws IOException {
|
||||
assertTrue(Files.exists(CONTROLLER), "控制器必须落在 " + CONTROLLER);
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
assertTrue(source.contains("/api/admin/jd-products"), "端点必须挂在 /api/admin/jd-products");
|
||||
assertTrue(source.contains("@GetMapping"), "查询端点必须落在 @GetMapping");
|
||||
assertTrue(source.contains("\"/{id}\""), "详情端点必须是 GET /{id}");
|
||||
assertTrue(source.contains("\"/export\""), "导出端点必须是 GET /export");
|
||||
// 本页只读(出表走导出端点):禁 POST/PUT/DELETE,分组管理另有同款鉴权闸的分组控制器。
|
||||
assertFalse(source.contains("@PostMapping") || source.contains("@PutMapping")
|
||||
|| source.contains("@DeleteMapping"),
|
||||
"京东数据库页只读:不得有 POST/PUT/DELETE(分组 CRUD 落 AdminJdProductGroupController)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 鉴权闸照外观专利只读页私有require形状() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
for (String seam : List.of("requireUser", "X-Internal-Token", "isSuper",
|
||||
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
|
||||
assertTrue(source.contains(seam), "鉴权闸缺接缝 " + seam
|
||||
+ "——照 AdminAppearancePatentCleanItemsController 私有 requireXxxAccess 形状"
|
||||
+ "(JWT→内部令牌回退→超管放行→菜单双匹配)");
|
||||
}
|
||||
assertTrue(source.contains("getColumnKey") && source.contains("getRoutePath"),
|
||||
"菜单权限必须 column_key/route_path 双匹配(默认不命中即拒)");
|
||||
assertTrue(source.contains("无权访问京东数据库"), "拒绝文案必须点名京东数据库");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 公司隔离走readCompanyIdOrOwn() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
assertTrue(source.contains("DataReadScope"), "公司隔离唯一出口是 DataReadScope");
|
||||
assertTrue(source.contains("readCompanyIdOrOwn"),
|
||||
"读侧必须走 readCompanyIdOrOwn:超管显式传才收窄,非超管强制本公司");
|
||||
assertFalse(source.contains("superAdminScopedCompanyId"),
|
||||
"不得走 superAdminScopedCompanyId:它对非超管返回 null=按行 company_id 查询时把整张表交给每一家");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分页参数snake且带默认值() throws IOException {
|
||||
String source = stripComments(Files.readString(CONTROLLER));
|
||||
for (String param : List.of("page_size", "shop_name", "product_code", "title_keyword",
|
||||
"sale_status", "group_id", "synced_from", "synced_to", "company_id")) {
|
||||
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
|
||||
}
|
||||
assertTrue(source.contains("PageDefaults"), "page/page_size 默认值必须取 PageDefaults"
|
||||
+ "(page_size 默认 20=PageDefaults.JD_PRODUCTS_PAGE_SIZE);"
|
||||
+ "page 钳制防 (page-1)*page_size 溢出的行为样本见查询服务钳制支(铁律 15)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 查询SQL只落XML不写注解SQL() throws IOException {
|
||||
assertTrue(Files.exists(MAPPER), "查询必须走 JdProductMapper(铁律 1)");
|
||||
String mapperSource = stripComments(Files.readString(MAPPER));
|
||||
assertFalse(mapperSource.matches("(?s).*@(Select|Insert|Update|Delete)\\s*\\(.*"),
|
||||
"不得新写注解 SQL(铁律 1:查询 SQL 全部落 XML Mapper)");
|
||||
assertTrue(mapperSource.contains("@Mapper"), "mapper 接口必须带 @Mapper");
|
||||
Path xml = findJdProductMapperXml();
|
||||
assertNotNull(xml, "mapper XML 必须落在 src/main/resources/mapper/**(铁律 1)");
|
||||
String xmlText = stripComments(Files.readString(xml));
|
||||
assertTrue(xmlText.contains("countProducts"), "XML 必须有 countProducts(只读页总数)");
|
||||
assertTrue(xmlText.contains("selectProductPage"), "XML 必须有 selectProductPage(只读页分页)");
|
||||
assertFalse(xmlText.contains("LIMIT #{page}"),
|
||||
"分页只收服务钳制后的 offset/limit,绝不 LIMIT #{page} 直拼(铁律 15)");
|
||||
assertTrue(xmlText.contains("ORDER BY p.synced_at DESC, p.id DESC"),
|
||||
"排序必须是 synced_at 倒序(同外观专利只读页口径)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分组控制器与同款鉴权闸就位() throws IOException {
|
||||
assertTrue(Files.exists(GROUP_CONTROLLER),
|
||||
"分组控制器必须落在 " + GROUP_CONTROLLER + "(AC-9:普通授权用户可读写分组)");
|
||||
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 + "(与商品页同款)");
|
||||
}
|
||||
// 普通(非超管)授权用户可读写分组:菜单双匹配那道闸在两个控制器上逐字同源。
|
||||
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
|
||||
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb + "(AC-9)");
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 行为样本 =====================
|
||||
|
||||
@Test
|
||||
void 控制器把公司参数交给readCompanyIdOrOwn并把结果装进200信封() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, authSupport, permissionMenuService, dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 超管显式传 company_id=5 ⇒ 正门把 5 交出来(不传时正门给 null=全量,同一行为样本家族)。
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
|
||||
JdProductPageVo pageVo = new JdProductPageVo();
|
||||
pageVo.setItems(List.of());
|
||||
pageVo.setTotal(0L);
|
||||
pageVo.setPage(1L);
|
||||
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
|
||||
when(queryService.page(1L, 20L, 5L, null, null, null, null, null, null, null)).thenReturn(pageVo);
|
||||
|
||||
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
|
||||
null, null, 5L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
|
||||
verify(queryService).page(1L, 20L, 5L, null, null, null, null, null, null, null);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
|
||||
assertEquals(pageVo, response.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 控制器详情走同一鉴权正门并回详情() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, authSupport, mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 详情不收 company 参数:超管不传=全量可见;非超管由正门强制本公司(服务按返回值收口)。
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, null)).thenReturn(null);
|
||||
JdProductDetailVo detailVo = new JdProductDetailVo();
|
||||
detailVo.setId(11L);
|
||||
when(queryService.detail(11L, null)).thenReturn(detailVo);
|
||||
|
||||
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, null);
|
||||
verify(queryService).detail(11L, null);
|
||||
assertEquals(Boolean.TRUE, response.isSuccess());
|
||||
assertEquals(detailVo, response.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 控制器导出走同一正门并回Excel响应() {
|
||||
JdProductQueryService queryService = mock(JdProductQueryService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
AdminJdProductController controller = new AdminJdProductController(
|
||||
queryService, authSupport, mock(PermissionMenuService.class), dataReadScope);
|
||||
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(7L);
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
|
||||
byte[] payload = "xlsx-bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
when(queryService.export(5L, null, null, null, null, null, null, null)).thenReturn(payload);
|
||||
|
||||
ResponseEntity<byte[]> response = controller.export(null, null, null, null, null, null, null,
|
||||
5L, request);
|
||||
|
||||
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
|
||||
verify(queryService).export(5L, null, null, null, null, null, null, null);
|
||||
assertEquals(MediaType.parseMediaType(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
|
||||
response.getHeaders().getContentType(), "导出必须是 xlsx Content-Type");
|
||||
assertTrue(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION).contains("filename*=UTF-8''"),
|
||||
"中文文件名必须带 filename* UTF-8 轨(DownloadHeaderUtil 双轨口径)");
|
||||
assertArrayEquals(payload, response.getBody(), "响应体必须原样是服务侧产出的字节");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 查询服务分页钳制防溢出() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
|
||||
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
|
||||
service.page(0L, null, null, null, null, null, null, null, null, null);
|
||||
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
|
||||
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), offset.capture(), limit.capture());
|
||||
assertEquals(0L, offset.getValue());
|
||||
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
|
||||
|
||||
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
|
||||
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null);
|
||||
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
|
||||
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
|
||||
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
|
||||
any(), any(), offsetMax.capture(), limitMax.capture());
|
||||
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
|
||||
assertEquals(100, limitMax.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 查询服务同步起止倒挂拒绝() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
|
||||
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.page(1L, 20L, null, null, null, null, null, null, from, to));
|
||||
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
|
||||
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
// 导出与分页共用同一过滤面校验(同一个拒绝时机:不碰 mapper)。
|
||||
BusinessException exportEx = assertThrows(BusinessException.class,
|
||||
() -> service.export(null, null, null, null, null, null, from, to));
|
||||
assertTrue(exportEx.getMessage().contains("开始时间不能晚于结束时间"),
|
||||
"导出端点必须同样拒绝倒挂时间,不得绕过分页页签的校验口径");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 查询服务过滤面原样直传且空串归null() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
|
||||
|
||||
// 超管显式传 5 ⇒ 按公司 5 筛(收窄);groupId ≤0 按没选分组处理;文本两侧空白剥掉。
|
||||
service.page(1L, 20L, 5L, " 店铺甲 ", " SKU-1 ", " 连衣裙 ", "上架中", 0L, null, null);
|
||||
verify(mapper).countProducts(eq(5L), eq("店铺甲"), eq("SKU-1"), eq("连衣裙"), eq("上架中"),
|
||||
isNull(), isNull(), isNull());
|
||||
// 全量(scopedCompanyId=null)⇒ companyId 不过滤。
|
||||
service.page(1L, 20L, null, null, null, null, null, null, null, null);
|
||||
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull());
|
||||
}
|
||||
|
||||
@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.JdProductGroupMapper.class));
|
||||
|
||||
JdProductEntity row = productEntity(11L);
|
||||
// 客户端实拍契约:tabs[{tab, attrs[{key,label,value}]}];value 允许数字型 JSON 值(转字符串)。
|
||||
row.setAttrJson("{\"tabs\":["
|
||||
+ "{\"tab\":\"商品基本信息\",\"attrs\":["
|
||||
+ "{\"key\":\"款号\",\"label\":\"货号\",\"value\":\"A123\"},"
|
||||
+ "{\"key\":\"颜色\",\"label\":\"颜色分类\",\"value\":3}]},"
|
||||
+ "{\"tab\":\"规格\",\"attrs\":[{\"key\":\"size\",\"label\":\"尺码\",\"value\":\"M\"}]}],"
|
||||
+ "\"images\":[],\"productCode\":\"A123\"}");
|
||||
when(mapper.selectById(11L)).thenReturn(row);
|
||||
JdProductImageEntity image = new JdProductImageEntity();
|
||||
image.setProductId(11L);
|
||||
image.setImageType("MAIN");
|
||||
image.setSortNo(0);
|
||||
image.setUrl("https://oss.aishufu.top/jd-products/a.jpg");
|
||||
image.setByteSize(1024L);
|
||||
image.setWidth(800);
|
||||
image.setHeight(800);
|
||||
when(imageMapper.selectList(any())).thenReturn(List.of(image));
|
||||
|
||||
JdProductDetailVo vo = service.detail(11L, 5L);
|
||||
|
||||
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
|
||||
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
|
||||
assertEquals(2, vo.getAttrGroups().get(0).getAttrs().size());
|
||||
assertEquals("货号", vo.getAttrGroups().get(0).getAttrs().get(0).getLabel());
|
||||
assertEquals("A123", vo.getAttrGroups().get(0).getAttrs().get(0).getValue());
|
||||
assertEquals("3", vo.getAttrGroups().get(0).getAttrs().get(1).getValue(),
|
||||
"数字型 value 转字符串下发(读侧不丢键)");
|
||||
assertEquals("规格", vo.getAttrGroups().get(1).getGroupName());
|
||||
assertNull(vo.getAttrJsonRaw(), "契约形状解析成功时不带原文兜底(原文只在不识别时透出)");
|
||||
assertEquals(1, vo.getImages().size());
|
||||
assertEquals("MAIN", vo.getImages().get(0).getImageType());
|
||||
assertEquals("https://oss.aishufu.top/jd-products/a.jpg", vo.getImages().get(0).getUrl(),
|
||||
"图片 URL 100% 自有域名(AC-4)");
|
||||
// 主表高频列直接从 entity 映射,不走 JSON。
|
||||
assertEquals("A123", vo.getProductCode());
|
||||
assertEquals(new BigDecimal("129.00"), vo.getPriceMin());
|
||||
}
|
||||
|
||||
@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.JdProductGroupMapper.class));
|
||||
|
||||
// 形状一:非法 JSON(解析异常)。
|
||||
JdProductEntity broken = productEntity(11L);
|
||||
broken.setAttrJson("{\"tabs\": [broken");
|
||||
when(mapper.selectById(11L)).thenReturn(broken);
|
||||
JdProductDetailVo brokenVo = service.detail(11L, 5L);
|
||||
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
|
||||
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
|
||||
|
||||
// 形状二:合法 JSON 但没有 tabs(形状不识别)。
|
||||
JdProductEntity foreign = productEntity(11L);
|
||||
foreign.setAttrJson("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}");
|
||||
when(mapper.selectById(11L)).thenReturn(foreign);
|
||||
JdProductDetailVo foreignVo = service.detail(11L, 5L);
|
||||
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
|
||||
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
|
||||
"未识别属性不丢弃:原文兜底透出(AC-7)");
|
||||
|
||||
// 形状三:attr_json 为空 ⇒ 空分组、无原文兜底。
|
||||
JdProductEntity blank = productEntity(11L);
|
||||
blank.setAttrJson(null);
|
||||
when(mapper.selectById(11L)).thenReturn(blank);
|
||||
JdProductDetailVo blankVo = service.detail(11L, 5L);
|
||||
assertTrue(blankVo.getAttrGroups().isEmpty());
|
||||
assertNull(blankVo.getAttrJsonRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 详情公司越界按不存在拒绝() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
|
||||
JdProductEntity row = productEntity(11L);
|
||||
row.setCompanyId(6L);
|
||||
when(mapper.selectById(11L)).thenReturn(row);
|
||||
|
||||
// 非超管(scopedCompanyId=5):行属公司 6 ⇒ 按「商品不存在」拒绝,不泄露跨公司行的存在性。
|
||||
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, 5L));
|
||||
assertTrue(ex.getMessage().contains("商品不存在"));
|
||||
// 超管不选公司(null)=全量可见。
|
||||
assertNotNull(service.detail(11L, null));
|
||||
// id 非法同样拒绝。
|
||||
assertThrows(BusinessException.class, () -> service.detail(0L, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 导出超上限按业务错误拒绝且不取数() {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
|
||||
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(JdProductQueryService.EXPORT_MAX_ROWS + 1);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.export(null, null, null, null, null, null, null, null));
|
||||
assertTrue(ex.getMessage().contains("超过导出上限"),
|
||||
"超上限必须给「缩小筛选范围」的可读文案,不能让用户等一次注定 OOM 的全量查询");
|
||||
verify(mapper, never()).selectProductPage(any(), any(), any(), any(), any(), any(), any(),
|
||||
any(), anyLong(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
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),
|
||||
groupMapper);
|
||||
|
||||
JdProductEntity grouped = productEntity(1L);
|
||||
grouped.setGroupId(3L);
|
||||
JdProductEntity missing = productEntity(2L);
|
||||
missing.setGroupId(99L);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
|
||||
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
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));
|
||||
|
||||
JdProductPageVo vo = service.page(1L, 20L, 5L, null, null, null, null, null, null, null);
|
||||
|
||||
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
|
||||
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
|
||||
verify(groupMapper, times(1)).selectBatchIds(any());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
/** 列表/详情用例共用的商品行夹具:归属公司 5,主字段齐备便于按字段对撞。 */
|
||||
private static JdProductEntity productEntity(long id) {
|
||||
JdProductEntity entity = new JdProductEntity();
|
||||
entity.setId(id);
|
||||
entity.setCompanyId(5L);
|
||||
entity.setShopId("shop-1");
|
||||
entity.setShopName("测试店铺");
|
||||
entity.setProductCode("A123");
|
||||
entity.setSkuId("SKU-1");
|
||||
entity.setTitle("测试连衣裙");
|
||||
entity.setBrand("Anker");
|
||||
entity.setCategoryPath("女装 > 连衣裙 > 碎花裙");
|
||||
entity.setPriceMin(new BigDecimal("129.00"));
|
||||
entity.setPriceMax(new BigDecimal("159.00"));
|
||||
entity.setStockTotal(300);
|
||||
entity.setSaleStatus("上架中");
|
||||
entity.setListTab("ONSALE");
|
||||
entity.setAttrCount(12);
|
||||
entity.setImageCount(1);
|
||||
entity.setSyncedAt(LocalDateTime.of(2026, 11, 14, 10, 30));
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static Path findJdProductMapperXml() throws IOException {
|
||||
Path resources = MODULE.resolve("src/main/resources/mapper");
|
||||
if (!Files.exists(resources)) {
|
||||
return null;
|
||||
}
|
||||
try (Stream<Path> files = Files.walk(resources)) {
|
||||
return files.filter(path -> path.getFileName().toString()
|
||||
.equals("JdProductMapper.xml")).findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
private static String stripComments(String source) {
|
||||
String noBlock = source.replaceAll("(?s)/\\*.*?\\*/", "");
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (String line : noBlock.split("\n", -1)) {
|
||||
int idx = line.indexOf("//");
|
||||
out.append(idx >= 0 ? line.substring(0, idx) : line).append('\n');
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.JdProductGroupEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
|
||||
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
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;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
|
||||
*
|
||||
* <p>判据:同公司重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行
|
||||
* (事务两步,AC-8)、越公司 id 操作按不存在拒绝(不泄露存在性)、productCount
|
||||
* 读侧现算统计(分组下拉展示用)。</p>
|
||||
*/
|
||||
class JdProductGroupServiceTest {
|
||||
|
||||
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
|
||||
private final JdProductMapper productMapper = mock(JdProductMapper.class);
|
||||
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
|
||||
|
||||
@BeforeEach
|
||||
void initTableInfo() {
|
||||
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
|
||||
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
JdProductEntity.class);
|
||||
}
|
||||
|
||||
// ===================== 新建 =====================
|
||||
|
||||
@Test
|
||||
void 新建同公司重名拒绝且不落库() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.create(5L, " 秋冬款 ", 2));
|
||||
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
|
||||
assertTrue(ex.getMessage().contains("同名分组"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500");
|
||||
verify(groupMapper, never()).insert(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建成功落公司归属与归一名() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
when(groupMapper.insert(any(JdProductGroupEntity.class))).thenAnswer(invocation -> {
|
||||
JdProductGroupEntity group = invocation.getArgument(0);
|
||||
group.setId(9L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
Long id = service.create(5L, " 秋冬款 ", 2);
|
||||
|
||||
assertEquals(9L, id);
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
JdProductGroupEntity saved = captor.getValue();
|
||||
assertEquals(5L, saved.getCompanyId(), "归属公司来自隔离正门的 scopedCompanyId,不是请求体");
|
||||
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
|
||||
assertEquals(2, saved.getSortOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建缺公司或空名直接拒绝() {
|
||||
// 超管没选公司(scopedCompanyId=null)=分组没有归属公司,直接拒绝。
|
||||
BusinessException noCompany = assertThrows(BusinessException.class,
|
||||
() -> service.create(null, "秋冬款", null));
|
||||
assertEquals(400, noCompany.getCode());
|
||||
BusinessException blankName = assertThrows(BusinessException.class,
|
||||
() -> service.create(5L, " ", null));
|
||||
assertEquals(400, blankName.getCode());
|
||||
verifyNoInteractions(groupMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 新建排序缺省归零() {
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.create(5L, "默认排序", null);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).insert(captor.capture());
|
||||
assertEquals(0, captor.getValue().getSortOrder(), "sortOrder 缺省 0(下拉按 sort_order, id 升序)");
|
||||
}
|
||||
|
||||
// ===================== 改名 =====================
|
||||
|
||||
@Test
|
||||
void 改名越公司id按不存在拒绝() {
|
||||
JdProductGroupEntity group = groupEntity(1L, 6L, "别家的组");
|
||||
when(groupMapper.selectById(1L)).thenReturn(group);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.rename(1L, 5L, "新名字", null));
|
||||
assertTrue(ex.getMessage().contains("分组不存在"),
|
||||
"越界 id 与 id 不存在是同一种响应,不泄露跨公司行的存在性");
|
||||
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名重名拒绝且不落库() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.rename(1L, 5L, "已有名", 3));
|
||||
assertEquals(409, ex.getCode());
|
||||
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名成功带归一名与排序() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, 5L, " 新名 ", 7);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
assertEquals("新名", captor.getValue().getName());
|
||||
assertEquals(7, captor.getValue().getSortOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改名排序不传保持原值() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
|
||||
when(groupMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
service.rename(1L, 5L, "只改名", null);
|
||||
|
||||
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
assertEquals(3, captor.getValue().getSortOrder(), "sortOrder 不传=保持原值(改名不改排序)");
|
||||
}
|
||||
|
||||
// ===================== 删除(AC-8 事务两步) =====================
|
||||
|
||||
@Test
|
||||
void 删除先把商品组置NULL再删分组行() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "秋冬款"));
|
||||
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
|
||||
|
||||
int detached = service.delete(1L, 5L);
|
||||
|
||||
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);
|
||||
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
|
||||
assertEquals(5L, ((Number) whereEq.get("company_id")).longValue(), "脱组必须限定本公司");
|
||||
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
|
||||
verify(groupMapper).deleteById(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除越公司id拒绝且一个字节都不写() {
|
||||
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 6L, "别家的组"));
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.delete(1L, 5L));
|
||||
verifyNoInteractions(productMapper);
|
||||
verify(groupMapper, never()).deleteById(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除分组不存在直接拒绝() {
|
||||
when(groupMapper.selectById(404L)).thenReturn(null);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.delete(404L, null));
|
||||
verifyNoInteractions(productMapper);
|
||||
}
|
||||
|
||||
// ===================== 列表(productCount 统计) =====================
|
||||
|
||||
@Test
|
||||
void 列表按排序返回且productCount现算() {
|
||||
JdProductGroupEntity first = groupEntity(2L, 5L, "晚出厂");
|
||||
first.setSortOrder(0);
|
||||
JdProductGroupEntity second = groupEntity(1L, 5L, "早出厂");
|
||||
second.setSortOrder(1);
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
|
||||
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
|
||||
|
||||
List<JdProductGroupVo> items = service.list(5L);
|
||||
|
||||
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(1, items.get(1).getSortOrder());
|
||||
verify(productMapper, times(2)).selectCount(any());
|
||||
assertNotNull(items.get(0).getCreatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 列表超管不选公司查全量() {
|
||||
when(groupMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
List<JdProductGroupVo> items = service.list(null);
|
||||
|
||||
assertTrue(items.isEmpty());
|
||||
verify(groupMapper).selectList(any());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
private static JdProductGroupEntity groupEntity(long id, long companyId, String name) {
|
||||
JdProductGroupEntity group = new JdProductGroupEntity();
|
||||
group.setId(id);
|
||||
group.setCompanyId(companyId);
|
||||
group.setName(name);
|
||||
group.setSortOrder(3);
|
||||
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
|
||||
return group;
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,13 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
|
||||
href: '/convert',
|
||||
permissionKeys: ['convert'],
|
||||
},
|
||||
{
|
||||
id: 'jd',
|
||||
name: '京东采集',
|
||||
desc: '采集京东店铺商品列表与详情全部属性,同步到后台京东数据库',
|
||||
href: '/jd-collect',
|
||||
permissionKeys: ['jd-collect', 'jd_collect'],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -280,6 +287,7 @@ export const TOOL_ICON_GRADIENTS: Record<string, string> = {
|
||||
shop: 'linear-gradient(180deg, #93C5FD, #3B82F6)',
|
||||
purchase: 'linear-gradient(180deg, #C4B5FD, #8B5CF6)',
|
||||
erp: 'linear-gradient(180deg, #F9A8D4, #EC4899)',
|
||||
jd: 'linear-gradient(180deg, #FCA5A5, #DC2626)',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -327,6 +335,8 @@ export const TOOL_ICON_SHAPES: Record<string, string> = {
|
||||
purchase: '<path d="M10 14 L34 14 L30 34 L14 34 Z"/><line x1="34" y1="14" x2="40" y2="14"/><line x1="40" y1="14" x2="38" y2="20"/><circle class="fill" cx="19" cy="39" r="3"/><circle class="fill" cx="33" cy="39" r="3"/>',
|
||||
// ERP:网格
|
||||
erp: '<rect x="8" y="8" width="32" height="32"/><line x1="24" y1="8" x2="24" y2="40"/><line x1="8" y1="24" x2="40" y2="24"/>',
|
||||
// 京东采集:商品袋
|
||||
jd: '<path d="M12 16 L36 16 L34 38 L14 38 Z"/><path d="M19 16 A 5 6 0 0 1 29 16"/><circle class="fill" cx="19" cy="26" r="2"/><circle class="fill" cx="29" cy="26" r="2"/>',
|
||||
}
|
||||
|
||||
export const TOOL_MAP: ReadonlyMap<string, ToolInfo> = new Map(
|
||||
@@ -349,6 +359,7 @@ export const TOOL_DETAILS: Readonly<Record<string, string>> = {
|
||||
qasin: '通过店小蜜导出出单 ASIN,上传后台,时不时排查是否还在店铺售卖,确保优质数据时刻在店。',
|
||||
scrape:
|
||||
'没排名、久未出单数据可优化删除;获取店铺所有数据的排名、品牌和销售情况。半个月到一个月复查一次品牌,确保数据没有被注册。',
|
||||
jd: '在本机已登录京麦的窗口里采集店铺商品(列表 + 详情全部属性 + 图片),同步到后台「京东数据库」。任务由本机客户端执行,提交后保持客户端在线。',
|
||||
}
|
||||
|
||||
export type VisibleGroup = ToolGroup & { tools: ToolInfo[] }
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { createJdCollectTask, type JdListTab } from '../../shared/api/types/modules/jd-collect.ts'
|
||||
|
||||
/** 京东店铺商品采集建单页(v1.4 AC-1,蓝图 §3.2)。
|
||||
*
|
||||
* 页面只做建单:任务落 PENDING、执行通道固定 LOCAL,由本机客户端在已登录京麦的
|
||||
* 窗口内领取执行;进度与结果到客户端任务列表(或后台「京东数据库」)查看。
|
||||
*/
|
||||
|
||||
const form = reactive({
|
||||
shopName: '',
|
||||
onsale: true,
|
||||
offsale: false,
|
||||
maxProducts: 0,
|
||||
})
|
||||
|
||||
const submitting = ref(false)
|
||||
const successMessage = ref('')
|
||||
const errorMessage = ref('')
|
||||
|
||||
function buildListTabs(): JdListTab[] {
|
||||
const tabs: JdListTab[] = []
|
||||
if (form.onsale) tabs.push('ONSALE')
|
||||
if (form.offsale) tabs.push('OFFSALE')
|
||||
return tabs
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
const tabs = buildListTabs()
|
||||
if (!form.shopName.trim()) {
|
||||
errorMessage.value = '请填写要采集的京东店铺名称'
|
||||
return
|
||||
}
|
||||
if (!tabs.length) {
|
||||
errorMessage.value = '请至少勾选一个商品页签(在售中 / 已下架)'
|
||||
return
|
||||
}
|
||||
submitting.value = true
|
||||
try {
|
||||
const vo = await createJdCollectTask(form.shopName.trim(), tabs, form.maxProducts)
|
||||
successMessage.value = `建单成功:任务号 ${vo.taskId}${vo.taskNo ? `(${vo.taskNo})` : ''}。` +
|
||||
'任务由本机客户端执行,请保持客户端在线并已登录京麦;采集进度在客户端任务列表查看,' +
|
||||
'落库数据到后台「京东数据库」菜单查询。'
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="jd-collect-page">
|
||||
<div class="jd-collect-panel">
|
||||
<h2>京东采集</h2>
|
||||
<p class="jd-collect-desc">
|
||||
采集京东店铺商品(列表 + 详情全部属性 + 图片),同步到后台「京东数据库」。
|
||||
任务由本机客户端执行:提交后请保持客户端在线,并确保已在客户端登录京麦。
|
||||
</p>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="jd-shop-name">京东店铺名称</label>
|
||||
<input
|
||||
id="jd-shop-name"
|
||||
v-model="form.shopName"
|
||||
type="text"
|
||||
placeholder="填写京麦后台显示的店铺名称"
|
||||
:disabled="submitting"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>采集商品页签</label>
|
||||
<div class="tab-checks">
|
||||
<label class="tab-check">
|
||||
<input v-model="form.onsale" type="checkbox" :disabled="submitting" />
|
||||
在售中
|
||||
</label>
|
||||
<label class="tab-check">
|
||||
<input v-model="form.offsale" type="checkbox" :disabled="submitting" />
|
||||
已下架
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="jd-max-products">采集商品数上限(0 = 不限制)</label>
|
||||
<input
|
||||
id="jd-max-products"
|
||||
v-model.number="form.maxProducts"
|
||||
type="number"
|
||||
min="0"
|
||||
:disabled="submitting"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button class="jd-submit" type="button" :disabled="submitting" @click="submit">
|
||||
{{ submitting ? '提交中…' : '开始采集' }}
|
||||
</button>
|
||||
|
||||
<p v-if="successMessage" class="jd-feedback success">{{ successMessage }}</p>
|
||||
<p v-if="errorMessage" class="jd-feedback error">{{ errorMessage }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.jd-collect-page {
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.jd-collect-panel {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.jd-collect-desc {
|
||||
color: #6b7280;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
margin: 8px 0 20px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #374151;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.form-group input[type='text'],
|
||||
.form-group input[type='number'] {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tab-checks {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.tab-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 14px;
|
||||
color: #374151;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.jd-submit {
|
||||
width: 100%;
|
||||
background: #2dd4bf;
|
||||
color: #062a26;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 10px 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.jd-submit:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.jd-feedback {
|
||||
margin-top: 16px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.jd-feedback.success {
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.jd-feedback.error {
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
</style>
|
||||
@@ -67,6 +67,11 @@ const routes = [
|
||||
name: 'appearance-patent',
|
||||
component: () => import('@/pages/brand/components/BrandAppearancePatentTab.vue'),
|
||||
},
|
||||
{
|
||||
path: '/jd-collect',
|
||||
name: 'jd-collect',
|
||||
component: () => import('@/pages/jd/JdCollectTab.vue'),
|
||||
},
|
||||
{
|
||||
path: '/split',
|
||||
name: 'split',
|
||||
|
||||
@@ -204,6 +204,12 @@ export const API_ENDPOINTS = {
|
||||
collectRouting: {
|
||||
get: '/api/collect-routing',
|
||||
},
|
||||
/** 京东店铺商品采集(v1.4):建单走 LOCAL 通道,由本机客户端在已登录京麦的窗口内执行。 */
|
||||
jdCollect: {
|
||||
create: '/api/jd-collect/tasks',
|
||||
heartbeat: '/api/jd-collect/tasks/{taskId}/heartbeat',
|
||||
chunk: '/api/jd-collect/tasks/{taskId}/chunk',
|
||||
},
|
||||
userSecret: {
|
||||
bundle: '/api/user-secrets',
|
||||
save: '/api/user-secrets/{moduleKey}',
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl } from '../../url.ts'
|
||||
import { getCurrentUserId } from '../../user.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
|
||||
/** 京东店铺采集建单回执(蓝图 §3.2):任务落 PENDING、执行通道固定 LOCAL,由本机客户端领取执行。 */
|
||||
export interface JdCollectTaskVo {
|
||||
taskId: number;
|
||||
taskNo?: string;
|
||||
collectChannel?: string;
|
||||
}
|
||||
|
||||
/** 可选采集 Tab(京麦商品列表页签):在售中 / 已下架。 */
|
||||
export type JdListTab = 'ONSALE' | 'OFFSALE'
|
||||
|
||||
/**
|
||||
* 建单(v1.4 AC-1):选择店铺 + 商品 Tab + 采集范围。未选店铺 / 未登记京麦登录态时
|
||||
* 服务端按蓝图 §3.2 拒绝并返回点名文案(业务码信封,unwrapJavaResponse 抛出)。
|
||||
*/
|
||||
export function createJdCollectTask(shopName: string, listTabs: JdListTab[], maxProducts = 0) {
|
||||
return unwrapJavaResponse(post<JavaApiResponse<JdCollectTaskVo>, Record<string, unknown>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.create),
|
||||
{
|
||||
user_id: getCurrentUserId(),
|
||||
shopName,
|
||||
listTabs,
|
||||
maxProducts,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
TOOL_MAP,
|
||||
} from '../src/pages/amazon/tool-catalog.ts'
|
||||
|
||||
test('工具目录:20 个工具 id 唯一且每个都有图标与渐变配色', () => {
|
||||
test('工具目录:21 个工具 id 唯一且每个都有图标与渐变配色', () => {
|
||||
const ids = TOOL_GROUPS.flatMap((g) => g.tools.map((t) => t.id))
|
||||
assert.equal(ids.length, 20, '工具总数应为 20(前端8 + 运营10 + 后勤2)')
|
||||
assert.equal(ids.length, 21, '工具总数应为 21(前端9 + 运营10 + 后勤2;v1.4 前端组加京东采集)')
|
||||
assert.equal(new Set(ids).size, ids.length, '工具 id 不应重复')
|
||||
for (const id of ids) {
|
||||
assert.ok(TOOL_ICON_SHAPES[id], `图标形状缺失: ${id}`)
|
||||
@@ -38,7 +38,7 @@ test('权限过滤:组键命中整组保留,未命中按工具权限过滤
|
||||
const frontOnly = filterGroupsByPermission(TOOL_GROUPS, ['brand_front_tools'])
|
||||
assert.equal(frontOnly.length, 1)
|
||||
assert.equal(frontOnly[0].key, 'front')
|
||||
assert.equal(frontOnly[0].tools.length, 8)
|
||||
assert.equal(frontOnly[0].tools.length, 9)
|
||||
|
||||
// 无组键时按单个工具权限过滤
|
||||
const partial = filterGroupsByPermission(TOOL_GROUPS, ['collect-data', 'publish'])
|
||||
|
||||
@@ -64,7 +64,9 @@ const BASELINE = {
|
||||
// 弹全局打扰会把用户下一次正常操作也打断,所以刻意不 ElMessage。
|
||||
// 按扫描器口径这一支不算静默(首条语句是状态写入、不是 console.*,console 只作留链),
|
||||
// 所以 silent 一格没涨、逐文件台账不动,只进 blocks。
|
||||
blocks: 312,
|
||||
// 313 = 312 + 1(2026-11-14 v1.4 Phase 5):JdCollectTab.vue 建单失败 catch 1 枚——错误经
|
||||
// errorMessage 显示给用户(非静默,故 perFile 台账不记;新文件没有 silent 形状)。
|
||||
blocks: 313,
|
||||
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
|
||||
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
|
||||
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
|
||||
|
||||
@@ -20,12 +20,12 @@ function readIfExists(path: string, what: string): string {
|
||||
return readFileSync(path, 'utf8')
|
||||
}
|
||||
|
||||
test('路由注册京东采集页', { skip: 'Pending Phase 5: 京东采集入口落地后激活' }, () => {
|
||||
test('路由注册京东采集页', () => {
|
||||
assert.ok(readIfExists(ROUTER, 'router/index.ts').includes('/jd-collect'),
|
||||
'router 缺 /jd-collect 路由')
|
||||
})
|
||||
|
||||
test('工具台卡片声明京东工具且带权限键', { skip: 'Pending Phase 5: 京东采集入口落地后激活' }, () => {
|
||||
test('工具台卡片声明京东工具且带权限键', () => {
|
||||
const catalog = readIfExists(TOOL_CATALOG, 'tool-catalog.ts')
|
||||
assert.ok(catalog.includes('jd-collect') || catalog.includes('京东采集'),
|
||||
'TOOL_GROUPS 缺京东采集工具卡')
|
||||
@@ -33,7 +33,7 @@ test('工具台卡片声明京东工具且带权限键', { skip: 'Pending Phase
|
||||
'京东工具卡必须声明非空 permissionKeys(显隐按后端 app 菜单 key 过滤)')
|
||||
})
|
||||
|
||||
test('endpoints 注册 jdCollect 端点组', { skip: 'Pending Phase 5: 京东采集入口落地后激活' }, () => {
|
||||
test('endpoints 注册 jdCollect 端点组', () => {
|
||||
assert.ok(readIfExists(ENDPOINTS, 'endpoints.ts').includes('jdCollect'),
|
||||
'endpoints.ts 缺 jdCollect 端点组(建单/心跳/回传三件)')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user