mini_user_news_logic.go 2.5 KB
package user

import (
	"context"
	"github.com/samber/lo"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/contextdata"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MiniUserNewsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMiniUserNewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MiniUserNewsLogic {
	return &MiniUserNewsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MiniUserNewsLogic) MiniUserNews(req *types.MiniUserNewsRequest) (resp *types.MiniUserNewsResposne, err error) {
	var (
		conn           = l.svcCtx.DefaultDBConn()
		user           *domain.User
		userToken      = contextdata.GetUserTokenFromCtx(l.ctx)
		articles       []*domain.Article
		readedArticles = make([]*domain.UserReadArticle, 0)
	)
	if user, err = l.svcCtx.UserRepository.FindOne(l.ctx, conn, userToken.UserId); err != nil {
		return nil, xerr.NewErrMsgErr("用户不存在", err)
	}
	var (
		users = user.Following
	)
	if req.AuthorId > 0 {
		users = []int64{req.AuthorId}
	}
	if _, articles, err = l.svcCtx.ArticleRepository.FindAuthorsLatestArticle(l.ctx, conn, user.CompanyId, users, user.Id, req.LastArticleId, req.Size); err != nil {
		return nil, xerr.NewErrMsgErr("获取快讯异常", err)
	}
	resp = &types.MiniUserNewsResposne{
		List: make([]types.UserNewsItem, 0),
	}
	articleIds := domain.Values(articles, func(item *domain.Article) int64 {
		return item.Id
	})
	if len(articleIds) > 0 {
		resp.LastArticleId = articleIds[len(articleIds)-1]
		_, readedArticles, _ = l.svcCtx.UserReadArticleRepository.Find(l.ctx, conn, domain.IndexCompanyId(userToken.CompanyId)().WithKV("articleIds", articleIds))
	}
	readArticlesMap := lo.KeyBy(readedArticles, func(item *domain.UserReadArticle) int64 {
		return item.ArticleId
	})
	lo.ForEach(articles, func(item *domain.Article, index int) {
		newsItem := types.UserNewsItem{
			NewsId:   item.Id,
			Type:     "article",
			Title:    item.Title,
			Summary:  item.Summary,
			Time:     item.CreatedAt,
			ReadFlag: false,
		}
		if _, ok := readArticlesMap[item.Id]; ok {
			newsItem.ReadFlag = true
		}
		resp.List = append(resp.List, newsItem)
	})
	return
}