阶段十:完成 Go Server 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 04:56:57 +08:00
1 parent 6257fad453
commit c47271ae9c
64 files changed
+4217 -30552

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -627,3 +627,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 10 第一个 PR 切片“前端共享 types.ts 注释基线清零” | 为分页、会话、账号、聊天、订单、卡券、商品、自动化规则、统计、设置、AI、默认回复和通知 DTO 的全部字段补齐准确中文注释,解释字段职责、敏感性、状态和时间/数量单位;`frontend/types.ts` 历史注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:前端 services/api.ts 注释基线清零 |
| 2026-08-15 | 完成阶段 10 第二个 PR 切片“前端 services/api.ts 注释基线清零” | 为 API 适配层全部导出函数、局部变量、请求参数和内联响应字段补齐中文注释,明确认证、账号、聊天、订单、商品、卡密、自动化、设置和通知接口的数据职责;增强注释检查器对调用参数、类型字面量和循环变量内联注释的识别能力,`services/api.ts` 注释基线清零;前端注释门禁、类型检查和 185 个测试通过并合并为一个可回滚提交 | 阶段 10:前端 components/hooks 注释基线按领域清零 |
| 2026-08-15 | 完成阶段 10 第三个 PR 切片“前端 components/hooks 注释基线按领域清零” | 为账号、聊天、仪表盘、设置、规则、商品、卡密、订单、通知和二维码等组件、Hook、状态模块及其测试补齐函数、变量、回调和字段中文注释;补强注释检查器对箭头函数主体内联注释的识别,保持路由源码断言和 JSX 行为不变;目标目录注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:Go 核心领域注释基线按领域清零 |
| 2026-08-15 | 完成阶段 10 第四个 PR 切片“Go internal/server 注释基线按领域清零” | 为 HTTP handlers、应用服务、事务边界、批量发布、登录/二维码、请求解析、测试辅助和错误处理代码补齐函数、变量、字段及常量中文注释;增强 Go 注释检查器对多行文档块与分组 const/var 注释的识别;`internal/server` 注释基线清零,Server 定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/db 与 internal/xianyu 领域注释基线 |
+16
View File
@@ -12,8 +12,10 @@ import (
"xianyu-go/internal/db"
)
// accountTaskTimePattern 保存账号任务时间Pattern,供当前处理流程使用
var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`)
// mountAccountTasks 负责mount账号任务列表相关处理。
func (s *Server) mountAccountTasks(r chi.Router) {
r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings)
r.Put("/api/account-tasks/{cid}", s.updateAccountTaskSettings)
@@ -21,12 +23,15 @@ func (s *Server) mountAccountTasks(r chi.Router) {
r.Post("/api/account-tasks/{cid}/run", s.runAccountTask)
}
// getAccountTaskSettings 负责get账号任务设置相关处理。
func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := s.communicationApplication().GetAccountTaskSettings(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
@@ -35,17 +40,21 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(settings))
}
// updateAccountTaskSettings 负责update账号任务设置相关处理。
func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// input 保存input,供当前处理流程使用
var input db.AccountTaskSettings
if decodeJSON(r, &input) != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// stored、err 保存stored、err,供当前处理流程使用
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(), "格式必须") {
@@ -58,12 +67,15 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(stored))
}
// listAccountTaskRuns 负责list账号任务运行记录相关处理。
func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// runs、err 保存runs、err,供当前处理流程使用
runs, err := s.communicationApplication().ListAccountTaskRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
@@ -72,7 +84,9 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newAccountTaskRunResponses(runs)})
}
// runAccountTask 负责运行账号任务相关处理。
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if s.automation == nil {
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
@@ -82,6 +96,7 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// input 保存input,供当前处理流程使用
var input struct {
TaskType string `json:"task_type"`
}
@@ -89,6 +104,7 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "不支持的任务类型")
return
}
// summary、err 保存summary、err,供当前处理流程使用
summary, err := s.communicationApplication().RunAccountTask(r.Context(), cid, input.TaskType)
if err != nil {
if errors.Is(err, errCommunicationUnavailable) {
+145 -4
View File
@@ -11,18 +11,24 @@ import (
// TestAdminListCookies 管理员列出所有账号。
func TestAdminListCookies(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["id"] != "acc1" {
@@ -32,16 +38,23 @@ func TestAdminListCookies(t *testing.T) {
// TestAdminDeleteUser 删除其他用户。
func TestAdminDeleteUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.Users.Create(ctx, "user-del", "u@e.com", "pw")
// u 保存u,供当前处理流程使用
u, _ := store.Users.GetByUsername(ctx, "user-del")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -49,42 +62,58 @@ func TestAdminDeleteUser(t *testing.T) {
}
}
// TestAdminDeleteUserRevokesSessions 负责TestAdminDelete用户RevokesSessions相关处理。
func TestAdminDeleteUserRevokesSessions(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if _, err := store.Users.Create(ctx, "session-del", "session-del@example.com", "pw"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.Users.Create(ctx, "session-del", "session-del@example.com", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// u、err 保存u、err,供当前处理流程使用
u, err := store.Users.GetByUsername(ctx, "session-del")
if err != nil {
t.Fatalf("get user: %v", err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// userLogin 保存用户登录,供当前处理流程使用
userLogin := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"session-del","password":"pw"}`))
// userLoginRec 保存用户登录Rec,供当前处理流程使用
userLoginRec := httptest.NewRecorder()
h.ServeHTTP(userLoginRec, userLogin)
if userLoginRec.Code != http.StatusOK || len(userLoginRec.Result().Cookies()) == 0 {
t.Fatalf("user login status=%d body=%s", userLoginRec.Code, userLoginRec.Body.String())
}
// userCookie 保存用户登录凭证,供当前处理流程使用
userCookie := userLoginRec.Result().Cookies()[0]
// adminCookie 保存admin登录凭证,供当前处理流程使用
adminCookie := loginHelper(t, h)
// delReq 保存delReq,供当前处理流程使用
delReq := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
delReq.AddCookie(adminCookie)
// delRec 保存delRec,供当前处理流程使用
delRec := httptest.NewRecorder()
h.ServeHTTP(delRec, delReq)
if delRec.Code != http.StatusOK {
t.Fatalf("delete status=%d body=%s", delRec.Code, delRec.Body.String())
}
// verifyReq 保存verifyReq,供当前处理流程使用
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(userCookie)
// verifyRec 保存verifyRec,供当前处理流程使用
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verify 保存verify,供当前处理流程使用
var verify map[string]any
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
t.Fatalf("decode verify: %v", err)
}
if verify["authenticated"] == true {
@@ -94,14 +123,20 @@ func TestAdminDeleteUserRevokesSessions(t *testing.T) {
// TestAdminDeleteUserSelf 不能删除自己 400。
func TestAdminDeleteUserSelf(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(admin.ID), nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -111,13 +146,18 @@ func TestAdminDeleteUserSelf(t *testing.T) {
// TestAdminDeleteUserBadID 无效 ID 400。
func TestAdminDeleteUserBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/admin/users/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -127,21 +167,28 @@ func TestAdminDeleteUserBadID(t *testing.T) {
// TestAdminStatsWithOrders 带订单的统计。
func TestAdminStatsWithOrders(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('s1','i1','acc1','2')`)
store.DB.ExecContext(ctx, `INSERT INTO cards (name, type, user_id) VALUES ('卡1','text',1)`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d", rec.Code)
}
// stats 保存stats,供当前处理流程使用
var stats map[string]any
json.Unmarshal(rec.Body.Bytes(), &stats)
if stats["total_orders"] != float64(1) || stats["total_cards"] != float64(1) {
@@ -151,19 +198,26 @@ func TestAdminStatsWithOrders(t *testing.T) {
// TestChangeAdminPassword 修改管理员密码成功。
func TestChangeAdminPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"pw","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true {
@@ -173,16 +227,23 @@ func TestChangeAdminPassword(t *testing.T) {
// TestChangeAdminPasswordWrongCurrent 当前密码错误。
func TestChangeAdminPasswordWrongCurrent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"wrong","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] == true {
@@ -192,13 +253,18 @@ func TestChangeAdminPasswordWrongCurrent(t *testing.T) {
// TestChangeAdminPasswordBadJSON 非法 JSON 400。
func TestChangeAdminPasswordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -206,14 +272,20 @@ func TestChangeAdminPasswordBadJSON(t *testing.T) {
}
}
// TestChangeAdminPasswordShortNewPassword 负责TestChangeAdmin密码ShortNew密码相关处理。
func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -223,18 +295,26 @@ func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
// TestChangeAdminPasswordNonAdmin 非 admin 403。
func TestChangeAdminPasswordNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw")
// h 保存h,供当前处理流程使用
h := srv.Router()
// body 保存请求体,供当前处理流程使用
body := `{"username":"user2","password":"pw"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
cookie := rec.Result().Cookies()[0]
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusForbidden {
@@ -244,19 +324,26 @@ func TestChangeAdminPasswordNonAdmin(t *testing.T) {
// TestChangePassword 修改当前用户密码。
func TestChangePassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"pw","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true {
@@ -264,33 +351,45 @@ func TestChangePassword(t *testing.T) {
}
}
// TestChangePasswordRevokesCurrentSession 负责TestChange密码RevokesCurrent会话相关处理。
func TestChangePasswordRevokesCurrentSession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("change status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode change response: %v", err)
}
if res["success"] != true || res["requires_relogin"] != true {
t.Fatalf("change response should require relogin: %+v", res)
}
// verifyReq 保存verifyReq,供当前处理流程使用
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookie)
// verifyRec 保存verifyRec,供当前处理流程使用
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verify 保存verify,供当前处理流程使用
var verify map[string]any
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
t.Fatalf("decode verify: %v", err)
}
if verify["authenticated"] == true {
@@ -300,16 +399,23 @@ func TestChangePasswordRevokesCurrentSession(t *testing.T) {
// TestChangePasswordWrongCurrent 当前密码错误。
func TestChangePasswordWrongCurrent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"wrong","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] == true {
@@ -319,13 +425,18 @@ func TestChangePasswordWrongCurrent(t *testing.T) {
// TestChangePasswordBadJSON 非法 JSON 400。
func TestChangePasswordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -333,14 +444,20 @@ func TestChangePasswordBadJSON(t *testing.T) {
}
}
// TestChangePasswordShortNewPassword 负责TestChange密码ShortNew密码相关处理。
func TestChangePasswordShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -350,14 +467,20 @@ func TestChangePasswordShortNewPassword(t *testing.T) {
// TestUpdateCredentialsBadUsername 用户名长度不足 400。
func TestUpdateCredentialsBadUsername(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"pw","new_username":"ab"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -367,14 +490,20 @@ func TestUpdateCredentialsBadUsername(t *testing.T) {
// TestUpdateCredentialsMissingCurrentPassword 缺当前密码 400。
func TestUpdateCredentialsMissingCurrentPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"new_username":"newname"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -384,14 +513,20 @@ func TestUpdateCredentialsMissingCurrentPassword(t *testing.T) {
// TestUpdateCredentialsShortNewPassword 新密码过短 400。
func TestUpdateCredentialsShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"pw","new_password":"123"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -401,14 +536,20 @@ func TestUpdateCredentialsShortNewPassword(t *testing.T) {
// TestUpdateCredentialsNothingChanged 用户名密码均未修改 400。
func TestUpdateCredentialsNothingChanged(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"current_password":"pw","new_username":"admin"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+13 -1
View File
@@ -15,13 +15,17 @@ func (s *Server) mountAdminReal(r chi.Router) {
r.Get("/admin/stats", s.adminStats)
}
// adminListUsers 负责adminList用户列表相关处理。
func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Admin.ListUsers(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
var out []adminUserResponse
// row 表示当前遍历过程中的row
for _, row := range rows {
out = append(out, adminUserResponse{
ID: row.ID, Username: row.Username, Email: row.Email,
@@ -32,7 +36,9 @@ func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// adminDeleteUser 负责adminDelete用户相关处理。
func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
// uid、err 保存uid、err,供当前处理流程使用
uid, err := strconv.ParseInt(chi.URLParam(r, "user_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效用户ID")
@@ -51,20 +57,25 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
}
}
}
if err := s.Store.Users.Delete(r.Context(), uid); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Users.Delete(r.Context(), uid); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// adminListCookies 负责adminListCookies相关处理。
func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Admin.ListCookies(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
var out []adminCookieResponse
// row 表示当前遍历过程中的row
for _, row := range rows {
out = append(out, adminCookieResponse{
ID: row.ID, UserID: row.UserID, Remark: row.Remark,
@@ -75,6 +86,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// adminStats 负责adminStats相关处理。
func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
// stats 是管理员仪表盘的数据库聚合结果。
stats, err := s.Store.Admin.Stats(r.Context())
+25 -1
View File
@@ -21,6 +21,7 @@ func (s *Server) mountAnalyticsReal(r chi.Router) {
// dashboardStats 返回当前登录用户的数据概览。管理员全局统计仍由 /admin/stats 提供,
// 避免普通用户访问管理员接口,也避免把全局资源数和用户自己的订单收益混在一起。
// dashboardStats 负责dashboardStats相关处理。
func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) {
// sess 是当前请求的认证会话。
sess := auth.SessionFromContext(r.Context())
@@ -42,7 +43,9 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
// startDate、endDate 和 location 是订单分析的日期范围及时区参数。
startDate := r.URL.Query().Get("start_date")
// endDate 保存结束日期,供当前处理流程使用
endDate := r.URL.Query().Get("end_date")
// location 保存地址,供当前处理流程使用
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
// where 和 params 是按用户、日期和状态归一化后的查询条件。
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
@@ -65,7 +68,9 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
// startDate、endDate 和 location 是有效订单的日期范围及时区参数。
startDate := r.URL.Query().Get("start_date")
// endDate 保存结束日期,供当前处理流程使用
endDate := r.URL.Query().Get("end_date")
// location 保存地址,供当前处理流程使用
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
// where 和 params 是按用户、日期和状态归一化后的查询条件。
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
@@ -73,6 +78,7 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "orders.amount")
// page 和 pageSize 是已经限制在安全范围内的分页参数。
page := atoiDefault(r.URL.Query().Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
pageSize := atoiDefault(r.URL.Query().Get("page_size"), 500)
if page < 1 {
page = 1
@@ -93,8 +99,11 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。
// 返回 (whereClause, params),whereClause 已含 WHERE 前缀。
// buildAnalyticsWhere 负责buildAnalyticsWhere相关处理。
func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []string, location *time.Location) (string, []any) {
// conds 保存conds,供当前处理流程使用
conds := []string{"orders.deleted_at IS NULL"}
// params 保存params,供当前处理流程使用
params := []any{}
if startDate != "" {
conds = append(conds, "orders.created_at >= ?")
@@ -109,13 +118,16 @@ func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []str
params = append(params, userID)
}
if len(statuses) > 0 {
// ph 保存ph,供当前处理流程使用
ph := strings.Repeat("?,", len(statuses))
ph = strings.TrimSuffix(ph, ",")
conds = append(conds, "orders.order_status IN ("+ph+")")
// s 表示当前遍历过程中的s
for _, s := range statuses {
params = append(params, s)
}
}
// where 保存where,供当前处理流程使用
where := ""
if len(conds) > 0 {
where = "WHERE " + strings.Join(conds, " AND ")
@@ -127,10 +139,12 @@ func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []str
return where, params
}
// analyticsDateBoundary 负责analytics日期Boundary相关处理。
func analyticsDateBoundary(raw string, endExclusive bool, location *time.Location) string {
if location == nil {
location = time.Local
}
// t、err 保存t、err,供当前处理流程使用
t, err := time.ParseInLocation("2006-01-02", strings.TrimSpace(raw), location)
if err != nil {
return raw
@@ -141,7 +155,9 @@ func analyticsDateBoundary(raw string, endExclusive bool, location *time.Locatio
return t.UTC().Format("2006-01-02 15:04:05")
}
// analyticsLocation 负责analytics地址相关处理。
func analyticsLocation(rawOffset string) *time.Location {
// offset、err 保存offset、err,供当前处理流程使用
offset, err := strconv.Atoi(strings.TrimSpace(rawOffset))
if err != nil || offset < -14*60 || offset > 14*60 {
return time.Local
@@ -149,7 +165,9 @@ func analyticsLocation(rawOffset string) *time.Location {
return time.FixedZone("browser", offset*60)
}
// analyticsAmountExpression 负责analyticsAmountExpression相关处理。
func analyticsAmountExpression(dialect db.Dialect, column string) string {
// clean 保存clean,供当前处理流程使用
clean := `TRIM(REPLACE(REPLACE(` + column + `, '¥', ''), ',', ''))`
switch dialect {
case db.DialectPostgres:
@@ -161,21 +179,27 @@ func analyticsAmountExpression(dialect db.Dialect, column string) string {
}
}
// parseAnalyticsDBTime 负责parseAnalyticsDB时间相关处理。
func parseAnalyticsDBTime(raw string) time.Time {
// layout 表示当前遍历过程中的layout
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"} {
if t, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC); err == nil {
if // t、err 保存t、err,供当前处理流程使用
t, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC); err == nil {
return t
}
}
return time.Time{}
}
// parseAnalyticsAmount 负责parseAnalyticsAmount相关处理。
func parseAnalyticsAmount(raw string) float64 {
raw = strings.TrimSpace(strings.NewReplacer("¥", "", ",", "").Replace(raw))
// value 保存值,供当前处理流程使用
value, _ := strconv.ParseFloat(raw, 64)
return value
}
// round2 负责round2相关处理。
func round2(f float64) float64 {
return float64(int(f*100+0.5)) / 100
}
+86 -12
View File
@@ -11,9 +11,12 @@ import (
"time"
)
// TestValidOrdersMatchesAnalyticsScope 负责Test有效订单列表MatchesAnalyticsScope相关处理。
func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `
@@ -24,45 +27,56 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("analytics status=%d body=%s", rec.Code, rec.Body.String())
}
// analytics 保存analytics,供当前处理流程使用
var analytics struct {
RevenueStats struct {
TotalOrders int `json:"total_orders"`
TotalAmount float64 `json:"total_amount"`
} `json:"revenue_stats"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &analytics); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &analytics); err != nil {
t.Fatal(err)
}
if analytics.RevenueStats.TotalOrders != 1 || analytics.RevenueStats.TotalAmount != 12.5 {
t.Fatalf("统计口径异常: %+v", analytics.RevenueStats)
}
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("valid orders status=%d body=%s", rec2.Code, rec2.Body.String())
}
// valid 保存有效,供当前处理流程使用
var valid struct {
Orders []map[string]any `json:"orders"`
}
if err := json.Unmarshal(rec2.Body.Bytes(), &valid); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec2.Body.Bytes(), &valid); err != nil {
t.Fatal(err)
}
if len(valid.Orders) != 1 {
t.Fatalf("有效订单明细数量应与统计订单数一致,got %d body=%s", len(valid.Orders), rec2.Body.String())
}
// order 保存订单,供当前处理流程使用
order := valid.Orders[0]
if order["order_id"] != "ord-valid" || order["item_title"] != "测试商品" || !strings.Contains(order["item_image"].(string), "img.example") {
t.Fatalf("有效订单明细字段异常: %+v", order)
@@ -72,28 +86,37 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
}
}
// TestValidOrdersIncludesPaidAndReportsPagination 负责Test有效订单列表IncludesPaidAndReportsPagination相关处理。
func TestValidOrdersIncludesPaidAndReportsPagination(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES
('paid-1','10','paid','acc1','2026-06-28 10:00:00'),
('paid-2','20','pending_ship','acc1','2026-06-28 11:00:00')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28&page_size=1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
var result struct {
Orders []map[string]any `json:"orders"`
Total int `json:"total"`
Truncated bool `json:"truncated"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if len(result.Orders) != 1 || result.Total != 2 || !result.Truncated {
@@ -101,19 +124,25 @@ func TestValidOrdersIncludesPaidAndReportsPagination(t *testing.T) {
}
}
// TestDashboardStatsAreAvailableAndScopedToCurrentUser 负责TestDashboardStatsAreAvailableAndScopedToCurrent用户相关处理。
func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "member", "member@example.com", "pw"); err != nil || !ok {
if // ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.Create(ctx, "member", "member@example.com", "pw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
// member、err 保存member、err,供当前处理流程使用
member, err := store.Users.GetByUsername(ctx, "member")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "member-acc", "unb=456", member.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(ctx, "member-acc", "unb=456", member.ID); err != nil {
t.Fatal(err)
}
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,data_content,enabled,user_id) VALUES ('member-card','data',?,1,?)`, "CARD-1\n\nCARD-2\n", member.ID)
@@ -124,25 +153,33 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,user_id) VALUES ('admin-card','text',1)`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,cookie_id,order_status) VALUES ('admin-order','acc1','completed')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"member","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK || len(loginRec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", loginRec.Code, loginRec.Body.String())
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil)
req.AddCookie(loginRec.Result().Cookies()[0])
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// stats 保存stats,供当前处理流程使用
var stats map[string]int64
if err := json.Unmarshal(rec.Body.Bytes(), &stats); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &stats); err != nil {
t.Fatal(err)
}
// key 表示当前遍历过程中的key
for _, key := range []string{"total_cookies", "active_cookies", "total_cards", "total_keywords", "total_orders"} {
if stats[key] != 1 {
t.Fatalf("%s=%d want 1; stats=%+v", key, stats[key], stats)
@@ -152,8 +189,10 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
t.Fatalf("available_card_stock=%d want 2; stats=%+v", stats["available_card_stock"], stats)
}
// adminReq 保存adminReq,供当前处理流程使用
adminReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
adminReq.AddCookie(loginRec.Result().Cookies()[0])
// adminRec 保存adminRec,供当前处理流程使用
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusForbidden {
@@ -161,34 +200,45 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
}
}
// TestAnalyticsIncludesLegacyNumericValidStatuses 负责TestAnalyticsIncludesLegacyNumeric有效Statuses相关处理。
func TestAnalyticsIncludesLegacyNumericValidStatuses(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at)
VALUES ('legacy-shipped','8.50','3','acc1','2026-06-28 12:00:00')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
var response struct {
RevenueStats struct {
TotalOrders int `json:"total_orders"`
} `json:"revenue_stats"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.RevenueStats.TotalOrders != 1 {
t.Fatalf("legacy numeric valid status was excluded: %+v", response)
}
// validReq 保存有效Req,供当前处理流程使用
validReq := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28", nil)
validReq.AddCookie(cookie)
// validRec 保存有效Rec,供当前处理流程使用
validRec := httptest.NewRecorder()
h.ServeHTTP(validRec, validReq)
if !strings.Contains(validRec.Body.String(), `"order_status":"shipped"`) {
@@ -196,56 +246,79 @@ func TestAnalyticsIncludesLegacyNumericValidStatuses(t *testing.T) {
}
}
// TestAnalyticsCustomRangeDoesNotSilentlyDropDays 负责TestAnalyticsCustomRangeDoesNotSilentlyDropDays相关处理。
func TestAnalyticsCustomRangeDoesNotSilentlyDropDays(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
for day := 1; day <= 31; day++ {
for // day 保存day,供当前处理流程使用
day := 1; day <= 31; day++ {
// date 保存日期,供当前处理流程使用
date := time.Date(2026, 1, day, 12, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES (?,?,?,?,?)`, fmt.Sprintf("day-%02d", day), "1", "completed", "acc1", date)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-01-01&end_date=2026-01-31", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// response 保存响应,供当前处理流程使用
var response struct {
Daily []map[string]any `json:"daily_stats"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || len(response.Daily) != 31 {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || len(response.Daily) != 31 {
t.Fatalf("daily range len=%d err=%v body=%s", len(response.Daily), err, rec.Body.String())
}
}
// TestAnalyticsDateBoundaryConvertsLocalDayToUTC 负责TestAnalytics日期BoundaryConvertsLocalDayToUTC相关处理。
func TestAnalyticsDateBoundaryConvertsLocalDayToUTC(t *testing.T) {
// previous 保存previous,供当前处理流程使用
previous := time.Local
time.Local = time.FixedZone("UTC+8", 8*60*60)
defer func() { time.Local = previous }()
if got := analyticsDateBoundary("2026-06-28", false, time.Local); got != "2026-06-27 16:00:00" {
if // got 保存got,供当前处理流程使用
got := analyticsDateBoundary("2026-06-28", false, time.Local); got != "2026-06-27 16:00:00" {
t.Fatalf("start boundary=%q", got)
}
if got := analyticsDateBoundary("2026-06-28", true, time.Local); got != "2026-06-28 16:00:00" {
if // got 保存got,供当前处理流程使用
got := analyticsDateBoundary("2026-06-28", true, time.Local); got != "2026-06-28 16:00:00" {
t.Fatalf("end boundary=%q", got)
}
}
// TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts 负责TestAnalyticsUses浏览器TimezoneAndSkipsInvalidAmounts相关处理。
func TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES
('tz-valid','10.50','completed','acc1','2026-06-27 16:30:00'),
('tz-invalid','abc','completed','acc1','2026-06-27 17:00:00')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28&timezone_offset_minutes=480", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
var response struct {
Revenue struct {
TotalOrders int `json:"total_orders"`
@@ -253,7 +326,8 @@ func TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts(t *testing.T) {
} `json:"revenue_stats"`
Daily []map[string]any `json:"daily_stats"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Revenue.TotalOrders != 1 || response.Revenue.TotalAmount != 10.5 || len(response.Daily) != 1 || response.Daily[0]["date"] != "2026-06-28" {
+46 -10
View File
@@ -32,11 +32,14 @@ type loginResponse struct {
// initialize 首次启动时通过 Web UI 创建管理员账号。
// 该接口只允许在系统尚未存在管理员时调用,避免把初始化能力变成重置密码入口。
// initialize 负责initialize相关处理。
func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
Password string `json:"password"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -49,6 +52,7 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
s.initializationMu.Lock()
defer s.initializationMu.Unlock()
// initialized、err 保存initialized、err,供当前处理流程使用
initialized, err := s.Store.Users.IsSystemInitialized(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "检查系统初始化状态失败")
@@ -59,7 +63,8 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
return
}
if _, err := auth.InitAdmin(r.Context(), s.Store, "admin@example.com", req.Password); err != nil {
if // err 保存err,供当前处理流程使用
_, err := auth.InitAdmin(r.Context(), s.Store, "admin@example.com", req.Password); err != nil {
writeErr(w, http.StatusInternalServerError, "初始化管理员失败")
return
}
@@ -79,23 +84,30 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
// login 用户名密码登录(邮箱登录同走此接口,按字段判断)。
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req loginRequest
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// clientIP 保存clientIP,供当前处理流程使用
clientIP := loginClientIP(r)
// principal 保存principal,供当前处理流程使用
principal := loginPrincipal(req.Username, req.Email)
if allowed, retry := s.loginLimiter.allow(clientIP, principal, time.Now()); !allowed {
if // allowed、retry 保存allowed、retry,供当前处理流程使用
allowed, retry := s.loginLimiter.allow(clientIP, principal, time.Now()); !allowed {
w.Header().Set("Retry-After", strconv.Itoa(max(1, int(retry.Round(time.Second)/time.Second))))
writeErr(w, http.StatusTooManyRequests, "登录尝试过于频繁,请稍后再试")
return
}
// resp 保存resp,供当前处理流程使用
var resp loginResponse
switch {
case req.Username != "" && req.Password != "":
// sid、user、err 保存sid、user、err,供当前处理流程使用
sid, user, err := s.Auth.Login(r.Context(), req.Username, req.Password)
if err != nil || user == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -113,6 +125,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
return
case req.Email != "" && req.Password != "":
// user、err 保存user、err,供当前处理流程使用
user, err := s.Store.Users.GetByEmail(r.Context(), req.Email)
if err != nil || user == nil {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -120,6 +133,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
"邮箱或密码错误", "")
return
}
// sid、loginUser、lerr 保存sid、loginUser、lerr,供当前处理流程使用
sid, loginUser, lerr := s.Auth.Login(r.Context(), user.Username, req.Password)
if lerr != nil || loginUser == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -143,8 +157,11 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// verify 校验会话有效性。返回 authenticated / initialized / is_admin。
func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
// ctx 保存ctx,供当前处理流程使用
ctx := r.Context()
// initialized 保存initialized,供当前处理流程使用
initialized, _ := s.Store.Users.IsSystemInitialized(ctx)
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(ctx)
if sess != nil {
writeJSON(w, http.StatusOK, sessionVerificationResponse{
@@ -164,6 +181,7 @@ func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
// logout 登出。
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess != nil {
s.Auth.Logout(r.Context(), sess.SessionID)
@@ -174,11 +192,13 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// changeAdminPassword 修改管理员密码。
func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -186,7 +206,9 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
return
}
// ctx 保存ctx,供当前处理流程使用
ctx := r.Context()
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(ctx)
if sess == nil || !sess.IsAdmin {
writeErr(w, http.StatusForbidden, "仅管理员可执行此操作")
@@ -198,7 +220,8 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
if // err 保存err,供当前处理流程使用
_, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -208,11 +231,13 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
// changePassword 修改当前用户密码。
func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -220,18 +245,22 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
return
}
// ctx 保存ctx,供当前处理流程使用
ctx := r.Context()
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(ctx)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// user 保存用户,供当前处理流程使用
user, _, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword)
if user == nil {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
if // err 保存err,供当前处理流程使用
_, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -241,21 +270,26 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
// updateCredentials 修改当前登录用户的用户名和/或密码,并撤销全部旧会话。
func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewUsername string `json:"new_username"`
NewPassword string `json:"new_password"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// username 保存username,供当前处理流程使用
username := strings.TrimSpace(req.NewUsername)
// usernameLength 保存usernameLength,供当前处理流程使用
usernameLength := utf8.RuneCountInString(username)
if usernameLength < 3 || usernameLength > 64 {
writeErr(w, http.StatusBadRequest, "用户名长度必须为 3 到 64 个字符")
@@ -273,6 +307,7 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "用户名和密码均未修改")
return
}
// user、ok、err 保存user、ok、err,供当前处理流程使用
user, ok, err := s.Store.Users.VerifyAndUpgrade(r.Context(), sess.Username, req.CurrentPassword)
if err != nil {
writeCredentialVerificationError(w, err)
@@ -282,7 +317,8 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
if errors.Is(err, db.ErrUsernameTaken) {
writeErrCode(w, http.StatusConflict, "username_taken", "用户名已被占用", "")
return
+135 -7
View File
@@ -14,41 +14,51 @@ import (
// TestAutomationRulesCRUD 自动化规则增删查 + 校验分支。
func TestAutomationRulesCRUD(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 准备一个卡密组用于 send_card 动作。
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡密组1", Type: "text", TextContent: "卡密ABC", Enabled: true, UserID: 1})
// 准备一个商品。
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-auto','商品A')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 创建规则:付款后自动发货(send_card)。
body := `{"cookie_id":"acc1","item_id":"it-auto","trigger_type":"order_paid","enabled":true,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":0}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
if cr["success"] != true {
t.Fatalf("创建失败: %+v", cr)
}
// ruleID 保存规则ID,供当前处理流程使用
ruleID := itoa(int64(cr["id"].(float64)))
// 列表。
req2 := httptest.NewRequest(http.MethodGet, "/automation-rules", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 {
@@ -58,8 +68,10 @@ func TestAutomationRulesCRUD(t *testing.T) {
// 更新规则(改名为自定义)。
updBody := `{"cookie_id":"acc1","item_id":"it-auto","name":"自定义规则","trigger_type":"order_paid","enabled":false,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":2}]}`
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodPut, "/automation-rules/"+ruleID, strings.NewReader(updBody))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -69,6 +81,7 @@ func TestAutomationRulesCRUD(t *testing.T) {
// 删除。
req4 := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+ruleID, nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
@@ -76,58 +89,76 @@ func TestAutomationRulesCRUD(t *testing.T) {
}
}
// TestAutomationRulesListFiltersAndPagination 负责Test自动化规则列表ListFiltersAndPagination相关处理。
func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','item-blue','蓝色会员')`)
// input 表示当前遍历过程中的input
for _, input := range []db.AutomationRuleInput{
{UserID: 1, CookieID: "acc1", ItemID: "item-blue", Name: "付款规则", TriggerType: automation.TriggerOrderPaid, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionConfirmShipment, Enabled: true}}},
{UserID: 1, CookieID: "acc1", Name: "评价赠品", TriggerType: automation.TriggerBuyerReviewed, Enabled: false, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "gift", Enabled: true}}},
{UserID: 1, CookieID: "acc1", Name: "求评价", TriggerType: automation.TriggerReviewMissingTimeout, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "review", Enabled: true}}},
} {
if _, err := store.Automation.Create(ctx, input); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.Automation.Create(ctx, input); err != nil {
t.Fatalf("create rule: %v", err)
}
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// request 保存请求,供当前处理流程使用
request := func(path string) (int, map[string]any) {
t.Helper()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// body 保存请求体,供当前处理流程使用
var body map[string]any
if rec.Code == http.StatusOK {
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
}
return rec.Code, body
}
// status、filtered 保存status、filtered,供当前处理流程使用
status, filtered := request("/automation-rules?page=1&page_size=10&cookie_id=acc1&trigger_type=order_paid&enabled=true&search=%E8%93%9D%E8%89%B2")
if status != http.StatusOK || filtered["total"] != float64(1) || filtered["total_pages"] != float64(1) {
t.Fatalf("filtered status=%d body=%+v", status, filtered)
}
// filteredCounts、ok 保存filteredCounts、ok,供当前处理流程使用
filteredCounts, ok := filtered["trigger_counts"].(map[string]any)
if !ok || filteredCounts[automation.TriggerOrderPaid] != float64(1) || len(filteredCounts) != 1 {
t.Fatalf("filtered trigger counts=%+v", filtered["trigger_counts"])
}
// data、ok 保存data、ok,供当前处理流程使用
data, ok := filtered["data"].([]any)
if !ok || len(data) != 1 || data[0].(map[string]any)["name"] != "付款规则" {
t.Fatalf("filtered data=%+v", filtered["data"])
}
// status、lastPage 保存status、last页码,供当前处理流程使用
status, lastPage := request("/automation-rules?page=99&page_size=1")
if status != http.StatusOK || lastPage["total"] != float64(3) || lastPage["page"] != float64(3) {
t.Fatalf("last page status=%d body=%+v", status, lastPage)
}
if data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
if // data、ok 保存data、ok,供当前处理流程使用
data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
t.Fatalf("last page data=%+v", lastPage["data"])
}
// lastPageCounts、ok 保存last页码Counts、ok,供当前处理流程使用
lastPageCounts, ok := lastPage["trigger_counts"].(map[string]any)
if !ok || lastPageCounts[automation.TriggerOrderPaid] != float64(1) ||
lastPageCounts[automation.TriggerBuyerReviewed] != float64(1) ||
@@ -143,14 +174,20 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
func TestAutomationRuleBadTriggerType(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"bogus","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -160,14 +197,20 @@ func TestAutomationRuleBadTriggerType(t *testing.T) {
// TestAutomationRuleBadCookie 账号不属于当前用户 400。
func TestAutomationRuleBadCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"other-account","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -177,14 +220,20 @@ func TestAutomationRuleBadCookie(t *testing.T) {
// TestAutomationRuleBadActionType 不支持的动作类型 400。
func TestAutomationRuleBadActionType(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"bogus"}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -192,20 +241,28 @@ func TestAutomationRuleBadActionType(t *testing.T) {
}
}
// TestAutomationRuleRejectsAPICard 负责Test自动化规则RejectsAPI卡密相关处理。
func TestAutomationRuleRejectsAPICard(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// cardID、err 保存卡密ID、err,供当前处理流程使用
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{
Name: "旧 API 卡密", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
@@ -215,14 +272,20 @@ func TestAutomationRuleRejectsAPICard(t *testing.T) {
// TestAutomationRuleSendCardMissingCardID send_card 缺 card_id 400。
func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":0}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -232,14 +295,20 @@ func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
// TestAutomationRuleSendTextMissingTemplate send_text 缺文案 400。
func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":""}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -247,42 +316,56 @@ func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
}
}
// TestAutomationIssueEndpointsAndActiveDeleteConflict 负责Test自动化问题EndpointsAndActiveDeleteConflict相关处理。
func TestAutomationIssueEndpointsAndActiveDeleteConflict(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{UserID: admin.ID, CookieID: "acc1", Name: "issue",
TriggerType: automation.TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "x", Enabled: true}}})
if err != nil {
t.Fatal(err)
}
// runID 保存运行ID,供当前处理流程使用
runID, _, _ := store.Automation.TryStartRun(ctx, db.AutomationRun{RuleID: ruleID, CookieID: "acc1", OrderID: "o",
TriggerType: automation.TriggerBuyerReviewed, TriggerKey: "k", RawEventJSON: `{}`, LeaseExpiresAt: 1})
_, _ = store.Automation.StartRunAction(ctx, runID, 1, 0, 1)
_ = store.Automation.QuarantineRun(ctx, runID, 1, "unknown")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
listReq := httptest.NewRequest(http.MethodGet, "/automation-issues", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK || !strings.Contains(listRec.Body.String(), "unknown") {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// deleteReq 保存deleteReq,供当前处理流程使用
deleteReq := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+itoa(ruleID), nil)
deleteReq.AddCookie(cookie)
// deleteRec 保存deleteRec,供当前处理流程使用
deleteRec := httptest.NewRecorder()
h.ServeHTTP(deleteRec, deleteReq)
if deleteRec.Code != http.StatusConflict {
t.Fatalf("active delete status=%d body=%s", deleteRec.Code, deleteRec.Body.String())
}
// resolveReq 保存resolveReq,供当前处理流程使用
resolveReq := httptest.NewRequest(http.MethodPost, "/automation-runs/"+itoa(runID)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`))
resolveReq.AddCookie(cookie)
// resolveRec 保存resolveRec,供当前处理流程使用
resolveRec := httptest.NewRecorder()
h.ServeHTTP(resolveRec, resolveReq)
if resolveRec.Code != http.StatusOK {
@@ -292,14 +375,20 @@ func TestAutomationIssueEndpointsAndActiveDeleteConflict(t *testing.T) {
// TestAutomationRuleNoActions 缺动作 400。
func TestAutomationRuleNoActions(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -307,23 +396,32 @@ func TestAutomationRuleNoActions(t *testing.T) {
}
}
// TestAutomationRuleRejectsIncompatibleTriggerActions 负责Test自动化规则RejectsIncompatibleTrigger动作列表相关处理。
func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// cardID、err 保存卡密ID、err,供当前处理流程使用
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{Name: "card", Type: "text", TextContent: "x", Enabled: true, UserID: 1})
if err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// tests 保存tests,供当前处理流程使用
tests := []string{
`{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":"x"}]}`,
`{"cookie_id":"acc1","trigger_type":"buyer_reviewed","actions":[{"action_type":"confirm_shipment"}]}`,
`{"cookie_id":"acc1","trigger_type":"review_missing_timeout","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`,
}
// body 表示当前遍历过程中的请求体
for _, body := range tests {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -334,13 +432,18 @@ func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
// TestAutomationRuleBadJSON 非法 JSON 400。
func TestAutomationRuleBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -350,14 +453,20 @@ func TestAutomationRuleBadJSON(t *testing.T) {
// TestAutomationRuleUpdateBadID 无效 ID 400。
func TestAutomationRuleUpdateBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/automation-rules/abc", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -367,13 +476,18 @@ func TestAutomationRuleUpdateBadID(t *testing.T) {
// TestAutomationRuleDeleteBadID 无效 ID 400。
func TestAutomationRuleDeleteBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -383,13 +497,18 @@ func TestAutomationRuleDeleteBadID(t *testing.T) {
// TestAutomationRuleDeleteNotFound 不存在规则 404。
func TestAutomationRuleDeleteNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/999999", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -399,25 +518,30 @@ func TestAutomationRuleDeleteNotFound(t *testing.T) {
// TestDefaultAutomationRuleName 默认规则名。
func TestDefaultAutomationRuleName(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
"bogus": "自动化规则",
}
// trigger、want 表示当前遍历过程中的trigger、want
for trigger, want := range cases {
// got 保存got,供当前处理流程使用
got := defaultAutomationRuleName(trigger, "")
if got != want {
t.Errorf("defaultAutomationRuleName(%q)=%q want %q", trigger, got, want)
}
}
if got := defaultAutomationRuleName(automation.TriggerOrderPaid, "item-x"); got != "付款后自动发货 - item-x" {
if // got 保存got,供当前处理流程使用
got := defaultAutomationRuleName(automation.TriggerOrderPaid, "item-x"); got != "付款后自动发货 - item-x" {
t.Errorf("带 itemID 的默认名异常: %q", got)
}
}
// TestIsJSONObject isJSONObject 表驱动。
func TestIsJSONObject(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]bool{
`{}`: true,
`{"a":1}`: true,
@@ -427,8 +551,10 @@ func TestIsJSONObject(t *testing.T) {
`invalid`: false,
``: false,
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := isJSONObject(in); got != want {
if // got 保存got,供当前处理流程使用
got := isJSONObject(in); got != want {
t.Errorf("isJSONObject(%q)=%v want %v", in, got, want)
}
}
@@ -436,10 +562,12 @@ func TestIsJSONObject(t *testing.T) {
// TestFirstNonZero firstNonZero 表驱动。
func TestFirstNonZero(t *testing.T) {
if got := firstNonZero(0, 5); got != 5 {
if // got 保存got,供当前处理流程使用
got := firstNonZero(0, 5); got != 5 {
t.Fatalf("got %d", got)
}
if got := firstNonZero(3, 5); got != 3 {
if // got 保存got,供当前处理流程使用
got := firstNonZero(3, 5); got != 3 {
t.Fatalf("got %d", got)
}
}
+76 -9
View File
@@ -14,6 +14,7 @@ import (
"xianyu-go/internal/db"
)
// mountAutomation 负责mount自动化相关处理。
func (s *Server) mountAutomation(r chi.Router) {
r.Get("/automation-rules", s.listAutomationRules)
r.Post("/automation-rules", s.createAutomationRule)
@@ -24,8 +25,11 @@ func (s *Server) mountAutomation(r chi.Router) {
r.Post("/automation-pending-tasks/{task_id}/resolve", s.resolveDeferredAutomationTask)
}
// listAutomationIssues 负责list自动化问题列表相关处理。
func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// runs、tasks、err 保存runs、tasks、err,供当前处理流程使用
runs, tasks, err := s.Store.Automation.ListIssues(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
@@ -34,21 +38,27 @@ func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, automationIssuesResponse{Runs: runs, PendingTasks: tasks})
}
// resolveAutomationRun 负责resolve自动化运行相关处理。
func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
// runID、err 保存运行ID、err,供当前处理流程使用
runID, err := strconv.ParseInt(chi.URLParam(r, "run_id"), 10, 64)
if err != nil || runID <= 0 {
writeErr(w, http.StatusBadRequest, "无效运行ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Resolution string `json:"resolution"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "异常运行不存在或已处理")
return
@@ -59,27 +69,34 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// resolveDeferredAutomationTask 负责resolveDeferred自动化任务相关处理。
func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Request) {
// taskID、err 保存任务ID、err,供当前处理流程使用
taskID, err := strconv.ParseInt(chi.URLParam(r, "task_id"), 10, 64)
if err != nil || taskID <= 0 {
writeErr(w, http.StatusBadRequest, "无效任务ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Resolution string `json:"resolution"`
}
if err := decodeJSON(r, &req); err != nil || (req.Resolution != "retry" && req.Resolution != "dismiss") {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || (req.Resolution != "retry" && req.Resolution != "dismiss") {
writeErr(w, http.StatusBadRequest, "处理方式必须是 retry 或 dismiss")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution == "retry"); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution == "retry"); err != nil {
writeErr(w, http.StatusNotFound, "异常任务不存在或已处理")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// automationActionRequest 保存自动化动作请求,供当前处理流程使用
type automationActionRequest struct {
ActionType string `json:"action_type"`
CardID int64 `json:"card_id"`
@@ -91,6 +108,7 @@ type automationActionRequest struct {
SortOrder int `json:"sort_order"`
}
// automationRuleRequest 保存自动化规则请求,供当前处理流程使用
type automationRuleRequest struct {
CookieID string `json:"cookie_id"`
ItemID string `json:"item_id"`
@@ -102,11 +120,16 @@ type automationRuleRequest struct {
Actions []automationActionRequest `json:"actions"`
}
// listAutomationRules 负责list自动化规则列表相关处理。
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// query 保存查询,供当前处理流程使用
query := r.URL.Query()
// paginated 保存paginated,供当前处理流程使用
_, paginated := query["page"]
if !paginated {
// rules、err 保存rules、err,供当前处理流程使用
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
@@ -116,7 +139,9 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
// page 保存页码,供当前处理流程使用
page := atoiDefault(query.Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
pageSize := atoiDefault(query.Get("page_size"), 10)
if page < 1 {
page = 1
@@ -127,6 +152,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
if pageSize > 100 {
pageSize = 100
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := strings.TrimSpace(query.Get("cookie_id"))
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
@@ -134,6 +160,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
}
// triggerType 保存trigger类型,供当前处理流程使用
triggerType := strings.TrimSpace(query.Get("trigger_type"))
if triggerType != "" {
switch triggerType {
@@ -143,8 +170,11 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
}
// enabled 保存启用状态,供当前处理流程使用
var enabled *bool
if rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
if // rawEnabled 保存原始启用状态,供当前处理流程使用
rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
// value、parseErr 保存value、parseErr,供当前处理流程使用
value, parseErr := strconv.ParseBool(rawEnabled)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
@@ -153,6 +183,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
enabled = &value
}
// rules、total、err 保存rules、total、err,供当前处理流程使用
rules, total, err := s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
@@ -161,15 +192,18 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
// filter 保存filter,供当前处理流程使用
filter := db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"),
}
// triggerCounts、err 保存triggerCounts、err,供当前处理流程使用
triggerCounts, err := s.Store.Automation.CountByTriggerForUser(r.Context(), filter)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计自动化规则失败")
return
}
// totalPages 保存总数Pages,供当前处理流程使用
totalPages := (total + pageSize - 1) / pageSize
if totalPages > 0 && page > totalPages {
page = totalPages
@@ -188,10 +222,15 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
})
}
// automationRulesJSON 负责自动化规则列表JSON相关处理。
func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse {
// out 保存out,供当前处理流程使用
out := make([]automationRuleResponse, 0, len(rules))
// rule 表示当前遍历过程中的规则
for _, rule := range rules {
// actions 保存动作列表,供当前处理流程使用
actions := make([]automationActionResponse, 0, len(rule.Actions))
// action 表示当前遍历过程中的动作
for _, action := range rule.Actions {
actions = append(actions, automationActionResponse{
ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName,
@@ -211,17 +250,22 @@ func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse {
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Automation.Create(r.Context(), in)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
@@ -230,24 +274,31 @@ func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateAutomationRule 负责update自动化规则相关处理。
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if err := s.Store.Automation.Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
@@ -258,14 +309,18 @@ func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAutomationRule 负责delete自动化规则相关处理。
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.Delete(r.Context(), sess.UserID, ruleID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.Delete(r.Context(), sess.UserID, ruleID); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
@@ -280,6 +335,7 @@ func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// normalizeAutomationRuleRequest 负责normalize自动化规则请求相关处理。
func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) {
req.CookieID = strings.TrimSpace(req.CookieID)
req.ItemID = strings.TrimSpace(req.ItemID)
@@ -299,6 +355,7 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if req.Priority <= 0 {
req.Priority = 100
}
// config 保存配置,供当前处理流程使用
config := req.ConfigJSON
if config == "" {
config = "{}"
@@ -312,9 +369,13 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if req.Name == "" {
req.Name = defaultAutomationRuleName(req.TriggerType, req.ItemID)
}
// actions 保存动作列表,供当前处理流程使用
actions := make([]db.AutomationActionInput, 0, len(req.Actions))
// hasSendCard、hasSendText、hasConfirmShipment 保存hasSendCard、hasSendText、hasConfirmShipment,供当前处理流程使用
hasSendCard, hasSendText, hasConfirmShipment := false, false, false
// i、act 表示当前遍历过程中的i、act
for i, act := range req.Actions {
// enabled 保存启用状态,供当前处理流程使用
enabled := true
if act.Enabled != nil {
enabled = *act.Enabled
@@ -327,6 +388,7 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if act.CardID <= 0 {
return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组")
}
// card、cardErr 保存card、cardErr,供当前处理流程使用
card, cardErr := s.Store.Cards.Get(r.Context(), act.CardID)
if cardErr != nil || card.UserID != userID {
return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户")
@@ -388,7 +450,9 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
}, nil
}
// defaultAutomationRuleName 负责default自动化规则名称相关处理。
func defaultAutomationRuleName(triggerType, itemID string) string {
// name 保存名称,供当前处理流程使用
name := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
@@ -403,11 +467,14 @@ func defaultAutomationRuleName(triggerType, itemID string) string {
return name
}
// isJSONObject 负责isJSONObject相关处理。
func isJSONObject(s string) bool {
// m 保存m,供当前处理流程使用
var m map[string]any
return json.Unmarshal([]byte(s), &m) == nil
}
// firstNonZero 负责firstNonZero相关处理。
func firstNonZero(v, fallback int) int {
if v != 0 {
return v
+29 -3
View File
@@ -12,8 +12,10 @@ import (
"xianyu-go/internal/db"
)
// maxCardBatchRows 保存max卡密批次Rows,供当前处理流程使用
const maxCardBatchRows = 200
// cardBatchResultRow 保存卡密批次结果Row,供当前处理流程使用
type cardBatchResultRow struct {
RowNo int `json:"row_no"`
Success bool `json:"success"`
@@ -25,19 +27,23 @@ type cardBatchResultRow struct {
// batchCreateCards 上传表格批量创建卡密组。每行一个组定义。
func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// 表格最大 5 MiB(卡密组定义都很小)。
r.Body = http.MaxBytesReader(w, r.Body, maxCardBatchUploadBytes)
if err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil {
if // err 保存err,供当前处理流程使用
err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil {
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
return
}
// source、sourceHeader、err 保存source、sourceHeader、err,供当前处理流程使用
source, sourceHeader, err := r.FormFile("file")
if err != nil {
writeErr(w, http.StatusBadRequest, "缺少卡密表格文件")
return
}
defer source.Close()
// sourceBytes、tooLarge、err 保存sourceBytes、tooLarge、err,供当前处理流程使用
sourceBytes, tooLarge, err := readLimitedBytes(source, 5<<20)
if err != nil {
writeErr(w, http.StatusBadRequest, "读取卡密表格失败")
@@ -47,10 +53,12 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "卡密表格不能超过 5 MiB")
return
}
// sourceName 保存source名称,供当前处理流程使用
sourceName := safeBaseName(sourceHeader.Filename)
if sourceName == "" {
sourceName = "cards.csv"
}
// maps、err 保存maps、err,供当前处理流程使用
maps, err := parsePublishSheetBytesWithLimit(sourceBytes, sourceName, maxCardBatchRows)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -61,12 +69,19 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
return
}
// results 保存results,供当前处理流程使用
results := make([]cardBatchResultRow, 0, len(maps))
// created、failed 保存created、failed,供当前处理流程使用
created, failed := 0, 0
// i、m 表示当前遍历过程中的i、m
for i, m := range maps {
// rowNo 保存rowNo,供当前处理流程使用
rowNo := i + 2
// name 保存名称,供当前处理流程使用
name := strings.TrimSpace(firstImportString(m, "name", "名称", "卡密组名称", "卡密名称"))
// cardType 保存卡密类型,供当前处理流程使用
cardType := strings.ToLower(strings.TrimSpace(firstImportString(m, "type", "类型", "卡密类型")))
// content 保存内容,供当前处理流程使用
content := firstImportString(m, "content", "内容", "卡密内容")
// 校验
@@ -91,6 +106,7 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
failed++
continue
}
// delaySeconds 保存延迟秒数,供当前处理流程使用
delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0)
if delaySeconds < 0 || delaySeconds > 3600 {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 3600 秒之间"})
@@ -98,6 +114,7 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
continue
}
// cf 保存cf,供当前处理流程使用
cf := &db.CardFull{
Name: name,
Type: cardType,
@@ -109,7 +126,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
SpecValue: firstImportString(m, "spec_value", "规格值"),
UserID: sess.UserID,
}
if v := firstImportString(m, "enabled", "启用"); v != "" {
if // v 保存v,供当前处理流程使用
v := firstImportString(m, "enabled", "启用"); v != "" {
cf.Enabled = parseLooseBool(v)
}
switch cardType {
@@ -121,6 +139,7 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
cf.ImageURL = content
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Cards.Create(r.Context(), cf)
if err != nil {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "创建失败: " + err.Error()})
@@ -142,24 +161,30 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
// appendCardData 往 data 类型卡密组追加卡密号(按行)。
func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Content string `json:"content"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// content 保存内容,供当前处理流程使用
content := strings.TrimSpace(req.Content)
if content == "" {
writeErr(w, http.StatusBadRequest, "内容为空")
return
}
// cf、err 保存cf、err,供当前处理流程使用
cf, err := s.Store.Cards.Get(r.Context(), id)
if err != nil {
writeErr(w, http.StatusNotFound, "卡券不存在")
@@ -173,6 +198,7 @@ func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "只有 data(批量卡密)类型支持追加卡密")
return
}
// added、err 保存added、err,供当前处理流程使用
added, err := s.Store.Cards.AppendBatchData(r.Context(), id, content)
if err != nil {
writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error())
+30 -4
View File
@@ -23,8 +23,11 @@ func (s *Server) mountCardsReal(r chi.Router) {
r.Delete("/cards/{card_id}", s.deleteCard)
}
// listCards 负责list卡密列表相关处理。
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// cards、err 保存cards、err,供当前处理流程使用
cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -33,12 +36,15 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newCardResponses(cards))
}
// getCard 负责get卡密相关处理。
func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// cf、ok 保存cf、ok,供当前处理流程使用
cf, ok := s.requireCardOwner(w, r, id)
if !ok {
return
@@ -46,8 +52,11 @@ func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newCardResponse(*cf))
}
// createCard 负责create卡密相关处理。
func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// cf、err 保存cf、err,供当前处理流程使用
cf, err := decodeCard(r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -58,6 +67,7 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Cards.Create(r.Context(), cf)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建失败")
@@ -66,17 +76,21 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateCard 负责update卡密相关处理。
func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// cf、err 保存cf、err,供当前处理流程使用
cf, err := decodeCard(r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// existing、ok 保存existing、ok,供当前处理流程使用
existing, ok := s.requireCardOwner(w, r, id)
if !ok {
return
@@ -87,30 +101,37 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
}
cf.ID = id
cf.UserID = existing.UserID
if err := s.Store.Cards.Update(r.Context(), cf); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cards.Update(r.Context(), cf); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteCard 负责delete卡密相关处理。
func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
if _, ok := s.requireCardOwner(w, r, id); !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := s.requireCardOwner(w, r, id); !ok {
return
}
if err := s.Store.Cards.Delete(r.Context(), id); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cards.Delete(r.Context(), id); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// decodeCard 负责decode卡密相关处理。
func decodeCard(r *http.Request) (*db.CardFull, error) {
// req 保存req,供当前处理流程使用
var req struct {
Name string `json:"name"`
Type string `json:"type"`
@@ -125,7 +146,8 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
SpecName string `json:"spec_name"`
SpecValue string `json:"spec_value"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
return nil, err
}
if req.Name == "" || req.Type == "" {
@@ -163,6 +185,7 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
// itemOwnedByUser 校验 cookieID 归属当前用户且其下存在 itemID 商品。
// 由自动化规则校验复用(原 deliveryRuleItemOwned,发货规则删除后改名)。
// itemOwnedByUser 负责商品OwnedBy用户相关处理。
func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID string) bool {
if itemID == "" {
return true
@@ -178,8 +201,11 @@ func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID
return err == nil
}
// errStr 负责errStr相关处理。
func errStr(s string) error { return &simpleError{s} }
// simpleError 保存simple错误,供当前处理流程使用
type simpleError struct{ msg string }
// Error 负责错误相关处理。
func (e *simpleError) Error() string { return e.msg }
+33 -3
View File
@@ -15,20 +15,27 @@ import (
"xianyu-go/internal/db"
)
// TestChatHistoryAndAccountTaskSettingsEndpoints 负责Test聊天HistoryAnd账号任务设置Endpoints相关处理。
func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServerWithChat(t)
defer cleanup()
// handler 保存handler,供当前处理流程使用
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, handler)
// err 保存err,供当前处理流程使用
_, _, err := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲"},
db.ChatMessage{MessageKey: "platform-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家甲", MessageType: "text", Content: "你好", Status: "received", SentAt: 1000}, true)
if err != nil {
t.Fatal(err)
}
// request 保存请求,供当前处理流程使用
request := httptest.NewRequest(http.MethodGet, "/api/chat/sessions?account_id=acc1", nil)
request.AddCookie(cookie)
// recorder 保存recorder,供当前处理流程使用
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "买家甲") {
@@ -53,50 +60,70 @@ func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "交易愉快") {
t.Fatalf("task settings status=%d body=%s", recorder.Code, recorder.Body.String())
}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := store.AccountTasks.Get(context.Background(), "acc1")
if err != nil || !settings.AutoRateEnabled || !settings.AutoPolishEnabled || settings.PolishTime != "04:30" {
t.Fatalf("settings=%+v err=%v", settings, err)
}
}
// TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents 负责Test聊天WebSocketStreamsOnlyAuthenticated账号Events相关处理。
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// service 保存service,供当前处理流程使用
service := srv.chat
// handler 保存handler,供当前处理流程使用
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, handler)
// httpServer 保存httpServer,供当前处理流程使用
httpServer := httptest.NewServer(handler)
defer httpServer.Close()
// header 保存header,供当前处理流程使用
header := make(http.Header)
header.Set("Cookie", cookie.String())
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// conn、err 保存conn、err,供当前处理流程使用
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
// ready 保存ready,供当前处理流程使用
var ready map[string]any
if err := wsjson.Read(ctx, conn, &ready); err != nil || ready["type"] != "ready" {
if // err 保存err,供当前处理流程使用
err := wsjson.Read(ctx, conn, &ready); err != nil || ready["type"] != "ready" {
t.Fatalf("ready=%+v err=%v", ready, err)
}
if _, _, err := service.RecordIncoming(ctx, chat.Incoming{AccountID: "acc1", ChatID: "chat-live", BuyerID: "buyer",
if // err 保存err,供当前处理流程使用
_, _, err := service.RecordIncoming(ctx, chat.Incoming{AccountID: "acc1", ChatID: "chat-live", BuyerID: "buyer",
BuyerName: "实时买家", Text: "实时消息", Raw: map[string]any{"messageId": "live-1"}}); err != nil {
t.Fatal(err)
}
// event 保存event,供当前处理流程使用
var event chat.Event
if err := wsjson.Read(ctx, conn, &event); err != nil || event.Type != "message.created" || event.Message.Content != "实时消息" {
if // err 保存err,供当前处理流程使用
err := wsjson.Read(ctx, conn, &event); err != nil || event.Type != "message.created" || event.Message.Content != "实时消息" {
t.Fatalf("event=%+v err=%v", event, err)
}
}
// TestChatAndTaskEndpointsEnforceOwnershipAndValidation 负责Test聊天And任务EndpointsEnforceOwnershipAndValidation相关处理。
func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// handler 保存handler,供当前处理流程使用
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, handler)
// cases 保存cases,供当前处理流程使用
cases := []struct {
method, path, body string
want int
@@ -106,10 +133,13 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"","auto_polish_enabled":false,"polish_time":"03:00"}`, http.StatusBadRequest},
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":false,"rate_content":"x","auto_polish_enabled":true,"polish_time":"25:99"}`, http.StatusBadRequest},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
// request 保存请求,供当前处理流程使用
request := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(cookie)
// recorder 保存recorder,供当前处理流程使用
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != tc.want {
+96 -15
View File
@@ -19,6 +19,7 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// mountChat 负责mount聊天相关处理。
func (s *Server) mountChat(r chi.Router) {
r.Get("/api/chat/sessions", s.listChatSessions)
r.Get("/api/chat/messages", s.listChatMessages)
@@ -28,30 +29,43 @@ func (s *Server) mountChat(r chi.Router) {
r.Get("/api/chat/ws", s.chatWebSocket)
}
// listChatSessions 负责list聊天Sessions相关处理。
func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// accountID 保存账号ID,供当前处理流程使用
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// cursor 保存游标,供当前处理流程使用
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
// refresh 保存refresh,供当前处理流程使用
refresh := r.URL.Query().Get("refresh") == "1"
// hasMore 保存hasMore,供当前处理流程使用
var hasMore bool
// nextCursor 保存next游标,供当前处理流程使用
var nextCursor int64
if err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil {
writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败")
return
}
if refresh && s.chat != nil && s.Manager != nil {
if sender, ok := s.Manager.GetInstance(accountID); ok {
if fetcher, ok := sender.(interface {
if // sender、ok 保存sender、ok,供当前处理流程使用
sender, ok := s.Manager.GetInstance(accountID); ok {
if // fetcher、ok 保存fetcher、ok,供当前处理流程使用
fetcher, ok := sender.(interface {
FetchChatConversations(context.Context, int64, int) (map[string]any, string, error)
}); ok {
// fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
// body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用
body, myID, fetchErr := fetcher.FetchChatConversations(fetchCtx, cursor, 100)
cancel()
if fetchErr == nil {
// page、saveErr 保存page、saveErr,供当前处理流程使用
page, saveErr := s.chat.RecordConversationPage(r.Context(), accountID, myID, body)
if saveErr != nil {
writeErr(w, http.StatusInternalServerError, "保存历史联系人失败")
@@ -64,13 +78,16 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
}
}
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200))
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取聊天会话失败")
return
}
if refresh {
if cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil {
if // cookieValue、cookieErr 保存登录凭证Value、cookieErr,供当前处理流程使用
cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil {
// client、canResolve 保存client、canResolve,供当前处理流程使用
client, canResolve := s.mtopClient().(interface {
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
})
@@ -78,18 +95,27 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
return
}
// resolveCtx、resolveCancel 保存resolveCtx、resolve取消,供当前处理流程使用
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
defer resolveCancel()
// jobs 保存jobs,供当前处理流程使用
jobs := make(chan int)
// workers 保存workers,供当前处理流程使用
var workers sync.WaitGroup
// sessionOnce 保存会话Once,供当前处理流程使用
var sessionOnce sync.Once
// sessionErr 保存会话Err,供当前处理流程使用
var sessionErr error
for worker := 0; worker < 8; worker++ {
for // worker 保存工作器,供当前处理流程使用
worker := 0; worker < 8; worker++ {
workers.Add(1)
go func() {
defer workers.Done()
// index 表示当前遍历过程中的index
for index := range jobs {
// infoCtx、cancel 保存infoCtx、cancel,供当前处理流程使用
infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second)
// info、infoErr 保存info、infoErr,供当前处理流程使用
info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID)
cancel()
if mtop.IsSessionExpiredErr(infoErr) {
@@ -102,7 +128,8 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
if infoErr != nil || info == nil {
continue
}
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
if // nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(info.Nickname); nickname != "" {
rows[index].BuyerName = nickname
}
if info.AvatarURL != "" {
@@ -114,6 +141,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
}()
}
queue:
// index 表示当前遍历过程中的index
for index := range rows {
if rows[index].BuyerID == "1400" {
continue
@@ -134,18 +162,23 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
}
// sendChatImage 负责send聊天图片相关处理。
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
if s.chat == nil || s.Manager == nil {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
return
}
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
if err := r.ParseMultipartForm(10 << 20); err != nil {
if // err 保存err,供当前处理流程使用
err := r.ParseMultipartForm(10 << 20); err != nil {
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
return
}
// accountID 保存账号ID,供当前处理流程使用
accountID := strings.TrimSpace(r.FormValue("account_id"))
// chatID 保存聊天ID,供当前处理流程使用
chatID := strings.TrimSpace(r.FormValue("chat_id"))
// buyerID 保存买家ID,供当前处理流程使用
buyerID := strings.TrimSpace(r.FormValue("buyer_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
@@ -155,25 +188,30 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "会话和买家不能为空")
return
}
// file、header、err 保存file、header、err,供当前处理流程使用
file, header, err := r.FormFile("image")
if err != nil {
writeErr(w, http.StatusBadRequest, "请选择图片")
return
}
defer file.Close()
// contentType 保存内容类型,供当前处理流程使用
contentType := header.Header.Get("Content-Type")
if !strings.HasPrefix(strings.ToLower(contentType), "image/") {
writeErr(w, http.StatusBadRequest, "只支持图片文件")
return
}
// data、err 保存data、err,供当前处理流程使用
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
if err != nil || len(data) == 0 || len(data) > 10<<20 {
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
return
}
// session 保存会话,供当前处理流程使用
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")}
// sent、err 保存sent、err,供当前处理流程使用
sent, err := s.communicationApplication().SendChatImage(r.Context(), chatImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
if err != nil {
if errors.Is(err, errCommunicationUnavailable) {
@@ -192,9 +230,13 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
}
// listChatMessages 负责list聊天消息列表相关处理。
func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// accountID 保存账号ID,供当前处理流程使用
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
// chatID 保存聊天ID,供当前处理流程使用
chatID := strings.TrimSpace(r.URL.Query().Get("chat_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
@@ -204,26 +246,37 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 chat_id")
return
}
// beforeID 保存beforeID,供当前处理流程使用
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before_id"), 10, 64)
// cursor 保存游标,供当前处理流程使用
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
// limit 保存上限,供当前处理流程使用
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
if s.chat != nil && s.Manager != nil {
if sender, ok := s.Manager.GetInstance(accountID); ok {
if fetcher, ok := sender.(interface {
if // sender、ok 保存sender、ok,供当前处理流程使用
sender, ok := s.Manager.GetInstance(accountID); ok {
if // fetcher、ok 保存fetcher、ok,供当前处理流程使用
fetcher, ok := sender.(interface {
FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error)
}); ok {
// fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
// body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用
body, myID, fetchErr := fetcher.FetchChatHistory(fetchCtx, chatID, cursor, limit)
cancel()
if fetchErr == nil {
// sessions 保存sessions,供当前处理流程使用
sessions, _ := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500)
// current 保存current,供当前处理流程使用
var current db.ChatSession
// candidate 表示当前遍历过程中的candidate
for _, candidate := range sessions {
if candidate.ChatID == chatID {
current = candidate
break
}
}
// page、saveErr 保存page、saveErr,供当前处理流程使用
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, current, body)
if saveErr != nil {
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
@@ -236,6 +289,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
}
}
}
// page、err 保存page、err,供当前处理流程使用
page, err := s.communicationApplication().ListStoredChatMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取聊天消息失败")
@@ -244,18 +298,24 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(page.Session)})
}
// resolveSelectedChatIdentity 负责resolveSelected聊天Identity相关处理。
func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession {
if session.BuyerID != "1400" {
// cookies、cookieErr 保存cookies、cookieErr,供当前处理流程使用
cookies, cookieErr := s.Store.Cookies.GetValue(ctx, accountID)
// client、supported 保存client、supported,供当前处理流程使用
client, supported := s.mtopClient().(interface {
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
})
if cookieErr == nil && supported {
// resolveCtx、cancel 保存resolveCtx、cancel,供当前处理流程使用
resolveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
// info、err 保存info、err,供当前处理流程使用
info, err := client.FetchChatUserInfo(resolveCtx, cookies, session.ChatID)
cancel()
if err == nil && info != nil {
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
if // nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(info.Nickname); nickname != "" {
session.BuyerName = nickname
}
if info.AvatarURL != "" {
@@ -270,6 +330,7 @@ func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID stri
return session
}
// sendChatMessageRequest 保存send聊天消息请求,供当前处理流程使用
type sendChatMessageRequest struct {
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
@@ -280,13 +341,16 @@ type sendChatMessageRequest struct {
Text string `json:"text"`
}
// sendChatMessage 负责send聊天消息相关处理。
func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
if s.chat == nil || s.Manager == nil {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
return
}
// input 保存input,供当前处理流程使用
var input sendChatMessageRequest
if err := decodeJSON(r, &input); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &input); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -304,6 +368,7 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符")
return
}
// sent、err 保存sent、err,供当前处理流程使用
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 {
if errors.Is(err, errCommunicationUnavailable) {
@@ -322,7 +387,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
}
// markChatRead 负责mark聊天Read相关处理。
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
// input 保存input,供当前处理流程使用
var input struct {
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
@@ -335,50 +402,60 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.communicationApplication().MarkChatRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().MarkChatRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// chatWebSocket 负责聊天WebSocket相关处理。
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
if s.chat == nil {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// events、unsubscribe、err 保存events、unsubscribe、err,供当前处理流程使用
events, unsubscribe, err := s.chat.Subscribe(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
return
}
defer unsubscribe()
// conn、err 保存conn、err,供当前处理流程使用
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
conn.SetReadLimit(8 << 10)
go func() {
for {
if _, _, readErr := conn.Read(ctx); readErr != nil {
if // readErr 保存readErr,供当前处理流程使用
_, _, readErr := conn.Read(ctx); readErr != nil {
cancel()
return
}
}
}()
if err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
if // err 保存err,供当前处理流程使用
err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
return
}
for {
select {
case <-ctx.Done():
return
case event, ok := <-events:
case // event、ok 保存event、ok,供当前处理流程使用
event, ok := <-events:
if !ok || wsjson.Write(ctx, conn, event) != nil {
return
}
@@ -386,10 +463,12 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
}
}
// ownsAccount 负责owns账号相关处理。
func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
if accountID == "" {
return false
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
owned, err := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, accountID) // owned 和 err 表示账号归属及查询错误。
return err == nil && owned
@@ -399,7 +478,9 @@ func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
账号查询已采用所有权窄接口。
*/
// parsePositiveInt 将正整数文本转换为整数,无法解析时返回备用值。
// parsePositiveInt 负责parsePositiveInt相关处理。
func parsePositiveInt(raw string, fallback int) int {
// value、err 保存value、err,供当前处理流程使用
value, err := strconv.Atoi(raw)
if err != nil || value <= 0 {
return fallback
+1
View File
@@ -188,6 +188,7 @@ func (svc *communicationService) ListNotificationBindings(ctx context.Context, u
}
// result 是按账号分组的通知绑定列表。
result := make(map[string][]notificationBindingRow)
// row 表示当前遍历过程中的row
for _, row := range rows {
// binding 保存当前扫描到的通知绑定记录。
binding := notificationBindingRow{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled}
+141 -29
View File
@@ -40,27 +40,37 @@ func (s *Server) mountCookies(r chi.Router) {
r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration)
}
// getLongLoginSettings 负责getLong登录设置相关处理。
func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := scopedCookieHeader(detail, xrenew.QueryLoginSettingsURL)
// result 保存结果,供当前处理流程使用
var result *xrenew.LongLoginSettings
// requestErr 保存请求Err,供当前处理流程使用
var requestErr error
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies, snapshot)
} else {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies)
}
// credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
@@ -77,34 +87,46 @@ func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// setLongLoginSettings 负责setLong登录设置相关处理。
func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Enabled *bool `json:"enabled"`
}
if err := decodeJSON(r, &req); err != nil || req.Enabled == nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.Enabled == nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := scopedCookieHeader(detail, xrenew.SetLoginSettingsURL)
// result 保存结果,供当前处理流程使用
var result *xrenew.LongLoginSettings
// requestErr 保存请求Err,供当前处理流程使用
var requestErr error
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled, snapshot)
} else {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled)
}
// credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
@@ -123,11 +145,14 @@ func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// persistLongLoginCookies 必须在账号凭证锁内调用。它只更新持久化状态;
// 运行中实例的 Cookie 更新必须等调用方释放凭证锁后再执行。
// persistLongLoginCookies 负责persistLong登录Cookies相关处理。
func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) {
if result == nil || detail == nil {
return false, nil
}
// metadata 保存metadata,供当前处理流程使用
metadata := detail.MetadataJSON
// snapshot、hasSnapshot 保存snapshot、hasSnapshot,供当前处理流程使用
snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if result.CookieSnapshotComplete {
snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot)
@@ -155,22 +180,26 @@ func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieD
result.NewCookies = xrenew.MergeSetCookies(detail.Value, result.SetCookies)
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
}
// credentialChanged 保存credentialChanged,供当前处理流程使用
credentialChanged := result.NewCookies != detail.Value || metadata != detail.MetadataJSON
if !credentialChanged && len(result.SetCookies) == 0 {
return false, nil
}
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err)
return false, err
}
if credentialChanged && s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil {
s.Logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", err)
}
}
return credentialChanged, nil
}
// updateRunningCookie 负责updateRunning登录凭证相关处理。
func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
s.wakeCredentialBlockedAutomation(ctx, cookieID)
// repository 提供运行时更新前的账号启用状态读取。
@@ -178,32 +207,39 @@ func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string
if s.Manager == nil || repository == nil || !repository.GetStatus(ctx, cookieID) {
return
}
if sender, ok := s.Manager.GetInstance(cookieID); ok {
if // sender、ok 保存sender、ok,供当前处理流程使用
sender, ok := s.Manager.GetInstance(cookieID); ok {
sender.UpdateCookie(value)
}
}
// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。
func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
if s == nil || s.Store == nil || s.Store.Automation == nil {
return
}
if err := s.Store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
}
}
// scopedCookieHeader 负责scoped登录凭证Header相关处理。
func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string {
if detail == nil {
return ""
}
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
if header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative {
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
if // header、authoritative 保存header、authoritative,供当前处理流程使用
header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative {
return header
}
}
return detail.Value
}
// updateCookieSettingsRequest 保存update登录凭证设置请求,供当前处理流程使用
type updateCookieSettingsRequest struct {
Cookie *string `json:"cookie"`
Remark *string `json:"remark"`
@@ -218,13 +254,17 @@ type updateCookieSettingsRequest struct {
// updateCookieSettings 原子保存编辑弹窗中的账号字段和通知绑定。
func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// detail、ok 保存detail、ok,供当前处理流程使用
detail, ok := s.requireCookieSecretOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req updateCookieSettingsRequest
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -245,7 +285,9 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latestDetail、err 保存latestDetail、err,供当前处理流程使用
latestDetail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || latestDetail == nil || latestDetail.UserID != detail.UserID {
credentialUnlock()
@@ -254,6 +296,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
}
detail = latestDetail
// input 保存input,供当前处理流程使用
input := db.AccountSettingsUpdate{
UserID: detail.UserID,
Value: req.Cookie,
@@ -262,12 +305,15 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
PauseDuration: req.PauseDuration,
ChannelIDs: req.ChannelIDs,
}
// loginChanged 保存登录Changed,供当前处理流程使用
loginChanged := req.Username != nil || req.LoginPassword != nil || req.ShowBrowser != nil || req.ClearPassword
if loginChanged {
// username 保存username,供当前处理流程使用
username := detail.Username
if req.Username != nil {
username = *req.Username
}
// password 保存密码,供当前处理流程使用
password := detail.Password
if req.LoginPassword != nil && *req.LoginPassword != "" {
password = *req.LoginPassword
@@ -275,6 +321,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
if req.ClearPassword {
password = ""
}
// showBrowser 保存show浏览器,供当前处理流程使用
showBrowser := detail.ShowBrowser
if req.ShowBrowser != nil {
showBrowser = *req.ShowBrowser
@@ -283,6 +330,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
input.Password = &password
input.ShowBrowser = &showBrowser
}
// pausedUntil、err 保存pausedUntil、err,供当前处理流程使用
pausedUntil, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, input)
if err != nil {
credentialUnlock()
@@ -300,14 +348,16 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
// UpdateSettings 已在同一事务中写入 Cookie 并清除旧快照,不能再做
// 第二次非原子覆盖。
if s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", err)
}
}
}
credentialUnlock()
if req.Cookie != nil && s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
}
}
@@ -438,6 +488,7 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
// profile、err 保存profile、err,供当前处理流程使用
profile, err := s.accountLoginApplication().RefreshProfile(r.Context(), sess.UserID, cid)
if err != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
@@ -468,17 +519,21 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
// addCookie 添加账号 cookie。
func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
ID string `json:"id"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" {
writeErr(w, http.StatusBadRequest, "缺少 id 或 value")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if // err 保存err,供当前处理流程使用
err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
return
@@ -495,21 +550,27 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// updateCookie 更新 cookie 值。
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ok 保存ok,供当前处理流程使用
_, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if // err 保存err,供当前处理流程使用
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
@@ -522,11 +583,14 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// detail、ok 保存detail、ok,供当前处理流程使用
detail, ok := s.requireCookieSecretOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Username string `json:"username"`
Password string `json:"password"`
@@ -534,10 +598,12 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
ShowBrowser bool `json:"show_browser"`
ClearPassword bool `json:"clear_password"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// password 保存密码,供当前处理流程使用
password := req.Password
if password == "" {
password = req.LoginPassword
@@ -547,7 +613,8 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
} else if password == "" && detail != nil {
password = detail.Password
}
if err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -556,30 +623,38 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// setCookieStatus 启用/禁用账号。
func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Enabled bool `json:"enabled"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// reason 保存原因,供当前处理流程使用
reason := ""
if !req.Enabled {
reason = db.DisableReasonManual
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil {
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "更新失败")
return
@@ -590,7 +665,8 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
if req.Enabled {
// 重启拉取最新 cookie。
if _, e := s.loadCookiePlatformDetail(r.Context(), cid); e == nil {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("启用后重启账号失败", "cookie_id", cid, "err", err)
}
}
@@ -603,19 +679,24 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// deleteCookie 删除账号。
func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "删除失败")
return
@@ -636,20 +717,24 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
// setCookieAutoConfirm 设置自动确认发货。
func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
AutoConfirm bool `json:"auto_confirm"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
sess := authSess(r)
if _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
if // err 保存err,供当前处理流程使用
_, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
UserID: sess.UserID, AutoConfirm: &req.AutoConfirm,
}); err != nil {
writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败")
@@ -660,7 +745,9 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// getCookieAutoConfirm 获取自动确认发货设置。
func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// d、ok 保存d、ok,供当前处理流程使用
d, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
@@ -670,20 +757,24 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// setCookieRemark 设置备注。
func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Remark string `json:"remark"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
sess := authSess(r)
if _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
if // err 保存err,供当前处理流程使用
_, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
UserID: sess.UserID, Remark: &req.Remark,
}); err != nil {
writeErr(w, http.StatusInternalServerError, "保存账号备注失败")
@@ -694,14 +785,17 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
// setCookiePauseDuration 设置暂停时长。
func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
PauseDuration int `json:"pause_duration"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -709,6 +803,7 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, "暂停时长必须在 0 到 1440 分钟之间")
return
}
// pausedUntil、err 保存pausedUntil、err,供当前处理流程使用
pausedUntil, err := s.Store.Cookies.SetPause(r.Context(), cid, req.PauseDuration)
if err != nil {
writeErr(w, http.StatusInternalServerError, "保存暂停时长失败")
@@ -721,10 +816,12 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
// getCookiePauseDuration 获取暂停时长。
func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// paused、pausedUntil 保存paused、pausedUntil,供当前处理流程使用
paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid)
writeJSON(w, http.StatusOK, pauseDurationResponse{
PauseDuration: s.Store.Cookies.GetPauseDuration(r.Context(), cid), PausedUntil: pausedUntil, Paused: paused,
@@ -733,6 +830,7 @@ func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request)
// refreshAccountProfile 刷新账号平台资料并返回展示字段。
// 该流程按需读取平台凭证,调用方负责所有权校验。
// refreshAccountProfile 负责refresh账号Profile相关处理。
func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) {
if d == nil {
return "", "", ""
@@ -746,7 +844,9 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
if repository == nil {
return cachedAccountNickname(d), d.AvatarURL, "账号登录持久化未初始化"
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := repository.LockCredentials(d.ID)
// latest、latestErr 保存latest、latestErr,供当前处理流程使用
latest, latestErr := repository.LoadPlatformDetail(ctx, d.ID)
if latestErr != nil || latest == nil || latest.UserID != d.UserID {
credentialUnlock()
@@ -755,10 +855,15 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
}
return cachedAccountNickname(d), d.AvatarURL, truncate(latestErr.Error(), 180)
}
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
// profile、callErr 保存profile、callErr,供当前处理流程使用
profile, callErr := s.MTop.FetchUserProfile(mtopCtx, latest.Value)
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
// runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用
runtimeCookieChanged := false
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
if s.Logger != nil {
@@ -774,7 +879,8 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
} else if callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != latest.Value {
// 注入 mock 或没有权威快照的历史账号继续沿用扁平 Cookie 路径;
// 该路径必须清除旧 snapshot,不能伪造完整 Jar。
if err := repository.UpdateFlatCookieOwned(ctx, latest, profile.UpdatedCookies); err != nil {
if // err 保存err,供当前处理流程使用
err := repository.UpdateFlatCookieOwned(ctx, latest, profile.UpdatedCookies); err != nil {
if s.Logger != nil {
s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
}
@@ -800,9 +906,12 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
return cachedAccountNickname(d), d.AvatarURL, "账号资料接口未返回结果"
}
// apiNickname 保存apiNickname,供当前处理流程使用
apiNickname := strings.TrimSpace(profile.Nickname)
// apiAvatarURL 保存apiAvatarURL,供当前处理流程使用
apiAvatarURL := normalizeProfileAvatarURL(profile.AvatarURL)
if err := repository.UpdateProfile(ctx, d.ID, apiNickname, apiAvatarURL); err != nil && s.Logger != nil {
if // err 保存err,供当前处理流程使用
err := repository.UpdateProfile(ctx, d.ID, apiNickname, apiAvatarURL); err != nil && s.Logger != nil {
s.Logger.Warn("保存账号资料失败", "account", d.ID, "err", err)
}
if apiNickname == "" {
@@ -814,6 +923,7 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
return apiNickname, apiAvatarURL, ""
}
// cachedAccountNickname 负责cached账号Nickname相关处理。
func cachedAccountNickname(d *db.CookieDetail) string {
if strings.TrimSpace(d.Remark) != "" {
return strings.TrimSpace(d.Remark)
@@ -824,6 +934,7 @@ func cachedAccountNickname(d *db.CookieDetail) string {
return "账号 " + truncate(d.ID, 6)
}
// normalizeProfileAvatarURL 负责normalizeProfileAvatarURL相关处理。
func normalizeProfileAvatarURL(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -838,6 +949,7 @@ func normalizeProfileAvatarURL(raw string) string {
return raw
}
// truncate 负责truncate相关处理。
func truncate(s string, n int) string {
if len(s) <= n {
return s
File diff suppressed because it is too large. Load diff
+49 -4
View File
@@ -11,15 +11,20 @@ import (
// TestListDefaultReplies 列表(数组形式)。
func TestListDefaultReplies(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好","reply_once":false}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -29,11 +34,13 @@ func TestListDefaultReplies(t *testing.T) {
// 列表(数组)。
req2 := httptest.NewRequest(http.MethodGet, "/default-replies", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["reply_content"] != "你好" {
@@ -43,11 +50,13 @@ func TestListDefaultReplies(t *testing.T) {
// 列表(map 形式,兼容路径)。
req3 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("map status=%d", rec3.Code)
}
// m 保存m,供当前处理流程使用
var m map[string]map[string]any
json.Unmarshal(rec3.Body.Bytes(), &m)
if m["acc1"]["reply_content"] != "你好" {
@@ -57,13 +66,18 @@ func TestListDefaultReplies(t *testing.T) {
// TestSetDefaultReplyBadJSON 非法 JSON 400。
func TestSetDefaultReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -71,14 +85,20 @@ func TestSetDefaultReplyBadJSON(t *testing.T) {
}
}
// TestGetDefaultReplyMissingAccountIsNotFound 负责TestGetDefault回复Missing账号IsNotFound相关处理。
func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/default-replies/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -86,19 +106,26 @@ func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
}
}
// TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault 负责TestGetDefault回复Existing账号Without配置ReturnsDefault相关处理。
func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["enabled"] != false || got["reply_content"] != "" {
@@ -106,25 +133,35 @@ func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T)
}
}
// TestGetDefaultReplyRejectsCrossUserAccount 负责TestGetDefault回复RejectsCross用户账号相关处理。
func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if _, err := store.Users.Create(ctx, "default-other", "default-other@example.com", "pw"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.Users.Create(ctx, "default-other", "default-other@example.com", "pw"); err != nil {
t.Fatalf("create other user: %v", err)
}
// other、err 保存other、err,供当前处理流程使用
other, err := store.Users.GetByUsername(ctx, "default-other")
if err != nil {
t.Fatalf("get other user: %v", err)
}
if err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", other.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", other.ID); err != nil {
t.Fatalf("save other cookie: %v", err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/default-replies/other-acc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -134,21 +171,27 @@ func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
// TestDeleteDefaultReply 删除。
func TestDeleteDefaultReply(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// 删除。
req2 := httptest.NewRequest(http.MethodDelete, "/default-replies/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -168,10 +211,12 @@ func TestBtoi(t *testing.T) {
// TestNullIfEmpty nullIfEmpty 表驱动。
func TestNullIfEmpty(t *testing.T) {
if v := nullIfEmpty(""); v != nil {
if // v 保存v,供当前处理流程使用
v := nullIfEmpty(""); v != nil {
t.Fatalf("空串应为 nil,got %v", v)
}
if v := nullIfEmpty("x"); v != "x" {
if // v 保存v,供当前处理流程使用
v := nullIfEmpty("x"); v != "x" {
t.Fatalf("非空应原样返回,got %v", v)
}
}
@@ -38,11 +38,14 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
r.Post("/api/default-reply/{cid}/clear-records", s.clearDefaultReplyRecords)
}
// getDefaultReply 负责getDefault回复相关处理。
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// dr、err 保存dr、err,供当前处理流程使用
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
if err != nil {
writeJSON(w, http.StatusOK, defaultReplyResponse{Enabled: false, ReplyContent: "", ReplyOnce: false})
@@ -95,6 +98,7 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
}
// out 是默认回复列表响应。
var out []defaultReplyResponse
// row 表示当前遍历过程中的row
for _, row := range rows {
out = append(out, defaultReplyResponse{
CookieID: row.CookieID, Enabled: row.Enabled, ReplyContent: row.ReplyContent, ReplyOnce: row.ReplyOnce,
@@ -117,6 +121,7 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
}
// out 是按账号标识索引的默认回复映射。
out := make(map[string]defaultReplyResponse)
// row 表示当前遍历过程中的row
for _, row := range rows {
out[row.CookieID] = defaultReplyResponse{
CookieID: row.CookieID,
+33 -2
View File
@@ -15,13 +15,17 @@ func loginHelper(t *testing.T, h http.Handler) *http.Cookie {
return loginAsHelper(t, h, "admin", "pw")
}
// loginAsHelper 负责登录AsHelper相关处理。
func loginAsHelper(t *testing.T, h http.Handler, username, password string) *http.Cookie {
t.Helper()
// body、err 保存body、err,供当前处理流程使用
body, err := json.Marshal(map[string]string{"username": username, "password": password})
if err != nil {
t.Fatal(err)
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(string(body)))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || len(rec.Result().Cookies()) == 0 {
@@ -32,24 +36,30 @@ func loginAsHelper(t *testing.T, h http.Handler, username, password string) *htt
// TestOrderListAndDetail 订单列表 + 详情 + 状态码归一。
func TestOrderListAndDetail(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 插入一条订单(order_status 用数字码 "2" 测试归一)。
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('ord1','item1','buyer1','2','acc1')`)
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 列表。
req := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("list status=%d body=%s", rec.Code, rec.Body.String())
}
// resp 保存resp,供当前处理流程使用
var resp struct {
Success bool `json:"success"`
Total int `json:"total"`
@@ -72,11 +82,13 @@ func TestOrderListAndDetail(t *testing.T) {
// 详情。
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("detail status=%d", rec2.Code)
}
// det 保存det,供当前处理流程使用
var det map[string]any
json.Unmarshal(rec2.Body.Bytes(), &det)
if det["order_id"] != "ord1" {
@@ -89,38 +101,49 @@ func TestOrderListAndDetail(t *testing.T) {
// 删除。
req3 := httptest.NewRequest(http.MethodDelete, "/api/orders/ord1", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("delete status=%d", rec3.Code)
}
// deletedAt 保存deletedAt,供当前处理流程使用
var deletedAt string
if err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "ord1").Scan(&deletedAt); err != nil || deletedAt == "" {
if // err 保存err,供当前处理流程使用
err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "ord1").Scan(&deletedAt); err != nil || deletedAt == "" {
t.Fatalf("订单删除应为逻辑删除,deleted_at=%q err=%v", deletedAt, err)
}
if _, err := store.Orders.Get(ctx, "ord1"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(ctx, "ord1"); err == nil {
t.Fatal("逻辑删除订单不应再出现在活动订单查询中")
}
}
// TestCardCRUD 卡券增删改查。
func TestCardCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 创建。
body := `{"name":"测试卡","type":"text","text_content":"卡密ABC","enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
id := cr["id"].(float64)
if id == 0 {
t.Fatal("应返回 id")
@@ -129,8 +152,10 @@ func TestCardCRUD(t *testing.T) {
// 列表。
req2 := httptest.NewRequest(http.MethodGet, "/cards", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["name"] != "测试卡" {
@@ -139,8 +164,10 @@ func TestCardCRUD(t *testing.T) {
// 更新。
updBody := `{"name":"改名卡","type":"text","text_content":"卡密XYZ","enabled":true}`
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodPut, "/cards/"+itoa(int64(id)), strings.NewReader(updBody))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -150,8 +177,10 @@ func TestCardCRUD(t *testing.T) {
// 获取验证改名。
req4 := httptest.NewRequest(http.MethodGet, "/cards/"+itoa(int64(id)), nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec4.Body.Bytes(), &got)
if got["name"] != "改名卡" {
@@ -161,6 +190,7 @@ func TestCardCRUD(t *testing.T) {
// 删除。
req5 := httptest.NewRequest(http.MethodDelete, "/cards/"+itoa(int64(id)), nil)
req5.AddCookie(cookie)
// rec5 保存rec5,供当前处理流程使用
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
if rec5.Code != 200 {
@@ -168,4 +198,5 @@ func TestCardCRUD(t *testing.T) {
}
}
// itoa 负责itoa相关处理。
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
+114 -4
View File
@@ -11,15 +11,20 @@ import (
// TestKeywordsCRUD 关键字增删查。
func TestKeywordsCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 添加(普通 + 商品ID)。
post := func(body string) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -32,8 +37,10 @@ func TestKeywordsCRUD(t *testing.T) {
// 列表(带类型)。
req := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 2 {
@@ -43,6 +50,7 @@ func TestKeywordsCRUD(t *testing.T) {
// 按索引删除第一条。
req2 := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/0", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -52,15 +60,20 @@ func TestKeywordsCRUD(t *testing.T) {
// TestDefaultReplyCRUD 默认回复。
func TestDefaultReplyCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好老板","reply_once":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -70,8 +83,10 @@ func TestDefaultReplyCRUD(t *testing.T) {
// 读取。
req2 := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// dr 保存dr,供当前处理流程使用
var dr map[string]any
json.Unmarshal(rec2.Body.Bytes(), &dr)
if dr["enabled"] != true || dr["reply_content"] != "你好老板" || dr["reply_once"] != true {
@@ -81,22 +96,28 @@ func TestDefaultReplyCRUD(t *testing.T) {
// 前端兼容路径:/api/default-reply/* 与 /api/default-replies。
req3 := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(body))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("compat set status=%d", rec3.Code)
}
// req4 保存req4,供当前处理流程使用
req4 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// all 保存all,供当前处理流程使用
var all map[string]map[string]any
json.Unmarshal(rec4.Body.Bytes(), &all)
if all["acc1"]["reply_content"] != "你好老板" {
t.Fatalf("兼容默认回复列表异常: %+v", all)
}
// req5 保存req5,供当前处理流程使用
req5 := httptest.NewRequest(http.MethodPost, "/api/default-reply/acc1/clear-records", nil)
req5.AddCookie(cookie)
// rec5 保存rec5,供当前处理流程使用
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
if rec5.Code != 200 {
@@ -106,28 +127,37 @@ func TestDefaultReplyCRUD(t *testing.T) {
// TestNotificationChannelCRUD 通知渠道 + 绑定。
func TestNotificationChannelCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 创建渠道。
body := `{"name":"我的钉钉","type":"dingtalk","config":"{\"webhook_url\":\"http://x\"}","enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create channel status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
id := int64(cr["id"].(float64))
// 绑定到账号。
bindBody := `{"channel_ids":[` + itoa(id) + `]}`
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(bindBody))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -137,10 +167,13 @@ func TestNotificationChannelCRUD(t *testing.T) {
// 查询绑定。
req3 := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// b 保存b,供当前处理流程使用
var b map[string]any
json.Unmarshal(rec3.Body.Bytes(), &b)
// ids 保存ids,供当前处理流程使用
ids, _ := b["channel_ids"].([]any)
if len(ids) != 1 {
t.Fatalf("绑定数异常: %+v", b)
@@ -149,38 +182,49 @@ func TestNotificationChannelCRUD(t *testing.T) {
// TestSystemSettings 系统设置。
func TestSystemSettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 公开设置无需登录。
req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("public settings status=%d", rec.Code)
}
// pub 保存pub,供当前处理流程使用
var pub map[string]any
json.Unmarshal(rec.Body.Bytes(), &pub)
if _, ok := pub["theme_color"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := pub["theme_color"]; !ok {
t.Fatalf("公开设置应含 theme_color: %+v", pub)
}
// 已认证:设置 + 读取全部。
body := `{"value":"green"}`
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(body))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("set status=%d", rec2.Code)
}
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodGet, "/system-settings", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// all 保存all,供当前处理流程使用
var all map[string]any
json.Unmarshal(rec3.Body.Bytes(), &all)
if all["theme_color"] != "green" {
@@ -190,14 +234,20 @@ func TestSystemSettings(t *testing.T) {
// TestAIReplySettings AI 回复设置。
func TestAIReplySettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"按商品信息回复"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -207,8 +257,10 @@ func TestAIReplySettings(t *testing.T) {
// 账号级设置只包含开关、议价策略和自定义提示词;模型/API Key/URL 走系统设置。
req2 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// cfg 保存cfg,供当前处理流程使用
var cfg map[string]any
json.Unmarshal(rec2.Body.Bytes(), &cfg)
if cfg["ai_enabled"] != true ||
@@ -218,17 +270,22 @@ func TestAIReplySettings(t *testing.T) {
cfg["custom_prompts"] != "按商品信息回复" {
t.Fatalf("AI 设置异常: %+v", cfg)
}
if _, ok := cfg["model_name"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := cfg["model_name"]; ok {
t.Fatalf("账号级 AI 设置不应返回模型: %+v", cfg)
}
if _, ok := cfg["api_key"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := cfg["api_key"]; ok {
t.Fatalf("账号级 AI 设置不应返回 API Key: %+v", cfg)
}
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// all 保存all,供当前处理流程使用
var all map[string]map[string]any
json.Unmarshal(rec3.Body.Bytes(), &all)
if all["acc1"]["ai_enabled"] != true {
@@ -236,19 +293,26 @@ func TestAIReplySettings(t *testing.T) {
}
}
// TestAIReplySettingsRejectInvalidBargainLimits 负责TestAI回复设置RejectInvalidBargainLimits相关处理。
func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
for _, body := range []string{
`{"ai_enabled":true,"max_discount_percent":101,"max_discount_amount":1,"max_bargain_rounds":1}`,
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":-1,"max_bargain_rounds":1}`,
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":1,"max_bargain_rounds":0}`,
} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -257,15 +321,19 @@ func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
}
}
// TestParseOpenAIModels 负责TestParseOpenAI模型列表相关处理。
func TestParseOpenAIModels(t *testing.T) {
// models、err 保存models、err,供当前处理流程使用
models, err := parseOpenAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"id":"qwen-max"},{"name":"fallback-name"}]}`))
if err != nil {
t.Fatalf("parse models: %v", err)
}
// want 保存want,供当前处理流程使用
want := []string{"qwen-plus", "qwen-max", "fallback-name"}
if len(models) != len(want) {
t.Fatalf("models length=%d want=%d: %+v", len(models), len(want), models)
}
// i 表示当前遍历过程中的i
for i := range want {
if models[i] != want[i] {
t.Fatalf("models[%d]=%q want=%q: %+v", i, models[i], want[i], models)
@@ -275,18 +343,24 @@ func TestParseOpenAIModels(t *testing.T) {
// TestItems 物品列表 + 多规格设置。
func TestItems(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it1','商品A')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 列表。
req := httptest.NewRequest(http.MethodGet, "/items", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["item_title"] != "商品A" {
@@ -295,8 +369,10 @@ func TestItems(t *testing.T) {
// 设置多规格。
body := `{"is_multi_spec":true}`
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPut, "/items/acc1/it1/multi-spec", strings.NewReader(body))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -313,34 +389,45 @@ func TestItems(t *testing.T) {
}
}
// TestOrderImportCompat 负责Test订单ImportCompat相关处理。
func TestOrderImportCompat(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `[{"order_id":"order-import-1","item_id":"item-import-1","item_title":"导入商品","buyer_id":"buyer1","status":"pending_ship","quantity":2,"amount":"19.90"}]`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("import status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success_count"] != float64(1) {
t.Fatalf("导入结果异常: %+v", res)
}
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/order-import-1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("get imported order status=%d body=%s", rec2.Code, rec2.Body.String())
}
// order 保存订单,供当前处理流程使用
var order map[string]any
json.Unmarshal(rec2.Body.Bytes(), &order)
if order["cookie_id"] != "acc1" || order["status"] != "pending_ship" {
@@ -348,26 +435,35 @@ func TestOrderImportCompat(t *testing.T) {
}
}
// TestOrderImportReportsPartialFailure 负责Test订单ImportReportsPartialFailure相关处理。
func TestOrderImportReportsPartialFailure(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `[{"order_id":"order-ok","status":"pending_ship"},{"item_id":"missing-order-id"}]`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
var result struct {
PartialFailure bool `json:"partial_failure"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if !result.PartialFailure || result.SuccessCount != 1 || result.FailedCount != 1 {
@@ -377,19 +473,25 @@ func TestOrderImportReportsPartialFailure(t *testing.T) {
// TestAdminEndpoints 管理员统计 + 用户列表 + 非 admin 被拒。
func TestAdminEndpoints(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// stats。
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("stats status=%d", rec.Code)
}
// stats 保存stats,供当前处理流程使用
var stats map[string]any
json.Unmarshal(rec.Body.Bytes(), &stats)
if stats["total_users"] == nil || stats["total_cookies"] == nil {
@@ -399,8 +501,10 @@ func TestAdminEndpoints(t *testing.T) {
// 用户列表。
req2 := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// users 保存用户列表,供当前处理流程使用
var users []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &users)
if len(users) != 1 || users[0]["username"] != "admin" {
@@ -412,8 +516,10 @@ func TestAdminEndpoints(t *testing.T) {
// 普通用户不应能访问 admin(需单独登录验证,此处仅验证 admin 能看到)。
req3 := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// users2 保存users2,供当前处理流程使用
var users2 []map[string]any
json.Unmarshal(rec3.Body.Bytes(), &users2)
if len(users2) != 2 {
@@ -423,11 +529,15 @@ func TestAdminEndpoints(t *testing.T) {
// TestPublicSettingsNoAuth 公开设置无需登录。
func TestPublicSettingsNoAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
+41
View File
@@ -10,13 +10,18 @@ import (
// TestOrderDetailNotFound 查询不存在的订单应 404。
func TestOrderDetailNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/api/orders/no-such-order", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -26,15 +31,20 @@ func TestOrderDetailNotFound(t *testing.T) {
// TestCardEndpointsErrorBranches 卡券相关错误分支:
// 无效 ID → 400;不存在 → 404;请求体非法 → 400。
// TestCardEndpointsErrorBranches 负责Test卡密Endpoints错误Branches相关处理。
func TestCardEndpointsErrorBranches(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 无效 card_id(非数字)→ 400。
req := httptest.NewRequest(http.MethodGet, "/cards/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -44,6 +54,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 合法但不存在的 ID → 404。
req2 := httptest.NewRequest(http.MethodGet, "/cards/999999", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusNotFound {
@@ -53,6 +64,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 创建卡券请求体非法 → 400。
req3 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader("not-json"))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -62,6 +74,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 创建卡券缺类型 → 400(decodeCard 校验)。
req4 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"无类型卡"}`))
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != http.StatusBadRequest {
@@ -69,12 +82,17 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
}
}
// TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay 负责TestCreate卡密RejectsUnsupportedAPI类型AndInvalid延迟相关处理。
func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
for _, body := range []string{
`{"name":"API 卡密","type":"api","enabled":true}`,
`{"name":"非法类型","type":"unknown","enabled":true}`,
@@ -83,8 +101,10 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
`{"name":"空库存","type":"data","data_content":"\n","enabled":true}`,
`{"name":"空图片","type":"image","image_url":"","enabled":true}`,
} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -95,10 +115,13 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
// TestProtectedEndpointsRequireAuth 受保护端点未登录应 401。
func TestProtectedEndpointsRequireAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// path 表示当前遍历过程中的路径
for _, path := range []string{
"/cards",
"/api/orders",
@@ -108,7 +131,9 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) {
"/admin/stats",
"/ai-reply-settings",
} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, path, nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -119,24 +144,31 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) {
// TestAdminEndpointRejectsNonAdmin 非 admin 用户访问管理端点应 403。
func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// 创建普通用户并登录。
srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw")
// body 保存请求体,供当前处理流程使用
body := `{"username":"user2","password":"pw"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("普通用户登录 status=%d", rec.Code)
}
// cookie 保存登录凭证,供当前处理流程使用
cookie := rec.Result().Cookies()[0]
// 访问 admin 端点 → 403。
req2 := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusForbidden {
@@ -146,14 +178,19 @@ func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
// TestOrderImportEmptyBody 空导入内容应 400。
func TestOrderImportEmptyBody(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(""))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -163,11 +200,15 @@ func TestOrderImportEmptyBody(t *testing.T) {
// TestLoginMalformedJSON 登录请求体非法 JSON 应不致命(400 或失败响应)。
func TestLoginMalformedJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader("not-json"))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+37
View File
@@ -15,15 +15,20 @@ import (
// TestAddKeywordWithItemID 带商品ID的关键词添加 + 缺 keyword 400。
func TestAddKeywordWithItemID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 正常添加。
body := `{"keyword":"价格","reply":"50元","item_id":"item1"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -33,6 +38,7 @@ func TestAddKeywordWithItemID(t *testing.T) {
// 缺 keyword → 400。
req2 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"reply":"x"}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -42,6 +48,7 @@ func TestAddKeywordWithItemID(t *testing.T) {
// 非法 JSON → 400。
req3 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader("not-json"))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -51,26 +58,36 @@ func TestAddKeywordWithItemID(t *testing.T) {
// TestBatchCreateCards CSV 批量建卡密组。
func TestBatchCreateCards(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// csv 保存csv,供当前处理流程使用
csv := "name,type,content,delay_seconds\n卡A,text,内容A,0\n卡B,text,内容B,5\nAPI卡,api,https://example.com,0\n延时异常,text,内容,-1\n"
// body 保存请求体,供当前处理流程使用
body := &bytes.Buffer{}
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(body)
// fw 保存fw,供当前处理流程使用
fw, _ := mw.CreateFormFile("file", "cards.csv")
fw.Write([]byte(csv))
mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/cards/batch", body)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("batch status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["created"].(float64) != 2 {
@@ -84,6 +101,7 @@ func TestBatchCreateCards(t *testing.T) {
req2 := httptest.NewRequest(http.MethodPost, "/cards/batch", &bytes.Buffer{})
req2.Header.Set("Content-Type", "multipart/form-data; boundary=x")
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -93,20 +111,27 @@ func TestBatchCreateCards(t *testing.T) {
// TestAppendCardData 追加批量卡密号 + 校验分支。
func TestAppendCardData(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
// 建一个 data 类型卡密组。
id, _ := store.Cards.Create(ctx, &db.CardFull{Name: "批量卡", Type: "data", DataContent: "K1\nK2", Enabled: true, UserID: admin.ID})
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 追加。
body := `{"content":"K3\nK4"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -116,6 +141,7 @@ func TestAppendCardData(t *testing.T) {
// 空 content → 400。
req2 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(`{"content":""}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -125,6 +151,7 @@ func TestAppendCardData(t *testing.T) {
// 无效 card_id → 400。
req3 := httptest.NewRequest(http.MethodPost, "/cards/abc/append-data", strings.NewReader(`{"content":"x"}`))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -133,8 +160,10 @@ func TestAppendCardData(t *testing.T) {
// 非 data 类型卡密组追加 → 400。建一个 text 类型。
textID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "文本卡", Type: "text", TextContent: "T", Enabled: true, UserID: admin.ID})
// req4 保存req4,供当前处理流程使用
req4 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(textID)+"/append-data", strings.NewReader(`{"content":"x"}`))
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != http.StatusBadRequest {
@@ -144,7 +173,9 @@ func TestAppendCardData(t *testing.T) {
// TestParseXLSXPublishSheet 解析 XLSX 表格(复用 buildMinimalXLSX 构造)。
func TestParseXLSXPublishSheet(t *testing.T) {
// xlsx 保存xlsx,供当前处理流程使用
xlsx := buildMinimalXLSXForPublish(t, [][]string{{"title", "price"}, {"商品A", "9.9"}})
// rows、err 保存rows、err,供当前处理流程使用
rows, err := parseXLSXPublishSheet(xlsx)
if err != nil {
t.Fatalf("parseXLSX: %v", err)
@@ -161,6 +192,7 @@ func TestParseXLSXPublishSheet(t *testing.T) {
// TestPublicHTTPClient 公网 HTTP 客户端拒绝非公网地址 + 重定向协议校验。
func TestPublicHTTPClient(t *testing.T) {
// cli 保存cli,供当前处理流程使用
cli := publicHTTPClient()
if cli == nil {
t.Fatal("应返回非 nil client")
@@ -174,15 +206,19 @@ func TestPublicHTTPClient(t *testing.T) {
// TestPublishBatchToMap 批次转具名 DTO 序列化并校验状态计数。
func TestPublishBatchToMap(t *testing.T) {
// batch 保存批次,供当前处理流程使用
batch := &db.ItemPublishBatch{ID: "b1", Status: "running", Filename: "x.csv"}
// rows 保存rows,供当前处理流程使用
rows := []db.ItemPublishBatchRow{
{ID: 1, RowNo: 1, CookieID: "c1", Title: "t1", Status: "pending", ImagesJSON: `["a.png"]`},
{ID: 2, RowNo: 2, CookieID: "c1", Title: "t2", Status: "running"},
}
// m 保存m,供当前处理流程使用
m := publishBatchToMap(batch, rows)
if m.ID != "b1" || m.Status != "running" {
t.Fatalf("batch 字段异常: %+v", m)
}
// rs 保存rs,供当前处理流程使用
rs := m.Rows
if len(rs) != 2 {
t.Fatalf("rows 数异常: %d", len(rs))
@@ -191,6 +227,7 @@ func TestPublishBatchToMap(t *testing.T) {
// buildMinimalXLSXForPublish 构造最小 xlsx 供 parseXLSXPublishSheet 测试。
// 复用 parser_test.go 的 buildMinimalXLSX 但独立命名避免冲突。
// buildMinimalXLSXForPublish 负责buildMinimalXLSXFor发布相关处理。
func buildMinimalXLSXForPublish(t *testing.T, grid [][]string) []byte {
t.Helper()
return buildMinimalXLSX(t, grid)
+8 -2
View File
@@ -9,6 +9,7 @@ import (
"net/http"
)
// maxJSONRequestBytes 保存maxJSON请求Bytes,供当前处理流程使用
const maxJSONRequestBytes = 1 << 20
// writeJSON 写 JSON 响应。
@@ -30,6 +31,7 @@ func writeErr(w http.ResponseWriter, status int, msg string) {
// decodeJSON 解析请求体 JSON。
func decodeJSON(r *http.Request, v any) error {
// body、err 保存body、err,供当前处理流程使用
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONRequestBytes+1))
if err != nil {
return err
@@ -37,12 +39,16 @@ func decodeJSON(r *http.Request, v any) error {
if len(body) > maxJSONRequestBytes {
return fmt.Errorf("JSON 请求体超过 %d 字节", maxJSONRequestBytes)
}
// dec 保存dec,供当前处理流程使用
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(v); err != nil {
if // err 保存err,供当前处理流程使用
err := dec.Decode(v); err != nil {
return err
}
// trailing 保存trailing,供当前处理流程使用
var trailing any
if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
if // err 保存err,供当前处理流程使用
err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
if err == nil {
return errors.New("JSON 请求体只能包含一个值")
}
+9 -3
View File
@@ -6,16 +6,22 @@ import (
"testing"
)
// TestDecodeJSONLimitsAndRejectsTrailingValues 负责TestDecodeJSONLimitsAndRejectsTrailingValues相关处理。
func TestDecodeJSONLimitsAndRejectsTrailingValues(t *testing.T) {
// out 保存out,供当前处理流程使用
var out map[string]any
if err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{"ok":true}`)), &out); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{"ok":true}`)), &out); err != nil {
t.Fatalf("valid JSON: %v", err)
}
if err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{} {}`)), &out); err == nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{} {}`)), &out); err == nil {
t.Fatal("trailing JSON value should fail")
}
// oversized 保存oversized,供当前处理流程使用
oversized := `{"value":"` + strings.Repeat("x", maxJSONRequestBytes) + `"}`
if err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(oversized)), &out); err == nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(oversized)), &out); err == nil {
t.Fatal("oversized JSON should fail")
}
}
+1
View File
@@ -5,6 +5,7 @@ import (
"time"
)
// init 负责init相关处理。
func init() {
// 服务器单测通过 httptest 模拟 AI 端点;生产构造器仍使用 netguard。
newSettingsOutboundHTTPClient = func(string) (*http.Client, error) {
+154 -20
View File
@@ -50,65 +50,84 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误,请使用 multipart/form-data")
return
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := strings.TrimSpace(r.FormValue("cookie_id"))
if cookieID == "" {
writeErr(w, http.StatusBadRequest, "请选择发布账号")
return
}
// userID、ok 保存用户ID、ok,供当前处理流程使用
_, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
if !ok {
return
}
// title 保存标题,供当前处理流程使用
title := strings.TrimSpace(r.FormValue("title"))
// description 保存description,供当前处理流程使用
description := strings.TrimSpace(r.FormValue("description"))
// priceCents、err 保存priceCents、err,供当前处理流程使用
priceCents, err := parseMoneyCents(r.FormValue("price"))
if err != nil || priceCents <= 0 {
writeErr(w, http.StatusBadRequest, "商品价格必须大于 0")
return
}
// origCents、err 保存origCents、err,供当前处理流程使用
origCents, err := parseMoneyCents(r.FormValue("original_price"))
if err != nil || origCents < 0 {
writeErr(w, http.StatusBadRequest, "商品原价格式错误")
return
}
// quantity、err 保存quantity、err,供当前处理流程使用
quantity, err := strconv.Atoi(strings.TrimSpace(r.FormValue("quantity")))
if err != nil || quantity <= 0 {
writeErr(w, http.StatusBadRequest, "库存数量必须大于 0")
return
}
// postageMode 保存postage模式,供当前处理流程使用
postageMode := strings.TrimSpace(r.FormValue("postage_mode"))
if postageMode == "" {
postageMode = "free"
}
// postageCents、err 保存postageCents、err,供当前处理流程使用
postageCents, err := parseMoneyCents(r.FormValue("postage"))
if err != nil || postageCents < 0 || (postageMode == "fixed" && postageCents <= 0) {
writeErr(w, http.StatusBadRequest, "固定邮费必须大于 0")
return
}
// images、err 保存images、err,供当前处理流程使用
images, err := readPublishImages(r, 9)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// location 保存地址,供当前处理流程使用
var location mtop.PublishLocation
// selectedLocation 保存selected地址,供当前处理流程使用
var selectedLocation *mtop.PublishLocation
if rawLocation := strings.TrimSpace(r.FormValue("location")); rawLocation != "" {
if err := json.Unmarshal([]byte(rawLocation), &location); err != nil {
if // rawLocation 保存原始地址,供当前处理流程使用
rawLocation := strings.TrimSpace(r.FormValue("location")); rawLocation != "" {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(rawLocation), &location); err != nil {
writeErr(w, http.StatusBadRequest, "发货地格式错误,请重新定位")
return
}
selectedLocation = &location
}
// outcome、callErr 保存outcome、callErr,供当前处理流程使用
outcome, callErr := s.itemPublishApplication().PublishSingle(r.Context(), itemPublishInput{
UserID: userID, CookieID: cookieID, Title: title, Description: description,
PriceCents: priceCents, OriginalPriceCents: origCents, Quantity: quantity,
PostageMode: postageMode, PostageCents: postageCents, Location: selectedLocation, Images: images,
})
// res 保存响应,供当前处理流程使用
res := outcome.Result
if callErr != nil {
// perr 保存perr,供当前处理流程使用
var perr *mtop.PublishError
if errors.As(callErr, &perr) {
// status 保存状态,供当前处理流程使用
status := http.StatusBadGateway
// msg 保存msg,供当前处理流程使用
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
status = http.StatusForbidden
@@ -272,10 +291,12 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
// 后续版本化路径迁移继续复用该具名 DTO。
}
// readPublishImages 负责read发布Images相关处理。
func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) {
if r.MultipartForm == nil || r.MultipartForm.File == nil {
return nil, errors.New("至少上传 1 张商品图片")
}
// files 保存文件列表,供当前处理流程使用
files := r.MultipartForm.File["images"]
if len(files) == 0 {
files = r.MultipartForm.File["image"]
@@ -286,12 +307,16 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err
if len(files) > maxImages {
return nil, fmt.Errorf("商品图片最多 %d 张", maxImages)
}
// images 保存images,供当前处理流程使用
images := make([]mtop.PublishImage, 0, len(files))
// fh 表示当前遍历过程中的fh
for _, fh := range files {
// f、err 保存f、err,供当前处理流程使用
f, err := fh.Open()
if err != nil {
return nil, fmt.Errorf("读取图片失败: %w", err)
}
// data、tooLarge、err 保存data、tooLarge、err,供当前处理流程使用
data, tooLarge, err := readLimitedBytes(f, 10<<20)
_ = f.Close()
if err != nil {
@@ -303,6 +328,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err
if len(data) == 0 {
return nil, errors.New("图片文件为空")
}
// contentType 保存内容类型,供当前处理流程使用
contentType := fh.Header.Get("Content-Type")
if contentType == "" {
contentType = http.DetectContentType(data)
@@ -315,6 +341,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err
return images, nil
}
// parseMoneyCents 负责parseMoneyCents相关处理。
func parseMoneyCents(raw string) (int64, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -322,6 +349,7 @@ func parseMoneyCents(raw string) (int64, error) {
}
raw = strings.TrimPrefix(raw, "¥")
raw = strings.TrimPrefix(raw, "¥")
// sign 保存sign,供当前处理流程使用
sign := int64(1)
if strings.HasPrefix(raw, "-") {
sign = -1
@@ -329,16 +357,20 @@ func parseMoneyCents(raw string) (int64, error) {
} else {
raw = strings.TrimPrefix(raw, "+")
}
// parts 保存parts,供当前处理流程使用
parts := strings.Split(raw, ".")
if len(parts) > 2 {
return 0, fmt.Errorf("金额格式错误")
}
// yuan、err 保存yuan、err,供当前处理流程使用
yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
if err != nil {
return 0, err
}
// cents 保存cents,供当前处理流程使用
cents := int64(0)
if len(parts) == 2 {
// frac 保存frac,供当前处理流程使用
frac := strings.TrimSpace(parts[1])
if len(frac) > 2 {
return 0, fmt.Errorf("金额最多支持两位小数")
@@ -354,13 +386,16 @@ func parseMoneyCents(raw string) (int64, error) {
return sign * (yuan*100 + cents), nil
}
// listItems 负责list商品列表相关处理。
func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
cookieIDs, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := strings.TrimSpace(r.URL.Query().Get("cookie_id"))
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
@@ -369,9 +404,13 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
}
cookieIDs = []string{cookieID}
}
// result 保存结果,供当前处理流程使用
result := []itemListResponse{}
// cid 表示当前遍历过程中的cid
for _, cid := range cookieIDs {
// items 保存商品列表,供当前处理流程使用
items, _ := s.Store.Items.AllForCookie(r.Context(), cid)
// it 表示当前遍历过程中的it
for _, it := range items {
result = append(result, itemToMap(it))
}
@@ -379,40 +418,52 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// syncItemsFromAccount 负责sync商品列表From账号相关处理。
func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CookieID string `json:"cookie_id"`
PageSize int `json:"page_size"`
MaxPages int `json:"max_pages"`
}
if err := decodeJSON(r, &req); err != nil || req.CookieID == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.CookieID == "" {
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
// userID、ok 保存用户ID、ok,供当前处理流程使用
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
// cookieValue 保存登录凭证值,供当前处理流程使用
cookieValue := latest.Value
if req.PageSize <= 0 {
req.PageSize = 20
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
// client 保存client,供当前处理流程使用
client := s.mtopClient()
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
// res、callErr 保存res、callErr,供当前处理流程使用
res, callErr := client.FetchAllItems(mtopCtx, cookieValue, req.PageSize, req.MaxPages)
if callErr == nil && res == nil {
callErr = errors.New("商品列表接口未返回结果")
}
if callErr != nil {
// value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
credentialUnlock()
if persistErr != nil {
@@ -426,13 +477,18 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
// detailCookies 保存detailCookies,供当前处理流程使用
detailCookies := cookieValue
if res.UpdatedCookies != "" {
detailCookies = res.UpdatedCookies
}
// detailErr 保存detailErr,供当前处理流程使用
detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
// runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用
runtimeCookieChanged := false
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
@@ -445,7 +501,8 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
runtimeCookieChanged = true
}
} else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
if // saveErr 保存saveErr,供当前处理流程使用
saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
@@ -464,6 +521,7 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadGateway, detailErr.Error())
return
}
// syncResult、syncErr 保存syncResult、syncErr,供当前处理流程使用
syncResult, syncErr := s.syncSyncedItems(r.Context(), req.CookieID, res.Items)
if syncErr != nil {
if s.Logger != nil {
@@ -482,37 +540,49 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
// syncItemsPageFromAccount 同步指定页商品并返回分页统计 DTO。
// 该接口沿用现有凭证锁和 Cookie 持久化流程。
// 分页成功响应使用 itemPageSyncResponse。
// syncItemsPageFromAccount 负责sync商品列表页码From账号相关处理。
func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CookieID string `json:"cookie_id"`
PageNumber int `json:"page_number"`
PageSize int `json:"page_size"`
}
if err := decodeJSON(r, &req); err != nil || req.CookieID == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.CookieID == "" {
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
// userID、ok 保存用户ID、ok,供当前处理流程使用
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
// cookieValue 保存登录凭证值,供当前处理流程使用
cookieValue := latest.Value
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
// client 保存client,供当前处理流程使用
client := s.mtopClient()
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
// res、callErr 保存res、callErr,供当前处理流程使用
res, callErr := client.FetchItemsPage(mtopCtx, cookieValue, req.PageNumber, req.PageSize)
if callErr == nil && res == nil {
callErr = errors.New("商品列表接口未返回结果")
}
if callErr != nil {
// value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
credentialUnlock()
if persistErr != nil {
@@ -526,13 +596,18 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
// detailCookies 保存detailCookies,供当前处理流程使用
detailCookies := cookieValue
if res.UpdatedCookies != "" {
detailCookies = res.UpdatedCookies
}
// detailErr 保存detailErr,供当前处理流程使用
detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
// runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用
runtimeCookieChanged := false
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
@@ -545,7 +620,8 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
runtimeCookieChanged = true
}
} else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
if // saveErr 保存saveErr,供当前处理流程使用
saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
@@ -564,6 +640,7 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusBadGateway, detailErr.Error())
return
}
// saved 保存saved,供当前处理流程使用
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, itemPageSyncResponse{
Success: true, Message: "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品",
@@ -575,7 +652,9 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
// 失败仍由统一错误响应负责,不在成功 DTO 中嵌入错误别名。
}
// cookieForCurrentUser 负责登录凭证ForCurrent用户相关处理。
func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
value, err := s.Store.Cookies.GetValueOwned(r.Context(), sess.UserID, cookieID) // value 和 err 是单个 Cookie 明文及读取错误。
if err != nil {
@@ -595,12 +674,16 @@ func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, co
// saveSyncedItems 以下历史同步流程保持原有行为。
func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) int {
// saved 保存saved,供当前处理流程使用
saved := 0
// item 表示当前遍历过程中的商品
for _, item := range items {
// priceText 保存price文本,供当前处理流程使用
priceText := item.PriceText
if priceText == "" {
priceText = item.Price
}
// err 保存err,供当前处理流程使用
err := s.Store.Items.UpsertBasic(ctx, &db.ItemInfoRow{
CookieID: cookieID,
ItemID: item.ID,
@@ -612,7 +695,8 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
})
if err == nil {
if item.IsMultiSpec {
if multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil {
if // multiErr 保存multiErr,供当前处理流程使用
multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil {
s.Logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr)
}
}
@@ -624,9 +708,13 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
return saved
}
// syncSyncedItems 负责syncSynced商品列表相关处理。
func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) {
// rows 保存rows,供当前处理流程使用
rows := make([]db.ItemInfoRow, 0, len(items))
// item 表示当前遍历过程中的商品
for _, item := range items {
// priceText 保存price文本,供当前处理流程使用
priceText := item.PriceText
if priceText == "" {
priceText = item.Price
@@ -644,16 +732,20 @@ func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []m
return s.Store.Items.SyncFromRemote(ctx, cookieID, rows)
}
// enrichSyncedItemMultiSpec 负责enrichSynced商品MultiSpec相关处理。
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) error {
// fetcher、ok 保存fetcher、ok,供当前处理流程使用
fetcher, ok := client.(mtop.ItemDetailFetcher)
if !ok {
return nil
}
// index 表示当前遍历过程中的index
for index := range items {
if items[index].IsMultiSpec || s.Store.Items.IsMultiSpec(ctx, cookieID, items[index].ID) {
items[index].IsMultiSpec = true
continue
}
// isMultiSpec、err 保存isMultiSpec、err,供当前处理流程使用
isMultiSpec, err := fetcher.DetectItemMultiSpec(ctx, cookies, items[index].ID)
if err != nil {
if mtop.IsSessionExpiredErr(err) {
@@ -669,29 +761,38 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
return nil
}
// listItemsByCookie 负责list商品列表By登录凭证相关处理。
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// items、err 保存items、err,供当前处理流程使用
items, err := s.Store.Items.AllForCookie(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]itemListResponse, 0, len(items))
// it 表示当前遍历过程中的it
for _, it := range items {
out = append(out, itemToMap(it))
}
writeJSON(w, http.StatusOK, out)
}
// getItem 负责get商品相关处理。
func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// it、err 保存it、err,供当前处理流程使用
it, err := s.Store.Items.Get(r.Context(), cid, itemID)
if err != nil {
writeErr(w, http.StatusNotFound, "商品不存在")
@@ -706,10 +807,12 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
// createItem 创建本地商品记录并返回统一操作结果。
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
ItemID string `json:"item_id"`
ItemTitle string `json:"item_title"`
@@ -721,14 +824,16 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
IsMultiQtyShip bool `json:"is_multi_qty_ship"`
}
if err := decodeJSON(r, &req); err != nil || req.ItemID == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.ItemID == "" {
writeErr(w, http.StatusBadRequest, "缺少商品 ID")
return
}
if req.MultiQuantityDelivery || req.IsMultiQtyShip {
req.MultiQuantityDelivery = true
}
if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{
if // err 保存err,供当前处理流程使用
err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{
CookieID: cid, ItemID: req.ItemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription,
ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail,
IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery,
@@ -739,12 +844,16 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// updateItem 负责update商品相关处理。
func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// req 保存req,供当前处理流程使用
var req struct {
ItemTitle *string `json:"item_title"`
ItemDescription *string `json:"item_description"`
@@ -755,10 +864,12 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
MultiQuantityDelivery *bool `json:"multi_quantity_delivery"`
IsMultiQtyShip *bool `json:"is_multi_qty_ship"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// existing、err 保存existing、err,供当前处理流程使用
existing, err := s.Store.Items.Get(r.Context(), cid, itemID)
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "商品不存在")
@@ -768,6 +879,7 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
// row 保存row,供当前处理流程使用
row := &db.ItemInfoRow{
CookieID: cid,
ItemID: itemID,
@@ -803,60 +915,77 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
if req.IsMultiQtyShip != nil {
row.MultiQuantityDelivery = *req.IsMultiQtyShip
}
if err := s.Store.Items.Upsert(r.Context(), row); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Items.Upsert(r.Context(), row); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteItem 负责delete商品相关处理。
func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
if err := s.Store.Items.Delete(r.Context(), cid, itemID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Items.Delete(r.Context(), cid, itemID); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setItemMultiSpec 负责set商品MultiSpec相关处理。
func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// req 保存req,供当前处理流程使用
var req struct {
IsMultiSpec bool `json:"is_multi_spec"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if err := s.Store.Items.SetMultiSpec(r.Context(), cid, itemID, req.IsMultiSpec); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Items.SetMultiSpec(r.Context(), cid, itemID, req.IsMultiSpec); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setItemMultiQuantity 负责set商品MultiQuantity相关处理。
func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// req 保存req,供当前处理流程使用
var req struct {
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if err := s.Store.Items.SetMultiQuantity(r.Context(), cid, itemID, req.MultiQuantityDelivery); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Items.SetMultiQuantity(r.Context(), cid, itemID, req.MultiQuantityDelivery); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -880,16 +1009,21 @@ func itemImageFromDetail(detail string) string {
if detail == "" {
return ""
}
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(detail), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(detail), &m); err != nil {
return ""
}
if pic, ok := m["pic_info"].(map[string]any); ok {
if url, ok := pic["picUrl"].(string); ok {
if // pic、ok 保存pic、ok,供当前处理流程使用
pic, ok := m["pic_info"].(map[string]any); ok {
if // url、ok 保存url、ok,供当前处理流程使用
url, ok := pic["picUrl"].(string); ok {
return url
}
}
if url, ok := m["item_image"].(string); ok {
if // url、ok 保存url、ok,供当前处理流程使用
url, ok := m["item_image"].(string); ok {
return url
}
return ""
+221 -10
View File
@@ -17,22 +17,29 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// stubPublishMTop 保存stub发布MTop,供当前处理流程使用
type stubPublishMTop struct {
mtop.Client
publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error)
}
// TestRecommendItemPublishCategory 负责TestRecommend商品发布分类相关处理。
func TestRecommendItemPublishCategory(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := srv.Manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); err != nil {
if // err 保存err,供当前处理流程使用
err := srv.Manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); err != nil {
t.Fatal(err)
}
if err := store.Tokens.Save(context.Background(), "acc1", "device", "stale-token", time.Now().Add(time.Hour).Unix()); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Tokens.Save(context.Background(), "acc1", "device", "stale-token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
// client 保存client,供当前处理流程使用
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.Query().Get("api") != "mtop.taobao.idle.kgraph.property.recommend" {
@@ -50,35 +57,44 @@ func TestRecommendItemPublishCategory(t *testing.T) {
}, nil
})}
srv.MTop = client
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"课程资料"}`))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
var response struct {
Category mtop.PublishCategory `json:"category"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatalf("decode: %v", err)
}
if response.Category.CatID != "50023914" || response.Category.CatName != "电子资料" || response.Category.ChannelCatID != "202036301" {
t.Fatalf("category=%+v", response.Category)
}
// saved、err 保存saved、err,供当前处理流程使用
saved, err := store.Cookies.GetValue(context.Background(), "acc1")
if err != nil || !strings.Contains(saved, "_m_h5_tk=recommended_2") {
t.Fatalf("类目推荐响应 Cookie 未保存: value=%q err=%v", saved, err)
}
// token、err 保存token、err,供当前处理流程使用
token, err := store.Tokens.Get(context.Background(), "acc1")
if err != nil || token.AccessToken != "" {
t.Fatalf("类目推荐 Cookie 更新后未同步运行时并清理旧 token: token=%+v err=%v", token, err)
}
}
// PublishItem 负责发布商品相关处理。
func (s *stubPublishMTop) PublishItem(ctx context.Context, cookies string, req mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return s.publish(ctx, cookies, req)
}
@@ -86,10 +102,14 @@ func (s *stubPublishMTop) PublishItem(ctx context.Context, cookies string, req m
// buildPublishMultipart 构造一个 multipart/form-data 请求体,包含一个 1x1 PNG 图片字段。
func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffer, string) {
t.Helper()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
// 1x1 PNG.
// png 保存png,供当前处理流程使用
png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
// w、err 保存w、err,供当前处理流程使用
w, err := mw.CreatePart(textproto.MIMEHeader{
"Content-Disposition": []string{`form-data; name="images"; filename="test.png"`},
"Content-Type": []string{"image/png"},
@@ -98,10 +118,12 @@ func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffe
t.Fatal(err)
}
w.Write(png)
// k、v 表示当前遍历过程中的k、v
for k, v := range fields {
_ = mw.WriteField(k, v)
}
if err := mw.Close(); err != nil {
if // err 保存err,供当前处理流程使用
err := mw.Close(); err != nil {
t.Fatal(err)
}
return &buf, mw.FormDataContentType()
@@ -109,17 +131,23 @@ func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffe
// TestPublishItemMissingCookieID 缺 cookie_id 应 400。
func TestPublishItemMissingCookieID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"title": "测试商品", "price": "12.50", "quantity": "5",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -129,17 +157,23 @@ func TestPublishItemMissingCookieID(t *testing.T) {
// TestPublishItemBadPrice 价格非法 400。
func TestPublishItemBadPrice(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"cookie_id": "acc1", "title": "测试商品", "price": "0", "quantity": "5",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -149,17 +183,23 @@ func TestPublishItemBadPrice(t *testing.T) {
// TestPublishItemBadQuantity 库存非法 400。
func TestPublishItemBadQuantity(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "0",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -169,17 +209,23 @@ func TestPublishItemBadQuantity(t *testing.T) {
// TestPublishItemBadCookie 无权操作账号 403。
func TestPublishItemBadCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"cookie_id": "other-account", "title": "测试商品", "price": "12.50", "quantity": "5",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -189,13 +235,18 @@ func TestPublishItemBadCookie(t *testing.T) {
// TestPublishItemBadMultipart 非 multipart 请求 400。
func TestPublishItemBadMultipart(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", strings.NewReader("plain text"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -205,12 +256,17 @@ func TestPublishItemBadMultipart(t *testing.T) {
// TestPublishItemNoImages 缺图片 400。
func TestPublishItemNoImages(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("cookie_id", "acc1")
_ = mw.WriteField("title", "测试商品")
@@ -218,9 +274,11 @@ func TestPublishItemNoImages(t *testing.T) {
_ = mw.WriteField("quantity", "5")
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -230,13 +288,17 @@ func TestPublishItemNoImages(t *testing.T) {
// TestPublishItemSuccess mtop PublishItem 成功路径。
// 由于 PublishItem 内部串行调用上传图片/类目/定位/发布多个端点,mock 按 URL 分发。
// TestPublishItemSuccess 负责Test发布商品Success相关处理。
func TestPublishItemSuccess(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 替换为按 URL 分发的 mock。
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 保存u,供当前处理流程使用
u := req.URL.String()
// respBody 保存resp请求体,供当前处理流程使用
var respBody string
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
@@ -257,20 +319,26 @@ func TestPublishItemSuccess(t *testing.T) {
}))
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "5",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("publish status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true || res["item_id"] != "pub-item-1" {
@@ -278,18 +346,25 @@ func TestPublishItemSuccess(t *testing.T) {
}
}
// TestPublishItemRejectsMissingRemoteItemID 负责Test发布商品RejectsMissingRemote商品ID相关处理。
func TestPublishItemRejectsMissingRemoteItemID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return &mtop.PublishItemResult{Title: "测试商品"}, nil
}}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "1"})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway || !strings.Contains(rec.Body.String(), "publish_result_missing_item_id") {
@@ -297,19 +372,26 @@ func TestPublishItemRejectsMissingRemoteItemID(t *testing.T) {
}
}
// TestPublishItemReportsRemoteSuccessLocalSaveFailure 负责Test发布商品ReportsRemoteSuccessLocalSaveFailure相关处理。
func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
_, _ = store.DB.ExecContext(context.Background(), `DELETE FROM cookies WHERE id='acc1'`)
return &mtop.PublishItemResult{ItemID: "remote-only", ItemURL: "https://example/item/remote-only", Title: "测试商品"}, nil
}}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "1"})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError || !strings.Contains(rec.Body.String(), "remote_published_local_save_failed") || !strings.Contains(rec.Body.String(), "remote-only") {
@@ -319,11 +401,15 @@ func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) {
// TestPublishItemStockPermissionMissing 库存权限缺失应 403。
func TestPublishItemStockPermissionMissing(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 保存prev,供当前处理流程使用
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 保存u,供当前处理流程使用
u := req.URL.String()
// respBody 保存resp请求体,供当前处理流程使用
var respBody string
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
@@ -345,20 +431,26 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
}))
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body、ct 保存body、ct,供当前处理流程使用
body, ct := buildPublishMultipart(t, map[string]string{
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "5",
})
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", ct)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("库存权限缺失应 403,got %d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["code"] != "stock_permission_missing" {
@@ -368,25 +460,33 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
// TestSyncItemsFromAccountSuccess mtop FetchAllItems 成功,保存商品。
func TestSyncItemsFromAccountSuccess(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
if // err 保存err,供当前处理流程使用
err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "it-sync-1", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "it-sync-1", true); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Items.SetMultiSpec(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "it-sync-1", true); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Items.SetMultiQuantity(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "acc1", ItemID: "it-removed", ItemTitle: "已删除商品"}); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "acc1", ItemID: "it-removed", ItemTitle: "已删除商品"}); err != nil {
t.Fatal(err)
}
// prev 保存prev,供当前处理流程使用
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
`{"cardData":{"id":"it-sync-1","title":"同步商品A","priceInfo":{"price":"12.50","preText":"¥"},"picInfo":{"picUrl":"https://img.alicdn.com/a.png"},"categoryId":"9","detailParams":{"itemId":"it-sync-1"}}}]}}`
return &http.Response{
@@ -398,17 +498,23 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
}))
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","page_size":10}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("sync status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["saved_count"] != float64(1) {
@@ -422,6 +528,7 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
if len(items) != 1 {
t.Fatalf("同步后本地应只保留1件商品: %+v", items)
}
// item 保存商品,供当前处理流程使用
item := items[0]
if item.ItemID != "it-sync-1" || item.ItemTitle != "同步商品A" || item.ItemPrice != "¥12.50" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
@@ -429,10 +536,13 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
}
}
// TestSyncItemsFromAccountDetectsMultiSpecFromDetail 负责TestSync商品列表From账号DetectsMultiSpecFromDetail相关处理。
func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
if strings.Contains(req.URL.String(), "mtop.idle.web.xyh.item.list") {
body = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"multi-item","title":"多规格商品","detailParams":{"itemId":"multi-item"}}}]}}`
@@ -441,15 +551,20 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// item、err 保存item、err,供当前处理流程使用
item, err := store.Items.Get(context.Background(), "acc1", "multi-item")
if err != nil || !item.IsMultiSpec {
t.Fatalf("item=%+v err=%v", item, err)
@@ -458,10 +573,13 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
func TestSyncItemsFromAccountFail(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 保存prev,供当前处理流程使用
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["FAIL_SYS_USER_VALIDATE::用户校验失败"]}`
return &http.Response{
StatusCode: http.StatusOK,
@@ -472,12 +590,17 @@ func TestSyncItemsFromAccountFail(t *testing.T) {
}))
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
@@ -487,14 +610,20 @@ func TestSyncItemsFromAccountFail(t *testing.T) {
// TestSyncItemsFromAccountBadCookie 无权账号 403。
func TestSyncItemsFromAccountBadCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"other-account"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -504,13 +633,18 @@ func TestSyncItemsFromAccountBadCookie(t *testing.T) {
// TestSyncItemsFromAccountMissingCookieID 缺 cookie_id 400。
func TestSyncItemsFromAccountMissingCookieID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -520,10 +654,13 @@ func TestSyncItemsFromAccountMissingCookieID(t *testing.T) {
// TestSyncItemsPageFromAccountSuccess mtop FetchItemsPage 成功。
func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 保存prev,供当前处理流程使用
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
`{"cardData":{"id":"it-page-1","title":"分页商品","priceInfo":{"price":"9.90","preText":"¥"},"picInfo":{"picUrl":"https://img.alicdn.com/p.png"},"categoryId":"1","detailParams":{"itemId":"it-page-1"}}}]}}`
return &http.Response{
@@ -535,17 +672,23 @@ func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
}))
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1","page_number":1,"page_size":10}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-by-page", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["saved_count"] != float64(1) {
@@ -555,17 +698,24 @@ func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
// TestSyncItemsPageFromAccountFail mtop 失败 502。
func TestSyncItemsPageFromAccountFail(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// prev 保存prev,供当前处理流程使用
prev := srv.MTop
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_SYS_USER_VALIDATE::失败"}})
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"cookie_id":"acc1"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/get-by-page", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
@@ -575,25 +725,32 @@ func TestSyncItemsPageFromAccountFail(t *testing.T) {
// TestItemCRUD 商品增删改查 + 多规格。
func TestItemCRUD(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if _, err := store.DB.ExecContext(ctx, `INSERT INTO item_info
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx, `INSERT INTO item_info
(cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery)
VALUES ('acc1','it-crud','商品C','原描述','原分类','12.00','原详情',1,1)`); err != nil {
t.Fatalf("seed item: %v", err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 按账号列表。
req := httptest.NewRequest(http.MethodGet, "/items/cookie/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("list by cookie status=%d body=%s", rec.Code, rec.Body.String())
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["item_id"] != "it-crud" {
@@ -603,6 +760,7 @@ func TestItemCRUD(t *testing.T) {
// 单品详情。
req2 := httptest.NewRequest(http.MethodGet, "/items/acc1/it-crud", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -611,13 +769,16 @@ func TestItemCRUD(t *testing.T) {
// 更新。
updBody := `{"item_title":"改名商品","item_price":"88.00"}`
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(updBody))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
}
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Items.Get(ctx, "acc1", "it-crud")
if err != nil {
t.Fatalf("get updated item: %v", err)
@@ -634,8 +795,10 @@ func TestItemCRUD(t *testing.T) {
// 显式传空字符串时允许清空文本字段。
clearBody := `{"item_description":""}`
// reqClear 保存reqClear,供当前处理流程使用
reqClear := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(clearBody))
reqClear.AddCookie(cookie)
// recClear 保存recClear,供当前处理流程使用
recClear := httptest.NewRecorder()
h.ServeHTTP(recClear, reqClear)
if recClear.Code != 200 {
@@ -651,8 +814,10 @@ func TestItemCRUD(t *testing.T) {
// 显式传 false 时仍允许清除布尔配置。
updFlagsBody := `{"item_title":"改名商品","item_price":"88.00","is_multi_spec":false,"is_multi_qty_ship":false}`
// reqFlags 保存reqFlags,供当前处理流程使用
reqFlags := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(updFlagsBody))
reqFlags.AddCookie(cookie)
// recFlags 保存recFlags,供当前处理流程使用
recFlags := httptest.NewRecorder()
h.ServeHTTP(recFlags, reqFlags)
if recFlags.Code != 200 {
@@ -666,8 +831,10 @@ func TestItemCRUD(t *testing.T) {
t.Fatalf("explicit false flags should be persisted: %+v", updated)
}
// reqMissing 保存reqMissing,供当前处理流程使用
reqMissing := httptest.NewRequest(http.MethodPut, "/items/acc1/missing-item", strings.NewReader(`{"item_title":"不会创建"}`))
reqMissing.AddCookie(cookie)
// recMissing 保存recMissing,供当前处理流程使用
recMissing := httptest.NewRecorder()
h.ServeHTTP(recMissing, reqMissing)
if recMissing.Code != http.StatusNotFound {
@@ -676,8 +843,10 @@ func TestItemCRUD(t *testing.T) {
// 多规格 + 多件发货。
multiBody := `{"multi_quantity_delivery":true}`
// req4 保存req4,供当前处理流程使用
req4 := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud/multi-quantity-delivery", strings.NewReader(multiBody))
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
@@ -687,6 +856,7 @@ func TestItemCRUD(t *testing.T) {
// 删除。
req5 := httptest.NewRequest(http.MethodDelete, "/items/acc1/it-crud", nil)
req5.AddCookie(cookie)
// rec5 保存rec5,供当前处理流程使用
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
if rec5.Code != 200 {
@@ -694,22 +864,32 @@ func TestItemCRUD(t *testing.T) {
}
}
// TestListItemsFiltersByOwnedAccount 负责TestList商品列表FiltersByOwned账号相关处理。
func TestListItemsFiltersByOwnedAccount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
if err := store.Cookies.Save(ctx, "acc2", "unb=456; _m_h5_tk=tk2_1;", admin.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(ctx, "acc2", "unb=456; _m_h5_tk=tk2_1;", admin.ID); err != nil {
t.Fatal(err)
}
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-a','商品A'),('acc2','item-b','商品B')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items?cookie_id=acc2", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// rows 保存rows,供当前处理流程使用
var rows []map[string]any
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &rows) != nil {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
@@ -718,8 +898,10 @@ func TestListItemsFiltersByOwnedAccount(t *testing.T) {
t.Fatalf("rows=%+v", rows)
}
// forbidden 保存forbidden,供当前处理流程使用
forbidden := httptest.NewRequest(http.MethodGet, "/items?cookie_id=not-owned", nil)
forbidden.AddCookie(cookie)
// forbiddenRec 保存forbiddenRec,供当前处理流程使用
forbiddenRec := httptest.NewRecorder()
h.ServeHTTP(forbiddenRec, forbidden)
if forbiddenRec.Code != http.StatusForbidden {
@@ -729,13 +911,18 @@ func TestListItemsFiltersByOwnedAccount(t *testing.T) {
// TestItemGetNotFound 不存在商品 404。
func TestItemGetNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/acc1/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -745,14 +932,20 @@ func TestItemGetNotFound(t *testing.T) {
// TestCreateItem 新建商品。
func TestCreateItem(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -762,14 +955,20 @@ func TestCreateItem(t *testing.T) {
// TestCreateItemMissingID 缺商品 ID 400。
func TestCreateItemMissingID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"item_title":"无ID商品"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -779,15 +978,21 @@ func TestCreateItemMissingID(t *testing.T) {
// TestUpdateItemBadJSON 非法 JSON 400。
func TestUpdateItemBadJSON(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id) VALUES ('acc1','it-bad')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/items/acc1/it-bad", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -797,15 +1002,21 @@ func TestUpdateItemBadJSON(t *testing.T) {
// TestSetItemMultiSpecBadJSON 非法 JSON 400。
func TestSetItemMultiSpecBadJSON(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id) VALUES ('acc1','it-spec')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/items/acc1/it-spec/multi-spec", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
File diff suppressed because it is too large. Load diff
+60 -5
View File
@@ -29,13 +29,18 @@ import (
// isPublicIP 保留给同包校验调用;实际策略统一由 netguard 维护。
func isPublicIP(ip net.IP) bool { return netguard.IsPublicIP(ip) }
// extractPublishImagesZip 负责extract发布ImagesZip相关处理。
func extractPublishImagesZip(raw []byte, dest string) error {
// zr、err 保存zr、err,供当前处理流程使用
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return fmt.Errorf("解析图片 zip 失败: %w", err)
}
// extractedFiles 保存extracted文件列表,供当前处理流程使用
extractedFiles := 0
// extractedBytes 保存extractedBytes,供当前处理流程使用
extractedBytes := int64(0)
// f 表示当前遍历过程中的f
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
@@ -44,23 +49,28 @@ func extractPublishImagesZip(raw []byte, dest string) error {
if extractedFiles > maxItemPublishZipFiles {
return fmt.Errorf("图片 zip 文件数不能超过 %d", maxItemPublishZipFiles)
}
// rel、err 保存rel、err,供当前处理流程使用
rel, err := safeZipPath(f.Name)
if err != nil {
return err
}
// root、err 保存root、err,供当前处理流程使用
root, err := os.OpenRoot(dest)
if err != nil {
return err
}
if err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
if // err 保存err,供当前处理流程使用
err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
_ = root.Close()
return err
}
// rc、err 保存rc、err,供当前处理流程使用
rc, err := f.Open()
if err != nil {
_ = root.Close()
return err
}
// data、err 保存data、err,供当前处理流程使用
data, err := io.ReadAll(io.LimitReader(rc, (10<<20)+1))
_ = rc.Close()
if err != nil {
@@ -84,9 +94,11 @@ func extractPublishImagesZip(raw []byte, dest string) error {
_ = root.Close()
return fmt.Errorf("图片 zip 解压后总大小不能超过 %d MiB", maxItemPublishZipExtractBytes>>20)
}
// file、err 保存file、err,供当前处理流程使用
file, err := root.OpenFile(rel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err == nil {
_, err = file.Write(data)
// closeErr 保存closeErr,供当前处理流程使用
closeErr := file.Close()
if err == nil {
err = closeErr
@@ -100,19 +112,28 @@ func extractPublishImagesZip(raw []byte, dest string) error {
return nil
}
// loadBatchPublishImages 负责load批次发布Images相关处理。
func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) {
// refs 保存refs,供当前处理流程使用
var refs []string
if err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil {
return nil, fmt.Errorf("图片字段格式错误")
}
if len(refs) == 0 {
return nil, errors.New("至少上传 1 张商品图片")
}
// images 保存images,供当前处理流程使用
images := make([]mtop.PublishImage, 0, len(refs))
// ref 表示当前遍历过程中的ref
for _, ref := range refs {
// data 保存数据,供当前处理流程使用
var data []byte
// contentType 保存内容类型,供当前处理流程使用
var contentType string
// filename 保存filename,供当前处理流程使用
var filename string
// err 保存err,供当前处理流程使用
var err error
if isHTTPURL(ref) {
data, contentType, err = downloadImageURL(ctx, ref)
@@ -128,21 +149,26 @@ func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPu
return images, nil
}
// readBatchImageFile 负责read批次图片文件相关处理。
func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
// rel、err 保存rel、err,供当前处理流程使用
rel, err := safeZipPath(ref)
if err != nil {
return nil, "", "", err
}
// root、err 保存root、err,供当前处理流程使用
root, err := os.OpenRoot(uploadDir)
if err != nil {
return nil, "", "", fmt.Errorf("打开图片目录失败")
}
defer root.Close()
// file、err 保存file、err,供当前处理流程使用
file, err := root.Open(rel)
if err != nil {
return nil, "", "", fmt.Errorf("读取图片失败: %s", ref)
}
defer file.Close()
// data、err 保存data、err,供当前处理流程使用
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
if err != nil || len(data) > 10<<20 {
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", ref)
@@ -150,6 +176,7 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
if len(data) == 0 {
return nil, "", "", fmt.Errorf("图片文件为空: %s", ref)
}
// contentType 保存内容类型,供当前处理流程使用
contentType := http.DetectContentType(data)
if !strings.HasPrefix(contentType, "image/") {
return nil, "", "", fmt.Errorf("不是有效图片: %s", ref)
@@ -159,28 +186,35 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
// writeFileWithinRoot 将上传文件限制在指定根目录内,拒绝符号链接和路径逃逸。
func writeFileWithinRoot(rootDir, name string, data []byte) error {
// root、err 保存root、err,供当前处理流程使用
root, err := os.OpenRoot(rootDir)
if err != nil {
return err
}
defer root.Close()
// file、err 保存file、err,供当前处理流程使用
file, err := root.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if _, err := file.Write(data); err != nil {
if // err 保存err,供当前处理流程使用
_, err := file.Write(data); err != nil {
_ = file.Close()
return err
}
return file.Close()
}
// downloadImageURL 负责download图片URL相关处理。
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil || (req.URL.Scheme != "http" && req.URL.Scheme != "https") || req.URL.Hostname() == "" {
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
}
// client 保存client,供当前处理流程使用
client := publicHTTPClient()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
@@ -189,6 +223,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode)
}
// data、err 保存data、err,供当前处理流程使用
data, err := io.ReadAll(io.LimitReader(resp.Body, (10<<20)+1))
if err != nil {
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
@@ -196,8 +231,10 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
if len(data) > 10<<20 {
return nil, "", fmt.Errorf("远程图片不能超过 10 MiB: %s", rawURL)
}
// contentType 保存内容类型,供当前处理流程使用
contentType := resp.Header.Get("Content-Type")
if i := strings.Index(contentType, ";"); i >= 0 {
if // i 保存i,供当前处理流程使用
i := strings.Index(contentType, ";"); i >= 0 {
contentType = contentType[:i]
}
if contentType == "" || contentType == "application/octet-stream" {
@@ -214,15 +251,19 @@ func publicHTTPClient() *http.Client {
return netguard.PublicHTTPClient(30 * time.Second)
}
// validateBatchImageRef 负责validate批次图片Ref相关处理。
func validateBatchImageRef(uploadDir, ref string) error {
if isHTTPURL(ref) {
return nil
}
// rel、err 保存rel、err,供当前处理流程使用
rel, err := safeZipPath(ref)
if err != nil {
return err
}
// path 保存路径,供当前处理流程使用
path := filepath.Join(uploadDir, rel)
// info、err 保存info、err,供当前处理流程使用
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return fmt.Errorf("图片文件不存在: %s", ref)
@@ -230,14 +271,18 @@ func validateBatchImageRef(uploadDir, ref string) error {
return nil
}
// isHTTPURL 负责isHTTPURL相关处理。
func isHTTPURL(ref string) bool {
ref = strings.ToLower(strings.TrimSpace(ref))
return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://")
}
// pathBaseFromURL 负责路径BaseFromURL相关处理。
func pathBaseFromURL(rawURL string) string {
// base 保存base,供当前处理流程使用
base := filepath.Base(strings.Split(rawURL, "?")[0])
if base == "." || base == "/" || base == "" {
// exts 保存exts,供当前处理流程使用
exts, _ := mime.ExtensionsByType(http.DetectContentType(nil))
if len(exts) > 0 {
return "image" + exts[0]
@@ -247,14 +292,18 @@ func pathBaseFromURL(rawURL string) string {
return base
}
// randomHex 负责randomHex相关处理。
func randomHex(n int) string {
// buf 保存buf,供当前处理流程使用
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
if // err 保存err,供当前处理流程使用
_, err := rand.Read(buf); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(buf)
}
// safeBaseName 负责safeBase名称相关处理。
func safeBaseName(name string) string {
name = strings.TrimSpace(filepath.Base(name))
name = strings.ReplaceAll(name, string(os.PathSeparator), "_")
@@ -264,11 +313,13 @@ func safeBaseName(name string) string {
return name
}
// safeZipPath 负责safeZip路径相关处理。
func safeZipPath(raw string) (string, error) {
raw = strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/"))
if raw == "" || strings.HasPrefix(raw, "/") {
return "", fmt.Errorf("图片路径不安全: %s", raw)
}
// clean 保存clean,供当前处理流程使用
clean := filepath.Clean(raw)
if clean == "." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) || clean == ".." {
return "", fmt.Errorf("图片路径不安全: %s", raw)
@@ -276,11 +327,15 @@ func safeZipPath(raw string) (string, error) {
return clean, nil
}
// splitImageRefs 负责split图片Refs相关处理。
func splitImageRefs(raw string) []string {
raw = strings.ReplaceAll(raw, "\n", ";")
raw = strings.ReplaceAll(raw, ";", ";")
// parts 保存parts,供当前处理流程使用
parts := strings.Split(raw, ";")
// out 保存out,供当前处理流程使用
out := []string{}
// p 表示当前遍历过程中的p
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
+41 -1
View File
@@ -12,10 +12,12 @@ import (
"strings"
)
// parsePublishSheetBytes 负责parse发布SheetBytes相关处理。
func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) {
return parsePublishSheetBytesWithLimit(raw, filename, 0)
}
// parsePublishSheetBytesWithLimit 负责parse发布SheetBytesWith上限相关处理。
func parsePublishSheetBytesWithLimit(raw []byte, filename string, maxRows int) ([]map[string]any, error) {
if len(bytes.TrimSpace(raw)) == 0 {
return nil, fmt.Errorf("导入内容为空")
@@ -34,19 +36,26 @@ func parsePublishSheetBytesWithLimit(raw []byte, filename string, maxRows int) (
}
}
// parseDelimitedPublishSheet 负责parseDelimited发布Sheet相关处理。
func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[string]any, error) {
// reader 保存reader,供当前处理流程使用
reader := csv.NewReader(bytes.NewReader(raw))
reader.Comma = comma
reader.FieldsPerRecord = -1
reader.LazyQuotes = true
// header、err 保存header、err,供当前处理流程使用
header, err := reader.Read()
if err != nil {
return nil, fmt.Errorf("解析表格失败: %w", err)
}
// keys 保存keys,供当前处理流程使用
keys := publishHeaderKeys(header)
// rows 保存rows,供当前处理流程使用
rows := make([]map[string]any, 0, 64)
// seenDataRow 保存seen数据Row,供当前处理流程使用
seenDataRow := false
for {
// record、err 保存record、err,供当前处理流程使用
record, err := reader.Read()
if err == io.EOF {
break
@@ -55,6 +64,7 @@ func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[stri
return nil, fmt.Errorf("解析表格失败: %w", err)
}
seenDataRow = true
// row、nonEmpty 保存row、nonEmpty,供当前处理流程使用
row, nonEmpty := publishRowToMap(keys, record)
if !nonEmpty {
continue
@@ -70,20 +80,26 @@ func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[stri
return rows, nil
}
// parseXLSXPublishSheet 负责parseXLSX发布Sheet相关处理。
func parseXLSXPublishSheet(raw []byte) ([]map[string]any, error) {
return parseXLSXPublishSheetWithLimit(raw, 0)
}
// parseXLSXPublishSheetWithLimit 负责parseXLSX发布SheetWith上限相关处理。
func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any, error) {
// zr、err 保存zr、err,供当前处理流程使用
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
}
// shared、err 保存shared、err,供当前处理流程使用
shared, err := xlsxSharedStrings(zr)
if err != nil {
return nil, err
}
// sheet 保存sheet,供当前处理流程使用
var sheet *zip.File
// f 表示当前遍历过程中的f
for _, f := range zr.File {
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
sheet = f
@@ -93,18 +109,26 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
if sheet == nil {
return nil, fmt.Errorf("xlsx 中未找到工作表")
}
// rawSheet、err 保存原始Sheet、err,供当前处理流程使用
rawSheet, err := readXLSXPart(sheet)
if err != nil {
return nil, err
}
// ws 保存ws,供当前处理流程使用
var ws xlsxWorksheet
if err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
if // err 保存err,供当前处理流程使用
err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
return nil, fmt.Errorf("解析工作表失败: %w", err)
}
// rows 保存rows,供当前处理流程使用
rows := make([][]string, 0, len(ws.SheetData.Rows))
// row 表示当前遍历过程中的row
for _, row := range ws.SheetData.Rows {
// values 保存values,供当前处理流程使用
values := []string{}
// cell 表示当前遍历过程中的cell
for _, cell := range row.Cells {
// idx 保存idx,供当前处理流程使用
idx := xlsxCellIndex(cell.Ref)
for len(values) <= idx {
values = append(values, "")
@@ -116,6 +140,7 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
if len(rows) < 2 {
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
}
// out 保存out,供当前处理流程使用
out := rowsToPublishMaps(rows[0], rows[1:])
if maxRows > 0 && len(out) > maxRows {
return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows)
@@ -123,10 +148,15 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
return out, nil
}
// rowsToPublishMaps 负责rowsTo发布Maps相关处理。
func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
// keys 保存keys,供当前处理流程使用
keys := publishHeaderKeys(headers)
// out 保存out,供当前处理流程使用
out := make([]map[string]any, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
// m、nonEmpty 保存m、nonEmpty,供当前处理流程使用
m, nonEmpty := publishRowToMap(keys, row)
if nonEmpty {
out = append(out, m)
@@ -135,21 +165,29 @@ func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
return out
}
// publishHeaderKeys 负责发布HeaderKeys相关处理。
func publishHeaderKeys(headers []string) []string {
// keys 保存keys,供当前处理流程使用
keys := make([]string, len(headers))
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
keys[i] = normalizePublishHeader(h)
}
return keys
}
// publishRowToMap 负责发布RowToMap相关处理。
func publishRowToMap(keys []string, row []string) (map[string]any, bool) {
// m 保存m,供当前处理流程使用
m := map[string]any{}
// nonEmpty 保存nonEmpty,供当前处理流程使用
nonEmpty := false
// i、key 表示当前遍历过程中的i、key
for i, key := range keys {
if key == "" || i >= len(row) {
continue
}
// value 保存值,供当前处理流程使用
value := strings.TrimSpace(row[i])
if value != "" {
nonEmpty = true
@@ -159,7 +197,9 @@ func publishRowToMap(keys []string, row []string) (map[string]any, bool) {
return m, nonEmpty
}
// normalizePublishHeader 负责normalize发布Header相关处理。
func normalizePublishHeader(header string) string {
// h 保存h,供当前处理流程使用
h := strings.ToLower(strings.TrimSpace(header))
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
switch h {
+70 -10
View File
@@ -24,51 +24,66 @@ func (s *Server) mountKeywordsReal(r chi.Router) {
r.Delete("/keywords/{cid}/{index}", s.deleteKeyword)
}
// listKeywords 负责listKeywords相关处理。
func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordBasicResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordBasicResponse{Keyword: k.Keyword, Reply: k.Reply})
}
writeJSON(w, http.StatusOK, out)
}
// listKeywordsWithItemID 负责listKeywordsWith商品ID相关处理。
func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordItemResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordItemResponse{Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID})
}
writeJSON(w, http.StatusOK, out)
}
// listKeywordsWithType 负责listKeywordsWith类型相关处理。
func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordTypedResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordTypedResponse{
ID: k.ID, Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID,
@@ -78,16 +93,20 @@ func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// addKeyword 负责add关键词相关处理。
func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
}
if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
@@ -95,18 +114,22 @@ func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
if _, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil {
if // err 保存err,供当前处理流程使用
_, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// addKeywordWithItemID 负责add关键词With商品ID相关处理。
func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
@@ -121,12 +144,15 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
ImageURL string `json:"image_url"`
} `json:"keywords"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.Keywords != nil {
// rows 保存rows,供当前处理流程使用
rows := make([]db.KeywordRow, 0, len(*req.Keywords))
// item 表示当前遍历过程中的商品
for _, item := range *req.Keywords {
if strings.TrimSpace(item.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
@@ -162,7 +188,8 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
ImageURL: item.ImageURL,
})
}
if err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -194,6 +221,7 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
} else {
req.ImageURL = ""
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, req.ItemID, req.Type, req.ImageURL)
if err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
@@ -202,16 +230,20 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateKeywordByID 负责update关键词ByID相关处理。
func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
@@ -219,7 +251,8 @@ func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
Type string `json:"type"`
ImageURL string `json:"image_url"`
}
if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
@@ -259,30 +292,38 @@ func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteKeywordByID 负责delete关键词ByID相关处理。
func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
if err := s.Store.Keywords.DeleteByID(r.Context(), cid, id); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.DeleteByID(r.Context(), cid, id); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteKeyword 负责delete关键词相关处理。
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// index 保存index,供当前处理流程使用
index := atoiDefault(chi.URLParam(r, "index"), -1)
if err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
@@ -297,12 +338,17 @@ func (s *Server) mountItemRepliesReal(r chi.Router) {
r.Delete("/item-reply/{cookie_id}/{item_id}", s.deleteItemReply)
}
// listItemReplies 负责list商品回复列表相关处理。
func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
cookieIDs, _ := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 是当前用户拥有的账号 ID。
var result []itemReplyResponse
// cid 表示当前遍历过程中的cid
for _, cid := range cookieIDs {
// rows 保存rows,供当前处理流程使用
rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid)
// ir 表示当前遍历过程中的ir
for _, ir := range rows {
result = append(result, itemReplyResponse{
ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent,
@@ -312,12 +358,16 @@ func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// getItemReply 负责get商品回复相关处理。
func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// ir、err 保存ir、err,供当前处理流程使用
ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID)
if err != nil {
writeJSON(w, http.StatusOK, itemReplyResponse{ReplyContent: ""})
@@ -328,33 +378,43 @@ func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
})
}
// setItemReply 负责set商品回复相关处理。
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// req 保存req,供当前处理流程使用
var req struct {
ReplyContent string `json:"reply_content"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteItemReply 负责delete商品回复相关处理。
func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
if err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
+12 -3
View File
@@ -8,6 +8,7 @@ import (
"xianyu-go/internal/db"
)
// loginMethodManual 保存登录方法Manual,供当前处理流程使用
const (
loginMethodManual = "manual"
loginMethodPassword = "password"
@@ -16,6 +17,7 @@ const (
loginStatusFailed = "failed"
)
// normalizeLoginMethod 负责normalize登录方法相关处理。
func normalizeLoginMethod(method string) string {
switch strings.ToLower(strings.TrimSpace(method)) {
case "manual", "cookie", "manual_cookie":
@@ -29,6 +31,7 @@ func normalizeLoginMethod(method string) string {
}
}
// markSuccessfulLogin 负责markSuccessful登录相关处理。
func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) {
// repository 提供登录审计和账号状态持久化能力。
repository := s.accountLoginRepositoryForServer()
@@ -39,21 +42,25 @@ func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userI
if method == "" {
return
}
// at 保存at,供当前处理流程使用
at := time.Now().Unix()
if err := repository.MarkLogin(ctx, cookieID, method, at); err != nil {
if // err 保存err,供当前处理流程使用
err := repository.MarkLogin(ctx, cookieID, method, at); err != nil {
if s.Logger != nil {
s.Logger.Warn("记录账号登录方式失败", "cookie_id", cookieID, "method", method, "err", err)
}
return
}
if method == loginMethodPassword || method == loginMethodQRScan {
if err := repository.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil {
if // err 保存err,供当前处理流程使用
err := repository.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil {
s.Logger.Warn("成功登录后启用账号失败", "cookie_id", cookieID, "method", method, "err", err)
}
}
s.addLoginLog(ctx, cookieID, userID, method, loginStatusSuccess, "", message, at)
}
// addLoginLog 负责add登录Log相关处理。
func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64, method, status, failureReason, message string, at int64) {
// repository 提供登录日志持久化能力。
repository := s.accountLoginRepositoryForServer()
@@ -63,7 +70,8 @@ func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64,
if at == 0 {
at = time.Now().Unix()
}
if err := repository.AddLoginLog(ctx, db.AccountLoginLog{
if // err 保存err,供当前处理流程使用
err := repository.AddLoginLog(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
OwnerID: userID,
@@ -80,6 +88,7 @@ func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64,
}
}
// loginTriggerReason 负责登录Trigger原因相关处理。
func loginTriggerReason(method string) string {
switch normalizeLoginMethod(method) {
case loginMethodManual:
+19 -1
View File
@@ -8,12 +8,14 @@ import (
"time"
)
// loginFailureWindow 保存登录FailureWindow,供当前处理流程使用
const (
loginFailureWindow = 5 * time.Minute
loginFailuresPerIP = 30
loginFailuresPerPrincipal = 10
)
// loginFailureBucket 保存登录FailureBucket,供当前处理流程使用
type loginFailureBucket struct {
count int
expires time.Time
@@ -21,6 +23,7 @@ type loginFailureBucket struct {
// loginFailureLimiter 仅记录失败登录。IP 和账号两个维度同时限制,避免攻击者
// 通过轮换账号绕过 IP 限制,或通过轮换 IP 集中爆破单个账号。
// loginFailureLimiter 保存登录FailureLimiter,供当前处理流程使用
type loginFailureLimiter struct {
mu sync.Mutex
buckets map[string]loginFailureBucket
@@ -29,6 +32,7 @@ type loginFailureLimiter struct {
perPrincipal int
}
// newLoginFailureLimiter 负责new登录FailureLimiter相关处理。
func newLoginFailureLimiter() *loginFailureLimiter {
return &loginFailureLimiter{
buckets: make(map[string]loginFailureBucket),
@@ -38,7 +42,9 @@ func newLoginFailureLimiter() *loginFailureLimiter {
}
}
// loginClientIP 负责登录ClientIP相关处理。
func loginClientIP(r *http.Request) string {
// host、err 保存host、err,供当前处理流程使用
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
return host
@@ -46,22 +52,29 @@ func loginClientIP(r *http.Request) string {
return r.RemoteAddr
}
// loginPrincipal 负责登录Principal相关处理。
func loginPrincipal(username, email string) string {
if value := strings.TrimSpace(username); value != "" {
if // value 保存值,供当前处理流程使用
value := strings.TrimSpace(username); value != "" {
return strings.ToLower(value)
}
return strings.ToLower(strings.TrimSpace(email))
}
// allow 负责allow相关处理。
func (l *loginFailureLimiter) allow(ip, principal string, now time.Time) (bool, time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
// retry 保存重试,供当前处理流程使用
var retry time.Duration
// key 表示当前遍历过程中的key
for _, key := range []string{"ip:" + ip, "principal:" + principal} {
// bucket、ok 保存bucket、ok,供当前处理流程使用
bucket, ok := l.buckets[key]
if !ok || !now.Before(bucket.expires) {
continue
}
// limit 保存上限,供当前处理流程使用
limit := l.perPrincipal
if strings.HasPrefix(key, "ip:") {
limit = l.perIP
@@ -73,10 +86,13 @@ func (l *loginFailureLimiter) allow(ip, principal string, now time.Time) (bool,
return retry == 0, retry
}
// failure 负责failure相关处理。
func (l *loginFailureLimiter) failure(ip, principal string, now time.Time) {
l.mu.Lock()
defer l.mu.Unlock()
// key 表示当前遍历过程中的key
for _, key := range []string{"ip:" + ip, "principal:" + principal} {
// bucket 保存bucket,供当前处理流程使用
bucket := l.buckets[key]
if !now.Before(bucket.expires) {
bucket = loginFailureBucket{expires: now.Add(l.window)}
@@ -85,6 +101,7 @@ func (l *loginFailureLimiter) failure(ip, principal string, now time.Time) {
l.buckets[key] = bucket
}
if len(l.buckets) > 2048 {
// key、bucket 表示当前遍历过程中的key、bucket
for key, bucket := range l.buckets {
if !now.Before(bucket.expires) {
delete(l.buckets, key)
@@ -93,6 +110,7 @@ func (l *loginFailureLimiter) failure(ip, principal string, now time.Time) {
}
}
// success 负责success相关处理。
func (l *loginFailureLimiter) success(ip, principal string) {
l.mu.Lock()
delete(l.buckets, "ip:"+ip)
+13 -5
View File
@@ -5,33 +5,41 @@ import (
"time"
)
// TestLoginFailureLimiterScopesExpiresAndResets 负责Test登录FailureLimiterScopesExpiresAndResets相关处理。
func TestLoginFailureLimiterScopesExpiresAndResets(t *testing.T) {
// limiter 保存limiter,供当前处理流程使用
limiter := newLoginFailureLimiter()
limiter.perIP = 3
limiter.perPrincipal = 2
limiter.window = time.Minute
// now 保存now,供当前处理流程使用
now := time.Unix(100, 0)
limiter.failure("10.0.0.1", "admin", now)
limiter.failure("10.0.0.1", "admin", now)
if allowed, retry := limiter.allow("10.0.0.2", "admin", now); allowed || retry != time.Minute {
if // allowed、retry 保存allowed、retry,供当前处理流程使用
allowed, retry := limiter.allow("10.0.0.2", "admin", now); allowed || retry != time.Minute {
t.Fatalf("principal limit: allowed=%v retry=%v", allowed, retry)
}
if allowed, _ := limiter.allow("10.0.0.1", "other", now); !allowed {
if // allowed 保存allowed,供当前处理流程使用
allowed, _ := limiter.allow("10.0.0.1", "other", now); !allowed {
t.Fatal("IP should remain below its independent limit")
}
limiter.failure("10.0.0.1", "other", now)
if allowed, _ := limiter.allow("10.0.0.1", "third", now); allowed {
if // allowed 保存allowed,供当前处理流程使用
allowed, _ := limiter.allow("10.0.0.1", "third", now); allowed {
t.Fatal("IP limit should apply across principals")
}
limiter.success("10.0.0.1", "admin")
if allowed, _ := limiter.allow("10.0.0.1", "admin", now); !allowed {
if // allowed 保存allowed,供当前处理流程使用
allowed, _ := limiter.allow("10.0.0.1", "admin", now); !allowed {
t.Fatal("successful authentication should reset matching buckets")
}
limiter.failure("10.0.0.3", "blocked", now)
limiter.failure("10.0.0.3", "blocked", now)
if allowed, _ := limiter.allow("10.0.0.4", "blocked", now.Add(time.Minute)); !allowed {
if // allowed 保存allowed,供当前处理流程使用
allowed, _ := limiter.allow("10.0.0.4", "blocked", now.Add(time.Minute)); !allowed {
t.Fatal("expired failure window should allow a new attempt")
}
}
+5
View File
@@ -19,6 +19,7 @@ type mtopResp struct {
// withMTopTransport 用自定义 transport 构造 *mtop.ClientImpl(按 URL 分发用闭包)。
func withMTopTransport(rt roundTripFunc) *mtop.ClientImpl {
// cli 保存cli,供当前处理流程使用
cli := mtop.NewClient()
cli.HTTPClient = &http.Client{Transport: rt}
return cli
@@ -27,16 +28,20 @@ func withMTopTransport(rt roundTripFunc) *mtop.ClientImpl {
// 默认对未匹配 URL 返回 SUCCESS。
func newMockMTop(t *testing.T, resp mtopResp) *mtop.ClientImpl {
t.Helper()
// cli 保存cli,供当前处理流程使用
cli := mtop.NewClient()
cli.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := resp.body
if body == "" {
body = `{"ret":["` + strings.Join(resp.ret, "\",\"") + `"]}`
}
// status 保存状态,供当前处理流程使用
status := resp.statusCode
if status == 0 {
status = http.StatusOK
}
// r 保存r,供当前处理流程使用
r := &http.Response{
StatusCode: status,
Header: make(http.Header),
+9 -1
View File
@@ -12,10 +12,12 @@ import (
// withMTopCookieSnapshot 为一次业务 MTOP 流程挂载账号 Cookie 会话。有完整
// Jar 时保持所有作用域;历史账号则使用不冒充完整 Jar 的 flat session,仍能
// 在成功或失败路径观察并持久化 Set-Cookie。
// withMTopCookieSnapshot 负责withMTop登录凭证Snapshot相关处理。
func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (context.Context, *mtop.CookieSession) {
if detail == nil {
return ctx, nil
}
// snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
return mtop.WithFlatCookieSession(ctx, detail.Value)
@@ -23,6 +25,7 @@ func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (conte
return mtop.WithCookieSnapshot(ctx, snapshot)
}
// hasStoredCookieCredential 负责hasStored登录凭证Credential相关处理。
func hasStoredCookieCredential(detail *db.CookieDetail) bool {
if detail == nil {
return false
@@ -30,6 +33,7 @@ func hasStoredCookieCredential(detail *db.CookieDetail) bool {
if detail.Value != "" {
return true
}
// complete 保存complete,供当前处理流程使用
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
@@ -39,6 +43,7 @@ func hasStoredCookieCredential(detail *db.CookieDetail) bool {
// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
// 此时即使 Jar 未变化,也不得因扁平 Cookie 的顺序/尾分号差异退回
// UpdatedCookies 写回,否则会把刚保存的完整 Jar 清掉。
// persistMTopCookieSessionLocked 负责persistMTop登录凭证会话Locked相关处理。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *db.CookieDetail,
@@ -47,6 +52,7 @@ func (s *Server) persistMTopCookieSessionLocked(
if detail == nil || session == nil {
return "", false, false, nil
}
// value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用
value, snapshot, changed := session.State()
if !changed {
if snapshot != nil {
@@ -54,11 +60,13 @@ func (s *Server) persistMTopCookieSessionLocked(
}
return "", false, false, nil
}
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil {
return value, value != detail.Value, true, err
}
return value, value != detail.Value, true, nil
+27 -2
View File
@@ -12,36 +12,47 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// stubProfileMTop 保存stubProfileMTop,供当前处理流程使用
type stubProfileMTop struct {
mtop.Client
profile func(context.Context, string) (*mtop.UserProfileResult, error)
}
// FetchUserProfile 负责Fetch用户Profile相关处理。
func (s *stubProfileMTop) FetchUserProfile(ctx context.Context, cookies string) (*mtop.UserProfileResult, error) {
return s.profile(ctx, cookies)
}
// TestRefreshAccountProfilePersistsCookieSessionOnResponseError 负责TestRefresh账号ProfilePersists登录凭证会话On响应错误相关处理。
func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// detail、err 保存detail、err,供当前处理流程使用
detail, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "tk1_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "keep", Value: "yes", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if err := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, detail.Value, metadata, time.Now().Unix()); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, detail.Value, metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
// client 保存client,供当前处理流程使用
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
// header 保存header,供当前处理流程使用
header := make(http.Header)
header.Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
return &http.Response{
@@ -57,11 +68,13 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
if err != nil {
t.Fatal(err)
}
// message 保存消息,供当前处理流程使用
_, _, message := srv.refreshAccountProfile(ctx, detail)
if message == "" {
t.Fatal("无效响应应返回解析错误")
}
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
@@ -69,11 +82,14 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
if !strings.Contains(updated.Value, "rotated=fresh") {
t.Fatalf("响应错误时仍应保存 canonical Cookie: %q", updated.Value)
}
// updatedSnapshot、ok 保存updatedSnapshot、ok,供当前处理流程使用
updatedSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON)
if !ok {
t.Fatal("响应错误时不应清除权威 Cookie Jar")
}
// values 保存values,供当前处理流程使用
values := make(map[string]string, len(updatedSnapshot))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range updatedSnapshot {
values[cookie.Name+"@"+cookie.Domain+cookie.Path] = cookie.Value
}
@@ -82,7 +98,9 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
}
}
// TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock 负责TestRefresh账号ProfileKeepsAuthoritativeSnapshotWithFlatMock相关处理。
func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
seedStaleCookieSnapshot(t, store, "acc1")
@@ -93,12 +111,14 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
// detail、err 保存detail、err,供当前处理流程使用
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
@@ -106,12 +126,15 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
if strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
t.Fatalf("完整 Jar 不得被 mock 扁平 Cookie 覆盖: %q", updated.Value)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON); !complete {
if // complete 保存complete,供当前处理流程使用
_, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON); !complete {
t.Fatalf("完整 Jar 未发生变化时不得清除: %s", updated.MetadataJSON)
}
}
// TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot 负责TestRefresh账号ProfileKeepsFlatMockFallbackWithoutSnapshot相关处理。
func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
@@ -121,12 +144,14 @@ func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T)
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
// detail、err 保存detail、err,供当前处理流程使用
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
+130 -5
View File
@@ -13,15 +13,20 @@ import (
// TestListChannels 列出通知渠道。
func TestListChannels(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 先创建一个渠道。
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -31,11 +36,13 @@ func TestListChannels(t *testing.T) {
// 列出。
req2 := httptest.NewRequest(http.MethodGet, "/notification-channels", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["name"] != "钉钉" {
@@ -45,14 +52,20 @@ func TestListChannels(t *testing.T) {
// TestCreateChannelMissingName 缺 name/type 400。
func TestCreateChannelMissingName(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"type":"dingtalk"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -62,13 +75,18 @@ func TestCreateChannelMissingName(t *testing.T) {
// TestCreateChannelBadJSON 非法 JSON 400。
func TestCreateChannelBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -78,30 +96,40 @@ func TestCreateChannelBadJSON(t *testing.T) {
// TestUpdateChannel 更新渠道。
func TestUpdateChannel(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 创建。
body := `{"name":"钉钉","type":"dingtalk","config":"{\"webhook_url\":\"https://example.com\"}","event_types":"[\"account_offline\"]","enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cr 保存cr,供当前处理流程使用
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
id := int64(cr["id"].(float64))
// 部分更新:只切换 enabled,不应清空 name/type/config/event_types。
upd := `{"enabled":false}`
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(upd))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("update status=%d body=%s", rec2.Code, rec2.Body.String())
}
// row、err 保存row、err,供当前处理流程使用
row, err := store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
if err != nil {
t.Fatalf("get channel row: %v", err)
@@ -117,6 +145,7 @@ func TestUpdateChannel(t *testing.T) {
// 显式传空 event_types 表示恢复为接收全部事件,其它字段仍保留。
req3 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(`{"event_types":""}`))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -133,13 +162,18 @@ func TestUpdateChannel(t *testing.T) {
// TestUpdateChannelBadID 无效 ID 400。
func TestUpdateChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/notification-channels/abc", strings.NewReader(`{}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -149,13 +183,18 @@ func TestUpdateChannelBadID(t *testing.T) {
// TestUpdateChannelBadJSON 非法 JSON 400。
func TestUpdateChannelBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/notification-channels/1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -165,22 +204,32 @@ func TestUpdateChannelBadJSON(t *testing.T) {
// TestDeleteChannel 删除渠道。
func TestDeleteChannel(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cr 保存cr,供当前处理流程使用
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
id := int64(cr["id"].(float64))
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(id), nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -190,13 +239,18 @@ func TestDeleteChannel(t *testing.T) {
// TestDeleteChannelBadID 无效 ID 400。
func TestDeleteChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/notification-channels/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -206,13 +260,18 @@ func TestDeleteChannelBadID(t *testing.T) {
// TestTestChannelNoNotifier 未注入通知器 503。
func TestTestChannelNoNotifier(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels/1/test", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
@@ -222,13 +281,18 @@ func TestTestChannelNoNotifier(t *testing.T) {
// TestTestChannelBadID 无效 ID 400。
func TestTestChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/notification-channels/abc/test", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -238,22 +302,29 @@ func TestTestChannelBadID(t *testing.T) {
// TestListMessageNotifications 列出消息通知绑定。
func TestListMessageNotifications(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 创建渠道 + 绑定。
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// m 保存m,供当前处理流程使用
var m map[string][]map[string]any
json.Unmarshal(rec.Body.Bytes(), &m)
if len(m["acc1"]) != 1 {
@@ -261,74 +332,97 @@ func TestListMessageNotifications(t *testing.T) {
}
}
// TestMessageNotificationsFilterCrossUserChannels 负责Test消息通知列表FilterCross用户渠道列表相关处理。
func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if _, err := store.Users.Create(ctx, "notif2", "notif2@example.com", "pw"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.Users.Create(ctx, "notif2", "notif2@example.com", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// u2 保存u2,供当前处理流程使用
u2, _ := store.Users.GetByUsername(ctx, "notif2")
// ownID、err 保存ownID、err,供当前处理流程使用
ownID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "own", Type: "webhook", Config: `{}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatalf("create own channel: %v", err)
}
// otherID、err 保存otherID、err,供当前处理流程使用
otherID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "other-secret", Type: "webhook", Config: `{}`, Enabled: true, UserID: u2.ID,
})
if err != nil {
t.Fatalf("create other channel: %v", err)
}
if _, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, ownID); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, ownID); err != nil {
t.Fatalf("insert own binding: %v", err)
}
if _, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, otherID); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, otherID); err != nil {
t.Fatalf("insert dirty binding: %v", err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
listReq := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// listed 保存listed,供当前处理流程使用
var listed map[string][]map[string]any
if err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
t.Fatalf("decode list: %v", err)
}
if len(listed["acc1"]) != 1 || listed["acc1"][0]["channel_name"] != "own" {
t.Fatalf("list should filter dirty binding: %+v", listed)
}
// getReq 保存getReq,供当前处理流程使用
getReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
getReq.AddCookie(cookie)
// getRec 保存getRec,供当前处理流程使用
getRec := httptest.NewRecorder()
h.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusOK {
t.Fatalf("get status=%d body=%s", getRec.Code, getRec.Body.String())
}
// got 保存got,供当前处理流程使用
var got map[string]any
if err := json.Unmarshal(getRec.Body.Bytes(), &got); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(getRec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode get: %v", err)
}
// ids 保存ids,供当前处理流程使用
ids, _ := got["channel_ids"].([]any)
if len(ids) != 1 || int64(ids[0].(float64)) != ownID {
t.Fatalf("bindings should filter dirty binding: %+v", got)
}
// updateOtherReq 保存updateOtherReq,供当前处理流程使用
updateOtherReq := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(otherID), strings.NewReader(`{"enabled":false}`))
updateOtherReq.AddCookie(cookie)
// updateOtherRec 保存updateOtherRec,供当前处理流程使用
updateOtherRec := httptest.NewRecorder()
h.ServeHTTP(updateOtherRec, updateOtherReq)
if updateOtherRec.Code != http.StatusForbidden {
t.Fatalf("cross-user update should be 403, got %d body=%s", updateOtherRec.Code, updateOtherRec.Body.String())
}
// otherRow、err 保存otherRow、err,供当前处理流程使用
otherRow, err := store.Notifications.GetChannelRowForUser(ctx, otherID, u2.ID)
if err != nil {
t.Fatalf("get other channel: %v", err)
@@ -337,8 +431,10 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
t.Fatalf("cross-user update should not mutate other channel: %+v", otherRow)
}
// deleteOtherReq 保存deleteOtherReq,供当前处理流程使用
deleteOtherReq := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(otherID), nil)
deleteOtherReq.AddCookie(cookie)
// deleteOtherRec 保存deleteOtherRec,供当前处理流程使用
deleteOtherRec := httptest.NewRecorder()
h.ServeHTTP(deleteOtherRec, deleteOtherReq)
if deleteOtherRec.Code != http.StatusForbidden {
@@ -348,16 +444,22 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
// TestDeleteMessageNotification 删除单条消息通知。
func TestDeleteMessageNotification(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -367,13 +469,18 @@ func TestDeleteMessageNotification(t *testing.T) {
// TestDeleteMessageNotificationBadID 无效 ID 400。
func TestDeleteMessageNotificationBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -383,16 +490,22 @@ func TestDeleteMessageNotificationBadID(t *testing.T) {
// TestDeleteAccountNotifications 删除账号的所有通知绑定。
func TestDeleteAccountNotifications(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/account/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -402,13 +515,18 @@ func TestDeleteAccountNotifications(t *testing.T) {
// TestSetAccountBindingsBadJSON 非法 JSON 400。
func TestSetAccountBindingsBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -418,16 +536,23 @@ func TestSetAccountBindingsBadJSON(t *testing.T) {
// TestSetAccountBindingsSingleChannel 单渠道绑定。
func TestSetAccountBindingsSingleChannel(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"channel_id":1,"enabled":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
+53 -7
View File
@@ -25,8 +25,11 @@ func (s *Server) mountNotificationsReal(r chi.Router) {
r.Post("/message-notifications/{cid}", s.setAccountBindings)
}
// listChannels 负责list渠道列表相关处理。
func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// chs、err 保存chs、err,供当前处理流程使用
chs, err := s.communicationApplication().ListNotificationChannels(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -35,8 +38,11 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newNotificationChannelResponses(chs))
}
// createChannel 负责create渠道相关处理。
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// req 保存req,供当前处理流程使用
var req struct {
Name string `json:"name"`
Type string `json:"type"`
@@ -44,10 +50,12 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
EventTypes string `json:"event_types"`
Enabled bool `json:"enabled"`
}
if err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
// id、err 保存id、err,供当前处理流程使用
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,
})
@@ -58,12 +66,15 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateChannel 负责update渠道相关处理。
func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Name *string `json:"name"`
Type *string `json:"type"`
@@ -71,11 +82,14 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
EventTypes *string `json:"event_types"`
Enabled *bool `json:"enabled"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// row、err 保存row、err,供当前处理流程使用
row, err := s.communicationApplication().GetNotificationChannel(r.Context(), id, sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -104,7 +118,8 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
if err := s.communicationApplication().UpdateNotificationChannel(r.Context(), *row, sess.UserID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().UpdateNotificationChannel(r.Context(), *row, sess.UserID); err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
@@ -115,14 +130,18 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteChannel 负责delete渠道相关处理。
func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
if err := s.communicationApplication().DeleteNotificationChannel(r.Context(), id, sess.UserID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().DeleteNotificationChannel(r.Context(), id, sess.UserID); err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
@@ -135,6 +154,7 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
// testChannel 向指定渠道发送一条测试通知,便于用户验证配置是否正确。
func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
@@ -147,9 +167,11 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
if !s.requireChannelOwner(w, r, id) {
return
}
// body 保存请求体,供当前处理流程使用
body := "🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
time.Now().Format("2006-01-02 15:04:05")
if err := s.communicationApplication().TestNotificationChannel(r.Context(), id, authSess(r).UserID, body); err != nil {
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().TestNotificationChannel(r.Context(), id, authSess(r).UserID, body); err != nil {
if errors.Is(err, errCommunicationUnavailable) {
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
return
@@ -160,11 +182,14 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// getAccountBindings 负责get账号Bindings相关处理。
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// ids、err 保存ids、err,供当前处理流程使用
ids, err := s.communicationApplication().GetNotificationBindingIDs(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -173,15 +198,21 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, accountBindingsResponse{CookieID: cid, ChannelIDs: ids})
}
// listMessageNotifications 负责list消息通知列表相关处理。
func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.communicationApplication().ListNotificationBindings(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make(notificationBindingListResponse, len(rows))
// cookieID、bindings 表示当前遍历过程中的登录凭证ID、bindings
for cookieID, bindings := range rows {
// binding 表示当前遍历过程中的binding
for _, binding := range bindings {
out[cookieID] = append(out[cookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled})
}
@@ -189,17 +220,21 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, out)
}
// setAccountBindings 负责set账号Bindings相关处理。
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
ChannelIDs []int64 `json:"channel_ids"`
ChannelID int64 `json:"channel_id"`
Enabled *bool `json:"enabled"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -207,10 +242,12 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
if !s.requireChannelOwner(w, r, req.ChannelID) {
return
}
// enabled 保存启用状态,供当前处理流程使用
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
// err 保存err,供当前处理流程使用
err := s.communicationApplication().SetSingleNotificationBinding(r.Context(), cid, req.ChannelID, enabled)
if err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
@@ -219,20 +256,25 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
return
}
// channelID 表示当前遍历过程中的渠道ID
for _, channelID := range req.ChannelIDs {
if !s.requireChannelOwner(w, r, channelID) {
return
}
}
if err := s.communicationApplication().SetNotificationBindings(r.Context(), cid, req.ChannelIDs); err != nil {
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().SetNotificationBindings(r.Context(), cid, req.ChannelIDs); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteMessageNotification 负责delete消息通知相关处理。
func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "notification_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
@@ -246,9 +288,13 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAccountNotifications 负责delete账号通知列表相关处理。
func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// err 保存err,供当前处理流程使用
err := s.communicationApplication().DeleteAccountNotificationBindings(r.Context(), sess.UserID, cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
+87 -11
View File
@@ -15,14 +15,19 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// refreshOrderChunkSize 保存refresh订单Chunk数量,供当前处理流程使用
const refreshOrderChunkSize = 100
// maxSoldOrderPages 保存maxSold订单Pages,供当前处理流程使用
const maxSoldOrderPages = 100
// refreshTarget 保存refreshTarget,供当前处理流程使用
type refreshTarget struct {
OrderID string
CurrentStatus string
}
// orderDetailMTop 保存订单DetailMTop,供当前处理流程使用
type orderDetailMTop interface {
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
}
@@ -41,7 +46,9 @@ func (s *Server) mountOrdersReal(r chi.Router) {
// listOrders 分页查询当前用户订单。
func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().List(r.Context(), orderListQuery{
UserID: sess.UserID, CookieID: r.URL.Query().Get("cookie_id"),
Status: r.URL.Query().Get("status"), Search: r.URL.Query().Get("search"),
@@ -67,8 +74,11 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
// getOrder 订单详情。
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().GetView(r.Context(), sess.UserID, orderID)
if err != nil {
if errors.Is(err, db.ErrForbidden) {
@@ -85,7 +95,9 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
// refreshOrders 将 HTTP 请求转换为订单刷新应用服务调用并编码兼容响应。
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().Refresh(r.Context(), sess.UserID, r.FormValue("cookie_id"), r.FormValue("status"))
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
@@ -101,34 +113,47 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
// 订单发现阶段将远端订单索引与本地软删除状态保持一致。
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) { // discoverSoldOrders 拉取远端订单列表并同步本地订单索引。
discovered, updated := 0, 0
// newOrderIDs 保存new订单IDs,供当前处理流程使用
newOrderIDs := make(map[string]struct{})
// remoteOrderIDs 保存remote订单IDs,供当前处理流程使用
remoteOrderIDs := make(map[string]struct{})
for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
for // pageNumber 保存页码Number,供当前处理流程使用
pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
// page、err 保存page、err,供当前处理流程使用
page, err := fetcher.FetchSoldOrdersPage(ctx, cookies, pageNumber, 30)
if err != nil {
return discovered, updated, newOrderIDs, remoteOrderIDs, err
}
// remote 表示当前遍历过程中的remote
for _, remote := range page.Items {
remoteOrderIDs[remote.OrderID] = struct{}{}
if normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok {
if // normalizedAmount、ok 保存normalizedAmount、ok,供当前处理流程使用
normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok {
remote.Amount = normalizedAmount
}
// existing、getErr 保存existing、getErr,供当前处理流程使用
existing, getErr := s.Store.Orders.Get(ctx, remote.OrderID)
// isNew 保存isNew,供当前处理流程使用
isNew := errors.Is(getErr, db.ErrNotFound)
if getErr != nil && !isNew {
return discovered, updated, newOrderIDs, remoteOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr)
}
// changed 保存changed,供当前处理流程使用
changed := isNew || soldOrderChanged(existing, remote)
// status 保存状态,供当前处理流程使用
status := remote.OrderStatus
if !isNew && status == "unknown" {
status = ""
}
// isBargain 保存isBargain,供当前处理流程使用
var isBargain *bool
if remote.IsBargain {
// value 保存值,供当前处理流程使用
value := true
isBargain = &value
}
if err := s.Store.Orders.Upsert(ctx, remote.OrderID, db.OrderUpsertOpts{
if // err 保存err,供当前处理流程使用
err := s.Store.Orders.Upsert(ctx, remote.OrderID, db.OrderUpsertOpts{
ItemID: remote.ItemID, BuyerID: remote.BuyerID, CookieID: cookieID,
OrderStatus: status, Quantity: remote.Quantity, Amount: remote.Amount,
ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone,
@@ -151,10 +176,12 @@ func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderF
return discovered, updated, newOrderIDs, remoteOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages)
}
// soldOrderChanged 负责sold订单Changed相关处理。
func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool {
if existing == nil {
return true
}
// statusChanged 保存状态Changed,供当前处理流程使用
statusChanged := remote.OrderStatus != "" && remote.OrderStatus != "unknown" &&
db.NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus
return statusChanged ||
@@ -169,12 +196,16 @@ func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool {
(remote.IsBargain && existing.IsBargain == 0)
}
// chunkRefreshTargets 负责chunkRefreshTargets相关处理。
func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
if size <= 0 {
size = refreshOrderChunkSize
}
// chunks 保存chunks,供当前处理流程使用
chunks := make([][]refreshTarget, 0, (len(targets)+size-1)/size)
for start := 0; start < len(targets); start += size {
for // start 保存开始,供当前处理流程使用
start := 0; start < len(targets); start += size {
// end 保存结束,供当前处理流程使用
end := start + size
if end > len(targets) {
end = len(targets)
@@ -184,10 +215,14 @@ func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
return chunks
}
// missingRefreshTargetIDs 负责missingRefreshTargetIDs相关处理。
func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{}) []string {
// missing 保存missing,供当前处理流程使用
missing := make([]string, 0)
// target 表示当前遍历过程中的target
for _, target := range targets {
if _, ok := seen[target.OrderID]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := seen[target.OrderID]; !ok {
missing = append(missing, target.OrderID)
}
}
@@ -196,7 +231,9 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { // refreshSingleOrder 保持单订单刷新与批量刷新使用相同的详情 DTO。
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().RefreshSingle(r.Context(), sess.UserID, orderID)
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "订单不存在")
@@ -227,9 +264,12 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { //
// deleteOrder 逻辑删除订单,保留订单历史,避免破坏自动化审计数据。
func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.orders().Delete(r.Context(), sess.UserID, orderID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.orders().Delete(r.Context(), sess.UserID, orderID); err != nil {
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
} else {
@@ -242,7 +282,9 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
// updateOrder 更新订单(手动发货等)。
func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
orderID := chi.URLParam(r, "order_id")
// req 保存req,供当前处理流程使用
var req struct {
OrderStatus *string `json:"order_status"`
Status *string `json:"status"`
@@ -260,15 +302,18 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
SystemShipped *bool `json:"system_shipped"`
ItemTitle *string `json:"item_title"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// status 保存状态,供当前处理流程使用
status := req.OrderStatus
if status == nil {
status = req.Status
}
if status != nil {
// normalized 保存normalized,供当前处理流程使用
normalized := db.NormalizeOrderStatus(strings.TrimSpace(*status))
if !validEditableOrderStatus(normalized) {
writeErr(w, http.StatusBadRequest, "不支持的订单状态")
@@ -276,15 +321,19 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
}
status = &normalized
}
// stringPtrFromAny 保存stringPtrFromAny,供当前处理流程使用
stringPtrFromAny := func(value *any) *string {
if value == nil {
return nil
}
// v 保存v,供当前处理流程使用
v := stringFromAny(*value)
return &v
}
// amount 保存amount,供当前处理流程使用
amount := stringPtrFromAny(req.Amount)
if amount != nil {
// normalized、ok 保存normalized、ok,供当前处理流程使用
normalized, ok := normalizeOrderAmount(*amount)
if !ok {
writeErr(w, http.StatusBadRequest, "订单金额必须是普通格式的非负有限数字")
@@ -292,14 +341,17 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
}
amount = &normalized
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if err := s.orders().Update(r.Context(), sess.UserID, orderID, orderUpdateRequest{
if // err 保存err,供当前处理流程使用
err := s.orders().Update(r.Context(), sess.UserID, orderID, orderUpdateRequest{
OrderStatus: status, ItemID: req.ItemID, BuyerID: req.BuyerID, SpecName: req.SpecName,
SpecValue: req.SpecValue, Quantity: stringPtrFromAny(req.Quantity), Amount: amount,
ReceiverName: req.ReceiverName, ReceiverPhone: req.ReceiverPhone, ReceiverAddress: req.ReceiverAddress,
ReceiverCity: req.ReceiverCity, ChatID: req.ChatID, SystemShipped: req.SystemShipped, ItemTitle: req.ItemTitle,
}); err != nil {
if kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest {
if // kind、classified 保存kind、classified,供当前处理流程使用
kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest {
writeErr(w, http.StatusBadRequest, err.Error())
} else if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
@@ -313,15 +365,19 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// validOrderAmount 负责有效订单Amount相关处理。
func validOrderAmount(raw string) bool {
// ok 保存ok,供当前处理流程使用
_, ok := normalizeOrderAmount(raw)
return ok
}
// normalizeOrderAmount 负责normalize订单Amount相关处理。
func normalizeOrderAmount(raw string) (string, bool) {
return db.NormalizeOrderAmount(raw)
}
// validEditableOrderStatus 负责有效Editable订单状态相关处理。
func validEditableOrderStatus(status string) bool {
switch status {
case "processing", "pending_ship", "shipped", "completed", "cancelled", "refunding":
@@ -331,12 +387,15 @@ func validEditableOrderStatus(status string) bool {
}
}
// manualShipOrders 负责manualShip订单列表相关处理。
func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
OrderIDs []string `json:"order_ids"`
ShipMode string `json:"ship_mode"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -351,7 +410,9 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "发货模式必须是 status_only 或 full_delivery")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().ManualShip(r.Context(), manualShipRequest{
UserID: sess.UserID, OrderIDs: req.OrderIDs, ShipMode: req.ShipMode,
})
@@ -367,9 +428,12 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
}
// consignWithCurrentCookie 负责consignWithCurrent登录凭证相关处理。
func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
defer credentialUnlock()
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(ctx, cookieID)
if err != nil {
return false, nil, "", false, err
@@ -380,8 +444,11 @@ func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID
if !hasStoredCookieCredential(detail) {
return false, nil, "", false, errors.New("账号 Cookie 为空")
}
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, detail)
// ok、ret、updatedCookies、callErr 保存ok、ret、updatedCookies、callErr,供当前处理流程使用
ok, ret, updatedCookies, callErr := s.MTop.ConsignContext(mtopCtx, detail.Value, orderID)
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, detail, cookieSession)
if persistErr != nil {
persistErr = fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr)
@@ -391,6 +458,7 @@ func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID
return ok, ret, "", false, persistErr
}
if handled {
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
if valueChanged {
runtimeCookie = value
@@ -403,19 +471,24 @@ func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID
if updatedCookies == "" || updatedCookies == detail.Value {
return ok, ret, "", false, nil
}
if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return ok, ret, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err)
}
return ok, ret, updatedCookies, true, nil
}
// importOrders 负责import订单列表相关处理。
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
// orders、err 保存orders、err,供当前处理流程使用
orders, err := parseImportedOrders(w, r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().Import(r.Context(), sess.UserID, orders)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询账号失败")
@@ -430,10 +503,12 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
})
}
// atoiDefault 负责atoiDefault相关处理。
func atoiDefault(s string, def int) int {
if s == "" {
return def
}
// n、err 保存n、err,供当前处理流程使用
n, err := strconv.Atoi(s)
if err != nil {
return def
@@ -441,6 +516,7 @@ func atoiDefault(s string, def int) int {
return n
}
// isStableOrderStatus 负责isStable订单状态相关处理。
func isStableOrderStatus(status string) bool {
switch status {
case "shipped", "completed", "cancelled":
+234 -14
View File
@@ -15,13 +15,18 @@ import (
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
func TestRefreshOrdersNoBrowser(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", strings.NewReader(""))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") {
@@ -29,14 +34,18 @@ func TestRefreshOrdersNoBrowser(t *testing.T) {
}
}
// TestRefreshOrdersDiscoversNewOrdersWithoutBrowser 负责TestRefresh订单列表DiscoversNew订单列表Without浏览器相关处理。
func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
`"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` +
`"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` +
@@ -44,15 +53,20 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
`"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order、err 保存order、err,供当前处理流程使用
order, err := store.Orders.Get(context.Background(), "sold-new-1")
if err != nil {
t.Fatal(err)
@@ -63,41 +77,56 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
}
}
// TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList 负责TestRefresh订单列表SoftDeletes订单列表MissingFromSellerList相关处理。
func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,cookie_id,order_status) VALUES ('buyer-order','buy-item','seller-account','acc1','pending_ship')`)
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"1"},"priceInfo":{"amount":{"value":"10.00"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
`"commonData":{"orderId":"seller-order","itemId":"seller-item","orderStatus":"待发货"},` +
`"buyerInfoVO":{"buyerId":"buyer-1"},"priceVO":{"totalPrice":"10.00","buyNum":"1"}}]}}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"soft_deleted":1`) {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// deletedAt 保存deletedAt,供当前处理流程使用
var deletedAt string
if err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "buyer-order").Scan(&deletedAt); err != nil || deletedAt == "" {
if // err 保存err,供当前处理流程使用
err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "buyer-order").Scan(&deletedAt); err != nil || deletedAt == "" {
t.Fatalf("缺失订单应逻辑删除,deleted_at=%q err=%v", deletedAt, err)
}
if _, err := store.Orders.Get(ctx, "buyer-order"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(ctx, "buyer-order"); err == nil {
t.Fatal("逻辑删除的购买订单不应再出现在活动订单查询中")
}
}
// TestMissingRefreshResultsAreCounted 负责TestMissingRefreshResultsAreCounted相关处理。
func TestMissingRefreshResultsAreCounted(t *testing.T) {
// targets 保存targets,供当前处理流程使用
targets := []refreshTarget{{OrderID: "a"}, {OrderID: "b"}, {OrderID: "c"}}
// missing 保存missing,供当前处理流程使用
missing := missingRefreshTargetIDs(targets, map[string]struct{}{"b": {}})
if len(missing) != 2 || missing[0] != "a" || missing[1] != "c" {
t.Fatalf("missing=%v", missing)
@@ -106,19 +135,26 @@ func TestMissingRefreshResultsAreCounted(t *testing.T) {
// TestRefreshSingleOrderUsesGoMTop 单订单刷新不依赖浏览器。
func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2","specName":"套餐","specValue":"30天"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('ord-x','item1','acc1','2')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/ord-x/refresh", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -128,14 +164,18 @@ func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
// TestRefreshSingleOrderNotFound 单订单刷新不存在订单 404。
func TestRefreshSingleOrderNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入非 nil Browser 但内部 playwright 不可用,订单查询先行 404。
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/no-such/refresh", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// Browser==nil → 503;先校验此路径不 panic。
@@ -146,17 +186,24 @@ func TestRefreshSingleOrderNotFound(t *testing.T) {
// TestUpdateOrder 更新订单字段(status 归一)。
func TestUpdateOrder(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('ord-u','item1','b1','2','acc1')`)
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item1','旧标题')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"status":"shipped","receiver_name":"张三","receiver_phone":"13800000000","receiver_address":"北京","item_title":"新标题"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-u", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -166,138 +213,185 @@ func TestUpdateOrder(t *testing.T) {
// 验证已写入。
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-u", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec2.Body.Bytes(), &got)
if got["order_status"] != "shipped" || got["receiver_name"] != "张三" {
t.Fatalf("更新未生效: %+v", got)
}
// item、err 保存item、err,供当前处理流程使用
item, err := store.Items.Get(ctx, "acc1", "item1")
if err != nil || item.ItemTitle != "新标题" {
t.Fatalf("商品标题未保存: item=%+v err=%v", item, err)
}
}
// TestUpdateOrderUsesNewItemIDForTitle 负责TestUpdate订单UsesNew商品IDFor标题相关处理。
func TestUpdateOrderUsesNewItemIDForTitle(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,order_status,cookie_id) VALUES ('ord-new-item','old-item','2','acc1')`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','old-item','旧商品')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-new-item", strings.NewReader(`{"item_id":" new-item ","item_title":"新商品"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order 保存订单,供当前处理流程使用
order, _ := store.Orders.Get(ctx, "ord-new-item")
if order.ItemID != "new-item" {
t.Fatalf("order item_id=%q", order.ItemID)
}
// newItem、err 保存newItem、err,供当前处理流程使用
newItem, err := store.Items.Get(ctx, "acc1", "new-item")
if err != nil || newItem.ItemTitle != "新商品" {
t.Fatalf("new item=%+v err=%v", newItem, err)
}
// oldItem 保存old商品,供当前处理流程使用
oldItem, _ := store.Items.Get(ctx, "acc1", "old-item")
if oldItem.ItemTitle != "旧商品" {
t.Fatalf("old item title changed: %+v", oldItem)
}
}
// TestImportOrdersRejectsInvalidAmountWithoutWritingOrder 负责TestImport订单列表RejectsInvalidAmountWithoutWriting订单相关处理。
func TestImportOrdersRejectsInvalidAmountWithoutWritingOrder(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
`[{"order_id":"bad-import-amount","cookie_id":"acc1","amount":"1e3"}]`,
))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "普通格式") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := store.Orders.Get(context.Background(), "bad-import-amount"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(context.Background(), "bad-import-amount"); err == nil {
t.Fatal("invalid imported amount must not create an order")
}
}
// TestImportOrdersRejectsUnknownStatusWithoutWritingOrder 负责TestImport订单列表RejectsUnknown状态WithoutWriting订单相关处理。
func TestImportOrdersRejectsUnknownStatusWithoutWritingOrder(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
`[{"order_id":"bad-import-status","cookie_id":"acc1","status":"anything","amount":"10"}]`,
))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "不支持的订单状态") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := store.Orders.Get(context.Background(), "bad-import-status"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(context.Background(), "bad-import-status"); err == nil {
t.Fatal("unknown imported status must not create an order")
}
}
// TestImportOrdersRollsBackOrderWhenItemWriteFails 负责TestImport订单列表RollsBack订单When商品WriteFails相关处理。
func TestImportOrdersRollsBackOrderWhenItemWriteFails(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `CREATE TRIGGER reject_import_item BEFORE INSERT ON item_info
WHEN NEW.item_id='reject-import-item' BEGIN SELECT RAISE(ABORT,'forced item failure'); END`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
`[{"order_id":"import-tx","cookie_id":"acc1","item_id":"reject-import-item","item_title":"商品","amount":"¥1,200.50"}]`,
))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "补全商品信息失败") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := store.Orders.Get(ctx, "import-tx"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(ctx, "import-tx"); err == nil {
t.Fatal("order must roll back when imported item write fails")
}
}
// TestUpdateOrderRejectsInvalidAmount 负责TestUpdate订单RejectsInvalidAmount相关处理。
func TestUpdateOrderRejectsInvalidAmount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,amount,order_status,cookie_id) VALUES ('ord-amount','item1','9.9','2','acc1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-amount", strings.NewReader(`{"amount":"abc"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order 保存订单,供当前处理流程使用
order, _ := store.Orders.Get(ctx, "ord-amount")
if order.Amount != "9.9" {
t.Fatalf("invalid amount was stored: %q", order.Amount)
}
}
// TestValidOrderAmountMatchesAnalyticsDecimalFormat 负责Test有效订单AmountMatchesAnalyticsDecimalFormat相关处理。
func TestValidOrderAmountMatchesAnalyticsDecimalFormat(t *testing.T) {
// invalid 表示当前遍历过程中的invalid
for _, invalid := range []string{"abc", "1e3", "+Inf", "NaN", "-1", "1.", "1,2", "12,34", "1,,000"} {
if validOrderAmount(invalid) {
t.Fatalf("%q must be rejected", invalid)
}
}
// input、want 表示当前遍历过程中的input、want
for input, want := range map[string]string{"": "", "0": "0", "12.50": "12.50", "¥1,200.50": "1200.50", "¥12.50": "12.50"} {
// got、ok 保存got、ok,供当前处理流程使用
got, ok := normalizeOrderAmount(input)
if !ok || got != want {
t.Fatalf("normalize(%q)=%q,%v want %q,true", input, got, ok, want)
@@ -305,76 +399,104 @@ func TestValidOrderAmountMatchesAnalyticsDecimalFormat(t *testing.T) {
}
}
// TestChunkRefreshTargetsBoundsBrowserBatchSize 负责TestChunkRefreshTargetsBounds浏览器批次数量相关处理。
func TestChunkRefreshTargetsBoundsBrowserBatchSize(t *testing.T) {
// targets 保存targets,供当前处理流程使用
targets := make([]refreshTarget, 205)
// i 表示当前遍历过程中的i
for i := range targets {
targets[i].OrderID = fmt.Sprintf("o-%d", i)
}
// chunks 保存chunks,供当前处理流程使用
chunks := chunkRefreshTargets(targets, 100)
if len(chunks) != 3 || len(chunks[0]) != 100 || len(chunks[1]) != 100 || len(chunks[2]) != 5 {
t.Fatalf("unexpected chunk sizes: %d/%d/%d total=%d", len(chunks[0]), len(chunks[1]), len(chunks[2]), len(chunks))
}
}
// TestUpdateOrderAndItemTitleRollBackTogether 负责TestUpdate订单And商品标题RollBackTogether相关处理。
func TestUpdateOrderAndItemTitleRollBackTogether(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,amount,order_status,cookie_id) VALUES ('ord-tx','old-item','9.9','2','acc1')`)
_, _ = store.DB.ExecContext(ctx, `CREATE TRIGGER reject_tx_item BEFORE INSERT ON item_info
WHEN NEW.item_id='tx-fail' BEGIN SELECT RAISE(ABORT,'forced item failure'); END`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-tx", strings.NewReader(`{"item_id":"tx-fail","item_title":"new","amount":"20"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order 保存订单,供当前处理流程使用
order, _ := store.Orders.Get(ctx, "ord-tx")
if order.ItemID != "old-item" || order.Amount != "9.9" {
t.Fatalf("order must roll back with item failure: %+v", order)
}
}
// TestUpdateOrderRejectsUnknownStatus 负责TestUpdate订单RejectsUnknown状态相关处理。
func TestUpdateOrderRejectsUnknownStatus(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,order_status,cookie_id) VALUES ('ord-status','item1','2','acc1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-status", strings.NewReader(`{"status":"anything"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order 保存订单,供当前处理流程使用
order, _ := store.Orders.Get(ctx, "ord-status")
if order.OrderStatus != "2" {
t.Fatalf("invalid status changed order: %+v", order)
}
}
// TestUpdateOrderCanExplicitlyClearFields 负责TestUpdate订单CanExplicitlyClear字段列表相关处理。
func TestUpdateOrderCanExplicitlyClearFields(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders
(order_id,item_id,buyer_id,order_status,cookie_id,amount,receiver_phone)
VALUES ('ord-clear','item1','b1','2','acc1','99.9','13800000000')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-clear", strings.NewReader(`{"amount":"","receiver_phone":""}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("clear status=%d body=%s", rec.Code, rec.Body.String())
}
// order、err 保存order、err,供当前处理流程使用
order, err := store.Orders.Get(ctx, "ord-clear")
if err != nil {
t.Fatal(err)
@@ -384,28 +506,37 @@ func TestUpdateOrderCanExplicitlyClearFields(t *testing.T) {
}
}
// TestListOrdersSearchUsesBackendPaginationScope 负责TestList订单列表搜索UsesBackendPaginationScope相关处理。
func TestListOrdersSearchUsesBackendPaginationScope(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id) VALUES
('ord-search-1','item-search','buyer-a','2','acc1'),
('ord-search-2','item-other','buyer-b','2','acc1')`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-search','Unique Product Name')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/api/orders?search=unique&page=1&page_size=1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("search status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
var response struct {
Total int `json:"total"`
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Total != 1 || len(response.Data) != 1 || response.Data[0]["order_id"] != "ord-search-1" {
@@ -415,15 +546,21 @@ func TestListOrdersSearchUsesBackendPaginationScope(t *testing.T) {
// TestUpdateOrderBadJSON 非法 JSON 应 400。
func TestUpdateOrderBadJSON(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id) VALUES ('ord-bad','item1','acc1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-bad", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -433,34 +570,45 @@ func TestUpdateOrderBadJSON(t *testing.T) {
// TestManualShipOrdersStatusOnlySuccess mtop ConsignContext 成功路径。
func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-m','item1','b1','2','acc1','chat1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":["ord-m"],"ship_mode":"status_only"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("manual ship status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["partial_failure"] != false {
t.Fatalf("应成功: %+v", res)
}
// results 保存results,供当前处理流程使用
results, _ := res["results"].([]any)
if len(results) != 1 {
t.Fatalf("应1条结果,got %d", len(results))
}
// 订单状态应已变为 shipped。
var ord map[string]any
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-m", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
json.Unmarshal(rec2.Body.Bytes(), &ord)
@@ -469,20 +617,28 @@ func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
}
}
// TestManualShipOrdersRejectsNonPendingStatus 负责TestManualShip订单列表RejectsNonPending状态相关处理。
func TestManualShipOrdersRejectsNonPendingStatus(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id,chat_id) VALUES ('ord-cancelled','item1','b1','cancelled','acc1','chat1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(`{"order_ids":["ord-cancelled"],"ship_mode":"status_only"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "仅待发货订单") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// order 保存订单,供当前处理流程使用
order, _ := store.Orders.Get(ctx, "ord-cancelled")
if order.OrderStatus != "cancelled" {
t.Fatalf("status changed: %+v", order)
@@ -491,8 +647,10 @@ func TestManualShipOrdersRejectsNonPendingStatus(t *testing.T) {
// TestManualShipOrdersConsignFail mtop ConsignContext 失败(非 success ret)。
func TestManualShipOrdersConsignFail(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-f','item1','b1','2','acc1','chat1')`)
@@ -501,16 +659,22 @@ func TestManualShipOrdersConsignFail(t *testing.T) {
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"}})
defer func() { srv.MTop = prev }()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":["ord-f"],"ship_mode":"status_only"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["partial_failure"] != true {
@@ -520,19 +684,26 @@ func TestManualShipOrdersConsignFail(t *testing.T) {
// TestManualShipOrdersOrderNotFound 订单不存在 → failed。
func TestManualShipOrdersOrderNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":["no-such-ord"],"ship_mode":"status_only"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d", rec.Code)
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["failed_count"] != float64(1) {
@@ -542,14 +713,20 @@ func TestManualShipOrdersOrderNotFound(t *testing.T) {
// TestManualShipOrdersBadMode 非法发货模式 400。
func TestManualShipOrdersBadMode(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":["ord-x"],"ship_mode":"bogus"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -559,14 +736,20 @@ func TestManualShipOrdersBadMode(t *testing.T) {
// TestManualShipOrdersEmpty 缺少订单 ID 400。
func TestManualShipOrdersEmpty(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":[],"ship_mode":"status_only"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -576,13 +759,18 @@ func TestManualShipOrdersEmpty(t *testing.T) {
// TestManualShipOrdersBadJSON 非法 JSON 400。
func TestManualShipOrdersBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -592,30 +780,40 @@ func TestManualShipOrdersBadJSON(t *testing.T) {
// TestManualShipOrdersFullDeliveryNoAutomation full_delivery 但自动化未初始化 → failed。
func TestManualShipOrdersFullDeliveryNoAutomation(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-full','item1','b1','2','acc1','chat1')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"order_ids":["ord-full"],"ship_mode":"full_delivery"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["failed_count"] != float64(1) {
t.Fatalf("应1失败,got %+v", res)
}
// results 保存results,供当前处理流程使用
results, _ := res["results"].([]any)
if len(results) != 1 {
t.Fatalf("结果数异常: %d", len(results))
}
// r0 保存r0,供当前处理流程使用
r0, _ := results[0].(map[string]any)
if !strings.Contains(r0["message"].(string), "自动化") {
t.Fatalf("应提示自动化未初始化,got %v", r0["message"])
@@ -624,15 +822,21 @@ func TestManualShipOrdersFullDeliveryNoAutomation(t *testing.T) {
// TestIsStableOrderStatus 稳定状态判定。
func TestIsStableOrderStatus(t *testing.T) {
// stable 保存stable,供当前处理流程使用
stable := map[string]bool{"shipped": true, "completed": true, "cancelled": true}
// unstable 保存unstable,供当前处理流程使用
unstable := map[string]bool{"pending_ship": false, "processing": false, "": false, "unknown": false}
// s、want 表示当前遍历过程中的s、want
for s, want := range stable {
if got := isStableOrderStatus(s); got != want {
if // got 保存got,供当前处理流程使用
got := isStableOrderStatus(s); got != want {
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
}
}
// s、want 表示当前遍历过程中的s、want
for s, want := range unstable {
if got := isStableOrderStatus(s); got != want {
if // got 保存got,供当前处理流程使用
got := isStableOrderStatus(s); got != want {
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
}
}
@@ -640,10 +844,14 @@ func TestIsStableOrderStatus(t *testing.T) {
// TestOrderApplicationServiceUsesTypedBusinessInputs 验证订单应用服务可脱离 HTTP 适配直接执行核心用例。
func TestOrderApplicationServiceUsesTypedBusinessInputs(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// service 保存service,供当前处理流程使用
service := srv.orders()
// list、err 保存list、err,供当前处理流程使用
list, err := service.List(ctx, orderListQuery{UserID: 1, Page: 0, PageSize: 999})
if err != nil {
t.Fatalf("订单服务列表查询失败: %v", err)
@@ -651,20 +859,25 @@ func TestOrderApplicationServiceUsesTypedBusinessInputs(t *testing.T) {
if list.Page != 1 || list.PageSize != 200 {
t.Fatalf("订单服务分页规范化异常: %+v", list)
}
if _, err := service.Import(ctx, 1, []map[string]any{{"order_id": "service-order", "cookie_id": "acc1", "status": "pending_ship", "amount": "12.50"}}); err != nil {
if // err 保存err,供当前处理流程使用
_, err := service.Import(ctx, 1, []map[string]any{{"order_id": "service-order", "cookie_id": "acc1", "status": "pending_ship", "amount": "12.50"}}); err != nil {
t.Fatalf("订单服务导入失败: %v", err)
}
if err := service.Update(ctx, 1, "service-order", orderUpdateRequest{Amount: stringPtrForOrderTest("13.00")}); err != nil {
if // err 保存err,供当前处理流程使用
err := service.Update(ctx, 1, "service-order", orderUpdateRequest{Amount: stringPtrForOrderTest("13.00")}); err != nil {
t.Fatalf("订单服务更新失败: %v", err)
}
// order、err 保存order、err,供当前处理流程使用
order, err := store.Orders.Get(ctx, "service-order")
if err != nil || order.Amount != "13.00" {
t.Fatalf("订单服务更新结果异常: order=%+v err=%v", order, err)
}
if err := service.Delete(ctx, 1, "service-order"); err != nil {
if // err 保存err,供当前处理流程使用
err := service.Delete(ctx, 1, "service-order"); err != nil {
t.Fatalf("订单服务删除失败: %v", err)
}
if _, err := store.Orders.Get(ctx, "service-order"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := store.Orders.Get(ctx, "service-order"); err == nil {
t.Fatal("订单服务删除后仍可查询活动订单")
}
}
@@ -676,22 +889,29 @@ func stringPtrForOrderTest(value string) *string {
// TestOrderResponseMappingAndErrorClassification 验证订单响应映射和业务错误分类不依赖 HTTP。
func TestOrderResponseMappingAndErrorClassification(t *testing.T) {
// row 保存row,供当前处理流程使用
row := db.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"}
// view 保存view,供当前处理流程使用
view := orderDTOFromRow(row)
if view.OrderStatus != "pending_ship" || view.Status != "pending_ship" || view.ItemImage != "https://img.example/mapped.png" {
t.Fatalf("订单响应映射异常: %+v", view)
}
// validationErr 保存validationErr,供当前处理流程使用
validationErr := newOrderBadRequest("不支持的订单状态")
if kind, ok := orderErrorKindOf(validationErr); !ok || kind != orderErrorBadRequest {
if // kind、ok 保存kind、ok,供当前处理流程使用
kind, ok := orderErrorKindOf(validationErr); !ok || kind != orderErrorBadRequest {
t.Fatalf("订单错误分类异常: kind=%v ok=%v", kind, ok)
}
}
// TestAtoiDefault atoiDefault 表驱动。
func TestAtoiDefault(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]int{"": 5, "abc": 5, "3": 3, "12": 12}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := atoiDefault(in, 5); got != want {
if // got 保存got,供当前处理流程使用
got := atoiDefault(in, 5); got != want {
t.Errorf("atoiDefault(%q)=%d want %d", in, got, want)
}
}
+91 -10
View File
@@ -22,7 +22,9 @@ import (
// parseImportedOrders 从 HTTP 请求体解析导入的订单。
// 支持两种入口:multipart/form-data 上传文件(按扩展名分流),或 raw body(按内容分流)。
// 上限 maxOrderImportBytes(32 MiB),由调用方在更上层用 MaxBytesReader 强制。
// parseImportedOrders 负责parseImported订单列表相关处理。
func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) {
// ct 保存ct,供当前处理流程使用
ct := r.Header.Get("Content-Type")
if strings.HasPrefix(ct, "multipart/form-data") {
// 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。
@@ -31,11 +33,13 @@ func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]a
if err := r.ParseMultipartForm(maxOrderImportBytes); err != nil {
return nil, fmt.Errorf("解析上传文件失败: %w", err)
}
// file、header、err 保存file、header、err,供当前处理流程使用
file, header, err := r.FormFile("file")
if err != nil {
return nil, fmt.Errorf("缺少上传文件")
}
defer file.Close()
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(file, int64(maxOrderImportBytes)+1))
if err != nil {
return nil, fmt.Errorf("读取上传文件失败: %w", err)
@@ -45,6 +49,7 @@ func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]a
}
return parseImportedOrderBytes(raw, header.Filename)
}
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(r.Body, int64(maxOrderImportBytes)+1))
if err != nil {
return nil, fmt.Errorf("读取请求失败: %w", err)
@@ -79,6 +84,7 @@ func parseImportedOrderBytes(raw []byte, filename string) ([]map[string]any, err
// parseJSONOrders 解析 JSON 数组或单对象。
func parseJSONOrders(raw []byte) ([]map[string]any, error) {
// trimmed 保存trimmed,供当前处理流程使用
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 {
return nil, fmt.Errorf("导入内容为空")
@@ -86,26 +92,35 @@ func parseJSONOrders(raw []byte) ([]map[string]any, error) {
if trimmed[0] == '[' {
return parseJSONOrderArray(trimmed)
}
// single 保存single,供当前处理流程使用
var single map[string]any
if err := json.Unmarshal(trimmed, &single); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(trimmed, &single); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
return normalizeImportOrderMaps([]map[string]any{single}), nil
}
// parseJSONOrderArray 负责parseJSON订单Array相关处理。
func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
// dec 保存dec,供当前处理流程使用
dec := json.NewDecoder(bytes.NewReader(raw))
// tok、err 保存tok、err,供当前处理流程使用
tok, err := dec.Token()
if err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
if delim, ok := tok.(json.Delim); !ok || delim != '[' {
if // delim、ok 保存delim、ok,供当前处理流程使用
delim, ok := tok.(json.Delim); !ok || delim != '[' {
return nil, fmt.Errorf("解析 JSON 失败: 不是数组")
}
// out 保存out,供当前处理流程使用
out := make([]map[string]any, 0, 256)
for dec.More() {
// row 保存row,供当前处理流程使用
var row map[string]any
if err := dec.Decode(&row); err != nil {
if // err 保存err,供当前处理流程使用
err := dec.Decode(&row); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
out = append(out, normalizeImportOrderMap(row))
@@ -115,11 +130,14 @@ func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
}
if tok, err = dec.Token(); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
} else if delim, ok := tok.(json.Delim); !ok || delim != ']' {
} else if // delim、ok 保存delim、ok,供当前处理流程使用
delim, ok := tok.(json.Delim); !ok || delim != ']' {
return nil, fmt.Errorf("解析 JSON 失败: 数组未闭合")
}
// extra 保存extra,供当前处理流程使用
var extra any
if err := dec.Decode(&extra); err != io.EOF {
if // err 保存err,供当前处理流程使用
err := dec.Decode(&extra); err != io.EOF {
if err == nil {
return nil, fmt.Errorf("解析 JSON 失败: 存在额外内容")
}
@@ -130,18 +148,24 @@ func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
// parseDelimitedOrders 解析 CSV/TSV(按 comma 分隔)。首行为表头,其余为数据行。
// 全空行跳过。
// parseDelimitedOrders 负责parseDelimited订单列表相关处理。
func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
// reader 保存reader,供当前处理流程使用
reader := csv.NewReader(bytes.NewReader(raw))
reader.Comma = comma
reader.FieldsPerRecord = -1
reader.LazyQuotes = true
// headerRow、err 保存headerRow、err,供当前处理流程使用
headerRow, err := reader.Read()
if err != nil {
return nil, fmt.Errorf("解析表格失败: %w", err)
}
// headers 保存headers,供当前处理流程使用
headers := normalizeImportHeaders(headerRow)
// rows 保存rows,供当前处理流程使用
rows := make([][]string, 0, 256)
for {
// record、err 保存record、err,供当前处理流程使用
record, err := reader.Read()
if err == io.EOF {
break
@@ -162,16 +186,21 @@ func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
// parseXLSXOrders 解析 .xlsx(OOXML):读取 sharedStrings + 第一个 worksheet,
// 按 cell ref(如 "C3")定位列索引,支持共享字符串、内联字符串、数字三种 cell 类型。
// parseXLSXOrders 负责parseXLSX订单列表相关处理。
func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
// zr、err 保存zr、err,供当前处理流程使用
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
}
// shared、err 保存shared、err,供当前处理流程使用
shared, err := xlsxSharedStrings(zr)
if err != nil {
return nil, err
}
// sheet 保存sheet,供当前处理流程使用
var sheet *zip.File
// f 表示当前遍历过程中的f
for _, f := range zr.File {
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
sheet = f
@@ -181,18 +210,26 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
if sheet == nil {
return nil, fmt.Errorf("xlsx 中未找到工作表")
}
// rawSheet、err 保存原始Sheet、err,供当前处理流程使用
rawSheet, err := readXLSXPart(sheet)
if err != nil {
return nil, err
}
// ws 保存ws,供当前处理流程使用
var ws xlsxWorksheet
if err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
if // err 保存err,供当前处理流程使用
err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
return nil, fmt.Errorf("解析工作表失败: %w", err)
}
// rows 保存rows,供当前处理流程使用
rows := make([][]string, 0, len(ws.SheetData.Rows))
// row 表示当前遍历过程中的row
for _, row := range ws.SheetData.Rows {
// values 保存values,供当前处理流程使用
values := []string{}
// cell 表示当前遍历过程中的cell
for _, cell := range row.Cells {
// idx 保存idx,供当前处理流程使用
idx := xlsxCellIndex(cell.Ref)
for len(values) <= idx {
values = append(values, "")
@@ -204,7 +241,9 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
if len(rows) < 2 {
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
}
// headers 保存headers,供当前处理流程使用
headers := normalizeImportHeaders(rows[0])
// out 保存out,供当前处理流程使用
out := rowsToMaps(headers, rows[1:])
if len(out) > maxOrderImportRows {
return nil, fmt.Errorf("单次最多导入 %d 条订单", maxOrderImportRows)
@@ -214,14 +253,20 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
// rowsToMaps 把表头 + 数据行转为 map 列表,全空行跳过。
func rowsToMaps(headers []string, rows [][]string) []map[string]any {
// out 保存out,供当前处理流程使用
out := make([]map[string]any, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
// m 保存m,供当前处理流程使用
m := make(map[string]any)
// nonEmpty 保存nonEmpty,供当前处理流程使用
nonEmpty := false
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
if h == "" || i >= len(row) {
continue
}
// v 保存v,供当前处理流程使用
v := strings.TrimSpace(row[i])
if v != "" {
nonEmpty = true
@@ -237,16 +282,19 @@ func rowsToMaps(headers []string, rows [][]string) []map[string]any {
// ---- XLSX OOXML 内部结构 ----
// xlsxWorksheet 保存xlsxWorksheet,供当前处理流程使用
type xlsxWorksheet struct {
SheetData struct {
Rows []xlsxRow `xml:"row"`
} `xml:"sheetData"`
}
// xlsxRow 保存xlsxRow,供当前处理流程使用
type xlsxRow struct {
Cells []xlsxCell `xml:"c"`
}
// xlsxCell 保存xlsxCell,供当前处理流程使用
type xlsxCell struct {
Ref string `xml:"r,attr"`
Type string `xml:"t,attr"`
@@ -254,6 +302,7 @@ type xlsxCell struct {
InlineStr string `xml:"is>t"`
}
// xlsxSST 保存xlsxSST,供当前处理流程使用
type xlsxSST struct {
Items []struct {
Inner string `xml:",innerxml"`
@@ -262,19 +311,25 @@ type xlsxSST struct {
// xlsxSharedStrings 读取 xl/sharedStrings.xml(共享字符串表),供 cell type="s" 引用。
func xlsxSharedStrings(zr *zip.Reader) ([]string, error) {
// f 表示当前遍历过程中的f
for _, f := range zr.File {
if f.Name != "xl/sharedStrings.xml" {
continue
}
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readXLSXPart(f)
if err != nil {
return nil, err
}
// sst 保存sst,供当前处理流程使用
var sst xlsxSST
if err := xmlUnmarshalXLSX(raw, &sst); err != nil {
if // err 保存err,供当前处理流程使用
err := xmlUnmarshalXLSX(raw, &sst); err != nil {
return nil, err
}
// out 保存out,供当前处理流程使用
out := make([]string, 0, len(sst.Items))
// item 表示当前遍历过程中的商品
for _, item := range sst.Items {
out = append(out, xmlCharData(item.Inner))
}
@@ -283,7 +338,9 @@ func xlsxSharedStrings(zr *zip.Reader) ([]string, error) {
return nil, nil
}
// readXLSXPart 负责readXLSXPart相关处理。
func readXLSXPart(f *zip.File) ([]byte, error) {
// rc、err 保存rc、err,供当前处理流程使用
rc, err := f.Open()
if err != nil {
return nil, err
@@ -292,7 +349,9 @@ func readXLSXPart(f *zip.File) ([]byte, error) {
return readLimitedXLSXXML(rc)
}
// readLimitedXLSXXML 负责readLimitedXLSXXML相关处理。
func readLimitedXLSXXML(r io.Reader) ([]byte, error) {
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(r, maxXLSXXMLPartBytes+1))
if err != nil {
return nil, err
@@ -303,6 +362,7 @@ func readLimitedXLSXXML(r io.Reader) ([]byte, error) {
return raw, nil
}
// xmlUnmarshalXLSX 负责xmlUnmarshalXLSX相关处理。
func xmlUnmarshalXLSX(raw []byte, v any) error {
return xml.Unmarshal(raw, v)
}
@@ -311,6 +371,7 @@ func xmlUnmarshalXLSX(raw []byte, v any) error {
func xlsxCellValue(cell xlsxCell, shared []string) string {
switch cell.Type {
case "s":
// idx 保存idx,供当前处理流程使用
idx, _ := strconv.Atoi(strings.TrimSpace(cell.Value))
if idx >= 0 && idx < len(shared) {
return shared[idx]
@@ -323,7 +384,9 @@ func xlsxCellValue(cell xlsxCell, shared []string) string {
// xlsxCellIndex 把 cell ref 的列部分(如 "C3" → "C")转为 0-based 列索引。
func xlsxCellIndex(ref string) int {
// idx 保存idx,供当前处理流程使用
idx := 0
// r 表示当前遍历过程中的r
for _, r := range ref {
if r < 'A' || r > 'Z' {
break
@@ -338,14 +401,18 @@ func xlsxCellIndex(ref string) int {
// xmlCharData 从 innerxml 片段中抽取所有字符数据(拼接富文本格式的单元格内容)。
func xmlCharData(inner string) string {
// dec 保存dec,供当前处理流程使用
dec := xml.NewDecoder(strings.NewReader("<x>" + inner + "</x>"))
// parts 保存parts,供当前处理流程使用
var parts []string
for {
// tok、err 保存tok、err,供当前处理流程使用
tok, err := dec.Token()
if err != nil {
break
}
if data, ok := tok.(xml.CharData); ok {
if // data、ok 保存data、ok,供当前处理流程使用
data, ok := tok.(xml.CharData); ok {
parts = append(parts, string(data))
}
}
@@ -356,23 +423,31 @@ func xmlCharData(inner string) string {
// normalizeImportOrderMaps 归一化 JSON 解析结果的 key(中文/英文别名 → 标准字段名)。
func normalizeImportOrderMaps(in []map[string]any) []map[string]any {
// out 保存out,供当前处理流程使用
out := make([]map[string]any, 0, len(in))
// raw 表示当前遍历过程中的原始
for _, raw := range in {
out = append(out, normalizeImportOrderMap(raw))
}
return out
}
// normalizeImportOrderMap 负责normalizeImport订单Map相关处理。
func normalizeImportOrderMap(raw map[string]any) map[string]any {
// m 保存m,供当前处理流程使用
m := make(map[string]any)
// k、v 表示当前遍历过程中的k、v
for k, v := range raw {
m[normalizeImportHeader(k)] = v
}
return m
}
// normalizeImportHeaders 负责normalizeImportHeaders相关处理。
func normalizeImportHeaders(headers []string) []string {
// out 保存out,供当前处理流程使用
out := make([]string, len(headers))
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
out[i] = normalizeImportHeader(h)
}
@@ -381,7 +456,9 @@ func normalizeImportHeaders(headers []string) []string {
// normalizeImportHeader 把表头归一为小写无分隔的标准字段名。
// 支持中英文别名(如 "订单号"→"order_id"、"商品标题"→"item_title")。
// normalizeImportHeader 负责normalizeImportHeader相关处理。
func normalizeImportHeader(header string) string {
// h 保存h,供当前处理流程使用
h := strings.ToLower(strings.TrimSpace(header))
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
switch h {
@@ -426,8 +503,11 @@ func normalizeImportHeader(header string) string {
// firstImportString 从归一化后的 map 中按候选 key 顺序取首个非空字符串。
func firstImportString(m map[string]any, keys ...string) string {
// k 表示当前遍历过程中的k
for _, k := range keys {
if v, ok := m[k]; ok {
if // v、ok 保存v、ok,供当前处理流程使用
v, ok := m[k]; ok {
// s 保存s,供当前处理流程使用
s := strings.TrimSpace(stringFromAny(v))
if s != "" {
return s
@@ -439,7 +519,8 @@ func firstImportString(m map[string]any, keys ...string) string {
// stringFromAny 把 any 安全转为字符串(nil→"",数字/布尔格式化)。
func stringFromAny(v any) string {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case nil:
return ""
case string:
+116 -12
View File
@@ -15,6 +15,7 @@ import (
// orderApplicationService 承载订单用例的业务编排,不依赖 HTTP 请求或响应对象。
// HTTP handler 只负责把请求转换为这些类型,再把结果编码为兼容 DTO。
// orderApplicationService 保存订单ApplicationService,供当前处理流程使用
type orderApplicationService struct {
// server 提供订单服务访问数据库、平台客户端和运行时依赖。
server *Server
@@ -22,7 +23,10 @@ type orderApplicationService struct {
repository orderRepository
}
// errOrderDetailUnsupported 保存err订单DetailUnsupported,供当前处理流程使用
var errOrderDetailUnsupported = errors.New("当前 Go MTOP 客户端不支持订单详情接口")
// errOrderCredentialChanged 保存err订单CredentialChanged,供当前处理流程使用
var errOrderCredentialChanged = errors.New("账号凭证已变化,请重试")
// orderErrorKind 标识应用服务错误的业务分类,避免 HTTP 层依赖错误文本判断状态码。
@@ -54,6 +58,7 @@ func newOrderBadRequest(message string) error {
// orderErrorKindOf 读取订单应用服务错误分类。
func orderErrorKindOf(err error) (orderErrorKind, bool) {
// applicationErr 保存applicationErr,供当前处理流程使用
var applicationErr *orderApplicationError
if !errors.As(err, &applicationErr) {
return 0, false
@@ -105,6 +110,7 @@ type orderListResult struct {
// orderDTOFromRow 把数据库订单列表行转换为稳定的订单响应视图。
func orderDTOFromRow(row db.OrderRow) orderDTO {
// status 保存状态,供当前处理流程使用
status := db.NormalizeOrderStatus(row.OrderStatus)
return orderDTO{
OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle,
@@ -120,11 +126,13 @@ func orderDTOFromRow(row db.OrderRow) orderDTO {
// orderDTOFromOrder 把订单实体和关联商品信息转换为详情响应视图。
func orderDTOFromOrder(order *db.Order, item *db.ItemInfo) orderDTO {
// itemTitle、itemImage 保存商品Title、item图片,供当前处理流程使用
itemTitle, itemImage := "", ""
if item != nil {
itemTitle = item.ItemTitle
itemImage = itemImageFromDetail(item.ItemDetail)
}
// status 保存状态,供当前处理流程使用
status := db.NormalizeOrderStatus(order.OrderStatus)
return orderDTO{
OrderID: order.OrderID, ItemID: order.ItemID, ItemTitle: itemTitle, ItemImage: itemImage,
@@ -157,7 +165,9 @@ func (a *orderApplicationService) List(ctx context.Context, query orderListQuery
if query.CookieID != "" && !a.orderOwnedByUser(ctx, query.UserID, query.CookieID) {
return orderListResult{}, db.ErrForbidden
}
// offset 保存偏移量,供当前处理流程使用
offset := (query.Page - 1) * query.PageSize
// rows、total、err 保存rows、total、err,供当前处理流程使用
rows, total, err := a.repository.ListOrdersForUser(ctx, db.OrderListFilter{
UserID: query.UserID, CookieID: query.CookieID, Status: query.Status,
Search: query.Search, Limit: query.PageSize, Offset: offset,
@@ -165,7 +175,9 @@ func (a *orderApplicationService) List(ctx context.Context, query orderListQuery
if err != nil {
return orderListResult{}, err
}
// orders 保存订单列表,供当前处理流程使用
orders := make([]orderDTO, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
orders = append(orders, orderDTOFromRow(row))
}
@@ -177,6 +189,7 @@ func (a *orderApplicationService) List(ctx context.Context, query orderListQuery
// Get 查询订单并校验订单绑定账号属于当前用户。
func (a *orderApplicationService) Get(ctx context.Context, userID int64, orderID string) (*db.Order, error) {
// order、err 保存order、err,供当前处理流程使用
order, err := a.repository.GetOrder(ctx, orderID)
if err != nil || order == nil {
if err != nil {
@@ -195,10 +208,12 @@ func (a *orderApplicationService) Get(ctx context.Context, userID int64, orderID
// GetView 查询订单并补全商品标题和主图,供详情 handler 直接编码。
func (a *orderApplicationService) GetView(ctx context.Context, userID int64, orderID string) (orderDetailResult, error) {
// order、err 保存order、err,供当前处理流程使用
order, err := a.Get(ctx, userID, orderID)
if err != nil {
return orderDetailResult{}, err
}
// item、itemErr 保存item、itemErr,供当前处理流程使用
item, itemErr := a.repository.GetItem(ctx, order.CookieID, order.ItemID)
if itemErr != nil {
item = nil
@@ -208,9 +223,11 @@ func (a *orderApplicationService) GetView(ctx context.Context, userID int64, ord
// Delete 逻辑删除订单,保留历史记录供审计使用。
func (a *orderApplicationService) Delete(ctx context.Context, userID int64, orderID string) error {
if _, err := a.Get(ctx, userID, orderID); err != nil {
if // err 保存err,供当前处理流程使用
_, err := a.Get(ctx, userID, orderID); err != nil {
return err
}
// err 保存err,供当前处理流程使用
_, err := a.repository.SoftDeleteOrder(ctx, orderID)
return err
}
@@ -249,11 +266,13 @@ type orderUpdateRequest struct {
// Update 在单事务内更新订单及可选的商品标题。
func (a *orderApplicationService) Update(ctx context.Context, userID int64, orderID string, request orderUpdateRequest) error {
// order、err 保存order、err,供当前处理流程使用
order, err := a.Get(ctx, userID, orderID)
if err != nil {
return err
}
if request.OrderStatus != nil {
// normalized 保存normalized,供当前处理流程使用
normalized := db.NormalizeOrderStatus(strings.TrimSpace(*request.OrderStatus))
if !validEditableOrderStatus(normalized) {
return newOrderBadRequest("不支持的订单状态")
@@ -261,17 +280,20 @@ func (a *orderApplicationService) Update(ctx context.Context, userID int64, orde
request.OrderStatus = &normalized
}
if request.Amount != nil {
// normalized、ok 保存normalized、ok,供当前处理流程使用
normalized, ok := normalizeOrderAmount(*request.Amount)
if !ok {
return newOrderBadRequest("订单金额必须是普通格式的非负有限数字")
}
request.Amount = &normalized
}
// finalItemID 保存final商品ID,供当前处理流程使用
finalItemID := strings.TrimSpace(order.ItemID)
if request.ItemID != nil {
finalItemID = strings.TrimSpace(*request.ItemID)
request.ItemID = &finalItemID
}
// itemTitle 保存商品标题,供当前处理流程使用
itemTitle := ""
if request.ItemTitle != nil {
itemTitle = strings.TrimSpace(*request.ItemTitle)
@@ -280,7 +302,8 @@ func (a *orderApplicationService) Update(ctx context.Context, userID int64, orde
}
}
return a.repository.WithTransaction(ctx, func(tx *sql.Tx) error {
if err := a.repository.PatchOrderTx(ctx, tx, orderID, db.OrderPatch{
if // err 保存err,供当前处理流程使用
err := a.repository.PatchOrderTx(ctx, tx, orderID, db.OrderPatch{
OrderStatus: request.OrderStatus, ItemID: request.ItemID, BuyerID: request.BuyerID,
SpecName: request.SpecName, SpecValue: request.SpecValue, Quantity: request.Quantity,
Amount: request.Amount, ReceiverName: request.ReceiverName, ReceiverPhone: request.ReceiverPhone,
@@ -290,7 +313,8 @@ func (a *orderApplicationService) Update(ctx context.Context, userID int64, orde
return err
}
if request.ItemTitle != nil {
if err := a.repository.UpsertItemBasicTx(ctx, tx, &db.ItemInfoRow{
if // err 保存err,供当前处理流程使用
err := a.repository.UpsertItemBasicTx(ctx, tx, &db.ItemInfoRow{
CookieID: order.CookieID, ItemID: finalItemID, ItemTitle: itemTitle,
}); err != nil {
return fmt.Errorf("更新商品标题失败: %w", err)
@@ -314,17 +338,22 @@ type orderImportResult struct {
// Import 按当前用户账号所有权逐单导入订单,并为订单关联商品补全基础信息。
func (a *orderApplicationService) Import(ctx context.Context, userID int64, rawOrders []map[string]any) (orderImportResult, error) {
// ownedCookieIDs、err 保存owned登录凭证IDs、err,供当前处理流程使用
ownedCookieIDs, err := a.repository.ListOwnedIDs(ctx, userID)
if err != nil {
return orderImportResult{}, err
}
// defaultCookieID 保存default登录凭证ID,供当前处理流程使用
defaultCookieID := ""
if len(ownedCookieIDs) == 1 {
defaultCookieID = ownedCookieIDs[0]
}
// result 保存结果,供当前处理流程使用
result := orderImportResult{Total: len(rawOrders), Results: make([]map[string]any, 0, len(rawOrders))}
// raw 表示当前遍历过程中的原始
for _, raw := range rawOrders {
if err := a.importOne(ctx, ownedCookieIDs, defaultCookieID, raw, &result); err != nil {
if // err 保存err,供当前处理流程使用
err := a.importOne(ctx, ownedCookieIDs, defaultCookieID, raw, &result); err != nil {
result.FailedCount++
result.Results = append(result.Results, errResult(raw, err.Error()))
continue
@@ -337,10 +366,12 @@ func (a *orderApplicationService) Import(ctx context.Context, userID int64, rawO
// importOne 在独立事务中写入一条订单及其商品信息。
func (a *orderApplicationService) importOne(ctx context.Context, ownedCookieIDs []string, defaultCookieID string, raw map[string]any, result *orderImportResult) error {
// orderID 保存订单ID,供当前处理流程使用
orderID := firstImportString(raw, "order_id")
if orderID == "" {
return errors.New("缺少必需字段: order_id")
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := firstImportString(raw, "cookie_id")
if cookieID == "" {
cookieID = defaultCookieID
@@ -351,6 +382,7 @@ func (a *orderApplicationService) importOne(ctx context.Context, ownedCookieIDs
if !containsCookieID(ownedCookieIDs, cookieID) {
return errors.New("无权操作此账号的订单")
}
// status 保存状态,供当前处理流程使用
status := firstImportString(raw, "order_status", "status", "status_text")
if status != "" {
status = db.NormalizeOrderStatus(status)
@@ -358,12 +390,15 @@ func (a *orderApplicationService) importOne(ctx context.Context, ownedCookieIDs
return errors.New("不支持的订单状态")
}
}
// amount、ok 保存amount、ok,供当前处理流程使用
amount, ok := normalizeOrderAmount(firstImportString(raw, "amount"))
if !ok {
return errors.New("订单金额必须是普通格式的非负有限数字")
}
if err := a.repository.WithTransaction(ctx, func(tx *sql.Tx) error {
if err := a.repository.UpsertOrderTx(ctx, tx, orderID, db.OrderUpsertOpts{
if // err 保存err,供当前处理流程使用
err := a.repository.WithTransaction(ctx, func(tx *sql.Tx) error {
if // err 保存err,供当前处理流程使用
err := a.repository.UpsertOrderTx(ctx, tx, orderID, db.OrderUpsertOpts{
CookieID: cookieID, ItemID: firstImportString(raw, "item_id"), BuyerID: firstImportString(raw, "buyer_id"),
OrderStatus: status, SpecName: firstImportString(raw, "spec_name"), SpecValue: firstImportString(raw, "spec_value"),
Quantity: firstImportString(raw, "quantity"), Amount: amount, ReceiverName: firstImportString(raw, "receiver_name"),
@@ -375,7 +410,8 @@ func (a *orderApplicationService) importOne(ctx context.Context, ownedCookieIDs
// itemID 是导入订单中关联的商品标识。
itemID := firstImportString(raw, "item_id")
if itemID != "" {
if err := a.repository.UpsertItemBasicTx(ctx, tx, &db.ItemInfoRow{
if // err 保存err,供当前处理流程使用
err := a.repository.UpsertItemBasicTx(ctx, tx, &db.ItemInfoRow{
CookieID: cookieID, ItemID: itemID, ItemTitle: firstImportString(raw, "item_title"),
ItemPrice: firstImportString(raw, "item_price"), ItemDetail: firstImportString(raw, "item_detail", "item_description"),
}); err != nil {
@@ -391,6 +427,7 @@ func (a *orderApplicationService) importOne(ctx context.Context, ownedCookieIDs
// errResult 生成导入失败的兼容结果行。
func errResult(raw map[string]any, message string) map[string]any {
// orderID 保存订单ID,供当前处理流程使用
orderID := firstImportString(raw, "order_id")
if orderID == "" {
orderID = "unknown"
@@ -420,16 +457,21 @@ type manualShipResult struct {
// ManualShip 执行状态确认或完整自动化发货,并集中处理逐单失败而不中断批次的规则。
func (a *orderApplicationService) ManualShip(ctx context.Context, request manualShipRequest) (manualShipResult, error) {
// ownedCookieIDs、err 保存owned登录凭证IDs、err,供当前处理流程使用
ownedCookieIDs, err := a.repository.ListOwnedIDs(ctx, request.UserID)
if err != nil {
return manualShipResult{}, err
}
// result 保存结果,供当前处理流程使用
result := manualShipResult{Results: make([]map[string]any, 0, len(request.OrderIDs))}
// rawOrderID 表示当前遍历过程中的原始订单ID
for _, rawOrderID := range request.OrderIDs {
// orderID 保存订单ID,供当前处理流程使用
orderID := strings.TrimSpace(rawOrderID)
if orderID == "" {
continue
}
// order、getErr 保存order、getErr,供当前处理流程使用
order, getErr := a.repository.GetOrder(ctx, orderID)
if getErr != nil || order == nil {
a.appendManualFailure(&result, orderID, "订单不存在")
@@ -464,10 +506,12 @@ func (a *orderApplicationService) manualFullDelivery(ctx context.Context, order
a.appendManualFailure(result, orderID, "自动化中心未初始化")
return
}
if _, running := a.server.Manager.GetInstance(order.CookieID); !running {
if // running 保存running,供当前处理流程使用
_, running := a.server.Manager.GetInstance(order.CookieID); !running {
a.appendManualFailure(result, orderID, "该账号未在线运行,无法执行完整发货")
return
}
// sent、err 保存sent、err,供当前处理流程使用
sent, err := a.server.automation.ManualFullDelivery(ctx, order)
if err != nil {
a.appendManualFailure(result, orderID, err.Error())
@@ -485,6 +529,7 @@ func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID i
a.appendManualFailure(result, orderID, "mtop 客户端未初始化")
return
}
// ok、ret、runtimeCookie、runtimeCookieChanged、err 保存ok、ret、runtimeCookie、runtime登录凭证Changed、err,供当前处理流程使用
ok, ret, runtimeCookie, runtimeCookieChanged, err := a.server.consignWithCurrentCookie(ctx, order.CookieID, orderID, userID)
if runtimeCookieChanged {
a.server.updateRunningCookie(ctx, order.CookieID, runtimeCookie)
@@ -495,6 +540,7 @@ func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID i
return
}
if !ok {
// message 保存消息,供当前处理流程使用
message := "确认发货失败"
if len(ret) > 0 {
message += ": " + strings.Join(ret, "; ")
@@ -503,7 +549,9 @@ func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID i
a.server.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货失败: "+message)
return
}
// sysShip 保存sysShip,供当前处理流程使用
sysShip := true
// upsertErr 保存upsertErr,供当前处理流程使用
upsertErr := a.repository.UpsertOrder(ctx, orderID, db.OrderUpsertOpts{
CookieID: order.CookieID, OrderStatus: "shipped", SystemShipped: &sysShip, ItemID: order.ItemID,
BuyerID: order.BuyerID, ReceiverName: order.ReceiverName, ReceiverPhone: order.ReceiverPhone,
@@ -514,7 +562,9 @@ func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID i
a.server.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", upsertErr)
}
result.SuccessCount++
// message 保存消息,供当前处理流程使用
message := "已成功修改闲鱼发货状态"
// warning 保存warning,供当前处理流程使用
warning := ""
if upsertErr != nil {
message += ";但登录凭证更新保存失败,请尽快重新登录(请勿重复确认发货)"
@@ -526,43 +576,57 @@ func (a *orderApplicationService) manualStatusShip(ctx context.Context, userID i
// RefreshSingle 刷新单个订单详情并写回本地订单。
func (a *orderApplicationService) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderSingleRefreshResponse, error) {
// order、err 保存order、err,供当前处理流程使用
order, err := a.Get(ctx, userID, orderID)
if err != nil {
return orderSingleRefreshResponse{}, err
}
// detailFetcher、ok 保存detailFetcher、ok,供当前处理流程使用
detailFetcher, ok := a.server.mtopClient().(orderDetailMTop)
if !ok {
return orderSingleRefreshResponse{}, errOrderDetailUnsupported
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := order.CookieID
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := a.repository.LockCredentials(cookieID)
// credentialLocked 保存credentialLocked,供当前处理流程使用
credentialLocked := true
defer func() {
if credentialLocked {
credentialUnlock()
}
}()
// latest、err 保存latest、err,供当前处理流程使用
latest, err := a.repository.LoadCookiePlatformDetail(ctx, cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
return orderSingleRefreshResponse{}, errOrderCredentialChanged
}
// refreshCtx、cancel 保存refreshCtx、cancel,供当前处理流程使用
refreshCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(refreshCtx, latest)
// detail、callErr 保存detail、callErr,供当前处理流程使用
detail, callErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, orderID)
if callErr == nil && detail == nil {
callErr = errors.New("订单详情接口未返回结果")
}
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
// runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用
runtimeCookieChanged := false
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
} else if handled && valueChanged {
runtimeCookie, runtimeCookieChanged = value, true
} else if !handled && callErr == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != latest.Value {
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithoutSnapshot(latest.MetadataJSON)
if saveErr := a.repository.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); saveErr == nil {
if // saveErr 保存saveErr,供当前处理流程使用
saveErr := a.repository.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); saveErr == nil {
runtimeCookie, runtimeCookieChanged = detail.UpdatedCookies, true
}
}
@@ -575,17 +639,22 @@ func (a *orderApplicationService) RefreshSingle(ctx context.Context, userID int6
a.server.recoverExpiredMTOPSession(ctx, cookieID, callErr)
return orderSingleRefreshResponse{}, callErr
}
// status 保存状态,供当前处理流程使用
status := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(status) {
status = db.NormalizeOrderStatus(order.OrderStatus)
}
if err := a.repository.UpsertOrder(ctx, orderID, db.OrderUpsertOpts{CookieID: cookieID, OrderStatus: status, SpecName: detail.SpecName, SpecValue: detail.SpecValue, Quantity: detail.Quantity, Amount: detail.Amount}); err != nil {
if // err 保存err,供当前处理流程使用
err := a.repository.UpsertOrder(ctx, orderID, db.OrderUpsertOpts{CookieID: cookieID, OrderStatus: status, SpecName: detail.SpecName, SpecValue: detail.SpecValue, Quantity: detail.Quantity, Amount: detail.Amount}); err != nil {
return orderSingleRefreshResponse{}, err
}
return orderSingleRefreshResponse{Success: true, Message: "订单刷新完成", Order: orderRefreshDetailResponse{Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, OrderStatus: db.NormalizeOrderStatus(detail.OrderStatus), Amount: detail.Amount}}, nil
}
// Refresh 刷新当前值。
func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) {
// cookieIDs、err 保存登录凭证IDs、err,供当前处理流程使用
cookieIDs, err := a.repository.ListOwnedIDs(ctx, userID)
if err != nil {
return orderRefreshResponse{}, err
@@ -597,13 +666,19 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
cookieIDs = []string{cookieID}
}
// discovered、listUpdated、softDeleted、failed 保存discovered、listUpdated、softDeleted、failed,供当前处理流程使用
discovered, listUpdated, softDeleted, failed := 0, 0, 0, 0
// results 保存results,供当前处理流程使用
results := []map[string]any{}
// newOrderIDs 保存new订单IDs,供当前处理流程使用
newOrderIDs := make(map[string]struct{})
// sessionExpiredAccounts 保存会话Expired账号列表,供当前处理流程使用
sessionExpiredAccounts := make(map[string]struct{})
if fetcher, ok := a.server.mtopClient().(mtop.SoldOrderFetcher); ok {
if // fetcher、ok 保存fetcher、ok,供当前处理流程使用
fetcher, ok := a.server.mtopClient().(mtop.SoldOrderFetcher); ok {
for _, cid := range cookieIDs { // cid 是当前待刷新的账号 ID。
credentialUnlock := a.repository.LockCredentials(cid)
// latest、latestErr 保存latest、latestErr,供当前处理流程使用
latest, latestErr := a.repository.LoadCookiePlatformDetail(ctx, cid)
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
@@ -618,7 +693,9 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
}
// latest.Value 仅用于当前账号的凭证调用,不需要写回账号列表。
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
// accountDiscovered、accountUpdated、accountNewIDs、accountRemoteIDs、discoveryErr 保存账号Discovered、accountUpdated、accountNewIDs、accountRemoteIDs、discoveryErr,供当前处理流程使用
accountDiscovered, accountUpdated, accountNewIDs, accountRemoteIDs, discoveryErr := a.server.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
// value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
@@ -635,14 +712,17 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
}
discovered += accountDiscovered
listUpdated += accountUpdated
// orderID 表示当前遍历过程中的订单ID
for orderID := range accountNewIDs {
newOrderIDs[orderID] = struct{}{}
}
// result 保存结果,供当前处理流程使用
result := map[string]any{
"cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
"discovered": accountDiscovered, "updated": accountUpdated,
}
if discoveryErr == nil {
// deleted、deleteErr 保存deleted、deleteErr,供当前处理流程使用
deleted, deleteErr := a.repository.SoftDeleteMissingOrders(ctx, cid, accountRemoteIDs)
if deleteErr != nil {
discoveryErr = fmt.Errorf("标记缺失订单失败: %w", deleteErr)
@@ -663,17 +743,22 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
results = append(results, map[string]any{"stage": "discover", "success": false, "message": "当前 MTop 客户端不支持订单列表发现"})
}
// ordersByCookie 保存订单列表By登录凭证,供当前处理流程使用
ordersByCookie := map[string][]refreshTarget{}
for _, cid := range cookieIDs { // cid 是当前需要补充订单的账号 ID。
if _, blocked := sessionExpiredAccounts[cid]; blocked {
continue
}
for offset := 0; ; offset += 500 {
for // offset 保存偏移量,供当前处理流程使用
offset := 0; ; offset += 500 {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := a.repository.ListOrdersByCookiePage(ctx, cid, 500, offset)
if err != nil {
break
}
// row 表示当前遍历过程中的row
for _, row := range rows {
// currentStatus 保存current状态,供当前处理流程使用
currentStatus := db.NormalizeOrderStatus(row.OrderStatus)
if status != "" && status != "all" && currentStatus != status {
continue
@@ -691,12 +776,16 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
}
}
// total 保存总数,供当前处理流程使用
total := 0
// targets 表示当前遍历过程中的targets
for _, targets := range ordersByCookie {
total += len(targets)
}
// detailFetcher、detailSupported 保存detailFetcher、detailSupported,供当前处理流程使用
detailFetcher, detailSupported := a.server.mtopClient().(orderDetailMTop)
if !detailSupported {
// message 保存消息,供当前处理流程使用
message := "订单列表同步完成"
if discovered > 0 {
message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
@@ -727,10 +816,15 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
// 订单详情刷新阶段分别统计状态变化和无变化结果。
updated, noChange := 0, 0
// cid、targets 表示当前遍历过程中的cid、targets
for cid, targets := range ordersByCookie {
// accountSessionExpired 保存账号会话Expired,供当前处理流程使用
accountSessionExpired := false
// chunk 表示当前遍历过程中的chunk
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := a.repository.LockCredentials(cid)
// latest、latestErr 保存latest、latestErr,供当前处理流程使用
latest, latestErr := a.repository.LoadCookiePlatformDetail(ctx, cid)
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
@@ -738,13 +832,19 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
results = append(results, map[string]any{"cookie_id": cid, "success": false, "message": "账号凭证已变化"})
continue
}
// detailCtx、cancel 保存detailCtx、cancel,供当前处理流程使用
detailCtx, cancel := context.WithTimeout(ctx, 3*time.Minute)
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(detailCtx, latest)
// sessionErr 保存会话Err,供当前处理流程使用
var sessionErr error
// target 表示当前遍历过程中的target
for _, target := range chunk {
// detail、fetchErr 保存detail、fetchErr,供当前处理流程使用
detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
if fetchErr != nil || detail == nil {
failed++
// message 保存消息,供当前处理流程使用
message := "订单详情接口未返回结果"
if fetchErr != nil {
message = fetchErr.Error()
@@ -760,10 +860,12 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
}
continue
}
// newStatus 保存new状态,供当前处理流程使用
newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(newStatus) {
newStatus = target.CurrentStatus
}
// err 保存err,供当前处理流程使用
err := a.repository.UpsertOrder(ctx, target.OrderID, db.OrderUpsertOpts{
CookieID: cid,
OrderStatus: newStatus,
@@ -777,6 +879,7 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "message": "更新数据库失败"})
continue
}
// changed 保存changed,供当前处理流程使用
changed := newStatus != "" && newStatus != target.CurrentStatus
if changed {
updated++
@@ -791,6 +894,7 @@ func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, coo
})
}
cancel()
// value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
credentialUnlock()
if persistErr != nil {
+3
View File
@@ -7,12 +7,15 @@ import (
"xianyu-go/internal/db"
)
// requireCookieOwner 负责require登录凭证所有者相关处理。
func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return nil, false
}
// d、err 保存d、err,供当前处理流程使用
d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cookieID)
if err != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
+90 -19
View File
@@ -12,21 +12,29 @@ import (
"testing"
)
// TestParseMoneyCents 负责TestParseMoneyCents相关处理。
func TestParseMoneyCents(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]int64{"1": 100, "1.2": 120, "¥12.34": 1234, "¥0.01": 1, "-0.50": -50, "+2.05": 205, "": 0}
// raw、want 表示当前遍历过程中的raw、want
for raw, want := range cases {
// got、err 保存got、err,供当前处理流程使用
got, err := parseMoneyCents(raw)
if err != nil || got != want {
t.Errorf("parseMoneyCents(%q) = %d, %v; want %d", raw, got, err, want)
}
}
if _, err := parseMoneyCents("1.2.3"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := parseMoneyCents("1.2.3"); err == nil {
t.Fatal("invalid money should fail")
}
}
// TestOrderImportParsers 负责Test订单ImportParsers相关处理。
func TestOrderImportParsers(t *testing.T) {
// csvData 保存csv数据,供当前处理流程使用
csvData := []byte("订单号,商品ID,买家ID,金额,状态\no1,i1,b1,12.50,已付款\n")
// rows、err 保存rows、err,供当前处理流程使用
rows, err := parseImportedOrderBytes(csvData, "orders.csv")
if err != nil || len(rows) != 1 {
t.Fatalf("parse csv = %#v, %v", rows, err)
@@ -38,7 +46,8 @@ func TestOrderImportParsers(t *testing.T) {
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o2" {
t.Fatalf("parse json = %#v, %v", rows, err)
}
if _, err := parseImportedOrderBytes(nil, "orders.csv"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := parseImportedOrderBytes(nil, "orders.csv"); err == nil {
t.Fatal("empty import should fail")
}
}
@@ -46,7 +55,9 @@ func TestOrderImportParsers(t *testing.T) {
// TestOrderImportFormats 覆盖 TSV、单对象 JSON、.xls 拒绝、无扩展名默认 CSV。
func TestOrderImportFormats(t *testing.T) {
// TSV
// tsv 保存tsv,供当前处理流程使用
tsv := []byte("order_id\tamount\no1\t1.5\n")
// rows、err 保存rows、err,供当前处理流程使用
rows, err := parseImportedOrderBytes(tsv, "orders.tsv")
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o1" {
t.Fatalf("parse tsv = %#v, %v", rows, err)
@@ -81,33 +92,41 @@ func TestOrderImportFormats(t *testing.T) {
}
}
// TestOrderImportRejectsTooManyRows 负责Test订单ImportRejectsTooManyRows相关处理。
func TestOrderImportRejectsTooManyRows(t *testing.T) {
// b 保存b,供当前处理流程使用
var b strings.Builder
b.WriteString("order_id\n")
for i := 0; i < maxOrderImportRows+1; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < maxOrderImportRows+1; i++ {
_, _ = fmt.Fprintf(&b, "o%d\n", i)
}
if _, err := parseImportedOrderBytes([]byte(b.String()), "orders.csv"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := parseImportedOrderBytes([]byte(b.String()), "orders.csv"); err == nil {
t.Fatal("too many import rows should fail")
}
b.Reset()
b.WriteString("[")
for i := 0; i < maxOrderImportRows+1; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < maxOrderImportRows+1; i++ {
if i > 0 {
b.WriteString(",")
}
_, _ = fmt.Fprintf(&b, `{"order_id":"o%d"}`, i)
}
b.WriteString("]")
if _, err := parseImportedOrderBytes([]byte(b.String()), "orders.json"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := parseImportedOrderBytes([]byte(b.String()), "orders.json"); err == nil {
t.Fatal("too many JSON import rows should fail")
}
}
// TestParseXLSXOrders 构造一个最小 xlsx,验证 shared string + 数字 cell 解析。
func TestParseXLSXOrders(t *testing.T) {
// xlsx 保存xlsx,供当前处理流程使用
xlsx := buildMinimalXLSX(t, [][]string{{"order_id", "amount"}, {"o1", "12.5"}})
// rows、err 保存rows、err,供当前处理流程使用
rows, err := parseXLSXOrders(xlsx)
if err != nil {
t.Fatalf("parseXLSX: %v", err)
@@ -117,16 +136,21 @@ func TestParseXLSXOrders(t *testing.T) {
}
}
// TestReadLimitedXLSXXMLRejectsOversizedPart 负责TestReadLimitedXLSXXMLRejectsOversizedPart相关处理。
func TestReadLimitedXLSXXMLRejectsOversizedPart(t *testing.T) {
// err 保存err,供当前处理流程使用
_, err := readLimitedXLSXXML(io.LimitReader(endlessByteReader{}, maxXLSXXMLPartBytes+1))
if err == nil {
t.Fatal("oversized xlsx XML should fail")
}
}
// endlessByteReader 保存endlessByteReader,供当前处理流程使用
type endlessByteReader struct{}
// Read 读取当前值。
func (endlessByteReader) Read(p []byte) (int, error) {
// i 表示当前遍历过程中的i
for i := range p {
p[i] = 'x'
}
@@ -135,6 +159,7 @@ func (endlessByteReader) Read(p []byte) (int, error) {
// TestNormalizeImportHeader 表驱动验证中英文别名归一。
func TestNormalizeImportHeader(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"订单号": "order_id",
"OrderID": "order_id",
@@ -146,8 +171,10 @@ func TestNormalizeImportHeader(t *testing.T) {
"会话id": "chat_id",
"unknown_field": "unknown_field",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := normalizeImportHeader(in); got != want {
if // got 保存got,供当前处理流程使用
got := normalizeImportHeader(in); got != want {
t.Errorf("normalizeImportHeader(%q) = %q; want %q", in, got, want)
}
}
@@ -155,14 +182,20 @@ func TestNormalizeImportHeader(t *testing.T) {
// buildMinimalXLSX 构造一个仅含 sheet1 + sharedStrings 的最小 .xlsx 字节流。
// cell 用 shared string(t="s")引用,与 Excel 默认导出一致。
// buildMinimalXLSX 负责buildMinimalXLSX相关处理。
func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
t.Helper()
// shared 保存shared,供当前处理流程使用
var shared []string
// sharedIdx 保存sharedIdx,供当前处理流程使用
sharedIdx := map[string]int{}
// addShared 保存addShared,供当前处理流程使用
addShared := func(s string) int {
if i, ok := sharedIdx[s]; ok {
if // i、ok 保存i、ok,供当前处理流程使用
i, ok := sharedIdx[s]; ok {
return i
}
// i 保存i,供当前处理流程使用
i := len(shared)
shared = append(shared, s)
sharedIdx[s] = i
@@ -172,10 +205,14 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
// 构造 worksheet xml。
var rowsXML strings.Builder
rowsXML.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>`)
// r、row 表示当前遍历过程中的r、row
for r, row := range grid {
fmt.Fprintf(&rowsXML, `<row r="%d">`, r+1)
// c、val 表示当前遍历过程中的c、val
for c, val := range row {
// ref 保存ref,供当前处理流程使用
ref := fmt.Sprintf("%c%d", 'A'+c, r+1)
// idx 保存idx,供当前处理流程使用
idx := addShared(val)
fmt.Fprintf(&rowsXML, `<c r="%s" t="s"><v>%d</v></c>`, ref, idx)
}
@@ -183,21 +220,28 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
}
rowsXML.WriteString(`</sheetData></worksheet>`)
// sstXML 保存sstXML,供当前处理流程使用
var sstXML strings.Builder
sstXML.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
// s 表示当前遍历过程中的s
for _, s := range shared {
sstXML.WriteString(`<si><t>` + s + `</t></si>`)
}
sstXML.WriteString(`</sst>`)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
zw := zip.NewWriter(&buf)
// must 保存must,供当前处理流程使用
must := func(name, content string) {
// f、err 保存f、err,供当前处理流程使用
f, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write([]byte(content)); err != nil {
if // err 保存err,供当前处理流程使用
_, err := f.Write([]byte(content)); err != nil {
t.Fatal(err)
}
}
@@ -210,26 +254,36 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
return buf.Bytes()
}
// TestPublishBatchPathAndZipSafety 负责Test发布批次路径AndZipSafety相关处理。
func TestPublishBatchPathAndZipSafety(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{"../secret.png", "/etc/passwd", `..\\secret.png`, ""} {
if _, err := safeZipPath(raw); err == nil {
if // err 保存err,供当前处理流程使用
_, err := safeZipPath(raw); err == nil {
t.Errorf("safeZipPath(%q) should fail", raw)
}
}
if got, err := safeZipPath("images/a.png"); err != nil || got != filepath.Join("images", "a.png") {
if // got、err 保存got、err,供当前处理流程使用
got, err := safeZipPath("images/a.png"); err != nil || got != filepath.Join("images", "a.png") {
t.Fatalf("safe path = %q, %v", got, err)
}
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
zw := zip.NewWriter(&buf)
// f 保存f,供当前处理流程使用
f, _ := zw.Create("images/a.png")
_, _ = f.Write([]byte("not-an-image"))
_ = zw.Close()
if err := extractPublishImagesZip(buf.Bytes(), dest); err != nil {
if // err 保存err,供当前处理流程使用
err := extractPublishImagesZip(buf.Bytes(), dest); err != nil {
t.Fatalf("extract non-image: %v", err)
}
if _, err := os.Stat(filepath.Join(dest, "images", "a.png")); !os.IsNotExist(err) {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(filepath.Join(dest, "images", "a.png")); !os.IsNotExist(err) {
t.Fatal("non-image must not be extracted")
}
@@ -238,26 +292,33 @@ func TestPublishBatchPathAndZipSafety(t *testing.T) {
f, _ = zw.Create("../escape.png")
_, _ = f.Write([]byte("x"))
_ = zw.Close()
if err := extractPublishImagesZip(buf.Bytes(), dest); err == nil {
if // err 保存err,供当前处理流程使用
err := extractPublishImagesZip(buf.Bytes(), dest); err == nil {
t.Fatal("zip traversal should fail")
}
}
// TestPublishBatchHelpers 负责Test发布批次Helpers相关处理。
func TestPublishBatchHelpers(t *testing.T) {
if got := splitImageRefs("a.png; b.png\nc.png"); len(got) != 3 {
if // got 保存got,供当前处理流程使用
got := splitImageRefs("a.png; b.png\nc.png"); len(got) != 3 {
t.Fatalf("splitImageRefs = %#v", got)
}
// value 表示当前遍历过程中的值
for _, value := range []string{"1", "TRUE", "yes", "是", "启用"} {
if !parseLooseBool(value) {
t.Errorf("parseLooseBool(%q) = false", value)
}
}
if got := atoiPublishDefault("2.9", 1); got != 2 {
if // got 保存got,供当前处理流程使用
got := atoiPublishDefault("2.9", 1); got != 2 {
t.Fatalf("atoiPublishDefault = %d", got)
}
}
// TestParsePublishCardActions 负责TestParse发布卡密动作列表相关处理。
func TestParsePublishCardActions(t *testing.T) {
// actions、parseErr 保存actions、parseErr,供当前处理流程使用
actions, parseErr := parsePublishCardActions("101:1:0; 102:2:3")
if parseErr != "" {
t.Fatalf("parsePublishCardActions: %s", parseErr)
@@ -271,15 +332,19 @@ func TestParsePublishCardActions(t *testing.T) {
if actions[1].CardID != 102 || actions[1].DeliveryCount != 2 || actions[1].DelaySeconds != 3 {
t.Fatalf("actions[1]=%+v", actions[1])
}
if _, parseErr := parsePublishCardActions("101:0"); parseErr == "" {
if // parseErr 保存parseErr,供当前处理流程使用
_, parseErr := parsePublishCardActions("101:0"); parseErr == "" {
t.Fatal("每件份数为0时应返回格式错误")
}
if got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" {
if // got 保存got,供当前处理流程使用
got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" {
t.Fatalf("normalizePublishHeader=%q", got)
}
}
// TestNormalizePublishHeaderCategoryFallbackLabels 负责TestNormalize发布Header分类FallbackLabels相关处理。
func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"类目ID": "category_id",
"类目名称": "category_name",
@@ -287,14 +352,18 @@ func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
"淘宝类目ID": "tb_category_id",
"category_id": "category_id",
}
// input、want 表示当前遍历过程中的input、want
for input, want := range cases {
if got := normalizePublishHeader(input); got != want {
if // got 保存got,供当前处理流程使用
got := normalizePublishHeader(input); got != want {
t.Fatalf("normalizePublishHeader(%q)=%q want %q", input, got, want)
}
}
}
// TestParsePublishAutomationSupportsMultipleCards 负责TestParse发布自动化SupportsMultiple卡密列表相关处理。
func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
// cfg 保存cfg,供当前处理流程使用
cfg := parsePublishAutomation(map[string]any{
"paid_delivery_enabled": "是",
"paid_delivery_contents": "101:1:0;102:2:0",
@@ -309,7 +378,9 @@ func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
}
}
// TestPublicIPValidation 负责TestPublicIPValidation相关处理。
func TestPublicIPValidation(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{"127.0.0.1", "10.0.0.1", "169.254.1.1", "::1"} {
if isPublicIP(net.ParseIP(raw)) {
t.Errorf("private IP accepted: %s", raw)
@@ -8,6 +8,7 @@ import (
// mountPasswordLogin 保留历史 API 路径,避免旧前端收到 404。Go 客户端的
// 登录凭证只允许由扫码流程产生;这里永远不会调用 Chromium 密码登录。
// mountPasswordLogin 负责mount密码登录相关处理。
func (s *Server) mountPasswordLogin(r chi.Router) {
r.Post("/password-login", s.passwordLoginDisabled)
r.Get("/password-login/check/{session_id}", s.passwordLoginDisabled)
@@ -8,26 +8,35 @@ import (
"testing"
)
// TestPasswordLoginAPIsArePermanentlyDisabled 负责Test密码登录APIsArePermanentlyDisabled相关处理。
func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// authCookie 保存auth登录凭证,供当前处理流程使用
authCookie := loginHelper(t, h)
// requests 保存请求列表,供当前处理流程使用
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(`{"account_id":"acc1","account":"u","password":"p"}`)),
httptest.NewRequest(http.MethodGet, "/password-login/check/legacy", nil),
httptest.NewRequest(http.MethodDelete, "/password-login/cancel/legacy", nil),
}
// req 表示当前遍历过程中的req
for _, req := range requests {
req.AddCookie(authCookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotImplemented {
t.Fatalf("%s %s status=%d body=%s", req.Method, req.URL.Path, rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
var result map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result["code"] != "password_login_disabled" || result["message"] == "" {
+134 -16
View File
@@ -23,7 +23,9 @@ import (
// minimalPNG 是一张 1x1 PNG,供发布批次图片 zip 复用。
var minimalPNG = []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
// TestFinalPublishBatchStatus 负责TestFinal发布批次状态相关处理。
func TestFinalPublishBatchStatus(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in db.ItemPublishBatch
@@ -33,16 +35,20 @@ func TestFinalPublishBatchStatus(t *testing.T) {
{name: "failed", in: db.ItemPublishBatch{FailedCount: 2}, want: "failed"},
{name: "partially failed", in: db.ItemPublishBatch{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"},
}
// tt 表示当前遍历过程中的tt
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
if got := finalPublishBatchStatus(&tt.in); got != tt.want {
if // got 保存got,供当前处理流程使用
got := finalPublishBatchStatus(&tt.in); got != tt.want {
t.Fatalf("got %q want %q", got, tt.want)
}
})
}
}
// TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled 负责Test发布批次FailurePreservesUncertainRemoteWarningWhenCanceled相关处理。
func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testing.T) {
// message、kind 保存message、kind,供当前处理流程使用
message, kind := publishBatchFailure(&uncertainRemotePublishError{err: context.Canceled}, "canceling")
if kind != "uncertain_remote" || !strings.Contains(message, "任务已取消") ||
!strings.Contains(message, "禁止自动重试") || !strings.Contains(message, "人工核对") {
@@ -54,13 +60,17 @@ func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testi
}
}
// TestCancelPublishBatchRequiresMatchingWorkerToken 负责Test取消发布批次RequiresMatching工作器令牌相关处理。
func TestCancelPublishBatchRequiresMatchingWorkerToken(t *testing.T) {
// srv 保存srv,供当前处理流程使用
srv := &Server{publishCancels: make(map[string]publishBatchWorker)}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
srv.registerPublishBatchCancel("batch", "current", cancel)
if canceled := srv.cancelPublishBatch("batch", "stale"); canceled {
if // canceled 保存canceled,供当前处理流程使用
canceled := srv.cancelPublishBatch("batch", "stale"); canceled {
t.Fatal("stale worker token must not cancel current worker")
}
select {
@@ -68,7 +78,8 @@ func TestCancelPublishBatchRequiresMatchingWorkerToken(t *testing.T) {
t.Fatal("current worker was canceled by stale token")
default:
}
if canceled := srv.cancelPublishBatch("batch", "current"); !canceled {
if // canceled 保存canceled,供当前处理流程使用
canceled := srv.cancelPublishBatch("batch", "current"); !canceled {
t.Fatal("matching token should cancel current worker")
}
select {
@@ -81,8 +92,11 @@ func TestCancelPublishBatchRequiresMatchingWorkerToken(t *testing.T) {
// buildImageZip 构造含一张图片的 zip 字节流。
func buildImageZip(t *testing.T) []byte {
t.Helper()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
zw := zip.NewWriter(&buf)
// f 保存f,供当前处理流程使用
f, _ := zw.Create("img/a.png")
f.Write(minimalPNG)
_ = zw.Close()
@@ -92,26 +106,33 @@ func buildImageZip(t *testing.T) []byte {
// previewPublishBatch 构造一个预检批次(单行商品 + 1 张图片),返回 preview_id。
func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
// zipField 保存zip字段,供当前处理流程使用
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 1 {
@@ -120,28 +141,36 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
return res["preview_id"].(string)
}
// previewTwoRowPublishBatch 负责previewTwoRow发布批次相关处理。
func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
// zipField 保存zip字段,供当前处理流程使用
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 2 {
@@ -152,7 +181,9 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。
// TestRunItemPublishBatch_FailureMarksRowFailed 负责Test运行商品发布批次FailureMarksRow失败相关处理。
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入 mock mtop:所有请求返回非成功 ret(触发 PublishError)。
@@ -165,13 +196,17 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
batchID := previewPublishBatch(t, h, cookie)
// 启动批次。
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != 200 {
@@ -180,16 +215,20 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// 轮询批次状态,等待 running 结束(最多 5 秒)。
deadline := time.Now().Add(5 * time.Second)
// status 保存状态,供当前处理流程使用
var status any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
time.Sleep(50 * time.Millisecond)
continue
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
status = got["status"]
@@ -205,8 +244,10 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// 验证至少一行被标记 failed(或 completed)。
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "failed" {
@@ -215,17 +256,21 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
if got["failed"] != float64(1) {
t.Fatalf("failed=%v want 1 body=%+v", got["failed"], got)
}
// rows 保存rows,供当前处理流程使用
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
// row 保存row,供当前处理流程使用
row, _ := rows[0].(map[string]any)
if row["status"] != "failed" || row["error_message"] == "" {
t.Fatalf("row should be failed with error message: %+v", row)
}
}
// TestCancelItemPublishBatchMarksUnfinishedRowsFailed 负责Test取消商品发布批次MarksUnfinishedRows失败相关处理。
func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
@@ -242,31 +287,42 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
batchID := previewTwoRowPublishBatch(t, h, cookie)
// startReq 保存开始Req,供当前处理流程使用
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
}
// cancelReq 保存取消Req,供当前处理流程使用
cancelReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
cancelReq.AddCookie(cookie)
// cancelRec 保存取消Rec,供当前处理流程使用
cancelRec := httptest.NewRecorder()
h.ServeHTTP(cancelRec, cancelReq)
if cancelRec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", cancelRec.Code, cancelRec.Body.String())
}
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(2 * time.Second)
// got 保存got,供当前处理流程使用
var got map[string]any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -287,6 +343,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
if got["failed"] != got["total"] {
t.Fatalf("取消后未完成行应全部失败: total=%v failed=%v body=%+v", got["total"], got["failed"], got)
}
// batch、err 保存batch、err,供当前处理流程使用
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
if err != nil {
t.Fatal(err)
@@ -294,19 +351,24 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
if strings.TrimSpace(batch.UploadDir) == "" {
t.Fatal("取消运行中的任务后应保留 upload_dir 供失败项重试")
}
if _, err := os.Stat(batch.UploadDir); err != nil {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(batch.UploadDir); err != nil {
t.Fatalf("取消运行中的任务后应保留图片目录: %v", err)
}
}
// TestRunItemPublishBatch_Success 启动批次,mock mtop 全程返回 SUCCESS,验证行最终成功。
func TestRunItemPublishBatch_Success(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// publishedCategory 保存published分类,供当前处理流程使用
var publishedCategory map[string]any
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 保存u,供当前处理流程使用
u := req.URL.String()
// body 保存请求体,供当前处理流程使用
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
@@ -314,8 +376,11 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
// rawBody 保存原始请求体,供当前处理流程使用
rawBody, _ := io.ReadAll(req.Body)
// form 保存表单,供当前处理流程使用
form, _ := url.ParseQuery(string(rawBody))
// publishData 保存发布数据,供当前处理流程使用
var publishData map[string]any
_ = json.Unmarshal([]byte(form.Get("data")), &publishData)
publishedCategory, _ = publishData["itemCatDTO"].(map[string]any)
@@ -329,12 +394,17 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
batchID := previewPublishBatch(t, h, cookie)
// startReq 保存开始Req,供当前处理流程使用
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != 200 {
@@ -343,16 +413,20 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
// 轮询至完成。
deadline := time.Now().Add(8 * time.Second)
// status 保存状态,供当前处理流程使用
var status any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
time.Sleep(50 * time.Millisecond)
continue
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
status = got["status"]
@@ -364,13 +438,16 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if status == "running" {
t.Fatal("批次应在 8s 内完成")
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "completed" {
@@ -379,10 +456,12 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if got["success"] != float64(1) {
t.Fatalf("success=%v want 1 body=%+v", got["success"], got)
}
// rows 保存rows,供当前处理流程使用
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
// row 保存row,供当前处理流程使用
row, _ := rows[0].(map[string]any)
if row["status"] != "success" || row["item_id"] == "" {
t.Fatalf("row should be success with item_id: %+v", row)
@@ -392,63 +471,83 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
}
}
// TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain 负责Test发布批次重试ResumesSavedRemote结果WithoutPublishingAgain相关处理。
func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin、err 保存admin、err,供当前处理流程使用
admin, err := store.Users.GetByUsername(ctx, "admin")
if err != nil {
t.Fatal(err)
}
// batch 保存批次,供当前处理流程使用
batch := &db.ItemPublishBatch{
ID: "resume-remote", UserID: admin.ID, DefaultCookieID: "acc1", Filename: "resume.csv", Status: "pending",
}
if err := store.PublishBatches.Create(ctx, batch, []db.ItemPublishBatchRow{{
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.Create(ctx, batch, []db.ItemPublishBatchRow{{
BatchID: batch.ID, RowNo: 1, CookieID: "acc1", Title: "已发布商品", Description: "详情",
Price: "12.50", Quantity: 1, PostageMode: "free", AutomationJSON: `{}`,
}}); err != nil {
t.Fatal(err)
}
// lease 保存lease,供当前处理流程使用
lease := time.Now().UTC().Add(time.Minute).Unix()
if claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-1", lease); err != nil || !claimed {
if // claimed、err 保存claimed、err,供当前处理流程使用
claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-1", lease); err != nil || !claimed {
t.Fatalf("claim first worker: claimed=%v err=%v", claimed, err)
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := store.PublishBatches.Rows(ctx, batch.ID)
if err != nil || len(rows) != 1 {
t.Fatalf("rows=%+v err=%v", rows, err)
}
// rowID 保存rowID,供当前处理流程使用
rowID := rows[0].ID
if claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-1"); err != nil || !claimed {
if // claimed、err 保存claimed、err,供当前处理流程使用
claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-1"); err != nil || !claimed {
t.Fatalf("claim row: claimed=%v err=%v", claimed, err)
}
if saved, err := store.PublishBatches.SaveClaimedRemoteResult(ctx, rowID, "worker-1", "remote-123", "https://x/item/remote-123", `{"remote":true}`); err != nil || !saved {
if // saved、err 保存saved、err,供当前处理流程使用
saved, err := store.PublishBatches.SaveClaimedRemoteResult(ctx, rowID, "worker-1", "remote-123", "https://x/item/remote-123", `{"remote":true}`); err != nil || !saved {
t.Fatalf("save remote result: saved=%v err=%v", saved, err)
}
if marked, err := store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, "worker-1", "local database unavailable", "post_publish"); err != nil || !marked {
if // marked、err 保存marked、err,供当前处理流程使用
marked, err := store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, "worker-1", "local database unavailable", "post_publish"); err != nil || !marked {
t.Fatalf("mark post publish failure: marked=%v err=%v", marked, err)
}
if finished, err := store.PublishBatches.FinishBatchStatus(ctx, batch.ID, "worker-1", "failed"); err != nil || !finished {
if // finished、err 保存finished、err,供当前处理流程使用
finished, err := store.PublishBatches.FinishBatchStatus(ctx, batch.ID, "worker-1", "failed"); err != nil || !finished {
t.Fatalf("finish first batch: finished=%v err=%v", finished, err)
}
if err := store.PublishBatches.ResetFailed(ctx, batch.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.ResetFailed(ctx, batch.ID); err != nil {
t.Fatal(err)
}
if claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-2", lease); err != nil || !claimed {
if // claimed、err 保存claimed、err,供当前处理流程使用
claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-2", lease); err != nil || !claimed {
t.Fatalf("claim retry worker: claimed=%v err=%v", claimed, err)
}
rows, _ = store.PublishBatches.Rows(ctx, batch.ID)
if rows[0].ItemID != "remote-123" || rows[0].Status != "pending" {
t.Fatalf("retry checkpoint lost: %+v", rows[0])
}
if claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-2"); err != nil || !claimed {
if // claimed、err 保存claimed、err,供当前处理流程使用
claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-2"); err != nil || !claimed {
t.Fatalf("retry claim row: claimed=%v err=%v", claimed, err)
}
// remoteCalls 保存remoteCalls,供当前处理流程使用
remoteCalls := 0
// client 保存client,供当前处理流程使用
client := withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
remoteCalls++
return nil, context.Canceled
}))
if err := srv.publishBatchRow(ctx, admin.ID, client, rows[0], "worker-2"); err != nil {
if // err 保存err,供当前处理流程使用
err := srv.publishBatchRow(ctx, admin.ID, client, rows[0], "worker-2"); err != nil {
t.Fatalf("resume local persistence: %v", err)
}
if remoteCalls != 0 {
@@ -460,13 +559,19 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
}
}
// TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow 负责Test发布批次RecoveryAutomaticallyResumesInterruptedRow相关处理。
func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
// batchID 保存批次ID,供当前处理流程使用
batchID := "auto-recover-batch"
if err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: batchID, UserID: admin.ID, DefaultCookieID: "acc1", Filename: "recover.csv", Status: "failed",
}, []db.ItemPublishBatchRow{{
RowNo: 1, CookieID: "acc1", Title: "Recovered", Price: "9.90", Quantity: 1,
@@ -476,10 +581,13 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
t.Fatal(err)
}
srv.recoverPublishBatchesOnce(ctx)
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
// batch、err 保存batch、err,供当前处理流程使用
batch, err := store.PublishBatches.Get(ctx, admin.ID, batchID)
if err == nil && batch.Status == "completed" {
// rows 保存rows,供当前处理流程使用
rows, _ := store.PublishBatches.Rows(ctx, batchID)
if len(rows) != 1 || rows[0].Status != "success" || rows[0].ItemID != "remote-recovered" {
t.Fatalf("rows=%+v", rows)
@@ -488,28 +596,38 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
}
time.Sleep(20 * time.Millisecond)
}
// batch 保存批次,供当前处理流程使用
batch, _ := store.PublishBatches.Get(ctx, admin.ID, batchID)
// rows 保存rows,供当前处理流程使用
rows, _ := store.PublishBatches.Rows(ctx, batchID)
t.Fatalf("batch=%+v rows=%+v", batch, rows)
}
// TestCreatePublishAutomationRules 覆盖自动化规则创建(通过成功发布路径间接覆盖)。
// 这里直接验证 runItemPublishBatch 在成功路径上调用了 createPublishAutomationRules。
// TestCreatePublishAutomationRules 负责TestCreate发布自动化规则列表相关处理。
func TestCreatePublishAutomationRules(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// 预置一个自动化规则配置的批次行,直接调 createPublishAutomationRules 验证不 panic + 写规则。
// 先建一个卡密组供规则引用。
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
// cardID 保存卡密ID,供当前处理流程使用
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡", Type: "text", TextContent: "K", Enabled: true, UserID: admin.ID})
// automationJSON 保存自动化JSON,供当前处理流程使用
automationJSON := `{"paid_delivery":{"enabled":true,"actions":[{"card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":23}]}}`
if err := srv.createPublishAutomationRules(ctx, admin.ID, db.ItemPublishBatchRow{
if // err 保存err,供当前处理流程使用
err := srv.createPublishAutomationRules(ctx, admin.ID, db.ItemPublishBatchRow{
CookieID: "acc1", Title: "商品A", AutomationJSON: automationJSON,
}, &mtop.PublishItemResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil {
t.Fatal(err)
}
// rules、err 保存rules、err,供当前处理流程使用
rules, err := store.Automation.Match(ctx, "acc1", "published-delay-item", automation.TriggerOrderPaid)
if err != nil || len(rules) != 1 {
t.Fatalf("rules=%+v err=%v", rules, err)
+249 -31
View File
@@ -20,6 +20,7 @@ import (
// TestParsePublishSheetBytes 表格解析各格式。
func TestParsePublishSheetBytes(t *testing.T) {
// CSV。
// rows、err 保存rows、err,供当前处理流程使用
rows, err := parsePublishSheetBytes([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,a.png\n"), "products.csv")
if err != nil || len(rows) != 1 {
t.Fatalf("csv parse = %#v, %v", rows, err)
@@ -50,119 +51,162 @@ func TestParsePublishSheetBytes(t *testing.T) {
}
}
// TestParsePublishSheetBytesWithLimitRejectsTooManyRows 负责TestParse发布SheetBytesWith上限RejectsTooManyRows相关处理。
func TestParsePublishSheetBytesWithLimitRejectsTooManyRows(t *testing.T) {
// b 保存b,供当前处理流程使用
var b strings.Builder
b.WriteString("账号ID,标题\n")
for i := 0; i < 3; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 3; i++ {
b.WriteString("acc1,商品\n")
}
if _, err := parsePublishSheetBytesWithLimit([]byte(b.String()), "products.csv", 2); err == nil {
if // err 保存err,供当前处理流程使用
_, err := parsePublishSheetBytesWithLimit([]byte(b.String()), "products.csv", 2); err == nil {
t.Fatal("too many publish rows should fail")
}
}
// TestPreviewItemPublishBatchCSV 预检 CSV 批量发布(含图片 zip)。
func TestPreviewItemPublishBatchCSV(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 构造一个最小图片 zip(含一张 1x1 PNG)。
png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
// zipBuf 保存zipBuf,供当前处理流程使用
var zipBuf bytes.Buffer
// zw 保存zw,供当前处理流程使用
zw := zip.NewWriter(&zipBuf)
// f 保存f,供当前处理流程使用
f, _ := zw.Create("img/a.png")
f.Write(png)
_ = zw.Close()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
// zipField 保存zip字段,供当前处理流程使用
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(zipBuf.Bytes())
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true || res["valid"] != float64(1) {
t.Fatalf("预检异常: %+v", res)
}
// previewRow 保存previewRow,供当前处理流程使用
previewRow := res["rows"].([]any)[0].(map[string]any)
// category 保存分类,供当前处理流程使用
category := previewRow["category"].(map[string]any)
if category["cat_id"] != "5001" || category["cat_name"] != "虚拟商品" {
t.Fatalf("预检未保存兜底类目: %+v", category)
}
}
// TestPreviewItemPublishBatchAllowsEmptyDefaultCategory 负责TestPreview商品发布批次AllowsEmptyDefault分类相关处理。
func TestPreviewItemPublishBatchAllowsEmptyDefaultCategory(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
// file 保存文件,供当前处理流程使用
file, _ := mw.CreateFormFile("file", "products.csv")
file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &res)
// row 保存row,供当前处理流程使用
row := res["rows"].([]any)[0].(map[string]any)
// category 保存分类,供当前处理流程使用
category := row["category"].(map[string]any)
if category["cat_id"] != "" || category["cat_name"] != "" {
t.Fatalf("category should be empty: %+v", category)
}
}
// TestPreviewItemPublishBatchRowCategoryOverridesFallback 负责TestPreview商品发布批次Row分类OverridesFallback相关处理。
func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "批次类目")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// file 保存文件,供当前处理流程使用
file, _ := mw.CreateFormFile("file", "products.csv")
file.Write([]byte("标题,价格,图片,类目ID,类目名称,频道类目ID\n商品A,12.50,https://example.com/a.png,7001,行指定类目,8001\n"))
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &res)
// row 保存row,供当前处理流程使用
row := res["rows"].([]any)[0].(map[string]any)
// category 保存分类,供当前处理流程使用
category := row["category"].(map[string]any)
if category["cat_id"] != "7001" || category["cat_name"] != "行指定类目" {
t.Fatalf("row category=%+v", category)
@@ -171,12 +215,17 @@ func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
// TestPreviewItemPublishBatchNoFile 缺表格文件 400。
func TestPreviewItemPublishBatchNoFile(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
@@ -184,9 +233,11 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
_ = mw.WriteField("fallback_channel_category_id", "6001")
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -194,20 +245,29 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
}
}
// TestPreviewItemPublishBatchRequiresDefaultAccount 负责TestPreview商品发布批次RequiresDefault账号相关处理。
func TestPreviewItemPublishBatchRequiresDefaultAccount(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
// file 保存文件,供当前处理流程使用
file, _ := mw.CreateFormFile("file", "products.csv")
file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "请选择默认发布账号") {
@@ -217,19 +277,26 @@ func TestPreviewItemPublishBatchRequiresDefaultAccount(t *testing.T) {
// TestPreviewItemPublishBatchBadDefaultCookie 默认账号不属于当前用户 403。
func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "other-account")
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -239,31 +306,40 @@ func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) {
// TestPreviewItemPublishBatchTooManyRows 超过最大行数 400。
func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 构造 51 行 CSV。
var csvBuf bytes.Buffer
csvBuf.WriteString("账号ID,标题,价格,库存,图片\n")
for i := 0; i < maxPublishBatchRows+1; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < maxPublishBatchRows+1; i++ {
csvBuf.WriteString("acc1,商品,12.50,5,a.png\n")
}
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write(csvBuf.Bytes())
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -273,32 +349,44 @@ func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
// TestPreviewItemPublishBatchZipTraversal zip 路径穿越拒绝 400。
func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// zipBuf 保存zipBuf,供当前处理流程使用
var zipBuf bytes.Buffer
// zw 保存zw,供当前处理流程使用
zw := zip.NewWriter(&zipBuf)
// f 保存f,供当前处理流程使用
f, _ := zw.Create("../escape.png")
f.Write([]byte("x"))
_ = zw.Close()
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,../escape.png\n"))
// zipField 保存zip字段,供当前处理流程使用
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(zipBuf.Bytes())
_ = mw.Close()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -308,13 +396,18 @@ func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
// TestGetItemPublishBatchNotFound 不存在批次 404。
func TestGetItemPublishBatchNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -322,20 +415,29 @@ func TestGetItemPublishBatchNotFound(t *testing.T) {
}
}
// TestListItemPublishBatchesRestoresRecentTask 负责TestList商品发布批次列表RestoresRecent任务相关处理。
func TestListItemPublishBatchesRestoresRecentTask(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
if err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: "listed-batch", UserID: admin.ID, DefaultCookieID: "acc1", Filename: "x.csv", Status: "failed",
}, []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "acc1", Title: "A", Price: "1", Status: "failed", FailureKind: "publish"}}); err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches?limit=10", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"id":"listed-batch"`) {
@@ -345,13 +447,18 @@ func TestListItemPublishBatchesRestoresRecentTask(t *testing.T) {
// TestCancelItemPublishBatchNotFound 不存在批次 404。
func TestCancelItemPublishBatchNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/no-such/cancel", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -359,67 +466,92 @@ func TestCancelItemPublishBatchNotFound(t *testing.T) {
}
}
// TestCancelPreviewBatchRetainsUploadDirectoryForRetry 负责Test取消Preview批次RetainsUploadDirectoryFor重试相关处理。
func TestCancelPreviewBatchRetainsUploadDirectoryForRetry(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
batchID := previewPublishBatch(t, h, cookie)
// batch、err 保存batch、err,供当前处理流程使用
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
if err != nil {
t.Fatal(err)
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(batch.UploadDir); err != nil {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(batch.UploadDir); err != nil {
t.Fatalf("取消后应保留上传目录供重试: %v", err)
}
// retained、err 保存retained、err,供当前处理流程使用
retained, err := store.PublishBatches.Get(context.Background(), 1, batchID)
if err != nil || retained.UploadDir != batch.UploadDir {
t.Fatalf("取消后应保留 upload_dir: batch=%+v err=%v", retained, err)
}
}
// TestDeletePreviewBatchRemovesUploadDirectory 负责TestDeletePreview批次RemovesUploadDirectory相关处理。
func TestDeletePreviewBatchRemovesUploadDirectory(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
batchID := previewPublishBatch(t, h, cookie)
// batch、err 保存batch、err,供当前处理流程使用
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(batch.UploadDir); err != nil {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(batch.UploadDir); err != nil {
t.Fatalf("upload dir missing before delete: %v", err)
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("delete status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(batch.UploadDir); !os.IsNotExist(err) {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(batch.UploadDir); !os.IsNotExist(err) {
t.Fatalf("upload dir still exists: %v", err)
}
}
// TestRetryFailedItemPublishBatchNotFound 不存在批次 404。
func TestRetryFailedItemPublishBatchNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/no-such/retry-failed", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -427,53 +559,73 @@ func TestRetryFailedItemPublishBatchNotFound(t *testing.T) {
}
}
// TestRetryFailedItemPublishBatchRejectsActiveWorker 负责Test重试失败商品发布批次RejectsActive工作器相关处理。
func TestRetryFailedItemPublishBatchRejectsActiveWorker(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin、err 保存admin、err,供当前处理流程使用
admin, err := store.Users.GetByUsername(ctx, "admin")
if err != nil {
t.Fatal(err)
}
if err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: "running-batch", UserID: admin.ID, DefaultCookieID: "acc1", Filename: "x.csv", Status: "running",
}, []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "acc1", Title: "A", Price: "1", Status: "failed", FailureKind: "publish"}}); err != nil {
t.Fatal(err)
}
if _, err := store.DB.ExecContext(ctx, `UPDATE item_publish_batches SET worker_token='active',lease_expires_at=? WHERE id='running-batch'`, time.Now().Add(time.Hour).Unix()); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx, `UPDATE item_publish_batches SET worker_token='active',lease_expires_at=? WHERE id='running-batch'`, time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/running-batch/retry-failed", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("running retry status=%d body=%s", rec.Code, rec.Body.String())
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := store.PublishBatches.Rows(ctx, "running-batch")
if err != nil || len(rows) != 1 || rows[0].Status != "failed" {
t.Fatalf("active retry must not reset rows: rows=%+v err=%v", rows, err)
}
}
// TestStartItemPublishBatchReclaimsExpiredWorker 负责Test开始商品发布批次ReclaimsExpired工作器相关处理。
func TestStartItemPublishBatchReclaimsExpiredWorker(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(ctx, "admin")
if err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
if // err 保存err,供当前处理流程使用
err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: "expired-batch", UserID: admin.ID, DefaultCookieID: "acc1", Filename: "x.csv", Status: "running",
}, []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "acc1", Title: "A", Price: "1", Status: "running"}}); err != nil {
t.Fatal(err)
}
_, _ = store.DB.ExecContext(ctx, `UPDATE item_publish_batches SET worker_token='dead',lease_expires_at=? WHERE id='expired-batch'`, time.Now().Add(-time.Minute).Unix())
_, _ = store.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows SET worker_token='dead' WHERE batch_id='expired-batch'`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"batch_id":"expired-batch"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -483,13 +635,18 @@ func TestStartItemPublishBatchReclaimsExpiredWorker(t *testing.T) {
// TestDownloadItemPublishBatchResultNotFound 不存在批次 404。
func TestDownloadItemPublishBatchResultNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/no-such/result.csv", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -497,14 +654,19 @@ func TestDownloadItemPublishBatchResultNotFound(t *testing.T) {
}
}
// TestSafeCSVCellPreventsSpreadsheetFormulaExecution 负责TestSafeCSVCellPreventsSpreadsheetFormulaExecution相关处理。
func TestSafeCSVCellPreventsSpreadsheetFormulaExecution(t *testing.T) {
// input 表示当前遍历过程中的input
for _, input := range []string{"=cmd()", "+SUM(1,2)", " -1+2", "@evil"} {
if got := safeCSVCell(input); !strings.HasPrefix(got, "'") {
if // got 保存got,供当前处理流程使用
got := safeCSVCell(input); !strings.HasPrefix(got, "'") {
t.Fatalf("dangerous cell %q was not escaped: %q", input, got)
}
}
// input 表示当前遍历过程中的input
for _, input := range []string{"normal", "https://example.com", "123"} {
if got := safeCSVCell(input); got != input {
if // got 保存got,供当前处理流程使用
got := safeCSVCell(input); got != input {
t.Fatalf("safe cell %q unexpectedly changed to %q", input, got)
}
}
@@ -512,13 +674,18 @@ func TestSafeCSVCellPreventsSpreadsheetFormulaExecution(t *testing.T) {
// TestStartItemPublishBatchBadJSON 非法 JSON 400。
func TestStartItemPublishBatchBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -528,13 +695,18 @@ func TestStartItemPublishBatchBadJSON(t *testing.T) {
// TestStartItemPublishBatchMissingPreviewID 缺 preview_id 400。
func TestStartItemPublishBatchMissingPreviewID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -544,13 +716,18 @@ func TestStartItemPublishBatchMissingPreviewID(t *testing.T) {
// TestStartItemPublishBatchNotFound 不存在 404。
func TestStartItemPublishBatchNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"no-such"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -560,10 +737,13 @@ func TestStartItemPublishBatchNotFound(t *testing.T) {
// TestWriteFileWithinRoot 写文件限制在根目录内。
func TestWriteFileWithinRoot(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
if err := writeFileWithinRoot(dest, "file.txt", []byte("hello")); err != nil {
if // err 保存err,供当前处理流程使用
err := writeFileWithinRoot(dest, "file.txt", []byte("hello")); err != nil {
t.Fatalf("write: %v", err)
}
// data、err 保存data、err,供当前处理流程使用
data, err := os.ReadFile(filepath.Join(dest, "file.txt"))
if err != nil || string(data) != "hello" {
t.Fatalf("read back: %v %q", err, data)
@@ -572,19 +752,24 @@ func TestWriteFileWithinRoot(t *testing.T) {
// TestWriteFileWithinRootTraversal 路径穿越拒绝。
func TestWriteFileWithinRootTraversal(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
if err := writeFileWithinRoot(dest, "../escape.txt", []byte("x")); err == nil {
if // err 保存err,供当前处理流程使用
err := writeFileWithinRoot(dest, "../escape.txt", []byte("x")); err == nil {
t.Fatal("路径穿越应拒绝")
}
}
// TestReadBatchImageFile 读取本地图片文件。
func TestReadBatchImageFile(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
// png 保存png,供当前处理流程使用
png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
_ = os.MkdirAll(filepath.Join(dest, "imgs"), 0o750)
_ = os.WriteFile(filepath.Join(dest, "imgs", "a.png"), png, 0o600)
// data、ct、name、err 保存data、ct、name、err,供当前处理流程使用
data, ct, name, err := readBatchImageFile(dest, "imgs/a.png")
if err != nil {
t.Fatalf("read: %v", err)
@@ -596,42 +781,53 @@ func TestReadBatchImageFile(t *testing.T) {
// TestReadBatchImageFileNotFound 不存在图片报错。
func TestReadBatchImageFileNotFound(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
if _, _, _, err := readBatchImageFile(dest, "no-such.png"); err == nil {
if // err 保存err,供当前处理流程使用
_, _, _, err := readBatchImageFile(dest, "no-such.png"); err == nil {
t.Fatal("不存在应报错")
}
}
// TestReadBatchImageFileTraversal 路径穿越拒绝。
func TestReadBatchImageFileTraversal(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
if _, _, _, err := readBatchImageFile(dest, "../escape.png"); err == nil {
if // err 保存err,供当前处理流程使用
_, _, _, err := readBatchImageFile(dest, "../escape.png"); err == nil {
t.Fatal("路径穿越应报错")
}
}
// TestValidateBatchImageRef 校验图片引用。
func TestValidateBatchImageRef(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
// png 保存png,供当前处理流程使用
png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
_ = os.WriteFile(filepath.Join(dest, "a.png"), png, 0o600)
if err := validateBatchImageRef(dest, "a.png"); err != nil {
if // err 保存err,供当前处理流程使用
err := validateBatchImageRef(dest, "a.png"); err != nil {
t.Fatalf("存在图片应通过: %v", err)
}
if err := validateBatchImageRef(dest, "no-such.png"); err == nil {
if // err 保存err,供当前处理流程使用
err := validateBatchImageRef(dest, "no-such.png"); err == nil {
t.Fatal("不存在应报错")
}
if err := validateBatchImageRef(dest, "https://example.com/a.png"); err != nil {
if // err 保存err,供当前处理流程使用
err := validateBatchImageRef(dest, "https://example.com/a.png"); err != nil {
t.Fatalf("HTTP URL 应直接通过: %v", err)
}
if err := validateBatchImageRef(dest, "../escape.png"); err == nil {
if // err 保存err,供当前处理流程使用
err := validateBatchImageRef(dest, "../escape.png"); err == nil {
t.Fatal("穿越应报错")
}
}
// TestIsHTTPURL isHTTPURL 表驱动。
func TestIsHTTPURL(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]bool{
"http://x.com/a.png": true,
"https://x.com/a.png": true,
@@ -640,8 +836,10 @@ func TestIsHTTPURL(t *testing.T) {
"a.png": false,
"": false,
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := isHTTPURL(in); got != want {
if // got 保存got,供当前处理流程使用
got := isHTTPURL(in); got != want {
t.Errorf("isHTTPURL(%q)=%v want %v", in, got, want)
}
}
@@ -649,7 +847,8 @@ func TestIsHTTPURL(t *testing.T) {
// TestPathBaseFromURL pathBaseFromURL 表驱动。
func TestPathBaseFromURL(t *testing.T) {
if got := pathBaseFromURL("https://example.com/path/a.png?x=1"); got != "a.png" {
if // got 保存got,供当前处理流程使用
got := pathBaseFromURL("https://example.com/path/a.png?x=1"); got != "a.png" {
t.Fatalf("got %q", got)
}
// 仅 host 的 URL:base 为 host 名。
@@ -660,6 +859,7 @@ func TestPathBaseFromURL(t *testing.T) {
// TestSafeBaseName safeBaseName 表驱动。
func TestSafeBaseName(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"normal.png": "normal.png",
" trim.png ": "trim.png",
@@ -667,8 +867,10 @@ func TestSafeBaseName(t *testing.T) {
"": "",
".": "",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := safeBaseName(in); got != want {
if // got 保存got,供当前处理流程使用
got := safeBaseName(in); got != want {
t.Errorf("safeBaseName(%q)=%q want %q", in, got, want)
}
}
@@ -676,33 +878,39 @@ func TestSafeBaseName(t *testing.T) {
// TestRandomHex randomHex 长度。
func TestRandomHex(t *testing.T) {
if s := randomHex(8); len(s) != 16 {
if // s 保存s,供当前处理流程使用
s := randomHex(8); len(s) != 16 {
t.Fatalf("randomHex(8) 长度=%d want 16", len(s))
}
}
// TestFirstNonEmpty firstNonEmpty 表驱动。
func TestFirstNonEmpty(t *testing.T) {
if got := firstNonEmpty("", "", "x"); got != "x" {
if // got 保存got,供当前处理流程使用
got := firstNonEmpty("", "", "x"); got != "x" {
t.Fatalf("got %q", got)
}
if got := firstNonEmpty("", "", ""); got != "" {
if // got 保存got,供当前处理流程使用
got := firstNonEmpty("", "", ""); got != "" {
t.Fatalf("got %q", got)
}
}
// TestDownloadImageURLInvalid 无效 URL 报错。
func TestDownloadImageURLInvalid(t *testing.T) {
if _, _, err := downloadImageURL(context.Background(), "ftp://x.com/a.png"); err == nil {
if // err 保存err,供当前处理流程使用
_, _, err := downloadImageURL(context.Background(), "ftp://x.com/a.png"); err == nil {
t.Fatal("ftp 应报错")
}
if _, _, err := downloadImageURL(context.Background(), "not-a-url"); err == nil {
if // err 保存err,供当前处理流程使用
_, _, err := downloadImageURL(context.Background(), "not-a-url"); err == nil {
t.Fatal("非 URL 应报错")
}
}
// TestLoadBatchPublishImagesBadJSON imagesJSON 非数组。
func TestLoadBatchPublishImagesBadJSON(t *testing.T) {
// dest 保存dest,供当前处理流程使用
dest := t.TempDir()
// ImagesJSON 非法 JSON。
_, err := loadBatchPublishImages(context.Background(), dest, db.ItemPublishBatchRow{ImagesJSON: `not-json`})
@@ -718,8 +926,10 @@ func TestLoadBatchPublishImagesBadJSON(t *testing.T) {
// TestCookieOwnedByUser 归属判定。
func TestCookieOwnedByUser(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if !srv.cookieOwnedByUser(ctx, 1, "acc1") {
t.Fatal("acc1 应属于 user 1")
@@ -734,8 +944,10 @@ func TestCookieOwnedByUser(t *testing.T) {
// TestCardOwnedByUser 卡密归属判定。
func TestCardOwnedByUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO cards (name, type, user_id) VALUES ('卡1','text',1)`)
if !srv.cardOwnedByUser(ctx, 1, 1) {
@@ -748,14 +960,18 @@ func TestCardOwnedByUser(t *testing.T) {
// TestCookieValueForUser 取 cookie 值。
func TestCookieValueForUser(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// v、err 保存v、err,供当前处理流程使用
v, err := srv.cookieValueForUser(ctx, 1, "acc1")
if err != nil || v == "" {
t.Fatalf("取 cookie 值异常: v=%q err=%v", v, err)
}
if _, err := srv.cookieValueForUser(ctx, 1, "no-such"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := srv.cookieValueForUser(ctx, 1, "no-such"); err == nil {
t.Fatal("不存在应报错")
}
}
@@ -763,11 +979,13 @@ func TestCookieValueForUser(t *testing.T) {
// TestDefaultPublishUploadRoot 默认上传根目录。
func TestDefaultPublishUploadRoot(t *testing.T) {
t.Setenv("XIANYU_UPLOAD_DIR", "")
if got := defaultPublishUploadRoot(); got != filepath.Join("data", "uploads") {
if // got 保存got,供当前处理流程使用
got := defaultPublishUploadRoot(); got != filepath.Join("data", "uploads") {
t.Fatalf("默认根目录异常: %q", got)
}
t.Setenv("XIANYU_UPLOAD_DIR", "/tmp/uploads")
if got := defaultPublishUploadRoot(); got != "/tmp/uploads" {
if // got 保存got,供当前处理流程使用
got := defaultPublishUploadRoot(); got != "/tmp/uploads" {
t.Fatalf("env 根目录异常: %q", got)
}
}
+50 -5
View File
@@ -13,6 +13,7 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// qrLoginGenerateTimeout 保存qr登录GenerateTimeout,供当前处理流程使用
const qrLoginGenerateTimeout = 2 * time.Minute
// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。
@@ -25,6 +26,7 @@ func (s *Server) mountQRLoginReal(r chi.Router) {
// generateQRLogin 生成扫码登录二维码。
func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
@@ -33,10 +35,13 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
s.cleanupQRLoginSessions()
// 风控后的闲鱼匿名 token 接口偶尔会明显变慢。二维码生成需要连续完成
// token、登录参数和二维码请求,不能沿用前端通用接口的短超时。
// generateCtx、cancel 保存generateCtx、cancel,供当前处理流程使用
generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout)
defer cancel()
// sessionID、qrCodeURL、err 保存会话ID、qrCodeURL、err,供当前处理流程使用
sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(generateCtx)
if err != nil {
// message 保存消息,供当前处理流程使用
message := "生成二维码失败: " + err.Error()
switch {
case errors.Is(err, context.Canceled):
@@ -66,6 +71,7 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
// checkQRLoginStatus 检查扫码登录状态。
func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -74,12 +80,14 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
if !s.requireQRSessionOwner(w, r, sessionID) {
return
}
// result 保存结果,供当前处理流程使用
result := publicQRStatus(s.QRLogin.GetSessionStatus(sessionID))
writeJSON(w, http.StatusOK, result)
}
// checkQRLoginStatusAndPersist 兼容上游 /status 语义:扫码成功后由后端幂等保存账号。
func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -88,16 +96,19 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
if !s.requireQRSessionOwner(w, r, sessionID) {
return
}
// result 保存结果,供当前处理流程使用
result := cloneQRStatus(s.QRLogin.GetSessionStatus(sessionID))
if qrStatus(result) != "success" {
writeJSON(w, http.StatusOK, publicQRStatus(result))
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// persisted、err 保存persisted、err,供当前处理流程使用
persisted, err := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, "")
if err != nil {
if s.Logger != nil {
@@ -117,6 +128,7 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
// completeQRVerification 用户完成风控验证后调用,提取真实 cookie 并入库。
func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -125,6 +137,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
if !s.requireQRSessionOwner(w, r, sessionID) {
return
}
// cookies、unb、err 保存cookies、unb、err,供当前处理流程使用
cookies, unb, err := s.QRLogin.CompleteVerification(r.Context(), sessionID)
if err != nil {
s.Logger.Error("验证完成处理失败", "err", err)
@@ -134,11 +147,13 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
err.Error(), "")
return
}
// req 保存req,供当前处理流程使用
var req struct {
TargetAccountID string `json:"target_account_id"`
}
if r.Body != nil && r.ContentLength != 0 {
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -152,22 +167,28 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
"", map[string]any{"scanned_account_id": unb})
return
}
// resp 保存resp,供当前处理流程使用
resp := qrLoginVerificationResponse{
Success: true, UNB: unb,
// 验证完成响应保留平台账号标识,兼容旧客户端。
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess != nil {
// result 保存结果,供当前处理流程使用
result := map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
}
if current := s.QRLogin.GetSessionStatus(sessionID); current != nil {
if snapshot, ok := current["cookie_snapshot"]; ok {
if // current 保存current,供当前处理流程使用
current := s.QRLogin.GetSessionStatus(sessionID); current != nil {
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := current["cookie_snapshot"]; ok {
result["cookie_snapshot"] = snapshot
}
}
// persisted、persistErr 保存persisted、persistErr,供当前处理流程使用
persisted, persistErr := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
if persistErr != nil {
if s.Logger != nil {
@@ -184,14 +205,18 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, resp)
}
// requireQRSessionOwner 负责requireQR会话所有者相关处理。
func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, sessionID string) bool {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
s.qrMu.Lock()
// owner、ok 保存owner、ok,供当前处理流程使用
owner, ok := s.qrOwners[sessionID]
// expired 保存expired,供当前处理流程使用
expired := ok && owner.CreatedAt.Before(time.Now().UTC().Add(-30*time.Minute))
if expired {
delete(s.qrOwners, sessionID)
@@ -200,7 +225,8 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
}
s.qrMu.Unlock()
if expired {
if cleaner, cleanable := s.QRLogin.(interface{ DeleteSession(string) }); cleanable {
if // cleaner、cleanable 保存cleaner、cleanable,供当前处理流程使用
cleaner, cleanable := s.QRLogin.(interface{ DeleteSession(string) }); cleanable {
cleaner.DeleteSession(sessionID)
}
}
@@ -211,10 +237,14 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
return true
}
// cleanupQRLoginSessions 负责cleanupQR登录Sessions相关处理。
func (s *Server) cleanupQRLoginSessions() {
// cutoff 保存cutoff,供当前处理流程使用
cutoff := time.Now().UTC().Add(-30 * time.Minute)
// expired 保存expired,供当前处理流程使用
expired := make([]string, 0)
s.qrMu.Lock()
// id、owner 表示当前遍历过程中的id、owner
for id, owner := range s.qrOwners {
if owner.CreatedAt.Before(cutoff) {
delete(s.qrOwners, id)
@@ -224,15 +254,20 @@ func (s *Server) cleanupQRLoginSessions() {
}
}
s.qrMu.Unlock()
if cleaner, ok := s.QRLogin.(interface{ DeleteSession(string) }); ok {
if // cleaner、ok 保存cleaner、ok,供当前处理流程使用
cleaner, ok := s.QRLogin.(interface{ DeleteSession(string) }); ok {
// id 表示当前遍历过程中的标识
for _, id := range expired {
cleaner.DeleteSession(id)
}
}
}
// cloneQRStatus 负责cloneQR状态相关处理。
func cloneQRStatus(src map[string]any) map[string]any {
// dst 保存dst,供当前处理流程使用
dst := make(map[string]any, len(src))
// k、v 表示当前遍历过程中的k、v
for k, v := range src {
dst[k] = v
}
@@ -241,32 +276,42 @@ func cloneQRStatus(src map[string]any) map[string]any {
// publicQRStatus 返回可暴露给浏览器的扫码状态。闲鱼 Cookie 只在服务端持久化,
// 永远不进入前端、浏览器日志或代理响应。
// publicQRStatus 负责publicQR状态相关处理。
func publicQRStatus(src map[string]any) qrLoginStatusResponse {
// dst 保存dst,供当前处理流程使用
dst := qrLoginStatusResponse(cloneQRStatus(src))
delete(dst, "cookies")
delete(dst, "cookie_snapshot")
return dst
}
// qrStatus 负责qr状态相关处理。
func qrStatus(result map[string]any) string {
// status 保存状态,供当前处理流程使用
status, _ := result["status"].(string)
return status
}
// qrString 负责qrString相关处理。
func qrString(result map[string]any, key string) string {
// value 保存值,供当前处理流程使用
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
// qrCookieSnapshot 负责qr登录凭证Snapshot相关处理。
func qrCookieSnapshot(result map[string]any) ([]cookierefresh.BrowserCookie, bool) {
// raw、ok 保存raw、ok,供当前处理流程使用
raw, ok := result["cookie_snapshot"]
if !ok {
return nil, false
}
// snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := raw.([]cookierefresh.BrowserCookie)
if !ok || snapshot == nil {
return nil, false
}
// normalized 保存normalized,供当前处理流程使用
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
+178 -16
View File
@@ -14,6 +14,7 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// fakeQRLoginService 保存fakeQR登录Service,供当前处理流程使用
type fakeQRLoginService struct {
status map[string]any
generateErr error
@@ -23,6 +24,7 @@ type fakeQRLoginService struct {
completeErr error
}
// GenerateQRCode 负责GenerateQRCode相关处理。
func (f *fakeQRLoginService) GenerateQRCode(ctx context.Context) (string, string, error) {
f.generateDeadline, _ = ctx.Deadline()
if f.generateErr != nil {
@@ -31,20 +33,25 @@ func (f *fakeQRLoginService) GenerateQRCode(ctx context.Context) (string, string
return "qr-session", "data:image/png;base64,abc", nil
}
// GetSessionStatus 读取会话状态。
func (f *fakeQRLoginService) GetSessionStatus(sessionID string) map[string]any {
if sessionID == "no-such-session" {
return map[string]any{"status": "not_found"}
}
// out 保存out,供当前处理流程使用
out := make(map[string]any, len(f.status)+1)
// k、v 表示当前遍历过程中的k、v
for k, v := range f.status {
out[k] = v
}
if _, ok := out["session_id"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := out["session_id"]; !ok {
out["session_id"] = sessionID
}
return out
}
// CompleteVerification 负责CompleteVerification相关处理。
func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (string, string, error) {
if f.completeErr != nil {
return "", "", f.completeErr
@@ -54,60 +61,80 @@ func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (stri
// TestGenerateQRLogin 生成扫码登录二维码。
func TestGenerateQRLogin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// qr 保存qr,供当前处理流程使用
qr := &fakeQRLoginService{}
srv.QRLogin = qr
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true || res["session_id"] == nil || res["session_id"] == "" {
t.Fatalf("生成二维码响应异常: %+v", res)
}
// remaining 保存remaining,供当前处理流程使用
remaining := time.Until(qr.generateDeadline)
if remaining < qrLoginGenerateTimeout-time.Second || remaining > qrLoginGenerateTimeout {
t.Fatalf("二维码生成超时窗口=%v want≈%v", remaining, qrLoginGenerateTimeout)
}
}
// TestQRLoginSessionCannotBeReadByAnotherUser 负责TestQR登录会话CannotBeReadByAnother用户相关处理。
func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
if ok, err := store.Users.Create(context.Background(), "member", "member@example.com", "memberpw"); err != nil || !ok {
if // ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.Create(context.Background(), "member", "member@example.com", "memberpw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
// h 保存h,供当前处理流程使用
h := srv.Router()
// adminCookie 保存admin登录凭证,供当前处理流程使用
adminCookie := loginHelper(t, h)
// memberCookie 保存member登录凭证,供当前处理流程使用
memberCookie := loginAsHelper(t, h, "member", "memberpw")
// generateReq 保存generateReq,供当前处理流程使用
generateReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
generateReq.AddCookie(adminCookie)
// generateRec 保存generateRec,供当前处理流程使用
generateRec := httptest.NewRecorder()
h.ServeHTTP(generateRec, generateReq)
if generateRec.Code != http.StatusOK {
t.Fatalf("generate status=%d body=%s", generateRec.Code, generateRec.Body.String())
}
// memberReq 保存memberReq,供当前处理流程使用
memberReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/qr-session", nil)
memberReq.AddCookie(memberCookie)
// memberRec 保存memberRec,供当前处理流程使用
memberRec := httptest.NewRecorder()
h.ServeHTTP(memberRec, memberReq)
if memberRec.Code != http.StatusNotFound {
t.Fatalf("cross-user QR session read status=%d body=%s", memberRec.Code, memberRec.Body.String())
}
// adminReq 保存adminReq,供当前处理流程使用
adminReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/qr-session", nil)
adminReq.AddCookie(adminCookie)
// adminRec 保存adminRec,供当前处理流程使用
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusOK {
@@ -115,7 +142,9 @@ func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
}
}
// TestQRLoginStatusNeverExposesCookies 负责TestQR登录状态NeverExposesCookies相关处理。
func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -124,40 +153,56 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
"cookie_snapshot": []cookierefresh.BrowserCookie{{Name: "secret", Value: "value", Domain: ".goofish.com", Path: "/"}},
}}
ownQRSession(t, srv, store, "redacted")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// path 表示当前遍历过程中的路径
for _, path := range []string{"/qr-login/check/redacted", "/qr-login/status/redacted"} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("%s status=%d body=%s", path, rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode %s: %v", path, err)
}
if _, exists := res["cookies"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := res["cookies"]; exists {
t.Fatalf("%s must redact cookies: %+v", path, res)
}
if _, exists := res["cookie_snapshot"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := res["cookie_snapshot"]; exists {
t.Fatalf("%s must redact cookie snapshot: %+v", path, res)
}
}
}
// TestQRLoginSessionExpiresWithoutAnotherGenerateRequest 负责TestQR登录会话ExpiresWithoutAnotherGenerate请求相关处理。
func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
srv.qrOwners["expired-session"] = qrLoginOwner{UserID: admin.ID, CreatedAt: time.Now().UTC().Add(-31 * time.Minute)}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/qr-login/check/expired-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -167,16 +212,21 @@ func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
// TestCheckQRLoginStatusEmptySession 缺 session_id 400。
func TestCheckQRLoginStatusEmptySession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// chi 路由 /qr-login/check/{session_id};空 session 走不到 handler(404)。
// 用一个不存在的 session 验证不 panic。
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/qr-login/check/no-such-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -186,14 +236,19 @@ func TestCheckQRLoginStatusEmptySession(t *testing.T) {
// TestCompleteQRVerificationBadSession 不存在的 session 应返回失败响应(不 panic)。
func TestCompleteQRVerificationBadSession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("会话不存在")}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/no-such-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -201,8 +256,10 @@ func TestCompleteQRVerificationBadSession(t *testing.T) {
}
}
// ownQRSession 负责ownQR会话相关处理。
func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string) {
t.Helper()
// admin、err 保存admin、err,供当前处理流程使用
admin, err := store.Users.GetByUsername(context.Background(), "admin")
if err != nil {
t.Fatalf("GetByUsername admin: %v", err)
@@ -212,7 +269,9 @@ func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string)
srv.qrMu.Unlock()
}
// TestQRLoginStatusPersistsSuccessIdempotently 负责TestQR登录状态PersistsSuccessIdempotently相关处理。
func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -225,23 +284,31 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
{Name: "_m_h5_tk", Value: "qr-token", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
},
}}
if snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
}
ownQRSession(t, srv, store, "s1")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
for i := 0; i < 2; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 2; i++ {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/qr-login/status/s1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "qr-new" {
@@ -249,6 +316,7 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
}
}
// d、err 保存d、err,供当前处理流程使用
d, err := store.Cookies.GetDetails(context.Background(), "qr-new")
if err != nil {
t.Fatalf("GetDetails qr-new: %v", err)
@@ -256,18 +324,23 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !ok || len(snapshot) != 2 {
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !ok || len(snapshot) != 2 {
t.Fatalf("纯 Go 扫码完整 Cookie Jar 未持久化: ok=%v snapshot=%+v metadata=%s", ok, snapshot, d.MetadataJSON)
}
// logs、err 保存logs、err,供当前处理流程使用
logs, err := store.LoginLogs.ListByCookie(context.Background(), "qr-new", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" || logs[0].Method != "qr_scan" {
t.Fatalf("重复轮询不应重复记录登录日志: logs=%#v err=%v", logs, err)
}
}
// TestCompleteQRVerificationPersistsAndReenablesAccount 负责TestCompleteQRVerificationPersistsAndReenables账号相关处理。
func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
@@ -275,43 +348,55 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
completeUNB: "acc1",
}
ownQRSession(t, srv, store, "s1")
if err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
if err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
seedStaleCookieSnapshot(t, store, "acc1")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "acc1" {
t.Fatalf("完成验证响应异常: %+v", res)
}
if _, exists := res["cookies"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := res["cookies"]; exists {
t.Fatalf("完成验证响应不得暴露 cookies: %+v", res)
}
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码验证成功后应重新启用账号")
}
requireCookieSnapshotCleared(t, store, "acc1")
if tk, err := store.Tokens.Get(ctx, "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
if // tk、err 保存tk、err,供当前处理流程使用
tk, err := store.Tokens.Get(ctx, "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("扫码验证成功后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
// TestCompleteQRVerificationRejectsDifferentTarget 负责TestCompleteQRVerificationRejectsDifferentTarget相关处理。
func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -320,29 +405,39 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
completeUNB: "scanned-other",
}
ownQRSession(t, srv, store, "s-mismatch")
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// request 保存请求,供当前处理流程使用
request := func() map[string]any {
// body 保存请求体,供当前处理流程使用
body := `{"target_account_id":"acc1"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s-mismatch", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
var result map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
// result 保存结果,供当前处理流程使用
result := request()
if result["code"] != "qr_account_mismatch" || result["details"].(map[string]any)["scanned_account_id"] != "scanned-other" {
t.Fatalf("response=%+v", result)
}
// original 保存original,供当前处理流程使用
original, _ := store.Cookies.GetValue(context.Background(), "acc1")
if strings.Contains(original, "qr-fresh") {
t.Fatal("mismatched account must never overwrite the target account")
@@ -351,15 +446,20 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
func TestKeywordsListAndDelete(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 添加(普通 + 带 item_id)。
post := func(body string) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -369,14 +469,18 @@ func TestKeywordsListAndDelete(t *testing.T) {
post(`{"keyword":"在吗","reply":"在的"}`)
post(`{"keyword":"价格","reply":"50元","item_id":"item1"}`)
// path 表示当前遍历过程中的路径
for _, path := range []string{"/keywords/acc1", "/keywords-with-item-id/acc1", "/keywords-with-type/acc1"} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("GET %s status=%d", path, rec.Code)
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 2 {
@@ -387,13 +491,18 @@ func TestKeywordsListAndDelete(t *testing.T) {
// TestAddKeywordMissingKeyword 缺 keyword 400。
func TestAddKeywordMissingKeyword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(`{"reply":"x"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -403,13 +512,18 @@ func TestAddKeywordMissingKeyword(t *testing.T) {
// TestAddKeywordBadJSON 非法 JSON 400。
func TestAddKeywordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -417,35 +531,47 @@ func TestAddKeywordBadJSON(t *testing.T) {
}
}
// TestReplaceKeywordsWithItemID 负责TestReplaceKeywordsWith商品ID相关处理。
func TestReplaceKeywordsWithItemID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// postBatch 保存post批次,供当前处理流程使用
postBatch := func(body string) []map[string]any {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("replace status=%d body=%s", rec.Code, rec.Body.String())
}
// listReq 保存listReq,供当前处理流程使用
listReq := httptest.NewRequest(http.MethodGet, "/keywords-with-item-id/acc1", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// rows 保存rows,供当前处理流程使用
var rows []map[string]any
if err := json.Unmarshal(listRec.Body.Bytes(), &rows); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(listRec.Body.Bytes(), &rows); err != nil {
t.Fatal(err)
}
return rows
}
// rows 保存rows,供当前处理流程使用
rows := postBatch(`{"keywords":[{"keyword":"在吗","reply":"在的","item_id":""},{"keyword":"价格","reply":"50","item_id":"it1"}]}`)
if len(rows) != 2 || rows[1]["item_id"] != "it1" {
t.Fatalf("批量新增异常: %+v", rows)
@@ -462,18 +588,25 @@ func TestReplaceKeywordsWithItemID(t *testing.T) {
}
}
// TestReplaceKeywordsValidatesReplyTypeContent 负责TestReplaceKeywordsValidates回复类型内容相关处理。
func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
for _, body := range []string{
`{"keywords":[{"keyword":"文字","type":"text","reply":""}]}`,
`{"keywords":[{"keyword":"图片","type":"image","image_url":""}]}`,
`{"keywords":[{"keyword":"未知","type":"api","reply":"x"}]}`,
} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -481,9 +614,12 @@ func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
}
}
// valid 保存有效,供当前处理流程使用
valid := `{"keywords":[{"keyword":"图片","type":"image","reply":"stale","image_url":"https://example.com/a.png"}]}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(valid))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -493,13 +629,18 @@ func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
// TestDeleteKeywordNotFound 不存在关键字 404。
func TestDeleteKeywordNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/999", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -509,17 +650,23 @@ func TestDeleteKeywordNotFound(t *testing.T) {
// TestItemRepliesCRUD 指定商品回复增删查。
func TestItemRepliesCRUD(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-reply','商品R')`)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 设。
body := `{"reply_content":"这是专属回复"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it-reply", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -529,11 +676,13 @@ func TestItemRepliesCRUD(t *testing.T) {
// 查。
req2 := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/it-reply", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("get status=%d", rec2.Code)
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec2.Body.Bytes(), &got)
if got["reply_content"] != "这是专属回复" {
@@ -543,6 +692,7 @@ func TestItemRepliesCRUD(t *testing.T) {
// 列表。
req3 := httptest.NewRequest(http.MethodGet, "/itemReplays", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -552,6 +702,7 @@ func TestItemRepliesCRUD(t *testing.T) {
// 删除。
req4 := httptest.NewRequest(http.MethodDelete, "/item-reply/acc1/it-reply", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
@@ -561,18 +712,24 @@ func TestItemRepliesCRUD(t *testing.T) {
// TestGetItemReplyNotFound 不存在回复返回空。
func TestGetItemReplyNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d", rec.Code)
}
// got 保存got,供当前处理流程使用
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["reply_content"] != "" {
@@ -582,13 +739,18 @@ func TestGetItemReplyNotFound(t *testing.T) {
// TestSetItemReplyBadJSON 非法 JSON 400。
func TestSetItemReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+22 -3
View File
@@ -11,10 +11,12 @@ import (
// freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。
func freeAddr(t *testing.T) string {
t.Helper()
// l、err 保存l、err,供当前处理流程使用
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
// addr 保存addr,供当前处理流程使用
addr := l.Addr().String()
l.Close()
return addr
@@ -22,19 +24,25 @@ func freeAddr(t *testing.T) string {
// TestRun_ServesHealthAndShutdowns 启动 HTTP 服务,/health 可访问,ctx 取消后优雅退出。
func TestRun_ServesHealthAndShutdowns(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Addr = freeAddr(t)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// runDone 保存运行Done,供当前处理流程使用
runDone := make(chan error, 1)
go func() { runDone <- srv.Run(ctx) }()
// 轮询 /health 直到可用(最多 3s)。
url := "http://" + srv.Addr + "/health"
// ok 保存ok,供当前处理流程使用
var ok bool
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
// resp、err 保存resp、err,供当前处理流程使用
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
@@ -53,7 +61,8 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) {
// 取消 ctx → Run 应优雅退出。
cancel()
select {
case err := <-runDone:
case // err 保存err,供当前处理流程使用
err := <-runDone:
if err != nil {
t.Fatalf("Run 应返回 nil,got %v", err)
}
@@ -62,10 +71,14 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) {
}
}
// TestPublishWorkerTrackingWaitsForCompletion 负责Test发布工作器TrackingWaitsForCompletion相关处理。
func TestPublishWorkerTrackingWaitsForCompletion(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// doneWorker 保存done工作器,供当前处理流程使用
doneWorker := srv.beginWorker()
// waited 保存waited,供当前处理流程使用
waited := make(chan struct{})
go func() {
srv.waitForWorkers(time.Second)
@@ -84,12 +97,16 @@ func TestPublishWorkerTrackingWaitsForCompletion(t *testing.T) {
}
}
// TestPublishRecoveryLifecycleStopsBeforeWorkerWait 负责Test发布RecoveryLifecycleStopsBefore工作器Wait相关处理。
func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
srv.StartPublishBatchRecovery(ctx)
cancel()
// done 保存done,供当前处理流程使用
done := make(chan struct{})
go func() {
srv.WaitForBackground()
@@ -126,10 +143,12 @@ func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Addr = freeAddr(t)
if err := srv.Start(context.Background()); err != nil {
if // err 保存err,供当前处理流程使用
err := srv.Start(context.Background()); err != nil {
t.Fatalf("Start: %v", err)
}
if err := srv.Start(context.Background()); err != nil {
if // err 保存err,供当前处理流程使用
err := srv.Start(context.Background()); err != nil {
t.Fatalf("重复 Start: %v", err)
}
// workerDone 是模拟批量发布 worker 完成时调用的释放函数。
+28 -1
View File
@@ -10,10 +10,14 @@ import (
"time"
)
// TestProtectedRouteGroupsRequireAuthentication 负责TestProtectedRouteGroupsRequireAuthentication相关处理。
func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// routes 保存routes,供当前处理流程使用
routes := []struct {
method string
path string
@@ -31,9 +35,12 @@ func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
{http.MethodGet, "/user-settings"},
{http.MethodGet, "/admin/stats"},
}
// route 表示当前遍历过程中的route
for _, route := range routes {
t.Run(route.method+" "+route.path, func(t *testing.T) {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(route.method, route.path, nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -43,12 +50,17 @@ func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
}
}
// TestCookiePreferenceEndpoints 负责Test登录凭证PreferenceEndpoints相关处理。
func TestCookiePreferenceEndpoints(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// requests 保存请求列表,供当前处理流程使用
requests := []struct {
path string
body string
@@ -57,10 +69,13 @@ func TestCookiePreferenceEndpoints(t *testing.T) {
{"/cookies/acc1/remark", `{"remark":"primary"}`},
{"/cookies/acc1/pause-duration", `{"pause_duration":30}`},
}
// tc 表示当前遍历过程中的tc
for _, tc := range requests {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -68,38 +83,50 @@ func TestCookiePreferenceEndpoints(t *testing.T) {
}
}
// path 表示当前遍历过程中的路径
for _, path := range []string{"/cookies/acc1/auto-confirm", "/cookies/acc1/pause-duration", "/cookie/acc1/details"} {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("GET %s status=%d body=%s", path, rec.Code, rec.Body.String())
}
}
// paused、pausedUntil、err 保存paused、pausedUntil、err,供当前处理流程使用
paused, pausedUntil, err := store.Cookies.IsPaused(context.Background(), "acc1")
if err != nil || !paused || pausedUntil <= time.Now().UTC().Unix() {
t.Fatalf("pause deadline not persisted: paused=%v until=%d err=%v", paused, pausedUntil, err)
}
// pauseReq 保存pauseReq,供当前处理流程使用
pauseReq := httptest.NewRequest(http.MethodGet, "/cookies/acc1/pause-duration", nil)
pauseReq.AddCookie(cookie)
// pauseRec 保存pauseRec,供当前处理流程使用
pauseRec := httptest.NewRecorder()
h.ServeHTTP(pauseRec, pauseReq)
// pauseResponse 保存pause响应,供当前处理流程使用
var pauseResponse map[string]any
if err := json.Unmarshal(pauseRec.Body.Bytes(), &pauseResponse); err != nil || pauseResponse["paused"] != true {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(pauseRec.Body.Bytes(), &pauseResponse); err != nil || pauseResponse["paused"] != true {
t.Fatalf("pause response=%+v err=%v", pauseResponse, err)
}
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/pause-duration", strings.NewReader(`{"pause_duration":-1}`))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("negative pause status=%d body=%s", rec.Code, rec.Body.String())
}
// tooLongReq 保存tooLongReq,供当前处理流程使用
tooLongReq := httptest.NewRequest(http.MethodPut, "/cookies/acc1/pause-duration", strings.NewReader(`{"pause_duration":1441}`))
tooLongReq.AddCookie(cookie)
// tooLongRec 保存tooLongRec,供当前处理流程使用
tooLongRec := httptest.NewRecorder()
h.ServeHTTP(tooLongRec, tooLongReq)
if tooLongRec.Code != http.StatusBadRequest {
+43 -2
View File
@@ -32,12 +32,14 @@ import (
xrenew "xianyu-go/internal/xianyu/renew"
)
// qrLoginService 保存qr登录Service,供当前处理流程使用
type qrLoginService interface {
GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error)
GetSessionStatus(sessionID string) map[string]any
CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error)
}
// qrLoginPersistence 保存qr登录Persistence,供当前处理流程使用
type qrLoginPersistence struct {
AccountID string
IsNew bool
@@ -45,11 +47,13 @@ type qrLoginPersistence struct {
CreatedAt time.Time
}
// qrLoginOwner 保存qr登录所有者,供当前处理流程使用
type qrLoginOwner struct {
UserID int64
CreatedAt time.Time
}
// publishBatchWorker 保存发布批次工作器,供当前处理流程使用
type publishBatchWorker struct {
token string
cancel context.CancelFunc
@@ -60,6 +64,7 @@ type ServerOption func(*Server)
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
// Server 保存Server,供当前处理流程使用
type Server struct {
Store *db.Store
Auth *auth.Service
@@ -113,6 +118,7 @@ func WithChatService(service *chat.Service) ServerOption {
// New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入
// (创建顺序:adapter → manager → automation → notifier → server)。
// New 负责New相关处理。
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
if store == nil {
return nil, fmt.Errorf("server 依赖 db.Store 不能为空")
@@ -146,6 +152,7 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
}
// option 表示当前遍历过程中的option
for _, option := range options {
// option 是当前构造调用提供的可选依赖配置。
if option != nil {
@@ -167,6 +174,7 @@ func (s *Server) mtopClient() mtop.Client {
// recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。
// 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。
// recoverExpiredMTOPSession 负责recoverExpiredMTOP会话相关处理。
func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool {
if !mtop.IsSessionExpiredErr(err) {
return false
@@ -182,6 +190,7 @@ func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string,
// Router 构建完整路由树。
func (s *Server) Router() http.Handler {
// r 保存r,供当前处理流程使用
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Recoverer)
@@ -269,14 +278,18 @@ func (s *Server) authMiddleware(h http.Handler) http.Handler {
// requestLogger 记录请求完成状态、耗时和 chi request_id。
func (s *Server) requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// start 保存开始,供当前处理流程使用
start := time.Now()
// ww 保存ww,供当前处理流程使用
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
// status 保存状态,供当前处理流程使用
status := ww.Status()
if status == 0 {
status = http.StatusOK
}
// level 保存level,供当前处理流程使用
level := slog.LevelDebug
if status >= 500 {
level = slog.LevelError
@@ -300,11 +313,13 @@ func (s *Server) requestLogger(next http.Handler) http.Handler {
// 前端 vite base 为 /static/,构建后 index.html 引用 /static/assets/...、/static/favicon.svg。
// 故静态资源统一从 /static/ 前缀提供;非 API 的 GET 请求(/、/login 等客户端路由)
// 返回 /static/index.html,交给 React Router 接管。
// mountSPA 负责mountSPA相关处理。
func (s *Server) mountSPA(r chi.Router) {
if s.WebDir != "" {
s.mountDirSPA(r)
return
}
// embedded、err 保存embedded、err,供当前处理流程使用
embedded, err := webui.Static()
if err != nil {
return
@@ -312,10 +327,13 @@ func (s *Server) mountSPA(r chi.Router) {
s.mountFSSPA(r, embedded)
}
// mountDirSPA 负责mountDirSPA相关处理。
func (s *Server) mountDirSPA(r chi.Router) {
// indexFile 保存index文件,供当前处理流程使用
indexFile := filepath.Join(s.WebDir, "index.html")
// /static/* 直接作为静态文件服务(assets/、favicon.svg 等)。
// StripPrefix("/static/") 后,URL /static/assets/x.js → WebDir/assets/x.js。
// staticFiles 保存static文件列表,供当前处理流程使用
staticFiles := http.StripPrefix("/static/", http.FileServer(http.Dir(s.WebDir)))
r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" {
@@ -330,7 +348,8 @@ func (s *Server) mountDirSPA(r chi.Router) {
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
return
}
if _, err := os.Stat(indexFile); err != nil {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(indexFile); err != nil {
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
return
}
@@ -339,7 +358,9 @@ func (s *Server) mountDirSPA(r chi.Router) {
})
}
// mountFSSPA 负责mountFSSPA相关处理。
func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
// staticFiles 保存static文件列表,供当前处理流程使用
staticFiles := http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))
r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" {
@@ -353,6 +374,7 @@ func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
return
}
// index、err 保存index、err,供当前处理流程使用
index, err := fs.ReadFile(staticFS, "index.html")
if err != nil {
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
@@ -364,6 +386,7 @@ func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
})
}
// setNoStore 负责setNoStore相关处理。
func setNoStore(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
@@ -372,7 +395,9 @@ func setNoStore(w http.ResponseWriter) {
// isAPIPath 判断是否为 API 路径(不应被 SPA 拦截)。
// 仅保留实际挂载的路由前缀,与 Router() 中的 mount* 一一对应。
// isAPIPath 负责isAPI路径相关处理。
func isAPIPath(path string) bool {
// apiPrefixes 保存apiPrefixes,供当前处理流程使用
apiPrefixes := []string{
"/api/", "/admin/", "/health", "/login", "/initialize", "/logout", "/verify",
"/change-password", "/change-admin-password", "/account/",
@@ -385,6 +410,7 @@ func isAPIPath(path string) bool {
"/qr-login", "/password-login",
"/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all)
}
// p 表示当前遍历过程中的p
for _, p := range apiPrefixes {
if strings.HasPrefix(path, p) {
return true
@@ -395,6 +421,7 @@ func isAPIPath(path string) bool {
// health 健康检查。
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if s.Store == nil || s.Store.DB == nil || s.Store.DB.PingContext(ctx) != nil {
@@ -438,6 +465,7 @@ func (s *Server) Start(ctx context.Context) error {
}
// lifecycleCtx 是 Server 内部可取消的生命周期上下文。
// lifecycleCancel 是触发 Server 生命周期收束的取消函数。
// lifecycleCtx、lifecycleCancel 保存lifecycleCtx、lifecycle取消,供当前处理流程使用
lifecycleCtx, lifecycleCancel := context.WithCancel(ctx)
s.lifecycleCtx = lifecycleCtx
s.lifecycleCancel = lifecycleCancel
@@ -456,9 +484,11 @@ func (s *Server) Start(ctx context.Context) error {
<-lifecycleCtx.Done()
// stopCtx 是自动关闭 HTTP 服务时使用的有限时长上下文。
// cancel 释放 stopCtx 的定时器资源。
// stopCtx、cancel 保存stopCtx、cancel,供当前处理流程使用
stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.Stop(stopCtx); err != nil && s.Logger != nil {
if // err 保存err,供当前处理流程使用
err := s.Stop(stopCtx); err != nil && s.Logger != nil {
s.Logger.Warn("HTTP 服务关闭异常", "err", err)
}
}()
@@ -526,8 +556,11 @@ func (s *Server) Stop(ctx context.Context) error {
// httpServer 是需要执行优雅关闭的标准库 HTTP 服务。
// httpDone 是监听 goroutine 退出的完成信号。
// lifecycleCancel 是取消 Server 内部生命周期上下文的函数。
// httpServer 保存httpServer,供当前处理流程使用
httpServer := s.httpServer
// httpDone 保存httpDone,供当前处理流程使用
httpDone := s.httpDone
// lifecycleCancel 保存lifecycle取消,供当前处理流程使用
lifecycleCancel := s.lifecycleCancel
s.lifecycleMu.Unlock()
@@ -565,12 +598,15 @@ func (s *Server) WaitForBackground() {
s.waitForWorkers(10 * time.Second)
}
// closedSignal 负责closedSignal相关处理。
func closedSignal() chan struct{} {
// done 保存done,供当前处理流程使用
done := make(chan struct{})
close(done)
return done
}
// lifecycleContext 负责lifecycle上下文相关处理。
func (s *Server) lifecycleContext() context.Context {
s.lifecycleMu.RLock()
defer s.lifecycleMu.RUnlock()
@@ -579,6 +615,7 @@ func (s *Server) lifecycleContext() context.Context {
// startBackgroundTask 登记并启动一个受 Server 生命周期管理的后台任务。
// 调用方负责在任务函数内部响应上下文取消;WaitForBackground 会等待任务退出。
// startBackgroundTask 负责开始Background任务相关处理。
func (s *Server) startBackgroundTask(name string, task func()) {
s.backgroundWG.Add(1)
// #nosec G118 -- 任务由调用方提供的 Server 生命周期控制。
@@ -594,6 +631,7 @@ func (s *Server) startBackgroundTask(name string, task func()) {
}()
}
// beginWorker 负责begin工作器相关处理。
func (s *Server) beginWorker() func() {
s.workerMu.Lock()
if s.workerCount == 0 {
@@ -611,14 +649,17 @@ func (s *Server) beginWorker() func() {
}
}
// waitForWorkers 负责waitForWorkers相关处理。
func (s *Server) waitForWorkers(timeout time.Duration) {
s.workerMu.Lock()
// done 保存done,供当前处理流程使用
done := s.workersDone
s.workerMu.Unlock()
if timeout <= 0 {
<-done
return
}
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
+118 -9
View File
@@ -40,6 +40,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
if err != nil {
t.Fatalf("New: %v", err)
}
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := mtop.NewClient()
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
@@ -69,8 +70,10 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
return srv, store, cleanup
}
// newUninitializedTestServer 负责newUninitializedTestServer相关处理。
func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d 是当前未初始化测试使用的数据库连接;err 是打开错误。
d, _, err := db.Open(context.Background(), dbPath)
@@ -92,38 +95,54 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
}
// roundTripFunc 保存roundTripFunc,供当前处理流程使用
type roundTripFunc func(*http.Request) (*http.Response, error)
// RoundTrip 负责RoundTrip相关处理。
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// noopHandler 保存noopHandler,供当前处理流程使用
type noopHandler struct{}
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// HandleChatMessage 处理聊天消息。
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
// HandleSystemEvent 处理系统Event。
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestLoginVerifyLogout 登录→verify→登出 全链路。
func TestLoginVerifyLogout(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// 1) 登录(用户名密码)。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
// lr 保存lr,供当前处理流程使用
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if !lr.Success || !lr.IsAdmin {
t.Fatalf("登录响应异常: %+v", lr)
}
// cookie 保存登录凭证,供当前处理流程使用
cookie := rec.Result().Cookies()[0]
if cookie.Name != "session" || cookie.Value == "" || !cookie.HttpOnly {
t.Fatalf("Cookie 异常: %+v", cookie)
@@ -132,8 +151,10 @@ func TestLoginVerifyLogout(t *testing.T) {
// 2) verify 带 cookie 应 authenticated。
req2 := httptest.NewRequest(http.MethodGet, "/verify", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// v 保存v,供当前处理流程使用
var v map[string]any
json.Unmarshal(rec2.Body.Bytes(), &v)
if v["authenticated"] != true || v["initialized"] != true {
@@ -142,6 +163,7 @@ func TestLoginVerifyLogout(t *testing.T) {
// 3) 无 cookie verify 应未认证。
req3 := httptest.NewRequest(http.MethodGet, "/verify", nil)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
json.Unmarshal(rec3.Body.Bytes(), &v)
@@ -152,11 +174,14 @@ func TestLoginVerifyLogout(t *testing.T) {
// 4) 登出。
req4 := httptest.NewRequest(http.MethodPost, "/logout", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// 登出后 cookie 应被清除(MaxAge=-1)。
dc := rec4.Result().Cookies()
// cleared 保存cleared,供当前处理流程使用
cleared := false
// c 表示当前遍历过程中的c
for _, c := range dc {
if c.Name == "session" && c.MaxAge < 0 {
cleared = true
@@ -169,14 +194,20 @@ func TestLoginVerifyLogout(t *testing.T) {
// TestLoginWrongPassword 错误密码。
func TestLoginWrongPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// body 保存请求体,供当前处理流程使用
body := `{"username":"admin","password":"wrong"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// lr 保存lr,供当前处理流程使用
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if lr.Success {
@@ -184,57 +215,75 @@ func TestLoginWrongPassword(t *testing.T) {
}
}
// TestInitializeFromWebUI 负责TestInitializeFromWebUI相关处理。
func TestInitializeFromWebUI(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newUninitializedTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// shortReq 保存shortReq,供当前处理流程使用
shortReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"short"}`))
// shortRec 保存shortRec,供当前处理流程使用
shortRec := httptest.NewRecorder()
h.ServeHTTP(shortRec, shortReq)
if shortRec.Code != http.StatusBadRequest {
t.Fatalf("短密码应返回 400,got %d body=%s", shortRec.Code, shortRec.Body.String())
}
// initReq 保存initReq,供当前处理流程使用
initReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"newpassword"}`))
// initRec 保存initRec,供当前处理流程使用
initRec := httptest.NewRecorder()
h.ServeHTTP(initRec, initReq)
if initRec.Code != http.StatusOK {
t.Fatalf("初始化 status=%d body=%s", initRec.Code, initRec.Body.String())
}
// initResult 保存init结果,供当前处理流程使用
var initResult loginResponse
if err := json.Unmarshal(initRec.Body.Bytes(), &initResult); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(initRec.Body.Bytes(), &initResult); err != nil {
t.Fatalf("解析初始化响应: %v", err)
}
if !initResult.Success || !initResult.IsAdmin || initResult.Username != "admin" {
t.Fatalf("初始化响应异常: %+v", initResult)
}
// admin、err 保存admin、err,供当前处理流程使用
admin, err := store.Users.GetAdmin(context.Background())
if err != nil || admin == nil {
t.Fatalf("初始化后 admin 不存在: admin=%+v err=%v", admin, err)
}
if _, ok, err := store.Users.VerifyAndUpgrade(context.Background(), "admin", "newpassword"); err != nil || !ok {
if // ok、err 保存ok、err,供当前处理流程使用
_, ok, err := store.Users.VerifyAndUpgrade(context.Background(), "admin", "newpassword"); err != nil || !ok {
t.Fatalf("初始化密码不可用: ok=%v err=%v", ok, err)
}
// cookies 保存cookies,供当前处理流程使用
cookies := initRec.Result().Cookies()
if len(cookies) == 0 || cookies[0].Name != "session" || cookies[0].Value == "" {
t.Fatalf("初始化后应自动建立会话: %+v", cookies)
}
// verifyReq 保存verifyReq,供当前处理流程使用
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookies[0])
// verifyRec 保存verifyRec,供当前处理流程使用
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
var verifyResult map[string]any
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult); err != nil {
t.Fatalf("解析 verify 响应: %v", err)
}
if verifyResult["authenticated"] != true || verifyResult["initialized"] != true {
t.Fatalf("初始化后 verify 异常: %+v", verifyResult)
}
// secondReq 保存secondReq,供当前处理流程使用
secondReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"anotherpw"}`))
// secondRec 保存secondRec,供当前处理流程使用
secondRec := httptest.NewRecorder()
h.ServeHTTP(secondRec, secondReq)
if secondRec.Code != http.StatusConflict {
@@ -242,53 +291,71 @@ func TestInitializeFromWebUI(t *testing.T) {
}
}
// TestUpdateCredentialsRenamesUserAndRevokesSessions 负责TestUpdateCredentialsRenames用户AndRevokesSessions相关处理。
func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// sessionCookie 保存会话登录凭证,供当前处理流程使用
sessionCookie := loginRec.Result().Cookies()[0]
// updateReq 保存updateReq,供当前处理流程使用
updateReq := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(
`{"current_password":"pw","new_username":"operator","new_password":"newpassword"}`,
))
updateReq.AddCookie(sessionCookie)
// updateRec 保存updateRec,供当前处理流程使用
updateRec := httptest.NewRecorder()
h.ServeHTTP(updateRec, updateReq)
if updateRec.Code != http.StatusOK {
t.Fatalf("update status=%d body=%s", updateRec.Code, updateRec.Body.String())
}
// updateResult 保存update结果,供当前处理流程使用
var updateResult map[string]any
json.Unmarshal(updateRec.Body.Bytes(), &updateResult)
if updateResult["success"] != true || updateResult["requires_relogin"] != true {
t.Fatalf("update result=%+v", updateResult)
}
// verifyReq 保存verifyReq,供当前处理流程使用
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(sessionCookie)
// verifyRec 保存verifyRec,供当前处理流程使用
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
var verifyResult map[string]any
json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult)
if verifyResult["authenticated"] == true || verifyResult["initialized"] != true {
t.Fatalf("旧会话应失效且系统仍已初始化: %+v", verifyResult)
}
// oldLoginReq 保存old登录Req,供当前处理流程使用
oldLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// oldLoginRec 保存old登录Rec,供当前处理流程使用
oldLoginRec := httptest.NewRecorder()
h.ServeHTTP(oldLoginRec, oldLoginReq)
// oldLogin 保存old登录,供当前处理流程使用
var oldLogin loginResponse
json.Unmarshal(oldLoginRec.Body.Bytes(), &oldLogin)
if oldLogin.Success {
t.Fatal("旧用户名不应继续登录")
}
// newLoginReq 保存new登录Req,供当前处理流程使用
newLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"operator","password":"newpassword"}`))
// newLoginRec 保存new登录Rec,供当前处理流程使用
newLoginRec := httptest.NewRecorder()
h.ServeHTTP(newLoginRec, newLoginReq)
// newLogin 保存new登录,供当前处理流程使用
var newLogin loginResponse
json.Unmarshal(newLoginRec.Body.Bytes(), &newLogin)
if !newLogin.Success {
@@ -298,11 +365,15 @@ func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// TestCookiesDetailsRequiresAuth 未登录访问受保护端点应 401。
func TestCookiesDetailsRequiresAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -312,25 +383,32 @@ func TestCookiesDetailsRequiresAuth(t *testing.T) {
// TestCookiesDetailsWithAuth 登录后能取账号详情。
func TestCookiesDetailsWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// 登录拿 cookie。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
cookie := rec.Result().Cookies()[0]
// 取详情。
req2 := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("status=%d body=%s", rec2.Code, rec2.Body.String())
}
// arr 保存arr,供当前处理流程使用
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["id"] != "acc1" {
@@ -345,25 +423,35 @@ func TestCookiesDetailsWithAuth(t *testing.T) {
}
}
// TestCookieRuntimeStatusWithAuth 负责Test登录凭证Runtime状态WithAuth相关处理。
func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginRec.Result().Cookies()[0]
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/cookies/runtime-status", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// statuses 保存statuses,供当前处理流程使用
var statuses map[string]engine.RuntimeStatus
if err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil {
t.Fatal(err)
}
if statuses["acc1"].State != engine.RuntimeError {
@@ -373,20 +461,28 @@ func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// TestAddAndDeleteCookie 添加/删除账号。
func TestAddAndDeleteCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// body 保存请求体,供当前处理流程使用
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
cookie := rec.Result().Cookies()[0]
// 添加。
addBody := `{"id":"acc2","value":"unb=456; _m_h5_tk=tk2_2;"}`
// req2 保存req2,供当前处理流程使用
req2 := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(addBody))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -396,6 +492,7 @@ func TestAddAndDeleteCookie(t *testing.T) {
// 删除。
req3 := httptest.NewRequest(http.MethodDelete, "/cookies/acc2", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -405,11 +502,15 @@ func TestAddAndDeleteCookie(t *testing.T) {
// TestHealth 健康检查无需认证。
func TestHealth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -420,21 +521,29 @@ func TestHealth(t *testing.T) {
}
}
// TestHealthReportsUnavailableDatabase 负责TestHealthReportsUnavailableDatabase相关处理。
func TestHealthReportsUnavailableDatabase(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
if err := store.DB.Close(); err != nil {
if // err 保存err,供当前处理流程使用
err := store.DB.Close(); err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("health status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
var response map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response["status"] != "degraded" || response["database"] != "unavailable" {
+121 -10
View File
@@ -14,6 +14,7 @@ import (
// TestListAIModels 通过 mock OpenAI 端点返回模型列表。
func TestListAIModels(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入一个本地 HTTP server 作为 ai_api_url。
@@ -23,26 +24,35 @@ func TestListAIModels(t *testing.T) {
}))
defer ts.Close()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"base_url":"` + ts.URL + `","api_key":"sk-test"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
// models 保存模型列表,供当前处理流程使用
models, _ := res["models"].([]any)
if len(models) != 2 {
t.Fatalf("应2个模型,got %+v", res)
}
}
// TestReadOpenAIModelsBodyRejectsOversizedResponse 负责TestReadOpenAI模型列表请求体RejectsOversized响应相关处理。
func TestReadOpenAIModelsBodyRejectsOversizedResponse(t *testing.T) {
// err 保存err,供当前处理流程使用
_, err := readOpenAIModelsBody(strings.NewReader(strings.Repeat("x", maxOpenAIModelsResponseBytes+1)))
if err == nil {
t.Fatal("oversized models response should fail")
@@ -51,13 +61,18 @@ func TestReadOpenAIModelsBodyRejectsOversizedResponse(t *testing.T) {
// TestListAIModelsBadJSON 非法 JSON 400。
func TestListAIModelsBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -67,6 +82,7 @@ func TestListAIModelsBadJSON(t *testing.T) {
// TestListAIModelsEmptyBaseURL 空地址使用默认并失败(默认阿里云地址不可达或返回非 2xx)。
func TestListAIModelsEmptyBaseURL(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入一个返回错误状态码的本地 server。
@@ -77,12 +93,17 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) {
// 设置系统设置 ai_api_url 指向该 server。
srv.Store.Settings.Set(context.Background(), "ai_api_url", ts.URL)
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
@@ -92,13 +113,18 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) {
// TestSetSettingBadJSON 非法 JSON 400。
func TestSetSettingBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -106,54 +132,72 @@ func TestSetSettingBadJSON(t *testing.T) {
}
}
// TestSetLogLevelValidatesAndAppliesRuntimeLevel 负责TestSetLogLevelValidatesAndAppliesRuntimeLevel相关处理。
func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
defer logging.Level.Set(slog.LevelInfo)
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// badReq 保存badReq,供当前处理流程使用
badReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"verbose"}`))
badReq.AddCookie(cookie)
// badRec 保存badRec,供当前处理流程使用
badRec := httptest.NewRecorder()
h.ServeHTTP(badRec, badReq)
if badRec.Code != http.StatusBadRequest {
t.Fatalf("invalid log level should be 400, got %d body=%s", badRec.Code, badRec.Body.String())
}
// goodReq 保存goodReq,供当前处理流程使用
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"debug"}`))
goodReq.AddCookie(cookie)
// goodRec 保存goodRec,供当前处理流程使用
goodRec := httptest.NewRecorder()
h.ServeHTTP(goodRec, goodReq)
if goodRec.Code != http.StatusOK {
t.Fatalf("valid log level should be 200, got %d body=%s", goodRec.Code, goodRec.Body.String())
}
if got := logging.Level.Level(); got != slog.LevelDebug {
if // got 保存got,供当前处理流程使用
got := logging.Level.Level(); got != slog.LevelDebug {
t.Fatalf("runtime log level=%v want debug", got)
}
// saved、err 保存saved、err,供当前处理流程使用
saved, err := srv.Store.Settings.Get(context.Background(), "log_level")
if err != nil || saved != "debug" {
t.Fatalf("saved log_level=%q err=%v", saved, err)
}
}
// TestSystemSettingsRequireAdmin 负责Test系统设置RequireAdmin相关处理。
func TestSystemSettingsRequireAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
if _, err := srv.Store.Users.Create(context.Background(), "user-settings", "user-settings@example.com", "pw"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := srv.Store.Users.Create(context.Background(), "user-settings", "user-settings@example.com", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// loginReq 保存登录Req,供当前处理流程使用
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"user-settings","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK || len(loginRec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", loginRec.Code, loginRec.Body.String())
}
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginRec.Result().Cookies()[0]
// cases 保存cases,供当前处理流程使用
cases := []struct {
method string
path string
@@ -163,9 +207,12 @@ func TestSystemSettingsRequireAdmin(t *testing.T) {
{http.MethodPut, "/system-settings/theme_color", `{"value":"red"}`},
{http.MethodPost, "/ai-models", `{"base_url":"http://127.0.0.1","api_key":"sk"}`},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -174,49 +221,65 @@ func TestSystemSettingsRequireAdmin(t *testing.T) {
}
}
// TestBulkSystemSettingsAreAtomic 负责TestBulk系统设置AreAtomic相关处理。
func TestBulkSystemSettingsAreAtomic(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// badReq 保存badReq,供当前处理流程使用
badReq := httptest.NewRequest(http.MethodPut, "/system-settings", strings.NewReader(`{"theme_color":"red","log_level":"verbose"}`))
badReq.AddCookie(cookie)
// badRec 保存badRec,供当前处理流程使用
badRec := httptest.NewRecorder()
h.ServeHTTP(badRec, badReq)
if badRec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", badRec.Code, badRec.Body.String())
}
if value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value == "red" {
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value == "red" {
t.Fatal("invalid bulk request partially saved theme_color")
}
// goodReq 保存goodReq,供当前处理流程使用
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings", strings.NewReader(`{"theme_color":"blue","renewal_log_retention_days":15}`))
goodReq.AddCookie(cookie)
// goodRec 保存goodRec,供当前处理流程使用
goodRec := httptest.NewRecorder()
h.ServeHTTP(goodRec, goodReq)
if goodRec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", goodRec.Code, goodRec.Body.String())
}
if value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value != "blue" {
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value != "blue" {
t.Fatalf("theme_color=%q", value)
}
if value, _ := srv.Store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" {
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" {
t.Fatalf("retention=%q", value)
}
}
// TestListUserSettings 用户设置增删查。
func TestListUserSettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// 设。
body := `{"value":"dark"}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -226,11 +289,13 @@ func TestListUserSettings(t *testing.T) {
// 查全部。
req2 := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// m 保存m,供当前处理流程使用
var m map[string]string
json.Unmarshal(rec2.Body.Bytes(), &m)
if m["theme"] != "dark" {
@@ -240,8 +305,10 @@ func TestListUserSettings(t *testing.T) {
// 查单。
req3 := httptest.NewRequest(http.MethodGet, "/user-settings/theme", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// one 保存one,供当前处理流程使用
var one map[string]any
json.Unmarshal(rec3.Body.Bytes(), &one)
if one["value"] != "dark" {
@@ -251,8 +318,10 @@ func TestListUserSettings(t *testing.T) {
// 查不存在的 key。
req4 := httptest.NewRequest(http.MethodGet, "/user-settings/no-such-key", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// miss 保存miss,供当前处理流程使用
var miss map[string]any
json.Unmarshal(rec4.Body.Bytes(), &miss)
if miss["value"] != "" {
@@ -262,13 +331,18 @@ func TestListUserSettings(t *testing.T) {
// TestSetUserSettingBadJSON 非法 JSON 400。
func TestSetUserSettingBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -278,13 +352,18 @@ func TestSetUserSettingBadJSON(t *testing.T) {
// TestSetAIReplyBadJSON 非法 JSON 400。
func TestSetAIReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -292,14 +371,20 @@ func TestSetAIReplyBadJSON(t *testing.T) {
}
}
// TestGetAIReplyMissingAccountIsNotFound 负责TestGetAI回复Missing账号IsNotFound相关处理。
func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -307,19 +392,26 @@ func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
}
}
// TestGetAIReplyExistingAccountWithoutConfigReturnsDefault 负责TestGetAI回复Existing账号Without配置ReturnsDefault相关处理。
func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["ai_enabled"] != false || res["max_discount_percent"] != float64(10) {
@@ -327,55 +419,73 @@ func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
}
}
// TestAIReplySettingsAreUserScoped 负责TestAI回复设置Are用户Scoped相关处理。
func TestAIReplySettingsAreUserScoped(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
if _, err := store.Users.Create(ctx, "user2", "u2@e.com", "pw"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.Users.Create(ctx, "user2", "u2@e.com", "pw"); err != nil {
t.Fatalf("create user2: %v", err)
}
// user2、err 保存user2、err,供当前处理流程使用
user2, err := store.Users.GetByUsername(ctx, "user2")
if err != nil {
t.Fatalf("get user2: %v", err)
}
if err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", user2.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", user2.ID); err != nil {
t.Fatalf("save other cookie: %v", err)
}
if _, err := store.DB.ExecContext(ctx,
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx,
`INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('other-acc', 1, 'secret')`); err != nil {
t.Fatalf("insert ai settings: %v", err)
}
// h 保存h,供当前处理流程使用
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
listReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// listed 保存listed,供当前处理流程使用
var listed map[string]any
if err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
t.Fatalf("decode list: %v", err)
}
if _, ok := listed["other-acc"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := listed["other-acc"]; ok {
t.Fatalf("list leaked other user's AI settings: %+v", listed)
}
// getReq 保存getReq,供当前处理流程使用
getReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/other-acc", nil)
getReq.AddCookie(cookie)
// getRec 保存getRec,供当前处理流程使用
getRec := httptest.NewRecorder()
h.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusForbidden {
t.Fatalf("cross-user get should be 403, got %d body=%s", getRec.Code, getRec.Body.String())
}
// setReq 保存setReq,供当前处理流程使用
setReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/other-acc", strings.NewReader(
`{"ai_enabled":true,"max_discount_percent":20,"max_discount_amount":200,"max_bargain_rounds":5,"custom_prompts":"override"}`,
))
setReq.AddCookie(cookie)
// setRec 保存setRec,供当前处理流程使用
setRec := httptest.NewRecorder()
h.ServeHTTP(setRec, setReq)
if setRec.Code != http.StatusForbidden {
@@ -385,6 +495,7 @@ func TestAIReplySettingsAreUserScoped(t *testing.T) {
// TestFetchOpenAIModelsEmptyBaseURL 空地址错误。
func TestFetchOpenAIModelsEmptyBaseURL(t *testing.T) {
// err 保存err,供当前处理流程使用
_, err := fetchOpenAIModels(context.Background(), "", "")
if err == nil {
t.Fatal("空地址应报错")
+95 -18
View File
@@ -18,6 +18,7 @@ import (
"xianyu-go/internal/netguard"
)
// maxOpenAIModelsResponseBytes 保存maxOpenAI模型列表响应Bytes,供当前处理流程使用
const maxOpenAIModelsResponseBytes = 4 << 20
// authSess 从上下文取会话。
@@ -36,13 +37,18 @@ func (s *Server) mountSettingsReal(r chi.Router) {
})
}
// setSettings 负责set设置相关处理。
func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
// raw 保存原始,供当前处理流程使用
var raw map[string]any
if err := decodeJSON(r, &raw); err != nil || len(raw) == 0 {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &raw); err != nil || len(raw) == 0 {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// values 保存values,供当前处理流程使用
values := make(map[string]string, len(raw))
// key、value 表示当前遍历过程中的key、value
for key, value := range raw {
key = strings.TrimSpace(key)
if key == "" || len(key) > 100 || value == nil {
@@ -51,23 +57,29 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
}
values[key] = stringFromAny(value)
}
if level, ok := values["log_level"]; ok {
if _, err := logging.ParseLevel(level); err != nil {
if // level、ok 保存level、ok,供当前处理流程使用
level, ok := values["log_level"]; ok {
if // err 保存err,供当前处理流程使用
_, err := logging.ParseLevel(level); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
}
if err := s.Store.Settings.SetMany(r.Context(), values); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Settings.SetMany(r.Context(), values); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
if level, ok := values["log_level"]; ok {
if // level、ok 保存level、ok,供当前处理流程使用
level, ok := values["log_level"]; ok {
_ = logging.SetLevel(level)
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// publicSettings 负责public设置相关处理。
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
// m、err 保存m、err,供当前处理流程使用
m, err := s.Store.Settings.Public(r.Context())
if err != nil {
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
@@ -76,7 +88,9 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, settingsResponse(m))
}
// allSettings 负责all设置相关处理。
func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
// m、err 保存m、err,供当前处理流程使用
m, err := s.Store.Settings.All(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -85,22 +99,28 @@ func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, settingsResponse(m))
}
// setSetting 负责set设置相关处理。
func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
// key 保存key,供当前处理流程使用
key := chi.URLParam(r, "key")
// req 保存req,供当前处理流程使用
var req struct {
Value string `json:"value"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if key == "log_level" {
if err := logging.SetLevel(req.Value); err != nil {
if // err 保存err,供当前处理流程使用
err := logging.SetLevel(req.Value); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
}
if err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -109,20 +129,26 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
// ---- AI 回复设置 ----
// mountAIReplyReal 负责mountAI回复Real相关处理。
func (s *Server) mountAIReplyReal(r chi.Router) {
r.Get("/ai-reply-settings", s.listAIReply)
r.Get("/ai-reply-settings/{cookie_id}", s.getAIReply)
r.Put("/ai-reply-settings/{cookie_id}", s.setAIReply)
}
// listAIReply 负责listAI回复相关处理。
func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.AIReply.ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// result 保存结果,供当前处理流程使用
result := make(map[string]aiReplySettingsResponse)
// row 表示当前遍历过程中的row
for _, row := range rows {
result[row.CookieID] = aiReplySettingsResponse{
CookieID: row.CookieID, AIEnabled: row.AIEnabled, MaxDiscountPercent: row.MaxDiscountPercent,
@@ -136,11 +162,14 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// getAIReply 负责getAI回复相关处理。
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// cfg、err 保存cfg、err,供当前处理流程使用
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
if err != nil {
if !errors.Is(err, db.ErrNotFound) {
@@ -166,8 +195,11 @@ func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, aiReplySettingsResponse{CookieID: cfg.CookieID, AIEnabled: cfg.AIEnabled, MaxDiscountPercent: cfg.MaxDiscountPercent, MaxDiscountAmount: cfg.MaxDiscountAmount, MaxBargainRounds: cfg.MaxBargainRounds, CustomPrompts: cfg.CustomPrompts})
}
// setAIReply 负责setAI回复相关处理。
func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
// req 保存req,供当前处理流程使用
var req struct {
AIEnabled bool `json:"ai_enabled"`
MaxDiscountPercent int `json:"max_discount_percent"`
@@ -175,7 +207,8 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
MaxBargainRounds int `json:"max_bargain_rounds"`
CustomPrompts string `json:"custom_prompts"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
@@ -207,17 +240,22 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// listAIModels 负责listAI模型列表相关处理。
func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// baseURL 保存baseURL,供当前处理流程使用
baseURL := strings.TrimSpace(req.BaseURL)
if baseURL == "" {
// v、err 保存v、err,供当前处理流程使用
v, err := s.Store.Settings.Get(r.Context(), "ai_api_url")
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取AI地址失败")
@@ -228,8 +266,10 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
if baseURL == "" {
baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
// apiKey 保存apiKey,供当前处理流程使用
apiKey := strings.TrimSpace(req.APIKey)
if apiKey == "" {
// v、err 保存v、err,供当前处理流程使用
v, err := s.Store.Settings.Get(r.Context(), "ai_api_key")
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取AI Key失败")
@@ -238,6 +278,7 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
apiKey = v
}
// models、err 保存models、err,供当前处理流程使用
models, err := fetchOpenAIModels(r.Context(), baseURL, apiKey)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
@@ -246,15 +287,18 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, aiModelsResponse{Models: models})
}
// newSettingsOutboundHTTPClient 保存new设置OutboundHTTPClient,供当前处理流程使用
var newSettingsOutboundHTTPClient = func(baseURL string) (*http.Client, error) {
return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second)
}
// fetchOpenAIModels 负责fetchOpenAI模型列表相关处理。
func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if baseURL == "" {
return nil, fmt.Errorf("AI API 地址为空")
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/models", nil)
if err != nil {
return nil, err
@@ -263,15 +307,18 @@ func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, e
if strings.TrimSpace(apiKey) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(apiKey))
}
// client、err 保存client、err,供当前处理流程使用
client, err := newSettingsOutboundHTTPClient(baseURL)
if err != nil {
return nil, fmt.Errorf("AI API 地址无效: %w", err)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("读取模型失败: %w", err)
}
defer resp.Body.Close()
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readOpenAIModelsBody(resp.Body)
if err != nil {
return nil, err
@@ -279,6 +326,7 @@ func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, e
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("读取模型失败: HTTP %d %s", resp.StatusCode, truncate(string(raw), 180))
}
// models、err 保存models、err,供当前处理流程使用
models, err := parseOpenAIModels(raw)
if err != nil {
return nil, err
@@ -289,7 +337,9 @@ func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, e
return models, nil
}
// readOpenAIModelsBody 负责readOpenAI模型列表请求体相关处理。
func readOpenAIModelsBody(r io.Reader) ([]byte, error) {
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(r, maxOpenAIModelsResponseBytes+1))
if err != nil {
return nil, err
@@ -300,13 +350,19 @@ func readOpenAIModelsBody(r io.Reader) ([]byte, error) {
return raw, nil
}
// parseOpenAIModels 负责parseOpenAI模型列表相关处理。
func parseOpenAIModels(raw []byte) ([]string, error) {
// payload 保存请求载荷,供当前处理流程使用
var payload any
if err := json.Unmarshal(raw, &payload); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("解析模型列表失败: %w", err)
}
// seen 保存seen,供当前处理流程使用
seen := make(map[string]bool)
// out 保存out,供当前处理流程使用
var out []string
// add 保存add,供当前处理流程使用
add := func(v string) {
v = strings.TrimSpace(v)
if v == "" || seen[v] {
@@ -315,27 +371,35 @@ func parseOpenAIModels(raw []byte) ([]string, error) {
seen[v] = true
out = append(out, v)
}
// walk 保存walk,供当前处理流程使用
var walk func(any)
walk = func(v any) {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case []any:
// item 表示当前遍历过程中的商品
for _, item := range x {
walk(item)
}
case map[string]any:
if id, _ := x["id"].(string); id != "" {
if // id 保存标识,供当前处理流程使用
id, _ := x["id"].(string); id != "" {
add(id)
} else if name, _ := x["name"].(string); name != "" {
} else if // name 保存名称,供当前处理流程使用
name, _ := x["name"].(string); name != "" {
add(name)
}
case string:
add(x)
}
}
if root, ok := payload.(map[string]any); ok {
if data, ok := root["data"]; ok {
if // root、ok 保存root、ok,供当前处理流程使用
root, ok := payload.(map[string]any); ok {
if // data、ok 保存data、ok,供当前处理流程使用
data, ok := root["data"]; ok {
walk(data)
} else if models, ok := root["models"]; ok {
} else if // models、ok 保存models、ok,供当前处理流程使用
models, ok := root["models"]; ok {
walk(models)
}
} else {
@@ -346,14 +410,18 @@ func parseOpenAIModels(raw []byte) ([]string, error) {
// ---- 用户设置 ----
// mountUserReal 负责mount用户Real相关处理。
func (s *Server) mountUserReal(r chi.Router) {
r.Get("/user-settings", s.listUserSettings)
r.Put("/user-settings/{key}", s.setUserSetting)
r.Get("/user-settings/{key}", s.getUserSetting)
}
// listUserSettings 负责list用户设置相关处理。
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// settings、err 保存settings、err,供当前处理流程使用
settings, err := s.Store.UserSettings.AllForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
@@ -362,9 +430,13 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, settingsResponse(settings))
}
// getUserSetting 负责get用户设置相关处理。
func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// key 保存key,供当前处理流程使用
key := chi.URLParam(r, "key")
// v、err 保存v、err,供当前处理流程使用
v, err := s.Store.UserSettings.GetForUser(r.Context(), sess.UserID, key)
if err != nil {
writeJSON(w, http.StatusOK, userSettingResponse{Value: ""})
@@ -373,13 +445,18 @@ func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, userSettingResponse{Value: v})
}
// setUserSetting 负责set用户设置相关处理。
func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := authSess(r)
// key 保存key,供当前处理流程使用
key := chi.URLParam(r, "key")
// req 保存req,供当前处理流程使用
var req struct {
Value string `json:"value"`
}
if err := decodeJSON(r, &req); err != nil {
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
+13
View File
@@ -19,13 +19,16 @@ func TestSPAServing(t *testing.T) {
os.WriteFile(filepath.Join(webDir, "assets", "app.js"), []byte("console.log(1)"), 0644)
os.WriteFile(filepath.Join(webDir, "favicon.svg"), []byte("<svg/>"), 0644)
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.WebDir = webDir
// h 保存h,供当前处理流程使用
h := srv.Router()
// 1) / 应返回 index.html。
req := httptest.NewRequest(http.MethodGet, "/", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -37,6 +40,7 @@ func TestSPAServing(t *testing.T) {
// 2) /static/assets/app.js 应返回 JS(vite base=/static/)。
req2 := httptest.NewRequest(http.MethodGet, "/static/assets/app.js", nil)
// rec2 保存rec2,供当前处理流程使用
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -47,7 +51,9 @@ func TestSPAServing(t *testing.T) {
}
// 3) /static/favicon.svg。
// req3 保存req3,供当前处理流程使用
req3 := httptest.NewRequest(http.MethodGet, "/static/favicon.svg", nil)
// rec3 保存rec3,供当前处理流程使用
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -56,6 +62,7 @@ func TestSPAServing(t *testing.T) {
// 4) 客户端路由(如 /dashboard)应返回 index.html(React Router 接管)。
req4 := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
// rec4 保存rec4,供当前处理流程使用
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 || rec4.Body.String() != "<html>SPA</html>" {
@@ -64,6 +71,7 @@ func TestSPAServing(t *testing.T) {
// 5) API 路径不应返回 index.html。
req5 := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
// rec5 保存rec5,供当前处理流程使用
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
// /api/orders 需认证,应 401(不是 index.html)。
@@ -74,12 +82,16 @@ func TestSPAServing(t *testing.T) {
// TestSPAEmbeddedWithoutWebDir 未配置 WebDir 时使用内嵌 SPA。
func TestSPAEmbeddedWithoutWebDir(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.WebDir = ""
// h 保存h,供当前处理流程使用
h := srv.Router()
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodGet, "/", nil)
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -90,6 +102,7 @@ func TestSPAEmbeddedWithoutWebDir(t *testing.T) {
}
}
// init 负责init相关处理。
func init() {
// newTestServer 用 context.Background,确保可用。
_ = context.Background
+3 -1
View File
@@ -27,6 +27,7 @@ func (r storeTransactionRepository) WithTransaction(ctx context.Context, work fu
}
// tx 是本次用例使用的数据库事务。
// err 表示事务创建错误。
// tx、err 保存tx、err,供当前处理流程使用
tx, err := r.store.DB.BeginTx(ctx, nil)
if err != nil {
return err
@@ -38,7 +39,8 @@ func (r storeTransactionRepository) WithTransaction(ctx context.Context, work fu
_ = tx.Rollback()
}
}()
if err := work(tx); err != nil {
if // err 保存err,供当前处理流程使用
err := work(tx); err != nil {
return err
}
// err 表示事务提交错误。
+1
View File
@@ -8,6 +8,7 @@ import (
// withTransaction 在 Server 应用层统一创建、提交或回滚数据库事务。
// 调用方只描述事务内的数据库操作,不再直接管理事务生命周期。
// withTransaction 负责withTransaction相关处理。
func (s *Server) withTransaction(ctx context.Context, work func(*sql.Tx) error) error {
// repository 是当前 Server 装配的事务执行边界。
repository := s.transactionRepository
+6 -2
View File
@@ -20,6 +20,7 @@ func TestWithTransactionCommitAndRollback(t *testing.T) {
}
// commitErr 是提交事务执行结果。
commitErr := srv.withTransaction(ctx, func(tx *sql.Tx) error {
// err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (1, 'committed')`)
return err
})
@@ -28,7 +29,9 @@ func TestWithTransactionCommitAndRollback(t *testing.T) {
}
// rollbackErr 是故意触发回滚事务的错误。
rollbackErr := errors.New("故意回滚")
if err := srv.withTransaction(ctx, func(tx *sql.Tx) error {
if // err 保存err,供当前处理流程使用
err := srv.withTransaction(ctx, func(tx *sql.Tx) error {
// err 保存err,供当前处理流程使用
_, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (2, 'rolled back')`)
if err != nil {
return err
@@ -39,7 +42,8 @@ func TestWithTransactionCommitAndRollback(t *testing.T) {
}
// count 是事务提交后测试表中的记录数。
var count int
if err := srv.Store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil {
if // err 保存err,供当前处理流程使用
err := srv.Store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil {
t.Fatalf("查询事务测试结果失败: %v", err)
}
if count != 1 {
+2
View File
@@ -2,7 +2,9 @@ package server
import "io"
// readLimitedBytes 负责readLimitedBytes相关处理。
func readLimitedBytes(r io.Reader, maxBytes int64) ([]byte, bool, error) {
// data、err 保存data、err,供当前处理流程使用
data, err := io.ReadAll(io.LimitReader(r, maxBytes+1))
if err != nil {
return nil, false, err
+4 -2
View File
@@ -205,7 +205,8 @@ func checkSpec(fileNode *ast.File, fileSet *token.FileSet, relativePath string,
case *ast.ValueSpec:
// name 表示常量或变量规范中的一个绑定名称。
for _, name := range current.Names {
if name.Name == "_" || hasChineseComment(fileNode, fileSet, current) {
// declaration 允许分组 const/var 声明共用紧邻声明块的职责说明。
if name.Name == "_" || hasChineseComment(fileNode, fileSet, declaration) || hasChineseComment(fileNode, fileSet, current) {
continue
}
*findings = append(*findings, newFinding(relativePath, fileSet, current, kind, name.Name))
@@ -265,7 +266,8 @@ func hasChineseComment(fileNode *ast.File, fileSet *token.FileSet, node ast.Node
commentStart := fileSet.Position(group.Pos()).Line
// commentEnd 是注释组末尾所在的行。
commentEnd := fileSet.Position(group.End()).Line
if commentEnd > startLine || commentStart < startLine-1 {
// commentEnd 必须紧邻声明;同一文档块可以跨越多行说明完整职责。
if commentEnd > startLine || commentEnd < startLine-1 {
continue
}
if commentStart == startLine || commentEnd == startLine-1 || commentStart <= endLine && commentEnd >= startLine {