article_repository.go 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
package repository

import (
	"context"
	"fmt"
	"strings"

	"github.com/pkg/errors"
	"github.com/tiptok/gocomm/pkg/cache"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/models"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gorm.io/gorm"
)

type ArticleRepository struct {
	*cache.CachedRepository
}

func (repository *ArticleRepository) Insert(ctx context.Context, conn transaction.Conn, dm *domain.Article) (*domain.Article, error) {
	var (
		err error
		m   = &models.Article{}
		tx  = conn.DB()
	)
	if m, err = repository.DomainModelToModel(dm); err != nil {
		return nil, err
	}
	if tx = tx.Model(m).Save(m); tx.Error != nil {
		return nil, tx.Error
	}
	dm.Id = m.Id
	return repository.ModelToDomainModel(m)

}

func (repository *ArticleRepository) Update(ctx context.Context, conn transaction.Conn, dm *domain.Article) (*domain.Article, error) {
	var (
		err error
		m   *models.Article
		tx  = conn.DB()
	)
	if m, err = repository.DomainModelToModel(dm); err != nil {
		return nil, err
	}
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Select("*").Updates(m)
		return nil, tx.Error
	}
	if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return nil, err
	}
	return repository.ModelToDomainModel(m)
}

func (repository *ArticleRepository) UpdateWithVersion(ctx context.Context, transaction transaction.Conn, dm *domain.Article) (*domain.Article, error) {
	var (
		err error
		m   *models.Article
		tx  = transaction.DB()
	)
	if m, err = repository.DomainModelToModel(dm); err != nil {
		return nil, err
	}
	oldVersion := dm.Version
	m.Version += 1
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Select("*").Where("id = ?", m.Id).Where("version = ?", oldVersion).Updates(m)
		if tx.RowsAffected == 0 {
			return nil, domain.ErrUpdateFail
		}
		return nil, tx.Error
	}
	if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return nil, err
	}
	return repository.ModelToDomainModel(m)
}

func (repository *ArticleRepository) Delete(ctx context.Context, conn transaction.Conn, dm *domain.Article) (*domain.Article, error) {
	var (
		tx = conn.DB()
		m  = &models.Article{Id: dm.Id}
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Where("id = ?", m.Id).Delete(m)
		return m, tx.Error
	}
	if _, err := repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return dm, err
	}
	return repository.ModelToDomainModel(m)
}

func (repository *ArticleRepository) FindOne(ctx context.Context, conn transaction.Conn, id int64) (*domain.Article, error) {
	var (
		err error
		tx  = conn.DB()
		m   = new(models.Article)
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Where("id = ?", id).First(m)
		if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			return nil, domain.ErrNotFound
		}
		return m, tx.Error
	}
	cacheModel := new(models.Article)
	cacheModel.Id = id
	if err = repository.QueryCache(cacheModel.CacheKeyFunc, m, queryFunc); err != nil {
		return nil, err
	}
	return repository.ModelToDomainModel(m)
}

func (repository *ArticleRepository) Find(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(&ms).Order("id desc").Where("company_id=?", companyId)
		if v, ok := queryOptions["ids"]; ok {
			tx = tx.Where("id in (?)", v)
		}
		if v, ok := queryOptions["title"]; ok && v.(string) != "" {
			tx = tx.Where("title like ?", "%"+v.(string)+"%")
		}
		if v, ok := queryOptions["beginCreatedAt"]; ok {
			tx = tx.Where("created_at >= ?", v)
		}
		if v, ok := queryOptions["endCreatedAt"]; ok {
			tx = tx.Where("created_at < ?", v)
		}
		if v, ok := queryOptions["authorId"]; ok {
			tx = tx.Where("author_id=?", v)
		}
		if v, ok := queryOptions["tags"]; ok && len(v.([]int64)) > 0 {
			values := make([]string, 0)
			for _, item := range v.([]int64) {
				values = append(values, fmt.Sprintf("%v", item))
			}
			tx = tx.Where("tags @> ?", "["+strings.Join(values, ",")+"]")
		}
		if total, tx = transaction.PaginationAndCount(ctx, tx, queryOptions, &ms); tx.Error != nil {
			return dms, tx.Error
		}
		return dms, nil
	}

	if _, err := repository.Query(queryFunc); err != nil {
		return 0, nil, err
	}

	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

