refactor(server): 会话/访客/设置业务逻辑下沉 internal/service 层,handler 瘦身
- handler 只保留请求绑定、权限检查与响应映射;业务校验顺序、状态码与文案逐字保留 - 新增 service.Error 语义错误,由 handler 统一映射 HTTP 响应 - session 875→361 行、widget 745→321 行、settings 540→73 行 - 自动分配/租户设置(工作时间、欢迎语)/消息校验/黑名单检查/联系方式提取随迁 service 包 - 相关单元测试随迁 service 包,go test ./... 全部通过
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
"kefu-cloud/server/internal/ws"
|
||||
)
|
||||
|
||||
var assignmentLocks sync.Map
|
||||
|
||||
func assignmentLock(tenantID uint) *sync.Mutex {
|
||||
lock, _ := assignmentLocks.LoadOrStore(tenantID, &sync.Mutex{})
|
||||
return lock.(*sync.Mutex)
|
||||
}
|
||||
|
||||
const (
|
||||
AssignStrategyLeastLoad = "least_load"
|
||||
AssignStrategyRoundRobin = "round_robin"
|
||||
)
|
||||
|
||||
func NormalizeAssignStrategy(raw string) string {
|
||||
switch strings.TrimSpace(raw) {
|
||||
case AssignStrategyRoundRobin:
|
||||
return AssignStrategyRoundRobin
|
||||
default:
|
||||
return AssignStrategyLeastLoad
|
||||
}
|
||||
}
|
||||
|
||||
// listOnlineAgents 租户内可自动接待的一线客服(online + role=agent)。
|
||||
func listOnlineAgents(tenantID uint) ([]model.User, error) {
|
||||
var agents []model.User
|
||||
err := model.DB.Where("tenant_id = ? AND role = ? AND status = ?", tenantID, "agent", "online").
|
||||
Order("id asc").Find(&agents).Error
|
||||
return agents, err
|
||||
}
|
||||
|
||||
func agentActiveSessionCount(tenantID, agentID uint) (int64, error) {
|
||||
var count int64
|
||||
err := model.DB.Model(&model.Session{}).
|
||||
Where("tenant_id = ? AND agent_id = ? AND status = ?", tenantID, agentID, "active").
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// filterAssignable 按最大并发过滤;maxActive<=0 表示不限制。
|
||||
func filterAssignable(tenantID uint, agents []model.User, maxActive int) ([]model.User, map[uint]int64, error) {
|
||||
counts := make(map[uint]int64, len(agents))
|
||||
out := make([]model.User, 0, len(agents))
|
||||
for i := range agents {
|
||||
n, err := agentActiveSessionCount(tenantID, agents[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
counts[agents[i].ID] = n
|
||||
if maxActive > 0 && int(n) >= maxActive {
|
||||
continue
|
||||
}
|
||||
out = append(out, agents[i])
|
||||
}
|
||||
return out, counts, nil
|
||||
}
|
||||
|
||||
// pickLeastLoadedAgent 在候选中选 active 会话最少者;平局取 id 更小。
|
||||
func pickLeastLoadedAgent(candidates []model.User, counts map[uint]int64) *model.User {
|
||||
if len(candidates) == 0 {
|
||||
return nil
|
||||
}
|
||||
best := &candidates[0]
|
||||
bestCount := counts[best.ID]
|
||||
for i := 1; i < len(candidates); i++ {
|
||||
c := counts[candidates[i].ID]
|
||||
if c < bestCount || (c == bestCount && candidates[i].ID < best.ID) {
|
||||
bestCount = c
|
||||
best = &candidates[i]
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// pickRoundRobinAgent 在按 id 排序的候选中,从 lastAgentID 之后轮转下一位。
|
||||
func pickRoundRobinAgent(candidates []model.User, lastAgentID *uint) *model.User {
|
||||
if len(candidates) == 0 {
|
||||
return nil
|
||||
}
|
||||
if lastAgentID == nil || *lastAgentID == 0 {
|
||||
return &candidates[0]
|
||||
}
|
||||
// 找到 last 在全序中的位置,取其后第一个仍在候选中的
|
||||
start := 0
|
||||
for i, a := range candidates {
|
||||
if a.ID > *lastAgentID {
|
||||
start = i
|
||||
return &candidates[start]
|
||||
}
|
||||
if a.ID == *lastAgentID {
|
||||
start = (i + 1) % len(candidates)
|
||||
return &candidates[start]
|
||||
}
|
||||
}
|
||||
// last 已不在列表(离线/满载),从头开始
|
||||
return &candidates[0]
|
||||
}
|
||||
|
||||
// pickAgent 按租户策略选择可分配坐席。
|
||||
func pickAgent(tenantID uint, strategy string, maxActive int, rrLast *uint) (*model.User, error) {
|
||||
agents, err := listOnlineAgents(tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(agents) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
candidates, counts, err := filterAssignable(tenantID, agents, maxActive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
strategy = NormalizeAssignStrategy(strategy)
|
||||
if strategy == AssignStrategyRoundRobin {
|
||||
return pickRoundRobinAgent(candidates, rrLast), nil
|
||||
}
|
||||
return pickLeastLoadedAgent(candidates, counts), nil
|
||||
}
|
||||
|
||||
// CountOnlineAgents 统计租户当前可接待的在线客服数。
|
||||
func CountOnlineAgents(tenantID uint) (int64, error) {
|
||||
var count int64
|
||||
err := model.DB.Model(&model.User{}).
|
||||
Where("tenant_id = ? AND role = ? AND status = ?", tenantID, "agent", "online").
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// TryAutoAssign 按租户分配策略自动分配 waiting 会话;无可分配客服时返回 nil。
|
||||
func TryAutoAssign(session *model.Session) (*model.User, error) {
|
||||
if session == nil || session.ID == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if session.Status != "waiting" || session.AgentID != nil {
|
||||
return nil, nil
|
||||
}
|
||||
// 负载统计与会话更新必须串行,否则并发新会话会同时看到旧负载并突破最大并发。
|
||||
lock := assignmentLock(session.TenantID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
if err := model.DB.First(session, session.ID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if session.Status != "waiting" || session.AgentID != nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
setting, err := GetOrCreateTenantSettings(session.TenantID)
|
||||
if err != nil {
|
||||
// 设置失败时回退默认 least_load、不限制并发
|
||||
setting = &model.TenantSetting{AssignStrategy: AssignStrategyLeastLoad}
|
||||
}
|
||||
strategy := NormalizeAssignStrategy(setting.AssignStrategy)
|
||||
maxActive := setting.MaxActivePerAgent
|
||||
if maxActive < 0 {
|
||||
maxActive = 0
|
||||
}
|
||||
|
||||
agent, err := pickAgent(session.TenantID, strategy, maxActive, setting.RRLastAgentID)
|
||||
if err != nil || agent == nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status = ? AND agent_id IS NULL", session.ID, session.TenantID, "waiting").
|
||||
Updates(map[string]interface{}{
|
||||
"agent_id": agent.ID,
|
||||
"status": "active",
|
||||
"last_read_seq": 0,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
// 并发下可能已被他人领取
|
||||
if err := model.DB.First(session, session.ID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
session.AgentID = &agent.ID
|
||||
session.Status = "active"
|
||||
|
||||
// 推进轮询游标(仅 round_robin)
|
||||
if strategy == AssignStrategyRoundRobin && setting.ID > 0 {
|
||||
aid := agent.ID
|
||||
_ = model.DB.Model(&model.TenantSetting{}).
|
||||
Where("id = ?", setting.ID).
|
||||
Update("rr_last_agent_id", aid).Error
|
||||
setting.RRLastAgentID = &aid
|
||||
}
|
||||
|
||||
strategyLabel := "负载最低"
|
||||
if strategy == AssignStrategyRoundRobin {
|
||||
strategyLabel = "轮询"
|
||||
}
|
||||
detail := fmt.Sprintf("系统自动分配给 %s(%s)", agent.Nickname, strategyLabel)
|
||||
if agent.Nickname == "" {
|
||||
detail = fmt.Sprintf("系统自动分配给 %s(%s)", agent.Username, strategyLabel)
|
||||
}
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: 0,
|
||||
Action: "auto_assign",
|
||||
Detail: detail,
|
||||
})
|
||||
|
||||
if payload, err := ws.NewEvent("session_updated", session.ID, session); err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
ws.DefaultHub.BroadcastToVisitor(session.TenantID, session.ID, payload)
|
||||
}
|
||||
return agent, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
)
|
||||
|
||||
// NormalizeDeviceKey 规范化设备指纹:优先客户端 device_id;否则用 UA 摘要哈希兜底。
|
||||
func NormalizeDeviceKey(deviceID, userAgent string) string {
|
||||
id := strings.TrimSpace(deviceID)
|
||||
if id != "" {
|
||||
if utf8.RuneCountInString(id) > 64 {
|
||||
id = string([]rune(id)[:64])
|
||||
}
|
||||
return id
|
||||
}
|
||||
ua := strings.TrimSpace(userAgent)
|
||||
if ua == "" {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.ToLower(ua)))
|
||||
return hex.EncodeToString(sum[:])[:32]
|
||||
}
|
||||
|
||||
// IsBlacklisted 检查租户下 IP/设备是否在有效黑名单中。
|
||||
func IsBlacklisted(tenantID uint, kind, value string) (bool, *model.BlacklistEntry) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || (kind != "ip" && kind != "device") {
|
||||
return false, nil
|
||||
}
|
||||
now := time.Now()
|
||||
var entry model.BlacklistEntry
|
||||
err := model.DB.
|
||||
Where("tenant_id = ? AND kind = ? AND value = ?", tenantID, kind, value).
|
||||
Where("expires_at IS NULL OR expires_at > ?", now).
|
||||
Order("id desc").
|
||||
First(&entry).Error
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
return true, &entry
|
||||
}
|
||||
|
||||
// CheckVisitorBlacklist 同时检查 IP 与设备。
|
||||
func CheckVisitorBlacklist(tenantID uint, ip, deviceKey string) (blocked bool, kind string, reason string) {
|
||||
if ok, e := IsBlacklisted(tenantID, "ip", ip); ok {
|
||||
return true, "ip", e.Reason
|
||||
}
|
||||
if ok, e := IsBlacklisted(tenantID, "device", deviceKey); ok {
|
||||
return true, "device", e.Reason
|
||||
}
|
||||
return false, "", ""
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
"kefu-cloud/server/internal/ws"
|
||||
)
|
||||
|
||||
var (
|
||||
reMobileCN = regexp.MustCompile(`(?i)(?:手机|电话|联系|号|tel|phone|mobile)?[::\s]*((?:\+?86[-\s]?)?1[3-9]\d{9})`)
|
||||
reMobileStrict = regexp.MustCompile(`(?:^|[^\d])(1[3-9]\d{9})(?:[^\d]|$)`)
|
||||
reEmail = regexp.MustCompile(`(?i)[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}`)
|
||||
// 允许「微信是 xxx / 微信:xxx / 微信号 xxx」等口语写法
|
||||
reWechat = regexp.MustCompile(`(?i)(?:微信|微信号|vx|v信|wx)[号]?(?:是|为|:|:|[\s ]+)[\s ]*([a-zA-Z][-_a-zA-Z0-9]{5,19})`)
|
||||
reWechatID = regexp.MustCompile(`(?i)\b(wxid_[a-zA-Z0-9]{5,20})\b`)
|
||||
reQQ = regexp.MustCompile(`(?i)(?:QQ|扣扣)[号]?(?:是|为|:|:|[\s ]+)[\s ]*([1-9]\d{4,11})`)
|
||||
)
|
||||
|
||||
type ExtractedContact struct {
|
||||
Kind string
|
||||
Value string
|
||||
}
|
||||
|
||||
// ExtractContactsFromText 从文本中提取联系方式(手机/微信/邮箱/QQ)。
|
||||
func ExtractContactsFromText(text string) []ExtractedContact {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
// 限制扫描长度
|
||||
if utf8.RuneCountInString(text) > 2000 {
|
||||
text = string([]rune(text)[:2000])
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
var out []ExtractedContact
|
||||
add := func(kind, val string) {
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" {
|
||||
return
|
||||
}
|
||||
// 规范化手机号
|
||||
if kind == "phone" {
|
||||
val = regexp.MustCompile(`[^\d]`).ReplaceAllString(val, "")
|
||||
if strings.HasPrefix(val, "86") && len(val) == 13 {
|
||||
val = val[2:]
|
||||
}
|
||||
if len(val) != 11 || val[0] != '1' {
|
||||
return
|
||||
}
|
||||
}
|
||||
key := kind + ":" + strings.ToLower(val)
|
||||
if seen[key] {
|
||||
return
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, ExtractedContact{Kind: kind, Value: val})
|
||||
}
|
||||
|
||||
for _, m := range reMobileCN.FindAllStringSubmatch(text, -1) {
|
||||
if len(m) > 1 {
|
||||
add("phone", m[1])
|
||||
}
|
||||
}
|
||||
for _, m := range reMobileStrict.FindAllStringSubmatch(text, -1) {
|
||||
if len(m) > 1 {
|
||||
add("phone", m[1])
|
||||
}
|
||||
}
|
||||
for _, m := range reEmail.FindAllString(text, -1) {
|
||||
add("email", strings.ToLower(m))
|
||||
}
|
||||
for _, m := range reWechat.FindAllStringSubmatch(text, -1) {
|
||||
if len(m) > 1 {
|
||||
add("wechat", m[1])
|
||||
}
|
||||
}
|
||||
for _, m := range reWechatID.FindAllStringSubmatch(text, -1) {
|
||||
if len(m) > 1 {
|
||||
add("wechat", m[1])
|
||||
}
|
||||
}
|
||||
for _, m := range reQQ.FindAllStringSubmatch(text, -1) {
|
||||
if len(m) > 1 {
|
||||
add("qq", m[1])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MergeCustomerContacts 将提取结果写入客户联系方式表(已存在则跳过,不覆盖)。
|
||||
// 同时:若 customers.phone/email 为空,用第一条补全(兼容旧列表搜索)。
|
||||
// 返回新插入的条数。
|
||||
func MergeCustomerContacts(tenantID, customerID uint, contacts []ExtractedContact, source string) (int, []model.CustomerContact) {
|
||||
if customerID == 0 || len(contacts) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
var customer model.Customer
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", customerID, tenantID).First(&customer).Error; err != nil {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
added := 0
|
||||
var inserted []model.CustomerContact
|
||||
updates := map[string]interface{}{}
|
||||
|
||||
for _, c := range contacts {
|
||||
var exists int64
|
||||
model.DB.Model(&model.CustomerContact{}).
|
||||
Where("customer_id = ? AND kind = ? AND value = ?", customerID, c.Kind, c.Value).
|
||||
Count(&exists)
|
||||
if exists > 0 {
|
||||
continue
|
||||
}
|
||||
row := model.CustomerContact{
|
||||
TenantID: tenantID,
|
||||
CustomerID: customerID,
|
||||
Kind: c.Kind,
|
||||
Value: c.Value,
|
||||
Source: source,
|
||||
}
|
||||
if err := model.DB.Create(&row).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
added++
|
||||
inserted = append(inserted, row)
|
||||
|
||||
// 主字段仅在为空时填充,绝不覆盖已有值
|
||||
if c.Kind == "phone" && strings.TrimSpace(customer.Phone) == "" && updates["phone"] == nil {
|
||||
updates["phone"] = c.Value
|
||||
customer.Phone = c.Value
|
||||
}
|
||||
if c.Kind == "email" && strings.TrimSpace(customer.Email) == "" && updates["email"] == nil {
|
||||
updates["email"] = c.Value
|
||||
customer.Email = c.Value
|
||||
}
|
||||
if c.Kind == "wechat" && strings.TrimSpace(customer.Wechat) == "" && updates["wechat"] == nil {
|
||||
updates["wechat"] = c.Value
|
||||
customer.Wechat = c.Value
|
||||
}
|
||||
if c.Kind == "qq" && strings.TrimSpace(customer.QQ) == "" && updates["qq"] == nil {
|
||||
updates["qq"] = c.Value
|
||||
customer.QQ = c.Value
|
||||
}
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
model.DB.Model(&model.Customer{}).Where("id = ?", customerID).Updates(updates)
|
||||
}
|
||||
return added, inserted
|
||||
}
|
||||
|
||||
// ListCustomerContacts 客户全部联系方式(按 id 升序)。
|
||||
func ListCustomerContacts(customerID uint) []model.CustomerContact {
|
||||
var list []model.CustomerContact
|
||||
model.DB.Where("customer_id = ?", customerID).Order("id asc").Find(&list)
|
||||
return list
|
||||
}
|
||||
|
||||
// OnVisitorDraftContacts 草稿文本提取联系方式并通知坐席刷新客户资料。
|
||||
func OnVisitorDraftContacts(tenantID, customerID, sessionID uint, text string) {
|
||||
contacts := ExtractContactsFromText(text)
|
||||
if len(contacts) == 0 {
|
||||
return
|
||||
}
|
||||
n, inserted := MergeCustomerContacts(tenantID, customerID, contacts, "draft")
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
// 推送客户资料更新(含全部联系方式)
|
||||
var customer model.Customer
|
||||
if err := model.DB.First(&customer, customerID).Error; err != nil {
|
||||
return
|
||||
}
|
||||
all := ListCustomerContacts(customerID)
|
||||
payload, err := ws.NewEvent("customer_updated", sessionID, map[string]interface{}{
|
||||
"customer": customer,
|
||||
"contacts": all,
|
||||
"added_contacts": inserted,
|
||||
})
|
||||
if err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(tenantID, payload)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package service
|
||||
|
||||
// Error 带语义状态码的业务错误,由 handler 层映射为 HTTP 响应。
|
||||
type Error struct {
|
||||
Status int
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Message }
|
||||
|
||||
// E 构造业务错误。
|
||||
func E(status int, message string) *Error {
|
||||
return &Error{Status: status, Message: message}
|
||||
}
|
||||
|
||||
// BadRequest / Forbidden / NotFound / Conflict / Internal 便捷构造。
|
||||
func BadRequest(message string) *Error { return &Error{Status: 400, Message: message} }
|
||||
func Forbidden(message string) *Error { return &Error{Status: 403, Message: message} }
|
||||
func NotFound(message string) *Error { return &Error{Status: 404, Message: message} }
|
||||
func Conflict(message string) *Error { return &Error{Status: 409, Message: message} }
|
||||
func Internal(message string) *Error { return &Error{Status: 500, Message: message} }
|
||||
@@ -0,0 +1,57 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"kefu-cloud/server/internal/storage"
|
||||
)
|
||||
|
||||
const (
|
||||
maxTextMessageLength = 2000
|
||||
)
|
||||
|
||||
// imagePublicBase 由 SetupRoutes 注入,用于校验图片消息 URL 归属
|
||||
var imagePublicBase string
|
||||
|
||||
// SetImagePublicBase 设置允许的图片存储公开前缀。
|
||||
func SetImagePublicBase(base string) {
|
||||
imagePublicBase = storage.NormalizePublicBase(base)
|
||||
}
|
||||
|
||||
// ValidateMessageContent 校验消息内容;文本去空白,图片校验存储白名单。
|
||||
func ValidateMessageContent(messageType, content string) (string, error) {
|
||||
switch messageType {
|
||||
case "text":
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" {
|
||||
return "", errors.New("消息内容不能为空")
|
||||
}
|
||||
if utf8.RuneCountInString(content) > maxTextMessageLength {
|
||||
return "", errors.New("单条文本消息不能超过 2000 字")
|
||||
}
|
||||
return content, nil
|
||||
case "image":
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" {
|
||||
return "", errors.New("图片地址不能为空")
|
||||
}
|
||||
// 开发阶段直接切换为对象存储 URL,不再接受 base64
|
||||
if strings.HasPrefix(content, "data:") {
|
||||
return "", errors.New("请先上传图片,勿直接发送 base64")
|
||||
}
|
||||
if !strings.HasPrefix(content, "http://") && !strings.HasPrefix(content, "https://") {
|
||||
return "", errors.New("图片地址无效")
|
||||
}
|
||||
if imagePublicBase != "" && !storage.IsAllowedObjectURL(imagePublicBase, content) {
|
||||
return "", errors.New("图片地址不在允许的存储域名下")
|
||||
}
|
||||
if len(content) > 2000 {
|
||||
return "", errors.New("图片地址过长")
|
||||
}
|
||||
return content, nil
|
||||
default:
|
||||
return "", errors.New("不支持的消息类型")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPageURLLen = 1000
|
||||
maxPageTitleLen = 200
|
||||
// 单会话最多保留轨迹条数(超出删最旧)
|
||||
MaxPageViewsPerSession = 50
|
||||
)
|
||||
|
||||
// 常见敏感 query 参数,上报 URL 时剥离
|
||||
var sensitiveQueryKeys = map[string]bool{
|
||||
"token": true, "access_token": true, "refresh_token": true,
|
||||
"password": true, "passwd": true, "pwd": true,
|
||||
"phone": true, "mobile": true, "tel": true,
|
||||
"idcard": true, "id_card": true, "secret": true, "key": true,
|
||||
"authorization": true, "auth": true, "session": true, "sid": true,
|
||||
"code": true, "otp": true, "verify": true,
|
||||
}
|
||||
|
||||
func truncateRunes(s string, max int) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if max <= 0 || s == "" {
|
||||
return s
|
||||
}
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)
|
||||
return string(r[:max])
|
||||
}
|
||||
|
||||
// SanitizePageURL 规范化并脱敏 URL,非法则返回空。
|
||||
func SanitizePageURL(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
if utf8.RuneCountInString(raw) > maxPageURLLen*2 {
|
||||
raw = string([]rune(raw)[:maxPageURLLen*2])
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
// 允许无 scheme 的相对路径拼不成绝对时,若已是 http(s) 失败则截断原文
|
||||
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
|
||||
return truncateRunes(raw, maxPageURLLen)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return ""
|
||||
}
|
||||
q := u.Query()
|
||||
changed := false
|
||||
for k := range q {
|
||||
lk := strings.ToLower(k)
|
||||
if sensitiveQueryKeys[lk] || strings.Contains(lk, "token") || strings.Contains(lk, "password") {
|
||||
q.Del(k)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
// 保留 hash:大量 SPA(含演示站 demo-shop)靠 #/path 区分页面;
|
||||
// 若去掉 fragment,换页后 URL 相同会被服务端当成重复而丢弃轨迹。
|
||||
// 仅截断过长 hash,避免异常数据撑爆字段。
|
||||
if utf8.RuneCountInString(u.Fragment) > 200 {
|
||||
u.Fragment = string([]rune(u.Fragment)[:200])
|
||||
}
|
||||
out := u.String()
|
||||
return truncateRunes(out, maxPageURLLen)
|
||||
}
|
||||
|
||||
// SanitizePageTitle 截断页面标题。
|
||||
func SanitizePageTitle(raw string) string {
|
||||
return truncateRunes(raw, maxPageTitleLen)
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"kefu-cloud/server/internal/model"
|
||||
)
|
||||
|
||||
// Actor 请求发起者(由 handler 从鉴权中间件结果构造),service 层据此做数据范围判断。
|
||||
type Actor struct {
|
||||
UserID uint
|
||||
SessionAll bool // 对 session 模块具有全量数据范围(主管/管理员)
|
||||
HistoryAll bool // 对 chat_history 模块具有全量数据范围
|
||||
}
|
||||
|
||||
// SessionListItem 会话列表项(含批量补全的关联信息)。
|
||||
type SessionListItem struct {
|
||||
model.Session
|
||||
UnreadCount int `json:"unread_count"`
|
||||
LastMessage string `json:"last_message"`
|
||||
LastMessageAt *time.Time `json:"last_message_at,omitempty"`
|
||||
MessageCount int `json:"message_count"`
|
||||
CustomerName string `json:"customer_name"`
|
||||
AgentName string `json:"agent_name"`
|
||||
ChannelName string `json:"channel_name"`
|
||||
ChannelType string `json:"channel_type"`
|
||||
}
|
||||
|
||||
// AgentItem 可转接/筛选坐席项。
|
||||
type AgentItem struct {
|
||||
ID uint `json:"id"`
|
||||
Nickname string `json:"nickname"`
|
||||
Status string `json:"status"` // online | busy | offline | disabled
|
||||
Role string `json:"role,omitempty"`
|
||||
}
|
||||
|
||||
// SessionFilter 会话列表筛选。
|
||||
type SessionFilter struct {
|
||||
Status string
|
||||
Priority string
|
||||
AgentID string
|
||||
ChannelID string
|
||||
Search string
|
||||
From string
|
||||
To string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// LoadTenantSession 加载本租户会话;跨租户访问返回 403。
|
||||
func LoadTenantSession(id string, tenantID uint) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := model.DB.First(&session, id).Error; err != nil {
|
||||
return nil, NotFound("会话不存在")
|
||||
}
|
||||
if session.TenantID != tenantID {
|
||||
return nil, Forbidden("无权访问其他租户会话")
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
// CanReadSession 按会话状态区分数据范围(进行中走 session,已结束走 chat_history)。
|
||||
func CanReadSession(actor Actor, session *model.Session) bool {
|
||||
all := actor.SessionAll
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
all = actor.HistoryAll
|
||||
}
|
||||
if all {
|
||||
return true
|
||||
}
|
||||
return session.Status == "waiting" || (session.AgentID != nil && *session.AgentID == actor.UserID)
|
||||
}
|
||||
|
||||
// CanOperateSession 是否可操作(转接/结束/备注/发消息)该会话。
|
||||
func CanOperateSession(actor Actor, session *model.Session) bool {
|
||||
if actor.SessionAll {
|
||||
return true
|
||||
}
|
||||
return session.AgentID != nil && *session.AgentID == actor.UserID
|
||||
}
|
||||
|
||||
// loadAssignableAgent 校验目标坐席属于本租户、未停用,且具备接待能力。
|
||||
func loadAssignableAgent(tenantID, agentID uint) error {
|
||||
var agent model.User
|
||||
if err := model.DB.First(&agent, agentID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if agent.TenantID != tenantID || agent.Status == "disabled" {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if agent.Role == "agent" {
|
||||
return nil
|
||||
}
|
||||
var count int64
|
||||
if err := model.DB.Table("roles r").
|
||||
Joins("JOIN role_permissions rp ON rp.role_id = r.id").
|
||||
Joins("JOIN permissions p ON p.id = rp.permission_id").
|
||||
Where("r.tenant_id = ? AND r.code = ? AND r.type = ? AND p.code = ?", tenantID, agent.Role, "custom", "session.reply").
|
||||
Count(&count).Error; err != nil || count == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// assignableRoleCodes 可被分配/转接的角色(内置 agent + 拥有 session.reply 的自定义角色)。
|
||||
func assignableRoleCodes(tenantID uint) []string {
|
||||
codes := []string{"agent"}
|
||||
var customCodes []string
|
||||
model.DB.Table("roles r").
|
||||
Joins("JOIN role_permissions rp ON rp.role_id = r.id").
|
||||
Joins("JOIN permissions p ON p.id = rp.permission_id").
|
||||
Where("r.tenant_id = ? AND r.type = ? AND p.code = ?", tenantID, "custom", "session.reply").
|
||||
Distinct().Pluck("r.code", &customCodes)
|
||||
return append(codes, customCodes...)
|
||||
}
|
||||
|
||||
func unreadCount(session model.Session) int {
|
||||
var count int64
|
||||
model.DB.Model(&model.Message{}).
|
||||
Where("session_id = ? AND sender_type = ? AND seq > ?", session.ID, "visitor", session.LastReadSeq).
|
||||
Count(&count)
|
||||
return int(count)
|
||||
}
|
||||
|
||||
// ListSessions 会话列表:筛选、分页并批量补全客户/坐席/渠道/消息数。
|
||||
func ListSessions(actor Actor, tenantID uint, f SessionFilter) ([]SessionListItem, int64, error) {
|
||||
var sessions []model.Session
|
||||
var total int64
|
||||
|
||||
query := model.DB.Model(&model.Session{}).Where("sessions.tenant_id = ?", tenantID)
|
||||
if !actor.SessionAll || !actor.HistoryAll {
|
||||
query = query.Where("sessions.agent_id = ? OR sessions.status = ?", actor.UserID, "waiting")
|
||||
}
|
||||
if f.Status != "" {
|
||||
query = query.Where("sessions.status = ?", f.Status)
|
||||
}
|
||||
if f.Priority != "" {
|
||||
query = query.Where("sessions.priority = ?", f.Priority)
|
||||
}
|
||||
if f.AgentID != "" {
|
||||
query = query.Where("sessions.agent_id = ?", f.AgentID)
|
||||
}
|
||||
if f.ChannelID != "" {
|
||||
query = query.Where("sessions.channel_id = ?", f.ChannelID)
|
||||
}
|
||||
if f.From != "" {
|
||||
if t, err := time.ParseInLocation("2006-01-02", f.From, time.Local); err == nil {
|
||||
query = query.Where("sessions.created_at >= ?", t)
|
||||
}
|
||||
}
|
||||
if f.To != "" {
|
||||
if t, err := time.ParseInLocation("2006-01-02", f.To, time.Local); err == nil {
|
||||
query = query.Where("sessions.created_at < ?", t.Add(24*time.Hour))
|
||||
}
|
||||
}
|
||||
if f.Search != "" {
|
||||
like := "%" + f.Search + "%"
|
||||
query = query.Joins("LEFT JOIN customers ON customers.id = sessions.customer_id").
|
||||
Where("customers.name LIKE ? OR CAST(sessions.id AS TEXT) LIKE ? OR COALESCE(sessions.end_reason, '') LIKE ?", like, like, like)
|
||||
}
|
||||
|
||||
query.Count(&total)
|
||||
if err := query.Order("sessions.created_at desc").Offset((f.Page - 1) * f.PageSize).Limit(f.PageSize).Find(&sessions).Error; err != nil {
|
||||
return nil, 0, Internal("查询会话失败")
|
||||
}
|
||||
|
||||
// 批量补全客户 / 客服 / 渠道 / 消息数
|
||||
customerIDs := make([]uint, 0)
|
||||
agentIDs := make([]uint, 0)
|
||||
channelIDs := make([]uint, 0)
|
||||
sessionIDs := make([]uint, 0, len(sessions))
|
||||
for _, s := range sessions {
|
||||
sessionIDs = append(sessionIDs, s.ID)
|
||||
customerIDs = append(customerIDs, s.CustomerID)
|
||||
channelIDs = append(channelIDs, s.ChannelID)
|
||||
if s.AgentID != nil {
|
||||
agentIDs = append(agentIDs, *s.AgentID)
|
||||
}
|
||||
}
|
||||
customerMap := map[uint]model.Customer{}
|
||||
if len(customerIDs) > 0 {
|
||||
var customers []model.Customer
|
||||
model.DB.Where("id IN ?", UniqueUint(customerIDs)).Find(&customers)
|
||||
for _, cu := range customers {
|
||||
customerMap[cu.ID] = cu
|
||||
}
|
||||
}
|
||||
agentMap := map[uint]model.User{}
|
||||
if len(agentIDs) > 0 {
|
||||
var users []model.User
|
||||
model.DB.Where("id IN ?", UniqueUint(agentIDs)).Find(&users)
|
||||
for _, u := range users {
|
||||
agentMap[u.ID] = u
|
||||
}
|
||||
}
|
||||
channelMap := map[uint]model.Channel{}
|
||||
if len(channelIDs) > 0 {
|
||||
var channels []model.Channel
|
||||
model.DB.Where("id IN ?", UniqueUint(channelIDs)).Find(&channels)
|
||||
for _, ch := range channels {
|
||||
channelMap[ch.ID] = ch
|
||||
}
|
||||
}
|
||||
msgCountMap := map[uint]int{}
|
||||
if len(sessionIDs) > 0 {
|
||||
type row struct {
|
||||
SessionID uint
|
||||
Cnt int
|
||||
}
|
||||
var rows []row
|
||||
model.DB.Model(&model.Message{}).
|
||||
Select("session_id, COUNT(*) as cnt").
|
||||
Where("session_id IN ?", sessionIDs).
|
||||
Group("session_id").
|
||||
Scan(&rows)
|
||||
for _, r := range rows {
|
||||
msgCountMap[r.SessionID] = r.Cnt
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]SessionListItem, 0, len(sessions))
|
||||
for _, session := range sessions {
|
||||
item := SessionListItem{Session: session, MessageCount: msgCountMap[session.ID]}
|
||||
if !actor.SessionAll && session.AgentID != nil && *session.AgentID == actor.UserID {
|
||||
item.UnreadCount = unreadCount(session)
|
||||
}
|
||||
if cu, ok := customerMap[session.CustomerID]; ok {
|
||||
item.CustomerName = cu.Name
|
||||
}
|
||||
if session.AgentID != nil {
|
||||
if u, ok := agentMap[*session.AgentID]; ok {
|
||||
item.AgentName = u.Nickname
|
||||
}
|
||||
}
|
||||
if ch, ok := channelMap[session.ChannelID]; ok {
|
||||
item.ChannelName = ch.Name
|
||||
item.ChannelType = ch.Type
|
||||
}
|
||||
var lastMsg model.Message
|
||||
if err := model.DB.Where("session_id = ?", session.ID).Order("seq desc").First(&lastMsg).Error; err == nil {
|
||||
if lastMsg.Type == "image" {
|
||||
item.LastMessage = "[图片]"
|
||||
} else {
|
||||
item.LastMessage = lastMsg.Content
|
||||
if utf8.RuneCountInString(item.LastMessage) > 40 {
|
||||
runes := []rune(item.LastMessage)
|
||||
item.LastMessage = string(runes[:40]) + "…"
|
||||
}
|
||||
}
|
||||
t := lastMsg.SentAt
|
||||
item.LastMessageAt = &t
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// SessionDetailResult 会话详情聚合结果。
|
||||
type SessionDetailResult struct {
|
||||
Messages []model.Message
|
||||
Events []model.SessionEvent
|
||||
PageViews []model.VisitorPageView
|
||||
PendingCount int64
|
||||
MaxSeq int
|
||||
}
|
||||
|
||||
// SessionDetail 会话详情:消息、事件、浏览轨迹与同客户排队数。
|
||||
func SessionDetail(session *model.Session) (*SessionDetailResult, error) {
|
||||
var messages []model.Message
|
||||
if err := model.DB.Where("session_id = ?", session.ID).Order("seq asc").Find(&messages).Error; err != nil {
|
||||
return nil, Internal("查询消息失败")
|
||||
}
|
||||
var events []model.SessionEvent
|
||||
model.DB.Where("session_id = ?", session.ID).Order("created_at asc").Find(&events)
|
||||
var pageViews []model.VisitorPageView
|
||||
// 最新在前,坐席侧无需滚到底
|
||||
model.DB.Where("session_id = ?", session.ID).Order("entered_at desc").Limit(MaxPageViewsPerSession).Find(&pageViews)
|
||||
var pendingCount int64
|
||||
model.DB.Model(&model.Session{}).Where("customer_id = ? AND tenant_id = ? AND status = ?", session.CustomerID, session.TenantID, "waiting").Count(&pendingCount)
|
||||
|
||||
maxSeq := 0
|
||||
for _, m := range messages {
|
||||
if m.Seq > maxSeq {
|
||||
maxSeq = m.Seq
|
||||
}
|
||||
}
|
||||
return &SessionDetailResult{
|
||||
Messages: messages,
|
||||
Events: events,
|
||||
PageViews: pageViews,
|
||||
PendingCount: pendingCount,
|
||||
MaxSeq: maxSeq,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MessagePage 按 seq 增量拉取的消息页。
|
||||
type MessagePage struct {
|
||||
Messages []model.Message
|
||||
AfterSeq int
|
||||
MaxSeq int
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// SessionMessagePage 按 seq 增量拉取消息(重连 catch-up)。
|
||||
func SessionMessagePage(sessionID uint, afterSeq, limit int) (*MessagePage, error) {
|
||||
query := model.DB.Where("session_id = ?", sessionID)
|
||||
if afterSeq > 0 {
|
||||
query = query.Where("seq > ?", afterSeq)
|
||||
}
|
||||
|
||||
var messages []model.Message
|
||||
if err := query.Order("seq asc").Limit(limit).Find(&messages).Error; err != nil {
|
||||
return nil, Internal("查询消息失败")
|
||||
}
|
||||
|
||||
var maxSeq int
|
||||
if err := model.DB.Model(&model.Message{}).
|
||||
Where("session_id = ?", sessionID).
|
||||
Select("COALESCE(MAX(seq), 0)").
|
||||
Scan(&maxSeq).Error; err != nil {
|
||||
return nil, Internal("查询消息失败")
|
||||
}
|
||||
|
||||
return &MessagePage{
|
||||
Messages: messages,
|
||||
AfterSeq: afterSeq,
|
||||
MaxSeq: maxSeq,
|
||||
HasMore: len(messages) >= limit && (len(messages) == 0 || messages[len(messages)-1].Seq < maxSeq),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MarkSessionRead 坐席标记已读;仅会话归属坐席生效,其余原样返回当前进度。
|
||||
func MarkSessionRead(session *model.Session, actor Actor) (int, error) {
|
||||
if session.AgentID == nil || actor.SessionAll || *session.AgentID != actor.UserID {
|
||||
return session.LastReadSeq, nil
|
||||
}
|
||||
var maxSeq int
|
||||
if err := model.DB.Model(&model.Message{}).Where("session_id = ?", session.ID).Select("COALESCE(MAX(seq), 0)").Scan(&maxSeq).Error; err != nil {
|
||||
return 0, Internal("标记已读失败")
|
||||
}
|
||||
if err := model.DB.Model(&model.Session{}).Where("id = ?", session.ID).Update("last_read_seq", maxSeq).Error; err != nil {
|
||||
return 0, Internal("标记已读失败")
|
||||
}
|
||||
return maxSeq, nil
|
||||
}
|
||||
|
||||
// AddSessionNote 添加内部备注(1-500 字)。
|
||||
func AddSessionNote(session *model.Session, operatorID uint, content string) (model.SessionEvent, error) {
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" || utf8.RuneCountInString(content) > 500 {
|
||||
return model.SessionEvent{}, BadRequest("内部备注需为 1 至 500 字")
|
||||
}
|
||||
event := model.SessionEvent{SessionID: session.ID, OperatorID: operatorID, Action: "note", Detail: content}
|
||||
if err := model.DB.Create(&event).Error; err != nil {
|
||||
return model.SessionEvent{}, Internal("保存内部备注失败")
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
// ListAvailableAgents 可转接/筛选坐席列表;includeOffline 用于对话记录筛选。
|
||||
func ListAvailableAgents(tenantID uint, includeOffline bool) ([]AgentItem, error) {
|
||||
q := model.DB.Where("tenant_id = ? AND role IN ?", tenantID, assignableRoleCodes(tenantID))
|
||||
if !includeOffline {
|
||||
q = q.Where("status IN ?", []string{"online", "busy"})
|
||||
}
|
||||
var users []model.User
|
||||
if err := q.Order("nickname asc").Find(&users).Error; err != nil {
|
||||
return nil, Internal("查询客服失败")
|
||||
}
|
||||
// 在线优先,其次忙碌,再按昵称(Order 已按昵称,稳定排序保持次序)
|
||||
statusRank := map[string]int{"online": 0, "busy": 1, "offline": 2, "disabled": 3}
|
||||
sort.SliceStable(users, func(i, j int) bool {
|
||||
return statusRank[users[i].Status] < statusRank[users[j].Status]
|
||||
})
|
||||
items := make([]AgentItem, 0, len(users))
|
||||
for _, user := range users {
|
||||
items = append(items, AgentItem{
|
||||
ID: user.ID, Nickname: user.Nickname, Status: user.Status, Role: user.Role,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// CreateSession 主管/管理员代客建会话。
|
||||
func CreateSession(tenantID, channelID, customerID uint, priority string) (model.Session, error) {
|
||||
var channel model.Channel
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ? AND status = ?", channelID, tenantID, "enabled").First(&channel).Error; err != nil {
|
||||
return model.Session{}, BadRequest("渠道不存在或未启用")
|
||||
}
|
||||
var customer model.Customer
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", customerID, tenantID).First(&customer).Error; err != nil {
|
||||
return model.Session{}, BadRequest("客户不存在")
|
||||
}
|
||||
|
||||
session := model.Session{
|
||||
TenantID: tenantID,
|
||||
ChannelID: channelID,
|
||||
CustomerID: customerID,
|
||||
Priority: priority,
|
||||
Status: "waiting",
|
||||
}
|
||||
|
||||
if session.Priority == "" {
|
||||
session.Priority = "normal"
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&session).Error; err != nil {
|
||||
return model.Session{}, Internal("创建会话失败")
|
||||
}
|
||||
model.DB.Model(&model.Customer{}).Where("id = ? AND tenant_id = ?", customer.ID, tenantID).
|
||||
Updates(map[string]interface{}{"conversation_count": gorm.Expr("conversation_count + 1"), "last_contact_at": time.Now()})
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// AssignSession 分配/领取会话(仅 waiting)。
|
||||
// 无转接权限时强制分配给本人;有权限的非管理员只能领取给自己。
|
||||
func AssignSession(session *model.Session, actor Actor, canTransfer bool, agentID uint) (string, error) {
|
||||
if session.Status != "waiting" {
|
||||
return "", Conflict("会话已被分配")
|
||||
}
|
||||
if !canTransfer {
|
||||
agentID = actor.UserID
|
||||
} else if !actor.SessionAll && agentID != actor.UserID {
|
||||
return "", Forbidden("无权分配会话")
|
||||
}
|
||||
if agentID == 0 {
|
||||
return "", BadRequest("请选择目标客服")
|
||||
}
|
||||
if err := loadAssignableAgent(session.TenantID, agentID); err != nil {
|
||||
return "", BadRequest("目标客服不存在或不可用")
|
||||
}
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status = ?", session.ID, session.TenantID, "waiting").
|
||||
Updates(map[string]interface{}{"agent_id": agentID, "status": "active", "last_read_seq": 0})
|
||||
|
||||
if result.Error != nil {
|
||||
return "", Internal("分配失败")
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return "", Conflict("会话已被分配")
|
||||
}
|
||||
|
||||
operatorID := actor.UserID
|
||||
operatorName := UserDisplayName(operatorID)
|
||||
targetName := UserDisplayName(agentID)
|
||||
detail := "会话分配给 " + targetName
|
||||
if operatorID == agentID {
|
||||
detail = operatorName + " 领取了会话"
|
||||
} else {
|
||||
detail = operatorName + " 将会话分配给 " + targetName
|
||||
}
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: operatorID,
|
||||
Action: "assign",
|
||||
Detail: detail,
|
||||
})
|
||||
session.AgentID = &agentID
|
||||
session.Status = "active"
|
||||
BroadcastSessionUpdate(session)
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
// TransferSession 转接进行中的会话。
|
||||
func TransferSession(session *model.Session, actor Actor, agentID uint) (string, error) {
|
||||
if err := loadAssignableAgent(session.TenantID, agentID); err != nil {
|
||||
return "", BadRequest("目标客服不存在或不可用")
|
||||
}
|
||||
if session.AgentID != nil && *session.AgentID == agentID {
|
||||
return "", BadRequest("不能转接给当前接待坐席")
|
||||
}
|
||||
|
||||
operatorID := actor.UserID
|
||||
operatorName := UserDisplayName(operatorID)
|
||||
targetName := UserDisplayName(agentID)
|
||||
fromName := ""
|
||||
if session.AgentID != nil {
|
||||
fromName = UserDisplayName(*session.AgentID)
|
||||
}
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status = ?", session.ID, session.TenantID, "active").
|
||||
Updates(map[string]interface{}{"agent_id": agentID, "last_read_seq": 0})
|
||||
if result.Error != nil {
|
||||
return "", Internal("转接失败")
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return "", Conflict("会话不可转接")
|
||||
}
|
||||
|
||||
// 详情写明「谁 → 谁」,便于接手坐席在备注/时间线中一眼看清
|
||||
detail := operatorName + " 转接给 " + targetName
|
||||
if fromName != "" && fromName != operatorName {
|
||||
detail = operatorName + " 将会话由 " + fromName + " 转接给 " + targetName
|
||||
}
|
||||
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: operatorID,
|
||||
Action: "transfer",
|
||||
Detail: detail,
|
||||
})
|
||||
session.AgentID = &agentID
|
||||
BroadcastSessionUpdate(session)
|
||||
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
var endReasons = map[string]bool{
|
||||
"resolved": true, "no_response": true, "visitor_left": true, "transferred": true, "other": true,
|
||||
}
|
||||
|
||||
// EndSession 结束会话(记录原因)。
|
||||
func EndSession(session *model.Session, operatorID uint, reason string) error {
|
||||
if reason == "" {
|
||||
return BadRequest("请填写结束原因")
|
||||
}
|
||||
if !endReasons[reason] {
|
||||
return BadRequest("结束原因无效")
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status <> ?", session.ID, session.TenantID, "ended").
|
||||
Updates(map[string]interface{}{"status": "ended", "end_reason": reason, "ended_at": now})
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return NotFound("会话不存在")
|
||||
}
|
||||
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: operatorID,
|
||||
Action: "end",
|
||||
Detail: "结束会话: " + reason,
|
||||
})
|
||||
session.Status = "ended"
|
||||
session.EndedAt = &now
|
||||
BroadcastSessionUpdate(session)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateSessionPriority 调整会话优先级(urgent / normal)。
|
||||
func UpdateSessionPriority(session *model.Session, actor Actor, priority string) error {
|
||||
if priority != "urgent" && priority != "normal" {
|
||||
return BadRequest("优先级无效")
|
||||
}
|
||||
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ?", session.ID, session.TenantID).
|
||||
Update("priority", priority)
|
||||
if result.Error != nil || result.RowsAffected == 0 {
|
||||
return Internal("更新失败")
|
||||
}
|
||||
session.Priority = priority
|
||||
BroadcastSessionUpdate(session)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ArchiveSession 将已结束会话归档。
|
||||
func ArchiveSession(session *model.Session, operatorID uint) (*model.Session, error) {
|
||||
if session.Status != "ended" {
|
||||
return nil, BadRequest("仅已结束的会话可归档")
|
||||
}
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("id = ? AND tenant_id = ? AND status = ?", session.ID, session.TenantID, "ended").
|
||||
Update("status", "archived")
|
||||
if result.Error != nil || result.RowsAffected == 0 {
|
||||
return nil, Internal("归档失败")
|
||||
}
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: operatorID,
|
||||
Action: "archive",
|
||||
Detail: "会话已归档",
|
||||
})
|
||||
session.Status = "archived"
|
||||
BroadcastSessionUpdate(session)
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// BatchArchiveSessions 批量归档已结束会话,返回归档条数。
|
||||
func BatchArchiveSessions(tenantID, operatorID uint, ids []uint) (int64, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, BadRequest("请选择要归档的会话")
|
||||
}
|
||||
if len(ids) > 100 {
|
||||
return 0, BadRequest("单次最多归档 100 条")
|
||||
}
|
||||
result := model.DB.Model(&model.Session{}).
|
||||
Where("tenant_id = ? AND status = ? AND id IN ?", tenantID, "ended", ids).
|
||||
Update("status", "archived")
|
||||
if result.Error != nil {
|
||||
return 0, Internal("批量归档失败")
|
||||
}
|
||||
for _, id := range ids {
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: id,
|
||||
OperatorID: operatorID,
|
||||
Action: "archive",
|
||||
Detail: "会话已归档",
|
||||
})
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
// AgentSendMessage 坐席向会话发送消息并广播。
|
||||
func AgentSendMessage(session *model.Session, actor Actor, msgType, content string) (*model.Message, error) {
|
||||
validated, err := ValidateMessageContent(msgType, content)
|
||||
if err != nil {
|
||||
return nil, BadRequest(err.Error())
|
||||
}
|
||||
|
||||
if !CanOperateSession(actor, session) {
|
||||
return nil, Forbidden("无权向该会话发送消息")
|
||||
}
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
return nil, Conflict("会话已结束")
|
||||
}
|
||||
|
||||
senderID := actor.UserID
|
||||
msg := model.Message{
|
||||
SessionID: session.ID,
|
||||
SenderType: "agent",
|
||||
SenderID: &senderID,
|
||||
Content: validated,
|
||||
Type: msgType,
|
||||
SentAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := model.CreateMessage(&msg); err != nil {
|
||||
return nil, Internal("发送失败")
|
||||
}
|
||||
// 一线坐席发送后同步自己的已读进度;管理员/主管非会话归属,不推进
|
||||
if !actor.SessionAll {
|
||||
model.DB.Model(&model.Session{}).Where("id = ?", session.ID).Update("last_read_seq", msg.Seq)
|
||||
session.LastReadSeq = msg.Seq
|
||||
}
|
||||
BroadcastSessionMessage(session, msg)
|
||||
|
||||
return &msg, nil
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultWelcomeMessage = "您好!欢迎咨询,请问有什么可以帮您?"
|
||||
DefaultOfflinePrompt = "当前无客服在线,请留言并留下联系方式,我们上线后会尽快回复您。"
|
||||
DefaultWorktimePrompt = "当前为非工作时间,我们会在工作时段尽快回复您。"
|
||||
DefaultAgentNickname = "在线客服"
|
||||
defaultTimezone = "Asia/Shanghai"
|
||||
|
||||
MaxWelcomeSegments = 10
|
||||
maxWelcomeTextLen = 1000 // 纯文字上限(HTML 标签不计)
|
||||
maxWelcomeHTMLLen = 8000 // 富文本原始 HTML 上限
|
||||
)
|
||||
|
||||
// stripHTMLTags 粗暴去标签,用于字数与摘要(欢迎语 HTML)。
|
||||
func stripHTMLTags(s string) string {
|
||||
var b strings.Builder
|
||||
inTag := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r == '<':
|
||||
inTag = true
|
||||
case r == '>':
|
||||
inTag = false
|
||||
case !inTag:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
// 简单实体
|
||||
out := b.String()
|
||||
out = strings.ReplaceAll(out, " ", " ")
|
||||
out = strings.ReplaceAll(out, "&", "&")
|
||||
out = strings.ReplaceAll(out, "<", "<")
|
||||
out = strings.ReplaceAll(out, ">", ">")
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
// WelcomeSegment 单段欢迎语:文本或图片(content 为正文或对象存储 URL)。
|
||||
type WelcomeSegment struct {
|
||||
Type string `json:"type"` // text | image
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
var weekdayKeys = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
|
||||
|
||||
func defaultWelcomeSegments() []WelcomeSegment {
|
||||
return []WelcomeSegment{{Type: "text", Content: DefaultWelcomeMessage}}
|
||||
}
|
||||
|
||||
func defaultWelcomeMessagesJSON() string {
|
||||
b, _ := json.Marshal(defaultWelcomeSegments())
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// FirstWelcomeText 取第一段可用文本欢迎语(剥离 HTML),用于旧字段兼容展示。
|
||||
func FirstWelcomeText(segs []WelcomeSegment) string {
|
||||
for _, s := range segs {
|
||||
if s.Type != "text" {
|
||||
continue
|
||||
}
|
||||
plain := stripHTMLTags(s.Content)
|
||||
if plain == "" {
|
||||
plain = strings.TrimSpace(s.Content)
|
||||
}
|
||||
if plain == "" {
|
||||
continue
|
||||
}
|
||||
// welcome_message 列 size:500
|
||||
if utf8.RuneCountInString(plain) > 500 {
|
||||
return string([]rune(plain)[:500])
|
||||
}
|
||||
return plain
|
||||
}
|
||||
return DefaultWelcomeMessage
|
||||
}
|
||||
|
||||
// ResolveWelcomeSegments 解析多段欢迎语;兼容仅有旧 welcome_message 的数据。
|
||||
func ResolveWelcomeSegments(setting *model.TenantSetting) []WelcomeSegment {
|
||||
if setting == nil {
|
||||
return defaultWelcomeSegments()
|
||||
}
|
||||
raw := strings.TrimSpace(setting.WelcomeMessagesJSON)
|
||||
if raw != "" {
|
||||
var segs []WelcomeSegment
|
||||
if err := json.Unmarshal([]byte(raw), &segs); err == nil {
|
||||
out := make([]WelcomeSegment, 0, len(segs))
|
||||
for _, s := range segs {
|
||||
t := strings.TrimSpace(s.Type)
|
||||
c := strings.TrimSpace(s.Content)
|
||||
if (t == "text" || t == "image") && c != "" {
|
||||
out = append(out, WelcomeSegment{Type: t, Content: c})
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
if msg := strings.TrimSpace(setting.WelcomeMessage); msg != "" {
|
||||
return []WelcomeSegment{{Type: "text", Content: msg}}
|
||||
}
|
||||
return defaultWelcomeSegments()
|
||||
}
|
||||
|
||||
// NormalizeWelcomeSegments 校验并规范化欢迎语段落;返回规范化列表与兼容用首段文本。
|
||||
func NormalizeWelcomeSegments(input []WelcomeSegment) ([]WelcomeSegment, string, error) {
|
||||
if len(input) == 0 {
|
||||
return nil, "", fmt.Errorf("至少保留一段欢迎语")
|
||||
}
|
||||
if len(input) > MaxWelcomeSegments {
|
||||
return nil, "", fmt.Errorf("欢迎语最多 %d 段", MaxWelcomeSegments)
|
||||
}
|
||||
out := make([]WelcomeSegment, 0, len(input))
|
||||
for i, seg := range input {
|
||||
t := strings.ToLower(strings.TrimSpace(seg.Type))
|
||||
c := strings.TrimSpace(seg.Content)
|
||||
switch t {
|
||||
case "text":
|
||||
// 允许 HTML 富文本;禁止明显脚本
|
||||
lower := strings.ToLower(c)
|
||||
if strings.Contains(lower, "<script") || strings.Contains(lower, "javascript:") {
|
||||
return nil, "", fmt.Errorf("第 %d 段欢迎语包含不安全内容", i+1)
|
||||
}
|
||||
plain := stripHTMLTags(c)
|
||||
if plain == "" {
|
||||
return nil, "", fmt.Errorf("第 %d 段文本不能为空", i+1)
|
||||
}
|
||||
if utf8.RuneCountInString(plain) > maxWelcomeTextLen {
|
||||
return nil, "", fmt.Errorf("第 %d 段文字不能超过 %d 字", i+1, maxWelcomeTextLen)
|
||||
}
|
||||
if utf8.RuneCountInString(c) > maxWelcomeHTMLLen {
|
||||
return nil, "", fmt.Errorf("第 %d 段内容过长", i+1)
|
||||
}
|
||||
out = append(out, WelcomeSegment{Type: "text", Content: c})
|
||||
case "image":
|
||||
validated, err := ValidateMessageContent("image", c)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("第 %d 段图片:%s", i+1, err.Error())
|
||||
}
|
||||
out = append(out, WelcomeSegment{Type: "image", Content: validated})
|
||||
default:
|
||||
return nil, "", fmt.Errorf("第 %d 段类型无效,请使用 text 或 image", i+1)
|
||||
}
|
||||
}
|
||||
return out, FirstWelcomeText(out), nil
|
||||
}
|
||||
|
||||
func defaultWorkHoursJSON() string {
|
||||
// 默认全周全天可接待,租户可在设置中收紧为工作日时段
|
||||
hours := map[string]string{
|
||||
"monday": "全天", "tuesday": "全天", "wednesday": "全天",
|
||||
"thursday": "全天", "friday": "全天", "saturday": "全天", "sunday": "全天",
|
||||
}
|
||||
b, _ := json.Marshal(hours)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// GetOrCreateTenantSettings 读取租户设置;首次访问时以默认值落库。
|
||||
func GetOrCreateTenantSettings(tenantID uint) (*model.TenantSetting, error) {
|
||||
var setting model.TenantSetting
|
||||
err := model.DB.Where("tenant_id = ?", tenantID).First(&setting).Error
|
||||
if err == nil {
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
var tenant model.Tenant
|
||||
_ = model.DB.First(&tenant, tenantID).Error
|
||||
displayName := tenant.Name
|
||||
if displayName == "" {
|
||||
displayName = "在线客服"
|
||||
}
|
||||
setting = model.TenantSetting{
|
||||
TenantID: tenantID,
|
||||
DisplayName: displayName,
|
||||
AgentNickname: DefaultAgentNickname,
|
||||
Timezone: defaultTimezone,
|
||||
WelcomeMessage: DefaultWelcomeMessage,
|
||||
WelcomeMessagesJSON: defaultWelcomeMessagesJSON(),
|
||||
OfflinePrompt: DefaultOfflinePrompt,
|
||||
WorkHoursJSON: defaultWorkHoursJSON(),
|
||||
WorktimePrompt: DefaultWorktimePrompt,
|
||||
NotifyNewSession: true,
|
||||
NotifyOfflineLeave: true,
|
||||
NotifyDailyReport: false,
|
||||
AssignStrategy: AssignStrategyLeastLoad,
|
||||
MaxActivePerAgent: 0,
|
||||
}
|
||||
if err := model.DB.Create(&setting).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func ParseWorkHours(raw string) map[string]string {
|
||||
result := map[string]string{}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
_ = json.Unmarshal([]byte(defaultWorkHoursJSON()), &result)
|
||||
return result
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &result); err != nil {
|
||||
_ = json.Unmarshal([]byte(defaultWorkHoursJSON()), &result)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// NormalizeWorkHourSlot 规范化单日工作时间配置。
|
||||
// 允许:空/休息(→ 空)、全天、HH:MM-HH:MM(支持跨午夜,如 22:00-06:00)。
|
||||
func NormalizeWorkHourSlot(val string) (string, error) {
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" || val == "休息" {
|
||||
return "", nil
|
||||
}
|
||||
if val == "全天" {
|
||||
return "全天", nil
|
||||
}
|
||||
// 仅允许一个区间:HH:MM-HH:MM
|
||||
parts := strings.Split(val, "-")
|
||||
if len(parts) != 2 {
|
||||
return "", fmt.Errorf("工作时间格式无效,请使用 09:00-18:00 / 全天 / 空")
|
||||
}
|
||||
startS := strings.TrimSpace(parts[0])
|
||||
endS := strings.TrimSpace(parts[1])
|
||||
start, err1 := time.Parse("15:04", startS)
|
||||
end, err2 := time.Parse("15:04", endS)
|
||||
if err1 != nil || err2 != nil {
|
||||
return "", fmt.Errorf("工作时间格式无效,请使用 09:00-18:00(24 小时制)")
|
||||
}
|
||||
return start.Format("15:04") + "-" + end.Format("15:04"), nil
|
||||
}
|
||||
|
||||
// slotCoversLocal 判断 slot(全天 / HH:MM-HH:MM)是否覆盖 local 时刻。
|
||||
func slotCoversLocal(slot string, local time.Time, loc *time.Location) bool {
|
||||
slot = strings.TrimSpace(slot)
|
||||
if slot == "" || slot == "休息" {
|
||||
return false
|
||||
}
|
||||
if slot == "全天" {
|
||||
return true
|
||||
}
|
||||
parts := strings.Split(slot, "-")
|
||||
if len(parts) != 2 {
|
||||
// 非法配置 fail-open,避免因脏数据整站拒接
|
||||
return true
|
||||
}
|
||||
start, err1 := time.ParseInLocation("15:04", strings.TrimSpace(parts[0]), loc)
|
||||
end, err2 := time.ParseInLocation("15:04", strings.TrimSpace(parts[1]), loc)
|
||||
if err1 != nil || err2 != nil {
|
||||
return true
|
||||
}
|
||||
startAt := time.Date(local.Year(), local.Month(), local.Day(), start.Hour(), start.Minute(), 0, 0, loc)
|
||||
endAt := time.Date(local.Year(), local.Month(), local.Day(), end.Hour(), end.Minute(), 0, 0, loc)
|
||||
if !endAt.After(startAt) {
|
||||
// 跨午夜:当前 >= start 或 < end
|
||||
return !local.Before(startAt) || local.Before(endAt)
|
||||
}
|
||||
return !local.Before(startAt) && local.Before(endAt)
|
||||
}
|
||||
|
||||
// IsWithinWorkHours 根据租户工作时间配置判断当前是否在工作时段。
|
||||
// 未配置或某日为空视为休息;时段格式 HH:MM-HH:MM(可跨午夜)。
|
||||
func IsWithinWorkHours(setting *model.TenantSetting, now time.Time) bool {
|
||||
if setting == nil {
|
||||
return true
|
||||
}
|
||||
loc, err := time.LoadLocation(setting.Timezone)
|
||||
if err != nil || setting.Timezone == "" {
|
||||
loc, _ = time.LoadLocation(defaultTimezone)
|
||||
}
|
||||
local := now.In(loc)
|
||||
hours := ParseWorkHours(setting.WorkHoursJSON)
|
||||
var key string
|
||||
switch local.Weekday() {
|
||||
case time.Monday:
|
||||
key = "monday"
|
||||
case time.Tuesday:
|
||||
key = "tuesday"
|
||||
case time.Wednesday:
|
||||
key = "wednesday"
|
||||
case time.Thursday:
|
||||
key = "thursday"
|
||||
case time.Friday:
|
||||
key = "friday"
|
||||
case time.Saturday:
|
||||
key = "saturday"
|
||||
default:
|
||||
key = "sunday"
|
||||
}
|
||||
return slotCoversLocal(hours[key], local, loc)
|
||||
}
|
||||
|
||||
// SettingsResponse 组装设置响应体。
|
||||
func SettingsResponse(setting *model.TenantSetting) map[string]interface{} {
|
||||
strategy := NormalizeAssignStrategy(setting.AssignStrategy)
|
||||
maxActive := setting.MaxActivePerAgent
|
||||
if maxActive < 0 {
|
||||
maxActive = 0
|
||||
}
|
||||
welcomeSegs := ResolveWelcomeSegments(setting)
|
||||
return map[string]interface{}{
|
||||
"tenant_id": setting.TenantID,
|
||||
"display_name": setting.DisplayName,
|
||||
"agent_nickname": setting.AgentNickname,
|
||||
"timezone": setting.Timezone,
|
||||
"welcome_message": FirstWelcomeText(welcomeSegs),
|
||||
"welcome_messages": welcomeSegs,
|
||||
"offline_prompt": setting.OfflinePrompt,
|
||||
"work_hours": ParseWorkHours(setting.WorkHoursJSON),
|
||||
"worktime_prompt": setting.WorktimePrompt,
|
||||
"notify_new_session": setting.NotifyNewSession,
|
||||
"notify_offline_leave": setting.NotifyOfflineLeave,
|
||||
"notify_daily_report": setting.NotifyDailyReport,
|
||||
"assign_strategy": strategy,
|
||||
"max_active_per_agent": maxActive,
|
||||
}
|
||||
}
|
||||
|
||||
// SettingsUpdateReq 设置更新请求(pointer 字段表示是否提交该字段)。
|
||||
type SettingsUpdateReq struct {
|
||||
DisplayName *string `json:"display_name"`
|
||||
AgentNickname *string `json:"agent_nickname"`
|
||||
Timezone *string `json:"timezone"`
|
||||
WelcomeMessage *string `json:"welcome_message"`
|
||||
WelcomeMessages *[]WelcomeSegment `json:"welcome_messages"`
|
||||
OfflinePrompt *string `json:"offline_prompt"`
|
||||
WorkHours map[string]string `json:"work_hours"`
|
||||
WorktimePrompt *string `json:"worktime_prompt"`
|
||||
NotifyNewSession *bool `json:"notify_new_session"`
|
||||
NotifyOfflineLeave *bool `json:"notify_offline_leave"`
|
||||
NotifyDailyReport *bool `json:"notify_daily_report"`
|
||||
AssignStrategy *string `json:"assign_strategy"`
|
||||
MaxActivePerAgent *int `json:"max_active_per_agent"`
|
||||
}
|
||||
|
||||
// TouchesAssignRule / TouchesAutoReply / TouchesWorktime / TouchesNotification
|
||||
// 供 handler 按字段分区校验权限。
|
||||
func (r *SettingsUpdateReq) TouchesAssignRule() bool {
|
||||
return r.AssignStrategy != nil || r.MaxActivePerAgent != nil
|
||||
}
|
||||
|
||||
func (r *SettingsUpdateReq) TouchesAutoReply() bool {
|
||||
return r.WelcomeMessage != nil || r.WelcomeMessages != nil || r.OfflinePrompt != nil
|
||||
}
|
||||
|
||||
func (r *SettingsUpdateReq) TouchesWorktime() bool {
|
||||
return r.WorkHours != nil || r.WorktimePrompt != nil
|
||||
}
|
||||
|
||||
func (r *SettingsUpdateReq) TouchesNotification() bool {
|
||||
return r.NotifyNewSession != nil || r.NotifyOfflineLeave != nil || r.NotifyDailyReport != nil
|
||||
}
|
||||
|
||||
// UpdateTenantSettings 校验并持久化租户设置,返回刷新后的响应体。
|
||||
func UpdateTenantSettings(tenantID uint, req *SettingsUpdateReq) (map[string]interface{}, error) {
|
||||
setting, err := GetOrCreateTenantSettings(tenantID)
|
||||
if err != nil {
|
||||
return nil, Internal("加载设置失败")
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{}
|
||||
if req.DisplayName != nil {
|
||||
name := strings.TrimSpace(*req.DisplayName)
|
||||
if name == "" || len([]rune(name)) > 100 {
|
||||
return nil, BadRequest("租户显示名称无效")
|
||||
}
|
||||
updates["display_name"] = name
|
||||
// 同步更新租户主表名称(唯一约束下若冲突则仅更新 setting)
|
||||
var conflict int64
|
||||
model.DB.Model(&model.Tenant{}).Where("name = ? AND id <> ?", name, tenantID).Count(&conflict)
|
||||
if conflict == 0 {
|
||||
model.DB.Model(&model.Tenant{}).Where("id = ?", tenantID).Update("name", name)
|
||||
}
|
||||
}
|
||||
if req.AgentNickname != nil {
|
||||
nick := strings.TrimSpace(*req.AgentNickname)
|
||||
if len([]rune(nick)) > 50 {
|
||||
return nil, BadRequest("客服昵称过长")
|
||||
}
|
||||
updates["agent_nickname"] = nick
|
||||
}
|
||||
if req.Timezone != nil {
|
||||
tz := strings.TrimSpace(*req.Timezone)
|
||||
if tz == "" {
|
||||
tz = defaultTimezone
|
||||
}
|
||||
if _, err := time.LoadLocation(tz); err != nil {
|
||||
return nil, BadRequest("时区无效")
|
||||
}
|
||||
updates["timezone"] = tz
|
||||
}
|
||||
// 优先多段欢迎语;若仅传旧 welcome_message 则同步为单段文本
|
||||
if req.WelcomeMessages != nil {
|
||||
segs, firstText, err := NormalizeWelcomeSegments(*req.WelcomeMessages)
|
||||
if err != nil {
|
||||
return nil, BadRequest(err.Error())
|
||||
}
|
||||
b, err := json.Marshal(segs)
|
||||
if err != nil {
|
||||
return nil, BadRequest("欢迎语序列化失败")
|
||||
}
|
||||
updates["welcome_messages_json"] = string(b)
|
||||
updates["welcome_message"] = firstText
|
||||
} else if req.WelcomeMessage != nil {
|
||||
msg := strings.TrimSpace(*req.WelcomeMessage)
|
||||
if len([]rune(msg)) > 500 {
|
||||
return nil, BadRequest("欢迎语不能超过 500 字")
|
||||
}
|
||||
updates["welcome_message"] = msg
|
||||
// 同步为单段,避免旧字段与 JSON 不一致
|
||||
if msg == "" {
|
||||
updates["welcome_messages_json"] = defaultWelcomeMessagesJSON()
|
||||
updates["welcome_message"] = DefaultWelcomeMessage
|
||||
} else {
|
||||
b, _ := json.Marshal([]WelcomeSegment{{Type: "text", Content: msg}})
|
||||
updates["welcome_messages_json"] = string(b)
|
||||
}
|
||||
}
|
||||
if req.OfflinePrompt != nil {
|
||||
msg := strings.TrimSpace(*req.OfflinePrompt)
|
||||
if len([]rune(msg)) > 500 {
|
||||
return nil, BadRequest("离线提示不能超过 500 字")
|
||||
}
|
||||
updates["offline_prompt"] = msg
|
||||
}
|
||||
if req.WorktimePrompt != nil {
|
||||
msg := strings.TrimSpace(*req.WorktimePrompt)
|
||||
if len([]rune(msg)) > 500 {
|
||||
return nil, BadRequest("非工作时间提示不能超过 500 字")
|
||||
}
|
||||
updates["worktime_prompt"] = msg
|
||||
}
|
||||
if req.WorkHours != nil {
|
||||
normalized := map[string]string{}
|
||||
for _, key := range weekdayKeys {
|
||||
slot, err := NormalizeWorkHourSlot(req.WorkHours[key])
|
||||
if err != nil {
|
||||
return nil, BadRequest(err.Error())
|
||||
}
|
||||
normalized[key] = slot
|
||||
}
|
||||
b, err := json.Marshal(normalized)
|
||||
if err != nil {
|
||||
return nil, BadRequest("工作时间序列化失败")
|
||||
}
|
||||
updates["work_hours_json"] = string(b)
|
||||
}
|
||||
if req.NotifyNewSession != nil {
|
||||
updates["notify_new_session"] = *req.NotifyNewSession
|
||||
}
|
||||
if req.NotifyOfflineLeave != nil {
|
||||
updates["notify_offline_leave"] = *req.NotifyOfflineLeave
|
||||
}
|
||||
if req.NotifyDailyReport != nil {
|
||||
updates["notify_daily_report"] = *req.NotifyDailyReport
|
||||
}
|
||||
if req.AssignStrategy != nil {
|
||||
raw := strings.TrimSpace(*req.AssignStrategy)
|
||||
if raw != AssignStrategyLeastLoad && raw != AssignStrategyRoundRobin {
|
||||
return nil, BadRequest("分配策略无效,可选 least_load / round_robin")
|
||||
}
|
||||
updates["assign_strategy"] = raw
|
||||
}
|
||||
if req.MaxActivePerAgent != nil {
|
||||
if *req.MaxActivePerAgent < 0 || *req.MaxActivePerAgent > 200 {
|
||||
return nil, BadRequest("最大并发需为 0–200(0 表示不限制)")
|
||||
}
|
||||
updates["max_active_per_agent"] = *req.MaxActivePerAgent
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
return nil, BadRequest("没有可更新字段")
|
||||
}
|
||||
|
||||
if err := model.DB.Model(setting).Updates(updates).Error; err != nil {
|
||||
return nil, Internal("保存失败")
|
||||
}
|
||||
_ = model.DB.Where("tenant_id = ?", tenantID).First(setting).Error
|
||||
return SettingsResponse(setting), nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
)
|
||||
|
||||
func TestNormalizeWelcomeSegments(t *testing.T) {
|
||||
SetImagePublicBase("http://localhost:9100/kefu")
|
||||
|
||||
_, _, err := NormalizeWelcomeSegments(nil)
|
||||
if err == nil {
|
||||
t.Fatal("空列表应失败")
|
||||
}
|
||||
|
||||
ok, first, err := NormalizeWelcomeSegments([]WelcomeSegment{
|
||||
{Type: "text", Content: " 你好 "},
|
||||
{Type: "image", Content: "http://localhost:9100/kefu/tenants/1/welcome/a.webp"},
|
||||
{Type: "text", Content: "请描述问题"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("合法多段应通过: %v", err)
|
||||
}
|
||||
if len(ok) != 3 || ok[0].Content != "你好" || first != "你好" {
|
||||
t.Fatalf("规范化结果异常: %+v first=%s", ok, first)
|
||||
}
|
||||
|
||||
_, _, err = NormalizeWelcomeSegments([]WelcomeSegment{
|
||||
{Type: "image", Content: "https://evil.example/x.png"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("非白名单图片 URL 应失败")
|
||||
}
|
||||
|
||||
tooMany := make([]WelcomeSegment, MaxWelcomeSegments+1)
|
||||
for i := range tooMany {
|
||||
tooMany[i] = WelcomeSegment{Type: "text", Content: "x"}
|
||||
}
|
||||
if _, _, err := NormalizeWelcomeSegments(tooMany); err == nil {
|
||||
t.Fatal("超过段数上限应失败")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWelcomeSegmentsCompat(t *testing.T) {
|
||||
// 仅有旧字段
|
||||
s1 := &model.TenantSetting{WelcomeMessage: "旧欢迎语"}
|
||||
segs := ResolveWelcomeSegments(s1)
|
||||
if len(segs) != 1 || segs[0].Type != "text" || segs[0].Content != "旧欢迎语" {
|
||||
t.Fatalf("旧字段兼容失败: %+v", segs)
|
||||
}
|
||||
|
||||
// 优先 JSON
|
||||
s2 := &model.TenantSetting{
|
||||
WelcomeMessage: "旧",
|
||||
WelcomeMessagesJSON: `[{"type":"text","content":"新1"},{"type":"image","content":"http://x/a.webp"}]`,
|
||||
}
|
||||
segs = ResolveWelcomeSegments(s2)
|
||||
if len(segs) != 2 || segs[0].Content != "新1" {
|
||||
t.Fatalf("JSON 优先失败: %+v", segs)
|
||||
}
|
||||
|
||||
// 空 → 默认
|
||||
segs = ResolveWelcomeSegments(&model.TenantSetting{})
|
||||
if len(segs) != 1 || segs[0].Content != DefaultWelcomeMessage {
|
||||
t.Fatalf("默认欢迎语失败: %+v", segs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeWorkHourSlot(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{"", "", false},
|
||||
{" 休息 ", "", false},
|
||||
{"全天", "全天", false},
|
||||
{"09:00-18:00", "09:00-18:00", false},
|
||||
{" 9:30 - 18:05 ", "09:30-18:05", false},
|
||||
{"22:00-06:00", "22:00-06:00", false},
|
||||
{"全天营业", "", true},
|
||||
{"09:00", "", true},
|
||||
{"25:00-26:00", "", true},
|
||||
{"09:00-18:00-extra", "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := NormalizeWorkHourSlot(tc.in)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("NormalizeWorkHourSlot(%q) 期望错误,got=%q", tc.in, got)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizeWorkHourSlot(%q) 意外错误: %v", tc.in, err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("NormalizeWorkHourSlot(%q)=%q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotCoversLocal(t *testing.T) {
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 2026-03-16 周一
|
||||
mk := func(h, m int) time.Time {
|
||||
return time.Date(2026, 3, 16, h, m, 0, 0, loc)
|
||||
}
|
||||
|
||||
if !slotCoversLocal("全天", mk(3, 0), loc) {
|
||||
t.Fatal("全天应覆盖任意时刻")
|
||||
}
|
||||
if slotCoversLocal("", mk(10, 0), loc) {
|
||||
t.Fatal("空应视为休息")
|
||||
}
|
||||
if slotCoversLocal("休息", mk(10, 0), loc) {
|
||||
t.Fatal("休息应不覆盖")
|
||||
}
|
||||
// 09:00-18:00 半开区间 [start, end)
|
||||
if !slotCoversLocal("09:00-18:00", mk(9, 0), loc) {
|
||||
t.Fatal("09:00 应在工作时间内")
|
||||
}
|
||||
if !slotCoversLocal("09:00-18:00", mk(17, 59), loc) {
|
||||
t.Fatal("17:59 应在工作时间内")
|
||||
}
|
||||
if slotCoversLocal("09:00-18:00", mk(18, 0), loc) {
|
||||
t.Fatal("18:00 不应在工作时间内(半开)")
|
||||
}
|
||||
if slotCoversLocal("09:00-18:00", mk(8, 59), loc) {
|
||||
t.Fatal("08:59 不应在工作时间内")
|
||||
}
|
||||
// 跨午夜 22:00-06:00
|
||||
if !slotCoversLocal("22:00-06:00", mk(23, 0), loc) {
|
||||
t.Fatal("23:00 应在跨午夜时段内")
|
||||
}
|
||||
if !slotCoversLocal("22:00-06:00", mk(5, 0), loc) {
|
||||
t.Fatal("05:00 应在跨午夜时段内")
|
||||
}
|
||||
if slotCoversLocal("22:00-06:00", mk(12, 0), loc) {
|
||||
t.Fatal("12:00 不应在跨午夜时段内")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWithinWorkHoursCustomRange(t *testing.T) {
|
||||
setting := &model.TenantSetting{
|
||||
Timezone: "Asia/Shanghai",
|
||||
WorkHoursJSON: `{
|
||||
"monday":"09:30-12:00",
|
||||
"tuesday":"全天",
|
||||
"wednesday":"",
|
||||
"thursday":"22:00-06:00",
|
||||
"friday":"全天",
|
||||
"saturday":"休息",
|
||||
"sunday":""
|
||||
}`,
|
||||
}
|
||||
loc, _ := time.LoadLocation("Asia/Shanghai")
|
||||
|
||||
// 周一 10:00 → 在 09:30-12:00
|
||||
mon := time.Date(2026, 3, 16, 10, 0, 0, 0, loc)
|
||||
if !IsWithinWorkHours(setting, mon) {
|
||||
t.Fatal("周一 10:00 应在自定义时段内")
|
||||
}
|
||||
// 周一 14:00 → 不在
|
||||
monPM := time.Date(2026, 3, 16, 14, 0, 0, 0, loc)
|
||||
if IsWithinWorkHours(setting, monPM) {
|
||||
t.Fatal("周一 14:00 不应在工作时间")
|
||||
}
|
||||
// 周三休息
|
||||
wed := time.Date(2026, 3, 18, 10, 0, 0, 0, loc)
|
||||
if IsWithinWorkHours(setting, wed) {
|
||||
t.Fatal("周三应休息")
|
||||
}
|
||||
// 周四跨午夜 23:00
|
||||
thu := time.Date(2026, 3, 19, 23, 0, 0, 0, loc)
|
||||
if !IsWithinWorkHours(setting, thu) {
|
||||
t.Fatal("周四 23:00 应在跨午夜时段")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"kefu-cloud/server/internal/model"
|
||||
"kefu-cloud/server/internal/ws"
|
||||
)
|
||||
|
||||
// UniqueUint 去重并过滤零值。
|
||||
func UniqueUint(ids []uint) []uint {
|
||||
seen := make(map[uint]struct{}, len(ids))
|
||||
out := make([]uint, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id == 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// UserDisplayName 坐席展示名(昵称优先,其次用户名)。
|
||||
func UserDisplayName(userID uint) string {
|
||||
var user model.User
|
||||
if err := model.DB.Select("id", "nickname", "username").First(&user, userID).Error; err != nil {
|
||||
return "未知坐席"
|
||||
}
|
||||
if strings.TrimSpace(user.Nickname) != "" {
|
||||
return user.Nickname
|
||||
}
|
||||
if strings.TrimSpace(user.Username) != "" {
|
||||
return user.Username
|
||||
}
|
||||
return "未知坐席"
|
||||
}
|
||||
|
||||
// BroadcastSessionMessage 会话新消息广播(坐席 + 访客)。
|
||||
func BroadcastSessionMessage(session *model.Session, message model.Message) {
|
||||
payload, err := ws.NewEvent("message", session.ID, message)
|
||||
if err == nil {
|
||||
ws.DefaultHub.BroadcastToSession(session.TenantID, session.ID, session.AgentID, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastSessionUpdate 会话状态变更广播:坐席列表需要刷新;访客也必须收到
|
||||
// ended/active,才能弹出评价或更新接待状态。
|
||||
func BroadcastSessionUpdate(session *model.Session) {
|
||||
payload, err := ws.NewEvent("session_updated", session.ID, map[string]interface{}{"status": session.Status})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
ws.DefaultHub.BroadcastToVisitor(session.TenantID, session.ID, payload)
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"kefu-cloud/server/internal/model"
|
||||
"kefu-cloud/server/internal/ws"
|
||||
)
|
||||
|
||||
var channelKeyPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{3,64}$`)
|
||||
var phonePattern = regexp.MustCompile(`^1[3-9]\d{9}$`)
|
||||
var emailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
||||
|
||||
// VisitorMeta 访客环境信息(由 handler 从请求解析,service 不感知 HTTP)。
|
||||
type VisitorMeta struct {
|
||||
IP string
|
||||
Region string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// WidgetSession 校验访客凭证并加载会话。
|
||||
func WidgetSession(sessionID uint, token string) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := model.DB.First(&session, sessionID).Error; err != nil {
|
||||
return nil, NotFound("会话不存在")
|
||||
}
|
||||
if !model.VerifyVisitorToken(&session, token) {
|
||||
return nil, &Error{Status: 401, Message: "访客会话凭证无效"}
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
// WidgetInitInput 访客初始化入参。
|
||||
type WidgetInitInput struct {
|
||||
ChannelKey string
|
||||
VisitorName string
|
||||
DeviceID string
|
||||
PageURL string
|
||||
PageTitle string
|
||||
Referrer string
|
||||
Meta VisitorMeta
|
||||
}
|
||||
|
||||
// WidgetInit 访客进线:渠道校验、客户/会话创建、黑名单拦截、自动分配与欢迎语组装。
|
||||
func WidgetInit(in WidgetInitInput) (map[string]interface{}, error) {
|
||||
if !channelKeyPattern.MatchString(in.ChannelKey) {
|
||||
return nil, BadRequest("渠道标识无效")
|
||||
}
|
||||
|
||||
var channel model.Channel
|
||||
if err := model.DB.
|
||||
Where("type = ? AND status = ? AND script_code LIKE ?", "web", "enabled", "%data-id=\""+in.ChannelKey+"\"%").
|
||||
First(&channel).Error; err != nil {
|
||||
return nil, NotFound("渠道不存在或已关闭")
|
||||
}
|
||||
|
||||
name := strings.TrimSpace(in.VisitorName)
|
||||
if name == "" {
|
||||
name = "访客"
|
||||
}
|
||||
|
||||
// 创建或查找客户
|
||||
var customer model.Customer
|
||||
model.DB.Where("tenant_id = ? AND name = ? AND phone = ''", channel.TenantID, name).First(&customer)
|
||||
if customer.ID == 0 {
|
||||
customer = model.Customer{
|
||||
TenantID: channel.TenantID,
|
||||
Name: name,
|
||||
Source: "网页",
|
||||
Status: "online",
|
||||
}
|
||||
model.DB.Create(&customer)
|
||||
}
|
||||
|
||||
visitorToken, visitorTokenHash, err := model.NewVisitorToken()
|
||||
if err != nil {
|
||||
return nil, Internal("创建访客会话失败")
|
||||
}
|
||||
|
||||
deviceKey := NormalizeDeviceKey(in.DeviceID, in.Meta.UserAgent)
|
||||
// 黑名单拦截(IP / 设备)
|
||||
if blocked, blKind, blReason := CheckVisitorBlacklist(channel.TenantID, in.Meta.IP, deviceKey); blocked {
|
||||
kindLabel := "IP"
|
||||
if blKind == "device" {
|
||||
kindLabel = "设备"
|
||||
}
|
||||
msg := "您暂时无法使用在线客服"
|
||||
if strings.TrimSpace(blReason) != "" {
|
||||
msg = msg + "(" + kindLabel + "限制)"
|
||||
}
|
||||
return nil, Forbidden(msg)
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
// 创建会话
|
||||
session := model.Session{
|
||||
TenantID: channel.TenantID,
|
||||
ChannelID: channel.ID,
|
||||
CustomerID: customer.ID,
|
||||
VisitorTokenHash: visitorTokenHash,
|
||||
VisitorIP: in.Meta.IP,
|
||||
VisitorRegion: in.Meta.Region,
|
||||
UserAgent: in.Meta.UserAgent,
|
||||
DeviceKey: deviceKey,
|
||||
LandingURL: in.PageURL,
|
||||
LandingTitle: in.PageTitle,
|
||||
Referrer: in.Referrer,
|
||||
CurrentURL: in.PageURL,
|
||||
CurrentTitle: in.PageTitle,
|
||||
LastSeenAt: &now,
|
||||
Status: "waiting",
|
||||
Priority: "normal",
|
||||
}
|
||||
if err := model.DB.Create(&session).Error; err != nil {
|
||||
return nil, Internal("创建会话失败")
|
||||
}
|
||||
// 首条浏览轨迹
|
||||
if in.PageURL != "" {
|
||||
_ = model.DB.Create(&model.VisitorPageView{
|
||||
SessionID: session.ID,
|
||||
TenantID: channel.TenantID,
|
||||
URL: in.PageURL,
|
||||
Title: in.PageTitle,
|
||||
EnteredAt: now,
|
||||
}).Error
|
||||
}
|
||||
model.DB.Model(&model.Customer{}).Where("id = ? AND tenant_id = ?", customer.ID, channel.TenantID).
|
||||
Updates(map[string]interface{}{"conversation_count": gorm.Expr("conversation_count + 1"), "last_contact_at": time.Now()})
|
||||
|
||||
onlineCount, err := CountOnlineAgents(channel.TenantID)
|
||||
if err != nil {
|
||||
return nil, Internal("查询在线客服失败")
|
||||
}
|
||||
|
||||
setting, _ := GetOrCreateTenantSettings(channel.TenantID)
|
||||
withinWorkHours := IsWithinWorkHours(setting, time.Now())
|
||||
// 非工作时间不自动分配,走留言/排队提示
|
||||
canServeNow := onlineCount > 0 && withinWorkHours
|
||||
|
||||
var assignedAgent *model.User
|
||||
if canServeNow {
|
||||
assignedAgent, err = TryAutoAssign(&session)
|
||||
if err != nil {
|
||||
return nil, Internal("自动分配失败")
|
||||
}
|
||||
}
|
||||
|
||||
if payload, err := ws.NewEvent("session_created", session.ID, session); err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
}
|
||||
|
||||
welcomeSegs := ResolveWelcomeSegments(setting)
|
||||
welcome := FirstWelcomeText(welcomeSegs)
|
||||
offlinePrompt := DefaultOfflinePrompt
|
||||
agentNickname := DefaultAgentNickname
|
||||
displayName := "在线客服"
|
||||
worktimePrompt := DefaultWorktimePrompt
|
||||
if setting != nil {
|
||||
if setting.OfflinePrompt != "" {
|
||||
offlinePrompt = setting.OfflinePrompt
|
||||
}
|
||||
if setting.AgentNickname != "" {
|
||||
agentNickname = setting.AgentNickname
|
||||
}
|
||||
if setting.DisplayName != "" {
|
||||
displayName = setting.DisplayName
|
||||
}
|
||||
if setting.WorktimePrompt != "" {
|
||||
worktimePrompt = setting.WorktimePrompt
|
||||
}
|
||||
}
|
||||
// 非工作时间优先展示非工作时间提示
|
||||
if !withinWorkHours {
|
||||
offlinePrompt = worktimePrompt
|
||||
}
|
||||
|
||||
resp := map[string]interface{}{
|
||||
"session_id": session.ID,
|
||||
"customer_id": customer.ID,
|
||||
"channel_id": channel.ID,
|
||||
"tenant_id": channel.TenantID,
|
||||
"visitor_token": visitorToken,
|
||||
"agents_online": canServeNow,
|
||||
"online_agent_count": onlineCount,
|
||||
"within_work_hours": withinWorkHours,
|
||||
"session_status": session.Status,
|
||||
"welcome_message": welcome,
|
||||
"welcome_messages": welcomeSegs,
|
||||
"display_name": displayName,
|
||||
"agent_nickname": agentNickname,
|
||||
}
|
||||
if !canServeNow {
|
||||
resp["offline_prompt"] = offlinePrompt
|
||||
}
|
||||
if assignedAgent != nil {
|
||||
resp["agent_id"] = assignedAgent.ID
|
||||
resp["agent_name"] = assignedAgent.Nickname
|
||||
} else if canServeNow {
|
||||
resp["agent_name"] = agentNickname
|
||||
}
|
||||
resp["landing_url"] = session.LandingURL
|
||||
resp["current_url"] = session.CurrentURL
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// WidgetPageView 访客换页上报:与当前页相同只刷新活跃时间/标题,否则插入轨迹并裁剪。
|
||||
func WidgetPageView(session *model.Session, pageURL, pageTitle string) (interface{}, error) {
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
return nil, Conflict("会话已结束")
|
||||
}
|
||||
if pageURL == "" {
|
||||
return nil, BadRequest("页面地址无效")
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
// 与当前页相同:只刷新活跃时间/标题,不插重复轨迹
|
||||
if strings.TrimSpace(session.CurrentURL) == pageURL {
|
||||
updates := map[string]interface{}{
|
||||
"last_seen_at": now,
|
||||
}
|
||||
titleFixed := false
|
||||
if pageTitle != "" && pageTitle != strings.TrimSpace(session.CurrentTitle) {
|
||||
updates["current_title"] = pageTitle
|
||||
// 同步最新一条轨迹的标题(纠正「慢一页」时写入的旧 title)
|
||||
var last model.VisitorPageView
|
||||
if err := model.DB.Where("session_id = ? AND url = ?", session.ID, pageURL).
|
||||
Order("entered_at desc").First(&last).Error; err == nil {
|
||||
_ = model.DB.Model(&last).Update("title", pageTitle).Error
|
||||
titleFixed = true
|
||||
if payload, err := ws.NewEvent("page_view", session.ID, map[string]interface{}{
|
||||
"id": last.ID,
|
||||
"session_id": last.SessionID,
|
||||
"url": pageURL,
|
||||
"title": pageTitle,
|
||||
"entered_at": last.EnteredAt,
|
||||
"title_fix": true,
|
||||
}); err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = model.DB.Model(session).Updates(updates).Error
|
||||
return map[string]interface{}{"deduped": true, "title_updated": titleFixed}, nil
|
||||
}
|
||||
|
||||
pv := model.VisitorPageView{
|
||||
SessionID: session.ID,
|
||||
TenantID: session.TenantID,
|
||||
URL: pageURL,
|
||||
Title: pageTitle,
|
||||
EnteredAt: now,
|
||||
}
|
||||
if err := model.DB.Create(&pv).Error; err != nil {
|
||||
return nil, Internal("记录失败")
|
||||
}
|
||||
_ = model.DB.Model(session).Updates(map[string]interface{}{
|
||||
"current_url": pageURL,
|
||||
"current_title": pageTitle,
|
||||
"last_seen_at": now,
|
||||
}).Error
|
||||
|
||||
// 控制单会话条数
|
||||
var count int64
|
||||
model.DB.Model(&model.VisitorPageView{}).Where("session_id = ?", session.ID).Count(&count)
|
||||
if count > MaxPageViewsPerSession {
|
||||
var oldest []model.VisitorPageView
|
||||
model.DB.Where("session_id = ?", session.ID).Order("entered_at asc").
|
||||
Limit(int(count - MaxPageViewsPerSession)).Find(&oldest)
|
||||
ids := make([]uint, 0, len(oldest))
|
||||
for _, o := range oldest {
|
||||
ids = append(ids, o.ID)
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
model.DB.Where("id IN ?", ids).Delete(&model.VisitorPageView{})
|
||||
}
|
||||
}
|
||||
|
||||
if payload, err := ws.NewEvent("page_view", session.ID, map[string]interface{}{
|
||||
"id": pv.ID,
|
||||
"session_id": pv.SessionID,
|
||||
"url": pv.URL,
|
||||
"title": pv.Title,
|
||||
"entered_at": pv.EnteredAt,
|
||||
}); err == nil {
|
||||
// 排队中 AgentID 为空时,BroadcastToSessionStaff 只会推给 admin/supervisor,
|
||||
// 一线坐席看不到实时轨迹;轨迹对租户内工作人员统一广播。
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
}
|
||||
|
||||
return pv, nil
|
||||
}
|
||||
|
||||
// WidgetHeartbeat 刷新访客 last_seen;会话已结束时仅返回结束标记。
|
||||
func WidgetHeartbeat(session *model.Session) (ended bool, lastSeen *time.Time, err error) {
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
return true, nil, nil
|
||||
}
|
||||
now := time.Now()
|
||||
_ = model.DB.Model(session).Update("last_seen_at", now).Error
|
||||
return false, &now, nil
|
||||
}
|
||||
|
||||
// WidgetSendMessage 访客发送消息;排队中会尝试自动分配并广播。
|
||||
func WidgetSendMessage(session *model.Session, msgType, content string) (*model.Message, error) {
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
return nil, Conflict("会话已结束,请重新发起咨询")
|
||||
}
|
||||
|
||||
custID := session.CustomerID
|
||||
msg := model.Message{
|
||||
SessionID: session.ID,
|
||||
SenderType: "visitor",
|
||||
SenderID: &custID,
|
||||
Content: content,
|
||||
Type: msgType,
|
||||
SentAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := model.CreateMessage(&msg); err != nil {
|
||||
return nil, Internal("发送失败")
|
||||
}
|
||||
// 发送后清空草稿
|
||||
_ = model.DB.Model(session).Updates(map[string]interface{}{
|
||||
"draft_text": "",
|
||||
"draft_updated_at": time.Now(),
|
||||
}).Error
|
||||
model.DB.Model(&model.Customer{}).Where("id = ? AND tenant_id = ?", session.CustomerID, session.TenantID).Update("last_contact_at", time.Now())
|
||||
|
||||
// 从已发送消息再提取一次联系方式
|
||||
if msgType == "text" {
|
||||
go OnVisitorDraftContacts(session.TenantID, session.CustomerID, session.ID, content)
|
||||
}
|
||||
|
||||
// 仍在排队时尝试自动分配(客服刚上线的场景)
|
||||
if session.Status == "waiting" && session.AgentID == nil {
|
||||
if _, err := TryAutoAssign(session); err == nil {
|
||||
_ = model.DB.First(session, session.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if payload, err := ws.NewEvent("message", session.ID, msg); err == nil {
|
||||
if session.AgentID == nil {
|
||||
// 等待会话的消息要通知全部客服,便于任一在线客服及时领取。
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
} else {
|
||||
ws.DefaultHub.BroadcastToSession(session.TenantID, session.ID, session.AgentID, payload)
|
||||
}
|
||||
}
|
||||
// 通知坐席清空草稿预览
|
||||
if clearPayload, err := ws.NewEvent("input_draft", session.ID, map[string]interface{}{
|
||||
"from": "visitor",
|
||||
"text": "",
|
||||
}); err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, clearPayload)
|
||||
}
|
||||
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
// WidgetLeaveMessageResult 离线留言结果。
|
||||
type WidgetLeaveMessageResult struct {
|
||||
Message model.Message
|
||||
SessionStatus string
|
||||
AgentsOnline bool
|
||||
}
|
||||
|
||||
// WidgetLeaveMessage 无客服在线时提交留言并沉淀联系方式。
|
||||
func WidgetLeaveMessage(session *model.Session, content, name, phone, email string) (*WidgetLeaveMessageResult, error) {
|
||||
if session.Status == "ended" || session.Status == "archived" {
|
||||
return nil, Conflict("会话已结束,请重新发起咨询")
|
||||
}
|
||||
|
||||
// 若此刻已有客服在线,直接走自动分配,留言仍作为普通消息入库
|
||||
onlineCount, _ := CountOnlineAgents(session.TenantID)
|
||||
if onlineCount > 0 && session.Status == "waiting" {
|
||||
if _, err := TryAutoAssign(session); err == nil {
|
||||
_ = model.DB.First(session, session.ID)
|
||||
}
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{"last_contact_at": time.Now()}
|
||||
if name != "" {
|
||||
updates["name"] = name
|
||||
}
|
||||
if phone != "" {
|
||||
updates["phone"] = phone
|
||||
}
|
||||
if email != "" {
|
||||
updates["email"] = email
|
||||
}
|
||||
if err := model.DB.Model(&model.Customer{}).Where("id = ? AND tenant_id = ?", session.CustomerID, session.TenantID).
|
||||
Updates(updates).Error; err != nil {
|
||||
return nil, Internal("更新联系方式失败")
|
||||
}
|
||||
|
||||
custID := session.CustomerID
|
||||
msg := model.Message{
|
||||
SessionID: session.ID,
|
||||
SenderType: "visitor",
|
||||
SenderID: &custID,
|
||||
Content: content,
|
||||
Type: "text",
|
||||
SentAt: time.Now(),
|
||||
}
|
||||
if err := model.CreateMessage(&msg); err != nil {
|
||||
return nil, Internal("留言失败")
|
||||
}
|
||||
|
||||
contactBits := make([]string, 0, 3)
|
||||
if name != "" {
|
||||
contactBits = append(contactBits, "姓名:"+name)
|
||||
}
|
||||
if phone != "" {
|
||||
contactBits = append(contactBits, "手机:"+phone)
|
||||
}
|
||||
if email != "" {
|
||||
contactBits = append(contactBits, "邮箱:"+email)
|
||||
}
|
||||
model.DB.Create(&model.SessionEvent{
|
||||
SessionID: session.ID,
|
||||
OperatorID: 0,
|
||||
Action: "offline_leave",
|
||||
Detail: "离线留言 · " + strings.Join(contactBits, " · "),
|
||||
})
|
||||
|
||||
if payload, err := ws.NewEvent("message", session.ID, msg); err == nil {
|
||||
if session.AgentID == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
} else {
|
||||
ws.DefaultHub.BroadcastToSession(session.TenantID, session.ID, session.AgentID, payload)
|
||||
}
|
||||
}
|
||||
if payload, err := ws.NewEvent("session_updated", session.ID, session); err == nil {
|
||||
ws.DefaultHub.BroadcastToTenantStaff(session.TenantID, payload)
|
||||
}
|
||||
|
||||
return &WidgetLeaveMessageResult{
|
||||
Message: msg,
|
||||
SessionStatus: session.Status,
|
||||
AgentsOnline: onlineCount > 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateLeaveContact 校验留言联系方式(至少一项 + 格式)。
|
||||
func ValidateLeaveContact(name, phone, email string) error {
|
||||
if phone == "" && email == "" {
|
||||
return BadRequest("请至少填写手机号或邮箱,便于我们回复")
|
||||
}
|
||||
if phone != "" && !phonePattern.MatchString(phone) {
|
||||
return BadRequest("手机号格式不正确")
|
||||
}
|
||||
if email != "" && !emailPattern.MatchString(email) {
|
||||
return BadRequest("邮箱格式不正确")
|
||||
}
|
||||
if name != "" && (len([]rune(name)) < 2 || len([]rune(name)) > 50) {
|
||||
return BadRequest("姓名需为 2 至 50 个字符")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WidgetSubmitRating 会话结束后提交星级评价(一次性)。
|
||||
func WidgetSubmitRating(session *model.Session, score int, text string) error {
|
||||
if session.Status != "ended" {
|
||||
return Conflict("会话结束后才能评价")
|
||||
}
|
||||
if session.SatisfactionScore != nil {
|
||||
return Conflict("该会话已评价")
|
||||
}
|
||||
|
||||
if err := model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&model.Session{}).Where("id = ? AND satisfaction_score IS NULL", session.ID).
|
||||
Updates(map[string]interface{}{"satisfaction_score": score, "satisfaction_text": text})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return tx.Model(&model.Customer{}).Where("id = ? AND tenant_id = ?", session.CustomerID, session.TenantID).
|
||||
Updates(map[string]interface{}{
|
||||
"satisfaction_sum": gorm.Expr("satisfaction_sum + ?", score),
|
||||
"satisfaction_count": gorm.Expr("satisfaction_count + 1"),
|
||||
}).Error
|
||||
}); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return Conflict("该会话已评价")
|
||||
}
|
||||
return Internal("提交评价失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WidgetMessages 访客按 seq 增量拉取消息。
|
||||
func WidgetMessages(session *model.Session, afterSeq, limit int) (map[string]interface{}, error) {
|
||||
page, err := SessionMessagePage(session.ID, afterSeq, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"messages": page.Messages,
|
||||
"after_seq": page.AfterSeq,
|
||||
"max_seq": page.MaxSeq,
|
||||
"has_more": page.HasMore,
|
||||
"session_status": session.Status,
|
||||
"satisfaction_score": session.SatisfactionScore,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user