init
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string
|
||||
JWTSecret string
|
||||
DBPath string
|
||||
Mode string // debug / release
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
Port: getEnv("PORT", "8080"),
|
||||
JWTSecret: getEnv("JWT_SECRET", "affiliate-dash-dev-secret-change-me"),
|
||||
DBPath: getEnv("DB_PATH", "data/app.db"),
|
||||
Mode: getEnv("GIN_MODE", "debug"),
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getEnvInt(key string, def int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"affiliate_dash/internal/middleware"
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
svc *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(svc *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{svc: svc}
|
||||
}
|
||||
|
||||
type loginReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req loginReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请输入用户名和密码")
|
||||
return
|
||||
}
|
||||
result, err := h.svc.Login(req.Username, req.Password)
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
type registerReq struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=32"`
|
||||
Password string `json:"password" binding:"required,min=6,max=64"`
|
||||
Nickname string `json:"nickname"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Register(c *gin.Context) {
|
||||
var req registerReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误:用户名至少3位,密码至少6位")
|
||||
return
|
||||
}
|
||||
user, err := h.svc.Register(req.Username, req.Password, req.Nickname)
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, user)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Profile(c *gin.Context) {
|
||||
user, err := h.svc.GetProfile(middleware.GetUserID(c))
|
||||
if err != nil {
|
||||
response.NotFound(c, "用户不存在")
|
||||
return
|
||||
}
|
||||
response.OK(c, user)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"affiliate_dash/internal/middleware"
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type OrderHandler struct {
|
||||
svc *service.OrderService
|
||||
}
|
||||
|
||||
func NewOrderHandler(svc *service.OrderService) *OrderHandler {
|
||||
return &OrderHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *OrderHandler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
q := service.OrderListQuery{
|
||||
Page: page,
|
||||
Size: size,
|
||||
Status: c.Query("status"),
|
||||
}
|
||||
// 分销商只能看自己的订单
|
||||
if middleware.GetRole(c) == model.RoleDistributor {
|
||||
id := middleware.GetUserID(c)
|
||||
q.DistributorID = &id
|
||||
} else if d := c.Query("distributor_id"); d != "" {
|
||||
id, _ := strconv.ParseUint(d, 10, 64)
|
||||
uid := uint(id)
|
||||
q.DistributorID = &uid
|
||||
}
|
||||
list, total, err := h.svc.List(q)
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
type createOrderReq struct {
|
||||
SkinID uint `json:"skin_id" binding:"required"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
func (h *OrderHandler) Create(c *gin.Context) {
|
||||
var req createOrderReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
distributorID := middleware.GetUserID(c)
|
||||
// 管理员可指定分销商
|
||||
if middleware.GetRole(c) == model.RoleAdmin {
|
||||
if d := c.Query("distributor_id"); d != "" {
|
||||
id, _ := strconv.ParseUint(d, 10, 64)
|
||||
distributorID = uint(id)
|
||||
}
|
||||
}
|
||||
order, err := h.svc.Create(service.CreateOrderInput{
|
||||
SkinID: req.SkinID,
|
||||
DistributorID: distributorID,
|
||||
BuyerName: req.BuyerName,
|
||||
Remark: req.Remark,
|
||||
})
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, order)
|
||||
}
|
||||
|
||||
type orderStatusReq struct {
|
||||
Status string `json:"status" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *OrderHandler) UpdateStatus(c *gin.Context) {
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var req orderStatusReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
if err := h.svc.UpdateStatus(uint(id), req.Status); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, nil)
|
||||
}
|
||||
|
||||
func (h *OrderHandler) Dashboard(c *gin.Context) {
|
||||
stats, err := h.svc.Dashboard()
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, stats)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SkinHandler struct {
|
||||
svc *service.SkinService
|
||||
}
|
||||
|
||||
func NewSkinHandler(svc *service.SkinService) *SkinHandler {
|
||||
return &SkinHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *SkinHandler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
q := service.SkinListQuery{
|
||||
Page: page,
|
||||
Size: size,
|
||||
Keyword: c.Query("keyword"),
|
||||
Game: c.Query("game"),
|
||||
Category: c.Query("category"),
|
||||
}
|
||||
if s := c.Query("status"); s != "" {
|
||||
v, _ := strconv.Atoi(s)
|
||||
q.Status = &v
|
||||
}
|
||||
list, total, err := h.svc.List(q)
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
func (h *SkinHandler) Get(c *gin.Context) {
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
skin, err := h.svc.Get(uint(id))
|
||||
if err != nil {
|
||||
response.NotFound(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, skin)
|
||||
}
|
||||
|
||||
type skinCreateReq struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Game string `json:"game"`
|
||||
Category string `json:"category"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
Price float64 `json:"price" binding:"required"`
|
||||
CostPrice float64 `json:"cost_price"`
|
||||
Commission float64 `json:"commission"`
|
||||
Stock int `json:"stock"`
|
||||
Status int `json:"status"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (h *SkinHandler) Create(c *gin.Context) {
|
||||
var req skinCreateReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
status := req.Status
|
||||
if status != 0 && status != 1 {
|
||||
status = 1
|
||||
}
|
||||
// 未传 status 时默认上架;若明确要下架请先创建再更新
|
||||
if status == 0 {
|
||||
status = 1
|
||||
}
|
||||
skin := &model.Skin{
|
||||
Name: req.Name,
|
||||
Game: req.Game,
|
||||
Category: req.Category,
|
||||
CoverURL: req.CoverURL,
|
||||
Price: req.Price,
|
||||
CostPrice: req.CostPrice,
|
||||
Commission: req.Commission,
|
||||
Stock: req.Stock,
|
||||
Status: status,
|
||||
Description: req.Description,
|
||||
}
|
||||
if err := h.svc.Create(skin); err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, skin)
|
||||
}
|
||||
|
||||
func (h *SkinHandler) Update(c *gin.Context) {
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
delete(updates, "id")
|
||||
delete(updates, "created_at")
|
||||
delete(updates, "updated_at")
|
||||
if err := h.svc.Update(uint(id), updates); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, nil)
|
||||
}
|
||||
|
||||
func (h *SkinHandler) Delete(c *gin.Context) {
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err := h.svc.Delete(uint(id)); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, nil)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
svc *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(svc *service.UserService) *UserHandler {
|
||||
return &UserHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *UserHandler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
q := service.UserListQuery{
|
||||
Page: page,
|
||||
Size: size,
|
||||
Keyword: c.Query("keyword"),
|
||||
Role: c.Query("role"),
|
||||
}
|
||||
if s := c.Query("status"); s != "" {
|
||||
v, _ := strconv.Atoi(s)
|
||||
q.Status = &v
|
||||
}
|
||||
list, total, err := h.svc.List(q)
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
type createUserReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Nickname string `json:"nickname"`
|
||||
Role string `json:"role"`
|
||||
ParentID *uint `json:"parent_id"`
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(c *gin.Context) {
|
||||
var req createUserReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
user, err := h.svc.Create(req.Username, req.Password, req.Nickname, req.Role, req.ParentID)
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, user)
|
||||
}
|
||||
|
||||
type userStatusReq struct {
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func (h *UserHandler) UpdateStatus(c *gin.Context) {
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var req userStatusReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
if err := h.svc.UpdateStatus(uint(id), req.Status); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, nil)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"affiliate_dash/internal/pkg/jwt"
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
CtxUserID = "user_id"
|
||||
CtxUsername = "username"
|
||||
CtxRole = "role"
|
||||
)
|
||||
|
||||
func Auth(jm *jwt.Manager) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
auth := c.GetHeader("Authorization")
|
||||
if auth == "" {
|
||||
response.Unauthorized(c, "未登录")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
parts := strings.SplitN(auth, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
response.Unauthorized(c, "无效的认证头")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
claims, err := jm.Parse(parts[1])
|
||||
if err != nil {
|
||||
response.Unauthorized(c, "登录已过期,请重新登录")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Set(CtxUserID, claims.UserID)
|
||||
c.Set(CtxUsername, claims.Username)
|
||||
c.Set(CtxRole, claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func RequireRole(roles ...string) gin.HandlerFunc {
|
||||
set := make(map[string]struct{}, len(roles))
|
||||
for _, r := range roles {
|
||||
set[r] = struct{}{}
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get(CtxRole)
|
||||
roleStr, _ := role.(string)
|
||||
if _, ok := set[roleStr]; !ok {
|
||||
response.Forbidden(c, "权限不足")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserID(c *gin.Context) uint {
|
||||
v, _ := c.Get(CtxUserID)
|
||||
id, _ := v.(uint)
|
||||
return id
|
||||
}
|
||||
|
||||
func GetRole(c *gin.Context) string {
|
||||
v, _ := c.Get(CtxRole)
|
||||
role, _ := v.(string)
|
||||
return role
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 用户角色
|
||||
const (
|
||||
RoleAdmin = "admin" // 管理员
|
||||
RoleDistributor = "distributor" // 分销商
|
||||
)
|
||||
|
||||
// User 系统用户
|
||||
type User struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
Username string `gorm:"uniqueIndex;size:64;not null" json:"username"`
|
||||
PasswordHash string `gorm:"size:255;not null" json:"-"`
|
||||
Nickname string `gorm:"size:64" json:"nickname"`
|
||||
Role string `gorm:"size:32;not null;default:distributor" json:"role"`
|
||||
Status int `gorm:"default:1" json:"status"` // 1启用 0禁用
|
||||
InviteCode string `gorm:"uniqueIndex;size:32" json:"invite_code"`
|
||||
ParentID *uint `gorm:"index" json:"parent_id"` // 上级分销商
|
||||
}
|
||||
|
||||
// Skin 游戏皮肤商品
|
||||
type Skin struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
Name string `gorm:"size:128;not null" json:"name"`
|
||||
Game string `gorm:"size:64;index" json:"game"` // 所属游戏
|
||||
Category string `gorm:"size:64;index" json:"category"` // 分类
|
||||
CoverURL string `gorm:"size:512" json:"cover_url"`
|
||||
Price float64 `gorm:"not null;default:0" json:"price"` // 售价
|
||||
CostPrice float64 `gorm:"default:0" json:"cost_price"` // 成本价
|
||||
Commission float64 `gorm:"default:0" json:"commission"` // 佣金比例 0-1
|
||||
Stock int `gorm:"default:0" json:"stock"` // -1 无限
|
||||
Status int `gorm:"default:1" json:"status"` // 1上架 0下架
|
||||
Description string `gorm:"type:text" json:"description"`
|
||||
}
|
||||
|
||||
// Order 订单
|
||||
type Order struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
OrderNo string `gorm:"uniqueIndex;size:64;not null" json:"order_no"`
|
||||
SkinID uint `gorm:"index;not null" json:"skin_id"`
|
||||
Skin *Skin `gorm:"foreignKey:SkinID" json:"skin,omitempty"`
|
||||
DistributorID uint `gorm:"index;not null" json:"distributor_id"`
|
||||
Distributor *User `gorm:"foreignKey:DistributorID" json:"distributor,omitempty"`
|
||||
BuyerName string `gorm:"size:64" json:"buyer_name"`
|
||||
Amount float64 `gorm:"not null" json:"amount"`
|
||||
CommissionAmt float64 `gorm:"default:0" json:"commission_amt"`
|
||||
Status string `gorm:"size:32;default:pending" json:"status"` // pending/paid/delivered/cancelled
|
||||
Remark string `gorm:"size:255" json:"remark"`
|
||||
}
|
||||
|
||||
// 订单状态
|
||||
const (
|
||||
OrderStatusPending = "pending"
|
||||
OrderStatusPaid = "paid"
|
||||
OrderStatusDelivered = "delivered"
|
||||
OrderStatusCancelled = "cancelled"
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
secret []byte
|
||||
expire time.Duration
|
||||
}
|
||||
|
||||
func NewManager(secret string) *Manager {
|
||||
return &Manager{
|
||||
secret: []byte(secret),
|
||||
expire: 7 * 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) Generate(userID uint, username, role string) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Role: role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.expire)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(m.secret)
|
||||
}
|
||||
|
||||
func (m *Manager) Parse(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return m.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Body struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func OK(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Body{Code: 0, Message: "ok", Data: data})
|
||||
}
|
||||
|
||||
func Fail(c *gin.Context, httpStatus int, code int, message string) {
|
||||
c.JSON(httpStatus, Body{Code: code, Message: message})
|
||||
}
|
||||
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Fail(c, http.StatusBadRequest, 400, message)
|
||||
}
|
||||
|
||||
func Unauthorized(c *gin.Context, message string) {
|
||||
Fail(c, http.StatusUnauthorized, 401, message)
|
||||
}
|
||||
|
||||
func Forbidden(c *gin.Context, message string) {
|
||||
Fail(c, http.StatusForbidden, 403, message)
|
||||
}
|
||||
|
||||
func NotFound(c *gin.Context, message string) {
|
||||
Fail(c, http.StatusNotFound, 404, message)
|
||||
}
|
||||
|
||||
func ServerError(c *gin.Context, message string) {
|
||||
Fail(c, http.StatusInternalServerError, 500, message)
|
||||
}
|
||||
|
||||
type PageData struct {
|
||||
List interface{} `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
func Page(c *gin.Context, list interface{}, total int64, page, size int) {
|
||||
OK(c, PageData{List: list, Total: total, Page: page, Size: size})
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"affiliate_dash/internal/handler"
|
||||
"affiliate_dash/internal/middleware"
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/jwt"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
Auth *handler.AuthHandler
|
||||
Skin *handler.SkinHandler
|
||||
Order *handler.OrderHandler
|
||||
User *handler.UserHandler
|
||||
JWT *jwt.Manager
|
||||
}
|
||||
|
||||
func Setup(h *Handlers) *gin.Engine {
|
||||
r := gin.Default()
|
||||
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"http://localhost:5173", "http://127.0.0.1:5173"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: true,
|
||||
}))
|
||||
|
||||
r.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.POST("/auth/login", h.Auth.Login)
|
||||
api.POST("/auth/register", h.Auth.Register)
|
||||
|
||||
auth := api.Group("")
|
||||
auth.Use(middleware.Auth(h.JWT))
|
||||
{
|
||||
auth.GET("/auth/profile", h.Auth.Profile)
|
||||
auth.GET("/dashboard", h.Order.Dashboard)
|
||||
|
||||
// 皮肤
|
||||
auth.GET("/skins", h.Skin.List)
|
||||
auth.GET("/skins/:id", h.Skin.Get)
|
||||
auth.POST("/skins", middleware.RequireRole(model.RoleAdmin), h.Skin.Create)
|
||||
auth.PUT("/skins/:id", middleware.RequireRole(model.RoleAdmin), h.Skin.Update)
|
||||
auth.DELETE("/skins/:id", middleware.RequireRole(model.RoleAdmin), h.Skin.Delete)
|
||||
|
||||
// 订单
|
||||
auth.GET("/orders", h.Order.List)
|
||||
auth.POST("/orders", h.Order.Create)
|
||||
auth.PATCH("/orders/:id/status", middleware.RequireRole(model.RoleAdmin), h.Order.UpdateStatus)
|
||||
|
||||
// 用户 / 分销商(仅管理员)
|
||||
admin := auth.Group("")
|
||||
admin.Use(middleware.RequireRole(model.RoleAdmin))
|
||||
{
|
||||
admin.GET("/users", h.User.List)
|
||||
admin.POST("/users", h.User.Create)
|
||||
admin.PATCH("/users/:id/status", h.User.UpdateStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/jwt"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
db *gorm.DB
|
||||
jwt *jwt.Manager
|
||||
}
|
||||
|
||||
func NewAuthService(db *gorm.DB, jm *jwt.Manager) *AuthService {
|
||||
return &AuthService{db: db, jwt: jm}
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
Token string `json:"token"`
|
||||
User *model.User `json:"user"`
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(username, password string) (*LoginResult, error) {
|
||||
var user model.User
|
||||
if err := s.db.Where("username = ?", username).First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if user.Status != 1 {
|
||||
return nil, errors.New("账号已禁用")
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
|
||||
return nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
token, err := s.jwt.Generate(user.ID, user.Username, user.Role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &LoginResult{Token: token, User: &user}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Register(username, password, nickname string) (*model.User, error) {
|
||||
var count int64
|
||||
s.db.Model(&model.User{}).Where("username = ?", username).Count(&count)
|
||||
if count > 0 {
|
||||
return nil, errors.New("用户名已存在")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := &model.User{
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: nickname,
|
||||
Role: model.RoleDistributor,
|
||||
Status: 1,
|
||||
InviteCode: generateInviteCode(),
|
||||
}
|
||||
if user.Nickname == "" {
|
||||
user.Nickname = username
|
||||
}
|
||||
if err := s.db.Create(user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) GetProfile(userID uint) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := s.db.First(&user, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) EnsureAdmin() error {
|
||||
var count int64
|
||||
s.db.Model(&model.User{}).Where("role = ?", model.RoleAdmin).Count(&count)
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
admin := &model.User{
|
||||
Username: "admin",
|
||||
PasswordHash: string(hash),
|
||||
Nickname: "管理员",
|
||||
Role: model.RoleAdmin,
|
||||
Status: 1,
|
||||
InviteCode: "ADMIN001",
|
||||
}
|
||||
return s.db.Create(admin).Error
|
||||
}
|
||||
|
||||
func generateInviteCode() string {
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
return fmt.Sprintf("D%06d", r.Intn(1000000))
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderService(db *gorm.DB) *OrderService {
|
||||
return &OrderService{db: db}
|
||||
}
|
||||
|
||||
type OrderListQuery struct {
|
||||
Page int
|
||||
Size int
|
||||
Status string
|
||||
DistributorID *uint
|
||||
}
|
||||
|
||||
type CreateOrderInput struct {
|
||||
SkinID uint
|
||||
DistributorID uint
|
||||
BuyerName string
|
||||
Remark string
|
||||
}
|
||||
|
||||
func (s *OrderService) List(q OrderListQuery) ([]model.Order, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.Order{})
|
||||
if q.Status != "" {
|
||||
tx = tx.Where("status = ?", q.Status)
|
||||
}
|
||||
if q.DistributorID != nil {
|
||||
tx = tx.Where("distributor_id = ?", *q.DistributorID)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.Order
|
||||
err := tx.Preload("Skin").Preload("Distributor").
|
||||
Order("id DESC").
|
||||
Offset((q.Page - 1) * q.Size).Limit(q.Size).
|
||||
Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *OrderService) Create(in CreateOrderInput) (*model.Order, error) {
|
||||
var skin model.Skin
|
||||
if err := s.db.First(&skin, in.SkinID).Error; err != nil {
|
||||
return nil, errors.New("皮肤不存在")
|
||||
}
|
||||
if skin.Status != 1 {
|
||||
return nil, errors.New("皮肤已下架")
|
||||
}
|
||||
if skin.Stock == 0 {
|
||||
return nil, errors.New("库存不足")
|
||||
}
|
||||
|
||||
order := &model.Order{
|
||||
OrderNo: generateOrderNo(),
|
||||
SkinID: in.SkinID,
|
||||
DistributorID: in.DistributorID,
|
||||
BuyerName: in.BuyerName,
|
||||
Amount: skin.Price,
|
||||
CommissionAmt: skin.Price * skin.Commission,
|
||||
Status: model.OrderStatusPending,
|
||||
Remark: in.Remark,
|
||||
}
|
||||
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if skin.Stock > 0 {
|
||||
res := tx.Model(&model.Skin{}).
|
||||
Where("id = ? AND stock > 0", skin.ID).
|
||||
Update("stock", gorm.Expr("stock - 1"))
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("库存不足")
|
||||
}
|
||||
}
|
||||
return tx.Create(order).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) UpdateStatus(id uint, status string) error {
|
||||
allowed := map[string]bool{
|
||||
model.OrderStatusPending: true,
|
||||
model.OrderStatusPaid: true,
|
||||
model.OrderStatusDelivered: true,
|
||||
model.OrderStatusCancelled: true,
|
||||
}
|
||||
if !allowed[status] {
|
||||
return errors.New("无效的订单状态")
|
||||
}
|
||||
res := s.db.Model(&model.Order{}).Where("id = ?", id).Update("status", status)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("订单不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type DashboardStats struct {
|
||||
SkinCount int64 `json:"skin_count"`
|
||||
DistributorCount int64 `json:"distributor_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalSales float64 `json:"total_sales"`
|
||||
TotalCommission float64 `json:"total_commission"`
|
||||
PendingOrderCount int64 `json:"pending_order_count"`
|
||||
}
|
||||
|
||||
func (s *OrderService) Dashboard() (*DashboardStats, error) {
|
||||
stats := &DashboardStats{}
|
||||
s.db.Model(&model.Skin{}).Count(&stats.SkinCount)
|
||||
s.db.Model(&model.User{}).Where("role = ?", model.RoleDistributor).Count(&stats.DistributorCount)
|
||||
s.db.Model(&model.Order{}).Count(&stats.OrderCount)
|
||||
s.db.Model(&model.Order{}).Where("status = ?", model.OrderStatusPending).Count(&stats.PendingOrderCount)
|
||||
s.db.Model(&model.Order{}).
|
||||
Where("status IN ?", []string{model.OrderStatusPaid, model.OrderStatusDelivered}).
|
||||
Select("COALESCE(SUM(amount),0)").Scan(&stats.TotalSales)
|
||||
s.db.Model(&model.Order{}).
|
||||
Where("status IN ?", []string{model.OrderStatusPaid, model.OrderStatusDelivered}).
|
||||
Select("COALESCE(SUM(commission_amt),0)").Scan(&stats.TotalCommission)
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func generateOrderNo() string {
|
||||
return fmt.Sprintf("O%s%04d", time.Now().Format("20060102150405"), time.Now().Nanosecond()%10000)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SkinService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSkinService(db *gorm.DB) *SkinService {
|
||||
return &SkinService{db: db}
|
||||
}
|
||||
|
||||
type SkinListQuery struct {
|
||||
Page int
|
||||
Size int
|
||||
Keyword string
|
||||
Game string
|
||||
Category string
|
||||
Status *int
|
||||
}
|
||||
|
||||
func (s *SkinService) List(q SkinListQuery) ([]model.Skin, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.Skin{})
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("name LIKE ?", "%"+q.Keyword+"%")
|
||||
}
|
||||
if q.Game != "" {
|
||||
tx = tx.Where("game = ?", q.Game)
|
||||
}
|
||||
if q.Category != "" {
|
||||
tx = tx.Where("category = ?", q.Category)
|
||||
}
|
||||
if q.Status != nil {
|
||||
tx = tx.Where("status = ?", *q.Status)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.Skin
|
||||
err := tx.Order("id DESC").Offset((q.Page - 1) * q.Size).Limit(q.Size).Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *SkinService) Get(id uint) (*model.Skin, error) {
|
||||
var skin model.Skin
|
||||
if err := s.db.First(&skin, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("皮肤不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &skin, nil
|
||||
}
|
||||
|
||||
func (s *SkinService) Create(skin *model.Skin) error {
|
||||
return s.db.Create(skin).Error
|
||||
}
|
||||
|
||||
func (s *SkinService) Update(id uint, updates map[string]interface{}) error {
|
||||
res := s.db.Model(&model.Skin{}).Where("id = ?", id).Updates(updates)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("皮肤不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SkinService) Delete(id uint) error {
|
||||
res := s.db.Delete(&model.Skin{}, id)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("皮肤不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SkinService) SeedDemo() error {
|
||||
var count int64
|
||||
s.db.Model(&model.Skin{}).Count(&count)
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
demos := []model.Skin{
|
||||
{Name: "龙之觉醒", Game: "王者荣耀", Category: "史诗", Price: 88, CostPrice: 50, Commission: 0.15, Stock: -1, Status: 1, Description: "史诗皮肤示例"},
|
||||
{Name: "星空旅人", Game: "和平精英", Category: "限定", Price: 128, CostPrice: 80, Commission: 0.12, Stock: 100, Status: 1, Description: "限定皮肤示例"},
|
||||
{Name: "暗夜骑士", Game: "英雄联盟", Category: "传说", Price: 199, CostPrice: 120, Commission: 0.10, Stock: 50, Status: 1, Description: "传说皮肤示例"},
|
||||
}
|
||||
return s.db.Create(&demos).Error
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserService(db *gorm.DB) *UserService {
|
||||
return &UserService{db: db}
|
||||
}
|
||||
|
||||
type UserListQuery struct {
|
||||
Page int
|
||||
Size int
|
||||
Keyword string
|
||||
Role string
|
||||
Status *int
|
||||
}
|
||||
|
||||
func (s *UserService) List(q UserListQuery) ([]model.User, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.User{})
|
||||
if q.Keyword != "" {
|
||||
like := "%" + q.Keyword + "%"
|
||||
tx = tx.Where("username LIKE ? OR nickname LIKE ?", like, like)
|
||||
}
|
||||
if q.Role != "" {
|
||||
tx = tx.Where("role = ?", q.Role)
|
||||
}
|
||||
if q.Status != nil {
|
||||
tx = tx.Where("status = ?", *q.Status)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.User
|
||||
err := tx.Order("id DESC").Offset((q.Page - 1) * q.Size).Limit(q.Size).Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *UserService) Create(username, password, nickname, role string, parentID *uint) (*model.User, error) {
|
||||
var count int64
|
||||
s.db.Model(&model.User{}).Where("username = ?", username).Count(&count)
|
||||
if count > 0 {
|
||||
return nil, errors.New("用户名已存在")
|
||||
}
|
||||
if role == "" {
|
||||
role = model.RoleDistributor
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := &model.User{
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: nickname,
|
||||
Role: role,
|
||||
Status: 1,
|
||||
InviteCode: generateInviteCode(),
|
||||
ParentID: parentID,
|
||||
}
|
||||
if user.Nickname == "" {
|
||||
user.Nickname = username
|
||||
}
|
||||
if err := s.db.Create(user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *UserService) UpdateStatus(id uint, status int) error {
|
||||
res := s.db.Model(&model.User{}).Where("id = ?", id).Update("status", status)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("用户不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user