// FindLatestAccessibleArticle 最新可访问的文章
func (repository *ArticleRepository) FindLatestAccessibleArticle(ctx context.Context, conn transaction.Conn,
	companyId int64, whoRead int64, lastId int64, limit int) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(&ms).
			Where("company_id=?", companyId).
			Where(fmt.Sprintf("author_id = %d or target_user=0 or who_read @>'[%d]'", whoRead, whoRead)).
			Where("show = 1")
		if lastId > 0 {
			tx.Where("id < ?", lastId)
		}
		tx.Order("id desc")
		if limit > 0 {
			tx.Limit(limit)
		}
		if total, tx = transaction.PaginationAndCount(ctx, tx, domain.NewQueryOptions().WithFindOnly(), &ms); tx.Error != nil {
			return dms, tx.Error
		}
		return dms, nil
	}

	if _, err := repository.Query(queryFunc); err != nil {
		return 0, nil, err
	}

	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

// FindAuthorsLatestArticle 作者最新的文章
func (repository *ArticleRepository) FindAuthorsLatestArticle(ctx context.Context, conn transaction.Conn,
	companyId int64, authors []int64, whoRead int64, lastId int64, limit int, queryOptions map[string]interface{}) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(&ms).
			Where("company_id=?", companyId).
			Where("author_id in (?)", authors). // 包含自己的文章
			Where(fmt.Sprintf("author_id = %d or target_user=0 or who_read @>'[%d]'", whoRead, whoRead)).
			Where("show = 1")
		if lastId > 0 {
			tx.Where("id < ?", lastId)
		}
		if v, ok := queryOptions["beginTime"]; ok {
			tx.Where("created_at >= ?", v)
		}
		if v, ok := queryOptions["endTime"]; ok {
			tx.Where("created_at < ?", v)
		}
		if v, ok := queryOptions["keywords"]; ok {
			tx.Where("title like ?", fmt.Sprintf("%%%v%%", v))
		}
		if v, ok := queryOptions["orderByHotScore"]; ok {
			tx.Order(fmt.Sprintf("(count_comment+count_love) %v", v))
		} else if v, ok := queryOptions["orderByAll"]; ok {
			tx.Order(fmt.Sprintf("id %v", v))
		} else {
			tx.Order("id desc")
		}
		if limit > 0 {
			tx.Limit(limit)
		}
		if total, tx = transaction.PaginationAndCount(ctx, tx, queryOptions, &ms); tx.Error != nil {
			return dms, tx.Error
		}
		return dms, nil
	}

	if _, err := repository.Query(queryFunc); err != nil {
		return 0, nil, err
	}

	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

// FindAuthorsLatestFirstArticle 作者最新的第一篇文章
func (repository *ArticleRepository) FindAuthorsLatestFirstArticle(ctx context.Context, conn transaction.Conn,
	companyId int64, authors []int64, whoRead int64, limit int) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(&ms).Select("max(id) id", "max(author_id) author_id", "max(created_at) created_at").
			Where("company_id=?", companyId).
			Where("author_id in (?)", authors).
			Where("target_user=0 or who_read @>? ", fmt.Sprintf("[%d]", whoRead)).
			Where("show = 1").
			Group("author_id").
			Order("id desc")
		if limit > 0 {
			tx.Limit(limit)
		}
		if total, tx = transaction.PaginationAndCount(ctx, tx, domain.NewQueryOptions().WithFindOnly(), &ms); tx.Error != nil {
			return dms, tx.Error
		}
		return dms, nil
	}

	if _, err := repository.Query(queryFunc); err != nil {
		return 0, nil, err
	}

	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

