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

1035 lines
31 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"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/columns/order", a.reorderSuffixColumns)
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"`
AfterID uint64 `json:"after_id"`
}
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
}
sortAt := -1
if in.AfterID > 0 {
var afterSort int
var afterDir uint64
if err := a.db.QueryRowContext(c,
"SELECT sort_order,dir_id FROM suffix_columns WHERE id=?", in.AfterID).Scan(&afterSort, &afterDir); err != nil || afterDir != dirID {
apiError(c, 404, "not_found", "插入位置的列不存在")
return
}
if _, err := a.db.ExecContext(c,
"UPDATE suffix_columns SET sort_order=sort_order+1 WHERE dir_id=? AND sort_order>?",
dirID, afterSort); err != nil {
apiError(c, 500, "internal_error", "列创建失败")
return
}
sortAt = afterSort
} else {
var order sql.NullInt64
_ = a.db.QueryRowContext(c,
"SELECT MAX(sort_order) FROM suffix_columns WHERE dir_id=?", dirID).Scan(&order)
sortAt = int(order.Int64)
}
res, err := a.db.ExecContext(c,
"INSERT INTO suffix_columns(dir_id,name,is_value,sort_order) VALUES(?,?,?,?)",
dirID, name, in.IsValue, sortAt+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) reorderSuffixColumns(c *gin.Context) {
dirID, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var in struct {
IDs []uint64 `json:"ids"`
}
if c.ShouldBindJSON(&in) != nil || len(in.IDs) == 0 {
apiError(c, 400, "invalid_request", "ids 必须为非空数组")
return
}
// 校验:id 必须属于该目录且不可重复;没传进来的列按原顺序补到末尾,防漏传错位。
owned := map[uint64]int{}
rows, err := a.db.QueryContext(c,
"SELECT id,sort_order FROM suffix_columns WHERE dir_id=? ORDER BY sort_order ASC,id ASC", dirID)
if err != nil {
apiError(c, 500, "internal_error", "列加载失败")
return
}
original := []uint64{}
for rows.Next() {
var cid uint64
var so int
if err := rows.Scan(&cid, &so); err != nil {
rows.Close()
apiError(c, 500, "internal_error", "列加载失败")
return
}
owned[cid] = so
original = append(original, cid)
}
rows.Close()
seen := map[uint64]bool{}
for _, cid := range in.IDs {
if _, ok := owned[cid]; !ok {
apiError(c, 404, "not_found", fmt.Sprintf("列不属于该目录: %d", cid))
return
}
if seen[cid] {
apiError(c, 400, "invalid_request", "ids 重复")
return
}
seen[cid] = true
}
final := []uint64{}
final = append(final, in.IDs...)
for _, cid := range original {
if !seen[cid] {
final = append(final, cid)
}
}
for i, cid := range final {
if _, err := a.db.ExecContext(c,
"UPDATE suffix_columns SET sort_order=? WHERE id=?", i, cid); err != nil {
apiError(c, 500, "internal_error", "排序失败")
return
}
}
c.JSON(200, gin.H{"data": gin.H{"ok": true, "ordered": len(final)}})
}
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
}