refactor: support i18n

This commit is contained in:
mlogclub
2026-05-25 12:06:15 +08:00
parent 309ac1fe9e
commit 988f55c80d
179 changed files with 10968 additions and 3763 deletions
+51 -4
View File
@@ -6,6 +6,7 @@ import (
"cs-agent/internal/models"
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/pkg/enums"
"cs-agent/internal/pkg/i18nx"
"cs-agent/internal/pkg/utils"
"cs-agent/internal/services"
@@ -13,6 +14,10 @@ import (
)
func BuildConversation(item *models.Conversation) response.ConversationResponse {
return BuildConversationWithLocale(item, i18nx.LocaleZhCN)
}
func BuildConversationWithLocale(item *models.Conversation, locale string) response.ConversationResponse {
agentReadState, customerReadState := services.ConversationReadStateService.GetConversationReadStates(item.ID)
ret := response.ConversationResponse{
ID: item.ID,
@@ -28,7 +33,7 @@ func BuildConversation(item *models.Conversation) response.ConversationResponse
LastMessageID: item.LastMessageID,
LastMessageAt: utils.FormatTime(item.LastMessageAt),
LastActiveAt: utils.FormatTime(item.LastActiveAt),
LastMessageSummary: item.LastMessageSummary,
LastMessageSummary: localizeConversationSummary(locale, item.LastMessageSummary),
CustomerUnreadCount: item.CustomerUnreadCount,
AgentUnreadCount: item.AgentUnreadCount,
CustomerLastReadMessageID: readStateMessageID(customerReadState),
@@ -68,6 +73,26 @@ func BuildConversation(item *models.Conversation) response.ConversationResponse
return ret
}
func localizeConversationSummary(locale string, summary string) string {
if i18nx.NormalizeLocale(locale) != i18nx.LocaleEnUS {
return summary
}
switch {
case summary == "[图片]":
return "[Image]"
case strings.HasPrefix(summary, "[图片] "):
return "[Image] " + strings.TrimPrefix(summary, "[图片] ")
case summary == "[附件]":
return "[Attachment]"
case strings.HasPrefix(summary, "[附件] "):
return "[Attachment] " + strings.TrimPrefix(summary, "[附件] ")
case summary == "该消息已撤回":
return "This message was recalled."
default:
return summary
}
}
func BuildParticipantResponses(conversationID int64) []response.ConversationParticipantResponse {
list := services.ConversationParticipantService.Find(sqls.NewCnd().Eq("conversation_id", conversationID).Asc("id"))
if len(list) == 0 {
@@ -89,6 +114,10 @@ func BuildParticipantResponses(conversationID int64) []response.ConversationPart
}
func BuildMessages(list []models.Message) []response.MessageResponse {
return BuildMessagesWithLocale(list, i18nx.LocaleZhCN)
}
func BuildMessagesWithLocale(list []models.Message, locale string) []response.MessageResponse {
if len(list) == 0 {
return nil
}
@@ -97,17 +126,25 @@ func BuildMessages(list []models.Message) []response.MessageResponse {
agentProfiles := collectAgentProfilesByMessages(list)
ret := make([]response.MessageResponse, 0, len(list))
for i := range list {
ret = append(ret, BuildMessageWithReadStates(&list[i], agentReadState, customerReadState, aiSenderNames, userSenderNames, agentProfiles))
ret = append(ret, BuildMessageWithReadStatesAndLocale(&list[i], agentReadState, customerReadState, aiSenderNames, userSenderNames, agentProfiles, locale))
}
return ret
}
func BuildMessage(item *models.Message) response.MessageResponse {
return BuildMessageWithLocale(item, i18nx.LocaleZhCN)
}
func BuildMessageWithLocale(item *models.Message, locale string) response.MessageResponse {
agentReadState, customerReadState := services.ConversationReadStateService.GetConversationReadStates(item.ConversationID)
return BuildMessageWithReadStates(item, agentReadState, customerReadState, nil, nil, nil)
return BuildMessageWithReadStatesAndLocale(item, agentReadState, customerReadState, nil, nil, nil, locale)
}
func BuildMessageWithReadStates(item *models.Message, agentReadState, customerReadState *models.ConversationReadState, aiSenderNames, userSenderNames map[int64]string, agentProfiles map[int64]*models.AgentProfile) response.MessageResponse {
return BuildMessageWithReadStatesAndLocale(item, agentReadState, customerReadState, aiSenderNames, userSenderNames, agentProfiles, i18nx.LocaleZhCN)
}
func BuildMessageWithReadStatesAndLocale(item *models.Message, agentReadState, customerReadState *models.ConversationReadState, aiSenderNames, userSenderNames map[int64]string, agentProfiles map[int64]*models.AgentProfile, locale string) response.MessageResponse {
content, payload := utils.BuildRenderableMessage(item)
ret := response.MessageResponse{
ID: item.ID,
@@ -116,7 +153,7 @@ func BuildMessageWithReadStates(item *models.Message, agentReadState, customerRe
SenderType: item.SenderType,
SenderID: item.SenderID,
MessageType: item.MessageType,
Content: content,
Content: localizeRenderableMessageContent(locale, content),
Payload: payload,
SeqNo: item.SeqNo,
SendStatus: item.SendStatus,
@@ -169,6 +206,16 @@ func BuildMessageWithReadStates(item *models.Message, agentReadState, customerRe
return ret
}
func localizeRenderableMessageContent(locale string, content string) string {
if i18nx.NormalizeLocale(locale) != i18nx.LocaleEnUS {
return content
}
if content == "该消息已撤回" {
return "This message was recalled."
}
return content
}
func collectAgentProfilesByMessages(list []models.Message) map[int64]*models.AgentProfile {
var agentUserIDs []int64
seen := make(map[int64]struct{})
@@ -0,0 +1,99 @@
package builders
import (
"testing"
"cs-agent/internal/pkg/i18nx"
)
func TestLocalizeConversationSummary(t *testing.T) {
t.Parallel()
tests := []struct {
name string
locale string
summary string
want string
}{
{
name: "image summary in english",
locale: i18nx.LocaleEnUS,
summary: "[图片]",
want: "[Image]",
},
{
name: "attachment summary in english",
locale: i18nx.LocaleEnUS,
summary: "[附件] spec.pdf",
want: "[Attachment] spec.pdf",
},
{
name: "recalled message in english",
locale: i18nx.LocaleEnUS,
summary: "该消息已撤回",
want: "This message was recalled.",
},
{
name: "business text is not translated",
locale: i18nx.LocaleEnUS,
summary: "客户反馈无法登录",
want: "客户反馈无法登录",
},
{
name: "chinese locale keeps existing summary",
locale: i18nx.LocaleZhCN,
summary: "[图片]",
want: "[图片]",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := localizeConversationSummary(tt.locale, tt.summary); got != tt.want {
t.Fatalf("localizeConversationSummary() = %q, want %q", got, tt.want)
}
})
}
}
func TestLocalizeRenderableMessageContent(t *testing.T) {
t.Parallel()
tests := []struct {
name string
locale string
content string
want string
}{
{
name: "recalled message in english",
locale: i18nx.LocaleEnUS,
content: "该消息已撤回",
want: "This message was recalled.",
},
{
name: "normal customer message is not translated",
locale: i18nx.LocaleEnUS,
content: "客户反馈无法登录",
want: "客户反馈无法登录",
},
{
name: "chinese locale keeps content",
locale: i18nx.LocaleZhCN,
content: "该消息已撤回",
want: "该消息已撤回",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := localizeRenderableMessageContent(tt.locale, tt.content); got != tt.want {
t.Fatalf("localizeRenderableMessageContent() = %q, want %q", got, tt.want)
}
})
}
}
+96 -3
View File
@@ -3,18 +3,32 @@ package builders
import (
"cs-agent/internal/models"
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/pkg/i18nx"
"cs-agent/internal/pkg/utils"
"fmt"
"regexp"
"strings"
)
var (
ticketAssignedNotificationPattern = regexp.MustCompile(`^工单 (.+) 已指派给你$`)
conversationAssignedNotificationPattern = regexp.MustCompile(`^会话 #([0-9]+) 已分配给你$`)
)
func BuildNotification(item *models.Notification) *response.NotificationResponse {
return BuildNotificationWithLocale(item, i18nx.LocaleZhCN)
}
func BuildNotificationWithLocale(item *models.Notification, locale string) *response.NotificationResponse {
if item == nil {
return nil
}
title, content := localizeNotificationText(item, locale)
return &response.NotificationResponse{
ID: item.ID,
RecipientUserID: item.RecipientUserID,
Title: item.Title,
Content: item.Content,
Title: title,
Content: content,
NotificationType: item.NotificationType,
BizType: item.BizType,
BizID: item.BizID,
@@ -25,11 +39,90 @@ func BuildNotification(item *models.Notification) *response.NotificationResponse
}
func BuildNotificationList(list []models.Notification) []response.NotificationResponse {
return BuildNotificationListWithLocale(list, i18nx.LocaleZhCN)
}
func BuildNotificationListWithLocale(list []models.Notification, locale string) []response.NotificationResponse {
results := make([]response.NotificationResponse, 0, len(list))
for i := range list {
if item := BuildNotification(&list[i]); item != nil {
if item := BuildNotificationWithLocale(&list[i], locale); item != nil {
results = append(results, *item)
}
}
return results
}
func localizeNotificationText(item *models.Notification, locale string) (string, string) {
title := item.Title
content := item.Content
if i18nx.NormalizeLocale(locale) != i18nx.LocaleEnUS {
return title, content
}
switch strings.TrimSpace(item.NotificationType) {
case "ticket_assigned":
return localizeTicketAssignedNotification(title, content)
case "conversation_assigned":
return localizeConversationAssignedNotification(title, content)
default:
return title, content
}
}
func localizeTicketAssignedNotification(title string, content string) (string, string) {
lines := splitNotificationLines(content)
if len(lines) == 0 {
return localizeNotificationTitle(title), content
}
if matches := ticketAssignedNotificationPattern.FindStringSubmatch(lines[0]); len(matches) == 2 {
lines[0] = fmt.Sprintf("Ticket %s has been assigned to you.", matches[1])
}
for i, line := range lines[1:] {
if reason, ok := strings.CutPrefix(line, "指派原因: "); ok {
lines[i+1] = "Assignment reason: " + reason
}
}
return localizeNotificationTitle(title), strings.Join(lines, "\n")
}
func localizeConversationAssignedNotification(title string, content string) (string, string) {
lines := splitNotificationLines(content)
if len(lines) == 0 {
return localizeNotificationTitle(title), content
}
if matches := conversationAssignedNotificationPattern.FindStringSubmatch(lines[0]); len(matches) == 2 {
lines[0] = fmt.Sprintf("Conversation #%s has been assigned to you.", matches[1])
}
for i, line := range lines[1:] {
if reason, ok := strings.CutPrefix(line, "分配原因: "); ok {
lines[i+1] = "Assignment reason: " + reason
continue
}
if reason, ok := strings.CutPrefix(line, "转接原因: "); ok {
lines[i+1] = "Transfer reason: " + reason
}
}
return localizeNotificationTitle(title), strings.Join(lines, "\n")
}
func localizeNotificationTitle(title string) string {
switch strings.TrimSpace(title) {
case "工单指派提醒":
return "Ticket assigned"
case "会话转接提醒":
return "Conversation transferred"
case "会话自动分配提醒":
return "Conversation auto-assigned"
case "会话分配提醒":
return "Conversation assigned"
default:
return title
}
}
func splitNotificationLines(content string) []string {
normalized := strings.TrimSpace(content)
if normalized == "" {
return nil
}
return strings.Split(normalized, "\n")
}
@@ -4,6 +4,7 @@ import (
"testing"
"cs-agent/internal/models"
"cs-agent/internal/pkg/i18nx"
)
func TestBuildNotificationListReturnsEmptySlice(t *testing.T) {
@@ -16,3 +17,22 @@ func TestBuildNotificationListReturnsEmptySlice(t *testing.T) {
t.Fatalf("expected empty slice, got %d items", len(results))
}
}
func TestBuildNotificationLocalizesKnownSystemNotification(t *testing.T) {
result := BuildNotificationWithLocale(&models.Notification{
Title: "工单指派提醒",
Content: "工单 TK-100 已指派给你\n无法登录后台\n指派原因: 优先处理",
NotificationType: "ticket_assigned",
}, i18nx.LocaleEnUS)
if result == nil {
t.Fatalf("expected notification response")
}
if result.Title != "Ticket assigned" {
t.Fatalf("title = %q", result.Title)
}
wantContent := "Ticket TK-100 has been assigned to you.\n无法登录后台\nAssignment reason: 优先处理"
if result.Content != wantContent {
t.Fatalf("content = %q, want %q", result.Content, wantContent)
}
}