sms_staff_assess.go 2.9 KB
package notify

import (
	"fmt"
	"time"

	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
)

// 短信通知

// 每日自评短信通知
// 条件:每日自评结束前30分钟,且还未完成评估填写
type NotifyStaffAssess struct {
	newSms   chan *domain.LogSms
	interval time.Duration
}

func (notices *NotifyStaffAssess) init() {
	notices.newSms = make(chan *domain.LogSms, 50)
	notices.interval = 10 * time.Minute
	if constant.Env != "prd" {
		notices.interval = 1 * time.Minute
	}
}

func (notices *NotifyStaffAssess) From() string {
	return "StaffAssess"
}

// AddTask 添加待执行的短信通知任务
func (notices *NotifyStaffAssess) AddTask(index int, phone string, param map[string]string, executeAt time.Time) {
	newSms := &domain.LogSms{
		Id:         0,
		Phone:      phone,
		TemplateId: 5475050,
		Template:   "您好,#name#,百忙之中不要忘记填写今天的绩效自评反馈哦",
		Value:      param,
		Result:     "",
		Status:     domain.SmsWait,
		From:       notices.From(),
		Index:      index,
		ExecuteAt:  executeAt,
		CreatedAt:  time.Now(),
	}
	notices.newSms <- newSms
}

// RunTask 执行短信通知任务
func (notices *NotifyStaffAssess) RunTask() {
	notices.init()
	timer := time.NewTimer(notices.interval)
	for {
		select {
		case newSms := <-notices.newSms:
			err := notices.addNewSms(newSms)
			if err != nil {
				e := fmt.Sprintf("添加短信通知任务:%+v %s", newSms, err)
				log.Logger.Error(e)
			}
		case <-timer.C:
			err := notices.sendSms()
			if err != nil {
				log.Logger.Error("发送短信通知任务:" + err.Error())
			}
			timer.Reset(notices.interval) // 重置定时
		}
	}
}

func (notices *NotifyStaffAssess) addNewSms(newSms *domain.LogSms) error {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	logSmsRepo := factory.CreateLogSmsRepository(map[string]interface{}{"transactionContext": transactionContext})
	err = logSmsRepo.Save(newSms)
	if err != nil {
		return err
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return err
	}
	return nil
}

func (notices *NotifyStaffAssess) sendSms() error {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	logSmsRepo := factory.CreateLogSmsRepository(map[string]interface{}{"transactionContext": transactionContext})
	_ = logSmsRepo
	if err := transactionContext.CommitTransaction(); err != nil {
		return err
	}
	return nil
}