diff --git a/admin-frontend-vue/src/pages/patent/AppearancePatentCleanItemsPage.vue b/admin-frontend-vue/src/pages/patent/AppearancePatentCleanItemsPage.vue index a35a0f95b..e42f29492 100644 --- a/admin-frontend-vue/src/pages/patent/AppearancePatentCleanItemsPage.vue +++ b/admin-frontend-vue/src/pages/patent/AppearancePatentCleanItemsPage.vue @@ -2,9 +2,16 @@ import { formatDateTime, orderedPair } from '@/utils/datetime' /** 外观专利无侵权数据 · 只读分页列表(v1.3,展示形式参照「去重数据库」页:自绘 table + * OldPagination,不做卡片宫格)。数据由出表成功点自动同步(后端 SyncService),本页零写操作: - * 无编辑/导入/导出,下载走既有结果直链/任务中心。 */ + * 无编辑/导入,下载走既有结果直链/任务中心;导出(2026-11-11 客户需求)带当前过滤面 + + * 公司 tab 走后端 /export 全量出 xlsx(含所属主管列)。分组下拉(主管=组长)选项与去重页 + * 共用 GET /shop-manages/groups,选中后以 group_id 走同一过滤面(列表与导出同源)。 */ import { computed, onMounted, reactive, ref, watch } from 'vue' -import { fetchAppearancePatentCleanList } from './appearance-patent-clean-api.ts' +import { + exportAppearancePatentCleanList, + fetchAppearancePatentCleanList, + fetchDedupeTotalGroups, + type DedupeGroupOption, +} from './appearance-patent-clean-api.ts' import type { AppearancePatentCleanItem } from './appearance-patent-clean-model.ts' import { cleanItemReasonTooltip } from './appearance-patent-clean-model.ts' import { createAppearancePatentCleanFilterState } from './appearance-patent-clean-filter.ts' @@ -23,8 +30,12 @@ const rows = ref([]) const total = ref(0) const page = ref(1) const pageSize = ref(10) +/** 导出在途锁:避免连点导出把同一份过滤面重复请求两遍。 */ +const exporting = ref(false) /** 同步台账是累计数据,日期初值故意留空(默认当天会让首屏只剩今天同步的行);见 date-filter-default-today 护栏的 EXEMPT。 */ const filter = reactive(createAppearancePatentCleanFilterState()) +/** 分组(主管)下拉选项:公司 tab 切换时重取;选项失败不拦列表,只回空下拉(可见「全部分组」)。 */ +const groupOptions = ref([]) /** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */ function clampDatePair(): void { const [s, e] = orderedPair(filter.startDate, filter.endDate) @@ -34,6 +45,16 @@ function clampDatePair(): void { const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value))) +/** 分组选项与去重页/店铺管理同源(GET /shop-manages/groups);失败静默回空——分组只是筛选项, + * 不该让它把首屏行集一起拖死(列表失败有自己的 LoadFailureBar)。 */ +async function loadGroupOptions(): Promise { + try { + groupOptions.value = await fetchDedupeTotalGroups(companyTab.requestCompanyId) + } catch { + groupOptions.value = [] + } +} + async function load(): Promise { loading.value = true loadFailure.value = '' @@ -44,6 +65,7 @@ async function load(): Promise { taskId: filter.taskId, asin: filter.asin, country: filter.country, + groupId: filter.groupId, startDate: filter.startDate, endDate: filter.endDate, companyId: companyTab.requestCompanyId, @@ -59,6 +81,37 @@ async function load(): Promise { } } +/** 导出与页签同一过滤面(含公司 tab 与分组),服务端全量出 xlsx;成功后浏览器落盘,失败弹可读文案。 */ +async function exportAll(): Promise { + if (exporting.value) return + exporting.value = true + try { + const result = await exportAppearancePatentCleanList({ + taskId: filter.taskId, + asin: filter.asin, + country: filter.country, + groupId: filter.groupId, + startDate: filter.startDate, + endDate: filter.endDate, + 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() @@ -76,10 +129,12 @@ function changeSize(size: number) { void load() } -// 切公司 = 重新取数:任务号/ASIN 是上一家选中的值,在新一家的行集里筛不出东西,必须一起清。 -watch(() => companyTab.activeId, () => { filter.taskId = ''; filter.asin = ''; page.value = 1; void load() }) +// 切公司 = 重新取数:任务号/ASIN/分组是上一家选中的值,在新一家的行集里筛不出东西,必须一起清, +// 分组选项也按新公司重取(选项集是公司隔离的)。 +watch(() => companyTab.activeId, () => { filter.taskId = ''; filter.asin = ''; filter.groupId = ''; page.value = 1; void loadGroupOptions(); void load() }) onMounted(() => { + void loadGroupOptions() void load() }) @@ -107,6 +162,13 @@ onMounted(() => { +
+ + +
@@ -117,6 +179,9 @@ onMounted(() => {
+
@@ -126,6 +191,7 @@ onMounted(() => { 任务号 + 所属主管 ASIN 国家 SKU @@ -140,6 +206,7 @@ onMounted(() => { - 加载中... + 加载中... - 暂无无侵权数据 + 暂无无侵权数据 @@ -195,7 +262,7 @@ h3 { } .clean-filter-row { display: grid; - grid-template-columns: repeat(5, minmax(150px, 1fr)) auto; + grid-template-columns: repeat(6, minmax(150px, 1fr)) auto; gap: 12px; align-items: end; margin-bottom: 16px; diff --git a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-api.ts b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-api.ts index 0f7252954..9535dcc09 100644 --- a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-api.ts +++ b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-api.ts @@ -1,9 +1,13 @@ /** 外观专利无侵权数据列表查询适配(v1.3 AC-5):GET /api/admin/appearance-patent-clean-items。 - * 只读页,无写/删/导出入口。公司 tab 的值由本发送口从原始入参自己下传(白名单构造不认识 - * company_id),取值口形状由 company-tab-wiring 护栏钉住。 */ + * 只读页+导出(2026-11-11 客户需求「数据得导出来」):公司 tab 的值由本发送口从原始入参自己下传 + * (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。 */ import { http } from '@/api/http' +import { errorTextOf } from '../../api/envelope.ts' import { + toAppearancePatentCleanExportParams, toAppearancePatentCleanListParams, + type AppearancePatentCleanExportParams, + type AppearancePatentCleanExportQuery, type AppearancePatentCleanListParams, } from './appearance-patent-clean-filter.ts' import { @@ -21,6 +25,7 @@ export async function fetchAppearancePatentCleanList( taskId: params.taskId ?? '', asin: params.asin ?? '', country: params.country ?? '', + groupId: params.groupId ?? '', startDate: params.startDate ?? '', endDate: params.endDate ?? '', }, @@ -31,3 +36,66 @@ export async function fetchAppearancePatentCleanList( const { data } = await http.get(APPEARANCE_PATENT_CLEAN_ENDPOINT, { params: query }) return parseAppearancePatentCleanPage(data) } + +export interface AppearancePatentCleanExportResult { + 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 exportAppearancePatentCleanList( + params: AppearancePatentCleanExportParams, +): Promise { + const query: AppearancePatentCleanExportQuery = toAppearancePatentCleanExportParams({ + taskId: params.taskId ?? '', + asin: params.asin ?? '', + country: params.country ?? '', + groupId: params.groupId ?? '', + startDate: params.startDate ?? '', + endDate: params.endDate ?? '', + }) + if (params.companyId != null) query.company_id = params.companyId + const response = await http.get(`${APPEARANCE_PATENT_CLEAN_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 /shop-manages/groups(与去重页/店铺管理共用同一分组集, + * 不下新端点)。2026-11-11 客户口径「主管就是组长,可以筛选组长来导出,就是分组」—— + * 选项是分组管理里那一行(DedupeGroupOption {id, name, leaderUserId}),选中后以 group_id + * 走本文件 list/export 同一过滤面。 */ +export { fetchDedupeTotalGroups } from '../asin/dedupe-total-api.ts' +export type { DedupeGroupOption } from '../asin/dedupe-total-api.ts' diff --git a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-filter.ts b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-filter.ts index 5d1cf7b5f..d1ef35477 100644 --- a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-filter.ts +++ b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-filter.ts @@ -1,10 +1,13 @@ -/** 外观专利无侵权数据页筛选纯函数(v1.3 AC-5):任务号/ASIN/国家/起止时间 + snake 分页参数。 +/** 外观专利无侵权数据页筛选纯函数(v1.3 AC-5):任务号/ASIN/国家/分组/起止时间 + snake 分页参数。 * 产出与后端 §3.2 参数归一逐字对撞:`page`/`page_size`(默认 10、上限 100)、`task_id`、 - * `asin`、`country`、`start_date`/`end_date`(ISO yyyy-MM-dd;空白不下发)。 + * `asin`、`country`、`group_id`、`start_date`/`end_date`(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(同 asin-filter 惯例),由 api 发送口从 - * 原始入参自己下传——取值口由 company-tab-wiring 护栏的发送行钉看守。 */ + * 原始入参自己下传——取值口由 company-tab-wiring 护栏的发送行钉看守。 + * 分组语义(2026-11-11 客户口径「主管就是组长,可以筛选组长来导出,就是分组」):下拉选项是 + * 分组管理里那一行(biz_shop_manage_group),group_id 下发后服务端解析「组长本人+名下子账户」 + * 整集 SQL 下推;行上「所属主管」列与它同源(组长行=自己,子账户行=创建人)。 */ import { validIsoDateOrUndefined } from '../asin/asin-filter.ts' /** 每页条数默认 10(蓝图 §3.2),上限 100。 */ @@ -20,6 +23,8 @@ export interface AppearancePatentCleanFilterState { asin: string /** 国家代码,空串=全部。 */ country: string + /** 分组 id 文本(分组管理里那一行,组长即该组主管),空串=全部分组。 */ + groupId: string /** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */ startDate: string /** 同步结束日期(ISO yyyy-MM-dd;空串不限)。 */ @@ -27,7 +32,7 @@ export interface AppearancePatentCleanFilterState { } export function createAppearancePatentCleanFilterState(): AppearancePatentCleanFilterState { - return { taskId: '', asin: '', country: '', startDate: '', endDate: '' } + return { taskId: '', asin: '', country: '', groupId: '', startDate: '', endDate: '' } } /** 是否有任一激活筛选条件。 */ @@ -35,6 +40,7 @@ export function appearancePatentCleanFilterActive(state: AppearancePatentCleanFi if ((state.taskId || '').trim()) return true if ((state.asin || '').trim()) return true if ((state.country || '').trim()) return true + if ((state.groupId || '').trim()) return true if (validIsoDateOrUndefined(state.startDate) || validIsoDateOrUndefined(state.endDate)) return true return false } @@ -46,12 +52,25 @@ export interface AppearancePatentCleanQuery { task_id?: number asin?: string country?: string + group_id?: number start_date?: string end_date?: string /** 公司 tab:白名单构造不点名它,字段只为 api 发送口的 `query.company_id = params.companyId` 存在。 */ company_id?: number } +/** 导出查询参数:与列表同一过滤面、无分页(全量导出由服务侧 EXPORT_MAX_ROWS 上限兜住)。 */ +export interface AppearancePatentCleanExportQuery { + task_id?: number + asin?: string + country?: string + group_id?: number + start_date?: string + end_date?: string + /** 公司 tab 同列表口径:白名单构造不点名,由 api 发送口下传。 */ + company_id?: number +} + /** api 模块的入参:筛选态 + 分页 + 公司值(camel)。 */ export interface AppearancePatentCleanListParams { page: number @@ -59,11 +78,42 @@ export interface AppearancePatentCleanListParams { taskId?: string asin?: string country?: string + groupId?: string startDate?: string endDate?: string companyId?: number | null } +/** api 导出入口的入参:筛选态 + 公司值(camel,无分页)。 */ +export interface AppearancePatentCleanExportParams { + taskId?: string + asin?: string + country?: string + groupId?: string + startDate?: string + endDate?: string + companyId?: number | null +} + +/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段);列表与导出共用这一个取值口, + * 「导出的过滤面和页签看到的永远同源」由这条单出口保证,不出现两处各算各的。 */ +function toAppearancePatentCleanFilterQuery(state: AppearancePatentCleanFilterState): AppearancePatentCleanExportQuery { + const query: AppearancePatentCleanExportQuery = {} + const taskId = Number.parseInt((state.taskId || '').trim(), 10) + if (Number.isFinite(taskId) && taskId > 0) query.task_id = taskId + const asin = (state.asin || '').trim() + if (asin) query.asin = asin + const country = (state.country || '').trim() + if (country) query.country = country + const groupId = Number.parseInt((state.groupId || '').trim(), 10) + if (Number.isFinite(groupId) && groupId > 0) query.group_id = groupId + const startDate = validIsoDateOrUndefined(state.startDate) + if (startDate) query.start_date = startDate + const endDate = validIsoDateOrUndefined(state.endDate) + if (endDate) query.end_date = endDate + return query +} + /** 过滤态 + 分页 → 列表查询参数;空白/非法日期不下发,分页钳制在此单出口(不含公司维)。 */ export function toAppearancePatentCleanListParams( state: AppearancePatentCleanFilterState, @@ -73,16 +123,16 @@ export function toAppearancePatentCleanListParams( const safePage = Math.min(Math.max(Math.floor(page) || 1, 1), APPEARANCE_PATENT_CLEAN_MAX_PAGE) const rawSize = Math.floor(pageSize) || APPEARANCE_PATENT_CLEAN_PAGE_SIZE const safeSize = Math.min(Math.max(rawSize, 1), APPEARANCE_PATENT_CLEAN_MAX_PAGE_SIZE) - const query: AppearancePatentCleanQuery = { page: safePage, page_size: safeSize } - const taskId = Number.parseInt((state.taskId || '').trim(), 10) - if (Number.isFinite(taskId) && taskId > 0) query.task_id = taskId - const asin = (state.asin || '').trim() - if (asin) query.asin = asin - const country = (state.country || '').trim() - if (country) query.country = country - const startDate = validIsoDateOrUndefined(state.startDate) - if (startDate) query.start_date = startDate - const endDate = validIsoDateOrUndefined(state.endDate) - if (endDate) query.end_date = endDate - return query + return { + page: safePage, + page_size: safeSize, + ...toAppearancePatentCleanFilterQuery(state), + } +} + +/** 过滤态 → 导出查询参数(无分页;归一规则与列表逐字同源)。 */ +export function toAppearancePatentCleanExportParams( + state: AppearancePatentCleanFilterState, +): AppearancePatentCleanExportQuery { + return toAppearancePatentCleanFilterQuery(state) } diff --git a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-model.ts b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-model.ts index 58cedc04b..4094a0280 100644 --- a/admin-frontend-vue/src/pages/patent/appearance-patent-clean-model.ts +++ b/admin-frontend-vue/src/pages/patent/appearance-patent-clean-model.ts @@ -7,6 +7,8 @@ export interface AppearancePatentCleanItem { resultId: number | null taskId: number | null userId: number | null + /** 所属主管(后端读侧现算列:主管/公司超管=自己,普通账户=创建人;读不到为空 → 界面展示 -)。 */ + supervisorName: string companyId: number | null rowNo: number | null asin: string @@ -58,6 +60,7 @@ export function toAppearancePatentCleanItem(raw: unknown): AppearancePatentClean resultId: numberOrNull(record.resultId ?? record.result_id), taskId: numberOrNull(record.taskId ?? record.task_id), userId: numberOrNull(record.userId ?? record.user_id), + supervisorName: text(record.supervisorName ?? record.supervisor_name), companyId: numberOrNull(record.companyId ?? record.company_id), rowNo: numberOrNull(record.rowNo ?? record.row_no), asin: text(record.asin), diff --git a/admin-frontend-vue/tests/appearance-patent-clean-filter.test.ts b/admin-frontend-vue/tests/appearance-patent-clean-filter.test.ts index 784e3ed1f..e3004aa70 100644 --- a/admin-frontend-vue/tests/appearance-patent-clean-filter.test.ts +++ b/admin-frontend-vue/tests/appearance-patent-clean-filter.test.ts @@ -16,22 +16,25 @@ import assert from 'node:assert/strict' import { APPEARANCE_PATENT_CLEAN_MAX_PAGE, createAppearancePatentCleanFilterState, + toAppearancePatentCleanExportParams, toAppearancePatentCleanListParams, } from '../src/pages/patent/appearance-patent-clean-filter.ts' -test('AC-5 筛选参数——snake page/page_size/task_id/asin/country/start_date/end_date 形状', () => { +test('AC-5 筛选参数——snake page/page_size/task_id/asin/country/group_id/start_date/end_date 形状', () => { const full = toAppearancePatentCleanListParams( - { taskId: '33179', asin: ' B0AB8CDEF9 ', country: 'DE', startDate: '2026-11-01', endDate: '2026-11-09' }, + { taskId: '33179', asin: ' B0AB8CDEF9 ', country: 'DE', groupId: ' 7 ', startDate: '2026-11-01', endDate: '2026-11-09' }, 2, 20, ) // snake 逐字对撞后端 §3.2;ASIN 前后空白被构造器剥掉(后端服务侧再 trim 一次是双保险)。 + // 分组(主管=组长,2026-11-11 客户口径「就是分组」):group_id 下发,选中行是分组管理里那一行。 assert.deepEqual(full, { page: 2, page_size: 20, task_id: 33179, asin: 'B0AB8CDEF9', country: 'DE', + group_id: 7, start_date: '2026-11-01', end_date: '2026-11-09', }) @@ -40,12 +43,13 @@ test('AC-5 筛选参数——snake page/page_size/task_id/asin/country/start_dat const blank = toAppearancePatentCleanListParams(createAppearancePatentCleanFilterState(), 1, 10) assert.deepEqual(blank, { page: 1, page_size: 10 }) const dirty = toAppearancePatentCleanListParams( - { taskId: 'abc', asin: ' ', country: '', startDate: '2026/11/01', endDate: 'not-a-date' }, + { taskId: 'abc', asin: ' ', country: '', groupId: 'abc', startDate: '2026/11/01', endDate: 'not-a-date' }, 1, 10, ) assert.deepEqual(dirty, { page: 1, page_size: 10 }) assert.equal('task_id' in dirty, false, '非数字任务号不下发') + assert.equal('group_id' in dirty, false, '非数字分组 id 不下发') assert.equal('start_date' in dirty, false, '非法日期不下发') }) @@ -65,3 +69,31 @@ test('AC-5 筛选参数——page 钳制防 (page-1)*page_size 溢出(铁律 1 assert.equal(Number.isSafeInteger(offset), true, `(page-1)*page_size=${offset} 必须留在安全整数域`) assert.equal(offset, 999_900) }) + +test('导出参数——与列表同一过滤面单出口(无分页,空白/非法值不下发)', () => { + // 同一过滤态下导出与列表的过滤面字段逐字同源(防「页签筛了公司、导出全量」的两处各算各的)。 + const state = { taskId: '33179', asin: ' B0AB8CDEF9 ', country: 'de', groupId: '7', startDate: '2026-11-01', endDate: '' } + const list = toAppearancePatentCleanListParams(state, 3, 20) + const exp = toAppearancePatentCleanExportParams(state) + for (const key of Object.keys(exp) as Array) { + assert.equal((list as Record)[key], exp[key], `导出与列表的 ${key} 必须同源`) + } + assert.equal('page' in exp, false, '导出参数无分页(全量导出由服务侧上限兜住)') + assert.deepEqual(exp, { + task_id: 33179, + asin: 'B0AB8CDEF9', + country: 'de', + group_id: 7, + start_date: '2026-11-01', + }) + + // 全空态零字段;非法日期与非数字任务号/分组同列表口径不下发。 + assert.deepEqual(toAppearancePatentCleanExportParams(createAppearancePatentCleanFilterState()), {}) + assert.deepEqual( + toAppearancePatentCleanExportParams( + { taskId: 'abc', asin: ' ', country: '', groupId: 'abc', startDate: '2026/11/01', endDate: 'not-a-date' }, + ), + {}, + '脏值不下发,与列表参数归一规则逐字同源', + ) +}) diff --git a/admin-frontend-vue/tests/company-tab-wiring.test.ts b/admin-frontend-vue/tests/company-tab-wiring.test.ts index 4bd925d58..f0a2fe2a0 100644 --- a/admin-frontend-vue/tests/company-tab-wiring.test.ts +++ b/admin-frontend-vue/tests/company-tab-wiring.test.ts @@ -70,12 +70,12 @@ function escapeRegExp(text: string): string { } /** - * 全部 24 个字面发送口:批次 1 的任务看板 5 处 + 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页)7 处 + * 全部 25 个字面发送口:批次 1 的任务看板 5 处 + 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页)7 处 * + 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」那两页)4 处 * + 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」里的用户管理)1 处 * + 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)1 处 * + 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」)3 处:菜单目录 / 新建菜单 / 用户管理里的授权树 - * + 批次 7(2026-11-10 v1.3 外观专利无侵权数据)1 处:只读列表。 + * + 批次 7(2026-11-10 v1.3 外观专利无侵权数据)2 处:只读列表 + 导出(2026-11-11 客户需求「数据得导出来」)。 * 批次 2 原 12 处里的品牌库 1 处 + 商品类目 4 处,随 2026-10-06「这两页退回全平台共享」一并摘掉。 * *

`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须 @@ -124,8 +124,12 @@ const SEND_POINTS: ReadonlyArray = [ { menuKey: 'admin_columns', file: 'src/pages/account/menu-manage-api.ts', fn: 'createMenu', line: TASK_CENTER_SEND_LINE, window: 300, title: 'POST /permission-menus 新建:归属由端点参数决定,前端不从树里猜' }, { menuKey: 'admin_users', file: 'src/pages/account/user-menu-auth-api.ts', fn: 'fetchGrantableMenus', line: TASK_CENTER_SEND_LINE, window: 300, title: 'GET /permission-menus?grantableOnly 授权树:一家一套树后取错公司=已授权勾不上、提交必判无效' }, // ↓ 批次 7(2026-11-10 v1.3 外观专利无侵权数据):出表成功自动同步的只读明细,归属物化在行 - // company_id 列(V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn;这一页只有一个发送口。 - { 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: 400, title: 'GET /appearance-patent-clean-items 无侵权只读列表' }, + // company_id 列(V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn;2026-11-11 客户需求 + // 「数据得导出来」补导出发送口(与列表共用同一过滤面与正门),这一页共两个发送口。 + // 窗口 500:两处 own 实测 416/395(groupId 行加入后),同文件两条塞键行的间距 1585 ⇒ + // 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 客户需求「数据得导出来」,与列表共用同一过滤面)' }, ] /** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */ @@ -348,7 +352,7 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company // 批次 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 无侵权只读页 1 条 = 24 条)⇒ 有人把钉从表里摘了,取值口看守成空`) + `发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权只读页与导出 2 条 = 25 条)⇒ 有人把钉从表里摘了,取值口看守成空`) for (const p of SEND_POINTS) { const shape = pointShape(p) const compliant = pointCompliant(p) @@ -381,7 +385,7 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company else grouped.set(key, { file: p.file, line: p.line, pinned: 1 }) } assert.equal(grouped.size, 19, - `发送口表按 (文件, 整行) 应聚成 19 组(24 处发送口,批次 7 再落 1 处),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`) + `发送口表按 (文件, 整行) 应聚成 19 组(25 处发送口,批次 7 的列表与导出逐字同行走同一组),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`) for (const g of grouped.values()) { const actual = occurrences(stripComments(read(g.file)), g.line) assert.equal(g.pinned, actual, @@ -725,11 +729,14 @@ const WATCH_BODY_PINS: ReadonlyArray<{ }, // ↓ 批次 7(2026-11-10 v1.3 无侵权只读页):任务号/ASIN 是自由文本筛选,上一家填的值在新一家的 // 行集里筛不出东西 ⇒ 首屏「暂无无侵权数据」而输入框里还显示着那个值;页码回 1 同理。 + // 2026-11-11 分组筛选(主管=组长,就是分组)落地:分组选项集是公司隔离的(GET /shop-manages/groups + // 带 company_id),上一家选的 groupId 在新一家的选项集里不存在 ⇒ 同罪必清,选项也按新公司重取。 { file: 'src/pages/patent/AppearancePatentCleanItemsPage.vue', - token: "filter.taskId = ''; filter.asin = ''; page.value = 1; void load()", + token: "filter.taskId = ''; filter.asin = ''; filter.groupId = ''; page.value = 1; void loadGroupOptions(); void load()", why: '任务号/ASIN 是按行集筛的自由文本,上一家的值在新一家的行里不存在 ⇒ 切 tab 后首屏被筛成「暂无无侵权数据」,' - + '而输入框还显示着上一家填的值;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据', + + '而输入框还显示着上一家填的值;分组(主管)选项集是公司隔离的,上一家选的 groupId 在新一家的选项里不存在,' + + '同罪必清且选项重取;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据', premise: [ { file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, ], diff --git a/admin-frontend-vue/tests/mount/appearance-patent-clean-page.test.ts b/admin-frontend-vue/tests/mount/appearance-patent-clean-page.test.ts index 7aabbdb4d..b44cee93c 100644 --- a/admin-frontend-vue/tests/mount/appearance-patent-clean-page.test.ts +++ b/admin-frontend-vue/tests/mount/appearance-patent-clean-page.test.ts @@ -26,6 +26,8 @@ const MENU_KEY = 'admin_appearance_patent_clean_items' const cleanApi = vi.hoisted(() => ({ fetchAppearancePatentCleanList: vi.fn(), + exportAppearancePatentCleanList: vi.fn(), + fetchDedupeTotalGroups: vi.fn(), })) vi.mock('@/pages/patent/appearance-patent-clean-api.ts', () => cleanApi) @@ -36,6 +38,7 @@ function row(id: number, over: Record = {}) { resultId: 900 + id, taskId: 33179, userId: 7, + supervisorName: `主管${id}`, companyId: 1, rowNo: id, asin: `B0AB8CDEF${id}`, @@ -64,6 +67,8 @@ beforeEach(() => { setActivePinia(pinia) useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' } useCompanyTabStore().setActiveId(1) + // 分组(主管)选项默认空集:分组用例各自覆写 + cleanApi.fetchDedupeTotalGroups.mockResolvedValue([]) }) async function mountWith(payload: unknown): Promise> { @@ -109,6 +114,79 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数 expect(wrapper.text()).toContain('无侵权') }) + it('主管列(2026-11-11 客户需求):表头就位,行值展示 supervisorName,读不到展示 -', async () => { + const wrapper = await mountWith({ + items: [row(1, { supervisorName: '主管甲' }), row(2, { supervisorName: '' })], + total: 2, + page: 1, + pageSize: 10, + }) + const headers = wrapper.findAll('thead th').map((th) => th.text()) + expect(headers).toContain('所属主管') + expect(headers.indexOf('所属主管')).toBe(headers.indexOf('任务号') + 1, '主管列紧跟任务号之后') + const firstRowCells = wrapper.findAll('tbody tr')[0].findAll('td') + expect(firstRowCells[headers.indexOf('所属主管')].text()).toBe('主管甲') + const secondRowCells = wrapper.findAll('tbody tr')[1].findAll('td') + expect(secondRowCells[headers.indexOf('所属主管')].text()).toBe('-', '读不到主管不猜名字,展示 -') + }) + + it('导出按钮带当前过滤面与公司 tab 调导出接口,成功触发 blob 落盘', async () => { + const createObjectURL = vi.fn(() => 'blob:mock-url') + const revokeObjectURL = vi.fn() + const urlRecord = URL as unknown as Record + const origCreate = urlRecord.createObjectURL + const origRevoke = urlRecord.revokeObjectURL + 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(() => {}) + cleanApi.exportAppearancePatentCleanList.mockImplementation(() => + Promise.resolve({ blob: new Blob(['xlsx'], { type: 'application/vnd.ms-excel' }), filename: '外观专利数据库-20261111103000.xlsx' }), + ) + + try { + const wrapper = await mountWith({ items: [row(1)], total: 1, page: 1, pageSize: 10 }) + const textInputs = wrapper.findAll('input[type="text"]') + await textInputs[0].setValue('33179') + const exportBtn = wrapper.findAll('button').find((b) => b.text() === '导出') + expect(exportBtn).toBeTruthy() + await exportBtn!.trigger('click') + await flushPromises() + await flushPromises() + + expect(cleanApi.exportAppearancePatentCleanList).toHaveBeenCalledTimes(1) + const call = cleanApi.exportAppearancePatentCleanList.mock.calls[0][0] + expect(call).toMatchObject({ + taskId: '33179', + asin: '', + country: '', + groupId: '', + startDate: '', + endDate: '', + companyId: 1, + }) + expect(createObjectURL).toHaveBeenCalledTimes(1) + expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-url') + expect(clickSpy).toHaveBeenCalled() + expect(document.body.textContent).toContain('已导出', '成功反馈点名落盘文件') + } finally { + Object.defineProperty(URL, 'createObjectURL', { value: origCreate, configurable: true }) + Object.defineProperty(URL, 'revokeObjectURL', { value: origRevoke, configurable: true }) + clickSpy.mockRestore() + } + }) + + it('导出失败把服务端业务文案弹出来,不许静默', async () => { + cleanApi.exportAppearancePatentCleanList.mockImplementation(() => + Promise.reject(new Error('无侵权数据共 90001 行,超过导出上限 50000 行,请缩小筛选范围后重试'))) + const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 }) + await wrapper.findAll('button').find((b) => b.text() === '导出')!.trigger('click') + await flushPromises() + await flushPromises() + expect(document.body.textContent).toContain('超过导出上限', '失败反馈必须是服务端那句可读文案') + // 失败后导出锁复位,按钮可再次点击 + expect(wrapper.findAll('button').find((b) => b.text() === '导出')!.text()).toBe('导出') + }) + it('翻页与改每页条数都重发请求,改条数回第一页', async () => { const wrapper = await mountWith({ items: [row(11)], total: 42, page: 2, pageSize: 10 }) @@ -143,12 +221,36 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数 taskId: '33179', asin: 'B0AB8CDEF1', country: 'DE', + groupId: '', startDate: '2026-11-01', endDate: '2026-11-09', page: 1, }) }) + it('分组下拉(主管=组长):选项与去重页同源,选中后 groupId 进列表请求', async () => { + cleanApi.fetchDedupeTotalGroups.mockResolvedValue([ + { id: 7, name: '甲组', leaderUserId: 9 }, + { id: 8, name: '乙组', leaderUserId: 10 }, + ]) + const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 }) + + // 选项取数走的是公司隔离的同一分组集(GET /shop-manages/groups 的适配层) + expect(cleanApi.fetchDedupeTotalGroups).toHaveBeenCalledWith(1) + + const groupSelect = wrapper.findAll('select')[1] + const optionTexts = groupSelect.findAll('option').map((o) => o.text()) + expect(optionTexts).toContain('全部分组') + expect(optionTexts).toContain('甲组') + expect(optionTexts).toContain('乙组') + + await groupSelect.setValue('7') + await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click') + await flushPromises() + const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0] + expect(last.groupId).toBe('7', '选中的分组 id 以 groupId 进列表过滤面(服务端解析组长+名下整集)') + }) + it('空态与加载失败条(失败给重试,不把整页打死)', async () => { const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 }) const thCount = empty.findAll('thead th').length @@ -166,9 +268,13 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数 }) it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径)', async () => { + cleanApi.fetchDedupeTotalGroups.mockResolvedValue([{ id: 7, name: '甲组', leaderUserId: 9 }]) const wrapper = await mountWith({ items: [row(1)], total: 1, page: 1, pageSize: 10 }) const textInputs = wrapper.findAll('input[type="text"]') await textInputs[0].setValue('33179') + // 选上上一家公司的分组:切走后必须连同 groupId 一起清(分组的成员集是公司隔离的) + const groupSelect = wrapper.findAll('select')[1] + await groupSelect.setValue('7') const callsAfterMount = cleanApi.fetchAppearancePatentCleanList.mock.calls.length useCompanyTabStore().setActiveId(2) @@ -179,6 +285,9 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数 const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0] expect(last.companyId).toBe(2) expect(last.taskId).toBe('', '切公司必须清掉上一家填的任务号') + expect(last.groupId).toBe('', '切公司必须清掉上一家选的分组') expect(last.page).toBe(1) + // 分组选项按新公司重取(选项集公司隔离) + expect(cleanApi.fetchDedupeTotalGroups).toHaveBeenLastCalledWith(2) }) }) diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsController.java index f66058444..7d4d450d7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsController.java @@ -7,6 +7,7 @@ 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.appearancepatent.model.vo.AppearancePatentCleanItemPageVo; import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentCleanItemQueryService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService; @@ -19,17 +20,26 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; /** * 后管「外观专利无侵权数据」只读页(v1.3 R2/R3)。数据由出表成功点自动同步落表 - * ({@code AppearancePatentCleanSyncService}),本页只读——无写/删/导出接口, - * 下载走既有结果直链/任务中心。 + * ({@code AppearancePatentCleanSyncService}),本页只读——无写/删接口,下载走既有结果直链/ + * 任务中心;另有 GET 导出端点(2026-11-11 客户需求「数据得导出来」):与分页查询同一过滤面 + * (含公司隔离正门),服务侧卡导出上限,主管列为读侧现算列,无写/删/导入;分组筛选同日落地 + * (客户口径「主管就是组长,可以筛选组长来导出,就是分组」)——group_id 参数(biz_shop_manage_group.id) + * 在分页与导出同面生效,服务侧按 selectUserIdsByGroupId 解析「组长本人+名下子账户」整集后 + * SQL 侧下推;下拉选项复用既有 GET /shop-manages/groups(与去重页/店铺管理同源),不下新端点。 * *

鉴权照去重页私有 {@code requireXxxAccess} 形状:JWT → 内部令牌回退 → 超管放行 → * 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V190 只插 columns 不预授权 @@ -38,11 +48,14 @@ import java.time.LocalDate; @RestController @RequiredArgsConstructor @RequestMapping("/api/admin/appearance-patent-clean-items") -@Tag(name = "外观专利无侵权数据", description = "后管只读页:出表成功自动同步的「结论=无侵权」明细,按分公司隔离分页查询。") +@Tag(name = "外观专利无侵权数据", description = "后管只读页:出表成功自动同步的「结论=无侵权」明细,按分公司隔离分页查询与导出。") public class AdminAppearancePatentCleanItemsController { private static final String CLEAN_ITEMS_COLUMN_KEY = "admin_appearance_patent_clean_items"; private static final String CLEAN_ITEMS_ROUTE_PATH = "patent-center/clean-items"; + private static final String XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + /** 导出文件名时间戳(同 QueryAsinController 口径),中文文件名的 ASCII 回退由 DownloadHeaderUtil 兜底。 */ + private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm"); private final AppearancePatentCleanItemQueryService cleanItemQueryService; private final AdminAuthSupport adminAuthSupport; @@ -65,6 +78,8 @@ public class AdminAppearancePatentCleanItemsController { @RequestParam(name = "start_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, @Parameter(description = "同步结束日期(包含)") @RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate, + @Parameter(description = "分组 id:按该分组「组长本人+名下子账户」的用户集过滤(主管=组长)") + @RequestParam(name = "group_id", required = false) Long groupId, @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId, HttpServletRequest request) { RequestOperator operator = requireCleanItemsAccess(request); @@ -75,7 +90,39 @@ public class AdminAppearancePatentCleanItemsController { // 等于把整张表交给每一家(该方法 javadoc 点名的越权形状),不是本表该走的门。 Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId); return ApiResponse.success(cleanItemQueryService.page(page, pageSize, taskId, asin, country, - startDate, endDate, scopedCompanyId)); + startDate, endDate, groupId, scopedCompanyId)); + } + + @GetMapping("/export") + @Operation(summary = "导出外观专利数据库 Excel", description = "与分页查询同一过滤面(任务号/ASIN/国家/同步起止日期/分组)," + + "公司隔离走同一正门:company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。" + + "含所属主管列;超过导出上限按业务错误拒绝(QueryAsinController 导出 javadoc 点名的越权形状在此不成立:" + + "页签筛了公司、导出就只导该公司)。") + public ResponseEntity export( + @Parameter(description = "任务号") @RequestParam(name = "task_id", required = false) Long taskId, + @Parameter(description = "ASIN 前缀") @RequestParam(name = "asin", required = false) String asin, + @Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country, + @Parameter(description = "同步开始日期(包含)") + @RequestParam(name = "start_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, + @Parameter(description = "同步结束日期(包含)") + @RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate, + @Parameter(description = "分组 id:按该分组「组长本人+名下子账户」的用户集过滤(主管=组长)") + @RequestParam(name = "group_id", required = false) Long groupId, + @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId, + HttpServletRequest request) { + RequestOperator operator = requireCleanItemsAccess(request); + AdminUserEntity user = operator.user(); + // 导出与分页共用 readCompanyIdOrOwn 正门(同 page 的口径注释):超管显式传才收窄、 + // 不传全量;非超管强制本公司(忽略请求传参),绝不让导出绕过页签的公司隔离。 + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId); + byte[] bytes = cleanItemQueryService.export(taskId, asin, country, startDate, endDate, groupId, + scopedCompanyId); + 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 requireCleanItemsAccess(HttpServletRequest request) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/mapper/AppearancePatentCleanItemMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/mapper/AppearancePatentCleanItemMapper.java index 8aa83b159..d8192f778 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/mapper/AppearancePatentCleanItemMapper.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/mapper/AppearancePatentCleanItemMapper.java @@ -15,6 +15,10 @@ import java.util.List; * 覆盖式落表({@link #deleteByResultId} + {@link #insertBatch});后管只读页 * (Phase 3)走 {@link #countCleanItems}/{@link #selectCleanItemPage}。SQL 全部落 * {@code mapper/appearancepatent/AppearancePatentCleanItemMapper.xml}(铁律 1)。

+ * + *

{@code userIds}(2026-11-11 分组筛选,主管=组长):服务侧由 {@code ShopManageGroupMapper + * #selectUserIdsByGroupId} 按分组解析出「组长本人+名下子账户」的 id 集后整集传入, + * SQL 侧下推——不得在 Java 侧对已取页做过滤(铁律 20:先 limit 再过滤会饿死另一档)。

*/ @Mapper public interface AppearancePatentCleanItemMapper extends BaseMapper { @@ -36,7 +40,8 @@ public interface AppearancePatentCleanItemMapper extends BaseMapper userIds); /** * 只读页分页查询(synced_at 倒序)。 @@ -51,6 +56,7 @@ public interface AppearancePatentCleanItemMapper extends BaseMapper userIds, @Param("offset") long offset, @Param("limit") int limit); } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/model/vo/AppearancePatentCleanItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/model/vo/AppearancePatentCleanItemVo.java index 1b6024092..1c8f301af 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/model/vo/AppearancePatentCleanItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/model/vo/AppearancePatentCleanItemVo.java @@ -8,7 +8,9 @@ import java.time.LocalDateTime; /** * 外观专利无侵权数据明细行(后管只读页,v1.3 R3)。字段与 {@code biz_appearance_patent_clean_item} * 表列(V189)一一对应——行值是同步服务从 chunk payload 原样落的(不 trim、不转写,AC-1 - * 「与 payload 一致」),读侧只做搬运不做二次加工。 + * 「与 payload 一致」),读侧只搬运不做二次加工。唯一例外是 {@code supervisorName}: + * 表里没有这一列,查询服务在读侧按「行属用户 → 归属主管」现算补上(2026-11-11 客户需求 + * 「显示哪一个主管的」),不落库、不回写同步链。 */ @Data @Schema(description = "外观专利无侵权数据明细行") @@ -26,6 +28,10 @@ public class AppearancePatentCleanItemVo { @Schema(description = "任务 owner 用户 id") private Long userId; + @Schema(description = "所属主管(读侧现算:owner 是主管/公司超管=自己的用户名,普通账户=创建人的用户名;" + + "用户读不到为空,前端展示 -)") + private String supervisorName; + @Schema(description = "物化归属分公司 id") private Long companyId; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanItemQueryService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanItemQueryService.java index 6613a14d0..ae91ab58d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanItemQueryService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanItemQueryService.java @@ -2,18 +2,32 @@ package com.nanri.aiimage.modules.appearancepatent.service; import com.nanri.aiimage.common.api.PageDefaults; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.mapper.AdminUserMapper; +import com.nanri.aiimage.common.mapper.ShopManageGroupMapper; +import com.nanri.aiimage.common.model.entity.AdminUserEntity; +import com.nanri.aiimage.common.security.DeviceSessionPolicy; import com.nanri.aiimage.modules.appearancepatent.mapper.AppearancePatentCleanItemMapper; import com.nanri.aiimage.modules.appearancepatent.model.entity.CleanItemEntity; import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentCleanItemPageVo; import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentCleanItemVo; 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.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; /** - * 后管「外观专利无侵权数据」只读查询(v1.3 R2)。 + * 后管「外观专利无侵权数据」只读查询(v1.3 R2)+ 导出(2026-11-11 客户需求「数据得导出来」)。 * *

分页钳制是本服务的职责(铁律 15):mapper 的 {@code offset}/{@code limit} 只收钳制后的值 * (Phase 1 定下的单一出口,mapper 不做第二次换算)。钳制形状照关键词服务 CR-18 先例: @@ -24,7 +38,29 @@ import java.util.List; *

{@code scopedCompanyId} 由控制器经 {@code DataReadScope#readCompanyIdOrOwn} 算好传入 * (本表与店铺密钥同形状:归属物化在行 {@code company_id} 列、可见集不靠账号/分组): * {@code null} = 超管没选公司、查全量;正数 = 只查该公司(非超管恒为自己的公司)。

+ * + *

所属主管(supervisorName)是唯一的读侧加工列(表 V189 没有该列,同步链一字不动): + * 批量取行属用户后按 {@link DeviceSessionPolicy#resolveRole} 分档——owner 是 admin/公司超管/ + * 站点超管=主管本人,取自己的用户名;普通账户(role 为 null)=创建人({@code users.created_by_id}, + * 与密钥管理页「所属主管(创建人)」同口径,AccountExpiryService 也认这条为「普通账户的归属主管」) + * 的用户名。用户读不到=展示为空(铁律 30:读不出≠没有,不猜名字),全程两次批量查询,无逐行查询。

+ * + *

分组(主管)筛选(2026-11-11 客户口径「主管就是组长,可以筛选组长来导出,就是分组」): + * {@code groupId} 是分组管理里那一行的 {@code biz_shop_manage_group.id},服务侧经 + * {@link ShopManageGroupMapper#selectUserIdsByGroupId} 一次取出「该分组创建人(组长)本人+ + * 其名下子账户」的 id 集(与数据可见范围同源:组长旧字段 user_id/新字段 created_by_id 都算, + * 成员表基本未使用)后整集下推 SQL({@code user_id IN},铁律 20:不得取页后 Java 过滤)。 + * 选项不下新端点:后管下拉直接复用既有 {@code GET /shop-manages/groups}(与去重页/店铺管理 + * 共用同一分组集)。行上「所属主管」列的展示口径与它同源:组长本人行=自己,名下子账户行= + * 创建人(创建人即组长,AccountExpiryService 同一口径)。

+ * + *

导出与分页共用同一过滤面与 {@code selectCleanItemPage} 这一条 SQL(offset=0、 + * limit=导出上限,不另写导出查询),先 {@code countCleanItems} 卡 {@link #EXPORT_MAX_ROWS} + * 上限防内存,行集经同一 {@code toVo}+主管富化后按后管页面的列序写 xlsx(SXSSF 流式, + * 口径同 {@code QueryAsinService.export} 的 byte[] 形状)。国家列落中文标签, + * 字典与前端 {@code asin-country.ts}(ASIN 数据中心共享国家字典)同表。

*/ +@Slf4j @Service @RequiredArgsConstructor public class AppearancePatentCleanItemQueryService { @@ -33,17 +69,35 @@ public class AppearancePatentCleanItemQueryService { private static final long MAX_PAGE = 10_000; /** 每页条数上限(蓝图 §3.2)。 */ private static final long MAX_PAGE_SIZE = 100; + /** 单次导出行数上限:超限按业务错误拒(提示缩小筛选面),不把无界内存写进一次 HTTP 响应。 */ + public static final long EXPORT_MAX_ROWS = 50_000; + /** 导出同步时间列的展示格式。 */ + private static final DateTimeFormatter EXPORT_SYNCED_AT_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** 导出列序(与后管页面同序,主管列插在结论后、同步时间前)。 */ + private static final List EXPORT_HEADERS = List.of( + "任务号", "ASIN", "国家", "SKU", "品牌", "价格", "标题", "结论", "所属主管", "同步时间"); + /** 国家码 → 中文标签:与前端 asin-country.ts 同表,不在字典的原样回显(读侧不加工未知值)。 */ + private static final Map COUNTRY_LABELS = Map.of( + "DE", "德国", + "UK", "英国", + "FR", "法国", + "IT", "意大利", + "ES", "西班牙"); private final AppearancePatentCleanItemMapper cleanItemMapper; + private final AdminUserMapper adminUserMapper; + private final ShopManageGroupMapper shopManageGroupMapper; /** * 分页查询只读明细({@code synced_at} 倒序)。 * *

过滤面:公司(物化列 eq)、任务号、ASIN 前缀(保 {@code idx_asin} 可用,同去重页口径)、 - * 国家、同步起止日期(闭区间,含 end 当天)。

+ * 国家、同步起止日期(闭区间,含 end 当天)、分组({@code user_id IN 组长名下用户集})。

*/ public AppearancePatentCleanItemPageVo page(Long page, Long pageSize, Long taskId, String asin, - String country, LocalDate startDate, LocalDate endDate, Long scopedCompanyId) { + String country, LocalDate startDate, LocalDate endDate, Long groupId, Long scopedCompanyId) { if (startDate != null && endDate != null && startDate.isAfter(endDate)) { throw new BusinessException("开始日期不能晚于结束日期"); } @@ -53,18 +107,207 @@ public class AppearancePatentCleanItemQueryService { Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null; String safeAsin = trimToNull(asin); String safeCountry = trimToNull(country); - long total = cleanItemMapper.countCleanItems(companyId, taskId, safeAsin, safeCountry, startDate, endDate); + List groupUserIds = groupUserIds(groupId); + if (groupUserIds != null && groupUserIds.isEmpty()) { + // 分组读不出任何用户(如分组已被删):结果必为空,短路不碰 mapper。 + return emptyPage(safePage, safeSize); + } + long total = cleanItemMapper.countCleanItems(companyId, taskId, safeAsin, safeCountry, startDate, endDate, + groupUserIds); List rows = total <= 0 ? List.of() : cleanItemMapper.selectCleanItemPage(companyId, taskId, safeAsin, safeCountry, startDate, endDate, - (safePage - 1) * safeSize, (int) safeSize); + groupUserIds, (safePage - 1) * safeSize, (int) safeSize); + List items = rows.stream().map(AppearancePatentCleanItemQueryService::toVo).toList(); + fillSupervisorNames(items); AppearancePatentCleanItemPageVo vo = new AppearancePatentCleanItemPageVo(); - vo.setItems(rows.stream().map(AppearancePatentCleanItemQueryService::toVo).toList()); + vo.setItems(items); vo.setTotal(total); vo.setPage(safePage); vo.setPageSize(safeSize); return vo; } + private static AppearancePatentCleanItemPageVo emptyPage(long page, long pageSize) { + AppearancePatentCleanItemPageVo vo = new AppearancePatentCleanItemPageVo(); + vo.setItems(List.of()); + vo.setTotal(0L); + vo.setPage(page); + vo.setPageSize(pageSize); + return vo; + } + + /** + * 导出当前过滤面全量明细为 xlsx 字节(控制器直接回 {@code ResponseEntity}, + * 口径同 {@code QueryAsinService.export})。 + * + *

先 count 卡 {@link #EXPORT_MAX_ROWS} 上限再取数;取数复用 {@code selectCleanItemPage} + * 这一条 SQL(offset=0、limit=上限),不另写导出查询——过滤面永远和分页页签同源, + * 不会出现「页签筛了公司、导出全量」的越权形状(QueryAsinController 导出 javadoc 点名的语义)。

+ */ + public byte[] export(Long taskId, String asin, String country, LocalDate startDate, LocalDate endDate, + Long groupId, Long scopedCompanyId) { + if (startDate != null && endDate != null && startDate.isAfter(endDate)) { + throw new BusinessException("开始日期不能晚于结束日期"); + } + Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null; + String safeAsin = trimToNull(asin); + String safeCountry = trimToNull(country); + List groupUserIds = groupUserIds(groupId); + if (groupUserIds != null && groupUserIds.isEmpty()) { + // 与分页同口径:分组读不出用户=空结果,导出只给表头(不碰 mapper)。 + return writeExportWorkbook(List.of()); + } + long total = cleanItemMapper.countCleanItems(companyId, taskId, safeAsin, safeCountry, startDate, endDate, + groupUserIds); + if (total > EXPORT_MAX_ROWS) { + throw new BusinessException("无侵权数据共 " + total + " 行,超过导出上限 " + EXPORT_MAX_ROWS + + " 行,请缩小筛选范围后重试"); + } + List rows = total <= 0 ? List.of() + : cleanItemMapper.selectCleanItemPage(companyId, taskId, safeAsin, safeCountry, startDate, endDate, + groupUserIds, 0L, (int) EXPORT_MAX_ROWS); + List items = rows.stream().map(AppearancePatentCleanItemQueryService::toVo).toList(); + fillSupervisorNames(items); + return writeExportWorkbook(items); + } + + /** + * 分组筛选 → 该分组「组长本人+名下子账户」的用户 id 集({@code null} = 没选分组、不过滤); + * id 非法(≤0)按没选处理,不把它当全量之外的第三档。解析交给 + * {@link ShopManageGroupMapper#selectUserIdsByGroupId}(组长旧字段 user_id/新字段 + * created_by_id 都算,与数据可见范围同源),分组不存在/无成员返回空集由调用方短路。 + */ + private List groupUserIds(Long groupId) { + if (groupId == null || groupId <= 0) { + return null; + } + List userIds = shopManageGroupMapper.selectUserIdsByGroupId(groupId); + return userIds == null ? List.of() : userIds; + } + + private byte[] writeExportWorkbook(List items) { + try (SXSSFWorkbook workbook = new SXSSFWorkbook(100); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + Sheet sheet = workbook.createSheet("外观专利数据库"); + Row header = sheet.createRow(0); + for (int c = 0; c < EXPORT_HEADERS.size(); c++) { + header.createCell(c).setCellValue(EXPORT_HEADERS.get(c)); + } + for (int i = 0; i < items.size(); i++) { + writeExportRow(sheet, i + 1, items.get(i)); + } + // 标题列放宽,其余走默认窄列;与页面列宽观感对齐即可,不追求逐像素。 + sheet.setColumnWidth(6, 46 * 256); + sheet.setColumnWidth(2, 10 * 256); + workbook.write(outputStream); + workbook.dispose(); + return outputStream.toByteArray(); + } catch (Exception ex) { + // 落盘/序列化失败必须给可读业务错误(用户手里的导出请求不能变成 500 裸堆栈), + // 细节进日志;CatchSilenceRatchetTest 基线随本支 +1(RETHROW 形状)。 + log.warn("[appearance-patent-clean] 导出 xlsx 失败 rows={} msg={}", items.size(), ex.getMessage()); + throw new BusinessException("导出外观专利数据库失败,请稍后重试"); + } + } + + private void writeExportRow(Sheet sheet, int rowIndex, AppearancePatentCleanItemVo item) { + Row row = sheet.createRow(rowIndex); + row.createCell(0).setCellValue(item.getTaskId() == null ? "" : String.valueOf(item.getTaskId())); + row.createCell(1).setCellValue(safe(item.getAsin())); + row.createCell(2).setCellValue(countryLabel(item.getCountry())); + row.createCell(3).setCellValue(safe(item.getSku())); + row.createCell(4).setCellValue(safe(item.getBrand())); + row.createCell(5).setCellValue(safe(item.getPrice())); + row.createCell(6).setCellValue(safe(item.getTitle())); + row.createCell(7).setCellValue(safe(item.getConclusion())); + row.createCell(8).setCellValue(safe(item.getSupervisorName())); + row.createCell(9).setCellValue(item.getSyncedAt() == null + ? "" : EXPORT_SYNCED_AT_FORMATTER.format(item.getSyncedAt())); + } + + private static String countryLabel(String country) { + if (country == null || country.isBlank()) { + return ""; + } + return COUNTRY_LABELS.getOrDefault(country.trim(), country.trim()); + } + + private static String safe(String value) { + return value == null ? "" : value; + } + + /** + * 批量补「所属主管」:行属用户一次取齐;普通账户的创建人再一次取齐(全程两次批量查询, + * 同密钥管理页 fillRowGroups 的「用户→创建人→创建人用户名」形状)。读不到的用户/创建人 + * 不猜名字,supervisorName 留空由前端展示 -(铁律 30)。 + */ + private void fillSupervisorNames(List items) { + List userIds = items.stream() + .map(AppearancePatentCleanItemVo::getUserId) + .filter(id -> id != null) + .distinct() + .toList(); + if (userIds.isEmpty()) { + return; + } + Map ownersById = new LinkedHashMap<>(); + for (AdminUserEntity owner : adminUserMapper.selectBatchIds(userIds)) { + if (owner.getId() != null) { + ownersById.put(owner.getId(), owner); + } + } + Map supervisorByUserId = new LinkedHashMap<>(); + Set creatorIds = new LinkedHashSet<>(); + for (Long userId : userIds) { + AdminUserEntity owner = ownersById.get(userId); + if (owner == null) { + continue; + } + String username = trimmed(owner.getUsername()); + if (DeviceSessionPolicy.resolveRole(owner.getRole(), owner.getIsAdmin(), owner.getCreatedById()) != null) { + // 主管本人(admin/公司超管/站点超管)跑的单:主管就是自己,不外指创建人。 + if (!username.isEmpty()) { + supervisorByUserId.put(userId, username); + } + continue; + } + Long creatorId = owner.getCreatedById(); + if (creatorId == null || creatorId <= 0) { + continue; + } + creatorIds.add(creatorId); + } + if (!creatorIds.isEmpty()) { + Map creatorNames = new LinkedHashMap<>(); + for (AdminUserEntity creator : adminUserMapper.selectBatchIds(creatorIds)) { + String username = trimmed(creator.getUsername()); + if (creator.getId() != null && !username.isEmpty()) { + creatorNames.put(creator.getId(), username); + } + } + for (Long userId : userIds) { + AdminUserEntity owner = ownersById.get(userId); + if (owner == null || creatorNames.isEmpty()) { + continue; + } + Long creatorId = owner.getCreatedById(); + if (creatorId != null && creatorNames.containsKey(creatorId) + && !supervisorByUserId.containsKey(userId)) { + supervisorByUserId.put(userId, creatorNames.get(creatorId)); + } + } + } + for (AppearancePatentCleanItemVo item : items) { + if (item.getUserId() != null) { + item.setSupervisorName(supervisorByUserId.get(item.getUserId())); + } + } + } + + private static String trimmed(String value) { + return value == null ? "" : value.trim(); + } + private static String trimToNull(String value) { if (value == null) { return null; diff --git a/backend-java/src/main/resources/mapper/appearancepatent/AppearancePatentCleanItemMapper.xml b/backend-java/src/main/resources/mapper/appearancepatent/AppearancePatentCleanItemMapper.xml index d0a651b3a..d422d2160 100644 --- a/backend-java/src/main/resources/mapper/appearancepatent/AppearancePatentCleanItemMapper.xml +++ b/backend-java/src/main/resources/mapper/appearancepatent/AppearancePatentCleanItemMapper.xml @@ -3,7 +3,10 @@ + 国家、同步起止日期、组长名下用户集(2026-11-11 分组筛选,主管=组长:服务侧按 + ShopManageGroupMapper.selectUserIdsByGroupId 解析「组长本人+名下子账户」整集传入, + SQL 侧下推——铁律 20,不得取页后 Java 过滤); + 全部走 #{} 占位符。offset/limit 必须是服务侧钳制后的值(铁律 15)。 --> AND company_id = #{companyId} @@ -12,6 +15,10 @@ AND country = #{country} AND synced_at >= #{startDate} AND synced_at < DATE_ADD(#{endDate}, INTERVAL 1 DAY) + + AND user_id IN + #{uid} + diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java index 08c682246..a49fae993 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java @@ -318,7 +318,13 @@ class CatchSilenceRatchetTest { // 上层把原 401/403 原样抛回(回退失败必须显形,不吞)。 // 本批复核办法:上限压 0/下限抬 99999 单跑一次,实测 total 1073、rethrow 406、 // notRethrow 611、logOnly 193、empty 56(EMPTY 一格没涨)。 - static final int STRICT_TOTAL = 1073; + // 11-11 外观专利数据库导出抬 1073 -> 1074,一枚逐处记名: + // `AppearancePatentCleanItemQueryService.writeExportWorkbook`:SXSSF 落盘 catch Exception + // → BusinessException「导出外观专利数据库失败,请稍后重试」(RETHROW 形状,rethrow 406 -> 407, + // 本格与 NOT_RETHROW/LOG_ONLY/EMPTY 都不动)。误差方向:导出请求的 IO 失败必须给用户 + // 可读业务错误而不是 500 裸堆栈;反向对照——改成往外抛 IOException=前端拿到 Spring 兜底文案, + // 改成吞掉返回空字节=用户拿到 0 字节 xlsx 还以为导出成功(比报错更贵)。 + static final int STRICT_TOTAL = 1074; /** * 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。 * 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。 diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsControllerTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsControllerTest.java index c20d0d48d..15a6be57b 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsControllerTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/controller/AdminAppearancePatentCleanItemsControllerTest.java @@ -3,6 +3,8 @@ package com.nanri.aiimage.modules.appearancepatent.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.mapper.AdminUserMapper; +import com.nanri.aiimage.common.mapper.ShopManageGroupMapper; import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.service.DataReadScope; @@ -13,28 +15,42 @@ import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentClean import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentCleanItemQueryService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import jakarta.servlet.http.HttpServletRequest; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; 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.ByteArrayInputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Collection; 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.anyCollection; +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.verify; import static org.mockito.Mockito.when; @@ -195,13 +211,13 @@ class AdminAppearancePatentCleanItemsControllerTest { pageVo.setTotal(0L); pageVo.setPage(1L); pageVo.setPageSize((long) PageDefaults.CLEAN_ITEMS_PAGE_SIZE_INT); - when(queryService.page(1L, 10L, null, null, null, null, null, 5L)).thenReturn(pageVo); + when(queryService.page(1L, 10L, null, null, null, null, null, null, 5L)).thenReturn(pageVo); ApiResponse response = - controller.page(1L, 10L, null, null, null, null, null, 5L, request); + controller.page(1L, 10L, null, null, null, null, null, null, 5L, request); verify(dataReadScope).readCompanyIdOrOwn(operator, 5L); - verify(queryService).page(1L, 10L, null, null, null, null, null, 5L); + verify(queryService).page(1L, 10L, null, null, null, null, null, null, 5L); assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)"); assertEquals(pageVo, response.getData()); } @@ -209,24 +225,25 @@ class AdminAppearancePatentCleanItemsControllerTest { @Test void 查询服务分页钳制防溢出() { AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); - AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService(mapper); - when(mapper.countCleanItems(any(), any(), any(), any(), any(), any())).thenReturn(1L); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, mock(AdminUserMapper.class), mock(ShopManageGroupMapper.class)); + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(1L); - // page=0 / size=null ⇒ 归一为第 1 页、默认 10 条;offset = 0。 - service.page(0L, null, null, null, null, null, null, null); + // page=0 / size=null ⇒ 归一为第 1 页、默认 10 条;offset = 0(groupId 不传=不做分组过滤)。 + service.page(0L, null, null, null, null, null, null, null, null); ArgumentCaptor offset = ArgumentCaptor.forClass(Long.class); ArgumentCaptor limit = ArgumentCaptor.forClass(Integer.class); verify(mapper).selectCleanItemPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), - offset.capture(), limit.capture()); + isNull(), offset.capture(), limit.capture()); assertEquals(0L, offset.getValue()); assertEquals(PageDefaults.CLEAN_ITEMS_PAGE_SIZE_INT, limit.getValue()); // page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15,CR-18 同值)。 - service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null); + service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null); ArgumentCaptor offsetMax = ArgumentCaptor.forClass(Long.class); ArgumentCaptor limitMax = ArgumentCaptor.forClass(Integer.class); verify(mapper, org.mockito.Mockito.times(2)).selectCleanItemPage(any(), any(), any(), any(), any(), any(), - offsetMax.capture(), limitMax.capture()); + any(), offsetMax.capture(), limitMax.capture()); assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负"); assertEquals(100, limitMax.getValue()); } @@ -234,32 +251,77 @@ class AdminAppearancePatentCleanItemsControllerTest { @Test void 查询服务公司过滤原样直传() { AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); - AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService(mapper); - when(mapper.countCleanItems(any(), any(), any(), any(), any(), any())).thenReturn(0L); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, mock(AdminUserMapper.class), mock(ShopManageGroupMapper.class)); + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(0L); // 超管显式传 5 ⇒ 按公司 5 筛(收窄);null ⇒ 全量(AC-4 前半句)。 - service.page(1L, 10L, null, null, null, null, null, 5L); - verify(mapper).countCleanItems(eq(5L), isNull(), isNull(), isNull(), isNull(), isNull()); - service.page(1L, 10L, null, null, null, null, null, null); - verify(mapper).countCleanItems(isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); + service.page(1L, 10L, null, null, null, null, null, null, 5L); + verify(mapper).countCleanItems(eq(5L), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); + service.page(1L, 10L, null, null, null, null, null, null, null); + verify(mapper).countCleanItems(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); } @Test void 查询服务日期倒挂拒绝() { AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); - AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService(mapper); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, mock(AdminUserMapper.class), mock(ShopManageGroupMapper.class)); BusinessException ex = assertThrows(BusinessException.class, () -> service.page(1L, 10L, null, null, null, - LocalDate.of(2026, 11, 9), LocalDate.of(2026, 11, 1), null)); + LocalDate.of(2026, 11, 9), LocalDate.of(2026, 11, 1), null, null)); assertTrue(ex.getMessage().contains("开始日期不能晚于结束日期"), "倒挂日期按业务异常拒绝(同去重页文案口径)"); - verify(mapper, org.mockito.Mockito.never()).countCleanItems(any(), any(), any(), any(), any(), any()); + verify(mapper, org.mockito.Mockito.never()).countCleanItems(any(), any(), any(), any(), any(), any(), any()); + // 导出与分页共用同一过滤面校验(同一句文案,同一个拒绝时机:不碰 mapper)。 + BusinessException exportEx = assertThrows(BusinessException.class, + () -> service.export(null, null, null, + LocalDate.of(2026, 11, 9), LocalDate.of(2026, 11, 1), null, null)); + assertTrue(exportEx.getMessage().contains("开始日期不能晚于结束日期"), + "导出端点必须同样拒绝倒挂日期,不得绕过分页页签的校验口径"); + } + + @Test + void 分组筛选按组长名下用户集下推SQL且空集短路() { + AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); + AdminUserMapper adminUserMapper = mock(AdminUserMapper.class); + ShopManageGroupMapper shopManageGroupMapper = mock(ShopManageGroupMapper.class); + AppearancePatentCleanItemQueryService service = + new AppearancePatentCleanItemQueryService(mapper, adminUserMapper, shopManageGroupMapper); + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(2L); + when(shopManageGroupMapper.selectUserIdsByGroupId(9L)).thenReturn(List.of(9L, 33L)); + + // 选了分组 9 ⇒ 解析出的「组长本人+名下子账户」整集传给 mapper(SQL 侧下推,铁律 20)。 + service.page(1L, 10L, null, null, null, null, null, 9L, 5L); + verify(shopManageGroupMapper).selectUserIdsByGroupId(9L); + verify(mapper).countCleanItems(eq(5L), isNull(), isNull(), isNull(), isNull(), isNull(), + eq(List.of(9L, 33L))); + + // 分组读不出任何用户(如分组已被删)⇒ 结果必为空:短路不碰 mapper(IN () 不是合法 SQL)。 + when(shopManageGroupMapper.selectUserIdsByGroupId(66L)).thenReturn(List.of()); + AppearancePatentCleanItemPageVo empty = service.page(1L, 10L, null, null, null, null, null, 66L, 5L); + assertEquals(0L, empty.getTotal()); + assertTrue(empty.getItems().isEmpty(), "分组空集=空页,不碰 mapper"); + // 此刻 selectCleanItemPage 仍只有分组 9 那一页的 1 次调用(空集短路没有追加取数)。 + verify(mapper, org.mockito.Mockito.times(1)).selectCleanItemPage(any(), any(), any(), any(), any(), any(), + any(), anyLong(), anyInt()); + + // 导出同口径:空集只给表头(不追加取数)。 + byte[] bytes = service.export(null, null, null, null, null, 66L, 5L); + assertNotNull(bytes); + verify(mapper, org.mockito.Mockito.times(1)).selectCleanItemPage(any(), any(), any(), any(), any(), any(), + any(), anyLong(), anyInt()); + + // groupId ≤ 0 按没选分组处理(不当第三档):分组解析不新增调用(此前 9L×1+66L×2=3 次)。 + service.page(1L, 10L, null, null, null, null, null, 0L, 5L); + verify(shopManageGroupMapper, org.mockito.Mockito.times(3)).selectUserIdsByGroupId(anyLong()); } @Test void 行字段与VO搬运一致不加工() { AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); - AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService(mapper); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, mock(AdminUserMapper.class), mock(ShopManageGroupMapper.class)); CleanItemEntity entity = new CleanItemEntity(); entity.setId(11L); entity.setResultId(901L); @@ -279,11 +341,11 @@ class AdminAppearancePatentCleanItemsControllerTest { entity.setSourceFilename("list.xlsx"); LocalDateTime syncedAt = LocalDateTime.of(2026, 11, 10, 10, 30); entity.setSyncedAt(syncedAt); - when(mapper.countCleanItems(any(), any(), any(), any(), any(), any())).thenReturn(1L); - when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), anyLong(), + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(1L); + when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), any(), anyLong(), org.mockito.ArgumentMatchers.anyInt())).thenReturn(List.of(entity)); - AppearancePatentCleanItemPageVo vo = service.page(1L, 10L, 33179L, null, null, null, null, 5L); + AppearancePatentCleanItemPageVo vo = service.page(1L, 10L, 33179L, null, null, null, null, null, 5L); assertEquals(1L, vo.getTotal()); AppearancePatentCleanItemVo row = vo.getItems().get(0); // 读侧只搬运不加工:标题两侧空格原样保留(AC-1「与 payload 一致」,后端不 trim 是与行值同口径)。 @@ -297,6 +359,204 @@ class AdminAppearancePatentCleanItemsControllerTest { assertEquals("标题含品牌词", row.getTitleReason()); assertEquals("list.xlsx", row.getSourceFilename()); assertEquals(syncedAt, row.getSyncedAt()); + // 行属用户读不到(AdminUserMapper 未命中)时主管列不猜名字,留空由前端展示 -(铁律 30)。 + assertNull(row.getSupervisorName(), "用户读不到=supervisorName 为空,不得编造归属"); + } + + // ===================== 2026-11-11 客户需求:主管列+导出 ===================== + + @Test + void 导出端点就位且与分页共用同一正门() throws IOException { + String source = stripComments(Files.readString(CONTROLLER)); + assertTrue(source.contains("\"/export\""), + "导出必须是 GET /api/admin/appearance-patent-clean-items/export(2026-11-11 客户需求「数据得导出来」)"); + // 导出仍是只读:本页禁写/删/导入的判据由「控制器与只读端点就位」一格把守(无 Post/Put/Delete), + // 导出落 GET 不破那格;导出与分页都必须各自调用 requireCleanItemsAccess+readCompanyIdOrOwn + //(私有两支各调一次,缺一支即红——导出不许绕过页签的鉴权与公司隔离)。 + long gateCalls = source.split("requireCleanItemsAccess\\(request\\)", -1).length - 1; + assertTrue(gateCalls >= 2, "分页与导出两支 handler 都必须过 requireCleanItemsAccess 正门,实得 " + gateCalls); + long scopeCalls = source.split("readCompanyIdOrOwn\\(", -1).length - 1; + assertTrue(scopeCalls >= 2, "分页与导出两支 handler 都必须走 readCompanyIdOrOwn 公司隔离,实得 " + scopeCalls); + // 导出是全量导出(服务侧另有 EXPORT_MAX_ROWS 上限),不收 page/page_size: + // 全文件 page_size 只允许出现一次(分页 handler 的参数声明)。 + long pageSizeParams = source.split("page_size", -1).length - 1; + assertEquals(1, pageSizeParams, "导出不收分页参数,page_size 只许出现在分页 handler 的参数声明里"); + // 分组(主管=组长)筛选:group_id 在分页与导出两支都要收;选项不下新端点(复用 + // 既有 GET /shop-manages/groups,与去重页/店铺管理同源)。 + long groupParams = source.split("group_id", -1).length - 1; + assertTrue(groupParams >= 2, "分页与导出都必须收 group_id(主管=组长,就是分组,2026-11-11 客户口径)"); + assertFalse(source.contains("\"/supervisors\""), + "选项复用既有分组端点,本控制器不得再挂 /supervisors 第二份选项源"); + } + + @Test + void 控制器导出走同一鉴权正门并回Excel响应() { + AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); + AppearancePatentCleanItemQueryService queryService = mock(AppearancePatentCleanItemQueryService.class); + AdminAuthSupport authSupport = mock(AdminAuthSupport.class); + PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); + DataReadScope dataReadScope = mock(DataReadScope.class); + AdminAppearancePatentCleanItemsController controller = new AdminAppearancePatentCleanItemsController( + 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"); + when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L); + byte[] payload = "xlsx-bytes".getBytes(StandardCharsets.UTF_8); + when(queryService.export(null, null, null, null, null, null, 5L)).thenReturn(payload); + + ResponseEntity response = controller.export(null, null, null, null, null, null, 5L, request); + + verify(dataReadScope).readCompanyIdOrOwn(operator, 5L); + verify(queryService).export(null, null, null, null, null, null, 5L); + 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 导出超上限按业务错误拒绝且不取数() { + AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, mock(AdminUserMapper.class), mock(ShopManageGroupMapper.class)); + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(AppearancePatentCleanItemQueryService.EXPORT_MAX_ROWS + 1); + + BusinessException ex = assertThrows(BusinessException.class, + () -> service.export(null, null, null, null, null, null, 5L)); + assertTrue(ex.getMessage().contains("超过导出上限"), + "超上限必须给「缩小筛选范围」的可读文案,不能让用户等一次注定 OOM 的全量查询"); + verify(mapper, never()).selectCleanItemPage(any(), any(), any(), any(), any(), any(), any(), + anyLong(), anyInt()); + } + + @Test + void 分页行补所属主管按角色分档() { + AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); + AdminUserMapper adminUserMapper = mock(AdminUserMapper.class); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, adminUserMapper, mock(ShopManageGroupMapper.class)); + + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(3L); + when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), any(), anyLong(), anyInt())) + .thenReturn(List.of(rowEntity(1L, 33L), rowEntity(2L, 44L), rowEntity(3L, 55L))); + + // owner 33=普通账户(role 空,创建人 9=主管甲);owner 44=admin 本人=主管就是自己; + // owner 55=库里读不到(users 已删)=不猜名字。 + AdminUserEntity plainOwner = new AdminUserEntity(); + plainOwner.setId(33L); + plainOwner.setUsername("sub-user-1"); + plainOwner.setCreatedById(9L); + AdminUserEntity adminOwner = new AdminUserEntity(); + adminOwner.setId(44L); + adminOwner.setUsername("leader-b"); + adminOwner.setRole("admin"); + AdminUserEntity creator = new AdminUserEntity(); + creator.setId(9L); + creator.setUsername(" 主管甲 "); + when(adminUserMapper.selectBatchIds(anyCollection())).thenAnswer(invocation -> { + Collection ids = invocation.getArgument(0); + List out = new ArrayList<>(); + for (Object id : ids) { + if (Long.valueOf(33L).equals(id)) out.add(plainOwner); + if (Long.valueOf(44L).equals(id)) out.add(adminOwner); + if (Long.valueOf(9L).equals(id)) out.add(creator); + } + return out; + }); + + AppearancePatentCleanItemPageVo vo = service.page(1L, 10L, null, null, null, null, null, null, null); + assertEquals("主管甲", vo.getItems().get(0).getSupervisorName(), + "普通账户的主管=创建人(与密钥管理页「所属主管(创建人)」同口径),用户名两侧空白剥掉"); + assertEquals("leader-b", vo.getItems().get(1).getSupervisorName(), + "admin 本人的单主管就是自己,不外指创建人(company_super_admin/super_admin 同支)"); + assertNull(vo.getItems().get(2).getSupervisorName(), + "owner 用户读不到=不猜名字(铁律 30:读不出≠没有)"); + } + + @Test + void 导出xlsx行含主管列与国家中文标签() throws Exception { + AppearancePatentCleanItemMapper mapper = mock(AppearancePatentCleanItemMapper.class); + AdminUserMapper adminUserMapper = mock(AdminUserMapper.class); + AppearancePatentCleanItemQueryService service = new AppearancePatentCleanItemQueryService( + mapper, adminUserMapper, mock(ShopManageGroupMapper.class)); + + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())).thenReturn(2L); + CleanItemEntity deRow = rowEntity(1L, 33L); + deRow.setCountry("DE"); + CleanItemEntity ukRow = rowEntity(2L, 44L); + ukRow.setCountry("UK"); + ukRow.setSyncedAt(null); + when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), any(), eq(0L), anyInt())) + .thenReturn(List.of(deRow, ukRow)); + AdminUserEntity plainOwner = new AdminUserEntity(); + plainOwner.setId(33L); + plainOwner.setUsername("sub-user-1"); + plainOwner.setCreatedById(9L); + AdminUserEntity adminOwner = new AdminUserEntity(); + adminOwner.setId(44L); + adminOwner.setUsername("leader-b"); + adminOwner.setRole("admin"); + AdminUserEntity creator = new AdminUserEntity(); + creator.setId(9L); + creator.setUsername("主管甲"); + when(adminUserMapper.selectBatchIds(anyCollection())).thenAnswer(invocation -> { + Collection ids = invocation.getArgument(0); + List out = new ArrayList<>(); + for (Object id : ids) { + if (Long.valueOf(33L).equals(id)) out.add(plainOwner); + if (Long.valueOf(44L).equals(id)) out.add(adminOwner); + if (Long.valueOf(9L).equals(id)) out.add(creator); + } + return out; + }); + + byte[] bytes = service.export(null, null, null, null, null, null, 5L); + try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(bytes))) { + Sheet sheet = workbook.getSheetAt(0); + assertEquals(2, sheet.getLastRowNum(), "表头 + 2 行明细,不多不少"); + Row header = sheet.getRow(0); + assertEquals("任务号", header.getCell(0).getStringCellValue()); + assertEquals("所属主管", header.getCell(8).getStringCellValue(), "主管列插在结论后、同步时间前"); + assertEquals("同步时间", header.getCell(9).getStringCellValue()); + Row row1 = sheet.getRow(1); + assertEquals("德国", row1.getCell(2).getStringCellValue(), + "国家列落中文标签(与前端 asin-country.ts 字典同表)"); + assertEquals("33179", row1.getCell(0).getStringCellValue(), "首列是任务号(owner 33 是行属用户,不上表)"); + assertEquals("主管甲", row1.getCell(8).getStringCellValue(), + "普通账户 owner 的主管=创建人(创建人用户名两批查询后命中)"); + Row row2 = sheet.getRow(2); + assertEquals("英国", row2.getCell(2).getStringCellValue()); + assertEquals("leader-b", row2.getCell(8).getStringCellValue()); + assertEquals("", row2.getCell(9).getStringCellValue(), "syncedAt 为空落空串,不出 'null' 字样"); + } + } + + /** 导出/分页用例共用的明细行夹具:task 归 owner,值非空便于按列对撞。 */ + private static CleanItemEntity rowEntity(long id, long userId) { + CleanItemEntity entity = new CleanItemEntity(); + entity.setId(id); + entity.setResultId(900 + id); + entity.setTaskId(33179L); + entity.setUserId(userId); + entity.setCompanyId(5L); + entity.setRowNo((int) id); + entity.setAsin("B0AB8CDEF" + id); + entity.setCountry("DE"); + entity.setSku("SKU-" + id); + entity.setBrand("Anker"); + entity.setPrice("29.99"); + entity.setTitle("无侵权商品 " + id); + entity.setConclusion("无侵权"); + entity.setSourceFilename("list.xlsx"); + entity.setSyncedAt(LocalDateTime.of(2026, 11, 11, 10, 30)); + return entity; } private static Path findCleanItemMapperXml() throws IOException { diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanSyncRoundTripTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanSyncRoundTripTest.java index 13416cc7c..e4cd23af6 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanSyncRoundTripTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/AppearancePatentCleanSyncRoundTripTest.java @@ -71,7 +71,9 @@ class AppearancePatentCleanSyncRoundTripTest { AppearancePatentCleanSyncService sync = new AppearancePatentCleanSyncService( cleanItemMapper, taskChunkMapper, adminUserMapper, json, storage, mock(org.springframework.transaction.PlatformTransactionManager.class)); - AppearancePatentCleanItemQueryService query = new AppearancePatentCleanItemQueryService(cleanItemMapper); + AppearancePatentCleanItemQueryService query = new AppearancePatentCleanItemQueryService( + cleanItemMapper, adminUserMapper, + mock(com.nanri.aiimage.common.mapper.ShopManageGroupMapper.class)); FileTaskEntity task = task(33001L, 77L); // ⓪ 出表未成功(url 未回填):不写任何行,后管查不到 @@ -84,7 +86,7 @@ class AppearancePatentCleanSyncRoundTripTest { assertEquals(0, table.rows.get(0).getRowNo(), "row_no 按 payload 全行序号计(含被过滤行)"); // ② 后管同一查询入口立即可见(超管全量),行值与 payload 一致(AC-1)、synced_at 倒序 - AppearancePatentCleanItemPageVo vo = query.page(null, null, null, null, null, null, null, null); + AppearancePatentCleanItemPageVo vo = query.page(null, null, null, null, null, null, null, null, null); assertEquals(2L, vo.getTotal(), "后管全量 total=2"); assertEquals("B0CLEAN002", vo.getItems().get(0).getAsin(), "synced_at 倒序=后同步的在前"); assertEquals("英国", vo.getItems().get(0).getCountry()); @@ -95,8 +97,8 @@ class AppearancePatentCleanSyncRoundTripTest { assertEquals(7L, vo.getItems().get(0).getCompanyId(), "company_id=任务 owner 公司(物化列)"); // ③ 分公司隔离:本公司(7)看得见,别家公司(9)看不见 - assertEquals(2L, query.page(null, null, null, null, null, null, null, 7L).getTotal()); - assertEquals(0L, query.page(null, null, null, null, null, null, null, 9L).getTotal(), + assertEquals(2L, query.page(null, null, null, null, null, null, null, null, 7L).getTotal()); + assertEquals(0L, query.page(null, null, null, null, null, null, null, null, 9L).getTotal(), "别的公司查不到本公司同步行"); // ④ 补检重新出表 → 覆盖式重写:首行翻成侵权后全库只剩 1 行(uk(result_id,row_no) 零重复) @@ -104,20 +106,20 @@ class AppearancePatentCleanSyncRoundTripTest { assertEquals(1, table.rows.size(), "覆盖式重写后只剩仍满足严格口径的 1 行"); assertEquals(1, table.rows.get(0).getRowNo()); assertEquals("B0CLEAN002", table.rows.get(0).getAsin()); - assertEquals(1L, query.page(null, null, null, null, null, null, null, null).getTotal(), + assertEquals(1L, query.page(null, null, null, null, null, null, null, null, null).getTotal(), "重出后后管立即可见新结果面"); // ⑤ 后管筛选面与 XML 同语义:任务号 eq、ASIN 前缀、同步日期半开区间 - assertEquals(1L, query.page(null, null, 33001L, null, null, null, null, null).getTotal()); - assertEquals(0L, query.page(null, null, 99999L, null, null, null, null, null).getTotal()); - assertEquals(1L, query.page(null, null, null, "B0CLEAN", null, null, null, null).getTotal(), + assertEquals(1L, query.page(null, null, 33001L, null, null, null, null, null, null).getTotal()); + assertEquals(0L, query.page(null, null, 99999L, null, null, null, null, null, null).getTotal()); + assertEquals(1L, query.page(null, null, null, "B0CLEAN", null, null, null, null, null).getTotal(), "ASIN 前缀命中"); - assertEquals(0L, query.page(null, null, null, "B0NOPE", null, null, null, null).getTotal()); + assertEquals(0L, query.page(null, null, null, "B0NOPE", null, null, null, null, null).getTotal()); LocalDate syncDay = table.lastSyncedAt.toLocalDate(); - assertEquals(1L, query.page(null, null, null, null, null, syncDay, syncDay, null).getTotal(), + assertEquals(1L, query.page(null, null, null, null, null, syncDay, syncDay, null, null).getTotal(), "同步当天闭区间命中(synced_at < 次日 0 点)"); assertEquals(0L, query.page(null, null, null, null, null, - syncDay.plusDays(1), syncDay.plusDays(1), null).getTotal(), + syncDay.plusDays(1), syncDay.plusDays(1), null, null).getTotal(), "同步日之后的一天查不到"); assertTrue(vo.getPage() >= 1 && vo.getPageSize() >= 1, "分页归一形状随行"); } @@ -221,13 +223,13 @@ class AppearancePatentCleanSyncRoundTripTest { .thenAnswer(inv -> table.deleteByResultId(inv.getArgument(0, Long.class))); when(mapper.insertBatch(any())) .thenAnswer(inv -> table.insertBatch(inv.getArgument(0))); - when(mapper.countCleanItems(any(), any(), any(), any(), any(), any())) + when(mapper.countCleanItems(any(), any(), any(), any(), any(), any(), any())) .thenAnswer(inv -> table.count(inv.getArgument(0), inv.getArgument(1), inv.getArgument(2), inv.getArgument(3), inv.getArgument(4), inv.getArgument(5))); - when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), anyLong(), anyInt())) + when(mapper.selectCleanItemPage(any(), any(), any(), any(), any(), any(), any(), anyLong(), anyInt())) .thenAnswer(inv -> table.page(inv.getArgument(0), inv.getArgument(1), inv.getArgument(2), inv.getArgument(3), inv.getArgument(4), inv.getArgument(5), - inv.getArgument(6, Long.class), inv.getArgument(7, Integer.class))); + inv.getArgument(7, Long.class), inv.getArgument(8, Integer.class))); return mapper; } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentChunkRowContractTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentChunkRowContractTest.java index 7730f5d86..068bcfeff 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentChunkRowContractTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/appearancepatent/service/support/AppearancePatentChunkRowContractTest.java @@ -171,13 +171,17 @@ class AppearancePatentChunkRowContractTest { assertFalse(flagged.isEmpty(), "扫描空跑=判据失效:LlmClient 自身必须命中"); // 结论值唯一来源仍是 LlmClient(NO_INFRINGEMENT 常量);白名单其余条目必须是页面名/文档 // 文案,不得出现第二个"造结论"的出处。新增命中必须在此登记并说明为何不产结论值。 + // 2026-11-11 登记 service/AppearancePatentCleanItemQueryService:导出超上限的业务错误文案 + // 「无侵权数据共 N 行…」(页面名口径,与控制器 403 文案同族)——不产任何结论值,行集的 + // conclusion 原样搬运自 payload(toVo 只搬运不加工)。 assertIterableEquals(List.of( "client/AppearancePatentLlmClient.java", "controller/AdminAppearancePatentCleanItemsController.java", "model/vo/AppearancePatentCleanItemPageVo.java", - "model/vo/AppearancePatentCleanItemVo.java"), new ArrayList<>(flagged), - "「无侵权」字面量只许落在登记白名单(LlmClient=结论值单一来源;控制器/VO 命中全是" - + "菜单名/Swagger/403 文案);同步/导出/查询侧产结论值一律引用 NO_INFRINGEMENT 常量," + "model/vo/AppearancePatentCleanItemVo.java", + "service/AppearancePatentCleanItemQueryService.java"), new ArrayList<>(flagged), + "「无侵权」字面量只许落在登记白名单(LlmClient=结论值单一来源;控制器/VO/查询服务命中全是" + + "菜单名/Swagger/403 文案/导出上限文案);同步/导出/查询侧产结论值一律引用 NO_INFRINGEMENT 常量," + "注释里的举例不算(本判据已剥离注释)"); }