feat(order): 一键拉单进度在订单页卡片头部持续显示

- 新增 useOrderSyncTask 组合式函数:拉单任务轮询从弹窗抽为模块级单例,弹窗关闭后仍继续轮询

- 订单页卡片头部在任务进行中显示进度条与店铺进度,结束后自动隐藏并刷新列表;刷新页面可恢复进度

- OrderSyncDialog 复用共享状态,去掉自持 timer 与 done 事件;StatusPanel 改为订阅任务结束通知

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-06 22:22:18 +08:00
parent adfc48d8bf
commit 262d9d4203
4 changed files with 258 additions and 105 deletions

View File

@ -0,0 +1,168 @@
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
getOrderSyncTask,
getRunningOrderSyncTask,
submitOrderSyncTask,
type OrderSyncSubmitPayload,
type OrderSyncTaskItem,
} from '@/api/orderSyncTask'
/**
* 一键拉单任务状态(模块级单例)
*
* 弹窗与订单页卡片头部共用同一份进度:弹窗关掉(后台执行)后头部继续显示进度条,
* 任务结束时通知订阅方刷新列表,避免出现「关掉弹窗就看不到拉单结果」。
*/
/** 轮询间隔(毫秒):拉单按店铺串行,进度变化不快 */
const POLL_INTERVAL = 3000
const task = ref<OrderSyncTaskItem | null>(null)
/** 本轮任务是否已结束(已完成 / 部分失败 / 失败) */
const finished = ref(false)
let timer: number | null = null
/** 已提示/通知过的任务ID,避免重复弹提示、重复刷新 */
let notifiedTaskId = 0
const finishListeners = new Set<() => void>()
/** 是否有任务在排队 / 执行中 */
const isRunning = computed(() => {
const status = task.value?.status
return status === 0 || status === 1
})
/** 进度百分比(后端可能返回越界值,兜底到 0~100) */
const progress = computed(() => Math.min(100, Math.max(0, Number(task.value?.progress) || 0)))
/** 进度描述:已处理店铺 / 总店铺 */
const progressText = computed(() => {
if (!task.value) return ''
const done = task.value.processed_shops || 0
const total = task.value.total_shops || 0
return `${done} / ${total} 个店铺`
})
function stopPolling() {
if (timer != null) {
window.clearInterval(timer)
timer = null
}
}
function notifyFinished() {
for (const listener of Array.from(finishListeners)) {
try {
listener()
} catch {
// 单个订阅方异常不影响其它订阅方
}
}
}
function startPolling() {
stopPolling()
timer = window.setInterval(() => {
pollOnce().catch(() => {})
}, POLL_INTERVAL)
}
/** 拉一次进度;到终态时停轮询并通知订阅方 */
async function pollOnce() {
if (!task.value) return
const data = await getOrderSyncTask(task.value.id).catch(() => null)
if (!data) return
task.value = data
if (data.status === 2 || data.status === 3 || data.status === 4) {
stopPolling()
finished.value = true
if (notifiedTaskId === data.id) return
notifiedTaskId = data.id
notifyFinished()
if (data.status === 2) {
ElMessage.success(`拉单完成:新增 ${data.created_orders} 单,更新 ${data.updated_orders} 单`)
} else if (data.status === 3) {
ElMessage.warning(`拉单结束,${data.failed_shops} 个店铺失败,请查看结果`)
} else {
ElMessage.error(`拉单失败:${data.error_message || '未知原因'}`)
}
}
}
/**
* 提交拉单任务并开始轮询
* @param payload 提交参数(范围 / 回看天数 / 指定店铺)
* @return 提交结果(含任务ID与店铺数)
*/
async function submit(payload: OrderSyncSubmitPayload) {
const res = await submitOrderSyncTask(payload)
finished.value = false
task.value = {
id: res.id,
principal_id: 0,
scope: res.scope,
status: res.status,
start_time: res.start_time,
end_time: res.end_time,
lookback_days: payload.lookback_days ?? null,
total_shops: res.total_shops,
processed_shops: 0,
failed_shops: 0,
created_orders: 0,
updated_orders: 0,
skipped_orders: 0,
voided_orders: 0,
progress: 0,
items: [],
error_message: null,
created_at: new Date().toISOString(),
started_at: null,
finished_at: null,
}
startPolling()
return res
}
/**
* 恢复未完成任务(进入页面 / 打开弹窗时调用)
* 服务端已没有排队任务、但本地仍认为是执行中时,补拉一次拿到终态并通知刷新
* @return 未完成任务;没有则为 null
*/
async function refreshRunning() {
const running = await getRunningOrderSyncTask().catch(() => null)
if (running) {
task.value = running
finished.value = false
startPolling()
} else if (task.value && isRunning.value) {
await pollOnce()
}
return running
}
/**
* 订阅任务结束(用于刷新订单列表)
* @param listener 结束回调
* @return 取消订阅函数
*/
function onFinished(listener: () => void) {
finishListeners.add(listener)
return () => {
finishListeners.delete(listener)
}
}
export function useOrderSyncTask() {
return {
task,
finished,
isRunning,
progress,
progressText,
submit,
refreshRunning,
stopPolling,
onFinished,
}
}

