feat: add user posts

This commit is contained in:
rogeecn
2025-03-22 20:01:45 +08:00
parent 1d66f95397
commit ea6db56fb3
3 changed files with 122 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ package models
import (
"context"
"errors"
"quyun/app/requests"
"quyun/database/fields"
@@ -9,6 +10,7 @@ import (
"quyun/database/schemas/public/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/sirupsen/logrus"
)
@@ -147,3 +149,58 @@ func (m *postsModel) List(ctx context.Context, pagination *requests.Pagination,
Pagination: *pagination,
}, nil
}
func (m *postsModel) IsUserBought(ctx context.Context, userId int64, postId int64) (bool, error) {
tbl := table.UserPosts
stmt := tbl.
SELECT(tbl.ID).
WHERE(
tbl.UserID.EQ(Int64(userId)).AND(
tbl.PostID.EQ(Int64(postId)),
),
)
m.log.Infof("sql: %s", stmt.DebugSql())
var userPost model.UserPosts
err := stmt.QueryContext(ctx, db, &userPost)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return false, nil
}
m.log.Errorf("error querying user post item: %v", err)
return false, err
}
return userPost.ID > 0, nil
}
func (m *postsModel) Buy(ctx context.Context, userId int64, postId int64) error {
tbl := table.UserPosts
post, err := m.GetByID(ctx, postId)
if err != nil {
m.log.Errorf("error getting post by ID: %v", err)
return err
}
user, err := Users.GetByID(ctx, userId)
if err != nil {
m.log.Errorf("error getting user by ID: %v", err)
return err
}
record := model.UserPosts{
UserID: user.ID,
PostID: post.ID,
Price: post.Price * int64(post.Discount) / 100,
}
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(record)
m.log.Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log.Errorf("error buying post: %v", err)
return err
}
return nil
}