chore(AdminCost): 移除 COS4 数据结构迁移的一次性脚本与参考资料

This commit is contained in:
lianjianwei2024
2026-11-01 15:27:27 +08:00
parent 386e1ad624
commit f0b1033b12
69 changed files with 5936 additions and 42964 deletions

View File

@@ -0,0 +1,872 @@
diff --git a/AGENTS.md b/AGENTS.md
index c0f0bd8..d1acc5f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,16 +14,22 @@
- **蓝本**:以广联达、易达两家实际导出的 cos4 文件为唯一蓝本(样例:`后台需要导入的项目/广联达导出最新架子.COS4`、`1易达导出骨架.cos4`;cos4=ZIP,内含 Project.xml + 若干单位工程 xml)。
- **目录=XML元素**:后台「按信息价目录」树的每个目录对应 cos4 里的一个 XML 元素;目录的**锚定行**填该元素的英文名(如 建设项目→ConstructionProject);目录中文名取自 DBJ/T 15-145-2025 第 6 章对应表(参考资料在 AdminCost/参考资料/规范与COS4/)。
-- **两点式结构(2026-10-31 用户定稿)**:XML 的每个输出点=一个显式目录,深度优先顺序=输出顺序。成对元素用**两个目录**:`中文名(起)`(起点,锚定=元素名,如 工程信息(起)→ConstructionInfo)+ `中文名(闭)`(闭合点,排在起点整个子树后面的同级位置,锚定=`/元素名`,如 工程信息(闭)→/ConstructionInfo);**自闭合元素=单目录**(无子目录、无(闭)目录,如 系统信息→SystemInfo,导出 `<SystemInfo 属性.../>`)。(起)(闭) 不批量预建,填到哪个成对元素时逐个补。**层级铁律(2026-10-31 用户实证)**:(闭) 必须与其(起)**同级**(挂同一个上级、排(起)子树之后),绝不能挂成(起)的子级;嵌套层是(起)的**子级**(对应 XML 里嵌套元素深一层)——建(闭)时选中(起)用「+平」,不要选中(起)的子级用「+子」。自嵌套明细(AttrInfoItem/AddiInfoItem):容器(起)→明细(起)→明细(嵌套层·自闭合形态)→明细(闭)→容器(闭),树里表达一层,租户端按真实数据递归。
+- **两点式结构(2026-10-31 用户定稿)**:XML 的每个输出点=一个显式目录,深度优先顺序=输出顺序。成对元素用**两个目录**:`中文名(起)`(起点,锚定=元素名,如 工程信息(起)→ConstructionInfo)+ `中文名(闭)`(闭合点,排在起点整个子树后面的同级位置,锚定=`/元素名`,如 工程信息(闭)→/ConstructionInfo);**自闭合元素=单目录**(无子目录、无(闭)目录,如 系统信息→SystemInfo,导出 `<SystemInfo 属性.../>`)。(起)(闭) 不批量预建,填到哪个成对元素时逐个补。**唯一例外=根(2026-10-31 用户定稿:保持隐式)**:根元素(建设项目⇢ConstructionProject)不设 (闭) 目录——XML 单根规范下 `</ConstructionProject>` 永远是文件最后一行,位置由文件结构唯一决定,由导出引擎在 DFS 收尾时隐式补出;API 本身也禁止根层建兄弟目录。审计路径记法里开头的 `/ConstructionProject` 只是"从根起"的路径前缀,不是锚定值。**层级铁律(2026-10-31 用户实证)**:(闭) 必须与其(起)**同级**(挂同一个上级、排(起)子树之后),绝不能挂成(起)的子级;嵌套层是(起)的**子级**(对应 XML 里嵌套元素深一层)——建(闭)时选中(起)用「+平」,不要选中(起)的子级用「+子」。自嵌套明细(AttrInfoItem/AddiInfoItem):容器(起)→明细(起)→明细(嵌套层·自闭合形态)→明细(闭)→容器(闭),树里表达一层,租户端按真实数据递归。
- **起点不混入字段(2026-10-31 用户定稿)**:工作区行只放本元素的属性;子元素一律用目录表达,不在父工作区登记行(建设项目工作区原 23–26 行元素名已删,元素名只存各目录锚定行)。
- **导出模型(2026-10-31 用户定稿)**:数据留在租户侧;租户通过平台拉取骨架结构→按点位填数据→导出成两份蓝本之一的形状。骨架必须 ⊇ 两份并集(元素路径并集 59 条:广联达 37 / 易达 57,广联达独有 2、易达独有 22;属性广联达独有 35、易达独有 283)。租户有数据的点位导出、没有的跳过(例:BulidAuthorizer 仅易达有,广联达型项目导出时自然跳过)。
- **属性定义表目录已删(2026-10-31)**:它曾是重复的第二份元素定义(当时已按 SystemInfo 填过一套);每个目录的工作区本身就是该元素的「属性定义表」,不再另建同名目录。
- **列=元素属性**:目录里的列 = 该元素的属性;列名用 2025 标准属性表的「中文解释」;单元格值 = **两家实际导出的属性英文名**,并以**两家字段的并集**为准——不是标准全集,也不是单家。
- **以实际为准 + 提醒**:填入值一律以两家实际导出为准,不按标准拼写改(例:两家都把 BuildUnit 拼成 `BulidUnit`,按错的填);与标准不一致(拼写差异、某家缺失、标准有但两家都没导出)时必须向用户提醒。已知差异:建设单位/法定代表人两家都拼错(BulidUnit/BulidAuthorizer);`BulidAuthorizer` 仅易达导出;标准表 6.2.1 的 4 个价格指数字段(ProjectIndex/LabourPriceIndex/MaterialPriceIndex/MachinePriceIndex)两家均未导出,故不建列。
-- **进度**:建设项目(ConstructionProject)工作区 25 列(22 家并集属性 + 3 个 swt 专属行:接口编码/清单标准/版本)。2026-10-31 树定稿:建设项目子级=[系统信息(SystemInfo,自闭合,4行ID1/ID2/MakeDate1/MakeDate2) → 工程信息(起)(ConstructionInfo){费用精度Option 4行 / 估概预结 ProjectInfo 14行 / 招标 TendereeInfo 36行 / 投标 BidderInfo 12行 / 工程特征信息(起)(闭)+明细(起)(闭) AttrInfo/AttrInfoItem 两层嵌套 / 补充信息(起)(闭)+明细(起)(闭) AddiInfo/AddiInfoItem} → 工程信息(闭) → 费用汇总(起)(SummaryOfCost,26行,工程变更在第14位,两家都拼 Labor) → 费用汇总(闭) → 建筑安装工程费(ProjectInstallationWorkCost)]。费用汇总(起) 下已建 补充费用(AddiCost,自闭合,3行 Name/Total/Code;易达14条代表一条,广联达自闭合无此元素)。全部只填了 cos4 列。cos 行(老格式)留空,后续单独讨论;cos4-1=湖南省分组变体。费用汇总在广联达蓝本中自闭合(19属性⊂易达26)、易达带 14 条 AddiCost——骨架建并集,导出按租户数据决定形态。
+- **进度**:建设项目(ConstructionProject)工作区 25 列(22 家并集属性 + 3 个 swt 专属行:接口编码/清单标准/版本)。2026-10-31 树定稿并完成**建安费批次1(含全链条 DB 审计)**:全树两点式合规(骨架接口核验:119目录 / (起)23 / (闭)23 / 1163行 / 配对0问题)。建筑安装工程费(起)(23行){费用汇总(起){补充费用}(闭)26行、建安费汇总(起){标题(起){嵌套}(闭)明细}(闭)、单项工程(起){工程特征信息(起){明细}(闭)、费用汇总(起){补充费用}(闭)、单项工程(嵌套层)、单位工程(起)、单位工程(闭)}(闭) 26行、措施项目(起){合计费用、措施分部工程(起){嵌套}(闭)、措施清单项目(起)}(闭)、其他项目(起){其他项目费(起){明细}(闭)、暂列金额(起)、专业工程暂估价(自闭合)、计日工(起)、总承包服务费(起)}(闭)、法律法规/工程变更/工程索赔/增值税/材料暂估价(自闭合)、工料机汇总(起){工料机含量明细}(闭)49行}+建筑安装工程费(闭)。20行元素混入行已清(两层#23x/#25x都清了)、工程变更归位第14位×2、#286补漏。**批次2待做**:单位工程内部剩余(#252费用汇总起闭+补充费用、TechnicalAndEconomicIndex等英文列名14处、分部工程/清单项目/定额等成对目录的起闭、措施分部工程下缺的合计费用/措施清单项目子目录、**混入行34行**(此前误记28,实数34,全在#249-279单位工程子树)、值设置列合规化(如#238/#341 的汇总条目/不汇总条目 is_value 未勾、值未用 {"a","v"} JSON 格式——存量如此,工料机汇总已改造过)。**2026-10-31 补建**:#341 建筑安装工程费汇总明细(Group 级,克隆#238 十四行,锚定 PIWCSItem——蓝本实证 Item 挂 Summary/Group/嵌套Group 三级,树建前两级、嵌套级递归代表);嵌套层目录(如#247)锚定=元素名本身是约定,勿当成错误。**操作事故记录(已修复,引以为戒)**:①同名同签名孪生目录导致5个job删错对象(后被id选择法修正);②建(闭)时锚定误写到仍选中的(起)上(16个被污染成/元素名,已修复);③339建错父级(+平/+子用错,已删重建为340)——**后续一律用「目录id+树DFS序号」定位,操作后必须DB复核**。cos 行(老格式)留空;cos4-1=湖南省分组变体。
- **操作注意**:用 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)、中文解释词序颠倒),与库内 列名/格子值 按锚定行逐一比对;解析器分隔行守卫不能误杀空序号行。
+- **全库体检 SQL(2026-10-31 定为标准审计,改动后必跑)**:①混入行判定器=「工作区行值==任一子目录的非/开头锚定」(JOIN 查询零漏,别用行数/名字过滤式抽查——216 就是这么漏的);②列名英文残留 REGEXP '^[A-Za-z]{4,}$';③斜杠异常=非(闭)带/或(闭)不带/;④无锚定目录=0;⑤孤儿格/空串格=0;⑥目录内重名列=0;⑦有列全空目录=0。锚定/删行等每次写入后**立即 DB 复核**(319-322 锚定曾在批量操作中静默丢失,靠体检抓回)。
- **枚举映射核实来源**: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 本地不存在,需要时向用户索取)。
- **红线(2026-10-31)**:后期所有改动必须先过自动化测试再汇报——后端 go 集成测试(独立测试库真库跑)、数据审计脚本清零、前端 vitest + Playwright 无头 E2E 入仓。禁止"API 填完就当完成",禁止让用户当人肉测试。
-- **检测门禁(已入仓,改动后必跑)**:① 后端 `MYSQL_TEST_DSN="license_app:local_dev_2026@tcp(127.0.0.1:13307)/license_platform_test?parseTime=true" go test ./internal/httpapi/ -run TestSuffixAdminIntegration`(独立测试库,勿用开发库);② 前端 `npx vitest run` + `npx vue-tsc --noEmit`;③ E2E `cd frontend && node node_modules/@playwright/test/cli.js test`(Playwright + channel:chrome 无头,baseURL 默认 127.0.0.1:15173,登录 fillcos4c)。三项全绿才算完成。
+- **检测门禁(已入仓,改动后必跑)**:① 后端 `MYSQL_TEST_DSN="license_app:local_dev_2026@tcp(127.0.0.1:13307)/license_platform_test?parseTime=true" go test ./internal/httpapi/ -run TestSuffixAdminIntegration`(独立测试库,勿用开发库);② 前端 `npx vitest run` + `npx vue-tsc --noEmit`;③ E2E `cd frontend && node node_modules/@playwright/test/cli.js test`(Playwright + channel:chrome 无头,baseURL 默认 127.0.0.1:15173,登录 fillcos4c)。三项全绿才算完成。④ **骨架审计** `python scripts/audit_suffix_skeleton.py --credential <购买凭据>`(双蓝本覆盖+两点式配对+七项体检;自嵌套按"连续同名段折叠"归一化比对;FAIL=exit 1)——填完每层/每次数据改动后必跑,缺口清单以它输出为准(别再人肉抽查)。2026-10-31 首版基线:FAIL 88=缺路径37(单位工程分部分项/定额直挂/暂列金额标题下明细/单位工程汇总标题下明细/#252补充费用/#259工料机含量明细/措施分部下合计费用与措施清单+其子/DAE直挂清单项目等)+缺属性2(ProjectInfo 应为 ApproverDate 非ApproveDate、WorkElement 缺 Type)+体检49(混入行34/英文列名14/等)。
+- **骨架下发管道(2026-10-31 打通,第一阶段)**:管理台 `GET /api/v1/client/skeleton/:suffix`(购买凭据 Bearer 认证,purchaseAuthenticated 同门)聚合下发 目录树+锚定+属性行(含值设置标记)+格子值+文件清单,version=内容哈希做 ETag/304;**带 Accept-Encoding 时回 gzip**(123KB→16KB)。测试 `TestSkeletonClientIntegration`(真库,含 gzip/304/版本变化)。结构始终下发,文件发布标记只随清单。租户端 `CostReview/app/core/platform_skeleton.py`:fetch/缓存(data/skeleton_cache_*.json)/validate/summary;**取数节奏「一天问一次」(用户 2026-10-31 定稿):TTL 24h 内直接用本地缓存不联网,过期带 If-None-Match 核对,304 复用,平台不可达回落旧缓存,force=True 强拉**;配置键 `skeleton_api_base`+`skeleton_credential`(环境变量→data/license/config.json→默认生产),开发态指向本机 18081(dev 后端实为 license_app@**license_platform_local** 库,启动脚本 D:/yhy-mager-local/start-platform.bat)。联调基线:cos4=98目录/98锚定/6闭合点/1180行/1177格,强拉 ~210ms / TTL 命中 ~18ms。万级在线评估:日常 304≈2MB/万人、发布雷群 gzip 后 0.16GB/万人;服务端微缓存(内存缓存渲染结果)留到上生产前按需做。第二阶段待做:租户端导出引擎按点位消费骨架(点位序列=DFS,`/开头锚定=闭合点`、无子目录=自闭合)。
+- **逐层推进工作法(2026-10-31 用户定稿)**:①层级高优先,一层一层来;②每层先「目录+锚定行」全部落位,内容(属性行)随后,**(闭)锚定点最后补**;③每个事实≥2次独立复核才确认(蓝本侧=ET解析+原文正则两法;骨架侧=客户端API+直连数据库两源),不立马下结论;④视图(三方对照可视化)+原始数据结合使用。**L0-L5 已全部核验并修复完毕(2026-10-31):审计 FAIL 0**——蓝本 148 条元素路径(归一化后 136)全覆盖、(起)48=(闭)48 配对完整、骨架接口 184 目录/1741 行/1738 已填。唯一 WARN:`/PIWC/SW/SummaryOfCost/AddiCost`(SectionalWorks 的费用汇总带补充费用)两家蓝本恰无实例但标准 6.2.10/6.2.25 合法,人工判保留。蓝本核验教训:**`.find()` 只取首实例不可信**(LMESummary 易达54实例首个恰自闭合),必须全实例聚合。标准"属性与子元素同名共存"合法对:WorkElement/PWE/UWPE 的 WorkContent(6.3.4 #27 属性 + 子元素)——审计已加白名单。可视化:session visualizations 目录 skbp.html。
+- **批跑工具链(2026-10-31 定稿)**:`scripts/apply_skeleton_batch.py`(声明式 JSON→API 批跑,每步读库断言,幂等可重跑;原语 rename/delete/create_dir、set_anchor、move_dir(双向)、add/delete/rename_column、set_cell、**pair_dir(运行时原子:改名(起)+建(闭)+双向归位——同父多对插入时预计算位次必错,必须运行时定位)**)+ `scripts/audit_suffix_skeleton.py`(FAIL=exit 1)+ 各 gen_*.py 生成器。**修复类操作一律:生成器读现状→dry-run 审阅→执行→审计清零**;界面只作人工查看。
+- **空数据结构导出(2026-10-31 入产品)**:管理台 列设置对话框 → 选格式 →「导出 XML」(`GET /api/v1/suffix-admin/suffixes/:id/structure.xml`,structure_export.go)。渲染规则=两点式((起)=开标签、(闭)=收标签、叶=自闭合、成对元素不双关门、根隐式收尾),属性=工作区普通列该后缀有值的(值留空),含义列不出,注释=管理台目录名。测试 `TestStructureExportIntegration`(真库:良构+关键片段+无双关门+含义列排除+401/404)。桌面核对文件 `C:\Users\MZ\Desktop\骨架结构-空数据模板.xml`(cos4 全量,已验:归一化路径 126 vs 蓝本并集 125,缺 0 多 1=合法 WARN)。
+- **⚠️ 本机环境异常:node.exe 写盘被驱动加密(2026-10-31 实锤,未解决)**:node/npm 写的任何文件**落盘即被加头加密**(固定头 `88 7d 1c ?? 62 00 0a 00`),非 node 进程(python/git)读到密文;node 自读自写透明(所以开发时毫无察觉)。**铁证**:node.exe 现场写→python 读=损坏;python 写→完好;git 里提交的 package-lock.json 本就是密文(HEAD blob 即乱码,2023-04 起全机 11+ 个 lock 中招,D:\web 各项目连 5-26 备份都坏)。`npm warn install-scripts` 是 npm 11.19 官方新功能(脚本审批),**不是**套壳——初判有误已更正。头号嫌疑=**广联达加密锁驱动**(本机装有 广联达加密锁程序 3.8 + GCCP7Service/gcpsvc/gdpsvc/gssvc 全家桶;确认需管理员跑 `fltmc filters` 看过滤驱动)。后果与处置:lock 已删(依赖真源=package.json,@playwright/test 已入 devDeps);**修复后须全机重生成各仓 lock**;**历史备份/拷给别人的压缩包里 node 写过的文件在别的机器上都是密文**——重要资料请抽查。本机 npm 生成 lock 必坏勿再尝试;python/git 写文件不受影响。
diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go
index 5b019f0..14c374b 100644
--- a/backend/internal/httpapi/business.go
+++ b/backend/internal/httpapi/business.go
@@ -86,7 +86,6 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
api.POST("/payments/:channel/notify", a.paymentNotify)
api.POST("/payments/checkout", a.paymentCheckout)
client := api.Group("/client", a.purchaseAuthenticated)
- client.GET("/skeleton/:suffix", a.clientSkeleton)
client.POST("/plans", a.clientPlans)
client.POST("/purchases", a.clientCreatePurchase)
client.POST("/purchases/status", a.clientPurchaseStatus)
diff --git a/backend/internal/httpapi/skeleton_client.go b/backend/internal/httpapi/skeleton_client.go
deleted file mode 100644
index 946dd40..0000000
--- a/backend/internal/httpapi/skeleton_client.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package httpapi
-
-// 客户端骨架下发:GET /api/v1/client/skeleton/:suffix(购买凭据认证,与采购接口同门)。
-// 聚合该后缀的完整数据结构:目录树(含起/闭点位)+ 每目录锚定值 + 属性行(含值设置标记)
-// + 格子值 + 已上传模板文件清单(含发布标记)。
-// 结构始终下发;version=内容哈希,支持 If-None-Match 增量(304 不回体)。
-// 两点式约定(租户端导出引擎消费):锚定值以 "/" 开头 = 闭合点;无子目录且非闭合 = 自闭合。
-
-import (
- "crypto/sha256"
- "encoding/hex"
- "net/http"
- "strconv"
- "strings"
- "unicode/utf8"
-
- "github.com/gin-gonic/gin"
-)
-
-type clientSkeletonColumn struct {
- ID uint64 `json:"id"`
- Name string `json:"name"`
- IsValue bool `json:"is_value"`
- Sort int `json:"sort"`
- ParentID *uint64 `json:"parent_id"`
- Value string `json:"value"`
-}
-
-type clientSkeletonDir struct {
- ID uint64 `json:"id"`
- ParentID *uint64 `json:"parent_id"`
- Name string `json:"name"`
- Sort int `json:"sort"`
- Anchor string `json:"anchor"`
- Columns []clientSkeletonColumn `json:"columns"`
-}
-
-type clientSkeletonFile struct {
- ID uint64 `json:"id"`
- FileName string `json:"file_name"`
- FileSize int64 `json:"file_size"`
- Published bool `json:"published"`
-}
-
-func (a *BusinessAPI) clientSkeleton(c *gin.Context) {
- name := strings.TrimSpace(c.Param("suffix"))
- if name == "" || utf8.RuneCountInString(name) > 64 {
- apiError(c, 400, "invalid_request", "后缀名无效")
- return
- }
- var suffixID uint64
- var groupName string
- if err := a.db.QueryRowContext(c,
- "SELECT s.id,g.name FROM suffixes s JOIN suffix_groups g ON g.id=s.group_id WHERE s.name=? LIMIT 1",
- name).Scan(&suffixID, &groupName); err != nil {
- apiError(c, 404, "not_found", "后缀不存在")
- return
- }
-
- // 目录树(骨架全局一棵;锚定与格子按后缀取值)
- type dirRow struct {
- ID, Parent uint64
- Name string
- Sort int
- }
- dirRows := []dirRow{}
- dRows, err := a.db.QueryContext(c,
- "SELECT id,COALESCE(parent_id,0),name,sort_order FROM suffix_dirs ORDER BY sort_order ASC,id ASC")
- if err != nil {
- apiError(c, 500, "internal_error", "目录加载失败")
- return
- }
- for dRows.Next() {
- var r dirRow
- if err = dRows.Scan(&r.ID, &r.Parent, &r.Name, &r.Sort); err != nil {
- dRows.Close()
- apiError(c, 500, "internal_error", "目录加载失败")
- return
- }
- dirRows = append(dirRows, r)
- }
- if err = dRows.Err(); err != nil {
- dRows.Close()
- apiError(c, 500, "internal_error", "目录加载失败")
- return
- }
- dRows.Close()
-
- anchors := map[uint64]string{}
- aRows, err := a.db.QueryContext(c,
- "SELECT dir_id,value FROM suffix_dir_anchors WHERE suffix_id=?", suffixID)
- if err != nil {
- apiError(c, 500, "internal_error", "锚定加载失败")
- return
- }
- for aRows.Next() {
- var id uint64
- var v string
- if err = aRows.Scan(&id, &v); err != nil {
- aRows.Close()
- apiError(c, 500, "internal_error", "锚定加载失败")
- return
- }
- anchors[id] = v
- }
- aRows.Close()
-
- cells := map[uint64]string{}
- cRows, err := a.db.QueryContext(c,
- "SELECT column_id,value FROM suffix_cells WHERE suffix_id=? AND value<>''", suffixID)
- if err != nil {
- apiError(c, 500, "internal_error", "格子加载失败")
- return
- }
- for cRows.Next() {
- var id uint64
- var v string
- if err = cRows.Scan(&id, &v); err != nil {
- cRows.Close()
- apiError(c, 500, "internal_error", "格子加载失败")
- return
- }
- cells[id] = v
- }
- cRows.Close()
-
- type colRow struct {
- Dir uint64
- Col clientSkeletonColumn
- }
- colRows := []colRow{}
- coRows, err := a.db.QueryContext(c,
- "SELECT id,dir_id,name,is_value,sort_order,parent_id FROM suffix_columns ORDER BY dir_id ASC,sort_order ASC,id ASC")
- if err != nil {
- apiError(c, 500, "internal_error", "列加载失败")
- return
- }
- for coRows.Next() {
- var r colRow
- var parent uint64
- if err = coRows.Scan(&r.Col.ID, &r.Dir, &r.Col.Name, &r.Col.IsValue, &r.Col.Sort, &parent); err != nil {
- coRows.Close()
- apiError(c, 500, "internal_error", "列加载失败")
- return
- }
- if parent > 0 {
- p := parent
- r.Col.ParentID = &p
- }
- r.Col.Value = cells[r.Col.ID]
- colRows = append(colRows, r)
- }
- if err = coRows.Err(); err != nil {
- coRows.Close()
- apiError(c, 500, "internal_error", "列加载失败")
- return
- }
- coRows.Close()
-
- files := []clientSkeletonFile{}
- fRows, err := a.db.QueryContext(c,
- "SELECT id,file_name,file_size,published FROM suffix_files WHERE suffix_id=? ORDER BY id ASC", suffixID)
- if err != nil {
- apiError(c, 500, "internal_error", "文件加载失败")
- return
- }
- for fRows.Next() {
- var f clientSkeletonFile
- if err = fRows.Scan(&f.ID, &f.FileName, &f.FileSize, &f.Published); err != nil {
- fRows.Close()
- apiError(c, 500, "internal_error", "文件加载失败")
- return
- }
- files = append(files, f)
- }
- if err = fRows.Err(); err != nil {
- fRows.Close()
- apiError(c, 500, "internal_error", "文件加载失败")
- return
- }
- fRows.Close()
-
- // 组装 + 内容哈希(目录/锚定/列/格子/文件全量参与,任何改动都会变版本)
- dirs := make([]clientSkeletonDir, 0, len(dirRows))
- hash := sha256.New()
- hash.Write([]byte("suffix:" + strconv.FormatUint(suffixID, 10) + ":" + name))
- colsByDir := map[uint64][]clientSkeletonColumn{}
- for _, r := range colRows {
- colsByDir[r.Dir] = append(colsByDir[r.Dir], r.Col)
- s := strconv.FormatUint(r.Col.ID, 10) + ":" + r.Col.Name
- if r.Col.IsValue {
- s += ":v"
- }
- s += ":" + r.Col.Value
- hash.Write([]byte("|c" + s))
- }
- for _, d := range dirRows {
- var parent *uint64
- if d.Parent > 0 {
- p := d.Parent
- parent = &p
- }
- cols := colsByDir[d.ID]
- if cols == nil {
- cols = []clientSkeletonColumn{}
- }
- dirs = append(dirs, clientSkeletonDir{ID: d.ID, ParentID: parent, Name: d.Name, Sort: d.Sort, Anchor: anchors[d.ID], Columns: cols})
- hash.Write([]byte("|d" + strconv.FormatUint(d.ID, 10) + ":" + d.Name + ":" + anchors[d.ID]))
- }
- for _, f := range files {
- hash.Write([]byte("|f" + strconv.FormatUint(f.ID, 10) + ":" + f.FileName + ":" + strconv.FormatInt(f.FileSize, 10) + ":" + strconv.FormatBool(f.Published)))
- }
- version := hex.EncodeToString(hash.Sum(nil))
-
- etag := `"` + version + `"`
- c.Header("ETag", etag)
- c.Header("Cache-Control", "no-store")
- if match := c.GetHeader("If-None-Match"); match != "" && strings.Contains(match, version) {
- c.Status(http.StatusNotModified)
- return
- }
- c.JSON(200, gin.H{"data": gin.H{
- "suffix": gin.H{"id": suffixID, "name": name, "group": groupName},
- "version": version,
- "dirs": dirs,
- "files": files,
- }})
-}
diff --git a/backend/internal/httpapi/suffixes.go b/backend/internal/httpapi/suffixes.go
index 5022238..a36fbe5 100644
--- a/backend/internal/httpapi/suffixes.go
+++ b/backend/internal/httpapi/suffixes.go
@@ -58,6 +58,7 @@ func registerSuffixRoutes(secured *gin.RouterGroup, a *BusinessAPI) {
s.DELETE("/files/:id", a.deleteSuffixFile)
s.GET("/files/:id/download", a.downloadSuffixFile)
s.POST("/files/:id/publish", a.publishSuffixFile)
+ s.GET("/suffixes/:id/structure.xml", a.exportSuffixStructure)
}
func suffixTrimName(raw string, max int) (string, bool) {
@@ -838,8 +839,7 @@ type suffixOverview struct {
func (a *BusinessAPI) createSuffixGroup(c *gin.Context) {
var in struct {
- Name string `json:"name"`
- FirstSuffixName string `json:"first_suffix_name"`
+ Name string `json:"name"`
}
if c.ShouldBindJSON(&in) != nil {
apiError(c, 400, "invalid_request", "参数无效")
@@ -855,50 +855,16 @@ func (a *BusinessAPI) createSuffixGroup(c *gin.Context) {
apiError(c, 409, "duplicate_name", "已有同名分组")
return
}
- // 首个后缀名可选:填了就随组自动建一行工作行(同名自动 -1)。
- firstName, firstOK := suffixTrimName(in.FirstSuffixName, 64)
- if firstOK {
- final := firstName
- for i := 1; ; i++ {
- var dup2 int
- if a.db.QueryRowContext(c, "SELECT 1 FROM suffixes WHERE name=?", final).Scan(&dup2) != nil {
- break
- }
- final = firstName + "-" + strconv.Itoa(i)
- }
- firstName = final
- }
var order sql.NullInt64
_ = a.db.QueryRowContext(c, "SELECT MAX(sort_order) FROM suffix_groups").Scan(&order)
- tx, err := a.db.BeginTx(c, nil)
- if err != nil {
- apiError(c, 500, "internal_error", "分组创建失败")
- return
- }
- defer tx.Rollback()
- gres, err := tx.ExecContext(c,
+ res, err := a.db.ExecContext(c,
"INSERT INTO suffix_groups(name,sort_order) VALUES(?,?)", name, order.Int64+1)
if err != nil {
apiError(c, 500, "internal_error", "分组创建失败")
return
}
- gid, _ := gres.LastInsertId()
- created := []suffixOverview{}
- if firstOK {
- sres, err := tx.ExecContext(c,
- "INSERT INTO suffixes(group_id,name,sort_order) VALUES(?,?,0)", gid, firstName)
- if err != nil {
- apiError(c, 500, "internal_error", "分组创建失败")
- return
- }
- sid, _ := sres.LastInsertId()
- created = append(created, suffixOverview{ID: uint64(sid), Name: firstName})
- }
- if err := tx.Commit(); err != nil {
- apiError(c, 500, "internal_error", "分组创建失败")
- return
- }
- c.JSON(201, gin.H{"data": gin.H{"id": gid, "name": name, "suffixes": created}})
+ gid, _ := res.LastInsertId()
+ c.JSON(201, gin.H{"data": gin.H{"id": gid, "name": name, "suffixes": []suffixOverview{}}})
}
func (a *BusinessAPI) renameSuffixGroup(c *gin.Context) {
@@ -1096,24 +1062,23 @@ func (a *BusinessAPI) moveSuffix(c *gin.Context) {
func (a *BusinessAPI) deleteSuffix(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
- files := []string{}
- fRows, err := a.db.QueryContext(c,
- "SELECT rel_path FROM suffix_files WHERE suffix_id=?", id)
- if err == nil {
- for fRows.Next() {
- var p string
- if fRows.Scan(&p) == nil {
- files = append(files, p)
- }
- }
- fRows.Close()
+ // 行删除保护:名下还有上传附件时不允许删,先清附件才能删行
+ var n int
+ if err := a.db.QueryRowContext(c,
+ "SELECT COUNT(*) FROM suffix_files WHERE suffix_id=?", id).Scan(&n); err != nil {
+ apiError(c, 500, "internal_error", "删除失败")
+ return
+ }
+ if n > 0 {
+ apiError(c, 409, "suffix_has_files",
+ fmt.Sprintf("该行已上传 %d 个附件,请先删除附件再删除本行", n))
+ return
}
res, err := a.db.ExecContext(c, "DELETE FROM suffixes WHERE id=?", id)
if err != nil || rowsAffected(res) == 0 {
apiError(c, 404, "not_found", "后缀不存在")
return
}
- a.removeDiskFiles(c, files)
c.JSON(200, gin.H{"data": gin.H{"deleted": id}})
}
diff --git a/backend/internal/httpapi/suffixes_test.go b/backend/internal/httpapi/suffixes_test.go
index 231015c..90f9dbd 100644
--- a/backend/internal/httpapi/suffixes_test.go
+++ b/backend/internal/httpapi/suffixes_test.go
@@ -123,17 +123,6 @@ func TestSuffixAdminIntegration(t *testing.T) {
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 {
@@ -459,6 +448,14 @@ func TestSuffixAdminIntegration(t *testing.T) {
if _, err := os.Stat(filepath.Join(storageRoot, "attachments", strconv.FormatUint(suffixID, 10), storedName)); err != nil {
t.Fatalf("附件未落在 attachments 目录: %v", err)
}
+ // 行删除保护:名下有附件 → 409
+ w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d", suffixID), "")
+ if w.Code != 409 {
+ t.Fatalf("有附件删行 status=%d, want 409", w.Code)
+ }
+ if msg := getJSON(w)["error"].(map[string]any)["message"].(string); !strings.Contains(msg, "附件") {
+ t.Fatalf("409 提示应包含附件: %s", msg)
+ }
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"}`,
@@ -487,6 +484,17 @@ func TestSuffixAdminIntegration(t *testing.T) {
if w.Code != 200 {
t.Fatalf("删模板 status=%d", w.Code)
}
+ // 附件清空后行可删:新建无附件临时行直接删
+ w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes",
+ fmt.Sprintf(`{"group_id":%d,"name":"tmpdel"}`, groupID))
+ if w.Code != 201 {
+ t.Fatalf("建临时行 status=%d body=%s", w.Code, w.Body.String())
+ }
+ tmpID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
+ w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d", tmpID), "")
+ if w.Code != 200 {
+ t.Fatalf("无附件删行 status=%d body=%s", w.Code, w.Body.String())
+ }
// 删除保护:子目录未清 / 格子、锚定值有内容 → 409;清空后空列随删 → 200
w = authed(http.MethodPost, "/api/v1/suffix-admin/dirs", fmt.Sprintf(`{"parent_id":%d,"name":"删除保护目录"}`, rootID))
diff --git a/frontend/e2e/suffix-workspace.spec.ts b/frontend/e2e/suffix-workspace.spec.ts
index d8931d1..5bc985a 100644
--- a/frontend/e2e/suffix-workspace.spec.ts
+++ b/frontend/e2e/suffix-workspace.spec.ts
@@ -1,7 +1,9 @@
import { expect, test } from '@playwright/test'
// 后缀管理转置工作区 E2E:登录 → 选目录 → 断言转置渲染 → 编辑格/元素名。
-// 依赖开发库中的固定夹具:广东省分组 + cos/cos4/swt 三格式 + 单项工程目录(id 228)。
+// 依赖开发库中的固定夹具:cos/cos4/swt 三格式 + 单项工程目录(id 228)。
+// 格式列是动态的(后缀/分组随时增删推送),不做写死清单断言:
+// 只断言核心格式在列,格式列序号从表头实时解析。
const USER = 'fillcos4c'
const PASS = 'Fill-Cos4c-2026!'
@@ -23,15 +25,28 @@ async function openSuffix(page: import('@playwright/test').Page) {
// 展开树到 单项工程 并选中(建设项目 → 建筑安装工程费 → 单项工程)
async function openSingleProject(page: import('@playwright/test').Page) {
- // 展开靠 .tw(+/−)开关,目录名点击只做选中
- const node = page.locator('.side-node', { hasText: '建筑安装工程费' })
- await node.locator('.tw').click()
+ // 目录名点击只做选中;展开靠 .tw(+/−)开关,且要状态感知——
+ // 树的初始展开态不保证(可能全展开),已展开时再点 .tw 反而会收起。
+ // 目录名用精确匹配(树里有 建筑安装工程费汇总/标题 等同名前缀目录)。
const sw = page.locator('.side-name', { hasText: '单项工程' }).first()
+ if (!(await sw.isVisible().catch(() => false))) {
+ const node = page.locator('.side-node').filter({ has: page.locator('.side-name', { hasText: /^建筑安装工程费$/ }) })
+ await node.locator('.tw').click()
+ }
await sw.waitFor({ state: 'visible', timeout: 10_000 })
await sw.click()
await expect(page.locator('.attr-sheet')).toBeVisible({ timeout: 10_000 })
}
+// 从表头实时解析某格式列在 .cell 序列里的下标(td.cell 只存在于格式列,
+// 前面还有 # 与 属性 两个固定列),后缀增删后自动适应。
+async function fmtCellIndex(page: import('@playwright/test').Page, fmt: string) {
+ const headers = (await page.locator('.attr-sheet thead th').allTextContents()).map((t) => t.trim())
+ const at = headers.indexOf(fmt)
+ expect(headers, `表头应含格式列 ${fmt}`).toContain(fmt)
+ return at - 2
+}
+
test('转置工作区:格式列头 + 元素名行 + 属性行渲染', async ({ page }) => {
await login(page)
await openSuffix(page)
@@ -39,15 +54,20 @@ test('转置工作区:格式列头 + 元素名行 + 属性行渲染', async ({
await openSingleProject(page)
const sheet = page.locator('.attr-sheet')
await expect(sheet).toBeVisible()
- // 列头 = 三个格式
- await expect(sheet.locator('thead th')).toHaveText(['属性', 'cos', 'cos4', 'swt'])
- // 首行 = 元素名:cos4 列 = SectionalWorks
+ // 列头:固定两列在前;核心格式在列(不锁死后缀全集,后缀可动态增删)
+ const headers = (await sheet.locator('thead th').allTextContents()).map((t) => t.trim())
+ expect(headers.slice(0, 2)).toEqual(['#', '属性'])
+ for (const fmt of ['cos', 'cos4', 'swt']) {
+ expect(headers, `表头应含 ${fmt}`).toContain(fmt)
+ }
+ // 首行 = 元素名:cos4 列 = SectionalWorks(列序实时解析)
+ const cos4At = await fmtCellIndex(page, 'cos4')
const anchorRow = sheet.locator('tr.anchor-row')
- await expect(anchorRow.locator('.cell').nth(1)).toHaveText('SectionalWorks')
+ await expect(anchorRow.locator('.cell').nth(cos4At)).toHaveText('SectionalWorks')
// 属性行含 工程编号(cos4 = Number)
const row = sheet.locator('tr.data-tr', { hasText: '工程编号' })
await expect(row).toBeVisible()
- await expect(row.locator('.cell').nth(1)).toHaveText('Number')
+ await expect(row.locator('.cell').nth(cos4At)).toHaveText('Number')
})
test('双击元素名格 → 编辑 swt 锚定值 → 走锚定 API 保存', async ({ page }) => {
@@ -55,28 +75,30 @@ test('双击元素名格 → 编辑 swt 锚定值 → 走锚定 API 保存', asy
await openSuffix(page)
await openSingleProject(page)
const anchorRow = page.locator('tr.anchor-row')
- // swt 列(第 3 个格式格)双击 → 输入深圳标准的元素名
- const swtCell = anchorRow.locator('.cell').nth(2)
+ // swt 列双击 → 输入深圳标准的元素名(列序实时解析)
+ const swtAt = await fmtCellIndex(page, 'swt')
+ const swtCell = anchorRow.locator('.cell').nth(swtAt)
await swtCell.dblclick()
const input = swtCell.locator('input')
await expect(input).toBeVisible()
await input.fill('SectionalWorks')
await input.press('Enter')
// 保存后回显
- await expect(anchorRow.locator('.cell').nth(2)).toHaveText('SectionalWorks', { timeout: 10_000 })
+ await expect(anchorRow.locator('.cell').nth(swtAt)).toHaveText('SectionalWorks', { timeout: 10_000 })
})
test('双击属性格 → 编辑 swt 映射值 → 走 cells API 保存', async ({ page }) => {
await login(page)
await openSuffix(page)
await openSingleProject(page)
- // 工程编号 行 × swt 列:深圳标准的属性名 Code
+ // 工程编号 行 × swt 列:深圳标准的属性名 Code(列序实时解析)
const row = page.locator('tr.data-tr', { hasText: '工程编号' })
- const swtCell = row.locator('.cell').nth(2)
+ const swtAt = await fmtCellIndex(page, 'swt')
+ const swtCell = row.locator('.cell').nth(swtAt)
await swtCell.dblclick()
const input = swtCell.locator('input')
await expect(input).toBeVisible()
await input.fill('Code')
await input.press('Enter')
- await expect(row.locator('.cell').nth(2)).toHaveText('Code', { timeout: 10_000 })
+ await expect(row.locator('.cell').nth(swtAt)).toHaveText('Code', { timeout: 10_000 })
})
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
deleted file mode 100644
index 27c0686..0000000
Binary files a/frontend/package-lock.json and /dev/null differ
diff --git a/frontend/package.json b/frontend/package.json
index 58378d5..fd7766b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -19,6 +19,7 @@
"vue-router": "^4.5.0"
},
"devDependencies": {
+ "@playwright/test": "^1.64.1",
"@types/qrcode": "^1.5.6",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/test-utils": "^2.5.1",
diff --git a/frontend/src/suffix-admin.ts b/frontend/src/suffix-admin.ts
index 3c9ffc7..2e5a07e 100644
--- a/frontend/src/suffix-admin.ts
+++ b/frontend/src/suffix-admin.ts
@@ -27,7 +27,7 @@ export const getSuffixColWidths = () => api.get<{data:{widths:SuffixColWidths}}>
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 createSuffixGroup = (name:string) => api.post<{data:SuffixGroup}>('/suffix-admin/groups', { name })
export const renameSuffixGroup = (id:number, name:string) => api.put(`/suffix-admin/groups/${id}`, { name })
export const moveSuffixGroup = (id:number, dir:number) => api.post(`/suffix-admin/groups/${id}/move`, { dir })
export const deleteSuffixGroup = (id:number) => api.delete(`/suffix-admin/groups/${id}`)
diff --git a/frontend/src/views/SuffixPanel.test.ts b/frontend/src/views/SuffixPanel.test.ts
index 69e982d..4b82441 100644
--- a/frontend/src/views/SuffixPanel.test.ts
+++ b/frontend/src/views/SuffixPanel.test.ts
@@ -3,7 +3,7 @@ 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, moveSuffixDir, deleteSuffixDir, renameSuffixColumn, saveSuffixCell, setSuffixAnchor, updateSuffixColWidth, updateSuffixColumnWidth,
+ createSuffixColumn, createSuffixGroup, deleteSuffix, deleteSuffixColumn, getSuffixColWidths, getSuffixOverview, getSuffixPage, getSuffixTree, moveSuffixDir, deleteSuffixDir, renameSuffixColumn, saveSuffixCell, setSuffixAnchor, updateSuffixColWidth, updateSuffixColumnWidth,
} from '../suffix-admin'
vi.mock('../suffix-admin', () => ({
@@ -77,8 +77,8 @@ const page: any = {
anchors: { '138': '', '139': 'LabourMaterialsEquipmentsMachinesSummary', '142': '' },
}
-function setup(widths: Record<string, Record<string, number>> = {}) {
- vi.mocked(getSuffixOverview).mockResolvedValue(ok({ groups: [{ id: 1, name: '广东省', suffixes: [{ id: 138, name: 'cos', files: [] }, { id: 139, name: 'cos4', files: [] }, { id: 142, name: 'swt', files: [] }] }] }) as never)
+function setup(widths: Record<string, Record<string, number>> = {}, overview?: unknown) {
+ vi.mocked(getSuffixOverview).mockResolvedValue(ok(overview ?? { groups: [{ id: 1, name: '广东省', suffixes: [{ id: 138, name: 'cos', files: [] }, { id: 139, name: 'cos4', files: [] }, { id: 142, name: 'swt', files: [] }] }] }) as never)
vi.mocked(getSuffixTree).mockResolvedValue(ok({ dirs }) as never)
vi.mocked(getSuffixPage).mockResolvedValue(ok(JSON.parse(JSON.stringify(page))) as never)
vi.mocked(getSuffixColWidths).mockResolvedValue(ok({ widths }) as never)
@@ -94,7 +94,7 @@ describe('SuffixPanel', () => {
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('广东省')
expect(wrapper.text()).toContain('cos4')
@@ -173,6 +173,52 @@ describe('SuffixPanel', () => {
expect(wrapper.findAll('tbody tr.data-tr').map(rowName)).toEqual(['元素名', '类型'])
})
+ it('creates a group with name only and colors file chips by publish state', async () => {
+ const overview = { groups: [{ id: 1, name: '广东省', suffixes: [{ id: 138, name: 'cos', files: [
+ { id: 21, file_name: '某某项目骨架文件名很长很长很长很长.cos', file_size: 10, published: true },
+ { id: 22, file_name: 'b.cos', file_size: 10, published: false },
+ ] }] }] }
+ const wrapper = setup({}, overview)
+ await flushPromises()
+ // 发布块=绿底类,未发布=蓝底类;不再有「已发布」小标签
+ const pub = wrapper.find('.file-chip.is-pub')
+ expect(pub.exists()).toBe(true)
+ expect(pub.text()).not.toContain('已发布')
+ expect(wrapper.find('.file-chip.no-pub').exists()).toBe(true)
+ // 新建分组弹框只问分组名(首个后缀名与提示段已取消)
+ await wrapper.findAll('button').find((b) => b.text() === '+ 新建分组')!.trigger('click')
+ const labels = wrapper.findAll('.dialog-stub .lab').map((l) => l.text())
+ expect(labels).toEqual(['分组名(分类名)'])
+ vi.mocked(createSuffixGroup).mockResolvedValue(ok({ id: 9, name: '湖南省', suffixes: [] }) as never)
+ const nameInput = wrapper.find('.dialog-stub input')
+ await nameInput.setValue('湖南省')
+ await wrapper.findAll('.dialog-stub button').find((b) => b.text() === '确定')!.trigger('click')
+ await flushPromises()
+ expect(createSuffixGroup).toHaveBeenCalledWith('湖南省')
+ })
+
+ it('blocks deleting a suffix row that has attachments and allows empty ones', async () => {
+ const overview = { groups: [{ id: 1, name: '广东省', suffixes: [
+ { id: 138, name: 'cos', files: [{ id: 21, file_name: 'a.cos', file_size: 5, published: false }] },
+ { id: 139, name: 'cos4', files: [] },
+ ] }] }
+ const wrapper = setup({}, overview)
+ await flushPromises()
+ const rowByName = (n: string) => wrapper.findAll('table.basic tbody tr.data-tr').find((r) => r.find('.suffix-name').text() === n)!
+ // 有附件:直接警告,不弹确认、不发请求
+ await rowByName('cos').find('button[title="删除后缀"]').trigger('click')
+ await flushPromises()
+ expect(ElMessage.warning).toHaveBeenCalledWith('「cos」名下已上传 1 个附件,请先删除附件再删除本行')
+ expect(ElMessageBox.confirm).not.toHaveBeenCalled()
+ expect(deleteSuffix).not.toHaveBeenCalled()
+ // 无附件:确认后删除
+ vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm' as never)
+ vi.mocked(deleteSuffix).mockResolvedValue(ok({ deleted: 139 }) as never)
+ await rowByName('cos4').find('button[title="删除后缀"]').trigger('click')
+ await flushPromises()
+ expect(deleteSuffix).toHaveBeenCalledWith(139)
+ })
+
it('resizes the directory sidebar by dragging its right edge', async () => {
localStorage.removeItem('suffixSideWidth')
try {
diff --git a/frontend/src/views/SuffixPanel.vue b/frontend/src/views/SuffixPanel.vue
index 0687783..11751fe 100644
--- a/frontend/src/views/SuffixPanel.vue
+++ b/frontend/src/views/SuffixPanel.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, onMounted, reactive, ref } from 'vue'
+import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
createSuffix, createSuffixColumn, createSuffixDir, createSuffixGroup,
@@ -78,6 +78,13 @@ const wsFixedCols = [
{ key: 'attr', name: '属性名列' },
]
const wsWidths = reactive({ visible: false })
+// 空数据结构导出(列设置入口):按两点式渲染当前后缀的骨架为空值 XML
+const exportSid = ref<number | null>(null)
+watch(() => wsWidths.visible, (v) => { if (v) exportSid.value = fmts.value[0]?.id ?? null })
+const structureUrl = computed(() => {
+ const sid = exportSid.value ?? fmts.value[0]?.id ?? 0
+ return sid ? `/api/v1/suffix-admin/suffixes/${sid}/structure.xml` : undefined
+})
// 格式列隐藏(列设置弹窗勾选):本机界面偏好,存 localStorage
const hiddenCols = ref(new Set<string>())
@@ -281,11 +288,11 @@ async function moveDir(dir: SuffixDir, dirNum: number) {
}
}
-// ---- 基本设置:分组与后缀 ----
+// ---- 电子标书:分组与后缀 ----
-const groupDialog = reactive({ visible: false, name: '', suffixName: '', saving: false })
+const groupDialog = reactive({ visible: false, name: '', saving: false })
-// 基本设置:分组行 −/+ 把手,收起该组后缀行(组名与计数保留)
+// 电子标书:分组行 −/+ 把手,收起该组后缀行(组名与计数保留)
const collapsedGroups = ref(new Set<number>())
function toggleGroup(id: number) {
const next = new Set(collapsedGroups.value)
@@ -296,7 +303,7 @@ function toggleGroup(id: number) {
function addGroup() {
groupDialog.name = ''
- groupDialog.suffixName = ''
+ groupDialog.name = ''
groupDialog.visible = true
}
@@ -309,10 +316,10 @@ async function submitGroup() {
}
groupDialog.saving = true
try {
- await createSuffixGroup(name, groupDialog.suffixName.trim())
+ await createSuffixGroup(name)
groupDialog.visible = false
await loadOverview()
- ElMessage.success(groupDialog.suffixName.trim() ? '分组已创建(含一行后缀)' : '分组已创建')
+ ElMessage.success('分组已创建')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '创建失败')
} finally {
@@ -374,9 +381,14 @@ async function moveSuffixRow(id: number, dir: number) {
}
}
-async function removeSuffix(s: { id:number; name:string }) {
+async function removeSuffix(s: { id:number; name:string; files?: { id:number }[] }) {
+ // 行删除保护:名下还有上传附件时不允许删,先清附件
+ if (s.files?.length) {
+ ElMessage.warning(`「${s.name || '(未命名)'}」名下已上传 ${s.files.length} 个附件,请先删除附件再删除本行`)
+ return
+ }
try {
- await ElMessageBox.confirm(`删除后缀「${s.name || '(未命名)'}」会连同它名下的模板文件一起删除,确定吗?`, '删除后缀', { type: 'warning' })
+ await ElMessageBox.confirm(`删除后缀「${s.name || '(未命名)'}」?`, '删除后缀', { type: 'warning' })
} catch { return }
try {
await deleteSuffix(s.id)
@@ -640,7 +652,7 @@ onMounted(() => {
<div class="suffix-shell">
<aside v-show="!dirCollapsed" class="suffix-side" :style="{ width: sideWidth + 'px', flexBasis: sideWidth + 'px' }">
<div class="side-resizer" @mousedown="startSideResize"></div>
- <div class="side-root" :class="{ active: selected.kind === 'basic' }" @click="selectNode({ kind: 'basic' })">基本设置</div>
+ <div class="side-root" :class="{ active: selected.kind === 'basic' }" @click="selectNode({ kind: 'basic' })">电子标书</div>
<div class="side-sep"></div>
<div
class="side-root"
@@ -677,10 +689,10 @@ onMounted(() => {
@click="toggleDirFold"
>{{ dirCollapsed ? '›' : '‹' }}</div>
<main class="suffix-main">
- <!-- 基本设置:分组 + 后缀 + 模板 -->
+ <!-- 电子标书:分组 + 后缀 + 模板 -->
<template v-if="selected.kind === 'basic'">
<div class="bar">
- <strong>基本设置</strong>
+ <strong>电子标书</strong>
<span class="grow"></span>
<span class="bar-btns">
<el-button size="small" @click="basicWidths.visible = true">列宽</el-button>
@@ -723,9 +735,8 @@ onMounted(() => {
<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">
+ <span v-for="f in s.files" :key="f.id" class="file-chip" :class="f.published ? 'is-pub' : 'no-pub'" :title="f.published ? '已发布' : '未发布'">
<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>
@@ -847,10 +858,6 @@ onMounted(() => {
<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>
@@ -859,7 +866,7 @@ onMounted(() => {
</el-dialog>
<el-dialog v-model="basicWidths.visible" title="列宽设置" width="480px">
- <div class="col-order-hint">基本设置的所有列(含固定列)宽度均可自由设置,单位 px;0=自适应,导入文件为 0 时占满剩余宽度。</div>
+ <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>
@@ -919,6 +926,17 @@ onMounted(() => {
/>
</div>
</div>
+ <div class="col-export-row">
+ <span class="coe-label">导出空数据结构</span>
+ <el-select v-model="exportSid" size="small" placeholder="选择格式" class="coe-select">
+ <el-option v-for="f in fmts" :key="f.id" :label="`${f.name}(${f.group_name})`" :value="f.id" />
+ </el-select>
+ <a
+ v-if="structureUrl"
+ class="el-button el-button--primary el-button--plain el-button--small"
+ :href="structureUrl"
+ >导出 XML</a>
+ </div>
<template #footer>
<el-button @click="wsWidths.visible = false">关闭</el-button>
</template>
@@ -927,6 +945,9 @@ onMounted(() => {
</template>
<style scoped>
+.col-export-row{display:flex;align-items:center;gap:8px;margin:10px 2px 2px}
+.col-export-row .coe-label{font-size:12px;color:#526173}
+.col-export-row .coe-select{width:180px}
.suffix-shell{display:flex;gap:8px;height:calc(100vh - 5px);align-items:stretch;position:relative;overflow:hidden}
.dir-fold{position:absolute;top:50%;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}
.dir-fold.collapsed{border-left:1px solid #d8dfe8;border-radius:6px 0 0 6px}
@@ -942,7 +963,7 @@ onMounted(() => {
.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{display:flex;align-items:center;gap:5px;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}
@@ -952,7 +973,8 @@ onMounted(() => {
.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{display:flex;align-items:center;gap:5px;padding:0 0 6px;width:100%}
+.bar .el-button+.el-button{margin-left:0}
.bar strong{font-size:15px}
.bar-btns{display:inline-flex;align-items:center;gap:5px}
.bar-btns .el-button+.el-button{margin-left:0}
@@ -961,6 +983,10 @@ onMounted(() => {
.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}
+/* 所有 el-button 相邻间距统一 5px(弹框 footer 等);bar 内由 flex gap 接管 */
+.suffix-shell :deep(.el-button + .el-button){margin-left:5px}
+.suffix-shell .bar .el-button + .el-button,
+.suffix-shell .bar-btns .el-button + .el-button{margin-left:0}
.col-set-head{display:flex;align-items:center;gap:8px;font-size:12px;color:#8a97a8;border-bottom:1px solid #e5eaf0;padding-bottom:6px;margin-bottom:6px}
.col-set-head .csh-name{flex:1}
.col-set-head .csh-width{width:88px;text-align:center}
@@ -1014,9 +1040,10 @@ table.sheet.basic tr.data-tr:hover td{background:#fafcff}
.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}
+.file-chip{display:inline-flex;align-items:center;gap:4px;border:1px solid #d8e4f5;border-radius:4px;padding:1px 6px;font-size:12px;width:150px;flex:0 0 150px;overflow:hidden}
+.file-chip.is-pub{background:#e8f6ef;border-color:#b9e2cd}
+.file-chip.no-pub{background:#f2f7ff}
+.file-chip a{color:#1769e0;text-decoration:none;flex:1;min-width:0;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}