搭建Go后端框架:数据模型、JWT鉴权、租户隔离、WebSocket、REST API路由

This commit is contained in:
yml2213
2026-07-14 11:23:05 +08:00
parent 81c32cfdea
commit 05ab468498
16 changed files with 1692 additions and 1 deletions
+64
View File
@@ -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
}
+221
View File
@@ -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": "已删除"})
}
+103
View File
@@ -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": "注册成功"})
}
+111
View File
@@ -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": "已删除"})
}
+117
View File
@@ -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": "已删除"})
}
+92
View File
@@ -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)
}
}
}
+180
View File
@@ -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
}
+78
View File
@@ -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)
}
+27
View File
@@ -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)
}
+126
View File
@@ -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,
})
}
+41
View File
@@ -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("数据库迁移完成")
}
+152
View File
@@ -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"`
}
+159
View File
@@ -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
}