pg_cooperation_company_statistics_service.go 13.7 KB
package domain_service

import (
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/linmadan/egglib-go/utils/json"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/repository"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	"math"
	"time"
)

// totalOrganizationUser 统计组织用户

// rankType 排行榜类型,1月榜,2年榜 3总榜,默认展示年榜
// top      排名前n个
func (ptr *CooperationStatisticsService) CooperationGoodsStatistics(queryOptions map[string]interface{}) ([]*domain.CooperationGoodsStatisticsDto, error) {
	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
		RankType  int   `json:"rankType" valid:"Required"`
		Top       int   `json:"top" valid:"Required"`
		Offset    int   `json:"offset"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	y := time.Now().Year()
	m := time.Now().Month()
	var beginTime, endTime time.Time
	if request.RankType == 1 { //1月榜
		beginTime = time.Date(y, m, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(0, 1, 0)
		queryOptions["beginTime"] = beginTime.Format(time.RFC3339)
		queryOptions["endTime"] = endTime.Format(time.RFC3339)
	} else if request.RankType == 2 { //2年榜
		beginTime = time.Date(y, 1, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(1, 0, 0)
		queryOptions["beginTime"] = beginTime.Format(time.RFC3339)
		queryOptions["endTime"] = endTime.Format(time.RFC3339)
	}
	if request.Top > 0 {
		queryOptions["limit"] = request.Top
	}
	if request.Offset > 0 {
		queryOptions["offset"] = request.Offset
	}
	goods, err := orderGoodDao.CooperationGoodsStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	if len(goods) == 0 {
		goods = make([]*domain.CooperationGoodsStatisticsDto, 0)
	}

	// 2.计算百分比
	var totalAmount float64
	for i := range goods {
		goods[i].Rank = int32(i + 1)
		totalAmount += goods[i].GoodAmount
	}
	for i := range goods {
		if totalAmount == 0 {
			goods[i].GoodRatio = 0
			continue
		}
		goods[i].GoodRatio = utils.Round((goods[i].GoodAmount/totalAmount)*100, 0)
	}
	return goods, nil
}

// CooperationModeStatistics  企业-共创模式统计
//
// p1 p1_desc
func (ptr *CooperationStatisticsService) CooperationModeStatistics(queryOptions map[string]interface{}) ([]*domain.CooperationModeStatisticsDto, error) {
	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	modeStatistics, err := orderGoodDao.CooperationCompanyModeStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	if len(modeStatistics) == 0 {
		modeStatistics = make([]*domain.CooperationModeStatisticsDto, 0)
	}

	return modeStatistics, nil
}

// DividendsStatistics  分红统计
//
// action 1:当前月
func (ptr *CooperationStatisticsService) CompanyDividendsStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
		Action    int   `json:"action" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	var beginTime, endTime time.Time
	var res = make(map[string]interface{})
	if request.Action == 1 {
		y := time.Now().Year()
		m := time.Now().Month()
		beginTime = time.Date(y, m, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(0, 1, 0)
		queryOptions["beginTime"] = beginTime
		queryOptions["endTime"] = endTime
	}
	totalDividends, err := orderGoodDao.CompanyDividendsStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	queryOptions["paymentStatus"] = 2
	dividendsEstimate, err := orderGoodDao.CompanyDividendsStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	orderAmount := ptr.CalculateOrderAmount(queryOptions)

	res["creditAccount"] = dividendsEstimate.DividendsEstimate  // 本月账期结算统计
	res["orderAmount"] = orderAmount                            // 订单金额统计
	res["dividendsEstimate"] = totalDividends.DividendsEstimate // 分红预算统计
	return res, nil
}

func (ptr *CooperationStatisticsService) CalculateOrderAmount(queryOption map[string]interface{}) float64 {
	orderDao, err := dao.NewDividendsOrderDao(ptr.transactionContext)
	if err != nil {
		log.Logger.Error(err.Error())
	}
	amount, err := orderDao.CalculateDividendsOrderAmount(queryOption)
	if err != nil {
		log.Logger.Error(err.Error())
	}
	returnedOrderDao, _ := dao.NewDividendsReturnedOrderDao(ptr.transactionContext)
	returnedAmount, _ := returnedOrderDao.CalculateDividendsReturnedOrderAmount(queryOption)
	if math.Abs(returnedAmount) > math.Abs(amount) {
		return 0
	}
	return utils.Round(math.Abs(amount)-math.Abs(returnedAmount), 1)
}

func 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
}

