搭建Go后端框架:数据模型、JWT鉴权、租户隔离、WebSocket、REST API路由
This commit is contained in:
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user