feat: Adjust alarm settings (#9616)

This commit is contained in:
2025-07-23 16:58:24 +08:00 committed by GitHub
parent 033f08a6d2
commit cca1863b63
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 174 additions and 112 deletions

View file

@ -307,13 +307,13 @@ type AlertSendTimeRange struct {
}
type AlertCommonConfig struct {
AlertDailyNum uint `json:"alertDailyNum"`
IsOffline string `json:"isOffline"`
AlertSendTimeRange AlertSendTimeRange `json:"alertSendTimeRange"`
}
type AlertSmsConfig struct {
Phone string `json:"phone"`
Phone string `json:"phone"`
AlertDailyNum uint `json:"alertDailyNum"`
}
type AlertEmailConfig struct {

View file

@ -18,6 +18,7 @@ type AlertTask struct {
Type string `gorm:"type:varchar(64);not null" json:"type"`
Quota string `gorm:"type:varchar(64)" json:"quota"`
QuotaType string `gorm:"type:varchar(64)" json:"quotaType"`
Method string `gorm:"type:varchar(64);not null;default:'sms" json:"method"`
}
type AlertLog struct {

View file

@ -44,7 +44,7 @@ type IAlertRepo interface {
GetAlertTask(opts ...DBOption) (model.AlertTask, error)
LoadTaskCount(alertType string, project string) (uint, uint, error)
GetTaskLog(alertType string, alertId uint) (time.Time, error)
GetLicensePushCount() (uint, error)
GetLicensePushCount(method string) (uint, error)
GetConfig(opts ...DBOption) (model.AlertConfig, error)
AlertConfigList(opts ...DBOption) ([]model.AlertConfig, error)
@ -267,14 +267,14 @@ func getAlertDB(opts ...DBOption) (*gorm.DB, error) {
return db, nil
}
func (a *AlertRepo) GetLicensePushCount() (uint, error) {
func (a *AlertRepo) GetLicensePushCount(method string) (uint, error) {
var (
todayCount int64
)
now := time.Now()
todayMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
tomorrowMidnight := todayMidnight.Add(24 * time.Hour)
err := global.AlertDB.Model(&model.AlertTask{}).Where("created_at > ? AND created_at < ?", todayMidnight, tomorrowMidnight).Count(&todayCount).Error
err := global.AlertDB.Model(&model.AlertTask{}).Where("created_at > ? AND created_at < ? AND method = ?", todayMidnight, tomorrowMidnight, method).Count(&todayCount).Error
return uint(todayCount), err
}

View file

@ -87,9 +87,6 @@ func (m *AlertTaskHelper) InitTask(alertType string) {
func resourceTask(resourceAlert []dto.AlertDTO) {
for _, alert := range resourceAlert {
if !alertUtil.CheckTaskFrequency() {
return
}
if !alertUtil.CheckSendTimeRange(alert.Type) {
continue
}
@ -109,9 +106,6 @@ func resourceTask(resourceAlert []dto.AlertDTO) {
func baseTask(baseAlert []dto.AlertDTO) {
for _, alert := range baseAlert {
if !alertUtil.CheckTaskFrequency() {
return
}
if !alertUtil.CheckSendTimeRange(alert.Type) {
continue
}
@ -245,7 +239,11 @@ func loadSSLInfo(alert dto.AlertDTO) {
params = createAlertBaseParams(strconv.Itoa(len(primaryDomain)), strconv.Itoa(daysDifference))
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, primaryDomain, params, constant.SMS)
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON, constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, primaryDomain, params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -253,12 +251,11 @@ func loadSSLInfo(alert dto.AlertDTO) {
create.AlertDetail = alertDetail
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON, constant.Email)
default:
}
}
}
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON)
global.LOG.Info("SSL alert push successful")
}
}
@ -305,7 +302,11 @@ func loadWebsiteInfo(alert dto.AlertDTO) {
params = createAlertBaseParams(strconv.Itoa(len(websites)), strconv.Itoa(daysDifference))
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, primaryDomain, params, constant.SMS)
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON, constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, primaryDomain, params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -313,11 +314,11 @@ func loadWebsiteInfo(alert dto.AlertDTO) {
create.AlertRule = alertRule
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON, constant.Email)
default:
}
}
}
alertUtil.CreateNewAlertTask(alert.Project, alert.Type, projectJSON)
global.LOG.Info("website expiration alert push successful")
}
}
@ -358,7 +359,11 @@ func loadPanelPwd(alert dto.AlertDTO) {
m = strings.TrimSpace(m)
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, strconv.Itoa(daysDifference), params, constant.SMS)
alertUtil.CreateNewAlertTask(expirationTime.Value, alert.Type, expirationTime.Value, constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, strconv.Itoa(daysDifference), params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -366,10 +371,10 @@ func loadPanelPwd(alert dto.AlertDTO) {
create.AlertDetail = alertDetail
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(expirationTime.Value, alert.Type, expirationTime.Value, constant.Email)
default:
}
}
alertUtil.CreateNewAlertTask(expirationTime.Value, alert.Type, expirationTime.Value)
global.LOG.Info("panel password expiration alert push successful")
}
}
@ -411,7 +416,11 @@ func loadPanelUpdate(alert dto.AlertDTO) {
m = strings.TrimSpace(m)
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, version, params, constant.SMS)
alertUtil.CreateNewAlertTask(version, alert.Type, version, constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, version, params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -419,10 +428,10 @@ func loadPanelUpdate(alert dto.AlertDTO) {
create.AlertDetail = alertDetail
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(version, alert.Type, version, constant.Email)
default:
}
}
alertUtil.CreateNewAlertTask(version, alert.Type, version)
global.LOG.Info("panel update alert push successful")
}
@ -586,7 +595,11 @@ func createAndLogAlert(alert dto.AlertDTO, avgUsage float64, todayCount uint) {
m = strings.TrimSpace(m)
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, avgUsagePercent, params, constant.SMS)
alertUtil.CreateNewAlertTask(avgUsagePercent, alert.Type, strconv.Itoa(int(alert.Cycle)), constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, avgUsagePercent, params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -594,10 +607,10 @@ func createAndLogAlert(alert dto.AlertDTO, avgUsage float64, todayCount uint) {
create.AlertDetail = alertDetail
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(avgUsagePercent, alert.Type, strconv.Itoa(int(alert.Cycle)), constant.Email)
default:
}
}
alertUtil.CreateNewAlertTask(avgUsagePercent, alert.Type, strconv.Itoa(int(alert.Cycle)))
}
func getModule(alertType string) string {
@ -649,25 +662,20 @@ func processAllDisks(alert dto.AlertDTO, todayCount uint) error {
flag = true
}
}
if flag {
alertUtil.CreateNewAlertTask(strconv.Itoa(int(alert.Cycle)), alert.Type, alert.Project)
global.LOG.Info("all disk alert push successful")
}
return nil
}
func processSingleDisk(alert dto.AlertDTO, todayCount uint) error {
success, err := checkAndCreateDiskAlert(alert, alert.Project, todayCount)
if err != nil {
return err
}
if success {
alertUtil.CreateNewAlertTask(strconv.Itoa(int(alert.Cycle)), alert.Type, alert.Project)
global.LOG.Info("disk alert push successful")
}
return nil
}
@ -700,7 +708,11 @@ func checkAndCreateDiskAlert(alert dto.AlertDTO, path string, todayCount uint) (
m = strings.TrimSpace(m)
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateSMSAlertLog(alert, create, path, params, constant.SMS)
alertUtil.CreateNewAlertTask(strconv.Itoa(int(alert.Cycle)), alert.Type, alert.Project, constant.SMS)
case constant.Email:
alertDetail := alertUtil.ProcessAlertDetail(alert, path, params, constant.Email)
alertRule := alertUtil.ProcessAlertRule(alert)
@ -708,6 +720,7 @@ func checkAndCreateDiskAlert(alert dto.AlertDTO, path string, todayCount uint) (
create.AlertDetail = alertDetail
transport := xpack.LoadRequestTransport()
_ = alertUtil.CreateEmailAlertLog(create, alert, params, transport)
alertUtil.CreateNewAlertTask(strconv.Itoa(int(alert.Cycle)), alert.Type, alert.Project, constant.Email)
default:
}
}

