功能:新增聊天快捷回复与买家备注

This commit is contained in:
Christ committed 2026-08-20 23:24:08 +08:00
1 parent 3b67ab81ee
commit dab4fb54bf
49 files changed
+2349 -122

No files matched your search

+5
View File
@@ -233,6 +233,11 @@ type ChatPort interface {
ReportPlatformRead(context.Context, string, string, []map[string]any) error
ResolveSessionIdentity(context.Context, chatapp.Session) (chatapp.Session, error)
RefreshSessionIdentities(context.Context, string, []chatapp.Session) ([]chatapp.Session, error)
ListQuickReplies(context.Context, int64, string) ([]chatapp.QuickReply, error)
CreateQuickReply(context.Context, int64, string, string) (chatapp.QuickReply, error)
DeleteQuickReply(context.Context, int64, string, int64) error
GetBuyerNote(context.Context, int64, string, string) (chatapp.BuyerNote, error)
SaveBuyerNote(context.Context, int64, string, string, string) (chatapp.BuyerNote, error)
}
// UncertainNotificationsPort 定义通知不确定状态的查询能力。
@@ -67,6 +67,64 @@ func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
}
}
// canceledReadReportPort 在本地已读保存后取消浏览器请求,用于验证平台上报使用独立的短时 Context。
type canceledReadReportPort struct {
// contractChatPort 提供无关聊天能力的稳定测试实现。
contractChatPort
// cancel 在本地已读状态写入完成后模拟浏览器中止当前 HTTP 请求。
cancel context.CancelFunc
// reportContextCanceled 记录平台上报调用当刻是否已被取消,不能继承浏览器请求的取消状态。
reportContextCanceled bool
// reportContextHasDeadline 记录平台上报是否具有有界远端等待截止时间。
reportContextHasDeadline bool
}
// MarkRead 模拟本地未读状态已成功落库后浏览器立即中断连接。
func (port *canceledReadReportPort) MarkRead(context.Context, int64, string, string) error {
port.cancel()
return nil
}
// ReportPlatformRead 记录平台上报使用的 Context,不进行真实外部调用。
func (port *canceledReadReportPort) ReportPlatformRead(ctx context.Context, _ string, _ string, _ []map[string]any) error {
port.reportContextCanceled = ctx.Err() != nil
_, port.reportContextHasDeadline = ctx.Deadline()
return nil
}
// TestMarkChatReadKeepsPlatformReportAliveAfterClientCancellation 验证本地已读成功后,浏览器取消不会中断有界的平台已读回执。
func TestMarkChatReadKeepsPlatformReportAliveAfterClientCancellation(t *testing.T) {
// srv、cleanup 分别是聊天路由测试服务器和测试资源释放函数。
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// requestCtx 和 cancel 模拟浏览器请求生命周期;测试端口在本地已读完成后触发取消。
requestCtx, cancel := context.WithCancel(context.Background())
defer cancel()
// port 保存会记录平台回执 Context 的聊天应用替身。
port := &canceledReadReportPort{cancel: cancel}
srv.applications.chat = port
// handler 是替换聊天端口后的真实 HTTP Router。
handler := srv.Router()
// cookie 是通过真实认证流程取得的管理员会话。
cookie := loginHelper(t, handler)
// request 是带有一条有效平台消息标识的已读请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/chat/read", strings.NewReader(`{"account_id":"acc1","chat_id":"chat-read","message_ids":[{"messageId":"message.PNM"}]}`)).WithContext(requestCtx)
request.Header.Set("Content-Type", "application/json")
request.AddCookie(cookie)
// recorder 保存真实 handler 响应,已取消的浏览器请求不应使本地状态返回失败。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("已读请求状态=%d,响应=%s", recorder.Code, recorder.Body.String())
}
if port.reportContextCanceled {
t.Fatal("平台已读上报错误继承了浏览器取消")
}
if !port.reportContextHasDeadline {
t.Fatal("平台已读上报缺少独立超时限制")
}
}
// TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents 封装Test聊天WebSocketStreamsOnlyAuthenticated账号Events业务协调。
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
// srv、cleanup 用于本次流程后续判断的srv、cleanup
+12 -2
View File
@@ -29,6 +29,9 @@ type markChatReadRequest struct {
MessageIDs []map[string]any `json:"message_ids"`
}
// platformReadReportTimeout 限制平台已读回执的独立远端等待时间,浏览器断开不应取消该尽力上报。
const platformReadReportTimeout = 5 * time.Second
// mountChat 封装mount聊天业务协调。
func (s *Server) mountChat(r chi.Router) {
r.Get("/api/chat/sessions", s.listChatSessions)
@@ -326,9 +329,16 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
return
}
// reportCtx 和 reportCancel 为尽力上报提供独立的有界生命周期:本地已读提交成功后,浏览器中止请求不应取消平台回执。
reportCtx, reportCancel := context.WithTimeout(context.Background(), platformReadReportTimeout)
defer reportCancel()
// reportErr 表示平台已读上报失败;本地已读状态已成功保存,不能回滚。
if reportErr := s.chatApplication().ReportPlatformRead(r.Context(), input.AccountID, input.ChatID, input.MessageIDs); reportErr != nil {
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", reportErr)
if reportErr := s.chatApplication().ReportPlatformRead(reportCtx, input.AccountID, input.ChatID, input.MessageIDs); reportErr != nil {
if errors.Is(reportErr, context.Canceled) {
slog.Debug("上报闲鱼已读状态已取消", "account", input.AccountID, "chat_id", input.ChatID)
} else {
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", reportErr)
}
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
+188
View File
@@ -0,0 +1,188 @@
package server
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/auth"
)
// chatQuickReplyResponse 是账号级人工快捷回复的具名 HTTP 响应 DTO。
type chatQuickReplyResponse struct {
// ID 是快捷回复稳定标识,用于删除操作。
ID int64 `json:"id"`
// AccountID 是快捷回复所属账号标识。
AccountID string `json:"account_id"`
// Content 是发送到聊天会话的文本模板。
Content string `json:"content"`
// CreatedAt 是快捷回复创建的 Unix 秒时间戳。
CreatedAt int64 `json:"created_at"`
}
// chatQuickReplyListResponse 是快捷回复列表接口的具名响应 DTO。
type chatQuickReplyListResponse struct {
// QuickReplies 保存当前账号可用的人工快捷回复。
QuickReplies []chatQuickReplyResponse `json:"quick_replies"`
}
// chatQuickReplyCreateRequest 是创建账号级快捷回复的具名请求 DTO。
type chatQuickReplyCreateRequest struct {
// AccountID 是当前用户拥有的目标账号标识。
AccountID string `json:"account_id"`
// Content 是待保存的人工快捷回复正文。
Content string `json:"content"`
}
// chatBuyerNoteResponse 是按账号和买家 ID 隔离的完整备注响应 DTO。
type chatBuyerNoteResponse struct {
// AccountID 是备注所属账号标识。
AccountID string `json:"account_id"`
// BuyerID 是备注所属的平台买家标识。
BuyerID string `json:"buyer_id"`
// Content 是完整备注正文;空字符串代表未保存备注。
Content string `json:"content"`
// UpdatedAt 是最近保存时间;空备注保持零值。
UpdatedAt int64 `json:"updated_at"`
}
// chatBuyerNoteSaveRequest 是保存买家备注的具名请求 DTO。
type chatBuyerNoteSaveRequest struct {
// AccountID 是当前用户拥有的目标账号标识。
AccountID string `json:"account_id"`
// Content 是完整备注正文,空字符串表示清除备注。
Content string `json:"content"`
}
// listChatQuickReplies 查询当前账号可复用的人工快捷回复。
func (s *Server) listChatQuickReplies(w http.ResponseWriter, r *http.Request) {
// session 保存认证中间件写入的当前用户身份。
session := auth.SessionFromContext(r.Context())
// accountID 保存去除空白后的目标账号标识。
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
// replies 和 listErr 保存应用服务返回的快捷回复及查询错误。
replies, listErr := s.chatApplication().ListQuickReplies(r.Context(), session.UserID, accountID)
if listErr != nil {
writeChatMetadataError(w, listErr)
return
}
writeJSON(w, http.StatusOK, newChatQuickReplyListResponse(replies))
}
// createChatQuickReply 校验请求后为账号保存一条人工快捷回复。
func (s *Server) createChatQuickReply(w http.ResponseWriter, r *http.Request) {
// session 保存认证中间件写入的当前用户身份。
session := auth.SessionFromContext(r.Context())
// request 保存反序列化后的快捷回复创建参数。
var request chatQuickReplyCreateRequest
// decodeErr 保存快捷回复创建请求体反序列化失败原因。
if decodeErr := decodeJSON(r, &request); decodeErr != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// reply 和 createErr 保存创建后的快捷回复及应用层校验错误。
reply, createErr := s.chatApplication().CreateQuickReply(r.Context(), session.UserID, request.AccountID, request.Content)
if createErr != nil {
writeChatMetadataError(w, createErr)
return
}
writeJSON(w, http.StatusCreated, newChatQuickReplyResponse(reply))
}
// deleteChatQuickReply 删除当前账号下由路径标识的快捷回复。
func (s *Server) deleteChatQuickReply(w http.ResponseWriter, r *http.Request) {
// session 保存认证中间件写入的当前用户身份。
session := auth.SessionFromContext(r.Context())
// accountID 保存查询参数提供的快捷回复所属账号标识。
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
// quickReplyID 和 parseErr 保存路径快捷回复 ID 及解析错误。
quickReplyID, parseErr := strconv.ParseInt(chi.URLParam(r, "quick_reply_id"), 10, 64)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "快捷回复标识无效")
return
}
// deleteErr 保存删除快捷回复时应用服务返回的业务或持久化错误。
if deleteErr := s.chatApplication().DeleteQuickReply(r.Context(), session.UserID, accountID, quickReplyID); deleteErr != nil {
writeChatMetadataError(w, deleteErr)
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// getChatBuyerNote 返回当前账号下指定买家的完整备注;未保存时仍返回空备注。
func (s *Server) getChatBuyerNote(w http.ResponseWriter, r *http.Request) {
// session 保存认证中间件写入的当前用户身份。
session := auth.SessionFromContext(r.Context())
// accountID 和 buyerID 保存备注的账号与买家复合隔离键。
accountID, buyerID := strings.TrimSpace(r.URL.Query().Get("account_id")), strings.TrimSpace(chi.URLParam(r, "buyer_id"))
// note 和 readErr 保存应用层读取的备注及错误。
note, readErr := s.chatApplication().GetBuyerNote(r.Context(), session.UserID, accountID, buyerID)
if readErr != nil {
writeChatMetadataError(w, readErr)
return
}
writeJSON(w, http.StatusOK, newChatBuyerNoteResponse(note))
}
// saveChatBuyerNote 保存或清除当前账号下指定买家的备注。
func (s *Server) saveChatBuyerNote(w http.ResponseWriter, r *http.Request) {
// session 保存认证中间件写入的当前用户身份。
session := auth.SessionFromContext(r.Context())
// buyerID 保存路径提供的稳定平台买家标识。
buyerID := strings.TrimSpace(chi.URLParam(r, "buyer_id"))
// request 保存反序列化后的备注保存参数。
var request chatBuyerNoteSaveRequest
// decodeErr 保存买家备注保存请求体反序列化失败原因。
if decodeErr := decodeJSON(r, &request); decodeErr != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// note 和 saveErr 保存更新后的备注及应用层校验错误。
note, saveErr := s.chatApplication().SaveBuyerNote(r.Context(), session.UserID, request.AccountID, buyerID, request.Content)
if saveErr != nil {
writeChatMetadataError(w, saveErr)
return
}
writeJSON(w, http.StatusOK, newChatBuyerNoteResponse(note))
}
// newChatQuickReplyResponse 将应用层快捷回复转换为稳定 HTTP DTO。
func newChatQuickReplyResponse(reply chatapp.QuickReply) chatQuickReplyResponse {
return chatQuickReplyResponse{ID: reply.ID, AccountID: reply.AccountID, Content: reply.Content, CreatedAt: reply.CreatedAt}
}
// newChatQuickReplyListResponse 批量转换快捷回复,避免传输层序列化应用层模型。
func newChatQuickReplyListResponse(replies []chatapp.QuickReply) chatQuickReplyListResponse {
// response 保存将要返回给前端的具名列表 DTO。
response := chatQuickReplyListResponse{QuickReplies: make([]chatQuickReplyResponse, 0, len(replies))}
// reply 表示当前待转换的应用层快捷回复。
for _, reply := range replies {
response.QuickReplies = append(response.QuickReplies, newChatQuickReplyResponse(reply))
}
return response
}
// newChatBuyerNoteResponse 将应用层买家备注转换为稳定 HTTP DTO。
func newChatBuyerNoteResponse(note chatapp.BuyerNote) chatBuyerNoteResponse {
return chatBuyerNoteResponse{AccountID: note.AccountID, BuyerID: note.BuyerID, Content: note.Content, UpdatedAt: note.UpdatedAt}
}
// writeChatMetadataError 将聊天元数据用例错误映射到统一 HTTP 状态和错误 envelope。
func writeChatMetadataError(w http.ResponseWriter, operationErr error) {
switch {
case errors.Is(operationErr, chatapp.ErrInvalidInput):
writeErr(w, http.StatusBadRequest, "账号、买家或内容无效")
case errors.Is(operationErr, chatapp.ErrMetadataForbidden):
writeErr(w, http.StatusForbidden, "无权访问该账号")
case errors.Is(operationErr, chatapp.ErrQuickReplyLimitReached):
writeErrCode(w, http.StatusConflict, "chat_quick_reply_limit_reached", "快捷回复最多保存 50 条", "")
case errors.Is(operationErr, chatapp.ErrQuickReplyNotFound):
writeErr(w, http.StatusNotFound, "快捷回复不存在")
default:
writeErr(w, http.StatusInternalServerError, "聊天数据操作失败")
}
}
@@ -32,6 +32,7 @@ func TestOpenAPIRemainingVersionedSuccessResponses(t *testing.T) {
t.Run("ai-models", testOpenAPIAIModelsSuccess)
t.Run("cards-batch", testOpenAPICardsBatchSuccess)
t.Run("chat-history-and-read", testOpenAPIChatHistoryAndReadSuccess)
t.Run("chat-metadata", testOpenAPIChatMetadataSuccess)
t.Run("local-item-and-manual-ship", testOpenAPILocalItemAndManualShipSuccess)
t.Run("category-recommendation", testOpenAPIItemCategoryRecommendationSuccess)
t.Run("publish-batch-preview", testOpenAPIPublishBatchPreviewSuccess)
@@ -228,6 +229,59 @@ func testOpenAPIChatHistoryAndReadSuccess(t *testing.T) {
assertOpenAPIRecordedSuccessResponse(t, deleteRequest, deleteRecorder)
}
// testOpenAPIChatMetadataSuccess 覆盖快捷回复和按买家 ID 隔离备注的所有版本化成功响应。
func testOpenAPIChatMetadataSuccess(t *testing.T) {
// srv、_、cleanup 分别是装配真实聊天元数据用例的服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// handler 是当前场景使用的真实版本化 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// createRequest 是创建账号快捷回复的版本化请求。
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/quick-replies", strings.NewReader(`{"account_id":"acc1","content":"契约快捷回复"}`))
createRequest.Header.Set("Content-Type", "application/json")
createRequest.AddCookie(sessionCookie)
// createRecorder 保存快捷回复创建响应。
createRecorder := httptest.NewRecorder()
handler.ServeHTTP(createRecorder, createRequest)
assertOpenAPIRecordedSuccessResponse(t, createRequest, createRecorder)
// created 保存创建成功响应中的快捷回复标识,供删除操作精确定位。
var created chatQuickReplyResponse
// decodeErr 保存解析快捷回复创建响应以取得删除标识时的失败原因。
if decodeErr := json.Unmarshal(createRecorder.Body.Bytes(), &created); decodeErr != nil {
t.Fatalf("解析快捷回复创建响应失败: %v", decodeErr)
}
// listRequest 是读取账号快捷回复列表的版本化请求。
listRequest := httptest.NewRequest(http.MethodGet, "/api/v1/chat/quick-replies?account_id=acc1", nil)
listRequest.AddCookie(sessionCookie)
// listRecorder 保存快捷回复列表响应。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listRequest)
assertOpenAPIRecordedSuccessResponse(t, listRequest, listRecorder)
// noteRequests 保存买家备注读取和保存的版本化请求。
noteRequests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/chat/buyer-notes/buyer-contract?account_id=acc1", nil),
httptest.NewRequest(http.MethodPut, "/api/v1/chat/buyer-notes/buyer-contract", strings.NewReader(`{"account_id":"acc1","content":"契约买家备注"}`)),
}
// noteRequest 表示当前待验证的买家备注 HTTP 请求。
for _, noteRequest := range noteRequests {
noteRequest.Header.Set("Content-Type", "application/json")
noteRequest.AddCookie(sessionCookie)
// noteRecorder 保存当前买家备注成功响应。
noteRecorder := httptest.NewRecorder()
handler.ServeHTTP(noteRecorder, noteRequest)
assertOpenAPIRecordedSuccessResponse(t, noteRequest, noteRecorder)
}
// deleteRequest 是删除刚创建快捷回复的版本化请求。
deleteRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/chat/quick-replies/"+strconv.FormatInt(created.ID, 10)+"?account_id=acc1", nil)
deleteRequest.AddCookie(sessionCookie)
// deleteRecorder 保存快捷回复删除响应。
deleteRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteRecorder, deleteRequest)
assertOpenAPIRecordedSuccessResponse(t, deleteRequest, deleteRecorder)
}
// testOpenAPILocalItemAndManualShipSuccess 覆盖无需平台请求的商品创建和状态型手动发货成功响应。
func testOpenAPILocalItemAndManualShipSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、订单夹具存储和资源释放函数。
@@ -737,6 +791,29 @@ func (contractChatPort) RefreshSessionIdentities(context.Context, string, []chat
return nil, nil
}
// ListQuickReplies 返回确定性的空快捷回复集合,供只验证消息发送契约的测试端口满足完整接口。
func (contractChatPort) ListQuickReplies(context.Context, int64, string) ([]chatapp.QuickReply, error) {
return []chatapp.QuickReply{}, nil
}
// CreateQuickReply 返回确定性的测试快捷回复,避免该端口在未来契约场景中依赖数据库。
func (contractChatPort) CreateQuickReply(context.Context, int64, string, string) (chatapp.QuickReply, error) {
return chatapp.QuickReply{ID: 1, AccountID: "acc1", Content: "测试快捷回复", CreatedAt: 1}, nil
}
// DeleteQuickReply 保持确定性成功,用于满足聊天 HTTP 应用端口。
func (contractChatPort) DeleteQuickReply(context.Context, int64, string, int64) error { return nil }
// GetBuyerNote 返回逻辑空备注,避免发送契约测试依赖真实备注持久化。
func (contractChatPort) GetBuyerNote(context.Context, int64, string, string) (chatapp.BuyerNote, error) {
return chatapp.BuyerNote{}, nil
}
// SaveBuyerNote 返回逻辑空备注,避免发送契约测试依赖真实备注持久化。
func (contractChatPort) SaveBuyerNote(context.Context, int64, string, string, string) (chatapp.BuyerNote, error) {
return chatapp.BuyerNote{}, nil
}
// contractItemPublishPort 是只返回确定性商品结果的单商品发布端口。
type contractItemPublishPort struct{}
@@ -18,6 +18,11 @@ func (s *Server) mountVersionedChatTaskRoutes(r chi.Router) {
r.Post("/api/v1/chat/images", s.sendChatImage)
r.Post("/api/v1/chat/read", s.markChatRead)
r.Get("/api/v1/chat/ws", s.chatWebSocket)
r.Get("/api/v1/chat/quick-replies", s.listChatQuickReplies)
r.Post("/api/v1/chat/quick-replies", s.createChatQuickReply)
r.Delete("/api/v1/chat/quick-replies/{quick_reply_id}", s.deleteChatQuickReply)
r.Get("/api/v1/chat/buyer-notes/{buyer_id}", s.getChatBuyerNote)
r.Put("/api/v1/chat/buyer-notes/{buyer_id}", s.saveChatBuyerNote)
r.Get("/api/v1/account-tasks/{cid}", s.getAccountTaskSettings)
r.Put("/api/v1/account-tasks/{cid}", s.updateAccountTaskSettings)