pg_cooperation_application_repository.go 16.3 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	"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 CooperationApplicationRepository struct {
	transactionContext *pgTransaction.TransactionContext
	IdWorker           *snowflake.IdWorker
}

func (repository *CooperationApplicationRepository) nextIdentify() (int64, error) {
	id, err := repository.IdWorker.NextId()
	return id, err
}

func (repository *CooperationApplicationRepository) Save(cooperationApplication *domain.CooperationApplication) (*domain.CooperationApplication, error) {
	sqlBuildFields := []string{
		"cooperation_application_id",
		"cooperation_application_applicant",
		"cooperation_application_attachment",
		"cooperation_application_description",
		"cooperation_application_status",
		"cooperation_application_verifier",
		"cooperation_application_verify_description",
		"cooperation_application_verify_time",
		"cooperation_apply_time",
		"cooperation_project_number",
		"org",
		"is_canceled",
		"company",
		"created_at",
		"deleted_at",
		"updated_at",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "cooperationApplication_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if cooperationApplication.Identify() == nil {
		cooperationApplicationId, err := repository.nextIdentify()
		if err != nil {
			return cooperationApplication, err
		} else {
			cooperationApplication.CooperationApplicationId = cooperationApplicationId
		}
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationApplication.CooperationApplicationId,
				&cooperationApplication.CooperationApplicationApplicant,
				&cooperationApplication.CooperationApplicationAttachment,
				&cooperationApplication.CooperationApplicationDescription,
				&cooperationApplication.CooperationApplicationStatus,
				&cooperationApplication.CooperationApplicationVerifier,
				&cooperationApplication.CooperationApplicationVerifyDescription,
				&cooperationApplication.CooperationApplicationVerifyTime,
				&cooperationApplication.CooperationApplyTime,
				&cooperationApplication.CooperationProject.CooperationProjectNumber,
				&cooperationApplication.Org,
				&cooperationApplication.IsCanceled,
				&cooperationApplication.Company,
				&cooperationApplication.CreatedAt,
				&cooperationApplication.DeletedAt,
				&cooperationApplication.UpdatedAt,
			),
			fmt.Sprintf("INSERT INTO cooperation_applications (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			cooperationApplication.CooperationApplicationId,
			cooperationApplication.CooperationApplicationApplicant,
			cooperationApplication.CooperationApplicationAttachment,
			cooperationApplication.CooperationApplicationDescription,
			cooperationApplication.CooperationApplicationStatus,
			cooperationApplication.CooperationApplicationVerifier,
			cooperationApplication.CooperationApplicationVerifyDescription,
			cooperationApplication.CooperationApplicationVerifyTime,
			cooperationApplication.CooperationApplyTime,
			cooperationApplication.CooperationProject.CooperationProjectNumber,
			cooperationApplication.Org,
			cooperationApplication.IsCanceled,
			cooperationApplication.Company,
			cooperationApplication.CreatedAt,
			nil,
			cooperationApplication.UpdatedAt,
		); err != nil {
			return cooperationApplication, err
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationApplication.CooperationApplicationId,
				&cooperationApplication.CooperationApplicationApplicant,
				&cooperationApplication.CooperationApplicationAttachment,
				&cooperationApplication.CooperationApplicationDescription,
				&cooperationApplication.CooperationApplicationStatus,
				&cooperationApplication.CooperationApplicationVerifier,
				&cooperationApplication.CooperationApplicationVerifyDescription,
				&cooperationApplication.CooperationApplicationVerifyTime,
				&cooperationApplication.CooperationApplyTime,
				&cooperationApplication.CooperationProject.CooperationProjectNumber,
				&cooperationApplication.Org,
				&cooperationApplication.IsCanceled,
				&cooperationApplication.Company,
				&cooperationApplication.CreatedAt,
				&cooperationApplication.DeletedAt,
				&cooperationApplication.UpdatedAt,
			),
			fmt.Sprintf("UPDATE cooperation_applications SET %s WHERE cooperation_application_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			cooperationApplication.CooperationApplicationId,
			cooperationApplication.CooperationApplicationApplicant,
			cooperationApplication.CooperationApplicationAttachment,
			cooperationApplication.CooperationApplicationDescription,
			cooperationApplication.CooperationApplicationStatus,
			cooperationApplication.CooperationApplicationVerifier,
			cooperationApplication.CooperationApplicationVerifyDescription,
			cooperationApplication.CooperationApplicationVerifyTime,
			cooperationApplication.CooperationApplyTime,
			cooperationApplication.CooperationProject.CooperationProjectNumber,
			cooperationApplication.Org,
			cooperationApplication.IsCanceled,
			cooperationApplication.Company,
			cooperationApplication.CreatedAt,
			nil,
			cooperationApplication.UpdatedAt,
			cooperationApplication.Identify(),
		); err != nil {
			return cooperationApplication, err
		}
	}
	return cooperationApplication, nil
}

