79 lines
2.5 KiB
Go
79 lines
2.5 KiB
Go
package user
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"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 GetUserInviteStatsLogic struct {
|
|
logger.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// Get user invite statistics
|
|
func NewGetUserInviteStatsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserInviteStatsLogic {
|
|
return &GetUserInviteStatsLogic{
|
|
Logger: logger.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *GetUserInviteStatsLogic) GetUserInviteStats(req *types.GetUserInviteStatsRequest) (resp *types.GetUserInviteStatsResponse, err error) {
|
|
// 1. 从 context 中获取当前登录用户
|
|
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
|
if !ok {
|
|
l.Errorw("[GetUserInviteStats] user not found in context")
|
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
|
}
|
|
userId := u.Id
|
|
|
|
// 2. 获取历史邀请佣金 (FriendlyCount): 所有被邀请用户产生订单的佣金总和
|
|
// 注意:这里复用了 friendly_count 字段名,实际含义是佣金总额
|
|
var totalCommission sql.NullInt64
|
|
err = l.svcCtx.DB.WithContext(l.ctx).
|
|
Table("`order` o").
|
|
Select("COALESCE(SUM(o.commission), 0) as total").
|
|
Joins("JOIN user u ON o.user_id = u.id").
|
|
Where("u.referer_id = ? AND o.status IN (?, ?)", userId, 2, 5). // 只统计已支付和已完成的订单
|
|
Scan(&totalCommission).Error
|
|
|
|
if err != nil {
|
|
l.Errorw("[GetUserInviteStats] sum commission failed",
|
|
logger.Field("error", err.Error()),
|
|
logger.Field("user_id", userId))
|
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
|
|
"sum commission failed: %v", err.Error())
|
|
}
|
|
|
|
friendlyCount := totalCommission.Int64
|
|
|
|
// 3. 获取历史邀请总数 (HistoryCount)
|
|
var historyCount int64
|
|
err = l.svcCtx.DB.WithContext(l.ctx).
|
|
Table("user").
|
|
Where("referer_id = ?", userId).
|
|
Count(&historyCount).Error
|
|
if err != nil {
|
|
l.Errorw("[GetUserInviteStats] count history users failed",
|
|
logger.Field("error", err.Error()),
|
|
logger.Field("user_id", userId))
|
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
|
|
"count history users failed: %v", err.Error())
|
|
}
|
|
|
|
return &types.GetUserInviteStatsResponse{
|
|
FriendlyCount: friendlyCount,
|
|
HistoryCount: historyCount,
|
|
}, nil
|
|
}
|