pg_cooperation_contract_repository.go 17.4 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"time"

	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/snowflake"
	"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"
)

type CooperationContractRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *CooperationContractRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}
func (repository *CooperationContractRepository) Save(cooperationContract *domain.CooperationContract) (*domain.CooperationContract, error) {
	sqlBuildFields := []string{
		"cooperation_contract_id",
		"cooperation_contract_description",
		"cooperation_contract_name",
		"cooperation_contract_number",
		"cooperation_contract_referrer",
		"cooperation_contract_salesman",
		"cooperation_contract_undertaker_type",
		"cooperation_contract_sponsor",
		"cooperation_mode_number",
		"status",
		"org",
		"company",
		"operator",
		"operate_time",
		"created_at",
		"deleted_at",
		"updated_at",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "cooperationContract_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if cooperationContract.Identify() == nil {
		cooperationContractId, err := repository.nextIdentify()
		if err != nil {
			return cooperationContract, err
		} else {
			cooperationContract.CooperationContractId = cooperationContractId
		}
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationContract.CooperationContractId,
				&cooperationContract.CooperationContractDescription,
				&cooperationContract.CooperationContractName,
				&cooperationContract.CooperationContractNumber,
				&cooperationContract.CooperationContractReferrer,
				&cooperationContract.CooperationContractSalesman,
				pg.Array(&cooperationContract.CooperationContractUndertakerType),
				&cooperationContract.CooperationContractSponsor,
				&cooperationContract.CooperationMode.CooperationModeNumber,
				&cooperationContract.Status,
				&cooperationContract.Org,
				&cooperationContract.Company,
				&cooperationContract.Operator,
				&cooperationContract.OperateTime,
				&cooperationContract.CreatedAt,
				&cooperationContract.DeletedAt,
				&cooperationContract.UpdatedAt,
			),
			fmt.Sprintf("INSERT INTO cooperation_contracts (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			cooperationContract.CooperationContractId,
			cooperationContract.CooperationContractDescription,
			cooperationContract.CooperationContractName,
			cooperationContract.CooperationContractNumber,
			cooperationContract.CooperationContractReferrer,
			cooperationContract.CooperationContractSalesman,
			pg.Array(cooperationContract.CooperationContractUndertakerType),
			cooperationContract.CooperationContractSponsor,
			cooperationContract.CooperationMode.CooperationModeNumber,
			cooperationContract.Status,
			cooperationContract.Org,
			cooperationContract.Company,
			cooperationContract.Operator,
			cooperationContract.OperateTime,
			cooperationContract.CreatedAt,
			cooperationContract.DeletedAt,
			cooperationContract.UpdatedAt,
		); err != nil {
			return cooperationContract, err
		} else {
			// 新增相关人
			var relevantPeopleModel []*models.CooperationContractRelevant
			for _, relevant := range cooperationContract.RelevantPeople {
				relevantPeopleModel = append(relevantPeopleModel, &models.CooperationContractRelevant{
					CooperationContractNumber: cooperationContract.CooperationContractNumber,
					Relevant:                  relevant,
					UpdatedAt:                 time.Time{},
					DeletedAt:                 time.Time{},
					CreatedAt:                 time.Now(),
				})
			}
			if _, err := tx.Model(&relevantPeopleModel).Insert(); err != nil {
				return nil, err
			}

			// 新增承接人
			var undertakersModel []*models.CooperationContractUndertaker
			for _, undertaker := range cooperationContract.Undertakers {
				undertakersModel = append(undertakersModel, &models.CooperationContractUndertaker{
					CooperationContractNumber: cooperationContract.CooperationContractNumber,
					Undertaker:                undertaker,
					CreatedAt:                 time.Time{},
					UpdatedAt:                 time.Time{},
					DeletedAt:                 time.Now(),
				})
			}
			if _, err := tx.Model(&undertakersModel).Insert(); err != nil {
				return nil, err
			}

			// 新增分红激励规则
			var dividendsIncentivesRulesModel []*models.DividendsIncentivesRule
			for _, rule := range cooperationContract.DividendsIncentivesRules {
				dividendsIncentivesRulesModel = append(dividendsIncentivesRulesModel, &models.DividendsIncentivesRule{
					CooperationContractNumber:     cooperationContract.CooperationContractNumber,
					ReferrerPercentage:            rule.ReferrerPercentage,
					SalesmanPercentage:            rule.SalesmanPercentage,
					DividendsIncentivesPercentage: rule.DividendsIncentivesPercentage,
					DividendsIncentivesStage:      rule.DividendsIncentivesStage,
					DividendsIncentivesStageStart: rule.DividendsIncentivesStageStart,
					DividendsIncentivesStageEnd:   rule.DividendsIncentivesStageEnd,
					Org:                           rule.Org,
					Company:                       rule.Company,
					UpdatedAt:                     time.Time{},
					DeletedAt:                     time.Time{},
					CreatedAt:                     time.Now(),
				})
			}
			if _, err := tx.Model(&dividendsIncentivesRulesModel).Insert(); err != nil {
				return nil, err
			}
			// 新增金额激励规则
			var moneyIncentivesRulesModel []*models.MoneyIncentivesRule
			for _, rule := range cooperationContract.MoneyIncentivesRules {
				moneyIncentivesRulesModel = append(moneyIncentivesRulesModel, &models.MoneyIncentivesRule{
					CooperationContractNumber: cooperationContract.CooperationContractNumber,
					MoneyIncentivesAmount:     rule.MoneyIncentivesAmount,
					MoneyIncentivesStage:      rule.MoneyIncentivesStage,
					MoneyIncentivesStageStart: rule.MoneyIncentivesStageStart,
					MoneyIncentivesStageEnd:   rule.MoneyIncentivesStageEnd,
					MoneyIncentivesTime:       rule.MoneyIncentivesTime,
					ReferrerPercentage:        rule.ReferrerPercentage,
					SalesmanPercentage:        rule.SalesmanPercentage,
					Org:                       rule.Org,
					Company:                   rule.Company,
					UpdatedAt:                 time.Time{},
					DeletedAt:                 time.Time{},
					CreatedAt:                 time.Now(),
				})
			}
			if _, err := tx.Model(&moneyIncentivesRulesModel).Insert(); err != nil {
				return nil, err
			}
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationContract.CooperationContractId,
				&cooperationContract.CooperationContractDescription,
				&cooperationContract.CooperationContractName,
				&cooperationContract.CooperationContractNumber,
				&cooperationContract.CooperationContractReferrer,
				&cooperationContract.CooperationContractSalesman,
				pg.Array(&cooperationContract.CooperationContractUndertakerType),
				&cooperationContract.CooperationContractSponsor,
				&cooperationContract.CooperationMode.CooperationModeNumber,
				&cooperationContract.Status,
				&cooperationContract.Org,
				&cooperationContract.Company,
				&cooperationContract.Operator,
				&cooperationContract.OperateTime,
				&cooperationContract.CreatedAt,
				&cooperationContract.DeletedAt,
				&cooperationContract.UpdatedAt,
			),
			fmt.Sprintf("UPDATE cooperation_contracts SET %s WHERE cooperation_contract_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			cooperationContract.CooperationContractId,
			cooperationContract.CooperationContractDescription,
			cooperationContract.CooperationContractName,
			cooperationContract.CooperationContractNumber,
			cooperationContract.CooperationContractReferrer,
			cooperationContract.CooperationContractSalesman,
			pg.Array(cooperationContract.CooperationContractUndertakerType),
			cooperationContract.CooperationContractSponsor,
			cooperationContract.CooperationMode.CooperationModeNumber,
			cooperationContract.Status,
			cooperationContract.Org,
			cooperationContract.Company,
			cooperationContract.Operator,
			cooperationContract.OperateTime,
			cooperationContract.CreatedAt,
			cooperationContract.DeletedAt,
			cooperationContract.UpdatedAt,
			cooperationContract.Identify(),
		); err != nil {
			return cooperationContract, err
		} else {
			//TODO 	更新相关人
			// 获取相关人列表
			var cooperationContractRelevantModels []*models.CooperationContractRelevant
			cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
			if err := cooperationContractRelevantQuery.Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).Select(); err != nil {
				return nil, err
			}
			var cooperationContractRelevantModelsUpdate []*models.CooperationContractRelevant // 待更新的相关人
			var cooperationContractRelevantModelsDelete []*models.CooperationContractRelevant // 待删除的相关人
			var cooperationContractRelevantModelsCreate []*models.CooperationContractRelevant // 待增加的相关人

			for _, cooperationContractRelevantModels := range cooperationContractRelevantModels {
				for _, cooperationContractRelevantDomain := range cooperationContract.RelevantPeople {

				}
			}

			//TODO	更新承接人
			// 获取承接人列表
			var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
			cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
			if err := cooperationContractUndertakerQuery.Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).Select(); err != nil {
				return nil, err
			}

			//TODO	更新分红激励规则
			// 获取分红激励规则列表
			var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
			dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
			if err := dividendsIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).Select(); err != nil {
				return nil, err
			}

			//TODO	更新金额激励规则
			// 获取金额激励规则列表
			var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
			moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
			if err := moneyIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).Select(); err != nil {
				return nil, err
			}
		}
	}
	return cooperationContract, nil
}
func (repository *CooperationContractRepository) Remove(cooperationContract *domain.CooperationContract) (*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	cooperationContractModel.CooperationContractId = cooperationContract.Identify().(int64)
	if _, err := tx.Model(cooperationContractModel).WherePK().Delete(); err != nil {
		return cooperationContract, err
	} else {
		//TODO 删除关联数据
	}
	return cooperationContract, nil
}
func (repository *CooperationContractRepository) FindOne(queryOptions map[string]interface{}) (*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	query := sqlbuilder.BuildQuery(tx.Model(cooperationContractModel), queryOptions)
	query.SetWhereByQueryOption("cooperation_contract.cooperation_contract_id = ?", "cooperationContractId")
	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 {
		// 获取共创模式
		cooperationModeModels := new(models.CooperationMode)
		cooperationModeQuery := tx.Model(cooperationModeModels)
		if err := cooperationModeQuery.Where("cooperation_mode_number = ?", cooperationContractModel.CooperationModeNumber).First(); err != nil {
			return nil, err
		}
		// 获取分红激励规则列表
		var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
		dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
		if err := dividendsIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
			return nil, err
		}
		// 获取金额激励规则列表
		var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
		moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
		if err := moneyIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
			return nil, err
		}
		// 获取承接人列表
		var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
		cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
		if err := cooperationContractUndertakerQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
			return nil, err
		}
		// 获取相关人列表
		var cooperationContractRelevantModels []*models.CooperationContractRelevant
		cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
		if err := cooperationContractRelevantQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
			return nil, err
		}
		return transform.TransformToCooperationContractDomainModelFromPgModels(
			cooperationContractModel,
			cooperationModeModels,
			dividendsIncentivesRuleModels,
			moneyIncentivesRuleModels,
			cooperationContractRelevantModels,
			cooperationContractUndertakerModels)
	}
}
func (repository *CooperationContractRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	cooperationContracts := make([]*domain.CooperationContract, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&cooperationContractModels), queryOptions)
	query.SetOffsetAndLimit(20)
	query.SetOrderDirect("cooperation_contract_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, cooperationContracts, err
	} else {
		for _, cooperationContractModel := range cooperationContractModels {
			// 获取共创模式
			cooperationModeModels := new(models.CooperationMode)
			cooperationModeQuery := tx.Model(cooperationModeModels)
			if err := cooperationModeQuery.Where("cooperation_mode_number = ?", cooperationContractModel.CooperationModeNumber).First(); err != nil {
				return 0, nil, err
			}
			// 获取分红激励规则列表
			var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
			dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
			if err := dividendsIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
				return 0, nil, err
			}
			// 获取金额激励规则列表
			var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
			moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
			if err := moneyIncentivesRuleQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
				return 0, nil, err
			}
			// 获取承接人列表
			var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
			cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
			if err := cooperationContractUndertakerQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
				return 0, nil, err
			}
			// 获取相关人列表
			var cooperationContractRelevantModels []*models.CooperationContractRelevant
			cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
			if err := cooperationContractRelevantQuery.Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).Select(); err != nil {
				return 0, nil, err
			}
			if cooperationContract, err := transform.TransformToCooperationContractDomainModelFromPgModels(
				cooperationContractModel,
				cooperationModeModels,
				dividendsIncentivesRuleModels,
				moneyIncentivesRuleModels,
				cooperationContractRelevantModels,
				cooperationContractUndertakerModels); err != nil {
				return 0, cooperationContracts, err
			} else {
				cooperationContracts = append(cooperationContracts, cooperationContract)
			}
		}
		return int64(count), cooperationContracts, nil
	}
}
func NewCooperationContractRepository(transactionContext *pgTransaction.TransactionContext) (*CooperationContractRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &CooperationContractRepository{
			transactionContext: transactionContext,
		}, nil
	}
}