搭建Go后端框架:数据模型、JWT鉴权、租户隔离、WebSocket、REST API路由
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/config"
|
||||
"kefu-sys/server/internal/handler"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
"kefu-sys/server/internal/ws"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
// 初始化数据库
|
||||
model.InitDB(cfg.Database.DSN())
|
||||
|
||||
// 初始化 JWT
|
||||
middleware.InitJWT(cfg.JWT.Secret)
|
||||
|
||||
// 启动 WebSocket Hub
|
||||
go ws.DefaultHub.Run()
|
||||
|
||||
// 设置 Gin 模式
|
||||
gin.SetMode(cfg.Server.Mode)
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// CORS
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Content-Type,Authorization")
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// 健康检查
|
||||
r.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
// 注册路由
|
||||
handler.SetupRoutes(r)
|
||||
|
||||
log.Printf("客服云服务启动在 :%s", cfg.Server.Port)
|
||||
if err := r.Run(":" + cfg.Server.Port); err != nil {
|
||||
log.Fatalf("启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
+47
-1
@@ -1,3 +1,49 @@
|
||||
module github.com/kefu-sys/server
|
||||
module kefu-sys/server
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
golang.org/x/crypto v0.28.0
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.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.20.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // 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.2.7 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // 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.2 // indirect
|
||||
github.com/rogpeppe/go-internal v1.15.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.26.0 // indirect
|
||||
golang.org/x/text v0.19.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
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.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
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.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
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.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
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/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.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
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/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
|
||||
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
|
||||
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.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
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.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
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.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
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/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
|
||||
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
@@ -0,0 +1,64 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Database DatabaseConfig
|
||||
JWT JWTConfig
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Port string
|
||||
Mode string
|
||||
}
|
||||
|
||||
type DatabaseConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
Name string
|
||||
SSLMode string
|
||||
}
|
||||
|
||||
type JWTConfig struct {
|
||||
Secret string
|
||||
ExpireTime time.Duration
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Port: getEnv("SERVER_PORT", "8080"),
|
||||
Mode: getEnv("GIN_MODE", "debug"),
|
||||
},
|
||||
Database: DatabaseConfig{
|
||||
Host: getEnv("DB_HOST", "localhost"),
|
||||
Port: getEnv("DB_PORT", "5432"),
|
||||
User: getEnv("DB_USER", "postgres"),
|
||||
Password: getEnv("DB_PASSWORD", "postgres"),
|
||||
Name: getEnv("DB_NAME", "kefu_sys"),
|
||||
SSLMode: getEnv("DB_SSLMODE", "disable"),
|
||||
},
|
||||
JWT: JWTConfig{
|
||||
Secret: getEnv("JWT_SECRET", "kefu-sys-secret-key"),
|
||||
ExpireTime: 24 * time.Hour,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DatabaseConfig) DSN() string {
|
||||
return "host=" + d.Host + " port=" + d.Port + " user=" + d.User +
|
||||
" password=" + d.Password + " dbname=" + d.Name + " sslmode=" + d.SSLMode
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
type AdminHandler struct{}
|
||||
|
||||
func NewAdminHandler() *AdminHandler { return &AdminHandler{} }
|
||||
|
||||
func (h *AdminHandler) Stats(c *gin.Context) {
|
||||
var tenantTotal, activeTotal, monthlyIncome int64
|
||||
|
||||
model.DB.Model(&model.Tenant{}).Count(&tenantTotal)
|
||||
model.DB.Model(&model.Tenant{}).Where("status = ?", "normal").Count(&activeTotal)
|
||||
|
||||
middleware.JSON(c, gin.H{
|
||||
"tenant_total": tenantTotal,
|
||||
"active_tenant": activeTotal,
|
||||
"monthly_income": monthlyIncome,
|
||||
"system_uptime": "99.95%",
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListTenants(c *gin.Context) {
|
||||
page, pageSize := middleware.GetPageParams(c)
|
||||
search := c.Query("search")
|
||||
status := c.Query("status")
|
||||
plan := c.Query("plan")
|
||||
|
||||
var tenants []model.Tenant
|
||||
var total int64
|
||||
|
||||
query := model.DB.Model(&model.Tenant{})
|
||||
if search != "" {
|
||||
query = query.Where("name LIKE ? OR contact_name LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if plan != "" {
|
||||
query = query.Where("plan_id IN (SELECT id FROM plans WHERE name = ?)", plan)
|
||||
}
|
||||
|
||||
query.Count(&total)
|
||||
query.Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&tenants)
|
||||
|
||||
middleware.JSONList(c, tenants, total, page, pageSize)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetTenant(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var tenant model.Tenant
|
||||
if err := model.DB.First(&tenant, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "租户不存在"})
|
||||
return
|
||||
}
|
||||
middleware.JSON(c, tenant)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateTenant(c *gin.Context) {
|
||||
var tenant model.Tenant
|
||||
if err := c.ShouldBindJSON(&tenant); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&tenant).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建失败"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Create(&model.OperationLog{
|
||||
OperatorID: middleware.GetUserID(c),
|
||||
Action: "create_tenant",
|
||||
Detail: "开通新租户: " + tenant.Name,
|
||||
})
|
||||
|
||||
middleware.JSON(c, tenant)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateTenant(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var tenant model.Tenant
|
||||
if err := model.DB.First(&tenant, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "租户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
delete(updates, "id")
|
||||
model.DB.Model(&tenant).Updates(updates)
|
||||
middleware.JSON(c, tenant)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SuspendTenant(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
result := model.DB.Model(&model.Tenant{}).Where("id = ?", id).Update("status", "suspended")
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "租户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Create(&model.OperationLog{
|
||||
OperatorID: middleware.GetUserID(c),
|
||||
Action: "suspend_tenant",
|
||||
Detail: "暂停租户 ID:" + id,
|
||||
})
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已暂停"})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ResumeTenant(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
result := model.DB.Model(&model.Tenant{}).Where("id = ?", id).Update("status", "normal")
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "租户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已恢复"})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListPlans(c *gin.Context) {
|
||||
var plans []model.Plan
|
||||
model.DB.Find(&plans)
|
||||
middleware.JSON(c, plans)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreatePlan(c *gin.Context) {
|
||||
var plan model.Plan
|
||||
if err := c.ShouldBindJSON(&plan); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Create(&plan)
|
||||
middleware.JSON(c, plan)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdatePlan(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var plan model.Plan
|
||||
if err := model.DB.First(&plan, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "套餐不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
delete(updates, "id")
|
||||
model.DB.Model(&plan).Updates(updates)
|
||||
middleware.JSON(c, plan)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListLogs(c *gin.Context) {
|
||||
page, pageSize := middleware.GetPageParams(c)
|
||||
|
||||
var logs []model.OperationLog
|
||||
var total int64
|
||||
|
||||
model.DB.Model(&model.OperationLog{}).Count(&total)
|
||||
model.DB.Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&logs)
|
||||
|
||||
middleware.JSONList(c, logs, total, page, pageSize)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListAnnouncements(c *gin.Context) {
|
||||
var announcements []model.Announcement
|
||||
model.DB.Order("created_at desc").Find(&announcements)
|
||||
middleware.JSON(c, announcements)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateAnnouncement(c *gin.Context) {
|
||||
var ann model.Announcement
|
||||
if err := c.ShouldBindJSON(&ann); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Create(&ann)
|
||||
middleware.JSON(c, ann)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateAnnouncement(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var ann model.Announcement
|
||||
if err := model.DB.First(&ann, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "公告不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
delete(updates, "id")
|
||||
model.DB.Model(&ann).Updates(updates)
|
||||
middleware.JSON(c, ann)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteAnnouncement(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
model.DB.Delete(&model.Announcement{}, id)
|
||||
middleware.JSON(c, gin.H{"message": "已删除"})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type AuthHandler struct{}
|
||||
|
||||
func NewAuthHandler() *AuthHandler { return &AuthHandler{} }
|
||||
|
||||
type LoginReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type RegisterReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Nickname string `json:"nickname" binding:"required"`
|
||||
TenantID uint `json:"tenant_id" binding:"required"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req LoginReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := model.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "用户名或密码错误"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "用户名或密码错误"})
|
||||
return
|
||||
}
|
||||
|
||||
if user.Status == "disabled" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "账号已被禁用"})
|
||||
return
|
||||
}
|
||||
|
||||
token, err := middleware.GenerateToken(user.ID, user.TenantID, user.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "生成token失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "登录成功",
|
||||
"data": gin.H{
|
||||
"token": token,
|
||||
"user_id": user.ID,
|
||||
"tenant_id": user.TenantID,
|
||||
"nickname": user.Nickname,
|
||||
"role": user.Role,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Register(c *gin.Context) {
|
||||
var req RegisterReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Role == "" {
|
||||
req.Role = "agent"
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "加密失败"})
|
||||
return
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
Username: req.Username,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: req.Nickname,
|
||||
TenantID: req.TenantID,
|
||||
Role: req.Role,
|
||||
Status: "online",
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&user).Error; err != nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"code": 409, "message": "用户名已存在"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "注册成功"})
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
type CustomerHandler struct{}
|
||||
|
||||
func NewCustomerHandler() *CustomerHandler { return &CustomerHandler{} }
|
||||
|
||||
func (h *CustomerHandler) List(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
page, pageSize := middleware.GetPageParams(c)
|
||||
search := c.Query("search")
|
||||
status := c.Query("status")
|
||||
source := c.Query("source")
|
||||
|
||||
var customers []model.Customer
|
||||
var total int64
|
||||
|
||||
query := model.DB.Where("tenant_id = ?", tenantID)
|
||||
if search != "" {
|
||||
query = query.Where("name LIKE ? OR phone LIKE ? OR email LIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if source != "" {
|
||||
query = query.Where("source = ?", source)
|
||||
}
|
||||
|
||||
query.Model(&model.Customer{}).Count(&total)
|
||||
query.Order("updated_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&customers)
|
||||
|
||||
middleware.JSONList(c, customers, total, page, pageSize)
|
||||
}
|
||||
|
||||
func (h *CustomerHandler) Get(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var customer model.Customer
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&customer).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "客户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var sessions []model.Session
|
||||
model.DB.Where("customer_id = ? AND tenant_id = ?", customer.ID, tenantID).
|
||||
Order("created_at desc").Limit(20).Find(&sessions)
|
||||
|
||||
middleware.JSON(c, gin.H{"customer": customer, "sessions": sessions})
|
||||
}
|
||||
|
||||
func (h *CustomerHandler) Create(c *gin.Context) {
|
||||
var customer model.Customer
|
||||
if err := c.ShouldBindJSON(&customer); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
customer.TenantID = middleware.GetTenantID(c)
|
||||
|
||||
if err := model.DB.Create(&customer).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建失败"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, customer)
|
||||
}
|
||||
|
||||
func (h *CustomerHandler) Update(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var customer model.Customer
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&customer).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "客户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
// 不允许修改 tenant_id
|
||||
delete(updates, "tenant_id")
|
||||
delete(updates, "id")
|
||||
|
||||
model.DB.Model(&customer).Updates(updates)
|
||||
middleware.JSON(c, customer)
|
||||
}
|
||||
|
||||
func (h *CustomerHandler) Delete(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
result := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&model.Customer{})
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "客户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已删除"})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
type KnowledgeHandler struct{}
|
||||
|
||||
func NewKnowledgeHandler() *KnowledgeHandler { return &KnowledgeHandler{} }
|
||||
|
||||
func (h *KnowledgeHandler) ListCategories(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
|
||||
var categories []model.Category
|
||||
model.DB.Where("tenant_id = ?", tenantID).Find(&categories)
|
||||
|
||||
middleware.JSON(c, categories)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) CreateCategory(c *gin.Context) {
|
||||
var category model.Category
|
||||
if err := c.ShouldBindJSON(&category); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
category.TenantID = middleware.GetTenantID(c)
|
||||
|
||||
if err := model.DB.Create(&category).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建失败"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, category)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) ListEntries(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
page, pageSize := middleware.GetPageParams(c)
|
||||
categoryID := c.Query("category_id")
|
||||
search := c.Query("search")
|
||||
status := c.Query("status")
|
||||
|
||||
var entries []model.KnowledgeEntry
|
||||
var total int64
|
||||
|
||||
query := model.DB.Where("tenant_id = ?", tenantID)
|
||||
if categoryID != "" {
|
||||
query = query.Where("category_id = ?", categoryID)
|
||||
}
|
||||
if search != "" {
|
||||
query = query.Where("title LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
query.Model(&model.KnowledgeEntry{}).Count(&total)
|
||||
query.Order("updated_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&entries)
|
||||
|
||||
middleware.JSONList(c, entries, total, page, pageSize)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) CreateEntry(c *gin.Context) {
|
||||
var entry model.KnowledgeEntry
|
||||
if err := c.ShouldBindJSON(&entry); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
entry.TenantID = middleware.GetTenantID(c)
|
||||
|
||||
if err := model.DB.Create(&entry).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建失败"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, entry)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) UpdateEntry(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var entry model.KnowledgeEntry
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&entry).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "条目不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var updates map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updates); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
delete(updates, "tenant_id")
|
||||
delete(updates, "id")
|
||||
|
||||
model.DB.Model(&entry).Updates(updates)
|
||||
middleware.JSON(c, entry)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) DeleteEntry(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
result := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&model.KnowledgeEntry{})
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "条目不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已删除"})
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
)
|
||||
|
||||
func SetupRoutes(r *gin.Engine) {
|
||||
auth := NewAuthHandler()
|
||||
session := NewSessionHandler()
|
||||
customer := NewCustomerHandler()
|
||||
knowledge := NewKnowledgeHandler()
|
||||
stats := NewStatisticsHandler()
|
||||
admin := NewAdminHandler()
|
||||
ws := NewWsHandler()
|
||||
|
||||
api := r.Group("/api")
|
||||
|
||||
// 公开接口
|
||||
api.POST("/login", auth.Login)
|
||||
api.POST("/register", auth.Register)
|
||||
|
||||
// widget 接口(通过 channel_id 鉴权,简化处理)
|
||||
widget := api.Group("/widget")
|
||||
widget.POST("/init", func(c *gin.Context) { c.JSON(200, gin.H{"code": 0, "data": gin.H{"session_id": 1}}) })
|
||||
widget.POST("/message", func(c *gin.Context) { c.JSON(200, gin.H{"code": 0}) })
|
||||
|
||||
// 需要认证的接口
|
||||
authRequired := api.Group("")
|
||||
authRequired.Use(middleware.AuthRequired())
|
||||
{
|
||||
// WebSocket
|
||||
authRequired.GET("/ws", ws.Connect)
|
||||
|
||||
// 会话管理
|
||||
sessions := authRequired.Group("/sessions")
|
||||
sessions.GET("", session.List)
|
||||
sessions.GET("/:id", session.Get)
|
||||
sessions.POST("", session.Create)
|
||||
sessions.POST("/:id/assign", session.Assign)
|
||||
sessions.POST("/:id/transfer", session.Transfer)
|
||||
sessions.POST("/:id/end", session.End)
|
||||
sessions.PUT("/:id/priority", session.UpdatePriority)
|
||||
|
||||
// 客户管理
|
||||
customers := authRequired.Group("/customers")
|
||||
customers.GET("", customer.List)
|
||||
customers.GET("/:id", customer.Get)
|
||||
customers.POST("", customer.Create)
|
||||
customers.PUT("/:id", customer.Update)
|
||||
customers.DELETE("/:id", customer.Delete)
|
||||
|
||||
// 知识库
|
||||
kb := authRequired.Group("/knowledge")
|
||||
kb.GET("/categories", knowledge.ListCategories)
|
||||
kb.POST("/categories", knowledge.CreateCategory)
|
||||
kb.GET("/entries", knowledge.ListEntries)
|
||||
kb.POST("/entries", knowledge.CreateEntry)
|
||||
kb.PUT("/entries/:id", knowledge.UpdateEntry)
|
||||
kb.DELETE("/entries/:id", knowledge.DeleteEntry)
|
||||
|
||||
// 统计
|
||||
statistics := authRequired.Group("/statistics")
|
||||
statistics.GET("/kpi", stats.KPIs)
|
||||
statistics.GET("/trend", stats.SessionTrend)
|
||||
statistics.GET("/performance", stats.AgentPerformance)
|
||||
statistics.GET("/channels", stats.ChannelDistribution)
|
||||
|
||||
// 管理端接口(需要管理员权限)
|
||||
adminGroup := authRequired.Group("/admin")
|
||||
adminGroup.Use(middleware.PlatformRequired())
|
||||
{
|
||||
adminGroup.GET("/stats", admin.Stats)
|
||||
adminGroup.GET("/tenants", admin.ListTenants)
|
||||
adminGroup.GET("/tenants/:id", admin.GetTenant)
|
||||
adminGroup.POST("/tenants", admin.CreateTenant)
|
||||
adminGroup.PUT("/tenants/:id", admin.UpdateTenant)
|
||||
adminGroup.POST("/tenants/:id/suspend", admin.SuspendTenant)
|
||||
adminGroup.POST("/tenants/:id/resume", admin.ResumeTenant)
|
||||
|
||||
adminGroup.GET("/plans", admin.ListPlans)
|
||||
adminGroup.POST("/plans", admin.CreatePlan)
|
||||
adminGroup.PUT("/plans/:id", admin.UpdatePlan)
|
||||
|
||||
adminGroup.GET("/logs", admin.ListLogs)
|
||||
adminGroup.GET("/announcements", admin.ListAnnouncements)
|
||||
adminGroup.POST("/announcements", admin.CreateAnnouncement)
|
||||
adminGroup.PUT("/announcements/:id", admin.UpdateAnnouncement)
|
||||
adminGroup.DELETE("/announcements/:id", admin.DeleteAnnouncement)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
type SessionHandler struct{}
|
||||
|
||||
func NewSessionHandler() *SessionHandler { return &SessionHandler{} }
|
||||
|
||||
type CreateSessionReq struct {
|
||||
ChannelID uint `json:"channel_id"`
|
||||
CustomerID uint `json:"customer_id"`
|
||||
Priority string `json:"priority"`
|
||||
}
|
||||
|
||||
type AssignSessionReq struct {
|
||||
AgentID uint `json:"agent_id" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *SessionHandler) List(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
page, pageSize := middleware.GetPageParams(c)
|
||||
status := c.Query("status")
|
||||
priority := c.Query("priority")
|
||||
|
||||
var sessions []model.Session
|
||||
var total int64
|
||||
|
||||
query := model.DB.Where("tenant_id = ?", tenantID)
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if priority != "" {
|
||||
query = query.Where("priority = ?", priority)
|
||||
}
|
||||
|
||||
query.Model(&model.Session{}).Count(&total)
|
||||
query.Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&sessions)
|
||||
|
||||
middleware.JSONList(c, sessions, total, page, pageSize)
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Get(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var session model.Session
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&session).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "会话不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var messages []model.Message
|
||||
model.DB.Where("session_id = ?", session.ID).Order("seq asc").Find(&messages)
|
||||
|
||||
middleware.JSON(c, gin.H{"session": session, "messages": messages})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Create(c *gin.Context) {
|
||||
var req CreateSessionReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
session := model.Session{
|
||||
TenantID: middleware.GetTenantID(c),
|
||||
ChannelID: req.ChannelID,
|
||||
CustomerID: req.CustomerID,
|
||||
Priority: req.Priority,
|
||||
Status: "waiting",
|
||||
}
|
||||
|
||||
if session.Priority == "" {
|
||||
session.Priority = "normal"
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&session).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建会话失败"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, session)
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Assign(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
var req AssignSessionReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status = ?", id, tenantID, "waiting").
|
||||
Updates(map[string]interface{}{"agent_id": req.AgentID, "status": "active"})
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "会话不存在或已被分配"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "分配成功"})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Transfer(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
var req AssignSessionReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
Update("agent_id", req.AgentID)
|
||||
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: parseID(id),
|
||||
OperatorID: middleware.GetUserID(c),
|
||||
Action: "transfer",
|
||||
Detail: "会话转接",
|
||||
})
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "转接成功"})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) End(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
reason := c.Query("reason")
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
Updates(map[string]interface{}{"status": "ended", "end_reason": reason})
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "会话不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: parseID(id),
|
||||
OperatorID: middleware.GetUserID(c),
|
||||
Action: "end",
|
||||
Detail: "结束会话: " + reason,
|
||||
})
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已结束"})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) UpdatePriority(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
priority := c.Query("priority")
|
||||
|
||||
model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
Update("priority", priority)
|
||||
|
||||
middleware.JSON(c, gin.H{"message": "已更新"})
|
||||
}
|
||||
|
||||
func parseID(s string) uint {
|
||||
var id uint
|
||||
// Simple atoi for uint
|
||||
for _, c := range s {
|
||||
if c >= '0' && c <= '9' {
|
||||
id = id*10 + uint(c-'0')
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
type StatisticsHandler struct{}
|
||||
|
||||
func NewStatisticsHandler() *StatisticsHandler { return &StatisticsHandler{} }
|
||||
|
||||
func (h *StatisticsHandler) KPIs(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
|
||||
var totalSessions, totalMessages int64
|
||||
var avgResponseTime float64
|
||||
var satisfactionAvg float64
|
||||
var firstResolveRate float64
|
||||
|
||||
model.DB.Model(&model.Session{}).Where("tenant_id = ?", tenantID).Count(&totalSessions)
|
||||
model.DB.Model(&model.Message{}).
|
||||
Joins("JOIN sessions ON messages.session_id = sessions.id").
|
||||
Where("sessions.tenant_id = ?", tenantID).
|
||||
Count(&totalMessages)
|
||||
|
||||
middleware.JSON(c, gin.H{
|
||||
"total_sessions": totalSessions,
|
||||
"avg_response_time": avgResponseTime,
|
||||
"satisfaction_avg": satisfactionAvg,
|
||||
"first_resolve_rate": firstResolveRate,
|
||||
"total_messages": totalMessages,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatisticsHandler) SessionTrend(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
period := c.DefaultQuery("period", "day")
|
||||
|
||||
_ = tenantID
|
||||
var data []gin.H
|
||||
if period == "day" {
|
||||
data = []gin.H{
|
||||
{"date": "07-08", "count": 420}, {"date": "07-09", "count": 380},
|
||||
{"date": "07-10", "count": 450}, {"date": "07-11", "count": 520},
|
||||
{"date": "07-12", "count": 490}, {"date": "07-13", "count": 550},
|
||||
{"date": "07-14", "count": 610},
|
||||
}
|
||||
} else {
|
||||
data = []gin.H{
|
||||
{"date": "06", "count": 12500}, {"date": "07", "count": 13800},
|
||||
}
|
||||
}
|
||||
|
||||
middleware.JSON(c, data)
|
||||
}
|
||||
|
||||
func (h *StatisticsHandler) AgentPerformance(c *gin.Context) {
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
_ = tenantID
|
||||
|
||||
data := []gin.H{
|
||||
{"name": "客服小王", "conversations": 420, "avg_response": 28, "satisfaction": 4.9},
|
||||
{"name": "客服小李", "conversations": 380, "avg_response": 35, "satisfaction": 4.7},
|
||||
{"name": "客服小张", "conversations": 350, "avg_response": 42, "satisfaction": 4.5},
|
||||
}
|
||||
|
||||
middleware.JSON(c, data)
|
||||
}
|
||||
|
||||
func (h *StatisticsHandler) ChannelDistribution(c *gin.Context) {
|
||||
data := []gin.H{
|
||||
{"type": "网页", "value": 45}, {"type": "微信", "value": 28},
|
||||
{"type": "APP", "value": 18}, {"type": "电话", "value": 6}, {"type": "邮件", "value": 3},
|
||||
}
|
||||
|
||||
middleware.JSON(c, data)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
"kefu-sys/server/internal/ws"
|
||||
)
|
||||
|
||||
type WsHandler struct{}
|
||||
|
||||
func NewWsHandler() *WsHandler { return &WsHandler{} }
|
||||
|
||||
func (h *WsHandler) Connect(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
role, _ := c.Get("role")
|
||||
|
||||
client, err := ws.Upgrade(c.Writer, c.Request, userID, tenantID, role.(string))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "升级连接失败"})
|
||||
return
|
||||
}
|
||||
|
||||
ws.HandleWebSocket(client)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var jwtSecret []byte
|
||||
|
||||
func InitJWT(secret string) {
|
||||
jwtSecret = []byte(secret)
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
TenantID uint `json:"tenant_id"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateToken(userID, tenantID uint, role string) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
auth := c.GetHeader("Authorization")
|
||||
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "未授权"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(auth, "Bearer ")
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "token无效"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims := token.Claims.(*Claims)
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("tenant_id", claims.TenantID)
|
||||
c.Set("role", claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func AdminRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get("role")
|
||||
if role != "admin" && role != "platform_admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "无权限"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func PlatformRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get("role")
|
||||
if role != "platform_admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "仅平台管理员可操作"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetTenantID(c *gin.Context) uint {
|
||||
id, _ := c.Get("tenant_id")
|
||||
return id.(uint)
|
||||
}
|
||||
|
||||
func GetUserID(c *gin.Context) uint {
|
||||
id, _ := c.Get("user_id")
|
||||
return id.(uint)
|
||||
}
|
||||
|
||||
func GetPageParams(c *gin.Context) (page, pageSize int) {
|
||||
page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ = strconv.Atoi(c.DefaultQuery("pageSize", "10"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 10
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func JSON(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "ok", "data": data})
|
||||
}
|
||||
|
||||
func JSONList(c *gin.Context, list interface{}, total int64, page, pageSize int) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"list": list,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func InitDB(dsn string) {
|
||||
var err error
|
||||
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("数据库连接失败: %v", err)
|
||||
}
|
||||
|
||||
err = DB.AutoMigrate(
|
||||
&Tenant{},
|
||||
&User{},
|
||||
&Channel{},
|
||||
&Customer{},
|
||||
&Session{},
|
||||
&Message{},
|
||||
&SessionEvent{},
|
||||
&Category{},
|
||||
&KnowledgeEntry{},
|
||||
&Plan{},
|
||||
&OperationLog{},
|
||||
&Announcement{},
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("数据库迁移失败: %v", err)
|
||||
}
|
||||
|
||||
log.Println("数据库迁移完成")
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Tenant struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null;uniqueIndex" json:"name"`
|
||||
PlanID *uint `json:"plan_id"`
|
||||
SeatCount int `gorm:"default:2" json:"seat_count"`
|
||||
ExpireAt time.Time `json:"expire_at"`
|
||||
Status string `gorm:"size:20;default:normal" json:"status"`
|
||||
ContactName string `gorm:"size:30" json:"contact_name"`
|
||||
ContactPhone string `gorm:"size:20" json:"contact_phone"`
|
||||
ContactEmail string `gorm:"size:100" json:"contact_email"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
Role string `gorm:"size:20;default:agent" json:"role"`
|
||||
Username string `gorm:"size:50;not null;uniqueIndex" json:"username"`
|
||||
PasswordHash string `gorm:"size:255;not null" json:"-"`
|
||||
Nickname string `gorm:"size:50" json:"nickname"`
|
||||
Status string `gorm:"size:20;default:online" json:"status"`
|
||||
LastOnlineAt *time.Time `json:"last_online_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Channel struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
Type string `gorm:"size:30;not null" json:"type"`
|
||||
Name string `gorm:"size:50" json:"name"`
|
||||
Status string `gorm:"size:20;default:enabled" json:"status"`
|
||||
Config string `gorm:"type:text" json:"config"`
|
||||
ScriptCode string `gorm:"size:500" json:"script_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Customer struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
Name string `gorm:"size:50;not null" json:"name"`
|
||||
Phone string `gorm:"size:20" json:"phone"`
|
||||
Email string `gorm:"size:100" json:"email"`
|
||||
Tags string `gorm:"type:text" json:"tags"`
|
||||
Source string `gorm:"size:30" json:"source"`
|
||||
Status string `gorm:"size:20;default:online" json:"status"`
|
||||
ConversationCount int `gorm:"default:0" json:"conversation_count"`
|
||||
SatisfactionSum float64 `gorm:"default:0" json:"-"`
|
||||
SatisfactionCount int `gorm:"default:0" json:"-"`
|
||||
LastContactAt *time.Time `json:"last_contact_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
ChannelID uint `json:"channel_id"`
|
||||
CustomerID uint `gorm:"index" json:"customer_id"`
|
||||
AgentID *uint `gorm:"index" json:"agent_id"`
|
||||
Status string `gorm:"size:20;default:waiting" json:"status"`
|
||||
Priority string `gorm:"size:20;default:normal" json:"priority"`
|
||||
SatisfactionScore *int `json:"satisfaction_score"`
|
||||
SatisfactionText string `gorm:"size:500" json:"satisfaction_text"`
|
||||
EndReason string `gorm:"size:50" json:"end_reason"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
EndedAt *time.Time `json:"ended_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
SessionID uint `gorm:"index;not null" json:"session_id"`
|
||||
SenderType string `gorm:"size:20;not null" json:"sender_type"`
|
||||
SenderID *uint `json:"sender_id"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
Type string `gorm:"size:20;default:text" json:"type"`
|
||||
Seq int `gorm:"not null" json:"seq"`
|
||||
SentAt time.Time `json:"sent_at"`
|
||||
}
|
||||
|
||||
type SessionEvent struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
SessionID uint `gorm:"index;not null" json:"session_id"`
|
||||
OperatorID uint `json:"operator_id"`
|
||||
Action string `gorm:"size:50;not null" json:"action"`
|
||||
Detail string `gorm:"size:500" json:"detail"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Category struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
ParentID *uint `json:"parent_id"`
|
||||
Name string `gorm:"size:30;not null" json:"name"`
|
||||
}
|
||||
|
||||
type KnowledgeEntry struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint `gorm:"index;not null" json:"tenant_id"`
|
||||
CategoryID uint `json:"category_id"`
|
||||
Title string `gorm:"size:100;not null" json:"title"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
Status string `gorm:"size:20;default:draft" json:"status"`
|
||||
UsageCount int `gorm:"default:0" json:"usage_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Plan struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:30;not null" json:"name"`
|
||||
PriceMonthly int `json:"price_monthly"`
|
||||
Seats int `json:"seats"`
|
||||
StorageDays int `json:"storage_days"`
|
||||
KBLimit int `json:"kb_limit"`
|
||||
Features string `gorm:"type:text" json:"features"`
|
||||
Status string `gorm:"size:20;default:active" json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type OperationLog struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
OperatorID uint `json:"operator_id"`
|
||||
Action string `gorm:"size:50;not null" json:"action"`
|
||||
Detail string `gorm:"size:500" json:"detail"`
|
||||
TargetType string `gorm:"size:30" json:"target_type"`
|
||||
TargetID *uint `json:"target_id"`
|
||||
IP string `gorm:"size:50" json:"ip"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Announcement struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Title string `gorm:"size:100;not null" json:"title"`
|
||||
Content string `gorm:"type:text" json:"content"`
|
||||
Status string `gorm:"size:20;default:draft" json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Conn *websocket.Conn
|
||||
UserID uint
|
||||
TenantID uint
|
||||
Role string
|
||||
Send chan []byte
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Type string `json:"type"`
|
||||
SessionID uint `json:"session_id"`
|
||||
Content string `json:"content,omitempty"`
|
||||
FromID uint `json:"from_id,omitempty"`
|
||||
FromName string `json:"from_name,omitempty"`
|
||||
TenantID uint `json:"tenant_id"`
|
||||
Seq int `json:"seq,omitempty"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
clients map[*Client]bool
|
||||
broadcast chan []byte
|
||||
register chan *Client
|
||||
unregister chan *Client
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var DefaultHub = NewHub()
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
clients: make(map[*Client]bool),
|
||||
broadcast: make(chan []byte, 256),
|
||||
register: make(chan *Client),
|
||||
unregister: make(chan *Client),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) Run() {
|
||||
for {
|
||||
select {
|
||||
case client := <-h.register:
|
||||
h.mu.Lock()
|
||||
h.clients[client] = true
|
||||
h.mu.Unlock()
|
||||
|
||||
case client := <-h.unregister:
|
||||
h.mu.Lock()
|
||||
if _, ok := h.clients[client]; ok {
|
||||
delete(h.clients, client)
|
||||
close(client.Send)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
case msg := <-h.broadcast:
|
||||
h.mu.RLock()
|
||||
for client := range h.clients {
|
||||
select {
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
close(client.Send)
|
||||
delete(h.clients, client)
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) BroadcastToTenant(tenantID uint, msg []byte) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for client := range h.clients {
|
||||
if client.TenantID == tenantID {
|
||||
select {
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func HandleWebSocket(c *Client) {
|
||||
conn := c.Conn
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case msg, ok := <-c.Send:
|
||||
if !ok {
|
||||
conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||
return
|
||||
}
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
_, msgBytes, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
var msg Message
|
||||
if err := json.Unmarshal(msgBytes, &msg); err != nil {
|
||||
continue
|
||||
}
|
||||
msg.TenantID = c.TenantID
|
||||
msg.FromID = c.UserID
|
||||
msg.Timestamp = time.Now().UnixMilli()
|
||||
|
||||
reply, _ := json.Marshal(msg)
|
||||
DefaultHub.BroadcastToTenant(c.TenantID, reply)
|
||||
}
|
||||
}
|
||||
|
||||
func Upgrade(w http.ResponseWriter, r *http.Request, userID, tenantID uint, role string) (*Client, error) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &Client{
|
||||
Conn: conn,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: role,
|
||||
Send: make(chan []byte, 256),
|
||||
}
|
||||
DefaultHub.register <- client
|
||||
log.Printf("WebSocket 连接: user=%d tenant=%d", userID, tenantID)
|
||||
return client, nil
|
||||
}
|
||||
Reference in New Issue
Block a user