pg_cooperation_contract_dao.go 14.8 KB
package dao

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/transform"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	"time"
)

type CooperationContractDao struct {
	transactionContext *pgTransaction.TransactionContext
}

// GenerateContractNumber 生成共创合约编号
func (dao *CooperationContractDao) GenerateContractNumber(queryOptions map[string]interface{}) (string, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	query := tx.Model(&cooperationContractModels)
	currentTime := time.Now()
	todayZeroTime := utils.GetZeroTime(currentTime)
	nextDayZeroTime := utils.GetNextDayZeroTime(currentTime)
	query.Where("cooperation_contract.created_at >= ?", todayZeroTime)
	query.Where("cooperation_contract.created_at < ?", nextDayZeroTime)
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query = query.Where(`cooperation_contract.company @> '{"companyId":"?"}'`, companyId)
	}
	if count, err := query.AllWithDeleted().SelectAndCount(); err != nil {
		return "", err
	} else {
		if count < 1000 {
			countStr := fmt.Sprintf("%03d", count+1)
			timestamp := currentTime.Unix()
			timeNow := time.Unix(timestamp, 0)
			timeString := timeNow.Format("20060102")
			timeString = timeString[2:len(timeString)]
			contractNumber := "HY" + timeString + "#" + countStr
			return contractNumber, nil
		} else {
			countStr := fmt.Sprintf("%d", count+1)
			timestamp := currentTime.Unix()
			timeNow := time.Unix(timestamp, 0)
			timeString := timeNow.Format("20060102")
			timeString = timeString[2:len(timeString)]
			dividendsOrderNumber := "HY" + timeString + "#" + countStr
			return dividendsOrderNumber, nil
		}

	}
}

// CheckUndertakerTypesUncheckedAvailable 校验合约承接对象是否可以删除
func (dao *CooperationContractDao) CheckUndertakerTypesUncheckedAvailable(queryOptions map[string]interface{}) (bool, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
	query := tx.Model(&cooperationContractUndertakerModels)
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query = query.Where("cooperation_contract_number = ?", cooperationContractNumber)
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query = query.Where(`cooperation_contract.company @> '{"companyId":"?"}'`, companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query = query.Where(`cooperation_contract.org @> '{"orgId":"?"}'`, orgId)
	}
	if user, ok := queryOptions["user"]; ok && user.(bool) != false {
		query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
			q.WhereOr("user_type = ?", 1)
			q.WhereOr("user_type = ?", 1025)
			return q, nil
		})
	}
	if partner, ok := queryOptions["partner"]; ok && partner.(bool) != false {
		query = query.Where("user_type = ?", 2)
	}
	ok, err := query.Exists()
	return !ok, err
}

// CheckContractNumberAvailable 检验合约编号唯一性
func (dao *CooperationContractDao) CheckContractNumberAvailable(queryOptions map[string]interface{}) (bool, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	query := tx.Model(&cooperationContractModels)
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query = query.Where("cooperation_contract_number = ?", cooperationContractNumber)
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query = query.Where(`cooperation_contract.company @> '{"companyId":"?"}'`, companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query = query.Where(`cooperation_contract.org @> '{"orgId":"?"}'`, orgId)
	}
	ok, err := query.Exists()
	return !ok, err
}

// CheckContractNumberExist 检验合约编号是否存在
func (dao *CooperationContractDao) CheckContractNumberExist(queryOptions map[string]interface{}) (bool, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	query := tx.Model(&cooperationContractModels)
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query = query.Where("cooperation_contract_number = ?", cooperationContractNumber)
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query = query.Where(`cooperation_contract.company @> '{"companyId":"?"}'`, companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query = query.Where(`cooperation_contract.org @> '{"orgId":"?"}'`, orgId)
	}
	ok, err := query.Exists()
	return ok, err
}

