From dd9d5470c2a3f16a70d8462040c4398a421569de Mon Sep 17 00:00:00 2001 From: lianjianwei2024 <168657369+lianjianwei2024@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:32:22 +0800 Subject: [PATCH] feat: add suffix management module under business admin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - migration 000017: suffix_dirs tree (info-price style, two-root sidebar), suffix_groups, suffixes, per-directory columns with value flag, cells, row anchors and template files (stored under PACKAGE_STORAGE_ROOT) - Go API /api/v1/suffix-admin/*: tree/page/CRUD/reorder for dirs, groups, suffixes and columns; cell upsert; anchor toggle; template upload with sha256 verification, scoped download/delete; admin session required - RequiredSchemaVersion 16 -> 17 - Vue panel /suffixes (menu below payment plans): two roots (basic setup + info-price directory tree), grouped suffix sheet with template upload, add-column dialog with 值设置 checkbox (value cells store {anchor,value}); removed attribute-table/field-mapping/column-sort/value-setting toolbar - tests: integration test (MYSQL_TEST_DSN gated) + 3 vitest cases --- backend/internal/httpapi/business.go | 1 + backend/internal/httpapi/readiness.go | 2 +- backend/internal/httpapi/suffixes.go | 954 ++++++++++++++++++ backend/internal/httpapi/suffixes_test.go | 239 +++++ .../000017_suffix_management.down.sql | 7 + .../000017_suffix_management.up.sql | 68 ++ frontend/src/router.ts | 2 +- frontend/src/suffix-admin.ts | 70 ++ frontend/src/views/Overview.vue | 8 +- frontend/src/views/SuffixPanel.test.ts | 112 ++ frontend/src/views/SuffixPanel.vue | 688 +++++++++++++ 11 files changed, 2146 insertions(+), 5 deletions(-) create mode 100644 backend/internal/httpapi/suffixes.go create mode 100644 backend/internal/httpapi/suffixes_test.go create mode 100644 backend/migrations/000017_suffix_management.down.sql create mode 100644 backend/migrations/000017_suffix_management.up.sql create mode 100644 frontend/src/suffix-admin.ts create mode 100644 frontend/src/views/SuffixPanel.test.ts create mode 100644 frontend/src/views/SuffixPanel.vue diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index 69973a2..14c374b 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -98,6 +98,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { purchaseAdmin.POST("/purchase-credentials", a.createPurchaseCredential) purchaseAdmin.PUT("/purchase-credentials/:id", a.updatePurchaseCredential) secured := api.Group("", a.authenticated) + registerSuffixRoutes(secured, a) secured.GET("/me", a.me) secured.GET("/admins", a.listAdmins) secured.POST("/admins", a.createAdmin) diff --git a/backend/internal/httpapi/readiness.go b/backend/internal/httpapi/readiness.go index 52ef8de..a640cf4 100644 --- a/backend/internal/httpapi/readiness.go +++ b/backend/internal/httpapi/readiness.go @@ -9,7 +9,7 @@ import ( "github.com/gin-gonic/gin" ) -const RequiredSchemaVersion = 16 +const RequiredSchemaVersion = 17 func RegisterReadiness(r *gin.Engine, db *sql.DB) { r.GET("/api/v1/health/ready", func(c *gin.Context) { diff --git a/backend/internal/httpapi/suffixes.go b/backend/internal/httpapi/suffixes.go new file mode 100644 index 0000000..1715f85 --- /dev/null +++ b/backend/internal/httpapi/suffixes.go @@ -0,0 +1,954 @@ +package httpapi + +import ( + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "unicode/utf8" + + "github.com/gin-gonic/gin" +) + +// 后缀管理(业务管理 → 后缀管理):目录树(两根之一「按信息价的目录」)、 +// 省份分组、后缀、每目录自定义列(可带值设置)、单元格值、锚定行、模板文件。 + +const ( + suffixFileNameMax = 255 + suffixCellValueMax = 2000 + suffixUploadMax = 128 << 20 // 128MB,解码前 base64 长度上限 +) + +var suffixBadNameRe = regexp.MustCompile(`[\\/:*?"<>|\x00-\x1f]`) + +func registerSuffixRoutes(secured *gin.RouterGroup, a *BusinessAPI) { + s := secured.Group("/suffix-admin") + s.GET("/tree", a.suffixTree) + s.POST("/dirs", a.createSuffixDir) + s.PUT("/dirs/:id", a.renameSuffixDir) + s.POST("/dirs/:id/move", a.moveSuffixDir) + s.DELETE("/dirs/:id", a.deleteSuffixDir) + s.GET("/dirs/:id/page", a.suffixDirPage) + s.POST("/dirs/:id/columns", a.createSuffixColumn) + s.POST("/dirs/:id/anchor", a.setSuffixAnchor) + s.DELETE("/columns/:id", a.deleteSuffixColumn) + s.PUT("/cells", a.saveSuffixCell) + s.GET("/overview", a.suffixOverview) + s.POST("/groups", a.createSuffixGroup) + s.PUT("/groups/:id", a.renameSuffixGroup) + s.POST("/groups/:id/move", a.moveSuffixGroup) + s.DELETE("/groups/:id", a.deleteSuffixGroup) + s.POST("/suffixes", a.createSuffix) + s.PUT("/suffixes/:id", a.renameSuffix) + s.POST("/suffixes/:id/move", a.moveSuffix) + s.DELETE("/suffixes/:id", a.deleteSuffix) + s.POST("/suffixes/:id/files", a.uploadSuffixFile) + s.DELETE("/files/:id", a.deleteSuffixFile) + s.GET("/files/:id/download", a.downloadSuffixFile) +} + +func suffixTrimName(raw string, max int) (string, bool) { + name := strings.TrimSpace(raw) + return name, name != "" && utf8.RuneCountInString(name) <= max +} + +const suffixRootNameValue = "按信息价的目录" + +// ---- 目录树 ---- + +type suffixDirRow struct { + ID uint64 `json:"id"` + ParentID uint64 `json:"parent_id"` + Name string `json:"name"` + SortOrder int `json:"sort_order"` + Children int `json:"children"` +} + +func (a *BusinessAPI) suffixTree(c *gin.Context) { + rows, err := a.db.QueryContext(c, + "SELECT id,COALESCE(parent_id,0),name,sort_order FROM suffix_dirs ORDER BY sort_order ASC,id ASC") + if err != nil { + apiError(c, 500, "internal_error", "目录加载失败") + return + } + defer rows.Close() + dirs := []suffixDirRow{} + byID := map[uint64]int{} + for rows.Next() { + var r suffixDirRow + if err := rows.Scan(&r.ID, &r.ParentID, &r.Name, &r.SortOrder); err != nil { + apiError(c, 500, "internal_error", "目录加载失败") + return + } + dirs = append(dirs, r) + byID[r.ID] = len(dirs) - 1 + } + if err := rows.Err(); err != nil { + apiError(c, 500, "internal_error", "目录加载失败") + return + } + for i := range dirs { + if p, ok := byID[dirs[i].ParentID]; ok { + dirs[p].Children++ + } + } + if len(dirs) > 0 { + dirs[0].Name = suffixRootNameValue + } + c.JSON(200, gin.H{"data": gin.H{"dirs": dirs}}) +} + +func (a *BusinessAPI) dirExists(c *gin.Context, id uint64) bool { + var one int + return a.db.QueryRowContext(c, "SELECT 1 FROM suffix_dirs WHERE id=?", id).Scan(&one) == nil +} + +func (a *BusinessAPI) createSuffixDir(c *gin.Context) { + var in struct { + ParentID uint64 `json:"parent_id"` + Name string `json:"name"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name, ok := suffixTrimName(in.Name, 190) + if !ok { + apiError(c, 400, "invalid_request", "目录名须为 1–190 字") + return + } + if in.ParentID == 0 { + apiError(c, 403, "forbidden", "只能建在「按信息价的目录」之内") + return + } + if !a.dirExists(c, in.ParentID) { + apiError(c, 404, "not_found", "上级目录不存在") + return + } + var order sql.NullInt64 + _ = a.db.QueryRowContext(c, + "SELECT MAX(sort_order) FROM suffix_dirs WHERE parent_id=?", in.ParentID).Scan(&order) + res, err := a.db.ExecContext(c, + "INSERT INTO suffix_dirs(parent_id,name,sort_order) VALUES(?,?,?)", + in.ParentID, name, order.Int64+1) + if err != nil { + apiError(c, 500, "internal_error", "目录创建失败") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{"id": id, "parent_id": in.ParentID, "name": name, "children": 0}}) +} + +func (a *BusinessAPI) dirIsRoot(c *gin.Context, id uint64) bool { + var parent sql.NullInt64 + if err := a.db.QueryRowContext(c, "SELECT parent_id FROM suffix_dirs WHERE id=?", id).Scan(&parent); err != nil { + return false + } + return !parent.Valid +} + +func (a *BusinessAPI) renameSuffixDir(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + if a.dirIsRoot(c, id) { + apiError(c, 403, "forbidden", "根目录名称固定,不能改名") + return + } + var in struct { + Name string `json:"name"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name, ok := suffixTrimName(in.Name, 190) + if !ok { + apiError(c, 400, "invalid_request", "目录名须为 1–190 字") + return + } + res, err := a.db.ExecContext(c, "UPDATE suffix_dirs SET name=? WHERE id=?", name, id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "目录不存在") + return + } + c.JSON(200, gin.H{"data": gin.H{"id": id, "name": name}}) +} + +func (a *BusinessAPI) moveSuffixDir(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + Dir int `json:"dir"` + } + if c.ShouldBindJSON(&in) != nil || (in.Dir != -1 && in.Dir != 1) { + apiError(c, 400, "invalid_request", "dir 只能是 -1 或 1") + return + } + if err := swapSortOrderScoped(c, a.db, "suffix_dirs", "parent_id", id, in.Dir); err != nil { + if errors.Is(err, errSwapNoNeighbor) { + apiError(c, 409, "no_neighbor", "已经到头,无法再移") + return + } + apiError(c, 500, "internal_error", "排序失败") + return + } + c.JSON(200, gin.H{"data": gin.H{"ok": true}}) +} + +func (a *BusinessAPI) deleteSuffixDir(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + if a.dirIsRoot(c, id) { + apiError(c, 403, "forbidden", "根目录不能删除") + return + } + res, err := a.db.ExecContext(c, "DELETE FROM suffix_dirs WHERE id=?", id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "目录不存在") + return + } + c.JSON(200, gin.H{"data": gin.H{"deleted": id}}) +} + +// ---- 目录工作区(列 + 行 + 单元格 + 锚定行) ---- + +type suffixColumnRow struct { + ID uint64 `json:"id"` + Name string `json:"name"` + IsValue bool `json:"is_value"` +} + +func (a *BusinessAPI) suffixDirPage(c *gin.Context) { + dirID, _ := strconv.ParseUint(c.Param("id"), 10, 64) + if !a.dirExists(c, dirID) { + apiError(c, 404, "not_found", "目录不存在") + return + } + columns := []suffixColumnRow{} + colRows, err := a.db.QueryContext(c, + "SELECT id,name,is_value FROM suffix_columns WHERE dir_id=? ORDER BY sort_order ASC,id ASC", dirID) + if err != nil { + apiError(c, 500, "internal_error", "列加载失败") + return + } + for colRows.Next() { + var col suffixColumnRow + if err := colRows.Scan(&col.ID, &col.Name, &col.IsValue); err != nil { + colRows.Close() + apiError(c, 500, "internal_error", "列加载失败") + return + } + columns = append(columns, col) + } + colRows.Close() + + type suffixLine struct { + ID uint64 `json:"id"` + GroupID uint64 `json:"group_id"` + GroupName string `json:"group_name"` + Name string `json:"name"` + Anchor bool `json:"anchor"` + } + suffixes := []suffixLine{} + sfxRows, err := a.db.QueryContext(c, + "SELECT s.id,s.group_id,g.name,s.name, EXISTS(SELECT 1 FROM suffix_dir_anchors x WHERE x.dir_id=? AND x.suffix_id=s.id)"+ + " FROM suffixes s JOIN suffix_groups g ON g.id=s.group_id"+ + " ORDER BY g.sort_order ASC,g.id ASC,s.sort_order ASC,s.id ASC", dirID) + if err != nil { + apiError(c, 500, "internal_error", "后缀加载失败") + return + } + for sfxRows.Next() { + var r suffixLine + if err := sfxRows.Scan(&r.ID, &r.GroupID, &r.GroupName, &r.Name, &r.Anchor); err != nil { + sfxRows.Close() + apiError(c, 500, "internal_error", "后缀加载失败") + return + } + suffixes = append(suffixes, r) + } + sfxRows.Close() + + cells := map[string]string{} + cellRows, err := a.db.QueryContext(c, + "SELECT suffix_id,column_id,value FROM suffix_cells WHERE dir_id=?", dirID) + if err != nil { + apiError(c, 500, "internal_error", "单元格加载失败") + return + } + for cellRows.Next() { + var sID, cID uint64 + var v string + if err := cellRows.Scan(&sID, &cID, &v); err != nil { + cellRows.Close() + apiError(c, 500, "internal_error", "单元格加载失败") + return + } + if v != "" { + cells[strconv.FormatUint(sID, 10)+":"+strconv.FormatUint(cID, 10)] = v + } + } + cellRows.Close() + c.JSON(200, gin.H{"data": gin.H{"dir_id": dirID, "columns": columns, "suffixes": suffixes, "cells": cells}}) +} + +func (a *BusinessAPI) createSuffixColumn(c *gin.Context) { + dirID, _ := strconv.ParseUint(c.Param("id"), 10, 64) + if !a.dirExists(c, dirID) { + apiError(c, 404, "not_found", "目录不存在") + return + } + var in struct { + Name string `json:"name"` + IsValue bool `json:"is_value"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name, ok := suffixTrimName(in.Name, 190) + if !ok { + apiError(c, 400, "invalid_request", "列名须为 1–190 字") + return + } + var dup int + if a.db.QueryRowContext(c, + "SELECT 1 FROM suffix_columns WHERE dir_id=? AND name=?", dirID, name).Scan(&dup) == nil { + apiError(c, 409, "duplicate_name", "这个目录里已有同名列") + return + } + var order sql.NullInt64 + _ = a.db.QueryRowContext(c, + "SELECT MAX(sort_order) FROM suffix_columns WHERE dir_id=?", dirID).Scan(&order) + res, err := a.db.ExecContext(c, + "INSERT INTO suffix_columns(dir_id,name,is_value,sort_order) VALUES(?,?,?,?)", + dirID, name, in.IsValue, order.Int64+1) + if err != nil { + apiError(c, 500, "internal_error", "列创建失败") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{"id": id, "name": name, "is_value": in.IsValue}}) +} + +func (a *BusinessAPI) deleteSuffixColumn(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + res, err := a.db.ExecContext(c, "DELETE FROM suffix_columns WHERE id=?", id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "列不存在") + return + } + c.JSON(200, gin.H{"data": gin.H{"deleted": id}}) +} + +func (a *BusinessAPI) saveSuffixCell(c *gin.Context) { + var in struct { + DirID uint64 `json:"dir_id"` + SuffixID uint64 `json:"suffix_id"` + ColumnID uint64 `json:"column_id"` + Value string `json:"value"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + if utf8.RuneCountInString(in.Value) > suffixCellValueMax { + apiError(c, 400, "invalid_request", "单元格内容过长") + return + } + var colDir uint64 + err := a.db.QueryRowContext(c, + "SELECT dir_id FROM suffix_columns WHERE id=?", in.ColumnID).Scan(&colDir) + switch { + case errors.Is(err, sql.ErrNoRows): + apiError(c, 404, "not_found", "列不存在") + return + case err != nil: + apiError(c, 500, "internal_error", "保存失败") + return + } + if colDir != in.DirID { + apiError(c, 400, "invalid_request", "列不属于该目录") + return + } + if _, err := a.db.ExecContext(c, + "INSERT INTO suffix_cells(dir_id,suffix_id,column_id,value) VALUES(?,?,?,?)"+ + " ON DUPLICATE KEY UPDATE value=VALUES(value)", + in.DirID, in.SuffixID, in.ColumnID, in.Value); err != nil { + apiError(c, 500, "internal_error", "保存失败") + return + } + c.JSON(200, gin.H{"data": gin.H{"ok": true}}) +} + +func (a *BusinessAPI) setSuffixAnchor(c *gin.Context) { + dirID, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + SuffixID uint64 `json:"suffix_id"` + On bool `json:"on"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + var exec error + if in.On { + _, exec = a.db.ExecContext(c, + "INSERT IGNORE INTO suffix_dir_anchors(dir_id,suffix_id) VALUES(?,?)", dirID, in.SuffixID) + } else { + _, exec = a.db.ExecContext(c, + "DELETE FROM suffix_dir_anchors WHERE dir_id=? AND suffix_id=?", dirID, in.SuffixID) + } + if exec != nil { + apiError(c, 500, "internal_error", "锚定失败") + return + } + c.JSON(200, gin.H{"data": gin.H{"ok": true}}) +} + +// ---- 基本设置:分组 + 后缀 + 模板文件 ---- + +type suffixFileRow struct { + ID uint64 `json:"id"` + FileName string `json:"file_name"` + FileSize int64 `json:"file_size"` + CreatedAt string `json:"created_at"` +} + +func (a *BusinessAPI) suffixOverview(c *gin.Context) { + type groupOut struct { + ID uint64 `json:"id"` + Name string `json:"name"` + Suffixes []suffixOverview `json:"suffixes"` + } + groups := []groupOut{} + gRows, err := a.db.QueryContext(c, + "SELECT id,name FROM suffix_groups ORDER BY sort_order ASC,id ASC") + if err != nil { + apiError(c, 500, "internal_error", "分组加载失败") + return + } + defer gRows.Close() + for gRows.Next() { + var g groupOut + if err := gRows.Scan(&g.ID, &g.Name); err != nil { + apiError(c, 500, "internal_error", "分组加载失败") + return + } + g.Suffixes = []suffixOverview{} + groups = append(groups, g) + } + if err := gRows.Err(); err != nil { + apiError(c, 500, "internal_error", "分组加载失败") + return + } + sRows, err := a.db.QueryContext(c, + "SELECT id,group_id,name FROM suffixes ORDER BY group_id ASC,sort_order ASC,id ASC") + if err != nil { + apiError(c, 500, "internal_error", "后缀加载失败") + return + } + defer sRows.Close() + idx := map[uint64]int{} + for i := range groups { + idx[groups[i].ID] = i + } + filesBySuffix := map[uint64][]suffixFileRow{} + for sRows.Next() { + var id, gid uint64 + var name string + if err := sRows.Scan(&id, &gid, &name); err != nil { + apiError(c, 500, "internal_error", "后缀加载失败") + return + } + if gi, ok := idx[gid]; ok { + groups[gi].Suffixes = append(groups[gi].Suffixes, suffixOverview{ID: id, Name: name}) + } + } + if err := sRows.Err(); err != nil { + apiError(c, 500, "internal_error", "后缀加载失败") + return + } + fRows, err := a.db.QueryContext(c, + "SELECT id,suffix_id,file_name,file_size,created_at FROM suffix_files ORDER BY id ASC") + if err != nil { + apiError(c, 500, "internal_error", "文件加载失败") + return + } + defer fRows.Close() + for fRows.Next() { + var f suffixFileRow + var sid uint64 + if err := fRows.Scan(&f.ID, &sid, &f.FileName, &f.FileSize, &f.CreatedAt); err != nil { + apiError(c, 500, "internal_error", "文件加载失败") + return + } + filesBySuffix[sid] = append(filesBySuffix[sid], f) + } + for i := range groups { + for j := range groups[i].Suffixes { + sid := groups[i].Suffixes[j].ID + list := filesBySuffix[sid] + if list == nil { + list = []suffixFileRow{} + } + groups[i].Suffixes[j].Files = list + } + } + c.JSON(200, gin.H{"data": gin.H{"groups": groups}}) +} + +type suffixOverview struct { + ID uint64 `json:"id"` + Name string `json:"name"` + Files []suffixFileRow `json:"files"` +} + +func (a *BusinessAPI) createSuffixGroup(c *gin.Context) { + var in struct { + Name string `json:"name"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name, ok := suffixTrimName(in.Name, 190) + if !ok { + apiError(c, 400, "invalid_request", "分组名须为 1–190 字") + return + } + var dup int + if a.db.QueryRowContext(c, "SELECT 1 FROM suffix_groups WHERE name=?", name).Scan(&dup) == nil { + apiError(c, 409, "duplicate_name", "已有同名分组") + return + } + var order sql.NullInt64 + _ = a.db.QueryRowContext(c, "SELECT MAX(sort_order) FROM suffix_groups").Scan(&order) + res, err := a.db.ExecContext(c, + "INSERT INTO suffix_groups(name,sort_order) VALUES(?,?)", name, order.Int64+1) + if err != nil { + apiError(c, 500, "internal_error", "分组创建失败") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{"id": id, "name": name, "suffixes": []suffixOverview{}}}) +} + +func (a *BusinessAPI) renameSuffixGroup(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + Name string `json:"name"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name, ok := suffixTrimName(in.Name, 190) + if !ok { + apiError(c, 400, "invalid_request", "分组名须为 1–190 字") + return + } + var dup int + if a.db.QueryRowContext(c, + "SELECT 1 FROM suffix_groups WHERE name=? AND id<>?", name, id).Scan(&dup) == nil { + apiError(c, 409, "duplicate_name", "已有同名分组") + return + } + res, err := a.db.ExecContext(c, "UPDATE suffix_groups SET name=? WHERE id=?", name, id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "分组不存在") + return + } + c.JSON(200, gin.H{"data": gin.H{"id": id, "name": name}}) +} + +func (a *BusinessAPI) moveSuffixGroup(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + Dir int `json:"dir"` + } + if c.ShouldBindJSON(&in) != nil || (in.Dir != -1 && in.Dir != 1) { + apiError(c, 400, "invalid_request", "dir 只能是 -1 或 1") + return + } + if err := swapSortOrder(c, a.db, "suffix_groups", id, in.Dir); err != nil { + if errors.Is(err, errSwapNoNeighbor) { + apiError(c, 409, "no_neighbor", "已经到头,无法再移") + return + } + apiError(c, 500, "internal_error", "排序失败") + return + } + c.JSON(200, gin.H{"data": gin.H{"ok": true}}) +} + +func (a *BusinessAPI) deleteSuffixGroup(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + files := a.suffixFilesOnDisk(c, id) + res, err := a.db.ExecContext(c, "DELETE FROM suffix_groups WHERE id=?", id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "分组不存在") + return + } + a.removeDiskFiles(c, files) + c.JSON(200, gin.H{"data": gin.H{"deleted": id}}) +} + +// 收集某分组全部后缀的盘上相对路径(删组/删后缀时清理实体文件)。 +func (a *BusinessAPI) suffixFilesOnDisk(c *gin.Context, groupID uint64) []string { + rows, err := a.db.QueryContext(c, + "SELECT f.rel_path FROM suffix_files f JOIN suffixes s ON s.id=f.suffix_id WHERE s.group_id=?", groupID) + if err != nil { + return nil + } + defer rows.Close() + paths := []string{} + for rows.Next() { + var p string + if rows.Scan(&p) == nil { + paths = append(paths, p) + } + } + return paths +} + +func (a *BusinessAPI) createSuffix(c *gin.Context) { + var in struct { + GroupID uint64 `json:"group_id"` + AfterID uint64 `json:"after_id"` + } + if c.ShouldBindJSON(&in) != nil || in.GroupID == 0 { + apiError(c, 400, "invalid_request", "参数无效") + return + } + var groupSort int + if err := a.db.QueryRowContext(c, + "SELECT sort_order FROM suffix_groups WHERE id=?", in.GroupID).Scan(&groupSort); err != nil { + apiError(c, 404, "not_found", "分组不存在") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 500, "internal_error", "后缀创建失败") + return + } + defer tx.Rollback() + sortAfter := -1 + if in.AfterID > 0 { + var afterSort int + var afterGroup uint64 + if err := tx.QueryRowContext(c, + "SELECT sort_order,group_id FROM suffixes WHERE id=?", in.AfterID).Scan(&afterSort, &afterGroup); err != nil { + apiError(c, 404, "not_found", "插入位置的后缀不存在") + return + } + if afterGroup != in.GroupID { + apiError(c, 400, "invalid_request", "插入位置不属于同一分组") + return + } + if _, err := tx.ExecContext(c, + "UPDATE suffixes SET sort_order=sort_order+1 WHERE group_id=? AND sort_order>?", + in.GroupID, afterSort); err != nil { + apiError(c, 500, "internal_error", "后缀创建失败") + return + } + sortAfter = afterSort + } + res, err := tx.ExecContext(c, + "INSERT INTO suffixes(group_id,name,sort_order) VALUES(?,?,?)", + in.GroupID, "", sortAfter+1) + if err != nil { + apiError(c, 500, "internal_error", "后缀创建失败") + return + } + id, _ := res.LastInsertId() + if err := tx.Commit(); err != nil { + apiError(c, 500, "internal_error", "后缀创建失败") + return + } + c.JSON(201, gin.H{"data": gin.H{"id": id, "group_id": in.GroupID, "name": ""}}) +} + +func (a *BusinessAPI) renameSuffix(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + Name string `json:"name"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + name := strings.TrimSpace(in.Name) + if utf8.RuneCountInString(name) > 64 { + apiError(c, 400, "invalid_request", "后缀名最多 64 字") + return + } + res, err := a.db.ExecContext(c, "UPDATE suffixes SET name=? WHERE id=?", name, id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "后缀不存在") + return + } + c.JSON(200, gin.H{"data": gin.H{"id": id, "name": name}}) +} + +func (a *BusinessAPI) moveSuffix(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + Dir int `json:"dir"` + } + if c.ShouldBindJSON(&in) != nil || (in.Dir != -1 && in.Dir != 1) { + apiError(c, 400, "invalid_request", "dir 只能是 -1 或 1") + return + } + if err := swapSortOrderScoped(c, a.db, "suffixes", "group_id", id, in.Dir); err != nil { + if errors.Is(err, errSwapNoNeighbor) { + apiError(c, 409, "no_neighbor", "已经到头,无法再移") + return + } + apiError(c, 500, "internal_error", "排序失败") + return + } + c.JSON(200, gin.H{"data": gin.H{"ok": true}}) +} + +func (a *BusinessAPI) deleteSuffix(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + files := []string{} + fRows, err := a.db.QueryContext(c, + "SELECT rel_path FROM suffix_files WHERE suffix_id=?", id) + if err == nil { + for fRows.Next() { + var p string + if fRows.Scan(&p) == nil { + files = append(files, p) + } + } + fRows.Close() + } + res, err := a.db.ExecContext(c, "DELETE FROM suffixes WHERE id=?", id) + if err != nil || rowsAffected(res) == 0 { + apiError(c, 404, "not_found", "后缀不存在") + return + } + a.removeDiskFiles(c, files) + c.JSON(200, gin.H{"data": gin.H{"deleted": id}}) +} + +// ---- 模板文件 ---- + +type suffixTemplateRootError struct{} + +func (suffixTemplateRootError) Error() string { return "模板存储目录未配置" } + +func suffixTemplateRoot() (string, error) { + base := strings.TrimSpace(os.Getenv("PACKAGE_STORAGE_ROOT")) + if base == "" { + return "", suffixTemplateRootError{} + } + return filepath.Join(base, "suffix-templates"), nil +} + +func suffixUniqueName(dir string, name string) string { + if _, err := os.Stat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) { + return name + } + ext := filepath.Ext(name) + stem := strings.TrimSuffix(name, ext) + for i := 1; ; i++ { + candidate := fmt.Sprintf("%s-%d%s", stem, i, ext) + if _, err := os.Stat(filepath.Join(dir, candidate)); errors.Is(err, os.ErrNotExist) { + return candidate + } + } +} + +func (a *BusinessAPI) uploadSuffixFile(c *gin.Context) { + suffixID, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var in struct { + FileName string `json:"file_name"` + Size int64 `json:"size"` + SHA256 string `json:"sha256"` + ContentBase64 string `json:"content_base64"` + } + if c.ShouldBindJSON(&in) != nil { + apiError(c, 400, "invalid_request", "参数无效") + return + } + fileName := suffixBadNameRe.ReplaceAllString(strings.TrimSpace(in.FileName), "_") + if fileName == "" || len(fileName) > suffixFileNameMax { + apiError(c, 400, "invalid_request", "文件名无效") + return + } + if in.Size <= 0 || in.Size > suffixUploadMax || len(in.ContentBase64) > suffixUploadMax { + apiError(c, 400, "invalid_request", "文件为空或超过 128MB 上限") + return + } + data, err := base64.StdEncoding.DecodeString(in.ContentBase64) + if err != nil || int64(len(data)) != in.Size { + apiError(c, 400, "invalid_request", "文件内容与大小不符") + return + } + sum := sha256.Sum256(data) + got := hex.EncodeToString(sum[:]) + if !strings.EqualFold(got, strings.TrimSpace(in.SHA256)) { + apiError(c, 400, "invalid_request", "文件哈希校验失败,请重新上传") + return + } + root, rootErr := suffixTemplateRoot() + if rootErr != nil { + apiError(c, 500, "storage_unconfigured", "PACKAGE_STORAGE_ROOT 未配置,模板无法落盘") + return + } + folder := filepath.Join(root, strconv.FormatUint(suffixID, 10)) + if err := os.MkdirAll(folder, 0o755); err != nil { + apiError(c, 500, "internal_error", "模板目录创建失败") + return + } + stored := suffixUniqueName(folder, fileName) + abs := filepath.Join(folder, stored) + if err := os.WriteFile(abs, data, 0o644); err != nil { + apiError(c, 500, "internal_error", "模板写入失败") + return + } + rel := filepath.ToSlash(filepath.Join(strconv.FormatUint(suffixID, 10), stored)) + res, err := a.db.ExecContext(c, + "INSERT INTO suffix_files(suffix_id,file_name,file_size,sha256,rel_path) VALUES(?,?,?,?,?)", + suffixID, stored, len(data), got, rel) + if err != nil { + _ = os.Remove(abs) + apiError(c, 500, "internal_error", "模板登记失败") + return + } + id, _ := res.LastInsertId() + c.JSON(201, gin.H{"data": gin.H{ + "id": id, "suffix_id": suffixID, "file_name": stored, + "file_size": len(data), "sha256": got, + }}) +} + +// 只认模板根目录以内的路径,越界一律不删。 +func (a *BusinessAPI) removeDiskFiles(c *gin.Context, relPaths []string) { + root, err := suffixTemplateRoot() + if err != nil { + return + } + for _, rel := range relPaths { + abs := filepath.Join(root, filepath.FromSlash(rel)) + clean := filepath.Clean(abs) + if strings.HasPrefix(clean, filepath.Clean(root)+string(filepath.Separator)) { + _ = os.Remove(clean) + } + } +} + +func (a *BusinessAPI) deleteSuffixFile(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var rel string + err := a.db.QueryRowContext(c, + "SELECT rel_path FROM suffix_files WHERE id=?", id).Scan(&rel) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "文件不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "文件删除失败") + return + } + if _, err := a.db.ExecContext(c, "DELETE FROM suffix_files WHERE id=?", id); err != nil { + apiError(c, 500, "internal_error", "文件删除失败") + return + } + a.removeDiskFiles(c, []string{rel}) + c.JSON(200, gin.H{"data": gin.H{"deleted": id}}) +} + +func (a *BusinessAPI) downloadSuffixFile(c *gin.Context) { + id, _ := strconv.ParseUint(c.Param("id"), 10, 64) + var rel, name string + err := a.db.QueryRowContext(c, + "SELECT rel_path,file_name FROM suffix_files WHERE id=?", id).Scan(&rel, &name) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "文件不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "文件下载失败") + return + } + root, rootErr := suffixTemplateRoot() + if rootErr != nil { + apiError(c, 500, "storage_unconfigured", "PACKAGE_STORAGE_ROOT 未配置") + return + } + abs := filepath.Clean(filepath.Join(root, filepath.FromSlash(rel))) + if !strings.HasPrefix(abs, filepath.Clean(root)+string(filepath.Separator)) { + apiError(c, 400, "invalid_path", "路径越界") + return + } + if _, err := os.Stat(abs); err != nil { + apiError(c, 404, "not_found", "文件已不在盘上") + return + } + c.FileAttachment(abs, name) +} + +// ---- 通用小工具 ---- + +func rowsAffected(res sql.Result) int64 { + n, _ := res.RowsAffected() + return n +} + +var errSwapNoNeighbor = errors.New("no neighbor to swap with") + +// 同表相邻交换排序:dir=-1 与前一个换,dir=1 与后一个换(按 sort_order,id 定序)。 +// scopeCol 为空=全表一条序列;非空=按该列分组(NULL 用 <=> 安全比较)。 +func swapSortOrder(c *gin.Context, db *sql.DB, table string, id uint64, dir int) error { + return swapSortOrderScoped(c, db, table, "", id, dir) +} + +func swapSortOrderScoped(c *gin.Context, db *sql.DB, table, scopeCol string, id uint64, dir int) error { + scopeSel := "NULL" + if scopeCol != "" { + scopeSel = scopeCol + } + var selfSort int + var selfScope sql.NullInt64 + if err := db.QueryRowContext(c, + "SELECT sort_order,"+scopeSel+" FROM "+table+" WHERE id=?", id).Scan(&selfSort, &selfScope); err != nil { + return err + } + where := "id<>?" + args := []any{id} + if scopeCol != "" { + where = scopeCol + "<=>? AND id<>?" + var v any + if selfScope.Valid { + v = selfScope.Int64 + } + args = []any{v, id} + } + cmp, order := ">", " ASC" + if dir == -1 { + cmp, order = "<", " DESC" + } + q := "SELECT id,sort_order FROM " + table + " WHERE " + where + + " AND (sort_order" + cmp + "? OR (sort_order=? AND id" + cmp + "?))" + + " ORDER BY sort_order" + order + ",id" + order + " LIMIT 1" + args = append(args, selfSort, selfSort) + var nid uint64 + var nsort int + if err := db.QueryRowContext(c, q, args...).Scan(&nid, &nsort); err != nil { + return errSwapNoNeighbor + } + if _, err := db.ExecContext(c, + "UPDATE "+table+" SET sort_order=? WHERE id=?", nsort, id); err != nil { + return err + } + _, err := db.ExecContext(c, "UPDATE "+table+" SET sort_order=? WHERE id=?", selfSort, nid) + return err +} diff --git a/backend/internal/httpapi/suffixes_test.go b/backend/internal/httpapi/suffixes_test.go new file mode 100644 index 0000000..51554fd --- /dev/null +++ b/backend/internal/httpapi/suffixes_test.go @@ -0,0 +1,239 @@ +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()) + } + 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.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) != 2 { + t.Fatalf("列数=%d, want 2", 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) + } +} diff --git a/backend/migrations/000017_suffix_management.down.sql b/backend/migrations/000017_suffix_management.down.sql new file mode 100644 index 0000000..8d309ba --- /dev/null +++ b/backend/migrations/000017_suffix_management.down.sql @@ -0,0 +1,7 @@ +DROP TABLE IF EXISTS suffix_files; +DROP TABLE IF EXISTS suffix_dir_anchors; +DROP TABLE IF EXISTS suffix_cells; +DROP TABLE IF EXISTS suffix_columns; +DROP TABLE IF EXISTS suffixes; +DROP TABLE IF EXISTS suffix_groups; +DROP TABLE IF EXISTS suffix_dirs; diff --git a/backend/migrations/000017_suffix_management.up.sql b/backend/migrations/000017_suffix_management.up.sql new file mode 100644 index 0000000..cccace8 --- /dev/null +++ b/backend/migrations/000017_suffix_management.up.sql @@ -0,0 +1,68 @@ +-- Suffix management (后缀管理): directory tree, province groups, suffixes, +-- per-directory custom columns (with value flag), cell values, anchors, template files. +CREATE TABLE suffix_dirs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + parent_id BIGINT UNSIGNED NULL, + name VARCHAR(190) NOT NULL, + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT fk_suffix_dirs_parent FOREIGN KEY(parent_id) REFERENCES suffix_dirs(id) ON DELETE CASCADE +) ENGINE=InnoDB; +INSERT INTO suffix_dirs(parent_id,name,sort_order) VALUES(NULL,'按信息价的目录',0); + +CREATE TABLE suffix_groups ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(190) NOT NULL UNIQUE, + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) +) ENGINE=InnoDB; + +CREATE TABLE suffixes ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + group_id BIGINT UNSIGNED NOT NULL, + name VARCHAR(64) NOT NULL DEFAULT '', + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT fk_suffixes_group FOREIGN KEY(group_id) REFERENCES suffix_groups(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE suffix_columns ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + dir_id BIGINT UNSIGNED NOT NULL, + name VARCHAR(190) NOT NULL, + is_value BOOLEAN NOT NULL DEFAULT FALSE, + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT fk_suffix_columns_dir FOREIGN KEY(dir_id) REFERENCES suffix_dirs(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE suffix_cells ( + dir_id BIGINT UNSIGNED NOT NULL, + suffix_id BIGINT UNSIGNED NOT NULL, + column_id BIGINT UNSIGNED NOT NULL, + value TEXT NOT NULL, + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY(dir_id,suffix_id,column_id), + CONSTRAINT fk_suffix_cells_dir FOREIGN KEY(dir_id) REFERENCES suffix_dirs(id) ON DELETE CASCADE, + CONSTRAINT fk_suffix_cells_suffix FOREIGN KEY(suffix_id) REFERENCES suffixes(id) ON DELETE CASCADE, + CONSTRAINT fk_suffix_cells_column FOREIGN KEY(column_id) REFERENCES suffix_columns(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE suffix_dir_anchors ( + dir_id BIGINT UNSIGNED NOT NULL, + suffix_id BIGINT UNSIGNED NOT NULL, + PRIMARY KEY(dir_id,suffix_id), + CONSTRAINT fk_suffix_anchors_dir FOREIGN KEY(dir_id) REFERENCES suffix_dirs(id) ON DELETE CASCADE, + CONSTRAINT fk_suffix_anchors_suffix FOREIGN KEY(suffix_id) REFERENCES suffixes(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE suffix_files ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + suffix_id BIGINT UNSIGNED NOT NULL, + file_name VARCHAR(255) NOT NULL, + file_size BIGINT UNSIGNED NOT NULL, + sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + rel_path VARCHAR(500) NOT NULL, + created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT fk_suffix_files_suffix FOREIGN KEY(suffix_id) REFERENCES suffixes(id) ON DELETE CASCADE +) ENGINE=InnoDB; diff --git a/frontend/src/router.ts b/frontend/src/router.ts index 44b6510..c99b7a1 100644 --- a/frontend/src/router.ts +++ b/frontend/src/router.ts @@ -5,7 +5,7 @@ import Checkout from './views/Checkout.vue' export default createRouter({ history: createWebHistory(), routes: [ - ...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})), + ...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/suffixes',view:'suffixes'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})), {path:'/checkout',component:Checkout,meta:{public:true}}, {path:'/customer',component:CustomerPortal}, {path:'/:pathMatch(.*)*',redirect:'/'} diff --git a/frontend/src/suffix-admin.ts b/frontend/src/suffix-admin.ts new file mode 100644 index 0000000..a9b6073 --- /dev/null +++ b/frontend/src/suffix-admin.ts @@ -0,0 +1,70 @@ +import { api } from './api' + +// 后缀管理(业务管理 → 后缀管理):目录树 / 分组 / 后缀 / 列 / 单元格 / 模板文件。 + +export type SuffixDir = { id:number; parent_id:number; name:string; sort_order:number; children:number } +export type SuffixColumn = { id:number; name:string; is_value:boolean } +export type SuffixLine = { id:number; group_id:number; group_name:string; name:string; anchor:boolean } +export type SuffixPage = { dir_id:number; columns:SuffixColumn[]; suffixes:SuffixLine[]; cells:Record } +export type SuffixFile = { id:number; suffix_id?:number; file_name:string; file_size:number; created_at?:string; sha256?:string } +export type SuffixGroup = { id:number; name:string; suffixes:{ id:number; name:string; files:SuffixFile[] }[] } + +export const getSuffixTree = () => api.get<{data:{dirs:SuffixDir[]}}>('/suffix-admin/tree') +export const createSuffixDir = (parent_id:number, name:string) => api.post<{data:SuffixDir}>('/suffix-admin/dirs', { parent_id, name }) +export const renameSuffixDir = (id:number, name:string) => api.put<{data:SuffixDir}>(`/suffix-admin/dirs/${id}`, { name }) +export const moveSuffixDir = (id:number, dir:number) => api.post(`/suffix-admin/dirs/${id}/move`, { dir }) +export const deleteSuffixDir = (id:number) => api.delete(`/suffix-admin/dirs/${id}`) +export const getSuffixPage = (id:number) => api.get<{data:SuffixPage}>(`/suffix-admin/dirs/${id}/page`) +export const createSuffixColumn = (dirId:number, name:string, is_value:boolean) => api.post<{data:SuffixColumn}>(`/suffix-admin/dirs/${dirId}/columns`, { name, is_value }) +export const deleteSuffixColumn = (id:number) => api.delete(`/suffix-admin/columns/${id}`) +export const saveSuffixCell = (dir_id:number, suffix_id:number, column_id:number, value:string) => api.put('/suffix-admin/cells', { dir_id, suffix_id, column_id, value }) +export const setSuffixAnchor = (dirId:number, suffix_id:number, on:boolean) => api.post(`/suffix-admin/dirs/${dirId}/anchor`, { suffix_id, on }) +export const getSuffixOverview = () => api.get<{data:{groups:SuffixGroup[]}}>('/suffix-admin/overview') +export const createSuffixGroup = (name:string) => api.post<{data:SuffixGroup}>('/suffix-admin/groups', { name }) +export const renameSuffixGroup = (id:number, name:string) => api.put(`/suffix-admin/groups/${id}`, { name }) +export const moveSuffixGroup = (id:number, dir:number) => api.post(`/suffix-admin/groups/${id}/move`, { dir }) +export const deleteSuffixGroup = (id:number) => api.delete(`/suffix-admin/groups/${id}`) +export const createSuffix = (group_id:number, after_id = 0) => api.post<{data:{id:number;group_id:number;name:string}}>('/suffix-admin/suffixes', { group_id, after_id }) +export const renameSuffix = (id:number, name:string) => api.put(`/suffix-admin/suffixes/${id}`, { name }) +export const moveSuffix = (id:number, dir:number) => api.post(`/suffix-admin/suffixes/${id}/move`, { dir }) +export const deleteSuffix = (id:number) => api.delete(`/suffix-admin/suffixes/${id}`) +export const uploadSuffixFile = (id:number, body:{file_name:string;size:number;sha256:string;content_base64:string}) => api.post<{data:SuffixFile}>(`/suffix-admin/suffixes/${id}/files`, body) +export const deleteSuffixFile = (id:number) => api.delete(`/suffix-admin/files/${id}`) +export const suffixFileUrl = (id:number) => `/api/v1/suffix-admin/files/${id}/download` + +// 读文件:算 sha256 + 分块转 base64(与后端上传接口配对)。 +export async function readSuffixFile(file:File):Promise<{size:number;sha256:string;content_base64:string}> { + const buffer = await file.arrayBuffer() + const digest = await crypto.subtle.digest('SHA-256', buffer) + const sha256 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('') + const bytes = new Uint8Array(buffer) + let binary = '' + const chunk = 0x8000 + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode(...bytes.subarray(i, i + chunk)) + } + return { size: bytes.length, sha256, content_base64: btoa(binary) } +} + +export function formatSuffixSize(size:number):string { + if (size >= 1 << 20) return (size / (1 << 20)).toFixed(1) + ' MB' + if (size >= 1024) return (size / 1024).toFixed(1) + ' KB' + return size + ' B' +} + +// 值列单元格存紧凑 JSON {"a":锚点,"v":值}。 +export function parseValueCell(raw:string):{a:string;v:string} { + if (!raw) return { a: '', v: '' } + if (raw.trimStart().startsWith('{')) { + try { + const o = JSON.parse(raw) + if (o && typeof o === 'object') return { a: String(o.a ?? ''), v: String(o.v ?? '') } + } catch { /* 旧数据可能是纯文本 */ } + } + return { a: '', v: raw } +} + +export function buildValueCell(a:string, v:string):string { + if (!a && !v) return '' + return JSON.stringify({ a, v }) +} diff --git a/frontend/src/views/Overview.vue b/frontend/src/views/Overview.vue index 0e66b6e..f68b2e1 100644 --- a/frontend/src/views/Overview.vue +++ b/frontend/src/views/Overview.vue @@ -20,6 +20,7 @@ import OrdersPanel from './OrdersPanel.vue' import PaymentsPanel from './PaymentsPanel.vue' import ReleasesPanel from './ReleasesPanel.vue' import PurchasePlansPanel from './PurchasePlansPanel.vue' +import SuffixPanel from './SuffixPanel.vue' import { listLicenseInstances, setInstanceFrozen, type LicenseInstance } from '../api' const selectedLicenseID = ref(null), changingInstance = ref('') const freezeRetries = new Map() @@ -39,8 +40,8 @@ async function showInstances(id:number) { selectedLicenseID.value = id; instance const route = useRoute() || ({ meta: {}, query: {} } as ReturnType) const router = useRouter() || ({ push: async () => undefined, replace: async () => undefined } as unknown as ReturnType) const pageView = computed(() => route.meta.view as string || 'dashboard') -const title=computed(()=>({dashboard:'仪表盘',licenses:'License 授权',customers:'客户管理',products:'产品目录',orders:'订单与套餐',payments:'支付管理','payment-plans':'套餐管理',releases:'版本管理',integration:'客户端接入',audit:'审计日志',settings:'系统设置',admins:'管理员账户'}[pageView.value] || '仪表盘')) -const nav=[{view:'dashboard',path:'/',name:'仪表盘',icon:'▦'},{view:'licenses',path:'/licenses',name:'License 授权',icon:'◇'},{view:'customers',path:'/customers',name:'客户管理',icon:'♙'},{view:'products',path:'/products',name:'产品目录',icon:'◫'},{view:'orders',path:'/orders',name:'订单与套餐',icon:'▤'},{view:'payments',path:'/payments',name:'支付管理',icon:'¥'},{view:'payment-plans',path:'/payment-plans',name:'套餐管理',icon:'▣'},{view:'releases',path:'/releases',name:'版本管理',icon:'↥'},{view:'integration',path:'/integration',name:'客户端接入',icon:'⌘'},{view:'audit',path:'/audit',name:'审计日志',icon:'≡'},{view:'settings',path:'/settings',name:'系统设置',icon:'⚙'},{view:'admins',path:'/admins',name:'管理员账户',icon:'♙'}] +const title=computed(()=>({dashboard:'仪表盘',licenses:'License 授权',customers:'客户管理',products:'产品目录',orders:'订单与套餐',payments:'支付管理','payment-plans':'套餐管理',suffixes:'后缀管理',releases:'版本管理',integration:'客户端接入',audit:'审计日志',settings:'系统设置',admins:'管理员账户'}[pageView.value] || '仪表盘')) +const nav=[{view:'dashboard',path:'/',name:'仪表盘',icon:'▦'},{view:'licenses',path:'/licenses',name:'License 授权',icon:'◇'},{view:'customers',path:'/customers',name:'客户管理',icon:'♙'},{view:'products',path:'/products',name:'产品目录',icon:'◫'},{view:'orders',path:'/orders',name:'订单与套餐',icon:'▤'},{view:'payments',path:'/payments',name:'支付管理',icon:'¥'},{view:'payment-plans',path:'/payment-plans',name:'套餐管理',icon:'▣'},{view:'suffixes',path:'/suffixes',name:'后缀管理',icon:'⊞'},{view:'releases',path:'/releases',name:'版本管理',icon:'↥'},{view:'integration',path:'/integration',name:'客户端接入',icon:'⌘'},{view:'audit',path:'/audit',name:'审计日志',icon:'≡'},{view:'settings',path:'/settings',name:'系统设置',icon:'⚙'},{view:'admins',path:'/admins',name:'管理员账户',icon:'♙'}] const adminEmail=ref('管理员'), detail=ref(null),detailOpen=ref(false),detailLoading=ref(false),detailError=ref('') async function showDetail(id:number){detailOpen.value=true;detail.value=null;detailError.value='';detailLoading.value=true;try{detail.value=(await getLicense(id)).data.data}catch(e){detailError.value=e instanceof Error?e.message:'详情加载失败'}finally{detailLoading.value=false}} async function openIssue(){await router.push('/licenses');document.getElementById('license-issue')?.scrollIntoView({behavior:'smooth'})} @@ -131,7 +132,7 @@ async function submitRenewal() { onMounted(() => { checkConnection(); checkSession() })