pg_login_services.go 10.2 KB
package domain_service

import (
	"github.com/tiptok/gocomm/xa/eda"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
	http_gateway "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
	protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
	"strings"
)

type PgLoginService struct {
	Phone string
	eda.EventCenterPublisher
	PartnerInfo        []*domain.PartnerInfo
	Users              []*domain.Users
	transactionContext *transaction.TransactionContext
	AvailableCompany   bool
}

func (svr *PgLoginService) Init(phone string) (err error) {
	var (
		PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
		UsersRepository, _    = repository.NewUsersRepository(svr.transactionContext)
	)
	svr.Phone = phone
	_, svr.PartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC"})
	_, svr.Users, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true})
	return nil
}

//合伙人登录
func (svr *PgLoginService) PartnerLogin(phone string, password string) (err error) {
	if len(svr.PartnerInfo) == 0 {
		//子账号
		err = protocol.NewErrWithMessage(502, err) //账号不存在
		return
	}
	if !strings.EqualFold(svr.PartnerInfo[0].Password, password) {
		err = protocol.NewCustomMessage(1, "密码输入有误!")
		return
	}
	return
}

//管理层登录
func (svr *PgLoginService) ManagerLogin(phone string, password string) (err error) {
	if len(svr.Users) == 0 {
		//子账号
		err = protocol.NewErrWithMessage(502, err) //账号不存在
		return
	}
	var openid int64
	ucenerSvr := http_gateway.NewHttplibUCenterApiServiceGateway()
	openid, err = ucenerSvr.ServerLogin(phone, password, 1)
	if err == nil && openid > 0 {
		_, err = svr.transactionContext.PgTx.Exec("update users set open_id=? where phone=?", openid, phone)
	}
	return
}