View file

@ -32,6 +32,7 @@ func InitAgentDB() {
migrations.AddTableAlert,
migrations.InitAlertConfig,
migrations.AddMethodToAlertLog,
migrations.AddMethodToAlertTask,
})
if err := m.Migrate(); err != nil {
global.LOG.Error(err)

View file

@ -376,13 +376,13 @@ var InitAlertConfig = &gormigrate.Migration{
Type: "sms",
Title: "xpack.alert.smsConfig",
Status: "Enable",
Config: "{}",
Config: `{"alertDailyNum":50}`,
},
{
Type: "common",
Title: "xpack.alert.commonConfig",
Status: "Enable",
Config: `{"alertDailyNum":50,"isOffline":"Disable","alertSendTimeRange":{"noticeAlert":{"sendTimeRange":"08:00:00 - 23:59:59","type":["ssl","siteEndTime","panelPwdEndTime","panelUpdate"]},"resourceAlert":{"sendTimeRange":"00:00:00 - 23:59:59","type":["clams","cronJob","cpu","memory","load","disk"]}}}`,
Config: `{"isOffline":"Disable","alertSendTimeRange":{"noticeAlert":{"sendTimeRange":"08:00:00 - 23:59:59","type":["ssl","siteEndTime","panelPwdEndTime","panelUpdate"]},"resourceAlert":{"sendTimeRange":"00:00:00 - 23:59:59","type":["clams","cronJob","cpu","memory","load","disk"]}}}`,
},
}
for _, r := range records {
@ -406,3 +406,16 @@ var AddMethodToAlertLog = &gormigrate.Migration{
return nil
},
}
var AddMethodToAlertTask = &gormigrate.Migration{
ID: "20250723-add-method-to-alert_task",
Migrate: func(tx *gorm.DB) error {
if err := global.AlertDB.AutoMigrate(&model.AlertTask{}); err != nil {
return err
}
if err := global.AlertDB.Model(&model.AlertTask{}).Where("method IS NULL OR method = ''").Update("method", "sms").Error; err != nil {
return err
}
return nil
},
}

