pg_users_repository.go 7.2 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/linmadan/egglib-go/persistent/cache"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/constant"

	"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-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/transform"
)

type UserRepository struct {
	*cache.CachedRepository
	transactionContext *pgTransaction.TransactionContext
}

func (repository *UserRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}
func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
	sqlBuildFields := []string{
		"user_id",
		"company_id",
		"user_base_id",
		"user_type",
		"user_code",
		"organization_id",
		"department_id",
		"user_org",
		"user_role",
		"favorite_menus",
		"cooperation_info",
		"enable_status",
		"ext",
		"created_at",
		"updated_at",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id"))
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id"))
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if user.Identify() == nil {
		//userId, err := repository.nextIdentify()
		//if err != nil {
		//	return user, err
		//} else {
		//	user.UserId = userId
		//}
		if _, err := tx.QueryOne(
			pg.Scan(
				&user.UserId,
				&user.CompanyId,
				&user.UserBaseId,
				&user.UserType,
				&user.UserCode,
				&user.OrganizationId,
				&user.DepartmentId,
				&user.UserOrg,
				&user.UserRole,
				&user.FavoriteMenus,
				&user.CooperationInfo,
				&user.EnableStatus,
				&user.Ext,
				&user.CreatedAt,
				&user.UpdatedAt,
			),
			fmt.Sprintf("INSERT INTO users.\"user\" (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			//user.UserId,
			user.CompanyId,
			user.UserBaseId,
			user.UserType,
			user.UserCode,
			user.OrganizationId,
			user.DepartmentId,
			user.UserOrg,
			user.UserRole,
			user.FavoriteMenus,
			user.CooperationInfo,
			user.EnableStatus,
			user.Ext,
			user.CreatedAt,
			user.UpdatedAt,
		); err != nil {
			return user, err
		}
	} else {
		queryFunc := func() (interface{}, error) {
			if _, err := tx.QueryOne(
				pg.Scan(
					&user.UserId,
					&user.CompanyId,
					&user.UserBaseId,
					&user.UserType,
					&user.UserCode,
					&user.OrganizationId,
					&user.DepartmentId,
					&user.UserOrg,
					&user.UserRole,
					&user.FavoriteMenus,
					&user.CooperationInfo,
					&user.EnableStatus,
					&user.Ext,
					&user.CreatedAt,
					&user.UpdatedAt,
				),
				fmt.Sprintf(`UPDATE users."user" SET %s WHERE user_id=? RETURNING %s`, updateFieldsSnippet, returningFieldsSnippet),
				user.CompanyId,
				user.UserBaseId,
				user.UserType,
				user.UserCode,
				user.OrganizationId,
				user.DepartmentId,
				user.UserOrg,
				user.UserRole,
				user.FavoriteMenus,
				user.CooperationInfo,
				user.EnableStatus,
				user.Ext,
				user.CreatedAt,
				user.UpdatedAt,
				user.Identify(),
			); err != nil {
				return user, err
			}
			return user, nil
		}
		if _, err := repository.Query(queryFunc, user.CacheKeyFunc()); err != nil {
			return user, err
		}
	}
	return user, nil
}
func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
	tx := repository.transactionContext.PgTx
	userModel := new(models.User)
	userModel.UserId = user.Identify().(int64)
	queryFunc := func() (interface{}, error) {
		if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
			return user, err
		}
		return user, nil
	}
	if _, err := repository.Query(queryFunc, user.CacheKeyFunc()); err != nil {
		return user, err
	}
	return user, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
	tx := repository.transactionContext.PgTx
	userModel := new(models.User)
	queryFunc := func() (interface{}, error) {
		query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
		query.SetWhereByQueryOption("user_id = ?", "userId")
		query.SetWhereByQueryOption("company_id=?", "companyId")
		query.SetWhereByQueryOption("organization_id=?", "organizationId")
		query.SetWhereByQueryOption("user_code = ?", "userCode")
		query.SetWhereByQueryOption("user_id != ?", "notEqualUserId")
		if err := query.First(); err != nil {
			if err.Error() == "pg: no rows in result set" {
				return nil, fmt.Errorf("没有此资源")
			} else {
				return nil, err
			}
		}
		return userModel, nil
	}
	var cacheModel = &domain.User{}
	if _, ok := queryOptions["userId"]; ok {
		cacheModel.UserId = queryOptions["userId"].(int64)
	}
	if err := repository.QueryCache(cacheModel.CacheKeyFunc, userModel, queryFunc, cache.WithObjectToExpire(constant.REPOSITORY_CACHE_EXPIRE)); err != nil {
		return nil, err
	}
	if userModel.UserId == 0 {
		return nil, nil
	} else {
		return transform.TransformToUserDomainModelFromPgModels(userModel)
	}
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
	tx := repository.transactionContext.PgTx
	var userModels []*models.User
	users := make([]*domain.User, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
	query.SetWhereByQueryOption("company_id=?", "companyId")
	query.SetWhereByQueryOption("organization_id=?", "organizationId")
	if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int64)) > 0 {
		query.Where(`organization_id in (?)`, pg.In(v))
	}
	query.SetWhereByQueryOption("user_base_id=?", "userBaseId")
	query.SetWhereByQueryOption("(user_type & ?)>0", "userType")
	if v, ok := queryOptions["depName"]; ok && len(v.(string)) > 0 {
		query.Where(fmt.Sprintf(`ext->>'depName' like '%%%v%%'`, v))
	}
	if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
		query.Where(fmt.Sprintf(`ext->>'userName' like '%%%v%%'`, v))
	}
	if v, ok := queryOptions["cooperationCompany"]; ok && len(v.(string)) > 0 {
		query.Where(fmt.Sprintf(`cooperation_info->>'cooperationCompany' like '%%%v%%'`, v))
	}
	query.SetOffsetAndLimit(20)
	query.SetOrderDirect("user_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, users, err
	} else {
		for _, userModel := range userModels {
			if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
				return 0, users, err
			} else {
				users = append(users, user)
			}
		}
		return int64(count), users, nil
	}
}
func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &UserRepository{
			transactionContext: transactionContext,
			CachedRepository:   cache.NewDefaultCachedRepository(),
		}, nil
	}
}