//合伙人统计信息
func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
	response := make(map[string]interface{})
	response["id"] = protocolx.AdminTypePartner
	response["name"] = protocolx.AdminTypePartnerName
	if len(svr.PartnerInfo) == 0 {
		response["companys"] = make([]struct{}, 0)
		return response, nil
	}
	var (
		OrderDao, _                      = dao.NewOrderBaseDao(svr.transactionContext)
		BusinessBonusDao, _              = dao.NewBusinessBonusDao(svr.transactionContext)
		PartnerCategoryInfoRepository, _ = repository.NewPartnerCategoryInfoRepository(svr.transactionContext)
		companyList                      []*domain.Company
		allPartnerCategory               []*domain.PartnerCategoryInfo
		BusinessBonusRepository, _       = repository.NewBusinessBonusRepository(svr.transactionContext)
		UsersRepository, _               = repository.NewUsersRepository(svr.transactionContext)
		adminApiGateway                  = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
	)
	doGetCompanyIds := func() []int64 {
		var companies []int64
		for i := range svr.PartnerInfo {
			companies = append(companies, svr.PartnerInfo[i].CompanyId)
		}
		return companies
	}
	doGetPartnerIds := func() []int64 {
		var array []int64
		for i := range svr.PartnerInfo {
			array = append(array, svr.PartnerInfo[i].Id)
		}
		return array
	}
	companyList = svr.GetCompanyList(doGetCompanyIds)
	if len(companyList) == 0 {
		return response, nil
	}
	totalBonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), OrderType: domain.OrderReal})
	if e != nil {
		return response, e
	}
	if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), IsDisable: 1}); e == nil {
		totalBonus.Bonus += businessBonus.Bonus
	}
	_, allPartnerCategory, e = PartnerCategoryInfoRepository.Find(map[string]interface{}{"sortById": domain.ASC})
	var mapPartnerBussinessBonus = make(map[int64]*domain.BusinessBonus)
	if _, bussinessBonus, e := BusinessBonusRepository.Find(map[string]interface{}{"inPartnerIds": doGetPartnerIds(), "isDisable": 1}); e == nil {
		for _, v := range bussinessBonus {
			mapPartnerBussinessBonus[v.PartnerInfoId] = v
		}
	}
	if e != nil {
		log.Error(e)
		return response, e
	}
	var mapCompanyAdminUsers map[int64]*domain.Users = make(map[int64]*domain.Users) //key:company_id value:domain.users
	if _, adminUsers, e := UsersRepository.Find(map[string]interface{}{"inCompanyIds": doGetCompanyIds(), "adminType": 2, "deleteAtIsNull": true}); e == nil {
		for i := range adminUsers {
			mapCompanyAdminUsers[adminUsers[i].CompanyId] = adminUsers[i]
		}
	}
	var companys = make([]*Company, 0)
	for i := range companyList {
		c := companyList[i]
		var partner *domain.PartnerInfo
		for j := range svr.PartnerInfo {
			if svr.PartnerInfo[j].CompanyId == c.Id {
				partner = svr.PartnerInfo[j]
				break
			}
		}
		if partner == nil {
			continue
		}
		if au, ok := mapCompanyAdminUsers[partner.CompanyId]; ok {
			if code, e := adminApiGateway.UserAuth(au.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
				log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, au.Id, code, e.Error())
				continue
			} else {
				log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, au.Id, code, e)
			}
		} else {
			log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, partner.Id, "公司管理员不存在")
			continue
		}

		bonus, _ := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: partner.Id, OrderType: domain.OrderReal})
		if v, ok := mapPartnerBussinessBonus[partner.Id]; ok {
			bonus.Bonus += v.Bonus
		}
		item := &Company{
			CompanyBase:   newCompanyBase(c),
			IncomePercent: computeBonusPercent(totalBonus.Bonus, bonus.Bonus*100),
			DividendMoney: utils.Decimal(bonus.Bonus),
			JoinWays:      svr.GetJoinWays(allPartnerCategory, partner, bonus.Bonus),
		}
		companys = append(companys, item)
	}
	if len(companys) > 0 {
		svr.AvailableCompany = true
	}

	response["companys"] = companys
	return response, nil
}
func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
	response := make(map[string]interface{})
	response["id"] = protocolx.AdminTypeManager
	response["name"] = protocolx.AdminTypeManagerName
	if len(svr.Users) == 0 {
		response["companys"] = make([]struct{}, 0)
		return response, nil
	}
	var (
		companyList     []*domain.Company
		adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
	)
	doGetCompanyIds := func() []int64 {
		var companies []int64
		for i := range svr.Users {
			companies = append(companies, svr.Users[i].CompanyId)
		}
		return companies
	}
	companyList = svr.GetCompanyList(doGetCompanyIds)
	var companys = make([]protocol.CompanyBase, 0)
	for i := range companyList {
		c := companyList[i]

		if constant.POSTGRESQL_DB_NAME != "partner_dev1" {
			//通过企业平台 校验模块权限
			var user *domain.Users
			for j := range svr.Users {
				if svr.Users[j].CompanyId == c.Id {
					user = svr.Users[j]
					break
				}
			}
			if user != nil {
				if code, e := adminApiGateway.UserAuth(user.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
					log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e.Error())
					continue
				} else {
					log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e)
				}
			}
		}
		item := newCompanyBase(c)
		companys = append(companys, item)
	}
	if len(companys) > 0 {
		svr.AvailableCompany = true
	}

	response["companys"] = companys
	return response, nil
}
func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*domain.Company {
	var (
		CompanyRepository, _ = repository.NewCompanyRepository(svr.transactionContext)
		companyList          []*domain.Company
	)
	var companies []int64 = funcGetCompanyIds()
	if len(companies) == 0 {
		return companyList
	}
	if _, v, e := CompanyRepository.Find(map[string]interface{}{"inCompanyIds": companies, "enable": 1, "sortByCreateTime": domain.DESC}); e != nil {
		log.Error(e)
		return companyList
	} else {
		companyList = v
	}
	return companyList
}
func (svr *PgLoginService) GetJoinWays(partnerCategory []*domain.PartnerCategoryInfo, partnerInfo *domain.PartnerInfo, bonus float64) []joinWay {
	searchCategory := func(partnerCategory []*domain.PartnerCategoryInfo, id int64) *domain.PartnerCategoryInfo {
		for i := range partnerCategory {
			if partnerCategory[i].Id == id {
				return partnerCategory[i]
			}
		}
		return nil
	}
	var joinWays []joinWay
	for i := range partnerCategory {
		c := partnerCategory[i]
		searchC := searchCategory(partnerInfo.PartnerCategoryInfos, c.Id)
		if searchC != nil {
			item := joinWay{
				Type: int(c.Id),
				Name: c.Name,
			}
			joinWays = append(joinWays, item)
		}
	}

	for i := range joinWays {
		joinWays[i].Percent = computeBonusPercent(float64(len(joinWays)), 1) * 100
	}
	return joinWays
}
func newCompanyBase(company *domain.Company) protocol.CompanyBase {
	return protocol.CompanyBase{
		Id:        company.Id,
		Name:      company.Name,
		ShortName: company.Abbreviation,
		Image:     protocol.NewImage(company.Logo),
		Phone:     company.Phone,
	}
}
func computeBonusPercent(totalBonus float64, bonus float64) float64 {
	if totalBonus == 0 {
		return 0
	}
	return utils.Decimal(bonus / totalBonus)
}

type Company struct {
	protocol.CompanyBase
	// 收入占比
	IncomePercent float64 `json:"incomePercent"`
	// 分红金额
	DividendMoney float64   `json:"dividendMoney"`
	JoinWays      []joinWay `json:"joinWays"`
}
type incomeInfo struct {
	// 收入占比
	IncomePercent float64 `json:"incomePercent"`
	// 分红金额
	DividendMoney float64 `json:"dividendMoney"`
}
type joinWay struct {
	Type    int     `json:"type"`
	Name    string  `json:"name"`
	Percent float64 `json:"percent"`
}

func NewPgLoginService(ctx *transaction.TransactionContext) *PgLoginService {
	return &PgLoginService{
		transactionContext: ctx,
		AvailableCompany:   false,
	}
}