Files
quyun/backend/app/models/users.go
2025-04-29 11:24:54 +08:00

346 lines
7.8 KiB
Go

package models
import (
"context"
"errors"
"time"
"quyun/app/requests"
"quyun/database/schemas/public/model"
"quyun/database/schemas/public/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
)
// @provider
type usersModel struct {
log *logrus.Entry `inject:"false"`
}
func (m *usersModel) Prepare() error {
m.log = logrus.WithField("model", "usersModel")
return nil
}
// GetByID
func (m *usersModel) GetByID(ctx context.Context, id int64) (*model.Users, error) {
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log.Infof("sql: %s", stmt.DebugSql())
var user model.Users
err := stmt.QueryContext(ctx, db, &user)
if err != nil {
m.log.Errorf("error querying user by ID: %v", err)
return nil, err
}
return &user, nil
}
func (m *usersModel) Own(ctx context.Context, userID, postID int64) error {
tbl := table.UserPosts
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(&model.UserPosts{
UserID: userID,
PostID: postID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
m.log.Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log.Errorf("error inserting user post: %v", err)
return err
}
m.log.Infof("user post inserted successfully: userID=%d, postID=%d", userID, postID)
return nil
}
// BuildConditionWithKey builds the WHERE clause for user queries
func (m *usersModel) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Users
cond := tbl.DeletedAt.IS_NULL()
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Username.LIKE(String("%" + *key + "%")),
)
return cond
}
// countByCondition counts users matching the given condition
func (m *usersModel) countByCondition(ctx context.Context, expr BoolExpression) (int64, error) {
var cnt struct {
Cnt int64
}
tbl := table.Users
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 users: %v", err)
return 0, err
}
return cnt.Cnt, nil
}
// List returns a paginated list of users
func (m *usersModel) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression) (*requests.Pager, error) {
pagination.Format()
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log.Infof("sql: %s", stmt.DebugSql())
var users []model.Users = make([]model.Users, 0)
err := stmt.QueryContext(ctx, db, &users)
if err != nil {
m.log.Errorf("error querying users: %v", err)
return nil, err
}
count, err := m.countByCondition(ctx, cond)
if err != nil {
m.log.Errorf("error getting user count: %v", err)
return nil, err
}
return &requests.Pager{
Items: users,
Total: count,
Pagination: *pagination,
}, nil
}
// Create creates a new user
func (m *usersModel) Create(ctx context.Context, model *model.Users) error {
model.CreatedAt = time.Now()
model.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.INSERT(tbl.MutableColumns).MODEL(model)
m.log.Infof("sql: %s", stmt.DebugSql())
_, err := stmt.ExecContext(ctx, db)
if err != nil {
m.log.Errorf("error creating user: %v", err)
return err
}
return nil
}
// Update updates an existing user
func (m *usersModel) Update(ctx context.Context, id int64, model *model.Users) error {
model.UpdatedAt = time.Now()
tbl := table.Users
stmt := tbl.UPDATE(tbl.MutableColumns.Except(tbl.CreatedAt, tbl.DeletedAt)).MODEL(model).WHERE(tbl.ID.EQ(Int64(id)))
m.log.Infof("sql: %s", stmt.DebugSql())
_, err := stmt.ExecContext(ctx, db)
if err != nil {
m.log.Errorf("error updating user: %v", err)
return err
}
return nil
}
// DeleteByID soft deletes a user by ID
func (m *usersModel) DeleteByID(ctx context.Context, id int64) error {
tbl := table.Users
stmt := tbl.
UPDATE(tbl.DeletedAt).
SET(TimestampT(time.Now())).
WHERE(
tbl.ID.EQ(Int64(id)),
)
m.log.Infof("sql: %s", stmt.DebugSql())
if _, err := stmt.ExecContext(ctx, db); err != nil {
m.log.Errorf("error deleting user: %v", err)
return err
}
return nil
}
// PostList returns a paginated list of posts for a user
func (m *usersModel) PostList(ctx context.Context, userId int64, pagination *requests.Pagination, cond BoolExpression, callbacks ...func(model.Posts) model.Posts) (*requests.Pager, error) {
pagination.Format()
tblUserPosts := table.UserPosts
cond = cond.AND(
tblUserPosts.UserID.EQ(Int64(userId)),
)
tbl := table.Posts
stmt := SELECT(tbl.AllColumns).
FROM(tbl.
RIGHT_JOIN(
tblUserPosts,
tblUserPosts.PostID.EQ(tbl.ID),
),
).
WHERE(cond).
ORDER_BY(tblUserPosts.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
m.log.Infof("sql: %s", stmt.DebugSql())
var posts []model.Posts
err := stmt.QueryContext(ctx, db, &posts)
if err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return &requests.Pager{
Items: nil,
Total: 0,
Pagination: *pagination,
}, nil
}
m.log.Errorf("error querying posts: %v", err)
return nil, err
}
// total count
var cnt struct {
Cnt int64
}
stmtCnt := tblUserPosts.SELECT(COUNT(tblUserPosts.ID).AS("cnt")).WHERE(tblUserPosts.UserID.EQ(Int64(userId)))
m.log.Infof("sql: %s", stmtCnt.DebugSql())
if err := stmtCnt.QueryContext(ctx, db, &cnt); err != nil {
m.log.Errorf("error counting users: %v", err)
return nil, err
}
if len(callbacks) > 0 {
for _, f := range callbacks {
posts = lo.Map(posts, func(item model.Posts, _ int) model.Posts {
return f(item)
})
}
}
return &requests.Pager{
Items: posts,
Total: cnt.Cnt,
Pagination: *pagination,
}, nil
}
// GetUserIDByOpenID
func (m *usersModel) GetUserByOpenID(ctx context.Context, openID string) (*model.Users, error) {
tbl := table.Users
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.OpenID.EQ(String(openID)),
)
m.log.Infof("sql: %s", stmt.DebugSql())
var user model.Users
if err := stmt.QueryContext(ctx, db, &user); err != nil {
m.log.Errorf("error querying user by OpenID: %v", err)
return nil, err
}
return &user, nil
}
// GetUsersMapByIDs
func (m *usersModel) GetUsersMapByIDs(ctx context.Context, ids []int64) (map[int64]model.Users, error) {
if len(ids) == 0 {
return nil, nil
}
tbl := table.Users
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 users []model.Users = make([]model.Users, 0)
err := stmt.QueryContext(ctx, db, &users)
if err != nil {
m.log.Errorf("error querying users: %v", err)
return nil, err
}
return lo.SliceToMap(users, func(item model.Users) (int64, model.Users) {
return item.ID, item
}), nil
}
// HasBought
func (m *usersModel) HasBought(ctx context.Context, userID, 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
if err := stmt.QueryContext(ctx, db, &userPost); err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return false, nil
}
m.log.Errorf("error querying user post: %v", err)
return false, err
}
return userPost.ID > 0, nil
}
// Count
func (m *usersModel) Count(ctx context.Context, cond BoolExpression) (int64, error) {
tbl := table.Users
stmt := tbl.
SELECT(COUNT(tbl.ID).AS("cnt")).
WHERE(cond)
m.log.Infof("sql: %s", stmt.DebugSql())
var cnt struct {
Cnt int64
}
if err := stmt.QueryContext(ctx, db, &cnt); err != nil {
m.log.Errorf("error counting users: %v", err)
return 0, err
}
return cnt.Cnt, nil
}