func (repository *CooperationApplicationRepository) UpdateMany(cooperationApplications []*domain.CooperationApplication) ([]*domain.CooperationApplication, error) {
	tx := repository.transactionContext.PgTx
	var cooperationApplicationModels []*models.CooperationApplication
	for _, cooperationApplication := range cooperationApplications {
		cooperationApplicationModels = append(cooperationApplicationModels, &models.CooperationApplication{
			CooperationApplicationId:                cooperationApplication.CooperationApplicationId,
			CooperationApplicationApplicant:         cooperationApplication.CooperationApplicationApplicant,
			CooperationApplicationAttachment:        cooperationApplication.CooperationApplicationAttachment,
			CooperationApplicationDescription:       cooperationApplication.CooperationApplicationDescription,
			CooperationApplicationStatus:            cooperationApplication.CooperationApplicationStatus,
			CooperationApplicationVerifier:          cooperationApplication.CooperationApplicationVerifier,
			CooperationApplicationVerifyDescription: cooperationApplication.CooperationApplicationVerifyDescription,
			CooperationApplicationVerifyTime:        cooperationApplication.CooperationApplicationVerifyTime,
			CooperationApplyTime:                    cooperationApplication.CooperationApplyTime,
			CooperationProjectNumber:                cooperationApplication.CooperationProject.CooperationProjectNumber,
			Org:                                     cooperationApplication.Org,
			IsCanceled:                              cooperationApplication.IsCanceled,
			Company:                                 cooperationApplication.Company,
			CreatedAt:                               cooperationApplication.CreatedAt,
			DeletedAt:                               cooperationApplication.DeletedAt,
			UpdatedAt:                               time.Now(),
		})
	}
	if _, err := tx.Model(&cooperationApplicationModels).WherePK().Update(); err != nil {
		return nil, err
	}
	return cooperationApplications, nil
}

func (repository *CooperationApplicationRepository) Remove(cooperationApplication *domain.CooperationApplication) (*domain.CooperationApplication, error) {
	tx := repository.transactionContext.PgTx
	cooperationApplicationModel := new(models.CooperationApplication)
	cooperationApplicationModel.CooperationApplicationId = cooperationApplication.Identify().(int64)
	if _, err := tx.Model(cooperationApplicationModel).WherePK().Delete(); err != nil {
		return cooperationApplication, err
	}
	return cooperationApplication, nil
}

func (repository *CooperationApplicationRepository) FindOne(queryOptions map[string]interface{}) (*domain.CooperationApplication, error) {
	tx := repository.transactionContext.PgTx
	cooperationApplicationModel := new(models.CooperationApplication)
	query := sqlbuilder.BuildQuery(tx.Model(cooperationApplicationModel), queryOptions)
	query.SetWhereByQueryOption("cooperation_application.cooperation_application_id = ?", "cooperationApplicationId")
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, fmt.Errorf("共创申请不存在")
		} else {
			return nil, err
		}
	}
	if cooperationApplicationModel.CooperationApplicationId == 0 {
		return nil, nil
	} else {
		// 获取共创项目
		cooperationProjectModel := new(models.CooperationProject)
		cooperationProjectQuery := tx.Model(cooperationProjectModel)
		if err := cooperationProjectQuery.
			Where("company->>'companyId' = '?'", cooperationApplicationModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationApplicationModel.Org.OrgId).
			Where("cooperation_project_number = ?", cooperationApplicationModel.CooperationProjectNumber).First(); err != nil {
			log.Logger.Error("申请关联的共创项目不存在", map[string]interface{}{
				"cooperationApplicationModel": cooperationApplicationModel,
			})
			return nil, fmt.Errorf("申请关联的共创项目不存在")
		}
		// 获取共创模式
		cooperationModeModel := new(models.CooperationMode)
		cooperationModeQuery := tx.Model(cooperationModeModel)
		if err := cooperationModeQuery.
			Where("company->>'companyId' = '?'", cooperationApplicationModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationApplicationModel.Org.OrgId).
			Where("cooperation_mode_number = ?", cooperationProjectModel.CooperationModeNumber).First(); err != nil {
			log.Logger.Error("申请关联的共创模式不存在", map[string]interface{}{
				"cooperationApplicationModel": cooperationApplicationModel,
			})
			return nil, fmt.Errorf("申请关联的共创模式不存在")
		}
		return transform.TransformToCooperationApplicationDomainModelFromPgModels(cooperationApplicationModel, cooperationProjectModel, cooperationModeModel)
	}
}