// SearchCooperationContractByUndertaker 查询共创合约并根据承接人返回
func (dao *CooperationContractDao) SearchCooperationContractByUndertaker(queryOptions map[string]interface{}) (int, []*models.CooperationContractByUndertaker, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractByUndertakerModels []*models.CooperationContractByUndertaker
	var cooperationUndertakerModels []*models.CooperationContractUndertaker
	query := tx.Model(&cooperationUndertakerModels)
	query.ColumnExpr("cooperation_contract_undertaker.cooperation_contract_undertaker_id")
	query.ColumnExpr("cooperation_contract_undertaker.user_info->>'userCode' AS undertaker_code")
	query.ColumnExpr("cooperation_contract_undertaker.user_info->>'userName' AS undertaker_name")
	query.ColumnExpr("cooperation_contract_undertaker.user_info->>'userPhone' AS undertaker_phone")
	query.ColumnExpr("cooperation_contract_undertaker.contract_attachment")
	query.ColumnExpr("A.cooperation_contract_sponsor")
	query.ColumnExpr("A.cooperation_contract_number")
	query.ColumnExpr("A.cooperation_contract_name")
	query.ColumnExpr("A.cooperation_contract_description")
	query.ColumnExpr("A.department")
	query.ColumnExpr("A.org")
	query.ColumnExpr("A.status AS contract_status")
	query.ColumnExpr("B.cooperation_mode_name")
	if cooperationContractName, ok := queryOptions["cooperationContractName"]; ok && cooperationContractName != "" {
		query = query.Where("A.cooperation_contract_name ilike ?", fmt.Sprintf("%%%s%%", cooperationContractName))
	}
	if sponsorName, ok := queryOptions["sponsorName"]; ok && sponsorName != "" {
		query = query.Where(`A.cooperation_contract_sponsor->>'userName')::text LIKE ?`, fmt.Sprintf("%%%s%%", sponsorName))
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query.Where("A.company->>'companyId' = '?'", companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query.Where("A.org->>'orgId' = '?'", orgId)
	}
	if orgIds, ok := queryOptions["orgIds"]; ok && len(orgIds.([]int64)) > 0 {
		newOrgIds := utils.SliceItoa(orgIds.([]int64))
		query.Where("A.org->>'orgId' in (?)", pg.In(newOrgIds))
	}
	query.Join("JOIN cooperation_contracts AS A ON A.cooperation_contract_number = cooperation_contract_undertaker.cooperation_contract_number")
	query.Join("JOIN cooperation_modes AS B ON B.cooperation_mode_number = A.cooperation_mode_number")
	query = query.Order("cooperation_contract_undertaker_id DESC")
	if offset, ok := queryOptions["offset"]; ok && offset.(int64) != 0 {
		offset := offset.(int64)
		if offset > -1 {
			query = query.Offset(int(offset))
		}
	} else {
		query = query.Offset(0)
	}
	if limit, ok := queryOptions["limit"]; ok && limit.(int64) != 0 {
		limit := limit.(int64)
		if limit > -1 {
			query = query.Limit(int(limit))
		}
	} else {
		query = query.Limit(20)
	}
	if count, err := query.SelectAndCount(&cooperationContractByUndertakerModels); err != nil {
		return 0, nil, err
	} else {
		return count, cooperationContractByUndertakerModels, nil
	}
}

func (dao *CooperationContractDao) Find(queryOptions map[string]interface{}) (int64, []*domain.CooperationContract, error) {
	tx := dao.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	cooperationContracts := make([]*domain.CooperationContract, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&cooperationContractModels), queryOptions)
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query.Where("cooperation_contract_number ilike ?", fmt.Sprintf("%%%s%%", cooperationContractNumber))
	}
	if cooperationContractName, ok := queryOptions["cooperationContactName"]; ok && cooperationContractName != "" {
		query.Where("cooperation_contract_name like ?", fmt.Sprintf("%%%s%%", cooperationContractName))
	}
	if departmentName, ok := queryOptions["departmentName"]; ok && departmentName != "" {
		query.Where(`(cooperation_contract.department->>'departmentName')::test LIKE ?`, fmt.Sprintf("%%%s%%", departmentName))
	}
	if sponsorName, ok := queryOptions["sponsorName"]; ok && sponsorName != "" {
		query.Where(`(cooperation_contract.cooperation_contract_sponsor->>'userName')::text LIKE ?`, fmt.Sprintf("%%%s%%", sponsorName))
	}
	if cooperationContractIds, ok := queryOptions["cooperationContractIds"]; ok && len(cooperationContractIds.([]int64)) != 0 {
		query.Where("cooperation_contract_id in (?)", pg.In(cooperationContractIds))
	}
	if cooperationContractNumbers, ok := queryOptions["cooperationContractNumbers"]; ok && len(cooperationContractNumbers.([]string)) != 0 {
		query.Where("cooperation_contract_number in (?)", pg.In(cooperationContractNumbers))
	}
	if cooperationModeNumber, ok := queryOptions["cooperationModeNumber"]; ok && cooperationModeNumber.(string) != "" {
		query.Where("cooperation_mode_number = ?", cooperationModeNumber)
	}
	if CooperationProjectNumber, ok := queryOptions["cooperationProjectNumber"]; ok && CooperationProjectNumber.(string) != "" {
		query.Where("cooperation_project_number = ?", CooperationProjectNumber)
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query.Where("company->>'companyId' = '?'", companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query.Where("org->>'orgId' = '?'", orgId)
	}
	if orgIds, ok := queryOptions["orgIds"]; ok && len(orgIds.([]int64)) > 0 {
		newOrgIds := utils.SliceItoa(orgIds.([]int64))
		query.Where("org->>'orgId' in (?)", pg.In(newOrgIds))
	}
	if incentivesType, ok := queryOptions["incentivesType"]; ok && incentivesType.(int32) != 0 {
		query.Where("incentives_type = ?", incentivesType)
	}
	offsetLimitFlag := true
	if offsetLimit, ok := queryOptions["offsetLimit"]; ok {
		offsetLimitFlag = offsetLimit.(bool)
	}
	if offsetLimitFlag {
		query.SetOffsetAndLimit(20)
	}
	query.SetOrderDirect("cooperation_contract_id", "DESC")
	var count int
	var err error
	if count, err = query.SelectAndCount(); err != nil {
		return 0, cooperationContracts, err
	}
	for _, cooperationContractModel := range cooperationContractModels {
		// 获取分红激励规则列表
		var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
		var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
		var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
		var cooperationContractRelevantModels []*models.CooperationContractRelevant
		if cooperationContract, err := transform.TransformToCooperationContractDomainModelFromPgModels(
			cooperationContractModel,
			&models.CooperationMode{CooperationModeNumber: cooperationContractModel.CooperationModeNumber},
			dividendsIncentivesRuleModels,
			moneyIncentivesRuleModels,
			cooperationContractRelevantModels,
			cooperationContractUndertakerModels); err != nil {
			return 0, cooperationContracts, err
		} else {
			cooperationContracts = append(cooperationContracts, cooperationContract)
		}
	}
	return int64(count), cooperationContracts, nil
}

