package repository import ( "context" "errors" "git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/mmorpg/service-common/utils" "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/model" "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/query" "gorm.io/gorm" ) type PointRecordsDao struct { ctx context.Context query *query.Query cache *redis.CacheClient } func NewPointRecordsDao(ctx context.Context, query *query.Query, cache ...*redis.CacheClient) *PointRecordsDao { dao := &PointRecordsDao{ ctx: ctx, query: query, } if len(cache) > 0 { dao.cache = cache[0] } return dao } func (d *PointRecordsDao) CreateAndIncrPointCard(pointRecord *model.PointRecord) error { return d.query.Transaction(func(tx *query.Query) error { if err := tx.PointRecord.WithContext(d.ctx). Create(pointRecord); err != nil { return err } pcd := NewPointCardDao(d.ctx, tx) if _, err := pcd.FindPointByUserSn(pointRecord.UserSn); err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { _, err = pcd.Create(&model.PointCard{ UserSn: pointRecord.UserSn, Point: pointRecord.Point, }) if err != nil { return utils.ErrorsWrap(err) } } else { return utils.ErrorsWrap(err) } } else { if err = pcd.IncrPointCard(pointRecord.UserSn, pointRecord.Point); err != nil { return utils.ErrorsWrap(err) } } return nil }) } func (d *PointRecordsDao) FindByUSN(usn int64, page, pageSize int) ([]*model.PointRecord, int64, error) { result := make([]*model.PointRecord, 0) count, err := d.query.PointRecord.WithContext(d.ctx). Select( d.query.PointRecord.Source, d.query.PointRecord.Point, d.query.PointRecord.CreatedAt, ). Where(d.query.PointRecord.UserSn.Eq(usn)). Order(d.query.PointRecord.CreatedAt.Desc()). ScanByPage(&result, (page-1)*pageSize, pageSize) if err != nil { return nil, 0, err } return result, count, nil }