pg_common_statistics_service.go 2.0 KB
package domainService

import (
	"fmt"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"
)

// PgCommonStatisticsService 通用统计服务
type PgCommonStatisticsService struct {
	transactionContext *pgTransaction.TransactionContext
}

const (
	// 累计组织用户
	TotalOrganizationUser = iota + 1
)

var (
	mapStatistics = map[int]string{
		TotalOrganizationUser: "totalOrganizationUser",
	}
)

// Scan  扫描需要统计的项
//
// keyFlags 统计项标识符号
// queryOption 查询参数
func (ptr *PgCommonStatisticsService) Scan(keyFlags []int, queryOption map[string]interface{}) (interface{}, error) {
	var res = make(map[string]interface{})
	for i := range keyFlags {
		switch keyFlags[i] {
		case TotalOrganizationUser:
			queryTotalOrganizationUser, err := ptr.loadQueryOptions(queryOption, "companyId", "organizationId")
			if err != nil {
				return nil, err
			}
			if v, err := ptr.totalOrganizationUser(queryTotalOrganizationUser); err != nil {
				return nil, err
			} else {
				res[v.key] = v.val
			}
		}
	}
	return res, nil
}

// totalOrganizationUser 统计组织用户
func (ptr *PgCommonStatisticsService) totalOrganizationUser(queryOption map[string]interface{}) (item, error) {
	res := item{
		key: mapStatistics[TotalOrganizationUser],
	}
	userRepository, _ := repository.NewUserRepository(ptr.transactionContext)
	if total, _, err := userRepository.Find(queryOption); err != nil {
		return res, err
	} else {
		res.val = map[string]interface{}{
			"total": total,
		}
	}
	return res, nil
}

func (ptr *PgCommonStatisticsService) loadQueryOptions(queryOption map[string]interface{}, keys ...string) (map[string]interface{}, error) {
	var res = make(map[string]interface{})
	for i := 0; i < len(keys); i++ {
		k := keys[i]
		if v, ok := queryOption[k]; ok {
			res[k] = v
		} else {
			return nil, fmt.Errorf("参数 %v 不存在", k)
		}
	}
	return res, nil
}

type item struct {
	key string
	val interface{}
}