// FindAuthorsLatestFirstUnreadArticle 作者最新的第一篇未读文章
func (repository *ArticleRepository) FindAuthorsLatestFirstUnreadArticle(ctx context.Context, conn transaction.Conn,
	companyId int64, authors []int64, whoRead int64, limit int) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(&ms).Select("max(id) id", "max(author_id) author_id", "max(created_at) created_at").
			Where("company_id=?", companyId).
			Where("author_id in (?)", authors).
			Where("target_user=0 or who_read @>? ", fmt.Sprintf("[%d]", whoRead)).
			Where("show = 1").
			Where("id not in (select article_id from user_read_article where user_id = ?)", whoRead).
			Group("author_id").
			Order("id desc")
		if limit > 0 {
			tx.Limit(limit)
		}
		if total, tx = transaction.PaginationAndCount(ctx, tx, domain.NewQueryOptions().WithFindOnly(), &ms); tx.Error != nil {
			return dms, tx.Error
		}
		return dms, nil
	}

	if _, err := repository.Query(queryFunc); err != nil {
		return 0, nil, err
	}

	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

func (repository *ArticleRepository) ModelToDomainModel(from *models.Article) (*domain.Article, error) {
	to := &domain.Article{
		Id:           from.Id,
		CompanyId:    from.CompanyId,
		CreatedAt:    from.CreatedAt,
		UpdatedAt:    from.UpdatedAt,
		DeletedAt:    from.DeletedAt,
		Version:      from.Version,
		AuthorId:     from.AuthorId,
		Author:       from.Author,
		Title:        from.Title,
		Images:       from.Images,
		WhoRead:      from.WhoRead,
		WhoReview:    from.WhoReview,
		Location:     from.Location,
		TargetUser:   domain.ArticleTarget(from.TargetUser),
		CountLove:    from.CountLove,
		CountComment: from.CountComment,
		CountRead:    from.CountRead,
		Show:         domain.ArticleShow(from.Show),
		Tags:         from.Tags,
		Summary:      from.Summary,
		MatchUrl:     from.MatchUrl,
		Videos:       from.Videos,
	}
	return to, nil
}

func (repository *ArticleRepository) DomainModelToModel(from *domain.Article) (*models.Article, error) {
	to := &models.Article{
		Id:           from.Id,
		CompanyId:    from.CompanyId,
		CreatedAt:    from.CreatedAt,
		UpdatedAt:    from.UpdatedAt,
		DeletedAt:    from.DeletedAt,
		IsDel:        0,
		Version:      from.Version,
		AuthorId:     from.AuthorId,
		Author:       from.Author,
		Title:        from.Title,
		Images:       from.Images,
		WhoRead:      from.WhoRead,
		WhoReview:    from.WhoReview,
		Location:     from.Location,
		TargetUser:   int(from.TargetUser),
		CountLove:    from.CountLove,
		CountRead:    from.CountRead,
		CountComment: from.CountComment,
		Tags:         from.Tags,
		Show:         int(from.Show),
		Summary:      from.Summary,
		MatchUrl:     from.MatchUrl,
		Videos:       from.Videos,
	}
	// err := copier.Copy(to, from)
	return to, nil
}

// 点赞数量变动
func (repository *ArticleRepository) IncreaseCountLove(ctx context.Context, conn transaction.Conn, incr int, articleId int64) error {
	//
	var (
		err error
		m   *models.Article
		tx  = conn.DB()
	)
	m = &models.Article{Id: articleId}
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Updates(map[string]interface{}{
			"count_love": gorm.Expr("count_love+?", incr),
			"version":    gorm.Expr("version+1"),
		})
		return nil, tx.Error
	}
	if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return err
	}
	return nil
}

