@@ -14,12 +14,15 @@
< div class = "section-title" > 备选店铺 < / div >
< div v-if = "!candidates.length" class="empty-candidates" > 暂无备选店铺 , 请先输入并添加 < / div >
< div v-else class = "candidate-table-scroll" >
< el-table :data = "c andidates" row -key = " id " height = "240" class = "candidate-table" @ selection -change = " onSelectionChange " >
< el-table :data = "pagedC andidates" row -key = " id " height = "240" class = "candidate-table" @ selection -change = " onSelectionChange " >
< el-table-column type = "selection" width = "42" / >
< el-table-column prop = "shop_name" label = "店铺名" min -width = " 120 " show -overflow -tooltip / >
< el-table-column label = "操作" width = "72" align = "center" > < template # default = "{ row }" > < button type = "button" class = "link-danger" @click ="removeCandidate(row)" > 删除 < / button > < / template > < / el -table -column >
< / el-table >
< / div >
< el-pagination v-if = "candidateTotal > candidatePageSize" class="candidate-pagination"
layout = "total, prev, pager, next" :total = "candidateTotal" :page-size = "candidatePageSize"
v -model :current-page = "candidatePage" / >
< div class = "section-title" > 国家配置 < / div >
< p class = "hint country-pref-hint" > 勾选的国家会在每一个执行时间点都执行一遍 。 勾选区会按照已选顺序排在前面 , 下方支持拖拽排序 , 和商品风险页保持一致 。 < / p >
< div class = "country-pref-checks" >
@@ -48,8 +51,8 @@
< div class = "section-title" > 定时执行 < / div >
< label class = "schedule-switch" > < input v-model = "scheduleEnabled" type="checkbox" :disabled="pushing" @change="onScheduleToggle" / > < span > 启用多时间点调度 < / span > < / label >
< div v-if = "scheduleEnabled" class="schedule-config" >
< div v-for = "(value , index) in schedulePickerValues" :key="`schedule-${index}` " class="schedule-row" >
< el -date -picker :model-value = "value" type = "datetime" value -format = " YYYY -MM -DD HH : mm : ss " format = "MM-DD HH:mm" placeholder = "选择执行时间" :disabled = "pushing" class = "schedule-picker" @ update : model -value = " updateScheduleValue ( index , $ event ) " / >
< div v-for = "(row , index) in schedulePickerValues" :key="row.id " class="schedule-row" >
< el -date -picker :model-value = "row. value" type = "datetime" value -format = " YYYY -MM -DD HH : mm : ss " format = "MM-DD HH:mm" placeholder = "选择执行时间" :disabled = "pushing" class = "schedule-picker" @ update : model -value = " updateScheduleValue ( index , $ event ) " / >
< button type = "button" class = "schedule-remove" : disabled = "pushing || schedulePickerValues.length <= 1" @click ="removeScheduleValue(index)" > 删除 < / button >
< / div >
< button type = "button" class = "schedule-add" :disabled = "pushing" @click ="addScheduleValue" > 添加时间点 < / button >
@@ -116,7 +119,7 @@
< / template >
< script setup lang = "ts" >
import { computed , onMounted , onUnmounted , ref } from 'vue'
import { computed , onMounted , onUnmounted , ref , shallowRef , triggerRef } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue' ;
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
@@ -128,6 +131,7 @@ import { getPollingProgressBatch } from '@/shared/api/task-progress-polling.ts'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { createRowId } from '@/shared/utils/row-id'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { taskStatusClass , taskStatusText } from '@/shared/utils/task-status-text'
import { useZiniaoVersion } from '@/shared/utils/ziniao-version'
@@ -148,6 +152,13 @@ const {
total : matchedTotal ,
paged : pagedMatchedItems ,
} = useTablePaging ( matchedItems )
// F9:备选店铺表同样只渲染当前页(loadCandidates 是全量返回,与其余工具页一致)
const {
page : candidatePage ,
pageSize : candidatePageSize ,
total : candidateTotal ,
paged : pagedCandidates ,
} = useTablePaging ( candidates )
const shopMatchListingFilter = ref < ListingFilterValue > ( 'Active' )
const adding = ref ( false )
const matching = ref ( false )
@@ -163,12 +174,18 @@ const countryPrefSaving = ref(false)
const countryPrefUserTouched = ref ( false )
let countryPrefSaveTimer : ReturnType < typeof setTimeout > | null = null
const scheduleEnabled = ref ( true )
const schedulePickerValues = ref < string [ ] > ( [ getDefaultScheduleValue ( ) ] )
/**
* 定时行状态:id 是给 v-for 用的稳定 key(此前用 index,删中间行时后面的 el-date-picker
* 实例会被错位复用),value 仍是页面上看到的时间串。业务侧只读 value。
*/
type ScheduleRow = { id : string ; value : string }
const schedulePickerValues = ref < ScheduleRow [ ] > ( [ { id : createRowId ( 'schedule' ) , value : getDefaultScheduleValue ( ) } ] )
const dashboard = ref < ShopMatchDashboardVo > ( { candidateCount : 0 , processedTaskCount : 0 , successTaskCount : 0 , failedTaskCount : 0 } )
const historyItems = ref < ShopMatchHistoryItem [ ] > ( [ ] )
const pollingTaskIds = ref < number [ ] > ( [ ] )
const taskDetails = ref < Record < number , string > > ( { } )
const taskSnapshots = ref < Record < number , ShopMatchTaskDetailVo > > ( { } )
/** 任务快照(审查 C3):整份数百 KB,shallowRef 只跟踪整份替换;本文件所有写入都是 .value = 新对象且随后 triggerRef */
const taskSnapshots = shallowRef < Record < number , ShopMatchTaskDetailVo > > ( { } )
/** 任务快照的 task 时间(开始=创建,结束=完成;运行中结束显示进行中) */
function snapTask ( item : ShopMatchHistoryItem ) {
@@ -260,7 +277,7 @@ function loadPollingIdsFromStorage() { try { const raw = window.localStorage.get
function savePollingIds ( ) { setStorageJson ( sessionKey ( ) , pollingTaskIds . value , pollingTaskIds . value . length === 0 ) }
function loadTaskDetailsFromStorage ( ) { try { const raw = window . localStorage . getItem ( taskStatusStorageKey ( ) ) ; taskDetails . value = raw ? JSON . parse ( raw ) : { } } catch { taskDetails . value = { } } }
function saveTaskDetailsToStorage ( ) { setStorageJson ( taskStatusStorageKey ( ) , taskDetails . value , Object . keys ( taskDetails . value ) . length === 0 ) }
function loadTaskSnapshotsFromStorage ( ) { try { const raw = window . localStorage . getItem ( taskSnapshotsStorageKey ( ) ) ; taskSnapshots . value = raw ? JSON . parse ( raw ) : { } } catch { taskSnapshots . value = { } } }
function loadTaskSnapshotsFromStorage ( ) { try { const raw = window . localStorage . getItem ( taskSnapshotsStorageKey ( ) ) ; taskSnapshots . value = raw ? JSON . parse ( raw ) : { } ; triggerRef ( taskSnapshots ) } catch { taskSnapshots . value = { } ; triggerRef ( taskSnapshots ) } }
function saveTaskSnapshotsToStorage ( ) { setStorageJson ( taskSnapshotsStorageKey ( ) , taskSnapshots . value , Object . keys ( taskSnapshots . value ) . length === 0 ) }
function loadMatchedItemsFromStorage ( ) { try { const raw = window . localStorage . getItem ( matchedItemsStorageKey ( ) ) ; matchedItems . value = raw ? JSON . parse ( raw ) : [ ] } catch { matchedItems . value = [ ] } }
function saveMatchedItemsToStorage ( ) { setStorageJson ( matchedItemsStorageKey ( ) , matchedItems . value , matchedItems . value . length === 0 ) }
@@ -275,7 +292,7 @@ function removePollingTask(taskId: number) {
if ( taskSnapshots . value [ taskId ] ) {
const nextSnapshots = { ... taskSnapshots . value }
delete nextSnapshots [ taskId ]
taskSnapshots . value = nextSnapshots
taskSnapshots . value = nextSnapshots ; triggerRef ( taskSnapshots )
saveTaskSnapshotsToStorage ( )
}
savePollingIds ( )
@@ -323,9 +340,9 @@ function onCountryDragStart(index: number) { dragCountryIndex.value = index }
function onCountryDragEnd ( ) { dragCountryIndex . value = null }
function onCountryDrop ( toIndex : number ) { const from = dragCountryIndex . value ; dragCountryIndex . value = null ; if ( from == null || from === toIndex ) return ; countryPrefUserTouched . value = true ; const list = [ ... orderedCountryCodes . value ] ; const [ item ] = list . splice ( from , 1 ) ; list . splice ( toIndex , 0 , item ) ; orderedCountryCodes . value = list ; scheduleSaveCountryPreference ( ) }
function onScheduleToggle ( ) { if ( scheduleEnabled . value ) schedulePickerValues . value = sanitizeSchedulePickerValues ( schedulePickerValues . value , true ) ; if ( ! scheduleEnabled . value ) schedulePickerValues . value = [ ] }
function addScheduleValue ( ) { const last = schedulePickerValues . value [ schedulePickerValues . value . length - 1 ] ; const nextValue = last ? nextScheduleValueAfter ( last , 60 ) : getDefaultScheduleValue ( ) ; schedulePickerValues . value = [ ... schedulePickerValues . value , nextValue ] }
function addScheduleValue ( ) { const last = schedulePickerValues . value [ schedulePickerValues . value . length - 1 ] ; const nextValue = last ? nextScheduleValueAfter ( last . value , 60 ) : getDefaultScheduleValue ( ) ; schedulePickerValues . value = [ ... schedulePickerValues . value , { id : createRowId ( 'schedule' ) , value : nextValue } ] }
function removeScheduleValue ( index : number ) { if ( schedulePickerValues . value . length <= 1 ) return ; schedulePickerValues . value = schedulePickerValues . value . filter ( ( _ , idx ) => idx !== index ) }
function updateScheduleValue ( index : number , value : string | null ) { const list = [ ... schedulePickerValues . value ] ; list [ index ] = value || '' ; schedulePickerValues . value = sanitizeSchedulePickerValues ( list , false ) }
function updateScheduleValue ( index : number , value : string | null ) { const list = [ ... schedulePickerValues . value ] ; list [ index ] = { ... list [ index ] , value : value || '' } ; schedulePickerValues . value = sanitizeSchedulePickerValues ( list , false ) }
function mergeMatchedItems ( base : ShopMatchShopQueueItem [ ] , incoming : ShopMatchShopQueueItem [ ] ) { const map = new Map < string , ShopMatchShopQueueItem > ( ) ; for ( const item of base ) map . set ( rowKeyForMatch ( item ) , item ) ; for ( const item of incoming ) map . set ( rowKeyForMatch ( item ) , item ) ; return Array . from ( map . values ( ) ) }
async function runMatch ( ) { const names = selectedCandidates . value . map ( ( item ) => item . shop _name ) . filter ( Boolean ) ; if ( ! names . length ) { ElMessage . warning ( '请先选择候选店铺' ) ; return } matching . value = true ; try { const data = await matchShopMatchShops ( names ) ; matchedItems . value = mergeMatchedItems ( matchedItems . value , data . items || [ ] ) ; saveMatchedItemsToStorage ( ) ; if ( autoQueueEnabled . value ) void processMatchedQueue ( ) ; ElMessage . success ( ` 本次返回 ${ data . items ? . length || 0 } 条匹配结果 ` ) } catch ( error ) { ElMessage . error ( error instanceof Error ? error . message : '匹配失败' ) } finally { matching . value = false } }
function removeMatchedRow ( row : ShopMatchShopQueueItem ) { matchedItems . value = matchedItems . value . filter ( ( item ) => rowKeyForMatch ( item ) !== rowKeyForMatch ( row ) ) ; saveMatchedItemsToStorage ( ) }
@@ -333,43 +350,46 @@ function removeMatchedRowsLocally(rows: ShopMatchHistoryItem[] | ShopMatchShopQu
function parseScheduleValues ( ) {
if ( ! scheduleEnabled . value ) return undefined
const now = Date . now ( )
const values = schedulePickerValues . value . map ( ( item ) => item . trim ( ) ) . filter ( Boolean )
if ( ! values . length ) throw new Error ( '请至少选择一个执行时间' )
const withTime = values . map ( ( value ) => {
const date = parseScheduleDateTime ( value )
if ( ! date ) throw new Error ( ` 时间格式无效: ${ value } ` )
return { raw : formatScheduleDateTime ( date ) , picker : formatPickerDateTime ( date ) , time : date . getTime ( ) }
const rows = schedulePickerValues . value
. map ( ( row ) => ( { id : row . id , value : row . value . trim ( ) } ) )
. filter ( ( row ) => row . value )
if ( ! rows . length ) throw new Error ( '请至少选择一个执行时间' )
const withTime = rows . map ( ( row ) => {
const date = parseScheduleDateTime ( row . value )
if ( ! date ) throw new Error ( ` 时间格式无效: ${ row . value } ` )
return { id : row . id , raw : formatScheduleDateTime ( date ) , picker : formatPickerDateTime ( date ) , time : date . getTime ( ) }
} ) . sort ( ( a , b ) => a . time - b . time )
for ( let i = 1 ; i < withTime . length ; i += 1 ) if ( withTime [ i ] . time === withTime [ i - 1 ] . time ) throw new Error ( '执行时间不能重复' )
const futureOnly = withTime . filter ( ( item ) => item . time > now )
if ( ! futureOnly . length ) throw new Error ( '执行时间必须晚于当前时间,请重新选择' )
if ( futureOnly . length !== withTime . length ) {
schedulePickerValues . value = futureOnly . map ( ( item ) => item . picker )
// 回填时沿用各行原有 id:否则被移除的行会让后面行的 key 变化,日期控件实例跟着错位
schedulePickerValues . value = futureOnly . map ( ( item ) => ( { id : item . id , value : item . picker } ) )
ElMessage . warning ( '已自动移除早于当前时间的执行时间' )
}
return futureOnly . map ( ( item ) => item . raw )
}
function sanitizeSchedulePickerValues ( values : string [ ] , ensureOne : boolean ) {
function sanitizeSchedulePickerValues ( values : ScheduleRow [ ] , ensureOne : boolean ) : ScheduleRow [ ] {
const now = Date . now ( )
const normalized = values
. map ( ( item ) => item . trim ( ) )
. filter ( Boolean )
. map ( ( value ) => {
const date = parseScheduleDateTime ( value )
return date ? { value : formatPickerDateTime ( date ) , time : date . getTime ( ) } : null
. map ( ( row ) => ( { id : row . id , value : row . value . trim ( ) } ) )
. filter ( ( row ) => row . value )
. map ( ( row ) => {
const date = parseScheduleDateTime ( row . value )
return date ? { id : row . id , value : formatPickerDateTime ( date ) , time : date . getTime ( ) } : null
} )
. filter ( ( item ) : item is { value : string ; time : number } => ! ! item )
. filter ( ( item ) : item is { id : string ; value : string ; time : number } => ! ! item )
. filter ( ( item ) => item . time > now )
. sort ( ( a , b ) => a . time - b . time )
const deduped : string [ ] = [ ]
const deduped : ScheduleRow [ ] = [ ]
const seen = new Set < string > ( )
for ( const item of normalized ) {
if ( seen . has ( item . value ) ) continue
seen . add ( item . value )
deduped . push ( item . value )
deduped . push ( { id : item . id , value : item . value } )
}
if ( ! deduped . length && ensureOne ) return [ getDefaultScheduleValue ( ) ]
if ( ! deduped . length && ensureOne ) return [ { id : createRowId ( 'schedule' ) , value : getDefaultScheduleValue ( ) } ]
return deduped
}
function getJavaApiBaseUrl ( ) { return ` ${ window . location . origin } /newApi/api ` }
@@ -415,7 +435,7 @@ function buildQueuePayload(taskId: number, item: Pick<ShopMatchHistoryItem, 'sho
}
}
function nextScheduleStage ( taskId : number ) { const task = taskSnapshots . value [ taskId ] ? . task ; const stages = task ? . scheduleStages || [ ] ; const currentStageIndex = task ? . currentStageIndex ; if ( typeof currentStageIndex !== 'number' ) return null ; const stage = stages . find ( ( item ) => item . stageIndex === currentStageIndex ) ; if ( ! stage ? . scheduledAt ) return null ; return { stageIndex : currentStageIndex , scheduledAt : stage . scheduledAt , finalStage : currentStageIndex === stages . length - 1 } }
async function dispatchScheduledTask ( taskId : number , item : ShopMatchHistoryItem ) { const api = getPywebviewApi ( ) ; if ( ! api ? . enqueue _json ) throw new Error ( '当前客户端未提供 enqueue_json' ) ; const stage = nextScheduleStage ( taskId ) ; const snapshot = taskSnapshots . value [ taskId ] ; const countryCodes = snapshot ? . task ? . countryCodes || orderedCountryCodes . value ; if ( ! stage ) throw new Error ( ` 任务 ${ taskId } 缺少待执行阶段 ` ) ; clearDispatchTimer ( taskId ) ; await withTransientRetry ( ( ) => activateShopMatchTask ( taskId , stage . stageIndex ) , ( attempt , maxAttempts ) => { queuePushResult . value = ` 任务 ${ taskId } 等待服务恢复后再激活执行( ${ attempt } / ${ maxAttempts } ) ...` } ) ; taskDetails . value = { ... taskDetails . value , [ taskId ] : 'RUNNING' } ; if ( snapshot ? . task ) taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : { ... snapshot , task : { ... snapshot . task , status : 'RUNNING' , activeStageIndex : stage . stageIndex } } } ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; const payload = buildQueuePayload ( taskId , item , countryCodes , stage . stageIndex , stage . finalStage ) ; queuePayloadText . value = JSON . stringify ( payload , null , 2 ) ; const result = await api . enqueue _json ( payload ) ; if ( ! result ? . success ) throw new Error ( result ? . error || ` 任务 ${ taskId } 启动失败 ` ) ; addPollingTask ( taskId ) ; queuePushResult . value = ` 任务 ${ taskId } 已启动第 ${ stage . stageIndex + 1 } 轮 ` ; ensurePolling ( true ) }
async function dispatchScheduledTask ( taskId : number , item : ShopMatchHistoryItem ) { const api = getPywebviewApi ( ) ; if ( ! api ? . enqueue _json ) throw new Error ( '当前客户端未提供 enqueue_json' ) ; const stage = nextScheduleStage ( taskId ) ; const snapshot = taskSnapshots . value [ taskId ] ; const countryCodes = snapshot ? . task ? . countryCodes || orderedCountryCodes . value ; if ( ! stage ) throw new Error ( ` 任务 ${ taskId } 缺少待执行阶段 ` ) ; clearDispatchTimer ( taskId ) ; await withTransientRetry ( ( ) => activateShopMatchTask ( taskId , stage . stageIndex ) , ( attempt , maxAttempts ) => { queuePushResult . value = ` 任务 ${ taskId } 等待服务恢复后再激活执行( ${ attempt } / ${ maxAttempts } ) ...` } ) ; taskDetails . value = { ... taskDetails . value , [ taskId ] : 'RUNNING' } ; if ( snapshot ? . task ) taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : { ... snapshot , task : { ... snapshot . task , status : 'RUNNING' , activeStageIndex : stage . stageIndex } } } ; triggerRef ( taskSnapshots ) ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; const payload = buildQueuePayload ( taskId , item , countryCodes , stage . stageIndex , stage . finalStage ) ; queuePayloadText . value = JSON . stringify ( payload , null , 2 ) ; const result = await api . enqueue _json ( payload ) ; if ( ! result ? . success ) throw new Error ( result ? . error || ` 任务 ${ taskId } 启动失败 ` ) ; addPollingTask ( taskId ) ; queuePushResult . value = ` 任务 ${ taskId } 已启动第 ${ stage . stageIndex + 1 } 轮 ` ; ensurePolling ( true ) }
function scheduledTimestamp ( value ? : string ) { const date = parseScheduleDateTime ( value ) ; return date ? date . getTime ( ) : Number . NaN }
function findReadyScheduledTasks ( ) { const taskIds = new Set < number > ( pollingTaskIds . value ) ; for ( const key of Object . keys ( taskSnapshots . value ) ) { const id = normalizeTaskId ( key ) ; if ( id > 0 ) taskIds . add ( id ) } for ( const item of historyItems . value ) { const id = normalizeTaskId ( item . taskId ) ; if ( id > 0 ) taskIds . add ( id ) } const ready = Array . from ( taskIds ) . map ( ( taskId ) => { const snapshot = taskSnapshots . value [ taskId ] ; const taskStatus = taskDetails . value [ taskId ] || snapshot ? . task ? . status ; const item = snapshot ? . items ? . [ 0 ] || historyItems . value . find ( ( row ) => normalizeTaskId ( row . taskId ) === taskId ) ; const stage = nextScheduleStage ( taskId ) ; if ( taskStatus !== 'SCHEDULED' || ! item || ! stage ? . scheduledAt ) return null ; const scheduledTime = scheduledTimestamp ( stage . scheduledAt ) ; if ( ! Number . isFinite ( scheduledTime ) || scheduledTime > Date . now ( ) ) return null ; return { taskId , item , scheduledTime } } ) . filter ( ( item ) : item is { taskId : number ; item : ShopMatchHistoryItem ; scheduledTime : number } => ! ! item ) ; ready . sort ( ( a , b ) => a . scheduledTime - b . scheduledTime || a . taskId - b . taskId ) ; return ready }
async function pumpScheduledQueue ( ) {
@@ -456,7 +476,7 @@ function clearSleepTimers() { timers.clearCategory('queue-wait') }
function isTransientBackendError ( error : unknown ) { const message = ( error instanceof Error ? error . message : String ( error || '' ) ) . toLowerCase ( ) ; return TRANSIENT _BACKEND _ERROR _PATTERNS . some ( ( pattern ) => message . includes ( pattern . toLowerCase ( ) ) ) }
async function withTransientRetry < T > ( action : ( ) => Promise < T > , onRetry : ( attempt : number , maxAttempts : number ) => void , maxAttempts = 10 ) { let attempt = 0 ; while ( true ) { if ( disposed ) throw new Error ( 'component disposed' ) ; try { return await action ( ) } catch ( error ) { attempt += 1 ; if ( ! isTransientBackendError ( error ) || attempt >= maxAttempts ) throw error ; onRetry ( attempt , maxAttempts ) ; await sleep ( getPollIntervalMs ( ) ) } } }
async function refreshTaskBatch ( ) { if ( ! pollingTaskIds . value . length ) return { settledTaskIds : [ ] as number [ ] } ; try { // F5:主轮询只读 status 等轻量白名单字段,走 light 端点减小响应体;轻量异常/空结果时回退重型 batch(否则会漏刷新结果)
const batch = await getPollingProgressBatch ( 'shopMatch' , pollingTaskIds . value , { fallback : ( ) => getShopMatchTaskProgressBatch ( pollingTaskIds . value ) } ) ; const nextSnapshots = { ... taskSnapshots . value } ; const settledTaskIds = new Set < number > ( ) ; for ( const missingId of batch . missingTaskIds || [ ] ) { removeTaskLocally ( missingId ) ; delete nextSnapshots [ missingId ] ; settledTaskIds . add ( missingId ) } for ( const detail of batch . items || [ ] ) { const taskId = detail . task ? . id ; if ( ! taskId ) continue ; const prev = nextSnapshots [ taskId ] ; nextSnapshots [ taskId ] = prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail ; const status = detail . task ? . status || '' ; if ( ! status ) continue ; taskDetails . value [ taskId ] = status ; if ( isTaskTerminalStatus ( status ) ) { removePollingTask ( taskId ) ; settledTaskIds . add ( taskId ) ; continue } if ( status === 'SCHEDULED' ) { stopPollingTask ( taskId ) ; settledTaskIds . add ( taskId ) } } taskSnapshots . value = nextSnapshots ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; restoreScheduledDispatches ( ) ; return { settledTaskIds : Array . from ( settledTaskIds ) } } catch { return { settledTaskIds : [ ] as number [ ] } } }
const batch = await getPollingProgressBatch ( 'shopMatch' , pollingTaskIds . value , { fallback : ( ) => getShopMatchTaskProgressBatch ( pollingTaskIds . value ) } ) ; const nextSnapshots = { ... taskSnapshots . value } ; const settledTaskIds = new Set < number > ( ) ; for ( const missingId of batch . missingTaskIds || [ ] ) { removeTaskLocally ( missingId ) ; delete nextSnapshots [ missingId ] ; settledTaskIds . add ( missingId ) } for ( const detail of batch . items || [ ] ) { const taskId = detail . task ? . id ; if ( ! taskId ) continue ; const prev = nextSnapshots [ taskId ] ; nextSnapshots [ taskId ] = prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail ; const status = detail . task ? . status || '' ; if ( ! status ) continue ; taskDetails . value [ taskId ] = status ; if ( isTaskTerminalStatus ( status ) ) { removePollingTask ( taskId ) ; settledTaskIds . add ( taskId ) ; continue } if ( status === 'SCHEDULED' ) { stopPollingTask ( taskId ) ; settledTaskIds . add ( taskId ) } } taskSnapshots . value = nextSnapshots ; triggerRef ( taskSnapshots ) ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; restoreScheduledDispatches ( ) ; return { settledTaskIds : Array . from ( settledTaskIds ) } } catch { return { settledTaskIds : [ ] as number [ ] } } }
function getPollIntervalMs ( ) { return getTaskPollIntervalMs ( ) }
function scheduleNextPoll ( immediate = false ) { if ( disposed ) return ; if ( pollTimer . value ) { if ( ! immediate ) return ; timers . clearTimer ( 'task-poll' , pollTimer . value ) ; pollTimer . value = null } const run = async ( ) => { pollTimer . value = null ; if ( disposed ) return ; if ( pollingInFlight . value || ! pollingTaskIds . value . length ) { if ( pollingTaskIds . value . length ) scheduleNextPoll ( ) ; return } pollingInFlight . value = true ; try { const { settledTaskIds } = await refreshTaskBatch ( ) ; if ( settledTaskIds . length ) await Promise . allSettled ( [ loadHistory ( ) , loadDashboard ( ) ] ) } finally { pollingInFlight . value = false } if ( ! disposed && pollingTaskIds . value . length ) pollTimer . value = timers . setTimeout ( 'task-poll' , run , getPollIntervalMs ( ) ) } ; if ( immediate ) void run ( ) ; else pollTimer . value = timers . setTimeout ( 'task-poll' , run , getPollIntervalMs ( ) ) }
function ensurePolling ( immediate = false ) { scheduleNextPoll ( immediate ) }
@@ -464,7 +484,7 @@ function stopPolling() { if (pollTimer.value) { timers.clearTimer('task-poll', p
async function waitForTaskTerminal ( taskId : number ) { let transientErrorCount = 0 ; const maxTransientErrors = 30 ; while ( true ) { if ( disposed ) return 'STOPPED' ; try { // F5:等待终态的紧循环只读 status,走 light 端点减小轮询响应体,异常回退重型 batch
const batch = await getPollingProgressBatch ( 'shopMatch' , [ taskId ] , {
fallback : ( ) => getShopMatchTaskProgressBatch ( [ taskId ] ) ,
} ) ; if ( transientErrorCount > 0 ) queuePushResult . value = ` 任务 ${ taskId } 服务已恢复,继续等待执行结果... ` ; transientErrorCount = 0 ; if ( ( batch . missingTaskIds || [ ] ) . includes ( taskId ) ) { removeTaskLocally ( taskId ) ; await refreshTaskViewsBestEffort ( ) ; restoreScheduledDispatches ( ) ; return 'FAILED' } const detail = ( batch . items || [ ] ) . find ( ( item ) => item . task ? . id === taskId ) ; const status = detail ? . task ? . status || '' ; if ( detail ) { const prev = taskSnapshots . value [ taskId ] ; taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail } ; saveTaskSnapshotsToStorage ( ) } if ( status ) { taskDetails . value [ taskId ] = status ; saveTaskDetailsToStorage ( ) } if ( isTaskTerminalStatus ( status ) ) { removePollingTask ( taskId ) ; await refreshTaskViewsBestEffort ( ) ; restoreScheduledDispatches ( ) ; return status } } catch ( error ) { if ( ! isTransientBackendError ( error ) ) throw error ; transientErrorCount += 1 ; if ( transientErrorCount >= maxTransientErrors ) throw new Error ( ` 任务 ${ taskId } 等待服务恢复超时,请稍后手动刷新查看状态 ` ) ; queuePushResult . value = ` 任务 ${ taskId } 运行中,正在等待服务恢复( ${ transientErrorCount } / ${ maxTransientErrors } ) ...` ; if ( transientErrorCount === 1 || transientErrorCount % 5 === 0 ) ElMessage . warning ( ` 任务 ${ taskId } 运行中,服务暂时不可用,正在自动重试 ` ) ; await sleep ( getPollIntervalMs ( ) ) ; continue } await sleep ( getPollIntervalMs ( ) ) } }
} ) ; if ( transientErrorCount > 0 ) queuePushResult . value = ` 任务 ${ taskId } 服务已恢复,继续等待执行结果... ` ; transientErrorCount = 0 ; if ( ( batch . missingTaskIds || [ ] ) . includes ( taskId ) ) { removeTaskLocally ( taskId ) ; await refreshTaskViewsBestEffort ( ) ; restoreScheduledDispatches ( ) ; return 'FAILED' } const detail = ( batch . items || [ ] ) . find ( ( item ) => item . task ? . id === taskId ) ; const status = detail ? . task ? . status || '' ; if ( detail ) { const prev = taskSnapshots . value [ taskId ] ; taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail } ; triggerRef ( taskSnapshots ) ; saveTaskSnapshotsToStorage ( ) } if ( status ) { taskDetails . value [ taskId ] = status ; saveTaskDetailsToStorage ( ) } if ( isTaskTerminalStatus ( status ) ) { removePollingTask ( taskId ) ; await refreshTaskViewsBestEffort ( ) ; restoreScheduledDispatches ( ) ; return status } } catch ( error ) { if ( ! isTransientBackendError ( error ) ) throw error ; transientErrorCount += 1 ; if ( transientErrorCount >= maxTransientErrors ) throw new Error ( ` 任务 ${ taskId } 等待服务恢复超时,请稍后手动刷新查看状态 ` ) ; queuePushResult . value = ` 任务 ${ taskId } 运行中,正在等待服务恢复( ${ transientErrorCount } / ${ maxTransientErrors } ) ...` ; if ( transientErrorCount === 1 || transientErrorCount % 5 === 0 ) ElMessage . warning ( ` 任务 ${ taskId } 运行中,服务暂时不可用,正在自动重试 ` ) ; await sleep ( getPollIntervalMs ( ) ) ; continue } await sleep ( getPollIntervalMs ( ) ) } }
async function waitForScheduledTaskStageExit ( taskId : number ) {
let transientErrorCount = 0
const maxTransientErrors = 30
@@ -484,7 +504,7 @@ async function waitForScheduledTaskStageExit(taskId: number) {
const status = detail ? . task ? . status || ''
if ( detail ) {
const prev = taskSnapshots . value [ taskId ]
taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail }
taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : prev ? { ... prev , task : { ... ( prev . task || { } ) , ... ( detail . task || { } ) } } : detail } ; triggerRef ( taskSnapshots )
saveTaskSnapshotsToStorage ( )
}
if ( status ) {
@@ -573,7 +593,7 @@ function formatMatchStatus(status?: string) { const value = (status || '').trim(
function formatMatchRemark ( row : ShopMatchShopQueueItem ) { const message = ( row . matchMessage || '' ) . trim ( ) ; if ( message ) return message ; if ( row . matched && row . matchStatus === 'MATCHED' ) return '已匹配成功,可启动任务' ; if ( row . matched ) return '已关联店铺,请查看状态确认' ; if ( row . matchStatus === 'CONFLICT' ) return '存在多个同名店铺,请人工确认' ; if ( row . matchStatus === 'PENDING' ) return '店铺尚未匹配完成,请稍后查看' ; return '未匹配成功,请检查店铺名' }
async function pushToPythonQueue ( ) { autoQueueEnabled . value = true ; await processMatchedQueue ( ) }
function nextMatchedQueueItem ( ) { return matchedItems . value . find ( ( item ) => item . matched ) }
async function processMatchedQueue ( ) { if ( disposed || queueWorkerRunning . value ) return ; const api = getPywebviewApi ( ) ; if ( ! api ? . enqueue _json ) { ElMessage . error ( '当前客户端未提供 enqueue_json' ) ; return } const matched = matchedItems . value . filter ( ( item ) => item . matched ) ; if ( ! matched . length ) { ElMessage . warning ( '请先匹配可用店铺' ) ; return } if ( ! orderedCountryCodes . value . length ) { ElMessage . warning ( '请至少勾选一个国家' ) ; return } let scheduleValues : string [ ] | undefined ; try { scheduleValues = parseScheduleValues ( ) } catch ( error ) { ElMessage . error ( error instanceof Error ? error . message : '定时配置无效' ) ; return } queueWorkerRunning . value = true ; pushing . value = true ; queuePayloadText . value = '' ; let successCount = 0 ; let failedCount = 0 ; let index = 0 ; try { while ( ! disposed && autoQueueEnabled . value ) { const item = nextMatchedQueueItem ( ) ; if ( ! item ) break ; index += 1 ; try { const created = await withTransientRetry ( ( ) => createShopMatchTask ( [ buildTaskCreateItem ( item ) ] , orderedCountryCodes . value , scheduleValues ) , ( attempt , maxAttempts ) => { queuePushResult . value = ` 服务暂时不可用,正在重试创建任务( ${ attempt } / ${ maxAttempts } ) ...` } ) ; const taskId = created . taskId ; const initialStatus = scheduleValues ? . length ? 'SCHEDULED' : 'RUNNING' ; const snapshot : ShopMatchTaskDetailVo = { task : { id : taskId , status : initialStatus , scheduledAt : scheduleValues ? . [ 0 ] , countryCodes : [ ... orderedCountryCodes . value ] , currentStageIndex : scheduleValues ? . length ? 0 : undefined , activeStageIndex : undefined , scheduleStages : ( scheduleValues || [ ] ) . map ( ( value , stageIndex ) => ( { stageIndex , scheduledAt : value , status : stageIndex === 0 ? 'SCHEDULED' : 'PENDING' } ) ) } , items : created . items } ; taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : snapshot } ; taskDetails . value = { ... taskDetails . value , [ taskId ] : initialStatus } ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; const createdItem = created . items ? . [ 0 ] ; if ( ! createdItem ) { removeMatchedRowsLocally ( [ item ] ) ; continue } if ( scheduleValues ? . length ) { successCount += 1 ; restoreScheduledDispatches ( ) ; queuePushResult . value = ` 任务 ${ taskId } 已创建,共 ${ scheduleValues . length } 个执行时间点 ` ; removeMatchedRowsLocally ( [ item ] ) ; continue } const payload = buildQueuePayload ( taskId , item , orderedCountryCodes . value ) ; queuePayloadText . value = JSON . stringify ( payload , null , 2 ) ; const result = await api . enqueue _json ( payload ) ; if ( ! result ? . success ) { failedCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 启动失败,已自动继续下一条: ${ result ? . error || '未知错误' } ` ; ElMessage . error ( queuePushResult . value ) ; removeMatchedRowsLocally ( [ item ] ) ; continue } addPollingTask ( taskId ) ; ensurePolling ( true ) ; removeMatchedRowsLocally ( [ item ] ) ; queuePushResult . value = ` 任务 ${ taskId } 已提交,等待执行完成 ` ; const finalStatus = await waitForTaskTerminal ( taskId ) ; if ( finalStatus !== 'SUCCESS' ) { failedCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 执行失败,已自动继续下一条 ` ; ElMessage . error ( queuePushResult . value ) ; continue } successCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 已完成 ` } catch ( error ) { if ( disposed ) break ; failedCount += 1 ; queuePushResult . value = ` 第 ${ index } 条任务处理失败,已自动继续下一条: ${ error instanceof Error ? error . message : '未知错误' } ` ; ElMessage . error ( queuePushResult . value ) ; removeMatchedRowsLocally ( [ item ] ) ; continue } } restoreScheduledDispatches ( ) ; if ( ! scheduleValues ? . length ) ensurePolling ( true ) ; if ( ! disposed && ( successCount > 0 || failedCount > 0 ) ) ElMessage . success ( scheduleValues ? . length ? ` 定时任务已创建:成功 ${ successCount } 条,失败 ${ failedCount } 条 ` : ` 店铺启动已完成:成功 ${ successCount } 条,失败 ${ failedCount } 条 ` ) } catch ( error ) { if ( disposed ) return ; const message = error instanceof Error ? error . message : '启动失败' ; queuePushResult . value = message ; ElMessage . error ( message ) } finally { queueWorkerRunning . value = false ; pushing . value = false } }
async function processMatchedQueue ( ) { if ( disposed || queueWorkerRunning . value ) return ; const api = getPywebviewApi ( ) ; if ( ! api ? . enqueue _json ) { ElMessage . error ( '当前客户端未提供 enqueue_json' ) ; return } const matched = matchedItems . value . filter ( ( item ) => item . matched ) ; if ( ! matched . length ) { ElMessage . warning ( '请先匹配可用店铺' ) ; return } if ( ! orderedCountryCodes . value . length ) { ElMessage . warning ( '请至少勾选一个国家' ) ; return } let scheduleValues : string [ ] | undefined ; try { scheduleValues = parseScheduleValues ( ) } catch ( error ) { ElMessage . error ( error instanceof Error ? error . message : '定时配置无效' ) ; return } queueWorkerRunning . value = true ; pushing . value = true ; queuePayloadText . value = '' ; let successCount = 0 ; let failedCount = 0 ; let index = 0 ; try { while ( ! disposed && autoQueueEnabled . value ) { const item = nextMatchedQueueItem ( ) ; if ( ! item ) break ; index += 1 ; try { const created = await withTransientRetry ( ( ) => createShopMatchTask ( [ buildTaskCreateItem ( item ) ] , orderedCountryCodes . value , scheduleValues ) , ( attempt , maxAttempts ) => { queuePushResult . value = ` 服务暂时不可用,正在重试创建任务( ${ attempt } / ${ maxAttempts } ) ...` } ) ; const taskId = created . taskId ; const initialStatus = scheduleValues ? . length ? 'SCHEDULED' : 'RUNNING' ; const snapshot : ShopMatchTaskDetailVo = { task : { id : taskId , status : initialStatus , scheduledAt : scheduleValues ? . [ 0 ] , countryCodes : [ ... orderedCountryCodes . value ] , currentStageIndex : scheduleValues ? . length ? 0 : undefined , activeStageIndex : undefined , scheduleStages : ( scheduleValues || [ ] ) . map ( ( value , stageIndex ) => ( { stageIndex , scheduledAt : value , status : stageIndex === 0 ? 'SCHEDULED' : 'PENDING' } ) ) } , items : created . items } ; taskSnapshots . value = { ... taskSnapshots . value , [ taskId ] : snapshot } ; triggerRef ( taskSnapshots ) ; taskDetails . value = { ... taskDetails . value , [ taskId ] : initialStatus } ; saveTaskSnapshotsToStorage ( ) ; saveTaskDetailsToStorage ( ) ; const createdItem = created . items ? . [ 0 ] ; if ( ! createdItem ) { removeMatchedRowsLocally ( [ item ] ) ; continue } if ( scheduleValues ? . length ) { successCount += 1 ; restoreScheduledDispatches ( ) ; queuePushResult . value = ` 任务 ${ taskId } 已创建,共 ${ scheduleValues . length } 个执行时间点 ` ; removeMatchedRowsLocally ( [ item ] ) ; continue } const payload = buildQueuePayload ( taskId , item , orderedCountryCodes . value ) ; queuePayloadText . value = JSON . stringify ( payload , null , 2 ) ; const result = await api . enqueue _json ( payload ) ; if ( ! result ? . success ) { failedCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 启动失败,已自动继续下一条: ${ result ? . error || '未知错误' } ` ; ElMessage . error ( queuePushResult . value ) ; removeMatchedRowsLocally ( [ item ] ) ; continue } addPollingTask ( taskId ) ; ensurePolling ( true ) ; removeMatchedRowsLocally ( [ item ] ) ; queuePushResult . value = ` 任务 ${ taskId } 已提交,等待执行完成 ` ; const finalStatus = await waitForTaskTerminal ( taskId ) ; if ( finalStatus !== 'SUCCESS' ) { failedCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 执行失败,已自动继续下一条 ` ; ElMessage . error ( queuePushResult . value ) ; continue } successCount += 1 ; queuePushResult . value = ` 任务 ${ taskId } 已完成 ` } catch ( error ) { if ( disposed ) break ; failedCount += 1 ; queuePushResult . value = ` 第 ${ index } 条任务处理失败,已自动继续下一条: ${ error instanceof Error ? error . message : '未知错误' } ` ; ElMessage . error ( queuePushResult . value ) ; removeMatchedRowsLocally ( [ item ] ) ; continue } } restoreScheduledDispatches ( ) ; if ( ! scheduleValues ? . length ) ensurePolling ( true ) ; if ( ! disposed && ( successCount > 0 || failedCount > 0 ) ) ElMessage . success ( scheduleValues ? . length ? ` 定时任务已创建:成功 ${ successCount } 条,失败 ${ failedCount } 条 ` : ` 店铺启动已完成:成功 ${ successCount } 条,失败 ${ failedCount } 条 ` ) } catch ( error ) { if ( disposed ) return ; const message = error instanceof Error ? error . message : '启动失败' ; queuePushResult . value = message ; ElMessage . error ( message ) } finally { queueWorkerRunning . value = false ; pushing . value = false } }
onMounted ( async ( ) => { loadPollingIdsFromStorage ( ) ; loadTaskDetailsFromStorage ( ) ; loadTaskSnapshotsFromStorage ( ) ; loadMatchedItemsFromStorage ( ) ; schedulePickerValues . value = sanitizeSchedulePickerValues ( schedulePickerValues . value , scheduleEnabled . value ) ; syncPollingIdsWithTaskState ( ) ; await Promise . allSettled ( [ loadCandidates ( ) , loadCountryPreference ( ) , loadHistory ( ) , loadDashboard ( ) ] ) ; window . addEventListener ( 'focus' , handleScheduleRecovery ) ; document . addEventListener ( 'visibilitychange' , handleScheduleRecovery ) ; restoreScheduledDispatches ( ) ; if ( pollingTaskIds . value . length ) ensurePolling ( true ) } )
onUnmounted ( ( ) => { disposed = true ; stopPolling ( ) ; stopScheduleHeartbeat ( ) ; clearSleepTimers ( ) ; window . removeEventListener ( 'focus' , handleScheduleRecovery ) ; document . removeEventListener ( 'visibilitychange' , handleScheduleRecovery ) ; if ( countryPrefSaveTimer ) timers . clearTimer ( 'preference-save' , countryPrefSaveTimer ) ; for ( const timer of dispatchTimers . values ( ) ) timers . clearTimer ( 'scheduled-dispatch' , timer ) ; dispatchTimers . clear ( ) ; timers . clearScope ( ) } )