99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package tribally_report
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"github.com/robfig/cron/v3"
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"nova_task/internal/consts"
|
|
"nova_task/internal/model"
|
|
"nova_task/internal/pkg/tribally"
|
|
"nova_task/internal/svc"
|
|
"time"
|
|
)
|
|
|
|
type Cron struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewCron(ctx context.Context, svcCtx *svc.ServiceContext) cron.Job {
|
|
return &Cron{ctx: ctx, svcCtx: svcCtx}
|
|
}
|
|
|
|
func (c *Cron) Spec() string {
|
|
return "@every 30s"
|
|
}
|
|
|
|
func (c *Cron) Run() {
|
|
apiKey, err := c.svcCtx.ConfigModel.GetTriballyApiKey(c.ctx)
|
|
if err != nil {
|
|
logx.Errorw("get tribally api key failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
if apiKey == "" {
|
|
logx.Errorw("tribally api key empty")
|
|
return
|
|
}
|
|
tr, err := c.svcCtx.GlobalDataModel.FindOneByKey(c.ctx, consts.TriballyReportTime)
|
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
|
logx.Errorw("get tribally report time failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
if tr == nil {
|
|
tr = &model.NhGlobalData{
|
|
Key: consts.TriballyReportTime,
|
|
}
|
|
}
|
|
var start time.Time
|
|
if tr.Value != "" {
|
|
start, err = time.Parse(time.DateTime, tr.Value)
|
|
if err != nil {
|
|
logx.Errorw("parse tribally report time failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
}
|
|
end := time.Now()
|
|
triballyUsers, err := c.svcCtx.TriballyUserModel.FindUpdateTriballyUsers(c.ctx, start, end, 100)
|
|
if err != nil {
|
|
logx.Errorw("find update tribally users failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
|
|
tr.Value = end.Format(time.DateTime)
|
|
if tr.Id > 0 {
|
|
err = c.svcCtx.GlobalDataModel.Update(c.ctx, tr)
|
|
} else {
|
|
_, err = c.svcCtx.GlobalDataModel.Insert(c.ctx, tr)
|
|
}
|
|
if err != nil {
|
|
logx.Errorw("insert or update tribally report time failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
|
|
if len(triballyUsers) == 0 {
|
|
logx.Infow("no tribally users", logx.Field("start", start), logx.Field("end", end))
|
|
return
|
|
}
|
|
var chapters []tribally.UserChapter
|
|
for _, u := range triballyUsers {
|
|
chapters = append(chapters, tribally.UserChapter{
|
|
Email: u.Email,
|
|
Chapter: u.MaxChapter,
|
|
})
|
|
}
|
|
err = tribally.PostUserChapter(apiKey, chapters...)
|
|
if err != nil {
|
|
logx.Errorw("post user chapter failed", logx.Field("err", err))
|
|
return
|
|
}
|
|
|
|
for _, u := range triballyUsers {
|
|
err = c.svcCtx.TriballyUserModel.UpdateUserChapter(c.ctx, u.Uid, u.MaxChapter)
|
|
if err != nil {
|
|
logx.Errorw("update user chapter failed", logx.Field("err", err))
|
|
}
|
|
}
|
|
|
|
}
|