From 18808200c20e84b71c34d4a593d0bccf846d8068 Mon Sep 17 00:00:00 2001 From: Rogee Date: Fri, 23 May 2025 20:49:10 +0800 Subject: [PATCH] feat: update models --- backend/app/http/admin/orders.go | 9 ++- backend/app/http/admin/users.go | 6 +- backend/app/http/posts.go | 8 +- backend/app/http/users.go | 2 +- backend/app/http/wechats.go | 2 +- backend/app/jobs/balance_pay_notify.go | 4 +- backend/app/jobs/demo_cron.go | 3 +- backend/app/jobs/remove_file.go | 2 +- backend/app/jobs/video_extract_head_image.go | 6 +- backend/app/jobs/video_store_short.go | 2 +- backend/app/jobs/wechat_pay_notify.go | 4 +- backend/app/jobs/wechat_refund_notify.go | 8 +- backend/app/model/users.go | 85 ++++++++------------ backend/go.mod | 1 - 14 files changed, 69 insertions(+), 73 deletions(-) diff --git a/backend/app/http/admin/orders.go b/backend/app/http/admin/orders.go index 38f91cd..e464141 100644 --- a/backend/app/http/admin/orders.go +++ b/backend/app/http/admin/orders.go @@ -41,17 +41,22 @@ func (ctl *orders) Refund(ctx fiber.Ctx, id int64) error { return err } + user, err := model.UsersModel.GetByID(ctx.Context(), order.UserID) + if err != nil { + return err + } + post, err := model.PostsModel.GetByID(ctx.Context(), order.PostID) if err != nil { return err } if order.PaymentMethod == "balance" { - if err := model.UsersModel.AddBalance(ctx.Context(), order.UserID, order.Meta.Data.CostBalance); err != nil { + if err := user.AddBalance(ctx.Context(), order.Meta.Data.CostBalance); err != nil { return errors.Wrap(err, "add balance failed") } - if err := model.UsersModel.RevokePosts(ctx.Context(), order.UserID, order.PostID); err != nil { + if err := user.RevokePosts(ctx.Context(), order.PostID); err != nil { return errors.Wrap(err, "revoke posts failed") } diff --git a/backend/app/http/admin/users.go b/backend/app/http/admin/users.go index df98dbe..437ad81 100644 --- a/backend/app/http/admin/users.go +++ b/backend/app/http/admin/users.go @@ -51,5 +51,9 @@ type UserBalance struct { // @Bind id path // @Bind balance body func (ctl *users) Balance(ctx fiber.Ctx, id int64, balance *UserBalance) error { - return model.UsersModel.AddBalance(ctx.Context(), id, balance.Balance) + user, err := model.UsersModel.GetByID(ctx.Context(), id) + if err != nil { + return err + } + return user.SetBalance(ctx.Context(), balance.Balance) } diff --git a/backend/app/http/posts.go b/backend/app/http/posts.go index b08eda7..832b872 100644 --- a/backend/app/http/posts.go +++ b/backend/app/http/posts.go @@ -53,7 +53,7 @@ func (ctl *posts) List(ctx fiber.Ctx, pagination *requests.Pagination, query *Li postIds := lo.Map(pager.Items.([]model.Posts), func(item model.Posts, _ int) int64 { return item.ID }) if len(postIds) > 0 { - userBoughtIds, err := model.UsersModel.BatchCheckHasBought(ctx.Context(), user.ID, postIds) + userBoughtIds, err := user.BatchCheckHasBought(ctx.Context(), postIds) if err != nil { log.WithError(err).Errorf("BatchCheckHasBought err: %v", err) } @@ -124,7 +124,7 @@ func (ctl *posts) Show(ctx fiber.Ctx, id int64, user *model.Users) (*PostItem, e return nil, err } - bought, err := model.UsersModel.HasBought(ctx.Context(), user.ID, post.ID) + bought, err := user.HasBought(ctx.Context(), post.ID) if err != nil { return nil, err } @@ -173,7 +173,7 @@ func (ctl *posts) Play(ctx fiber.Ctx, id int64, user *model.Users) (*PlayUrl, er // }, nil preview := false - bought, err := model.UsersModel.HasBought(ctx.Context(), user.ID, id) + bought, err := user.HasBought(ctx.Context(), id) if !bought || err != nil { preview = true } @@ -270,7 +270,7 @@ func (ctl *posts) Mine(ctx fiber.Ctx, pagination *requests.Pagination, query *Li // @Bind id path // @Bind user local func (ctl *posts) Buy(ctx fiber.Ctx, id int64, user *model.Users) (*wechat.JSAPIPayParams, error) { - bought, err := model.UsersModel.HasBought(ctx.Context(), user.ID, id) + bought, err := user.HasBought(ctx.Context(), id) if err != nil { return nil, errors.New("查询购买失败") } diff --git a/backend/app/http/users.go b/backend/app/http/users.go index 926526c..991f309 100644 --- a/backend/app/http/users.go +++ b/backend/app/http/users.go @@ -51,7 +51,7 @@ func (ctl *users) Update(ctx fiber.Ctx, user *model.Users, form *ProfileForm) er return fiber.NewError(fiber.StatusBadRequest, "Username cannot be empty") } - if err := model.UsersModel.UpdateUsername(ctx.Context(), user.ID, username); err != nil { + if err := user.SetUsername(ctx.Context(), username); err != nil { return err } return nil diff --git a/backend/app/http/wechats.go b/backend/app/http/wechats.go index 01f8ebf..bf374d4 100644 --- a/backend/app/http/wechats.go +++ b/backend/app/http/wechats.go @@ -40,7 +40,7 @@ func (ctl *wechats) GetJsSDK(ctx fiber.Ctx, url string, user *model.Users) (*wec oldToken.StableAccessToken = stableToken.AccessToken oldToken.StableExpiresAt = time.Now().Add(time.Second * time.Duration(stableToken.ExpiresIn)) - if err := model.UsersModel.UpdateUserToken(ctx.Context(), user.ID, oldToken); err != nil { + if err := user.UpdateUserToken(ctx.Context(), oldToken); err != nil { return nil, err } user.AuthToken.Data = oldToken diff --git a/backend/app/jobs/balance_pay_notify.go b/backend/app/jobs/balance_pay_notify.go index 53fea12..822f480 100644 --- a/backend/app/jobs/balance_pay_notify.go +++ b/backend/app/jobs/balance_pay_notify.go @@ -82,13 +82,13 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo defer tx.Rollback() // update user balance - err = model.UsersModel.SetBalance(ctx, user.ID, user.Balance-payPrice) + err = user.SetBalance(ctx, user.Balance-payPrice) if err != nil { log.WithError(err).Error("SetBalance error") return JobCancel(errors.Wrap(err, "set user balance failed")) } - if err := model.UsersModel.BuyPosts(context.Background(), order.UserID, order.PostID, order.Price); err != nil { + if err := user.BuyPosts(context.Background(), order.PostID, order.Price); err != nil { log.Errorf("BuyPosts error:%v", err) return errors.Wrap(err, "BuyPosts error") } diff --git a/backend/app/jobs/demo_cron.go b/backend/app/jobs/demo_cron.go index 1240493..55a2436 100644 --- a/backend/app/jobs/demo_cron.go +++ b/backend/app/jobs/demo_cron.go @@ -4,7 +4,6 @@ import ( "time" . "github.com/riverqueue/river" - "github.com/sirupsen/logrus" _ "go.ipao.vip/atom" "go.ipao.vip/atom/contracts" ) @@ -13,7 +12,7 @@ var _ contracts.CronJob = (*CronJob)(nil) // @provider(cronjob) type CronJob struct { - log *logrus.Entry `inject:"false"` + // log *logrus.Entry `inject:"false"` } // Prepare implements contracts.CronJob. diff --git a/backend/app/jobs/remove_file.go b/backend/app/jobs/remove_file.go index ab4c658..5e1ff6a 100644 --- a/backend/app/jobs/remove_file.go +++ b/backend/app/jobs/remove_file.go @@ -47,7 +47,7 @@ func (w *RemoveFileWorker) Work(ctx context.Context, job *Job[RemoveFile]) error // Check if the file exists if _, err := os.Stat(job.Args.FilePath); os.IsNotExist(err) { - log.Warn("File does not exist: %v", job.Args.FilePath) + log.Warnf("File does not exist: %v", job.Args.FilePath) return nil } // Remove the file diff --git a/backend/app/jobs/video_extract_head_image.go b/backend/app/jobs/video_extract_head_image.go index 813df34..bae54e5 100644 --- a/backend/app/jobs/video_extract_head_image.go +++ b/backend/app/jobs/video_extract_head_image.go @@ -106,7 +106,7 @@ func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoEx return errors.Wrap(err, "failed to upload image to OSS") } - if w.job.Add(&RemoveFile{FilePath: output}); err != nil { + if err := w.job.Add(&RemoveFile{FilePath: output}); err != nil { log.Errorf("Error removing original file: %v", err) } @@ -116,11 +116,11 @@ func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoEx } dst := filepath.Join(w.app.StoragePath, media.Path) - if w.job.Add(&RemoveFile{FilePath: dst}); err != nil { + if err := w.job.Add(&RemoveFile{FilePath: dst}); err != nil { log.Errorf("Error removing original file: %v", err) } - if w.job.Add(&PublishDraftPosts{MediaHash: media.Hash}); err != nil { + if err := w.job.Add(&PublishDraftPosts{MediaHash: media.Hash}); err != nil { log.Errorf("Error adding job: %v", err) return errors.Wrap(err, "failed to add job") } diff --git a/backend/app/jobs/video_store_short.go b/backend/app/jobs/video_store_short.go index 300a6d5..2af5421 100644 --- a/backend/app/jobs/video_store_short.go +++ b/backend/app/jobs/video_store_short.go @@ -119,7 +119,7 @@ func (w *VideoStoreShortWorker) Work(ctx context.Context, job *Job[VideoStoreSho log.Infof("Media record created with path: %s and hash: %s", filePath, fileMd5) log.Infof("pending remove local storage file %s", job.Args.FilePath) - if w.job.Add(&RemoveFile{FilePath: job.Args.FilePath}); err != nil { + if err := w.job.Add(&RemoveFile{FilePath: job.Args.FilePath}); err != nil { log.Errorf("Error removing original file: %v", err) } diff --git a/backend/app/jobs/wechat_pay_notify.go b/backend/app/jobs/wechat_pay_notify.go index 857b896..c973142 100644 --- a/backend/app/jobs/wechat_pay_notify.go +++ b/backend/app/jobs/wechat_pay_notify.go @@ -92,13 +92,13 @@ func (w *WechatPayNotifyWorker) Work(ctx context.Context, job *Job[WechatPayNoti defer tx.Rollback() // update user balance - err = model.UsersModel.SetBalance(ctx, user.ID, user.Balance-meta.CostBalance) + err = user.SetBalance(ctx, user.Balance-meta.CostBalance) if err != nil { log.WithError(err).Error("SetBalance error") return JobCancel(errors.Wrap(err, "set user balance failed")) } - if err := model.UsersModel.BuyPosts(context.Background(), order.UserID, order.PostID, order.Price); err != nil { + if err := user.BuyPosts(context.Background(), order.PostID, order.Price); err != nil { log.Errorf("BuyPosts error:%v", err) return errors.Wrap(err, "BuyPosts error") } diff --git a/backend/app/jobs/wechat_refund_notify.go b/backend/app/jobs/wechat_refund_notify.go index 7fa377f..d40b4e9 100644 --- a/backend/app/jobs/wechat_refund_notify.go +++ b/backend/app/jobs/wechat_refund_notify.go @@ -53,6 +53,12 @@ func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefu return err } + user, err := model.UsersModel.GetByID(context.Background(), order.UserID) + if err != nil { + log.Errorf("GetByID error:%v", err) + return err + } + meta := order.Meta.Data meta.RefundNotify = notify order.Status = fields.OrderStatusRefundProcessing @@ -76,7 +82,7 @@ func (w *WechatRefundNotifyWorker) Work(ctx context.Context, job *Job[WechatRefu defer tx.Rollback() if order.Status == fields.OrderStatusRefundSuccess { - if err := model.UsersModel.RevokePosts(context.Background(), order.UserID, order.PostID); err != nil { + if err := user.RevokePosts(context.Background(), order.PostID); err != nil { log.Errorf("RevokePosts error:%v", err) return errors.Wrap(err, "RevokePosts error") } diff --git a/backend/app/model/users.go b/backend/app/model/users.go index d0a8392..69f566c 100644 --- a/backend/app/model/users.go +++ b/backend/app/model/users.go @@ -27,13 +27,12 @@ func (m *Users) GetByID(ctx context.Context, id int64) (*Users, error) { stmt := tbl. SELECT(tbl.AllColumns). WHERE( - tbl.ID.EQ(Int64(id)), + tbl.ID.EQ(Int64(m.ID)), ) m.log().Infof("sql: %s", stmt.DebugSql()) var user Users - err := stmt.QueryContext(ctx, db, &user) - if err != nil { + if err := stmt.QueryContext(ctx, db, &user); err != nil { m.log().Errorf("error querying user by ID: %v", err) return nil, err } @@ -41,25 +40,6 @@ func (m *Users) GetByID(ctx context.Context, id int64) (*Users, error) { return &user, nil } -func (m *Users) Own(ctx context.Context, userID, postID int64) error { - tbl := table.UserPosts - stmt := tbl.INSERT(tbl.MutableColumns).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 *Users) BuildConditionWithKey(key *string) BoolExpression { tbl := table.Users @@ -148,29 +128,30 @@ func (m *Users) Create(ctx context.Context, userModel *Users) (*Users, error) { } // Update updates an existing user -func (m *Users) Update(ctx context.Context, id int64, userModel *Users) (*Users, error) { - userModel.UpdatedAt = time.Now() +func (m *Users) Update(ctx context.Context) (*Users, error) { + m.UpdatedAt = time.Now() tbl := table.Users stmt := tbl. UPDATE( tbl.MutableColumns.Except( + tbl.OpenID, tbl.Balance, tbl.CreatedAt, tbl.DeletedAt, ), ). - MODEL(userModel). - WHERE(tbl.ID.EQ(Int64(id))). + MODEL(m). + WHERE(tbl.ID.EQ(Int64(m.ID))). RETURNING(tbl.AllColumns) m.log().Infof("sql: %s", stmt.DebugSql()) - var updatedUser Users - if err := stmt.QueryContext(ctx, db, &updatedUser); err != nil { + var user Users + if err := stmt.QueryContext(ctx, db, &user); err != nil { m.log().Errorf("error updating user: %v", err) return nil, err } - return &updatedUser, nil + return &user, nil } // DeleteByID soft deletes a user by ID @@ -283,12 +264,14 @@ func (m *Users) GetUserByOpenIDOrCreate(ctx context.Context, openID string, user return nil, errors.Wrap(err, "failed to get user") } } else { - userModel.OpenID = user.OpenID - if !(user.Username == "" || user.Username == "-" || user.Username == "暂未设置昵称") { - userModel.Username = user.Username - userModel.Avatar = user.Avatar + if user.Username == "" || user.Username == "-" || user.Username == "暂未设置昵称" { + user.Username = userModel.Username + user.Avatar = userModel.Avatar } - user, err = m.Update(ctx, user.ID, userModel) + user.Metas = userModel.Metas + user.AuthToken = userModel.AuthToken + + user, err = user.Update(ctx) if err != nil { return nil, errors.Wrap(err, "failed to update user") } @@ -323,10 +306,10 @@ func (m *Users) GetUsersMapByIDs(ctx context.Context, ids []int64) (map[int64]Us }), nil } -func (m *Users) BatchCheckHasBought(ctx context.Context, userID int64, postIDs []int64) (map[int64]bool, error) { +func (m *Users) BatchCheckHasBought(ctx context.Context, postIDs []int64) (map[int64]bool, error) { tbl := table.UserPosts stmt := tbl.SELECT(tbl.PostID.AS("post_id")).WHERE( - tbl.UserID.EQ(Int64(userID)).AND( + tbl.UserID.EQ(Int64(m.ID)).AND( tbl.PostID.IN(lo.Map(postIDs, func(id int64, _ int) Expression { return Int64(id) })...), ), ) @@ -347,12 +330,12 @@ func (m *Users) BatchCheckHasBought(ctx context.Context, userID int64, postIDs [ } // HasBought -func (m *Users) HasBought(ctx context.Context, userID, postID int64) (bool, error) { +func (m *Users) HasBought(ctx context.Context, postID int64) (bool, error) { tbl := table.UserPosts stmt := tbl. SELECT(tbl.ID). WHERE( - tbl.UserID.EQ(Int64(userID)).AND( + tbl.UserID.EQ(Int64(m.ID)).AND( tbl.PostID.EQ(Int64(postID)), ), ) @@ -392,14 +375,14 @@ func (m *Users) Count(ctx context.Context, cond BoolExpression) (int64, error) { return cnt.Cnt, nil } -// UpdateUsername -func (m *Users) UpdateUsername(ctx context.Context, id int64, username string) error { +// SetUsername +func (m *Users) SetUsername(ctx context.Context, username string) error { tbl := table.Users stmt := tbl. UPDATE(tbl.Username). SET(String(username)). WHERE( - tbl.ID.EQ(Int64(id)), + tbl.ID.EQ(Int64(m.ID)), ) m.log().Infof("sql: %s", stmt.DebugSql()) @@ -411,13 +394,13 @@ func (m *Users) UpdateUsername(ctx context.Context, id int64, username string) e } // UpdateUserToken -func (m *Users) UpdateUserToken(ctx context.Context, id int64, token fields.UserAuthToken) error { +func (m *Users) UpdateUserToken(ctx context.Context, token fields.UserAuthToken) error { tbl := table.Users stmt := tbl. UPDATE(tbl.AuthToken). SET(fields.ToJson(token)). WHERE( - tbl.ID.EQ(Int64(id)), + tbl.ID.EQ(Int64(m.ID)), ) m.log().Infof("sql: %s", stmt.DebugSql()) @@ -429,12 +412,12 @@ func (m *Users) UpdateUserToken(ctx context.Context, id int64, token fields.User } // BuyPosts -func (m *Users) BuyPosts(ctx context.Context, userID, postID, price int64) error { +func (m *Users) BuyPosts(ctx context.Context, postID, price int64) error { tbl := table.UserPosts stmt := tbl. INSERT(tbl.MutableColumns). MODEL(&UserPosts{ - UserID: userID, + UserID: m.ID, PostID: postID, Price: price, CreatedAt: time.Now(), @@ -450,12 +433,12 @@ func (m *Users) BuyPosts(ctx context.Context, userID, postID, price int64) error return nil } -func (m *Users) RevokePosts(ctx context.Context, userID, postID int64) error { +func (m *Users) RevokePosts(ctx context.Context, postID int64) error { tbl := table.UserPosts stmt := tbl. DELETE(). WHERE( - tbl.UserID.EQ(Int64(userID)).AND( + tbl.UserID.EQ(Int64(m.ID)).AND( tbl.PostID.EQ(Int64(postID)), ), ) @@ -469,13 +452,13 @@ func (m *Users) RevokePosts(ctx context.Context, userID, postID int64) error { } // SetBalance -func (m *Users) SetBalance(ctx context.Context, id, balance int64) error { +func (m *Users) SetBalance(ctx context.Context, balance int64) error { tbl := table.Users stmt := tbl. UPDATE(tbl.Balance). SET(Int64(balance)). WHERE( - tbl.ID.EQ(Int64(id)), + tbl.ID.EQ(Int64(m.ID)), ) m.log().Infof("sql: %s", stmt.DebugSql()) @@ -487,13 +470,13 @@ func (m *Users) SetBalance(ctx context.Context, id, balance int64) error { } // AddBalance adds the given amount to the user's balance -func (m *Users) AddBalance(ctx context.Context, id, amount int64) error { +func (m *Users) AddBalance(ctx context.Context, amount int64) error { tbl := table.Users stmt := tbl. UPDATE(tbl.Balance). SET(tbl.Balance.ADD(Int64(amount))). WHERE( - tbl.ID.EQ(Int64(id)), + tbl.ID.EQ(Int64(m.ID)), ) m.log().Infof("sql: %s", stmt.DebugSql()) diff --git a/backend/go.mod b/backend/go.mod index 922a223..6c86c59 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -19,7 +19,6 @@ require ( github.com/jackc/pgx/v5 v5.7.2 github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a github.com/lib/pq v1.10.9 - github.com/matoous/go-nanoid/v2 v2.1.0 github.com/opentracing/opentracing-go v1.2.0 github.com/pkg/errors v0.9.1 github.com/pressly/goose/v3 v3.24.1