Files
yhy-mager/backend/internal/httpapi/suffixes_test.go
lianjianwei2024 2d9dcba800 feat: refine suffix management layout and column ordering
- column sort dialog: reorder via arrows (persisted via new
  POST /dirs/:id/columns/order), precise column insertion after a
  selected position (create column accepts after_id), value columns
  shown in blue text inside the dialog
- workspace cells: edit only after entering the row's 编辑 mode,
  then double-click the cell (matching legacy interaction)
- collapsible global sidebar with edge handle (state persisted);
  suffix panel directory collapses independently; independent
  scrollbars for directory and workspace; 5px gap to the sidebar
- suffix page drops the internal-console heading block and the
  内部管理台 topbar label; 退出 moves to the sidebar footer
  (same line as the admin email, 5px from the edge); brand subtitle
  统一授权管理平台 removed
- integration test covers column reorder/precise insert/dedupe
2026-10-30 13:20:12 +08:00

277 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"bytes"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
// 后缀管理全链路:分组/后缀/目录树/列(值设置)/单元格/锚定/模板上传下载删除。
// 需要真实 MySQL:MYSQL_TEST_DSN 未设置时跳过(与 business_integration_test 同口径)。
func TestSuffixAdminIntegration(t *testing.T) {
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN is not set")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = db.Ping(); err != nil {
t.Fatal(err)
}
for _, table := range []string{"suffix_files", "suffix_dir_anchors", "suffix_cells", "suffix_columns", "suffixes", "suffix_groups", "suffix_dirs"} {
if _, err = db.Exec("DELETE FROM " + table); err != nil {
t.Fatalf("清理 %s: %v", table, err)
}
}
// 只清测试自己的管理员与会话,绝不动共享开发库里的真实账号。
if _, err = db.Exec("DELETE FROM sessions WHERE admin_id IN (SELECT id FROM admins WHERE username='suffixtest')"); err != nil {
t.Fatalf("清理测试会话: %v", err)
}
if _, err = db.Exec("DELETE FROM admins WHERE username='suffixtest'"); err != nil {
t.Fatalf("清理测试管理员: %v", err)
}
if _, err = db.Exec("INSERT INTO suffix_dirs(parent_id,name,sort_order) VALUES(NULL,'按信息价的目录',0)"); err != nil {
t.Fatalf("播种根目录: %v", err)
}
hash, _ := bcrypt.GenerateFromPassword([]byte("test-pass-123"), bcrypt.DefaultCost)
if _, err = db.Exec("INSERT INTO admins(username,email,password_hash,role,active) VALUES('suffixtest','suffixtest@local.dev',?,'admin',1)", string(hash)); err != nil {
t.Fatalf("建管理员: %v", err)
}
router := NewRouter()
RegisterBusiness(router, db)
t.Setenv("PACKAGE_STORAGE_ROOT", t.TempDir())
do := func(method, path, body string) *httptest.ResponseRecorder {
var reader *strings.Reader
if body == "" {
reader = strings.NewReader("")
} else {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
// 登录拿会话
w := do(http.MethodPost, "/api/v1/auth/login", `{"username":"suffixtest","password":"test-pass-123"}`)
if w.Code != 200 {
t.Fatalf("登录 status=%d body=%s", w.Code, w.Body.String())
}
cookie := ""
for _, c := range w.Result().Cookies() {
if c.Name == "lp_session" {
cookie = c.Name + "=" + c.Value
}
}
if cookie == "" {
t.Fatal("登录未返回会话 Cookie")
}
authed := func(method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
getJSON := func(w *httptest.ResponseRecorder) map[string]any {
var out map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatalf("响应不是 JSON: %s", w.Body.String())
}
return out
}
// 未登录应 401
if w = do(http.MethodGet, "/api/v1/suffix-admin/tree", ""); w.Code != 401 {
t.Fatalf("未登录访问 tree status=%d, want 401", w.Code)
}
// 分组 + 后缀
w = authed(http.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广东省"}`)
if w.Code != 201 {
t.Fatalf("建分组 status=%d body=%s", w.Code, w.Body.String())
}
groupID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广东省"}`)
if w.Code != 409 {
t.Fatalf("重名分组 status=%d, want 409", w.Code)
}
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d}`, groupID))
if w.Code != 201 {
t.Fatalf("建后缀 status=%d body=%s", w.Code, w.Body.String())
}
suffixID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPut, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d", suffixID), `{"name":"cos4"}`)
if w.Code != 200 {
t.Fatalf("改后缀名 status=%d body=%s", w.Code, w.Body.String())
}
// 目录树:根 + 子目录 + 改名 + 删除保护
w = authed(http.MethodGet, "/api/v1/suffix-admin/tree", "")
dirs := getJSON(w)["data"].(map[string]any)["dirs"].([]any)
root := dirs[0].(map[string]any)
rootID := uint64(root["id"].(float64))
if root["name"] != "按信息价的目录" {
t.Fatalf("根目录名=%v", root["name"])
}
w = authed(http.MethodPost, "/api/v1/suffix-admin/dirs", fmt.Sprintf(`{"parent_id":%d,"name":"一、黑色及有色"}`, rootID))
if w.Code != 201 {
t.Fatalf("建子目录 status=%d body=%s", w.Code, w.Body.String())
}
dirID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, "/api/v1/suffix-admin/dirs", fmt.Sprintf(`{"parent_id":0,"name":"第二个根"}`))
if w.Code != 403 {
t.Fatalf("建第二根 status=%d, want 403", w.Code)
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", rootID), "")
if w.Code != 403 {
t.Fatalf("删根 status=%d, want 403", w.Code)
}
// 列(值设置勾选)+ 单元格 + 锚定
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
if w.Code != 201 {
t.Fatalf("建普通列 status=%d body=%s", w.Code, w.Body.String())
}
plainColID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"工料机类型","is_value":true}`)
if w.Code != 201 {
t.Fatalf("建值列 status=%d body=%s", w.Code, w.Body.String())
}
valueColID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
if w.Code != 409 {
t.Fatalf("同目录重名列 status=%d, want 409", w.Code)
}
// 精准插入:插到 招标人 之后
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID),
fmt.Sprintf(`{"name":"插队列","is_value":false,"after_id":%d}`, plainColID))
if w.Code != 201 {
t.Fatalf("精准插列 status=%d body=%s", w.Code, w.Body.String())
}
insertedID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
pageCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
if pageCols[1].(map[string]any)["id"].(float64) != float64(insertedID) {
t.Fatal("精准插列应落在 招标人 之后(第2位)")
}
// 列排序:插队列移回末位 → 顺序变为 招标人,工料机类型,插队列
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
fmt.Sprintf(`{"ids":[%d,%d,%d]}`, plainColID, valueColID, insertedID))
if w.Code != 200 {
t.Fatalf("列排序 status=%d body=%s", w.Code, w.Body.String())
}
// 漏传列:没传的按原顺序补到末尾 → 顺序不变(招标人,工料机类型,插队列)
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
fmt.Sprintf(`{"ids":[%d,%d]}`, plainColID, valueColID))
if w.Code != 200 {
t.Fatalf("漏传列补尾 status=%d body=%s", w.Code, w.Body.String())
}
// 外列 → 404
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
`{"ids":[999999]}`)
if w.Code != 404 {
t.Fatalf("外列 status=%d, want 404", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
orderedCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
if orderedCols[0].(map[string]any)["name"] != "招标人" || orderedCols[1].(map[string]any)["name"] != "工料机类型" || orderedCols[2].(map[string]any)["name"] != "插队列" {
t.Fatalf("排序后顺序不符: %v", orderedCols)
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/cells",
fmt.Sprintf(`{"dir_id":%d,"suffix_id":%d,"column_id":%d,"value":"普通文本"}`, dirID, suffixID, plainColID))
if w.Code == 404 || w.Code == 400 {
t.Fatalf("存普通单元格被拒 status=%d body=%s", w.Code, w.Body.String())
}
// 工作区载荷
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
page := getJSON(w)["data"].(map[string]any)
cols := page["columns"].([]any)
if len(cols) != 3 {
t.Fatalf("列数=%d, want 3", len(cols))
}
// 排序后顺序:招标人,工料机类型,插队列;第二列=值列
if !cols[1].(map[string]any)["is_value"].(bool) {
t.Fatal("第二列应为值列")
}
// 锚定开与关
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
fmt.Sprintf(`{"suffix_id":%d,"on":true}`, suffixID))
if w.Code != 200 {
t.Fatalf("锚定 status=%d", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
sfx := getJSON(w)["data"].(map[string]any)["suffixes"].([]any)
if !sfx[0].(map[string]any)["anchor"].(bool) {
t.Fatal("锚定后 anchor 应为 true")
}
// 模板上传(内容与哈希校验)→ 概览 → 删除
content := []byte("COS4-skeleton-demo")
sum := sha256.Sum256(content)
b64 := base64.StdEncoding.EncodeToString(content)
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
fmt.Sprintf(`{"file_name":"骨架.cos4","size":%d,"sha256":"%s","content_base64":"%s"}`,
len(content), hex.EncodeToString(sum[:]), b64))
if w.Code != 201 {
t.Fatalf("传模板 status=%d body=%s", w.Code, w.Body.String())
}
fileID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
badSum := sha256.Sum256([]byte("tampered"))
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
fmt.Sprintf(`{"file_name":"坏.cos4","size":%d,"sha256":"%s","content_base64":"%s"}`,
len(content), hex.EncodeToString(badSum[:]), b64))
if w.Code != 400 {
t.Fatalf("哈希不符 status=%d, want 400", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/files/%d/download", fileID), "")
if w.Code != 200 || !bytes.Contains(w.Body.Bytes(), content) {
t.Fatalf("下载 status=%d body=%q", w.Code, w.Body.String())
}
w = authed(http.MethodGet, "/api/v1/suffix-admin/overview", "")
groups := getJSON(w)["data"].(map[string]any)["groups"].([]any)
files := groups[0].(map[string]any)["suffixes"].([]any)[0].(map[string]any)["files"].([]any)
if len(files) != 1 {
t.Fatalf("概览文件数=%d, want 1", len(files))
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/files/%d", fileID), "")
if w.Code != 200 {
t.Fatalf("删模板 status=%d", w.Code)
}
// 删目录(级联)与删分组(级联文件)
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", dirID), "")
if w.Code != 200 {
t.Fatalf("删目录 status=%d", w.Code)
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/groups/%d", groupID), "")
if w.Code != 200 {
t.Fatalf("删分组 status=%d", w.Code)
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM suffix_files").Scan(&count); err != nil || count != 0 {
t.Fatalf("文件残留 count=%d err=%v", count, err)
}
}