func (dao *CooperationContractDao) FindOne(queryOptions map[string]interface{}) (*domain.CooperationContract, error) {
	tx := dao.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	query := sqlbuilder.BuildQuery(tx.Model(cooperationContractModel), queryOptions)
	query.SetWhereByQueryOption("cooperation_contract.cooperation_contract_id = ?", "cooperationContractId")
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query.Where("cooperation_contract.cooperation_contract_number = ?", cooperationContractNumber)
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query.Where("company->>'companyId' = '?'", companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query.Where("org->>'orgId' = '?'", orgId)
	}
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, fmt.Errorf("共创合约不存在")
		} else {
			return nil, err
		}
	}
	if cooperationContractModel.CooperationContractId == 0 {
		return nil, nil
	} else {
		var cooperationModeModels []*models.CooperationMode
		cooperationModeQuery := tx.Model(&cooperationModeModels)
		if countMode, err := cooperationModeQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_mode_number = ?", cooperationContractModel.CooperationModeNumber).
			Limit(1).
			SelectAndCount(); err != nil {
			log.Logger.Error("合约关联的共创模式不存在", map[string]interface{}{
				"cooperationContractModel": cooperationContractModel,
			})
		} else {
			if countMode > 0 {
				// 获取分红激励规则列表
				var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
				var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
				var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
				var cooperationContractRelevantModels []*models.CooperationContractRelevant
				return transform.TransformToCooperationContractDomainModelFromPgModels(
					cooperationContractModel,
					cooperationModeModels[0],
					dividendsIncentivesRuleModels,
					moneyIncentivesRuleModels,
					cooperationContractRelevantModels,
					cooperationContractUndertakerModels)
			}
		}
		return nil, fmt.Errorf("共创合约不存在")
	}
}

func NewCooperationContractDao(transactionContext *pgTransaction.TransactionContext) (*CooperationContractDao, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &CooperationContractDao{
			transactionContext: transactionContext,
		}, nil
	}
}