Compare commits
6 Commits
682f8737d0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fdac9902d | ||
|
|
ac4b4a1c06 | ||
|
|
4ebf0afc22 | ||
|
|
2d2bf50d11 | ||
|
|
2d9dcba800 | ||
|
|
dd9d5470c2 |
23
AGENTS.md
Normal file
23
AGENTS.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# 项目协作约定(长期记忆)
|
||||
|
||||
- 本项目是新开发软件,尚未交付真实用户:**不需要考虑旧数据 / 旧接口 / 旧存储路径的向后兼容**,直接切换到目标设计即可(例:附件存储目录从 suffix-templates 切到 attachments 时无需保留回退逻辑)。
|
||||
- 每次动手改代码前,先与用户核对任务清单,确认后再开工(用户定的铁律)。
|
||||
- 填 cos4 后缀管理数据时:**每一层先出草稿**(完整目录树 + 锚定行 + 每目录字段表「列名→填入值」),用户确认后才执行。
|
||||
- **重复明细条目只填一行代表**(如 AttrInfoItem/AddiInfoItem 在 XML 里重复多次,数据里填一条即可),但必须**记住 XML 的数据层级结构**(元素嵌套关系)。
|
||||
- **层级不同就各建目录,字段相同就克隆字段配置**(同一元素在多处出现,如 SummaryOfCost 挂在 建设项目/建筑安装工程费/单项工程 下,各自建目录,锚定行同名,字段列复制)。
|
||||
- **自嵌套元素**(如 AddiInfoItem 套 AddiInfoItem,标准中「支持树形结构」的明细元素):目录下建**同名子目录、克隆同样字段**,树里表达一层嵌套即可,租户端按真实数据递归展开。
|
||||
- **枚举字段的值设置列(2026-10-31 用户定稿:横向含义列)**:枚举属性表达为**每个含义一列**——列名=含义词,勾选值设置(is_value=true),格子存 `{"a":"字段名","v":"代码"}`(锚点=该枚举的属性英文名,值=该含义在此格式下的代码);属性本体列另建、普通列(格子=属性英文名),名用短名或标准中文解释。N 个含义 = N 个含义列 + 1 个本体列(N+1 处字段名)。值设置含义列组整体排在**锚定行右边、其他字段列左边**;同目录多枚举按组连排(各组含义列→各本体列→普通字段列)。不同地区代码不同时,各后缀行填各自代码。工料机汇总已全量改造:Kind(9 含义列:人工费~其他 + 本体「类型」)、ExtKind(3:普通工料/人工降效/机具降效 + 本体「扩展属性」)、Provider(3:乙供/甲供/甲招乙供 + 本体「供料方式」)。Class 工料机归属、PriceSource 价格来源是自由文本,保持普通列。
|
||||
- **列名取名规则(全列统一)**:列名一律取 2025 标准属性表该属性的「中文解释」原词(如 Kind→汇总类型、LockKind→锁定类别),不自造、不用英文名当列名;值设置列与普通列同规。格子值:值设置列存 `{"a":含义串,"v":代码串}`;普通列存两家实际导出的属性英文名。**值设置列判定**:标准里属性为 Integer 且注释给出「1=xx;2=xx」枚举 → 值设置列;自由文本(如 Class 工料机归属、PriceSource 价格来源)→ 普通列。OCR 丢中文名时用 2018 版全文交叉补(Volume=册),仍缺的语境推定并标「待核」。
|
||||
- **填数据不走脚本**:直接在管理台界面上操作(浏览器自动化),目录 → 字段(列)→ 字段名称(单元格值)按此顺序填。
|
||||
|
||||
## cos4 后缀管理数据规律(2026-10-30 与用户共同确立)
|
||||
|
||||
- **蓝本**:以广联达、易达两家实际导出的 cos4 文件为唯一蓝本(样例:`后台需要导入的项目/广联达导出最新架子.COS4`、`1易达导出骨架.cos4`;cos4=ZIP,内含 Project.xml + 若干单位工程 xml)。
|
||||
- **目录=XML元素**:后台「按信息价目录」树的每个目录对应 cos4 里的一个 XML 元素;目录的**锚定行**填该元素的英文名(如 建设项目→ConstructionProject);目录中文名取自 DBJ/T 15-145-2025 第 6 章对应表(参考资料在 AdminCost/参考资料/规范与COS4/)。
|
||||
- **列=元素属性**:目录里的列 = 该元素的属性;列名用 2025 标准属性表的「中文解释」;单元格值 = **两家实际导出的属性英文名**,并以**两家字段的并集**为准——不是标准全集,也不是单家。
|
||||
- **以实际为准 + 提醒**:填入值一律以两家实际导出为准,不按标准拼写改(例:两家都把 BuildUnit 拼成 `BulidUnit`,按错的填);与标准不一致(拼写差异、某家缺失、标准有但两家都没导出)时必须向用户提醒。已知差异:建设单位/法定代表人两家都拼错(BulidUnit/BulidAuthorizer);`BulidAuthorizer` 仅易达导出;标准表 6.2.1 的 4 个价格指数字段(ProjectIndex/LabourPriceIndex/MaterialPriceIndex/MachinePriceIndex)两家均未导出,故不建列。
|
||||
- **进度**:建设项目(ConstructionProject)已补全 22 列 + cos4 行 22 格(2026-10-30)。cos 行(老格式)留空,后续单独讨论。
|
||||
- **操作注意**:用 curl 调后端 API 填中文时,必须把 JSON 写进 UTF-8 文件用 `--data-binary @file` 发送;中文放命令行参数会被 Windows 代码页转成乱码(EFBFBD)。
|
||||
- **同名属性按锚定行分别查原表(2026-10-31 用户铁律)**:同一英文属性(如 Kind/Specialty/CalculationKind/EfficiencyKind/IncFeeKind)在不同锚定行(元素)下的中文解释与枚举值**可能完全不同**,填值设置前必须逐表核对原出处(md 表 → 2018 版交叉 → 原 PDF)。已实证差异:Specialty 专业类别在 WorkElement=12 项 / UnitWorks=21 项 / **Norm=19 项**(含 城市轨道交通(建筑)=8、城市轨道交通(安装)=16、建筑与装饰修缮=12、安装修缮=13、传统建筑(古建筑)=15、地下管廊建筑=17、地下管廊安装=18、古驿道=21,2=仿古建筑 OCR 缺按 2018 补);EfficiencyKind 降效类型 2025=3 项(1需计算降效费用的基础定额/2不需计算…/3降效费用定额,**与 2018 的 4 项不同**);IncFeeKind 2025=3 项(1需计算子目增加费的基础定额/2不需计算…/3子目增加费定额);Volume=册。汇总类型 Kind/章节类型 ChapterKind/锁定类别/取费类型/费用归属/单价计算方式/合价计算方式/子目类型 各锚定行同义。
|
||||
- **列名核对工具**:审计脚本做法——从 2025 版 md 解析每元素属性表(注意 OCR 陷阱:属性名常在「序号」列且序号列可能为空、长属性名折行连写(TechnicalAndEcono-+micIndex)、中文解释词序颠倒),与库内 列名/格子值 按锚定行逐一比对;解析器分隔行守卫不能误杀空序号行。
|
||||
- **枚举映射核实来源**:2025 版 OCR 的枚举注缺失时,用同目录 2018 版全文(DBJT15-145-2018_全文含表格.md)交叉核对(文本干净)。已核实:降效类型 EfficiencyKind(1降效基础定额/2非降效定额/3按市场价计算降效费用定额/4按定额价计算降效费用定额)、子目增加费类型 IncFeeKind(1子目增加费基础定额/2非子目增加费定额/3子目增加费用计算定额)、快速计算的 Kind=汇总类型(1汇总条目/2不汇总条目)、Volume=册(册号,无分册填0)。唯一残留待核:Norm 的 Chapter 列中文名两版文字均缺失,按语境暂记「章(待核)」(2025 原始 PDF 4793785.pdf 本地不存在,需要时向用户索取)。
|
||||
@@ -98,6 +98,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
purchaseAdmin.POST("/purchase-credentials", a.createPurchaseCredential)
|
||||
purchaseAdmin.PUT("/purchase-credentials/:id", a.updatePurchaseCredential)
|
||||
secured := api.Group("", a.authenticated)
|
||||
registerSuffixRoutes(secured, a)
|
||||
secured.GET("/me", a.me)
|
||||
secured.GET("/admins", a.listAdmins)
|
||||
secured.POST("/admins", a.createAdmin)
|
||||
|
||||
@@ -175,8 +175,10 @@ func (o *Operations) Middleware() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
}
|
||||
// Uploads have their own 64 MiB streaming bound; other JSON routes get a 64 KiB ceiling.
|
||||
if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") {
|
||||
// Uploads have their own streaming bounds (releases 64 MiB; suffix templates
|
||||
// bound in their handler); other JSON routes get a 64 KiB ceiling.
|
||||
if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") &&
|
||||
!(path == "/api/v1/suffix-admin/suffixes/:id/files" && c.Request.Method == "POST") {
|
||||
if c.Request.ContentLength > 64<<10 {
|
||||
apiError(c, 413, "body_too_large", "Request body too large")
|
||||
c.Abort()
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const RequiredSchemaVersion = 16
|
||||
const RequiredSchemaVersion = 21
|
||||
|
||||
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
||||
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
||||
|
||||
1278
backend/internal/httpapi/suffixes.go
Normal file
1278
backend/internal/httpapi/suffixes.go
Normal file
File diff suppressed because it is too large
Load Diff
429
backend/internal/httpapi/suffixes_test.go
Normal file
429
backend/internal/httpapi/suffixes_test.go
Normal file
@@ -0,0 +1,429 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"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", "suffix_col_widths"} {
|
||||
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)
|
||||
storageRoot := t.TempDir()
|
||||
t.Setenv("PACKAGE_STORAGE_ROOT", storageRoot)
|
||||
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,"name":"cos4"}`, 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.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广西自治区","first_suffix_name":"xml"}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("建组带后缀 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
gx := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
|
||||
sx := getJSON(w)["data"].(map[string]any)["suffixes"].([]any)
|
||||
if len(sx) != 1 || sx[0].(map[string]any)["name"] != "xml" {
|
||||
t.Fatalf("首后缀自动行不符: %v", sx)
|
||||
}
|
||||
_ = gx
|
||||
// 同名再建 → 自动 -1
|
||||
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d,"name":"cos4"}`, groupID))
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("同名后缀 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := getJSON(w)["data"].(map[string]any)["name"]; got != "cos4-1" {
|
||||
t.Fatalf("同名自动 -1: got %v", got)
|
||||
}
|
||||
// 空名 → 400
|
||||
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d,"name":""}`, groupID))
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("空名 status=%d, want 400", w.Code)
|
||||
}
|
||||
|
||||
// 目录树:根 + 子目录 + 改名 + 删除保护
|
||||
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.MethodPut, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", rootID), `{"name":"建设项目"}`)
|
||||
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)
|
||||
if dirs[0].(map[string]any)["name"] != "建设项目" {
|
||||
t.Fatalf("改根名后=%v", dirs[0].(map[string]any)["name"])
|
||||
}
|
||||
|
||||
// 列(值设置勾选)+ 单元格 + 锚定
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("建普通列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
plainColID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"工料机类型","is_value":true}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("建值列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
valueColID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
|
||||
if w.Code != 409 {
|
||||
t.Fatalf("同目录重名列 status=%d, want 409", w.Code)
|
||||
}
|
||||
// 精准插入:插到 招标人 之后
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID),
|
||||
fmt.Sprintf(`{"name":"插队列","is_value":false,"after_id":%d}`, plainColID))
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("精准插列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
insertedID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
|
||||
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
|
||||
pageCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
|
||||
if pageCols[1].(map[string]any)["id"].(float64) != float64(insertedID) {
|
||||
t.Fatal("精准插列应落在 招标人 之后(第2位)")
|
||||
}
|
||||
// 列排序:插队列移回末位 → 顺序变为 招标人,工料机类型,插队列
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
|
||||
fmt.Sprintf(`{"ids":[%d,%d,%d]}`, plainColID, valueColID, insertedID))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("列排序 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
// 漏传列:没传的按原顺序补到末尾 → 顺序不变(招标人,工料机类型,插队列)
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
|
||||
fmt.Sprintf(`{"ids":[%d,%d]}`, plainColID, valueColID))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("漏传列补尾 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
// 外列 → 404
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
|
||||
`{"ids":[999999]}`)
|
||||
if w.Code != 404 {
|
||||
t.Fatalf("外列 status=%d, want 404", w.Code)
|
||||
}
|
||||
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
|
||||
orderedCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
|
||||
if orderedCols[0].(map[string]any)["name"] != "招标人" || orderedCols[1].(map[string]any)["name"] != "工料机类型" || orderedCols[2].(map[string]any)["name"] != "插队列" {
|
||||
t.Fatalf("排序后顺序不符: %v", orderedCols)
|
||||
}
|
||||
w = authed(http.MethodPut, "/api/v1/suffix-admin/cells",
|
||||
fmt.Sprintf(`{"dir_id":%d,"suffix_id":%d,"column_id":%d,"value":"普通文本"}`, dirID, suffixID, plainColID))
|
||||
if w.Code == 404 || w.Code == 400 {
|
||||
t.Fatalf("存普通单元格被拒 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// 工作区载荷
|
||||
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
|
||||
page := getJSON(w)["data"].(map[string]any)
|
||||
cols := page["columns"].([]any)
|
||||
if len(cols) != 3 {
|
||||
t.Fatalf("列数=%d, want 3", len(cols))
|
||||
}
|
||||
// 排序后顺序:招标人,工料机类型,插队列;第二列=值列
|
||||
if !cols[1].(map[string]any)["is_value"].(bool) {
|
||||
t.Fatal("第二列应为值列")
|
||||
}
|
||||
|
||||
// 列重命名:成功、同目录重名 409、空名 400
|
||||
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":"招标单位"}`)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("重命名列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if name := getJSON(w)["data"].(map[string]any)["name"].(string); name != "招标单位" {
|
||||
t.Fatalf("重命名后 name=%q, want 招标单位", name)
|
||||
}
|
||||
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":"工料机类型"}`)
|
||||
if w.Code != 409 {
|
||||
t.Fatalf("重名列 status=%d, want 409", w.Code)
|
||||
}
|
||||
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":" "}`)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("空名列 status=%d, want 400", w.Code)
|
||||
}
|
||||
|
||||
// 列有值不可删除:普通列已存「普通文本」
|
||||
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), "")
|
||||
if w.Code != 409 {
|
||||
t.Fatalf("删有值列 status=%d, want 409", w.Code)
|
||||
}
|
||||
// 空列可直接删除
|
||||
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", insertedID), "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("删空列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
// 清空单元格后即可删除
|
||||
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 != 200 {
|
||||
t.Fatalf("清空单元格 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("清空后删列 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// 固定列列宽:默认值(后缀 50)→ 保存 → 回读;非法参数拒绝
|
||||
w = authed(http.MethodGet, "/api/v1/suffix-admin/col-widths", "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("读列宽 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
widths := getJSON(w)["data"].(map[string]any)["widths"].(map[string]any)
|
||||
if widths["basic"].(map[string]any)["suffix"].(float64) != 50 {
|
||||
t.Fatalf("basic.suffix 默认应为 50,got %v", widths["basic"].(map[string]any)["suffix"])
|
||||
}
|
||||
if _, has := widths["basic"].(map[string]any)["files"]; !has {
|
||||
t.Fatal("basic 固定列应含 files")
|
||||
}
|
||||
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"workspace","key":"ops","width":66}`)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("存列宽 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
w = authed(http.MethodGet, "/api/v1/suffix-admin/col-widths", "")
|
||||
widths = getJSON(w)["data"].(map[string]any)["widths"].(map[string]any)
|
||||
if widths["workspace"].(map[string]any)["ops"].(float64) != 66 {
|
||||
t.Fatalf("workspace.ops 应为 66,got %v", widths["workspace"].(map[string]any)["ops"])
|
||||
}
|
||||
if widths["workspace"].(map[string]any)["suffix"].(float64) != 50 {
|
||||
t.Fatalf("未保存过的 workspace.suffix 应仍为默认 50,got %v", widths["workspace"].(map[string]any)["suffix"])
|
||||
}
|
||||
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"nope","key":"ops","width":66}`)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("非法 scope status=%d, want 400", w.Code)
|
||||
}
|
||||
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"basic","key":"files","width":9999}`)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("列宽越界 status=%d, want 400", w.Code)
|
||||
}
|
||||
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"basic","key":"nope","width":10}`)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("未知列 key status=%d, want 400", w.Code)
|
||||
}
|
||||
|
||||
// 锚定行存值:保存 → 回读;空值清除;超长拒绝
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
|
||||
fmt.Sprintf(`{"suffix_id":%d,"value":"3"}`, 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)
|
||||
cos4 := func() map[string]any {
|
||||
for _, line := range sfx {
|
||||
if line.(map[string]any)["name"] == "cos4" {
|
||||
return line.(map[string]any)
|
||||
}
|
||||
}
|
||||
t.Fatal("找不到 cos4 行")
|
||||
return nil
|
||||
}()
|
||||
if cos4["anchor_value"].(string) != "3" {
|
||||
t.Fatalf("锚定后 anchor_value=%q, want 3", cos4["anchor_value"])
|
||||
}
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
|
||||
fmt.Sprintf(`{"suffix_id":%d,"value":""}`, 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)
|
||||
for _, line := range sfx {
|
||||
if line.(map[string]any)["name"] == "cos4" && line.(map[string]any)["anchor_value"].(string) != "" {
|
||||
t.Fatal("清空后 anchor_value 应为空")
|
||||
}
|
||||
}
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
|
||||
fmt.Sprintf(`{"suffix_id":%d,"value":"%s"}`, suffixID, strings.Repeat("长", 191)))
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("超长锚定值 status=%d, want 400", w.Code)
|
||||
}
|
||||
|
||||
// 模板上传(内容与哈希校验)→ 概览 → 删除
|
||||
content := []byte("COS4-skeleton-demo")
|
||||
sum := sha256.Sum256(content)
|
||||
b64 := base64.StdEncoding.EncodeToString(content)
|
||||
// 扩展名与本行后缀不符 → 400
|
||||
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
|
||||
fmt.Sprintf(`{"file_name":"骨架.xml","size":%d,"sha256":"%s","content_base64":"%s"}`,
|
||||
len(content), hex.EncodeToString(sum[:]), b64))
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("扩展名不符 status=%d, want 400", w.Code)
|
||||
}
|
||||
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))
|
||||
// 附件必须落盘在 attachments/<后缀id>/ 下
|
||||
storedName := getJSON(w)["data"].(map[string]any)["file_name"].(string)
|
||||
if _, err := os.Stat(filepath.Join(storageRoot, "attachments", strconv.FormatUint(suffixID, 10), storedName)); err != nil {
|
||||
t.Fatalf("附件未落在 attachments 目录: %v", err)
|
||||
}
|
||||
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)
|
||||
var files []any
|
||||
for _, line := range groups[0].(map[string]any)["suffixes"].([]any) {
|
||||
m := line.(map[string]any)
|
||||
if m["name"] == "cos4" {
|
||||
files = m["files"].([]any)
|
||||
break
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
7
backend/migrations/000017_suffix_management.down.sql
Normal file
7
backend/migrations/000017_suffix_management.down.sql
Normal 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;
|
||||
69
backend/migrations/000017_suffix_management.up.sql
Normal file
69
backend/migrations/000017_suffix_management.up.sql
Normal file
@@ -0,0 +1,69 @@
|
||||
-- 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,
|
||||
width 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;
|
||||
1
backend/migrations/000018_suffix_col_widths.down.sql
Normal file
1
backend/migrations/000018_suffix_col_widths.down.sql
Normal file
@@ -0,0 +1 @@
|
||||
DROP TABLE suffix_col_widths;
|
||||
9
backend/migrations/000018_suffix_col_widths.up.sql
Normal file
9
backend/migrations/000018_suffix_col_widths.up.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
-- Suffix management fixed-column widths (basic settings + directory workspace tables).
|
||||
-- scope: 'basic' | 'workspace'; col_key: idx/suffix/files/ops/anchor; width 0 = auto.
|
||||
CREATE TABLE suffix_col_widths (
|
||||
scope VARCHAR(20) NOT NULL,
|
||||
col_key VARCHAR(32) NOT NULL,
|
||||
width INT NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||
PRIMARY KEY(scope,col_key)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
2
backend/migrations/000019_rename_suffix_root.down.sql
Normal file
2
backend/migrations/000019_rename_suffix_root.down.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- 回滚:恢复根目录名称
|
||||
UPDATE suffix_dirs SET name='按信息价的目录' WHERE parent_id IS NULL AND name='建设项目';
|
||||
2
backend/migrations/000019_rename_suffix_root.up.sql
Normal file
2
backend/migrations/000019_rename_suffix_root.up.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- 根目录改名:按信息价的目录 → 建设项目(目录现已支持重命名,此处仅迁移存量数据)
|
||||
UPDATE suffix_dirs SET name='建设项目' WHERE parent_id IS NULL AND name='按信息价的目录';
|
||||
1
backend/migrations/000020_suffix_anchor_value.down.sql
Normal file
1
backend/migrations/000020_suffix_anchor_value.down.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE suffix_dir_anchors DROP COLUMN value;
|
||||
2
backend/migrations/000020_suffix_anchor_value.up.sql
Normal file
2
backend/migrations/000020_suffix_anchor_value.up.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- 锚定行从 1/— 开关改为存值:value 为锚定内容(如行号),'' = 未锚定。
|
||||
ALTER TABLE suffix_dir_anchors ADD COLUMN value VARCHAR(190) NOT NULL DEFAULT '';
|
||||
1
backend/migrations/000021_suffix_file_publish.down.sql
Normal file
1
backend/migrations/000021_suffix_file_publish.down.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE suffix_files DROP COLUMN published;
|
||||
2
backend/migrations/000021_suffix_file_publish.up.sql
Normal file
2
backend/migrations/000021_suffix_file_publish.up.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- 骨架文件发布状态:0=未发布,1=已发布
|
||||
ALTER TABLE suffix_files ADD COLUMN published TINYINT(1) NOT NULL DEFAULT 0;
|
||||
@@ -5,7 +5,7 @@ import Checkout from './views/Checkout.vue'
|
||||
export default createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})),
|
||||
...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/suffixes',view:'suffixes'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})),
|
||||
{path:'/checkout',component:Checkout,meta:{public:true}},
|
||||
{path:'/customer',component:CustomerPortal},
|
||||
{path:'/:pathMatch(.*)*',redirect:'/'}
|
||||
|
||||
File diff suppressed because one or more lines are too long
79
frontend/src/suffix-admin.ts
Normal file
79
frontend/src/suffix-admin.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
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; width:number }
|
||||
export type SuffixLine = { id:number; group_id:number; group_name:string; name:string; anchor_value:string }
|
||||
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; published?:boolean }
|
||||
export type SuffixGroup = { id:number; name:string; suffixes:{ id:number; name:string; files:SuffixFile[] }[] }
|
||||
// 固定列列宽(basic: idx/suffix/files/ops;workspace: idx/suffix/ops/anchor),0=自适应
|
||||
export type SuffixColWidths = { basic:Record<string,number>; workspace:Record<string,number> }
|
||||
|
||||
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, after_id = 0, width = 0) => api.post<{data:SuffixColumn}>(`/suffix-admin/dirs/${dirId}/columns`, { name, is_value, after_id, width })
|
||||
export const updateSuffixColumnWidth = (id:number, width:number) => api.patch<{data:{id:number;width:number}}>(`/suffix-admin/columns/${id}`, { width })
|
||||
export const renameSuffixColumn = (id:number, name:string) => api.patch<{data:SuffixColumn}>(`/suffix-admin/columns/${id}`, { name })
|
||||
export const reorderSuffixColumns = (dirId:number, ids:number[]) => api.post<{data:{ok:boolean;ordered:number}}>(`/suffix-admin/dirs/${dirId}/columns/order`, { ids })
|
||||
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 getSuffixColWidths = () => api.get<{data:{widths:SuffixColWidths}}>('/suffix-admin/col-widths')
|
||||
export const updateSuffixColWidth = (scope:'basic'|'workspace', key:string, width:number) => api.put<{data:{scope:string;key:string;width:number}}>('/suffix-admin/col-widths', { scope, key, width })
|
||||
export const setSuffixAnchor = (dirId:number, suffix_id:number, value:string) => api.post(`/suffix-admin/dirs/${dirId}/anchor`, { suffix_id, value })
|
||||
export const getSuffixOverview = () => api.get<{data:{groups:SuffixGroup[]}}>('/suffix-admin/overview')
|
||||
export const createSuffixGroup = (name:string, first_suffix_name = '') => api.post<{data:SuffixGroup}>('/suffix-admin/groups', { name, first_suffix_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, name:string, after_id = 0) => api.post<{data:{id:number;group_id:number;name:string}}>('/suffix-admin/suffixes', { group_id, name, 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}`)
|
||||
// 大文件 base64 上传耗时较长,单独关闭全局 8s 超时,避免被前端掐断后只剩兜底报错。
|
||||
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, { timeout: 0 })
|
||||
export const deleteSuffixFile = (id:number) => api.delete(`/suffix-admin/files/${id}`)
|
||||
export const publishSuffixFile = (id:number, on:boolean) => api.post(`/suffix-admin/files/${id}/publish`, { on })
|
||||
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 })
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import OrdersPanel from './OrdersPanel.vue'
|
||||
import PaymentsPanel from './PaymentsPanel.vue'
|
||||
import ReleasesPanel from './ReleasesPanel.vue'
|
||||
import PurchasePlansPanel from './PurchasePlansPanel.vue'
|
||||
import SuffixPanel from './SuffixPanel.vue'
|
||||
import { listLicenseInstances, setInstanceFrozen, type LicenseInstance } from '../api'
|
||||
const selectedLicenseID = ref<number | null>(null), changingInstance = ref('')
|
||||
const freezeRetries = new Map<string, { frozen: boolean; key: string }>()
|
||||
@@ -39,9 +40,11 @@ async function showInstances(id:number) { selectedLicenseID.value = id; instance
|
||||
const route = useRoute() || ({ meta: {}, query: {} } as ReturnType<typeof useRoute>)
|
||||
const router = useRouter() || ({ push: async () => undefined, replace: async () => undefined } as unknown as ReturnType<typeof useRouter>)
|
||||
const pageView = computed(() => route.meta.view as string || 'dashboard')
|
||||
const title=computed(()=>({dashboard:'仪表盘',licenses:'License 授权',customers:'客户管理',products:'产品目录',orders:'订单与套餐',payments:'支付管理','payment-plans':'套餐管理',releases:'版本管理',integration:'客户端接入',audit:'审计日志',settings:'系统设置',admins:'管理员账户'}[pageView.value] || '仪表盘'))
|
||||
const nav=[{view:'dashboard',path:'/',name:'仪表盘',icon:'▦'},{view:'licenses',path:'/licenses',name:'License 授权',icon:'◇'},{view:'customers',path:'/customers',name:'客户管理',icon:'♙'},{view:'products',path:'/products',name:'产品目录',icon:'◫'},{view:'orders',path:'/orders',name:'订单与套餐',icon:'▤'},{view:'payments',path:'/payments',name:'支付管理',icon:'¥'},{view:'payment-plans',path:'/payment-plans',name:'套餐管理',icon:'▣'},{view:'releases',path:'/releases',name:'版本管理',icon:'↥'},{view:'integration',path:'/integration',name:'客户端接入',icon:'⌘'},{view:'audit',path:'/audit',name:'审计日志',icon:'≡'},{view:'settings',path:'/settings',name:'系统设置',icon:'⚙'},{view:'admins',path:'/admins',name:'管理员账户',icon:'♙'}]
|
||||
const title=computed(()=>({dashboard:'仪表盘',licenses:'License 授权',customers:'客户管理',products:'产品目录',orders:'订单与套餐',payments:'支付管理','payment-plans':'套餐管理',suffixes:'后缀管理',releases:'版本管理',integration:'客户端接入',audit:'审计日志',settings:'系统设置',admins:'管理员账户'}[pageView.value] || '仪表盘'))
|
||||
const nav=[{view:'dashboard',path:'/',name:'仪表盘',icon:'▦'},{view:'licenses',path:'/licenses',name:'License 授权',icon:'◇'},{view:'customers',path:'/customers',name:'客户管理',icon:'♙'},{view:'products',path:'/products',name:'产品目录',icon:'◫'},{view:'orders',path:'/orders',name:'订单与套餐',icon:'▤'},{view:'payments',path:'/payments',name:'支付管理',icon:'¥'},{view:'payment-plans',path:'/payment-plans',name:'套餐管理',icon:'▣'},{view:'suffixes',path:'/suffixes',name:'后缀管理',icon:'⊞'},{view:'releases',path:'/releases',name:'版本管理',icon:'↥'},{view:'integration',path:'/integration',name:'客户端接入',icon:'⌘'},{view:'audit',path:'/audit',name:'审计日志',icon:'≡'},{view:'settings',path:'/settings',name:'系统设置',icon:'⚙'},{view:'admins',path:'/admins',name:'管理员账户',icon:'♙'}]
|
||||
const adminEmail=ref('管理员'), detail=ref<License|null>(null),detailOpen=ref(false),detailLoading=ref(false),detailError=ref('')
|
||||
const navCollapsed=ref(localStorage.getItem('magerNavCollapsed')==='1')
|
||||
function toggleNav(){ navCollapsed.value=!navCollapsed.value; try{localStorage.setItem('magerNavCollapsed',navCollapsed.value?'1':'0')}catch{} }
|
||||
async function showDetail(id:number){detailOpen.value=true;detail.value=null;detailError.value='';detailLoading.value=true;try{detail.value=(await getLicense(id)).data.data}catch(e){detailError.value=e instanceof Error?e.message:'详情加载失败'}finally{detailLoading.value=false}}
|
||||
async function openIssue(){await router.push('/licenses');document.getElementById('license-issue')?.scrollIntoView({behavior:'smooth'})}
|
||||
watch(()=>route.query.status,(value)=>{licensePage.value=1;licenseStatus.value=String(value??'');if(loggedIn.value)refresh()})
|
||||
@@ -131,9 +134,9 @@ async function submitRenewal() {
|
||||
onMounted(() => { checkConnection(); checkSession() })
|
||||
</script>
|
||||
<template>
|
||||
<div class="workspace" :class="{'admin-workspace':loggedIn}"><aside v-if="loggedIn" class="sidebar"><div class="brand"><span class="brand-mark">L</span><div>{{siteSettings?.site_name || 'License Hub'}}<small>统一授权管理平台</small></div></div><nav class="nav" aria-label="管理台导航"><template v-for="(item,index) in nav" :key="item.path"><div v-if="index===0||index===1||index===7" class="nav-label">{{index===0?'工作台':index===1?'业务管理':'系统'}}</div><router-link :to="item.path" :class="{active:pageView===item.view}" :title="item.name"><span class="ico">{{item.icon}}</span><span>{{item.name}}</span></router-link></template></nav><div class="sidebar-footer"><span class="user-dot">{{adminEmail.slice(0,1).toUpperCase()}}</span><span>{{adminEmail}}</span></div></aside><div class="main"><header class="topbar"><span v-if="loggedIn" class="crumb">{{pageView==='dashboard'?'工作台':'管理台'}} <strong>/ {{title}}</strong></span><span v-else class="wordmark"><span class="mark">L</span>License Hub</span><span class="environment">内部管理台 <el-button v-if="loggedIn" link @click="signOut">退出</el-button></span></header>
|
||||
<div class="workspace" :class="{'admin-workspace':loggedIn,'nav-collapsed':navCollapsed}"><aside v-if="loggedIn" class="sidebar"><div class="brand"><span class="brand-mark">L</span><div>{{siteSettings?.site_name || 'License Hub'}}</div></div><nav class="nav" aria-label="管理台导航"><template v-for="(item,index) in nav" :key="item.path"><div v-if="index===0||index===1||index===8" class="nav-label">{{index===0?'工作台':index===1?'业务管理':'系统'}}</div><router-link :to="item.path" :class="{active:pageView===item.view}" :title="item.name"><span class="ico">{{item.icon}}</span><span>{{item.name}}</span></router-link></template></nav><div class="sidebar-footer"><span class="user-dot">{{adminEmail.slice(0,1).toUpperCase()}}</span><span class="footer-email">{{adminEmail}}</span><button v-if="loggedIn" type="button" class="side-logout" title="退出登录" @click="signOut">退出</button></div></aside><div class="nav-fold" :class="{ collapsed: navCollapsed }" :title="navCollapsed ? '展开菜单' : '收起菜单'" @click="toggleNav">{{ navCollapsed ? '›' : '‹' }}</div><div class="main"><header v-if="pageView!=='suffixes'" class="topbar"><span v-if="loggedIn" class="crumb">{{pageView==='dashboard'?'工作台':'管理台'}} <strong>/ {{title}}</strong></span><span v-else class="wordmark"><span class="mark">L</span>License Hub</span><span v-if="pageView!=='suffixes'" class="environment">内部管理台</span></header>
|
||||
<main class="content" v-if="!loggedIn"><section class="status-section" aria-labelledby="api-title"><div><h2 id="api-title">API 连通性</h2><p>服务状态仅表示存活端点可访问。</p></div><div><span class="status" :class="connection" role="status">{{ connection === 'checking' ? '检测中' : connection === 'online' ? '服务在线' : '服务未连接' }}</span><el-button link @click="checkConnection">重新检测</el-button></div></section><section class="login-panel"><p class="eyebrow">内部管理员</p><h1>登录管理台</h1><p class="subheading">使用管理员用户名和密码登录。</p><el-form @submit.prevent="signIn"><el-input v-model="username" aria-label="用户名" placeholder="用户名" autocomplete="username"/><el-input v-model="password" type="password" show-password placeholder="密码" autocomplete="current-password" @keyup.enter="signIn"/><el-button type="primary" :loading="loading" @click="signIn">登录</el-button></el-form><p v-if="error" class="error">{{ error }}</p></section></main>
|
||||
<main class="content" v-else><p v-if="siteSettings?.announcement" class="site-announcement" role="note">{{siteSettings.announcement}}</p><p v-if="siteSettings?.support_email" class="subheading">支持联系:<a :href="`mailto:${siteSettings.support_email}`">{{siteSettings.support_email}}</a></p><DashboardPanel v-if="pageView==='dashboard'" @issue="openIssue" @detail="showDetail"/><div v-else class="heading"><div><p class="eyebrow">内部管理台</p><h1>{{title}}</h1><p class="subheading">{{pageView==='payments'?'查看渠道启用状态和最近支付流水':pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}</p></div><el-button v-if="pageView!=='payments'&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error&&pageView!=='payments'&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" class="error">{{ error }}</p>
|
||||
<main class="content" v-else :class="{'content-suffix':pageView==='suffixes'}"><p v-if="siteSettings?.announcement" class="site-announcement" role="note">{{siteSettings.announcement}}</p><p v-if="siteSettings?.support_email" class="subheading">支持联系:<a :href="`mailto:${siteSettings.support_email}`">{{siteSettings.support_email}}</a></p><DashboardPanel v-if="pageView==='dashboard'" @issue="openIssue" @detail="showDetail"/><div v-else-if="pageView==='suffixes'" class="suffix-page-host"><SuffixPanel/></div><div v-else class="heading"><div><p class="eyebrow">内部管理台</p><h1>{{title}}</h1><p class="subheading">{{pageView==='payments'?'查看渠道启用状态和最近支付流水':pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}</p></div><el-button v-if="pageView!=='payments'&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error&&pageView!=='payments'&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" class="error">{{ error }}</p>
|
||||
<div v-if="pageView==='customers'" class="admin-module">
|
||||
<section class="module-create" aria-labelledby="customer-create-title"><div class="module-section-heading"><div><h2 id="customer-create-title">新增客户</h2><p>建立客户档案并维护联系信息</p></div></div><div class="module-form customer-create-form"><label class="module-field"><span>客户名称</span><el-input v-model="newCustomer.name" placeholder="输入客户名称"/></label><label class="module-field"><span>联系邮箱</span><el-input v-model="newCustomer.contact_email" type="email" placeholder="name@example.com"/></label><el-button type="primary" @click="addCustomer">新增客户</el-button></div></section>
|
||||
<section class="module-list" aria-label="客户列表"><div class="module-toolbar"><div class="module-list-title"><h2>客户档案</h2><span class="module-count">{{ customerTotal }} 条</span></div><label class="module-filter"><span>搜索</span><el-input v-model="query" placeholder="客户名称或邮箱" clearable @change="refresh"/></label></div><div class="business-table module-table"><el-table :data="customers" v-loading="loading" empty-text="暂无客户"><el-table-column prop="name" label="客户名称" min-width="180"/><el-table-column prop="contact_email" label="联系邮箱" min-width="220"/><el-table-column prop="status" label="状态" width="120"/><el-table-column label="操作" width="100"><template #default="scope"><el-button link type="danger" @click="removeCustomer(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section>
|
||||
|
||||
215
frontend/src/views/SuffixPanel.test.ts
Normal file
215
frontend/src/views/SuffixPanel.test.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import SuffixPanel from './SuffixPanel.vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
createSuffixColumn, deleteSuffixColumn, getSuffixColWidths, getSuffixOverview, getSuffixPage, getSuffixTree, renameSuffixColumn, setSuffixAnchor, updateSuffixColWidth, updateSuffixColumnWidth,
|
||||
} 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(),
|
||||
updateSuffixColumnWidth: vi.fn(),
|
||||
renameSuffixColumn: vi.fn(),
|
||||
getSuffixColWidths: vi.fn(),
|
||||
updateSuffixColWidth: 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_value: '' }],
|
||||
cells: {},
|
||||
}
|
||||
|
||||
function setup(widths: Record<string, Record<string, number>> = {}) {
|
||||
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)
|
||||
vi.mocked(getSuffixColWidths).mockResolvedValue(ok({ widths }) 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.find('button[title="上传模板"]').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('+ 新建分组')
|
||||
})
|
||||
|
||||
it('lists workspace rows flat without region group headers', 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()).not.toContain('− 广东省')
|
||||
expect(wrapper.text()).toContain('cos4')
|
||||
expect(wrapper.findAll('td.anchor').length).toBeGreaterThan(0)
|
||||
expect(wrapper.findAll('tr.data-tr').length).toBe(1)
|
||||
})
|
||||
|
||||
it('applies default widths and saves every fixed column width', async () => {
|
||||
page.columns = [{ id: 5, name: '招标人', is_value: false }]
|
||||
const wrapper = setup({ workspace: { suffix: 88 } })
|
||||
await flushPromises()
|
||||
// 基本设置表:后缀默认 50px、导入文件 0=自适应占满、操作列收窄为默认 150px
|
||||
const basicCols = wrapper.findAll('table.basic col')
|
||||
expect(basicCols.length).toBe(4)
|
||||
expect(basicCols[0].attributes('style')).toContain('50px')
|
||||
expect(basicCols[1].attributes('style')).toContain('50px')
|
||||
expect(basicCols[2].attributes('style')).toBeUndefined()
|
||||
expect(basicCols[3].attributes('style')).toContain('150px')
|
||||
|
||||
// 目录工作区表:保存过的后缀列宽生效,其余用默认;3 固定列(无操作列)+ 自定义列
|
||||
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
|
||||
await flushPromises()
|
||||
const wsCols = wrapper.findAll('table.sheet:not(.basic)')[0].findAll('col')
|
||||
expect(wsCols.length).toBe(4)
|
||||
expect(wsCols[1].attributes('style')).toContain('88px')
|
||||
expect(wsCols[2].attributes('style')).toContain('300px')
|
||||
|
||||
// 列设置弹框顶部固定列宽度可改并保存
|
||||
vi.mocked(updateSuffixColWidth).mockResolvedValue(ok({ scope: 'workspace', key: 'idx', width: 66 }) as never)
|
||||
await wrapper.findAll('button').find((b) => b.text() === '列设置')!.trigger('click')
|
||||
const fixedInputs = wrapper.findAll('.col-order-row.fixed-row .co-width')
|
||||
expect(fixedInputs.length).toBe(3)
|
||||
await fixedInputs[0].setValue('66')
|
||||
await fixedInputs[0].trigger('change')
|
||||
await flushPromises()
|
||||
expect(updateSuffixColWidth).toHaveBeenCalledWith('workspace', 'idx', 66)
|
||||
|
||||
// 基本设置「列宽」弹框:固定列同样可改(先关掉列设置弹框,避免两个弹框同时开着)
|
||||
vi.mocked(updateSuffixColWidth).mockClear()
|
||||
vi.mocked(updateSuffixColWidth).mockResolvedValue(ok({ scope: 'basic', key: 'files', width: 300 }) as never)
|
||||
await wrapper.findAll('button').filter((b) => b.text() === '关闭').at(-1)!.trigger('click')
|
||||
await wrapper.findAll('.side-root').find((n) => n.text() === '基本设置')!.trigger('click')
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find((b) => b.text() === '列宽')!.trigger('click')
|
||||
const basicInputs = wrapper.findAll('.dialog-stub .col-order-row.fixed-row .co-width')
|
||||
expect(basicInputs.length).toBe(4)
|
||||
await basicInputs[2].setValue('300')
|
||||
await basicInputs[2].trigger('change')
|
||||
await flushPromises()
|
||||
expect(updateSuffixColWidth).toHaveBeenCalledWith('basic', 'files', 300)
|
||||
})
|
||||
|
||||
it('edits the anchor value by double-clicking the cell', async () => {
|
||||
const wrapper = setup()
|
||||
await flushPromises()
|
||||
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
|
||||
await flushPromises()
|
||||
// 双击锚定行 → 弹出输入框 → 填值回车保存
|
||||
await wrapper.find('td.anchor').trigger('dblclick')
|
||||
const input = wrapper.find('td.anchor .cell-input')
|
||||
expect(input.exists()).toBe(true)
|
||||
vi.mocked(setSuffixAnchor).mockResolvedValue(ok({ ok: true }) as never)
|
||||
await input.setValue('3')
|
||||
await input.trigger('keyup.enter')
|
||||
await flushPromises()
|
||||
expect(setSuffixAnchor).toHaveBeenCalledWith(2, 10, '3')
|
||||
expect(wrapper.find('td.anchor').text()).toContain('3')
|
||||
|
||||
// 留空保存 = 清除锚定
|
||||
await wrapper.find('td.anchor').trigger('dblclick')
|
||||
const input2 = wrapper.find('td.anchor .cell-input')
|
||||
vi.mocked(setSuffixAnchor).mockClear()
|
||||
await input2.setValue('')
|
||||
await input2.trigger('keyup.enter')
|
||||
await flushPromises()
|
||||
expect(setSuffixAnchor).toHaveBeenCalledWith(2, 10, '')
|
||||
expect(wrapper.find('td.anchor').text()).toContain('—')
|
||||
})
|
||||
|
||||
it('renames a custom column from the 列设置 dialog', async () => {
|
||||
page.columns = [{ id: 5, name: '招标人', is_value: false }]
|
||||
const wrapper = setup()
|
||||
await flushPromises()
|
||||
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find((b) => b.text() === '列设置')!.trigger('click')
|
||||
const row = wrapper.findAll('.col-order-row').find((r) => !r.classes().includes('fixed-row'))!
|
||||
vi.mocked(ElMessageBox.prompt).mockResolvedValue({ value: '招标单位' } as never)
|
||||
vi.mocked(renameSuffixColumn).mockResolvedValue(ok({ id: 5, name: '招标单位', is_value: false, width: 0 }) as never)
|
||||
await row.find('button[title="重命名列"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(renameSuffixColumn).toHaveBeenCalledWith(5, '招标单位')
|
||||
expect(wrapper.text()).toContain('招标单位')
|
||||
})
|
||||
|
||||
it('refuses to delete a column that has values but deletes an empty one', async () => {
|
||||
page.columns = [{ id: 5, name: '招标人', is_value: false }]
|
||||
page.cells = { '10:5': '普通文本' }
|
||||
const wrapper = setup()
|
||||
await flushPromises()
|
||||
await wrapper.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
|
||||
await flushPromises()
|
||||
await wrapper.find('.custom-th .th-x').trigger('click')
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('列「招标人」已有数据,不能删除')
|
||||
expect(deleteSuffixColumn).not.toHaveBeenCalled()
|
||||
|
||||
page.cells = {}
|
||||
const empty = setup()
|
||||
await flushPromises()
|
||||
await empty.findAll('.side-name').find((n) => n.text() === '一、黑色及有色金属')!.trigger('click')
|
||||
await flushPromises()
|
||||
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm' as never)
|
||||
vi.mocked(deleteSuffixColumn).mockResolvedValue(ok({ deleted: 5 }) as never)
|
||||
await empty.find('.custom-th .th-x').trigger('click')
|
||||
await flushPromises()
|
||||
expect(deleteSuffixColumn).toHaveBeenCalledWith(5)
|
||||
expect(empty.text()).not.toContain('招标人')
|
||||
})
|
||||
})
|
||||
983
frontend/src/views/SuffixPanel.vue
Normal file
983
frontend/src/views/SuffixPanel.vue
Normal file
@@ -0,0 +1,983 @@
|
||||
<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, publishSuffixFile,
|
||||
updateSuffixColumnWidth, formatSuffixSize, getSuffixColWidths, getSuffixOverview, getSuffixPage, getSuffixTree, moveSuffix, moveSuffixDir,
|
||||
moveSuffixGroup, parseValueCell, readSuffixFile, renameSuffixDir,
|
||||
renameSuffixGroup, reorderSuffixColumns, renameSuffixColumn, saveSuffixCell, setSuffixAnchor, suffixFileUrl, updateSuffixColWidth, 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 dirCollapsed = ref(localStorage.getItem('suffixDirCollapsed') === '1')
|
||||
function toggleDirFold() { dirCollapsed.value = !dirCollapsed.value; try { localStorage.setItem('suffixDirCollapsed', dirCollapsed.value ? '1' : '0') } catch {} }
|
||||
// 单元格编辑(双击任意单元格直接进入编辑)
|
||||
const editing = reactive({ sid: 0, cid: 0, text: '', a: '', v: '' })
|
||||
// 上传
|
||||
const uploadInput = ref<HTMLInputElement | null>(null)
|
||||
const uploadTarget = ref(0)
|
||||
const uploading = ref(false)
|
||||
|
||||
// 固定列列宽(与后端 suffixColWidthDefaults 一致):0=自适应,导入文件为 0 时占满剩余宽度
|
||||
const FIXED_COL_DEFAULTS: Record<string, Record<string, number>> = {
|
||||
basic: { idx: 50, suffix: 50, files: 0, ops: 150 },
|
||||
workspace: { idx: 50, suffix: 50, anchor: 300 },
|
||||
}
|
||||
const basicFixedCols = [
|
||||
{ key: 'idx', name: '序号' },
|
||||
{ key: 'suffix', name: '后缀' },
|
||||
{ key: 'files', name: '导入文件' },
|
||||
{ key: 'ops', name: '操作' },
|
||||
]
|
||||
const wsFixedCols = [
|
||||
{ key: 'idx', name: '序号' },
|
||||
{ key: 'suffix', name: '后缀' },
|
||||
{ key: 'anchor', name: '锚定行' },
|
||||
]
|
||||
const fixedWidths = ref<Record<string, Record<string, number>>>({})
|
||||
const basicWidths = reactive({ visible: false })
|
||||
|
||||
function wOf(scope: string, key: string): number {
|
||||
const w = fixedWidths.value[scope]?.[key]
|
||||
return w === undefined ? FIXED_COL_DEFAULTS[scope][key] : w
|
||||
}
|
||||
|
||||
function colW(w: number) {
|
||||
return w > 0 ? { width: w + 'px' } : undefined
|
||||
}
|
||||
|
||||
async function loadFixedWidths() {
|
||||
try {
|
||||
fixedWidths.value = (await getSuffixColWidths()).data.data.widths
|
||||
} catch { /* 列宽读取失败时沿用默认值 */ }
|
||||
}
|
||||
|
||||
async function setFixedColWidth(scope: 'basic' | 'workspace', key: string, event: Event) {
|
||||
const w = parseInt((event.target as HTMLInputElement).value, 10)
|
||||
if (Number.isNaN(w) || w < 0 || w > 2000) {
|
||||
ElMessage.warning('列宽须为 0–2000(0=自适应)')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await updateSuffixColWidth(scope, key, w)
|
||||
fixedWidths.value = { ...fixedWidths.value, [scope]: { ...fixedWidths.value[scope], [key]: w } }
|
||||
ElMessage.success('列宽已保存')
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '列宽保存失败')
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSheet() {
|
||||
if (selected.value.kind !== 'dir') return
|
||||
page.value = (await getSuffixPage(selected.value.id)).data.data
|
||||
}
|
||||
|
||||
// ---- 目录树 ----
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 统一目录操作条的目标:当前选中的目录;根目录只允许「+子」
|
||||
const selectedDir = computed<SuffixDir | null>(() => {
|
||||
const sel = selected.value
|
||||
return sel.kind === 'dir' ? dirs.value.find((d) => d.id === sel.id) ?? null : null
|
||||
})
|
||||
const dirOpsLocked = computed(() => !selectedDir.value || isRoot(selectedDir.value))
|
||||
function addSubToSelected() { if (selectedDir.value) addDir(selectedDir.value.id, '新建子目录') }
|
||||
function addSiblingToSelected() { const d = selectedDir.value; if (d && !isRoot(d)) addDir(d.parent_id, '新建平级目录') }
|
||||
function renameSelected() { const d = selectedDir.value; if (d) renameDir(d) }
|
||||
function moveSelected(dirNum: number) { const d = selectedDir.value; if (d && !isRoot(d)) moveDir(d, dirNum) }
|
||||
function removeSelected() { const d = selectedDir.value; if (d && !isRoot(d)) removeDir(d) }
|
||||
|
||||
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 : '移动失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 基本设置:分组与后缀 ----
|
||||
|
||||
const groupDialog = reactive({ visible: false, name: '', suffixName: '', saving: false })
|
||||
|
||||
function addGroup() {
|
||||
groupDialog.name = ''
|
||||
groupDialog.suffixName = ''
|
||||
groupDialog.visible = true
|
||||
}
|
||||
|
||||
async function submitGroup() {
|
||||
if (groupDialog.saving) return
|
||||
const name = groupDialog.name.trim()
|
||||
if (!name) {
|
||||
ElMessage.warning('请填写分组名')
|
||||
return
|
||||
}
|
||||
groupDialog.saving = true
|
||||
try {
|
||||
await createSuffixGroup(name, groupDialog.suffixName.trim())
|
||||
groupDialog.visible = false
|
||||
await loadOverview()
|
||||
ElMessage.success(groupDialog.suffixName.trim() ? '分组已创建(含一行后缀)' : '分组已创建')
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '创建失败')
|
||||
} finally {
|
||||
groupDialog.saving = false
|
||||
}
|
||||
}
|
||||
|
||||
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 insertSuffixRow(groupId: number, afterId: number, title: string) {
|
||||
const { value } = await ElMessageBox.prompt('输入后缀名(同名自动 -1,创建后不可修改)', title, { inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).catch(() => ({ value: '' }))
|
||||
if (!value) return
|
||||
try {
|
||||
const created = (await createSuffix(groupId, value.trim(), afterId)).data.data
|
||||
await loadOverview()
|
||||
ElMessage.success(`后缀「${created.name}」已创建`)
|
||||
} 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 : '删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
const row = groups.value.flatMap((g) => g.suffixes).find((s) => s.id === suffixId)
|
||||
const base = (row?.name || '').replace(/-\d+$/, '').toLowerCase()
|
||||
const ext = file.name.includes('.') ? file.name.split('.').pop()!.toLowerCase() : ''
|
||||
if (!base || ext !== base) {
|
||||
ElMessage.error(`上传文件的扩展名必须与本行后缀一致:本行是「${row?.name}」,只能上传 .${base || '?'} 文件`)
|
||||
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 : '删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 骨架发布 / 取消发布(「更多」下拉)
|
||||
async function onFilePublish(file: SuffixFile) {
|
||||
const next = !file.published
|
||||
try {
|
||||
await publishSuffixFile(file.id, next)
|
||||
file.published = next
|
||||
ElMessage.success(next ? `「${file.file_name}」已发布` : `「${file.file_name}」已取消发布`)
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 目录工作区:列 / 单元格 / 锚定 ----
|
||||
|
||||
const pageColumns = computed<SuffixColumn[]>(() => page.value?.columns || [])
|
||||
|
||||
// ---- 列设置(重命名 / 排序 / 列宽 / 精准插入新列) ----
|
||||
|
||||
const colOrder = reactive({ visible: false, ids: [] as number[], newName: '', newValue: false, saving: false })
|
||||
|
||||
const valColCount = computed(() => pageColumns.value.filter((c) => c.is_value).length)
|
||||
|
||||
function openColOrder() {
|
||||
if (selected.value.kind !== 'dir' || !page.value) return
|
||||
colOrder.ids = page.value.columns.map((c) => c.id)
|
||||
colOrder.newName = ''
|
||||
colOrder.newValue = false
|
||||
colOrder.visible = true
|
||||
}
|
||||
|
||||
function colWidthOf(id: number): number {
|
||||
return pageColumns.value.find((c) => c.id === id)?.width || 0
|
||||
}
|
||||
|
||||
async function setColWidth(id: number, event: Event) {
|
||||
const w = parseInt((event.target as HTMLInputElement).value, 10)
|
||||
if (Number.isNaN(w) || w < 0 || w > 2000) {
|
||||
ElMessage.warning('列宽须为 0–2000(0=自适应)')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await updateSuffixColumnWidth(id, w)
|
||||
const col = pageColumns.value.find((c) => c.id === id)
|
||||
if (col) col.width = w
|
||||
ElMessage.success('列宽已保存')
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '列宽保存失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 重命名自定义列:成功后原地更新,表头与弹框同步变化
|
||||
async function renameColOrder(cid: number) {
|
||||
const col = pageColumns.value.find((c) => c.id === cid)
|
||||
if (!col) return
|
||||
const { value } = await ElMessageBox.prompt('输入新的列名', '重命名列', { inputValue: col.name, inputPattern: /\S/, inputErrorMessage: '列名不能为空' }).catch(() => ({ value: '' }))
|
||||
if (!value || value.trim() === col.name) return
|
||||
try {
|
||||
await renameSuffixColumn(col.id, value.trim())
|
||||
col.name = value.trim()
|
||||
ElMessage.success('列名已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '重命名失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function moveColOrder(id: number, dir: number) {
|
||||
const sel = selected.value
|
||||
if (sel.kind !== 'dir' || !page.value) return
|
||||
const ids = colOrder.ids
|
||||
const i = ids.indexOf(id)
|
||||
const j = i + dir
|
||||
if (i < 0 || j < 0 || j >= ids.length) return
|
||||
;[ids[i], ids[j]] = [ids[j], ids[i]]
|
||||
try {
|
||||
await reorderSuffixColumns(sel.id, ids)
|
||||
await loadSheet()
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '排序失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 用右上角工具条里的列名/值设置建列:afterId>0 插到该列后,0 加到最右;弹框保持打开方便连续添加。
|
||||
async function createColAt(afterId: number) {
|
||||
if (colOrder.saving || selected.value.kind !== 'dir' || !page.value) return
|
||||
const name = colOrder.newName.trim()
|
||||
if (!name) {
|
||||
ElMessage.warning('请先在右上角填写列名')
|
||||
return
|
||||
}
|
||||
const isValue = colOrder.newValue
|
||||
colOrder.saving = true
|
||||
try {
|
||||
const created = (await createSuffixColumn(selected.value.id, name, isValue, afterId)).data.data
|
||||
colOrder.newName = ''
|
||||
colOrder.newValue = false
|
||||
await loadSheet()
|
||||
if (page.value) colOrder.ids = page.value.columns.map((c) => c.id)
|
||||
ElMessage.success(isValue
|
||||
? (afterId ? `已在选中列后插入值列「${created.name}」` : `已添加值列「${created.name}」`)
|
||||
: (afterId ? `已在选中列后插入列「${created.name}」` : `已添加列「${created.name}」`))
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '列创建失败')
|
||||
} finally {
|
||||
colOrder.saving = false
|
||||
}
|
||||
}
|
||||
|
||||
function submitColOrder() { createColAt(0) }
|
||||
|
||||
function insertColAfter(cid: number) { createColAt(cid) }
|
||||
|
||||
async function removeColumn(col: SuffixColumn) {
|
||||
const hasValue = !!page.value?.suffixes.some((s) => (page.value?.cells[cellKey(s.id, col.id)] || '') !== '')
|
||||
if (hasValue) {
|
||||
ElMessage.warning(`列「${col.name}」已有数据,不能删除`)
|
||||
return
|
||||
}
|
||||
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)
|
||||
colOrder.ids = colOrder.ids.filter((id) => 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 : '保存失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 锚定行编辑(双击存值,空=未锚定) ----
|
||||
|
||||
const editingAnchor = reactive({ sid: 0, value: '' })
|
||||
|
||||
function startAnchorEdit(sid: number) {
|
||||
const row = workspaceRows.value.find((r) => r.sid === sid)
|
||||
editingAnchor.sid = sid
|
||||
editingAnchor.value = row?.anchor || ''
|
||||
}
|
||||
|
||||
function cancelAnchorEdit() {
|
||||
editingAnchor.sid = 0
|
||||
editingAnchor.value = ''
|
||||
}
|
||||
|
||||
async function commitAnchorEdit() {
|
||||
const sid = editingAnchor.sid
|
||||
if (!sid || selected.value.kind !== 'dir' || !page.value) { cancelAnchorEdit(); return }
|
||||
const value = editingAnchor.value.trim()
|
||||
cancelAnchorEdit()
|
||||
try {
|
||||
await setSuffixAnchor(selected.value.id, sid, value)
|
||||
const line = page.value.suffixes.find((s) => s.id === sid)
|
||||
if (line) line.anchor_value = value
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '锚定失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 目录工作区的行:区域不再单独占一行,后缀直接平铺,把工作区让给数据
|
||||
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(() =>
|
||||
(page.value?.suffixes || []).map((s) => ({ key: 's:' + s.id, sid: s.id, name: s.name, anchor: s.anchor_value || '' })),
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
loadOverview()
|
||||
loadTree()
|
||||
loadFixedWidths()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="suffix-shell">
|
||||
<aside v-show="!dirCollapsed" 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>{{ rootDir?.name }}</span>
|
||||
<span class="side-plus" title="新建一级目录" @click.stop="rootDir && addDir(rootDir.id, '新建目录')">+</span>
|
||||
</div>
|
||||
<div class="side-ops-bar" :title="selectedDir ? `对选中的「${selectedDir.name}」操作` : '先选择一个目录'">
|
||||
<button type="button" title="新建子目录" :disabled="!selectedDir" @click="addSubToSelected">+子</button>
|
||||
<button type="button" title="新建平级目录" :disabled="dirOpsLocked" @click="addSiblingToSelected">+平</button>
|
||||
<button type="button" title="重命名" :disabled="!selectedDir" @click="renameSelected">✎</button>
|
||||
<button type="button" title="上移" :disabled="dirOpsLocked" @click="moveSelected(-1)">↑</button>
|
||||
<button type="button" title="下移" :disabled="dirOpsLocked" @click="moveSelected(1)">↓</button>
|
||||
<button type="button" class="danger" title="删除" :disabled="dirOpsLocked" @click="removeSelected">×</button>
|
||||
</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 v-for="a in node.depth - 1" :key="a" class="guide-line" :style="{ left: 21 + a * 18 + 'px' }"></span>
|
||||
<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>
|
||||
</div>
|
||||
</template>
|
||||
</aside>
|
||||
|
||||
<div class="dir-fold" :class="{ collapsed: dirCollapsed }" :title="dirCollapsed ? '展开目录' : '收起目录'" @click="toggleDirFold">{{ dirCollapsed ? '›' : '‹' }}</div>
|
||||
<main class="suffix-main">
|
||||
<!-- 基本设置:分组 + 后缀 + 模板 -->
|
||||
<template v-if="selected.kind === 'basic'">
|
||||
<div class="bar">
|
||||
<strong>基本设置</strong>
|
||||
<span class="grow"></span>
|
||||
<span class="bar-btns">
|
||||
<el-button size="small" @click="basicWidths.visible = true">列宽</el-button>
|
||||
<el-button size="small" @click="addGroup">+ 新建分组</el-button>
|
||||
</span>
|
||||
</div>
|
||||
<div v-loading="overviewLoading" class="sheet-wrap">
|
||||
<table class="sheet basic">
|
||||
<colgroup>
|
||||
<col v-for="fc in basicFixedCols" :key="fc.key" :style="colW(wOf('basic', fc.key))" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="b-idx">序号</th>
|
||||
<th class="b-suffix">后缀</th>
|
||||
<th class="b-files">导入文件</th>
|
||||
<th class="b-ops">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="g in groups" :key="g.id">
|
||||
<tr class="group-tr">
|
||||
<td class="group-cell" colspan="3">
|
||||
<span class="tw off">▾</span><strong>{{ g.name }}</strong>
|
||||
<span class="muted">{{ g.suffixes.length }} 个</span>
|
||||
<span class="grow"></span>
|
||||
</td>
|
||||
<td class="group-ops">
|
||||
<span class="ops-btns">
|
||||
<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>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="(s, i) in g.suffixes" :key="s.id" class="data-tr">
|
||||
<td class="b-idx">{{ i + 1 }}</td>
|
||||
<td :title="s.name">
|
||||
<span class="suffix-name">{{ s.name || '—' }}</span>
|
||||
</td>
|
||||
<td class="files-cell">
|
||||
<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>
|
||||
<em v-if="f.published" class="pub-tag" title="已发布">已发布</em>
|
||||
<button type="button" class="chip-x" title="删除模板" @click="removeFile(f)">×</button>
|
||||
</span>
|
||||
<span v-if="!s.files.length" class="muted">—</span>
|
||||
</td>
|
||||
<td class="ops-cell">
|
||||
<span class="ops-btns">
|
||||
<button type="button" class="btn-main" title="上传模板" :disabled="uploading" @click="pickUpload(s.id)">传</button>
|
||||
<button type="button" class="op" title="在这行下面插入一行(同名自动 -1)" @click="insertSuffixRow(g.id, s.id, '插入后缀')">插</button>
|
||||
<el-dropdown trigger="click" @command="onFilePublish">
|
||||
<button type="button" class="op" title="更多(骨架发布 / 取消发布)">更多</button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item v-for="f in s.files" :key="f.id" :command="f">
|
||||
{{ f.file_name }}({{ f.published ? '取消发布' : '发布' }})
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item v-if="!s.files.length" disabled>暂无骨架</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<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>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!g.suffixes.length" class="data-tr">
|
||||
<td class="b-idx">—</td>
|
||||
<td><span class="muted">—</span></td>
|
||||
<td class="files-cell"><span class="muted">这个分组还没有后缀,</span><button type="button" class="op" @click="insertSuffixRow(g.id, 0, '插入后缀')">插入后缀</button></td>
|
||||
<td class="ops-cell"></td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-if="!groups.length"><td colspan="4" class="empty-tip">还没有分组,点右上角「+ 新建分组」开始(新分组自动带一行后缀)。</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</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" @click="openColOrder">列设置</el-button>
|
||||
</div>
|
||||
<div v-loading="pageLoading" class="sheet-wrap">
|
||||
<table class="sheet">
|
||||
<colgroup>
|
||||
<col v-for="fc in wsFixedCols" :key="fc.key" :style="colW(wOf('workspace', fc.key))" />
|
||||
<col v-for="col in pageColumns" :key="col.id" :style="colW(col.width || 120)" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<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>
|
||||
<tr v-for="(row, i) in workspaceRows" :key="row.key" class="data-tr" :class="{ editing: editing.sid === row.sid }">
|
||||
<td class="fix idx">{{ i + 1 }}</td>
|
||||
<td class="fix" :title="row.name">{{ row.name || '—' }}</td>
|
||||
<td class="fix anchor" @dblclick="startAnchorEdit(row.sid)" title="双击编辑锚定值(留空=未锚定)">
|
||||
<template v-if="editingAnchor.sid === row.sid">
|
||||
<span class="cell-editor" @click.stop>
|
||||
<input v-model="editingAnchor.value" class="cell-input" placeholder="锚定值" @keyup.enter="commitAnchorEdit" @keyup.esc="cancelAnchorEdit" />
|
||||
<button type="button" class="op" title="确定" @click.stop="commitAnchorEdit">✓</button>
|
||||
</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="row.anchor" class="cell-text">{{ row.anchor }}</span>
|
||||
<span v-else class="cell-empty">—</span>
|
||||
</template>
|
||||
</td>
|
||||
<td
|
||||
v-for="col in pageColumns"
|
||||
:key="col.id"
|
||||
class="cell"
|
||||
@dblclick="startCellEdit(row.sid, col)"
|
||||
title="双击编辑"
|
||||
>
|
||||
<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>
|
||||
<tr v-if="!workspaceRows.length">
|
||||
<td :colspan="3 + 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="groupDialog.visible" title="新建分组" width="440px">
|
||||
<div class="col-form">
|
||||
<label><span class="lab">分组名(分类名)</span>
|
||||
<el-input v-model="groupDialog.name" placeholder="例如:广东省" maxlength="190" @keyup.enter="submitGroup" />
|
||||
</label>
|
||||
<label><span class="lab">首个后缀名</span>
|
||||
<el-input v-model="groupDialog.suffixName" placeholder="例如:cos4(留空则暂不建行)" maxlength="64" />
|
||||
</label>
|
||||
<p class="muted">分组建好后自动带一行工作行;行名按后缀命名,同名自动 -1,创建后不可修改。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="groupDialog.visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="groupDialog.saving" @click="submitGroup">确定</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="colOrder.visible" title="列设置" width="560px">
|
||||
<div class="col-set-toolbar">
|
||||
<el-input v-model="colOrder.newName" placeholder="新列名(点行内「插」插到该行后)" maxlength="190" @keyup.enter="submitColOrder" />
|
||||
<el-checkbox v-model="colOrder.newValue">值设置</el-checkbox>
|
||||
<el-button type="primary" :loading="colOrder.saving" @click="submitColOrder">添加列</el-button>
|
||||
<el-button @click="colOrder.visible = false">关闭</el-button>
|
||||
</div>
|
||||
<div class="col-order-hint">固定列只调宽度;自定义列操作:✎ 重命名、↑↓ 排序、插 = 把右上角填的新列插到该行后、✕ 删除。</div>
|
||||
<div class="col-order-list">
|
||||
<div v-for="fc in wsFixedCols" :key="'f-' + fc.key" class="col-order-row fixed-row">
|
||||
<span class="co-idx">固</span>
|
||||
<span class="co-name">{{ fc.name }}<span class="co-fixtag">固定列</span></span>
|
||||
<input
|
||||
class="co-width"
|
||||
type="number"
|
||||
min="0"
|
||||
max="2000"
|
||||
:value="wOf('workspace', fc.key)"
|
||||
title="列宽 px(0=自适应)"
|
||||
@change="setFixedColWidth('workspace', fc.key, $event)"
|
||||
/>
|
||||
<span class="co-ops"></span>
|
||||
</div>
|
||||
<div v-for="(cid, i) in colOrder.ids" :key="cid" class="col-order-row">
|
||||
<span class="co-idx">{{ i + 1 }}</span>
|
||||
<span class="co-name" :class="{ value: pageColumns.find((c) => c.id === cid)?.is_value }">
|
||||
{{ pageColumns.find((c) => c.id === cid)?.name }}
|
||||
<span v-if="pageColumns.find((c) => c.id === cid)?.is_value" class="co-vtag">值</span>
|
||||
</span>
|
||||
<input
|
||||
class="co-width"
|
||||
type="number"
|
||||
min="0"
|
||||
max="2000"
|
||||
:value="colWidthOf(cid)"
|
||||
title="列宽 px(0=自适应)"
|
||||
@change="setColWidth(cid, $event)"
|
||||
/>
|
||||
<span class="co-ops">
|
||||
<button type="button" class="op" title="重命名列" @click.stop="renameColOrder(cid)">✎</button>
|
||||
<button type="button" class="op" title="上移" :disabled="i === 0" @click.stop="moveColOrder(cid, -1)">↑</button>
|
||||
<button type="button" class="op" title="下移" :disabled="i === colOrder.ids.length - 1" @click.stop="moveColOrder(cid, 1)">↓</button>
|
||||
<button type="button" class="op" title="把右上角填的新列插到这一列后面" @click.stop="insertColAfter(cid)">插</button>
|
||||
<button type="button" class="op danger" title="删除列" @click.stop="removeColumn(pageColumns.find((c) => c.id === cid)!)">✕</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="basicWidths.visible" title="列宽设置" width="480px">
|
||||
<div class="col-order-hint">基本设置的所有列(含固定列)宽度均可自由设置,单位 px;0=自适应,导入文件为 0 时占满剩余宽度。</div>
|
||||
<div class="col-order-list">
|
||||
<div v-for="fc in basicFixedCols" :key="fc.key" class="col-order-row fixed-row">
|
||||
<span class="co-idx">固</span>
|
||||
<span class="co-name">{{ fc.name }}</span>
|
||||
<span class="co-fixtag">固定列</span>
|
||||
<span class="grow"></span>
|
||||
<input
|
||||
class="co-width"
|
||||
type="number"
|
||||
min="0"
|
||||
max="2000"
|
||||
:value="wOf('basic', fc.key)"
|
||||
title="列宽 px(0=自适应)"
|
||||
@change="setFixedColWidth('basic', fc.key, $event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="basicWidths.visible = false">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.suffix-shell{display:flex;gap:8px;height:calc(100vh - 5px);align-items:stretch;position:relative;overflow:hidden}
|
||||
.dir-fold{position:fixed;left:527px;top:calc(50% + 64px);transform:translateY(-50%);z-index:30;width:18px;height:52px;border:1px solid #d8dfe8;border-left:0;border-radius:0 6px 6px 0;background:#fff;color:#526173;cursor:pointer;display:grid;place-items:center;font-size:12px}
|
||||
.admin-workspace.nav-collapsed .dir-fold{left:285px}
|
||||
.dir-fold.collapsed{left:247px;border-left:1px solid #d8dfe8}
|
||||
.admin-workspace.nav-collapsed .dir-fold.collapsed{left:5px}
|
||||
.dir-fold:hover{color:#1769e0;border-color:#1769e0}
|
||||
.suffix-side{flex:0 0 280px;max-width:320px;border:1px solid #e5eaf0;border-radius:6px;background:#fbfcfe;padding:10px 8px;overflow:auto;height:100%}
|
||||
.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}
|
||||
.guide-line{position:absolute;top:0;bottom:0;width:1px;background:#e5eaf0;pointer-events:none}
|
||||
.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-ops-bar{display:flex;align-items:center;gap:3px;flex-wrap:wrap;padding:4px 10px 5px 26px;margin-top:2px;border-bottom:1px solid #e5eaf0}
|
||||
.side-ops-bar button{border:0;background:none;cursor:pointer;font-size:11px;color:#526173;padding:1px 4px;border-radius:3px}
|
||||
.side-ops-bar button:hover{background:#dfe9f7;color:#1769e0}
|
||||
.side-ops-bar button.danger:hover{background:#fbe0dc;color:#b44830}
|
||||
.side-ops-bar button:disabled{color:#c3ccd8;cursor:default;background:none}
|
||||
.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;height:100%;display:flex;flex-direction:column;overflow:hidden}
|
||||
.bar{display:flex;align-items:center;gap:8px;padding:0 0 6px;width:100%}
|
||||
.bar strong{font-size:15px}
|
||||
.bar-btns{display:inline-flex;align-items:center;gap:5px}
|
||||
.bar-btns .el-button+.el-button{margin-left:0}
|
||||
.bar-note{color:#8a97a8;font-size:12px}
|
||||
/* 列设置弹框 */
|
||||
.col-set-toolbar{display:flex;align-items:center;justify-content:flex-end;gap:5px;margin-bottom:8px}
|
||||
.col-set-toolbar .el-input{flex:0 1 210px;min-width:130px}
|
||||
.col-order-hint{color:#8a97a8;font-size:12px;margin-bottom:10px;line-height:1.6}
|
||||
.col-order-list{max-height:46vh;overflow:auto;border:1px solid #e5eaf0;border-radius:6px}
|
||||
.col-order-row{display:flex;align-items:center;gap:8px;padding:7px 10px;border-bottom:1px solid #eef1f5;font-size:13px}
|
||||
.col-order-row:hover{background:#f7faff}
|
||||
.co-idx{flex:0 0 24px;color:#9aa7b6;font-size:12px}
|
||||
.co-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.co-name.value{color:#1769e0;font-weight:600}
|
||||
.co-vtag{font-style:normal;background:#e6f5ee;color:#16845b;border-radius:3px;font-size:10px;padding:0 4px}
|
||||
.co-fixtag{font-style:normal;background:#eef1f5;color:#657387;border-radius:3px;font-size:10px;padding:0 4px}
|
||||
.col-order-row.fixed-row{background:#fbfcfe}
|
||||
.co-width{flex:0 0 58px;width:58px;text-align:center;font-size:12px;border:1px solid #d8dfe8;border-radius:3px;padding:1px 4px}
|
||||
.co-ops{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:flex-end;gap:5px;min-width:142px}
|
||||
.col-order-row .op{padding:2px 5px}
|
||||
.grow{flex:1}
|
||||
.sheet-wrap{flex:1;min-height:0;border:1px solid #e5eaf0;border-radius:6px;overflow:auto;background:#fff}
|
||||
table.sheet.basic{border-collapse:collapse;width:100%;font-size:13px;table-layout:fixed}
|
||||
table.sheet.basic th,table.sheet.basic td{border:1px solid #dfe5e7;padding:2px 8px;height:26px;text-align:left;vertical-align:middle;overflow:hidden;text-overflow:ellipsis}
|
||||
table.sheet.basic thead th{background:#f4f6fa;font-weight:600;height:28px;text-align:center;overflow:hidden;text-overflow:ellipsis}
|
||||
table.sheet.basic .b-idx{text-align:center;color:#9aa7b6}
|
||||
table.sheet.basic .group-tr td{background:#f4f6fa}
|
||||
table.sheet.basic .group-cell strong{font-size:13px}
|
||||
table.sheet.basic .group-ops{text-align:right;white-space:nowrap}
|
||||
table.sheet.basic .ops-cell{white-space:nowrap}
|
||||
table.sheet.basic .files-cell{white-space:normal}
|
||||
table.sheet.basic tr.data-tr:hover td{background:#fafcff}
|
||||
.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}
|
||||
.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;display:block;overflow:hidden;text-overflow:ellipsis}
|
||||
.ops-btns{display:inline-flex;align-items:center;gap:5px}
|
||||
.ops-cell .op,.ops-cell .btn-main{padding:2px 5px}
|
||||
.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}
|
||||
.pub-tag{font-style:normal;background:#e6f5ee;color:#16845b;border-radius:3px;font-size:10px;padding:0 4px;flex:0 0 auto}
|
||||
.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}
|
||||
/* 目录工作区表:列宽合计优先,不强行铺满;列多时在 sheet-wrap 内左右滚动 */
|
||||
table.sheet:not(.basic){width:max-content}
|
||||
table.sheet{border-collapse:collapse;width:100%;font-size:12.5px;table-layout:fixed}
|
||||
table.sheet th,table.sheet td{border-right:1px solid #eef1f5;border-bottom:1px solid #eef1f5;padding:3px 8px;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
table.sheet thead th{background:#f4f6fa;color:#657387;font-weight:600;position:relative;text-align:center;overflow:hidden;text-overflow:ellipsis}
|
||||
.fix{background:#fff}
|
||||
thead .fix{background:#f4f6fa}
|
||||
td.idx{color:#9aa7b6;font-size:12px;text-align:center}
|
||||
.custom-th>span{display:inline-block;max-width:calc(100% - 14px);overflow:hidden;text-overflow:ellipsis;vertical-align:middle}
|
||||
.custom-th:hover .th-x{visibility:visible}
|
||||
.th-x{visibility:hidden;position:absolute;right:3px;top:50%;transform:translateY(-50%);border:0;background:none;cursor:pointer;color:#b44830;padding:0 2px;line-height:1}
|
||||
.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;overflow:hidden;text-overflow:ellipsis}
|
||||
td.cell:hover{background:#f7faff}
|
||||
.cell-text.value{color:#1769e0}
|
||||
.cell-empty{color:#c3ccd8}
|
||||
.cell-editor{display:flex;gap:4px;align-items:center;width:100%}
|
||||
.cell-editor .op{flex:0 0 auto}
|
||||
.cell-input{font:inherit;border:1px solid #1769e0;border-radius:3px;padding:2px 6px;min-width:0;flex:1 1 auto;width:100%}
|
||||
.cell-input.half{flex:1 1 0;width:auto}
|
||||
.col-form{display:grid;gap:14px}
|
||||
.col-form > label{display:grid;gap:6px}
|
||||
.lab{font-size:12px;font-weight:600;color:#526173}
|
||||
td.anchor{cursor:text;text-align:center}
|
||||
td.anchor:hover{background:#f7faff}
|
||||
</style>
|
||||
Reference in New Issue
Block a user