func LoadQueryObject(queryOption map[string]interface{}, obj interface{}) error {
	json.UnmarshalFromString(json.MarshalToString(queryOption), obj)
	validation := validation.Validation{}
	_, err := validation.Valid(obj)
	return err
}

type item struct {
	key string
	val interface{}
}

// 公司 - 共创用户统计
func (ptr *CooperationStatisticsService) CompanyCooperationUsersStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		Limit                    int   `json:"limit" valid:"Required"`
		Offset                   int   `json:"offset"`
		OrgId                    int64 `json:"orgId" valid:"Required"`
		SortByActuallyPaidAmount int   `json:"sortByActuallyPaidAmount" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	var responses []usersStatisticsResponse
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	if err := creditAccountDao.CooperationUsersDividendsStatistics(queryOptions, &responses); err != nil {
		return nil, err
	}

	var retMap = make([]interface{}, 0)
	for i := range responses {
		responses[i].CooperationTime = time.Now().Unix() * 1000
		unPaidAmount := responses[i].DividesAmount - responses[i].ActuallyPaidAmount
		retMap = append(retMap, map[string]interface{}{
			"dividendsOrderAmount": responses[i].DividendsOrderAmount,
			"dividesAmount":        responses[i].DividesAmount,
			"unPaidAmount":         unPaidAmount,
			"cooperationTime":      time.Now().Unix() * 1000,
			"participator": map[string]interface{}{
				"userId": responses[i].UserId,
				"userInfo": map[string]interface{}{
					"userName": responses[i].UserName,
				},
			},
		})
	}

	return retMap, nil
}

type usersStatisticsResponse struct {
	CooperationTime      int64   `json:"cooperationTime"`
	DividendsOrderAmount float64 `json:"dividendsOrderAmount"`
	DividesAmount        float64 `json:"dividesAmount"`      // 分红金额
	ActuallyPaidAmount   float64 `json:"actuallyPaidAmount"` // 已支付金额
	UnPaidAmount         float64 `json:"unPaidAmount"`       // 未支付金额
	UserId               int64   `json:"userId,string"`
	UserName             string  `json:"userName"`

	Participator interface{} `json:"participator"`
}

// 公司 - 共创用户模式统计
func (ptr *CooperationStatisticsService) CooperationUserModeStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		UserId int64 `json:"offset" valid:"Required"`
		//OrgId                    int64 `json:"orgId" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	modeStatistics, err := orderGoodDao.CooperationUserModeStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	if len(modeStatistics) == 0 {
		return struct{}{}, nil
	}

	var modeNumbers []string
	var mapModeStatistics = make(map[string]*domain.CooperationModeStatisticsDto)
	for i := range modeStatistics {
		mapModeStatistics[modeStatistics[i].CooperationModeNumber] = modeStatistics[i]
		modeNumbers = append(modeNumbers, modeStatistics[i].CooperationModeNumber)
	}

	cooperationModeRepository, _ := repository.NewCooperationModeRepository(ptr.transactionContext)
	_, cooperModes, err := cooperationModeRepository.Find(map[string]interface{}{"cooperationModeNumbers": modeNumbers})
	if err != nil {
		return nil, err
	}
	var cooperationTypes, dividendsExpenseByTypes, orderAmountByTypes []interface{}
	var totalOrderAmount float64
	var totalDividendAmount float64
	for i := range cooperModes {
		m := cooperModes[i]
		if modeStatistics, ok := mapModeStatistics[m.CooperationModeNumber]; ok {
			totalOrderAmount += modeStatistics.OrderAmount
			totalDividendAmount += modeStatistics.SettlementAmount
			dividendsExpenseByTypes = append(dividendsExpenseByTypes, map[string]interface{}{
				"dividendsTypeName": m.CooperationModeName + "分红支出",
				"dividendsExpense":  modeStatistics.SettlementAmount,
			})
			orderAmountByTypes = append(orderAmountByTypes, map[string]interface{}{
				"orderAmount":   modeStatistics.OrderAmount,
				"orderTypeName": m.CooperationModeName + "成交订单",
			})
		}
		cooperationTypes = append(cooperationTypes, map[string]interface{}{
			"cooperationModeId":     m.CooperationModeId,
			"cooperationModeName":   m.CooperationModeName,
			"cooperationModeNumber": m.CooperationModeNumber,
		})
	}
	return map[string]interface{}{
		"cooperationTypes": cooperationTypes,
		"dividendsDetails": map[string]interface{}{
			"dividendsExpense":        totalDividendAmount,
			"dividendsExpenseByTypes": dividendsExpenseByTypes,
		},
		"orderDetails": map[string]interface{}{
			"orderAmount":        totalOrderAmount,
			"orderAmountByTypes": orderAmountByTypes,
		},
	}, nil
}

