Files
quyun/backend/app/model/posts.go
2025-05-23 21:21:12 +08:00

352 lines
7.8 KiB
Go

package model
import (
"context"
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
)
func (m *Posts) log() *log.Entry {
return log.WithField("model", "PostsModel")
}
func (m *Posts) IncrViewCount(ctx context.Context) error {
tbl := table.Posts
stmt := tbl.UPDATE(tbl.Views).SET(tbl.Views.ADD(Int64(1))).WHERE(tbl.ID.EQ(Int64(m.ID)))
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
m.log().Errorf("error updating post view count: %v", err)
return err
}
return nil
}
// GetByID
func (m *Posts) GetByID(ctx context.Context, id int64, cond ...conds.Cond) (*Posts, error) {
tbl := table.Posts
var combinedCond BoolExpression = tbl.ID.EQ(Int64(id))
for _, c := range cond {
combinedCond = c(combinedCond)
}
stmt := tbl.SELECT(tbl.AllColumns).WHERE(combinedCond)
m.log().Infof("sql: %s", stmt.DebugSql())
var post Posts
err := stmt.QueryContext(ctx, db, &post)
if err != nil {
m.log().Errorf("error getting post: %v", err)
return nil, err
}
return &post, nil
}
// Create
func (m *Posts) Create(ctx context.Context) error {
m.CreatedAt = time.Now()
m.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(m).RETURNING(tbl.AllColumns)
m.log().Infof("sql: %s", stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().Errorf("error creating post: %v", err)
return err
}
return nil
}
// Update
func (m *Posts) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
tbl := table.Posts
stmt := tbl.
UPDATE(
tbl.MutableColumns.Except(
tbl.CreatedAt,
tbl.DeletedAt,
tbl.Views,
tbl.Likes,
),
).
MODEL(m).
WHERE(tbl.ID.EQ(Int64(m.ID)))
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error updating post: %v", err)
return err
}
return nil
}
// countByCond
func (m *Posts) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Posts
stmt := SELECT(COUNT(tbl.ID).AS("cnt")).FROM(tbl).WHERE(expr)
m.log().Infof("sql: %s", stmt.DebugSql())
err := stmt.QueryContext(ctx, db, &cnt)
if err != nil {
m.log().Errorf("error counting post items: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
func (m *Posts) List(ctx context.Context, pagination *requests.Pagination, cond ...conds.Cond) (*requests.Pager, error) {
pagination.Format()
combinedCond := table.Posts.DeletedAt.IS_NULL()
for _, c := range cond {
combinedCond = c(combinedCond)
}
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(combinedCond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var posts []Posts = make([]Posts, 0)
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
m.log().Errorf("error querying post items: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, combinedCond)
if err != nil {
m.log().Errorf("error getting post count: %v", err)
return nil, err
}
return &requests.Pager{
Items: posts,
Total: count,
Pagination: *pagination,
}, nil
}
// DeleteByID soft delete item
func (m *Posts) Delete(ctx context.Context) error {
tbl := table.Posts
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(m.ID)),
)
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error deleting post: %v", err)
return err
}
return nil
}
// SendTo
func (m *Posts) SendTo(ctx context.Context, userId int64) error {
// add record to user_posts
tbl := table.UserPosts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(UserPosts{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
UserID: userId,
PostID: m.ID,
Price: -1,
})
m.log().Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log().Errorf("error sending post to user: %v", err)
return err
}
return nil
}
// PostBoughtStatistics 获取指定文件 ID 的购买次数
func (m *Posts) BoughtStatistics(ctx context.Context, postIds []int64) (map[int64]int64, error) {
tbl := table.UserPosts
// select count(user_id), post_id from user_posts up where post_id in (1, 2,3,4,5,6,7,8,9,10) group by post_id
stmt := tbl.
SELECT(
COUNT(tbl.UserID).AS("cnt"),
tbl.PostID.AS("post_id"),
).
WHERE(
tbl.PostID.IN(lo.Map(postIds, func(id int64, _ int) Expression { return Int64(id) })...),
).
GROUP_BY(
tbl.PostID,
)
m.log().Infof("sql: %s", stmt.DebugSql())
var result []struct {
Cnt int64
PostId int64
}
if err := stmt.QueryContext(ctx, db, &result); err != nil {
m.log().Errorf("error getting post bought statistics: %v", err)
return nil, err
}
// convert to map
resultMap := make(map[int64]int64)
for _, item := range result {
resultMap[item.PostId] = item.Cnt
}
return resultMap, nil
}
// Bought
func (m *Posts) Bought(ctx context.Context, userId int64, pagination *requests.Pagination) (*requests.Pager, error) {
pagination.Format()
// select up.price,up.created_at,p.* from user_posts up left join posts p on up.post_id = p.id where up.user_id =1
tbl := table.UserPosts
stmt := tbl.
SELECT(
tbl.Price.AS("price"),
tbl.CreatedAt.AS("bought_at"),
table.Posts.Title.AS("title"),
).
FROM(
tbl.INNER_JOIN(table.Posts, table.Posts.ID.EQ(tbl.PostID)),
).
WHERE(
tbl.UserID.EQ(Int64(userId)),
).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log().Infof("sql: %s", stmt.DebugSql())
var items []struct {
Title string `json:"title"`
Price int64 `json:"price"`
BoughtAt time.Time `json:"bought_at"`
}
if err := stmt.QueryContext(ctx, db, &items); err != nil {
m.log().Errorf("error getting bought posts: %v", err)
return nil, err
}
// convert to Posts
var cnt struct {
Cnt int64
}
stmtCnt := tbl.
SELECT(COUNT(tbl.ID).AS("cnt")).
WHERE(
tbl.UserID.EQ(Int64(userId)),
)
if err := stmtCnt.QueryContext(ctx, db, &cnt); err != nil {
m.log().Errorf("error getting bought posts count: %v", err)
return nil, err
}
return &requests.Pager{
Items: items,
Total: cnt.Cnt,
Pagination: *pagination,
}, nil
}
// GetPostsMapByIDs
func (m *Posts) GetPostsMapByIDs(ctx context.Context, ids []int64) (map[int64]Posts, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var posts []Posts = make([]Posts, 0)
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
m.log().Errorf("error querying posts: %v", err)
return nil, err
}
return lo.SliceToMap(posts, func(item Posts) (int64, Posts) {
return item.ID, item
}), nil
}
// GetMediaByIds
func (m *Posts) GetMediaByIds(ctx context.Context, ids []int64) ([]Medias, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Medias
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.IN(lo.Map(ids, func(id int64, _ int) Expression { return Int64(id) })...),
)
m.log().Infof("sql: %s", stmt.DebugSql())
var medias []Medias
if err := stmt.QueryContext(ctx, db, &medias); err != nil {
m.log().Errorf("error querying media: %v", err)
return nil, err
}
return medias, nil
}
// Count
func (m *Posts) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Posts
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("count")).
WHERE(cond)
var count struct {
Count int64
}
if err := stmt.QueryContext(ctx, db, &count); err != nil {
m.log().Errorf("error counting posts: %v", err)
return 0, err
}
return count.Count, nil
}