简单的定时任务--ok

This commit is contained in:
yml2213
2026-05-14 17:59:45 +08:00
parent b6c493d5e7
commit f7f3289d04
19 changed files with 954 additions and 5 deletions
@@ -1,6 +1,8 @@
<script setup lang="ts">
import type { AdminNotificationTestResult } from '@/types/admin'
import type { EditableNotificationRecipient } from '@/composables/admin/platform-shops/types'
import { computed } from 'vue'
import type { AdminNotificationTestResult, AdminScheduledJobRuntimeState } from '@/types/admin'
import type { EditableNotificationRecipient, EditableScheduledJob } from '@/composables/admin/platform-shops/types'
import { formatAdminDateTime } from '@/utils/admin-time'
type Props = {
notificationFilePath: string
@@ -17,20 +19,103 @@ type Props = {
notificationTesting: boolean
notificationResultError: string
notificationTestResult: AdminNotificationTestResult | null
scheduledJobsFilePath: string
scheduledJobsForm: {
enabled: boolean
}
scheduledJobs: EditableScheduledJob[]
scheduledJobRuntime: AdminScheduledJobRuntimeState[]
scheduledJobsSaving: boolean
scheduledJobRunningId: string
notificationStats: {
configuredRecipientCount: number
enabledRecipientCount: number
barkReady: boolean
lastSuccessCount: number
lastFailedCount: number
scheduledJobEnabledCount: number
}
addNotificationRecipient: () => void
removeNotificationRecipient: (id: string) => void
handleNotificationSaveConfig: () => void | Promise<void>
handleNotificationTest: () => void | Promise<void>
handleScheduledJobsSaveConfig: () => void | Promise<void>
handleScheduledJobRunNow: (jobId: string) => void | Promise<void>
getScheduledJobRuntime: (jobId: string) => AdminScheduledJobRuntimeState | null
}
defineProps<Props>()
const timeUnitOptions = [
{ label: '秒', value: 1 },
{ label: '分钟', value: 60 },
{ label: '小时', value: 3600 },
]
function formatJobType(type: string) {
if (type === 'cloudtentacles_health') {
return 'cloudtentacles 健康检查'
}
return type || '-'
}
function resolveTimeValue(seconds: number) {
const normalized = Math.max(0, Number(seconds || 0))
if (normalized >= 3600 && normalized % 3600 === 0) {
return { amount: normalized / 3600, unit: 3600 }
}
if (normalized >= 60 && normalized % 60 === 0) {
return { amount: normalized / 60, unit: 60 }
}
return { amount: normalized || 1, unit: 1 }
}
function formatDuration(seconds: number) {
const value = resolveTimeValue(seconds)
const unit = timeUnitOptions.find((item) => item.value === value.unit)?.label || '秒'
return `${value.amount} ${unit}`
}
function bindDuration(job: EditableScheduledJob, key: 'intervalSeconds' | 'cooldownSeconds') {
const amountKey = `${key}Amount` as keyof EditableScheduledJob
const unitKey = `${key}Unit` as keyof EditableScheduledJob
if (!Number(job[amountKey])) {
const resolved = resolveTimeValue(Number(job[key] || 0))
;(job[amountKey] as number) = resolved.amount
;(job[unitKey] as number) = resolved.unit
}
return computed({
get: () => Number(job[amountKey] || 1),
set: (value: number) => {
;(job[amountKey] as number) = Math.max(1, Number(value || 1))
job[key] = Number(job[amountKey] || 1) * Number(job[unitKey] || 1)
},
})
}
function bindDurationUnit(job: EditableScheduledJob, key: 'intervalSeconds' | 'cooldownSeconds') {
const amountKey = `${key}Amount` as keyof EditableScheduledJob
const unitKey = `${key}Unit` as keyof EditableScheduledJob
if (!Number(job[unitKey])) {
const resolved = resolveTimeValue(Number(job[key] || 0))
;(job[amountKey] as number) = resolved.amount
;(job[unitKey] as number) = resolved.unit
}
return computed({
get: () => Number(job[unitKey] || 1),
set: (value: number) => {
;(job[unitKey] as number) = Math.max(1, Number(value || 1))
job[key] = Number(job[amountKey] || 1) * Number(job[unitKey] || 1)
},
})
}
</script>
<template>
@@ -43,6 +128,10 @@ defineProps<Props>()
<span class="meta-label">配置文件</span>
<span>{{ notificationFilePath || '-' }}</span>
</div>
<div class="meta-line">
<span class="meta-label">监控任务</span>
<span>{{ scheduledJobsFilePath || '-' }}</span>
</div>
</section>
<section class="table-card">
@@ -108,6 +197,99 @@ defineProps<Props>()
</table>
</section>
<section class="table-card">
<div class="section-title-row">
<div>
<h3>监控任务</h3>
<p>间隔表示多久检查一次冷却表示同一个异常在这段时间内最多通知一次</p>
</div>
<div class="section-actions">
<el-button :loading="scheduledJobsSaving" round type="primary" @click="handleScheduledJobsSaveConfig">保存任务</el-button>
</div>
</div>
<div class="form-grid">
<label class="checkbox-line">
<input v-model="scheduledJobsForm.enabled" class="checkbox-box" type="checkbox" />
<span>启用监控任务系统</span>
</label>
</div>
<table class="data-table">
<thead>
<tr>
<th>任务</th>
<th>参数</th>
<th>最近状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="job in scheduledJobs" :key="job.id">
<td>
<div class="cell-stack">
<strong>{{ formatJobType(job.type) }}</strong>
<label class="checkbox-line">
<input v-model="job.enabled" class="checkbox-box" type="checkbox" />
<span>{{ job.enabled ? '启用' : '停用' }}</span>
</label>
</div>
</td>
<td>
<div class="form-grid">
<label class="field-block">
<span>检查间隔</span>
<div class="time-input-row">
<input v-model.number="bindDuration(job, 'intervalSeconds').value" class="text-input" type="number" min="1" />
<select v-model.number="bindDurationUnit(job, 'intervalSeconds').value" class="text-input time-unit-select">
<option v-for="unit in timeUnitOptions" :key="unit.value" :value="unit.value">{{ unit.label }}</option>
</select>
</div>
<span class="cell-subtle"> {{ formatDuration(job.intervalSeconds) }} 检查一次</span>
</label>
<label class="field-block">
<span>通知冷却</span>
<div class="time-input-row">
<input v-model.number="bindDuration(job, 'cooldownSeconds').value" class="text-input" type="number" min="1" />
<select v-model.number="bindDurationUnit(job, 'cooldownSeconds').value" class="text-input time-unit-select">
<option v-for="unit in timeUnitOptions" :key="unit.value" :value="unit.value">{{ unit.label }}</option>
</select>
</div>
<span class="cell-subtle">同类异常 {{ formatDuration(job.cooldownSeconds) }} 内只通知一次</span>
</label>
<label class="field-block">
<span>余额阈值</span>
<input v-model.number="job.assetThreshold" class="text-input" type="number" min="0" />
<span class="cell-subtle">低于该值时通知</span>
</label>
</div>
</td>
<td>
<div class="cell-stack">
<strong>{{ getScheduledJobRuntime(job.id)?.lastStatus || 'pending' }}</strong>
<span class="cell-subtle">{{ getScheduledJobRuntime(job.id)?.lastMessage || '-' }}</span>
<span class="cell-subtle">余额{{ getScheduledJobRuntime(job.id)?.lastAsset ?? '-' }}</span>
<span class="cell-subtle">上次{{ formatAdminDateTime(getScheduledJobRuntime(job.id)?.lastRunAt || '') }}</span>
<span class="cell-subtle">下次{{ formatAdminDateTime(getScheduledJobRuntime(job.id)?.nextRunAt || '') }}</span>
</div>
</td>
<td>
<el-button
:loading="scheduledJobRunningId === job.id"
round
@click="handleScheduledJobRunNow(job.id)"
>
立即检查
</el-button>
</td>
</tr>
<tr v-if="scheduledJobs.length === 0">
<td colspan="4" class="empty-inline">暂无可配置的监控任务</td>
</tr>
</tbody>
</table>
</section>
<section class="table-card">
<div class="section-title-row">
<div>
@@ -30,3 +30,16 @@ export type EditableNotificationRecipient = {
deviceKey: string
enabled: boolean
}
export type EditableScheduledJob = {
id: string
type: string
enabled: boolean
intervalSeconds: number
intervalSecondsAmount: number
intervalSecondsUnit: number
cooldownSeconds: number
cooldownSecondsAmount: number
cooldownSecondsUnit: number
assetThreshold: number
}
@@ -2,15 +2,20 @@ import { computed, ref } from 'vue'
import { showError, showSuccess } from '@/lib/feedback'
import {
runAdminScheduledJob,
saveAdminNotificationConfig,
saveAdminScheduledJobsConfig,
testAdminNotification,
} from '@/services/admin'
import type {
AdminNotificationConfig,
AdminNotificationTestResult,
AdminScheduledJobRuntimeState,
AdminScheduledJobsConfig,
AdminScheduledJobsResponse,
} from '@/types/admin'
import type { EditableNotificationRecipient } from './types'
import type { EditableNotificationRecipient, EditableScheduledJob } from './types'
export function useAdminNotificationPlatform() {
const notificationFilePath = ref('')
@@ -27,6 +32,14 @@ export function useAdminNotificationPlatform() {
const notificationTesting = ref(false)
const notificationResultError = ref('')
const notificationTestResult = ref<AdminNotificationTestResult | null>(null)
const scheduledJobsFilePath = ref('')
const scheduledJobsForm = ref({
enabled: true,
})
const scheduledJobs = ref<EditableScheduledJob[]>([])
const scheduledJobRuntime = ref<AdminScheduledJobRuntimeState[]>([])
const scheduledJobsSaving = ref(false)
const scheduledJobRunningId = ref('')
const notificationStats = computed(() => {
const enabledRecipients = notificationRecipients.value.filter((item) => item.enabled && item.deviceKey.trim())
@@ -37,6 +50,7 @@ export function useAdminNotificationPlatform() {
barkReady: notificationForm.value.enabled && notificationForm.value.barkEnabled && enabledRecipients.length > 0,
lastSuccessCount: notificationTestResult.value?.successCount || 0,
lastFailedCount: notificationTestResult.value?.failedCount || 0,
scheduledJobEnabledCount: scheduledJobs.value.filter((item) => item.enabled).length,
}
})
@@ -56,6 +70,24 @@ export function useAdminNotificationPlatform() {
}))
}
function hydrateScheduledJobsConfig(data: AdminScheduledJobsResponse) {
scheduledJobsFilePath.value = data.filePath
scheduledJobsForm.value.enabled = data.source.enabled !== false
scheduledJobs.value = data.source.jobs.map((item) => ({
id: item.id,
type: item.type,
enabled: item.enabled === true,
intervalSeconds: Number(item.intervalSeconds || 300),
intervalSecondsAmount: resolveTimeValue(Number(item.intervalSeconds || 300)).amount,
intervalSecondsUnit: resolveTimeValue(Number(item.intervalSeconds || 300)).unit,
cooldownSeconds: Number(item.cooldownSeconds || 1800),
cooldownSecondsAmount: resolveTimeValue(Number(item.cooldownSeconds || 1800)).amount,
cooldownSecondsUnit: resolveTimeValue(Number(item.cooldownSeconds || 1800)).unit,
assetThreshold: Number(item.config?.assetThreshold || 500),
}))
scheduledJobRuntime.value = data.runtime || []
}
function addNotificationRecipient() {
notificationRecipients.value.unshift({
id: crypto.randomUUID(),
@@ -88,6 +120,22 @@ export function useAdminNotificationPlatform() {
}
}
function buildScheduledJobsConfigPayload(): AdminScheduledJobsConfig {
return {
enabled: scheduledJobsForm.value.enabled,
jobs: scheduledJobs.value.map((item) => ({
id: item.id,
type: item.type,
enabled: item.enabled,
intervalSeconds: Number(item.intervalSeconds || 300),
cooldownSeconds: Number(item.cooldownSeconds || 1800),
config: {
assetThreshold: Number(item.assetThreshold || 500),
},
})),
}
}
async function handleNotificationSaveConfig() {
notificationSaving.value = true
notificationResultError.value = ''
@@ -134,6 +182,58 @@ export function useAdminNotificationPlatform() {
}
}
async function handleScheduledJobsSaveConfig() {
scheduledJobsSaving.value = true
notificationResultError.value = ''
try {
const response = await saveAdminScheduledJobsConfig(buildScheduledJobsConfigPayload())
hydrateScheduledJobsConfig(response.data)
showSuccess('监控任务配置已保存')
} catch (error) {
notificationResultError.value = error instanceof Error ? error.message : '监控任务配置保存失败'
showError(notificationResultError.value)
} finally {
scheduledJobsSaving.value = false
}
}
async function handleScheduledJobRunNow(jobId: string) {
scheduledJobRunningId.value = jobId
notificationResultError.value = ''
try {
const saved = await saveAdminScheduledJobsConfig(buildScheduledJobsConfigPayload())
hydrateScheduledJobsConfig(saved.data)
const response = await runAdminScheduledJob(jobId)
scheduledJobRuntime.value = response.data.runtime || []
const message = String(response.data.result?.message || '监控任务已执行')
showSuccess(message)
} catch (error) {
notificationResultError.value = error instanceof Error ? error.message : '监控任务执行失败'
showError(notificationResultError.value)
} finally {
scheduledJobRunningId.value = ''
}
}
function getScheduledJobRuntime(jobId: string) {
return scheduledJobRuntime.value.find((item) => item.id === jobId) || null
}
function resolveTimeValue(seconds: number) {
const normalized = Math.max(0, Number(seconds || 0))
if (normalized >= 3600 && normalized % 3600 === 0) {
return { amount: normalized / 3600, unit: 3600 }
}
if (normalized >= 60 && normalized % 60 === 0) {
return { amount: normalized / 60, unit: 60 }
}
return { amount: normalized || 1, unit: 1 }
}
return {
notificationFilePath,
notificationForm,
@@ -142,11 +242,21 @@ export function useAdminNotificationPlatform() {
notificationTesting,
notificationResultError,
notificationTestResult,
scheduledJobsFilePath,
scheduledJobsForm,
scheduledJobs,
scheduledJobRuntime,
scheduledJobsSaving,
scheduledJobRunningId,
notificationStats,
hydrateNotificationConfig,
hydrateScheduledJobsConfig,
addNotificationRecipient,
removeNotificationRecipient,
handleNotificationSaveConfig,
handleNotificationTest,
handleScheduledJobsSaveConfig,
handleScheduledJobRunNow,
getScheduledJobRuntime,
}
}
@@ -15,6 +15,8 @@ import type {
AdminNinetyoneOrderListResult,
AdminNotificationConfig,
AdminNotificationTestResult,
AdminScheduledJobsConfig,
AdminScheduledJobsResponse,
AdminKuaishouCloudFulfillmentConfig,
AdminKuaishouEticketConsumeResult,
AdminKuaishouEticketDetailResult,
@@ -65,6 +67,24 @@ export function testAdminNotification(payload: {
return apiPost<AdminNotificationTestResult>('/api/v1/admin/platform-config/notifications/test', payload)
}
export function fetchAdminScheduledJobsConfig() {
return apiGet<AdminScheduledJobsResponse>('/api/v1/admin/platform-config/scheduled-jobs')
}
export function saveAdminScheduledJobsConfig(payload: AdminScheduledJobsConfig) {
return apiPost<AdminScheduledJobsResponse>(
'/api/v1/admin/platform-config/scheduled-jobs',
payload as unknown as Record<string, unknown>,
)
}
export function runAdminScheduledJob(jobId: string) {
return apiPost<{
result: Record<string, unknown>
runtime: AdminScheduledJobsResponse['runtime']
}>(`/api/v1/admin/platform-config/scheduled-jobs/${jobId}/run`, {})
}
export function fetchAdminNinetyoneOrders(params: {
page?: number
pageSize?: number
@@ -505,6 +505,17 @@
font-size: 13px;
}
.admin-platform-shops .time-input-row {
display: grid;
grid-template-columns: minmax(96px, 1fr) 96px;
gap: 8px;
align-items: center;
}
.admin-platform-shops .time-unit-select {
min-width: 96px;
}
.admin-platform-shops .empty-block,
.admin-platform-shops .empty-inline {
color: #64748b;
+36
View File
@@ -202,6 +202,42 @@ export interface AdminNotificationTestResult {
results: AdminNotificationSendResult[]
}
export interface AdminScheduledJobItem {
id: string
type: string
enabled: boolean
intervalSeconds: number
cooldownSeconds: number
config: {
assetThreshold: number
}
}
export interface AdminScheduledJobsConfig {
enabled: boolean
jobs: AdminScheduledJobItem[]
}
export interface AdminScheduledJobRuntimeState {
id: string
enabled: boolean
running: boolean
lastRunAt: string
lastFinishedAt: string
nextRunAt: string
lastStatus: string
lastMessage: string
lastAsset: number | null
lastThreshold: number | null
lastManual: boolean
}
export interface AdminScheduledJobsResponse {
filePath: string
source: AdminScheduledJobsConfig
runtime: AdminScheduledJobRuntimeState[]
}
export interface AdminNinetyoneOrderItem {
orderId: number
orderNo: string
@@ -17,6 +17,7 @@ import {
fetchAdminCloudtentaclesSourceConfig,
fetchAdminKuaishouEticketSourceConfig,
fetchAdminNotificationConfig,
fetchAdminScheduledJobsConfig,
} from '@/services/admin'
import { hasAdminRole } from '@/utils/admin-auth'
import '@/styles/admin-platform-shops.css'
@@ -66,12 +67,22 @@ const {
notificationTesting,
notificationResultError,
notificationTestResult,
scheduledJobsFilePath,
scheduledJobsForm,
scheduledJobs,
scheduledJobRuntime,
scheduledJobsSaving,
scheduledJobRunningId,
notificationStats,
hydrateNotificationConfig,
hydrateScheduledJobsConfig,
addNotificationRecipient,
removeNotificationRecipient,
handleNotificationSaveConfig,
handleNotificationTest,
handleScheduledJobsSaveConfig,
handleScheduledJobRunNow,
getScheduledJobRuntime,
} = useAdminNotificationPlatform()
const {
@@ -151,15 +162,23 @@ async function loadConfigs() {
errorMessage.value = ''
try {
const [agisoResponse, notificationResponse, kuaishouEticketResponse, cloudtentaclesResponse] = await Promise.all([
const [
agisoResponse,
notificationResponse,
scheduledJobsResponse,
kuaishouEticketResponse,
cloudtentaclesResponse,
] = await Promise.all([
fetchAdminAgisoShopConfigs(),
fetchAdminNotificationConfig(),
fetchAdminScheduledJobsConfig(),
fetchAdminKuaishouEticketSourceConfig(),
fetchAdminCloudtentaclesSourceConfig(),
])
hydrateAgisoConfig(agisoResponse.data)
hydrateNotificationConfig(notificationResponse.data)
hydrateScheduledJobsConfig(scheduledJobsResponse.data)
hydrateKuaishouEticketConfig(kuaishouEticketResponse.data)
hydrateCloudtentaclesConfig(cloudtentaclesResponse.data)
await loadNinetyoneOrders(1)
@@ -368,11 +387,20 @@ onMounted(loadConfigs)
:notification-testing="notificationTesting"
:notification-result-error="notificationResultError"
:notification-test-result="notificationTestResult"
:scheduled-jobs-file-path="scheduledJobsFilePath"
:scheduled-jobs-form="scheduledJobsForm"
:scheduled-jobs="scheduledJobs"
:scheduled-job-runtime="scheduledJobRuntime"
:scheduled-jobs-saving="scheduledJobsSaving"
:scheduled-job-running-id="scheduledJobRunningId"
:notification-stats="notificationStats"
:add-notification-recipient="addNotificationRecipient"
:remove-notification-recipient="removeNotificationRecipient"
:handle-notification-save-config="handleNotificationSaveConfig"
:handle-notification-test="handleNotificationTest"
:handle-scheduled-jobs-save-config="handleScheduledJobsSaveConfig"
:handle-scheduled-job-run-now="handleScheduledJobRunNow"
:get-scheduled-job-runtime="getScheduledJobRuntime"
/>
<AdminPlatformKuaishouEticketSection