View File

@ -1,21 +1,16 @@
<script setup lang="ts">
import { computed, onUnmounted, reactive, ref, watch } from 'vue'
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import { getShops, type ShopItem } from '@/api/shop'
import {
getOrderSyncTask,
getRunningOrderSyncTask,
submitOrderSyncTask,
type OrderSyncShopItem,
type OrderSyncTaskItem,
} from '@/api/orderSyncTask'
import type { OrderSyncShopItem } from '@/api/orderSyncTask'
import { useOrderSyncTask } from '@/composables/useOrderSyncTask'
/**
* 一键拉单对话框
*
* 提交后后端落一条任务并由定时任务逐店拉取,本组件轮询进度;
* 结束(已完成/部分失败/失败)后向父组件抛出 done,由列表自行刷新。
* 提交后后端落一条任务并由定时任务逐店拉取,进度由 useOrderSyncTask 统一轮询
* (与订单页卡片头部共用),关闭弹窗后头部仍显示进度,任务结束时通知列表刷新。
*/
const props = defineProps<{
/** 是否显示 */
@ -24,8 +19,6 @@ const props = defineProps<{
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void
/** 拉单任务结束(无论成功失败) */
(e: 'done'): void
}>()
const visible = computed({
@ -33,8 +26,8 @@ const visible = computed({
set: (value: boolean) => emit('update:modelValue', value),
})
/** 轮询间隔(毫秒):拉单按店铺串行,进度变化不快 */
const POLL_INTERVAL = 3000
/** 拉单任务状态(模块级共享,关闭弹窗后仍继续轮询) */
const { task, finished, isRunning, progressText, submit, refreshRunning } = useOrderSyncTask()
const form = reactive({
scope: 'all',
@ -62,11 +55,6 @@ const shopOptions = ref<{ label: string; value: number }[]>([])
const shopsLoading = ref(false)
const submitting = ref(false)
/** 当前任务(提交后填充,用于展示进度) */
const task = ref<OrderSyncTaskItem | null>(null)
const finished = ref(false)
let timer: number | null = null
const statusType = computed(() => {
const status = task.value?.status
if (status === 2) return 'success'
@ -76,21 +64,8 @@ const statusType = computed(() => {
return 'info'
})
const isRunning = computed(() => {
const status = task.value?.status
return status === 0 || status === 1
})
const items = computed<OrderSyncShopItem[]>(() => task.value?.items || [])
/** 进度描述 */
const progressText = computed(() => {
if (!task.value) return ''
const done = task.value.processed_shops || 0
const total = task.value.total_shops || 0
return `${done} / ${total} 个店铺`
})
async function loadShops() {
if (shopOptions.value.length) return
shopsLoading.value = true
@ -110,73 +85,15 @@ async function loadShops() {
}
}
function stopPolling() {
if (timer != null) {
window.clearInterval(timer)
timer = null
}
}
async function pollOnce() {
if (!task.value) return
try {
const data = await getOrderSyncTask(task.value.id)
task.value = data
if (data.status === 2 || data.status === 3 || data.status === 4) {
stopPolling()
finished.value = true
emit('done')
if (data.status === 2) {
ElMessage.success(`拉单完成:新增 ${data.created_orders} 单,更新 ${data.updated_orders} 单`)
} else if (data.status === 3) {
ElMessage.warning(`拉单结束,${data.failed_shops} 个店铺失败,请查看结果`)
} else {
ElMessage.error(`拉单失败:${data.error_message || '未知原因'}`)
}
}
} catch {
// 单次查询失败不打断轮询
}
}
function startPolling() {
stopPolling()
timer = window.setInterval(() => { pollOnce().catch(() => {}) }, POLL_INTERVAL)
}
async function onSubmit() {
submitting.value = true
try {
const res = await submitOrderSyncTask({
const res = await submit({
scope: form.scope,
lookback_days: form.lookback_days,
shop_ids: form.shop_ids.length ? form.shop_ids : undefined,
})
finished.value = false
task.value = {
id: res.id,
principal_id: 0,
scope: res.scope,
status: res.status,
start_time: res.start_time,
end_time: res.end_time,
lookback_days: form.lookback_days,
total_shops: res.total_shops,
processed_shops: 0,
failed_shops: 0,
created_orders: 0,
updated_orders: 0,
skipped_orders: 0,
voided_orders: 0,
progress: 0,
items: [],
error_message: null,
created_at: new Date().toISOString(),
started_at: null,
finished_at: null,
}
ElMessage.success(`已提交拉单任务(${res.total_shops} 个店铺),正在后台执行`)
startPolling()
} finally {
submitting.value = false
}
@ -185,12 +102,7 @@ async function onSubmit() {
/** 打开时:先看有没有未完成任务(刷新页面/重新打开可恢复进度) */
async function restoreRunning() {
try {
const running = await getRunningOrderSyncTask()
if (running) {
task.value = running
finished.value = false
startPolling()
}
await refreshRunning()
} catch {
// 忽略:无未完成任务
}
@ -200,13 +112,9 @@ watch(visible, value => {
if (value) {
loadShops()
restoreRunning()
} else {
stopPolling()
}
})
onUnmounted(stopPolling)
/** 逐店结果行样式:失败标红 */
function rowClassName({ row }: { row: OrderSyncShopItem }) {
return row.success ? '' : 'sync-row-failed'

View File

@ -1,7 +1,8 @@
<script setup lang="ts">
import { ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import OrderStatusPanel from './StatusPanel.vue'
import { ORDER_STAGE_TABS, type OrderStage } from '@/api/orderStatus'
import { useOrderSyncTask } from '@/composables/useOrderSyncTask'
/**
* 订单
@ -9,14 +10,46 @@ import { ORDER_STAGE_TABS, type OrderStage } from '@/api/orderStatus'
* 订单按状态分表存储,页面按状态分视图管理:
* 左侧 tab 切换 5 个视图(待审核 / 异常 / 委外中 / 配送 / 历史),
* 历史为归档表且只读;tab 懒加载,首次切到才请求列表。
* 一键拉单进行中时卡片头部持续显示进度(弹窗关闭后台执行也不会丢进度)。
*/
const active = ref<OrderStage>('pending')
const { task, isRunning, progress, progressText, refreshRunning, stopPolling } = useOrderSyncTask()
/** 头部进度的悬浮提示:任务号 + 店铺进度 + 失败店铺数 */
const syncHint = computed(() => {
const current = task.value
if (!current) return ''
const failed = current.failed_shops ? `,失败 ${current.failed_shops} 个` : ''
return `拉单任务 #${current.id}:${progressText.value}${failed}`
})
onMounted(() => {
refreshRunning().catch(() => {})
})
onBeforeUnmount(stopPolling)
</script>
<template>
<el-card class="order-card">
<template #header>
<div class="page-header">订单</div>
<div class="page-header">
<span>订单</span>
<!-- 拉单任务进行中:弹窗关闭(后台执行)后仍能看到进度 -->
<div v-if="isRunning" class="header-sync">
<el-tooltip :content="syncHint" placement="bottom">
<span class="header-sync-text">一键拉单中 {{ progressText }}</span>
</el-tooltip>
<el-progress
:percentage="progress"
:stroke-width="8"
:show-text="false"
class="header-sync-bar"
/>
<span class="header-sync-percent">{{ progress }}%</span>
</div>
</div>
</template>
<el-tabs v-model="active" tab-position="left" class="order-tabs">
@ -35,8 +68,42 @@ const active = ref<OrderStage>('pending')
<style scoped>
.page-header {
display: flex;
align-items: center;
gap: 16px;
font-weight: 600;
}
/* 标题不参与压缩(中文可在任意字符间折行,窗口窄时会被挤成一列) */
.page-header > span {
flex: none;
white-space: nowrap;
}
.header-sync {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 8px;
min-width: 0;
font-size: 12px;
font-weight: 400;
color: var(--el-text-color-secondary);
}
.header-sync-text {
flex: 0 1 auto;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
cursor: default;
}
.header-sync-bar {
flex: 1 1 60px;
max-width: 160px;
}
.header-sync-percent {
flex: none;
min-width: 34px;
font-variant-numeric: tabular-nums;
}
.order-card {
height: 100%;
display: flex;

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import ExportButton from '@/components/ExportButton.vue'
@ -15,6 +15,7 @@ import {
type ExternalSendCounts,
} from '@/api/externalSendSync'
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
import { useOrderSyncTask } from '@/composables/useOrderSyncTask'
import { formatDateTime } from '@/utils/datetime'
import { platformNameOf } from '@/constants/platform'
import {
@ -532,6 +533,9 @@ const formOrderId = ref<number | null>(null)
/* -------------------- 一键拉取订单(异步任务) -------------------- */
const syncDialogVisible = ref(false)
/** 拉单任务结束的订阅(弹窗关闭后台执行时也能刷新列表) */
const { onFinished } = useOrderSyncTask()
let offSyncFinished: (() => void) | null = null
/** 拉单任务结束:刷新列表并清空勾选(订单集合已变化) */
async function refreshAfterSync() {
@ -709,10 +713,16 @@ function expressCodesOf(row: OrderStatusItem): string[] {
}
onMounted(async () => {
offSyncFinished = onFinished(refreshAfterSync)
await fetchFilters()
await fetchList()
await fetchExternalSendCounts()
})
onBeforeUnmount(() => {
if (offSyncFinished) offSyncFinished()
offSyncFinished = null
})
</script>
<template>
@ -1075,7 +1085,7 @@ onMounted(async () => {
/>
<!-- 一键拉取订单(异步任务 + 进度):完成后刷新列表 -->
<OrderSyncDialog v-model="syncDialogVisible" @done="refreshAfterSync" />
<OrderSyncDialog v-model="syncDialogVisible" />
<!-- 切换仓库:列表选择(店铺在创建订单时确定,不再提供设置店铺) -->
<RecordPickerDialog