View file

@ -100,12 +100,13 @@ func SaveAlertLog(create dto.AlertLogCreate, alertLog *model.AlertLog) error {
return nil
}
func CreateNewAlertTask(quota, alertType, quotaType string) {
func CreateNewAlertTask(quota, alertType, quotaType, method string) {
alertRepo := repo.NewIAlertRepo()
taskBase := model.AlertTask{
Type: alertType,
Quota: quota,
QuotaType: quotaType,
Method: method,
}
err := alertRepo.CreateAlertTask(&taskBase)
if err != nil {
@ -190,20 +191,20 @@ func CreateAlertParams(param string) []dto.Param {
var checkTaskMutex sync.Mutex
func CheckTaskFrequency() bool {
func CheckTaskFrequency(method string) bool {
alertRepo := repo.NewIAlertRepo()
config, err := alertRepo.GetConfig(alertRepo.WithByType(constant.CommonConfig))
config, err := alertRepo.GetConfig(alertRepo.WithByType(constant.SMSConfig))
if err != nil {
return false
}
var cfg dto.AlertCommonConfig
var cfg dto.AlertSmsConfig
err = json.Unmarshal([]byte(config.Config), &cfg)
if err != nil {
return false
}
limitCount := cfg.AlertDailyNum
checkTaskMutex.Lock()
todayCount, err := repo.NewIAlertRepo().GetLicensePushCount()
todayCount, err := alertRepo.GetLicensePushCount(method)
defer checkTaskMutex.Unlock()
if err != nil {
global.LOG.Errorf("error getting license push count info, err: %v", err)

View file

@ -13,10 +13,6 @@ import (
)
func PushAlert(pushAlert dto.PushAlert) error {
if !alertUtil.CheckTaskFrequency() {
return nil
}
if !alertUtil.CheckSendTimeRange(alertUtil.GetCronJobType(pushAlert.AlertType)) {
return nil
}
@ -45,18 +41,21 @@ func PushAlert(pushAlert dto.PushAlert) error {
m = strings.TrimSpace(m)
switch m {
case constant.SMS:
if !alertUtil.CheckTaskFrequency(constant.SMS) {
continue
}
_ = xpack.CreateTaskScanSMSAlertLog(alert, create, pushAlert, constant.SMS)
alertUtil.CreateNewAlertTask(strconv.Itoa(int(pushAlert.EntryID)), alertUtil.GetCronJobType(alert.Type), strconv.Itoa(int(pushAlert.EntryID)), constant.SMS)
case constant.Email:
transport := xpack.LoadRequestTransport()
err := alertUtil.CreateTaskScanEmailAlertLog(alert, create, pushAlert, constant.Email, transport)
if err != nil {
return err
}
alertUtil.CreateNewAlertTask(strconv.Itoa(int(pushAlert.EntryID)), alertUtil.GetCronJobType(alert.Type), strconv.Itoa(int(pushAlert.EntryID)), constant.Email)
default:
}
}
// 处理告警任务
alertUtil.CreateNewAlertTask(strconv.Itoa(int(pushAlert.EntryID)), alertUtil.GetCronJobType(alert.Type), strconv.Itoa(int(pushAlert.EntryID)))
global.LOG.Infof("%s alert push successful", alert.Type)
return nil
}

View file

@ -253,4 +253,10 @@ export namespace Setting {
force: boolean;
withDockerRestart: boolean;
}
export interface SmsInfo {
licenseName: string;
smsUsed: number;
smsTotal: number;
}
}

View file

@ -49,7 +49,7 @@ export const listAllNodes = () => {
};
export const getLicenseSmsInfo = () => {
return http.get<Setting.LicenseStatus>(`/core/licenses/sms/info`);
return http.get<Setting.SmsInfo>(`/core/licenses/sms/info`);
};
// agent

View file

@ -818,7 +818,7 @@ const form = reactive<Cronjob.CronjobInfo>({
status: '',
secret: '',
hasAlert: false,
alertCount: 0,
alertCount: 3,
alertTitle: '',
alertMethod: '',
alertMethodItems: [],

View file

@ -19,10 +19,6 @@
>
<el-row>
<el-col>
<el-form-item :label="$t('xpack.alert.dailyAlertNum')" prop="dailyAlertNum">
{{ commonConfig.config.alertDailyNum }}
</el-form-item>
<el-form-item :label="$t('xpack.alert.sendTimeRange')" prop="sendTimeRange">
{{ sendTimeRange }}
</el-form-item>
@ -111,19 +107,40 @@
v-if="globalStore.isProductPro && !globalStore.isIntl"
>
<div class="flex items-center justify-between mb-2">
<div class="text-lg font-semibold">{{ $t('xpack.alert.smsConfig') }}</div>
<div class="text-lg font-semibold">
{{ $t('xpack.alert.smsConfig') }}
</div>
<div>
<el-button plain round @click="onChangePhone(smsConfig.id)">
{{ $t('commons.button.edit') }}
</el-button>
</div>
</div>
<div class="text-sm mb-2">{{ $t('xpack.alert.smsConfigHelper') }}</div>
<!-- <div class="text-sm mb-2">{{ $t('xpack.alert.smsConfigHelper') }}</div>-->
<div class="text-sm mb-2">
{{ $t('xpack.alert.alertSmsHelper', [totalSms, usedSms]) }}
<el-link class="ml-1 text-xs" @click="goBuy" type="primary" icon="Position">
<span class="ml-0.5">{{ $t('xpack.alert.goBuy') }}</span>
</el-link>
</div>
<el-divider class="!mb-2 !mt-3" />
<el-form-item :label="$t('xpack.alert.phone')">
<span v-if="smsConfig.config.phone">{{ smsConfig.config.phone }}</span>
<span v-else class="label">{{ $t('xpack.alert.defaultPhone') }}</span>
</el-form-item>
<div class="text-sm email-form">
<el-form
:model="form"
@submit.prevent
ref="alertFormRef"
:label-position="mobile ? 'top' : 'left'"
label-width="110px"
>
<el-form-item :label="$t('xpack.alert.phone')">
<span v-if="smsConfig.config.phone">{{ smsConfig.config.phone }}</span>
<span v-else class="label">{{ $t('xpack.alert.defaultPhone') }}</span>
</el-form-item>
<el-form-item :label="$t('xpack.alert.dailyAlertNum')" prop="dailyAlertNum">
{{ smsConfig.config.alertDailyNum }}
</el-form-item>
</el-form>
</div>
</el-card>
</div>
</template>
@ -147,6 +164,7 @@ import { storeToRefs } from 'pinia';
import { MsgSuccess } from '@/utils/message';
import EmailDrawer from '@/views/setting/alert/setting/email/index.vue';
import { Alert } from '@/api/interface/alert';
import { getLicenseSmsInfo } from '@/api/modules/setting';
const globalStore = GlobalStore();
const { isMaster } = storeToRefs(globalStore);
@ -201,7 +219,6 @@ export interface CommonConfig {
status: string;
config: {
isOffline?: string;
alertDailyNum?: number;
alertSendTimeRange?: string;
};
}
@ -209,9 +226,8 @@ const defaultCommonConfig: CommonConfig = {
id: undefined,
type: 'common',
title: 'xpack.alert.commonConfig',
status: 'Ena ble',
status: 'Enable',
config: {
alertDailyNum: 50,
alertSendTimeRange:
i18n.global.t('xpack.alert.noticeAlert') +
': ' +
@ -233,6 +249,7 @@ export interface SmsConfig {
status: string;
config: {
phone?: string;
alertDailyNum?: number;
};
}
const defaultSmsConfig: SmsConfig = {
@ -242,6 +259,7 @@ const defaultSmsConfig: SmsConfig = {
status: 'Enable',
config: {
phone: '',
alertDailyNum: 50,
},
};
const smsConfig = ref<SmsConfig>({ ...defaultSmsConfig });
@ -253,6 +271,9 @@ const config = ref<Alert.AlertConfigInfo>({
status: '',
config: '',
});
const licenseName = ref('-');
const totalSms = ref(0);
const usedSms = ref(0);
const mobile = computed(() => {
return globalStore.isMobile();
});
@ -314,13 +335,16 @@ const search = async () => {
};
const onChangePhone = (id: any) => {
phoneRef.value.acceptParams({ id: id, phone: smsConfig.value.config.phone });
phoneRef.value.acceptParams({
id: id,
phone: smsConfig.value.config.phone,
dailyAlertNum: smsConfig.value.config.alertDailyNum,
});
};
const onChangeCommon = (id: any) => {
sendTimeRangeRef.value.acceptParams({
id: id,
dailyAlertNum: commonConfig.value.config.alertDailyNum,
sendTimeRange: sendTimeRangeValue.value,
isOffline: commonConfig.value.config.isOffline,
});
@ -378,8 +402,24 @@ const onDelete = (id: number) => {
await search();
});
};
const getSmsInfo = async () => {
const res = await getLicenseSmsInfo();
licenseName.value = res.data.licenseName;
usedSms.value = res.data.smsUsed;
totalSms.value = res.data.smsTotal;
};
const goBuy = async () => {
const uri = licenseName.value === '-' ? '' : `${licenseName.value}/buy-sms`;
window.open('https://www.lxware.cn/uc/cloud/licenses/' + uri, '_blank', 'noopener,noreferrer');
};
onMounted(async () => {
await search();
if (globalStore.isProductPro && !globalStore.isIntl) {
await getSmsInfo();
}
});
</script>
<style scoped lang="scss">

View file

@ -7,6 +7,14 @@
<el-input clearable v-model="form.phone" />
<span class="input-help">{{ $t('xpack.alert.phoneHelper') }}</span>
</el-form-item>
<el-form-item
:label="$t('xpack.alert.dailyAlertNum')"
:rules="[Rules.integerNumber, checkNumberRange(20, 100)]"
prop="dailyAlertNum"
>
<el-input clearable v-model.number="form.dailyAlertNum" min="20" max="100" />
<span class="input-help">{{ $t('xpack.alert.dailyAlertNumHelper') }}</span>
</el-form-item>
</el-col>
</el-row>
</el-form>
@ -25,12 +33,13 @@ import { reactive, ref } from 'vue';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
import { FormInstance } from 'element-plus';
import { Rules } from '@/global/form-rules';
import { checkNumberRange, Rules } from '@/global/form-rules';
import { UpdateAlertConfig } from '@/api/modules/alert';
const emit = defineEmits<{ (e: 'search'): void }>();
interface DialogProps {
phone: string;
dailyAlertNum: number;
id: number;
}
const drawerVisible = ref();
@ -38,6 +47,7 @@ const loading = ref();
const form = reactive({
phone: '',
dailyAlertNum: 50,
id: undefined,
});
@ -46,6 +56,7 @@ const formRef = ref<FormInstance>();
const acceptParams = (params: DialogProps): void => {
form.phone = params.phone;
form.id = params.id;
form.dailyAlertNum = Number(params.dailyAlertNum);
drawerVisible.value = true;
};
@ -55,7 +66,7 @@ const onSave = async (formEl: FormInstance | undefined) => {
if (!valid) return;
loading.value = true;
try {
const configInfo = { phone: form.phone };
const configInfo = { phone: form.phone, alertDailyNum: form.dailyAlertNum };
await UpdateAlertConfig({
id: form.id,
type: 'sms',

View file

@ -1,14 +1,6 @@
<template>
<DrawerPro v-model="drawerVisible" :header="$t('xpack.alert.sendTimeRange')" @close="handleClose" size="736">
<el-form ref="formRef" label-position="top" :model="form" @submit.prevent v-loading="loading">
<el-form-item
:label="$t('xpack.alert.dailyAlertNum')"
:rules="[Rules.integerNumber, checkNumberRange(20, 100)]"
prop="dailyAlertNum"
>
<el-input clearable v-model.number="form.dailyAlertNum" min="20" max="100" />
<span class="input-help">{{ $t('xpack.alert.dailyAlertNumHelper') }}</span>
</el-form-item>
<el-form ref="formRef" label-position="top" @submit.prevent v-loading="loading">
<el-form-item :label="$t('xpack.alert.sendTimeRange')" prop="sendTimeRange">
<div class="text-center">
<el-transfer
@ -64,7 +56,7 @@
<template #footer>
<span class="dialog-footer">
<el-button @click="drawerVisible = false">{{ $t('commons.button.cancel') }}</el-button>
<el-button :disabled="loading" type="primary" @click="onSave(formRef)">
<el-button :disabled="loading" type="primary" @click="onSave()">
{{ $t('commons.button.confirm') }}
</el-button>
</span>
@ -72,12 +64,11 @@
</DrawerPro>
</template>
<script lang="ts" setup>
import { computed, ComputedRef, reactive, ref } from 'vue';
import { computed, ComputedRef, ref } from 'vue';
import i18n from '@/lang';
import { MsgError, MsgSuccess } from '@/utils/message';
import { FormInstance } from 'element-plus';
import { UpdateAlertConfig } from '@/api/modules/alert';
import { checkNumberRange, Rules } from '@/global/form-rules';
import { Alert } from '@/api/interface/alert';
const emit = defineEmits<{ (e: 'search'): void }>();
@ -105,26 +96,20 @@ interface SendTimeRange {
interface DialogProps {
id: any;
dailyAlertNum: number;
sendTimeRange: SendTimeRange;
isOffline: string;
}
interface ConfigInfo {
alertDailyNum: number;
alertSendTimeRange: SendTimeRange;
isOffline: string;
}
const drawerVisible = ref(false);
const loading = ref(false);
const form = reactive({
dailyAlertNum: 50,
});
const isOffline = ref();
const id = ref();
const configInfo = ref<ConfigInfo>({
alertDailyNum: 0,
isOffline: '',
alertSendTimeRange: {
noticeAlert: { sendTimeRange: '', type: [] },
@ -170,53 +155,45 @@ const acceptParams = (params: DialogProps): void => {
resourceTimeRange.value = parseTimeRange(params.sendTimeRange.resourceAlert.sendTimeRange);
resourceValue.value = params.sendTimeRange.resourceAlert.type;
}
form.dailyAlertNum = Number(params.dailyAlertNum);
isOffline.value = params.isOffline;
id.value = params.id;
drawerVisible.value = true;
};
const onSave = async (formEl: FormInstance | undefined) => {
if (!formEl) return;
formEl.validate(async (valid) => {
if (!valid) return;
if (
typeof noticeTimeRange.value === 'object' &&
noticeTimeRange.value !== null &&
typeof resourceTimeRange.value === 'object' &&
resourceTimeRange.value !== null
) {
loading.value = true;
configInfo.value.alertSendTimeRange = {
noticeAlert: { sendTimeRange: stringifyTimeRange(noticeTimeRange.value), type: noticeValue.value },
resourceAlert: {
sendTimeRange: stringifyTimeRange(resourceTimeRange.value),
type: resourceValue.value,
},
};
configInfo.value.isOffline = isOffline.value;
configInfo.value.alertDailyNum = form.dailyAlertNum;
try {
config.value.id = id.value;
config.value.type = 'common';
config.value.title = 'xpack.alert.commonConfig';
config.value.status = 'Enable';
config.value.config = JSON.stringify(configInfo.value);
await UpdateAlertConfig(config.value);
const onSave = async () => {
if (
typeof noticeTimeRange.value === 'object' &&
noticeTimeRange.value !== null &&
typeof resourceTimeRange.value === 'object' &&
resourceTimeRange.value !== null
) {
loading.value = true;
configInfo.value.alertSendTimeRange = {
noticeAlert: { sendTimeRange: stringifyTimeRange(noticeTimeRange.value), type: noticeValue.value },
resourceAlert: {
sendTimeRange: stringifyTimeRange(resourceTimeRange.value),
type: resourceValue.value,
},
};
configInfo.value.isOffline = isOffline.value;
try {
config.value.id = id.value;
config.value.type = 'common';
config.value.title = 'xpack.alert.commonConfig';
config.value.status = 'Enable';
config.value.config = JSON.stringify(configInfo.value);
await UpdateAlertConfig(config.value);
loading.value = false;
handleClose();
emit('search');
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
} catch (error) {
loading.value = false;
}
} else {
MsgError(
i18n.global.t('commons.msg.confirmNoNull', [i18n.global.t('xpack.alert.timeRange').toLowerCase()]),
);
loading.value = false;
handleClose();
emit('search');
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
} catch (error) {
loading.value = false;
}
});
} else {
MsgError(i18n.global.t('commons.msg.confirmNoNull', [i18n.global.t('xpack.alert.timeRange').toLowerCase()]));
}
};
const parseTimeRange = (timeRangeStr: string): [Date, Date] => {