// 公司 - 共创用户分红支付统计
func (ptr *CooperationStatisticsService) CompanyPaymentHistoryStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		Limit                    int       `json:"limit" valid:"Required"`
		Offset                   int       `json:"offset"`
		OrgId                    int64     `json:"orgId" valid:"Required"`
		SortByActuallyPaidAmount int       `json:"sortByActuallyPaidAmount" valid:"Required"`
		BeginTime                time.Time `json:"beginTime"`
		EndTime                  time.Time `json:"endTime"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	var responses []usersStatisticsResponse
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	if err := creditAccountDao.CooperationUsersDividendsStatistics(queryOptions, &responses); err != nil {
		return nil, err
	}

	var retMap = make([]interface{}, 0)
	for i := range responses {
		retMap = append(retMap, map[string]interface{}{
			"paymentAmount": responses[i].ActuallyPaidAmount,
			"user": map[string]interface{}{
				"userId": responses[i].UserId,
				"userInfo": map[string]interface{}{
					"userName": responses[i].UserName,
				},
			},
		})
	}

	return retMap, nil
}

// 公司/个人 - 支付历史统计直方图
func (ptr *CooperationStatisticsService) PaymentHistoryHistogramStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)

	var request = struct {
		OrgId      int64 `json:"orgId"`
		UserBaseId int64 `json:"userBaseId"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	var dividends = &CreditAccountStatisticsResponse{}
	year, month := time.Now().Year(), time.Now().Month()
	var beginTime = time.Date(year, month, 1, 0, 0, 0, 0, time.Local)
	var endTime time.Time
	var increaseDay = 5
	var monthEnd = time.Date(year, month+1, 1, 0, 0, 0, 0, time.Local).Add(-time.Second)
	var xAxisData []string
	var values []float64
	for {
		if beginTime.AddDate(0, 0, increaseDay).After(monthEnd) {
			endTime = monthEnd
			break
		} else {
			endTime = beginTime.AddDate(0, 0, increaseDay).Add(-time.Second)
		}
		xAxisData = append(xAxisData, endTime.Format("01-02"))
		queryOptions["beginTime"] = beginTime
		queryOptions["endTime"] = beginTime.AddDate(0, 0, increaseDay)
		if err := creditAccountDao.DividendsStatistics(queryOptions, dividends); err != nil {
			return nil, err
		}
		dividends.Accounting = dividends.Total - dividends.Accounted
		values = append(values, dividends.Paid)
		beginTime = endTime
		if endTime == monthEnd {
			break
		}
	}
	return map[string]interface{}{
		"xAxis": map[string]interface{}{
			"data": xAxisData,
		},
		"source": map[string]interface{}{
			"value": values,
		},
	}, nil
}