func (repository *CooperationApplicationRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.CooperationApplication, error) {
	tx := repository.transactionContext.PgTx
	var cooperationApplicationModels []*models.CooperationApplication
	cooperationApplications := make([]*domain.CooperationApplication, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&cooperationApplicationModels), queryOptions)
	if cooperationProjectNumber, ok := queryOptions["cooperationProjectNumber"]; ok && cooperationProjectNumber != "" {
		query.Where("cooperation_project_number like ?", fmt.Sprintf("%%%s%%", cooperationProjectNumber))
	}
	if cooperationProjectNumberExact, ok := queryOptions["cooperationProjectNumberExact"]; ok && cooperationProjectNumberExact != "" {
		query.Where("cooperation_project_number = ? ", cooperationProjectNumberExact)
	}
	if cooperationProjectName, ok := queryOptions["cooperationProjectName"]; ok && cooperationProjectName != "" {
		query.Join("LEFT JOIN cooperation_projects AS a").
			JoinOn("a.cooperation_project_number = cooperation_application.cooperation_project_number").
			JoinOn("a.company->>'companyId' = cooperation_application.company->>'companyId'").
			JoinOn("a.org->>'orgId' = cooperation_application.org->>'orgId'").
			Where("a.cooperation_project_name like ?", fmt.Sprintf("%%%s%%", cooperationProjectName))
	}
	if applicantName, ok := queryOptions["applicantName"]; ok && applicantName != "" {
		query.Where(`(cooperation_application.cooperation_application_applicant->>'userName')::text LIKE ?`, fmt.Sprintf("%%%s%%", applicantName))
	}
	if cooperationApplicationStatus, ok := queryOptions["cooperationApplicationStatus"]; ok && cooperationApplicationStatus.(int32) != 0 {
		query.Where("cooperation_application_status = ?", cooperationApplicationStatus)
	}
	if cooperationApplicationIds, ok := queryOptions["cooperationApplicationIds"]; ok && len(cooperationApplicationIds.([]int64)) > 0 {
		query.Where("cooperation_application_id IN (?)", pg.In(cooperationApplicationIds))
	}
	if userBaseId, ok := queryOptions["userBaseId"]; ok && userBaseId.(int64) != 0 {
		query.Where(`(cooperation_application.cooperation_application_applicant->>'userBaseId' ='?')`, userBaseId)
	}
	if isCanceled, ok := queryOptions["isCanceled"]; ok && isCanceled.(int32) != 0 {
		if isCanceled.(int32) != 3 {
			query.Where("is_canceled = ?", isCanceled)
		}
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query.Where("cooperation_application.company->>'companyId' = '?'", companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query.Where("cooperation_application.org->>'orgId' = '?'", orgId)
	}
	if orgIds, ok := queryOptions["orgIds"]; ok && len(orgIds.([]int64)) > 0 {
		newOrgIds := utils.SliceItoa(orgIds.([]int64))
		query.Where("cooperation_application.org->>'orgId' in (?)", pg.In(newOrgIds))
	}
	offsetLimitFlag := true
	if offsetLimit, ok := queryOptions["offsetLimit"]; ok {
		offsetLimitFlag = offsetLimit.(bool)
	}
	if offsetLimitFlag {
		query.SetOffsetAndLimit(20)
	}

	query.SetOrderDirect("created_at", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, cooperationApplications, err
	} else {
		if count > 0 {
			for _, cooperationApplicationModel := range cooperationApplicationModels {
				// 获取共创项目
				var cooperationProjectModels []*models.CooperationProject
				cooperationProjectQuery := tx.Model(&cooperationProjectModels)
				if countProject, err := cooperationProjectQuery.
					Where("company->>'companyId' = '?'", cooperationApplicationModel.Company.CompanyId).
					Where("org->>'orgId' = '?'", cooperationApplicationModel.Org.OrgId).
					Where("cooperation_project_number = ?", cooperationApplicationModel.CooperationProjectNumber).
					Limit(1).
					SelectAndCount(); err != nil {
					log.Logger.Error("申请关联的共创项目不存在", map[string]interface{}{
						"cooperationApplicationModel": cooperationApplicationModel,
					})
				} else {
					if countProject > 0 {
						// 获取共创模式
						var cooperationModeModels []*models.CooperationMode
						cooperationModeQuery := tx.Model(&cooperationModeModels)
						if countMode, err := cooperationModeQuery.
							Where("company->>'companyId' = '?'", cooperationApplicationModel.Company.CompanyId).
							Where("org->>'orgId' = '?'", cooperationApplicationModel.Org.OrgId).
							Where("cooperation_mode_number = ?", cooperationProjectModels[0].CooperationModeNumber).
							Limit(1).
							SelectAndCount(); err != nil {
							log.Logger.Error("申请关联的共创模式不存在", map[string]interface{}{
								"cooperationApplicationModel": cooperationApplicationModel,
							})
						} else {
							if countMode > 0 {
								if cooperationApplication, err := transform.TransformToCooperationApplicationDomainModelFromPgModels(cooperationApplicationModel, cooperationProjectModels[0], cooperationModeModels[0]); err != nil {
									return 0, cooperationApplications, err
								} else {
									cooperationApplications = append(cooperationApplications, cooperationApplication)
								}
							}
						}
					}
				}
			}
		}
		return int64(count), cooperationApplications, nil
	}
}

func NewCooperationApplicationRepository(transactionContext *pgTransaction.TransactionContext) (*CooperationApplicationRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		idWorker, err := snowflake.NewIdWorker(1)
		if err != nil {
			return nil, err
		}
		return &CooperationApplicationRepository{
			transactionContext: transactionContext,
			IdWorker:           idWorker,
		}, nil
	}
}