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

300 lines
7.0 KiB
Go

package model
import (
"context"
"time"
"quyun/app/requests"
"quyun/database/fields"
"quyun/database/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/samber/lo"
)
var postsUpdateExcludeColumns = []Column{
table.Posts.CreatedAt,
table.Posts.DeletedAt,
table.Posts.Views,
table.Posts.Likes,
}
func (m *Posts) Update(ctx context.Context) error {
m.UpdatedAt = time.Now()
stmt := table.Posts.UPDATE(table.Posts.MutableColumns.Except(table.Posts.CreatedAt, table.Posts.DeletedAt, table.Posts.Views, table.Posts.Likes)).SET(m).WHERE(table.Posts.ID.EQ(Int(m.ID))).RETURNING(table.Posts.AllColumns)
m.log().WithField("func", "Update").Info(stmt.DebugSql())
if err := stmt.QueryContext(ctx, db, m); err != nil {
m.log().WithField("func", "Update").Errorf("error updating Posts item: %v", err)
return err
}
m.log().WithField("func", "Update").Infof("Posts item updated successfully")
return nil
}
func (m *Posts) CondStatus(s fields.PostStatus) Cond {
return func(cond BoolExpression) BoolExpression {
return cond.AND(table.Posts.Status.EQ(Int(int64(s))))
}
}
func (m *Posts) CondLike(key *string) Cond {
return func(cond BoolExpression) BoolExpression {
tbl := table.Posts
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Title.LIKE(String("%" + *key + "%")).
OR(
tbl.Content.LIKE(String("%" + *key + "%")),
).
OR(
tbl.Description.LIKE(String("%" + *key + "%")),
),
)
return cond
}
}
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
}
// 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, conds ...Cond) (*requests.Pager, error) {
pagination.Format()
cond := CondJoin(m.CondNotDeleted(), conds...)
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(CondTrue(cond...)).
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.Count(ctx, CondJoin(m.CondNotDeleted(), conds...)...)
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
}
// 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
}
func (m *Posts) PayPrice() int64 {
return m.Price * int64(m.Discount) / 100
}