feat: add suffix management module under business admin

- 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
This commit is contained in:
lianjianwei2024
2026-10-30 11:32:22 +08:00
parent 682f8737d0
commit dd9d5470c2
11 changed files with 2146 additions and 5 deletions

View File

@@ -98,6 +98,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
purchaseAdmin.POST("/purchase-credentials", a.createPurchaseCredential) purchaseAdmin.POST("/purchase-credentials", a.createPurchaseCredential)
purchaseAdmin.PUT("/purchase-credentials/:id", a.updatePurchaseCredential) purchaseAdmin.PUT("/purchase-credentials/:id", a.updatePurchaseCredential)
secured := api.Group("", a.authenticated) secured := api.Group("", a.authenticated)
registerSuffixRoutes(secured, a)
secured.GET("/me", a.me) secured.GET("/me", a.me)
secured.GET("/admins", a.listAdmins) secured.GET("/admins", a.listAdmins)
secured.POST("/admins", a.createAdmin) secured.POST("/admins", a.createAdmin)

View File

@@ -9,7 +9,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
const RequiredSchemaVersion = 16 const RequiredSchemaVersion = 17
func RegisterReadiness(r *gin.Engine, db *sql.DB) { func RegisterReadiness(r *gin.Engine, db *sql.DB) {
r.GET("/api/v1/health/ready", func(c *gin.Context) { r.GET("/api/v1/health/ready", func(c *gin.Context) {

View File

@@ -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
}

View File

@@ -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)
}
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -5,7 +5,7 @@ import Checkout from './views/Checkout.vue'
export default createRouter({ export default createRouter({
history: createWebHistory(), history: createWebHistory(),
routes: [ 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:'/checkout',component:Checkout,meta:{public:true}},
{path:'/customer',component:CustomerPortal}, {path:'/customer',component:CustomerPortal},
{path:'/:pathMatch(.*)*',redirect:'/'} {path:'/:pathMatch(.*)*',redirect:'/'}

View File

@@ -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<string,string> }
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 })
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,112 @@
import { mount, flushPromises } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import SuffixPanel from './SuffixPanel.vue'
import {
createSuffixColumn, getSuffixOverview, getSuffixPage, getSuffixTree,
} from '../suffix-admin'
vi.mock('../suffix-admin', () => ({
buildValueCell: (a: string, v: string) => (a || v ? JSON.stringify({ a, v }) : ''),
parseValueCell: (raw: string) => {
if (!raw) return { a: '', v: '' }
try { const o = JSON.parse(raw); return { a: String(o.a ?? ''), v: String(o.v ?? '') } } catch { return { a: '', v: raw } }
},
formatSuffixSize: (n: number) => n + ' B',
suffixFileUrl: (id: number) => `/api/v1/suffix-admin/files/${id}/download`,
getSuffixTree: vi.fn(),
createSuffixDir: vi.fn(),
renameSuffixDir: vi.fn(),
moveSuffixDir: vi.fn(),
deleteSuffixDir: vi.fn(),
getSuffixPage: vi.fn(),
createSuffixColumn: vi.fn(),
deleteSuffixColumn: vi.fn(),
saveSuffixCell: vi.fn(),
setSuffixAnchor: vi.fn(),
getSuffixOverview: vi.fn(),
createSuffixGroup: vi.fn(),
renameSuffixGroup: vi.fn(),
moveSuffixGroup: vi.fn(),
deleteSuffixGroup: vi.fn(),
createSuffix: vi.fn(),
renameSuffix: vi.fn(),
moveSuffix: vi.fn(),
deleteSuffix: vi.fn(),
uploadSuffixFile: vi.fn(),
deleteSuffixFile: vi.fn(),
readSuffixFile: vi.fn(),
}))
vi.mock('element-plus', () => ({
ElMessage: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
ElMessageBox: { prompt: vi.fn(), confirm: vi.fn() },
}))
const stubs = {
ElButton: { template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot/></button>', props: ['disabled'] },
ElInput: { template: '<input :value="modelValue" @input="$emit(\'update:modelValue\',$event.target.value)"/>', props: ['modelValue'] },
ElCheckbox: { template: '<input type="checkbox" :checked="modelValue" @change="$emit(\'update:modelValue\',$event.target.checked)"/>', props: ['modelValue'] },
ElDialog: { name: 'ElDialog', props: ['modelValue', 'title'], template: '<div v-if="modelValue" class="dialog-stub"><slot/><slot name="footer"/></div>' },
}
const directives = { loading: () => {} }
const ok = (data: unknown) => ({ data: { data } })
const dirs = [
{ id: 1, parent_id: 0, name: '按信息价的目录', sort_order: 0, children: 1 },
{ id: 2, parent_id: 1, name: '一、黑色及有色金属', sort_order: 1, children: 0 },
]
const page = {
dir_id: 2,
columns: [{ id: 5, name: '招标人', is_value: false }],
suffixes: [{ id: 10, group_id: 1, group_name: '广东省', name: 'cos4', anchor: false }],
cells: {},
}
function setup() {
vi.mocked(getSuffixOverview).mockResolvedValue(ok({ groups: [{ id: 1, name: '广东省', suffixes: [{ id: 10, name: 'cos4', files: [] }] }] }) as never)
vi.mocked(getSuffixTree).mockResolvedValue(ok({ dirs }) as never)
vi.mocked(getSuffixPage).mockResolvedValue(ok(page) as never)
const wrapper = mount(SuffixPanel, { global: { stubs, directives } })
return wrapper
}
describe('SuffixPanel', () => {
afterEach(() => { vi.clearAllMocks(); vi.restoreAllMocks() })
it('renders both roots and the basic suffix sheet', async () => {
const wrapper = setup()
await flushPromises()
expect(wrapper.text()).toContain('基本设置')
expect(wrapper.text()).toContain('按信息价的目录')
expect(wrapper.text()).toContain('广东省')
expect(wrapper.text()).toContain('cos4')
expect(wrapper.text()).toContain('上传模板')
expect(wrapper.text()).toContain('+ 新建分组')
})
it('adds a column with the 值设置 flag through the dialog', async () => {
const wrapper = setup()
await flushPromises()
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('招标人')
await wrapper.findAll('button').find((b) => b.text() === '+ 添加列')!.trigger('click')
expect(wrapper.text()).toContain('值设置')
const inputs = wrapper.findAll('.dialog-stub input')
await inputs[0].setValue('招标人')
await wrapper.find('.dialog-stub input[type="checkbox"]').setValue(true)
vi.mocked(createSuffixColumn).mockResolvedValue(ok({ id: 9, name: '招标人', is_value: true }) as never)
await wrapper.findAll('button').find((b) => b.text() === '确定')!.trigger('click')
await flushPromises()
expect(createSuffixColumn).toHaveBeenCalledWith(2, '招标人', true)
})
it('lists workspace rows grouped by province with fixed 锚定行 column', async () => {
const wrapper = setup()
await flushPromises()
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('锚定行')
expect(wrapper.text()).toContain('− 广东省')
expect(wrapper.findAll('td.anchor').length).toBeGreaterThan(0)
})
})

View File

@@ -0,0 +1,688 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
buildValueCell, createSuffix, createSuffixColumn, createSuffixDir, createSuffixGroup,
deleteSuffix, deleteSuffixColumn, deleteSuffixDir, deleteSuffixFile, deleteSuffixGroup,
formatSuffixSize, getSuffixOverview, getSuffixPage, getSuffixTree, moveSuffix, moveSuffixDir,
moveSuffixGroup, parseValueCell, readSuffixFile, renameSuffix, renameSuffixDir,
renameSuffixGroup, saveSuffixCell, setSuffixAnchor, suffixFileUrl, uploadSuffixFile,
type SuffixColumn, type SuffixDir, type SuffixFile, type SuffixPage,
} from '../suffix-admin'
type Selection = { kind: 'basic' } | { kind: 'dir'; id: number }
const groups = ref<{ id:number; name:string; suffixes:{ id:number; name:string; files:SuffixFile[] }[] }[]>([])
const dirs = ref<SuffixDir[]>([])
const expanded = ref<Set<number>>(new Set())
const selected = ref<Selection>({ kind: 'basic' })
const page = ref<SuffixPage | null>(null)
const pageLoading = ref(false)
const overviewLoading = ref(false)
// 增加列弹框(列名 + 值设置复选框)
const colDialog = reactive({ visible: false, name: '', isValue: false, saving: false })
// 单元格编辑
const editing = reactive({ sid: 0, cid: 0, text: '', a: '', v: '' })
// 行编辑态(视觉高亮,格子弹出编辑不受它限制)
const editRows = ref<Set<number>>(new Set())
// 后缀行内改名
const renamingSuffix = ref(0)
const renamingSuffixName = ref('')
// 上传
const uploadInput = ref<HTMLInputElement | null>(null)
const uploadTarget = ref(0)
const uploading = ref(false)
async function loadOverview() {
overviewLoading.value = true
try {
groups.value = (await getSuffixOverview()).data.data.groups
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '后缀加载失败')
} finally {
overviewLoading.value = false
}
}
async function loadTree() {
try {
dirs.value = (await getSuffixTree()).data.data.dirs
const root = dirs.value.find((d) => !d.parent_id)
if (root && root.children > 0 && !expanded.value.has(root.id)) {
expanded.value = new Set(expanded.value).add(root.id)
}
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '目录加载失败')
}
}
async function selectNode(sel: Selection) {
selected.value = sel
if (sel.kind === 'dir') {
pageLoading.value = true
page.value = null
try {
page.value = (await getSuffixPage(sel.id)).data.data
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '工作区加载失败')
} finally {
pageLoading.value = false
}
}
}
// ---- 目录树 ----
const rootDir = computed(() => dirs.value.find((d) => d.parent_id === 0 || d.parent_id === null) || null)
interface FlatNode { dir: SuffixDir; depth: number }
const visibleNodes = computed<FlatNode[]>(() => {
const out: FlatNode[] = []
const byParent = new Map<number, SuffixDir[]>()
for (const d of dirs.value) {
const key = d.parent_id || 0
if (!byParent.has(key)) byParent.set(key, [])
byParent.get(key)!.push(d)
}
const walk = (parent: number, depth: number) => {
for (const d of byParent.get(parent) || []) {
out.push({ dir: d, depth })
if (expanded.value.has(d.id)) walk(d.id, depth + 1)
}
}
if (rootDir.value) {
out.push({ dir: rootDir.value, depth: 0 })
if (expanded.value.has(rootDir.value.id)) walk(rootDir.value.id, 1)
}
return out
})
function toggleExpand(dir: SuffixDir) {
const next = new Set(expanded.value)
if (next.has(dir.id)) next.delete(dir.id)
else next.add(dir.id)
expanded.value = next
}
function isRoot(dir: SuffixDir) {
return !dir.parent_id
}
async function addDir(parentId: number, title: string) {
const { value } = await ElMessageBox.prompt('输入目录名称', title, { inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).catch(() => ({ value: '' }))
if (!value) return
try {
const created = (await createSuffixDir(parentId, value.trim())).data.data
await loadTree()
expanded.value = new Set(expanded.value).add(parentId)
ElMessage.success(`已创建「${created.name}」`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '创建失败')
}
}
async function renameDir(dir: SuffixDir) {
const { value } = await ElMessageBox.prompt('输入新的目录名称', '重命名目录', { inputValue: dir.name, inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).catch(() => ({ value: '' }))
if (!value || value.trim() === dir.name) return
try {
await renameSuffixDir(dir.id, value.trim())
await loadTree()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '重命名失败')
}
}
async function removeDir(dir: SuffixDir) {
await ElMessageBox.confirm(`删除「${dir.name}」会连同它的子目录、列和已填内容一起删除,确定吗?`, '删除目录', { type: 'warning' }).catch(() => null)
|| (() => { return })()
try {
await deleteSuffixDir(dir.id)
if (selected.value.kind === 'dir' && selected.value.id === dir.id) selected.value = { kind: 'basic' }
await loadTree()
ElMessage.success('目录已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
async function moveDir(dir: SuffixDir, dirNum: number) {
try {
await moveSuffixDir(dir.id, dirNum)
await loadTree()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '移动失败')
}
}
// ---- 基本设置:分组与后缀 ----
async function addGroup() {
const { value } = await ElMessageBox.prompt('输入分组名称(如:广东省)', '新建分组', { inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).catch(() => ({ value: '' }))
if (!value) return
try {
await createSuffixGroup(value.trim())
await loadOverview()
ElMessage.success('分组已创建')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '创建失败')
}
}
async function renameGroup(id: number, old: string) {
const { value } = await ElMessageBox.prompt('输入新的分组名称', '重命名分组', { inputValue: old, inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).catch(() => ({ value: '' }))
if (!value || value.trim() === old) return
try {
await renameSuffixGroup(id, value.trim())
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '重命名失败')
}
}
async function moveGroup(id: number, dir: number) {
try {
await moveSuffixGroup(id, dir)
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '移动失败')
}
}
async function removeGroup(g: { id:number; name:string }) {
try {
await ElMessageBox.confirm(`删除分组「${g.name}」会连同它下面的后缀与已上传模板一起删除,确定吗?`, '删除分组', { type: 'warning' })
} catch { return }
try {
await deleteSuffixGroup(g.id)
await loadOverview()
ElMessage.success('分组已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
async function insertSuffixAfter(groupId: number, afterId: number) {
try {
const created = (await createSuffix(groupId, afterId)).data.data
renamingSuffix.value = created.id
renamingSuffixName.value = ''
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '插入失败')
}
}
async function moveSuffixRow(id: number, dir: number) {
try {
await moveSuffix(id, dir)
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '移动失败')
}
}
async function removeSuffix(s: { id:number; name:string }) {
try {
await ElMessageBox.confirm(`删除后缀「${s.name || '(未命名)'}」会连同它名下的模板文件一起删除,确定吗?`, '删除后缀', { type: 'warning' })
} catch { return }
try {
await deleteSuffix(s.id)
await loadOverview()
ElMessage.success('后缀已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
function startRename(id: number, name: string) {
renamingSuffix.value = id
renamingSuffixName.value = name
}
async function commitRename() {
const id = renamingSuffix.value
const name = renamingSuffixName.value.trim()
renamingSuffix.value = 0
if (!id) return
try {
await renameSuffix(id, name)
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '改名失败')
}
}
async function onUploadPicked(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
const suffixId = uploadTarget.value
uploadTarget.value = 0
if (!file || !suffixId) return
uploading.value = true
try {
const payload = await readSuffixFile(file)
await uploadSuffixFile(suffixId, { file_name: file.name, size: payload.size, sha256: payload.sha256, content_base64: payload.content_base64 })
await loadOverview()
ElMessage.success(`已上传「${file.name}」`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '上传失败')
} finally {
uploading.value = false
}
}
function pickUpload(suffixId: number) {
uploadTarget.value = suffixId
uploadInput.value?.click()
}
async function removeFile(file: SuffixFile) {
try {
await ElMessageBox.confirm(`删除模板「${file.file_name}」?`, '删除模板', { type: 'warning' })
} catch { return }
try {
await deleteSuffixFile(file.id)
await loadOverview()
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
// ---- 目录工作区:列 / 单元格 / 锚定 ----
const pageColumns = computed<SuffixColumn[]>(() => page.value?.columns || [])
async function openAddColumn() {
if (selected.value.kind !== 'dir') return
colDialog.name = ''
colDialog.isValue = false
colDialog.visible = true
}
async function submitColumn() {
if (selected.value.kind !== 'dir' || colDialog.saving) return
const name = colDialog.name.trim()
if (!name) {
ElMessage.warning('请填写列名')
return
}
colDialog.saving = true
try {
const created = (await createSuffixColumn(selected.value.id, name, colDialog.isValue)).data.data
page.value?.columns.push(created)
colDialog.visible = false
ElMessage.success(colDialog.isValue ? `已添加值列「${created.name}」,点击它的单元格即可填写值设置` : `已添加列「${created.name}」`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '列创建失败')
} finally {
colDialog.saving = false
}
}
async function removeColumn(col: SuffixColumn) {
try {
await ElMessageBox.confirm(`删除列「${col.name}」会连同这一列已填的内容一起删除,确定吗?`, '删除列', { type: 'warning' })
} catch { return }
try {
await deleteSuffixColumn(col.id)
if (page.value) page.value.columns = page.value.columns.filter((c) => c.id !== col.id)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
function cellKey(sid: number, cid: number) { return `${sid}:${cid}` }
function cellDisplay(sid: number, col: SuffixColumn):string {
const raw = page.value?.cells[cellKey(sid, col.id)] || ''
if (!raw) return ''
if (col.is_value) {
const p = parseValueCell(raw)
return [p.a, p.v].filter(Boolean).join('=')
}
return raw
}
function startCellEdit(sid: number, col: SuffixColumn) {
const raw = page.value?.cells[cellKey(sid, col.id)] || ''
const p = parseValueCell(raw)
editing.sid = sid
editing.cid = col.id
editing.a = p.a
editing.v = p.v
editing.text = col.is_value ? '' : raw
}
function cancelCellEdit() {
editing.sid = 0
editing.cid = 0
}
async function commitCellEdit() {
const sid = editing.sid
const cid = editing.cid
if (!sid || !cid || !page.value) { cancelCellEdit(); return }
const col = page.value.columns.find((c) => c.id === cid)
const value = col?.is_value ? buildValueCell(editing.a.trim(), editing.v.trim()) : editing.text.trim()
cancelCellEdit()
try {
await saveSuffixCell(page.value.dir_id, sid, cid, value)
if (page.value) {
if (value) page.value.cells[cellKey(sid, cid)] = value
else delete page.value.cells[cellKey(sid, cid)]
}
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '保存失败')
}
}
async function toggleAnchor(sid: number, current: boolean) {
if (selected.value.kind !== 'dir' || !page.value) return
try {
await setSuffixAnchor(selected.value.id, sid, !current)
const line = page.value.suffixes.find((s) => s.id === sid)
if (line) line.anchor = !current
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '锚定失败')
}
}
function toggleRowEdit(sid: number) {
const next = new Set(editRows.value)
if (next.has(sid)) next.delete(sid)
else next.add(sid)
editRows.value = next
}
// 目录工作区的行(按分组分组的组头 + 后缀行)
type WorkspaceRow = { type: 'group'; key: string; name: string; count: number }
| { type: 'suffix'; key: string; sid: number; name: string; groupId: number; groupName: string; anchor: boolean }
const selectedDirName = computed(() => {
const sel = selected.value
if (sel.kind !== 'dir') return ''
return dirs.value.find((d) => d.id === sel.id)?.name || ''
})
const workspaceRows = computed(() => {
const rows: WorkspaceRow[] = []
let lastGroup = ''
for (const s of page.value?.suffixes || []) {
if (s.group_name !== lastGroup) {
rows.push({ type: 'group', key: 'g:' + s.group_id, name: s.group_name, count: 0 })
lastGroup = s.group_name
}
rows.push({ type: 'suffix', key: 's:' + s.id, sid: s.id, name: s.name, groupId: s.group_id, groupName: s.group_name, anchor: s.anchor })
}
for (const row of rows) {
if (row.type === 'group') {
row.count = (page.value?.suffixes || []).filter((s) => s.group_name === row.name).length
}
}
return rows
})
onMounted(() => {
loadOverview()
loadTree()
})
</script>
<template>
<div class="suffix-shell">
<aside class="suffix-side">
<div class="side-root" :class="{ active: selected.kind === 'basic' }" @click="selectNode({ kind: 'basic' })">基本设置</div>
<div class="side-sep"></div>
<div
class="side-root"
:class="{ active: selected.kind === 'dir' && selected.id === rootDir?.id }"
@click="rootDir && selectNode({ kind: 'dir', id: rootDir.id })"
>
<span v-if="rootDir && rootDir.children > 0" class="tw" @click.stop="rootDir && toggleExpand(rootDir)">{{ expanded.has(rootDir.id) ? '▾' : '▸' }}</span>
<span>按信息价的目录</span>
<span class="side-plus" title="新建一级目录" @click.stop="rootDir && addDir(rootDir.id, '新建目录')">+</span>
</div>
<template v-for="node in visibleNodes" :key="node.dir.id">
<div v-if="!isRoot(node.dir)" class="side-node" :style="{ paddingLeft: 14 + node.depth * 18 + 'px' }">
<span class="tw" :class="{ off: !node.dir.children }" @click.stop="node.dir.children && toggleExpand(node.dir)">{{ node.dir.children ? (expanded.has(node.dir.id) ? '▾' : '▸') : '·' }}</span>
<span class="side-name" :class="{ active: selected.kind === 'dir' && selected.id === node.dir.id }" @click="selectNode({ kind: 'dir', id: node.dir.id })">{{ node.dir.name }}</span>
<span class="side-count">{{ node.dir.children }}</span>
<span class="side-ops">
<button type="button" title="新建子目录" @click.stop="addDir(node.dir.id, '新建子目录')">+子</button>
<button type="button" title="新建平级目录" @click.stop="addDir(node.dir.parent_id, '新建平级目录')">+平</button>
<button type="button" title="重命名" @click.stop="renameDir(node.dir)">✎</button>
<button type="button" title="上移" @click.stop="moveDir(node.dir, -1)">↑</button>
<button type="button" title="下移" @click.stop="moveDir(node.dir, 1)">↓</button>
<button type="button" class="danger" title="删除" @click.stop="removeDir(node.dir)">×</button>
</span>
</div>
</template>
</aside>
<main class="suffix-main">
<!-- 基本设置:分组 + 后缀 + 模板 -->
<template v-if="selected.kind === 'basic'">
<div class="bar">
<strong>基本设置</strong>
<span class="bar-note">先在这里建分组与后缀,各目录工作区的行会跟着这里的顺序走。</span>
<span class="grow"></span>
<el-button size="small" @click="addGroup">+ 新建分组</el-button>
</div>
<div v-loading="overviewLoading" class="sheet-wrap">
<div v-for="g in groups" :key="g.id" class="group-block">
<div class="group-head">
<span class="tw off">▾</span>
<strong class="g-name" title="双击重命名" @dblclick="renameGroup(g.id, g.name)">{{ g.name }}</strong>
<span class="muted">{{ g.suffixes.length }} 个</span>
<span class="grow"></span>
<button type="button" class="op" title="上移" @click="moveGroup(g.id, -1)">↑</button>
<button type="button" class="op" title="下移" @click="moveGroup(g.id, 1)">↓</button>
<button type="button" class="op danger" title="删除分组" @click="removeGroup(g)">×</button>
</div>
<div v-for="(s, i) in g.suffixes" :key="s.id" class="suffix-row">
<span class="c-idx">{{ i + 1 }}</span>
<span class="c-suffix">
<template v-if="renamingSuffix === s.id">
<input
v-model="renamingSuffixName"
class="cell-input"
autofocus
@keyup.enter="commitRename"
@blur="commitRename"
/>
</template>
<template v-else>
<span class="suffix-name" :class="{ empty: !s.name }" title="双击重命名" @dblclick="startRename(s.id, s.name)">{{ s.name || '(双击命名)' }}</span>
</template>
</span>
<span class="c-files">
<span v-for="f in s.files" :key="f.id" class="file-chip">
<a :href="suffixFileUrl(f.id)" target="_blank" rel="noopener" :title="`下载 ${f.file_name}(${formatSuffixSize(f.file_size)})`">{{ f.file_name }}</a>
<button type="button" class="chip-x" title="删除模板" @click="removeFile(f)">×</button>
</span>
<span v-if="!s.files.length" class="muted">—</span>
</span>
<span class="c-ops">
<button type="button" class="btn-main" :disabled="uploading" @click="pickUpload(s.id)">上传模板</button>
<button type="button" class="op" title="在这行下面插入一行" @click="insertSuffixAfter(g.id, s.id)">向下插入行</button>
<button type="button" class="op" title="上移" @click="moveSuffixRow(s.id, -1)">↑</button>
<button type="button" class="op" title="下移" @click="moveSuffixRow(s.id, 1)">↓</button>
<button type="button" class="op danger" title="删除后缀" @click="removeSuffix(s)">×</button>
</span>
</div>
<div v-if="!g.suffixes.length" class="suffix-row empty-row"><span class="c-idx">—</span><span class="muted">这个分组还没有后缀</span></div>
</div>
<div v-if="!groups.length" class="empty-tip">还没有分组,点右上角「+ 新建分组」开始。</div>
</div>
</template>
<!-- 目录工作区 -->
<template v-else-if="page">
<div class="bar">
<strong>{{ selectedDirName }}</strong>
<span class="bar-note">点「+ 添加列」加列;勾选「值设置」的列,点单元格即可填 锚点+值。</span>
<span class="grow"></span>
<el-button size="small" type="primary" plain @click="openAddColumn">+ 添加列</el-button>
</div>
<div v-loading="pageLoading" class="sheet-wrap">
<table class="sheet">
<thead>
<tr>
<th class="fix">序号</th>
<th class="fix">后缀</th>
<th class="fix">操作</th>
<th class="fix">锚定行</th>
<th v-for="col in pageColumns" :key="col.id" class="custom-th">
<span :title="col.is_value ? '值列:点单元格填 锚点+值' : col.name">{{ col.name }}<em v-if="col.is_value" class="vtag">值</em></span>
<button type="button" class="th-x" title="删除列" @click="removeColumn(col)">×</button>
</th>
</tr>
</thead>
<tbody>
<template v-for="row in workspaceRows" :key="row.key">
<tr v-if="row.type === 'group'" class="group-tr">
<td colspan="4" class="group-td">− {{ row.name }} <span class="muted">{{ row.count }} 个</span></td>
<td v-for="col in pageColumns" :key="col.id" class="group-td"></td>
</tr>
<tr v-else class="data-tr" :class="{ editing: editRows.has(row.sid) }">
<td class="fix idx">{{ workspaceRows.filter((r) => r.type === 'suffix').findIndex((r) => (r as any).sid === row.sid) + 1 }}</td>
<td class="fix">{{ row.name || '—' }}</td>
<td class="fix">
<button type="button" class="btn-edit" :class="{ on: editRows.has(row.sid) }" @click="toggleRowEdit(row.sid)">编辑</button>
</td>
<td class="fix anchor" @click="toggleAnchor(row.sid, row.anchor)">{{ row.anchor ? '1' : '—' }}</td>
<td
v-for="col in pageColumns"
:key="col.id"
class="cell"
@click="startCellEdit(row.sid, col)"
>
<template v-if="editing.sid === row.sid && editing.cid === col.id">
<span class="cell-editor" @click.stop>
<template v-if="col.is_value">
<input v-model="editing.a" class="cell-input half" placeholder="锚点" @keyup.enter="commitCellEdit" @keyup.esc="cancelCellEdit" />
<input v-model="editing.v" class="cell-input half" placeholder="值" @keyup.enter="commitCellEdit" @keyup.esc="cancelCellEdit" />
</template>
<template v-else>
<input v-model="editing.text" class="cell-input" @keyup.enter="commitCellEdit" @keyup.esc="cancelCellEdit" />
</template>
<button type="button" class="op" title="确定" @click.stop="commitCellEdit">✓</button>
</span>
</template>
<template v-else>
<span v-if="cellDisplay(row.sid, col)" class="cell-text" :class="{ value: col.is_value }">{{ cellDisplay(row.sid, col) }}</span>
<span v-else class="cell-empty">—</span>
</template>
</td>
</tr>
</template>
<tr v-if="!workspaceRows.length">
<td :colspan="4 + pageColumns.length" class="empty-tip">先去「基本设置」建分组和后缀,这里才有行。</td>
</tr>
</tbody>
</table>
</div>
</template>
</main>
<input ref="uploadInput" type="file" class="hidden-file" @change="onUploadPicked" />
<el-dialog v-model="colDialog.visible" title="添加列" width="420px">
<div class="col-form">
<label><span class="lab">列名</span>
<el-input v-model="colDialog.name" placeholder="输入列名,例如:招标人" maxlength="190" @keyup.enter="submitColumn" />
</label>
<label class="val-line">
<el-checkbox v-model="colDialog.isValue">值设置</el-checkbox>
<span class="muted">勾选后该列为值列,点击单元格可填写 锚点+值;不勾选则为普通列,不可填值设置。</span>
</label>
</div>
<template #footer>
<el-button @click="colDialog.visible = false">取消</el-button>
<el-button type="primary" :loading="colDialog.saving" @click="submitColumn">确定</el-button>
</template>
</el-dialog>
</div>
</template>
<style scoped>
.suffix-shell{display:flex;gap:14px;min-height:420px;align-items:stretch}
.suffix-side{flex:0 0 280px;max-width:320px;border:1px solid #e5eaf0;border-radius:6px;background:#fbfcfe;padding:10px 8px;overflow:auto;max-height:70vh}
.side-root{display:flex;align-items:center;gap:6px;padding:7px 10px;border-radius:5px;cursor:pointer;font-weight:600;font-size:13.5px}
.side-root.active,.side-root:hover{background:#eaf2fd}
.side-sep{height:1px;background:#e5eaf0;margin:8px 4px}
.side-node{display:flex;align-items:center;gap:4px;padding:4px 6px;border-radius:5px;font-size:13px;position:relative;flex-wrap:nowrap;overflow:hidden}
.side-node:hover{background:#f1f5fb}
.side-name{cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0}
.side-name.active{color:#1769e0;font-weight:600}
.side-node:hover .side-ops{visibility:visible}
.side-ops{visibility:hidden;display:inline-flex;gap:2px;margin-left:auto}
.side-ops button{border:0;background:none;cursor:pointer;font-size:11px;color:#526173;padding:1px 3px;border-radius:3px}
.side-ops button:hover{background:#dfe9f7;color:#1769e0}
.side-ops button.danger:hover{background:#fbe0dc;color:#b44830}
.tw{width:14px;text-align:center;color:#8a97a8;cursor:pointer;user-select:none}
.tw.off{cursor:default;color:#c3ccd8}
.side-count{margin-left:0;color:#9aa7b6;font-size:11px;flex:0 0 auto}
.side-plus{margin-left:auto;color:#1769e0;cursor:pointer;font-weight:700}
.suffix-main{flex:1;min-width:0}
.bar{display:flex;align-items:center;gap:12px;padding:0 0 10px}
.bar strong{font-size:15px}
.bar-note{color:#8a97a8;font-size:12px}
.grow{flex:1}
.sheet-wrap{border:1px solid #e5eaf0;border-radius:6px;overflow:auto;max-height:68vh;background:#fff}
.group-block{border-bottom:1px solid #eef1f5}
.group-block:last-child{border-bottom:0}
.group-head{display:flex;align-items:center;gap:8px;padding:8px 12px;background:#f4f6fa;border-bottom:1px solid #eef1f5}
.g-name{font-size:13px}
.muted{color:#9aa7b6;font-size:12px}
.op{border:1px solid #d8dfe8;background:#fff;border-radius:4px;cursor:pointer;font-size:12px;color:#3c4a5c;padding:2px 8px}
.op:hover{border-color:#1769e0;color:#1769e0}
.op.danger:hover{border-color:#b44830;color:#b44830}
.btn-main{border:1px solid #1769e0;background:#1769e0;color:#fff;border-radius:4px;cursor:pointer;font-size:12px;padding:3px 10px}
.btn-main:hover{background:#125cc4}
.btn-main:disabled{opacity:.6;cursor:default}
.btn-edit{border:1px solid #d8dfe8;background:#fff;border-radius:4px;cursor:pointer;font-size:12px;padding:2px 10px}
.btn-edit.on{border-color:#1769e0;color:#1769e0;background:#eaf2fd}
.suffix-row{display:flex;align-items:center;gap:10px;padding:7px 12px;border-bottom:1px solid #f2f5f8}
.suffix-row:hover{background:#fafcff}
.empty-row{color:#9aa7b6}
.c-idx{flex:0 0 34px;color:#9aa7b6;font-size:12px}
.c-suffix{flex:0 0 140px}
.suffix-name{cursor:text}
.suffix-name.empty{color:#9aa7b6}
.c-files{flex:1;display:flex;gap:8px;flex-wrap:wrap;min-width:0}
.file-chip{display:inline-flex;align-items:center;gap:4px;border:1px solid #d8e4f5;background:#f2f7ff;border-radius:4px;padding:1px 6px;font-size:12px}
.file-chip a{color:#1769e0;text-decoration:none;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.chip-x{border:0;background:none;cursor:pointer;color:#8a97a8;padding:0 2px}
.chip-x:hover{color:#b44830}
.c-ops{display:flex;gap:6px;flex:0 0 auto}
.empty-tip{padding:26px;text-align:center;color:#9aa7b6;font-size:13px}
.hidden-file{display:none}
table.sheet{border-collapse:collapse;width:100%;font-size:13px}
table.sheet th,table.sheet td{border-right:1px solid #eef1f5;border-bottom:1px solid #eef1f5;padding:6px 10px;text-align:left;white-space:nowrap}
table.sheet thead th{background:#f4f6fa;color:#657387;font-weight:600;position:relative}
.fix{background:#fff}
thead .fix{background:#f4f6fa}
th.fix{min-width:52px}
td.idx{color:#9aa7b6;font-size:12px}
table.sheet thead th:nth-child(2),table.sheet tbody td:nth-child(2){min-width:110px}
.custom-th:hover .th-x{visibility:visible}
.th-x{visibility:hidden;border:0;background:none;cursor:pointer;color:#b44830;margin-left:6px}
.vtag{font-style:normal;background:#e6f5ee;color:#16845b;border-radius:3px;font-size:10px;padding:0 4px;margin-left:4px}
.group-tr td{background:#f8fafc;color:#526173;font-size:12.5px}
.data-tr.editing td{background:#f6faff}
td.cell{cursor:text;min-width:120px;max-width:320px;overflow:hidden;text-overflow:ellipsis}
td.cell:hover{background:#f7faff}
.cell-text.value{color:#1769e0}
.cell-empty{color:#c3ccd8}
.cell-editor{display:inline-flex;gap:4px;align-items:center}
.cell-input{font:inherit;border:1px solid #1769e0;border-radius:3px;padding:2px 6px;min-width:150px}
.cell-input.half{min-width:70px;width:70px}
.col-form{display:grid;gap:14px}
.col-form label{display:grid;gap:6px}
.lab{font-size:12px;font-weight:600;color:#526173}
.val-line{display:flex !important;align-items:center;gap:8px}
.val-line .muted{font-size:12px}
td.anchor{cursor:pointer;text-align:center;color:#9aa7b6}
td.anchor:hover{color:#1769e0}
</style>