merge: sync internal with main
Build docker and publish / build (20.15.1) (push) Failing after 8m22s
Build docker and publish / build (20.15.1) (push) Failing after 8m22s
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Approve withdrawal
|
||||
func ApproveWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.ApproveWithdrawalRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewApproveWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||
err := l.ApproveWithdrawal(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Get withdrawal list
|
||||
func GetWithdrawalListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetWithdrawalListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewGetWithdrawalListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetWithdrawalList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Reject withdrawal
|
||||
func RejectWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.RejectWithdrawalRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewRejectWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||
err := l.RejectWithdrawal(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -713,6 +713,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
|
||||
// Get admin user invite list
|
||||
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx))
|
||||
|
||||
// Get withdrawal list
|
||||
adminUserGroupRouter.GET("/withdrawal/list", adminUser.GetWithdrawalListHandler(serverCtx))
|
||||
|
||||
// Approve withdrawal
|
||||
adminUserGroupRouter.POST("/withdrawal/approve", adminUser.ApproveWithdrawalHandler(serverCtx))
|
||||
|
||||
// Reject withdrawal
|
||||
adminUserGroupRouter.POST("/withdrawal/reject", adminUser.RejectWithdrawalHandler(serverCtx))
|
||||
}
|
||||
|
||||
authGroupRouter := router.Group("/v1/auth")
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type ApproveWithdrawalLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewApproveWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApproveWithdrawalLogic {
|
||||
return &ApproveWithdrawalLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ApproveWithdrawalLogic) ApproveWithdrawal(req *types.ApproveWithdrawalRequest) error {
|
||||
return approveWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetWithdrawalListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetWithdrawalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWithdrawalListLogic {
|
||||
return &GetWithdrawalListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListRequest) (*types.GetWithdrawalListResponse, error) {
|
||||
page := req.Page
|
||||
size := req.Size
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).Model(&usermodel.Withdrawal{})
|
||||
if req.UserId != nil {
|
||||
query = query.Where("user_id = ?", *req.UserId)
|
||||
}
|
||||
if req.Status != nil {
|
||||
query = query.Where("status = ?", *req.Status)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawals failed: %v", err)
|
||||
}
|
||||
|
||||
var rows []usermodel.Withdrawal
|
||||
if err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawals failed: %v", err)
|
||||
}
|
||||
|
||||
list := make([]types.WithdrawalLog, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
list = append(list, types.WithdrawalLog{
|
||||
Id: row.Id,
|
||||
UserId: row.UserId,
|
||||
Amount: row.Amount,
|
||||
Content: row.Content,
|
||||
Status: row.Status,
|
||||
Reason: row.Reason,
|
||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetWithdrawalListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type RejectWithdrawalLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewRejectWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RejectWithdrawalLogic {
|
||||
return &RejectWithdrawalLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *RejectWithdrawalLogic) RejectWithdrawal(req *types.RejectWithdrawalRequest) error {
|
||||
return rejectWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId, req.Reason)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -100,21 +101,15 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
}
|
||||
|
||||
if req.Commission != userInfo.Commission {
|
||||
|
||||
commentLog := log.Commission{
|
||||
Type: log.CommissionTypeAdjust,
|
||||
Amount: req.Commission - userInfo.Commission,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
if isWithdrawalScene(req.Remark) {
|
||||
logWithdrawalGuard(l.Logger, userInfo.Id)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
|
||||
}
|
||||
|
||||
content, _ := commentLog.Marshal()
|
||||
err = tx.Create(&log.SystemLog{
|
||||
Type: log.TypeCommission.Uint8(),
|
||||
Date: time.Now().Format(time.DateOnly),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
}).Error
|
||||
if err != nil {
|
||||
change := req.Commission - userInfo.Commission
|
||||
if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.Commission = req.Commission
|
||||
|
||||
@@ -1,108 +1,120 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type ReportLogMessageLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewReportLogMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReportLogMessageLogic {
|
||||
return &ReportLogMessageLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx }
|
||||
return &ReportLogMessageLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
|
||||
}
|
||||
|
||||
func (l *ReportLogMessageLogic) ReportLogMessage(req *types.ReportLogMessageRequest, c *gin.Context) (resp *types.ReportLogMessageResponse, err error) {
|
||||
ip := clientIP(c)
|
||||
ua := c.GetHeader("User-Agent")
|
||||
locale := c.GetHeader("Accept-Language")
|
||||
ip := clientIP(c)
|
||||
ua := c.GetHeader("User-Agent")
|
||||
locale := c.GetHeader("Accept-Language")
|
||||
|
||||
// 简单限流:设备ID优先,其次IP
|
||||
limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId)
|
||||
if limitKey == "logmsg:" { limitKey = "logmsg:" + ip }
|
||||
count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result()
|
||||
if count == 1 { _ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err() }
|
||||
if count > 120 { // 每分钟最多120条
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports")
|
||||
}
|
||||
// 简单限流:设备ID优先,其次IP
|
||||
limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId)
|
||||
if limitKey == "logmsg:" {
|
||||
limitKey = "logmsg:" + ip
|
||||
}
|
||||
count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result()
|
||||
if count == 1 {
|
||||
_ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err()
|
||||
}
|
||||
if count > 120 { // 每分钟最多120条
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports")
|
||||
}
|
||||
|
||||
// 指纹生成
|
||||
h := sha256.New()
|
||||
h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|")))
|
||||
digest := hex.EncodeToString(h.Sum(nil))
|
||||
// 指纹生成
|
||||
h := sha256.New()
|
||||
h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|")))
|
||||
digest := hex.EncodeToString(h.Sum(nil))
|
||||
|
||||
var ctxStr string
|
||||
if req.Context != nil {
|
||||
if b, e := json.Marshal(req.Context); e == nil {
|
||||
ctxStr = string(b)
|
||||
}
|
||||
}
|
||||
var occurredAt *time.Time
|
||||
if req.OccurredAt > 0 {
|
||||
t := time.UnixMilli(req.OccurredAt)
|
||||
occurredAt = &t
|
||||
}
|
||||
var ctxStr string
|
||||
if req.Context != nil {
|
||||
if b, e := json.Marshal(req.Context); e == nil {
|
||||
ctxStr = string(b)
|
||||
}
|
||||
}
|
||||
var occurredAt *time.Time
|
||||
if req.OccurredAt > 0 {
|
||||
t := time.UnixMilli(req.OccurredAt)
|
||||
occurredAt = &t
|
||||
}
|
||||
|
||||
var userIdPtr *int64
|
||||
if req.UserId > 0 { userIdPtr = &req.UserId }
|
||||
var userIdPtr *int64
|
||||
if req.UserId > 0 {
|
||||
userIdPtr = &req.UserId
|
||||
}
|
||||
|
||||
row := &logmessage.LogMessage{
|
||||
Platform: req.Platform,
|
||||
AppVersion: req.AppVersion,
|
||||
OsName: req.OsName,
|
||||
OsVersion: req.OsVersion,
|
||||
DeviceId: req.DeviceId,
|
||||
UserId: userIdPtr,
|
||||
SessionId: req.SessionId,
|
||||
Level: req.Level,
|
||||
ErrorCode: req.ErrorCode,
|
||||
Message: safeTruncate(req.Message, 1024*64),
|
||||
Stack: safeTruncate(req.Stack, 1024*1024),
|
||||
Context: ctxStr,
|
||||
ClientIP: ip,
|
||||
UserAgent: safeTruncate(ua, 255),
|
||||
Locale: safeTruncate(locale, 16),
|
||||
Digest: digest,
|
||||
OccurredAt: occurredAt,
|
||||
}
|
||||
row := &logmessage.LogMessage{
|
||||
Platform: safeTruncate(req.Platform, 32),
|
||||
AppVersion: safeTruncate(req.AppVersion, 64),
|
||||
OsName: safeTruncate(req.OsName, 64),
|
||||
OsVersion: safeTruncate(req.OsVersion, 64),
|
||||
DeviceId: safeTruncate(req.DeviceId, 255),
|
||||
UserId: userIdPtr,
|
||||
SessionId: safeTruncate(req.SessionId, 255),
|
||||
Level: req.Level,
|
||||
ErrorCode: safeTruncate(req.ErrorCode, 128),
|
||||
Message: safeTruncate(req.Message, 1024*64),
|
||||
Stack: safeTruncate(req.Stack, 1024*1024),
|
||||
Context: ctxStr,
|
||||
ClientIP: ip,
|
||||
UserAgent: safeTruncate(ua, 255),
|
||||
Locale: safeTruncate(locale, 16),
|
||||
Digest: digest,
|
||||
OccurredAt: occurredAt,
|
||||
}
|
||||
|
||||
if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil {
|
||||
// 唯一指纹冲突时尝试查询已有记录返回ID
|
||||
ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{ Keyword: req.Message, Page: 1, Size: 1 })
|
||||
if findErr == nil && len(ex) > 0 {
|
||||
return &types.ReportLogMessageResponse{ Id: ex[0].Id }, nil
|
||||
}
|
||||
l.Errorf("[ReportLogMessage] insert error: %v", err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err)
|
||||
}
|
||||
return &types.ReportLogMessageResponse{ Id: row.Id }, nil
|
||||
if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil {
|
||||
// 唯一指纹冲突时尝试查询已有记录返回ID
|
||||
ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{Keyword: req.Message, Page: 1, Size: 1})
|
||||
if findErr == nil && len(ex) > 0 {
|
||||
return &types.ReportLogMessageResponse{Id: ex[0].Id}, nil
|
||||
}
|
||||
l.Errorf("[ReportLogMessage] insert error: %v", err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err)
|
||||
}
|
||||
return &types.ReportLogMessageResponse{Id: row.Id}, nil
|
||||
}
|
||||
|
||||
func safeTruncate(s string, n int) string {
|
||||
if len(s) <= n { return s }
|
||||
return s[:n]
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func clientIP(c *gin.Context) string {
|
||||
ip := c.ClientIP()
|
||||
if ip != "" { return ip }
|
||||
host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
||||
if err == nil && host != "" { return host }
|
||||
return ""
|
||||
ip := c.ClientIP()
|
||||
if ip != "" {
|
||||
return ip
|
||||
}
|
||||
host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
||||
if err == nil && host != "" {
|
||||
return host
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -109,14 +109,14 @@ func buildObjectKey(prefix string, userID int64, bizType, fileID, fileName strin
|
||||
if prefix == "" {
|
||||
prefix = "app-upload"
|
||||
}
|
||||
return fmt.Sprintf("%s/%s/%d/%04d/%02d/%s_%s",
|
||||
return fmt.Sprintf("%s/%04d/%02d/%02d/%d/%s__%s",
|
||||
prefix,
|
||||
strings.Trim(safeFileNameRegexp.ReplaceAllString(strings.ToLower(strings.TrimSpace(bizType)), "-"), "-"),
|
||||
userID,
|
||||
now.Year(),
|
||||
int(now.Month()),
|
||||
fileID,
|
||||
now.Day(),
|
||||
userID,
|
||||
safeFileName(fileName),
|
||||
fileID,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
authlogic "github.com/perfect-panel/server/internal/logic/auth"
|
||||
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||
modelOrder "github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
@@ -44,6 +46,7 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
}
|
||||
tool.DeepCopy(resp, u)
|
||||
resp.UseStatus = true
|
||||
|
||||
// 用家庭范围查设备,而不是只看当前用户自己的 UserDevices
|
||||
scopeHelper := newFamilyScopeHelper(l.ctx, l.svcCtx)
|
||||
@@ -65,6 +68,14 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
|
||||
}
|
||||
resp.UserDevices = userDevices
|
||||
}
|
||||
|
||||
useStatus, useStatusErr := l.resolveBindEmailTrialUseStatus(u.Id, scopeUserIds)
|
||||
if useStatusErr != nil {
|
||||
l.Errorw("resolve bind email trial use status failed", logger.Field("user_id", u.Id), logger.Field("error", useStatusErr.Error()))
|
||||
} else {
|
||||
resp.UseStatus = useStatus
|
||||
}
|
||||
|
||||
// refer_code 为空时自动生成
|
||||
if resp.ReferCode == "" {
|
||||
resp.ReferCode = uuidx.UserInviteCode(u.Id)
|
||||
@@ -108,6 +119,49 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// resolveBindEmailTrialUseStatus determines whether userinfo should show the
|
||||
// "bind email to get free trial" prompt. `true` means show the prompt.
|
||||
func (l *QueryUserInfoLogic) resolveBindEmailTrialUseStatus(currentUserId int64, scopeUserIds []int64) (bool, error) {
|
||||
if len(scopeUserIds) == 0 {
|
||||
scopeUserIds = []int64{currentUserId}
|
||||
}
|
||||
|
||||
var hasBoundEmailCount int64
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.AuthMethods{}).
|
||||
Where("user_id IN ? AND auth_type = ? AND auth_identifier != ''", scopeUserIds, "email").
|
||||
Count(&hasBoundEmailCount).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var hasPurchaseCount int64
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&modelOrder.Order{}).
|
||||
Where("user_id IN ? AND type IN ? AND status IN ?", scopeUserIds, []int64{1, 2}, []int64{2, 5}).
|
||||
Count(&hasPurchaseCount).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
hasTrial := false
|
||||
registerCfg := l.svcCtx.Config.Register
|
||||
if authlogic.IsTrialConfigReady(registerCfg) && registerCfg.TrialSubscribe > 0 {
|
||||
var hasTrialCount int64
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id IN ? AND subscribe_id = ?", scopeUserIds, registerCfg.TrialSubscribe).
|
||||
Count(&hasTrialCount).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
hasTrial = hasTrialCount > 0
|
||||
}
|
||||
|
||||
return shouldShowBindEmailTrialPrompt(hasBoundEmailCount > 0, hasPurchaseCount > 0, hasTrial), nil
|
||||
}
|
||||
|
||||
func shouldShowBindEmailTrialPrompt(hasBoundEmail, hasPurchased, hasTrial bool) bool {
|
||||
return !hasBoundEmail && !hasPurchased && !hasTrial
|
||||
}
|
||||
|
||||
func (l *QueryUserInfoLogic) fillFamilyContext(resp *types.User, userId int64) *user.AuthMethods {
|
||||
type familyRelation struct {
|
||||
FamilyId int64
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package user
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestShouldShowBindEmailTrialPrompt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
hasBoundEmail bool
|
||||
hasPurchased bool
|
||||
hasTrial bool
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "new user should see prompt",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "bound email should hide prompt",
|
||||
hasBoundEmail: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "paid purchase should hide prompt",
|
||||
hasPurchased: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "trial claimed should hide prompt",
|
||||
hasTrial: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "bound email and purchase should hide prompt",
|
||||
hasBoundEmail: true,
|
||||
hasPurchased: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "bound email and trial should hide prompt",
|
||||
hasBoundEmail: true,
|
||||
hasTrial: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "purchase and trial should hide prompt",
|
||||
hasPurchased: true,
|
||||
hasTrial: true,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "all blockers should hide prompt",
|
||||
hasBoundEmail: true,
|
||||
hasPurchased: true,
|
||||
hasTrial: true,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := shouldShowBindEmailTrialPrompt(tt.hasBoundEmail, tt.hasPurchased, tt.hasTrial)
|
||||
if got != tt.want {
|
||||
t.Fatalf("shouldShowBindEmailTrialPrompt(%v, %v, %v) = %v, want %v", tt.hasBoundEmail, tt.hasPurchased, tt.hasTrial, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,13 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryWithdrawalLogLogic struct {
|
||||
@@ -24,7 +28,49 @@ func NewQueryWithdrawalLogLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
||||
}
|
||||
|
||||
func (l *QueryWithdrawalLogLogic) QueryWithdrawalLog(req *types.QueryWithdrawalLogListRequest) (resp *types.QueryWithdrawalLogListResponse, err error) {
|
||||
// todo: add your logic here and delete this line
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok {
|
||||
l.Error("current user is not found in context")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
}
|
||||
|
||||
return
|
||||
page := req.Page
|
||||
size := req.Size
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).Model(&user.Withdrawal{}).Where("user_id = ?", u.Id)
|
||||
|
||||
var total int64
|
||||
if err = query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawal logs failed: %v", err)
|
||||
}
|
||||
|
||||
var rows []user.Withdrawal
|
||||
if err = query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawal logs failed: %v", err)
|
||||
}
|
||||
|
||||
list := make([]types.WithdrawalLog, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
list = append(list, types.WithdrawalLog{
|
||||
Id: row.Id,
|
||||
UserId: row.UserId,
|
||||
Amount: row.Amount,
|
||||
Content: row.Content,
|
||||
Status: row.Status,
|
||||
Reason: row.Reason,
|
||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.QueryWithdrawalLogListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ const (
|
||||
ctxDecryptedQueryKey = "decrypted_query"
|
||||
ctxEncryptedBodyKey = "encrypted_request_body"
|
||||
ctxDecryptedBodyKey = "decrypted_request_body"
|
||||
|
||||
deviceDecryptSkipPathPublicFileUpload = "/v1/public/file/upload"
|
||||
)
|
||||
|
||||
func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
@@ -70,6 +72,14 @@ func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
}
|
||||
|
||||
rw := NewResponseWriter(c, srvCtx)
|
||||
if shouldSkipDeviceRequestDecrypt(c) {
|
||||
c.Set(ctxDeviceDecryptStatusKey, "skipped")
|
||||
c.Set(ctxDeviceDecryptReasonKey, "multipart_upload_passthrough")
|
||||
c.Writer = rw
|
||||
c.Next()
|
||||
rw.FlushAbort()
|
||||
return
|
||||
}
|
||||
if !rw.Decrypt() {
|
||||
c.Set(ctxDeviceDecryptStatusKey, "failed")
|
||||
if _, exists := c.Get(ctxDeviceDecryptReasonKey); !exists {
|
||||
@@ -85,6 +95,13 @@ func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func shouldSkipDeviceRequestDecrypt(c *gin.Context) bool {
|
||||
if c.Request.URL.Path != deviceDecryptSkipPathPublicFileUpload {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type"))), "multipart/form-data")
|
||||
}
|
||||
|
||||
func NewResponseWriter(c *gin.Context, srvCtx *svc.ServiceContext) (rw *ResponseWriter) {
|
||||
rw = &ResponseWriter{
|
||||
c: c,
|
||||
|
||||
@@ -50,6 +50,7 @@ const (
|
||||
CommissionTypeWithdraw uint16 = 334 // withdraw
|
||||
CommissionTypeAdjust uint16 = 335 // Admin Adjust
|
||||
CommissionTypeConvertBalance uint16 = 336 // Convert to Balance
|
||||
CommissionTypeWithdrawReject uint16 = 337 // Withdraw rejected refund
|
||||
GiftTypeIncrease uint16 = 341 // Increase
|
||||
GiftTypeReduce uint16 = 342 // Reduce
|
||||
)
|
||||
|
||||
@@ -3,25 +3,25 @@ package logmessage
|
||||
import "time"
|
||||
|
||||
type LogMessage struct {
|
||||
Id int64 `gorm:"primaryKey;AUTO_INCREMENT"`
|
||||
Platform string `gorm:"type:varchar(32);not null"`
|
||||
AppVersion string `gorm:"type:varchar(32);default:null"`
|
||||
OsName string `gorm:"type:varchar(32);default:null"`
|
||||
OsVersion string `gorm:"type:varchar(32);default:null"`
|
||||
DeviceId string `gorm:"type:varchar(64);default:null"`
|
||||
UserId *int64 `gorm:"type:bigint;default:null"`
|
||||
SessionId string `gorm:"type:varchar(64);default:null"`
|
||||
Level uint8 `gorm:"type:tinyint(1);not null;default:3"`
|
||||
ErrorCode string `gorm:"type:varchar(64);default:null"`
|
||||
Message string `gorm:"type:text;not null"`
|
||||
Stack string `gorm:"type:mediumtext;default:null"`
|
||||
Context string `gorm:"type:json;default:null"`
|
||||
ClientIP string `gorm:"type:varchar(45);default:null"`
|
||||
UserAgent string `gorm:"type:varchar(255);default:null"`
|
||||
Locale string `gorm:"type:varchar(16);default:null"`
|
||||
Digest string `gorm:"type:varchar(64);uniqueIndex:uniq_digest;default:null"`
|
||||
OccurredAt *time.Time `gorm:"type:datetime;default:null"`
|
||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||
Id int64 `gorm:"primaryKey;AUTO_INCREMENT"`
|
||||
Platform string `gorm:"type:varchar(32);not null"`
|
||||
AppVersion string `gorm:"type:varchar(64);default:null"`
|
||||
OsName string `gorm:"type:varchar(64);default:null"`
|
||||
OsVersion string `gorm:"type:varchar(64);default:null"`
|
||||
DeviceId string `gorm:"type:varchar(255);default:null"`
|
||||
UserId *int64 `gorm:"type:bigint;default:null"`
|
||||
SessionId string `gorm:"type:varchar(255);default:null"`
|
||||
Level uint8 `gorm:"type:tinyint(1);not null;default:3"`
|
||||
ErrorCode string `gorm:"type:varchar(128);default:null"`
|
||||
Message string `gorm:"type:text;not null"`
|
||||
Stack string `gorm:"type:mediumtext;default:null"`
|
||||
Context string `gorm:"type:json;default:null"`
|
||||
ClientIP string `gorm:"type:varchar(45);default:null"`
|
||||
UserAgent string `gorm:"type:varchar(255);default:null"`
|
||||
Locale string `gorm:"type:varchar(16);default:null"`
|
||||
Digest string `gorm:"type:varchar(64);uniqueIndex:uniq_digest;default:null"`
|
||||
OccurredAt *time.Time `gorm:"type:datetime;default:null"`
|
||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||
}
|
||||
|
||||
func (LogMessage) TableName() string { return "log_message" }
|
||||
|
||||
@@ -26,6 +26,7 @@ type (
|
||||
Insert(ctx context.Context, data *User, tx ...*gorm.DB) error
|
||||
FindOne(ctx context.Context, id int64) (*User, error)
|
||||
Update(ctx context.Context, data *User, tx ...*gorm.DB) error
|
||||
UpdateCommission(ctx context.Context, userId int64, delta int64, tx ...*gorm.DB) error
|
||||
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
|
||||
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
||||
}
|
||||
@@ -111,6 +112,22 @@ func (m *defaultUserModel) Update(ctx context.Context, data *User, tx ...*gorm.D
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultUserModel) UpdateCommission(ctx context.Context, userId int64, delta int64, tx ...*gorm.DB) error {
|
||||
old, err := m.FindOne(ctx, userId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||
if len(tx) > 0 {
|
||||
conn = tx[0]
|
||||
}
|
||||
return conn.Model(&User{}).
|
||||
Where("id = ?", userId).
|
||||
UpdateColumn("commission", gorm.Expr("commission + ?", delta)).Error
|
||||
}, m.getCacheKeys(old)...)
|
||||
}
|
||||
|
||||
func (m *defaultUserModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
|
||||
data, err := m.FindOne(ctx, id)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,6 +8,22 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const userDeviceUserAgentMaxLength = 255
|
||||
|
||||
func normalizeDeviceForStorage(data *Device) {
|
||||
if data == nil {
|
||||
return
|
||||
}
|
||||
data.UserAgent = truncateForColumn(data.UserAgent, userDeviceUserAgentMaxLength)
|
||||
}
|
||||
|
||||
func truncateForColumn(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max]
|
||||
}
|
||||
|
||||
func (m *customUserModel) FindOneDevice(ctx context.Context, id int64) (*Device, error) {
|
||||
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, id)
|
||||
var resp Device
|
||||
@@ -69,6 +85,7 @@ func (m *customUserModel) QueryDeviceListByUserIds(ctx context.Context, userIds
|
||||
}
|
||||
|
||||
func (m *customUserModel) UpdateDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error {
|
||||
normalizeDeviceForStorage(data)
|
||||
old, err := m.FindOneDevice(ctx, data.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -100,6 +117,7 @@ func (m *customUserModel) DeleteDevice(ctx context.Context, id int64, tx ...*gor
|
||||
}
|
||||
|
||||
func (m *customUserModel) InsertDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error {
|
||||
normalizeDeviceForStorage(data)
|
||||
defer func() {
|
||||
if clearErr := m.ClearDeviceCache(ctx, data); clearErr != nil {
|
||||
// log cache clear error
|
||||
|
||||
@@ -2323,6 +2323,27 @@ type QueryWithdrawalLogListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
UserId *int64 `form:"user_id,omitempty"`
|
||||
Status *uint8 `form:"status,omitempty"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListResponse struct {
|
||||
List []WithdrawalLog `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type ApproveWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type RejectWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason" validate:"required,max=500"`
|
||||
}
|
||||
|
||||
type QuotaTask struct {
|
||||
Id int64 `json:"id"`
|
||||
Subscribers []int64 `json:"subscribers"`
|
||||
@@ -3317,6 +3338,7 @@ type User struct {
|
||||
EnableLoginNotify bool `json:"enable_login_notify"`
|
||||
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
|
||||
EnableTradeNotify bool `json:"enable_trade_notify"`
|
||||
UseStatus bool `json:"use_status"`
|
||||
AuthMethods []UserAuthMethod `json:"auth_methods"`
|
||||
UserDevices []UserDevice `json:"user_devices"`
|
||||
Rules []string `json:"rules"`
|
||||
|
||||
Reference in New Issue
Block a user