pg_cooperation_application_repository.go 12.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 CooperationApplicationRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *CooperationApplicationRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := 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("cooperation_project_number = ?", cooperationApplicationModel.CooperationProjectNumber).First(); err != nil {
			return nil, err
		}
		return transform.TransformToCooperationApplicationDomainModelFromPgModels(cooperationApplicationModel, cooperationProjectModel)
	}
}

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 cooperationProjectName, ok := queryOptions["cooperationProjectName"]; ok && cooperationProjectName != "" {
		query.Join("LEFT JOIN cooperation_projects AS a").
			JoinOn("a.cooperation_project_number = cooperation_application.cooperation_project_number").
			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)
	}
	offsetLimitFlag := true
	if offsetLimit, ok := queryOptions["offsetLimit"]; ok {
		offsetLimitFlag = offsetLimit.(bool)
	}
	if offsetLimitFlag {
		query.SetOffsetAndLimit(20)
	}
	query.SetOrderDirect("cooperation_application_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, cooperationApplications, err
	} else {
		for _, cooperationApplicationModel := range cooperationApplicationModels {
			// 获取共创项目
			cooperationProjectModel := new(models.CooperationProject)
			cooperationProjectQuery := tx.Model(cooperationProjectModel)
			if err := cooperationProjectQuery.Where("cooperation_project_number = ?", cooperationApplicationModel.CooperationProjectNumber).First(); err != nil {
				return 0, nil, err
			}
			if cooperationApplication, err := transform.TransformToCooperationApplicationDomainModelFromPgModels(cooperationApplicationModel, cooperationProjectModel); 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 {
		return &CooperationApplicationRepository{
			transactionContext: transactionContext,
		}, nil
	}
}