Compare commits

..

4 Commits

19 changed files with 496 additions and 116 deletions
@@ -2,8 +2,9 @@
/** 京东数据库页(v1.4 Phase 5):公司隔离的京东商品库,筛选行(店铺/商品编码/标题关键字/商品状态/ /** 京东数据库页(v1.4 Phase 5):公司隔离的京东商品库,筛选行(店铺/商品编码/标题关键字/商品状态/
* 分组/同步起止 date 对)+查询/导出/重置/管理分组 + 自绘明细表(勾选列+点行开详情抽屉) * 分组/同步起止 date 对)+查询/导出/重置/管理分组 + 自绘明细表(勾选列+点行开详情抽屉)
* + 删除(单行/批量,先删桶对象、全成功才删库行,确认弹窗点名数量)+ OldPagination。 * + 删除(单行/批量,先删桶对象、全成功才删库行,确认弹窗点名数量)+ OldPagination。
* 列表只摆部分字段(B104 用户口径「外边列表部分字段,详情显示全部属性」):类目/信息分/SKU 数/ * 列表按京麦商品列表样式(2026-11-15 用户口径):店铺/分组前置为第 1/2 列;商品信息列=京麦同款
* 上架时间/京东创建/修改时间不再上列表,全部收进详情抽屉基本信息。 * 合并布局(主图+图下信息分+标题两行+商品编码/货号+SKU 数标签,编码带一键复制);类目/上架
* 时间/京东创建/修改时间仍收详情抽屉基本信息(B104「详情显示全部属性」口径不变)。
* 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页); * 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页);
* 公司 tab 切换=清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、 * 公司 tab 切换=清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、
* 止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来(clampJdSyncedRange 照 clampDatePair)。 * 止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来(clampJdSyncedRange 照 clampDatePair)。
@@ -168,6 +169,17 @@ function closeDetail(): void {
detailItem.value = null detailItem.value = null
} }
/** 商品编码一键复制(京麦同款 ⧉):@click.stop 防冒泡开抽屉;剪贴板不可用(非安全上下文)时弹失败文案。 */
async function copyText(text: string): Promise<void> {
if (!text) return
try {
await navigator.clipboard.writeText(text)
showAdminFeedback(`已复制 ${text}`, 'success')
} catch {
showAdminFeedback('复制失败,请手动选择复制', 'error')
}
}
// ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ---------------- // ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ----------------
/** 本页勾选集(按行 id)。切页/切公司/重取后勾选清空——上一页勾的行不自动带到下一页。 */ /** 本页勾选集(按行 id)。切页/切公司/重取后勾选清空——上一页勾的行不自动带到下一页。 */
@@ -299,16 +311,13 @@ onMounted(() => {
<thead> <thead>
<tr> <tr>
<th style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th> <th style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
<th style="width: 76px">主图</th> <th style="width: 130px">店铺</th>
<th style="width: 96px">分组</th>
<th>商品信息</th> <th>商品信息</th>
<th style="width: 118px">商品编码</th> <th style="width: 90px">品牌</th>
<th style="width: 118px">货号</th> <th style="width: 110px">价格区间</th>
<th style="width: 96px">品牌</th>
<th style="width: 112px">价格区间</th>
<th style="width: 76px">总库存</th> <th style="width: 76px">总库存</th>
<th style="width: 86px">商品状态</th> <th style="width: 86px">商品状态</th>
<th style="width: 120px">店铺</th>
<th style="width: 100px">分组</th>
<th style="width: 170px">同步时间</th> <th style="width: 170px">同步时间</th>
</tr> </tr>
</thead> </thead>
@@ -316,27 +325,38 @@ onMounted(() => {
<template v-if="rows.length"> <template v-if="rows.length">
<tr v-for="row in rows" :key="row.id" class="jd-row" @click="openDetail(row)"> <tr v-for="row in rows" :key="row.id" class="jd-row" @click="openDetail(row)">
<td @click.stop><input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row, ($event.target as HTMLInputElement).checked)" /></td> <td @click.stop><input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row, ($event.target as HTMLInputElement).checked)" /></td>
<td> <td :title="row.shopName || ''">{{ row.shopName || '-' }}</td>
<img v-if="row.mainImageUrl" class="jd-thumb" :src="row.mainImageUrl" alt="" loading="lazy" /> <td :title="row.groupName || ''">{{ row.groupName || '未分组' }}</td>
<span v-else class="empty-mini">无图</span> <td class="jd-info-cell">
<div class="jd-info-wrap">
<div class="jd-info-figure">
<img v-if="row.mainImageUrl" class="jd-thumb" :src="row.mainImageUrl" alt="" loading="lazy" />
<span v-else class="jd-thumb jd-thumb-empty">无图</span>
<span v-if="row.healthScore !== null" class="jd-health">信息分 {{ row.healthScore }}</span>
</div>
<div class="jd-info-body">
<div class="jd-info-title" :title="row.title">{{ row.title || '-' }}</div>
<div class="jd-info-meta">
商品编码:<span class="jd-info-code">{{ row.productCode || '-' }}</span>
<button v-if="row.productCode" class="jd-copy-btn" type="button" title="复制商品编码" @click.stop="copyText(row.productCode)">⧉</button>
</div>
<div class="jd-info-meta">货号:<span class="jd-info-code">{{ row.itemNum || '-' }}</span></div>
<div v-if="row.skuCount" class="jd-info-tags"><span class="jd-tag">{{ row.skuCount }}个SKU</span></div>
</div>
</div>
</td> </td>
<td class="title-cell" :title="row.title">{{ row.title || '-' }}</td>
<td class="mono-cell">{{ row.productCode || '-' }}</td>
<td class="mono-cell">{{ row.itemNum || '-' }}</td>
<td>{{ row.brand || '-' }}</td> <td>{{ row.brand || '-' }}</td>
<td>{{ jdPriceRange(row) || '-' }}</td> <td>{{ jdPriceRange(row) || '-' }}</td>
<td>{{ row.stockTotal ?? '-' }}</td> <td>{{ row.stockTotal ?? '-' }}</td>
<td>{{ row.saleStatus || '-' }}</td> <td>{{ row.saleStatus || '-' }}</td>
<td :title="row.shopName || ''">{{ row.shopName || '-' }}</td>
<td :title="row.groupName || ''">{{ row.groupName || '未分组' }}</td>
<td>{{ formatDateTime(row.syncedAt || '') }}</td> <td>{{ formatDateTime(row.syncedAt || '') }}</td>
</tr> </tr>
</template> </template>
<tr v-else-if="loading"> <tr v-else-if="loading">
<td colspan="12" class="empty-tip">加载中...</td> <td colspan="9" class="empty-tip">加载中...</td>
</tr> </tr>
<tr v-else> <tr v-else>
<td colspan="12" class="empty-tip">暂无京东商品数据</td> <td colspan="9" class="empty-tip">暂无京东商品数据</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -522,7 +542,7 @@ h3 {
table-layout: fixed; table-layout: fixed;
} }
.jd-table-scroll > table { .jd-table-scroll > table {
min-width: 1360px; min-width: 1180px;
} }
.table-scroll th, .table-scroll th,
.table-scroll td { .table-scroll td {
@@ -563,16 +583,100 @@ h3 {
border-radius: 6px; border-radius: 6px;
background: #f2f7fb; background: #f2f7fb;
} }
.empty-mini { /* 商品信息列=京麦同款合并布局:td 的全局 nowrap/ellipsis 与多行内容冲突,本列放开换行,
截断交给内部各行(标题两行 line-clamp、编码/货号单行 ellipsis)。 */
.jd-info-cell {
white-space: normal;
text-overflow: clip;
}
.jd-info-wrap {
display: flex;
align-items: flex-start;
gap: 10px;
min-width: 0;
}
.jd-info-figure {
display: flex;
flex-direction: column;
align-items: center;
gap: 3px;
flex-shrink: 0;
}
.jd-thumb-empty {
display: flex;
align-items: center;
justify-content: center;
color: #8293a5; color: #8293a5;
font-size: 12px; font-size: 12px;
} }
.mono-cell { .jd-health {
font-family: "Cascadia Mono", "SF Mono", Consolas, "Courier New", monospace; color: #2e9e6b;
font-size: 12.5px; font-size: 11px;
line-height: 1.2;
white-space: nowrap;
} }
.title-cell { .jd-info-body {
max-width: 260px; min-width: 0;
display: flex;
flex-direction: column;
gap: 3px;
}
.jd-info-title {
color: #24384d;
font-size: 13.5px;
font-weight: 500;
line-height: 1.45;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-all;
}
.jd-info-meta {
display: flex;
align-items: center;
gap: 4px;
color: #7b8a99;
font-size: 12px;
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
}
.jd-info-code {
font-family: "Cascadia Mono", "SF Mono", Consolas, "Courier New", monospace;
color: #4e6479;
overflow: hidden;
text-overflow: ellipsis;
}
.jd-copy-btn {
flex-shrink: 0;
border: 0;
background: transparent;
color: #8aa5bf;
font-size: 12px;
cursor: pointer;
padding: 0 2px;
line-height: 1;
}
.jd-copy-btn:hover {
color: #3b82c4;
}
.jd-info-tags {
display: flex;
gap: 6px;
margin-top: 2px;
}
.jd-tag {
display: inline-flex;
align-items: center;
height: 18px;
padding: 0 6px;
border: 1px solid #cfe3f5;
border-radius: 3px;
background: #eef5fc;
color: #3b82c4;
font-size: 11.5px;
white-space: nowrap;
} }
.empty-tip { .empty-tip {
padding: 44px 24px; padding: 44px 24px;
@@ -98,42 +98,59 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品') expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
}) })
it('行内容只摆部分字段(B104 用户口径「外边列表部分字段」):勾选/主图/标题/编码/货号/品牌/价格/库存/状态/店铺/分组/同步(12 列),其余收进详情抽屉', async () => { it('行内容按京麦商品列表样式(2026-11-15 用户口径):勾选/店铺/分组/商品信息(图+标题+编码+货号+SKU/信息分)/品牌/价格/库存/状态/同步(9 列),类目等其余收进详情抽屉', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 }) const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const cells = wrapper.findAll('tbody tr')[0].findAll('td') const cells = wrapper.findAll('tbody tr')[0].findAll('td')
expect(cells).toHaveLength(12) expect(cells).toHaveLength(9)
expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框') expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框')
expect(cells[1].find('.jd-thumb').exists()).toBe(true, '第 2 列是主图') expect(cells[1].text()).toBe('旗舰自营店', '第 2 列=店铺(用户口径前置为第 1 数据列)')
expect(cells[2].text()).toContain('304不锈钢保温杯') expect(cells[2].text()).toBe('甲组', '第 3 列=分组')
expect(cells[3].text()).toBe('JD-1001') // 商品信息列=京麦同款合并布局:主图+信息分+标题+商品编码+货号+SKU 标签。
expect(cells[4].text()).toBe('ITEM-1', '货号列=京麦后台「货号」') const info = cells[3]
expect(cells[5].text()).toBe('锅宝') expect(info.find('.jd-thumb').exists()).toBe(true, '商品信息列含主图')
expect(cells[6].text()).toBe('12.90 ~ 15.90', '价格区间=min ~ max') expect(info.text()).toContain('304不锈钢保温杯')
expect(cells[7].text()).toBe('500', '总库存列') expect(info.text()).toContain('JD-1001', '商品编码并入商品信息列')
expect(cells[8].text()).toBe('上架中') expect(info.text()).toContain('ITEM-1', '货号并入商品信息列')
expect(cells[9].text()).toBe('旗舰自营店') expect(info.text()).toContain('12个SKU')
expect(cells[10].text()).toBe('甲组') expect(info.text()).toContain('信息分 81')
expect(cells[11].text()).not.toBe('-', '同步时间格式化展示') expect(cells[4].text()).toBe('锅宝')
// 从列表撤下的字段不许出现在表头(全部收进详情抽屉,见下方抽屉断言)。 expect(cells[5].text()).toBe('12.90 ~ 15.90', '价格区间=min ~ max')
expect(cells[6].text()).toBe('500', '总库存列')
expect(cells[7].text()).toBe('上架中')
expect(cells[8].text()).not.toBe('-', '同步时间格式化展示')
// 类目/上架时间/京东创建/修改时间仍收进详情抽屉(信息分/SKU 数 2026-11-15 起随京麦样式回列表)。
const headerText = wrapper.find('thead').text() const headerText = wrapper.find('thead').text()
for (const gone of ['类目', '信息分', 'SKU', '上架时间', '创建时间', '修改时间']) { for (const gone of ['类目', '上架时间', '创建时间', '修改时间']) {
expect(headerText).not.toContain(gone, `${gone}列已收进详情抽屉,不再上列表`) expect(headerText).not.toContain(gone, `${gone}列已收进详情抽屉,不再上列表`)
} }
expect(wrapper.find('.jd-thumb').exists()).toBe(true, '主图列渲染缩略图') expect(wrapper.find('.jd-thumb').exists()).toBe(true, '商品信息列渲染缩略图')
}) })
it('主图列:有自有桶 URL 才出图,没有就显示「无图」(不拿京东原图域名顶)', async () => { it('商品信息列:主图无 URL 显示「无图」占位、healthScore 为空不出信息分行、skuCount 为空不出 SKU 标签', async () => {
const wrapper = await mountWith({ const wrapper = await mountWith({
items: [item(1), item(2, { mainImageUrl: '' })], total: 2, page: 1, pageSize: 20, items: [item(1), item(2, { mainImageUrl: '', healthScore: null, skuCount: null })],
total: 2, page: 1, pageSize: 20,
}) })
const rowTexts = wrapper.findAll('tbody tr').map((tr) => tr.text()) const rowTexts = wrapper.findAll('tbody tr').map((tr) => tr.text())
expect(wrapper.findAll('.jd-thumb')).toHaveLength(1) expect(wrapper.findAll('img.jd-thumb')).toHaveLength(1, '只有有自有桶 URL 的行出真图(无图占位是 span,不冒充 img)')
expect(rowTexts[1]).toContain('无图') expect(rowTexts[1]).toContain('无图')
expect(rowTexts[1]).not.toContain('信息分')
expect(rowTexts[1]).not.toContain('个SKU')
})
it('商品编码旁复制按钮:写入剪贴板且不冒泡开抽屉', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '复制前抽屉未开')
await wrapper.findAll('.jd-copy-btn')[0].trigger('click')
expect(writeText).toHaveBeenCalledWith('JD-1001')
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '点复制按钮不冒泡开抽屉')
}) })
it('分组读不到的那行展示「未分组」(不猜名字)', async () => { it('分组读不到的那行展示「未分组」(不猜名字)', async () => {
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 }) const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
expect(wrapper.findAll('tbody tr')[0].findAll('td')[10].text()).toBe('未分组') expect(wrapper.findAll('tbody tr')[0].findAll('td')[2].text()).toBe('未分组')
}) })
it('筛选生效:店铺/编码/关键字/状态/分组/起止日期,查询回第一页重发', async () => { it('筛选生效:店铺/编码/关键字/状态/分组/起止日期,查询回第一页重发', async () => {
@@ -292,7 +309,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(drawerText).toContain('ITEM-1') expect(drawerText).toContain('ITEM-1')
expect(drawerText).toContain('信息分') expect(drawerText).toContain('信息分')
expect(drawerText).toContain('上架时间') expect(drawerText).toContain('上架时间')
// B104:从列表撤下的字段(类目/SKU 数/京东创建/修改时间)+店铺/分组,详情里全量可见。 // B104:详情里全量可见(店铺/分组 2026-11-15 起也上了列表,抽屉仍保留)。
expect(drawerText).toContain('家居 > 厨具 > 保温杯') expect(drawerText).toContain('家居 > 厨具 > 保温杯')
expect(drawerText).toContain('SKU 数') expect(drawerText).toContain('SKU 数')
expect(drawerText).toContain('京东创建时间') expect(drawerText).toContain('京东创建时间')
@@ -45,6 +45,24 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
@Param("syncedFrom") LocalDateTime syncedFrom, @Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo); @Param("syncedTo") LocalDateTime syncedTo);
/**
* 后管只读页分页查询(synced_at 倒序)。
*
* <p>{@code offset}/{@code limit} 必须是服务侧钳制后的值——page 钳制防
* {@code (page-1)*page_size} 溢出(铁律 15),mapper 不做第二次换算,避免两处各算各的。</p>
*/
/**
* 覆盖清理候选行(重爬覆盖语义,2026-11-15):本任务成功收尾时,同一公司、同一批店铺
* (shop_id 取本任务落过的行)、<b>不是本任务写的</b>、且所属任务已不在在飞
* (非 PENDING/RUNNING)的商品行 id。删除走 {@code JdProductRowDeleteService#deleteRows}
* (SKU/图片行随行级联),本查询只出 id 不删。
*
* <p>排除在飞任务行:同店铺并发两单时,先收尾的单不得把仍在跑的单已落的行抹掉
* (后收尾的单会在自己的收尾时清);空结果(本次全采到)返回空表不删。</p>
*/
List<Long> selectSupersededProductIds(@Param("companyId") Long companyId,
@Param("taskId") Long taskId);
/** /**
* 后管只读页分页查询(synced_at 倒序)。 * 后管只读页分页查询(synced_at 倒序)。
* *
@@ -36,12 +36,16 @@ import java.util.Map;
* 京东采集分片回传落库(v1.4 Phase 2,蓝图 §3.2 回传契约)。 * 京东采集分片回传落库(v1.4 Phase 2,蓝图 §3.2 回传契约)。
* *
* <p>链路:客户端回传 chunk → 归属解析({@code task.user_id -> users.company_id},读不出跳过 * <p>链路:客户端回传 chunk → 归属解析({@code task.user_id -> users.company_id},读不出跳过
* 不回填默认 1,铁律 30)→ 行 upsert(唯一出口 {@link JdProductMapper#upsertBatch}, * 不回填默认 1,铁律 30)→ 行 upsert(唯一出口 {@link JdProductMapper#upsertBatch})→
* upsert-only 不 delete,B94-01)→ 图片清单登记(Phase 4:直传完成的 objectKey 逐图 * 图片清单登记(Phase 4:直传完成的 objectKey 逐图
* statObject 对撞落 {@code biz_jd_product_image},唯一出口 * statObject 对撞落 {@code biz_jd_product_image},唯一出口
* {@link JdProductImageIngestService#registerTaskImages})→ * {@link JdProductImageIngestService#registerTaskImages})→
* scope 台账合并写(断点游标 + 批次号 + 累计行数)→ * scope 台账合并写(断点游标 + 批次号 + 累计行数)→
* {@code isEnd=true} 时任务落 SUCCESS。 * {@code isEnd=true} 时任务落 SUCCESS 并执行<b>覆盖清理</b>:同一店铺里本次没采到、
* 所属任务已不在在飞的旧行整行删掉(用户拍板 2026-11-15:重爬同一店铺直接覆盖旧数据)。
* 清理只在收尾时做且本次 {@code itemsReceived=0} 不清(B94-01 教训:载荷读不准的空回传
* 不得抹掉存量),在飞任务(PENDING/RUNNING)的行不动,删除本体走
* {@link JdProductRowDeleteService#deleteRows}(SKU/图片行级联)。</p>
* *
* <p>回传 payload 键集契约({@code JdIngestPayloadContractTest} 绊线钉住):顶层 * <p>回传 payload 键集契约({@code JdIngestPayloadContractTest} 绊线钉住):顶层
* {@code batchId / cursor / items / isEnd}(+ {@code error} 失败上报),行内 * {@code batchId / cursor / items / isEnd}(+ {@code error} 失败上报),行内
@@ -71,6 +75,7 @@ public class JdResultIngestService {
private final TaskProgressSnapshotService taskProgressSnapshotService; private final TaskProgressSnapshotService taskProgressSnapshotService;
private final JdProductImageIngestService jdProductImageIngestService; private final JdProductImageIngestService jdProductImageIngestService;
private final JdProductSkuIngestService jdProductSkuIngestService; private final JdProductSkuIngestService jdProductSkuIngestService;
private final JdProductRowDeleteService jdProductRowDeleteService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
public JdIngestChunkVo submitChunk(Long taskId, JdIngestChunkRequest request, boolean trustedErrorReporter) { public JdIngestChunkVo submitChunk(Long taskId, JdIngestChunkRequest request, boolean trustedErrorReporter) {
@@ -147,6 +152,7 @@ public class JdResultIngestService {
int itemsReceived = mergeScopeState(scope, request, request.getItems() == null ? 0 : request.getItems().size()); int itemsReceived = mergeScopeState(scope, request, request.getItems() == null ? 0 : request.getItems().size());
if (Boolean.TRUE.equals(request.getIsEnd())) { if (Boolean.TRUE.equals(request.getIsEnd())) {
finalizeSuccess(task, itemsReceived); finalizeSuccess(task, itemsReceived);
purgeSupersededRows(task, companyId, itemsReceived);
} }
JdIngestChunkVo vo = new JdIngestChunkVo(); JdIngestChunkVo vo = new JdIngestChunkVo();
vo.setAccept(true); vo.setAccept(true);
@@ -213,6 +219,39 @@ public class JdResultIngestService {
} }
} }
/**
* 覆盖清理(用户拍板 2026-11-15:重爬同一店铺直接覆盖旧数据,采集完成时清)。
*
* <p>只清「本次没采到」的旧行:同公司、同店铺(shop_id 取本任务落过的行)、
* task_id 不是本任务、且所属任务已不在在飞的行(在飞任务如 PENDING/RUNNING 的行不动,
* 同店铺并发两单时先收尾的单不得抹掉仍在跑的单的行,后收尾的单会在自己的收尾时清)。
* 删除本体走 {@link JdProductRowDeleteService#deleteRows}(SKU/图片行级联,同一事务)。</p>
*
* <p>两条护栏:① 本次 {@code itemsReceived=0} 不清(B94-01 教训——载荷读不准的空回传
* 一旦清库=存量整库抹掉);② 清理失败不推翻采集结果(新数据已完整落库且任务已落
* SUCCESS),但必须留痕不静默:error 日志+scope 台账记 lastError。</p>
*/
private void purgeSupersededRows(FileTaskEntity task, Long companyId, int itemsReceived) {
if (itemsReceived <= 0) {
log.warn("[{}] 收尾回传 0 行,跳过覆盖清理(B94-01:不清旧) taskId={}", LOG_TAG, task.getId());
return;
}
try {
List<Long> staleIds = jdProductMapper.selectSupersededProductIds(companyId, task.getId());
if (staleIds.isEmpty()) {
log.info("[{}] 覆盖清理无候选行(本次已覆盖全部旧行) taskId={}", LOG_TAG, task.getId());
return;
}
int deleted = jdProductRowDeleteService.deleteRows(staleIds);
log.info("[{}] 覆盖清理完成:本次没采到的旧行已删 taskId={} candidates={} deleted={}",
LOG_TAG, task.getId(), staleIds.size(), deleted);
} catch (Exception ex) {
log.error("[{}] 覆盖清理失败(本次采集数据已完整落库,仅旧数据未清,可重爬一次补清) taskId={}",
LOG_TAG, task.getId(), ex);
recordLastError(task.getId(), "覆盖清理失败(本次采集数据已完整落库,仅旧数据未清,可重爬一次补清)");
}
}
// ---------- scope 台账:断点游标合并写(铁律 30 / B84-01) ---------- // ---------- scope 台账:断点游标合并写(铁律 30 / B84-01) ----------
/** /**
@@ -60,6 +60,26 @@
synced_at = CURRENT_TIMESTAMP synced_at = CURRENT_TIMESTAMP
</insert> </insert>
<!-- 覆盖清理候选行(重爬覆盖语义,2026-11-15):本任务成功收尾后,同一公司同一批店铺里
不是本任务写、且所属任务已不在在飞(PENDING/RUNNING 不删——同店铺并发两单先收尾的
单不得抹掉仍在跑的单的行,后收尾的单会在自己的收尾时清)的商品行。
shop_id 取本任务落过的行的 DISTINCT 值(shop_id 缺省回落 shop_name,与 buildRow 同源),
删除本体走 JdProductRowDeleteService#deleteRows(SKU/图片行级联),本查询只出 id。 -->
<select id="selectSupersededProductIds" resultType="long">
SELECT p.id
FROM biz_jd_product p
WHERE p.company_id = #{companyId}
AND p.shop_id IN (
SELECT DISTINCT shop_id FROM biz_jd_product
WHERE company_id = #{companyId} AND task_id = #{taskId}
)
AND p.task_id != #{taskId}
AND NOT EXISTS (
SELECT 1 FROM biz_file_task t
WHERE t.id = p.task_id AND t.status IN ('PENDING', 'RUNNING')
)
</select>
<!-- 后管只读页(Phase 5,v1.4)过滤面:公司(物化列 eq)、店铺名/商品编码/标题关键词 <!-- 后管只读页(Phase 5,v1.4)过滤面:公司(物化列 eq)、店铺名/商品编码/标题关键词
(contains LIKE)、商品状态 eq、分组 eq、同步起止(datetime 闭区间)。 (contains LIKE)、商品状态 eq、分组 eq、同步起止(datetime 闭区间)。
全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 --> 全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 -->
@@ -82,6 +82,8 @@ class JdProductSyncServiceTest {
private JdProductImageIngestService jdProductImageIngestService; private JdProductImageIngestService jdProductImageIngestService;
@Mock @Mock
private JdProductSkuIngestService jdProductSkuIngestService; private JdProductSkuIngestService jdProductSkuIngestService;
@Mock
private JdProductRowDeleteService jdProductRowDeleteService;
@Spy @Spy
private ObjectMapper objectMapper = new ObjectMapper(); private ObjectMapper objectMapper = new ObjectMapper();
@@ -317,6 +319,91 @@ class JdProductSyncServiceTest {
verify(taskProgressSnapshotService).markTerminal(eq(TASK_ID), eq("JD_SHOP_COLLECT"), eq("SUCCESS"), anyString()); verify(taskProgressSnapshotService).markTerminal(eq(TASK_ID), eq("JD_SHOP_COLLECT"), eq("SUCCESS"), anyString());
} }
// ---------- 覆盖清理(2026-11-15 用户拍板:重爬同一店铺,采集完成时清掉旧数据) ----------
@Test
void 成功收尾后清掉本次没采到的旧行() {
stubHappyPath();
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
// 同店铺旧行:上次采集落的、本次没采到的商品行
when(jdProductMapper.selectSupersededProductIds(COMPANY_ID, TASK_ID)).thenReturn(List.of(901L, 902L));
when(jdProductRowDeleteService.deleteRows(anyList())).thenReturn(2);
JdIngestChunkRequest request = chunk(item("10036442942137", "艺考形体服女"));
request.setIsEnd(true);
JdIngestChunkVo vo = service.submitChunk(TASK_ID, request, true);
assertThat(vo.isAccept()).isTrue();
// 删除走行级联唯一出口(SKU/图片行随删),候选 id 原样透传
verify(jdProductRowDeleteService).deleteRows(List.of(901L, 902L));
// 删除只发生在收尾之后:先落库,后清理
org.mockito.InOrder order = inOrder(jdProductMapper, jdProductRowDeleteService);
order.verify(jdProductMapper).upsertBatch(anyList());
order.verify(jdProductMapper).selectSupersededProductIds(COMPANY_ID, TASK_ID);
order.verify(jdProductRowDeleteService).deleteRows(anyList());
}
@Test
void 收尾回传0行不清旧_B94_01() {
stubHappyPath();
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
// 全程累计 0 行的收尾(载荷读不准的空回传):不清旧——清了=存量整库抹掉(B94-01 实录)
TaskScopeStateEntity emptyScope = scopeRow();
emptyScope.setStateJson("{\"cursor\":{},\"itemsReceived\":0,\"lastBatchId\":null}");
when(collectTaskService.findScopeRow(TASK_ID)).thenReturn(emptyScope);
JdIngestChunkRequest request = chunk();
request.setItems(List.of());
request.setIsEnd(true);
JdIngestChunkVo vo = service.submitChunk(TASK_ID, request, true);
assertThat(vo.isAccept()).isTrue();
verify(jdProductMapper, never()).selectSupersededProductIds(any(), any());
verify(jdProductRowDeleteService, never()).deleteRows(anyList());
}
@Test
void 非isEnd分片不触发覆盖清理() {
stubHappyPath();
service.submitChunk(TASK_ID, chunk(item("10036442942137", "艺考形体服女")), true);
verify(jdProductMapper, never()).selectSupersededProductIds(any(), any());
verify(jdProductRowDeleteService, never()).deleteRows(anyList());
}
@Test
void 覆盖清理失败不推翻回执且台账留痕() {
stubHappyPath();
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
when(jdProductMapper.selectSupersededProductIds(COMPANY_ID, TASK_ID))
.thenThrow(new RuntimeException("db down"));
JdIngestChunkRequest request = chunk(item("10036442942137", "艺考形体服女"));
request.setIsEnd(true);
JdIngestChunkVo vo = service.submitChunk(TASK_ID, request, true);
// 新数据已完整落库且任务已 SUCCESS:清理失败不改回执、不炸整批,但必须留痕不静默
assertThat(vo.isAccept()).isTrue();
verify(jdProductRowDeleteService, never()).deleteRows(anyList());
ArgumentCaptor<TaskScopeStateEntity> scopeCaptor = ArgumentCaptor.forClass(TaskScopeStateEntity.class);
verify(taskScopeStateMapper, times(2)).updateById(scopeCaptor.capture());
assertThat(scopeCaptor.getAllValues().stream().map(TaskScopeStateEntity::getStateJson))
.anySatisfy(json -> assertThat(json).contains("覆盖清理失败"));
}
@Test
void 覆盖清理SQL必须排除在飞任务行_绊线() throws Exception {
// 同店铺并发两单:先收尾的单不得把仍在跑(PENDING/RUNNING)的单已落的行抹掉,
// 该排除必须钉在 SQL 侧(铁律 20),改回 Java 过滤或删掉守卫即红。
String xml = Files.readString(Path.of("src/main/resources/mapper/jd/JdProductMapper.xml"));
String purgeSql = xml.substring(xml.indexOf("selectSupersededProductIds"));
assertThat(purgeSql)
.contains("status IN ('PENDING', 'RUNNING')")
.contains("p.task_id != #{taskId}")
.contains("SELECT DISTINCT shop_id FROM biz_jd_product");
}
@Test @Test
void 京麦登录态失效整单落FAILED且不落库() { void 京麦登录态失效整单落FAILED且不落库() {
lenient().when(fileTaskMapper.selectById(TASK_ID)).thenReturn(runningTask()); lenient().when(fileTaskMapper.selectById(TASK_ID)).thenReturn(runningTask());
@@ -656,22 +656,25 @@ async function loadHistory() {
} }
} }
async function deleteTaskRecord(item: CollectDataHistoryItem) { async function deleteTaskRecord(item: CollectDataHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.resultId) { if (item.resultId) {
await deleteCollectDataHistory(item.resultId) await deleteCollectDataHistory(item.resultId)
} else if (item.taskId) { } else if (item.taskId) {
await deleteCollectDataTask(item.taskId) await deleteCollectDataTask(item.taskId)
} else { } else {
if (opts.silent) throw new Error('缺少记录标识')
return return
} }
if (item.taskId) { if (item.taskId) {
progressLoop.remove(item.taskId) progressLoop.remove(item.taskId)
} }
if (opts.silent) return
ElMessage.success('已删除') ElMessage.success('已删除')
await Promise.all([loadDashboard(), loadHistory()]) await Promise.all([loadDashboard(), loadHistory()])
} catch (error) { } catch (error) {
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : '删除失败') ElMessage.error(error instanceof Error ? error.message : '删除失败')
} }
} }
@@ -764,13 +767,15 @@ onBeforeUnmount(() => {
}) })
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadDashboard(), loadHistory()])
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -1149,8 +1149,8 @@ async function downloadResult(item: PatrolDeleteHistoryItem) {
} }
} }
async function deleteTaskRecord(item: PatrolDeleteHistoryItem) { async function deleteTaskRecord(item: PatrolDeleteHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.taskId) { if (item.taskId) {
await deletePatrolDeleteTask(item.taskId); await deletePatrolDeleteTask(item.taskId);
@@ -1163,6 +1163,7 @@ async function deleteTaskRecord(item: PatrolDeleteHistoryItem) {
throw new Error("缺少可删除的任务标识"); throw new Error("缺少可删除的任务标识");
} }
removeHistoryItemLocally(item); removeHistoryItemLocally(item);
if (opts.silent) return
await Promise.allSettled([loadCandidates(), refreshTaskViews()]); await Promise.allSettled([loadCandidates(), refreshTaskViews()]);
ElMessage.success("已删除"); ElMessage.success("已删除");
} catch (error) { } catch (error) {
@@ -1171,10 +1172,12 @@ async function deleteTaskRecord(item: PatrolDeleteHistoryItem) {
clearActiveQueueTask(); clearActiveQueueTask();
} }
removeHistoryItemLocally(item); removeHistoryItemLocally(item);
if (opts.silent) return
await loadCandidates(); await loadCandidates();
ElMessage.success("记录已不存在,已同步移除本地记录"); ElMessage.success("记录已不存在,已同步移除本地记录");
return; return;
} }
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : "删除失败"); ElMessage.error(error instanceof Error ? error.message : "删除失败");
} }
} }
@@ -1206,13 +1209,15 @@ onUnmounted(() => {
}); });
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadCandidates(), refreshTaskViews()])
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -1699,8 +1699,8 @@ async function downloadResult(item: PriceTrackHistoryItem) {
} }
} }
async function deleteTaskRecord(item: PriceTrackHistoryItem) { async function deleteTaskRecord(item: PriceTrackHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.resultId != null) { if (item.resultId != null) {
await deletePriceTrackHistory(item.resultId) await deletePriceTrackHistory(item.resultId)
@@ -1712,6 +1712,7 @@ async function deleteTaskRecord(item: PriceTrackHistoryItem) {
} }
if (item.taskId != null) removePollingTask(item.taskId) if (item.taskId != null) removePollingTask(item.taskId)
removeMatchedRowsLocally([item]) removeMatchedRowsLocally([item])
if (opts.silent) return
await loadHistory() await loadHistory()
await loadDashboard() await loadDashboard()
syncPollingIdsWithHistory() syncPollingIdsWithHistory()
@@ -1721,11 +1722,13 @@ async function deleteTaskRecord(item: PriceTrackHistoryItem) {
if (item.taskId != null) removePollingTask(item.taskId) if (item.taskId != null) removePollingTask(item.taskId)
removeMatchedRowsLocally([item]) removeMatchedRowsLocally([item])
removeHistoryItemLocally(item) removeHistoryItemLocally(item)
if (opts.silent) return
await loadDashboard() await loadDashboard()
syncPollingIdsWithHistory() syncPollingIdsWithHistory()
ElMessage.success('记录已不存在,已同步移除本地记录') ElMessage.success('记录已不存在,已同步移除本地记录')
return return
} }
if (opts.silent) throw e
ElMessage.error(e instanceof Error ? e.message : '删除失败') ElMessage.error(e instanceof Error ? e.message : '删除失败')
} }
} }
@@ -1773,13 +1776,16 @@ onUnmounted(() => {
}) })
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadHistory(), loadDashboard()])
syncPollingIdsWithHistory()
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -522,14 +522,15 @@ function syncPollingIdsWithHistory() {
} }
} }
async function deleteTaskRecord(item: ProductRiskHistoryItem) { async function deleteTaskRecord(item: ProductRiskHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.resultId != null && item.resultId > 0) { if (item.resultId != null && item.resultId > 0) {
await deleteProductRiskHistory(item.resultId) await deleteProductRiskHistory(item.resultId)
} else if (item.taskId != null && item.taskId > 0) { } else if (item.taskId != null && item.taskId > 0) {
await deleteProductRiskTask(item.taskId) await deleteProductRiskTask(item.taskId)
} else { } else {
if (opts.silent) throw new Error('缺少记录标识')
ElMessage.warning('无法删除:缺少记录标识') ElMessage.warning('无法删除:缺少记录标识')
return return
} }
@@ -537,6 +538,7 @@ async function deleteTaskRecord(item: ProductRiskHistoryItem) {
removePollingTask(item.taskId) removePollingTask(item.taskId)
} }
removeMatchedRowsLocally([item]) removeMatchedRowsLocally([item])
if (opts.silent) return
await loadHistory() await loadHistory()
await loadDashboard() await loadDashboard()
syncPollingIdsWithHistory() syncPollingIdsWithHistory()
@@ -548,11 +550,13 @@ async function deleteTaskRecord(item: ProductRiskHistoryItem) {
} }
removeMatchedRowsLocally([item]) removeMatchedRowsLocally([item])
removeHistoryItemLocally(item) removeHistoryItemLocally(item)
if (opts.silent) return
await loadDashboard() await loadDashboard()
syncPollingIdsWithHistory() syncPollingIdsWithHistory()
ElMessage.success('记录已不存在,已同步移除本地记录') ElMessage.success('记录已不存在,已同步移除本地记录')
return return
} }
if (opts.silent) throw e
ElMessage.error(e instanceof Error ? e.message : '删除失败') ElMessage.error(e instanceof Error ? e.message : '删除失败')
} }
} }
@@ -1314,13 +1318,16 @@ onUnmounted(() => {
}) })
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadHistory(), loadDashboard()])
syncPollingIdsWithHistory()
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -1091,30 +1091,34 @@ function removeTaskLocally(taskId: number) {
saveQueueState() saveQueueState()
} }
async function deleteTaskRecord(detail: PublishTaskDetailVo) { async function deleteTaskRecord(detail: PublishTaskDetailVo, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
const taskId = detail.task?.id const taskId = detail.task?.id
if (!taskId || isDeletingTask(taskId)) return if (!taskId || isDeletingTask(taskId)) return
try { if (!opts.skipConfirm) {
await ElMessageBox.confirm( try {
`确定删除上架任务 #${taskId}?任务明细和结果文件也会一并删除。`, await ElMessageBox.confirm(
'删除任务', `确定删除上架任务 #${taskId}?任务明细和结果文件也会一并删除。`,
{ '删除任务',
confirmButtonText: '删除', {
cancelButtonText: '取消', confirmButtonText: '删除',
type: 'warning', cancelButtonText: '取消',
}, type: 'warning',
) },
} catch { )
return } catch {
return
}
} }
deletingTaskIds.value = [...deletingTaskIds.value, taskId] deletingTaskIds.value = [...deletingTaskIds.value, taskId]
try { try {
await deletePublishTask(taskId) await deletePublishTask(taskId)
removeTaskLocally(taskId) removeTaskLocally(taskId)
if (opts.silent) return
ElMessage.success('任务已删除') ElMessage.success('任务已删除')
await Promise.all([loadDashboard(), loadHistory()]) await Promise.all([loadDashboard(), loadHistory()])
} catch (error) { } catch (error) {
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : '删除任务失败') ElMessage.error(error instanceof Error ? error.message : '删除任务失败')
} finally { } finally {
deletingTaskIds.value = deletingTaskIds.value.filter((id) => id !== taskId) deletingTaskIds.value = deletingTaskIds.value.filter((id) => id !== taskId)
@@ -1142,13 +1146,15 @@ onBeforeUnmount(() => {
}) })
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadDashboard(), loadHistory()])
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -1058,8 +1058,8 @@ async function downloadResult(item: QueryAsinHistoryItem) {
} }
} }
async function deleteTaskRecord(item: QueryAsinHistoryItem) { async function deleteTaskRecord(item: QueryAsinHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.taskId) { if (item.taskId) {
await deleteQueryAsinTask(item.taskId); await deleteQueryAsinTask(item.taskId);
@@ -1073,6 +1073,7 @@ async function deleteTaskRecord(item: QueryAsinHistoryItem) {
} else { } else {
throw new Error("缺少可删除的任务标识"); throw new Error("缺少可删除的任务标识");
} }
if (opts.silent) return
await Promise.all([loadCandidates(), refreshTaskViews()]); await Promise.all([loadCandidates(), refreshTaskViews()]);
resetQueueWorkerIfIdle(); resetQueueWorkerIfIdle();
ElMessage.success("已删除"); ElMessage.success("已删除");
@@ -1083,11 +1084,13 @@ async function deleteTaskRecord(item: QueryAsinHistoryItem) {
} }
clearTaskStartTime(item.taskId); clearTaskStartTime(item.taskId);
removeHistoryItemLocally(item); removeHistoryItemLocally(item);
if (opts.silent) return
await loadCandidates(); await loadCandidates();
resetQueueWorkerIfIdle(); resetQueueWorkerIfIdle();
ElMessage.success("记录已不存在,已同步移除本地记录"); ElMessage.success("记录已不存在,已同步移除本地记录");
return; return;
} }
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : "删除失败"); ElMessage.error(error instanceof Error ? error.message : "删除失败");
} }
} }
@@ -1118,13 +1121,16 @@ onUnmounted(() => {
}); });
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadCandidates(), refreshTaskViews()])
resetQueueWorkerIfIdle();
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -616,12 +616,12 @@ async function downloadResult(item: ShopDataCrawlHistoryItem) {
if (result.success) ElMessage.success(`已保存:${result.path || filename}`) if (result.success) ElMessage.success(`已保存:${result.path || filename}`)
else if (result.error && result.error !== '用户取消') ElMessage.error(userNotice(result.error)) else if (result.error && result.error !== '用户取消') ElMessage.error(userNotice(result.error))
} }
async function deleteTaskRecord(item: ShopDataCrawlHistoryItem) { async function deleteTaskRecord(item: ShopDataCrawlHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (!item.taskId && !item.resultId) { if (!item.taskId && !item.resultId) {
historyItems.value = historyItems.value.filter((row) => row !== item) historyItems.value = historyItems.value.filter((row) => row !== item)
ElMessage.success('已删除') if (!opts.silent) ElMessage.success('已删除')
return return
} }
if (item.taskId && !isTerminal(item.taskStatus)) await deleteShopDataCrawlTask(item.taskId) if (item.taskId && !isTerminal(item.taskStatus)) await deleteShopDataCrawlTask(item.taskId)
@@ -630,8 +630,12 @@ async function deleteTaskRecord(item: ShopDataCrawlHistoryItem) {
else throw new Error('缺少记录标识') else throw new Error('缺少记录标识')
if (item.taskId === activeTaskId.value) clearActiveTask() if (item.taskId === activeTaskId.value) clearActiveTask()
historyItems.value = historyItems.value.filter((row) => historyKey(row) !== historyKey(item)) historyItems.value = historyItems.value.filter((row) => historyKey(row) !== historyKey(item))
if (opts.silent) return
await loadDashboard(); ElMessage.success('已删除') await loadDashboard(); ElMessage.success('已删除')
} catch (error) { ElMessage.error(error instanceof Error ? error.message : '删除失败') } } catch (error) {
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : '删除失败')
}
} }
onMounted(async () => { onMounted(async () => {
@@ -655,13 +659,15 @@ onUnmounted(() => {
}) })
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await loadDashboard().catch(() => undefined)
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -635,8 +635,8 @@ function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskSt
// 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载 // 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载
function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && (!!item.fileReady || !!item.downloadUrl) && (status === 'SUCCESS' || status === 'COMPLETED' || status === 'FAILED') } function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && (!!item.fileReady || !!item.downloadUrl) && (status === 'SUCCESS' || status === 'COMPLETED' || status === 'FAILED') }
async function downloadResult(item: ShopMatchHistoryItem) { if (!item.resultId) return; const url = getShopMatchResultDownloadUrl(item.resultId); const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx`; const result = await saveUrlWithProgress(url, filename, `shop-match:${item.resultId}`); if (result.success) ElMessage.success(`已保存: ${result.path || filename}`); else if (result.error && result.error !== '用户取消') ElMessage.error(userNotice(result.error)) } async function downloadResult(item: ShopMatchHistoryItem) { if (!item.resultId) return; const url = getShopMatchResultDownloadUrl(item.resultId); const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx`; const result = await saveUrlWithProgress(url, filename, `shop-match:${item.resultId}`); if (result.success) ElMessage.success(`已保存: ${result.path || filename}`); else if (result.error && result.error !== '用户取消') ElMessage.error(userNotice(result.error)) }
async function deleteTaskRecord(item: ShopMatchHistoryItem) { async function deleteTaskRecord(item: ShopMatchHistoryItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
const taskId = normalizeTaskId(item.taskId) const taskId = normalizeTaskId(item.taskId)
const resultId = Number(item.resultId || 0) const resultId = Number(item.resultId || 0)
try { try {
@@ -650,6 +650,7 @@ async function deleteTaskRecord(item: ShopMatchHistoryItem) {
} else { } else {
throw new Error('缺少可删除的任务标识') throw new Error('缺少可删除的任务标识')
} }
if (opts.silent) return
await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()]) await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()])
ElMessage.success('删除成功') ElMessage.success('删除成功')
} catch (error) { } catch (error) {
@@ -660,10 +661,12 @@ async function deleteTaskRecord(item: ShopMatchHistoryItem) {
historyItems.value = historyItems.value.filter((row) => Number(row.resultId || 0) !== resultId) historyItems.value = historyItems.value.filter((row) => Number(row.resultId || 0) !== resultId)
} }
removeMatchedRowsLocally([item]) removeMatchedRowsLocally([item])
if (opts.silent) return
await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()]) await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()])
ElMessage.success('记录已不存在,本地记录已同步清理') ElMessage.success('记录已不存在,本地记录已同步清理')
return return
} }
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : '删除失败') ElMessage.error(error instanceof Error ? error.message : '删除失败')
} }
} }
@@ -678,11 +681,16 @@ onUnmounted(() => { disposed = true; stopPolling(); stopScheduleHeartbeat(); cle
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/ */
/**
* 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadHistory(), loadCandidates(), loadDashboard()])
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -1102,8 +1102,8 @@ async function downloadResult(item: WithdrawTaskGroupItem) {
} }
} }
async function deleteTaskRecord(item: WithdrawTaskGroupItem) { async function deleteTaskRecord(item: WithdrawTaskGroupItem, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
try { try {
if (item.taskId) { if (item.taskId) {
await deleteWithdrawTask(item.taskId); await deleteWithdrawTask(item.taskId);
@@ -1117,6 +1117,7 @@ async function deleteTaskRecord(item: WithdrawTaskGroupItem) {
} else { } else {
throw new Error("缺少可删除的任务标识"); throw new Error("缺少可删除的任务标识");
} }
if (opts.silent) return
await Promise.all([loadCandidates(), refreshTaskViews()]); await Promise.all([loadCandidates(), refreshTaskViews()]);
resetQueueWorkerIfIdle(); resetQueueWorkerIfIdle();
ElMessage.success("已删除"); ElMessage.success("已删除");
@@ -1127,11 +1128,13 @@ async function deleteTaskRecord(item: WithdrawTaskGroupItem) {
} }
clearTaskStartTime(item.taskId); clearTaskStartTime(item.taskId);
removeHistoryItemLocally(item); removeHistoryItemLocally(item);
if (opts.silent) return
await loadCandidates(); await loadCandidates();
resetQueueWorkerIfIdle(); resetQueueWorkerIfIdle();
ElMessage.success("记录已不存在,已同步移除本地记录"); ElMessage.success("记录已不存在,已同步移除本地记录");
return; return;
} }
if (opts.silent) throw error
ElMessage.error(error instanceof Error ? error.message : "删除失败"); ElMessage.error(error instanceof Error ? error.message : "删除失败");
} }
} }
@@ -1161,13 +1164,16 @@ onUnmounted(() => {
}); });
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表) * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已确认过一次,全部删完统一刷新一次、只报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view))) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view), { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadCandidates(), refreshTaskViews()])
resetQueueWorkerIfIdle();
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
+11 -1
View File
@@ -109,7 +109,7 @@ function toJdTaskView(item: JdCollectHistoryItemVo): TaskItemView {
: []), : []),
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []), ...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
], ],
progress: showProgress ? { percent: progressPercent(item), countLabel: `已采集 ${item.itemsReceived ?? item.rowCount ?? 0} 个商品` } : null, progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
source: item, source: item,
} }
} }
@@ -155,6 +155,16 @@ function progressPercent(item: JdCollectHistoryItemVo) {
return Math.max(0, Math.min(99, Math.round((done * 100) / total))) return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
} }
/** 计数文案:有 total 带分母和百分比「已采集 30/100 个商品(30%)」——TaskItemCard 的
* countLabel 会顶掉「总进度 X%」那行字,百分比只能随 countLabel 一起出;
* 没有 total 保持只报行数,不编造分母(与本页 progressPercent 同一口径)。 */
function progressCountLabel(item: JdCollectHistoryItemVo) {
const received = item.itemsReceived ?? item.rowCount ?? 0
const total = typeof item.total === 'number' && item.total > 0 ? item.total : null
if (!total) return `已采集 ${received} 个商品`
return `已采集 ${received}/${total} 个商品(${progressPercent(item)}%)`
}
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务),成功/进行中的任务不该出现这个按钮。 */ /** 失败/已中断的任务能续跑:在原任务上复位(不新建任务),成功/进行中的任务不该出现这个按钮。 */
function canRetryTask(item: JdCollectHistoryItemVo | null | undefined): boolean { function canRetryTask(item: JdCollectHistoryItemVo | null | undefined): boolean {
if (!item?.taskId) return false if (!item?.taskId) return false
@@ -648,7 +648,7 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
} }
} }
async function deleteTaskRecord(item: T, opts: { skipConfirm?: boolean } = {}) { async function deleteTaskRecord(item: T, opts: { skipConfirm?: boolean; silent?: boolean } = {}) {
if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return if (!opts.skipConfirm && !(await confirmTaskDeletion(item))) return
const deleteOptions = options.deleteTask const deleteOptions = options.deleteTask
try { try {
@@ -669,6 +669,7 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
// 没有任务也没有结果标识:宁可报错也不能假报「已删除」把用户挡在死胡同里 // 没有任务也没有结果标识:宁可报错也不能假报「已删除」把用户挡在死胡同里
throw new Error('该记录缺少任务/结果标识,无法删除,请刷新后重试') throw new Error('该记录缺少任务/结果标识,无法删除,请刷新后重试')
} }
if (opts.silent) return
await loadDashboard() await loadDashboard()
await loadHistory({ force: true }) await loadHistory({ force: true })
ElMessage.success('已删除') ElMessage.success('已删除')
@@ -676,24 +677,27 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
if (isRecordMissingError(e)) { if (isRecordMissingError(e)) {
// 记录已被别处删掉(多标签/多端):本地同步移除并刷新,别让「记录不存在」被当成删除失败 // 记录已被别处删掉(多标签/多端):本地同步移除并刷新,别让「记录不存在」被当成删除失败
if (item.taskId != null) deleteOptions?.onTaskDeleted?.(item) if (item.taskId != null) deleteOptions?.onTaskDeleted?.(item)
if (opts.silent) return
await loadDashboard().catch(() => undefined) await loadDashboard().catch(() => undefined)
await loadHistory({ force: true }).catch(() => undefined) await loadHistory({ force: true }).catch(() => undefined)
ElMessage.success('记录已不存在,已同步移除本地记录') ElMessage.success('记录已不存在,已同步移除本地记录')
return return
} }
if (opts.silent) throw e
ElMessage.error(e instanceof Error ? e.message : '删除失败') ElMessage.error(e instanceof Error ? e.message : '删除失败')
} }
} }
/** /**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)。 * 历史记录批量删除:复用单条删除逻辑(silent 模式逐条不弹框、不逐条刷新)。
* 批量入口已经弹过一次确认,逐条不再重复弹框。 * 批量入口已经弹过一次确认,全部删完只统一刷新一次、报一次总数。
*/ */
async function batchDeleteHistory(views: TaskItemView[]) { async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T, { skipConfirm: true })) const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T, { skipConfirm: true, silent: true }))
if (!total) return if (!total) return
await Promise.allSettled([loadDashboard(), loadHistory({ force: true })])
if (failed > 0) { if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`) ElMessage.warning(`删除完成:成功 ${total - failed} 条,失败 ${failed} 条`)
} else { } else {
ElMessage.success(`已删除 ${total} 条历史记录`) ElMessage.success(`已删除 ${total} 条历史记录`)
} }
@@ -71,7 +71,32 @@ test('记录已不存在时自愈:同步移除本地记录而不是报删除
test('批量删除不再逐条弹二次确认', () => { test('批量删除不再逐条弹二次确认', () => {
assert.match( assert.match(
boardSource, boardSource,
/deleteTaskRecord\(.*\{ skipConfirm: true \}\)/, /deleteTaskRecord\(.*\{ skipConfirm: true, silent: true \}\)/,
'批量入口已确认过一次,逐条再弹框会让用户以为批量删除没生效', '批量入口已确认过一次,逐条再弹框(确认框或成功提示)会让用户以为批量删除没生效',
) )
}) })
test('批量删除只报一次总数,不逐条弹成功提示', () => {
const fn = boardSource.slice(
boardSource.indexOf('async function batchDeleteHistory'),
boardSource.indexOf('function dispose'),
)
assert.ok(fn.includes('runBatchDelete'), '批量入口必须走 runBatchDelete')
assert.match(
fn,
/已删除 \$\{total\} 条历史记录/,
'删完只报一次总数(含失败时报告成功/失败条数)',
)
assert.match(
fn,
/Promise\.allSettled\(\[loadDashboard\(\), loadHistory/,
'批量删完统一刷新一次列表,不逐条刷新',
)
// 逐条成功提示必须被 silent 挡住:silent 模式下单条函数不再弹「已删除」
const single = boardSource.slice(
boardSource.indexOf('async function deleteTaskRecord'),
boardSource.indexOf('async function batchDeleteHistory'),
)
assert.match(single, /if \(opts\.silent\) return/, 'silent 模式必须跳过逐条刷新与成功提示')
assert.match(single, /if \(opts\.silent\) throw e/, 'silent 模式下单条失败要抛错交给批量计数')
})
@@ -172,7 +172,8 @@ describe('获取店铺数据:一键采集 + 任务面板', () => {
const bar = w.find('.file-progress-bar') const bar = w.find('.file-progress-bar')
expect(bar.exists()).toBe(true) expect(bar.exists()).toBe(true)
expect(bar.attributes('style')).toContain('width: 30%') expect(bar.attributes('style')).toContain('width: 30%')
expect(w.find('.file-progress-meta').text()).toContain('已采集 30 个商品') // 百分比文字随 countLabel 一起出(TaskItemCard 有 countLabel 就不显示「总进度 X%」)
expect(w.find('.file-progress-meta').text()).toContain('已采集 30/100 个商品(30%)')
}) })
it('没有分母(total 缺失)时只显示已采集行数,不编造百分比', async () => { it('没有分母(total 缺失)时只显示已采集行数,不编造百分比', async () => {