fix(cr2-frontend): 代理归属回退、换号继承确认与请求竞态收口

- CR-04:全局代理加 proxy_uid 归属,跨账号不再静默回退/补报
- CR-12:取消静默继承,设置页显式确认;同 OS 作用域、locked 代理排除、无效快照清除、uid+epoch 双校验、登出 capture 超时
- CR-26/27:关键词分页初始值与档位一致;两页面请求序号闸丢弃旧响应

vue-tsc 两前端 rc=0;定向 35 + 8 + 2 例全绿。
This commit is contained in:
2026-10-26 11:33:37 +08:00
parent b5e4c45add
commit b963561043
16 changed files with 1245 additions and 136 deletions
@@ -10,6 +10,7 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm'
import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import {
GATING_COUNTRIES,
GATING_SOURCES,
@@ -50,6 +51,10 @@ const batchText = ref('')
const importBusy = ref(false)
const busyRowId = ref(0)
// 快速改筛选/翻页时先发的请求可能后返回;列表与统计各一个序号闸(CR-27)
const pageGate = createLatestRequestGate()
const statsGate = createLatestRequestGate()
const countryOptions = GATING_COUNTRIES.filter((country) => country !== '全部')
const typeOptions = GATING_TYPES
@@ -72,30 +77,37 @@ function feedback(message: string, kind: AdminFeedbackKind): void {
}
async function loadStats(): Promise<void> {
const token = statsGate.begin()
statsLoading.value = true
statsError.value = ''
try {
stats.value = await fetchBrandGatingStats()
const result = await fetchBrandGatingStats()
if (!statsGate.isCurrent(token)) return
stats.value = result
} catch (error) {
if (!statsGate.isCurrent(token)) return
statsError.value = actionableErrorText(error)
} finally {
statsLoading.value = false
if (statsGate.isCurrent(token)) statsLoading.value = false
}
}
async function loadPage(nextPage = page.value): Promise<void> {
const token = pageGate.begin()
pageLoading.value = true
loadError.value = ''
try {
const result = await fetchBrandGatingPage(filter, nextPage, pageSize.value)
if (!pageGate.isCurrent(token)) return
rows.value = result.rows
total.value = result.total
page.value = nextPage
loaded.value = true
} catch (error) {
if (!pageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
pageLoading.value = false
if (pageGate.isCurrent(token)) pageLoading.value = false
}
}
@@ -10,7 +10,9 @@ import { useCompanyTabStore } from '@/stores/company-tab'
import { actionableErrorText } from '@/components/admin-feedback'
import OldPagination from '@/components/OldPagination.vue'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { createLatestRequestGate } from '@/utils/latest-request'
import {
KEYWORD_USAGE_PAGE_SIZE,
KEYWORD_USAGE_SCENES,
createKeywordUsageFilter,
keywordUsageCountsText,
@@ -40,16 +42,21 @@ const overviewLoading = ref(false)
const usageRows = ref<KeywordUsageRow[]>([])
const usageTotal = ref(0)
const usagePage = ref(1)
const usagePageSize = ref(15)
const usagePageSize = ref(KEYWORD_USAGE_PAGE_SIZE)
const usageCounts = ref<KeywordUsageCounts>({ copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 })
const usageLoading = ref(false)
const deleteRows = ref<KeywordUsageRow[]>([])
const deleteTotal = ref(0)
const deletePage = ref(1)
const deletePageSize = ref(15)
const deletePageSize = ref(KEYWORD_USAGE_PAGE_SIZE)
const deleteLoading = ref(false)
// 切公司/快速改筛选时,先发的请求可能后返回;每个加载口径各一个序号闸(CR-27)
const overviewGate = createLatestRequestGate()
const usageGate = createLatestRequestGate()
const deleteGate = createLatestRequestGate()
const statsCards = computed(() => {
const stats = overview.value?.stats
return [
@@ -76,42 +83,52 @@ function queryParams() {
}
async function loadOverview(): Promise<void> {
const token = overviewGate.begin()
overviewLoading.value = true
try {
overview.value = await fetchKeywordUsageOverview({ companyId: companyTab.requestCompanyId })
const result = await fetchKeywordUsageOverview({ companyId: companyTab.requestCompanyId })
if (!overviewGate.isCurrent(token)) return
overview.value = result
} catch (error) {
if (!overviewGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
overviewLoading.value = false
if (overviewGate.isCurrent(token)) overviewLoading.value = false
}
}
async function loadUsage(page = usagePage.value): Promise<void> {
const token = usageGate.begin()
usageLoading.value = true
try {
const result = await fetchKeywordUsage({ ...queryParams(), page, pageSize: usagePageSize.value })
if (!usageGate.isCurrent(token)) return
usageRows.value = result.rows
usageTotal.value = result.total
usageCounts.value = result.counts
usagePage.value = page
} catch (error) {
if (!usageGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
usageLoading.value = false
if (usageGate.isCurrent(token)) usageLoading.value = false
}
}
async function loadDeletes(page = deletePage.value): Promise<void> {
const token = deleteGate.begin()
deleteLoading.value = true
try {
const result = await fetchKeywordUsageDeletes({ ...queryParams(), page, pageSize: deletePageSize.value })
if (!deleteGate.isCurrent(token)) return
deleteRows.value = result.rows
deleteTotal.value = result.total
deletePage.value = page
} catch (error) {
if (!deleteGate.isCurrent(token)) return
loadError.value = actionableErrorText(error)
} finally {
deleteLoading.value = false
if (deleteGate.isCurrent(token)) deleteLoading.value = false
}
}
@@ -55,6 +55,9 @@ export interface KeywordUsageOverview {
export const KEYWORD_USAGE_SCENES = ['已使用', '添加关键词'] as const
/** 初始每页条数:必须落在 OldPagination 的档位(10/20/50/100)里(CR-26)。 */
export const KEYWORD_USAGE_PAGE_SIZE = 10
export function createKeywordUsageFilter(): KeywordUsageFilter {
return { user: '', country: '', keyword: '', scene: '' }
}
@@ -0,0 +1,27 @@
/**
* 只让最后一次请求落地(CR-27)。
*
* 快速切公司/筛选时,先发的请求可能后返回;如果直接写 ref,旧响应会覆盖新结果。
* 每个加载函数在发请求前 `begin()` 拿一个 token,回写前 `isCurrent(token)` 验一次;
* 新请求一发出,旧 token 立即作废(不需要 AbortController 也能丢掉晚到的响应)。
*/
export interface LatestRequestGate {
/** 开一次新请求并作废之前所有 token(含未返回的那些)。 */
begin(): number
/** 这个 token 是否仍是最后一次 `begin()` 发出的。 */
isCurrent(token: number): boolean
}
export function createLatestRequestGate(): LatestRequestGate {
let latest = 0
return {
begin(): number {
latest += 1
return latest
},
isCurrent(token: number): boolean {
// token 只由 begin() 发出(从 1 起);0 不是合法 token,避免未发请求时误判为当前
return token > 0 && token === latest
},
}
}
@@ -1,6 +1,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
KEYWORD_USAGE_PAGE_SIZE,
createKeywordUsageFilter,
keywordUsageCountsText,
keywordUsageSceneLabel,
@@ -8,6 +9,12 @@ import {
parseKeywordUsagePage,
} from '../src/pages/tasks/keyword-usage-model.ts'
test('keyword_usage_default_page_size_matches_pagination_options', () => {
// OldPagination 的档位是 10/20/50/100;初始值不在档位里时下拉显示与实际请求不一致(CR-26)
assert.equal(KEYWORD_USAGE_PAGE_SIZE, 10)
assert.ok([10, 20, 50, 100].includes(KEYWORD_USAGE_PAGE_SIZE))
})
test('keyword_usage_filter_defaults_and_scene_labels', () => {
assert.deepEqual(createKeywordUsageFilter(), { user: '', country: '', keyword: '', scene: '' })
assert.equal(keywordUsageSceneLabel('复制关键词'), '已使用(复制)')
@@ -0,0 +1,21 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createLatestRequestGate } from '../src/utils/latest-request.ts'
test('latest_request_gate_only_accepts_the_newest_token', () => {
const gate = createLatestRequestGate()
const first = gate.begin()
assert.equal(gate.isCurrent(first), true)
const second = gate.begin()
assert.equal(gate.isCurrent(second), true)
assert.equal(gate.isCurrent(first), false, '新请求一发出,旧 token 必须立即失效')
})
test('latest_request_gate_starts_with_no_current_token', () => {
const gate = createLatestRequestGate()
assert.equal(gate.isCurrent(0), false, '未发请求前不能用 0 号 token 回写')
const token = gate.begin()
assert.ok(token > 0)
assert.equal(gate.isCurrent(token), true)
})
@@ -0,0 +1,201 @@
/**
* 切公司/快速改筛选时,旧响应不得覆盖新结果(CR-27)。
*
* 跑真组件 + 真 pinia store,API 用可控 deferred 顶掉:
* 先让新请求落地,再让旧请求后返回,断言页面仍显示新结果。
*
* 跑法:`npx vitest run tests/mount/stale-response-drop.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import KeywordUsagePage from '@/pages/tasks/KeywordUsagePage.vue'
import BrandGatingPanel from '@/pages/tasks/BrandGatingPanel.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const keywordApi = vi.hoisted(() => ({
fetchKeywordUsage: vi.fn(),
fetchKeywordUsageDeletes: vi.fn(),
fetchKeywordUsageOverview: vi.fn(),
}))
const gatingApi = vi.hoisted(() => ({
fetchBrandGatingPage: vi.fn(),
fetchBrandGatingStats: vi.fn(),
deleteBrandGating: vi.fn(),
importBrandGatingText: vi.fn(),
submitBrandGating: vi.fn(),
updateBrandGatingStatus: vi.fn(),
}))
vi.mock('@/pages/tasks/keyword-usage-api.ts', () => keywordApi)
vi.mock('@/pages/tasks/brand-gating-api.ts', () => gatingApi)
interface Deferred<T> {
promise: Promise<T>
resolve: (value: T) => void
}
function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void
const promise = new Promise<T>((done) => {
resolve = done
})
return { promise, resolve }
}
const loadingDirective = { mounted() {}, updated() {} }
function mountPage(component: Parameters<typeof mount>[0], pinia: Pinia): VueWrapper {
return mount(component, {
global: {
plugins: [pinia],
directives: { loading: loadingDirective },
},
})
}
function usagePage(keyword: string) {
return {
total: 1,
rows: [{
userName: 'alice',
country: '英国',
keyword,
scene: '复制关键词',
time: '2026-10-25 10:00:00',
}],
counts: { copy: 1, copyExisting: 1, copyDeleted: 0, add: 0 },
}
}
function gatingPage(brand: string) {
return {
total: 1,
rows: [{
id: 1,
brand,
asin: '',
country: '英国',
gatingType: '品牌gating',
status: 1,
source: 'MANUAL',
shopName: '',
remark: '',
createdAt: '2026-10-25 10:00:00',
updatedAt: '',
disabledAt: '',
}],
}
}
describe('CR-27:切换期间晚到的响应必须丢弃', () => {
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
// 只有超管才带 company_id;company tab 的 activeId 直接改,不依赖公司目录接口
useCompanyTabStore().setActiveId(1)
keywordApi.fetchKeywordUsageOverview.mockResolvedValue({
stats: { used: 0, exist: 0, deletedKw: 0, added: 0, totalUse: 0, deletes: 0 },
users: [],
countries: [],
})
keywordApi.fetchKeywordUsageDeletes.mockResolvedValue({
total: 0,
rows: [],
counts: { copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 },
})
gatingApi.fetchBrandGatingStats.mockResolvedValue({
total: 0,
active: 0,
disabled: 0,
brands: 0,
byType: [],
byCountry: [],
bySource: [],
})
})
it('关键词使用记录:切公司后旧公司响应后到,页面仍显示新公司数据', async () => {
const calls: Array<{
companyId?: number | null
pageSize?: number
deferred: Deferred<ReturnType<typeof usagePage>>
}> = []
keywordApi.fetchKeywordUsage.mockImplementation((params: { companyId?: number | null; pageSize?: number }) => {
const pending = deferred<ReturnType<typeof usagePage>>()
calls.push({ companyId: params.companyId, pageSize: params.pageSize, deferred: pending })
return pending.promise
})
const wrapper = mountPage(KeywordUsagePage, pinia)
await flushPromises()
expect(calls).toHaveLength(1)
expect(calls[0].companyId).toBe(1)
expect(calls[0].pageSize).toBe(10)
useCompanyTabStore().setActiveId(2)
await flushPromises()
expect(calls).toHaveLength(2)
expect(calls[1].companyId).toBe(2)
calls[1].deferred.resolve(usagePage('beta-keyword'))
await flushPromises()
expect(wrapper.text()).toContain('beta-keyword')
// 旧公司的响应晚到:序号闸必须把它丢掉
calls[0].deferred.resolve(usagePage('alpha-keyword'))
await flushPromises()
expect(wrapper.text()).toContain('beta-keyword')
expect(wrapper.text()).not.toContain('alpha-keyword')
})
it('品牌 Gating:快速改筛选时旧筛选响应后到,列表仍显示新筛选结果', async () => {
const calls: Array<{
keyword: string
deferred: Deferred<ReturnType<typeof gatingPage>>
}> = []
gatingApi.fetchBrandGatingPage.mockImplementation((filter: { keyword: string }) => {
const pending = deferred<ReturnType<typeof gatingPage>>()
calls.push({ keyword: filter.keyword, deferred: pending })
return pending.promise
})
const wrapper = mountPage(BrandGatingPanel, pinia)
await flushPromises()
expect(calls).toHaveLength(1)
calls[0].deferred.resolve(gatingPage('initial-brand'))
await flushPromises()
expect(wrapper.text()).toContain('initial-brand')
const input = wrapper.get('input[placeholder="搜索品牌 / ASIN"]')
const queryButton = wrapper.findAll('button').find((button) => button.text() === '查询')
expect(queryButton, '页面里应有「查询」按钮').toBeDefined()
await input.setValue('old')
await queryButton!.trigger('click')
await flushPromises()
expect(calls).toHaveLength(2)
expect(calls[1].keyword).toBe('old')
await input.setValue('new')
await queryButton!.trigger('click')
await flushPromises()
expect(calls).toHaveLength(3)
expect(calls[2].keyword).toBe('new')
calls[2].deferred.resolve(gatingPage('new-brand'))
await flushPromises()
expect(wrapper.text()).toContain('new-brand')
calls[1].deferred.resolve(gatingPage('old-brand'))
await flushPromises()
expect(wrapper.text()).toContain('new-brand')
expect(wrapper.text()).not.toContain('old-brand')
})
})