feat: Refactor user context handling and service methods

- Updated middleware to fetch user and tenant models by ID and set them in context.
- Refactored common service methods to accept userID as a parameter instead of extracting from context.
- Modified content service methods to include userID as a parameter for better clarity and performance.
- Adjusted coupon, creator, notification, order, tenant, user, and wallet services to utilize userID directly.
- Enhanced context key constants for improved readability and maintainability.
This commit is contained in:
2025-12-30 22:49:26 +08:00
parent 619f7a69a7
commit 54de243fa1
19 changed files with 278 additions and 252 deletions

View File

@@ -20,15 +20,9 @@ import (
// @provider
type wallet struct{}
func (s *wallet) GetWallet(ctx context.Context) (*user_dto.WalletResponse, error) {
userID := ctx.Value(consts.CtxKeyUser)
if userID == nil {
return nil, errorx.ErrUnauthorized
}
uid := cast.ToInt64(userID)
func (s *wallet) GetWallet(ctx context.Context, userID int64) (*user_dto.WalletResponse, error) {
// Get Balance
u, err := models.UserQuery.WithContext(ctx).Where(models.UserQuery.ID.Eq(uid)).First()
u, err := models.UserQuery.WithContext(ctx).Where(models.UserQuery.ID.Eq(userID)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errorx.ErrRecordNotFound
@@ -39,7 +33,7 @@ func (s *wallet) GetWallet(ctx context.Context) (*user_dto.WalletResponse, error
// Get Transactions (Orders)
// Both purchase (expense) and recharge (income - if paid)
tbl, q := models.OrderQuery.QueryContext(ctx)
orders, err := q.Where(tbl.UserID.Eq(uid), tbl.Status.Eq(consts.OrderStatusPaid)).
orders, err := q.Where(tbl.UserID.Eq(userID), tbl.Status.Eq(consts.OrderStatusPaid)).
Order(tbl.CreatedAt.Desc()).
Limit(20). // Limit to recent 20
Find()
@@ -74,13 +68,7 @@ func (s *wallet) GetWallet(ctx context.Context) (*user_dto.WalletResponse, error
}, nil
}
func (s *wallet) Recharge(ctx context.Context, form *user_dto.RechargeForm) (*user_dto.RechargeResponse, error) {
userID := ctx.Value(consts.CtxKeyUser)
if userID == nil {
return nil, errorx.ErrUnauthorized
}
uid := cast.ToInt64(userID)
func (s *wallet) Recharge(ctx context.Context, userID int64, form *user_dto.RechargeForm) (*user_dto.RechargeResponse, error) {
amount := int64(form.Amount * 100)
if amount <= 0 {
return nil, errorx.ErrBadRequest.WithMsg("金额无效")
@@ -89,7 +77,7 @@ func (s *wallet) Recharge(ctx context.Context, form *user_dto.RechargeForm) (*us
// Create Recharge Order
order := &models.Order{
TenantID: 0, // Platform / System
UserID: uid,
UserID: userID,
Type: consts.OrderTypeRecharge,
Status: consts.OrderStatusCreated,
Currency: consts.CurrencyCNY,