This commit is contained in:
yml2213
2026-07-20 14:58:57 +08:00
commit 45db0aa4b9
50 changed files with 5861 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
# backend
backend/bin/
backend/data/
*.db
# frontend
frontend/node_modules/
frontend/dist/
# ide / os
.DS_Store
.idea/
.vscode/
*.log
+21
View File
@@ -0,0 +1,21 @@
.PHONY: start dev backend frontend install stop
# 一键启动前后端(推荐)
start dev:
@bash ./start.sh
backend:
cd backend && go run ./cmd/server
frontend:
cd frontend && npm run dev
install:
cd backend && go mod tidy
cd frontend && npm install
# 停止占用默认端口的进程
stop:
@-lsof -tiTCP:8080 -sTCP:LISTEN | xargs kill 2>/dev/null || true
@-lsof -tiTCP:5173 -sTCP:LISTEN | xargs kill 2>/dev/null || true
@echo "已尝试停止 8080 / 5173 端口服务"
+5
View File
@@ -0,0 +1,5 @@
bin/
data/
*.db
*.exe
.DS_Store
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"log"
"os"
"path/filepath"
"affiliate_dash/internal/config"
"affiliate_dash/internal/handler"
"affiliate_dash/internal/model"
"affiliate_dash/internal/pkg/jwt"
"affiliate_dash/internal/router"
"affiliate_dash/internal/service"
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func main() {
cfg := config.Load()
gin.SetMode(cfg.Mode)
if err := os.MkdirAll(filepath.Dir(cfg.DBPath), 0o755); err != nil {
log.Fatalf("create data dir: %v", err)
}
db, err := gorm.Open(sqlite.Open(cfg.DBPath), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Fatalf("open db: %v", err)
}
if err := db.AutoMigrate(&model.User{}, &model.Skin{}, &model.Order{}); err != nil {
log.Fatalf("migrate: %v", err)
}
jm := jwt.NewManager(cfg.JWTSecret)
authSvc := service.NewAuthService(db, jm)
skinSvc := service.NewSkinService(db)
orderSvc := service.NewOrderService(db)
userSvc := service.NewUserService(db)
if err := authSvc.EnsureAdmin(); err != nil {
log.Fatalf("ensure admin: %v", err)
}
if err := skinSvc.SeedDemo(); err != nil {
log.Printf("seed skins: %v", err)
}
h := &router.Handlers{
Auth: handler.NewAuthHandler(authSvc),
Skin: handler.NewSkinHandler(skinSvc),
Order: handler.NewOrderHandler(orderSvc),
User: handler.NewUserHandler(userSvc),
JWT: jm,
}
r := router.Setup(h)
addr := ":" + cfg.Port
log.Printf("游戏皮肤分销系统 API 启动: http://localhost%s", addr)
log.Printf("默认管理员: admin / admin123")
if err := r.Run(addr); err != nil {
log.Fatalf("server: %v", err)
}
}
+46
View File
@@ -0,0 +1,46 @@
module affiliate_dash
go 1.26.3
require (
github.com/gin-contrib/cors v1.7.7
github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.3.1
golang.org/x/crypto v0.54.0
gorm.io/driver/sqlite v1.6.0
gorm.io/gorm v1.31.2
)
require (
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
)
+103
View File
@@ -0,0 +1,103 @@
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
+38
View File
@@ -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
}
+65
View File
@@ -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)
}
+105
View File
@@ -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)
}
+123
View File
@@ -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)
}
+79
View File
@@ -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)
}
+72
View File
@@ -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
}
+75
View File
@@ -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"
)
+58
View File
@@ -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
}
+52
View File
@@ -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})
}
+71
View File
@@ -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
}
+110
View File
@@ -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))
}
+150
View File
@@ -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)
}
+106
View File
@@ -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
}
+95
View File
@@ -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
}
+28
View File
@@ -0,0 +1,28 @@
商品 sku
套装-Alan Walker
套装-暗影哥特
黑色高级特训官上衣
M416-仓鼠灰灰
萌熊伴侣背包
套装-双彩绵绵
套装-糯粉咩咩
套装-恋恋初桃
套装-浪漫天命
西部牛仔大礼包
烟雾弹-糯粉咩咩
破片手榴弹-糯粉咩咩
套装-仓鼠灰灰
套装-萌熊伴侣
糯粉咩咩背包
糯粉咩咩头盔
仓鼠灰灰背包
仓鼠灰灰头盔
套装-西部谜踪
国宝胖达头盔
套装-胖达圆圆
套装-胖达团团
熔岩游骑兵礼包
套装-狂沙舞者
星际漫游服装礼包
星际漫游枪械礼包
套装-绵云熊熊
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+32
View File
@@ -0,0 +1,32 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>游戏皮肤分销系统</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2763
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@ant-design/icons": "^6.3.2",
"antd": "^6.5.1",
"axios": "^1.18.1",
"dayjs": "^1.11.21",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3",
"oxlint": "^1.71.0",
"typescript": "~6.0.2",
"vite": "^8.1.1"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+76
View File
@@ -0,0 +1,76 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import { ConfigProvider, App as AntdApp } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import { AuthProvider, useAuth } from './store/auth'
import MainLayout from './layouts/MainLayout'
import Login from './pages/Login'
import Register from './pages/Register'
import Dashboard from './pages/Dashboard'
import Skins from './pages/Skins'
import Orders from './pages/Orders'
import Distributors from './pages/Distributors'
import type { ReactNode } from 'react'
function PrivateRoute({ children }: { children: ReactNode }) {
const { token } = useAuth()
if (!token) return <Navigate to="/login" replace />
return <>{children}</>
}
function AdminRoute({ children }: { children: ReactNode }) {
const { isAdmin } = useAuth()
if (!isAdmin) return <Navigate to="/" replace />
return <>{children}</>
}
function AppRoutes() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route
path="/"
element={
<PrivateRoute>
<MainLayout />
</PrivateRoute>
}
>
<Route index element={<Dashboard />} />
<Route path="skins" element={<Skins />} />
<Route path="orders" element={<Orders />} />
<Route
path="distributors"
element={
<AdminRoute>
<Distributors />
</AdminRoute>
}
/>
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}
export default function App() {
return (
<ConfigProvider
locale={zhCN}
theme={{
token: {
colorPrimary: '#1677ff',
borderRadius: 6,
},
}}
>
<AntdApp>
<AuthProvider>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
</AuthProvider>
</AntdApp>
</ConfigProvider>
)
}
+60
View File
@@ -0,0 +1,60 @@
import request from './request'
import type {
DashboardStats,
LoginResult,
Order,
PageResult,
Skin,
User,
} from '../types'
export const authApi = {
login: async (username: string, password: string) => {
const res = await request.post('/auth/login', { username, password })
return res.data.data as LoginResult
},
register: async (data: { username: string; password: string; nickname?: string }) => {
const res = await request.post('/auth/register', data)
return res.data.data as User
},
profile: async () => {
const res = await request.get('/auth/profile')
return res.data.data as User
},
}
export const dashboardApi = {
stats: () =>
request.get('/dashboard').then((r) => r.data.data as DashboardStats),
}
export const skinApi = {
list: (params?: Record<string, unknown>) =>
request.get('/skins', { params }).then((r) => r.data.data as PageResult<Skin>),
get: (id: number) =>
request.get(`/skins/${id}`).then((r) => r.data.data as Skin),
create: (data: Partial<Skin>) =>
request.post('/skins', data).then((r) => r.data.data as Skin),
update: (id: number, data: Partial<Skin>) =>
request.put(`/skins/${id}`, data).then((r) => r.data.data),
remove: (id: number) =>
request.delete(`/skins/${id}`).then((r) => r.data.data),
}
export const orderApi = {
list: (params?: Record<string, unknown>) =>
request.get('/orders', { params }).then((r) => r.data.data as PageResult<Order>),
create: (data: { skin_id: number; buyer_name?: string; remark?: string }) =>
request.post('/orders', data).then((r) => r.data.data as Order),
updateStatus: (id: number, status: string) =>
request.patch(`/orders/${id}/status`, { status }).then((r) => r.data.data),
}
export const userApi = {
list: (params?: Record<string, unknown>) =>
request.get('/users', { params }).then((r) => r.data.data as PageResult<User>),
create: (data: { username: string; password: string; nickname?: string; role?: string }) =>
request.post('/users', data).then((r) => r.data.data as User),
updateStatus: (id: number, status: number) =>
request.patch(`/users/${id}/status`, { status }).then((r) => r.data.data),
}
+38
View File
@@ -0,0 +1,38 @@
import axios from 'axios'
import type { ApiResponse } from '../types'
const request = axios.create({
baseURL: '/api',
timeout: 15000,
})
request.interceptors.request.use((config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
request.interceptors.response.use(
(res) => {
const body = res.data as ApiResponse
if (body.code !== 0) {
return Promise.reject(new Error(body.message || '请求失败'))
}
return res
},
(err) => {
const msg = err.response?.data?.message || err.message || '网络错误'
if (err.response?.status === 401) {
localStorage.removeItem('token')
localStorage.removeItem('user')
if (!window.location.pathname.includes('/login')) {
window.location.href = '/login'
}
}
return Promise.reject(new Error(msg))
},
)
export default request
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

+17
View File
@@ -0,0 +1,17 @@
* {
box-sizing: border-box;
}
html,
body,
#root {
margin: 0;
padding: 0;
min-height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
Arial, 'Noto Sans', sans-serif;
}
a {
color: #1677ff;
}
+126
View File
@@ -0,0 +1,126 @@
import { useMemo, useState } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import {
Layout,
Menu,
theme,
Dropdown,
Space,
Typography,
Avatar,
} from 'antd'
import {
DashboardOutlined,
SkinOutlined,
ShoppingOutlined,
TeamOutlined,
UserOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons'
import { useAuth } from '../store/auth'
import type { MenuProps } from 'antd'
const { Header, Sider, Content } = Layout
export default function MainLayout() {
const [collapsed, setCollapsed] = useState(false)
const { user, logout, isAdmin } = useAuth()
const navigate = useNavigate()
const location = useLocation()
const {
token: { colorBgContainer, borderRadiusLG },
} = theme.useToken()
const menuItems: MenuProps['items'] = useMemo(() => {
const items: MenuProps['items'] = [
{ key: '/', icon: <DashboardOutlined />, label: '数据概览' },
{ key: '/skins', icon: <SkinOutlined />, label: '皮肤商品' },
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单管理' },
]
if (isAdmin) {
items.push({ key: '/distributors', icon: <TeamOutlined />, label: '分销商' })
}
return items
}, [isAdmin])
const userMenu: MenuProps['items'] = [
{
key: 'logout',
icon: <LogoutOutlined />,
label: '退出登录',
onClick: () => {
logout()
navigate('/login')
},
},
]
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider trigger={null} collapsible collapsed={collapsed} theme="dark">
<div
style={{
height: 64,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontWeight: 700,
fontSize: collapsed ? 14 : 16,
letterSpacing: 1,
}}
>
{collapsed ? '皮肤' : '皮肤分销系统'}
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={[location.pathname === '/' ? '/' : `/${location.pathname.split('/')[1]}`]}
items={menuItems}
onClick={({ key }) => navigate(key)}
/>
</Sider>
<Layout>
<Header
style={{
padding: '0 24px',
background: colorBgContainer,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span
style={{ fontSize: 18, cursor: 'pointer' }}
onClick={() => setCollapsed(!collapsed)}
>
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</span>
<Dropdown menu={{ items: userMenu }}>
<Space style={{ cursor: 'pointer' }}>
<Avatar size="small" icon={<UserOutlined />} />
<Typography.Text>
{user?.nickname || user?.username}
{isAdmin ? '(管理员)' : '(分销商)'}
</Typography.Text>
</Space>
</Dropdown>
</Header>
<Content style={{ margin: 24 }}>
<div
style={{
padding: 24,
minHeight: 360,
background: colorBgContainer,
borderRadius: borderRadiusLG,
}}
>
<Outlet />
</div>
</Content>
</Layout>
</Layout>
)
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+90
View File
@@ -0,0 +1,90 @@
import { useEffect, useState } from 'react'
import { Card, Col, Row, Statistic, Typography, Spin, message } from 'antd'
import {
SkinOutlined,
TeamOutlined,
ShoppingOutlined,
DollarOutlined,
PercentageOutlined,
ClockCircleOutlined,
} from '@ant-design/icons'
import { dashboardApi } from '../api'
import type { DashboardStats } from '../types'
export default function Dashboard() {
const [stats, setStats] = useState<DashboardStats | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
dashboardApi
.stats()
.then(setStats)
.catch((e) => message.error(e.message))
.finally(() => setLoading(false))
}, [])
if (loading) {
return (
<div style={{ textAlign: 'center', padding: 80 }}>
<Spin size="large" />
</div>
)
}
return (
<div>
<Typography.Title level={4} style={{ marginTop: 0 }}>
</Typography.Title>
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic title="皮肤商品" value={stats?.skin_count ?? 0} prefix={<SkinOutlined />} />
</Card>
</Col>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic title="分销商" value={stats?.distributor_count ?? 0} prefix={<TeamOutlined />} />
</Card>
</Col>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic title="订单总数" value={stats?.order_count ?? 0} prefix={<ShoppingOutlined />} />
</Card>
</Col>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic
title="成交金额"
value={stats?.total_sales ?? 0}
precision={2}
prefix={<DollarOutlined />}
suffix="元"
/>
</Card>
</Col>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic
title="累计佣金"
value={stats?.total_commission ?? 0}
precision={2}
prefix={<PercentageOutlined />}
suffix="元"
/>
</Card>
</Col>
<Col xs={24} sm={12} lg={8}>
<Card>
<Statistic
title="待处理订单"
value={stats?.pending_order_count ?? 0}
prefix={<ClockCircleOutlined />}
valueStyle={{ color: (stats?.pending_order_count ?? 0) > 0 ? '#cf1322' : undefined }}
/>
</Card>
</Col>
</Row>
</div>
)
}
+169
View File
@@ -0,0 +1,169 @@
import { useCallback, useEffect, useState } from 'react'
import {
Button,
Form,
Input,
Modal,
Space,
Switch,
Table,
Tag,
Typography,
message,
} from 'antd'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'
import { userApi } from '../api'
import type { User } from '../types'
export default function Distributors() {
const [list, setList] = useState<User[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [size, setSize] = useState(10)
const [keyword, setKeyword] = useState('')
const [loading, setLoading] = useState(false)
const [open, setOpen] = useState(false)
const [form] = Form.useForm()
const load = useCallback(async () => {
setLoading(true)
try {
const data = await userApi.list({
page,
size,
keyword,
role: 'distributor',
})
setList(data.list || [])
setTotal(data.total)
} catch (e) {
message.error(e instanceof Error ? e.message : '加载失败')
} finally {
setLoading(false)
}
}, [page, size, keyword])
useEffect(() => {
load()
}, [load])
const onSubmit = async () => {
const values = await form.validateFields()
try {
await userApi.create({ ...values, role: 'distributor' })
message.success('创建成功')
setOpen(false)
form.resetFields()
load()
} catch (e) {
message.error(e instanceof Error ? e.message : '创建失败')
}
}
const toggleStatus = async (record: User, checked: boolean) => {
try {
await userApi.updateStatus(record.id, checked ? 1 : 0)
message.success('状态已更新')
load()
} catch (e) {
message.error(e instanceof Error ? e.message : '更新失败')
}
}
const columns: ColumnsType<User> = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '用户名', dataIndex: 'username' },
{ title: '昵称', dataIndex: 'nickname' },
{
title: '邀请码',
dataIndex: 'invite_code',
render: (v: string) => <Tag color="blue">{v}</Tag>,
},
{
title: '状态',
dataIndex: 'status',
width: 120,
render: (v: number, record) => (
<Switch
checkedChildren="启用"
unCheckedChildren="禁用"
checked={v === 1}
onChange={(checked) => toggleStatus(record, checked)}
/>
),
},
{
title: '注册时间',
dataIndex: 'created_at',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
]
return (
<div>
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
<Space>
<Input.Search
placeholder="搜索用户名/昵称"
allowClear
onSearch={(v) => {
setPage(1)
setKeyword(v)
}}
style={{ width: 220 }}
/>
<Button icon={<ReloadOutlined />} onClick={load}>
</Button>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => {
form.resetFields()
setOpen(true)
}}
>
</Button>
</Space>
</Space>
<Table
rowKey="id"
loading={loading}
columns={columns}
dataSource={list}
pagination={{
current: page,
pageSize: size,
total,
showSizeChanger: true,
onChange: (p, s) => {
setPage(p)
setSize(s)
},
}}
/>
<Modal title="新增分销商" open={open} onOk={onSubmit} onCancel={() => setOpen(false)} destroyOnClose>
<Form form={form} layout="vertical" style={{ marginTop: 16 }}>
<Form.Item name="username" label="用户名" rules={[{ required: true, min: 3 }]}>
<Input />
</Form.Item>
<Form.Item name="nickname" label="昵称">
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true, min: 6 }]}>
<Input.Password />
</Form.Item>
</Form>
</Modal>
</div>
)
}
+68
View File
@@ -0,0 +1,68 @@
import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Card, Form, Input, Button, Typography, message, Space } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useAuth } from '../store/auth'
export default function Login() {
const { login } = useAuth()
const navigate = useNavigate()
const [loading, setLoading] = useState(false)
const onFinish = async (values: { username: string; password: string }) => {
setLoading(true)
try {
await login(values.username, values.password)
message.success('登录成功')
navigate('/')
} catch (e) {
message.error(e instanceof Error ? e.message : '登录失败')
} finally {
setLoading(false)
}
}
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
}}
>
<Card style={{ width: 400, boxShadow: '0 8px 32px rgba(0,0,0,0.3)' }}>
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div style={{ textAlign: 'center' }}>
<Typography.Title level={3} style={{ marginBottom: 4 }}>
</Typography.Title>
<Typography.Text type="secondary"></Typography.Text>
</div>
<Form layout="vertical" onFinish={onFinish} initialValues={{ username: 'admin', password: 'admin123' }}>
<Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
<Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
</Form.Item>
<Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
<Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block size="large">
</Button>
</Form.Item>
</Form>
<div style={{ textAlign: 'center' }}>
<Typography.Text type="secondary">
<Link to="/register"></Link>
</Typography.Text>
</div>
<Typography.Paragraph type="secondary" style={{ fontSize: 12, marginBottom: 0, textAlign: 'center' }}>
admin / admin123
</Typography.Paragraph>
</Space>
</Card>
</div>
)
}
+177
View File
@@ -0,0 +1,177 @@
import { useCallback, useEffect, useState } from 'react'
import {
Button,
Select,
Space,
Table,
Tag,
Typography,
message,
} from 'antd'
import { ReloadOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'
import { orderApi } from '../api'
import { useAuth } from '../store/auth'
import type { Order } from '../types'
const statusMap: Record<string, { color: string; text: string }> = {
pending: { color: 'orange', text: '待支付' },
paid: { color: 'blue', text: '已支付' },
delivered: { color: 'green', text: '已交付' },
cancelled: { color: 'default', text: '已取消' },
}
export default function Orders() {
const { isAdmin } = useAuth()
const [list, setList] = useState<Order[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [size, setSize] = useState(10)
const [status, setStatus] = useState<string | undefined>()
const [loading, setLoading] = useState(false)
const load = useCallback(async () => {
setLoading(true)
try {
const data = await orderApi.list({ page, size, status })
setList(data.list || [])
setTotal(data.total)
} catch (e) {
message.error(e instanceof Error ? e.message : '加载失败')
} finally {
setLoading(false)
}
}, [page, size, status])
useEffect(() => {
load()
}, [load])
const changeStatus = async (id: number, next: string) => {
try {
await orderApi.updateStatus(id, next)
message.success('状态已更新')
load()
} catch (e) {
message.error(e instanceof Error ? e.message : '更新失败')
}
}
const columns: ColumnsType<Order> = [
{ title: '订单号', dataIndex: 'order_no', width: 200 },
{
title: '皮肤',
dataIndex: ['skin', 'name'],
render: (_, r) => r.skin?.name || `#${r.skin_id}`,
},
{
title: '分销商',
dataIndex: ['distributor', 'nickname'],
render: (_, r) => r.distributor?.nickname || r.distributor?.username || `#${r.distributor_id}`,
},
{ title: '买家', dataIndex: 'buyer_name', width: 100 },
{
title: '金额',
dataIndex: 'amount',
width: 100,
render: (v: number) => `¥${v.toFixed(2)}`,
},
{
title: '佣金',
dataIndex: 'commission_amt',
width: 100,
render: (v: number) => `¥${v.toFixed(2)}`,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (v: string) => {
const s = statusMap[v] || { color: 'default', text: v }
return <Tag color={s.color}>{s.text}</Tag>
},
},
{
title: '时间',
dataIndex: 'created_at',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
]
if (isAdmin) {
columns.push({
title: '操作',
key: 'action',
width: 220,
render: (_, record) => (
<Space>
{record.status === 'pending' && (
<>
<Button type="link" size="small" onClick={() => changeStatus(record.id, 'paid')}>
</Button>
<Button type="link" size="small" danger onClick={() => changeStatus(record.id, 'cancelled')}>
</Button>
</>
)}
{record.status === 'paid' && (
<Button type="link" size="small" onClick={() => changeStatus(record.id, 'delivered')}>
</Button>
)}
</Space>
),
})
}
return (
<div>
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
<Space>
<Select
allowClear
placeholder="订单状态"
style={{ width: 140 }}
value={status}
onChange={(v) => {
setPage(1)
setStatus(v)
}}
options={[
{ value: 'pending', label: '待支付' },
{ value: 'paid', label: '已支付' },
{ value: 'delivered', label: '已交付' },
{ value: 'cancelled', label: '已取消' },
]}
/>
<Button icon={<ReloadOutlined />} onClick={load}>
</Button>
</Space>
</Space>
<Table
rowKey="id"
loading={loading}
columns={columns}
dataSource={list}
pagination={{
current: page,
pageSize: size,
total,
showSizeChanger: true,
onChange: (p, s) => {
setPage(p)
setSize(s)
},
}}
/>
</div>
)
}
+71
View File
@@ -0,0 +1,71 @@
import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Card, Form, Input, Button, Typography, message, Space } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { authApi } from '../api'
export default function Register() {
const navigate = useNavigate()
const [loading, setLoading] = useState(false)
const onFinish = async (values: {
username: string
password: string
nickname?: string
}) => {
setLoading(true)
try {
await authApi.register(values)
message.success('注册成功,请登录')
navigate('/login')
} catch (e) {
message.error(e instanceof Error ? e.message : '注册失败')
} finally {
setLoading(false)
}
}
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
}}
>
<Card style={{ width: 400, boxShadow: '0 8px 32px rgba(0,0,0,0.3)' }}>
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div style={{ textAlign: 'center' }}>
<Typography.Title level={3} style={{ marginBottom: 4 }}>
</Typography.Title>
<Typography.Text type="secondary"></Typography.Text>
</div>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item name="username" rules={[{ required: true, min: 3, message: '用户名至少3位' }]}>
<Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
</Form.Item>
<Form.Item name="nickname">
<Input prefix={<UserOutlined />} placeholder="昵称(可选)" size="large" />
</Form.Item>
<Form.Item name="password" rules={[{ required: true, min: 6, message: '密码至少6位' }]}>
<Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block size="large">
</Button>
</Form.Item>
</Form>
<div style={{ textAlign: 'center' }}>
<Typography.Text type="secondary">
<Link to="/login"></Link>
</Typography.Text>
</div>
</Space>
</Card>
</div>
)
}
+252
View File
@@ -0,0 +1,252 @@
import { useCallback, useEffect, useState } from 'react'
import {
Button,
Form,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Space,
Table,
Tag,
Typography,
message,
} from 'antd'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { skinApi, orderApi } from '../api'
import { useAuth } from '../store/auth'
import type { Skin } from '../types'
export default function Skins() {
const { isAdmin } = useAuth()
const [list, setList] = useState<Skin[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [size, setSize] = useState(10)
const [keyword, setKeyword] = useState('')
const [loading, setLoading] = useState(false)
const [open, setOpen] = useState(false)
const [editing, setEditing] = useState<Skin | null>(null)
const [form] = Form.useForm()
const load = useCallback(async () => {
setLoading(true)
try {
const data = await skinApi.list({ page, size, keyword })
setList(data.list || [])
setTotal(data.total)
} catch (e) {
message.error(e instanceof Error ? e.message : '加载失败')
} finally {
setLoading(false)
}
}, [page, size, keyword])
useEffect(() => {
load()
}, [load])
const openCreate = () => {
setEditing(null)
form.resetFields()
form.setFieldsValue({ stock: -1, commission: 0.1, status: 1 })
setOpen(true)
}
const openEdit = (record: Skin) => {
setEditing(record)
form.setFieldsValue(record)
setOpen(true)
}
const onSubmit = async () => {
const values = await form.validateFields()
try {
if (editing) {
await skinApi.update(editing.id, values)
message.success('更新成功')
} else {
await skinApi.create(values)
message.success('创建成功')
}
setOpen(false)
load()
} catch (e) {
message.error(e instanceof Error ? e.message : '操作失败')
}
}
const onDelete = async (id: number) => {
try {
await skinApi.remove(id)
message.success('已删除')
load()
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
}
}
const onOrder = async (skin: Skin) => {
try {
await orderApi.create({ skin_id: skin.id, buyer_name: '演示买家' })
message.success('下单成功')
} catch (e) {
message.error(e instanceof Error ? e.message : '下单失败')
}
}
const columns: ColumnsType<Skin> = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '名称', dataIndex: 'name' },
{ title: '游戏', dataIndex: 'game', width: 120 },
{ title: '分类', dataIndex: 'category', width: 100 },
{
title: '售价',
dataIndex: 'price',
width: 100,
render: (v: number) => `¥${v.toFixed(2)}`,
},
{
title: '佣金比例',
dataIndex: 'commission',
width: 100,
render: (v: number) => `${(v * 100).toFixed(0)}%`,
},
{
title: '库存',
dataIndex: 'stock',
width: 80,
render: (v: number) => (v < 0 ? '无限' : v),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: number) =>
v === 1 ? <Tag color="green"></Tag> : <Tag></Tag>,
},
{
title: '操作',
key: 'action',
width: isAdmin ? 200 : 100,
render: (_, record) => (
<Space>
{isAdmin ? (
<>
<Button type="link" size="small" onClick={() => openEdit(record)}>
</Button>
<Popconfirm title="确认删除?" onConfirm={() => onDelete(record.id)}>
<Button type="link" size="small" danger>
</Button>
</Popconfirm>
</>
) : (
<Button type="link" size="small" disabled={record.status !== 1} onClick={() => onOrder(record)}>
</Button>
)}
</Space>
),
},
]
return (
<div>
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
<Space>
<Input.Search
placeholder="搜索名称"
allowClear
onSearch={(v) => {
setPage(1)
setKeyword(v)
}}
style={{ width: 220 }}
/>
<Button icon={<ReloadOutlined />} onClick={load}>
</Button>
{isAdmin && (
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
</Button>
)}
</Space>
</Space>
<Table
rowKey="id"
loading={loading}
columns={columns}
dataSource={list}
pagination={{
current: page,
pageSize: size,
total,
showSizeChanger: true,
onChange: (p, s) => {
setPage(p)
setSize(s)
},
}}
/>
<Modal
title={editing ? '编辑皮肤' : '新增皮肤'}
open={open}
onOk={onSubmit}
onCancel={() => setOpen(false)}
destroyOnClose
width={560}
>
<Form form={form} layout="vertical" style={{ marginTop: 16 }}>
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Space style={{ width: '100%' }} size="middle">
<Form.Item name="game" label="游戏" style={{ width: 240 }}>
<Input />
</Form.Item>
<Form.Item name="category" label="分类" style={{ width: 240 }}>
<Input />
</Form.Item>
</Space>
<Space style={{ width: '100%' }} size="middle">
<Form.Item name="price" label="售价" rules={[{ required: true }]} style={{ width: 160 }}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="cost_price" label="成本价" style={{ width: 160 }}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="commission" label="佣金比例" style={{ width: 160 }}>
<InputNumber min={0} max={1} step={0.01} style={{ width: '100%' }} />
</Form.Item>
</Space>
<Space style={{ width: '100%' }} size="middle">
<Form.Item name="stock" label="库存(-1无限)" style={{ width: 240 }}>
<InputNumber style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="status" label="状态" style={{ width: 240 }}>
<Select
options={[
{ value: 1, label: '上架' },
{ value: 0, label: '下架' },
]}
/>
</Form.Item>
</Space>
<Form.Item name="description" label="描述">
<Input.TextArea rows={3} />
</Form.Item>
</Form>
</Modal>
</div>
)
}
+76
View File
@@ -0,0 +1,76 @@
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
type ReactNode,
} from 'react'
import type { User } from '../types'
import { authApi } from '../api'
interface AuthState {
token: string | null
user: User | null
login: (username: string, password: string) => Promise<void>
logout: () => void
refreshProfile: () => Promise<void>
isAdmin: boolean
}
const AuthContext = createContext<AuthState | null>(null)
function loadUser(): User | null {
try {
const raw = localStorage.getItem('user')
return raw ? (JSON.parse(raw) as User) : null
} catch {
return null
}
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'))
const [user, setUser] = useState<User | null>(() => loadUser())
const login = useCallback(async (username: string, password: string) => {
const result = await authApi.login(username, password)
localStorage.setItem('token', result.token)
localStorage.setItem('user', JSON.stringify(result.user))
setToken(result.token)
setUser(result.user)
}, [])
const logout = useCallback(() => {
localStorage.removeItem('token')
localStorage.removeItem('user')
setToken(null)
setUser(null)
}, [])
const refreshProfile = useCallback(async () => {
const profile = await authApi.profile()
localStorage.setItem('user', JSON.stringify(profile))
setUser(profile)
}, [])
const value = useMemo(
() => ({
token,
user,
login,
logout,
refreshProfile,
isAdmin: user?.role === 'admin',
}),
[token, user, login, logout, refreshProfile],
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
return ctx
}
+67
View File
@@ -0,0 +1,67 @@
export interface User {
id: number
username: string
nickname: string
role: 'admin' | 'distributor'
status: number
invite_code: string
parent_id?: number | null
created_at: string
}
export interface Skin {
id: number
name: string
game: string
category: string
cover_url: string
price: number
cost_price: number
commission: number
stock: number
status: number
description: string
created_at: string
}
export interface Order {
id: number
order_no: string
skin_id: number
skin?: Skin
distributor_id: number
distributor?: User
buyer_name: string
amount: number
commission_amt: number
status: string
remark: string
created_at: string
}
export interface DashboardStats {
skin_count: number
distributor_count: number
order_count: number
total_sales: number
total_commission: number
pending_order_count: number
}
export interface PageResult<T> {
list: T[]
total: number
page: number
size: number
}
export interface ApiResponse<T = unknown> {
code: number
message: string
data: T
}
export interface LoginResult {
token: string
user: User
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/health': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
})
Executable
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env bash
# 一键启动前后端开发服务
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_PORT="${PORT:-8080}"
FRONTEND_PORT="${FRONTEND_PORT:-5173}"
PIDS=()
log() { echo ">>> $*"; }
# 结束指定端口上的进程(避免残留占用)
free_port() {
local port=$1
local pids
pids=$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null || true)
if [[ -n "${pids}" ]]; then
log "端口 ${port} 已被占用,正在释放: ${pids}"
# shellcheck disable=SC2086
kill ${pids} 2>/dev/null || true
sleep 0.5
pids=$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null || true)
if [[ -n "${pids}" ]]; then
# shellcheck disable=SC2086
kill -9 ${pids} 2>/dev/null || true
fi
fi
}
cleanup() {
trap - INT TERM EXIT
echo ""
log "正在停止前后端..."
for pid in "${PIDS[@]:-}"; do
if kill -0 "$pid" 2>/dev/null; then
# 结束子进程树
pkill -P "$pid" 2>/dev/null || true
kill "$pid" 2>/dev/null || true
fi
done
free_port "$BACKEND_PORT"
free_port "$FRONTEND_PORT"
wait 2>/dev/null || true
log "已全部停止"
exit 0
}
trap cleanup INT TERM
# 检查依赖
if ! command -v go >/dev/null 2>&1; then
echo "错误: 未找到 go,请先安装 Go"
exit 1
fi
if ! command -v npm >/dev/null 2>&1; then
echo "错误: 未找到 npm,请先安装 Node.js"
exit 1
fi
# 首次安装前端依赖
if [[ ! -d "$ROOT/frontend/node_modules" ]]; then
log "安装前端依赖..."
(cd "$ROOT/frontend" && npm install)
fi
free_port "$BACKEND_PORT"
free_port "$FRONTEND_PORT"
log "启动后端 http://localhost:${BACKEND_PORT}"
(
cd "$ROOT/backend"
export PORT="$BACKEND_PORT"
go run ./cmd/server
) &
PIDS+=($!)
# 等后端健康检查就绪(最多约 15 秒)
for i in $(seq 1 30); do
if curl -sf "http://127.0.0.1:${BACKEND_PORT}/health" >/dev/null 2>&1; then
log "后端已就绪"
break
fi
if ! kill -0 "${PIDS[0]}" 2>/dev/null; then
echo "错误: 后端启动失败"
cleanup
fi
sleep 0.5
done
log "启动前端 http://localhost:${FRONTEND_PORT}"
(
cd "$ROOT/frontend"
npm run dev -- --host --port "$FRONTEND_PORT"
) &
PIDS+=($!)
echo ""
log "========================================"
log " 游戏皮肤分销系统 已启动"
log " 前端: http://localhost:${FRONTEND_PORT}"
log " 后端: http://localhost:${BACKEND_PORT}"
log " 账号: admin / admin123"
log " 按 Ctrl+C 停止全部服务"
log "========================================"
echo ""
# 任一子进程退出则整体清理
wait -n 2>/dev/null || wait
cleanup