chore: checkpoint repaired xianyu-go baseline
This commit is contained in:
1 parent
62705c524d
commit
3d37ff7917
119 files changed
+20086
-2085
No files matched your search
@@ -0,0 +1,417 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAdminListCookies 管理员列出所有账号。
|
||||
func TestAdminListCookies(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 || arr[0]["id"] != "acc1" {
|
||||
t.Fatalf("账号列表异常: %+v", arr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminDeleteUser 删除其他用户。
|
||||
func TestAdminDeleteUser(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.Users.Create(ctx, "user-del", "[email protected]", "pw")
|
||||
u, _ := store.Users.GetByUsername(ctx, "user-del")
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminDeleteUserRevokesSessions(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "session-del", "[email protected]", "pw"); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
u, err := store.Users.GetByUsername(ctx, "session-del")
|
||||
if err != nil {
|
||||
t.Fatalf("get user: %v", err)
|
||||
}
|
||||
h := srv.Router()
|
||||
|
||||
userLogin := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"session-del","password":"pw"}`))
|
||||
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 := userLoginRec.Result().Cookies()[0]
|
||||
adminCookie := loginHelper(t, h)
|
||||
|
||||
delReq := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
|
||||
delReq.AddCookie(adminCookie)
|
||||
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 := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||||
verifyReq.AddCookie(userCookie)
|
||||
verifyRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(verifyRec, verifyReq)
|
||||
var verify map[string]any
|
||||
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
|
||||
t.Fatalf("decode verify: %v", err)
|
||||
}
|
||||
if verify["authenticated"] == true {
|
||||
t.Fatalf("deleted user's old session should be invalid: %+v", verify)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminDeleteUserSelf 不能删除自己 400。
|
||||
func TestAdminDeleteUserSelf(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(admin.ID), nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("不能删自己应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminDeleteUserBadID 无效 ID 400。
|
||||
func TestAdminDeleteUserBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/admin/users/abc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminStatsWithOrders 带订单的统计。
|
||||
func TestAdminStatsWithOrders(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
}
|
||||
var stats map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &stats)
|
||||
if stats["total_orders"] != float64(1) || stats["total_cards"] != float64(1) {
|
||||
t.Fatalf("stats 异常: %+v", stats)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangeAdminPassword 修改管理员密码成功。
|
||||
func TestChangeAdminPassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"pw","new_password":"newpw123"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true {
|
||||
t.Fatalf("应成功: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangeAdminPasswordWrongCurrent 当前密码错误。
|
||||
func TestChangeAdminPasswordWrongCurrent(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"wrong","new_password":"newpw123"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] == true {
|
||||
t.Fatal("错误密码不应成功")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangeAdminPasswordBadJSON 非法 JSON 400。
|
||||
func TestChangeAdminPasswordBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("管理员新密码过短应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangeAdminPasswordNonAdmin 非 admin 403。
|
||||
func TestChangeAdminPasswordNonAdmin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
|
||||
h := srv.Router()
|
||||
body := `{"username":"user2","password":"pw"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
cookie := rec.Result().Cookies()[0]
|
||||
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusForbidden {
|
||||
t.Fatalf("非 admin 应 403,got %d", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangePassword 修改当前用户密码。
|
||||
func TestChangePassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"pw","new_password":"newpw123"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true {
|
||||
t.Fatalf("应成功: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePasswordRevokesCurrentSession(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("change status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
if 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 := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||||
verifyReq.AddCookie(cookie)
|
||||
verifyRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(verifyRec, verifyReq)
|
||||
var verify map[string]any
|
||||
if err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
|
||||
t.Fatalf("decode verify: %v", err)
|
||||
}
|
||||
if verify["authenticated"] == true {
|
||||
t.Fatalf("old session should be revoked after password change: %+v", verify)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangePasswordWrongCurrent 当前密码错误。
|
||||
func TestChangePasswordWrongCurrent(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"wrong","new_password":"newpw123"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] == true {
|
||||
t.Fatal("错误密码不应成功")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangePasswordBadJSON 非法 JSON 400。
|
||||
func TestChangePasswordBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePasswordShortNewPassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("新密码过短应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCredentialsBadUsername 用户名长度不足 400。
|
||||
func TestUpdateCredentialsBadUsername(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"pw","new_username":"ab"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("用户名过短应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCredentialsMissingCurrentPassword 缺当前密码 400。
|
||||
func TestUpdateCredentialsMissingCurrentPassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"new_username":"newname"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺当前密码应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCredentialsShortNewPassword 新密码过短 400。
|
||||
func TestUpdateCredentialsShortNewPassword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"pw","new_password":"123"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("新密码过短应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCredentialsNothingChanged 用户名密码均未修改 400。
|
||||
func TestUpdateCredentialsNothingChanged(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"current_password":"pw","new_username":"admin"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("未修改应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
"created_at": createdAt, "cookie_count": cookieCount,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取用户数据失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -60,8 +64,7 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "不能删除当前登录用户")
|
||||
return
|
||||
}
|
||||
_, err = s.Store.DB.ExecContext(r.Context(), `DELETE FROM users WHERE id=?`, uid)
|
||||
if err != nil {
|
||||
if err := s.Store.Users.Delete(r.Context(), uid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
@@ -92,6 +95,10 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), id),
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号数据失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
|
||||
@@ -67,6 +67,11 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询每日统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 3. 按状态统计。
|
||||
@@ -89,6 +94,11 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询状态统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 4. 按城市统计。
|
||||
@@ -112,6 +122,11 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询城市统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 5. 商品排行。
|
||||
@@ -136,6 +151,11 @@ func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询商品统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -183,6 +203,10 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"orders": out})
|
||||
}
|
||||
|
||||
|
||||
@@ -121,6 +121,10 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(req.NewPassword) < 8 {
|
||||
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
sess := auth.SessionFromContext(ctx)
|
||||
if sess == nil || !sess.IsAdmin {
|
||||
@@ -137,7 +141,8 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功"})
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功,请重新登录", "requires_relogin": true})
|
||||
}
|
||||
|
||||
// changePassword 修改当前用户密码。
|
||||
@@ -150,6 +155,10 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(req.NewPassword) < 8 {
|
||||
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
sess := auth.SessionFromContext(ctx)
|
||||
if sess == nil {
|
||||
@@ -165,7 +174,8 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功"})
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功,请重新登录", "requires_relogin": true})
|
||||
}
|
||||
|
||||
// updateCredentials 修改当前登录用户的用户名和/或密码,并撤销全部旧会话。
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestAutomationRulesCRUD 自动化规则增删查 + 校验分支。
|
||||
func TestAutomationRulesCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
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 := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var cr map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &cr)
|
||||
if cr["success"] != true {
|
||||
t.Fatalf("创建失败: %+v", cr)
|
||||
}
|
||||
ruleID := itoa(int64(cr["id"].(float64)))
|
||||
|
||||
// 列表。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/automation-rules", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("list status=%d", rec2.Code)
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 {
|
||||
t.Fatalf("应1条规则,got %d", len(arr))
|
||||
}
|
||||
|
||||
// 更新规则(改名为自定义)。
|
||||
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 := httptest.NewRequest(http.MethodPut, "/automation-rules/"+ruleID, strings.NewReader(updBody))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
|
||||
// 删除。
|
||||
req4 := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+ruleID, nil)
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
if rec4.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec4.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
|
||||
func TestAutomationRuleBadTriggerType(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"bogus","actions":[{"action_type":"confirm_shipment"}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("不支持触发类型应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadCookie 账号不属于当前用户 400。
|
||||
func TestAutomationRuleBadCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"other-account","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无权账号应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadActionType 不支持的动作类型 400。
|
||||
func TestAutomationRuleBadActionType(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"bogus"}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("不支持动作类型应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleSendCardMissingCardID send_card 缺 card_id 400。
|
||||
func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":0}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("send_card 缺 card_id 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleSendTextMissingTemplate send_text 缺文案 400。
|
||||
func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":""}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("send_text 缺文案应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleNoActions 缺动作 400。
|
||||
func TestAutomationRuleNoActions(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺动作应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadJSON 非法 JSON 400。
|
||||
func TestAutomationRuleBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleUpdateBadID 无效 ID 400。
|
||||
func TestAutomationRuleUpdateBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/automation-rules/abc", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleDeleteBadID 无效 ID 400。
|
||||
func TestAutomationRuleDeleteBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/abc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleDeleteNotFound 不存在规则 404。
|
||||
func TestAutomationRuleDeleteNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/999999", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在规则应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultAutomationRuleName 默认规则名。
|
||||
func TestDefaultAutomationRuleName(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
automation.TriggerOrderPaid: "付款后自动发货",
|
||||
automation.TriggerBuyerReviewed: "评价后发送赠品",
|
||||
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
|
||||
"bogus": "自动化规则",
|
||||
}
|
||||
for trigger, want := range cases {
|
||||
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" {
|
||||
t.Errorf("带 itemID 的默认名异常: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsJSONObject isJSONObject 表驱动。
|
||||
func TestIsJSONObject(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
`{}`: true,
|
||||
`{"a":1}`: true,
|
||||
`null`: true, // null 能 unmarshal 为 map(nil),函数判定为对象
|
||||
`[]`: false,
|
||||
`"str"`: false,
|
||||
`invalid`: false,
|
||||
``: false,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := isJSONObject(in); got != want {
|
||||
t.Errorf("isJSONObject(%q)=%v want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstNonZero firstNonZero 表驱动。
|
||||
func TestFirstNonZero(t *testing.T) {
|
||||
if got := firstNonZero(0, 5); got != 5 {
|
||||
t.Fatalf("got %d", got)
|
||||
}
|
||||
if got := firstNonZero(3, 5); got != 3 {
|
||||
t.Fatalf("got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -28,8 +27,8 @@ type cardBatchResultRow struct {
|
||||
func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// 表格最大 5 MiB(卡密组定义都很小)。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 6<<20)
|
||||
if err := r.ParseMultipartForm(6 << 20); err != nil {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxCardBatchUploadBytes)
|
||||
if err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
|
||||
return
|
||||
}
|
||||
@@ -39,16 +38,20 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer source.Close()
|
||||
sourceBytes, err := io.ReadAll(io.LimitReader(source, 5<<20))
|
||||
sourceBytes, tooLarge, err := readLimitedBytes(source, 5<<20)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "读取卡密表格失败")
|
||||
return
|
||||
}
|
||||
if tooLarge {
|
||||
writeErr(w, http.StatusBadRequest, "卡密表格不能超过 5 MiB")
|
||||
return
|
||||
}
|
||||
sourceName := safeBaseName(sourceHeader.Filename)
|
||||
if sourceName == "" {
|
||||
sourceName = "cards.csv"
|
||||
}
|
||||
maps, err := parsePublishSheetBytes(sourceBytes, sourceName)
|
||||
maps, err := parsePublishSheetBytesWithLimit(sourceBytes, sourceName, maxCardBatchRows)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
|
||||
@@ -38,9 +38,8 @@ func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效卡券ID")
|
||||
return
|
||||
}
|
||||
cf, err := s.Store.Cards.Get(r.Context(), id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "卡券不存在")
|
||||
cf, ok := s.requireCardOwner(w, r, id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cf)
|
||||
@@ -73,7 +72,12 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
existing, ok := s.requireCardOwner(w, r, id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cf.ID = id
|
||||
cf.UserID = existing.UserID
|
||||
if err := s.Store.Cards.Update(r.Context(), cf); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
@@ -87,6 +91,9 @@ func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效卡券ID")
|
||||
return
|
||||
}
|
||||
if _, ok := s.requireCardOwner(w, r, id); !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Cards.Delete(r.Context(), id); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -170,6 +171,10 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if err := s.Store.Cookies.Save(r.Context(), req.ID, req.Value, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -177,7 +182,9 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
s.refreshAccountProfile(r.Context(), d)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
|
||||
_ = s.Manager.Restart(r.Context(), req.ID)
|
||||
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": req.ID})
|
||||
}
|
||||
@@ -185,6 +192,9 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
// updateCookie 更新 cookie 值。
|
||||
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
@@ -194,6 +204,10 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if err := s.Store.Cookies.Save(r.Context(), cid, req.Value, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -201,7 +215,9 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
s.refreshAccountProfile(r.Context(), d)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
|
||||
_ = s.Manager.Restart(r.Context(), cid)
|
||||
if err := s.Manager.Restart(r.Context(), cid); err != nil {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
@@ -209,6 +225,9 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
|
||||
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
@@ -240,6 +259,9 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
// setCookieStatus 启用/禁用账号。
|
||||
func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
@@ -252,14 +274,17 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// 启停引擎实例。
|
||||
if req.Enabled {
|
||||
// 重启拉取最新 cookie。
|
||||
if d, e := s.Store.Cookies.GetDetails(r.Context(), cid); e == nil {
|
||||
_ = s.Manager.Restart(r.Context(), cid)
|
||||
_ = d
|
||||
if s.Manager != nil {
|
||||
if req.Enabled {
|
||||
// 重启拉取最新 cookie。
|
||||
if _, e := s.Store.Cookies.GetDetails(r.Context(), cid); e == nil {
|
||||
if err := s.Manager.Restart(r.Context(), cid); err != nil {
|
||||
s.Logger.Error("启用后重启账号失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
s.Manager.Stop(cid)
|
||||
}
|
||||
} else {
|
||||
s.Manager.Stop(cid)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
@@ -267,7 +292,12 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
|
||||
// deleteCookie 删除账号。
|
||||
func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
s.Manager.Stop(cid)
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
if s.Manager != nil {
|
||||
s.Manager.Stop(cid)
|
||||
}
|
||||
if err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
@@ -278,6 +308,9 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
|
||||
// setCookieAutoConfirm 设置自动确认发货。
|
||||
func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
AutoConfirm bool `json:"auto_confirm"`
|
||||
}
|
||||
@@ -300,9 +333,8 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
// getCookieAutoConfirm 获取自动确认发货设置。
|
||||
func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
d, err := s.Store.Cookies.GetDetails(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
d, ok := s.requireCookieOwner(w, r, cid)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"auto_confirm": d.AutoConfirm})
|
||||
@@ -311,6 +343,9 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
// setCookieRemark 设置备注。
|
||||
func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
@@ -329,6 +364,9 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
|
||||
// setCookiePauseDuration 设置暂停时长。
|
||||
func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
PauseDuration int `json:"pause_duration"`
|
||||
}
|
||||
@@ -351,6 +389,9 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
|
||||
// getCookiePauseDuration 获取暂停时长。
|
||||
func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"pause_duration": s.Store.Cookies.GetPauseDuration(r.Context(), cid)})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestListCookies 列表 cookie_id。
|
||||
func TestListCookies(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookies", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var ids []string
|
||||
json.Unmarshal(rec.Body.Bytes(), &ids)
|
||||
if len(ids) != 1 || ids[0] != "acc1" {
|
||||
t.Fatalf("cookies 列表异常: %+v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshCookieProfile 主动刷新账号资料。
|
||||
func TestRefreshCookieProfile(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/cookies/acc1/refresh-profile", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true {
|
||||
t.Fatalf("刷新资料应成功: %+v", res)
|
||||
}
|
||||
if res["nickname"] != "测试账号" {
|
||||
t.Fatalf("昵称异常: %v", res["nickname"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshCookieProfileBadCookie 无权账号 403。
|
||||
func TestRefreshCookieProfileBadCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/cookies/other/refresh-profile", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("无权账号应 403,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCookieDetails 单账号详情。
|
||||
func TestGetCookieDetails(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookie/acc1/details", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var d map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &d)
|
||||
if d["id"] != "acc1" || d["has_cookie"] != true {
|
||||
t.Fatalf("详情异常: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCookieDetailsBadCookie 无权账号 403。
|
||||
func TestGetCookieDetailsBadCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookie/other/details", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("无权账号应 403,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookie 更新 cookie 值。
|
||||
func TestUpdateCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"value":"unb=123; _m_h5_tk=newtoken_2;"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieBadJSON 非法 JSON 400。
|
||||
func TestUpdateCookieBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieLoginInfo 更新登录信息。
|
||||
func TestUpdateCookieLoginInfo(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"username":"u1","password":"p1","show_browser":true}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieLoginInfoBadJSON 非法 JSON 400。
|
||||
func TestUpdateCookieLoginInfoBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetCookieStatus 启停账号。
|
||||
func TestSetCookieStatus(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
// 先设置账号为停用,便于测试启用路径。
|
||||
store.Cookies.SetStatus(ctx, "acc1", false)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 启用。
|
||||
body := `{"enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/status", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("enable status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !store.Cookies.GetStatus(ctx, "acc1") {
|
||||
t.Fatal("应已启用")
|
||||
}
|
||||
|
||||
// 停用。
|
||||
body2 := `{"enabled":false}`
|
||||
req2 := httptest.NewRequest(http.MethodPut, "/cookies/acc1/status", strings.NewReader(body2))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("disable status=%d", rec2.Code)
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, "acc1") {
|
||||
t.Fatal("应已停用")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetCookieStatusBadJSON 非法 JSON 400。
|
||||
func TestSetCookieStatusBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/status", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetCookieAutoConfirmBadJSON 非法 JSON 400。
|
||||
func TestSetCookieAutoConfirmBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/auto-confirm", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetCookieRemarkBadJSON 非法 JSON 400。
|
||||
func TestSetCookieRemarkBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/remark", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteCookie 删除账号。
|
||||
func TestDeleteCookie(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.Cookies.Save(ctx, "acc-del", "unb=1; _m_h5_tk=t_1;", 1)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/cookies/acc-del", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddCookieBad 缺 id 或 value 400。
|
||||
func TestAddCookieBad(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"id":"acc2"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 value 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddCookieBadJSON 非法 JSON 400。
|
||||
func TestAddCookieBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCookieAutoConfirmNotFound 不存在账号 404。
|
||||
func TestGetCookieAutoConfirmNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookies/no-such/auto-confirm", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在账号应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedAccountNickname 备注优先于昵称。
|
||||
func TestCachedAccountNickname(t *testing.T) {
|
||||
cases := []struct {
|
||||
remark, nickname, id, want string
|
||||
}{
|
||||
{"我的备注", "昵称", "acc1", "我的备注"},
|
||||
{"", "昵称", "acc1", "昵称"},
|
||||
{"", "", "acc1234567890", "账号 acc123"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := cachedAccountNickname(&db.CookieDetail{ID: c.id, Nickname: c.nickname, Remark: c.remark})
|
||||
if got != c.want {
|
||||
t.Errorf("cachedAccountNickname(remark=%q,nick=%q,id=%q)=%q want %q", c.remark, c.nickname, c.id, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeProfileAvatarURL 头像 URL 归一。
|
||||
func TestNormalizeProfileAvatarURL(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"": "",
|
||||
"//img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
|
||||
"http://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
|
||||
"https://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
|
||||
" https://img.alicdn.com/x.jpg ": "https://img.alicdn.com/x.jpg",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := normalizeProfileAvatarURL(in); got != want {
|
||||
t.Errorf("normalizeProfileAvatarURL(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTruncate truncate 不超长则原样返回。
|
||||
func TestTruncate(t *testing.T) {
|
||||
if got := truncate("abc", 5); got != "abc" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if got := truncate("abcdef", 3); got != "abc" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestListDefaultReplies 列表(数组形式)。
|
||||
func TestListDefaultReplies(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 设置。
|
||||
body := `{"enabled":true,"reply_content":"你好","reply_once":false}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("set status=%d", rec.Code)
|
||||
}
|
||||
|
||||
// 列表(数组)。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/default-replies", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("list status=%d", rec2.Code)
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 || arr[0]["reply_content"] != "你好" {
|
||||
t.Fatalf("列表异常: %+v", arr)
|
||||
}
|
||||
|
||||
// 列表(map 形式,兼容路径)。
|
||||
req3 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil)
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("map status=%d", rec3.Code)
|
||||
}
|
||||
var m map[string]map[string]any
|
||||
json.Unmarshal(rec3.Body.Bytes(), &m)
|
||||
if m["acc1"]["reply_content"] != "你好" {
|
||||
t.Fatalf("map 列表异常: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDefaultReplyBadJSON 非法 JSON 400。
|
||||
func TestSetDefaultReplyBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetDefaultReplyNotFound 不存在返回默认。
|
||||
func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/default-replies/no-such", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if got["enabled"] != false || got["reply_content"] != "" {
|
||||
t.Fatalf("默认值异常: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteDefaultReply 删除。
|
||||
func TestDeleteDefaultReply(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 设置。
|
||||
body := `{"enabled":true,"reply_content":"你好"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
// 删除。
|
||||
req2 := httptest.NewRequest(http.MethodDelete, "/default-replies/acc1", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBtoi btoi 表驱动。
|
||||
func TestBtoi(t *testing.T) {
|
||||
if btoi(true) != 1 {
|
||||
t.Fatal("btoi(true) should be 1")
|
||||
}
|
||||
if btoi(false) != 0 {
|
||||
t.Fatal("btoi(false) should be 0")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNullIfEmpty nullIfEmpty 表驱动。
|
||||
func TestNullIfEmpty(t *testing.T) {
|
||||
if v := nullIfEmpty(""); v != nil {
|
||||
t.Fatalf("空串应为 nil,got %v", v)
|
||||
}
|
||||
if v := nullIfEmpty("x"); v != "x" {
|
||||
t.Fatalf("非空应原样返回,got %v", v)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
@@ -39,6 +41,20 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
|
||||
|
||||
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "reply_content": "", "reply_once": false})
|
||||
@@ -52,6 +68,9 @@ func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReplyContent string `json:"reply_content"`
|
||||
@@ -80,8 +99,12 @@ func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT cookie_id, enabled, reply_content, reply_once, reply_image_url FROM default_replies`)
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content,''), dr.reply_once, COALESCE(dr.reply_image_url,'')
|
||||
FROM default_replies dr
|
||||
JOIN cookies c ON c.id=dr.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -99,12 +122,20 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
"reply_once": replyOnce != 0, "reply_image_url": imageURL,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT cookie_id, enabled, COALESCE(reply_content, ''), reply_once, COALESCE(reply_image_url, '') FROM default_replies`)
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content, ''), dr.reply_once, COALESCE(dr.reply_image_url, '')
|
||||
FROM default_replies dr
|
||||
JOIN cookies c ON c.id=dr.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -125,11 +156,18 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
"reply_image_url": imageURL,
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_replies WHERE cookie_id=?`, cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
@@ -140,6 +178,9 @@ func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_reply_records WHERE cookie_id=?`, cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "清空失败")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestOrderDetailNotFound 查询不存在的订单应 404。
|
||||
func TestOrderDetailNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/orders/no-such-order", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在订单应 404,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCardEndpointsErrorBranches 卡券相关错误分支:
|
||||
// 无效 ID → 400;不存在 → 404;请求体非法 → 400。
|
||||
func TestCardEndpointsErrorBranches(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 无效 card_id(非数字)→ 400。
|
||||
req := httptest.NewRequest(http.MethodGet, "/cards/abc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
|
||||
// 合法但不存在的 ID → 404。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/cards/999999", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在卡券应 404,got %d", rec2.Code)
|
||||
}
|
||||
|
||||
// 创建卡券请求体非法 → 400。
|
||||
req3 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader("not-json"))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法请求体应 400,got %d", rec3.Code)
|
||||
}
|
||||
|
||||
// 创建卡券缺类型 → 400(decodeCard 校验)。
|
||||
req4 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"无类型卡"}`))
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
if rec4.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺类型应 400,got %d body=%s", rec4.Code, rec4.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestProtectedEndpointsRequireAuth 受保护端点未登录应 401。
|
||||
func TestProtectedEndpointsRequireAuth(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
|
||||
for _, path := range []string{
|
||||
"/cards",
|
||||
"/api/orders",
|
||||
"/cookies/details",
|
||||
"/keywords/acc1",
|
||||
"/default-replies/acc1",
|
||||
"/admin/stats",
|
||||
"/ai-reply-settings",
|
||||
} {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s 未登录应 401,got %d", path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminEndpointRejectsNonAdmin 非 admin 用户访问管理端点应 403。
|
||||
func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
|
||||
// 创建普通用户并登录。
|
||||
srv.Store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
|
||||
body := `{"username":"user2","password":"pw"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("普通用户登录 status=%d", rec.Code)
|
||||
}
|
||||
cookie := rec.Result().Cookies()[0]
|
||||
|
||||
// 访问 admin 端点 → 403。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusForbidden {
|
||||
t.Fatalf("普通用户访问 admin 应 403,got %d", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrderImportEmptyBody 空导入内容应 400。
|
||||
func TestOrderImportEmptyBody(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(""))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("空导入应 400,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginMalformedJSON 登录请求体非法 JSON 应不致命(400 或失败响应)。
|
||||
func TestLoginMalformedJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader("not-json"))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法登录请求应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestAddKeywordWithItemID 带商品ID的关键词添加 + 缺 keyword 400。
|
||||
func TestAddKeywordWithItemID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 正常添加。
|
||||
body := `{"keyword":"价格","reply":"50元","item_id":"item1"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("add status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 缺 keyword → 400。
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"reply":"x"}`))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 keyword 应 400,got %d", rec2.Code)
|
||||
}
|
||||
|
||||
// 非法 JSON → 400。
|
||||
req3 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader("not-json"))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec3.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchCreateCards CSV 批量建卡密组。
|
||||
func TestBatchCreateCards(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
csv := "name,type,content\n卡A,text,内容A\n卡B,text,内容B\n"
|
||||
body := &bytes.Buffer{}
|
||||
mw := multipart.NewWriter(body)
|
||||
fw, _ := mw.CreateFormFile("file", "cards.csv")
|
||||
fw.Write([]byte(csv))
|
||||
mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/cards/batch", body)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("batch status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["created"].(float64) != 2 {
|
||||
t.Fatalf("应创建 2 个,got %+v", res)
|
||||
}
|
||||
|
||||
// 缺文件 → 400。
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/cards/batch", &bytes.Buffer{})
|
||||
req2.Header.Set("Content-Type", "multipart/form-data; boundary=x")
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺文件应 400,got %d", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppendCardData 追加批量卡密号 + 校验分支。
|
||||
func TestAppendCardData(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 追加。
|
||||
body := `{"content":"K3\nK4"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("append status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 空 content → 400。
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(`{"content":""}`))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != http.StatusBadRequest {
|
||||
t.Fatalf("空 content 应 400,got %d", rec2.Code)
|
||||
}
|
||||
|
||||
// 无效 card_id → 400。
|
||||
req3 := httptest.NewRequest(http.MethodPost, "/cards/abc/append-data", strings.NewReader(`{"content":"x"}`))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec3.Code)
|
||||
}
|
||||
|
||||
// 非 data 类型卡密组追加 → 400。建一个 text 类型。
|
||||
textID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "文本卡", Type: "text", TextContent: "T", Enabled: true, UserID: admin.ID})
|
||||
req4 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(textID)+"/append-data", strings.NewReader(`{"content":"x"}`))
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
if rec4.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非 data 类型应 400,got %d", rec4.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseXLSXPublishSheet 解析 XLSX 表格(复用 buildMinimalXLSX 构造)。
|
||||
func TestParseXLSXPublishSheet(t *testing.T) {
|
||||
xlsx := buildMinimalXLSXForPublish(t, [][]string{{"title", "price"}, {"商品A", "9.9"}})
|
||||
rows, err := parseXLSXPublishSheet(xlsx)
|
||||
if err != nil {
|
||||
t.Fatalf("parseXLSX: %v", err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0]["title"] != "商品A" {
|
||||
t.Fatalf("rows = %#v", rows)
|
||||
}
|
||||
|
||||
// 非 xlsx 字节 → 报错。
|
||||
if _, err := parseXLSXPublishSheet([]byte("not-xlsx")); err == nil {
|
||||
t.Fatal("非 xlsx 应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicHTTPClient 公网 HTTP 客户端拒绝非公网地址 + 重定向协议校验。
|
||||
func TestPublicHTTPClient(t *testing.T) {
|
||||
cli := publicHTTPClient()
|
||||
if cli == nil {
|
||||
t.Fatal("应返回非 nil client")
|
||||
}
|
||||
// 访问私有 IP 应被拒绝。
|
||||
_, err := cli.Get("http://127.0.0.1:1/")
|
||||
if err == nil {
|
||||
t.Fatal("私有 IP 应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishBatchToMap 批次转 map 序列化 + 状态计数。
|
||||
func TestPublishBatchToMap(t *testing.T) {
|
||||
batch := &db.ItemPublishBatch{ID: "b1", Status: "running", Filename: "x.csv"}
|
||||
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 := publishBatchToMap(batch, rows)
|
||||
if m["id"] != "b1" || m["status"] != "running" {
|
||||
t.Fatalf("batch 字段异常: %+v", m)
|
||||
}
|
||||
rs, _ := m["rows"].([]map[string]any)
|
||||
if len(rs) != 2 {
|
||||
t.Fatalf("rows 数异常: %d", len(rs))
|
||||
}
|
||||
}
|
||||
|
||||
// buildMinimalXLSXForPublish 构造最小 xlsx 供 parseXLSXPublishSheet 测试。
|
||||
// 复用 parser_test.go 的 buildMinimalXLSX 但独立命名避免冲突。
|
||||
func buildMinimalXLSXForPublish(t *testing.T, grid [][]string) []byte {
|
||||
t.Helper()
|
||||
return buildMinimalXLSX(t, grid)
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -41,9 +40,9 @@ func (s *Server) mountItemsReal(r chi.Router) {
|
||||
|
||||
func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
// 最多 9 张 10 MiB 图片,额外预留 multipart 元数据空间。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 96<<20)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 96 MiB。
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxItemPublishBytes)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制。
|
||||
if err := r.ParseMultipartForm(maxOrderImportBytes); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误,请使用 multipart/form-data")
|
||||
return
|
||||
}
|
||||
@@ -81,10 +80,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
defer cancel()
|
||||
client := s.MTop
|
||||
if client == nil {
|
||||
client = &mtop.Client{}
|
||||
}
|
||||
client := s.mtopClient()
|
||||
res, err := client.PublishItem(ctx, cookieValue, mtop.PublishItemRequest{
|
||||
Title: title,
|
||||
Description: description,
|
||||
@@ -116,7 +112,9 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(r.Context(), cookieID, res.UpdatedCookies, userID)
|
||||
if err := s.Store.Cookies.Save(r.Context(), cookieID, res.UpdatedCookies, userID); err != nil {
|
||||
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if res.ItemID != "" {
|
||||
detail := map[string]any{
|
||||
@@ -174,11 +172,14 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取图片失败: %w", err)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(f, 10<<20))
|
||||
data, tooLarge, err := readLimitedBytes(f, 10<<20)
|
||||
_ = f.Close()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取图片失败: %w", err)
|
||||
}
|
||||
if tooLarge {
|
||||
return nil, errors.New("单张图片不能超过 10 MiB")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("图片文件为空")
|
||||
}
|
||||
@@ -262,14 +263,16 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
defer cancel()
|
||||
client := &mtop.Client{}
|
||||
client := s.mtopClient()
|
||||
res, err := client.FetchAllItems(ctx, cookieValue, req.PageSize, req.MaxPages)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID)
|
||||
if err := s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
|
||||
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -297,14 +300,16 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
||||
defer cancel()
|
||||
client := &mtop.Client{}
|
||||
client := s.mtopClient()
|
||||
res, err := client.FetchItemsPage(ctx, cookieValue, req.PageNumber, req.PageSize)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID)
|
||||
if err := s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
|
||||
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -363,6 +368,9 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
|
||||
|
||||
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
items, err := s.Store.Items.AllForCookie(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
@@ -377,6 +385,9 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
it, err := s.Store.Items.Get(r.Context(), cid, itemID)
|
||||
if err != nil {
|
||||
@@ -393,6 +404,9 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ItemID string `json:"item_id"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
@@ -424,6 +438,9 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
ItemTitle string `json:"item_title"`
|
||||
@@ -452,6 +469,9 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
if err := s.Store.Items.Delete(r.Context(), cid, itemID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
@@ -462,6 +482,9 @@ func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
@@ -479,6 +502,9 @@ func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// buildPublishMultipart 构造一个 multipart/form-data 请求体,包含一个 1x1 PNG 图片字段。
|
||||
func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffer, string) {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
// 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}
|
||||
w, err := mw.CreatePart(textproto.MIMEHeader{
|
||||
"Content-Disposition": []string{`form-data; name="images"; filename="test.png"`},
|
||||
"Content-Type": []string{"image/png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.Write(png)
|
||||
for k, v := range fields {
|
||||
_ = mw.WriteField(k, v)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &buf, mw.FormDataContentType()
|
||||
}
|
||||
|
||||
// TestPublishItemMissingCookieID 缺 cookie_id 应 400。
|
||||
func TestPublishItemMissingCookieID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"title": "测试商品", "price": "12.50", "quantity": "5",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 cookie_id 应 400,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemBadPrice 价格非法 400。
|
||||
func TestPublishItemBadPrice(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"cookie_id": "acc1", "title": "测试商品", "price": "0", "quantity": "5",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("价格非法应 400,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemBadQuantity 库存非法 400。
|
||||
func TestPublishItemBadQuantity(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "0",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("库存非法应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemBadCookie 无权操作账号 403。
|
||||
func TestPublishItemBadCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"cookie_id": "other-account", "title": "测试商品", "price": "12.50", "quantity": "5",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("无权账号应 403,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemBadMultipart 非 multipart 请求 400。
|
||||
func TestPublishItemBadMultipart(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", strings.NewReader("plain text"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非 multipart 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemNoImages 缺图片 400。
|
||||
func TestPublishItemNoImages(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("cookie_id", "acc1")
|
||||
_ = mw.WriteField("title", "测试商品")
|
||||
_ = mw.WriteField("price", "12.50")
|
||||
_ = mw.WriteField("quantity", "5")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺图片应 400,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemSuccess mtop PublishItem 成功路径。
|
||||
// 由于 PublishItem 内部串行调用上传图片/类目/定位/发布多个端点,mock 按 URL 分发。
|
||||
func TestPublishItemSuccess(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 替换为按 URL 分发的 mock。
|
||||
prev := srv.MTop
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
u := req.URL.String()
|
||||
var respBody string
|
||||
switch {
|
||||
case strings.Contains(u, "stream-upload.goofish.com"):
|
||||
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"pub-item-1","url":"https://www.goofish.com/item?id=pub-item-1","picUrl":"https://img.alicdn.com/published.png","categoryId":"99","categoryName":"数码","title":"测试商品","priceText":"12.50","quantity":"5"}}`
|
||||
default:
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(respBody)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "5",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("publish status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true || res["item_id"] != "pub-item-1" {
|
||||
t.Fatalf("发布成功响应异常: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemStockPermissionMissing 库存权限缺失应 403。
|
||||
func TestPublishItemStockPermissionMissing(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
prev := srv.MTop
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
u := req.URL.String()
|
||||
var respBody string
|
||||
switch {
|
||||
case strings.Contains(u, "stream-upload.goofish.com"):
|
||||
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
// 触发 stock_permission_missing 分类。
|
||||
respBody = `{"ret":["FAIL_BIZ_STOCK_PERMISSION_MISSING::库存权限缺失"]}`
|
||||
default:
|
||||
respBody = `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(respBody)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body, ct := buildPublishMultipart(t, map[string]string{
|
||||
"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "5",
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", ct)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("库存权限缺失应 403,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["code"] != "stock_permission_missing" {
|
||||
t.Fatalf("code 异常: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsFromAccountSuccess mtop FetchAllItems 成功,保存商品。
|
||||
func TestSyncItemsFromAccountSuccess(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
prev := srv.MTop
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
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{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","page_size":10}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("sync status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["saved_count"] != float64(1) {
|
||||
t.Fatalf("应保存1件商品: %+v", res)
|
||||
}
|
||||
// 验证 DB 已写入。
|
||||
items, _ := store.Items.AllForCookie(context.Background(), "acc1")
|
||||
found := false
|
||||
for _, it := range items {
|
||||
if it.ItemID == "it-sync-1" && it.ItemTitle == "同步商品A" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("商品未保存: %+v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
|
||||
func TestSyncItemsFromAccountFail(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
prev := srv.MTop
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
body := `{"ret":["FAIL_SYS_USER_VALIDATE::用户校验失败"]}`
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("mtop 失败应 502,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsFromAccountBadCookie 无权账号 403。
|
||||
func TestSyncItemsFromAccountBadCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"other-account"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("无权账号应 403,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsFromAccountMissingCookieID 缺 cookie_id 400。
|
||||
func TestSyncItemsFromAccountMissingCookieID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 cookie_id 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsPageFromAccountSuccess mtop FetchItemsPage 成功。
|
||||
func TestSyncItemsPageFromAccountSuccess(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
prev := srv.MTop
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
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{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"cookie_id":"acc1","page_number":1,"page_size":10}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-by-page", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["saved_count"] != float64(1) {
|
||||
t.Fatalf("应保存1件: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncItemsPageFromAccountFail mtop 失败 502。
|
||||
func TestSyncItemsPageFromAccountFail(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
prev := srv.MTop
|
||||
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_SYS_USER_VALIDATE::失败"}})
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
body := `{"cookie_id":"acc1"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/get-by-page", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("mtop 失败应 502,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemCRUD 商品增删改查 + 多规格。
|
||||
func TestItemCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-crud','商品C')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 按账号列表。
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/cookie/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
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())
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 || arr[0]["item_id"] != "it-crud" {
|
||||
t.Fatalf("列表异常: %+v", arr)
|
||||
}
|
||||
|
||||
// 单品详情。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/items/acc1/it-crud", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("get status=%d", rec2.Code)
|
||||
}
|
||||
|
||||
// 更新。
|
||||
updBody := `{"item_title":"改名商品","item_price":"88.00"}`
|
||||
req3 := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(updBody))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
|
||||
// 多规格 + 多件发货。
|
||||
multiBody := `{"multi_quantity_delivery":true}`
|
||||
req4 := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud/multi-quantity-delivery", strings.NewReader(multiBody))
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
if rec4.Code != 200 {
|
||||
t.Fatalf("multi-qty status=%d", rec4.Code)
|
||||
}
|
||||
|
||||
// 删除。
|
||||
req5 := httptest.NewRequest(http.MethodDelete, "/items/acc1/it-crud", nil)
|
||||
req5.AddCookie(cookie)
|
||||
rec5 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec5, req5)
|
||||
if rec5.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec5.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemGetNotFound 不存在商品 404。
|
||||
func TestItemGetNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/acc1/no-such", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在商品应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateItem 新建商品。
|
||||
func TestCreateItem(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateItemMissingID 缺商品 ID 400。
|
||||
func TestCreateItemMissingID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"item_title":"无ID商品"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateItemBadJSON 非法 JSON 400。
|
||||
func TestUpdateItemBadJSON(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id) VALUES ('acc1','it-bad')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/items/acc1/it-bad", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetItemMultiSpecBadJSON 非法 JSON 400。
|
||||
func TestSetItemMultiSpecBadJSON(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id) VALUES ('acc1','it-spec')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/items/acc1/it-spec/multi-spec", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -88,9 +81,9 @@ type publishReviewRequestCfg struct {
|
||||
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// 表格最大 20 MiB,图片压缩包最大 200 MiB,额外预留 multipart 元数据空间。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 224<<20)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 224 MiB。
|
||||
if err := r.ParseMultipartForm(256 << 20); err != nil {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxItemPublishBatchBytes)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制。
|
||||
if err := r.ParseMultipartForm(maxItemPublishBatchParseBytes); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
|
||||
return
|
||||
}
|
||||
@@ -105,11 +98,15 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
defer source.Close()
|
||||
sourceBytes, err := io.ReadAll(io.LimitReader(source, 20<<20))
|
||||
sourceBytes, tooLarge, err := readLimitedBytes(source, 20<<20)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "读取商品表格失败")
|
||||
return
|
||||
}
|
||||
if tooLarge {
|
||||
writeErr(w, http.StatusBadRequest, "商品表格不能超过 20 MiB")
|
||||
return
|
||||
}
|
||||
batchID := "batch_" + randomHex(12)
|
||||
uploadDir := filepath.Join(s.publishUploadRoot(), "publish_batches", batchID)
|
||||
if err := os.MkdirAll(uploadDir, 0o750); err != nil {
|
||||
@@ -127,11 +124,15 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
if zipFile, zipHeader, err := r.FormFile("images_zip"); err == nil {
|
||||
defer zipFile.Close()
|
||||
zipBytes, err := io.ReadAll(io.LimitReader(zipFile, 200<<20))
|
||||
zipBytes, tooLarge, err := readLimitedBytes(zipFile, 200<<20)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "读取图片 zip 失败")
|
||||
return
|
||||
}
|
||||
if tooLarge {
|
||||
writeErr(w, http.StatusBadRequest, "图片 zip 不能超过 200 MiB")
|
||||
return
|
||||
}
|
||||
zipName := safeBaseName(zipHeader.Filename)
|
||||
if zipName == "" {
|
||||
zipName = "images.zip"
|
||||
@@ -146,7 +147,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
maps, err := parsePublishSheetBytes(sourceBytes, sourceName)
|
||||
maps, err := parsePublishSheetBytesWithLimit(sourceBytes, sourceName, maxPublishBatchRows)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
@@ -371,10 +372,7 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID
|
||||
}
|
||||
return
|
||||
}
|
||||
client := s.MTop
|
||||
if client == nil {
|
||||
client = &mtop.Client{}
|
||||
}
|
||||
client := s.mtopClient()
|
||||
for idx, row := range rows {
|
||||
status, err := s.Store.PublishBatches.BatchStatus(ctx, batchID)
|
||||
if err != nil || status == "canceled" {
|
||||
@@ -408,7 +406,7 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop.Client, row db.ItemPublishBatchRow) error {
|
||||
func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.Client, row db.ItemPublishBatchRow) error {
|
||||
batch, err := s.Store.PublishBatches.Get(ctx, userID, row.BatchID)
|
||||
if err != nil {
|
||||
return errors.New("批量任务不存在")
|
||||
@@ -447,7 +445,9 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop
|
||||
return err
|
||||
}
|
||||
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(ctx, row.CookieID, res.UpdatedCookies, userID)
|
||||
if err := s.Store.Cookies.Save(ctx, row.CookieID, res.UpdatedCookies, userID); err != nil {
|
||||
s.Logger.Error("发布商品后保存刷新 cookie 失败", "cookie_id", row.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if res.ItemID != "" {
|
||||
detail := map[string]any{
|
||||
@@ -458,7 +458,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop
|
||||
"publish_raw": res.RawData,
|
||||
}
|
||||
detailJSON, _ := json.Marshal(detail)
|
||||
_ = s.Store.Items.Upsert(ctx, &db.ItemInfoRow{
|
||||
if err := s.Store.Items.Upsert(ctx, &db.ItemInfoRow{
|
||||
CookieID: row.CookieID,
|
||||
ItemID: res.ItemID,
|
||||
ItemTitle: firstNonEmpty(res.Title, row.Title),
|
||||
@@ -467,8 +467,12 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop
|
||||
ItemPrice: res.PriceText,
|
||||
ItemDetail: string(detailJSON),
|
||||
MultiQuantityDelivery: row.Quantity > 1,
|
||||
})
|
||||
_ = s.createPublishAutomationRules(ctx, userID, row, res)
|
||||
}); err != nil {
|
||||
s.Logger.Error("发布商品后保存商品信息失败", "cookie_id", row.CookieID, "item_id", res.ItemID, "err", err)
|
||||
}
|
||||
if err := s.createPublishAutomationRules(ctx, userID, row, res); err != nil {
|
||||
s.Logger.Error("发布商品后创建自动化规则失败", "cookie_id", row.CookieID, "item_id", res.ItemID, "err", err)
|
||||
}
|
||||
}
|
||||
rawJSON, _ := json.Marshal(res.RawData)
|
||||
return s.Store.PublishBatches.MarkRowSuccess(ctx, row.ID, res.ItemID, res.ItemURL, string(rawJSON))
|
||||
@@ -705,372 +709,6 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf
|
||||
return errs
|
||||
}
|
||||
|
||||
func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(filename)) {
|
||||
case ".xlsx":
|
||||
return parseXLSXPublishSheet(raw)
|
||||
case ".csv":
|
||||
return parseDelimitedPublishSheet(raw, ',')
|
||||
case ".tsv":
|
||||
return parseDelimitedPublishSheet(raw, '\t')
|
||||
case ".xls":
|
||||
return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入")
|
||||
default:
|
||||
return parseDelimitedPublishSheet(raw, ',')
|
||||
}
|
||||
}
|
||||
|
||||
func parseDelimitedPublishSheet(raw []byte, comma rune) ([]map[string]any, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(raw))
|
||||
reader.Comma = comma
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.LazyQuotes = true
|
||||
records, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
if len(records) < 2 {
|
||||
return nil, fmt.Errorf("表格至少需要表头和一行数据")
|
||||
}
|
||||
return rowsToPublishMaps(records[0], records[1:]), nil
|
||||
}
|
||||
|
||||
func parseXLSXPublishSheet(raw []byte) ([]map[string]any, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
|
||||
}
|
||||
shared := xlsxSharedStrings(zr)
|
||||
var sheet *zip.File
|
||||
for _, f := range zr.File {
|
||||
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
|
||||
sheet = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if sheet == nil {
|
||||
return nil, fmt.Errorf("xlsx 中未找到工作表")
|
||||
}
|
||||
rc, err := sheet.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
var ws xlsxWorksheet
|
||||
if err := xml.NewDecoder(rc).Decode(&ws); err != nil {
|
||||
return nil, fmt.Errorf("解析工作表失败: %w", err)
|
||||
}
|
||||
rows := make([][]string, 0, len(ws.SheetData.Rows))
|
||||
for _, row := range ws.SheetData.Rows {
|
||||
values := []string{}
|
||||
for _, cell := range row.Cells {
|
||||
idx := xlsxCellIndex(cell.Ref)
|
||||
for len(values) <= idx {
|
||||
values = append(values, "")
|
||||
}
|
||||
values[idx] = xlsxCellValue(cell, shared)
|
||||
}
|
||||
rows = append(rows, values)
|
||||
}
|
||||
if len(rows) < 2 {
|
||||
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
|
||||
}
|
||||
return rowsToPublishMaps(rows[0], rows[1:]), nil
|
||||
}
|
||||
|
||||
func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
|
||||
keys := make([]string, len(headers))
|
||||
for i, h := range headers {
|
||||
keys[i] = normalizePublishHeader(h)
|
||||
}
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
m := map[string]any{}
|
||||
nonEmpty := false
|
||||
for i, key := range keys {
|
||||
if key == "" || i >= len(row) {
|
||||
continue
|
||||
}
|
||||
value := strings.TrimSpace(row[i])
|
||||
if value != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
m[key] = value
|
||||
}
|
||||
if nonEmpty {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizePublishHeader(header string) string {
|
||||
h := strings.ToLower(strings.TrimSpace(header))
|
||||
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
|
||||
switch h {
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "title", "itemtitle", "标题", "商品标题", "商品名称":
|
||||
return "title"
|
||||
case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情":
|
||||
return "description"
|
||||
case "price", "itemprice", "价格", "商品价格":
|
||||
return "price"
|
||||
case "originalprice", "原价":
|
||||
return "original_price"
|
||||
case "quantity", "库存", "数量":
|
||||
return "quantity"
|
||||
case "postagemode", "邮费模式":
|
||||
return "postage_mode"
|
||||
case "postage", "邮费":
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
return "paid_delivery_contents"
|
||||
case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品":
|
||||
return "review_gift_enabled"
|
||||
case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密":
|
||||
return "review_gift_contents"
|
||||
case "reviewrequestenabled", "求评价启用", "超时未评价时提醒":
|
||||
return "review_request_enabled"
|
||||
case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒":
|
||||
return "review_request_after_hours"
|
||||
case "reviewrequestmessage", "求评价文案", "提醒内容":
|
||||
return "review_request_message"
|
||||
case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次":
|
||||
return "review_request_max_attempts"
|
||||
case "reviewrequestdelayseconds", "求评价延迟秒":
|
||||
return "review_request_delay_seconds"
|
||||
default:
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
}
|
||||
|
||||
func extractPublishImagesZip(raw []byte, dest string) error {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析图片 zip 失败: %w", err)
|
||||
}
|
||||
for _, f := range zr.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
rel, err := safeZipPath(f.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := os.OpenRoot(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
|
||||
_ = root.Close()
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(rc, 10<<20))
|
||||
_ = rc.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(http.DetectContentType(data), "image/") {
|
||||
continue
|
||||
}
|
||||
file, err := root.OpenFile(rel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
_, err = file.Write(data)
|
||||
closeErr := file.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}
|
||||
_ = root.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) {
|
||||
var refs []string
|
||||
if err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil {
|
||||
return nil, fmt.Errorf("图片字段格式错误")
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
return nil, errors.New("至少上传 1 张商品图片")
|
||||
}
|
||||
images := make([]mtop.PublishImage, 0, len(refs))
|
||||
for _, ref := range refs {
|
||||
var data []byte
|
||||
var contentType string
|
||||
var filename string
|
||||
var err error
|
||||
if isHTTPURL(ref) {
|
||||
data, contentType, err = downloadImageURL(ctx, ref)
|
||||
filename = pathBaseFromURL(ref)
|
||||
} else {
|
||||
data, contentType, filename, err = readBatchImageFile(uploadDir, ref)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data})
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
|
||||
rel, err := safeZipPath(ref)
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
}
|
||||
root, err := os.OpenRoot(uploadDir)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("打开图片目录失败")
|
||||
}
|
||||
defer root.Close()
|
||||
file, err := root.Open(rel)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败: %s", ref)
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
|
||||
if err != nil || len(data) > 10<<20 {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", ref)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, "", "", fmt.Errorf("图片文件为空: %s", ref)
|
||||
}
|
||||
contentType := http.DetectContentType(data)
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return nil, "", "", fmt.Errorf("不是有效图片: %s", ref)
|
||||
}
|
||||
return data, contentType, filepath.Base(rel), nil
|
||||
}
|
||||
|
||||
// writeFileWithinRoot 将上传文件限制在指定根目录内,拒绝符号链接和路径逃逸。
|
||||
func writeFileWithinRoot(rootDir, name string, data []byte) error {
|
||||
root, err := os.OpenRoot(rootDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
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 {
|
||||
_ = file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
|
||||
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 := publicHTTPClient()
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, (10<<20)+1))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
|
||||
}
|
||||
if len(data) > 10<<20 {
|
||||
return nil, "", fmt.Errorf("远程图片不能超过 10 MiB: %s", rawURL)
|
||||
}
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if i := strings.Index(contentType, ";"); i >= 0 {
|
||||
contentType = contentType[:i]
|
||||
}
|
||||
if contentType == "" || contentType == "application/octet-stream" {
|
||||
contentType = http.DetectContentType(data)
|
||||
}
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return nil, "", fmt.Errorf("远程文件不是图片: %s", rawURL)
|
||||
}
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
// publicHTTPClient 只允许连接公网地址,防止批量铺货图片 URL 访问本机或内网服务。
|
||||
func publicHTTPClient() *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, resolved := range ips {
|
||||
if isPublicIP(resolved.IP) {
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("拒绝访问非公网地址")
|
||||
},
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 30 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
return fmt.Errorf("图片 URL 重定向次数过多")
|
||||
}
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("图片 URL 重定向协议不安全")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func isPublicIP(ip net.IP) bool {
|
||||
return ip != nil && !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() &&
|
||||
!ip.IsLinkLocalMulticast() && !ip.IsUnspecified() && !ip.IsMulticast()
|
||||
}
|
||||
|
||||
func validateBatchImageRef(uploadDir, ref string) error {
|
||||
if isHTTPURL(ref) {
|
||||
return nil
|
||||
}
|
||||
rel, err := safeZipPath(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(uploadDir, rel)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
return fmt.Errorf("图片文件不存在: %s", ref)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) map[string]any {
|
||||
outRows := make([]map[string]any, 0, len(rows))
|
||||
pending := 0
|
||||
@@ -1123,7 +761,7 @@ func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *Server) cardOwnedByUser(ctx context.Context, userID, cardID int64) bool {
|
||||
func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool {
|
||||
var exists int
|
||||
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
|
||||
return err == nil && exists != 0
|
||||
@@ -1140,49 +778,6 @@ func defaultPublishUploadRoot() string {
|
||||
return filepath.Join("data", "uploads")
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
func safeBaseName(name string) string {
|
||||
name = strings.TrimSpace(filepath.Base(name))
|
||||
name = strings.ReplaceAll(name, string(os.PathSeparator), "_")
|
||||
if name == "." || name == "/" {
|
||||
return ""
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func safeZipPath(raw string) (string, error) {
|
||||
raw = strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/"))
|
||||
if raw == "" || strings.HasPrefix(raw, "/") {
|
||||
return "", fmt.Errorf("图片路径不安全: %s", raw)
|
||||
}
|
||||
clean := filepath.Clean(raw)
|
||||
if clean == "." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) || clean == ".." {
|
||||
return "", fmt.Errorf("图片路径不安全: %s", raw)
|
||||
}
|
||||
return clean, nil
|
||||
}
|
||||
|
||||
func splitImageRefs(raw string) []string {
|
||||
raw = strings.ReplaceAll(raw, "\n", ";")
|
||||
raw = strings.ReplaceAll(raw, ";", ";")
|
||||
parts := strings.Split(raw, ";")
|
||||
out := []string{}
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parseLooseBool(raw string) bool {
|
||||
raw = strings.ToLower(strings.TrimSpace(raw))
|
||||
switch raw {
|
||||
@@ -1204,23 +799,6 @@ func atoiPublishDefault(raw string, def int) int {
|
||||
return def
|
||||
}
|
||||
|
||||
func isHTTPURL(ref string) bool {
|
||||
ref = strings.ToLower(strings.TrimSpace(ref))
|
||||
return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://")
|
||||
}
|
||||
|
||||
func pathBaseFromURL(rawURL string) string {
|
||||
base := filepath.Base(strings.Split(rawURL, "?")[0])
|
||||
if base == "." || base == "/" || base == "" {
|
||||
exts, _ := mime.ExtensionsByType(http.DetectContentType(nil))
|
||||
if len(exts) > 0 {
|
||||
return "image" + exts[0]
|
||||
}
|
||||
return "image.jpg"
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
package server
|
||||
|
||||
// item_publish_images.go: image zip extraction, image loading/validation, and safe path helpers for publish batches.
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func extractPublishImagesZip(raw []byte, dest string) error {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析图片 zip 失败: %w", err)
|
||||
}
|
||||
extractedFiles := 0
|
||||
extractedBytes := int64(0)
|
||||
for _, f := range zr.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
extractedFiles++
|
||||
if extractedFiles > maxItemPublishZipFiles {
|
||||
return fmt.Errorf("图片 zip 文件数不能超过 %d", maxItemPublishZipFiles)
|
||||
}
|
||||
rel, err := safeZipPath(f.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := os.OpenRoot(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
|
||||
_ = root.Close()
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
_ = root.Close()
|
||||
return err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(rc, (10<<20)+1))
|
||||
_ = rc.Close()
|
||||
if err != nil {
|
||||
_ = root.Close()
|
||||
return err
|
||||
}
|
||||
if len(data) > 10<<20 {
|
||||
_ = root.Close()
|
||||
return fmt.Errorf("图片文件不能超过 10 MiB: %s", f.Name)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
_ = root.Close()
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(http.DetectContentType(data), "image/") {
|
||||
_ = root.Close()
|
||||
continue
|
||||
}
|
||||
extractedBytes += int64(len(data))
|
||||
if extractedBytes > maxItemPublishZipExtractBytes {
|
||||
_ = root.Close()
|
||||
return fmt.Errorf("图片 zip 解压后总大小不能超过 %d MiB", maxItemPublishZipExtractBytes>>20)
|
||||
}
|
||||
file, err := root.OpenFile(rel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
_, err = file.Write(data)
|
||||
closeErr := file.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}
|
||||
_ = root.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) {
|
||||
var refs []string
|
||||
if err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil {
|
||||
return nil, fmt.Errorf("图片字段格式错误")
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
return nil, errors.New("至少上传 1 张商品图片")
|
||||
}
|
||||
images := make([]mtop.PublishImage, 0, len(refs))
|
||||
for _, ref := range refs {
|
||||
var data []byte
|
||||
var contentType string
|
||||
var filename string
|
||||
var err error
|
||||
if isHTTPURL(ref) {
|
||||
data, contentType, err = downloadImageURL(ctx, ref)
|
||||
filename = pathBaseFromURL(ref)
|
||||
} else {
|
||||
data, contentType, filename, err = readBatchImageFile(uploadDir, ref)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data})
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
|
||||
rel, err := safeZipPath(ref)
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
}
|
||||
root, err := os.OpenRoot(uploadDir)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("打开图片目录失败")
|
||||
}
|
||||
defer root.Close()
|
||||
file, err := root.Open(rel)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败: %s", ref)
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
|
||||
if err != nil || len(data) > 10<<20 {
|
||||
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", ref)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, "", "", fmt.Errorf("图片文件为空: %s", ref)
|
||||
}
|
||||
contentType := http.DetectContentType(data)
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return nil, "", "", fmt.Errorf("不是有效图片: %s", ref)
|
||||
}
|
||||
return data, contentType, filepath.Base(rel), nil
|
||||
}
|
||||
|
||||
// writeFileWithinRoot 将上传文件限制在指定根目录内,拒绝符号链接和路径逃逸。
|
||||
func writeFileWithinRoot(rootDir, name string, data []byte) error {
|
||||
root, err := os.OpenRoot(rootDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
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 {
|
||||
_ = file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
|
||||
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 := publicHTTPClient()
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, (10<<20)+1))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
|
||||
}
|
||||
if len(data) > 10<<20 {
|
||||
return nil, "", fmt.Errorf("远程图片不能超过 10 MiB: %s", rawURL)
|
||||
}
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if i := strings.Index(contentType, ";"); i >= 0 {
|
||||
contentType = contentType[:i]
|
||||
}
|
||||
if contentType == "" || contentType == "application/octet-stream" {
|
||||
contentType = http.DetectContentType(data)
|
||||
}
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return nil, "", fmt.Errorf("远程文件不是图片: %s", rawURL)
|
||||
}
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
// publicHTTPClient 只允许连接公网地址,防止批量铺货图片 URL 访问本机或内网服务。
|
||||
func publicHTTPClient() *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, resolved := range ips {
|
||||
if isPublicIP(resolved.IP) {
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("拒绝访问非公网地址")
|
||||
},
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 30 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
return fmt.Errorf("图片 URL 重定向次数过多")
|
||||
}
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("图片 URL 重定向协议不安全")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func isPublicIP(ip net.IP) bool {
|
||||
return ip != nil && !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() &&
|
||||
!ip.IsLinkLocalMulticast() && !ip.IsUnspecified() && !ip.IsMulticast()
|
||||
}
|
||||
|
||||
func validateBatchImageRef(uploadDir, ref string) error {
|
||||
if isHTTPURL(ref) {
|
||||
return nil
|
||||
}
|
||||
rel, err := safeZipPath(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(uploadDir, rel)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
return fmt.Errorf("图片文件不存在: %s", ref)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHTTPURL(ref string) bool {
|
||||
ref = strings.ToLower(strings.TrimSpace(ref))
|
||||
return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://")
|
||||
}
|
||||
|
||||
func pathBaseFromURL(rawURL string) string {
|
||||
base := filepath.Base(strings.Split(rawURL, "?")[0])
|
||||
if base == "." || base == "/" || base == "" {
|
||||
exts, _ := mime.ExtensionsByType(http.DetectContentType(nil))
|
||||
if len(exts) > 0 {
|
||||
return "image" + exts[0]
|
||||
}
|
||||
return "image.jpg"
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
func safeBaseName(name string) string {
|
||||
name = strings.TrimSpace(filepath.Base(name))
|
||||
name = strings.ReplaceAll(name, string(os.PathSeparator), "_")
|
||||
if name == "." || name == "/" {
|
||||
return ""
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func safeZipPath(raw string) (string, error) {
|
||||
raw = strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/"))
|
||||
if raw == "" || strings.HasPrefix(raw, "/") {
|
||||
return "", fmt.Errorf("图片路径不安全: %s", raw)
|
||||
}
|
||||
clean := filepath.Clean(raw)
|
||||
if clean == "." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) || clean == ".." {
|
||||
return "", fmt.Errorf("图片路径不安全: %s", raw)
|
||||
}
|
||||
return clean, nil
|
||||
}
|
||||
|
||||
func splitImageRefs(raw string) []string {
|
||||
raw = strings.ReplaceAll(raw, "\n", ";")
|
||||
raw = strings.ReplaceAll(raw, ";", ";")
|
||||
parts := strings.Split(raw, ";")
|
||||
out := []string{}
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package server
|
||||
|
||||
// item_publish_sheet.go: parse publish-batch spreadsheet sources (CSV/TSV/XLSX) into generic maps.
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) {
|
||||
return parsePublishSheetBytesWithLimit(raw, filename, 0)
|
||||
}
|
||||
|
||||
func parsePublishSheetBytesWithLimit(raw []byte, filename string, maxRows int) ([]map[string]any, error) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(filename)) {
|
||||
case ".xlsx":
|
||||
return parseXLSXPublishSheetWithLimit(raw, maxRows)
|
||||
case ".csv":
|
||||
return parseDelimitedPublishSheet(raw, ',', maxRows)
|
||||
case ".tsv":
|
||||
return parseDelimitedPublishSheet(raw, '\t', maxRows)
|
||||
case ".xls":
|
||||
return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入")
|
||||
default:
|
||||
return parseDelimitedPublishSheet(raw, ',', maxRows)
|
||||
}
|
||||
}
|
||||
|
||||
func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[string]any, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(raw))
|
||||
reader.Comma = comma
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.LazyQuotes = true
|
||||
header, err := reader.Read()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
keys := publishHeaderKeys(header)
|
||||
rows := make([]map[string]any, 0, 64)
|
||||
seenDataRow := false
|
||||
for {
|
||||
record, err := reader.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
seenDataRow = true
|
||||
row, nonEmpty := publishRowToMap(keys, record)
|
||||
if !nonEmpty {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, row)
|
||||
if maxRows > 0 && len(rows) > maxRows {
|
||||
return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows)
|
||||
}
|
||||
}
|
||||
if !seenDataRow {
|
||||
return nil, fmt.Errorf("表格至少需要表头和一行数据")
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func parseXLSXPublishSheet(raw []byte) ([]map[string]any, error) {
|
||||
return parseXLSXPublishSheetWithLimit(raw, 0)
|
||||
}
|
||||
|
||||
func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
|
||||
}
|
||||
shared, err := xlsxSharedStrings(zr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sheet *zip.File
|
||||
for _, f := range zr.File {
|
||||
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
|
||||
sheet = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if sheet == nil {
|
||||
return nil, fmt.Errorf("xlsx 中未找到工作表")
|
||||
}
|
||||
rawSheet, err := readXLSXPart(sheet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ws xlsxWorksheet
|
||||
if err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
|
||||
return nil, fmt.Errorf("解析工作表失败: %w", err)
|
||||
}
|
||||
rows := make([][]string, 0, len(ws.SheetData.Rows))
|
||||
for _, row := range ws.SheetData.Rows {
|
||||
values := []string{}
|
||||
for _, cell := range row.Cells {
|
||||
idx := xlsxCellIndex(cell.Ref)
|
||||
for len(values) <= idx {
|
||||
values = append(values, "")
|
||||
}
|
||||
values[idx] = xlsxCellValue(cell, shared)
|
||||
}
|
||||
rows = append(rows, values)
|
||||
}
|
||||
if len(rows) < 2 {
|
||||
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
|
||||
}
|
||||
out := rowsToPublishMaps(rows[0], rows[1:])
|
||||
if maxRows > 0 && len(out) > maxRows {
|
||||
return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
|
||||
keys := publishHeaderKeys(headers)
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
m, nonEmpty := publishRowToMap(keys, row)
|
||||
if nonEmpty {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func publishHeaderKeys(headers []string) []string {
|
||||
keys := make([]string, len(headers))
|
||||
for i, h := range headers {
|
||||
keys[i] = normalizePublishHeader(h)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func publishRowToMap(keys []string, row []string) (map[string]any, bool) {
|
||||
m := map[string]any{}
|
||||
nonEmpty := false
|
||||
for i, key := range keys {
|
||||
if key == "" || i >= len(row) {
|
||||
continue
|
||||
}
|
||||
value := strings.TrimSpace(row[i])
|
||||
if value != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
m[key] = value
|
||||
}
|
||||
return m, nonEmpty
|
||||
}
|
||||
|
||||
func normalizePublishHeader(header string) string {
|
||||
h := strings.ToLower(strings.TrimSpace(header))
|
||||
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
|
||||
switch h {
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "title", "itemtitle", "标题", "商品标题", "商品名称":
|
||||
return "title"
|
||||
case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情":
|
||||
return "description"
|
||||
case "price", "itemprice", "价格", "商品价格":
|
||||
return "price"
|
||||
case "originalprice", "原价":
|
||||
return "original_price"
|
||||
case "quantity", "库存", "数量":
|
||||
return "quantity"
|
||||
case "postagemode", "邮费模式":
|
||||
return "postage_mode"
|
||||
case "postage", "邮费":
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
return "paid_delivery_contents"
|
||||
case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品":
|
||||
return "review_gift_enabled"
|
||||
case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密":
|
||||
return "review_gift_contents"
|
||||
case "reviewrequestenabled", "求评价启用", "超时未评价时提醒":
|
||||
return "review_request_enabled"
|
||||
case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒":
|
||||
return "review_request_after_hours"
|
||||
case "reviewrequestmessage", "求评价文案", "提醒内容":
|
||||
return "review_request_message"
|
||||
case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次":
|
||||
return "review_request_max_attempts"
|
||||
case "reviewrequestdelayseconds", "求评价延迟秒":
|
||||
return "review_request_delay_seconds"
|
||||
default:
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ func (s *Server) mountKeywordsReal(r chi.Router) {
|
||||
|
||||
func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
@@ -34,6 +37,9 @@ func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
@@ -48,6 +54,9 @@ func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
@@ -65,6 +74,9 @@ func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Reply string `json:"reply"`
|
||||
@@ -82,6 +94,9 @@ func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Reply string `json:"reply"`
|
||||
@@ -100,6 +115,9 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
index := atoiDefault(chi.URLParam(r, "index"), -1)
|
||||
if err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil {
|
||||
writeErr(w, http.StatusNotFound, "关键字不存在")
|
||||
@@ -133,6 +151,9 @@ func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID)
|
||||
if err != nil {
|
||||
@@ -146,6 +167,9 @@ func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
ReplyContent string `json:"reply_content"`
|
||||
@@ -163,6 +187,9 @@ func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
if err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// mtopResp 描述一次 mock mtop HTTP 响应。
|
||||
type mtopResp struct {
|
||||
ret []string
|
||||
body string // 非 empty 时直接返回该 body(优先于 ret)
|
||||
updatedCookies string // 通过 Set-Cookie 头下发
|
||||
statusCode int
|
||||
}
|
||||
|
||||
// withMTopTransport 用自定义 transport 构造 *mtop.ClientImpl(按 URL 分发用闭包)。
|
||||
func withMTopTransport(rt roundTripFunc) *mtop.ClientImpl {
|
||||
cli := mtop.NewClient()
|
||||
cli.HTTPClient = &http.Client{Transport: rt}
|
||||
return cli
|
||||
}
|
||||
|
||||
// 默认对未匹配 URL 返回 SUCCESS。
|
||||
func newMockMTop(t *testing.T, resp mtopResp) *mtop.ClientImpl {
|
||||
t.Helper()
|
||||
cli := mtop.NewClient()
|
||||
cli.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
body := resp.body
|
||||
if body == "" {
|
||||
body = `{"ret":["` + strings.Join(resp.ret, "\",\"") + `"]}`
|
||||
}
|
||||
status := resp.statusCode
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
r := &http.Response{
|
||||
StatusCode: status,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}
|
||||
if resp.updatedCookies != "" {
|
||||
r.Header.Set("Set-Cookie", "_m_h5_tk="+resp.updatedCookies+"; Path=/")
|
||||
}
|
||||
return r, nil
|
||||
})}
|
||||
return cli
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestListChannels 列出通知渠道。
|
||||
func TestListChannels(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 先创建一个渠道。
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 列出。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/notification-channels", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("list status=%d", rec2.Code)
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 || arr[0]["name"] != "钉钉" {
|
||||
t.Fatalf("渠道列表异常: %+v", arr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateChannelMissingName 缺 name/type 400。
|
||||
func TestCreateChannelMissingName(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"type":"dingtalk"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 name 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateChannelBadJSON 非法 JSON 400。
|
||||
func TestCreateChannelBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateChannel 更新渠道。
|
||||
func TestUpdateChannel(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 创建。
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var cr map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &cr)
|
||||
id := int64(cr["id"].(float64))
|
||||
|
||||
// 更新。
|
||||
upd := `{"name":"改名钉钉","type":"dingtalk","config":"{}","enabled":false}`
|
||||
req2 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(upd))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec2.Code, rec2.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateChannelBadID 无效 ID 400。
|
||||
func TestUpdateChannelBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/notification-channels/abc", strings.NewReader(`{}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateChannelBadJSON 非法 JSON 400。
|
||||
func TestUpdateChannelBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/notification-channels/1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteChannel 删除渠道。
|
||||
func TestDeleteChannel(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var cr map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &cr)
|
||||
id := int64(cr["id"].(float64))
|
||||
|
||||
req2 := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(id), nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteChannelBadID 无效 ID 400。
|
||||
func TestDeleteChannelBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/notification-channels/abc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTestChannelNoNotifier 未注入通知器 503。
|
||||
func TestTestChannelNoNotifier(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels/1/test", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("无通知器应 503,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTestChannelBadID 无效 ID 400。
|
||||
func TestTestChannelBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels/abc/test", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListMessageNotifications 列出消息通知绑定。
|
||||
func TestListMessageNotifications(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var m map[string][]map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &m)
|
||||
if len(m["acc1"]) != 1 {
|
||||
t.Fatalf("绑定列表异常: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "notif2", "[email protected]", "pw"); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
u2, _ := store.Users.GetByUsername(ctx, "notif2")
|
||||
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 := 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 {
|
||||
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 {
|
||||
t.Fatalf("insert dirty binding: %v", err)
|
||||
}
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
listReq := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
|
||||
listReq.AddCookie(cookie)
|
||||
listRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(listRec, listReq)
|
||||
if listRec.Code != http.StatusOK {
|
||||
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
|
||||
}
|
||||
var listed map[string][]map[string]any
|
||||
if 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 := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
|
||||
getReq.AddCookie(cookie)
|
||||
getRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(getRec, getReq)
|
||||
if getRec.Code != http.StatusOK {
|
||||
t.Fatalf("get status=%d body=%s", getRec.Code, getRec.Body.String())
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(getRec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode get: %v", err)
|
||||
}
|
||||
ids, _ := got["channel_ids"].([]any)
|
||||
if len(ids) != 1 || int64(ids[0].(float64)) != ownID {
|
||||
t.Fatalf("bindings should filter dirty binding: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteMessageNotification 删除单条消息通知。
|
||||
func TestDeleteMessageNotification(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteMessageNotificationBadID 无效 ID 400。
|
||||
func TestDeleteMessageNotificationBadID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/abc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteAccountNotifications 删除账号的所有通知绑定。
|
||||
func TestDeleteAccountNotifications(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/account/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetAccountBindingsBadJSON 非法 JSON 400。
|
||||
func TestSetAccountBindingsBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetAccountBindingsSingleChannel 单渠道绑定。
|
||||
func TestSetAccountBindingsSingleChannel(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"channel_id":1,"enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,9 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.UpdateChannel(r.Context(), &db.NotificationChannelRow{
|
||||
ID: id, Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled,
|
||||
}); err != nil {
|
||||
@@ -87,6 +90,9 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.DeleteChannel(r.Context(), id); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
@@ -101,13 +107,16 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
if s.Notifier == nil {
|
||||
if s.notifier == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
body := "🧪 通知渠道测试\n\n这是一条来自闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
|
||||
time.Now().Format("2006-01-02 15:04:05")
|
||||
if err := s.Notifier.SendToChannel(id, body); err != nil {
|
||||
if err := s.notifier.SendToChannel(id, body); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -116,6 +125,9 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
ids, err := s.Store.Notifications.AccountBindings(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
@@ -130,7 +142,7 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
|
||||
`SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled
|
||||
FROM message_notifications mn
|
||||
JOIN cookies c ON c.id=mn.cookie_id
|
||||
LEFT JOIN notification_channels nc ON nc.id=mn.channel_id
|
||||
JOIN notification_channels nc ON nc.id=mn.channel_id AND nc.user_id=c.user_id
|
||||
WHERE c.user_id=?
|
||||
ORDER BY mn.id DESC`, sess.UserID)
|
||||
if err != nil {
|
||||
@@ -154,11 +166,18 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
|
||||
"enabled": enabled != 0,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
@@ -169,6 +188,9 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if req.ChannelID != 0 {
|
||||
if !s.requireChannelOwner(w, r, req.ChannelID) {
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
@@ -176,7 +198,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO message_notifications (cookie_id, channel_id, enabled)
|
||||
VALUES (?, ?, ?)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id", "channel_id"}, map[string]string{
|
||||
"enabled": "EXCLUDED.enabled",
|
||||
"enabled": "EXCLUDED.enabled",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cid, req.ChannelID, btoi(enabled))
|
||||
@@ -187,6 +209,11 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
return
|
||||
}
|
||||
for _, channelID := range req.ChannelIDs {
|
||||
if !s.requireChannelOwner(w, r, channelID) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.Notifications.SetBindings(r.Context(), cid, req.ChannelIDs); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -46,78 +39,53 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
|
||||
if cookieID != "" {
|
||||
if _, ok := s.cookieForUser(r, sess.UserID, cookieID); !ok {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
}
|
||||
if pageSize > 200 {
|
||||
pageSize = 200
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
rows, total, err := s.Store.Orders.ListForUser(r.Context(), db.OrderListFilter{
|
||||
UserID: sess.UserID, CookieID: cookieID, Status: status, Limit: pageSize, Offset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
if cookieID != "" {
|
||||
for k := range all {
|
||||
if k != cookieID {
|
||||
delete(all, k)
|
||||
}
|
||||
}
|
||||
orders := make([]map[string]any, 0, len(rows))
|
||||
for _, o := range rows {
|
||||
st := db.NormalizeOrderStatus(o.OrderStatus)
|
||||
orders = append(orders, map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": o.ItemTitle,
|
||||
"item_image": itemImageFromDetail(o.ItemDetail),
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": st,
|
||||
"status": st,
|
||||
"cookie_id": o.CookieID,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
})
|
||||
}
|
||||
var orders []map[string]any
|
||||
for cid := range all {
|
||||
itemRows, _ := s.Store.Items.AllForCookie(r.Context(), cid)
|
||||
itemsByID := make(map[string]db.ItemInfoRow, len(itemRows))
|
||||
for _, item := range itemRows {
|
||||
itemsByID[item.ItemID] = item
|
||||
}
|
||||
rows, err := s.Store.Orders.ByCookie(r.Context(), cid, 1000)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, o := range rows {
|
||||
st := db.NormalizeOrderStatus(o.OrderStatus)
|
||||
if status != "" && st != status {
|
||||
continue
|
||||
}
|
||||
item := itemsByID[o.ItemID]
|
||||
orders = append(orders, map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": item.ItemTitle,
|
||||
"item_image": itemImageFromDetail(item.ItemDetail),
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": st,
|
||||
"status": st,
|
||||
"cookie_id": cid,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
total := len(orders)
|
||||
totalPages := (total + pageSize - 1) / pageSize
|
||||
start := (page - 1) * pageSize
|
||||
end := start + pageSize
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
paged := []map[string]any{}
|
||||
if start < end {
|
||||
paged = orders[start:end]
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"data": paged,
|
||||
"data": orders,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
@@ -128,9 +96,8 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
|
||||
// getOrder 订单详情。
|
||||
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
o, err := s.Store.Orders.Get(r.Context(), orderID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "订单不存在")
|
||||
o, ok := s.requireOrderOwner(w, r, orderID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
itemTitle, itemImage := "", ""
|
||||
@@ -138,7 +105,7 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
itemTitle = item.ItemTitle
|
||||
itemImage = itemImageFromDetail(item.ItemDetail)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
payload := map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": itemTitle,
|
||||
@@ -159,7 +126,31 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
})
|
||||
}
|
||||
payload["success"] = true
|
||||
payload["data"] = map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": itemTitle,
|
||||
"item_image": itemImage,
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"cookie_id": o.CookieID,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -303,9 +294,8 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
order, err := s.Store.Orders.Get(r.Context(), orderID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "订单不存在")
|
||||
order, ok := s.requireOrderOwner(w, r, orderID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cookieID := order.CookieID
|
||||
@@ -321,7 +311,9 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(r.Context(), cookieID, detail.UpdatedCookies, 0)
|
||||
if err := s.Store.Cookies.Save(r.Context(), cookieID, detail.UpdatedCookies, 0); err != nil {
|
||||
s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
|
||||
}
|
||||
if s.Manager != nil {
|
||||
if account, running := s.Manager.GetInstance(cookieID); running {
|
||||
account.UpdateCookie(detail.UpdatedCookies)
|
||||
@@ -349,6 +341,9 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
// deleteOrder 删除订单。
|
||||
func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
if _, ok := s.requireOrderOwner(w, r, orderID); !ok {
|
||||
return
|
||||
}
|
||||
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM orders WHERE order_id=?`, orderID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
@@ -360,6 +355,9 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
|
||||
// updateOrder 更新订单(手动发货等)。
|
||||
func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
if _, ok := s.requireOrderOwner(w, r, orderID); !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
OrderStatus string `json:"order_status"`
|
||||
Status string `json:"status"`
|
||||
@@ -454,7 +452,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
if req.ShipMode == "full_delivery" {
|
||||
if s.Manager == nil || s.Automation == nil {
|
||||
if s.Manager == nil || s.automation == nil {
|
||||
failedCount++
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "自动化中心未初始化"})
|
||||
continue
|
||||
@@ -464,7 +462,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "该账号未在线运行,无法执行完整发货"})
|
||||
continue
|
||||
}
|
||||
sent, err := s.Automation.ManualFullDelivery(r.Context(), order)
|
||||
sent, err := s.automation.ManualFullDelivery(r.Context(), order)
|
||||
if err != nil {
|
||||
failedCount++
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": err.Error()})
|
||||
@@ -494,7 +492,9 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
if updatedCookies != "" && updatedCookies != cookieValue {
|
||||
_ = s.Store.Cookies.Save(r.Context(), order.CookieID, updatedCookies, sess.UserID)
|
||||
if err := s.Store.Cookies.Save(r.Context(), order.CookieID, updatedCookies, sess.UserID); err != nil {
|
||||
s.Logger.Error("保存发货刷新后的 cookie 失败", "cookie_id", order.CookieID, "err", err)
|
||||
}
|
||||
if s.Manager != nil {
|
||||
if acc, running := s.Manager.GetInstance(order.CookieID); running {
|
||||
acc.UpdateCookie(updatedCookies)
|
||||
@@ -512,7 +512,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
sysShip := true
|
||||
_ = s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{
|
||||
if err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{
|
||||
CookieID: order.CookieID,
|
||||
OrderStatus: "shipped",
|
||||
SystemShipped: &sysShip,
|
||||
@@ -527,7 +527,9 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
SpecValue: order.SpecValue,
|
||||
Quantity: order.Quantity,
|
||||
Amount: order.Amount,
|
||||
})
|
||||
}); err != nil {
|
||||
s.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err)
|
||||
}
|
||||
successCount++
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"})
|
||||
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
|
||||
@@ -609,13 +611,15 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
if itemID != "" {
|
||||
_ = s.Store.Items.UpsertBasic(r.Context(), &db.ItemInfoRow{
|
||||
if err := s.Store.Items.UpsertBasic(r.Context(), &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 {
|
||||
s.Logger.Error("导入订单时补全商品信息失败", "cookie_id", cookieID, "item_id", itemID, "err", err)
|
||||
}
|
||||
}
|
||||
successCount++
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"})
|
||||
@@ -652,357 +656,8 @@ func isStableOrderStatus(status string) bool {
|
||||
|
||||
// notifyDelivery 在 Notifier 已注入时发送发货结果通知,未注入则跳过。
|
||||
func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
|
||||
if s.Notifier == nil {
|
||||
if s.notifier == nil {
|
||||
return
|
||||
}
|
||||
s.Notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID)
|
||||
}
|
||||
|
||||
func stringFromAny(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return x
|
||||
case fmt.Stringer:
|
||||
return x.String()
|
||||
case float64:
|
||||
if x == float64(int64(x)) {
|
||||
return strconv.FormatInt(int64(x), 10)
|
||||
}
|
||||
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||
case int:
|
||||
return strconv.Itoa(x)
|
||||
case int64:
|
||||
return strconv.FormatInt(x, 10)
|
||||
case bool:
|
||||
return strconv.FormatBool(x)
|
||||
default:
|
||||
return fmt.Sprint(x)
|
||||
}
|
||||
}
|
||||
|
||||
func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(ct, "multipart/form-data") {
|
||||
// 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 32<<20)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 32 MiB。
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
return nil, fmt.Errorf("解析上传文件失败: %w", err)
|
||||
}
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("缺少上传文件")
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, (32<<20)+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取上传文件失败: %w", err)
|
||||
}
|
||||
if len(raw) > 32<<20 {
|
||||
return nil, fmt.Errorf("上传文件不能超过 32 MiB")
|
||||
}
|
||||
return parseImportedOrderBytes(raw, header.Filename)
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, (32<<20)+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取请求失败: %w", err)
|
||||
}
|
||||
if len(raw) > 32<<20 {
|
||||
return nil, fmt.Errorf("导入内容不能超过 32 MiB")
|
||||
}
|
||||
return parseImportedOrderBytes(raw, "orders.json")
|
||||
}
|
||||
|
||||
func parseImportedOrderBytes(raw []byte, filename string) ([]map[string]any, error) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(filename)) {
|
||||
case ".xlsx":
|
||||
return parseXLSXOrders(raw)
|
||||
case ".csv":
|
||||
return parseDelimitedOrders(raw, ',')
|
||||
case ".tsv":
|
||||
return parseDelimitedOrders(raw, '\t')
|
||||
case ".xls":
|
||||
return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入")
|
||||
default:
|
||||
if bytes.HasPrefix(bytes.TrimSpace(raw), []byte("[")) || bytes.HasPrefix(bytes.TrimSpace(raw), []byte("{")) {
|
||||
return parseJSONOrders(raw)
|
||||
}
|
||||
return parseDelimitedOrders(raw, ',')
|
||||
}
|
||||
}
|
||||
|
||||
func parseJSONOrders(raw []byte) ([]map[string]any, error) {
|
||||
var arr []map[string]any
|
||||
if err := json.Unmarshal(raw, &arr); err == nil {
|
||||
return normalizeImportOrderMaps(arr), nil
|
||||
}
|
||||
var single map[string]any
|
||||
if err := json.Unmarshal(raw, &single); err != nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
}
|
||||
return normalizeImportOrderMaps([]map[string]any{single}), nil
|
||||
}
|
||||
|
||||
func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(raw))
|
||||
reader.Comma = comma
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.LazyQuotes = true
|
||||
records, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
if len(records) < 2 {
|
||||
return nil, fmt.Errorf("表格至少需要表头和一行数据")
|
||||
}
|
||||
headers := normalizeImportHeaders(records[0])
|
||||
out := make([]map[string]any, 0, len(records)-1)
|
||||
for _, row := range records[1:] {
|
||||
m := make(map[string]any)
|
||||
nonEmpty := false
|
||||
for i, h := range headers {
|
||||
if h == "" || i >= len(row) {
|
||||
continue
|
||||
}
|
||||
v := strings.TrimSpace(row[i])
|
||||
if v != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
m[h] = v
|
||||
}
|
||||
if nonEmpty {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
|
||||
}
|
||||
shared := xlsxSharedStrings(zr)
|
||||
var sheet *zip.File
|
||||
for _, f := range zr.File {
|
||||
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
|
||||
sheet = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if sheet == nil {
|
||||
return nil, fmt.Errorf("xlsx 中未找到工作表")
|
||||
}
|
||||
rc, err := sheet.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
var ws xlsxWorksheet
|
||||
if err := xml.NewDecoder(rc).Decode(&ws); err != nil {
|
||||
return nil, fmt.Errorf("解析工作表失败: %w", err)
|
||||
}
|
||||
rows := make([][]string, 0, len(ws.SheetData.Rows))
|
||||
for _, row := range ws.SheetData.Rows {
|
||||
values := []string{}
|
||||
for _, cell := range row.Cells {
|
||||
idx := xlsxCellIndex(cell.Ref)
|
||||
for len(values) <= idx {
|
||||
values = append(values, "")
|
||||
}
|
||||
values[idx] = xlsxCellValue(cell, shared)
|
||||
}
|
||||
rows = append(rows, values)
|
||||
}
|
||||
if len(rows) < 2 {
|
||||
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
|
||||
}
|
||||
headers := normalizeImportHeaders(rows[0])
|
||||
out := make([]map[string]any, 0, len(rows)-1)
|
||||
for _, row := range rows[1:] {
|
||||
m := make(map[string]any)
|
||||
nonEmpty := false
|
||||
for i, h := range headers {
|
||||
if h == "" || i >= len(row) {
|
||||
continue
|
||||
}
|
||||
v := strings.TrimSpace(row[i])
|
||||
if v != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
m[h] = v
|
||||
}
|
||||
if nonEmpty {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type xlsxWorksheet struct {
|
||||
SheetData struct {
|
||||
Rows []xlsxRow `xml:"row"`
|
||||
} `xml:"sheetData"`
|
||||
}
|
||||
|
||||
type xlsxRow struct {
|
||||
Cells []xlsxCell `xml:"c"`
|
||||
}
|
||||
|
||||
type xlsxCell struct {
|
||||
Ref string `xml:"r,attr"`
|
||||
Type string `xml:"t,attr"`
|
||||
Value string `xml:"v"`
|
||||
InlineStr string `xml:"is>t"`
|
||||
}
|
||||
|
||||
type xlsxSST struct {
|
||||
Items []struct {
|
||||
Inner string `xml:",innerxml"`
|
||||
} `xml:"si"`
|
||||
}
|
||||
|
||||
func xlsxSharedStrings(zr *zip.Reader) []string {
|
||||
for _, f := range zr.File {
|
||||
if f.Name != "xl/sharedStrings.xml" {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer rc.Close()
|
||||
var sst xlsxSST
|
||||
if err := xml.NewDecoder(rc).Decode(&sst); err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(sst.Items))
|
||||
for _, item := range sst.Items {
|
||||
out = append(out, xmlCharData(item.Inner))
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func xlsxCellValue(cell xlsxCell, shared []string) string {
|
||||
switch cell.Type {
|
||||
case "s":
|
||||
idx, _ := strconv.Atoi(strings.TrimSpace(cell.Value))
|
||||
if idx >= 0 && idx < len(shared) {
|
||||
return shared[idx]
|
||||
}
|
||||
case "inlineStr":
|
||||
return strings.TrimSpace(cell.InlineStr)
|
||||
}
|
||||
return strings.TrimSpace(cell.Value)
|
||||
}
|
||||
|
||||
func xlsxCellIndex(ref string) int {
|
||||
idx := 0
|
||||
for _, r := range ref {
|
||||
if r < 'A' || r > 'Z' {
|
||||
break
|
||||
}
|
||||
idx = idx*26 + int(r-'A'+1)
|
||||
}
|
||||
if idx == 0 {
|
||||
return 0
|
||||
}
|
||||
return idx - 1
|
||||
}
|
||||
|
||||
func xmlCharData(inner string) string {
|
||||
dec := xml.NewDecoder(strings.NewReader("<x>" + inner + "</x>"))
|
||||
var parts []string
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if data, ok := tok.(xml.CharData); ok {
|
||||
parts = append(parts, string(data))
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(parts, ""))
|
||||
}
|
||||
|
||||
func normalizeImportOrderMaps(in []map[string]any) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(in))
|
||||
for _, raw := range in {
|
||||
m := make(map[string]any)
|
||||
for k, v := range raw {
|
||||
m[normalizeImportHeader(k)] = v
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeImportHeaders(headers []string) []string {
|
||||
out := make([]string, len(headers))
|
||||
for i, h := range headers {
|
||||
out[i] = normalizeImportHeader(h)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeImportHeader(header string) string {
|
||||
h := strings.ToLower(strings.TrimSpace(header))
|
||||
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
|
||||
switch h {
|
||||
case "orderid", "订单号", "订单id", "订单编号":
|
||||
return "order_id"
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "itemid", "商品id", "商品编号":
|
||||
return "item_id"
|
||||
case "itemtitle", "商品标题", "商品名称":
|
||||
return "item_title"
|
||||
case "itemprice", "商品价格":
|
||||
return "item_price"
|
||||
case "itemdetail", "itemdescription", "商品描述", "商品详情":
|
||||
return "item_detail"
|
||||
case "buyerid", "买家id":
|
||||
return "buyer_id"
|
||||
case "status", "orderstatus", "订单状态", "状态":
|
||||
return "status"
|
||||
case "specname", "规格名":
|
||||
return "spec_name"
|
||||
case "specvalue", "规格值":
|
||||
return "spec_value"
|
||||
case "quantity", "数量":
|
||||
return "quantity"
|
||||
case "amount", "金额", "订单金额":
|
||||
return "amount"
|
||||
case "receivername", "收件人", "收货人":
|
||||
return "receiver_name"
|
||||
case "receiverphone", "手机号", "收件电话", "收货电话":
|
||||
return "receiver_phone"
|
||||
case "receiveraddress", "地址", "收件地址", "收货地址":
|
||||
return "receiver_address"
|
||||
case "receivercity", "城市", "收件城市", "收货城市":
|
||||
return "receiver_city"
|
||||
case "chatid", "会话id":
|
||||
return "chat_id"
|
||||
default:
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
func firstImportString(m map[string]any, keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
s := strings.TrimSpace(stringFromAny(v))
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
s.notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRefreshOrdersNoBrowser 浏览器未启用时应 503。
|
||||
func TestRefreshOrdersNoBrowser(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", strings.NewReader(""))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("无浏览器应 503,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshSingleOrderNoBrowser 单订单刷新无浏览器时 503。
|
||||
func TestRefreshSingleOrderNoBrowser(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/ord-x/refresh", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("无浏览器应 503,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshSingleOrderNotFound 单订单刷新不存在订单 404。
|
||||
func TestRefreshSingleOrderNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 注入非 nil Browser 但内部 playwright 不可用,订单查询先行 404。
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/no-such/refresh", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
// Browser==nil → 503;先校验此路径不 panic。
|
||||
if rec.Code != http.StatusServiceUnavailable && rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 503/404, got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateOrder 更新订单字段(status 归一)。
|
||||
func TestUpdateOrder(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"status":"shipped","receiver_name":"张三","receiver_phone":"13800000000","receiver_address":"北京"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-u", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 验证已写入。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-u", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &got)
|
||||
if got["order_status"] != "shipped" || got["receiver_name"] != "张三" {
|
||||
t.Fatalf("更新未生效: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateOrderBadJSON 非法 JSON 应 400。
|
||||
func TestUpdateOrderBadJSON(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id) VALUES ('ord-bad','item1','acc1')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-bad", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersStatusOnlySuccess mtop ConsignContext 成功路径。
|
||||
func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"order_ids":["ord-m"],"ship_mode":"status_only"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("manual ship status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true {
|
||||
t.Fatalf("应成功: %+v", res)
|
||||
}
|
||||
results, _ := res["results"].([]any)
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("应1条结果,got %d", len(results))
|
||||
}
|
||||
// 订单状态应已变为 shipped。
|
||||
var ord map[string]any
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-m", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
json.Unmarshal(rec2.Body.Bytes(), &ord)
|
||||
if ord["order_status"] != "shipped" {
|
||||
t.Errorf("订单状态应为 shipped,got %v", ord["order_status"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersConsignFail mtop ConsignContext 失败(非 success ret)。
|
||||
func TestManualShipOrdersConsignFail(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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')`)
|
||||
|
||||
// 覆盖 mtop client:返回非 success ret。
|
||||
prev := srv.MTop
|
||||
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"}})
|
||||
defer func() { srv.MTop = prev }()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
body := `{"order_ids":["ord-f"],"ship_mode":"status_only"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != false {
|
||||
t.Fatalf("整体应失败: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersOrderNotFound 订单不存在 → failed。
|
||||
func TestManualShipOrdersOrderNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"order_ids":["no-such-ord"],"ship_mode":"status_only"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["failed_count"] != float64(1) {
|
||||
t.Fatalf("应1失败,got %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersBadMode 非法发货模式 400。
|
||||
func TestManualShipOrdersBadMode(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"order_ids":["ord-x"],"ship_mode":"bogus"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法模式应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersEmpty 缺少订单 ID 400。
|
||||
func TestManualShipOrdersEmpty(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"order_ids":[],"ship_mode":"status_only"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("空订单应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersBadJSON 非法 JSON 400。
|
||||
func TestManualShipOrdersBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManualShipOrdersFullDeliveryNoAutomation full_delivery 但自动化未初始化 → failed。
|
||||
func TestManualShipOrdersFullDeliveryNoAutomation(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"order_ids":["ord-full"],"ship_mode":"full_delivery"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["failed_count"] != float64(1) {
|
||||
t.Fatalf("应1失败,got %+v", res)
|
||||
}
|
||||
results, _ := res["results"].([]any)
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("结果数异常: %d", len(results))
|
||||
}
|
||||
r0, _ := results[0].(map[string]any)
|
||||
if !strings.Contains(r0["message"].(string), "自动化") {
|
||||
t.Fatalf("应提示自动化未初始化,got %v", r0["message"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsStableOrderStatus 稳定状态判定。
|
||||
func TestIsStableOrderStatus(t *testing.T) {
|
||||
stable := map[string]bool{"shipped": true, "completed": true, "cancelled": true}
|
||||
unstable := map[string]bool{"pending_ship": false, "processing": false, "": false, "unknown": false}
|
||||
for s, want := range stable {
|
||||
if got := isStableOrderStatus(s); got != want {
|
||||
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
|
||||
}
|
||||
}
|
||||
for s, want := range unstable {
|
||||
if got := isStableOrderStatus(s); got != want {
|
||||
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAtoiDefault atoiDefault 表驱动。
|
||||
func TestAtoiDefault(t *testing.T) {
|
||||
cases := map[string]int{"": 5, "abc": 5, "3": 3, "12": 12}
|
||||
for in, want := range cases {
|
||||
if got := atoiDefault(in, 5); got != want {
|
||||
t.Errorf("atoiDefault(%q)=%d want %d", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package server
|
||||
|
||||
// 订单导入解析:支持 JSON / CSV / TSV / XLSX 四种格式,统一输出 []map[string]any。
|
||||
// 表头经 normalizeImportHeader 归一(中英文别名 → 标准字段名),供 order_handlers 上层消费。
|
||||
//
|
||||
// 抽离自 order_handlers.go,便于独立单测。
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// parseImportedOrders 从 HTTP 请求体解析导入的订单。
|
||||
// 支持两种入口:multipart/form-data 上传文件(按扩展名分流),或 raw body(按内容分流)。
|
||||
// 上限 maxOrderImportBytes(32 MiB),由调用方在更上层用 MaxBytesReader 强制。
|
||||
func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(ct, "multipart/form-data") {
|
||||
// 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxOrderImportBytes)
|
||||
// #nosec G120 -- 请求体已由 MaxBytesReader 限制。
|
||||
if err := r.ParseMultipartForm(maxOrderImportBytes); err != nil {
|
||||
return nil, fmt.Errorf("解析上传文件失败: %w", err)
|
||||
}
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("缺少上传文件")
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, int64(maxOrderImportBytes)+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取上传文件失败: %w", err)
|
||||
}
|
||||
if len(raw) > maxOrderImportBytes {
|
||||
return nil, fmt.Errorf("上传文件不能超过 32 MiB")
|
||||
}
|
||||
return parseImportedOrderBytes(raw, header.Filename)
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, int64(maxOrderImportBytes)+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取请求失败: %w", err)
|
||||
}
|
||||
if len(raw) > maxOrderImportBytes {
|
||||
return nil, fmt.Errorf("导入内容不能超过 32 MiB")
|
||||
}
|
||||
return parseImportedOrderBytes(raw, "orders.json")
|
||||
}
|
||||
|
||||
// parseImportedOrderBytes 按文件扩展名/内容分流到具体解析器。
|
||||
func parseImportedOrderBytes(raw []byte, filename string) ([]map[string]any, error) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(filename)) {
|
||||
case ".xlsx":
|
||||
return parseXLSXOrders(raw)
|
||||
case ".csv":
|
||||
return parseDelimitedOrders(raw, ',')
|
||||
case ".tsv":
|
||||
return parseDelimitedOrders(raw, '\t')
|
||||
case ".xls":
|
||||
return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入")
|
||||
default:
|
||||
if bytes.HasPrefix(bytes.TrimSpace(raw), []byte("[")) || bytes.HasPrefix(bytes.TrimSpace(raw), []byte("{")) {
|
||||
return parseJSONOrders(raw)
|
||||
}
|
||||
return parseDelimitedOrders(raw, ',')
|
||||
}
|
||||
}
|
||||
|
||||
// parseJSONOrders 解析 JSON 数组或单对象。
|
||||
func parseJSONOrders(raw []byte) ([]map[string]any, error) {
|
||||
trimmed := bytes.TrimSpace(raw)
|
||||
if len(trimmed) == 0 {
|
||||
return nil, fmt.Errorf("导入内容为空")
|
||||
}
|
||||
if trimmed[0] == '[' {
|
||||
return parseJSONOrderArray(trimmed)
|
||||
}
|
||||
var single map[string]any
|
||||
if err := json.Unmarshal(trimmed, &single); err != nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
}
|
||||
return normalizeImportOrderMaps([]map[string]any{single}), nil
|
||||
}
|
||||
|
||||
func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
}
|
||||
if delim, ok := tok.(json.Delim); !ok || delim != '[' {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: 不是数组")
|
||||
}
|
||||
out := make([]map[string]any, 0, 256)
|
||||
for dec.More() {
|
||||
var row map[string]any
|
||||
if err := dec.Decode(&row); err != nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
}
|
||||
out = append(out, normalizeImportOrderMap(row))
|
||||
if len(out) > maxOrderImportRows {
|
||||
return nil, fmt.Errorf("单次最多导入 %d 条订单", maxOrderImportRows)
|
||||
}
|
||||
}
|
||||
if tok, err = dec.Token(); err != nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
} else if delim, ok := tok.(json.Delim); !ok || delim != ']' {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: 数组未闭合")
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); err != io.EOF {
|
||||
if err == nil {
|
||||
return nil, fmt.Errorf("解析 JSON 失败: 存在额外内容")
|
||||
}
|
||||
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseDelimitedOrders 解析 CSV/TSV(按 comma 分隔)。首行为表头,其余为数据行。
|
||||
// 全空行跳过。
|
||||
func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
|
||||
reader := csv.NewReader(bytes.NewReader(raw))
|
||||
reader.Comma = comma
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.LazyQuotes = true
|
||||
headerRow, err := reader.Read()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
headers := normalizeImportHeaders(headerRow)
|
||||
rows := make([][]string, 0, 256)
|
||||
for {
|
||||
record, err := reader.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析表格失败: %w", err)
|
||||
}
|
||||
rows = append(rows, record)
|
||||
if len(rows) > maxOrderImportRows {
|
||||
return nil, fmt.Errorf("单次最多导入 %d 条订单", maxOrderImportRows)
|
||||
}
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, fmt.Errorf("表格至少需要表头和一行数据")
|
||||
}
|
||||
return rowsToMaps(headers, rows), nil
|
||||
}
|
||||
|
||||
// parseXLSXOrders 解析 .xlsx(OOXML):读取 sharedStrings + 第一个 worksheet,
|
||||
// 按 cell ref(如 "C3")定位列索引,支持共享字符串、内联字符串、数字三种 cell 类型。
|
||||
func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
|
||||
}
|
||||
shared, err := xlsxSharedStrings(zr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sheet *zip.File
|
||||
for _, f := range zr.File {
|
||||
if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") {
|
||||
sheet = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if sheet == nil {
|
||||
return nil, fmt.Errorf("xlsx 中未找到工作表")
|
||||
}
|
||||
rawSheet, err := readXLSXPart(sheet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ws xlsxWorksheet
|
||||
if err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
|
||||
return nil, fmt.Errorf("解析工作表失败: %w", err)
|
||||
}
|
||||
rows := make([][]string, 0, len(ws.SheetData.Rows))
|
||||
for _, row := range ws.SheetData.Rows {
|
||||
values := []string{}
|
||||
for _, cell := range row.Cells {
|
||||
idx := xlsxCellIndex(cell.Ref)
|
||||
for len(values) <= idx {
|
||||
values = append(values, "")
|
||||
}
|
||||
values[idx] = xlsxCellValue(cell, shared)
|
||||
}
|
||||
rows = append(rows, values)
|
||||
}
|
||||
if len(rows) < 2 {
|
||||
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
|
||||
}
|
||||
headers := normalizeImportHeaders(rows[0])
|
||||
out := rowsToMaps(headers, rows[1:])
|
||||
if len(out) > maxOrderImportRows {
|
||||
return nil, fmt.Errorf("单次最多导入 %d 条订单", maxOrderImportRows)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// rowsToMaps 把表头 + 数据行转为 map 列表,全空行跳过。
|
||||
func rowsToMaps(headers []string, rows [][]string) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
m := make(map[string]any)
|
||||
nonEmpty := false
|
||||
for i, h := range headers {
|
||||
if h == "" || i >= len(row) {
|
||||
continue
|
||||
}
|
||||
v := strings.TrimSpace(row[i])
|
||||
if v != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
m[h] = v
|
||||
}
|
||||
if nonEmpty {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- XLSX OOXML 内部结构 ----
|
||||
|
||||
type xlsxWorksheet struct {
|
||||
SheetData struct {
|
||||
Rows []xlsxRow `xml:"row"`
|
||||
} `xml:"sheetData"`
|
||||
}
|
||||
|
||||
type xlsxRow struct {
|
||||
Cells []xlsxCell `xml:"c"`
|
||||
}
|
||||
|
||||
type xlsxCell struct {
|
||||
Ref string `xml:"r,attr"`
|
||||
Type string `xml:"t,attr"`
|
||||
Value string `xml:"v"`
|
||||
InlineStr string `xml:"is>t"`
|
||||
}
|
||||
|
||||
type xlsxSST struct {
|
||||
Items []struct {
|
||||
Inner string `xml:",innerxml"`
|
||||
} `xml:"si"`
|
||||
}
|
||||
|
||||
// xlsxSharedStrings 读取 xl/sharedStrings.xml(共享字符串表),供 cell type="s" 引用。
|
||||
func xlsxSharedStrings(zr *zip.Reader) ([]string, error) {
|
||||
for _, f := range zr.File {
|
||||
if f.Name != "xl/sharedStrings.xml" {
|
||||
continue
|
||||
}
|
||||
raw, err := readXLSXPart(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sst xlsxSST
|
||||
if err := xmlUnmarshalXLSX(raw, &sst); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(sst.Items))
|
||||
for _, item := range sst.Items {
|
||||
out = append(out, xmlCharData(item.Inner))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func readXLSXPart(f *zip.File) ([]byte, error) {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return readLimitedXLSXXML(rc)
|
||||
}
|
||||
|
||||
func readLimitedXLSXXML(r io.Reader) ([]byte, error) {
|
||||
raw, err := io.ReadAll(io.LimitReader(r, maxXLSXXMLPartBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) > maxXLSXXMLPartBytes {
|
||||
return nil, fmt.Errorf("xlsx 内部 XML 超过 %d MiB", maxXLSXXMLPartBytes>>20)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func xmlUnmarshalXLSX(raw []byte, v any) error {
|
||||
return xml.Unmarshal(raw, v)
|
||||
}
|
||||
|
||||
// xlsxCellValue 按 cell 类型取值:s=共享字符串索引、inlineStr=内联字符串、其余=原始值。
|
||||
func xlsxCellValue(cell xlsxCell, shared []string) string {
|
||||
switch cell.Type {
|
||||
case "s":
|
||||
idx, _ := strconv.Atoi(strings.TrimSpace(cell.Value))
|
||||
if idx >= 0 && idx < len(shared) {
|
||||
return shared[idx]
|
||||
}
|
||||
case "inlineStr":
|
||||
return strings.TrimSpace(cell.InlineStr)
|
||||
}
|
||||
return strings.TrimSpace(cell.Value)
|
||||
}
|
||||
|
||||
// xlsxCellIndex 把 cell ref 的列部分(如 "C3" → "C")转为 0-based 列索引。
|
||||
func xlsxCellIndex(ref string) int {
|
||||
idx := 0
|
||||
for _, r := range ref {
|
||||
if r < 'A' || r > 'Z' {
|
||||
break
|
||||
}
|
||||
idx = idx*26 + int(r-'A'+1)
|
||||
}
|
||||
if idx == 0 {
|
||||
return 0
|
||||
}
|
||||
return idx - 1
|
||||
}
|
||||
|
||||
// xmlCharData 从 innerxml 片段中抽取所有字符数据(拼接富文本格式的单元格内容)。
|
||||
func xmlCharData(inner string) string {
|
||||
dec := xml.NewDecoder(strings.NewReader("<x>" + inner + "</x>"))
|
||||
var parts []string
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if data, ok := tok.(xml.CharData); ok {
|
||||
parts = append(parts, string(data))
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(parts, ""))
|
||||
}
|
||||
|
||||
// ---- 表头归一 ----
|
||||
|
||||
// normalizeImportOrderMaps 归一化 JSON 解析结果的 key(中文/英文别名 → 标准字段名)。
|
||||
func normalizeImportOrderMaps(in []map[string]any) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(in))
|
||||
for _, raw := range in {
|
||||
out = append(out, normalizeImportOrderMap(raw))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeImportOrderMap(raw map[string]any) map[string]any {
|
||||
m := make(map[string]any)
|
||||
for k, v := range raw {
|
||||
m[normalizeImportHeader(k)] = v
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func normalizeImportHeaders(headers []string) []string {
|
||||
out := make([]string, len(headers))
|
||||
for i, h := range headers {
|
||||
out[i] = normalizeImportHeader(h)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// normalizeImportHeader 把表头归一为小写无分隔的标准字段名。
|
||||
// 支持中英文别名(如 "订单号"→"order_id"、"商品标题"→"item_title")。
|
||||
func normalizeImportHeader(header string) string {
|
||||
h := strings.ToLower(strings.TrimSpace(header))
|
||||
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
|
||||
switch h {
|
||||
case "orderid", "订单号", "订单id", "订单编号":
|
||||
return "order_id"
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "itemid", "商品id", "商品编号":
|
||||
return "item_id"
|
||||
case "itemtitle", "商品标题", "商品名称":
|
||||
return "item_title"
|
||||
case "itemprice", "商品价格":
|
||||
return "item_price"
|
||||
case "itemdetail", "itemdescription", "商品描述", "商品详情":
|
||||
return "item_detail"
|
||||
case "buyerid", "买家id":
|
||||
return "buyer_id"
|
||||
case "status", "orderstatus", "订单状态", "状态":
|
||||
return "status"
|
||||
case "specname", "规格名":
|
||||
return "spec_name"
|
||||
case "specvalue", "规格值":
|
||||
return "spec_value"
|
||||
case "quantity", "数量":
|
||||
return "quantity"
|
||||
case "amount", "金额", "订单金额":
|
||||
return "amount"
|
||||
case "receivername", "收件人", "收货人":
|
||||
return "receiver_name"
|
||||
case "receiverphone", "手机号", "收件电话", "收货电话":
|
||||
return "receiver_phone"
|
||||
case "receiveraddress", "地址", "收件地址", "收货地址":
|
||||
return "receiver_address"
|
||||
case "receivercity", "城市", "收件城市", "收货城市":
|
||||
return "receiver_city"
|
||||
case "chatid", "会话id":
|
||||
return "chat_id"
|
||||
default:
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
// firstImportString 从归一化后的 map 中按候选 key 顺序取首个非空字符串。
|
||||
func firstImportString(m map[string]any, keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
s := strings.TrimSpace(stringFromAny(v))
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// stringFromAny 把 any 安全转为字符串(nil→"",数字/布尔格式化)。
|
||||
func stringFromAny(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return x
|
||||
case float64:
|
||||
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||
case int:
|
||||
return strconv.Itoa(x)
|
||||
case int64:
|
||||
return strconv.FormatInt(x, 10)
|
||||
case bool:
|
||||
return strconv.FormatBool(x)
|
||||
default:
|
||||
return fmt.Sprint(x)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return nil, false
|
||||
}
|
||||
d, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return nil, false
|
||||
}
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return nil, false
|
||||
}
|
||||
return d, true
|
||||
}
|
||||
|
||||
func (s *Server) requireOrderOwner(w http.ResponseWriter, r *http.Request, orderID string) (*db.Order, bool) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return nil, false
|
||||
}
|
||||
order, err := s.Store.Orders.Get(r.Context(), orderID)
|
||||
if err != nil || order == nil {
|
||||
writeErr(w, http.StatusNotFound, "订单不存在")
|
||||
return nil, false
|
||||
}
|
||||
if order.CookieID == "" {
|
||||
writeErr(w, http.StatusForbidden, "订单未绑定账号,无法操作")
|
||||
return nil, false
|
||||
}
|
||||
if _, ok := s.cookieForUser(r, sess.UserID, order.CookieID); !ok {
|
||||
writeErr(w, http.StatusForbidden, "无权操作此订单")
|
||||
return nil, false
|
||||
}
|
||||
return order, true
|
||||
}
|
||||
|
||||
func (s *Server) requireCardOwner(w http.ResponseWriter, r *http.Request, cardID int64) (*db.CardFull, bool) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return nil, false
|
||||
}
|
||||
card, err := s.Store.Cards.Get(r.Context(), cardID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "卡券不存在")
|
||||
return nil, false
|
||||
}
|
||||
if card.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
|
||||
return nil, false
|
||||
}
|
||||
return card, true
|
||||
}
|
||||
|
||||
func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, channelID int64) bool {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return false
|
||||
}
|
||||
var exists int
|
||||
err := s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
|
||||
channelID, sess.UserID).Scan(&exists)
|
||||
if err != nil || exists == 0 {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) cookieForUser(r *http.Request, userID int64, cookieID string) (string, bool) {
|
||||
all, err := s.Store.Cookies.AllForUser(r.Context(), userID)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
value, ok := all[cookieID]
|
||||
return value, ok
|
||||
}
|
||||
@@ -3,9 +3,12 @@ package server
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -40,6 +43,173 @@ func TestOrderImportParsers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrderImportFormats 覆盖 TSV、单对象 JSON、.xls 拒绝、无扩展名默认 CSV。
|
||||
func TestOrderImportFormats(t *testing.T) {
|
||||
// TSV
|
||||
tsv := []byte("order_id\tamount\no1\t1.5\n")
|
||||
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)
|
||||
}
|
||||
|
||||
// 单对象 JSON
|
||||
rows, err = parseImportedOrderBytes([]byte(`{"order_id":"o3","amount":"3.0"}`), "orders.json")
|
||||
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o3" {
|
||||
t.Fatalf("parse single json = %#v, %v", rows, err)
|
||||
}
|
||||
|
||||
// .xls 应被拒绝
|
||||
if _, err := parseImportedOrderBytes([]byte("x"), "old.xls"); err == nil {
|
||||
t.Fatal(".xls should be rejected")
|
||||
}
|
||||
|
||||
// 无扩展名 + JSON 内容 → 走 JSON
|
||||
rows, err = parseImportedOrderBytes([]byte(`[{"order_id":"o4"}]`), "noext")
|
||||
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o4" {
|
||||
t.Fatalf("parse noext json = %#v, %v", rows, err)
|
||||
}
|
||||
|
||||
// 无扩展名 + 非 JSON → 默认 CSV
|
||||
rows, err = parseImportedOrderBytes([]byte("order_id\no5\n"), "noext")
|
||||
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o5" {
|
||||
t.Fatalf("parse noext csv = %#v, %v", rows, err)
|
||||
}
|
||||
|
||||
// 表格只有表头 → 报错
|
||||
if _, err := parseImportedOrderBytes([]byte("order_id,amount\n"), "orders.csv"); err == nil {
|
||||
t.Fatal("header-only csv should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderImportRejectsTooManyRows(t *testing.T) {
|
||||
var b strings.Builder
|
||||
b.WriteString("order_id\n")
|
||||
for i := 0; i < maxOrderImportRows+1; i++ {
|
||||
_, _ = fmt.Fprintf(&b, "o%d\n", i)
|
||||
}
|
||||
if _, 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++ {
|
||||
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 {
|
||||
t.Fatal("too many JSON import rows should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseXLSXOrders 构造一个最小 xlsx,验证 shared string + 数字 cell 解析。
|
||||
func TestParseXLSXOrders(t *testing.T) {
|
||||
xlsx := buildMinimalXLSX(t, [][]string{{"order_id", "amount"}, {"o1", "12.5"}})
|
||||
rows, err := parseXLSXOrders(xlsx)
|
||||
if err != nil {
|
||||
t.Fatalf("parseXLSX: %v", err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0]["order_id"] != "o1" || rows[0]["amount"] != "12.5" {
|
||||
t.Fatalf("xlsx rows = %#v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLimitedXLSXXMLRejectsOversizedPart(t *testing.T) {
|
||||
_, err := readLimitedXLSXXML(io.LimitReader(endlessByteReader{}, maxXLSXXMLPartBytes+1))
|
||||
if err == nil {
|
||||
t.Fatal("oversized xlsx XML should fail")
|
||||
}
|
||||
}
|
||||
|
||||
type endlessByteReader struct{}
|
||||
|
||||
func (endlessByteReader) Read(p []byte) (int, error) {
|
||||
for i := range p {
|
||||
p[i] = 'x'
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// TestNormalizeImportHeader 表驱动验证中英文别名归一。
|
||||
func TestNormalizeImportHeader(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"订单号": "order_id",
|
||||
"OrderID": "order_id",
|
||||
"商品标题": "item_title",
|
||||
"商品名称": "item_title",
|
||||
"金额": "amount",
|
||||
"收货地址": "receiver_address",
|
||||
"chat_id": "chat_id",
|
||||
"会话id": "chat_id",
|
||||
"unknown_field": "unknown_field",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := normalizeImportHeader(in); got != want {
|
||||
t.Errorf("normalizeImportHeader(%q) = %q; want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// buildMinimalXLSX 构造一个仅含 sheet1 + sharedStrings 的最小 .xlsx 字节流。
|
||||
// cell 用 shared string(t="s")引用,与 Excel 默认导出一致。
|
||||
func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
|
||||
t.Helper()
|
||||
var shared []string
|
||||
sharedIdx := map[string]int{}
|
||||
addShared := func(s string) int {
|
||||
if i, ok := sharedIdx[s]; ok {
|
||||
return i
|
||||
}
|
||||
i := len(shared)
|
||||
shared = append(shared, s)
|
||||
sharedIdx[s] = i
|
||||
return i
|
||||
}
|
||||
|
||||
// 构造 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>`)
|
||||
for r, row := range grid {
|
||||
fmt.Fprintf(&rowsXML, `<row r="%d">`, r+1)
|
||||
for c, val := range row {
|
||||
ref := fmt.Sprintf("%c%d", 'A'+c, r+1)
|
||||
idx := addShared(val)
|
||||
fmt.Fprintf(&rowsXML, `<c r="%s" t="s"><v>%d</v></c>`, ref, idx)
|
||||
}
|
||||
rowsXML.WriteString(`</row>`)
|
||||
}
|
||||
rowsXML.WriteString(`</sheetData></worksheet>`)
|
||||
|
||||
var sstXML strings.Builder
|
||||
sstXML.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
|
||||
for _, s := range shared {
|
||||
sstXML.WriteString(`<si><t>` + s + `</t></si>`)
|
||||
}
|
||||
sstXML.WriteString(`</sst>`)
|
||||
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
must := func(name, content string) {
|
||||
f, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must("xl/sharedStrings.xml", sstXML.String())
|
||||
must("xl/worksheets/sheet1.xml", rowsXML.String())
|
||||
// ContentTypes / rels 不是解析必需,跳过。
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestPublishBatchPathAndZipSafety(t *testing.T) {
|
||||
for _, raw := range []string{"../secret.png", "/etc/passwd", `..\\secret.png`, ""} {
|
||||
if _, err := safeZipPath(raw); err == nil {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// 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}
|
||||
|
||||
// buildImageZip 构造含一张图片的 zip 字节流。
|
||||
func buildImageZip(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
f, _ := zw.Create("img/a.png")
|
||||
f.Write(minimalPNG)
|
||||
_ = zw.Close()
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// previewPublishBatch 构造一个预检批次(单行商品 + 1 张图片),返回 preview_id。
|
||||
func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
zipField.Write(buildImageZip(t))
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["valid"].(float64) != 1 {
|
||||
t.Fatalf("预检应 1 行有效,got %+v", res)
|
||||
}
|
||||
return res["preview_id"].(string)
|
||||
}
|
||||
|
||||
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
|
||||
// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。
|
||||
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 注入 mock mtop:所有请求返回非成功 ret(触发 PublishError)。
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"ret":["FAIL_SYS_PERMISSION::无发布权限"],"data":{}}`)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
batchID := previewPublishBatch(t, h, cookie)
|
||||
|
||||
// 启动批次。
|
||||
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
|
||||
startReq.AddCookie(cookie)
|
||||
startRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(startRec, startReq)
|
||||
if startRec.Code != 200 {
|
||||
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
|
||||
}
|
||||
|
||||
// 轮询批次状态,等待 running 结束(最多 5 秒)。
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
var status any
|
||||
for time.Now().Before(deadline) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
status = got["status"]
|
||||
if status != "running" {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if status == "running" {
|
||||
t.Fatal("批次应在 5s 内离开 running 状态")
|
||||
}
|
||||
|
||||
// 验证至少一行被标记 failed(或 completed)。
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if got["status"] == nil {
|
||||
t.Fatalf("批次详情异常: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunItemPublishBatch_Success 启动批次,mock mtop 全程返回 SUCCESS,验证行最终成功。
|
||||
func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
body := `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","itemUrl":"https://x/item/123456"}}`
|
||||
// 类目推荐接口需要返回 catId 才能继续后续步骤。
|
||||
if strings.Contains(req.URL.RawQuery, "recommend") || strings.Contains(req.URL.RawQuery, "category") {
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"catId":"100","categoryId":"100"}}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}, nil
|
||||
}))
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
batchID := previewPublishBatch(t, h, cookie)
|
||||
|
||||
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
|
||||
startReq.AddCookie(cookie)
|
||||
startRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(startRec, startReq)
|
||||
if startRec.Code != 200 {
|
||||
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
|
||||
}
|
||||
|
||||
// 轮询至完成。
|
||||
deadline := time.Now().Add(8 * time.Second)
|
||||
var status any
|
||||
for time.Now().Before(deadline) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
status = got["status"]
|
||||
if status != "running" {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if status == "running" {
|
||||
t.Fatal("批次应在 8s 内完成")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreatePublishAutomationRules 覆盖自动化规则创建(通过成功发布路径间接覆盖)。
|
||||
// 这里直接验证 runItemPublishBatch 在成功路径上调用了 createPublishAutomationRules。
|
||||
func TestCreatePublishAutomationRules(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
// 预置一个自动化规则配置的批次行,直接调 createPublishAutomationRules 验证不 panic + 写规则。
|
||||
// 先建一个卡密组供规则引用。
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡", Type: "text", TextContent: "K", Enabled: true, UserID: admin.ID})
|
||||
|
||||
// 通过 preview 建批次,再读出 row。
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
batchID := previewPublishBatchWithAutomation(t, h, cookie, cardID)
|
||||
_ = batchID
|
||||
}
|
||||
|
||||
// previewPublishBatchWithAutomation 构造带自动化配置的预检批次。
|
||||
func previewPublishBatchWithAutomation(t *testing.T, h http.Handler, cookie *http.Cookie, cardID int64) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csv := strings.Join([]string{
|
||||
"账号ID,标题,价格,库存,付款后发送的卡密",
|
||||
"acc1,商品A,12.50,5," + itoa(cardID) + ":1:0",
|
||||
"",
|
||||
}, "\n")
|
||||
csvField.Write([]byte(csv))
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
return res["preview_id"].(string)
|
||||
}
|
||||
|
||||
// 编译期保证 mtop 包引用。
|
||||
var _ = mtop.NewClient
|
||||
@@ -0,0 +1,532 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestParsePublishSheetBytes 表格解析各格式。
|
||||
func TestParsePublishSheetBytes(t *testing.T) {
|
||||
// CSV。
|
||||
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)
|
||||
}
|
||||
if rows[0]["cookie_id"] != "acc1" || rows[0]["title"] != "商品A" {
|
||||
t.Fatalf("row = %#v", rows[0])
|
||||
}
|
||||
|
||||
// TSV。
|
||||
rows, err = parsePublishSheetBytes([]byte("账号ID\t标题\nacc1\t商品B\n"), "p.tsv")
|
||||
if err != nil || len(rows) != 1 || rows[0]["title"] != "商品B" {
|
||||
t.Fatalf("tsv parse = %#v, %v", rows, err)
|
||||
}
|
||||
|
||||
// 空内容。
|
||||
if _, err := parsePublishSheetBytes([]byte(" \n"), "x.csv"); err == nil {
|
||||
t.Fatal("空内容应报错")
|
||||
}
|
||||
|
||||
// .xls 拒绝。
|
||||
if _, err := parsePublishSheetBytes([]byte("x"), "old.xls"); err == nil {
|
||||
t.Fatal(".xls 应被拒绝")
|
||||
}
|
||||
|
||||
// 仅表头。
|
||||
if _, err := parsePublishSheetBytes([]byte("账号ID,标题\n"), "x.csv"); err == nil {
|
||||
t.Fatal("仅表头应报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublishSheetBytesWithLimitRejectsTooManyRows(t *testing.T) {
|
||||
var b strings.Builder
|
||||
b.WriteString("账号ID,标题\n")
|
||||
for i := 0; i < 3; i++ {
|
||||
b.WriteString("acc1,商品\n")
|
||||
}
|
||||
if _, 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 := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
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}
|
||||
var zipBuf bytes.Buffer
|
||||
zw := zip.NewWriter(&zipBuf)
|
||||
f, _ := zw.Create("img/a.png")
|
||||
f.Write(png)
|
||||
_ = zw.Close()
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
zipField.Write(zipBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true || res["valid"] != float64(1) {
|
||||
t.Fatalf("预检异常: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchNoFile 缺表格文件 400。
|
||||
func TestPreviewItemPublishBatchNoFile(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺表格应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchBadDefaultCookie 默认账号不属于当前用户 403。
|
||||
func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "other-account")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("无权默认账号应 403,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchTooManyRows 超过最大行数 400。
|
||||
func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 构造 51 行 CSV。
|
||||
var csvBuf bytes.Buffer
|
||||
csvBuf.WriteString("账号ID,标题,价格,库存,图片\n")
|
||||
for i := 0; i < maxPublishBatchRows+1; i++ {
|
||||
csvBuf.WriteString("acc1,商品,12.50,5,a.png\n")
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write(csvBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("超行应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchZipTraversal zip 路径穿越拒绝 400。
|
||||
func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var zipBuf bytes.Buffer
|
||||
zw := zip.NewWriter(&zipBuf)
|
||||
f, _ := zw.Create("../escape.png")
|
||||
f.Write([]byte("x"))
|
||||
_ = zw.Close()
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,../escape.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
zipField.Write(zipBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("zip 穿越应 400,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetItemPublishBatchNotFound 不存在批次 404。
|
||||
func TestGetItemPublishBatchNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/no-such", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在批次应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCancelItemPublishBatchNotFound 不存在批次 404。
|
||||
func TestCancelItemPublishBatchNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/no-such/cancel", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在批次应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryFailedItemPublishBatchNotFound 不存在批次 404。
|
||||
func TestRetryFailedItemPublishBatchNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/no-such/retry-failed", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在批次应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadItemPublishBatchResultNotFound 不存在批次 404。
|
||||
func TestDownloadItemPublishBatchResultNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/no-such/result.csv", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在批次应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartItemPublishBatchBadJSON 非法 JSON 400。
|
||||
func TestStartItemPublishBatchBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartItemPublishBatchMissingPreviewID 缺 preview_id 400。
|
||||
func TestStartItemPublishBatchMissingPreviewID(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 preview_id 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartItemPublishBatchNotFound 不存在 404。
|
||||
func TestStartItemPublishBatchNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"no-such"}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteFileWithinRoot 写文件限制在根目录内。
|
||||
func TestWriteFileWithinRoot(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
if err := writeFileWithinRoot(dest, "file.txt", []byte("hello")); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dest, "file.txt"))
|
||||
if err != nil || string(data) != "hello" {
|
||||
t.Fatalf("read back: %v %q", err, data)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteFileWithinRootTraversal 路径穿越拒绝。
|
||||
func TestWriteFileWithinRootTraversal(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
if err := writeFileWithinRoot(dest, "../escape.txt", []byte("x")); err == nil {
|
||||
t.Fatal("路径穿越应拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadBatchImageFile 读取本地图片文件。
|
||||
func TestReadBatchImageFile(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
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 := readBatchImageFile(dest, "imgs/a.png")
|
||||
if err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
if len(data) == 0 || !strings.HasPrefix(ct, "image/") || name != "a.png" {
|
||||
t.Fatalf("read result异常: ct=%s name=%s", ct, name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadBatchImageFileNotFound 不存在图片报错。
|
||||
func TestReadBatchImageFileNotFound(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
if _, _, _, err := readBatchImageFile(dest, "no-such.png"); err == nil {
|
||||
t.Fatal("不存在应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadBatchImageFileTraversal 路径穿越拒绝。
|
||||
func TestReadBatchImageFileTraversal(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
if _, _, _, err := readBatchImageFile(dest, "../escape.png"); err == nil {
|
||||
t.Fatal("路径穿越应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateBatchImageRef 校验图片引用。
|
||||
func TestValidateBatchImageRef(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
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 {
|
||||
t.Fatalf("存在图片应通过: %v", err)
|
||||
}
|
||||
if err := validateBatchImageRef(dest, "no-such.png"); err == nil {
|
||||
t.Fatal("不存在应报错")
|
||||
}
|
||||
if err := validateBatchImageRef(dest, "https://example.com/a.png"); err != nil {
|
||||
t.Fatalf("HTTP URL 应直接通过: %v", err)
|
||||
}
|
||||
if err := validateBatchImageRef(dest, "../escape.png"); err == nil {
|
||||
t.Fatal("穿越应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsHTTPURL isHTTPURL 表驱动。
|
||||
func TestIsHTTPURL(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"http://x.com/a.png": true,
|
||||
"https://x.com/a.png": true,
|
||||
"HTTP://X.com/a.png": true,
|
||||
"ftp://x.com/a.png": false,
|
||||
"a.png": false,
|
||||
"": false,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := isHTTPURL(in); got != want {
|
||||
t.Errorf("isHTTPURL(%q)=%v want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPathBaseFromURL pathBaseFromURL 表驱动。
|
||||
func TestPathBaseFromURL(t *testing.T) {
|
||||
if got := pathBaseFromURL("https://example.com/path/a.png?x=1"); got != "a.png" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
// 仅 host 的 URL:base 为 host 名。
|
||||
if got := pathBaseFromURL("https://example.com/"); got != "example.com" {
|
||||
t.Fatalf("host-only base 异常: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSafeBaseName safeBaseName 表驱动。
|
||||
func TestSafeBaseName(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"normal.png": "normal.png",
|
||||
" trim.png ": "trim.png",
|
||||
"path/with/slash.png": "slash.png",
|
||||
"": "",
|
||||
".": "",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := safeBaseName(in); got != want {
|
||||
t.Errorf("safeBaseName(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRandomHex randomHex 长度。
|
||||
func TestRandomHex(t *testing.T) {
|
||||
if 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" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if 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 {
|
||||
t.Fatal("ftp 应报错")
|
||||
}
|
||||
if _, _, err := downloadImageURL(context.Background(), "not-a-url"); err == nil {
|
||||
t.Fatal("非 URL 应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadBatchPublishImagesBadJSON imagesJSON 非数组。
|
||||
func TestLoadBatchPublishImagesBadJSON(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
// ImagesJSON 非法 JSON。
|
||||
_, err := loadBatchPublishImages(context.Background(), dest, db.ItemPublishBatchRow{ImagesJSON: `not-json`})
|
||||
if err == nil {
|
||||
t.Fatal("非法 JSON 应报错")
|
||||
}
|
||||
// 空 refs。
|
||||
_, err = loadBatchPublishImages(context.Background(), dest, db.ItemPublishBatchRow{ImagesJSON: `[]`})
|
||||
if err == nil {
|
||||
t.Fatal("空 refs 应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookieOwnedByUser 归属判定。
|
||||
func TestCookieOwnedByUser(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if !srv.cookieOwnedByUser(ctx, 1, "acc1") {
|
||||
t.Fatal("acc1 应属于 user 1")
|
||||
}
|
||||
if srv.cookieOwnedByUser(ctx, 1, "no-such") {
|
||||
t.Fatal("不存在账号不应属于")
|
||||
}
|
||||
if srv.cookieOwnedByUser(ctx, 999, "acc1") {
|
||||
t.Fatal("不存在用户不应拥有")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCardOwnedByUser 卡密归属判定。
|
||||
func TestCardOwnedByUser(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO cards (name, type, user_id) VALUES ('卡1','text',1)`)
|
||||
if !srv.cardOwnedByUser(ctx, 1, 1) {
|
||||
t.Fatal("card 1 应属于 user 1")
|
||||
}
|
||||
if srv.cardOwnedByUser(ctx, 1, 999) {
|
||||
t.Fatal("card 999 不应存在")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookieValueForUser 取 cookie 值。
|
||||
func TestCookieValueForUser(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
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 {
|
||||
t.Fatal("不存在应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultPublishUploadRoot 默认上传根目录。
|
||||
func TestDefaultPublishUploadRoot(t *testing.T) {
|
||||
t.Setenv("XIANYU_UPLOAD_DIR", "")
|
||||
if got := defaultPublishUploadRoot(); got != filepath.Join("data", "uploads") {
|
||||
t.Fatalf("默认根目录异常: %q", got)
|
||||
}
|
||||
t.Setenv("XIANYU_UPLOAD_DIR", "/tmp/uploads")
|
||||
if got := defaultPublishUploadRoot(); got != "/tmp/uploads" {
|
||||
t.Fatalf("env 根目录异常: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGenerateQRLogin 生成扫码登录二维码。
|
||||
func TestGenerateQRLogin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckQRLoginStatusEmptySession 缺 session_id 400。
|
||||
func TestCheckQRLoginStatusEmptySession(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// chi 路由 /qr-login/check/{session_id};空 session 走不到 handler(404)。
|
||||
// 用一个不存在的 session 验证不 panic。
|
||||
req := httptest.NewRequest(http.MethodGet, "/qr-login/check/no-such-session", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompleteQRVerificationBadSession 不存在的 session 应返回失败响应(不 panic)。
|
||||
func TestCompleteQRVerificationBadSession(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/no-such-session", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != false {
|
||||
t.Fatalf("不存在的 session 应 success=false: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
|
||||
func TestKeywordsListAndDelete(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 添加(普通 + 带 item_id)。
|
||||
post := func(body string) {
|
||||
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("add keyword status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
post(`{"keyword":"在吗","reply":"在的"}`)
|
||||
post(`{"keyword":"价格","reply":"50元","item_id":"item1"}`)
|
||||
|
||||
for _, path := range []string{"/keywords/acc1", "/keywords-with-item-id/acc1", "/keywords-with-type/acc1"} {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("GET %s status=%d", path, rec.Code)
|
||||
}
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &arr)
|
||||
if len(arr) != 2 {
|
||||
t.Fatalf("%s 应2条,got %d", path, len(arr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddKeywordMissingKeyword 缺 keyword 400。
|
||||
func TestAddKeywordMissingKeyword(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(`{"reply":"x"}`))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺 keyword 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddKeywordBadJSON 非法 JSON 400。
|
||||
func TestAddKeywordBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteKeywordNotFound 不存在关键字 404。
|
||||
func TestDeleteKeywordNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/999", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在关键字应 404,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemRepliesCRUD 指定商品回复增删查。
|
||||
func TestItemRepliesCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-reply','商品R')`)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 设。
|
||||
body := `{"reply_content":"这是专属回复"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it-reply", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("set status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 查。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/it-reply", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("get status=%d", rec2.Code)
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &got)
|
||||
if got["reply_content"] != "这是专属回复" {
|
||||
t.Fatalf("回复内容异常: %+v", got)
|
||||
}
|
||||
|
||||
// 列表。
|
||||
req3 := httptest.NewRequest(http.MethodGet, "/itemReplays", nil)
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("list status=%d", rec3.Code)
|
||||
}
|
||||
|
||||
// 删除。
|
||||
req4 := httptest.NewRequest(http.MethodDelete, "/item-reply/acc1/it-reply", nil)
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
if rec4.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec4.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetItemReplyNotFound 不存在回复返回空。
|
||||
func TestGetItemReplyNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/no-such", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if got["reply_content"] != "" {
|
||||
t.Fatalf("不存在应返回空: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetItemReplyBadJSON 非法 JSON 400。
|
||||
func TestSetItemReplyBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。
|
||||
func freeAddr(t *testing.T) string {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
addr := l.Addr().String()
|
||||
l.Close()
|
||||
return addr
|
||||
}
|
||||
|
||||
// TestRun_ServesHealthAndShutdowns 启动 HTTP 服务,/health 可访问,ctx 取消后优雅退出。
|
||||
func TestRun_ServesHealthAndShutdowns(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Addr = freeAddr(t)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
runDone := make(chan error, 1)
|
||||
go func() { runDone <- srv.Run(ctx) }()
|
||||
|
||||
// 轮询 /health 直到可用(最多 3s)。
|
||||
url := "http://" + srv.Addr + "/health"
|
||||
var ok bool
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := http.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == 200 {
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if !ok {
|
||||
cancel()
|
||||
t.Fatal("Run 启动后 /health 3s 内不可访问")
|
||||
}
|
||||
|
||||
// 取消 ctx → Run 应优雅退出。
|
||||
cancel()
|
||||
select {
|
||||
case err := <-runDone:
|
||||
if err != nil {
|
||||
t.Fatalf("Run 应返回 nil,got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run 未在 ctx 取消后 5s 内退出")
|
||||
}
|
||||
}
|
||||
+27
-15
@@ -28,23 +28,25 @@ import (
|
||||
"xianyu-go/internal/xianyu/qrlogin"
|
||||
)
|
||||
|
||||
// Server 聚合 HTTP 服务依赖。
|
||||
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
|
||||
// 不再允许外部直接改字段,避免运行时被替换成 nil。
|
||||
type Server struct {
|
||||
Store *db.Store
|
||||
Auth *auth.Service
|
||||
Manager *account.Manager
|
||||
Automation *automation.Center
|
||||
automation *automation.Center
|
||||
Browser *browser.Manager
|
||||
Notifier *notify.Notifier
|
||||
MTop *mtop.Client
|
||||
notifier *notify.Notifier
|
||||
MTop mtop.Client
|
||||
QRLogin *qrlogin.Manager
|
||||
Logger *slog.Logger
|
||||
WebDir string // 前端静态资源目录(含 index.html)
|
||||
Addr string
|
||||
}
|
||||
|
||||
// New 构造。bm 为浏览器管理器(风控验证后用浏览器提取 cookie;为 nil 则禁用浏览器自动化)。
|
||||
func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure bool, webDir, addr string, logger *slog.Logger) *Server {
|
||||
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
|
||||
// adapter → manager → automation → notifier → server)。
|
||||
func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
|
||||
if logger == nil {
|
||||
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
|
||||
}
|
||||
@@ -55,18 +57,28 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
|
||||
})
|
||||
}
|
||||
return &Server{
|
||||
Store: store,
|
||||
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
|
||||
Manager: manager,
|
||||
Browser: bm,
|
||||
MTop: &mtop.Client{},
|
||||
QRLogin: qrMgr,
|
||||
Logger: logger,
|
||||
WebDir: webDir,
|
||||
Addr: addr,
|
||||
Store: store,
|
||||
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
|
||||
Manager: manager,
|
||||
automation: autoCenter,
|
||||
Browser: bm,
|
||||
notifier: notifier,
|
||||
MTop: mtop.NewClient(),
|
||||
QRLogin: qrMgr,
|
||||
Logger: logger,
|
||||
WebDir: webDir,
|
||||
Addr: addr,
|
||||
}
|
||||
}
|
||||
|
||||
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
|
||||
func (s *Server) mtopClient() mtop.Client {
|
||||
if s.MTop != nil {
|
||||
return s.MTop
|
||||
}
|
||||
return mtop.NewClient()
|
||||
}
|
||||
|
||||
// Router 构建完整路由树。
|
||||
func (s *Server) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
|
||||
@@ -31,8 +32,9 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
|
||||
store.Cookies.Save(context.Background(), "acc1", "unb=123; _m_h5_tk=tk1_1;", admin.ID)
|
||||
|
||||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||||
srv := New(store, mgr, nil, false, "", ":0", nil)
|
||||
srv.MTop.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
srv := New(store, mgr, nil, false, "", ":0", nil, nil, nil)
|
||||
mtopClient := mtop.NewClient()
|
||||
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
@@ -42,6 +44,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
srv.MTop = mtopClient
|
||||
return srv, store, func() { d.Close() }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestListAIModels 通过 mock OpenAI 端点返回模型列表。
|
||||
func TestListAIModels(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 注入一个本地 HTTP server 作为 ai_api_url。
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"qwen-plus"},{"id":"qwen-max"}]}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"base_url":"` + ts.URL + `","api_key":"sk-test"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
models, _ := res["models"].([]any)
|
||||
if len(models) != 2 {
|
||||
t.Fatalf("应2个模型,got %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOpenAIModelsBodyRejectsOversizedResponse(t *testing.T) {
|
||||
_, err := readOpenAIModelsBody(strings.NewReader(strings.Repeat("x", maxOpenAIModelsResponseBytes+1)))
|
||||
if err == nil {
|
||||
t.Fatal("oversized models response should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// TestListAIModelsBadJSON 非法 JSON 400。
|
||||
func TestListAIModelsBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListAIModelsEmptyBaseURL 空地址使用默认并失败(默认阿里云地址不可达或返回非 2xx)。
|
||||
func TestListAIModelsEmptyBaseURL(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// 注入一个返回错误状态码的本地 server。
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer ts.Close()
|
||||
// 设置系统设置 ai_api_url 指向该 server。
|
||||
srv.Store.Settings.Set(context.Background(), "ai_api_url", ts.URL)
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("模型拉取失败应 502,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetSettingBadJSON 非法 JSON 400。
|
||||
func TestSetSettingBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemSettingsRequireAdmin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
if _, err := srv.Store.Users.Create(context.Background(), "user-settings", "[email protected]", "pw"); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
|
||||
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"user-settings","password":"pw"}`))
|
||||
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 := loginRec.Result().Cookies()[0]
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
}{
|
||||
{http.MethodGet, "/system-settings", ""},
|
||||
{http.MethodPut, "/system-settings/theme_color", `{"value":"red"}`},
|
||||
{http.MethodPost, "/ai-models", `{"base_url":"http://127.0.0.1","api_key":"sk"}`},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s %s should be 403, got %d body=%s", tc.method, tc.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestListUserSettings 用户设置增删查。
|
||||
func TestListUserSettings(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 设。
|
||||
body := `{"value":"dark"}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("set status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 查全部。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("list status=%d", rec2.Code)
|
||||
}
|
||||
var m map[string]string
|
||||
json.Unmarshal(rec2.Body.Bytes(), &m)
|
||||
if m["theme"] != "dark" {
|
||||
t.Fatalf("设置未生效: %+v", m)
|
||||
}
|
||||
|
||||
// 查单。
|
||||
req3 := httptest.NewRequest(http.MethodGet, "/user-settings/theme", nil)
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
var one map[string]any
|
||||
json.Unmarshal(rec3.Body.Bytes(), &one)
|
||||
if one["value"] != "dark" {
|
||||
t.Fatalf("查单异常: %+v", one)
|
||||
}
|
||||
|
||||
// 查不存在的 key。
|
||||
req4 := httptest.NewRequest(http.MethodGet, "/user-settings/no-such-key", nil)
|
||||
req4.AddCookie(cookie)
|
||||
rec4 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec4, req4)
|
||||
var miss map[string]any
|
||||
json.Unmarshal(rec4.Body.Bytes(), &miss)
|
||||
if miss["value"] != "" {
|
||||
t.Fatalf("不存在 key 应返回空: %+v", miss)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetUserSettingBadJSON 非法 JSON 400。
|
||||
func TestSetUserSettingBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetAIReplyBadJSON 非法 JSON 400。
|
||||
func TestSetAIReplyBadJSON(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader("not-json"))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAIReplyNotFound 不存在账号返回默认值。
|
||||
func TestGetAIReplyNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/no-such", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["ai_enabled"] != false || res["max_discount_percent"] != float64(10) {
|
||||
t.Fatalf("默认值异常: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIReplySettingsAreUserScoped(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "user2", "[email protected]", "pw"); err != nil {
|
||||
t.Fatalf("create user2: %v", 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 {
|
||||
t.Fatalf("save other cookie: %v", err)
|
||||
}
|
||||
if _, 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 := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
listReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil)
|
||||
listReq.AddCookie(cookie)
|
||||
listRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(listRec, listReq)
|
||||
if listRec.Code != http.StatusOK {
|
||||
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
|
||||
}
|
||||
var listed map[string]any
|
||||
if err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
|
||||
t.Fatalf("decode list: %v", err)
|
||||
}
|
||||
if _, ok := listed["other-acc"]; ok {
|
||||
t.Fatalf("list leaked other user's AI settings: %+v", listed)
|
||||
}
|
||||
|
||||
getReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/other-acc", nil)
|
||||
getReq.AddCookie(cookie)
|
||||
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 := 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 := httptest.NewRecorder()
|
||||
h.ServeHTTP(setRec, setReq)
|
||||
if setRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-user set should be 403, got %d body=%s", setRec.Code, setRec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOpenAIModelsEmptyBaseURL 空地址错误。
|
||||
func TestFetchOpenAIModelsEmptyBaseURL(t *testing.T) {
|
||||
_, err := fetchOpenAIModels(context.Background(), "", "")
|
||||
if err == nil {
|
||||
t.Fatal("空地址应报错")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -15,16 +16,21 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
const maxOpenAIModelsResponseBytes = 4 << 20
|
||||
|
||||
// authSess 从上下文取会话。
|
||||
func authSess(r *http.Request) *db.Session {
|
||||
return auth.SessionFromContext(r.Context())
|
||||
}
|
||||
|
||||
// mountSettingsReal 系统设置端点(已认证)。public 单独挂载在顶层。
|
||||
// mountSettingsReal 系统设置端点(管理员专用)。public 单独挂载在顶层。
|
||||
func (s *Server) mountSettingsReal(r chi.Router) {
|
||||
r.Get("/system-settings", s.allSettings)
|
||||
r.Put("/system-settings/{key}", s.setSetting)
|
||||
r.Post("/ai-models", s.listAIModels)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(auth.RequireAdmin)
|
||||
r.Get("/system-settings", s.allSettings)
|
||||
r.Put("/system-settings/{key}", s.setSetting)
|
||||
r.Post("/ai-models", s.listAIModels)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -70,10 +76,13 @@ func (s *Server) mountAIReplyReal(r chi.Router) {
|
||||
}
|
||||
|
||||
func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT cookie_id, ai_enabled, max_discount_percent, max_discount_amount,
|
||||
max_bargain_rounds, COALESCE(custom_prompts, '')
|
||||
FROM ai_reply_settings`)
|
||||
`SELECT a.cookie_id, a.ai_enabled, a.max_discount_percent, a.max_discount_amount,
|
||||
a.max_bargain_rounds, COALESCE(a.custom_prompts, '')
|
||||
FROM ai_reply_settings a
|
||||
JOIN cookies c ON c.id=a.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -97,13 +106,35 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
"custom_prompts": customPrompts,
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
|
||||
if err != nil {
|
||||
if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ai_enabled": false,
|
||||
"max_discount_percent": 10,
|
||||
@@ -136,17 +167,20 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO ai_reply_settings
|
||||
(cookie_id, ai_enabled, max_discount_percent, max_discount_amount,
|
||||
max_bargain_rounds, custom_prompts, updated_at)
|
||||
VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"ai_enabled": "EXCLUDED.ai_enabled",
|
||||
"max_discount_percent": "EXCLUDED.max_discount_percent",
|
||||
"max_discount_amount": "EXCLUDED.max_discount_amount",
|
||||
"max_bargain_rounds": "EXCLUDED.max_bargain_rounds",
|
||||
"custom_prompts": "EXCLUDED.custom_prompts",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
"ai_enabled": "EXCLUDED.ai_enabled",
|
||||
"max_discount_percent": "EXCLUDED.max_discount_percent",
|
||||
"max_discount_amount": "EXCLUDED.max_discount_amount",
|
||||
"max_bargain_rounds": "EXCLUDED.max_bargain_rounds",
|
||||
"custom_prompts": "EXCLUDED.custom_prompts",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cid, btoi(req.AIEnabled), req.MaxDiscountPercent, req.MaxDiscountAmount,
|
||||
req.MaxBargainRounds, nullIfEmpty(req.CustomPrompts))
|
||||
@@ -215,7 +249,7 @@ func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, e
|
||||
return nil, fmt.Errorf("读取模型失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
raw, err := readOpenAIModelsBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -232,6 +266,17 @@ func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, e
|
||||
return models, nil
|
||||
}
|
||||
|
||||
func readOpenAIModelsBody(r io.Reader) ([]byte, error) {
|
||||
raw, err := io.ReadAll(io.LimitReader(r, maxOpenAIModelsResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) > maxOpenAIModelsResponseBytes {
|
||||
return nil, fmt.Errorf("模型列表响应超过 %d MiB", maxOpenAIModelsResponseBytes>>20)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func parseOpenAIModels(raw []byte) ([]string, error) {
|
||||
var payload any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
@@ -300,6 +345,10 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
|
||||
m[k] = v
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package server
|
||||
|
||||
import "io"
|
||||
|
||||
func readLimitedBytes(r io.Reader, maxBytes int64) ([]byte, bool, error) {
|
||||
data, err := io.ReadAll(io.LimitReader(r, maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if int64(len(data)) > maxBytes {
|
||||
return nil, true, nil
|
||||
}
|
||||
return data, false, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package server
|
||||
|
||||
// 上传请求体大小上限。MaxBytesReader 必须在 ParseMultipartForm 之前应用到 r.Body。
|
||||
// 各值按对应业务场景的实际上限设定,#nosec G120 注释保留在各调用处。
|
||||
|
||||
const (
|
||||
// maxCardBatchUploadBytes 卡密组批量上传表格上限:5 MiB(卡密组定义都很小)。
|
||||
maxCardBatchUploadBytes = 6 << 20
|
||||
// maxOrderImportBytes 订单导入文件/请求体上限:32 MiB。
|
||||
maxOrderImportBytes = 32 << 20
|
||||
// maxOrderImportRows 单次订单导入最多订单数。
|
||||
maxOrderImportRows = 5000
|
||||
// maxItemPublishBytes 单品发布上限:9 张 10 MiB 图片 + multipart 元数据。
|
||||
maxItemPublishBytes = 96 << 20
|
||||
// maxItemPublishBatchBytes 批量发布上传上限:20 MiB 表格 + 200 MiB 图片压缩包 + multipart 元数据。
|
||||
maxItemPublishBatchBytes = 224 << 20
|
||||
// maxItemPublishBatchParseBytes 批量发布 multipart 解析上限(含图片压缩包解压缓冲)。
|
||||
maxItemPublishBatchParseBytes = 256 << 20
|
||||
// maxItemPublishZipFiles 批量发布图片 zip 内最多文件数。
|
||||
maxItemPublishZipFiles = 500
|
||||
// maxItemPublishZipExtractBytes 批量发布图片 zip 总解压上限。
|
||||
maxItemPublishZipExtractBytes = 500 << 20
|
||||
// maxXLSXXMLPartBytes xlsx 内 worksheet/sharedStrings 单个 XML 解压上限。
|
||||
maxXLSXXMLPartBytes = 32 << 20
|
||||
)
|
||||
Reference in new issue
Block a user