diff --git a/.commentlint/go-baseline.json b/.commentlint/go-baseline.json index 888e5fa..d805d9c 100644 --- a/.commentlint/go-baseline.json +++ b/.commentlint/go-baseline.json @@ -59407,121 +59407,121 @@ }, { "file": "internal/server/account_task_handlers.go", - "line": 14, + "line": 15, "kind": "var", "name": "accountTaskTimePattern" }, { "file": "internal/server/account_task_handlers.go", - "line": 16, + "line": 17, "kind": "function", "name": "mountAccountTasks" }, { "file": "internal/server/account_task_handlers.go", - "line": 23, + "line": 24, "kind": "function", "name": "getAccountTaskSettings" }, { "file": "internal/server/account_task_handlers.go", - "line": 24, + "line": 25, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/account_task_handlers.go", - "line": 29, + "line": 30, "kind": "local-variable", "name": "err" }, { "file": "internal/server/account_task_handlers.go", - "line": 29, + "line": 30, "kind": "local-variable", "name": "settings" }, { "file": "internal/server/account_task_handlers.go", - "line": 37, + "line": 38, "kind": "function", "name": "updateAccountTaskSettings" }, { "file": "internal/server/account_task_handlers.go", - "line": 38, + "line": 39, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/account_task_handlers.go", - "line": 43, + "line": 44, "kind": "var", "name": "input" }, { "file": "internal/server/account_task_handlers.go", - "line": 62, + "line": 49, "kind": "local-variable", "name": "err" }, { "file": "internal/server/account_task_handlers.go", - "line": 66, + "line": 49, "kind": "local-variable", "name": "stored" }, { "file": "internal/server/account_task_handlers.go", - "line": 70, + "line": 61, "kind": "function", "name": "listAccountTaskRuns" }, { "file": "internal/server/account_task_handlers.go", - "line": 71, + "line": 62, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/account_task_handlers.go", - "line": 76, + "line": 67, "kind": "local-variable", "name": "err" }, { "file": "internal/server/account_task_handlers.go", - "line": 76, + "line": 67, "kind": "local-variable", "name": "runs" }, { "file": "internal/server/account_task_handlers.go", - "line": 84, + "line": 75, "kind": "function", "name": "runAccountTask" }, { "file": "internal/server/account_task_handlers.go", - "line": 85, + "line": 76, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/account_task_handlers.go", - "line": 94, + "line": 81, "kind": "var", "name": "input" }, { "file": "internal/server/account_task_handlers.go", - "line": 101, + "line": 88, "kind": "local-variable", "name": "err" }, { "file": "internal/server/account_task_handlers.go", - "line": 101, + "line": 88, "kind": "local-variable", "name": "summary" }, @@ -64611,521 +64611,383 @@ "file": "internal/server/chat_handlers.go", "line": 174, "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 174, - "kind": "local-variable", - "name": "sender" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 179, - "kind": "local-variable", - "name": "cookies" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 179, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 184, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 184, - "kind": "local-variable", - "name": "uploader" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 191, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 191, - "kind": "local-variable", - "name": "upload" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 200, - "kind": "local-variable", "name": "session" }, { "file": "internal/server/chat_handlers.go", - "line": 203, + "line": 177, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 203, - "kind": "local-variable", - "name": "message" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 208, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 209, - "kind": "local-variable", - "name": "failed" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 213, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 213, + "line": 177, "kind": "local-variable", "name": "sent" }, { "file": "internal/server/chat_handlers.go", - "line": 221, + "line": 195, "kind": "function", "name": "listChatMessages" }, { "file": "internal/server/chat_handlers.go", - "line": 222, + "line": 196, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/chat_handlers.go", - "line": 223, + "line": 197, "kind": "local-variable", "name": "accountID" }, { "file": "internal/server/chat_handlers.go", - "line": 224, + "line": 198, "kind": "local-variable", "name": "chatID" }, { "file": "internal/server/chat_handlers.go", - "line": 233, + "line": 207, "kind": "local-variable", "name": "beforeID" }, { "file": "internal/server/chat_handlers.go", - "line": 234, + "line": 208, "kind": "local-variable", "name": "cursor" }, { "file": "internal/server/chat_handlers.go", - "line": 235, + "line": 209, "kind": "local-variable", "name": "limit" }, { "file": "internal/server/chat_handlers.go", - "line": 237, + "line": 211, "kind": "local-variable", "name": "ok" }, { "file": "internal/server/chat_handlers.go", - "line": 237, + "line": 211, "kind": "local-variable", "name": "sender" }, { "file": "internal/server/chat_handlers.go", - "line": 238, + "line": 212, "kind": "local-variable", "name": "fetcher" }, { "file": "internal/server/chat_handlers.go", - "line": 238, + "line": 212, "kind": "local-variable", "name": "ok" }, { "file": "internal/server/chat_handlers.go", - "line": 241, + "line": 215, "kind": "local-variable", "name": "cancel" }, { "file": "internal/server/chat_handlers.go", - "line": 241, + "line": 215, "kind": "local-variable", "name": "fetchCtx" }, { "file": "internal/server/chat_handlers.go", - "line": 242, + "line": 216, "kind": "local-variable", "name": "body" }, { "file": "internal/server/chat_handlers.go", - "line": 242, + "line": 216, "kind": "local-variable", "name": "fetchErr" }, { "file": "internal/server/chat_handlers.go", - "line": 242, + "line": 216, "kind": "local-variable", "name": "myID" }, { "file": "internal/server/chat_handlers.go", - "line": 245, + "line": 219, "kind": "local-variable", "name": "sessions" }, { "file": "internal/server/chat_handlers.go", - "line": 246, + "line": 220, "kind": "var", "name": "current" }, { "file": "internal/server/chat_handlers.go", - "line": 247, + "line": 221, "kind": "range-variable", "name": "candidate" }, { "file": "internal/server/chat_handlers.go", - "line": 253, + "line": 227, "kind": "local-variable", "name": "page" }, { "file": "internal/server/chat_handlers.go", - "line": 253, + "line": 227, "kind": "local-variable", "name": "saveErr" }, { "file": "internal/server/chat_handlers.go", - "line": 265, + "line": 239, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 265, + "line": 239, "kind": "local-variable", - "name": "rows" + "name": "page" }, { "file": "internal/server/chat_handlers.go", - "line": 271, - "kind": "var", - "name": "current" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 272, - "kind": "local-variable", - "name": "sessionErr" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 272, - "kind": "local-variable", - "name": "sessions" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 273, - "kind": "range-variable", - "name": "candidate" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 283, + "line": 247, "kind": "function", "name": "resolveSelectedChatIdentity" }, { "file": "internal/server/chat_handlers.go", - "line": 285, + "line": 249, "kind": "local-variable", "name": "cookieErr" }, { "file": "internal/server/chat_handlers.go", - "line": 285, + "line": 249, "kind": "local-variable", "name": "cookies" }, { "file": "internal/server/chat_handlers.go", - "line": 286, + "line": 250, "kind": "local-variable", "name": "client" }, { "file": "internal/server/chat_handlers.go", - "line": 286, + "line": 250, "kind": "local-variable", "name": "supported" }, { "file": "internal/server/chat_handlers.go", - "line": 290, + "line": 254, "kind": "local-variable", "name": "cancel" }, { "file": "internal/server/chat_handlers.go", - "line": 290, + "line": 254, "kind": "local-variable", "name": "resolveCtx" }, { "file": "internal/server/chat_handlers.go", - "line": 291, + "line": 255, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 291, + "line": 255, "kind": "local-variable", "name": "info" }, { "file": "internal/server/chat_handlers.go", - "line": 294, + "line": 258, "kind": "local-variable", "name": "nickname" }, { "file": "internal/server/chat_handlers.go", - "line": 309, + "line": 273, "kind": "type", "name": "sendChatMessageRequest" }, { "file": "internal/server/chat_handlers.go", - "line": 319, + "line": 283, "kind": "function", "name": "sendChatMessage" }, { "file": "internal/server/chat_handlers.go", - "line": 324, + "line": 288, "kind": "var", "name": "input" }, { "file": "internal/server/chat_handlers.go", - "line": 325, + "line": 289, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 343, - "kind": "local-variable", - "name": "ok" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 343, - "kind": "local-variable", - "name": "sender" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 348, + "line": 307, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 348, - "kind": "local-variable", - "name": "message" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 354, - "kind": "local-variable", - "name": "sendContext" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 355, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 356, - "kind": "local-variable", - "name": "failed" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 360, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/chat_handlers.go", - "line": 360, + "line": 307, "kind": "local-variable", "name": "sent" }, { "file": "internal/server/chat_handlers.go", - "line": 368, + "line": 325, "kind": "function", "name": "markChatRead" }, { "file": "internal/server/chat_handlers.go", - "line": 369, + "line": 326, "kind": "var", "name": "input" }, { "file": "internal/server/chat_handlers.go", - "line": 381, + "line": 338, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/chat_handlers.go", - "line": 382, + "line": 339, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 389, + "line": 346, "kind": "function", "name": "chatWebSocket" }, { "file": "internal/server/chat_handlers.go", - "line": 394, + "line": 351, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/chat_handlers.go", - "line": 395, + "line": 352, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 395, + "line": 352, "kind": "local-variable", "name": "events" }, { "file": "internal/server/chat_handlers.go", - "line": 395, + "line": 352, "kind": "local-variable", "name": "unsubscribe" }, { "file": "internal/server/chat_handlers.go", - "line": 401, + "line": 358, "kind": "local-variable", "name": "conn" }, { "file": "internal/server/chat_handlers.go", - "line": 401, + "line": 358, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 406, + "line": 363, "kind": "local-variable", "name": "cancel" }, { "file": "internal/server/chat_handlers.go", - "line": 406, + "line": 363, "kind": "local-variable", "name": "ctx" }, { "file": "internal/server/chat_handlers.go", - "line": 411, + "line": 368, "kind": "local-variable", "name": "readErr" }, { "file": "internal/server/chat_handlers.go", - "line": 417, + "line": 374, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 424, + "line": 381, "kind": "local-variable", "name": "event" }, { "file": "internal/server/chat_handlers.go", - "line": 424, + "line": 381, "kind": "local-variable", "name": "ok" }, { "file": "internal/server/chat_handlers.go", - "line": 432, + "line": 389, "kind": "function", "name": "ownsAccount" }, { "file": "internal/server/chat_handlers.go", - "line": 436, + "line": 393, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/chat_handlers.go", - "line": 445, + "line": 402, "kind": "function", "name": "parsePositiveInt" }, { "file": "internal/server/chat_handlers.go", - "line": 446, + "line": 403, "kind": "local-variable", "name": "err" }, { "file": "internal/server/chat_handlers.go", - "line": 446, + "line": 403, "kind": "local-variable", "name": "value" }, @@ -77005,13 +76867,13 @@ }, { "file": "internal/server/notification_handlers.go", - "line": 150, + "line": 146, "kind": "local-variable", "name": "body" }, { "file": "internal/server/notification_handlers.go", - "line": 152, + "line": 148, "kind": "local-variable", "name": "err" }, @@ -77065,145 +76927,121 @@ }, { "file": "internal/server/notification_handlers.go", - "line": 186, + "line": 179, "kind": "local-variable", "name": "out" }, { "file": "internal/server/notification_handlers.go", - "line": 188, - "kind": "var", - "name": "channelID" + "line": 180, + "kind": "range-variable", + "name": "bindings" }, { "file": "internal/server/notification_handlers.go", - "line": 188, - "kind": "var", - "name": "id" - }, - { - "file": "internal/server/notification_handlers.go", - "line": 189, - "kind": "var", - "name": "channelName" - }, - { - "file": "internal/server/notification_handlers.go", - "line": 189, - "kind": "var", + "line": 180, + "kind": "range-variable", "name": "cookieID" }, { "file": "internal/server/notification_handlers.go", - "line": 190, - "kind": "var", - "name": "enabled" + "line": 181, + "kind": "range-variable", + "name": "binding" }, { "file": "internal/server/notification_handlers.go", - "line": 191, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/notification_handlers.go", - "line": 202, - "kind": "local-variable", - "name": "err" - }, - { - "file": "internal/server/notification_handlers.go", - "line": 209, + "line": 188, "kind": "function", "name": "setAccountBindings" }, { "file": "internal/server/notification_handlers.go", - "line": 210, + "line": 189, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/notification_handlers.go", - "line": 214, + "line": 193, "kind": "var", "name": "req" }, { "file": "internal/server/notification_handlers.go", - "line": 219, + "line": 198, "kind": "local-variable", "name": "err" }, { "file": "internal/server/notification_handlers.go", - "line": 227, + "line": 206, "kind": "local-variable", "name": "enabled" }, { "file": "internal/server/notification_handlers.go", - "line": 231, + "line": 210, "kind": "local-variable", "name": "err" }, { "file": "internal/server/notification_handlers.go", - "line": 245, + "line": 218, "kind": "range-variable", "name": "channelID" }, { "file": "internal/server/notification_handlers.go", - "line": 250, + "line": 223, "kind": "local-variable", "name": "err" }, { "file": "internal/server/notification_handlers.go", - "line": 257, + "line": 230, "kind": "function", "name": "deleteMessageNotification" }, { "file": "internal/server/notification_handlers.go", - "line": 258, + "line": 231, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/notification_handlers.go", - "line": 259, + "line": 232, "kind": "local-variable", "name": "err" }, { "file": "internal/server/notification_handlers.go", - "line": 259, + "line": 232, "kind": "local-variable", "name": "id" }, { "file": "internal/server/notification_handlers.go", - "line": 275, + "line": 245, "kind": "function", "name": "deleteAccountNotifications" }, { "file": "internal/server/notification_handlers.go", - "line": 276, + "line": 246, "kind": "local-variable", "name": "sess" }, { "file": "internal/server/notification_handlers.go", - "line": 277, + "line": 247, "kind": "local-variable", "name": "cid" }, { "file": "internal/server/notification_handlers.go", - "line": 278, + "line": 248, "kind": "local-variable", "name": "err" }, diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 58315e3..aa9281f 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -157,7 +157,8 @@ app shell / routes - 已完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口”:订单列表状态/图片映射、详情商品补全、单订单刷新和批量刷新响应均由应用服务返回稳定视图;更新校验改用业务错误分类,HTTP 层不再依赖错误文本判断状态码;旧/版本化入口契约测试和全量门禁通过; - 已完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取”:新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;HTTP 层仅保留请求解析、鉴权和契约映射,保留 worker、锁、cancel map、租约和远端发布顺序;新增服务层直接调用测试并通过全量门禁,合并为一个可回滚提交; - 已完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取”:新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;HTTP handler 仅保留请求解析、所有权校验和契约映射,保留扫码会话锁与账号凭证锁不变量;新增服务层测试并通过全量门禁,合并为一个可回滚提交; -- 阶段 4 下一 PR 切片为“聊天与通知应用服务边界提取”:围绕聊天消息发送、账号任务事件、通知渠道绑定、消息读取和发送失败重试提取不依赖 `net/http` 的应用服务,保持 WebSocket、通知 outbox 和事件幂等不变量,不拆分单个 handler 提交; +- 已完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取”:新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试并通过全量门禁,合并为一个可回滚提交; +- 阶段 4 下一 PR 切片为“Server 事务与生命周期边界收口”:围绕跨 repository 操作、应用服务装配、worker 启停和 handler 直接依赖清理建立明确 Unit of Work 与生命周期入口,不拆分单个 handler 提交; - 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 ## 6. 阶段 0:治理文档与强约束 @@ -564,3 +565,4 @@ npm --prefix frontend run build | 2026-08-14 | 完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口” | 列表/详情/刷新响应视图由应用服务统一生成;错误分类模型替代 HTTP handler 中的错误文本判断;旧/版本化订单契约、全量测试、race、vet、lint、注释和 diff 门禁通过,合并为一个可回滚提交 | 阶段 4:商品发布应用服务边界提取 | | 2026-08-14 | 完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取” | 新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;保留 worker、凭证锁、cancel map、租约、远端发布与自动化规则时序;新增服务层测试,Go 全量测试、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:账号登录应用服务边界提取 | | 2026-08-14 | 完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取” | 新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;保留扫码会话锁、账号凭证锁和旧/版本化 HTTP 契约;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:聊天与通知应用服务边界提取 | +| 2026-08-14 | 完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取” | 新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 事务与生命周期边界收口 | diff --git a/internal/server/account_task_handlers.go b/internal/server/account_task_handlers.go index 8451338..0bc84eb 100644 --- a/internal/server/account_task_handlers.go +++ b/internal/server/account_task_handlers.go @@ -1,6 +1,7 @@ package server import ( + "errors" "net/http" "regexp" "strings" @@ -26,7 +27,7 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusForbidden, "无权访问该账号") return } - settings, err := s.Store.AccountTasks.Get(r.Context(), cid) + settings, err := s.communicationApplication().GetAccountTaskSettings(r.Context(), cid) if err != nil { writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败") return @@ -45,25 +46,15 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques writeErr(w, http.StatusBadRequest, "请求格式错误") return } - input.CookieID = cid - input.RateContent = strings.TrimSpace(input.RateContent) - if input.AutoRateEnabled && input.RateContent == "" { - writeErr(w, http.StatusBadRequest, "启用自动评价时评价内容不能为空") + stored, err := s.communicationApplication().UpdateAccountTaskSettings(r.Context(), accountTaskUpdateInput{CookieID: cid, Settings: input}) + if err != nil { + if strings.Contains(err.Error(), "不能为空") || strings.Contains(err.Error(), "不能超过") || strings.Contains(err.Error(), "格式必须") { + writeErr(w, http.StatusBadRequest, err.Error()) + } else { + writeErr(w, http.StatusInternalServerError, "保存账号任务配置失败") + } return } - if len([]rune(input.RateContent)) > 500 { - writeErr(w, http.StatusBadRequest, "评价内容不能超过 500 个字符") - return - } - if !accountTaskTimePattern.MatchString(input.PolishTime) { - writeErr(w, http.StatusBadRequest, "擦亮时间格式必须为 HH:mm") - return - } - if err := s.Store.AccountTasks.Upsert(r.Context(), input); err != nil { - writeErr(w, http.StatusInternalServerError, "保存账号任务配置失败") - return - } - stored, _ := s.Store.AccountTasks.Get(r.Context(), cid) writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(stored)) } @@ -73,7 +64,7 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权访问该账号") return } - runs, err := s.Store.AccountTasks.RecentRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20)) + runs, err := s.communicationApplication().ListAccountTaskRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20)) if err != nil { writeErr(w, http.StatusInternalServerError, "读取任务记录失败") return @@ -87,10 +78,6 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权操作该账号") return } - if s.automation == nil { - writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用") - return - } var input struct { TaskType string `json:"task_type"` } @@ -98,8 +85,12 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "不支持的任务类型") return } - summary, err := s.automation.RunAccountTask(r.Context(), cid, input.TaskType) + summary, err := s.communicationApplication().RunAccountTask(r.Context(), cid, input.TaskType) if err != nil { + if errors.Is(err, errCommunicationUnavailable) { + writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用") + return + } writeErr(w, http.StatusBadGateway, err.Error()) return } diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index f08f153..bc6e16d 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "io" "net/http" "strconv" @@ -15,7 +16,6 @@ import ( "xianyu-go/internal/auth" "xianyu-go/internal/db" - "xianyu-go/internal/engine" "xianyu-go/internal/xianyu/mtop" ) @@ -171,48 +171,22 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB") return } - sender, ok := s.Manager.GetInstance(accountID) - if !ok || sender == nil { - writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片") - return - } - cookies, err := s.Store.Cookies.GetValue(r.Context(), accountID) - if err != nil { - writeErr(w, http.StatusInternalServerError, "读取账号凭证失败") - return - } - uploader, ok := s.mtopClient().(interface { - UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) - }) - if !ok { - writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用") - return - } - upload, err := uploader.UploadChatImage(r.Context(), cookies, header.Filename, contentType, data) - if err != nil { - writeErr(w, http.StatusBadGateway, "图片上传到闲鱼失败: "+err.Error()) - return - } - if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies { - _ = s.Store.Cookies.UpdateValueExisting(r.Context(), accountID, upload.UpdatedCookies) - sender.UpdateCookie(upload.UpdatedCookies) - } session := db.ChatSession{CookieID: accountID, ChatID: chatID, BuyerID: buyerID, BuyerName: r.FormValue("buyer_name"), BuyerAvatar: r.FormValue("buyer_avatar_url"), ItemID: r.FormValue("item_id"), ItemTitle: r.FormValue("item_title")} - message, err := s.chat.CreateOutgoingMedia(r.Context(), session, "image", upload.URL) + sent, err := s.communicationApplication().SendChatImage(r.Context(), chatImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data}) if err != nil { - writeErr(w, http.StatusInternalServerError, "保存待发送图片失败") - return - } - if err := sender.SendImage(engine.WithOutgoingMessageKey(r.Context(), message.MessageKey), chatID, buyerID, upload.URL, 0); err != nil { - failed, _ := s.chat.SetOutgoingStatus(context.Background(), accountID, message.MessageKey, "failed") - writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": failed}) - return - } - sent, err := s.chat.SetOutgoingStatus(r.Context(), accountID, message.MessageKey, "sent") - if err != nil { - writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败") + if errors.Is(err, errCommunicationUnavailable) { + writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用") + } else if errors.Is(err, errChatOffline) { + writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片") + } else if errors.Is(err, errChatSend) { + writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": sent}) + } else if errors.Is(err, errChatStatusSave) { + writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败") + } else { + writeErr(w, http.StatusInternalServerError, "保存待发送图片失败") + } return } writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)}) @@ -262,22 +236,12 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { } } } - rows, err := s.Store.Chats.ListMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, - limit) + page, err := s.communicationApplication().ListStoredChatMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit) if err != nil { writeErr(w, http.StatusInternalServerError, "读取聊天消息失败") return } - var current db.ChatSession - if sessions, sessionErr := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500); sessionErr == nil { - for _, candidate := range sessions { - if candidate.ChatID == chatID { - current = s.resolveSelectedChatIdentity(r.Context(), accountID, candidate) - break - } - } - } - writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(rows), HasMore: len(rows) == limit, Session: newChatSessionDTO(current)}) + writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(page.Session)}) } func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession { @@ -340,26 +304,19 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符") return } - sender, ok := s.Manager.GetInstance(input.AccountID) - if !ok || sender == nil { - writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息") - return - } - message, err := s.chat.CreateOutgoing(r.Context(), db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID, - BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, input.Text) + sent, err := s.communicationApplication().SendChatText(r.Context(), chatTextInput{Session: db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID, BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, Text: input.Text}) if err != nil { - writeErr(w, http.StatusInternalServerError, "保存待发送消息失败") - return - } - sendContext := engine.WithOutgoingMessageKey(r.Context(), message.MessageKey) - if err := sender.SendText(sendContext, input.ChatID, input.BuyerID, input.Text); err != nil { - failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.AccountID, message.MessageKey, "failed") - writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": failed}) - return - } - sent, err := s.chat.SetOutgoingStatus(r.Context(), input.AccountID, message.MessageKey, "sent") - if err != nil { - writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败") + if errors.Is(err, errCommunicationUnavailable) { + writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") + } else if errors.Is(err, errChatOffline) { + writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息") + } else if errors.Is(err, errChatSend) { + writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": sent}) + } else if errors.Is(err, errChatStatusSave) { + writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败") + } else { + writeErr(w, http.StatusInternalServerError, "保存待发送消息失败") + } return } writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)}) @@ -379,7 +336,7 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { return } sess := auth.SessionFromContext(r.Context()) - if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { + if err := s.communicationApplication().MarkChatRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { writeErr(w, http.StatusInternalServerError, "更新已读状态失败") return } diff --git a/internal/server/communication_service.go b/internal/server/communication_service.go new file mode 100644 index 0000000..61cc264 --- /dev/null +++ b/internal/server/communication_service.go @@ -0,0 +1,360 @@ +package server + +import ( + "context" + "errors" + "fmt" + "strings" + + "xianyu-go/internal/automation" + "xianyu-go/internal/db" + "xianyu-go/internal/engine" + "xianyu-go/internal/xianyu/mtop" +) + +var ( + // errCommunicationUnavailable 表示聊天或自动化依赖尚未初始化。 + errCommunicationUnavailable = errors.New("通信服务未启用") + // errChatOffline 表示目标账号当前没有在线运行实例。 + errChatOffline = errors.New("账号当前离线") + // errChatSend 表示远端聊天消息发送失败。 + errChatSend = errors.New("聊天消息发送失败") + // errChatStatusSave 表示远端消息已发送但本地状态保存失败。 + errChatStatusSave = errors.New("聊天发送状态保存失败") +) + +// communicationService 是聊天、账号任务和通知应用服务。 +type communicationService struct { + // server 提供数据库、聊天事件中心、账号运行时和通知器依赖。 + server *Server +} + +// accountTaskUpdateInput 是账号任务设置更新的业务输入。 +type accountTaskUpdateInput struct { + // CookieID 是账号标识。 + CookieID string + // Settings 是待保存的任务设置。 + Settings db.AccountTaskSettings +} + +// chatTextInput 是发送文字消息的业务输入。 +type chatTextInput struct { + // Session 是聊天会话及买家信息。 + Session db.ChatSession + // Text 是待发送的文字内容。 + Text string +} + +// chatImageInput 是发送图片消息的业务输入。 +type chatImageInput struct { + // Session 是聊天会话及买家信息。 + Session db.ChatSession + // Filename 是上传图片文件名。 + Filename string + // ContentType 是图片 MIME 类型。 + ContentType string + // Data 是图片二进制内容。 + Data []byte +} + +// chatMessagePageResult 是聊天历史查询结果,不依赖 HTTP DTO。 +type chatMessagePageResult struct { + // Messages 是本地或远端保存的聊天消息。 + Messages []db.ChatMessage + // Session 是当前聊天会话摘要。 + Session db.ChatSession + // HasMore 表示是否还有更早消息。 + HasMore bool + // NextCursor 是远端历史分页游标。 + NextCursor int64 +} + +// notificationBindingRow 是通知绑定列表的一行业务数据。 +type notificationBindingRow struct { + // ID 是绑定记录标识。 + ID int64 + // CookieID 是绑定账号标识。 + CookieID string + // ChannelID 是通知渠道标识。 + ChannelID int64 + // ChannelName 是通知渠道名称。 + ChannelName string + // Enabled 表示绑定是否启用。 + Enabled bool +} + +// communicationApplication 返回当前 Server 绑定的通信应用服务。 +func (s *Server) communicationApplication() *communicationService { + return &communicationService{server: s} +} + +// GetAccountTaskSettings 读取指定账号的任务设置。 +func (svc *communicationService) GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) { + return svc.server.Store.AccountTasks.Get(ctx, cookieID) +} + +// UpdateAccountTaskSettings 校验并保存账号任务设置,然后返回数据库中的最终值。 +func (svc *communicationService) UpdateAccountTaskSettings(ctx context.Context, input accountTaskUpdateInput) (db.AccountTaskSettings, error) { + // settings 是规范化后的账号任务设置。 + settings := input.Settings + settings.CookieID = input.CookieID + settings.RateContent = strings.TrimSpace(settings.RateContent) + if settings.AutoRateEnabled && settings.RateContent == "" { + return db.AccountTaskSettings{}, errors.New("启用自动评价时评价内容不能为空") + } + if len([]rune(settings.RateContent)) > 500 { + return db.AccountTaskSettings{}, errors.New("评价内容不能超过 500 个字符") + } + if !accountTaskTimePattern.MatchString(settings.PolishTime) { + return db.AccountTaskSettings{}, errors.New("擦亮时间格式必须为 HH:mm") + } + // err 表示任务设置持久化错误。 + if err := svc.server.Store.AccountTasks.Upsert(ctx, settings); err != nil { + return db.AccountTaskSettings{}, err + } + return svc.server.Store.AccountTasks.Get(ctx, input.CookieID) +} + +// ListAccountTaskRuns 查询账号最近的任务执行记录。 +func (svc *communicationService) ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) { + return svc.server.Store.AccountTasks.RecentRuns(ctx, cookieID, limit) +} + +// RunAccountTask 执行一次账号自动化任务并返回执行摘要。 +func (svc *communicationService) RunAccountTask(ctx context.Context, cookieID, taskType string) (automation.AccountTaskSummary, error) { + if svc.server.automation == nil { + return automation.AccountTaskSummary{}, errCommunicationUnavailable + } + return svc.server.automation.RunAccountTask(ctx, cookieID, taskType) +} + +// ListNotificationChannels 查询用户拥有的通知渠道。 +func (svc *communicationService) ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) { + return svc.server.Store.Notifications.AllChannelsForUser(ctx, userID) +} + +// CreateNotificationChannel 创建用户通知渠道。 +func (svc *communicationService) CreateNotificationChannel(ctx context.Context, row db.NotificationChannelRow) (int64, error) { + return svc.server.Store.Notifications.CreateChannel(ctx, &row) +} + +// UpdateNotificationChannel 更新用户拥有的通知渠道。 +func (svc *communicationService) UpdateNotificationChannel(ctx context.Context, row db.NotificationChannelRow, userID int64) error { + return svc.server.Store.Notifications.UpdateChannelForUser(ctx, &row, userID) +} + +// GetNotificationChannel 查询用户拥有的单个通知渠道。 +func (svc *communicationService) GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) { + return svc.server.Store.Notifications.GetChannelRowForUser(ctx, channelID, userID) +} + +// DeleteNotificationChannel 删除用户拥有的通知渠道。 +func (svc *communicationService) DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error { + return svc.server.Store.Notifications.DeleteChannelForUser(ctx, channelID, userID) +} + +// TestNotificationChannel 向用户拥有的通知渠道发送测试消息。 +func (svc *communicationService) TestNotificationChannel(ctx context.Context, channelID, userID int64, body string) error { + if svc.server.notifier == nil { + return errCommunicationUnavailable + } + // channel 和 err 保存通知渠道查询结果。 + channel, err := svc.server.Store.Notifications.GetChannel(ctx, channelID) + if err != nil { + return err + } + if channel == nil { + return db.ErrForbidden + } + // row 和 err 保存带用户归属的渠道查询结果。 + row, err := svc.server.Store.Notifications.GetChannelRowForUser(ctx, channelID, userID) + if err != nil { + return err + } + if row == nil { + return db.ErrForbidden + } + return svc.server.notifier.SendToChannel(channelID, body) +} + +// ListNotificationBindings 查询用户账号的通知绑定。 +func (svc *communicationService) ListNotificationBindings(ctx context.Context, userID int64) (map[string][]notificationBindingRow, error) { + // rows 和 err 保存绑定查询结果集。 + rows, err := svc.server.Store.DB.QueryContext(ctx, ` + SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled + FROM message_notifications mn + JOIN cookies c ON c.id=mn.cookie_id + JOIN notification_channels nc ON nc.id=mn.channel_id AND nc.user_id=c.user_id + WHERE c.user_id=? ORDER BY mn.id DESC`, userID) + if err != nil { + return nil, err + } + defer rows.Close() + // result 是按账号分组的通知绑定列表。 + result := make(map[string][]notificationBindingRow) + for rows.Next() { + // binding 保存当前扫描到的通知绑定记录。 + var binding notificationBindingRow + // enabled 保存数据库中的整数布尔值。 + var enabled int + // err 表示当前绑定行扫描错误。 + if err := rows.Scan(&binding.ID, &binding.CookieID, &binding.ChannelID, &binding.ChannelName, &enabled); err != nil { + return nil, err + } + binding.Enabled = enabled != 0 + result[binding.CookieID] = append(result[binding.CookieID], binding) + } + return result, rows.Err() +} + +// SetNotificationBindings 覆盖保存账号的通知渠道绑定。 +func (svc *communicationService) SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error { + return svc.server.Store.Notifications.SetBindings(ctx, cookieID, channelIDs) +} + +// GetNotificationBindingIDs 查询账号当前启用的通知渠道标识。 +func (svc *communicationService) GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) { + return svc.server.Store.Notifications.AccountBindings(ctx, cookieID) +} + +// SetSingleNotificationBinding 更新单个账号通知渠道的启用状态。 +func (svc *communicationService) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error { + if !enabled { + // err 表示删除单个通知绑定的错误。 + _, err := svc.server.Store.DB.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=? AND channel_id=?`, cookieID, channelID) + return err + } + // err 表示写入单个通知绑定的错误。 + _, err := svc.server.Store.DB.ExecContext(ctx, + `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES (?, ?, ?)`+ + db.DialectUpsert(svc.server.Store.Dialect, []string{"cookie_id", "channel_id"}, map[string]string{"enabled": "EXCLUDED.enabled", "updated_at": "CURRENT_TIMESTAMP"}), + cookieID, channelID, 1) + return err +} + +// DeleteNotificationBinding 删除用户账号下的一条通知绑定。 +func (svc *communicationService) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error { + // err 表示删除指定通知绑定的错误。 + _, err := svc.server.Store.DB.ExecContext(ctx, ` + DELETE FROM message_notifications WHERE id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, bindingID, userID) + return err +} + +// DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。 +func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error { + // err 表示删除账号通知绑定的错误。 + _, err := svc.server.Store.DB.ExecContext(ctx, ` + DELETE FROM message_notifications WHERE cookie_id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, cookieID, userID) + return err +} + +// SendChatText 创建并发送一条文字消息,失败时保留可重试的本地失败状态。 +func (svc *communicationService) SendChatText(ctx context.Context, input chatTextInput) (*db.ChatMessage, error) { + // s 是当前通信应用服务依赖的 Server。 + s := svc.server + if s.chat == nil || s.Manager == nil { + return nil, errCommunicationUnavailable + } + // sender 保存目标账号的在线发送句柄。 + sender, ok := s.Manager.GetInstance(input.Session.CookieID) + if !ok || sender == nil { + return nil, errChatOffline + } + // message 和 err 保存待发送消息落库结果。 + message, err := s.chat.CreateOutgoing(ctx, input.Session, input.Text) + if err != nil { + return nil, fmt.Errorf("保存待发送消息失败: %w", err) + } + // err 表示文字发送错误。 + if err := sender.SendText(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, input.Text); err != nil { + // failed 保存发送失败后的本地消息状态。 + failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed") + return failed, fmt.Errorf("%w: %v", errChatSend, err) + } + // sent 和 err 保存远端发送成功后的本地状态。 + sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent") + if err != nil { + return sent, fmt.Errorf("%w: %v", errChatStatusSave, err) + } + return sent, nil +} + +// SendChatImage 上传并发送一条图片消息,失败时保留可重试的本地失败状态。 +func (svc *communicationService) SendChatImage(ctx context.Context, input chatImageInput) (*db.ChatMessage, error) { + // s 是当前通信应用服务依赖的 Server。 + s := svc.server + if s.chat == nil || s.Manager == nil { + return nil, errCommunicationUnavailable + } + // sender 和 ok 保存目标账号的在线发送句柄及存在性。 + sender, ok := s.Manager.GetInstance(input.Session.CookieID) + if !ok || sender == nil { + return nil, errChatOffline + } + // cookies 和 err 保存图片上传使用的账号凭证。 + cookies, err := s.Store.Cookies.GetValue(ctx, input.Session.CookieID) + if err != nil { + return nil, fmt.Errorf("读取账号凭证失败: %w", err) + } + // uploader 和 ok 表示图片上传客户端及其能力支持情况。 + uploader, ok := s.mtopClient().(interface { + UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) + }) + if !ok { + return nil, errCommunicationUnavailable + } + // upload 和 err 保存图片上传结果。 + upload, err := uploader.UploadChatImage(ctx, cookies, input.Filename, input.ContentType, input.Data) + if err != nil { + return nil, fmt.Errorf("%w: %v", errChatSend, err) + } + if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies { + // err 表示保存图片上传后刷新 Cookie 的错误,仅忽略并继续发送。 + _ = s.Store.Cookies.UpdateValueExisting(ctx, input.Session.CookieID, upload.UpdatedCookies) + sender.UpdateCookie(upload.UpdatedCookies) + } + // message 和 err 保存图片消息落库结果。 + message, err := s.chat.CreateOutgoingMedia(ctx, input.Session, "image", upload.URL) + if err != nil { + return nil, fmt.Errorf("保存待发送图片失败: %w", err) + } + // err 表示图片发送错误。 + if err := sender.SendImage(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, upload.URL, 0); err != nil { + // failed 保存图片发送失败后的本地消息状态。 + failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed") + return failed, fmt.Errorf("%w: %v", errChatSend, err) + } + // sent 和 err 保存图片发送成功后的本地状态。 + sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent") + if err != nil { + return sent, fmt.Errorf("%w: %v", errChatStatusSave, err) + } + return sent, nil +} + +// MarkChatRead 将指定聊天会话标记为已读。 +func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error { + return svc.server.Store.Chats.MarkRead(ctx, userID, accountID, chatID) +} + +// ListStoredChatMessages 查询本地聊天历史并返回会话摘要。 +func (svc *communicationService) ListStoredChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) (chatMessagePageResult, error) { + // messages 和 err 保存本地聊天历史查询结果。 + messages, err := svc.server.Store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) + if err != nil { + return chatMessagePageResult{}, err + } + // session 保存当前聊天会话摘要。 + var session db.ChatSession + // sessions 和 sessionErr 保存当前用户的聊天会话列表及查询错误。 + if sessions, sessionErr := svc.server.Store.Chats.ListSessions(ctx, userID, accountID, 500); sessionErr == nil { + // candidate 是当前遍历到的会话摘要。 + for _, candidate := range sessions { + if candidate.ChatID == chatID { + session = svc.server.resolveSelectedChatIdentity(ctx, accountID, candidate) + break + } + } + } + return chatMessagePageResult{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil +} diff --git a/internal/server/communication_service_test.go b/internal/server/communication_service_test.go new file mode 100644 index 0000000..733ae56 --- /dev/null +++ b/internal/server/communication_service_test.go @@ -0,0 +1,55 @@ +package server + +import ( + "context" + "testing" + + "xianyu-go/internal/db" +) + +// TestCommunicationServiceUpdatesAccountTask 验证账号任务设置由通信应用服务校验并持久化。 +func TestCommunicationServiceUpdatesAccountTask(t *testing.T) { + // srv、store 和 cleanup 构造并释放测试服务。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // settings 和 err 保存应用服务返回的最终任务设置。 + settings, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{ + CookieID: "acc1", + Settings: db.AccountTaskSettings{AutoRateEnabled: true, RateContent: " 好评 ", AutoPolishEnabled: false, PolishTime: "03:00"}, + }) + if err != nil { + t.Fatalf("UpdateAccountTaskSettings error: %v", err) + } + if settings.CookieID != "acc1" || settings.RateContent != "好评" || !settings.AutoRateEnabled { + t.Fatalf("unexpected task settings: %+v", settings) + } +} + +// TestCommunicationServiceRejectsInvalidAccountTask 验证账号任务业务校验不依赖 HTTP 请求。 +func TestCommunicationServiceRejectsInvalidAccountTask(t *testing.T) { + // srv、store 和 cleanup 构造并释放测试服务。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // err 保存无效任务设置的校验错误。 + _, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{ + CookieID: "acc1", Settings: db.AccountTaskSettings{AutoRateEnabled: true, PolishTime: "03:00"}, + }) + if err == nil { + t.Fatal("启用自动评价但没有内容应该失败") + } +} + +// TestCommunicationServiceListsStoredChatMessages 验证聊天历史查询服务返回稳定分页结果。 +func TestCommunicationServiceListsStoredChatMessages(t *testing.T) { + // srv、store 和 cleanup 构造并释放测试服务。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // page 和 err 保存聊天历史查询结果。 + page, err := srv.communicationApplication().ListStoredChatMessages(context.Background(), 1, "acc1", "chat-missing", 0, 20) + if err != nil { + t.Fatalf("ListStoredChatMessages error: %v", err) + } + if len(page.Messages) != 0 || page.Session.ChatID != "" { + t.Fatalf("unexpected empty chat page: %+v", page) + } +} diff --git a/internal/server/notification_handlers.go b/internal/server/notification_handlers.go index c5022e1..a2dec5b 100644 --- a/internal/server/notification_handlers.go +++ b/internal/server/notification_handlers.go @@ -27,7 +27,7 @@ func (s *Server) mountNotificationsReal(r chi.Router) { func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) { sess := authSess(r) - chs, err := s.Store.Notifications.AllChannelsForUser(r.Context(), sess.UserID) + chs, err := s.communicationApplication().ListNotificationChannels(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -48,7 +48,7 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "name 和 type 必填") return } - id, err := s.Store.Notifications.CreateChannel(r.Context(), &db.NotificationChannelRow{ + id, err := s.communicationApplication().CreateNotificationChannel(r.Context(), db.NotificationChannelRow{ Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled, UserID: sess.UserID, }) if err != nil { @@ -76,7 +76,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) { return } sess := authSess(r) - row, err := s.Store.Notifications.GetChannelRowForUser(r.Context(), id, sess.UserID) + row, err := s.communicationApplication().GetNotificationChannel(r.Context(), id, sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -104,7 +104,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "name 和 type 必填") return } - if err := s.Store.Notifications.UpdateChannelForUser(r.Context(), row, sess.UserID); err != nil { + if err := s.communicationApplication().UpdateNotificationChannel(r.Context(), *row, sess.UserID); err != nil { if errors.Is(err, db.ErrNotFound) { writeErr(w, http.StatusForbidden, "无权操作该通知渠道") return @@ -122,7 +122,7 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) { return } sess := authSess(r) - if err := s.Store.Notifications.DeleteChannelForUser(r.Context(), id, sess.UserID); err != nil { + if err := s.communicationApplication().DeleteNotificationChannel(r.Context(), id, sess.UserID); err != nil { if errors.Is(err, db.ErrNotFound) { writeErr(w, http.StatusForbidden, "无权操作该通知渠道") return @@ -140,16 +140,16 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "无效ID") return } - if s.notifier == nil { - writeErr(w, http.StatusServiceUnavailable, "通知器未启用") - return - } if !s.requireChannelOwner(w, r, id) { return } body := "🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " + time.Now().Format("2006-01-02 15:04:05") - if err := s.notifier.SendToChannel(id, body); err != nil { + if err := s.communicationApplication().TestNotificationChannel(r.Context(), id, authSess(r).UserID, body); err != nil { + if errors.Is(err, errCommunicationUnavailable) { + writeErr(w, http.StatusServiceUnavailable, "通知器未启用") + return + } writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error()) return } @@ -161,7 +161,7 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) { if !s.requireCookieOwnership(w, r, cid) { return } - ids, err := s.Store.Notifications.AccountBindings(r.Context(), cid) + ids, err := s.communicationApplication().GetNotificationBindingIDs(r.Context(), cid) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -171,37 +171,16 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) { func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) { sess := authSess(r) - rows, err := s.Store.DB.QueryContext(r.Context(), - `SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled - FROM message_notifications mn - JOIN cookies c ON c.id=mn.cookie_id - JOIN notification_channels nc ON nc.id=mn.channel_id AND nc.user_id=c.user_id - WHERE c.user_id=? - ORDER BY mn.id DESC`, sess.UserID) + rows, err := s.communicationApplication().ListNotificationBindings(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return } - defer rows.Close() - out := make(notificationBindingListResponse) - for rows.Next() { - var id, channelID int64 - var cookieID, channelName string - var enabled int - if err := rows.Scan(&id, &cookieID, &channelID, &channelName, &enabled); err != nil { - writeErr(w, http.StatusInternalServerError, "查询失败") - return + out := make(notificationBindingListResponse, len(rows)) + for cookieID, bindings := range rows { + for _, binding := range bindings { + out[cookieID] = append(out[cookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled}) } - out[cookieID] = append(out[cookieID], notificationBindingResponse{ - ID: id, - ChannelID: channelID, - ChannelName: channelName, - Enabled: enabled != 0, - }) - } - if err := rows.Err(); err != nil { - writeErr(w, http.StatusInternalServerError, "查询失败") - return } writeJSON(w, http.StatusOK, out) } @@ -228,13 +207,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) { if req.Enabled != nil { enabled = *req.Enabled } - _, err := s.Store.DB.ExecContext(r.Context(), - `INSERT INTO message_notifications (cookie_id, channel_id, enabled) - VALUES (?, ?, ?)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id", "channel_id"}, map[string]string{ - "enabled": "EXCLUDED.enabled", - "updated_at": "CURRENT_TIMESTAMP", - }), - cid, req.ChannelID, btoi(enabled)) + err := s.communicationApplication().SetSingleNotificationBinding(r.Context(), cid, req.ChannelID, enabled) if err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return @@ -247,7 +220,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) { return } } - if err := s.Store.Notifications.SetBindings(r.Context(), cid, req.ChannelIDs); err != nil { + if err := s.communicationApplication().SetNotificationBindings(r.Context(), cid, req.ChannelIDs); err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return } @@ -261,10 +234,7 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques writeErr(w, http.StatusBadRequest, "无效ID") return } - _, err = s.Store.DB.ExecContext(r.Context(), - `DELETE FROM message_notifications - WHERE id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, - id, sess.UserID) + err = s.communicationApplication().DeleteNotificationBinding(r.Context(), sess.UserID, id) if err != nil { writeErr(w, http.StatusInternalServerError, "删除失败") return @@ -275,10 +245,7 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) { sess := authSess(r) cid := chi.URLParam(r, "cid") - _, err := s.Store.DB.ExecContext(r.Context(), - `DELETE FROM message_notifications - WHERE cookie_id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, - cid, sess.UserID) + err := s.communicationApplication().DeleteAccountNotificationBindings(r.Context(), sess.UserID, cid) if err != nil { writeErr(w, http.StatusInternalServerError, "删除失败") return