// 浏览数量变动
func (repository *ArticleRepository) IncreaseCountRead(ctx context.Context, conn transaction.Conn, incr int, articleId int64) error {
	var (
		err error
		m   *models.Article
		tx  = conn.DB()
	)
	m = &models.Article{Id: articleId}
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Updates(map[string]interface{}{
			"version":    gorm.Expr("version+1"),
			"count_read": gorm.Expr("count_read+?", incr),
		})
		return nil, tx.Error
	}
	if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return err
	}
	return nil
}

// 评论数量变动
func (repository *ArticleRepository) IncreaseCountComment(ctx context.Context, conn transaction.Conn, incr int, articleId int64) error {
	var (
		err error
		m   *models.Article
		tx  = conn.DB()
	)
	m = &models.Article{Id: articleId}
	queryFunc := func() (interface{}, error) {
		tx = tx.Model(m).Updates(map[string]interface{}{
			"version":       gorm.Expr("version+1"),
			"count_comment": gorm.Expr("count_comment+?", incr),
		})
		return nil, tx.Error
	}
	if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
		return err
	}
	return nil
}

func NewArticleRepository(cache *cache.CachedRepository) domain.ArticleRepository {
	return &ArticleRepository{CachedRepository: cache}
}

// 小程序端搜索查询文章
// userId  人员id,谁查看文章
// companyId 公司id
// tagCategory 标签分类
// tagId 标签id
// createdAt  文章的发布时间,按范围查询 [开始时间,结束时间]
// titleLike 搜索标题
func (repository *ArticleRepository) CustomSearchBy(ctx context.Context, conn transaction.Conn, userId int64, companyId int64,
	tagCategory string, tagId int64, createdAt [2]int64, titleLike string, page int, size int) (int64, []*domain.Article, error) {
	var (
		tx    = conn.DB()
		ms    []*models.Article
		dms   = make([]*domain.Article, 0)
		total int64
	)
	tx = tx.Model(&ms).
		Where(`article."show" =?`, domain.ArticleShowEnable).
		Where(`article."deleted_at" = 0`).
		Where(`article."company_id"=?`, companyId).
		Where(
			fmt.Sprintf(`(article.target_user = 0 or article.who_read @> '[%d]' )`, userId),
		)
	if createdAt[0] > 0 {
		tx = tx.Where("article.created_at >=?", createdAt[0])
	}
	if createdAt[1] > 0 {
		tx = tx.Where("article.created_at <=?", createdAt[1])
	}
	if tagId > 0 {
		tx = tx.Joins(`join article_and_tag on article.id = article_and_tag.article_id`)
		tx = tx.Where("article_and_tag.tag_id=?", tagId)
	} else if len(tagCategory) > 0 {
		tx = tx.Joins(`join article_and_tag on article.id = article_and_tag.article_id`)
		tx = tx.Where(`article_and_tag.tag_id =any(select article_tag.id from article_tag where category =? )`, tagCategory)
	}
	if len(titleLike) > 0 {
		tx = tx.Where("article.title like ?", "%"+titleLike+"%")
	}

	result := tx.Count(&total)
	if result.Error != nil {
		return 0, nil, result.Error
	}
	if size <= 0 {
		size = 20

	}
	if page <= 0 {
		page = 1
	}
	result = tx.Limit(size).Offset((page - 1) * size).Order("id desc").Find(&ms)
	if result.Error != nil {
		return 0, nil, result.Error
	}
	for _, item := range ms {
		if dm, err := repository.ModelToDomainModel(item); err != nil {
			return 0, dms, err
		} else {
			dms = append(dms, dm)
		}
	}
	return total, dms, nil
}

// select *
// from article
// join article_and_tag on article.id = article_and_tag.article_id
// where article."show" =1
// and article_and_tag.tag_id =any(select article_tag.id from article_tag where category ='分组三' )
// and article_and_tag.tag_id =0
// and article.created_at >=0 and article.created_at <=9000000000
// and article.title like '%%'