95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"quyun/v2/app/errorx"
|
|
user_dto "quyun/v2/app/http/v1/dto"
|
|
"quyun/v2/app/jobs/args"
|
|
"quyun/v2/app/requests"
|
|
"quyun/v2/database/models"
|
|
"quyun/v2/pkg/consts"
|
|
"quyun/v2/providers/job"
|
|
|
|
"github.com/spf13/cast"
|
|
)
|
|
|
|
// @provider
|
|
type notification struct {
|
|
job *job.Job
|
|
}
|
|
|
|
func (s *notification) List(ctx context.Context, page int, typeArg string) (*requests.Pager, error) {
|
|
userID := ctx.Value(consts.CtxKeyUser)
|
|
if userID == nil {
|
|
return nil, errorx.ErrUnauthorized
|
|
}
|
|
uid := cast.ToInt64(userID)
|
|
|
|
tbl, q := models.NotificationQuery.QueryContext(ctx)
|
|
q = q.Where(tbl.UserID.Eq(uid))
|
|
|
|
if typeArg != "" && typeArg != "all" {
|
|
q = q.Where(tbl.Type.Eq(typeArg))
|
|
}
|
|
|
|
q = q.Order(tbl.CreatedAt.Desc())
|
|
|
|
p := requests.Pagination{Page: int64(page), Limit: 20}
|
|
total, err := q.Count()
|
|
if err != nil {
|
|
return nil, errorx.ErrDatabaseError.WithCause(err)
|
|
}
|
|
|
|
list, err := q.Offset(int(p.Offset())).Limit(int(p.Limit)).Find()
|
|
if err != nil {
|
|
return nil, errorx.ErrDatabaseError.WithCause(err)
|
|
}
|
|
|
|
data := make([]user_dto.Notification, len(list))
|
|
for i, v := range list {
|
|
data[i] = user_dto.Notification{
|
|
ID: cast.ToString(v.ID),
|
|
Type: v.Type,
|
|
Title: v.Title,
|
|
Content: v.Content,
|
|
Read: v.IsRead,
|
|
Time: v.CreatedAt.Format(time.RFC3339),
|
|
}
|
|
}
|
|
|
|
return &requests.Pager{
|
|
Pagination: requests.Pagination{Page: p.Page, Limit: p.Limit},
|
|
Total: total,
|
|
Items: data,
|
|
}, nil
|
|
}
|
|
|
|
func (s *notification) MarkRead(ctx context.Context, id string) error {
|
|
userID := ctx.Value(consts.CtxKeyUser)
|
|
if userID == nil {
|
|
return errorx.ErrUnauthorized
|
|
}
|
|
uid := cast.ToInt64(userID)
|
|
nid := cast.ToInt64(id)
|
|
|
|
_, err := models.NotificationQuery.WithContext(ctx).
|
|
Where(models.NotificationQuery.ID.Eq(nid), models.NotificationQuery.UserID.Eq(uid)).
|
|
UpdateSimple(models.NotificationQuery.IsRead.Value(true))
|
|
if err != nil {
|
|
return errorx.ErrDatabaseError.WithCause(err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *notification) Send(ctx context.Context, userID int64, typ, title, content string) error {
|
|
arg := args.NotificationArgs{
|
|
UserID: userID,
|
|
Type: typ,
|
|
Title: title,
|
|
Content: content,
|
|
}
|
|
return s.job.Add(arg)
|
|
}
|