system_user_statistics_logic.go 2.8 KB
package user

import (
	"context"
	"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/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 SystemUserStatisticsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SystemUserStatisticsLogic) SystemUserStatistics(req *types.UserStatisticsRequest) (resp *types.UserStatisticsResponse, err error) {
	var (
		userId    = req.UserId
		userToken = contextdata.GetUserTokenFromCtx(l.ctx)
	)
	s := StatisticsItems(l.ctx, l.svcCtx, userToken.CompanyId, userId, req.ItemFlag)
	resp = &types.UserStatisticsResponse{
		TotalArticle: s.TotalArticle,
		TotalComment: s.TotalComment,
		TotalLoved:   s.TotalLoved,
		TotalBeLoved: s.TotalBeLoved,
	}
	return
}

func StatisticsItems(ctx context.Context, svcCtx *svc.ServiceContext, companyId, userId int64, itemFlag int) (s Statistics) {
	var conn = svcCtx.DefaultDBConn()
	s = Statistics{}
	if itemFlag == 0 {
		itemFlag = -1
	}
	if (itemFlag & TotalArticle) > 0 {
		var total int64
		total, _, _ = svcCtx.ArticleRepository.Find(ctx, conn, companyId, domain.NewQueryOptions().WithCountOnly().MustWithKV("authorId", userId))
		s.TotalArticle = int(total)
	}
	if (itemFlag & TotalComment) > 0 {
		var total int64
		total, _, _ = svcCtx.ArticleCommentRepository.Find(ctx, conn, domain.IndexCompanyId(companyId)().WithCountOnly().MustWithKV("fromUserId", userId))
		s.TotalComment = int(total)
	}
	if (itemFlag & TotalLoved) > 0 {
		var total int64
		total, _, _ = svcCtx.UserLoveFlagRepository.Find(ctx, conn, domain.IndexCompanyId(0)().WithCountOnly().MustWithKV("userId", userId))
		s.TotalLoved = int(total)
	}
	if (itemFlag & TotalBeLoved) > 0 {
		var total int64
		total, _, _ = svcCtx.UserLoveFlagRepository.Find(ctx, conn, domain.IndexCompanyId(0)().WithCountOnly().MustWithKV("toUserId", userId))
		s.TotalBeLoved = int(total)
	}
	return
}

type Statistics struct {
	TotalArticle int `json:"totalArticle"`
	TotalComment int `json:"totalComment"`
	TotalLoved   int `json:"totalLoved"`
	TotalBeLoved int `json:"totalBeLoved"`
}

const (
	TotalArticle = 1 // 累计发布文章
	TotalComment = 2 // 累计发布评论
	TotalLoved   = 4 // 累计赞别人
	TotalBeLoved = 8 // 累计收到的赞
)

func NewStatisticsItem(itemFlag int, value float64) types.StatisticsItem {
	return types.StatisticsItem{
		ItemFlag: itemFlag,
		Value:    value,
	}
}