refactor(export): 整体采纳改块通道,退役骨架引擎与手工导出
This commit is contained in:
@@ -1,872 +0,0 @@
|
|||||||
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}
|
|
||||||
@@ -98,6 +98,8 @@ def _ru(v, dec):
|
|||||||
return "" if v is None else str(v)
|
return "" if v is None else str(v)
|
||||||
|
|
||||||
|
|
||||||
|
# 决策 276(2026-11-06 主人定「导出的整个逻辑」):骨架的空属性槽照导——项目数据存了值就导值
|
||||||
|
# (ExtraA="va"),没存就导空槽(ExtraA="");274 补记十一「空串属性剥离」与此相撞,已整体退回。
|
||||||
def _fmt_qty(v, dec):
|
def _fmt_qty(v, dec):
|
||||||
"""工程量按源文件规律定格式写出(规格 2026-10-16:横琴 234/234 定额 Quantity 恒 6 位
|
"""工程量按源文件规律定格式写出(规格 2026-10-16:横琴 234/234 定额 Quantity 恒 6 位
|
||||||
小数、113/113 清单恒 3 位)——改过的量按修改后的数字、按原文件同款小数位导出。"""
|
小数、113/113 清单恒 3 位)——改过的量按修改后的数字、按原文件同款小数位导出。"""
|
||||||
@@ -433,13 +435,24 @@ def _norm_xml(n, lres, template=None, bill_qty=None, form_bank=None):
|
|||||||
_m_up = (re.search('<UnitPriceCalculationOfItem[^>]*?/>', pre)
|
_m_up = (re.search('<UnitPriceCalculationOfItem[^>]*?/>', pre)
|
||||||
or re.search('<UnitPriceCalculationOfItem[^>]*?/>', post))
|
or re.search('<UnitPriceCalculationOfItem[^>]*?/>', post))
|
||||||
pre, post = _zero_results(pre), _zero_results(post)
|
pre, post = _zero_results(pre), _zero_results(post)
|
||||||
|
# 决策 279:IncFees 剥除网与实验开关退役(块通道自带成对层)
|
||||||
if _side_rows and _m_up:
|
if _side_rows and _m_up:
|
||||||
_order = re.findall(' ([A-Za-z0-9_]+)="', _m_up.group(0))
|
_order = re.findall(' ([A-Za-z0-9_]+)="', _m_up.group(0))
|
||||||
|
_oset = set(_order)
|
||||||
_rows = []
|
_rows = []
|
||||||
for _r in _side_rows:
|
for _r in _side_rows:
|
||||||
_at = _r.get("attrs") or {}
|
_at = _r.get("attrs") or {}
|
||||||
_rows.append('<%s%s/>' % (_r.get("tag"), "".join(
|
# 决策 275 护栏(2026-11-06 主人定「同后缀照搬,有则搬无则不搬」):行组
|
||||||
' %s="%s"' % (k, _esc(_at[k])) for k in _order if _at.get(k) is not None)))
|
# 记录带模板列集之外的属性(同后缀照搬的外部行、IncFees 组成等)→ 按记录
|
||||||
|
# 自己的属性集原样写(照源,不被模板列闸门削掉);属性全在模板列内的照
|
||||||
|
# 模板列序写(273 既有口径:列序照模板、来源多出的列不导)。
|
||||||
|
_keys = [k for k in _at if _at.get(k) is not None]
|
||||||
|
if any(k not in _oset for k in _keys):
|
||||||
|
_rows.append('<%s%s/>' % (_r.get("tag"), "".join(
|
||||||
|
' %s="%s"' % (k, _esc(_at[k])) for k in _keys)))
|
||||||
|
else:
|
||||||
|
_rows.append('<%s%s/>' % (_r.get("tag"), "".join(
|
||||||
|
' %s="%s"' % (k, _esc(_at[k])) for k in _order if _at.get(k) is not None)))
|
||||||
pre = re.sub('<UnitPriceCalculationOfItem[^>]*?/>', '', pre)
|
pre = re.sub('<UnitPriceCalculationOfItem[^>]*?/>', '', pre)
|
||||||
post = re.sub('<UnitPriceCalculationOfItem[^>]*?/>', '', post)
|
post = re.sub('<UnitPriceCalculationOfItem[^>]*?/>', '', post)
|
||||||
post = "".join(_rows) + post # 回插 LME 之后原区域(行序照库=显示端一致)
|
post = "".join(_rows) + post # 回插 LME 之后原区域(行序照库=显示端一致)
|
||||||
@@ -645,7 +658,32 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
|
|||||||
vs = _ru((agg[c] / bq if bq else 0.0), 4)
|
vs = _ru((agg[c] / bq if bq else 0.0), 4)
|
||||||
rows.append(_lme_row(lspans[0].group(0), c, vs, express=vs))
|
rows.append(_lme_row(lspans[0].group(0), c, vs, express=vs))
|
||||||
post = post[:lspans[0].start()] + _native_sep(tmpl_blk, _LME).join(rows) + post[lspans[-1].end():]
|
post = post[:lspans[0].start()] + _native_sep(tmpl_blk, _LME).join(rows) + post[lspans[-1].end():]
|
||||||
return t + _zero_results(pre) + region + _zero_results(post) + close
|
# 决策 274 补记九(2026-11-05 主人定):清单级工程量算式行=数据结构层必备,
|
||||||
|
# Express/Quantity 填本清单工程量(锚模板的量清零后按本清单量回填——
|
||||||
|
# 源件原生清单实证 Express=Quantity=清单量,如 1123.86)。
|
||||||
|
w_q = ""
|
||||||
|
try:
|
||||||
|
w_q = ("%.*f" % (6, float(b.get("Quantity")))).rstrip("0").rstrip(".") or "0"
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
w_q = "0"
|
||||||
|
def _fill_attr(tag_):
|
||||||
|
out = tag_
|
||||||
|
for nm_ in ("Express", "Quantity"):
|
||||||
|
key_ = nm_ + '="'
|
||||||
|
i_ = out.find(key_)
|
||||||
|
if i_ < 0:
|
||||||
|
continue
|
||||||
|
j_ = out.find('"', i_ + len(key_))
|
||||||
|
out = out[:i_ + len(key_)] + w_q + out[j_:]
|
||||||
|
return out
|
||||||
|
_el_pat = '<' + chr(92) + 'bExpressElement' + chr(92) + 'b[^>]*?/>'
|
||||||
|
pre = re.sub(_el_pat, lambda mm: _fill_attr(mm.group(0)), pre, count=1)
|
||||||
|
post = re.sub(_el_pat, lambda mm: _fill_attr(mm.group(0)), post, count=1)
|
||||||
|
pre = _zero_results(pre)
|
||||||
|
post = _zero_results(post)
|
||||||
|
pre = re.sub(_el_pat, lambda mm: _fill_attr(mm.group(0)), pre, count=1) # 清零后填本清单量(顺序不可反)
|
||||||
|
post = re.sub(_el_pat, lambda mm: _fill_attr(mm.group(0)), post, count=1)
|
||||||
|
return t + pre + region + post + close
|
||||||
|
|
||||||
|
|
||||||
def _attr_sep_of(txt):
|
def _attr_sep_of(txt):
|
||||||
@@ -760,6 +798,20 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
|||||||
# 决策 274 补记三:编辑过的原有清单按**该清单源件原文的小数位**写
|
# 决策 274 补记三:编辑过的原有清单按**该清单源件原文的小数位**写
|
||||||
# (原数据来多少位保留多少位);位数装不下真值时升位保真(_qty_like)
|
# (原数据来多少位保留多少位);位数装不下真值时升位保真(_qty_like)
|
||||||
want = _qty_like(_attr(mk["opentag"], "Quantity"), want)
|
want = _qty_like(_attr(mk["opentag"], "Quantity"), want)
|
||||||
|
elif attr == "Quantity" and cur is not None and not _num_eq(cur, want):
|
||||||
|
# 决策 274 补记九:清单量被修改时,块内清单级工程量算式行(ExpressElement)
|
||||||
|
# 的 Express/Quantity 同步为新量(易达「公式大于数字」:算式行在则按算式行
|
||||||
|
# 显示/计算——不同步则易达按旧量,数据结构层失真)。仅改已存在的纯数字算式行。
|
||||||
|
_m_el = re.search(
|
||||||
|
r'(<SummaryOfBasicCost\b[^>]*?/>\s*<ExpressElement\b[^>]*?)Express="([^"]*)"([^>]*?)Quantity="([^"]*)"([^>]*?/)',
|
||||||
|
txt[mk["s"]:mk["end"]])
|
||||||
|
if _m_el:
|
||||||
|
_wq = _qty_like(_attr(mk["opentag"], "Quantity"), want)
|
||||||
|
if _m_el.group(2) != _wq:
|
||||||
|
_seg_s, _seg_e = mk["s"] + _m_el.start(), mk["s"] + _m_el.end()
|
||||||
|
_rep = (_m_el.group(1) + 'Express="' + _wq + '"' + _m_el.group(3)
|
||||||
|
+ 'Quantity="' + _wq + '"' + _m_el.group(5))
|
||||||
|
edits.append((_seg_s, _seg_e, _rep))
|
||||||
elif attr in ("Price", "Total"):
|
elif attr in ("Price", "Total"):
|
||||||
# 决策 244 补六(2026-11-01 主人定):清单单价/合价统一 2 位小数导出
|
# 决策 244 补六(2026-11-01 主人定):清单单价/合价统一 2 位小数导出
|
||||||
# (数值未变的行不重写,原件格式保持)
|
# (数值未变的行不重写,原件格式保持)
|
||||||
@@ -850,8 +902,25 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
|||||||
# WorkContent 之后(工料机汇总平铺表之前)。此前裸 Norm 插在块尾
|
# WorkContent 之后(工料机汇总平铺表之前)。此前裸 Norm 插在块尾
|
||||||
# (汇总表和单价计算节点之后),广联达按 schema 解析错位 →
|
# (汇总表和单价计算节点之后),广联达按 schema 解析错位 →
|
||||||
# 采纳定额的工料机外溢到定额层(屏西五路 040301004001 实测)。
|
# 采纳定额的工料机外溢到定额层(屏西五路 040301004001 实测)。
|
||||||
body = "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"], form_bank=form_bank)
|
# 决策 279:有块的采纳定额 → 块进块出(原样吐块,工程量/合价清空);
|
||||||
for nn in napp)
|
# 无块 → 旧模板克隆路径。块内消耗码已在采纳拷块时按 108 改写。
|
||||||
|
def _norm_out(nn):
|
||||||
|
print("DBG _norm_out q=%s blk=%d" % (nn.get("Quantity"), len((nn.get("_block_xml") or ""))), flush=True)
|
||||||
|
_nb = (nn.get("_block_xml") or "").strip()
|
||||||
|
if _nb:
|
||||||
|
# 量=公式求值/库值、合价=量×价(显示什么导出什么;276 口径)
|
||||||
|
_q = _fmt_qty(nn.get("Quantity"), 6) if nn.get("Quantity") is not None else ""
|
||||||
|
_nb = re.sub(r'(<Norm' + chr(92) + 'b[^>]*?)' + chr(92) + 'sQuantity="[^"]*"',
|
||||||
|
lambda mo: mo.group(1) + ' Quantity="%s"' % _q, _nb, count=1)
|
||||||
|
try:
|
||||||
|
_tt = _ru(float(nn.get("Quantity") or 0) * float(nn.get("Price") or 0), 2)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
_tt = ""
|
||||||
|
_nb = re.sub(r'(<Norm' + chr(92) + 'b[^>]*?)' + chr(92) + 'sTotal="[^"]*"',
|
||||||
|
lambda mo: mo.group(1) + ' Total="%s"' % _tt, _nb, count=1)
|
||||||
|
return _nb
|
||||||
|
return _norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"], form_bank=form_bank)
|
||||||
|
body = "".join(_norm_out(nn) for nn in napp)
|
||||||
if has_wc and wc_close != -1:
|
if has_wc and wc_close != -1:
|
||||||
ins = wc_close + len("</WorkContent>")
|
ins = wc_close + len("</WorkContent>")
|
||||||
# 决策 99:原生 WorkContent 恒带 Name/Total/Remark 三属性(清单名/清单合价 2 位/空)
|
# 决策 99:原生 WorkContent 恒带 Name/Total/Remark 三属性(清单名/清单合价 2 位/空)
|
||||||
@@ -980,10 +1049,41 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
|||||||
break
|
break
|
||||||
if nn_tmpl is None:
|
if nn_tmpl is None:
|
||||||
nn_tmpl = norm_tmpl
|
nn_tmpl = norm_tmpl
|
||||||
norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl, form_bank=form_bank,
|
# 决策 279:清单壳块在库 → 块进块出(原样吐块)。
|
||||||
bill_qty=b["Quantity"])
|
# 定额块按库序整组替换进壳块(9.1/9.3 拷入的 Norm 原文,含 IncFees/调整记录成对层;
|
||||||
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
|
# 消耗码已在采纳拷块时按 108 code_map 改写,导出端零映射)。
|
||||||
parts.append(_bill_xml(b, tgt["tag"], norms_xml, tmpl_blk or tgt["opentag"], txt=txt))
|
# 工程量/合价清空(采纳清单量=0+GCL公式,块里是来源件旧值;276 口径同源)。
|
||||||
|
_shell = b.get("_block_xml")
|
||||||
|
if _shell:
|
||||||
|
_norm_blks = []
|
||||||
|
for nn in norms_by_bill.get(b["id"], {}).get("append") or []:
|
||||||
|
_nb = (nn.get("_block_xml") or "").strip()
|
||||||
|
_q = _fmt_qty(nn.get("Quantity"), 6) if nn.get("Quantity") is not None else ""
|
||||||
|
_nb = re.sub(r'(<Norm' + chr(92) + 'b[^>]*?)' + chr(92) + 'sQuantity="[^"]*"',
|
||||||
|
lambda mo: mo.group(1) + ' Quantity="%s"' % _q, _nb, count=1)
|
||||||
|
try:
|
||||||
|
_tt = _ru(float(nn.get("Quantity") or 0) * float(nn.get("Price") or 0), 2)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
_tt = ""
|
||||||
|
_nb = re.sub(r'(<Norm' + chr(92) + 'b[^>]*?)' + chr(92) + 'sTotal="[^"]*"',
|
||||||
|
lambda mo: mo.group(1) + ' Total="%s"' % _tt, _nb, count=1)
|
||||||
|
_norm_blks.append(_nb)
|
||||||
|
if _norm_blks:
|
||||||
|
# 壳块内的定额段整组替换:壳块原文里从第一个 <Norm 到最后一个 </Norm> 换成库序块
|
||||||
|
_s1 = _shell.find('<Norm')
|
||||||
|
_e1 = _shell.rfind('</Norm>') + len('</Norm>')
|
||||||
|
if 0 <= _s1 < _e1:
|
||||||
|
_shell = _shell[:_s1] + "".join(_norm_blks) + _shell[_e1:]
|
||||||
|
_shell = re.sub(r'(<WorkElement' + chr(92) + 'b[^>]*?)' + chr(92) + 'sQuantity="[^"]*"',
|
||||||
|
r'\1 Quantity=""', _shell, count=1)
|
||||||
|
_shell = re.sub(r'(<WorkElement' + chr(92) + 'b[^>]*?)' + chr(92) + 'sTotal="[^"]*"',
|
||||||
|
r'\1 Total=""', _shell, count=1)
|
||||||
|
parts.append(_shell)
|
||||||
|
else:
|
||||||
|
norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl, form_bank=form_bank,
|
||||||
|
bill_qty=b["Quantity"])
|
||||||
|
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
|
||||||
|
parts.append(_bill_xml(b, tgt["tag"], norms_xml, tmpl_blk or tgt["opentag"], txt=txt))
|
||||||
edits.append((pos, pos, "".join(parts)))
|
edits.append((pos, pos, "".join(parts)))
|
||||||
# 专修(2026-10-28,三溪采纳语境实测):删除块与「闭合前插入」相交时,删除按原跨度
|
# 专修(2026-10-28,三溪采纳语境实测):删除块与「闭合前插入」相交时,删除按原跨度
|
||||||
# 会咬掉已插入的采纳定额(定额丢失+孤儿闭标签=碎 XML)——删除终点收到插入点。
|
# 会咬掉已插入的采纳定额(定额丢失+孤儿闭标签=碎 XML)——删除终点收到插入点。
|
||||||
|
|||||||
@@ -1,954 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""手工工程导出(决策 231,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
|
||||||
|
|
||||||
口径(主人逐条拍板):
|
|
||||||
· 骨架只在导出时用;内部数据只管采纳。单位工程→清单的计价信息按采纳数值,
|
|
||||||
可计算的(清单合价、分部/容器合计)现算;**其他一切按骨架**(建设单位/编制人/
|
|
||||||
取费程序/费用汇总等工程级信息=代表件保留值,铁律 5 本通道调整);
|
|
||||||
· 我方清单下的定额/工料机=**克隆架子清值**:从骨架件挑最全样板清单整块克隆
|
|
||||||
(费用构成汇总+定额/工料机架子全保留——决策 106:易达按 SummaryOfBasicCost
|
|
||||||
认清单),量价结果与含量式全清、结构属性原样,易达/广联达打开按结构重算;
|
|
||||||
· 分部层级=我方 s_divides 树递归映射原生 DivisionalWorks 嵌套(原生实测:子分部
|
|
||||||
就是 DivisionalWorks 里嵌 DivisionalWorks,南屏 cos 实嵌 3 层;分部 Number 原生
|
|
||||||
即空串,Name/Total 落我方,Quantity/TechnicalAndEconomicIndex 指标清零不背旧值);
|
|
||||||
· 措施项目一起导:原生直接挂 Preliminaries 下,骨架有 PreliminaryDivisionalWorks
|
|
||||||
包装层就克隆一层包装;
|
|
||||||
· 工料机汇总节点:架子在、行不进(我方无工料机数据,别人的行不混入,决策 199 同源);
|
|
||||||
· Project.xml 只改名字:工程名/单项名/单位名落我方;**UnitWorks 引用节点的 Number
|
|
||||||
不动**(它关联成员文件名,动了断链,原生件名 @_001-1_… 实测);其余=保留值;
|
|
||||||
· 多后缀:cos/cos4 各取各的代表件,画像天然正确;SWT/SWZ 等后期注册。
|
|
||||||
实现:整件字节外科手术,复用 export_cos 的样板挑选/属性改写/结果值清零引擎
|
|
||||||
(决策 106/198/204 同款),不碰会话采纳与合并工料机内部逻辑(主人定:内部零改动)。
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
import classic_skeleton
|
|
||||||
import export_cos as ec
|
|
||||||
import dyn_lme
|
|
||||||
from formats.skeleton import build_plan, num as _num
|
|
||||||
|
|
||||||
_LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
_ITEM_CONT = "DivisionalAndElementalWorks" # 分部分项容器(cos 族两代同名)
|
|
||||||
_PRE_CONT = "Preliminaries" # 措施项目容器
|
|
||||||
_DW = "DivisionalWorks" # 分部(嵌套=子分部,原生实测)
|
|
||||||
_DW_PRE = "PreliminaryDivisionalWorks" # 措施分部包装层(有则克隆,无则不造)
|
|
||||||
_ITEM_BILL = "WorkElement"
|
|
||||||
_PRE_BILL = "UnitWorksPreliminaryWorkElement"
|
|
||||||
_SEC_TAGS = ("SectionalWorks", "DivisionalAndElementalProject") # 单项工程层(cos/cos4 各叫其一)
|
|
||||||
_ROOT_TAGS = ("ConstructionProject", "ConstructProject")
|
|
||||||
_MAX_DEPTH = 8 # 分部递归保险(我方上限 4 级,决策 230)
|
|
||||||
|
|
||||||
|
|
||||||
def _money(v):
|
|
||||||
if v is None:
|
|
||||||
return "0"
|
|
||||||
try:
|
|
||||||
return "%.2f" % round(float(v), 2)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return "0"
|
|
||||||
|
|
||||||
|
|
||||||
def _span(txt, tag, start=0):
|
|
||||||
"""首个 <tag …>…</tag> 的 (s,e)(e 含闭标签);自闭合返回 (s, 开标签止);
|
|
||||||
属性值里的 '>' 用 _open_tag_end 越过;同名嵌套按深度配对。找不到 → None。"""
|
|
||||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
|
||||||
if not m:
|
|
||||||
return None
|
|
||||||
s = m.start()
|
|
||||||
oe = ec._open_tag_end(txt, s)
|
|
||||||
if oe < 0:
|
|
||||||
return None
|
|
||||||
if txt[oe - 2:oe] == "/>":
|
|
||||||
return (s, oe)
|
|
||||||
depth, pos = 1, oe
|
|
||||||
while depth:
|
|
||||||
mn = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(txt, pos)
|
|
||||||
if not mn:
|
|
||||||
return None
|
|
||||||
if mn.group(0)[1] == "/":
|
|
||||||
depth -= 1
|
|
||||||
if depth == 0:
|
|
||||||
return (s, mn.end())
|
|
||||||
pos = mn.end()
|
|
||||||
continue
|
|
||||||
o2 = ec._open_tag_end(txt, mn.start())
|
|
||||||
if o2 < 0:
|
|
||||||
return None
|
|
||||||
if txt[o2 - 2:o2] == "/>":
|
|
||||||
pos = o2 # 自闭合同名子行=完整元素,不进深度(2026-10-28 修:
|
|
||||||
continue # 合成件 Summary 子行把深度顶穿→容器配对 None→只删开标签留孤儿闭合)
|
|
||||||
depth += 1
|
|
||||||
pos = o2
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _opentag(txt, tag, start=0):
|
|
||||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
|
||||||
if not m:
|
|
||||||
return None
|
|
||||||
e = ec._open_tag_end(txt, m.start())
|
|
||||||
return txt[m.start():e] if e > 0 else None
|
|
||||||
|
|
||||||
|
|
||||||
def _block_tag(blk):
|
|
||||||
m = re.match(r"<(\w+)", blk or "")
|
|
||||||
return m.group(1) if m else _ITEM_BILL
|
|
||||||
|
|
||||||
|
|
||||||
def _bill_block(sample_blk, b, norm_tmpl, express_by_norm, txt):
|
|
||||||
"""我方一条清单 → 整块(决策 231①+补记,主人定「和标准采纳一样」):
|
|
||||||
· 有采纳定额 → 走 export_cos 同款引擎挂**真实定额**(_norm_xml:费用构成/单价计算
|
|
||||||
innards 克隆、消耗量行重写、清单级工料机尾表按消耗量现算,决策 98/106);
|
|
||||||
· 没采纳 → **克隆架子清值**(231①,主人 2026-10-28 复确认):cos 清单架子导出、
|
|
||||||
值全清=「还没组价」的形态。
|
|
||||||
工程量按数据本体精度回写(_bill_xml 内部按单件 3 位规律写会截 6 位量,三溪实测)。"""
|
|
||||||
ns = [n for n in (b.get("norms") or []) if not n.get("x_tdel")]
|
|
||||||
# 补记十五(2026-10-28 主人定「分部/清单/定额/工料机全部按自己的值,不能采用骨架值
|
|
||||||
# 兜底」——推翻 231①/补记二的「未采纳=克隆架子清值」):没定额=我方五值+**无定额**
|
|
||||||
# 清单(采纳过源本无定额与未采纳同形态),不套骨架样例定额;骨架只出结构不出值
|
|
||||||
if not ns:
|
|
||||||
return ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), [],
|
|
||||||
template=sample_blk or None, txt=txt)
|
|
||||||
norms_xml = []
|
|
||||||
for n in ns:
|
|
||||||
lres = (express_by_norm or {}).get(n["id"]) or n.get("res") or []
|
|
||||||
norms_xml.append(ec._norm_xml(n, lres, template=norm_tmpl,
|
|
||||||
bill_qty=b.get("Quantity")))
|
|
||||||
t = ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), norms_xml,
|
|
||||||
template=sample_blk or None, txt=txt)
|
|
||||||
oe = ec._open_tag_end(t, 0)
|
|
||||||
if oe > 0:
|
|
||||||
ot = t[:oe]
|
|
||||||
if b.get("Quantity") is not None:
|
|
||||||
ot = ec._attr_set(ot, "Quantity", _num(b.get("Quantity")))
|
|
||||||
if not b.get("Number") and ' Number="' in ot:
|
|
||||||
ot = ec._attr_set(ot, "Number", "") # 编码空=空("0" 是数值占位口径)
|
|
||||||
t = ot + t[oe:]
|
|
||||||
return t
|
|
||||||
|
|
||||||
|
|
||||||
_LME_FILL_ROOTS = ("UnitWorks", "ConstructionProject", "ConstructProject",
|
|
||||||
"ProjectInstallationWorkCost")
|
|
||||||
|
|
||||||
|
|
||||||
def _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=None, lib=None):
|
|
||||||
"""现算行 → 行列 HTML(决策 231 补记五,主人拍板「按现有数据生成」):
|
|
||||||
行模板照骨架本件形态(198 槽不造);台班/配合比码带子级组成(s_lme_res)
|
|
||||||
→ 行转容器+子行;量 0 不导(199)。"""
|
|
||||||
out = []
|
|
||||||
dyn_codes = {str(r[0]) for r in rows9 or []}
|
|
||||||
# 组成子码全单位总额(2026-10-28 主人实测易达映射源组成子行编制价全空后的补行依据;
|
|
||||||
# 原生件铁证:折旧费等组成码在单位表**各有一行自己的价**,量=Σ(母现算量×构成值)——
|
|
||||||
# 构成值就是台班单价的组成(折旧3.44+检修0.80+…=台班价14.10),量×价1.00=总价)
|
|
||||||
comp_tot = {}
|
|
||||||
for r in rows9 or []:
|
|
||||||
for c, q in (children or {}).get(str(r[0])) or []:
|
|
||||||
try:
|
|
||||||
comp_tot[c] = comp_tot.get(c, 0.0) + float(q or 0) * float(r[5] or 0)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
comp_done = set()
|
|
||||||
# 决策 259(2026-11-02 主人定「骨架不能创造数据」):行 16 列(前 11 列同旧)尾部=
|
|
||||||
# 六价扩展四值 + x_flags(文字/标志属性 JSON)。导出三原则:
|
|
||||||
# ①数值属性一律灌项目真值(org=库基准价、四 Total=现算量×对应价);②来源没有的
|
|
||||||
# 属性整个删掉(不灌空、不造值);③文字/标志属性按 flags 有无灌/删。
|
|
||||||
_DATA_ATTRS = ("NoTaxOrgPrice", "NoTaxPriceExpress", "TaxOrgPrice", "TaxPriceExpress",
|
|
||||||
"NoTaxOrgTotal", "NoTaxTotal", "TaxOrgTotal", "TaxTotal",
|
|
||||||
"PriceSource", "Remark")
|
|
||||||
_FLAG_ATTRS = ("LossRate", "Class", "Concrete", "ExtKind", "AddiKind", "MainMaterial",
|
|
||||||
"ProvisionalMaterial", "Provider", "Delivery", "Location",
|
|
||||||
"ProducingArea", "Supplier", "Character")
|
|
||||||
for r in rows9 or []:
|
|
||||||
code, name, spec, unit, kind, qty, ntp, taxrate, taxp = r[:9]
|
|
||||||
try:
|
|
||||||
if float(qty or 0) == 0:
|
|
||||||
continue
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
org4 = (tuple(r[9:13]) + (None,) * 4)[:4] if len(r) >= 14 else (None,) * 4 # 决策 259:导出序 14 列(9+4+flags)
|
|
||||||
flags = r[13] if len(r) > 13 else None
|
|
||||||
t = ec._lme_row(row_tmpl, code, _num(qty))
|
|
||||||
if t.endswith("/>"): # 模板恒自闭合 → 先转开标签再灌/删属性
|
|
||||||
t = t[:-2] + ">" # (_attr_set 对自闭合行新增属性会挤掉 /> 产生残缺标签)
|
|
||||||
t = ec._attr_set_has(t, "Name", name or "")
|
|
||||||
t = ec._attr_set_has(t, "Specification", spec or "")
|
|
||||||
t = ec._attr_set_has(t, "Unit", unit or "")
|
|
||||||
if kind:
|
|
||||||
t = ec._attr_set_has(t, "Kind", str(int(kind)))
|
|
||||||
for k, v in (("Quantity", _num(qty)), ("NoTaxPrice", _money(ntp)),
|
|
||||||
("TaxRate", _money(taxrate)), ("TaxPrice", _money(taxp))):
|
|
||||||
t = ec._attr_set_has(t, k, v)
|
|
||||||
# ①先删全部数据/标志属性(清模板残留),②有来源的再灌真值——「原文件有才导」
|
|
||||||
# (flags=None=存量未采集=视为原文件没有 → 标志属性同样删,重导恢复)
|
|
||||||
for k in _DATA_ATTRS + _FLAG_ATTRS:
|
|
||||||
t = ec._attr_del(t, k)
|
|
||||||
_ntp_org, _ntp_expr, _taxp_org, _taxp_expr = org4
|
|
||||||
_fx = {}
|
|
||||||
if flags:
|
|
||||||
try:
|
|
||||||
_fx = json.loads(flags)
|
|
||||||
except Exception:
|
|
||||||
_fx = {}
|
|
||||||
if _ntp_org is not None:
|
|
||||||
t = ec._attr_set(t, "NoTaxOrgPrice", _money(_ntp_org))
|
|
||||||
t = ec._attr_set(t, "NoTaxOrgTotal", _money(float(qty) * float(_ntp_org)))
|
|
||||||
if _taxp_org is not None:
|
|
||||||
t = ec._attr_set(t, "TaxOrgPrice", _money(_taxp_org))
|
|
||||||
t = ec._attr_set(t, "TaxOrgTotal", _money(float(qty) * float(_taxp_org)))
|
|
||||||
if _ntp_expr is not None:
|
|
||||||
t = ec._attr_set(t, "NoTaxPriceExpress", str(_ntp_expr))
|
|
||||||
if _taxp_expr is not None:
|
|
||||||
t = ec._attr_set(t, "TaxPriceExpress", str(_taxp_expr))
|
|
||||||
t = ec._attr_set(t, "NoTaxTotal", _money(float(qty) * float(ntp or 0))) # 现价链永有→Total 永灌
|
|
||||||
t = ec._attr_set(t, "TaxTotal", _money(float(qty) * float(taxp or 0)))
|
|
||||||
for k, v in _fx.items(): # 文字/标志:原文件有才灌
|
|
||||||
t = ec._attr_set(t, k, v)
|
|
||||||
kids = (children or {}).get(str(code))
|
|
||||||
if kids and child_tmpl:
|
|
||||||
# 原生排版(两骨架实测):母行开标签→换行缩进→子行逐行同缩进→闭合标签前换行缩进
|
|
||||||
ci = (ind or {}).get("ci") or "\n "
|
|
||||||
cc = (ind or {}).get("cc") or "\n "
|
|
||||||
inner = ci + ci.join(ec._child_node(child_tmpl, c, q) for c, q in kids)
|
|
||||||
t = t + inner + cc + "</%s>" % _LME_SUM
|
|
||||||
else:
|
|
||||||
t = t[:-1] + "/>" # 无子级(或无子行模板)=直接走自闭合(2026-11-02 主人定)
|
|
||||||
out.append(t)
|
|
||||||
# 组成子码自有行(价格源行):紧跟首个引用它的母容器行(首现序),每码只补一行;
|
|
||||||
# 已有现算行的码不补(直耗行已带价);名称/规格/单位/类别/单价取 s_lme_lib 快照
|
|
||||||
for c, _q in (kids or ()):
|
|
||||||
if c in dyn_codes or c in comp_done:
|
|
||||||
continue
|
|
||||||
lb = (lib or {}).get(c)
|
|
||||||
if not lb or not comp_tot.get(c):
|
|
||||||
continue
|
|
||||||
nm2, sp2, un2, kd2, ntp2, taxp2 = lb
|
|
||||||
|
|
||||||
t2 = ec._lme_row(row_tmpl, c, _num(comp_tot[c]))
|
|
||||||
t2 = ec._attr_set_has(t2, "Name", nm2 or "")
|
|
||||||
t2 = ec._attr_set_has(t2, "Specification", sp2 or "")
|
|
||||||
t2 = ec._attr_set_has(t2, "Unit", un2 or "")
|
|
||||||
if kd2:
|
|
||||||
try:
|
|
||||||
t2 = ec._attr_set_has(t2, "Kind", str(int(kd2)))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
t2 = ec._attr_set_has(t2, "NoTaxPrice", _money(ntp2))
|
|
||||||
t2 = ec._attr_set_has(t2, "TaxPrice", _money(taxp2))
|
|
||||||
t2 = ec._attr_set_has(t2, "TaxRate", _money(0))
|
|
||||||
out.append(t2)
|
|
||||||
comp_done.add(c)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _lme_fill(txt, rows9=None, children=None, row_tmpl=None, child_tmpl=None, ind=None,
|
|
||||||
lib=None):
|
|
||||||
"""根层工料机汇总行(决策 231 补记五推翻补记三的「清空」定论——易达标准骨架铁证:
|
|
||||||
单位成员根层直挂的 LME_SUM=**单位级汇总表**(每码一行、台班带子级嵌套);项目成员
|
|
||||||
PIWC 内同款=项目级汇总表。骨架行/子行照本件形态克隆,灌**现算行**(主人拍板:
|
|
||||||
定额工程量×消耗量,dyn 引擎)+台班子级组成;无现算行 → 清空(架子在、别人的行不进);
|
|
||||||
行/子行模板缺位时本件全局取(调用方传入)。"""
|
|
||||||
if not row_tmpl:
|
|
||||||
return _lme_clear(txt)
|
|
||||||
sep = ec._native_sep(txt, _LME_SUM, "") or (ind or {}).get("sep") or "\n"
|
|
||||||
keep = _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=ind, lib=lib)
|
|
||||||
spans, stack, pos, n = [], [], 0, len(txt)
|
|
||||||
while pos < n:
|
|
||||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
|
||||||
if not m:
|
|
||||||
break
|
|
||||||
if m.group(1) == "/":
|
|
||||||
t = m.group(2)
|
|
||||||
for i in range(len(stack) - 1, -1, -1):
|
|
||||||
if stack[i] == t:
|
|
||||||
del stack[i:]
|
|
||||||
break
|
|
||||||
pos = m.end()
|
|
||||||
continue
|
|
||||||
tag = m.group(2)
|
|
||||||
oe = ec._open_tag_end(txt, m.start())
|
|
||||||
if oe < 0:
|
|
||||||
break
|
|
||||||
if txt[oe - 2:oe] == "/>":
|
|
||||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
|
||||||
spans.append((m.start(), oe))
|
|
||||||
pos = oe
|
|
||||||
continue
|
|
||||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
|
||||||
sp = _span(txt, _LME_SUM, m.start())
|
|
||||||
spans.append((m.start(), sp[1] if sp else oe))
|
|
||||||
pos = sp[1] if sp else oe
|
|
||||||
continue
|
|
||||||
stack.append(tag)
|
|
||||||
pos = oe
|
|
||||||
if not spans:
|
|
||||||
# 空槽成员没有旧行=没有锚(2026-10-28 实测:易达骨架 31 位仅 3 位有汇总行,其余
|
|
||||||
# 单位整表不插)。按原生「表在根尾」位补插(UnitWorksSummary 之后、根闭标签之前,
|
|
||||||
# 两骨架有行成员同款)。首行不补分隔——插入点前已有原生换行。
|
|
||||||
if not keep:
|
|
||||||
return txt
|
|
||||||
m = re.search(r"</([A-Za-z_][\w.]*)>\s*$", txt)
|
|
||||||
anchor = m.start() if m else len(txt)
|
|
||||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
|
||||||
return txt[:anchor] + body + txt[anchor:]
|
|
||||||
anchor = spans[0][0]
|
|
||||||
for s, e in reversed(spans): # 从后往前删,锚点偏移不失效
|
|
||||||
txt = txt[:s] + txt[e:]
|
|
||||||
if not keep:
|
|
||||||
return txt
|
|
||||||
# 首行不补分隔:锚点前保留着原首行的换行+缩进(删行只删 < 起),避免双分隔出空行
|
|
||||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
|
||||||
return txt[:anchor] + body + txt[anchor:]
|
|
||||||
|
|
||||||
|
|
||||||
def _lme_clear(txt):
|
|
||||||
"""无行模板(骨架件无样行)时退回清空——架子在、行不进。"""
|
|
||||||
spans, stack, pos, n = [], [], 0, len(txt)
|
|
||||||
while pos < n:
|
|
||||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
|
||||||
if not m:
|
|
||||||
break
|
|
||||||
if m.group(1) == "/":
|
|
||||||
t = m.group(2)
|
|
||||||
for i in range(len(stack) - 1, -1, -1):
|
|
||||||
if stack[i] == t:
|
|
||||||
del stack[i:]
|
|
||||||
break
|
|
||||||
pos = m.end()
|
|
||||||
continue
|
|
||||||
tag = m.group(2)
|
|
||||||
oe = ec._open_tag_end(txt, m.start())
|
|
||||||
if oe < 0:
|
|
||||||
break
|
|
||||||
if txt[oe - 2:oe] == "/>":
|
|
||||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
|
||||||
spans.append((m.start(), oe))
|
|
||||||
pos = oe
|
|
||||||
continue
|
|
||||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
|
||||||
sp = _span(txt, _LME_SUM, m.start())
|
|
||||||
spans.append((m.start(), sp[1] if sp else oe))
|
|
||||||
pos = sp[1] if sp else oe
|
|
||||||
continue
|
|
||||||
stack.append(tag)
|
|
||||||
pos = oe
|
|
||||||
for s, e in reversed(spans):
|
|
||||||
txt = txt[:s] + txt[e:]
|
|
||||||
return txt
|
|
||||||
|
|
||||||
|
|
||||||
def _dw_template(txt):
|
|
||||||
"""骨架件本单位里第一个分部完整块 → {ot 开标签, prefix 前缀(分部自己的费用构成等)}。
|
|
||||||
决策 106:费用构成子块是易达认块的关键——克隆时带上(值清零)。
|
|
||||||
前缀按顶层整元素吸收(_top_scan),费用构成是带子级容器时不会切半。"""
|
|
||||||
sp = _span(txt, _DW)
|
|
||||||
if not sp:
|
|
||||||
return None
|
|
||||||
blk = txt[sp[0]:sp[1]]
|
|
||||||
oe = ec._open_tag_end(blk, 0)
|
|
||||||
close = "</%s>" % _DW
|
|
||||||
inner = blk[oe:-len(close)] if blk.endswith(close) else blk[oe:]
|
|
||||||
prefix, _ = _top_scan(inner, (_DW, _ITEM_BILL))
|
|
||||||
return {"ot": blk[:oe], "prefix": prefix}
|
|
||||||
|
|
||||||
|
|
||||||
def _divtree(plan, uw_id):
|
|
||||||
"""我方 item 分部树:(roots, kids)——按 x_seq 排序(与界面同序),parent 不在集内=根。"""
|
|
||||||
ds = [d for d in plan["divides"].values()
|
|
||||||
if d["uw_id"] == uw_id and d["kind"] == "item"]
|
|
||||||
ds.sort(key=lambda d: (d.get("x_seq") is None,
|
|
||||||
d.get("x_seq") if d.get("x_seq") is not None else 0, d["id"]))
|
|
||||||
ids = {d["id"] for d in ds}
|
|
||||||
kids, roots = {}, []
|
|
||||||
for d in ds:
|
|
||||||
p = d["parent_id"]
|
|
||||||
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
|
|
||||||
return roots, kids
|
|
||||||
|
|
||||||
|
|
||||||
def _sum_bills(bills):
|
|
||||||
n = 0.0
|
|
||||||
for b in bills or []:
|
|
||||||
try:
|
|
||||||
n += float(b.get("Total") or 0)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
return n
|
|
||||||
|
|
||||||
|
|
||||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, norm_tmpl=None,
|
|
||||||
express_by_norm=None, txt="", depth=0):
|
|
||||||
"""一个分部节点:开标签克隆(Name/Total 落我方,指标清零)+费用构成前缀(清零)
|
|
||||||
+子分部/清单递归。Total=本级+全部子孙清单合计(现算,主人定可计算按采纳)。
|
|
||||||
我方上限 4 级(决策 230),递归保险 8 级。返回 (块文本, 合计)。"""
|
|
||||||
ot = ec._clone_open_tag(tmpl["ot"]) if tmpl else '<%s Name="x">' % _DW
|
|
||||||
ot = ec._attr_set_has(ot, "Name", d.get("name") or "")
|
|
||||||
for k in ("Quantity", "TechnicalAndEconomicIndex"): # 别人的指标不背
|
|
||||||
ot = ec._attr_set_has(ot, k, "0")
|
|
||||||
parts = []
|
|
||||||
total = _sum_bills(bills_by_div.get(d["id"], []))
|
|
||||||
if depth <= _MAX_DEPTH:
|
|
||||||
for sub in kids.get(d["id"], []):
|
|
||||||
blk, sub_total = _div_block(tmpl, sub, kids, bills_by_div, sample, sep,
|
|
||||||
norm_tmpl, express_by_norm, txt, depth + 1)
|
|
||||||
parts.append(blk)
|
|
||||||
total += sub_total
|
|
||||||
ot = ec._attr_set_has(ot, "Total", _money(total))
|
|
||||||
bills = [_bill_block(sample, b, norm_tmpl, express_by_norm, txt)
|
|
||||||
for b in bills_by_div.get(d["id"], [])]
|
|
||||||
prefix = ec._zero_results(tmpl["prefix"]) if tmpl else ""
|
|
||||||
return ot + prefix + sep.join(parts + bills) + "</%s>" % _DW, total
|
|
||||||
|
|
||||||
|
|
||||||
def _replace_span(txt, sp, new):
|
|
||||||
return txt[:sp[0]] + new + txt[sp[1]:]
|
|
||||||
|
|
||||||
|
|
||||||
def _top_scan(inner, stop_tags):
|
|
||||||
"""容器内顶层扫描:返回 (前缀, 命中位)。前缀=首个 stop 顶层元素之前的**完整**
|
|
||||||
顶层元素(费用构成块等,可能带子级——按标签裸切会切在容器中间造成 XML 错配)。"""
|
|
||||||
stop = set(stop_tags)
|
|
||||||
pos, n = 0, len(inner)
|
|
||||||
while pos < n:
|
|
||||||
m = re.compile(r"<([A-Za-z_][\w.]*)").search(inner, pos)
|
|
||||||
if not m:
|
|
||||||
return inner, n
|
|
||||||
tag = m.group(1)
|
|
||||||
if tag in stop:
|
|
||||||
return inner[:m.start()], m.start()
|
|
||||||
oe = ec._open_tag_end(inner, m.start())
|
|
||||||
if oe < 0:
|
|
||||||
return inner, n
|
|
||||||
if inner[oe - 2:oe] == "/>":
|
|
||||||
pos = oe
|
|
||||||
continue
|
|
||||||
depth, p = 1, oe
|
|
||||||
while depth:
|
|
||||||
m2 = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(inner, p)
|
|
||||||
if not m2:
|
|
||||||
return inner, n
|
|
||||||
depth += -1 if m2.group(0)[1] == "/" else 1
|
|
||||||
p = m2.end()
|
|
||||||
if depth == 0:
|
|
||||||
break
|
|
||||||
pos = p
|
|
||||||
return inner, n
|
|
||||||
|
|
||||||
|
|
||||||
def _render_unit(txt, u, plan, sc=None, sid=0, express_by_norm=None,
|
|
||||||
lme_ctx=None):
|
|
||||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总按现算挂真实行
|
|
||||||
(无采纳=空槽);单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
|
||||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"
|
|
||||||
and not b.get("x_tdel")]
|
|
||||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"
|
|
||||||
and not b.get("x_tdel")]
|
|
||||||
item_sample = ec._largest_bill_block(txt, tag=_ITEM_BILL, prelim=False) \
|
|
||||||
or _fallback_blk(txt, False) or (lme_ctx or {}).get("g_item")
|
|
||||||
pre_sample = ec._largest_bill_block(txt, prelim=True) \
|
|
||||||
or (lme_ctx or {}).get("g_pre") or item_sample
|
|
||||||
norm_tmpl_item = (ec._full_norm_block(item_sample) if item_sample else None) \
|
|
||||||
or (lme_ctx or {}).get("g_norm_item")
|
|
||||||
norm_tmpl_pre = (ec._full_norm_block(pre_sample) if pre_sample else None) \
|
|
||||||
or (lme_ctx or {}).get("g_norm_pre") or norm_tmpl_item
|
|
||||||
sep = ec._native_sep(txt, _ITEM_BILL, "") \
|
|
||||||
or (lme_ctx or {}).get("g_sep") or "\r\n"
|
|
||||||
sep_d = ec._native_sep(txt, _DW, sep) or (lme_ctx or {}).get("g_sep_d") or sep
|
|
||||||
tmpl = _dw_template(txt) or (lme_ctx or {}).get("g_dw")
|
|
||||||
bb = dict(norm_tmpl=norm_tmpl_item, express_by_norm=express_by_norm, txt=txt)
|
|
||||||
|
|
||||||
# ---- 分部分项容器:清仓 → 我方分部树(DivisionalWorks 递归嵌套)+ 容器合计现算 ----
|
|
||||||
sp = _span(txt, _ITEM_CONT)
|
|
||||||
if sp:
|
|
||||||
oe = ec._open_tag_end(txt, sp[0])
|
|
||||||
ot = txt[sp[0]:oe]
|
|
||||||
close = "</%s>" % _ITEM_CONT
|
|
||||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
|
||||||
if u:
|
|
||||||
roots, kids = _divtree(plan, u["id"])
|
|
||||||
bills_by_div = {}
|
|
||||||
for b in bills_item:
|
|
||||||
bills_by_div.setdefault(b.get("div_id"), []).append(b)
|
|
||||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d,
|
|
||||||
norm_tmpl=bb["norm_tmpl"],
|
|
||||||
express_by_norm=express_by_norm, txt=txt)[0]
|
|
||||||
for d in roots]
|
|
||||||
blocks += [_bill_block(item_sample, b, bb["norm_tmpl"],
|
|
||||||
express_by_norm, txt)
|
|
||||||
for b in bills_by_div.get(None, [])]
|
|
||||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_item)))
|
|
||||||
else:
|
|
||||||
blocks = []
|
|
||||||
prefix, _ = _top_scan(inner_old, (_DW, _ITEM_BILL))
|
|
||||||
inner = ec._zero_results(prefix)
|
|
||||||
txt = _replace_span(txt, sp, ot + inner + sep_d.join(blocks) + close)
|
|
||||||
|
|
||||||
# ---- 措施项目容器:清仓 → 我方措施行(有包装层就克隆一层);合计现算 ----
|
|
||||||
sp = _span(txt, _PRE_CONT)
|
|
||||||
if sp:
|
|
||||||
oe = ec._open_tag_end(txt, sp[0])
|
|
||||||
ot = txt[sp[0]:oe]
|
|
||||||
close = "</%s>" % _PRE_CONT
|
|
||||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
|
||||||
if u and bills_pre:
|
|
||||||
ot_wrap = _opentag(inner_old, _DW_PRE)
|
|
||||||
bills = [_bill_block(pre_sample, b, norm_tmpl_pre, express_by_norm, txt)
|
|
||||||
for b in bills_pre]
|
|
||||||
body = (ec._clone_open_tag(ot_wrap) + sep.join(bills) + "</%s>" % _DW_PRE) \
|
|
||||||
if ot_wrap else sep.join(bills)
|
|
||||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_pre)))
|
|
||||||
else:
|
|
||||||
body = ""
|
|
||||||
# 措施分部两种标签都在真实件里出现过:PreliminaryDivisionalWorks(新)与
|
|
||||||
# DivisionalWorks(三溪 .cos 实测)——都要停,包装层连同旧清单整块让位给我方平铺
|
|
||||||
prefix, _ = _top_scan(inner_old, (_DW_PRE, _DW, _PRE_BILL, _ITEM_BILL))
|
|
||||||
inner = ec._zero_results(prefix)
|
|
||||||
txt = _replace_span(txt, sp, ot + inner + body + close)
|
|
||||||
|
|
||||||
# ---- 单位级工料机汇总(补记五:根层 LME_SUM=单位级汇总表,易达标准骨架铁证):
|
|
||||||
# 灌现算行(dyn 引擎,定额工程量×消耗量)+台班子级;没采纳 → 清空(架子在行不进)
|
|
||||||
ctx = lme_ctx or {}
|
|
||||||
rows9 = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) if (sc and u) else None
|
|
||||||
txt = _lme_fill(txt, rows9, ctx.get("children"),
|
|
||||||
ctx.get("row_tmpl"), ctx.get("child_tmpl"),
|
|
||||||
ind={"ci": ctx.get("ci"), "cc": ctx.get("cc"), "sep": ctx.get("sep")},
|
|
||||||
lib=ctx.get("lib"))
|
|
||||||
|
|
||||||
# ---- 单位工程名 + 我方可算合计(分部分项费/措施费;其余保留值)----
|
|
||||||
if u:
|
|
||||||
m = re.compile(r"<UnitWorks\b").search(txt)
|
|
||||||
if m:
|
|
||||||
oe = ec._open_tag_end(txt, m.start())
|
|
||||||
ot = ec._attr_set(txt[m.start():oe], "Name", u.get("name") or "")
|
|
||||||
ot = ec._attr_set_has(ot, "DivisionalAndElementalWorks",
|
|
||||||
_money(_sum_bills(bills_item)))
|
|
||||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
|
||||||
txt = txt[:m.start()] + ot + txt[oe:]
|
|
||||||
sp = _span(txt, "SummaryOfCost")
|
|
||||||
if sp:
|
|
||||||
oe = ec._open_tag_end(txt, sp[0])
|
|
||||||
ot = ec._attr_set_has(txt[sp[0]:oe], "DivisionalAndElementalWorks",
|
|
||||||
_money(_sum_bills(bills_item)))
|
|
||||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
|
||||||
txt = txt[:sp[0]] + ot + txt[oe:]
|
|
||||||
return txt
|
|
||||||
|
|
||||||
|
|
||||||
def _fallback_blk(txt, prelim):
|
|
||||||
"""没有合格样板(无费用构成子块)时的兜底:第一条同区清单块原样当模板。"""
|
|
||||||
for mk in ec._scan_bills(txt):
|
|
||||||
is_pre = (mk["tag"] == _PRE_BILL or ec._in_prelim(txt, mk["s"]))
|
|
||||||
if is_pre == prelim:
|
|
||||||
return txt[mk["s"]:mk["end"]]
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _rename_opentags(txt, tag, names):
|
|
||||||
"""按出现顺序给 tag 开标签改 Name(第 n 个 → names[n],超出不动)。
|
|
||||||
单位/单项引用节点只改 Name——Number 关联成员文件名,动了断链(原生实测)。"""
|
|
||||||
out, pos, i = [], 0, 0
|
|
||||||
while i < len(names):
|
|
||||||
m = re.compile(r"<%s\b" % tag).search(txt, pos)
|
|
||||||
if not m:
|
|
||||||
break
|
|
||||||
e = ec._open_tag_end(txt, m.start())
|
|
||||||
if e < 0:
|
|
||||||
break
|
|
||||||
out.append(txt[pos:m.start()])
|
|
||||||
out.append(ec._attr_set(txt[m.start():e], "Name", names[i] or ""))
|
|
||||||
pos, i = e, i + 1
|
|
||||||
out.append(txt[pos:])
|
|
||||||
return "".join(out)
|
|
||||||
|
|
||||||
|
|
||||||
class _GbkNameZipInfo(ec._RawNameZipInfo):
|
|
||||||
"""克隆补位成员的条目名:骨架原生条目名是 GBK 字节(无旗标)。_RawNameZipInfo 对
|
|
||||||
cp437 编不回的串会退 UTF-8+旗标——那正是乱码教训——新中文名这里改按 GBK 写、同样
|
|
||||||
不打旗标(GBK 也编不了才 UTF-8 兜底)。"""
|
|
||||||
|
|
||||||
def _encodeFilenameFlags(self):
|
|
||||||
try:
|
|
||||||
return self.filename.encode("cp437"), 0
|
|
||||||
except UnicodeEncodeError:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
return self.filename.encode("gbk"), 0
|
|
||||||
except UnicodeEncodeError:
|
|
||||||
return self.filename.encode("utf-8"), 0x800
|
|
||||||
|
|
||||||
|
|
||||||
def _render_project(txt, plan, proj_name, n_ours, n_sections, extra_refs=None):
|
|
||||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。
|
|
||||||
extra_refs=骨架位不够时克隆出来的单位引用行 [(我方单位名, 成员文件名, 引用号)]
|
|
||||||
——克隆最后一条现有引用行,号/名/文件名改新,按原生分隔符顺延(2026-10-28 主人定
|
|
||||||
「骨架单位工程位可自由添加」)。"""
|
|
||||||
decl = re.match(r"^.*?\?>", txt, flags=re.S)
|
|
||||||
base = decl.end() if decl else 0
|
|
||||||
lead = base + (len(txt[base:]) - len(txt[base:].lstrip()))
|
|
||||||
root_m = re.match(r"<([\w.]+)", txt[lead:])
|
|
||||||
if root_m and root_m.group(1) in _ROOT_TAGS:
|
|
||||||
oe = ec._open_tag_end(txt, lead)
|
|
||||||
ot = ec._attr_set_has(txt[:oe], "Name", proj_name or "")
|
|
||||||
txt = ot + txt[oe:]
|
|
||||||
txt = _rename_opentags(txt, "UnitWorks",
|
|
||||||
[u.get("name") or "" for u in plan["units"][:n_ours]])
|
|
||||||
sec_names = [s.get("name") or "" for s in plan["sections"]]
|
|
||||||
for t in _SEC_TAGS:
|
|
||||||
txt = _rename_opentags(txt, t, sec_names)
|
|
||||||
if extra_refs:
|
|
||||||
ms = list(re.finditer(r"<UnitWorks\b[^>]*>", txt))
|
|
||||||
if ms:
|
|
||||||
tmpl_o = ms[-1].group(0)
|
|
||||||
# 自闭合引用行先转开标签形态改属性,改完再转回——_attr_set 对缺属性是尾插,
|
|
||||||
# 会把属性插到自闭合的 / 后面(Total="x"/ FileName="y"> 结构破)
|
|
||||||
self_close = tmpl_o.rstrip().endswith("/>")
|
|
||||||
if self_close:
|
|
||||||
tmpl_o = tmpl_o.rstrip()[:-2] + ">"
|
|
||||||
sep = ec._native_sep(txt, "UnitWorks", "\r\n")
|
|
||||||
add = []
|
|
||||||
for name_k, fname_k, num_k in extra_refs:
|
|
||||||
row = ec._attr_set(ec._attr_set(ec._attr_set(
|
|
||||||
tmpl_o, "Number", str(num_k)), "Name", name_k or ""), "FileName", fname_k)
|
|
||||||
if self_close:
|
|
||||||
row = row[:-1] + "/>"
|
|
||||||
add.append(row)
|
|
||||||
txt = txt[:ms[-1].end()] + "".join(sep + r for r in add) + txt[ms[-1].end():]
|
|
||||||
return txt
|
|
||||||
|
|
||||||
|
|
||||||
def export(sc, hcon, sid, suffix, progress=None, src_path=None):
|
|
||||||
"""经典骨架导出 cos/cos4(补记十二,主人定「骨架管导出,数据归软件」:cos4 全量走
|
|
||||||
骨架——手工+普通工程都算;数据全用软件里的现算/采纳,骨架只管格式与字段。"""
|
|
||||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
|
||||||
if not srow:
|
|
||||||
return None, None, "会话不存在"
|
|
||||||
rep = classic_skeleton.pick_frame(hcon, (suffix or "").lower(), src_path=src_path)
|
|
||||||
if not rep:
|
|
||||||
return None, None, ("该后缀(.%s)还没有经典骨架:请先在后台导入或用工作台"
|
|
||||||
"打开一份 .%s 原件" % (suffix, suffix))
|
|
||||||
plan = build_plan(sc, sid)
|
|
||||||
if plan is None:
|
|
||||||
return None, None, "会话数据读不出来"
|
|
||||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
|
||||||
# 采纳含量算式(s_norm_res.express,决策 106 补记十二:调整式跟着历史项目走)
|
|
||||||
express_by_norm = {}
|
|
||||||
for r in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express
|
|
||||||
FROM s_norm_res nr
|
|
||||||
JOIN s_norms n ON n.id=nr.norm_id
|
|
||||||
JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=?""", (sid,)):
|
|
||||||
express_by_norm.setdefault(r["norm_id"], []).append(
|
|
||||||
(r["res_code"], r["qty"], r["express"] or None))
|
|
||||||
try:
|
|
||||||
raw = _render(rep["blob"], plan, proj_name, progress, sc, sid,
|
|
||||||
express_by_norm, rep["suffix"])
|
|
||||||
except Exception as e:
|
|
||||||
return None, None, "导出失败:%s" % e
|
|
||||||
return raw, ((proj_name or "工程") + "-审核版." + rep["suffix"]), None
|
|
||||||
|
|
||||||
|
|
||||||
def _render(blob, plan, proj_name, progress=None, sc=None, sid=0,
|
|
||||||
express_by_norm=None, suffix=""):
|
|
||||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
|
||||||
members, texts = [], {}
|
|
||||||
for nm in src.namelist():
|
|
||||||
if not nm.lower().endswith(".xml"):
|
|
||||||
continue
|
|
||||||
txt, enc = ec._decode(src.read(nm))
|
|
||||||
members.append(nm)
|
|
||||||
texts[nm] = [txt, enc]
|
|
||||||
# 单位工程成员=剥掉 xml 声明后根元素是 UnitWorks;项目成员=含单项层标签或项目根
|
|
||||||
unit_nms, proj_nms = [], []
|
|
||||||
for nm in members:
|
|
||||||
body = re.sub(r"^.*?\?>", "", texts[nm][0], count=1, flags=re.S).lstrip()
|
|
||||||
if body.startswith("<UnitWorks"):
|
|
||||||
unit_nms.append(nm)
|
|
||||||
elif any(("<%s" % t) in body for t in _SEC_TAGS) or \
|
|
||||||
any(body[:200].find("<%s" % t) >= 0 for t in _ROOT_TAGS):
|
|
||||||
proj_nms.append(nm)
|
|
||||||
if not unit_nms:
|
|
||||||
raise ValueError("骨架件里没找到单位工程数据,请换一份原件再试")
|
|
||||||
# 单位成员处理序=**项目成员引用行的 FileName 序**(主人 2026-10-28 定:单项/单位排序
|
|
||||||
# 按项目目录先有顺序=引用行序,与压缩包内 xml 次序无关)。骨架自己的引用行序常与
|
|
||||||
# zip 成员序不同——按 zip 序灌名会让「引用行名 ↔ 成员名」错位(实测广联达骨架 20/44
|
|
||||||
# 不一致)。引用行没点到/点丢的成员按原 zip 序垫后,一个不漏。
|
|
||||||
if proj_nms:
|
|
||||||
disp_of = {}
|
|
||||||
for i in src.infolist():
|
|
||||||
if not i.filename.lower().endswith(".xml"):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
|
||||||
else i.filename.encode("cp437")
|
|
||||||
disp_of[raw.decode("gbk")] = i.filename
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
continue
|
|
||||||
ref_order = []
|
|
||||||
ref_nums = []
|
|
||||||
for x in re.findall(r"<UnitWorks\b[^>]*>", texts[proj_nms[0]][0]):
|
|
||||||
fn = re.search(r'\bFileName="([^"]*)"', x)
|
|
||||||
nm = re.search(r'\bNumber="([^"]*)"', x)
|
|
||||||
if fn and fn.group(1) in disp_of and disp_of[fn.group(1)] in unit_nms \
|
|
||||||
and disp_of[fn.group(1)] not in ref_order:
|
|
||||||
ref_order.append(disp_of[fn.group(1)])
|
|
||||||
ref_nums.append(nm.group(1) if nm else "")
|
|
||||||
if ref_order:
|
|
||||||
unit_nms = ref_order + [n for n in unit_nms if n not in ref_order]
|
|
||||||
# 决策 260 补记四(2026-11-02 主人定「数据按需自动增加行,按模板序排」):
|
|
||||||
# **我方单位数据(ours)与成员槽(unit_nms)同锚重排**——锚=引用行序(项目目录序)。
|
|
||||||
# 此前 units 序=单项分组+Number 数字自然序(build_plan),与引用行文本序不同的
|
|
||||||
# 源件(华宇路:引用行 3,107,148,146,145,… 非 Number 序)会成员数据错挂引用行。
|
|
||||||
# 关联键=引用行 Number ↔ s_unit_works.Number(解析原样入库)。
|
|
||||||
if ref_order and proj_nms:
|
|
||||||
num_map = {}
|
|
||||||
for _u in plan["units"]:
|
|
||||||
_k = str(_u.get("number") or "")
|
|
||||||
if _k and _k not in num_map:
|
|
||||||
num_map[_k] = _u
|
|
||||||
ours_sorted = [num_map.get(_n) for _n in ref_nums if _n in num_map]
|
|
||||||
ours_sorted += [_u for _u in plan["units"] if _u not in ours_sorted]
|
|
||||||
plan["units"] = ours_sorted
|
|
||||||
ours = plan["units"]
|
|
||||||
# 行/子行模板全局取(专用骨架的空单位位没有样行——借其他成员的形态,补记五):
|
|
||||||
# 行模板=任一自闭合 LME_SUM 行;子行=任一「容器行内嵌的原生 …Element 子行」+原生
|
|
||||||
# 换行缩进(广联达/易达两骨架实测同款:子行一律 Element 形态、只 Number/Express/
|
|
||||||
# Quantity/Remark;2026-10-28 修:旧正则 [^>]*> 会吃掉自闭合的 /,把相邻两条平铺行
|
|
||||||
# 误当「母行+子行」——子行模板成了别人的母行,Name/单价/金额残留全从这来)
|
|
||||||
row_tmpl = child_tmpl = None
|
|
||||||
ci_ind = cc_ind = None
|
|
||||||
g_lme_sep = None
|
|
||||||
pat_row = re.compile(r"<%s\b[^>]*/>" % _LME_SUM)
|
|
||||||
# 子行形态=容器开标签后内嵌的首个 …Element 行(多子行容器里第一条后面跟的是兄弟不是
|
|
||||||
# 闭合,所以闭合缩进单取:最后一条 Element 行与 </…Summary> 之间的空白)
|
|
||||||
pat_child = re.compile(r"<%s\b[^>]*[^/]>(\s*)(<LabourMaterialsEquipmentsMachinesElement"
|
|
||||||
r"\b[^>]*/>)" % _LME_SUM, re.S)
|
|
||||||
pat_close = re.compile(r"<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>"
|
|
||||||
r"(\s*)(</%s>)" % _LME_SUM, re.S)
|
|
||||||
# 清单/定额/分部样板与原生分隔符同样全局兜底(空单位位没有样板 → 借全件的)
|
|
||||||
g_item = g_pre = g_dw = None
|
|
||||||
g_item_nm = None
|
|
||||||
g_sep = g_sep_d = None
|
|
||||||
g_norm_item = g_norm_pre = None
|
|
||||||
for nm in unit_nms:
|
|
||||||
t0 = texts[nm][0]
|
|
||||||
if row_tmpl is None:
|
|
||||||
m1 = pat_row.search(t0)
|
|
||||||
if m1:
|
|
||||||
row_tmpl = m1.group(0)
|
|
||||||
g_lme_sep = ec._native_sep(t0, _LME_SUM, "\n")
|
|
||||||
if child_tmpl is None:
|
|
||||||
m2 = pat_child.search(t0)
|
|
||||||
if m2:
|
|
||||||
child_tmpl, ci_ind = m2.group(2), m2.group(1)
|
|
||||||
if cc_ind is None:
|
|
||||||
m3 = pat_close.search(t0)
|
|
||||||
if m3:
|
|
||||||
cc_ind = m3.group(1)
|
|
||||||
if g_item is None:
|
|
||||||
b1 = ec._largest_bill_block(t0, tag=_ITEM_BILL, prelim=False)
|
|
||||||
if b1:
|
|
||||||
g_item = b1
|
|
||||||
g_item_nm = nm
|
|
||||||
g_sep = ec._native_sep(t0, _ITEM_BILL, "\r\n")
|
|
||||||
g_sep_d = ec._native_sep(t0, _DW, g_sep)
|
|
||||||
g_dw = _dw_template(t0)
|
|
||||||
g_norm_item = ec._full_norm_block(b1)
|
|
||||||
if g_pre is None:
|
|
||||||
b2 = ec._largest_bill_block(t0, prelim=True)
|
|
||||||
if b2:
|
|
||||||
g_pre = b2
|
|
||||||
g_norm_pre = ec._full_norm_block(b2)
|
|
||||||
if row_tmpl and child_tmpl and cc_ind and g_item and g_pre:
|
|
||||||
break
|
|
||||||
# 台班/配合比子级组成(s_lme_res:p_code → [(子码, 含量)])
|
|
||||||
children = {}
|
|
||||||
if sc:
|
|
||||||
for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
|
|
||||||
"WHERE session_id=? ORDER BY seq, id", (sid,)):
|
|
||||||
children.setdefault(r["p_code"] or "", []).append((r["res_code"], r["qty"]))
|
|
||||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入;手工会话唯一价格源)
|
|
||||||
lib = {}
|
|
||||||
if sc:
|
|
||||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp FROM s_lme_lib "
|
|
||||||
"WHERE session_id=?", (sid,)):
|
|
||||||
lib[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
|
||||||
|
|
||||||
lme_ctx = {"children": children, "row_tmpl": row_tmpl, "child_tmpl": child_tmpl,
|
|
||||||
"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep, "lib": lib,
|
|
||||||
"g_item": g_item, "g_pre": g_pre, "g_dw": g_dw,
|
|
||||||
"g_sep": g_sep, "g_sep_d": g_sep_d,
|
|
||||||
"g_norm_item": g_norm_item, "g_norm_pre": g_norm_pre}
|
|
||||||
# 单位工程位自由复制(主人 2026-10-28 定:骨架=数据结构模板,单位工程/单项工程/
|
|
||||||
# 清单/分部/定额想插多少插多少,结构不变——位不够就克隆骨架自己的单位成员补位,
|
|
||||||
# 项目成员的引用行同步顺延;成员名按骨架自己的 @_序号_名.xml 命名顺延)
|
|
||||||
# 决策 260(2026-11-02 主人定「数据按需自动增加行」双向落成员层):位**多**了也删——
|
|
||||||
# 槽数>我方单位数 → 多余成员整槽不导出(卡槽只是结构样板),项目成员里对应引用行
|
|
||||||
# 同步删除(引用行 FileName=成员显示名);zip 写包时跳过(见写包段 _drop)。
|
|
||||||
drop_nms = []
|
|
||||||
if len(ours) < len(unit_nms):
|
|
||||||
drop_nms = unit_nms[len(ours):]
|
|
||||||
_drop_disp = set()
|
|
||||||
for i in src.infolist():
|
|
||||||
if i.filename in drop_nms:
|
|
||||||
try:
|
|
||||||
_drop_disp.add(i.filename.encode("cp437").decode("gbk")
|
|
||||||
if not (i.flag_bits & 0x800)
|
|
||||||
else i.filename)
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
_drop_disp.add(i.filename)
|
|
||||||
for pn in proj_nms:
|
|
||||||
pt = texts[pn][0]
|
|
||||||
for dd in _drop_disp:
|
|
||||||
# 自闭合引用行(主流形态)整行删;容器形态按完整块删
|
|
||||||
m1 = re.search(r'<UnitWorks\b[^>]*\bFileName="' + re.escape(dd) + r'"[^>]*?/>', pt)
|
|
||||||
if m1:
|
|
||||||
pt = pt[:m1.start()] + pt[m1.end():]
|
|
||||||
continue
|
|
||||||
mm = re.search(r'<UnitWorks\b[^>]*\bFileName="' + re.escape(dd) + r'"', pt)
|
|
||||||
if mm:
|
|
||||||
sp = ec._span(pt, "UnitWorks", mm.start())
|
|
||||||
if sp:
|
|
||||||
pt = pt[:sp[0]] + pt[sp[1]:]
|
|
||||||
texts[pn][0] = pt
|
|
||||||
# 决策 260:成员**文件名**=我方单位名(骨架造名不保留)——改名放在 _render_project
|
|
||||||
# **之后**(引用行 Name 已灌我方名,以引用行 Name↔FileName↔成员 三者为准名实一致),
|
|
||||||
# 见写包前的 ren_map 段;zip 写包段对改名成员用 _GbkNameZipInfo(GBK 字节名)。
|
|
||||||
_disp_of = {}
|
|
||||||
for i in src.infolist():
|
|
||||||
if i.filename in texts and i.filename not in _disp_of:
|
|
||||||
try:
|
|
||||||
_disp_of[i.filename] = i.filename if (i.flag_bits & 0x800) \
|
|
||||||
else i.filename.encode("cp437").decode("gbk")
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
_disp_of[i.filename] = i.filename
|
|
||||||
new_units = [] # [(新成员名, 克隆源名, 引用号, 我方单位名)]——写包时补 zip 条目
|
|
||||||
if drop_nms: # 决策 260:多余槽成员整槽出列(循环/写包都不再含)
|
|
||||||
unit_nms = [n for n in unit_nms if n not in drop_nms]
|
|
||||||
members = [n for n in members if n not in drop_nms]
|
|
||||||
for nm in drop_nms:
|
|
||||||
texts.pop(nm, None)
|
|
||||||
if len(ours) > len(unit_nms):
|
|
||||||
src_nm = g_item_nm or unit_nms[0]
|
|
||||||
orig_slots = len(unit_nms)
|
|
||||||
m2 = re.match(r"@_(\d+)_(.+)\.xml$", src_nm)
|
|
||||||
nums = [int(m.group(1)) for m in
|
|
||||||
(re.match(r"@_(\d+)_", n) for n in unit_nms) if m]
|
|
||||||
base_n = (max(nums) + 2) if nums else (len(unit_nms) + 1)
|
|
||||||
disp = m2.group(2) if m2 else "单位工程"
|
|
||||||
t2 = re.search(r"(\d+)$", disp)
|
|
||||||
# 引用号顺延基准:项目成员里现有 UnitWorks 引用行的最大号
|
|
||||||
nxt = 0
|
|
||||||
if proj_nms:
|
|
||||||
nxt = max([int(x.group(1)) for x in
|
|
||||||
re.finditer(r'<UnitWorks\b[^>]*?\bNumber="(\d+)"', texts[proj_nms[0]][0])]
|
|
||||||
or [0])
|
|
||||||
for k in range(len(ours) - orig_slots):
|
|
||||||
# 决策 260:克隆成员名=我方单位名(骨架顺延名也是造名,不保留)
|
|
||||||
_un_k = re.sub(r'[\\/:*?"<>|\r\n]', "_",
|
|
||||||
((ours[orig_slots + k].get("name") or "").strip() or "单位工程"))[:60]
|
|
||||||
nm_k = "@_%d_%s.xml" % (base_n + 2 * k, _un_k)
|
|
||||||
texts[nm_k] = [texts[src_nm][0], texts[src_nm][1]]
|
|
||||||
t0 = texts[nm_k][0]
|
|
||||||
mm = re.search(r"<UnitWorks\b", t0)
|
|
||||||
if mm:
|
|
||||||
oe = ec._open_tag_end(t0, mm.start())
|
|
||||||
t0 = t0[:mm.start()] + ec._attr_set(t0[mm.start():oe], "Number", str(nxt + 1 + k)) + t0[oe:]
|
|
||||||
texts[nm_k][0] = t0
|
|
||||||
members.append(nm_k)
|
|
||||||
unit_nms.append(nm_k)
|
|
||||||
new_units.append((nm_k, src_nm, nxt + 1 + k,
|
|
||||||
(ours[orig_slots + k].get("name") or "")))
|
|
||||||
proj_rows = None
|
|
||||||
if sc:
|
|
||||||
_dp = dyn_lme.dyn_rows(sc, sid, None)
|
|
||||||
if _dp:
|
|
||||||
proj_rows = [(r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8],
|
|
||||||
r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None)
|
|
||||||
for r in _dp] # 决策 259:导出序 14 列(9 列同形+org/expr 四值+flags)
|
|
||||||
total_steps = len(unit_nms) + len(proj_nms) + 1
|
|
||||||
step = [0]
|
|
||||||
|
|
||||||
def tick():
|
|
||||||
step[0] += 1
|
|
||||||
if progress:
|
|
||||||
progress(step[0], total_steps)
|
|
||||||
|
|
||||||
for i, nm in enumerate(unit_nms):
|
|
||||||
u = ours[i] if i < len(ours) else None
|
|
||||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan, sc, sid, express_by_norm,
|
|
||||||
lme_ctx=lme_ctx)
|
|
||||||
tick()
|
|
||||||
for nm in proj_nms:
|
|
||||||
texts[nm][0] = _render_project(texts[nm][0], plan, proj_name,
|
|
||||||
len(ours), len(plan["sections"]),
|
|
||||||
extra_refs=[(x[3], x[0], x[2]) for x in new_units])
|
|
||||||
texts[nm][0] = _lme_fill(texts[nm][0], proj_rows, children,
|
|
||||||
row_tmpl, child_tmpl,
|
|
||||||
ind={"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep},
|
|
||||||
lib=lib)
|
|
||||||
tick()
|
|
||||||
tick()
|
|
||||||
# 决策 260:成员文件名=我方单位名(引用行 Name 此时已灌我方名,以引用行 Name↔
|
|
||||||
# FileName↔成员 三者为准改名——骨架造名不保留)。zip 写包段按 ren_map 改名。
|
|
||||||
ren_map = {} # zip 内部名 → (旧显示名, 新显示名)
|
|
||||||
_disp_rev = {v: k for k, v in _disp_of.items()}
|
|
||||||
for pn in proj_nms:
|
|
||||||
pt = texts[pn][0]
|
|
||||||
for x in re.finditer(r"<UnitWorks\b[^>]*>", pt):
|
|
||||||
nm_a = re.search(r'\bName="([^"]*)"', x.group(0))
|
|
||||||
fn_a = re.search(r'\bFileName="([^"]*)"', x.group(0))
|
|
||||||
if not nm_a or not fn_a or not nm_a.group(1).strip():
|
|
||||||
continue
|
|
||||||
un = re.sub(r'[\\/:*?"<>|\r\n]', "_", nm_a.group(1).strip())[:60]
|
|
||||||
old_disp = fn_a.group(1)
|
|
||||||
m2 = re.match(r"@_(\d+)_", old_disp)
|
|
||||||
new_disp = "@_%s_%s.xml" % ((m2.group(1) if m2 else "1"), un)
|
|
||||||
in_nm = _disp_rev.get(old_disp)
|
|
||||||
if in_nm and new_disp != old_disp:
|
|
||||||
ren_map[in_nm] = (old_disp, new_disp)
|
|
||||||
pt = pt.replace('FileName="%s"' % old_disp, 'FileName="%s"' % new_disp)
|
|
||||||
texts[pn][0] = pt
|
|
||||||
out = io.BytesIO()
|
|
||||||
item_by_nm = {i.filename: i for i in src.infolist()}
|
|
||||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for item in src.infolist():
|
|
||||||
if item.filename in drop_nms:
|
|
||||||
continue # 决策 260:多余槽成员整槽不导出
|
|
||||||
data = src.read(item.filename)
|
|
||||||
if item.filename in texts:
|
|
||||||
data = ec._encode(texts[item.filename][0], texts[item.filename][1])
|
|
||||||
_rp = ren_map.get(item.filename)
|
|
||||||
if _rp:
|
|
||||||
# 决策 260:成员按我方单位名改名(GBK 字节名,cos4 惯例)
|
|
||||||
zi = _GbkNameZipInfo(_rp[1], date_time=item.date_time)
|
|
||||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
zi.external_attr = item.external_attr
|
|
||||||
zi.create_system = item.create_system
|
|
||||||
try:
|
|
||||||
zi.extra = ec._safe_extra(item.extra)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
zo.writestr(zi, data)
|
|
||||||
continue
|
|
||||||
zi = ec._RawNameZipInfo(item.filename, date_time=item.date_time)
|
|
||||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
zi.external_attr = item.external_attr
|
|
||||||
zi.create_system = item.create_system
|
|
||||||
try:
|
|
||||||
zi.extra = ec._safe_extra(item.extra)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
zo.writestr(zi, data)
|
|
||||||
# 克隆补位的单位成员(骨架原生条目名是 GBK 字节无旗标——新名字同样按 GBK 写)
|
|
||||||
for nm_k, src_nm, _num, _n in new_units:
|
|
||||||
data = ec._encode(texts[nm_k][0], texts[nm_k][1])
|
|
||||||
si = item_by_nm.get(src_nm)
|
|
||||||
zi = _GbkNameZipInfo(nm_k, date_time=si.date_time if si else (2026, 1, 1, 0, 0, 0))
|
|
||||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
if si:
|
|
||||||
zi.external_attr = si.external_attr
|
|
||||||
zi.create_system = si.create_system
|
|
||||||
zo.writestr(zi, data)
|
|
||||||
return out.getvalue()
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""导出引擎 v2(决策 260/264,2026-11-03 主人定「骨架是水管,不造水」):
|
|
||||||
|
|
||||||
- **结构 100% 取自骨架**(空骨架=卡槽集合):数据层按会话数据循环,固定组整组照出;
|
|
||||||
- **值一律透传**:骨架里有什么写什么、数据里有什么写什么;缺值写 "",引擎不解读、不加工;
|
|
||||||
- 数据层=单位工程/分部/清单/措施/定额/工料机/汇总行;其余层是文件固定结构(单价公式行等)。
|
|
||||||
|
|
||||||
数据链复用:build_plan(清单/定额/采纳/临删)+ dyn_lme(工料机现算)。
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import zipfile
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
|
|
||||||
import classic_skeleton
|
|
||||||
import skeleton_engine as se
|
|
||||||
|
|
||||||
LME = "LabourMaterialsEquipmentsMachinesElement"
|
|
||||||
LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
|
|
||||||
# 决策 263:LME Summary 的恒空链(备注/价格来源/交货地/产地/供应商/特征)——导出不回填
|
|
||||||
_HANG_KONG = {"Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
|
|
||||||
"Supplier", "Character"}
|
|
||||||
|
|
||||||
# 结果值区域:骨架样板里带的是别的项目的数——导出时清空(有数据层再灌)
|
|
||||||
_RESULT_REGIONS = {
|
|
||||||
"SummaryOfCost", "SummaryOfBasicCost", "UnitWorksSummary", "UnitWorksSummaryItem",
|
|
||||||
"UnitWorksSummaryGroup", "Tax", "Sundry", "SundryCostsItem",
|
|
||||||
"ProvisionalMaterialEquipment", "ProjectInstallationWorkCostSummary",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class _GbkZipInfo(zipfile.ZipInfo):
|
|
||||||
"""条目名按 **GBK 原始字节**写、不带 UTF-8 旗标——与易达/广联达原件完全一致。
|
|
||||||
Python 默认把非 ASCII 名写成「UTF-8 字节 + 0x800 旗标」,而 cos 族软件按 GBK 解名,
|
|
||||||
会找不到成员(主人 2026-11-03 实测:条目名乱码、Project.xml 的 FileName 对不上)。
|
|
||||||
非 GBK 字符(极端情况)才回退 UTF-8+旗标。"""
|
|
||||||
|
|
||||||
def _encodeFilenameFlags(self):
|
|
||||||
try:
|
|
||||||
return self.filename.encode("gbk"), 0
|
|
||||||
except UnicodeEncodeError:
|
|
||||||
return self.filename.encode("utf-8"), self.flag_bits | 0x800
|
|
||||||
|
|
||||||
|
|
||||||
def _kids(el, tag=None):
|
|
||||||
return [c for c in el if isinstance(c.tag, str) and (tag is None or c.tag == tag)]
|
|
||||||
|
|
||||||
|
|
||||||
def out_name(proj_name, suffix):
|
|
||||||
"""导出文件名:后缀跟导出格式走(原格式=源文件后缀,由调用方传入)。"""
|
|
||||||
return (proj_name or "工程") + "-审核版." + (suffix or "cos4")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 各层渲染(模板克隆 → 清数据子级 → 按数据回灌)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _own_layers(plan):
|
|
||||||
"""本项目骨架的**数据层**要求(2026-11-04 主人定:列不算全部数据,只要数据层能全部导出)。
|
|
||||||
→ (需要存在的层标签集合, 措施清单原生标签集合, 是否有措施分部)。"""
|
|
||||||
need = set()
|
|
||||||
prelim_tags = set()
|
|
||||||
if plan.get("units"):
|
|
||||||
need.add("UnitWorks")
|
|
||||||
has_item = has_prelim = has_norm = has_res = False
|
|
||||||
need_prelim_div = False
|
|
||||||
for d in (plan.get("divides") or {}).values():
|
|
||||||
if d.get("kind") == "prelim":
|
|
||||||
need_prelim_div = True
|
|
||||||
else:
|
|
||||||
need.add("DivisionalWorks")
|
|
||||||
for u in plan.get("units") or []:
|
|
||||||
for b in u.get("bills") or []:
|
|
||||||
if b.get("x_tdel"):
|
|
||||||
continue
|
|
||||||
if b.get("kind") == "prelim":
|
|
||||||
has_prelim = True
|
|
||||||
if b.get("x_ptag"):
|
|
||||||
prelim_tags.add(b["x_ptag"])
|
|
||||||
else:
|
|
||||||
has_item = True
|
|
||||||
for n in b.get("norms") or []:
|
|
||||||
if n.get("x_tdel"):
|
|
||||||
continue
|
|
||||||
has_norm = True
|
|
||||||
if n.get("x_adjust"):
|
|
||||||
need.add("NormAdjustmentList")
|
|
||||||
if n.get("res"):
|
|
||||||
has_res = True
|
|
||||||
if has_item or (has_prelim and "WorkElement" in prelim_tags):
|
|
||||||
need.add("WorkElement")
|
|
||||||
if has_prelim:
|
|
||||||
need.add("PRELIM")
|
|
||||||
if has_norm:
|
|
||||||
need.add("Norm")
|
|
||||||
if has_res:
|
|
||||||
need.add("LabourMaterialsEquipmentsMachinesElement")
|
|
||||||
if any((u.get("lme") or []) for u in plan.get("units") or []):
|
|
||||||
need.add("LabourMaterialsEquipmentsMachinesSummary")
|
|
||||||
return need, prelim_tags, need_prelim_div
|
|
||||||
|
|
||||||
|
|
||||||
def _missing_layers(need, prelim_tags, need_prelim_div, tags):
|
|
||||||
"""层覆盖判定(**不看列**):缺层才判不覆盖;列少不算。"""
|
|
||||||
miss = [t for t in need if t != "PRELIM" and t not in tags]
|
|
||||||
if "PRELIM" in need:
|
|
||||||
if prelim_tags:
|
|
||||||
for t in prelim_tags:
|
|
||||||
if t not in tags:
|
|
||||||
miss.append(t)
|
|
||||||
elif not any(t in tags for t in ("UnitWorksPreliminaryWorkElement", "WorkElement")):
|
|
||||||
miss.append("PRELIM")
|
|
||||||
if need_prelim_div and "PreliminaryDivisionalWorks" not in tags:
|
|
||||||
miss.append("PreliminaryDivisionalWorks")
|
|
||||||
return miss
|
|
||||||
|
|
||||||
|
|
||||||
_REGION_TAGS = {
|
|
||||||
"ConstructionProject", "ProjectInstallationWorkCost", "SectionalWorks",
|
|
||||||
"SystemInfo", "ConstructionInfo", "ProjectInfo", "TendereeInfo", "BidderInfo",
|
|
||||||
"AttrInfo", "AddiInfo", "SummaryOfCost", "UnitWorksSummary",
|
|
||||||
"DivisionalAndElementalWorks", "Preliminaries", "WorkContent",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def min_count(tag):
|
|
||||||
"""结构位基数下限:自增区域=1(至少一个空壳);自增块/自增行及其余=0。"""
|
|
||||||
return 1 if tag in _REGION_TAGS else 0
|
|
||||||
|
|
||||||
|
|
||||||
def row_count(el, data_n):
|
|
||||||
"""导出条数 = max(下限, 数据条数)(加固:区域即使 0 条数据也保留 1 个空壳)。"""
|
|
||||||
tag = el.tag if hasattr(el, "tag") else el
|
|
||||||
return max(min_count(tag), int(data_n or 0))
|
|
||||||
|
|
||||||
|
|
||||||
def rule_note(el):
|
|
||||||
"""导出规则标注(写进空骨架 XML 注释,供主人核对规则对不对)。
|
|
||||||
口径:骨架只给格式;**全部按自增设计**——区域=至少1个空壳、块=按数据块、
|
|
||||||
行=按数据行;不再有「固定」。"""
|
|
||||||
tag = el.tag if isinstance(el.tag, str) else ""
|
|
||||||
if min_count(tag) == 1:
|
|
||||||
return "自增区域:至少 1 个"
|
|
||||||
return "自增块:按数据块循环" if _kids(el) else "自增行:按数据行循环"
|
|
||||||
|
|
||||||
|
|
||||||
def build_blank_package(con, sig):
|
|
||||||
"""骨架库某件 → 完全空的原格式包(Project.xml + 单位成员),每个结构位带规则注释。
|
|
||||||
→ (字节, 文件名, 错误)。zip 族给 .cos4/.cos 包;裸 XML 族给单 XML。"""
|
|
||||||
row = con.execute("SELECT sig, original_name, suffix, x_blank, blob "
|
|
||||||
"FROM classic_skel WHERE sig=?", (sig,)).fetchone()
|
|
||||||
if not row:
|
|
||||||
return None, None, "骨架不存在"
|
|
||||||
name = row["original_name"] or "骨架"
|
|
||||||
suffix = row["suffix"] or "cos4"
|
|
||||||
blank = row["x_blank"]
|
|
||||||
if not blank:
|
|
||||||
blank, _fn = classic_skeleton.frame_blank(con, sig)
|
|
||||||
if not blank:
|
|
||||||
return None, None, "该骨架暂无法总结空骨架"
|
|
||||||
root, decl = classic_skeleton._blank_parse(bytes(blank).decode("utf-8"))
|
|
||||||
meta = classic_skeleton.frame_meta(con, sig) or {}
|
|
||||||
blob = bytes(row["blob"] or b"")
|
|
||||||
|
|
||||||
_LEGEND = ("导出规则:自增区域=至少 1 个空壳;自增块=按数据块循环;"
|
|
||||||
"自增行=按数据行循环。列由骨架决定,值来自数据库")
|
|
||||||
|
|
||||||
def _ser(el):
|
|
||||||
return (decl + "\n<!-- " + _LEGEND + " -->\n"
|
|
||||||
+ se.serialize(el, 0, " ", keep_values=True, note_fn=rule_note) + "\n")
|
|
||||||
|
|
||||||
fam = se.family_of(blob)
|
|
||||||
if fam != se.FAMILY_ZIP:
|
|
||||||
# 裸 XML 族(swt/swz):整件就是骨架,直接单 XML 标注
|
|
||||||
data = _ser(root).encode("utf-8")
|
|
||||||
return data, "%s-空骨架(标注).%s" % (name, suffix), None
|
|
||||||
|
|
||||||
# zip 族:从项目树里取出内嵌单位模板 → 换成 1 条空索引行;单位模板单独成成员
|
|
||||||
unit = None
|
|
||||||
holder = None
|
|
||||||
for par in root.iter():
|
|
||||||
for k in _kids(par, "UnitWorks"):
|
|
||||||
if _kids(k):
|
|
||||||
unit, holder = k, par
|
|
||||||
break
|
|
||||||
if unit is not None:
|
|
||||||
break
|
|
||||||
if unit is None:
|
|
||||||
# 退化骨架(没有单位层):整棵项目树带标注给单 XML,不硬造单位层
|
|
||||||
return _ser(root).encode("utf-8"), "%s-空骨架(标注).%s" % (name, suffix), None
|
|
||||||
member = "@_1_单位工程.xml"
|
|
||||||
holder.remove(unit)
|
|
||||||
idx_attrs = ((meta.get("index_row") or {}).get("attrs") or ["Number", "Name", "FileName"])
|
|
||||||
idx = ET.SubElement(holder, "UnitWorks")
|
|
||||||
for a in idx_attrs:
|
|
||||||
idx.set(a, "")
|
|
||||||
idx.set("FileName", member)
|
|
||||||
proj_xml = _ser(root)
|
|
||||||
unit_xml = _ser(unit)
|
|
||||||
out = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
zi = zipfile.ZipInfo("Project.xml", date_time=(2026, 1, 1, 0, 0, 0))
|
|
||||||
zo.writestr(zi, proj_xml.encode("utf-8"))
|
|
||||||
zi = _GbkZipInfo(member, date_time=(2026, 1, 1, 0, 0, 0))
|
|
||||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
zo.writestr(zi, unit_xml.encode("utf-8"))
|
|
||||||
return out.getvalue(), "%s-空骨架(标注).%s" % (name, suffix), None
|
|
||||||
@@ -239,6 +239,37 @@ def _capture_proj_side(root):
|
|||||||
return recs
|
return recs
|
||||||
|
|
||||||
|
|
||||||
|
def extract_blocks(txt):
|
||||||
|
"""决策 279(2026-11-07 主人定「整体采纳=块进块出」):从单位工程 xml 原文切
|
||||||
|
清单壳块/Norm 块原文。与 iterparse 主流程解耦(独立正则配对),块按文档序返回:
|
||||||
|
bills_blocks = [(清单序i, 块原文...)] —— 清单壳=WorkElement 起至 </WorkElement>,
|
||||||
|
壳块**含**定额块段(采纳时再按 norms_blocks 切开:壳+Σ定额=整块,两半都原文)
|
||||||
|
norms_blocks = [(定额序j, 块原文)]
|
||||||
|
对齐:清单序=parse 流程 bills.append 序(含措施条目);定额序=norms.append 序
|
||||||
|
(伪定额“单位=元”已在正则里排除,与 skip_res_norm 同口径)。
|
||||||
|
嵌套防护:WorkElement 不嵌套(源文件规律);Norm 不嵌套。"""
|
||||||
|
import re as _re
|
||||||
|
bills_blocks, norms_blocks = [], []
|
||||||
|
# Norm 块(含伪定额排除:Number 纯数字且 Unit="元" 的资源构成行不存——与 skip_res_norm 同口径)
|
||||||
|
for m in _re.finditer(r'<Norm\b[^>]*>', txt):
|
||||||
|
e = txt.find('</Norm>', m.start())
|
||||||
|
if e < 0:
|
||||||
|
continue
|
||||||
|
seg = txt[m.start():e + len('</Norm>')]
|
||||||
|
_n = _re.search(r'Number="([^"]*)"', m.group(0))
|
||||||
|
_u = _re.search(r'Unit="([^"]*)"', m.group(0))
|
||||||
|
if _n and (_n.group(1) or '').isdigit() and (_u and (_u.group(1) or '').strip() == '元'):
|
||||||
|
continue
|
||||||
|
norms_blocks.append(seg)
|
||||||
|
# 清单块(WorkElement / UnitWorksPreliminaryWorkElement 两种形态)
|
||||||
|
for m in _re.finditer(r'<(WorkElement|UnitWorksPreliminaryWorkElement)\b[^>]*>', txt):
|
||||||
|
tag = m.group(1)
|
||||||
|
e = txt.find('</%s>' % tag, m.start())
|
||||||
|
if e < 0:
|
||||||
|
continue
|
||||||
|
bills_blocks.append(txt[m.start():e + len(tag) + 3])
|
||||||
|
return bills_blocks, norms_blocks
|
||||||
|
|
||||||
def parse_std(path, out):
|
def parse_std(path, out):
|
||||||
out.setdefault("lme_res", {}) # 机械台班 / 配合比的**下一级组成**:编码 → [(子编码, 含量)]
|
out.setdefault("lme_res", {}) # 机械台班 / 配合比的**下一级组成**:编码 → [(子编码, 含量)]
|
||||||
z = zipfile.ZipFile(path)
|
z = zipfile.ZipFile(path)
|
||||||
@@ -371,6 +402,15 @@ def parse_std(path, out):
|
|||||||
unit_files = [n for n in names if n != proj] or names
|
unit_files = [n for n in names if n != proj] or names
|
||||||
for n in unit_files:
|
for n in unit_files:
|
||||||
txt = _encode_attr_newlines(z.read(n).decode("utf-8", errors="replace"))
|
txt = _encode_attr_newlines(z.read(n).decode("utf-8", errors="replace"))
|
||||||
|
# 决策 279:单位文件原文切块(清单壳/Norm 原文)——按文档序累计,save 时按
|
||||||
|
# bills/norms 的同序下标对齐入库(块序=解析序,两侧都是文档序)。
|
||||||
|
_bb, _nb = extract_blocks(txt)
|
||||||
|
if _bb:
|
||||||
|
out.setdefault("bill_blocks", []).extend(
|
||||||
|
(len(out["bills"]) + k, blk) for k, blk in enumerate(_bb))
|
||||||
|
if _nb:
|
||||||
|
out.setdefault("norm_blocks", []).extend(
|
||||||
|
(len(out["norms"]) + k, blk) for k, blk in enumerate(_nb))
|
||||||
# 每个 xml 文件彼此独立:本文件里没有单位工程的,不许继承上一个文件的归属
|
# 每个 xml 文件彼此独立:本文件里没有单位工程的,不许继承上一个文件的归属
|
||||||
out["cur_uw"] = -1
|
out["cur_uw"] = -1
|
||||||
out["cur_bill"] = -1
|
out["cur_bill"] = -1
|
||||||
@@ -1271,6 +1311,12 @@ def parse_file(path, out):
|
|||||||
# 已导入的 xml 批次也已从库中清除(tools/purge_batches.py --by-ext .xml)。
|
# 已导入的 xml 批次也已从库中清除(tools/purge_batches.py --by-ext .xml)。
|
||||||
# 将来若要恢复:git 历史里有,照 parse_std 的同款容器记账规则重写即可。
|
# 将来若要恢复:git 历史里有,照 parse_std 的同款容器记账规则重写即可。
|
||||||
|
|
||||||
|
def _block_maps(out):
|
||||||
|
"""279:[(序, 块)] → {序: 块};清单块含定额段,Norm 块另存(采纳端按需切/拼)。"""
|
||||||
|
return ({i: b for i, b in (out.get("bill_blocks") or [])},
|
||||||
|
{j: b for j, b in (out.get("norm_blocks") or [])})
|
||||||
|
|
||||||
|
|
||||||
def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||||
"""
|
"""
|
||||||
meta = {name, province, city, district, period_from, period_to, bulid_unit, file_kind}
|
meta = {name, province, city, district, period_from, period_to, bulid_unit, file_kind}
|
||||||
@@ -1279,6 +1325,8 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
|||||||
不传 = 新导入(INSERT 新批次行)。原位路径不动 x_note / x_enabled / x_attach_sha,
|
不传 = 新导入(INSERT 新批次行)。原位路径不动 x_note / x_enabled / x_attach_sha,
|
||||||
也不产生新 id —— sessions.x_batch_id 与 lme_attach 绑定才不至于断链(2026-10-11)
|
也不产生新 id —— sessions.x_batch_id 与 lme_attach 绑定才不至于断链(2026-10-11)
|
||||||
"""
|
"""
|
||||||
|
# 决策 279:块序→块原文 映射(save 内 bills/norms 循环按下标取)
|
||||||
|
out["bill_blocks_map"], out["norm_blocks_map"] = _block_maps(out)
|
||||||
ym = int(time.strftime("%Y", time.localtime(mtime))) * 12 + int(time.strftime("%m", time.localtime(mtime)))
|
ym = int(time.strftime("%Y", time.localtime(mtime))) * 12 + int(time.strftime("%m", time.localtime(mtime)))
|
||||||
if meta:
|
if meta:
|
||||||
name = meta.get("name") or out["proj_name"] or os.path.splitext(fn)[0]
|
name = meta.get("name") or out["proj_name"] or os.path.splitext(fn)[0]
|
||||||
@@ -1306,20 +1354,25 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
|||||||
feat_json = json.dumps([{"n": n, "v": v} for n, v in _feat], ensure_ascii=False) if _feat else None
|
feat_json = json.dumps([{"n": n, "v": v} for n, v in _feat], ensure_ascii=False) if _feat else None
|
||||||
_pside = out.get("proj_side") or []
|
_pside = out.get("proj_side") or []
|
||||||
side_json = json.dumps(_pside, ensure_ascii=False) if _pside else None
|
side_json = json.dumps(_pside, ensure_ascii=False) if _pside else None
|
||||||
|
# 决策 275:落盘名剥 sha 前缀=原始文件名(同后缀采纳判定用;原名自带 _ 也不怕——前缀恒 64 位十六进制)
|
||||||
|
# 决策 277:原位升级分支同样补写(重解析/打开工程升级旧批次时把留档名补齐,检索同后缀过滤用)
|
||||||
|
_mfn = re.match(r"[0-9a-f]{64}_(.+)$", fn or "")
|
||||||
|
_src_name = _mfn.group(1) if _mfn else (fn or "")
|
||||||
if bid is None:
|
if bid is None:
|
||||||
cur.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
|
cur.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
|
||||||
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme, x_imported_at,
|
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme, x_imported_at,
|
||||||
x_src_hash, x_note, x_parser_ver, x_info, x_feat, x_side)
|
x_src_hash, x_note, x_parser_ver, x_info, x_feat, x_side, x_src_name)
|
||||||
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?,?)""",
|
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||||
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"], 0, 0,
|
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"], 0, 0,
|
||||||
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json, side_json))
|
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json, side_json,
|
||||||
|
_src_name))
|
||||||
bid = cur.lastrowid
|
bid = cur.lastrowid
|
||||||
else:
|
else:
|
||||||
cur.execute("""UPDATE batches SET kind=?, Name=?, FileKind=?, BulidUnit=?, x_province=?, x_city=?,
|
cur.execute("""UPDATE batches SET kind=?, Name=?, FileKind=?, BulidUnit=?, x_province=?, x_city=?,
|
||||||
x_district=?, x_period_start_m=?, x_period_end_m=?, x_total=?, x_rows_bill=0, x_rows_lme=0,
|
x_district=?, x_period_start_m=?, x_period_end_m=?, x_total=?, x_rows_bill=0, x_rows_lme=0,
|
||||||
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=?, x_side=? WHERE id=?""",
|
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=?, x_side=?, x_src_name=? WHERE id=?""",
|
||||||
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"],
|
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"],
|
||||||
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, side_json, bid))
|
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, side_json, _src_name, bid))
|
||||||
if cur.rowcount != 1:
|
if cur.rowcount != 1:
|
||||||
raise RuntimeError("原位升级失败:批次 #%s 不存在" % bid)
|
raise RuntimeError("原位升级失败:批次 #%s 不存在" % bid)
|
||||||
|
|
||||||
@@ -1444,6 +1497,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
|||||||
n_bill += 1
|
n_bill += 1
|
||||||
bill_ids.append(cur.lastrowid)
|
bill_ids.append(cur.lastrowid)
|
||||||
seen_bill.add(h)
|
seen_bill.add(h)
|
||||||
|
# 决策 279:清单壳块原文入库(block_bank)。块序=i(同文档序对齐)。
|
||||||
|
_blk = (out.get("bill_blocks_map") or {}).get(i)
|
||||||
|
if _blk:
|
||||||
|
cur.execute("""INSERT INTO block_bank(batch_id, bill_id, norm_id, kind, block_xml, src_sha, src_member)
|
||||||
|
VALUES(?,?,NULL,'bill',?,?,?)""", (bid, bill_ids[-1], _blk, sha, fn))
|
||||||
|
|
||||||
# 定额(补 Quantity / Total,与 s_norms 对齐)
|
# 定额(补 Quantity / Total,与 s_norms 对齐)
|
||||||
# 规格 19:顺手算好定额工程量系数(**GCL 口径**:定额量÷历史GCL=GCL×系数还原原比例,
|
# 规格 19:顺手算好定额工程量系数(**GCL 口径**:定额量÷历史GCL=GCL×系数还原原比例,
|
||||||
@@ -1464,6 +1522,13 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
|||||||
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
|
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
|
||||||
(out.get("norm_side") or {}).get(norm_idx))))
|
(out.get("norm_side") or {}).get(norm_idx))))
|
||||||
norm_ids.append(cur.lastrowid)
|
norm_ids.append(cur.lastrowid)
|
||||||
|
# 决策 279:Norm 块原文入库。块序=norm_idx(同文档序对齐)。
|
||||||
|
_nblk = (out.get("norm_blocks_map") or {}).get(norm_idx)
|
||||||
|
if _nblk:
|
||||||
|
cur.execute("""INSERT INTO block_bank(batch_id, bill_id, norm_id, kind, block_xml, src_sha, src_member)
|
||||||
|
VALUES(?,?,?,'norm',?,?,?)""",
|
||||||
|
(bid, bill_ids[idx] if 0 <= idx < len(bill_ids) else None,
|
||||||
|
norm_ids[-1], _nblk, sha, fn))
|
||||||
|
|
||||||
# 定额消耗工料机(对应 s_norm_res)。
|
# 定额消耗工料机(对应 s_norm_res)。
|
||||||
# 决策 200(2026-10-25 主人定):同一定额下的相同工料机只出一条——消耗量相加
|
# 决策 200(2026-10-25 主人定):同一定额下的相同工料机只出一条——消耗量相加
|
||||||
|
|||||||
@@ -384,7 +384,7 @@ def _region3(p, c, d3):
|
|||||||
return "/".join(x for x in (p, c, d3) if x) or None
|
return "/".join(x for x in (p, c, d3) if x) or None
|
||||||
|
|
||||||
|
|
||||||
def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, projs=None, pmin=None, pmax=None, att="all", unit_free=False):
|
def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, projs=None, pmin=None, pmax=None, att="all", unit_free=False, only_batch_ids=None):
|
||||||
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
|
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
|
||||||
"""row: sqlite Row of s_bills
|
"""row: sqlite Row of s_bills
|
||||||
unit_free(2026-11-02 主人定,Excel 批量匹配专用):Excel 只有一列清单名称没有单位/编码 ——
|
unit_free(2026-11-02 主人定,Excel 批量匹配专用):Excel 只有一列清单名称没有单位/编码 ——
|
||||||
@@ -404,6 +404,14 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
|
|||||||
# 决策 211(2026-10-26 主人定):历史比对默认硬过滤——单位「项」的清单与单价 0 的清单
|
# 决策 211(2026-10-26 主人定):历史比对默认硬过滤——单位「项」的清单与单价 0 的清单
|
||||||
# 无比价意义,不搜出;空价(NULL)不算 0、保守保留(同 199 精神)。各档位共用本串。
|
# 无比价意义,不搜出;空价(NULL)不算 0、保守保留(同 199 精神)。各档位共用本串。
|
||||||
w += " AND COALESCE(b.Unit,'')<>'项' AND (b.Price IS NULL OR b.Price<>0)"
|
w += " AND COALESCE(b.Unit,'')<>'项' AND (b.Price IS NULL OR b.Price<>0)"
|
||||||
|
# 决策 277(2026-11-07 主人定):清单比对同后缀硬过滤——调用方传入允许的批次 id 集
|
||||||
|
# (同后缀+判不出后缀的;None=不过滤,工料机路径恒传 None)。四档共用本串。
|
||||||
|
if only_batch_ids is not None:
|
||||||
|
if only_batch_ids:
|
||||||
|
w += " AND bt.id IN (%s)" % ",".join("?" * len(only_batch_ids))
|
||||||
|
args = args + list(only_batch_ids)
|
||||||
|
else:
|
||||||
|
w += " AND 1=0"
|
||||||
out, seen_ids, qn = [], set(), norm_match(row["Name"])
|
out, seen_ids, qn = [], set(), norm_match(row["Name"])
|
||||||
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)。
|
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)。
|
||||||
# 2026-10-10 决策 27:哈希里的编码只取前 9 位(后 3 位是项目内顺序码,没有对比意义),
|
# 2026-10-10 决策 27:哈希里的编码只取前 9 位(后 3 位是项目内顺序码,没有对比意义),
|
||||||
@@ -486,7 +494,7 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
|
|||||||
return res[:limit]
|
return res[:limit]
|
||||||
|
|
||||||
|
|
||||||
def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=None, self_src=None, page=1, stop=None, projs=None, pmin=None, pmax=None, att="all"):
|
def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=None, self_src=None, page=1, stop=None, projs=None, pmin=None, pmax=None, att="all", only_batch_ids=None):
|
||||||
"""独立检索(2026-10-08 主人定第 4 轮 B 方案):跨**全部入库项目**(kind='project')按
|
"""独立检索(2026-10-08 主人定第 4 轮 B 方案):跨**全部入库项目**(kind='project')按
|
||||||
条件+关键词 直查清单库,与工作台选中的行无关(主人:"搜索条件高于点选清单")。
|
条件+关键词 直查清单库,与工作台选中的行无关(主人:"搜索条件高于点选清单")。
|
||||||
行结构与 match_bill() 完全一致 —— 前端 renderHist / 右栏 / ± 展开零改动复用,差异只有:
|
行结构与 match_bill() 完全一致 —— 前端 renderHist / 右栏 / ± 展开零改动复用,差异只有:
|
||||||
@@ -512,6 +520,14 @@ def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=N
|
|||||||
# 决策 211(2026-10-26 主人定):检索模式同款默认硬过滤——单位「项」与单价 0 的清单不搜出
|
# 决策 211(2026-10-26 主人定):检索模式同款默认硬过滤——单位「项」与单价 0 的清单不搜出
|
||||||
extra.append("COALESCE(b.Unit,'')<>'项'")
|
extra.append("COALESCE(b.Unit,'')<>'项'")
|
||||||
extra.append("(b.Price IS NULL OR b.Price<>0)")
|
extra.append("(b.Price IS NULL OR b.Price<>0)")
|
||||||
|
# 决策 277(2026-11-07 主人定):清单检索同后缀硬过滤——调用方传入允许的批次 id 集
|
||||||
|
# (同后缀+判不出后缀的;None=不过滤,工料机路径恒传 None)。
|
||||||
|
if only_batch_ids is not None:
|
||||||
|
if only_batch_ids:
|
||||||
|
extra.append("bt.id IN (%s)" % ",".join("?" * len(only_batch_ids)))
|
||||||
|
args = args + list(only_batch_ids)
|
||||||
|
else:
|
||||||
|
extra.append("1=0")
|
||||||
nm = (self_name or "").strip()
|
nm = (self_name or "").strip()
|
||||||
src = (self_src or "").strip()
|
src = (self_src or "").strip()
|
||||||
if src or nm:
|
if src or nm:
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""骨架来源(2026-10-31 定稿:随客户端升级包分发,服务端只负责套餐管理)。
|
|
||||||
|
|
||||||
骨架 JSON 由管理台导出脚本(yhy-mager scripts/export_skeleton_for_client.py)
|
|
||||||
生成、随升级包放入 app/skeletons/{suffix}.json。本模块只做:加载 + 结构校验 + 摘要,
|
|
||||||
**没有任何网络逻辑**——离线可用,不依赖凭据与服务端。
|
|
||||||
|
|
||||||
骨架即「数据结构」:租户端导出引擎按点位消费——
|
|
||||||
锚定值以 "/" 开头 = 闭合点;无子目录且非闭合 = 自闭合;其余 = 起点容器;
|
|
||||||
目录的 columns = 该元素属性(is_value/parent_id 标记的为枚举含义列,非属性)。
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
APP_DIR = os.path.dirname(_HERE) # .../CostReview/app
|
|
||||||
DEFAULT_SKELETON_DIR = os.path.join(APP_DIR, "skeletons")
|
|
||||||
|
|
||||||
|
|
||||||
class SkeletonError(Exception):
|
|
||||||
"""骨架缺失/损坏(信息给足,绝不带病前进)。"""
|
|
||||||
|
|
||||||
|
|
||||||
def skeleton_path(suffix, skeleton_dir=None):
|
|
||||||
safe = "".join(ch for ch in suffix if ch.isalnum() or ch in "-_.") or "x"
|
|
||||||
return os.path.join(skeleton_dir or DEFAULT_SKELETON_DIR, f"{safe}.json")
|
|
||||||
|
|
||||||
|
|
||||||
def load(suffix, skeleton_dir=None):
|
|
||||||
"""加载某后缀的骨架,返回 data dict。文件缺失/损坏一律抛 SkeletonError。"""
|
|
||||||
f = skeleton_path(suffix, skeleton_dir)
|
|
||||||
if not os.path.isfile(f):
|
|
||||||
raise SkeletonError(f"升级包内没有骨架文件:{f}(由管理台导出脚本生成并随包分发)")
|
|
||||||
try:
|
|
||||||
data = json.load(open(f, encoding="utf8"))["data"]
|
|
||||||
except Exception as e:
|
|
||||||
raise SkeletonError(f"骨架文件损坏({f}):{e}") from e
|
|
||||||
validate(data)
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def validate(data):
|
|
||||||
"""结构校验(坏骨架绝不出引擎)。返回摘要 dict。"""
|
|
||||||
if not isinstance(data, dict) or not isinstance(data.get("dirs"), list) or not data["dirs"]:
|
|
||||||
raise SkeletonError("骨架缺少 dirs 或为空")
|
|
||||||
seen = set()
|
|
||||||
roots = []
|
|
||||||
for d in data["dirs"]:
|
|
||||||
if not isinstance(d, dict) or not d.get("name"):
|
|
||||||
raise SkeletonError("目录项缺 name")
|
|
||||||
did = d.get("id")
|
|
||||||
if did in seen:
|
|
||||||
raise SkeletonError(f"目录 id 重复:{did}")
|
|
||||||
seen.add(did)
|
|
||||||
pid = d.get("parent_id")
|
|
||||||
if pid is None:
|
|
||||||
roots.append(d["name"])
|
|
||||||
elif pid not in {x.get("id") for x in data["dirs"]}:
|
|
||||||
raise SkeletonError(f"目录「{d['name']}」的 parent_id={pid} 不存在")
|
|
||||||
for col in d.get("columns") or []:
|
|
||||||
if not col.get("name"):
|
|
||||||
raise SkeletonError(f"目录「{d['name']}」存在无名属性行")
|
|
||||||
if not roots:
|
|
||||||
raise SkeletonError("骨架没有根目录")
|
|
||||||
if not data.get("version"):
|
|
||||||
raise SkeletonError("骨架缺少 version")
|
|
||||||
return summary(data)
|
|
||||||
|
|
||||||
|
|
||||||
def summary(data):
|
|
||||||
"""骨架摘要(核对/日志用)。"""
|
|
||||||
dirs = data["dirs"]
|
|
||||||
anchored = [d for d in dirs if d.get("anchor")]
|
|
||||||
closes = [d for d in dirs if str(d.get("anchor", "")).startswith("/")]
|
|
||||||
rows = sum(len(d.get("columns") or []) for d in dirs)
|
|
||||||
filled = sum(1 for d in dirs for c in (d.get("columns") or []) if c.get("value"))
|
|
||||||
return {
|
|
||||||
"suffix": (data.get("suffix") or {}).get("name"),
|
|
||||||
"group": (data.get("suffix") or {}).get("group"),
|
|
||||||
"version": data.get("version"),
|
|
||||||
"dirs": len(dirs),
|
|
||||||
"roots": [d["name"] for d in dirs if d.get("parent_id") is None],
|
|
||||||
"anchored": len(anchored),
|
|
||||||
"close_points": len(closes),
|
|
||||||
"rows": rows,
|
|
||||||
"filled_cells": filled,
|
|
||||||
"files": len(data.get("files") or []),
|
|
||||||
}
|
|
||||||
@@ -1,439 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""格式无关骨架引擎(决策 262,2026-11-03 主人定「引擎写活了,后期还有很多后缀」)。
|
|
||||||
|
|
||||||
口径(主人逐条定 + 实件勘察结论):
|
|
||||||
· **后缀不参与拦截**:能不能用由**内容**判定——zip 内 XML(cos/cos4 型)/ 裸 XML(swt/swz 型)。
|
|
||||||
后期新后缀(st/uuy…)只要是这两种之一,零代码接入。
|
|
||||||
· **唯一结构位** = (父路径, 标签, 列集):三者相同即同一结构位,只留 1 个样板;值全清空(卡槽)。
|
|
||||||
· **子节点取并集**:同一结构位的子节点按身份合并(递归);自嵌套按实件最大深度保留有限层。
|
|
||||||
· **区域/自增块/自增行**不是三种标签,而是同一套结构位的三种出现形态:
|
|
||||||
区域=全实件恒 1 次;自增块=容器重复;自增行=自闭合行重复。
|
|
||||||
· **次数不进骨架**:骨架只给结构+列序,重复次数由数据条数决定(0 条不输出)。
|
|
||||||
|
|
||||||
实测(2026-11-03):cos4 9507→131、cos 25581→73、swt 463→38、swz 185→37 个唯一结构位。
|
|
||||||
"""
|
|
||||||
import copy
|
|
||||||
import io
|
|
||||||
import zipfile
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 一、格式族判定(按内容,不按后缀)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
FAMILY_ZIP = "zip" # zip 容器 + 若干 XML 成员(主文件 + 单位工程成员)
|
|
||||||
FAMILY_RAW = "raw" # 裸 XML 单文件(单位工程内嵌)
|
|
||||||
|
|
||||||
|
|
||||||
def family_of(blob):
|
|
||||||
"""字节 → FAMILY_ZIP / FAMILY_RAW / None(加密壳、二进制、坏件一律 None)。"""
|
|
||||||
if not blob:
|
|
||||||
return None
|
|
||||||
if blob[:2] == b"PK":
|
|
||||||
try:
|
|
||||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
|
||||||
for nm in z.namelist():
|
|
||||||
if nm.lower().endswith(".xml"):
|
|
||||||
try:
|
|
||||||
ET.fromstring(z.read(nm))
|
|
||||||
return FAMILY_ZIP
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
return None
|
|
||||||
head = blob[:6].lstrip()
|
|
||||||
if head[:5].lower().startswith(b"<?xml") or head[:1] == b"<":
|
|
||||||
try:
|
|
||||||
ET.fromstring(blob)
|
|
||||||
return FAMILY_RAW
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _decode_bytes(raw):
|
|
||||||
"""按声明解码,声明缺失/错时退 utf-8、gb18030。返回 (bytes, encoding)。"""
|
|
||||||
import re
|
|
||||||
m = re.match(rb'(?:\xef\xbb\xbf|\s)*<\?xml[^>]*encoding="([^"]+)"', raw[:300])
|
|
||||||
enc = m.group(1).decode("ascii", "ignore") if m else "utf-8"
|
|
||||||
for e in (enc, "utf-8", "gb18030"):
|
|
||||||
try:
|
|
||||||
raw.decode(e)
|
|
||||||
return raw, e
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
return raw, "utf-8"
|
|
||||||
|
|
||||||
|
|
||||||
def parse_root(raw):
|
|
||||||
"""字节 → (根元素, 声明文本)。保留注释节点(原文件有才保留,引擎不造)。"""
|
|
||||||
import re
|
|
||||||
blob, _enc = _decode_bytes(raw)
|
|
||||||
text = blob.decode(_enc, errors="replace")
|
|
||||||
m = re.match(r"\s*<\?xml[^>]*\?>", text)
|
|
||||||
decl = m.group(0) if m else '<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
body = text[m.end():] if m else text
|
|
||||||
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
|
|
||||||
return ET.fromstring(body, parser=parser), decl
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 二、唯一结构收敛(本次核心)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _key(el):
|
|
||||||
return (el.tag, tuple(sorted(el.attrib.keys())))
|
|
||||||
|
|
||||||
|
|
||||||
# 骨架只给格式(列集 + 每层是否自增);**所有值来自数据库**,骨架一个值都不带。
|
|
||||||
# 主人 2026-11-03 定:「骨架只管导出格式及是不是自增行」——单价行/管理费/费用构成
|
|
||||||
# 这些值全部随导入进库(s_bills/s_norms 的 x_side),导出时有几行出几行。
|
|
||||||
_DATA_TAGS = set()
|
|
||||||
|
|
||||||
_ZERO_RULES = {}
|
|
||||||
|
|
||||||
|
|
||||||
def _copy_fixed(c):
|
|
||||||
"""(保留占位)固定结构节点深拷贝。"""
|
|
||||||
return copy.deepcopy(c)
|
|
||||||
|
|
||||||
|
|
||||||
def collapse_into(node, el):
|
|
||||||
"""把源元素 el 的子结构并入样板 node:同身份合并、子节点递归取并集、值清空。"""
|
|
||||||
seen = {}
|
|
||||||
for k in node:
|
|
||||||
if isinstance(k.tag, str):
|
|
||||||
seen[_key(k)] = k
|
|
||||||
for c in el:
|
|
||||||
if not isinstance(c.tag, str): # 注释:原样保留一次
|
|
||||||
if not any(isinstance(k.tag, type(c.tag)) and k.text == c.text for k in node):
|
|
||||||
node.append(c)
|
|
||||||
continue
|
|
||||||
key = _key(c)
|
|
||||||
sub = seen.get(key)
|
|
||||||
if sub is None:
|
|
||||||
sub = ET.SubElement(node, c.tag)
|
|
||||||
for a in c.attrib: # 列序=首次出现序,值=空卡槽
|
|
||||||
sub.set(a, "")
|
|
||||||
seen[key] = sub
|
|
||||||
collapse_into(sub, c)
|
|
||||||
return node
|
|
||||||
|
|
||||||
|
|
||||||
def collapse(root):
|
|
||||||
"""整树 → 唯一结构位树(每个结构位只出现一次,值全空)。"""
|
|
||||||
out = ET.Element(root.tag)
|
|
||||||
for a in root.attrib:
|
|
||||||
out.set(a, "")
|
|
||||||
collapse_into(out, root)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def paths_of(root):
|
|
||||||
"""→ {路径字符串: 出现次数};路径=根到该元素的标签链('A/B/C')。"""
|
|
||||||
out = {}
|
|
||||||
stack = [(root, root.tag)]
|
|
||||||
while stack:
|
|
||||||
el, p = stack.pop()
|
|
||||||
out[p] = out.get(p, 0) + 1
|
|
||||||
for c in el:
|
|
||||||
if isinstance(c.tag, str):
|
|
||||||
stack.append((c, p + "/" + c.tag))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 三、结构旁注(sidecar):哪些层是清单/定额/工料机/单位工程
|
|
||||||
# 判定只看结构(重复次数+嵌套关系),不看标签名——新后缀零配置。
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _attrs_by_path(roots):
|
|
||||||
"""→ {路径: 列集}(只取出现过的属性名,不看值)。"""
|
|
||||||
out = {}
|
|
||||||
for r in roots:
|
|
||||||
stack = [(r, r.tag)]
|
|
||||||
while stack:
|
|
||||||
el, p = stack.pop()
|
|
||||||
s = out.setdefault(p, set())
|
|
||||||
s.update(el.attrib.keys())
|
|
||||||
for c in el:
|
|
||||||
if isinstance(c.tag, str):
|
|
||||||
stack.append((c, p + "/" + c.tag))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def derive_meta(roots, unit_tag=None):
|
|
||||||
"""多份实件根 → {'v':1,'paths':{path:count},'roles':{...}}。
|
|
||||||
角色判定只用**结构 + 属性名**(不看标签名、不看后缀),顺序:
|
|
||||||
①工料机行=重复的自闭合叶行里,属性同时有"数量"和"编号/代码"、次数最多者;
|
|
||||||
②定额=工料机行的父节点(父是壳也照取——壳在清单层再跳);
|
|
||||||
③清单=从定额往上最近的非壳容器(壳=只有一个子标签的容器);
|
|
||||||
④分部=清单上方能重复的容器;⑤单位=根标签里出现最多的那个(zip 族=单位成员根)。
|
|
||||||
认结构(清单→定额→工料机三层嵌套)的格式适用;数据模型不同的族(如 SWT 工料机是
|
|
||||||
独立表、不挂在定额下)只认得出部分角色,导出端会回退旧引擎——这是适配器边界。"""
|
|
||||||
counts = {}
|
|
||||||
for r in roots:
|
|
||||||
for p, n in paths_of(r).items():
|
|
||||||
counts[p] = counts.get(p, 0) + n
|
|
||||||
attrs = _attrs_by_path(roots)
|
|
||||||
parent = {p: p.rsplit("/", 1)[0] for p in counts if "/" in p}
|
|
||||||
has_kid = {p: False for p in counts}
|
|
||||||
for p in counts:
|
|
||||||
if p in parent:
|
|
||||||
has_kid[parent[p]] = True
|
|
||||||
|
|
||||||
def kids(p):
|
|
||||||
return [q for q in counts if parent.get(q) == p]
|
|
||||||
|
|
||||||
def is_shell(p):
|
|
||||||
return len({q.rsplit("/", 1)[-1] for q in kids(p)}) == 1
|
|
||||||
|
|
||||||
colset = lambda p: {a.lower() for a in attrs.get(p, ())}
|
|
||||||
|
|
||||||
def is_norm_like(p):
|
|
||||||
"""定额样:有 名称/单位/数量/单价(Price 或 Rate 精确名,不用 NoTaxPrice 这类)。"""
|
|
||||||
c = colset(p)
|
|
||||||
return {"name", "unit", "quantity"} <= c and (("price" in c) or ("rate" in c))
|
|
||||||
|
|
||||||
# ① 工料机行="定额样"节点的子行(数量+编号),次数最大者;避免把汇总表当定额
|
|
||||||
rows = [p for p in counts
|
|
||||||
if counts[p] >= 2 and not has_kid[p]
|
|
||||||
and "quantity" in colset(p) and ({"number", "code"} & colset(p))
|
|
||||||
and is_norm_like(parent.get(p, ""))]
|
|
||||||
lme = max(rows, key=lambda p: counts[p]) if rows else None
|
|
||||||
# ② 定额 = 工料机行父节点
|
|
||||||
norm = parent.get(lme) if lme else None
|
|
||||||
# ③ 清单 = 从定额往上最近的非壳容器
|
|
||||||
bill = None
|
|
||||||
p = parent.get(norm) if norm else None
|
|
||||||
while p:
|
|
||||||
if has_kid[p] and not is_shell(p):
|
|
||||||
bill = p
|
|
||||||
break
|
|
||||||
p = parent.get(p)
|
|
||||||
# ④ 分部 = 清单上方能重复的容器
|
|
||||||
div = None
|
|
||||||
p = parent.get(bill) if bill else None
|
|
||||||
while p:
|
|
||||||
if counts.get(p, 0) >= 2 and not is_shell(p):
|
|
||||||
div = p
|
|
||||||
break
|
|
||||||
p = parent.get(p)
|
|
||||||
# ⑤ 单位 = 调用方指定的单位根(zip 族=单位成员根);否则取出现最多的根标签
|
|
||||||
from collections import Counter
|
|
||||||
roots_cnt = Counter(r.tag for r in roots)
|
|
||||||
unit = unit_tag or (roots_cnt.most_common(1)[0][0] if roots_cnt else None)
|
|
||||||
# 单位级工料机汇总行:单位之下、不在清单/定额链上、重复的自闭合叶行
|
|
||||||
lme_sum = None
|
|
||||||
if unit:
|
|
||||||
sub = [q for q in counts
|
|
||||||
if q.startswith(unit + "/") and counts[q] >= 2 and not has_kid[q]
|
|
||||||
and not (norm and q.startswith(norm))]
|
|
||||||
lme_sum = max(sub, key=lambda q: counts[q]) if sub else None
|
|
||||||
return {"v": 1, "paths": counts,
|
|
||||||
"roles": {"unit": unit, "bill": bill, "div": div,
|
|
||||||
"norm": norm, "lme": lme, "lme_sum": lme_sum}}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 四、分层列集指纹与匹配度(字段越像分越高 + 区域越像分越高)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def layer_cols(roots):
|
|
||||||
"""多份实件根 → {'v':2,'p':{路径:[列名…]}}(每层列集并集,首见列序)。"""
|
|
||||||
out = {}
|
|
||||||
for r in roots:
|
|
||||||
stack = [(r, r.tag)]
|
|
||||||
while stack:
|
|
||||||
el, p = stack.pop()
|
|
||||||
cols = out.setdefault(p, [])
|
|
||||||
for a in el.attrib:
|
|
||||||
if a not in cols:
|
|
||||||
cols.append(a)
|
|
||||||
for c in el:
|
|
||||||
if isinstance(c.tag, str):
|
|
||||||
stack.append((c, p + "/" + c.tag))
|
|
||||||
return {"v": 2, "p": out}
|
|
||||||
|
|
||||||
|
|
||||||
def _finger_paths(fp):
|
|
||||||
"""兼容新旧两种指纹 → {path: set(cols)}。旧= {tag:[...]};新= {'v':2,'p':{path:[...]}}。"""
|
|
||||||
if not isinstance(fp, dict):
|
|
||||||
return {}
|
|
||||||
if fp.get("v") == 2 and isinstance(fp.get("p"), dict):
|
|
||||||
return {k: set(v) for k, v in fp["p"].items()}
|
|
||||||
return {k: set(v) for k, v in fp.items() if isinstance(v, (list, tuple, set))}
|
|
||||||
|
|
||||||
|
|
||||||
def _root_path(paths):
|
|
||||||
for p in paths:
|
|
||||||
if "/" not in p:
|
|
||||||
return p, paths[p]
|
|
||||||
return None, set()
|
|
||||||
|
|
||||||
|
|
||||||
def match_score(src_fp, skel_fp):
|
|
||||||
"""0~100:字段匹配(同层列集重合,根层权重最高)+ 区域匹配(骨架的结构区域在原件里有没有)。
|
|
||||||
根标签不同=不同格式族,直接压低到 10 分以下。"""
|
|
||||||
src = _finger_paths(src_fp)
|
|
||||||
skel = _finger_paths(skel_fp)
|
|
||||||
if not src or not skel:
|
|
||||||
return 0.0
|
|
||||||
sroot, scols = _root_path(src)
|
|
||||||
kroot, kcols = _root_path(skel)
|
|
||||||
if sroot != kroot:
|
|
||||||
return 10.0 * (len(scols & kcols) / max(1, len(scols | kcols)))
|
|
||||||
# 字段:逐层 Jaccard,根层×3、二三层×2、其余×1
|
|
||||||
num = den = 0.0
|
|
||||||
for p, cols in skel.items():
|
|
||||||
if p not in src:
|
|
||||||
continue
|
|
||||||
depth = p.count("/")
|
|
||||||
w = 3.0 if depth == 0 else (2.0 if depth <= 2 else 1.0)
|
|
||||||
num += w * len(cols & src[p]) / max(1, len(cols | src[p]))
|
|
||||||
den += w
|
|
||||||
field = (num / den * 100.0) if den else 0.0
|
|
||||||
# 区域:骨架里出现过的结构位,原件里覆盖多少(只看骨架,不看原件多出来的)
|
|
||||||
cover = sum(1 for p in skel if p in src) / max(1, len(skel))
|
|
||||||
return round(field * 0.65 + cover * 100.0 * 0.35, 2)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 五、从实件提炼空骨架(主驱动:family 判定,不看后缀)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _members(blob):
|
|
||||||
"""→ [(成员名, 字节)];裸 XML 时 → [('(single)', blob)]。"""
|
|
||||||
if family_of(blob) == FAMILY_ZIP:
|
|
||||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
|
||||||
return [(nm, z.read(nm)) for nm in z.namelist() if nm.lower().endswith(".xml")]
|
|
||||||
return [("(single)", blob)]
|
|
||||||
|
|
||||||
|
|
||||||
def split_roots(blob):
|
|
||||||
"""→ (主根列表, 单位根列表, family)。zip:单位根=多数成员根标签;raw:整件即主根。
|
|
||||||
单位工程判定不靠标签名,靠"同一个根标签在多个成员里重复出现"。"""
|
|
||||||
fam = family_of(blob)
|
|
||||||
if fam is None:
|
|
||||||
return [], [], None
|
|
||||||
members = _members(blob)
|
|
||||||
roots = []
|
|
||||||
for nm, raw in members:
|
|
||||||
try:
|
|
||||||
r, _d = parse_root(raw)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
roots.append((nm, r))
|
|
||||||
if fam == FAMILY_RAW:
|
|
||||||
return [r for _n, r in roots], [], fam
|
|
||||||
# zip:根标签计数,出现 ≥2 次的当单位成员
|
|
||||||
from collections import Counter
|
|
||||||
cnt = Counter(r.tag for _n, r in roots)
|
|
||||||
unit_tag = None
|
|
||||||
for t, n in cnt.most_common():
|
|
||||||
if n >= 2:
|
|
||||||
unit_tag = t
|
|
||||||
break
|
|
||||||
if unit_tag is None and len(roots) > 1:
|
|
||||||
unit_tag = cnt.most_common()[-1][0]
|
|
||||||
units = [r for _n, r in roots if r.tag == unit_tag]
|
|
||||||
mains = [r for _n, r in roots if r.tag != unit_tag]
|
|
||||||
if not mains:
|
|
||||||
mains = [roots[0][1]]
|
|
||||||
units = [r for _n, r in roots[1:]]
|
|
||||||
return mains, units, fam
|
|
||||||
|
|
||||||
|
|
||||||
def build_blank(blob, ind_unit=" "):
|
|
||||||
"""实件 → (空骨架单 XML 文本, meta)。meta 给导出用(角色路径)。
|
|
||||||
zip 族:主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
|
|
||||||
raw 族:整件收敛。两种家族同一个收敛器,零后缀配置。"""
|
|
||||||
mains, units, fam = split_roots(blob)
|
|
||||||
if fam is None or not mains:
|
|
||||||
return None, None
|
|
||||||
main = collapse(mains[0])
|
|
||||||
if not units:
|
|
||||||
roots_for_meta = mains
|
|
||||||
text = _serialize(main, ind_unit)
|
|
||||||
return text, derive_meta(roots_for_meta)
|
|
||||||
unit_best = max(units, key=lambda r: len(list(r.iter())))
|
|
||||||
unit = collapse(unit_best)
|
|
||||||
# 2026-11-04 决策267:单位骨架取**全成员并集**——只取一个成员会丢别的成员才有的
|
|
||||||
# 层/列(实测:本项目分部 13 列、某个成员只有 7 列,导致导出丢列)。值仍为空。
|
|
||||||
for _u in units:
|
|
||||||
if _u is unit_best:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
collapse_into(unit, collapse(_u))
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
# 连接:主骨架里第一条带 FileName 的索引行 → 换成单位骨架
|
|
||||||
placed = False
|
|
||||||
for par in main.iter():
|
|
||||||
for k in list(par):
|
|
||||||
if not isinstance(k.tag, str):
|
|
||||||
continue
|
|
||||||
if "FileName" in k.attrib:
|
|
||||||
idx = list(par).index(k)
|
|
||||||
par.remove(k)
|
|
||||||
par.insert(idx, unit)
|
|
||||||
placed = True
|
|
||||||
break
|
|
||||||
if placed:
|
|
||||||
break
|
|
||||||
if not placed:
|
|
||||||
# 退化样例(Project.xml 没有单位索引行):单位骨架直接挂主根,导出端仍能按它建成员
|
|
||||||
main.append(unit)
|
|
||||||
text = _serialize(main, ind_unit)
|
|
||||||
meta = derive_meta(mains + units, unit_tag=unit_best.tag)
|
|
||||||
# 决策 264:记下被替换掉的**索引行**(导出时按它复制成 N 行),否则项目索引无法还原
|
|
||||||
meta["index_row"] = {"tag": None, "attrs": []}
|
|
||||||
for par in collapse(mains[0]).iter():
|
|
||||||
for k in par:
|
|
||||||
if isinstance(k.tag, str) and "FileName" in k.attrib:
|
|
||||||
meta["index_row"] = {"tag": k.tag, "attrs": list(k.attrib.keys())}
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
break
|
|
||||||
return text, meta
|
|
||||||
|
|
||||||
|
|
||||||
def _ind_unit(root):
|
|
||||||
"""缩进单位:优先从实件文本锚定(4 空格常见);此处按层给 4 空格,
|
|
||||||
真实缩进由 refine_blank 传入的件锚定(见 classic_skeleton._blank_ind_unit)。"""
|
|
||||||
return " "
|
|
||||||
|
|
||||||
|
|
||||||
def serialize(el, depth=0, ind=" ", keep_values=False, first=True, note_fn=None):
|
|
||||||
"""唯一结构位树 → 文本行(一行一层、叶自闭合、无空行)。
|
|
||||||
属性值按 XML 规则转义(数据里的 & < > " 会原样出现,不转义整件就坏)。
|
|
||||||
note_fn(el)→字符串:在开标签后追加 XML 注释(骨架库「空骨架+导出规则标注」用)。"""
|
|
||||||
pad = "" if first else "\n" + ind * depth
|
|
||||||
if keep_values:
|
|
||||||
from xml.sax.saxutils import escape
|
|
||||||
# 决策 263 补记(2026-11-04 主人报「项目特征导出后不点开换行乱」):
|
|
||||||
# 属性值里的字面 LF 在 XML 解析时按规范归一成空格——必须写 实体才能保住换行
|
|
||||||
# (老引擎外科手术保留原 实体无此问题;v2 全量序列化必须显式转)
|
|
||||||
attrs = "".join(' %s="%s"' % (k, escape(str(v), {'"': """}).replace("\n", " "))
|
|
||||||
for k, v in el.attrib.items())
|
|
||||||
else:
|
|
||||||
attrs = "".join(' %s=""' % k for k, _ in el.attrib.items())
|
|
||||||
kids = [k for k in el if isinstance(k.tag, str)]
|
|
||||||
note = note_fn(el) if note_fn else ""
|
|
||||||
note = ("<!-- %s -->" % str(note).replace("--", "-")) if note else ""
|
|
||||||
out = [pad + "<" + el.tag + attrs]
|
|
||||||
if not kids:
|
|
||||||
out[0] += " />" + note
|
|
||||||
return "".join(out)
|
|
||||||
out[0] += ">" + note
|
|
||||||
for k in kids:
|
|
||||||
out.append(serialize(k, depth + 1, ind, keep_values, first=False, note_fn=note_fn))
|
|
||||||
out.append("\n" + ind * depth + "</" + el.tag + ">")
|
|
||||||
return "".join(out)
|
|
||||||
|
|
||||||
|
|
||||||
def _serialize(root, ind=" ", keep_values=False):
|
|
||||||
decl = '<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
return decl + "\n" + serialize(root, 0, ind, keep_values) + "\n"
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,7 @@ CREATE TABLE IF NOT EXISTS batches(
|
|||||||
x_src_hash TEXT,
|
x_src_hash TEXT,
|
||||||
x_note TEXT,
|
x_note TEXT,
|
||||||
x_attach_sha TEXT, -- 关联 attachments.sha256(原始文件留档)
|
x_attach_sha TEXT, -- 关联 attachments.sha256(原始文件留档)
|
||||||
|
x_src_name TEXT, -- 原始文件名(导入落盘名剥 sha 前缀;同后缀采纳判定 275 用)
|
||||||
x_publisher TEXT, -- 发布单位(信息价用)
|
x_publisher TEXT, -- 发布单位(信息价用)
|
||||||
x_info TEXT, -- 项目级「基本信息」卡(原文件项目节点属性 JSON)
|
x_info TEXT, -- 项目级「基本信息」卡(原文件项目节点属性 JSON)
|
||||||
x_feat TEXT, -- 项目级「项目特征信息」卡(AttrInfo/AddiInfo JSON)
|
x_feat TEXT, -- 项目级「项目特征信息」卡(AttrInfo/AddiInfo JSON)
|
||||||
@@ -504,26 +505,22 @@ CREATE TABLE IF NOT EXISTS lme_skel_group(
|
|||||||
-- (决策 197 补) lme_skel_file 含 original_name 列(原名,剥 sha 前缀)——上面建表语句已含;
|
-- (决策 197 补) lme_skel_file 含 original_name 列(原名,剥 sha 前缀)——上面建表语句已含;
|
||||||
-- 旧库由 ensure_tables 的 ALTER 补列。
|
-- 旧库由 ensure_tables 的 ALTER 补列。
|
||||||
|
|
||||||
-- ===== 清单库(2026-11-04 主人定:后台「清单」页三区域)=====
|
-- ===== 决策 279(2026-11-07 主人定「整体采纳=块进块出」):原文块库 =====
|
||||||
-- 一棵目录树:depth 0=根目录(内置"根目录") 1=省 2=清单名称 3+=章节(区域2,层级不限);
|
-- 批次库版:导入时从各单位工程 XML 原文切出 清单壳块/Norm 块 原文存储。
|
||||||
-- 清单条目挂章节节点(depth>=3)。树内容全部由主人在界面里建,软件只种根。
|
-- 采纳=整块拷进会话库 s_block_bank;导出=有块吐块(原样回插,工程量属性按现行清空/回灌)。
|
||||||
CREATE TABLE IF NOT EXISTS qlist_dirs(
|
-- kind: 'bill'=清单壳块(WorkElement 起到 </WorkElement>,不含定额块段)
|
||||||
|
-- 'norm'=定额块(<Norm 起到 </Norm>)
|
||||||
|
-- 块与行 1:1(bill_id/norm_id 指向);删行即删块(外键无约束,应用层保证)。
|
||||||
|
CREATE TABLE IF NOT EXISTS block_bank(
|
||||||
id INTEGER PRIMARY KEY,
|
id INTEGER PRIMARY KEY,
|
||||||
parent_id INTEGER NOT NULL DEFAULT 0, -- 0=根
|
batch_id INTEGER,
|
||||||
name TEXT NOT NULL,
|
bill_id INTEGER, -- 批次库 bills.id(清单壳块/Norm 块都挂清单)
|
||||||
seq INTEGER NOT NULL DEFAULT 0, -- 同级排序(上移/下移换 seq)
|
norm_id INTEGER, -- kind='norm' 时指向 norms.id;清单壳块为 NULL
|
||||||
built_at TEXT
|
kind TEXT NOT NULL, -- 'bill' | 'norm'
|
||||||
|
block_xml TEXT NOT NULL, -- 块原文(GBK 解码后的 UTF-8 文本)
|
||||||
|
src_sha TEXT, -- 留档原件 sha256(追溯)
|
||||||
|
src_member TEXT -- 来源成员文件名(追溯)
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS ix_qld_parent ON qlist_dirs(parent_id, seq, id);
|
CREATE INDEX IF NOT EXISTS ix_bb_batch ON block_bank(batch_id);
|
||||||
CREATE TABLE IF NOT EXISTS qlist_items(
|
CREATE INDEX IF NOT EXISTS ix_bb_bill ON block_bank(bill_id);
|
||||||
id INTEGER PRIMARY KEY,
|
CREATE INDEX IF NOT EXISTS ix_bb_norm ON block_bank(norm_id);
|
||||||
dir_id INTEGER NOT NULL, -- 挂在哪个章节(qlist_dirs.id)
|
|
||||||
code TEXT, -- 编码
|
|
||||||
name TEXT NOT NULL, -- 名称
|
|
||||||
feature TEXT, -- 项目特征(多行)
|
|
||||||
unit TEXT, -- 单位
|
|
||||||
qty REAL, -- 工程量(空=默认 1.000)
|
|
||||||
seq INTEGER NOT NULL DEFAULT 0,
|
|
||||||
built_at TEXT
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_qli_dir ON qlist_items(dir_id, seq, id);
|
|
||||||
|
|||||||
@@ -270,3 +270,19 @@ CREATE TABLE IF NOT EXISTS adopt_src(
|
|||||||
adopted_at TEXT,
|
adopted_at TEXT,
|
||||||
UNIQUE(sid, row_type, row_id)
|
UNIQUE(sid, row_type, row_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- ===== 决策 279(2026-11-07 主人定「整体采纳=块进块出」):会话侧原文块库 =====
|
||||||
|
-- 采纳时从批次库 block_bank 整块拷入;导出=有块吐块。kind: 'bill'=清单壳块 / 'norm'=定额块。
|
||||||
|
CREATE TABLE IF NOT EXISTS s_block_bank(
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
sid INTEGER,
|
||||||
|
bill_id INTEGER, -- s_bills.id
|
||||||
|
norm_id INTEGER, -- kind='norm' 时指向 s_norms.id;清单壳块为 NULL
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
block_xml TEXT NOT NULL,
|
||||||
|
src_batch INTEGER,
|
||||||
|
src_sha TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS ix_sbb_sid ON s_block_bank(sid);
|
||||||
|
CREATE INDEX IF NOT EXISTS ix_sbb_bill ON s_block_bank(bill_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS ix_sbb_norm ON s_block_bank(norm_id);
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import io, zipfile
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
from api_harness import PERIOD_202607, post, server # noqa: F401
|
|
||||||
from test_manual_export import _seed_skeleton, _create_manual
|
|
||||||
|
|
||||||
def test_dbg(server):
|
|
||||||
_seed_skeleton(server)
|
|
||||||
sid = _create_manual(server) # 单单位既有流程
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
for i in z.infolist():
|
|
||||||
if not i.filename.lower().endswith(".xml"): continue
|
|
||||||
try:
|
|
||||||
ET.fromstring(z.read(i.filename)); print("OK ", i.filename)
|
|
||||||
except Exception as e:
|
|
||||||
print("BAD", i.filename, e)
|
|
||||||
t = z.read(i.filename).decode("utf-8", "replace").split("\n")
|
|
||||||
for k in range(26, min(36, len(t))):
|
|
||||||
print(" %3d| %s" % (k + 1, t[k][:140]))
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import io, sys, zipfile
|
|
||||||
from pathlib import Path
|
|
||||||
sys.path.insert(0, ".")
|
|
||||||
from api_harness import PERIOD_202607, post
|
|
||||||
import test_frame_skeleton as tf
|
|
||||||
|
|
||||||
# 复用 frame 夹具跑同流程,打印导出错误
|
|
||||||
srv = None
|
|
||||||
import subprocess, time, socket, shutil, os
|
|
||||||
root = Path("../_dbg_framesrv")
|
|
||||||
if root.exists(): shutil.rmtree(root)
|
|
||||||
srv = {"client": None}
|
|
||||||
# 直接调 fserver 夹具太绕——用 pytest 的夹具跑一次并在测试里打印
|
|
||||||
import api_harness
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 245 无头浏览器实测:工作台/后台「打开项目」弹框统一 + 单价类型落库 + 后台 Excel 通道。
|
|
||||||
|
|
||||||
真实 UI 路径(Playwright + 临时副本服务,生产库零接触):
|
|
||||||
① 工作台弹框:单价类型下拉 4 项默认预算综合单价、按钮行提示词逐字;
|
|
||||||
② 工作台必填:地区/建设单位不填被拦(提示文案与后台同款);
|
|
||||||
③ 工作台打开工程:选投标全费用 → session.db sessions.file_kind=3;刷新台账名称仍在;
|
|
||||||
④ 后台弹框:标题「打开项目」、字段名/顺序/按钮与工作台一致、提示词逐字;
|
|
||||||
⑤ 后台 Excel 通道:「导入Excel」展开 → 项目模板真实导入 → history.db 批次落库(FileKind/清单数);
|
|
||||||
⑥ 后台刷新:批次仍在列表里(数据持久化)。
|
|
||||||
跑法:python app/tests/_e2e_dialog245.py (产物 _dbg_e2e245/ 用完自清)
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import sqlite3
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
HERE = Path(__file__).resolve().parent
|
|
||||||
sys.path.insert(0, str(HERE))
|
|
||||||
from api_harness import _free_port, make_cos4 # noqa: E402
|
|
||||||
|
|
||||||
ROOT = HERE.parent.parent / "_dbg_e2e245"
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
METER = ("030405006001", "智能电度表", "1、三相;2、导轨式", "只", 20, 300)
|
|
||||||
LME = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
NAME = "e2e决策245工程"
|
|
||||||
XLSX_NAME = "e2e决策245Excel工程"
|
|
||||||
REMIND = ("提醒:建议在打开或导入项目时,先把工程独有的增加费(暗室、超高降效、预算包干、"
|
|
||||||
"垂直运输等)取消后再入库或工作台的审核对比,否则容易造成数据失真!")
|
|
||||||
|
|
||||||
_ok = []
|
|
||||||
|
|
||||||
|
|
||||||
def step(name, cond, detail=""):
|
|
||||||
_ok.append(bool(cond))
|
|
||||||
print((" ✓ " if cond else " ✗ ") + name + (" [%s]" % detail if detail else ""), flush=True)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if ROOT.exists():
|
|
||||||
shutil.rmtree(ROOT)
|
|
||||||
app_dst = ROOT / "CostReview" / "app"
|
|
||||||
shutil.copytree(HERE.parent, app_dst,
|
|
||||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
|
||||||
src_dir = ROOT / "后台需要导入的项目"
|
|
||||||
src_dir.mkdir()
|
|
||||||
lic = ROOT / "lic"
|
|
||||||
lic.mkdir()
|
|
||||||
(lic / "config.json").write_text('{"enforce": false}', encoding="utf-8")
|
|
||||||
port = _free_port()
|
|
||||||
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=str(lic))
|
|
||||||
log = open(ROOT / "server.log", "wb")
|
|
||||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
|
||||||
cwd=str(app_dst), env=env, stdout=log, stderr=subprocess.STDOUT)
|
|
||||||
base = "http://127.0.0.1:%d" % port
|
|
||||||
import httpx
|
|
||||||
cl = httpx.Client(base_url=base, timeout=120)
|
|
||||||
deadline = time.time() + 30
|
|
||||||
while time.time() < deadline:
|
|
||||||
try:
|
|
||||||
if cl.get("/api/license/status").status_code == 200:
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
time.sleep(0.3)
|
|
||||||
else:
|
|
||||||
proc.kill()
|
|
||||||
print(open(ROOT / "server.log", encoding="utf-8", errors="replace").read())
|
|
||||||
return 1
|
|
||||||
|
|
||||||
f1 = src_dir / "e2e245工程.cos4"
|
|
||||||
make_cos4(str(f1), NAME, [CAM, METER], [LME])
|
|
||||||
# 项目模板:走真实下载端点(带示例数据),再原样回导
|
|
||||||
tpl = src_dir / "整项目导入模板.xlsx"
|
|
||||||
tpl.write_bytes(cl.get("/api/session/manual/project_template").content)
|
|
||||||
|
|
||||||
def fill_common(pg, pre="o"):
|
|
||||||
pg.evaluate("""(pre) => {
|
|
||||||
const set=(id,v)=>{const s=document.getElementById(id); if(!s) return;
|
|
||||||
if(![...s.options].some(o=>o.value===v)){const o=document.createElement('option');
|
|
||||||
o.value=v;o.textContent=v;s.appendChild(o);} s.value=v;};
|
|
||||||
set(pre+'prov','广东省'); set(pre+'city','珠海市'); set(pre+'dist','香洲区');
|
|
||||||
document.getElementById(pre+'buid').value='E2E建设单位';
|
|
||||||
}""", pre)
|
|
||||||
|
|
||||||
from playwright.sync_api import sync_playwright
|
|
||||||
with sync_playwright() as p:
|
|
||||||
br = p.chromium.launch(channel="msedge", headless=True)
|
|
||||||
pg = br.new_page()
|
|
||||||
|
|
||||||
# ---------- ① 工作台弹框 ----------
|
|
||||||
pg.goto(base + "/workbench.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("button:has-text('打开项目')")
|
|
||||||
pg.wait_for_selector("#omask.on #ofile")
|
|
||||||
opts = pg.eval_on_selector_all("#okind option", "els=>els.map(e=>[e.value,e.textContent])")
|
|
||||||
step("① 工作台单价类型 4 项", [o[1] for o in opts] == ["预算综合单价", "投标综合单价", "预算全费用", "投标全费用"],
|
|
||||||
str(opts))
|
|
||||||
step("① 默认预算综合单价", pg.input_value("#okind") == "1", pg.input_value("#okind"))
|
|
||||||
tip = (pg.locator("#omRemind").inner_text() or "").strip()
|
|
||||||
step("① 工作台按钮行提示词逐字", tip == REMIND, tip[:20])
|
|
||||||
|
|
||||||
# ---------- ② 必填拦截 ----------
|
|
||||||
pg.set_input_files("#ofile", str(f1))
|
|
||||||
pg.fill("#oname", NAME)
|
|
||||||
pg.evaluate("setPeriod(document.querySelector('#oper'),'2026-07','2026-07')")
|
|
||||||
pg.click("#obtnGo")
|
|
||||||
pg.wait_for_timeout(300)
|
|
||||||
m = (pg.locator("#omsg").inner_text() or "").strip()
|
|
||||||
step("② 地区未填被拦", m == "请填写:地区(省/市/区)", m)
|
|
||||||
fill_common(pg,'o')
|
|
||||||
pg.evaluate("document.getElementById('obuid').value=''")
|
|
||||||
pg.click("#obtnGo")
|
|
||||||
pg.wait_for_timeout(300)
|
|
||||||
m = (pg.locator("#omsg").inner_text() or "").strip()
|
|
||||||
step("② 建设单位未填被拦", m == "请填写:建设单位", m)
|
|
||||||
|
|
||||||
# ---------- ③ 打开工程(单价类型=3 投标全费用)----------
|
|
||||||
fill_common(pg,'o')
|
|
||||||
pg.select_option("#okind", "3")
|
|
||||||
pg.click("#obtnGo")
|
|
||||||
ok_open = False
|
|
||||||
for _ in range(300):
|
|
||||||
pg.wait_for_timeout(100)
|
|
||||||
if "on" not in (pg.locator("#omask").get_attribute("class") or ""):
|
|
||||||
ok_open = True
|
|
||||||
break
|
|
||||||
step("③ 打开工程成功(弹框关闭)", ok_open,
|
|
||||||
(pg.locator("#omsg").inner_text() or "").strip())
|
|
||||||
sdb = str(ROOT / "CostReview" / "data" / "session.db")
|
|
||||||
con = sqlite3.connect(sdb)
|
|
||||||
row = con.execute("SELECT id, name, file_kind, bulid_unit FROM sessions WHERE TRIM(name)=?",
|
|
||||||
(NAME,)).fetchone()
|
|
||||||
con.close()
|
|
||||||
step("③ sessions.file_kind=3 落库", bool(row) and row[2] == 3, str(row))
|
|
||||||
# 刷新台账:名称仍在
|
|
||||||
pg.goto(base + "/sessions.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
step("③ 刷新后台账仍在", pg.locator("tr", has_text=NAME).count() >= 1)
|
|
||||||
|
|
||||||
# ---------- ④ 后台弹框与工作台一致 ----------
|
|
||||||
pg.goto(base + "/admin.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("#btnImp")
|
|
||||||
pg.wait_for_selector("#imask.on #ifile")
|
|
||||||
step("④ 标题=打开项目", (pg.locator("#impTitle").inner_text() or "").strip() == "打开项目",
|
|
||||||
pg.locator("#impTitle").inner_text())
|
|
||||||
step("④ 字段名一致",
|
|
||||||
("全国电子标书" in pg.locator("#irowFile").inner_text())
|
|
||||||
and pg.locator("span:has-text('工程名称 *')").count() >= 1
|
|
||||||
and pg.locator("span:has-text('基准期次 *')").count() >= 1,
|
|
||||||
pg.locator("#ileft").inner_text().replace("\n", "|")[:60])
|
|
||||||
step("④ 按钮 取消|导入Excel|打开",
|
|
||||||
(pg.locator("#impBtnX").inner_text() or "").strip() == "导入Excel"
|
|
||||||
and (pg.locator("#ibtnGo").inner_text() or "").strip() == "打开")
|
|
||||||
tip2 = (pg.locator("#imRemind").inner_text() or "").strip()
|
|
||||||
step("④ 后台提示词逐字", tip2 == REMIND, tip2[:20])
|
|
||||||
order = pg.evaluate("""() => ['#irowFile','#irowPer','#irowFk','#irowBuid'].map(s=>s)""")
|
|
||||||
step("④ 必填项齐全(单价类型行存在)", pg.locator("#irowFk").is_visible(), str(order))
|
|
||||||
|
|
||||||
# ---------- ⑤ 后台 Excel 通道 ----------
|
|
||||||
pg.fill("#iname", XLSX_NAME)
|
|
||||||
pg.evaluate("setPeriod(document.querySelector('#iper'),'2026-07','2026-07')")
|
|
||||||
fill_common(pg,'i')
|
|
||||||
pg.click("#impBtnX")
|
|
||||||
pg.wait_for_selector("#apanel", state="visible")
|
|
||||||
step("⑤ 树区展开、按钮同款",
|
|
||||||
pg.locator("#aitree button:has-text('单位模板')").count() == 1
|
|
||||||
and pg.locator("#aitree button:has-text('项目模板')").count() == 1
|
|
||||||
and pg.locator("#aitree button:has-text('项目导入')").count() == 1
|
|
||||||
and pg.locator("#aitree button:has-text('+单项工程')").count() == 1)
|
|
||||||
step("⑤ 树区展开后主按钮=创建工程",
|
|
||||||
(pg.locator("#ibtnGo").inner_text() or "").strip() == "创建工程",
|
|
||||||
pg.locator("#ibtnGo").inner_text())
|
|
||||||
pg.set_input_files("#iprojfile", str(tpl))
|
|
||||||
ok_x = False
|
|
||||||
for _ in range(400):
|
|
||||||
pg.wait_for_timeout(100)
|
|
||||||
if "on" not in (pg.locator("#imask").get_attribute("class") or ""):
|
|
||||||
ok_x = True
|
|
||||||
break
|
|
||||||
step("⑤ 项目模板导入成功(弹框关闭)", ok_x, (pg.locator("#aimsg").inner_text() or "").strip())
|
|
||||||
hdb = str(ROOT / "CostReview" / "data" / "history.db")
|
|
||||||
con = sqlite3.connect(hdb)
|
|
||||||
b = con.execute("SELECT id, Name, FileKind, BulidUnit, x_rows_bill FROM batches "
|
|
||||||
"WHERE Name=?", (XLSX_NAME,)).fetchone()
|
|
||||||
n_uw = n_sec = n_bill = 0
|
|
||||||
if b:
|
|
||||||
n_uw = con.execute("SELECT COUNT(*) FROM unit_works WHERE batch_id=?", (b[0],)).fetchone()[0]
|
|
||||||
n_sec = con.execute("SELECT COUNT(*) FROM sections WHERE batch_id=?", (b[0],)).fetchone()[0]
|
|
||||||
n_bill = con.execute("SELECT COUNT(*) FROM bills WHERE batch_id=?", (b[0],)).fetchone()[0]
|
|
||||||
con.close()
|
|
||||||
step("⑤ 批次落库(FileKind=1/1 单项/2 单位/清单>0)",
|
|
||||||
bool(b) and b[2] == 1 and n_sec == 1 and n_uw == 2 and n_bill > 0,
|
|
||||||
"batch=%s sec=%d uw=%d bill=%d" % (b, n_sec, n_uw, n_bill))
|
|
||||||
# 分部分项/措施项目两类都在
|
|
||||||
con = sqlite3.connect(hdb)
|
|
||||||
kinds = dict(con.execute("SELECT COALESCE(Kind,'item'), COUNT(*) FROM bills WHERE batch_id=? "
|
|
||||||
"GROUP BY COALESCE(Kind,'item')", (b[0],)).fetchall())
|
|
||||||
con.close()
|
|
||||||
step("⑤ 分部分项+措施项目都有", kinds.get("item", 0) > 0 and kinds.get("prelim", 0) > 0, str(kinds))
|
|
||||||
|
|
||||||
# ---------- ⑤b 价格类弹框不受影响(发布单位/附件/备注、按钮=开始导入、无导入Excel) ----------
|
|
||||||
pg.click(".tab[data-kind='market']")
|
|
||||||
pg.wait_for_timeout(400)
|
|
||||||
pg.click("#btnImp")
|
|
||||||
pg.wait_for_selector("#imask.on #ifile")
|
|
||||||
pg.wait_for_timeout(300)
|
|
||||||
step("⑤b 价格类:发布单位可见 / 单价类型隐藏 / 按钮=开始导入 / 无导入Excel",
|
|
||||||
pg.locator("#irowPub").is_visible() and not pg.locator("#irowFk").is_visible()
|
|
||||||
and (pg.locator("#ibtnGo").inner_text() or "").strip() == "开始导入"
|
|
||||||
and not pg.locator("#impBtnX").is_visible())
|
|
||||||
pg.click("#imask .btn:has-text('取消')")
|
|
||||||
|
|
||||||
# ---------- ⑥ 刷新持久化 ----------
|
|
||||||
pg.goto(base + "/admin.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.wait_for_timeout(800)
|
|
||||||
step("⑥ 刷新后列表里批次仍在", pg.locator("tr", has_text=XLSX_NAME).count() >= 1)
|
|
||||||
|
|
||||||
br.close()
|
|
||||||
proc.kill()
|
|
||||||
print("\n结果:%d/%d 通过" % (sum(_ok), len(_ok)), flush=True)
|
|
||||||
return 0 if all(_ok) else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
rc = main()
|
|
||||||
if os.environ.get("KEEP_E2E") != "1" and (rc == 0):
|
|
||||||
shutil.rmtree(ROOT, ignore_errors=True)
|
|
||||||
sys.exit(rc)
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 242 无头浏览器实测:导入入口一律按新文件处理。
|
|
||||||
|
|
||||||
真实 UI 路径走一遍(Playwright + 临时副本服务,生产库零接触):
|
|
||||||
① 首次导入工程 → 成功进台账;
|
|
||||||
② 同文件再导(改名副本同哈希)→ 弹框「与最近审核的:X重复导入,请删除后再导入」;
|
|
||||||
③ 同名不同文件 → 弹框「与最近审核的X名字重复,请修改名称后再导入」;
|
|
||||||
④ 台账删除该工程 → 行消失(等后台清理完成);
|
|
||||||
⑤ 再导同一份 → 成功、全新(行数一致、无旧数据);
|
|
||||||
⑥ 后台(admin)项目导入:同文件再导被拦、force 通道封死(API 层断言)。
|
|
||||||
跑法:python app/tests/_e2e_import_rules.py (产物 _dbg_e2e242/ 用完自清)
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import sqlite3
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
HERE = Path(__file__).resolve().parent
|
|
||||||
sys.path.insert(0, str(HERE))
|
|
||||||
from api_harness import _free_port, make_cos4 # noqa: E402
|
|
||||||
|
|
||||||
ROOT = HERE.parent.parent / "_dbg_e2e242b" # <root>/_dbg_e2e242b
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
METER = ("030405006001", "智能电度表", "1、三相;2、导轨式", "只", 20, 300)
|
|
||||||
LME = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
NAME = "e2e决策242工程"
|
|
||||||
|
|
||||||
_ok = []
|
|
||||||
|
|
||||||
|
|
||||||
def step(name, cond, detail=""):
|
|
||||||
_ok.append(bool(cond))
|
|
||||||
print((" ✓ " if cond else " ✗ ") + name + (" [%s]" % detail if detail else ""), flush=True)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if ROOT.exists():
|
|
||||||
shutil.rmtree(ROOT)
|
|
||||||
app_dst = ROOT / "CostReview" / "app"
|
|
||||||
shutil.copytree(HERE.parent, app_dst,
|
|
||||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
|
||||||
src_dir = ROOT / "后台需要导入的项目"
|
|
||||||
src_dir.mkdir()
|
|
||||||
lic = ROOT / "lic"
|
|
||||||
lic.mkdir()
|
|
||||||
(lic / "config.json").write_text('{"enforce": false}', encoding="utf-8")
|
|
||||||
port = _free_port()
|
|
||||||
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=str(lic))
|
|
||||||
log = open(ROOT / "server.log", "wb")
|
|
||||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
|
||||||
cwd=str(app_dst), env=env, stdout=log, stderr=subprocess.STDOUT)
|
|
||||||
base = "http://127.0.0.1:%d" % port
|
|
||||||
import httpx
|
|
||||||
cl = httpx.Client(base_url=base, timeout=60)
|
|
||||||
deadline = time.time() + 30
|
|
||||||
while time.time() < deadline:
|
|
||||||
try:
|
|
||||||
if cl.get("/api/license/status").status_code == 200:
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
time.sleep(0.3)
|
|
||||||
else:
|
|
||||||
proc.kill()
|
|
||||||
print(open(ROOT / "server.log", encoding="utf-8", errors="replace").read())
|
|
||||||
return 1
|
|
||||||
|
|
||||||
def b64(p):
|
|
||||||
return base64.b64encode(open(p, "rb").read()).decode("ascii")
|
|
||||||
|
|
||||||
# 造数:同一内容两份(原件+副本=同哈希);再一份同名不同内容
|
|
||||||
f1 = src_dir / "e2e工程原件.cos4"
|
|
||||||
make_cos4(str(f1), NAME, [CAM, METER], [LME])
|
|
||||||
f_copy = src_dir / "e2e工程副本.cos4"
|
|
||||||
shutil.copy(f1, f_copy)
|
|
||||||
f_diff = src_dir / "e2e工程改版.cos4"
|
|
||||||
make_cos4(str(f_diff), NAME, [CAM, METER, METER], [LME])
|
|
||||||
|
|
||||||
from playwright.sync_api import sync_playwright
|
|
||||||
with sync_playwright() as p:
|
|
||||||
br = p.chromium.launch(channel="msedge", headless=True) # 系统自带 Edge(chromium 下载不可用)
|
|
||||||
pg = br.new_page()
|
|
||||||
|
|
||||||
def open_and_import(fpath, name):
|
|
||||||
"""工作台「打开项目」弹框真实路径:选文件→填名→选期次→点打开;返回 #omsg 文本。"""
|
|
||||||
pg.goto(base + "/workbench.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("button:has-text('打开项目')")
|
|
||||||
pg.wait_for_selector("#omask.on #ofile")
|
|
||||||
pg.set_input_files("#ofile", str(fpath))
|
|
||||||
pg.fill("#oname", name)
|
|
||||||
pg.evaluate("setPeriod(document.querySelector('#oper'),'2026-07','2026-07')")
|
|
||||||
pg.click("#obtnGo")
|
|
||||||
# 成功=弹框关闭(omask 去 on);失败=omsg 出最终提示(不再是「正在…」)
|
|
||||||
for _ in range(200): # 最多 20 秒
|
|
||||||
pg.wait_for_timeout(100)
|
|
||||||
if "on" not in (pg.locator("#omask").get_attribute("class") or ""):
|
|
||||||
return ""
|
|
||||||
t = (pg.locator("#omsg").inner_text() or "").strip()
|
|
||||||
if t and not t.startswith("正在"):
|
|
||||||
return t
|
|
||||||
return (pg.locator("#omsg").inner_text() or "").strip()
|
|
||||||
|
|
||||||
def sess_count():
|
|
||||||
import urllib.request, json as _j
|
|
||||||
with urllib.request.urlopen(base + "/api/sessions") as r:
|
|
||||||
items = _j.load(r)["items"]
|
|
||||||
return [x for x in items if x.get("name") == NAME]
|
|
||||||
|
|
||||||
# ① 首次导入
|
|
||||||
t1 = open_and_import(f1, NAME)
|
|
||||||
step("① 首次导入成功(无拒绝提示)", t1 == "", t1)
|
|
||||||
step("① 台账出现该工程", len(sess_count()) == 1)
|
|
||||||
|
|
||||||
# ② 同文件(副本,同哈希)再导
|
|
||||||
t2 = open_and_import(f_copy, NAME)
|
|
||||||
step("② 同文件再导被拦", "与最近审核的:%s重复导入,请删除后再导入" % NAME == t2, t2)
|
|
||||||
|
|
||||||
# ③ 同名不同文件
|
|
||||||
t3 = open_and_import(f_diff, NAME)
|
|
||||||
step("③ 同名不同文件被拦",
|
|
||||||
"与最近审核的%s名字重复,请修改名称后再导入" % NAME == t3, t3)
|
|
||||||
|
|
||||||
# ④ 台账删除 → 行消失 + 等后台清理完
|
|
||||||
pg.goto(base + "/sessions.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.locator("tr", has_text=NAME).first.locator("a:has-text('删除')").click()
|
|
||||||
pg.wait_for_selector("#dlgok")
|
|
||||||
pg.click("#dlgok")
|
|
||||||
pg.wait_for_timeout(900)
|
|
||||||
step("④ 删除后台账行消失", len(sess_count()) == 0)
|
|
||||||
sessdb = ROOT / "CostReview" / "data" / "session.db"
|
|
||||||
for _ in range(100):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % sessdb, uri=True)
|
|
||||||
try:
|
|
||||||
n = con.execute("SELECT COUNT(*) FROM sessions WHERE TRIM(name)=?", (NAME,)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
if n == 0:
|
|
||||||
break
|
|
||||||
time.sleep(0.1)
|
|
||||||
|
|
||||||
# ⑤ 再导同一份 → 成功全新
|
|
||||||
t5 = open_and_import(f1, NAME)
|
|
||||||
step("⑤ 删除后再导成功", t5 == "", t5)
|
|
||||||
rows = cl.get("/api/session/rows", params={"session_id": sess_count()[0]["id"], "type": "bill"})
|
|
||||||
step("⑤ 新工程清单条数正常(3 = 2 分部分项 + 1 措施)", rows.json()["total"] == 3,
|
|
||||||
str(rows.json().get("total")))
|
|
||||||
|
|
||||||
# ⑥ 后台 admin 项目导入:同文件再导被拦 + force 封死
|
|
||||||
f3 = src_dir / "e2e后台工程.cos4"
|
|
||||||
make_cos4(str(f3), "e2e后台工程", [CAM], [LME])
|
|
||||||
up = cl.post("/api/admin/upload", json={"name": "e2e后台工程.cos4", "data": b64(f3)}).json()
|
|
||||||
body = {"path": up["path"], "kind": "project", "name": "e2e后台工程",
|
|
||||||
"province": "广东省", "city": "珠海市", "district": "香洲区",
|
|
||||||
"period_from": 2026 * 12 + 7, "period_to": 2026 * 12 + 7, "file_kind": 1}
|
|
||||||
r1 = cl.post("/api/admin/import", json=body)
|
|
||||||
step("⑥a 后台首次入库成功", r1.json().get("ok") is True, str(r1.json().get("msg"))[:60])
|
|
||||||
r2 = cl.post("/api/admin/import", json=body)
|
|
||||||
m = r2.json().get("msg", "")
|
|
||||||
step("⑥b 后台同文件再导被拦(与已入库的…重复导入)",
|
|
||||||
r2.json().get("ok") is False and "已入库" in m and "重复导入" in m
|
|
||||||
and "请删除后再导入" in m, m)
|
|
||||||
r3 = cl.post("/api/admin/import", json=dict(body, force=True))
|
|
||||||
step("⑥c force 强导通道已封死", r3.json().get("ok") is False, str(r3.json().get("msg"))[:60])
|
|
||||||
|
|
||||||
# ⑦ 决策 243:后台已入库的文件,工作台再打开 → 拦截「必须先删除后台的入库批次」
|
|
||||||
t7 = open_and_import(f3, "e2e后台工程X")
|
|
||||||
step("⑦ 前后台禁同文件(工作台向)",
|
|
||||||
t7 == "后台已入库同一份文件:e2e后台工程,必须先删除后台的入库批次后再导入", t7)
|
|
||||||
|
|
||||||
# ⑧ 决策 243:附件分「清单附件/工料机附件」两标签——清单采纳带附件进前者
|
|
||||||
import sqlite3 as _s
|
|
||||||
hdb = str(ROOT / "CostReview" / "data" / "history.db")
|
|
||||||
sdb = str(ROOT / "CostReview" / "data" / "session.db")
|
|
||||||
up7 = cl.post("/api/admin/upload", json={"name": "e2e后台工程.cos4", "data": b64(f3)}).json()
|
|
||||||
bid6 = _s.connect(hdb).execute(
|
|
||||||
"SELECT id FROM batches WHERE Name='e2e后台工程'").fetchone()[0]
|
|
||||||
finq = cl.post("/api/admin/batch/%d/inq" % bid6,
|
|
||||||
json={"name": "询价资料.zip",
|
|
||||||
"data": base64.b64encode(b"PK\x03\x04e2e-inq").decode()}).json()
|
|
||||||
con7 = _s.connect(hdb)
|
|
||||||
src_bill = con7.execute(
|
|
||||||
"SELECT id FROM bills WHERE batch_id=? AND Kind IS NULL", (bid6,)).fetchone()[0]
|
|
||||||
con7.close()
|
|
||||||
rbind = cl.post("/api/admin/batch/%d/inq/bind" % bid6,
|
|
||||||
json={"file_id": finq["id"], "bill_ids": [src_bill]})
|
|
||||||
# 工作台开同内容双胞胎件(前后台禁同文件)→ API 采纳该清单(UI 采纳按钮为既有功能)
|
|
||||||
from api_harness import twin_file as _twin
|
|
||||||
sid8 = cl.post("/api/audit", json={
|
|
||||||
"path": _twin({"root": str(ROOT)}, up7["path"], "e2e_att_t"),
|
|
||||||
"name": "e2e标签工程", "file_kind": 1,
|
|
||||||
"period_from": 2026 * 12 + 7, "period_to": 2026 * 12 + 7}).json()["session_id"]
|
|
||||||
con8 = _s.connect(sdb)
|
|
||||||
bill8 = con8.execute(
|
|
||||||
"SELECT id FROM s_bills WHERE session_id=? AND Kind IS NULL", (sid8,)).fetchone()[0]
|
|
||||||
con8.close()
|
|
||||||
radopt = cl.post("/api/session/bill/adopt",
|
|
||||||
json={"session_id": sid8, "bill_id": bill8,
|
|
||||||
"src_bill_id": src_bill}).json()
|
|
||||||
step("⑧a 清单采纳收附件(API)", radopt.get("ok") and radopt.get("n_att") == 1,
|
|
||||||
str(radopt.get("n_att")))
|
|
||||||
pg.goto(base + "/workbench.html?sid=%d" % sid8)
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("#btnInq")
|
|
||||||
pg.wait_for_selector("#inqTabs")
|
|
||||||
tb = (pg.locator("#inqTabBill").inner_text() or "").strip()
|
|
||||||
tl = (pg.locator("#inqTabLme").inner_text() or "").strip()
|
|
||||||
step("⑧b 标签计数:清单附件(1)/ 工料机附件(0)",
|
|
||||||
tb == "清单附件(1)" and tl == "工料机附件(0)", "%s | %s" % (tb, tl))
|
|
||||||
bt = (pg.locator("#btnInq").inner_text() or "").strip()
|
|
||||||
step("⑧b2 入口按钮名=「附件」(决策 243 补记)", bt == "附件(1)", bt)
|
|
||||||
n_sub = pg.locator("#inqTree .inqrow.sub").count()
|
|
||||||
step("⑧c 清单标签下列出该附件", n_sub == 1, str(n_sub))
|
|
||||||
step("⑧d 清单标签批量下载可用(默认全选)", pg.locator("#btnInqDl").is_enabled())
|
|
||||||
pg.click("#inqTabLme")
|
|
||||||
pg.wait_for_timeout(200)
|
|
||||||
n_sub2 = pg.locator("#inqTree .inqrow.sub").count()
|
|
||||||
step("⑧e 工料机标签为空", n_sub2 == 0 and "工料机附件" in pg.locator("#inqTree").inner_text())
|
|
||||||
step("⑧f 工料机标签批量下载禁用", pg.locator("#btnInqDl").is_disabled())
|
|
||||||
|
|
||||||
br.close()
|
|
||||||
|
|
||||||
cl.close()
|
|
||||||
proc.terminate()
|
|
||||||
try:
|
|
||||||
proc.wait(10)
|
|
||||||
except Exception:
|
|
||||||
proc.kill()
|
|
||||||
log.close()
|
|
||||||
shutil.rmtree(ROOT, ignore_errors=True) # 自清理(铁律 4)
|
|
||||||
print(("无头浏览器 %d 步全过" % len(_ok)) if all(_ok) else "存在失败步骤:%s" % _ok, flush=True)
|
|
||||||
return 0 if all(_ok) else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 245 截图取证:真实页面(临时副本服务)拍工作台/后台两个弹框,供主人过目。
|
|
||||||
|
|
||||||
跑法:python app/tests/_shot_245.py → 产物 app/tests/_shots_245/*.png(不留服务进程)
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
HERE = Path(__file__).resolve().parent
|
|
||||||
sys.path.insert(0, str(HERE))
|
|
||||||
from api_harness import _free_port # noqa: E402
|
|
||||||
|
|
||||||
ROOT = HERE.parent.parent / "_dbg_shot245"
|
|
||||||
OUT = HERE / "_shots_245"
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if ROOT.exists():
|
|
||||||
shutil.rmtree(ROOT)
|
|
||||||
app_dst = ROOT / "CostReview" / "app"
|
|
||||||
shutil.copytree(HERE.parent, app_dst,
|
|
||||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests", "_shots_245"))
|
|
||||||
lic = ROOT / "lic"
|
|
||||||
lic.mkdir()
|
|
||||||
(lic / "config.json").write_text('{"enforce": false}', encoding="utf-8")
|
|
||||||
OUT.mkdir(exist_ok=True)
|
|
||||||
port = _free_port()
|
|
||||||
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=str(lic))
|
|
||||||
log = open(ROOT / "server.log", "wb")
|
|
||||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
|
||||||
cwd=str(app_dst), env=env, stdout=log, stderr=subprocess.STDOUT)
|
|
||||||
base = "http://127.0.0.1:%d" % port
|
|
||||||
try:
|
|
||||||
import httpx
|
|
||||||
cl = httpx.Client(base_url=base, timeout=60)
|
|
||||||
deadline = time.time() + 30
|
|
||||||
while time.time() < deadline:
|
|
||||||
try:
|
|
||||||
if cl.get("/api/license/status").status_code == 200:
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
time.sleep(0.3)
|
|
||||||
from playwright.sync_api import sync_playwright
|
|
||||||
with sync_playwright() as p:
|
|
||||||
br = p.chromium.launch(channel="msedge", headless=True)
|
|
||||||
pg = br.new_page(viewport={"width": 1440, "height": 900})
|
|
||||||
pg.goto(base + "/workbench.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("button:has-text('打开项目')")
|
|
||||||
pg.wait_for_selector("#omask.on #ofile")
|
|
||||||
pg.wait_for_timeout(400)
|
|
||||||
pg.locator("#odlg").screenshot(path=str(OUT / "1_工作台_打开项目.png"))
|
|
||||||
# 后台
|
|
||||||
pg.goto(base + "/admin.html")
|
|
||||||
pg.wait_for_load_state("networkidle")
|
|
||||||
pg.click("#btnImp")
|
|
||||||
pg.wait_for_selector("#imask.on #ifile")
|
|
||||||
pg.wait_for_timeout(600)
|
|
||||||
pg.locator("#idlg").screenshot(path=str(OUT / "2_后台_打开项目.png"))
|
|
||||||
pg.click("#impBtnX")
|
|
||||||
pg.wait_for_selector("#apanel", state="visible")
|
|
||||||
pg.wait_for_timeout(400)
|
|
||||||
print(pg.evaluate("""()=>{
|
|
||||||
const g=s=>{const e=document.querySelector(s); if(!e) return null; const r=e.getBoundingClientRect();
|
|
||||||
return {w:Math.round(r.width),l:Math.round(r.left),ow:e.offsetWidth,sw:e.scrollWidth};};
|
|
||||||
return {dlg:g('#idlg'),body:g('#ibody'),left:g('#ileft'),panel:g('#apanel'),
|
|
||||||
foot:g('#idlg > div:last-child'),remind:g('#imRemind'),btn:g('#ibtnGo'),
|
|
||||||
cls:document.querySelector('#idlg').className,
|
|
||||||
st:document.querySelector('#idlg').style.width};
|
|
||||||
}"""), flush=True)
|
|
||||||
pg.locator("#idlg").screenshot(path=str(OUT / "3_后台_导入Excel树区.png"))
|
|
||||||
# 价格类(市场价)弹框:字段按 kind 条件显示,确认没被统一改坏
|
|
||||||
pg.click("#idlg button:has-text('取消')")
|
|
||||||
pg.wait_for_timeout(300)
|
|
||||||
pg.click(".tab[data-kind='market']")
|
|
||||||
pg.wait_for_timeout(400)
|
|
||||||
pg.click("#btnImp")
|
|
||||||
pg.wait_for_selector("#imask.on #ifile")
|
|
||||||
pg.wait_for_timeout(400)
|
|
||||||
pg.locator("#idlg").screenshot(path=str(OUT / "4_后台_市场价导入.png"))
|
|
||||||
br.close()
|
|
||||||
print("saved:", [p.name for p in OUT.glob("*.png")], flush=True)
|
|
||||||
return 0
|
|
||||||
finally:
|
|
||||||
proc.kill()
|
|
||||||
time.sleep(0.5)
|
|
||||||
shutil.rmtree(ROOT, ignore_errors=True)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,334 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""P0 接口测试夹具:把 app 源码拷进临时目录,随机端口起**真实服务子进程**。
|
|
||||||
|
|
||||||
为什么拷贝整个 app/:api_server / session_job 的库路径一律由 __file__ 推导
|
|
||||||
(<目录>/CostReview/data/history.db),把 app/ 原样拷到 tmp/CostReview/app 后,
|
|
||||||
同构目录自然指向临时库 —— 生产库(CostReview/data/*.db)零接触,也不用改任何被测代码。
|
|
||||||
|
|
||||||
门禁:副本没有 license_build_config.py(开发版路径),LICENSE_DATA_DIR 指到临时目录,
|
|
||||||
里面放 {"enforce": false} —— 与本地开发豁免同款,业务 API 全部放行。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import socket
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
import zipfile
|
|
||||||
from xml.sax.saxutils import quoteattr
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_APP_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) # .../CostReview/app
|
|
||||||
# 期次月序号(batches.x_period_start_m 口径:年*12+月)
|
|
||||||
PERIOD_202607 = 2026 * 12 + 7
|
|
||||||
|
|
||||||
|
|
||||||
def _free_port():
|
|
||||||
s = socket.socket()
|
|
||||||
s.bind(("127.0.0.1", 0))
|
|
||||||
port = s.getsockname()[1]
|
|
||||||
s.close()
|
|
||||||
return port
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ 造数
|
|
||||||
def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
|
|
||||||
proj_lmes=None, uw_lmes=None, zip_ts=None, uw_lme_attrs=None,
|
|
||||||
lme_rot=False, norm_extra=""):
|
|
||||||
"""构造最小可解析的 .cos4(zip 内 Project.xml + 单位工程 xml)。
|
|
||||||
|
|
||||||
bills: [(编码, 名称, 特征, 单位, 工程量, 单价)] —— 分部分项清单(自动配 1 条定额 + 定额消耗)
|
|
||||||
lmes: [(编码, 名称, 规格, 单位, 不含税价, 含税价)] —— 工料机(会进 lmes 与项目级汇总)
|
|
||||||
proj_lmes/uw_lmes: 分别覆盖项目级/单位级汇总的行(默认都用 lmes;
|
|
||||||
决策 108 测试用——造「仅项目工料机有」的场景)
|
|
||||||
uw_lme_attrs: {编码: ' Class="A" Weight="0"...'} 单位级 LME_SUM 追加的文字/标志属性
|
|
||||||
(定额单价专题·决策 259 flags 全采链路测试用;值须自带引号、前导空格)
|
|
||||||
另固定带:1 条措施清单(安全文明施工费)、项目特征 1 条、总造价 1234567.89。
|
|
||||||
"""
|
|
||||||
_uw_attr = (uw_lme_attrs or {}).get
|
|
||||||
lme_proj = "".join(
|
|
||||||
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s Unit=%s'
|
|
||||||
' Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s/>'
|
|
||||||
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
|
|
||||||
quoteattr(it[4]), quoteattr(it[5]))
|
|
||||||
for it in (lmes if proj_lmes is None else proj_lmes))
|
|
||||||
proj = (
|
|
||||||
'<ConstructionProject Name=%s FileKind="1" BulidUnit=%s>'
|
|
||||||
'<SummaryOfCost Total="1234567.89"/>'
|
|
||||||
'<InfoItem Name="工程类别" Value="房屋建筑"/>'
|
|
||||||
'<DivisionalAndElementalProject Number="SEC1" Name="主体工程">'
|
|
||||||
'<UnitWorks Number="UW1" FileName="UW1.xml"/></DivisionalAndElementalProject>'
|
|
||||||
'%s</ConstructionProject>'
|
|
||||||
% (quoteattr(proj_name), quoteattr(build_unit), lme_proj))
|
|
||||||
|
|
||||||
def _bill_xml(i, b):
|
|
||||||
num, name, attr, unit, qty, price = b
|
|
||||||
qty, price = float(qty), float(price)
|
|
||||||
lme0 = ((lmes[i % len(lmes)][0] if lme_rot else lmes[0][0])
|
|
||||||
if lmes else "000001") # lme_rot=多清单轮转引用不同 LME(各配现算量)
|
|
||||||
return (
|
|
||||||
'<WorkElement Number=%s Name=%s Attr=%s Unit=%s Quantity=%s Price=%s Total=%s>'
|
|
||||||
'<Norm Number="N-%d" Name=%s Unit=%s Quantity=%s Price="80" Total=%s NormIdentity="N%d" IsNorm="true">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number=%s Quantity="1.5"/>%s'
|
|
||||||
'</Norm></WorkElement>'
|
|
||||||
% (quoteattr(num), quoteattr(name), quoteattr(attr), quoteattr(unit),
|
|
||||||
quoteattr(str(qty)), quoteattr(str(price)), quoteattr(str(qty * price)),
|
|
||||||
i + 1, quoteattr(name + "安装"), quoteattr(unit),
|
|
||||||
quoteattr(str(qty)), quoteattr(str(qty * 80)), i + 1, quoteattr(lme0),
|
|
||||||
norm_extra))
|
|
||||||
|
|
||||||
uw = (
|
|
||||||
'<UnitWorks Number="UW1" Name="1号楼" Total="999999" Specialty="建筑工程">'
|
|
||||||
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
|
|
||||||
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>'
|
|
||||||
'<DivisionalWorks Number="D1" Name="安装工程" Code="03">%s</DivisionalWorks>'
|
|
||||||
'<Preliminaries><UnitWorksPreliminaryWorkElement Number="CS1"'
|
|
||||||
' Name="安全文明施工费" Attr="" Unit="项" Quantity="1" Price="50000" Total="50000"/>'
|
|
||||||
'</Preliminaries>%s</UnitWorks>'
|
|
||||||
% ("".join(_bill_xml(i, b) for i, b in enumerate(bills)),
|
|
||||||
"".join(
|
|
||||||
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s'
|
|
||||||
' Unit=%s Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s%s/>'
|
|
||||||
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
|
|
||||||
quoteattr(it[4]), quoteattr(it[5]), _uw_attr(it[0]) or "")
|
|
||||||
for it in (lmes if uw_lmes is None else uw_lmes))))
|
|
||||||
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
|
|
||||||
# zip_ts(决策 243 测试用):同内容不同 zip 时间戳 → 不同 sha256(前后台禁同文件后,
|
|
||||||
# 「同一份数据」要进两边就得是两个文件;解析结果不变,值断言不受影响)
|
|
||||||
if zip_ts is None:
|
|
||||||
z.writestr("Project.xml", proj.encode("utf-8"))
|
|
||||||
z.writestr("UW1.xml", uw.encode("utf-8"))
|
|
||||||
else:
|
|
||||||
for nm, data in (("Project.xml", proj.encode("utf-8")), ("UW1.xml", uw.encode("utf-8"))):
|
|
||||||
zi = zipfile.ZipInfo(nm, date_time=(2026, 1, 1, 0, 0, zip_ts))
|
|
||||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
z.writestr(zi, data)
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def make_swt(path, proj_name, units, total=None, tenderee="测试建设单位"):
|
|
||||||
"""构造最小可解析的 .SWT(深圳市工程造价数据交换标准 SJG77-2020)。
|
|
||||||
|
|
||||||
units: [{
|
|
||||||
"id","name","total","a","b","c","d","e","b1", # 单位工程与 Summary 五项
|
|
||||||
"bills":[{"code","name","feature","unit","qty","rate",
|
|
||||||
"norms":[{"code","name","unit","qty","rate","res":[(rid, usage)]}]}],
|
|
||||||
"resources":[{"id","code","name","spec","unit","rate","qty","kind",
|
|
||||||
"subs":[(rid, usage)]}],
|
|
||||||
"measures":[{"code","name","unit","total","children":[...]}] # 可嵌套
|
|
||||||
}]
|
|
||||||
⚠️ ResourceID 在 SWT 里是单位工程内部编号:不同 unit 可用同一个 id 指不同编码,
|
|
||||||
这正是回归要覆盖的重号场景。
|
|
||||||
"""
|
|
||||||
def attrs(d):
|
|
||||||
return " ".join("%s=%s" % (k, quoteattr(str(v))) for k, v in d.items() if v is not None)
|
|
||||||
|
|
||||||
def measure_xml(m):
|
|
||||||
return '<MeasureItem %s>%s</MeasureItem>' % (
|
|
||||||
attrs({"MeasureItemID": m.get("id", ""), "Code": m["code"], "Name": m["name"],
|
|
||||||
"Unit": m.get("unit", "项"), "Total": m.get("total", 0), "Sequence": 1}),
|
|
||||||
"".join(measure_xml(c) for c in m.get("children", [])))
|
|
||||||
|
|
||||||
ups = []
|
|
||||||
for u in units:
|
|
||||||
resources = "".join(
|
|
||||||
'<ResourceItem %s>%s</ResourceItem>' % (
|
|
||||||
attrs({"ResourceID": r["id"], "Code": r["code"], "Name": r["name"],
|
|
||||||
"Spec": r.get("spec", ""), "Unit": r.get("unit", ""),
|
|
||||||
"Rate": r.get("rate", 0), "Quantity": r.get("qty", 0), "Total": 0,
|
|
||||||
"CostKind": r.get("kind", 2), "Provider": 0,
|
|
||||||
"StandardCode": r["code"], "NormLibrary": ""}),
|
|
||||||
"".join('<ResourceUsage ResourceID=%s Usage=%s/>' % (
|
|
||||||
quoteattr(str(rid)), quoteattr(str(usage))) for rid, usage in r.get("subs", [])))
|
|
||||||
for r in u.get("resources", []))
|
|
||||||
bills = "".join(
|
|
||||||
'<BQItem %s><Norms>%s</Norms></BQItem>' % (
|
|
||||||
attrs({"BQItemID": b.get("id", ""), "Code": b["code"], "Name": b["name"],
|
|
||||||
"Feature": b.get("feature", ""), "Unit": b["unit"], "Quantity": b["qty"],
|
|
||||||
"Rate": b["rate"], "Total": round(float(b["qty"]) * float(b["rate"]), 2),
|
|
||||||
"Sequence": 1}),
|
|
||||||
"".join(
|
|
||||||
'<NormItem %s>%s</NormItem>' % (
|
|
||||||
attrs({"NormItemID": n.get("id", ""), "Code": n["code"], "Name": n["name"],
|
|
||||||
"Unit": n["unit"], "Quantity": n["qty"], "Rate": n["rate"],
|
|
||||||
"Total": round(float(n["qty"]) * float(n["rate"]), 2), "Sequence": 1}),
|
|
||||||
"".join('<NormResUsageItem ResourceID=%s Usage=%s/>' % (
|
|
||||||
quoteattr(str(rid)), quoteattr(str(usage)))
|
|
||||||
for rid, usage in n.get("res", [])))
|
|
||||||
for n in b.get("norms", [])))
|
|
||||||
for b in u.get("bills", []))
|
|
||||||
measures = "".join(measure_xml(m) for m in u.get("measures", []))
|
|
||||||
summary = "".join(
|
|
||||||
'<SummaryItem CostCode=%s CostKind=%s Name=%s Total=%s/>' % (
|
|
||||||
quoteattr(code), quoteattr(str(kind)), quoteattr(name),
|
|
||||||
quoteattr(str(u.get(key, 0))))
|
|
||||||
for code, kind, name, key in (("A", 8, "分部分项工程", "a"), ("B", 15, "措施项目", "b"),
|
|
||||||
("B1", 22, "安全文明施工费", "b1"),
|
|
||||||
("C", 16, "其他项目", "c"), ("D", 21, "增值税", "d"),
|
|
||||||
("E", 24, "工程造价", "e")))
|
|
||||||
ups.append(
|
|
||||||
'<UnitProject ProjectID=%s Name=%s Total=%s>'
|
|
||||||
'<Summary>%s</Summary>'
|
|
||||||
'<BQTable><BQTitle BQTitleID="1" Name="整个项目">%s</BQTitle></BQTable>'
|
|
||||||
'%s'
|
|
||||||
'<Resource>%s</Resource>'
|
|
||||||
'</UnitProject>' % (
|
|
||||||
quoteattr(str(u["id"])), quoteattr(u["name"]), quoteattr(str(u.get("total", 0))),
|
|
||||||
summary, bills,
|
|
||||||
('<MeasureTable><MeasureTitle MeasureTitleID="2" Name="措施项目">%s'
|
|
||||||
'</MeasureTitle></MeasureTable>' % measures) if measures else "",
|
|
||||||
resources))
|
|
||||||
if total is None:
|
|
||||||
total = sum(float(u.get("total", 0)) for u in units)
|
|
||||||
xml = ('<?xml version="1.0" encoding="utf-8"?>\r\n'
|
|
||||||
'<ConstructProject Code="001" Name=%s Tenderee=%s Standard="深圳市工程造价数据交换标准" '
|
|
||||||
'FileType="2" Version="SJG77-2020" TaxModel="1">'
|
|
||||||
'<TenderInfo Total=%s/>'
|
|
||||||
'<ProjectAddInfo><ProjectAddInfoItem Name="编制人" Value="测试"/></ProjectAddInfo>'
|
|
||||||
'<SingleProject ProjectID="1" Name="单项一" Total=%s>%s</SingleProject>'
|
|
||||||
'</ConstructProject>' % (
|
|
||||||
quoteattr(proj_name), quoteattr(tenderee), quoteattr(str(total)),
|
|
||||||
quoteattr(str(total)), "".join(ups)))
|
|
||||||
with open(path, "w", encoding="utf-8", newline="") as f:
|
|
||||||
f.write(xml)
|
|
||||||
return str(path)
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ 服务夹具
|
|
||||||
@pytest.fixture(scope="session")
|
|
||||||
def server(tmp_path_factory):
|
|
||||||
root = tmp_path_factory.mktemp("apisrv")
|
|
||||||
app_dst = root / "CostReview" / "app"
|
|
||||||
shutil.copytree(_APP_SRC, app_dst,
|
|
||||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
|
||||||
src_dir = root / "后台需要导入的项目" # api_server 的 SRC_DIR(PRJ_DIR 同级)
|
|
||||||
src_dir.mkdir()
|
|
||||||
lic = root / "lic"
|
|
||||||
lic.mkdir()
|
|
||||||
(lic / "config.json").write_text('{"enforce": false}', encoding="utf-8")
|
|
||||||
port = _free_port()
|
|
||||||
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=str(lic))
|
|
||||||
log = open(root / "server.log", "wb")
|
|
||||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
|
||||||
cwd=str(app_dst), env=env, stdout=log,
|
|
||||||
stderr=subprocess.STDOUT)
|
|
||||||
client = httpx.Client(base_url="http://127.0.0.1:%d" % port, timeout=60)
|
|
||||||
deadline = time.time() + 30
|
|
||||||
while time.time() < deadline:
|
|
||||||
try:
|
|
||||||
if client.get("/api/license/status").status_code == 200:
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
if proc.poll() is not None:
|
|
||||||
raise RuntimeError("测试服务进程退出,日志:\n" +
|
|
||||||
open(root / "server.log", encoding="utf-8",
|
|
||||||
errors="replace").read())
|
|
||||||
time.sleep(0.3)
|
|
||||||
else:
|
|
||||||
proc.terminate()
|
|
||||||
raise RuntimeError("测试服务 30s 未就绪,日志:\n" +
|
|
||||||
open(root / "server.log", encoding="utf-8",
|
|
||||||
errors="replace").read())
|
|
||||||
yield {"client": client, "root": root, "src_dir": src_dir, "port": port,
|
|
||||||
"db": str(root / "CostReview" / "data" / "history.db"),
|
|
||||||
"sessdb": str(root / "CostReview" / "data" / "session.db"),
|
|
||||||
"log": str(root / "server.log")}
|
|
||||||
client.close()
|
|
||||||
proc.terminate()
|
|
||||||
try:
|
|
||||||
proc.wait(10)
|
|
||||||
except Exception:
|
|
||||||
proc.kill()
|
|
||||||
log.close()
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ 请求小助手
|
|
||||||
def post(server, path, body):
|
|
||||||
r = server["client"].post(path, json=body)
|
|
||||||
assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:300])
|
|
||||||
return r.json()
|
|
||||||
|
|
||||||
|
|
||||||
def get(server, path, **params):
|
|
||||||
r = server["client"].get(path, params=params)
|
|
||||||
assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:300])
|
|
||||||
return r.json()
|
|
||||||
|
|
||||||
|
|
||||||
def fixture_file(server, name, proj_name, bills, lmes=()):
|
|
||||||
"""把 .cos4 造进副本的待导入目录(_allowed_source_path 只放行 SRC_DIR/uploads)。"""
|
|
||||||
return make_cos4(str(server["src_dir"] / name), proj_name, bills, lmes)
|
|
||||||
|
|
||||||
|
|
||||||
def twin_file(server, src_path, tag="twin"):
|
|
||||||
"""决策 243 测试用:把已有 zip 件重打包成**同内容不同哈希**的双胞胎件
|
|
||||||
(zip 时间戳平移),落 source_files 哈希命名——前后台禁同文件后,
|
|
||||||
同一份数据要进两边就用这一对(后台用原件、工作台用双胞胎)。"""
|
|
||||||
import hashlib
|
|
||||||
import io as _io
|
|
||||||
raw = open(src_path, "rb").read()
|
|
||||||
buf = _io.BytesIO()
|
|
||||||
with zipfile.ZipFile(_io.BytesIO(raw)) as zi, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for nm in zi.namelist():
|
|
||||||
zinfo = zipfile.ZipInfo(nm, date_time=(2026, 1, 1, 0, 0, 7))
|
|
||||||
zinfo.compress_type = zipfile.ZIP_DEFLATED
|
|
||||||
zo.writestr(zinfo, zi.read(nm))
|
|
||||||
tw = buf.getvalue()
|
|
||||||
dst = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_%s.cos4" % (hashlib.sha256(tw).hexdigest(), tag))
|
|
||||||
with open(dst, "wb") as f:
|
|
||||||
f.write(tw)
|
|
||||||
return dst
|
|
||||||
|
|
||||||
|
|
||||||
def drop_sessions(server, *names):
|
|
||||||
"""按工程名删台账(决策 242:导入入口同文件/同名一律拒绝——测试要重导同名,
|
|
||||||
必须先走真实删除接口清掉旧会话,顺带覆盖删除链路)。
|
|
||||||
删除是两段式:等后台清理线程把子表/备注清完再返回,避免毫秒级竞态。"""
|
|
||||||
import sqlite3
|
|
||||||
import time as _t
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
try:
|
|
||||||
ids = [r[0] for n in names
|
|
||||||
for r in con.execute("SELECT id FROM sessions WHERE TRIM(name)=?", (n,))]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
if not ids:
|
|
||||||
return
|
|
||||||
assert post(server, "/api/session/delete", {"ids": ids})["ok"] is True
|
|
||||||
for _ in range(100): # 最多等 5 秒:子表行清零 = 后台清理完成
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
try:
|
|
||||||
n = con.execute("SELECT COUNT(*) FROM s_bills WHERE session_id IN (%s)"
|
|
||||||
% ",".join("?" * len(ids)), ids).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
if n == 0:
|
|
||||||
return
|
|
||||||
_t.sleep(0.05)
|
|
||||||
raise AssertionError("后台清理超时:s_bills 仍有 %d 行" % n)
|
|
||||||
|
|
||||||
|
|
||||||
def price_xlsx_file(server, fname, rows, sheet="价格明细"):
|
|
||||||
"""造**标准模板** xlsx(2026-10-12 新口径,9 列表头严格)进待导入目录。
|
|
||||||
|
|
||||||
rows: [(目录路径, 编码, 名称, 规格, 单位, 不含税价, 税率, 含税价, 备注), ...]
|
|
||||||
目录路径用「/」分隔多级;空串 = 未分类。
|
|
||||||
"""
|
|
||||||
from openpyxl import Workbook
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = sheet
|
|
||||||
ws.append(["目录", "材料编码", "材料名称", "规格型号", "单位",
|
|
||||||
"不含税单价", "税率", "含税单价", "备注"])
|
|
||||||
for r in rows:
|
|
||||||
ws.append(list(r))
|
|
||||||
p = server["src_dir"] / fname
|
|
||||||
wb.save(p)
|
|
||||||
return str(p)
|
|
||||||
|
|
||||||
|
|
||||||
META = {"kind": "project", "province": "广东省", "city": "珠海市",
|
|
||||||
"district": "香洲区", "period_from": PERIOD_202607, "period_to": PERIOD_202607}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""把 lic_helpers 里的 fixtures 暴露给 pytest(fixtures 必须在 conftest 命名空间)。"""
|
|
||||||
from lic_helpers import client, keyring, priv_key # noqa: F401
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""license_client 测试辅助:本地生成 P-256 测试密钥、签名信封、假传输层。
|
|
||||||
|
|
||||||
⚠ 测试只用本地随机生成的密钥 / 包内 test-vectors 的 integration-test-only 公钥,
|
|
||||||
绝不进入生产 pinned_keys.json。
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from cryptography.hazmat.primitives import hashes, serialization
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
|
|
||||||
if SERVER_DIR not in sys.path:
|
|
||||||
sys.path.insert(0, SERVER_DIR)
|
|
||||||
|
|
||||||
from license_client.client import LicenseClient # noqa: E402
|
|
||||||
from license_client.store import JsonFileStore, SecretStore # noqa: E402
|
|
||||||
from license_client.verify import (FIELDSETS, LICENSE_V2, LEASE_V2, # noqa: E402
|
|
||||||
OPTIONAL_CERT_FIELDS, entitlements,
|
|
||||||
build_keyring)
|
|
||||||
|
|
||||||
IID = "11111111-2222-3333-4444-555555555555"
|
|
||||||
IID2 = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
|
|
||||||
NOW = datetime(2026, 10, 9, 3, 0, 0, tzinfo=timezone.utc)
|
|
||||||
Z = "%04d-%02d-%02dT%02d:%02d:%02dZ"
|
|
||||||
|
|
||||||
|
|
||||||
def z(dt):
|
|
||||||
return Z % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
|
|
||||||
|
|
||||||
|
|
||||||
def rfc(dt):
|
|
||||||
return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 信封构造
|
|
||||||
|
|
||||||
def canonical(payload, version):
|
|
||||||
def val(v):
|
|
||||||
# 构造方(模拟签发方):能签什么签什么——bool/负数等非法值也要能造出
|
|
||||||
# "带合法签名但字段非法"的恶意向量,把门是验证方(verify._check_payload)的事。
|
|
||||||
return v if isinstance(v, str) else str(v)
|
|
||||||
keys = list(FIELDSETS[version])
|
|
||||||
# 证书可选权益字段(2026-10-27):与 verify.canonical_bytes 同口径——
|
|
||||||
# 签发方带了才进 canonical,顺序固定追加在必填之后;缺省不出现。
|
|
||||||
if version == LICENSE_V2:
|
|
||||||
keys += [k for k in OPTIONAL_CERT_FIELDS if k in payload]
|
|
||||||
return "\n".join("%s=%s" % (k, val(payload[k])) for k in keys).encode("utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
def sign_b64(key, data):
|
|
||||||
der = key.sign(data, ec.ECDSA(hashes.SHA256()))
|
|
||||||
return base64.b64encode(der).decode("ascii").rstrip("=")
|
|
||||||
|
|
||||||
|
|
||||||
def cert_payload(key_id="integration-test-only", iid=IID, **over):
|
|
||||||
p = {"version": LICENSE_V2, "instance_id": iid, "license_id": 1, "customer_id": 2,
|
|
||||||
"product_id": 3, "starts_at": z(NOW), "expires_at": z(NOW + timedelta(days=365)),
|
|
||||||
"key_id": key_id}
|
|
||||||
p.update(over)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def lease_payload(key_id="integration-test-only", iid=IID,
|
|
||||||
state="active", server=None, ent=None, le=None, **over):
|
|
||||||
p = {"version": LEASE_V2, "instance_id": iid, "state": state,
|
|
||||||
"server_time": z(server or NOW),
|
|
||||||
"entitlement_expires_at": z(ent or NOW + timedelta(days=365)),
|
|
||||||
"lease_expires_at": z(le or (server or NOW) + timedelta(days=7)),
|
|
||||||
"key_id": key_id}
|
|
||||||
p.update(over)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def envelope(payload, key, kind, next_hb=60, sha=None):
|
|
||||||
"""kind="cert" → license-v2 信封;"lease" → lease-v2 信封。sha 传 "bad" 可篡改辅助校验。"""
|
|
||||||
version = LICENSE_V2 if kind == "cert" else LEASE_V2
|
|
||||||
data = canonical(payload, version)
|
|
||||||
env = {"payload": payload,
|
|
||||||
"signature": sign_b64(key, data),
|
|
||||||
"canonical_sha256": sha or hashlib.sha256(data).hexdigest()}
|
|
||||||
if kind == "cert":
|
|
||||||
env = {"version": version, **env}
|
|
||||||
else:
|
|
||||||
env = {"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": next_hb, **env}
|
|
||||||
return env
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 假设施
|
|
||||||
|
|
||||||
class MemSecret(SecretStore):
|
|
||||||
def __init__(self):
|
|
||||||
self.v = None
|
|
||||||
|
|
||||||
def get(self):
|
|
||||||
return self.v
|
|
||||||
|
|
||||||
def set(self, s):
|
|
||||||
self.v = s
|
|
||||||
|
|
||||||
def clear(self):
|
|
||||||
self.v = None
|
|
||||||
|
|
||||||
|
|
||||||
class FakeTransport:
|
|
||||||
"""脚本化传输层:依次消费 script(异常 / (status, headers, data));记录全部调用。"""
|
|
||||||
|
|
||||||
def __init__(self, script):
|
|
||||||
self.script = list(script)
|
|
||||||
self.calls = []
|
|
||||||
|
|
||||||
def __call__(self, method, url, body, headers):
|
|
||||||
self.calls.append({"method": method, "url": url, "body": dict(body),
|
|
||||||
"headers": dict(headers)})
|
|
||||||
item = self.script.pop(0) if self.script else (500, {}, {"error": {"code": "X", "message": "脚本耗尽"}})
|
|
||||||
if isinstance(item, Exception):
|
|
||||||
raise item
|
|
||||||
status, headers, data = item
|
|
||||||
return status, dict(headers), data
|
|
||||||
|
|
||||||
def keys(self):
|
|
||||||
return [c["headers"].get("Idempotency-Key") for c in self.calls]
|
|
||||||
|
|
||||||
|
|
||||||
def make_keyring(priv_key, key_id="integration-test-only", revoked=False):
|
|
||||||
pem = priv_key.public_key().public_bytes(
|
|
||||||
encoding=serialization.Encoding.PEM,
|
|
||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo)
|
|
||||||
return build_keyring([{"key_id": key_id, "public_key_pem": pem.decode("ascii"),
|
|
||||||
"revoked": revoked}])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def priv_key():
|
|
||||||
return ec.generate_private_key(ec.SECP256R1())
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def keyring(priv_key):
|
|
||||||
return make_keyring(priv_key)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def client(tmp_path, keyring):
|
|
||||||
"""已配置凭据的客户端:now 冻结在 NOW,sleep 记录不真等。"""
|
|
||||||
return make_client(tmp_path, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def make_client(tmp_path, keyring, transport=None, now_fn=None, max_attempts=4):
|
|
||||||
sleeps = []
|
|
||||||
tp = transport or FakeTransport([])
|
|
||||||
c = LicenseClient(
|
|
||||||
api_base="https://license.test",
|
|
||||||
state_store=JsonFileStore(str(tmp_path / "state.json")),
|
|
||||||
secret_store=MemSecret(),
|
|
||||||
keyring=keyring,
|
|
||||||
now_fn=now_fn or (lambda: NOW),
|
|
||||||
sleep_fn=lambda s: sleeps.append(s),
|
|
||||||
transport=tp,
|
|
||||||
max_attempts=max_attempts)
|
|
||||||
c._sleeps = sleeps
|
|
||||||
c._tp = tp
|
|
||||||
c.configure(IID, "LK-TEST-1", "SECRET-DO-NOT-LOG")
|
|
||||||
return c
|
|
||||||
|
|
||||||
|
|
||||||
def load_vectors():
|
|
||||||
p = os.path.join(HERE, "testdata", "license_test_vectors.json")
|
|
||||||
with open(p, encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 245(2026-11-01 主人定):后台「打开项目」Excel 通道 + 单价类型落库。
|
|
||||||
|
|
||||||
口径:①后台弹框与工作台同款,Excel 走同一套模板/校验,唯一区别=写 history.db 批次;
|
|
||||||
②/ api/admin/import_project 支持整项目模板(path)与目录树行内 Excel(tree);
|
|
||||||
③批次 FileKind=单价类型;④同名/单单位工程模板按既定口径拒绝。
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import importlib.util
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from api_harness import PERIOD_202607, get, post, server # noqa: F401
|
|
||||||
|
|
||||||
_mi_spec = importlib.util.spec_from_file_location(
|
|
||||||
"manual_import_src245", os.path.join(os.path.dirname(__file__), "..", "core", "manual_import.py"))
|
|
||||||
mi = importlib.util.module_from_spec(_mi_spec)
|
|
||||||
_mi_spec.loader.exec_module(mi)
|
|
||||||
|
|
||||||
|
|
||||||
def _save(server, fname, data):
|
|
||||||
p = str(server["src_dir"] / fname)
|
|
||||||
with open(p, "wb") as f:
|
|
||||||
f.write(data)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def _upload(server, path):
|
|
||||||
data = base64.b64encode(open(path, "rb").read()).decode("ascii")
|
|
||||||
r = post(server, "/api/admin/upload", {"name": os.path.basename(path), "data": data})
|
|
||||||
assert r.get("ok") is not False and r.get("path"), r
|
|
||||||
return r["path"]
|
|
||||||
|
|
||||||
|
|
||||||
def _body(name, up=None, **kw):
|
|
||||||
b = {"path": up or "", "name": name, "province": "广东省", "city": "珠海市", "district": "香洲区",
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607,
|
|
||||||
"bulid_unit": "某某建设单位", "file_kind": 3}
|
|
||||||
b.update(kw)
|
|
||||||
return b
|
|
||||||
|
|
||||||
|
|
||||||
def test_admin_excel_project_template(server):
|
|
||||||
p = _save(server, "整项目模板245.xlsx", mi.template_project_bytes())
|
|
||||||
up = _upload(server, p)
|
|
||||||
r = post(server, "/api/admin/import_project", _body("Excel项目245", up))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
bid = r["batch_id"]
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
row = con.execute("SELECT Name, FileKind, BulidUnit, x_province, x_period_start_m "
|
|
||||||
"FROM batches WHERE id=?", (bid,)).fetchone()
|
|
||||||
secs = con.execute("SELECT COUNT(*) FROM sections WHERE batch_id=?", (bid,)).fetchone()[0]
|
|
||||||
uws = con.execute("SELECT COUNT(*) FROM unit_works WHERE batch_id=?", (bid,)).fetchone()[0]
|
|
||||||
n_item = con.execute("SELECT COUNT(*) FROM bills WHERE batch_id=? AND Kind IS NULL",
|
|
||||||
(bid,)).fetchone()[0]
|
|
||||||
n_prelim = con.execute("SELECT COUNT(*) FROM bills WHERE batch_id=? AND Kind='prelim'",
|
|
||||||
(bid,)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
assert row == ("Excel项目245", 3, "某某建设单位", "广东省", PERIOD_202607), row
|
|
||||||
assert secs == 1 and uws == 2, (secs, uws)
|
|
||||||
assert n_item > 0 and n_prelim > 0, (n_item, n_prelim)
|
|
||||||
# 重复同名(不同文件)→ 拒绝(决策 242 后台口径);同文件先被哈希拦
|
|
||||||
p2 = _save(server, "整项目模板245_2.xlsx", mi.template_project_bytes() + b"0")
|
|
||||||
up2 = _upload(server, p2)
|
|
||||||
r2 = post(server, "/api/admin/import_project", _body("Excel项目245", up2))
|
|
||||||
assert r2["ok"] is False and "名字重复" in r2["msg"], r2
|
|
||||||
r3 = post(server, "/api/admin/import_project", _body("Excel项目245", up))
|
|
||||||
assert r3["ok"] is False and "重复导入" in r3["msg"], r3
|
|
||||||
|
|
||||||
|
|
||||||
def test_admin_excel_single_template_rejected(server):
|
|
||||||
p = _save(server, "单位模板245.xlsx", mi.template_bytes())
|
|
||||||
up = _upload(server, p)
|
|
||||||
r = post(server, "/api/admin/import_project", _body("单位模板工程245", up))
|
|
||||||
assert r["ok"] is False and "单位工程模板" in r["msg"], r
|
|
||||||
|
|
||||||
|
|
||||||
def test_admin_excel_tree_mode(server):
|
|
||||||
"""目录树 + 行内单位工程 Excel(同一份模板拆成两个单位工程)——与整项目模板同款落库。"""
|
|
||||||
p = _save(server, "单位树245.xlsx", mi.template_bytes())
|
|
||||||
up = _upload(server, p)
|
|
||||||
r = post(server, "/api/admin/import_project", _body(
|
|
||||||
"Excel树245", None,
|
|
||||||
tree=[{"name": "单项甲", "units": [{"name": "单位甲", "file": up}]},
|
|
||||||
{"name": "单项乙", "units": [{"name": "单位乙", "file": up}]}]))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
secs = con.execute("SELECT COUNT(*) FROM sections WHERE batch_id=?", (r["batch_id"],)).fetchone()[0]
|
|
||||||
uws = con.execute("SELECT COUNT(*) FROM unit_works WHERE batch_id=?", (r["batch_id"],)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
assert secs == 2 and uws == 2, (secs, uws)
|
|
||||||
|
|
||||||
|
|
||||||
def test_admin_excel_requires_common_fields(server):
|
|
||||||
p = _save(server, "整项目模板245b.xlsx", mi.template_project_bytes())
|
|
||||||
up = _upload(server, p)
|
|
||||||
for kw, msg in (({"file_kind": None}, "单价类型"), ({"bulid_unit": ""}, "建设单位"),
|
|
||||||
({"district": ""}, "地区")):
|
|
||||||
r = post(server, "/api/admin/import_project", _body("缺字段245" + msg, up, **kw))
|
|
||||||
assert r["ok"] is False and msg in r["msg"], (kw, r)
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 220(2026-10-27 主人定):③「两级都没有→补来源行」时,带子级的母行**子级组成整套随行带入**
|
|
||||||
(来源 lme_res → 会话 s_lme_res);①②(本单位有/仅项目有)绝不动子级——
|
|
||||||
主人原话「只有新加入的带子级工料机,本项目完全没有,采纳才会补进来」。函数级直调 _adopt_summary_rows。"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sc():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
|
||||||
taxp REAL, x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
|
||||||
taxp REAL, x_adopt_added INTEGER DEFAULT 0, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_hc():
|
|
||||||
hc = sqlite3.connect(":memory:")
|
|
||||||
hc.row_factory = sqlite3.Row
|
|
||||||
c = hc.cursor()
|
|
||||||
c.execute("CREATE TABLE bills(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT)")
|
|
||||||
c.execute("""CREATE TABLE lmes(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT,
|
|
||||||
Specification TEXT, Unit TEXT, Kind REAL, Quantity REAL, TaxRate REAL,
|
|
||||||
NoTaxPrice REAL, TaxPrice REAL)""")
|
|
||||||
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("INSERT INTO bills(id, batch_id, Number, Name) VALUES(900, 5, 'S1', '来源清单')")
|
|
||||||
# 两个来源工料机:M1=本项目完全没有的带子级母行(③+子级);M2=本项目已有同名规单(①/②,不动)
|
|
||||||
c.execute("INSERT INTO lmes(batch_id, Number, Name, Specification, Unit, NoTaxPrice, TaxPrice) "
|
|
||||||
"VALUES(5, 'M1', '灰浆搅拌机', '200L', '台班', 100.0, 100.0)")
|
|
||||||
c.execute("INSERT INTO lmes(batch_id, Number, Name, Specification, Unit, NoTaxPrice, TaxPrice) "
|
|
||||||
"VALUES(5, 'M2X', '电动夯实机', '20-62t·m', '台班', 50.0, 50.0)")
|
|
||||||
c.executemany("INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name) VALUES(5,'M1',?,?,?,?)",
|
|
||||||
[("C1", 2.0, 1, "人工"), ("C2", 3.0, 2, "电")])
|
|
||||||
hc.commit()
|
|
||||||
return hc
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_children_full_path():
|
|
||||||
sc, hc = _mk_sc(), _mk_hc()
|
|
||||||
hc.execute("CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
|
|
||||||
hc.execute("CREATE TABLE norm_res(norm_id INT, res_code TEXT, qty REAL)")
|
|
||||||
hc.execute("INSERT INTO norms(id, bill_id) VALUES(10, 900)")
|
|
||||||
hc.executemany("INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
|
|
||||||
[(10, "M1", 0.5), (10, "M2X", 0.2)])
|
|
||||||
hc.commit()
|
|
||||||
# 本项目已有 M2 同名规单(项目级),自带子级
|
|
||||||
sc.execute("""INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp)
|
|
||||||
VALUES(1, 'M2P', '电动夯实机', '20-62t·m', '台班', 3, 1, 60, 0, 60)""")
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(1,'M2P','OWN1',9,1,'本项目子级')")
|
|
||||||
sc.commit()
|
|
||||||
|
|
||||||
n, code_map = srv._adopt_summary_rows(sc, hc, 1, 101, 900)
|
|
||||||
# M1:③补两级 + 子级整套带入(决策 220)
|
|
||||||
m1 = sc.execute("SELECT ntp FROM s_lme_proj WHERE session_id=1 AND code='M1'").fetchone()
|
|
||||||
assert m1 and m1["ntp"] == 100.0
|
|
||||||
assert sc.execute("SELECT 1 FROM s_lme_uw WHERE session_id=1 AND uw_id=101 AND code='M1'").fetchone()
|
|
||||||
kids = [(r["res_code"], r["qty"]) for r in sc.execute(
|
|
||||||
"SELECT res_code, qty FROM s_lme_res WHERE session_id=1 AND p_code='M1' ORDER BY seq")]
|
|
||||||
assert kids == [("C1", 2.0), ("C2", 3.0)] # 来源子级整套进来
|
|
||||||
assert code_map.get("M1") == "M1"
|
|
||||||
# M2X:②按项目编码落地(M2P),两级零新增、子级**不动**(本项目子级 OWN1 唯一在场)
|
|
||||||
assert code_map.get("M2X") == "M2P"
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=1 AND p_code='M2P'").fetchone()[0] == 1
|
|
||||||
assert sc.execute("SELECT 1 FROM s_lme_res WHERE session_id=1 AND p_code='M2P' AND res_code='OWN1'").fetchone()
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 231 补记五 + 2026-11-04 主人定「数据只来源原数据」:
|
|
||||||
|
|
||||||
采纳补台班/配合比子级(`api_bill_adopt` 末段)**只认本次采纳来源批次**。
|
|
||||||
此前 SQL 漏 batch_id,实测把历史库 12 个批次的同码组成全灌进一个会话——
|
|
||||||
耗弹框展开 60 行(应为 5 行)、工料机汇总数量跟着翻 12 倍。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sc():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
div_id INT, Number TEXT, Name TEXT, Attr TEXT, Unit TEXT, Quantity REAL,
|
|
||||||
Price REAL, Total REAL, Kind TEXT, x_new INT, x_tdel INT, x_adopt INT,
|
|
||||||
x_price0 REAL, x_seq INT, src_remark TEXT, x_remark TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Number TEXT, Name TEXT,
|
|
||||||
Unit TEXT, Quantity REAL, Price REAL, Total REAL, x_tdel INT, x_adopt INT,
|
|
||||||
x_src_norm_id INT, x_adjust TEXT, qty_expr TEXT, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT,
|
|
||||||
qty REAL, express TEXT, x_ntp REAL, x_taxp REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INT, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT, k TEXT, v TEXT, PRIMARY KEY(scope,k))""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL,
|
|
||||||
taxrate REAL, taxp REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
|
||||||
taxp REAL)""")
|
|
||||||
c.execute("""INSERT INTO s_bills(id, session_id, uw_id, Number, Name, Attr, Unit,
|
|
||||||
Quantity, Price, Total, x_new, x_tdel, x_adopt)
|
|
||||||
VALUES(100,1,101,'B1','目标清单','','m',10,0,0,0,0,0)""")
|
|
||||||
# 本会话来源清单(src_self 分支用)
|
|
||||||
c.execute("""INSERT INTO s_bills(id, session_id, uw_id, Number, Name, Attr, Unit,
|
|
||||||
Quantity, Price, Total, x_new, x_tdel, x_adopt)
|
|
||||||
VALUES(101,1,101,'B2','本工程来源清单','','m',20,5,100,0,0,0)""")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_hc():
|
|
||||||
hc = sqlite3.connect(":memory:")
|
|
||||||
hc.row_factory = sqlite3.Row
|
|
||||||
c = hc.cursor()
|
|
||||||
c.execute("""CREATE TABLE bills(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT,
|
|
||||||
Attr TEXT, Unit TEXT, Price REAL, Quantity REAL)""")
|
|
||||||
c.execute("""CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT, Number TEXT, Name TEXT,
|
|
||||||
Unit TEXT, Quantity REAL, Price REAL, Total REAL, x_qty_coef REAL, x_adjust TEXT, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT,
|
|
||||||
qty REAL, express TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INT, name TEXT)""")
|
|
||||||
c.execute("""INSERT INTO bills(id, batch_id, Number, Name, Attr, Unit, Price, Quantity)
|
|
||||||
VALUES(900,5,'S1','来源清单','','m',3,100)""")
|
|
||||||
c.execute("""INSERT INTO norms(id, bill_id, Number, Name, Unit, Quantity, Price, Total,
|
|
||||||
x_qty_coef, x_adjust) VALUES(10,900,'D1','来源定额','m3',1,0,0,NULL,NULL)""")
|
|
||||||
c.execute("INSERT INTO norm_res(norm_id, res_code, qty, express) VALUES(10,'P1',0.5,NULL)")
|
|
||||||
# 批次 5 = 本次采纳来源;批次 6 = 别的工程的同码组成(不许被借)
|
|
||||||
c.executemany("INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name) VALUES(5,'P1',?,?,?,?)",
|
|
||||||
[("C1", 2.0, 0, "机上人工"), ("C2", 3.0, 1, "柴油")])
|
|
||||||
c.executemany("INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name) VALUES(6,'P1',?,?,?,?)",
|
|
||||||
[("C1", 9.0, 0, "别的批次人工"), ("C3", 7.0, 1, "别的批次电")])
|
|
||||||
hc.commit()
|
|
||||||
return hc
|
|
||||||
|
|
||||||
|
|
||||||
def _patch(monkeypatch):
|
|
||||||
monkeypatch.setattr(srv, "_adopt_summary_rows", lambda *a, **k: (0, {}))
|
|
||||||
monkeypatch.setattr(srv, "_adopt_bill_attachments", lambda *a, **k: 0)
|
|
||||||
monkeypatch.setattr(srv, "_gcl_coef_expr", lambda *a, **k: None)
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_children_only_from_source_batch(monkeypatch):
|
|
||||||
sc, hc = _mk_sc(), _mk_hc()
|
|
||||||
_patch(monkeypatch)
|
|
||||||
j = srv.api_bill_adopt(sc, hc, {"session_id": SID, "bill_id": 100, "src_bill_id": 900})
|
|
||||||
assert j.get("ok") is True, j
|
|
||||||
kids = [(r["res_code"], r["qty"]) for r in sc.execute(
|
|
||||||
"SELECT res_code, qty FROM s_lme_res WHERE session_id=1 AND p_code='P1' ORDER BY seq")]
|
|
||||||
assert kids == [("C1", 2.0), ("C2", 3.0)] # 只取批次 5 的一套
|
|
||||||
assert not sc.execute("SELECT 1 FROM s_lme_res WHERE res_code='C3'").fetchone()
|
|
||||||
assert not sc.execute("SELECT 1 FROM s_lme_res WHERE qty=9.0").fetchone()
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_self_source_never_borrows(monkeypatch):
|
|
||||||
"""来源=本会话清单:本会话组成只能来自自己的原件,绝不从批次库借。"""
|
|
||||||
sc, hc = _mk_sc(), _mk_hc()
|
|
||||||
_patch(monkeypatch)
|
|
||||||
sc.execute("INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, qty_expr)"
|
|
||||||
" VALUES(101,'D9','本工程定额','m3',1,0,0,NULL)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(1,'P1',0.5)")
|
|
||||||
sc.commit()
|
|
||||||
j = srv.api_bill_adopt(sc, hc, {"session_id": SID, "bill_id": 100, "src_self_bill_id": 101})
|
|
||||||
assert j.get("ok") is True, j
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=1").fetchone()[0] == 0
|
|
||||||
@@ -1,206 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 108(2026-10-18 主人改口径):采纳工料机按 **名称/规格/单位** 匹配两级汇总(编码不作匹配键):
|
|
||||||
① 单位工料机有 → 按单位编码落地,两级汇总零新增;
|
|
||||||
② 仅项目工料机有 → 按项目编码落地 + 项目行补进单位汇总(x_adopt_added=1);
|
|
||||||
③ 都没有 → 按采纳来源行补项目+单位两级(x_adopt_added=1)。
|
|
||||||
单价多条取除税价居中(升序中位)、只有 2 条取低价;合并隐藏行(x_merged_hide=1)不参选、
|
|
||||||
保留行按改后现值;后采纳按前采纳;消耗量(s_norm_res)随映射改码(n_recode)。
|
|
||||||
取代决策 74/75 的「编码命中→只更新不一致字段」采纳侧口径(导出 sync 机制不变)。"""
|
|
||||||
import hashlib
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
import api_harness as H
|
|
||||||
from api_harness import server # noqa: F401 (夹具须经导入注册)
|
|
||||||
from api_harness import get, post
|
|
||||||
|
|
||||||
SRC_LME = ("R9000001", "特制加固混凝土", "C30", "m3", "480", "545") # 历史定额消耗的工料机
|
|
||||||
SRC_BILL = ("S0001", "历史清单", "1、x", "m3", 100, 50)
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, params=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, params).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _hashed(server, tag, proj, bills, lmes, proj_lmes=None, uw_lmes=None, zip_ts=None):
|
|
||||||
"""造件并按 sha256_原名 落进 source_files(真实上传形态);zip_ts 区分同内容双件。"""
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("amlme_%s_raw.cos4" % tag)), proj, bills, lmes,
|
|
||||||
proj_lmes=proj_lmes, uw_lmes=uw_lmes, zip_ts=zip_ts)
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_amlme_%s.cos4" % (hashlib.sha256(raw).hexdigest(), tag))
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
return hp
|
|
||||||
|
|
||||||
|
|
||||||
def _import(server, tag, proj, bills, lmes, proj_lmes=None, uw_lmes=None):
|
|
||||||
hp = _hashed(server, tag, proj, bills, lmes, proj_lmes=proj_lmes, uw_lmes=uw_lmes)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
return hp
|
|
||||||
|
|
||||||
|
|
||||||
def _setup(server, tag, tgt_bills, tgt_lmes, proj_lmes=None, uw_lmes=None,
|
|
||||||
src_bills=(SRC_BILL,), src_lmes=(SRC_LME,)):
|
|
||||||
"""导入历史项目(批次)+打开目标工程会话(两份不同文件);返回 (sid, bill_id, src_id)。
|
|
||||||
决策 243:同一份文件前后台只能存在一边——目标件只进工作台(_hashed 不入库),
|
|
||||||
用 zip_ts 与后台件区分哈希(解析内容相同)。夹具接线:历史每条清单的定额消耗 lmes[0]。"""
|
|
||||||
hp_s = _import(server, tag + "_s", "历史项目-" + uuid.uuid4().hex[:6] + "-" + tag,
|
|
||||||
list(src_bills), list(src_lmes))
|
|
||||||
hp_t = _hashed(server, tag + "_t", "目标工程-" + uuid.uuid4().hex[:6] + "-" + tag,
|
|
||||||
list(tgt_bills), list(tgt_lmes), proj_lmes=proj_lmes, uw_lmes=uw_lmes, zip_ts=7)
|
|
||||||
audit = {"name": "目标工程-" + uuid.uuid4().hex[:6] + "-" + tag, "province": H.META["province"],
|
|
||||||
"city": H.META["city"], "district": H.META["district"],
|
|
||||||
"period_from": H.PERIOD_202607, "period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=hp_t))["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bill_id = [r[0] for r in rows if r[1] == tgt_bills[0][0]][0]
|
|
||||||
hc = sqlite3.connect("file:%s?mode=ro" % server["db"], uri=True)
|
|
||||||
src_id = hc.execute("SELECT id FROM bills WHERE Number=? AND Kind IS NULL "
|
|
||||||
"ORDER BY id DESC LIMIT 1", (src_bills[0][0],)).fetchone()[0]
|
|
||||||
hc.close()
|
|
||||||
return sid, bill_id, src_id
|
|
||||||
|
|
||||||
|
|
||||||
def _adopted_res_codes(server, bill_id):
|
|
||||||
return [r[0] for r in _q(server["sessdb"],
|
|
||||||
"SELECT res_code FROM s_norm_res WHERE norm_id IN "
|
|
||||||
"(SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1) ORDER BY id",
|
|
||||||
(bill_id,))]
|
|
||||||
|
|
||||||
def _wire(server, sid, bill_id, rows, level="both"):
|
|
||||||
"""决策 244 夹具接线(2026-11-01 主人定「只看现算」):目标工程定额**引用**被测码
|
|
||||||
(s_norm_res 插消耗行)并把两级汇总行补回(导入剪枝只留被引用码——被测码既然被引用,
|
|
||||||
真实导入时本来就会留库)。level: both=两级 / proj=仅项目级。"""
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
nid = con.execute("SELECT MIN(id) FROM s_norms WHERE bill_id=?", (bill_id,)).fetchone()[0]
|
|
||||||
uw = con.execute("SELECT uw_id FROM s_bills WHERE id=?", (bill_id,)).fetchone()[0]
|
|
||||||
for (code, name, spec, unit, ntp, taxp) in rows:
|
|
||||||
con.execute("INSERT OR IGNORE INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,1)",
|
|
||||||
(nid, code))
|
|
||||||
if level in ("both", "proj"):
|
|
||||||
con.execute("INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind,"
|
|
||||||
" qty, ntp, taxrate, taxp) VALUES(?,?,?,?,?,2,0,?,0,?)",
|
|
||||||
(sid, code, name, spec, unit, float(ntp), float(taxp)))
|
|
||||||
if level in ("both", "uw"):
|
|
||||||
con.execute("INSERT OR IGNORE INTO s_lme_uw(session_id, uw_id, code, name, spec, unit,"
|
|
||||||
" kind, qty, ntp, taxrate, taxp) VALUES(?,?,?,?,?,?,2,0,?,0,?)",
|
|
||||||
(sid, uw, code, name, spec, unit, float(ntp), float(taxp)))
|
|
||||||
con.commit()
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unit_match_two_prices_take_lower(server):
|
|
||||||
"""① 单位有同名称/规格/单位(2 条候选 500/450)→ 取**低价** R1000002;两级汇总零新增。"""
|
|
||||||
tgt = [("R1000001", "特制加固混凝土", "C30", "m3", "500", "560"),
|
|
||||||
("R1000002", "特制加固混凝土", "C30", "m3", "450", "510")]
|
|
||||||
sid, bill_id, src_id = _setup(server, "u2", [("T0001", "目标清单", "1、y", "m3", 200, 60)], tgt)
|
|
||||||
_wire(server, sid, bill_id, tgt) # 决策 244:被测码接定额引用
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True and r["n_sum"] == 0 and r["n_recode"] == 1, r
|
|
||||||
assert _adopted_res_codes(server, bill_id) == ["R1000002"]
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_uw WHERE session_id=? AND x_adopt_added=1",
|
|
||||||
(sid,))[0][0] == 0
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1",
|
|
||||||
(sid,))[0][0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_unit_match_three_prices_take_median(server):
|
|
||||||
"""① 3 条候选 420/450/500 → 取**居中** 450(R1000002)。"""
|
|
||||||
tgt = [("R1000001", "特制加固混凝土", "C30", "m3", "500", "560"),
|
|
||||||
("R1000002", "特制加固混凝土", "C30", "m3", "450", "510"),
|
|
||||||
("R1000003", "特制加固混凝土", "C30", "m3", "420", "480")]
|
|
||||||
sid, bill_id, src_id = _setup(server, "u3", [("T0001", "目标清单", "1、y", "m3", 200, 60)], tgt)
|
|
||||||
_wire(server, sid, bill_id, tgt) # 决策 244
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True and r["n_sum"] == 0, r
|
|
||||||
assert _adopted_res_codes(server, bill_id) == ["R1000002"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_proj_only_match_adds_unit_row(server):
|
|
||||||
"""② 仅项目工料机有 → 按项目编码 R2000001 落地 + 项目行补进单位汇总(x_adopt_added=1)。"""
|
|
||||||
tgt = [("R3000001", "普通混凝土", "C25", "m3", "400", "450")] # 单位级:不同物
|
|
||||||
proj = [("R2000001", "特制加固混凝土", "C30", "m3", "460", "520")] # 项目级:同物不同码
|
|
||||||
sid, bill_id, src_id = _setup(server, "pj", [("T0001", "目标清单", "1、y", "m3", 200, 60)],
|
|
||||||
tgt, proj_lmes=proj, uw_lmes=tgt)
|
|
||||||
_wire(server, sid, bill_id, proj, level="proj") # 决策 244:项目级被测码接引用
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True and r["n_sum"] == 1 and r["n_recode"] == 1, r
|
|
||||||
assert _adopted_res_codes(server, bill_id) == ["R2000001"]
|
|
||||||
row = _q(server["sessdb"], "SELECT code, x_adopt_added FROM s_lme_uw WHERE session_id=? AND code='R2000001'",
|
|
||||||
(sid,))
|
|
||||||
assert row and row[0][1] == 1, row # 项目行已补进单位汇总
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1",
|
|
||||||
(sid,))[0][0] == 0 # 项目级不动
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_match_adds_both_levels(server):
|
|
||||||
"""③ 都没有 → 来源行补两级(编码照带 R9000001,x_adopt_added=1),消耗量不改码。"""
|
|
||||||
tgt = [("R3000001", "普通混凝土", "C25", "m3", "400", "450")]
|
|
||||||
sid, bill_id, src_id = _setup(server, "nm", [("T0001", "目标清单", "1、y", "m3", 200, 60)], tgt)
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True and r["n_sum"] == 2 and r["n_recode"] == 0, r
|
|
||||||
assert _adopted_res_codes(server, bill_id) == ["R9000001"]
|
|
||||||
pj = _q(server["sessdb"], "SELECT name, spec, unit, x_adopt_added FROM s_lme_proj "
|
|
||||||
"WHERE session_id=? AND code='R9000001'", (sid,))
|
|
||||||
uw = _q(server["sessdb"], "SELECT name, spec, unit, x_adopt_added FROM s_lme_uw "
|
|
||||||
"WHERE session_id=? AND code='R9000001'", (sid,))
|
|
||||||
assert pj and pj[0][:3] == ("特制加固混凝土", "C30", "m3") and pj[0][3] == 1, pj
|
|
||||||
assert uw and uw[0][:3] == ("特制加固混凝土", "C30", "m3") and uw[0][3] == 1, uw
|
|
||||||
|
|
||||||
|
|
||||||
def test_later_adopt_follows_earlier(server):
|
|
||||||
"""后采纳按前采纳:前次③补的行已在两级汇总 → 后一次采纳被①命中,零新增零重复。"""
|
|
||||||
src_bills = [("S0001", "历史清单甲", "1、x", "m3", 100, 50),
|
|
||||||
("S0002", "历史清单乙", "1、x", "m3", 120, 55)]
|
|
||||||
tgt_bills = [("T0001", "目标清单甲", "1、y", "m3", 200, 60),
|
|
||||||
("T0002", "目标清单乙", "1、y", "m3", 220, 65)]
|
|
||||||
tgt = [("R3000001", "普通混凝土", "C25", "m3", "400", "450")]
|
|
||||||
sid, bill1, src1 = _setup(server, "later", tgt_bills, tgt, src_bills=src_bills)
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bill2 = [r[0] for r in rows if r[1] == "T0002"][0]
|
|
||||||
hc = sqlite3.connect("file:%s?mode=ro" % server["db"], uri=True)
|
|
||||||
src2 = hc.execute("SELECT id FROM bills WHERE Number='S0002' AND Kind IS NULL "
|
|
||||||
"ORDER BY id DESC LIMIT 1").fetchone()[0]
|
|
||||||
hc.close()
|
|
||||||
r1 = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill1,
|
|
||||||
"src_bill_id": src1})
|
|
||||||
assert r1["ok"] is True and r1["n_sum"] == 2, r1 # 首采:③补两级
|
|
||||||
r2 = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill2,
|
|
||||||
"src_bill_id": src2})
|
|
||||||
assert r2["ok"] is True and r2["n_sum"] == 0 and r2["n_recode"] == 0, r2 # 后采:①命中
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_proj WHERE session_id=? AND code='R9000001'",
|
|
||||||
(sid,))[0][0] == 1
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_uw WHERE session_id=? AND code='R9000001'",
|
|
||||||
(sid,))[0][0] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_merged_hidden_row_not_picked(server):
|
|
||||||
"""合并后为准:先走真实合并 API(R1000001 被隐藏→保留码 R1000002 改价 999),
|
|
||||||
采纳时被合并码按 recode_map 归并到保留码、按保留行改后现值选中。"""
|
|
||||||
tgt = [("R1000001", "特制加固混凝土", "C30", "m3", "450", "510"),
|
|
||||||
("R1000002", "特制加固混凝土", "C30", "m3", "500", "560")]
|
|
||||||
sid, bill_id, src_id = _setup(server, "mg", [("T0001", "目标清单", "1、y", "m3", 200, 60)], tgt)
|
|
||||||
_wire(server, sid, bill_id, tgt) # 决策 244
|
|
||||||
pj = {r[0]: r[1] for r in _q(server["sessdb"],
|
|
||||||
"SELECT code, id FROM s_lme_proj WHERE session_id=?", (sid,))}
|
|
||||||
r = post(server, "/api/session/lme/merge", {
|
|
||||||
"session_id": sid,
|
|
||||||
"groups": [{"sel": {"id": pj["R1000002"], "ntp": 999,
|
|
||||||
"taxrate": 3.5, "taxp": 1034.65},
|
|
||||||
"hide": [{"id": pj["R1000001"]}]}]})
|
|
||||||
assert r.get("ok") is True, r
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True and r["n_sum"] == 0, r
|
|
||||||
assert _adopted_res_codes(server, bill_id) == ["R1000002"] # 保留码+改后现值
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 273 e2e 回归:采纳外部定额的单价行组——行与列按本项目同区模板复制,
|
|
||||||
Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空);导出件同口径。"""
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, _HERE)
|
|
||||||
|
|
||||||
from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: F401,E402
|
|
||||||
|
|
||||||
from test_api_p1 import raw_post # noqa: E402
|
|
||||||
|
|
||||||
TPL_XML = ('<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00"'
|
|
||||||
' Total="100.00" Code="RGF" Remark="人工费"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="材料费" QtyFormula="_CLF" Rate="100.00"'
|
|
||||||
' Total="200.00" Code="CLF" Remark="材料费"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="子目单价" QtyFormula="1..3" Rate="100.00"'
|
|
||||||
' Total="350.00" Code="DJ" Remark=""/>')
|
|
||||||
EXT_XML = ('<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00"'
|
|
||||||
' Total="999.00" Code="RGF" Remark="人工费"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="子目单价" QtyFormula="1..2" Rate="100.00"'
|
|
||||||
' Total="777.00" Code="DJ" Remark=""/>')
|
|
||||||
|
|
||||||
# 本项目模板行组(3 行)与外部行组(2 行:人工费 Total 不同值、无材料费 → 验留空)
|
|
||||||
TPL_SIDE = [
|
|
||||||
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "人工费", "QtyFormula": "_RGF",
|
|
||||||
"Rate": "100.00", "Total": "100.00", "Code": "RGF", "Remark": "人工费"}},
|
|
||||||
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "材料费", "QtyFormula": "_CLF",
|
|
||||||
"Rate": "100.00", "Total": "200.00", "Code": "CLF", "Remark": "材料费"}},
|
|
||||||
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "子目单价", "QtyFormula": "1..3",
|
|
||||||
"Rate": "100.00", "Total": "350.00", "Code": "DJ", "Remark": ""}},
|
|
||||||
]
|
|
||||||
EXT_SIDE = [
|
|
||||||
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "人工费", "QtyFormula": "_RGF",
|
|
||||||
"Rate": "100.00", "Total": "999.00", "Code": "RGF", "Remark": "人工费"}},
|
|
||||||
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "子目单价", "QtyFormula": "1..2",
|
|
||||||
"Rate": "100.00", "Total": "777.00", "Code": "DJ", "Remark": ""}},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _import(server, fname, name, norm_extra=""):
|
|
||||||
"""造件+upload+audit 开会话(幂等:先删同名批次)。返回 (sid, db, sessdb)。"""
|
|
||||||
from api_harness import make_cos4
|
|
||||||
fix = server["root"] / "fixsrc"
|
|
||||||
fix.mkdir(exist_ok=True)
|
|
||||||
make_cos4(str(fix / fname), name,
|
|
||||||
[("030507008001", name + "清单项", "", "台", 3, 500)],
|
|
||||||
[("DTPL001", "模板定额", "", "m3", "10", "350")],
|
|
||||||
norm_extra=norm_extra)
|
|
||||||
import sqlite3 as _s
|
|
||||||
_con = _s.connect(server["db"])
|
|
||||||
try:
|
|
||||||
bids = [x[0] for x in _con.execute("SELECT id FROM batches WHERE name=?", (name,)).fetchall()]
|
|
||||||
finally:
|
|
||||||
_con.close()
|
|
||||||
for b in bids:
|
|
||||||
post(server, "/api/admin/batch/%d/delete" % b, {})
|
|
||||||
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
r = post(server, "/api/audit", dict(META, path=up["path"], name=name, file_kind=1))
|
|
||||||
assert r.get("ok") is True, r
|
|
||||||
return r["session_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_side_name_match(server): # noqa: F811
|
|
||||||
sid = _import(server, "决策273项目.cos4", "决策273项目", norm_extra=TPL_XML)
|
|
||||||
# 模板行组随造件导入自动入库(norm_side 通道 2026-11-03)——校验落到 s_norms.x_side
|
|
||||||
scon = __import__("sqlite3").connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
try:
|
|
||||||
bid = scon.execute("SELECT id FROM s_bills WHERE Name LIKE '%清单项%'").fetchone()[0]
|
|
||||||
xs = scon.execute("SELECT x_side FROM s_norms WHERE bill_id=? AND Number='N-1'",
|
|
||||||
(bid,)).fetchone()[0]
|
|
||||||
assert xs, "模板行组未入库"
|
|
||||||
finally:
|
|
||||||
scon.close()
|
|
||||||
# 外部件导入(批次;不再 audit 开会话——作为采纳源)
|
|
||||||
fix2 = server["root"] / "fixsrc"
|
|
||||||
make_cos4(str(fix2 / "决策273外部.cos4"), "决策273外部",
|
|
||||||
[("030507008002", "外部清单项", "", "台", 2, 400)],
|
|
||||||
[("DEXT001", "外部定额", "", "m3", "5", "777")])
|
|
||||||
make_cos4(str(fix2 / "决策273外部.cos4"), "决策273外部",
|
|
||||||
[("030507008002", "外部清单项", "", "台", 2, 400)],
|
|
||||||
[("DEXT001", "外部定额", "", "m3", "5", "777")],
|
|
||||||
norm_extra=EXT_XML)
|
|
||||||
up2 = raw_post(server, "/api/admin/upload", "决策273外部.cos4",
|
|
||||||
(fix2 / "决策273外部.cos4").read_bytes())
|
|
||||||
assert up2["ok"] is True, up2
|
|
||||||
r2 = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=up2["path"], name="决策273外部", file_kind=1))
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
con = __import__("sqlite3").connect(server["db"])
|
|
||||||
try:
|
|
||||||
src_bill = con.execute(
|
|
||||||
"SELECT id FROM bills WHERE batch_id=?", (r2["batch_id"],)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
# 采纳:目标清单(本项目)← 外部源清单
|
|
||||||
post(server, "/api/session/bill/adopt",
|
|
||||||
{"session_id": sid, "bill_id": bid, "src_bill_id": src_bill})
|
|
||||||
# 断言:采纳落库的新定额行 x_side=模板行组+Total 按 Name 匹配
|
|
||||||
scon2 = __import__("sqlite3").connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
scon2.row_factory = __import__("sqlite3").Row
|
|
||||||
try:
|
|
||||||
row = scon2.execute(
|
|
||||||
"SELECT x_side FROM s_norms WHERE bill_id=? AND x_adopt=1", (bid,)).fetchone()
|
|
||||||
finally:
|
|
||||||
scon2.close()
|
|
||||||
assert row and row["x_side"], "采纳行应带行组"
|
|
||||||
side = json.loads(row["x_side"])
|
|
||||||
rows = [x["attrs"] for x in side if x.get("tag") == "UnitPriceCalculationOfItem"]
|
|
||||||
names = [x["Name"] for x in rows]
|
|
||||||
assert names == ["人工费", "材料费", "子目单价"], names # 行与列=本项目模板(3 行)
|
|
||||||
by = {x["Name"]: x["Total"] for x in rows}
|
|
||||||
assert by["人工费"] == "999.00", by # Name 一致 → 外部值
|
|
||||||
assert by["子目单价"] == "777.00", by # Name 一致 → 外部值
|
|
||||||
assert by["材料费"] == "", by # 外部无同名行 → 留空
|
|
||||||
# 导出前:从件1 源文件提炼骨架入库(骨架回灌引擎需要骨架在库)
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
_up = str(next(iter(server["root"].rglob("*决策273项目.cos4")))) # 件1 副本(内容=原件)
|
|
||||||
_hc = __import__("sqlite3").connect(server["db"])
|
|
||||||
try:
|
|
||||||
_cs.seed_frame(_hc, _up, "骨架273")
|
|
||||||
finally:
|
|
||||||
_hc.close()
|
|
||||||
# 导出原格式:采纳定额块单价行同口径
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "name": "决策273项目",
|
|
||||||
"province": "广东省", "city": "珠海市",
|
|
||||||
"period_from": PERIOD_202607})
|
|
||||||
assert resp.status_code == 200, resp.text[:200]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
import re as _re
|
|
||||||
got = []
|
|
||||||
for n in z.namelist():
|
|
||||||
if n.endswith(".xml") and n != "Project.xml":
|
|
||||||
txt = z.read(n).decode("utf-8", "replace")
|
|
||||||
for mm in _re.finditer(r'<Norm\b[^>]*Name="外部清单项安装".*?</Norm>', txt, _re.S):
|
|
||||||
blk = mm.group(0)
|
|
||||||
got += [dict(_re.findall(r'(\w+)="([^"]*)"', x.group(1)))
|
|
||||||
for x in _re.finditer(r"<UnitPriceCalculationOfItem\b([^>]*?)/>", blk)]
|
|
||||||
if not got:
|
|
||||||
import sys as _sys
|
|
||||||
for n2 in z.namelist():
|
|
||||||
if n2.endswith(".xml"):
|
|
||||||
txt2 = z.read(n2).decode("utf-8", "replace")
|
|
||||||
print("=== 条目", n2, "len", len(txt2), file=_sys.stderr)
|
|
||||||
print(txt2[:1600], file=_sys.stderr)
|
|
||||||
assert got, "导出件应有采纳定额单价行"
|
|
||||||
byx = {x["Name"]: x["Total"] for x in got}
|
|
||||||
assert byx.get("人工费") == "999.00", byx
|
|
||||||
assert byx.get("子目单价") == "777.00", byx
|
|
||||||
assert byx.get("材料费") == "", byx # 留空
|
|
||||||
post(server, "/api/session/delete", {"ids": [sid]})
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 256(2026-11-06 主人定「乙 后端溯源」):采纳来源快照端点回归——
|
|
||||||
record 写/覆盖、get 溯源读(渲染行同形)、clear 清;跨重开定位的数据底座。
|
|
||||||
完整采纳→溯源插行链路由无头浏览器实测守门(台账 256 实测段),此处守端点契约。"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, _HERE)
|
|
||||||
|
|
||||||
from api_harness import get, post, server # noqa: F401,E402
|
|
||||||
|
|
||||||
SID = 1 # 测试库首个会话(写流程若未建会话,端点只按数值落库,无外键约束)
|
|
||||||
PATH = "/api/session/adopt/src"
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_src_record_get_clear(server):
|
|
||||||
src1 = {"src": "project", "src_id": 25552, "name": "旋挖钻成孔灌注桩 φ1500mm",
|
|
||||||
"unit": "m", "price": 1432.9, "proj": "不含10#、11#楼-北京师范大学珠海校区",
|
|
||||||
"period": "2026-11"}
|
|
||||||
# ① record → get:渲染行同形(溯源 tier / bill_id=src_id / 单价带回)
|
|
||||||
r = post(server, PATH, {"act": "record", "type": "bill", "row_id": 214,
|
|
||||||
"session_id": SID, "src": src1})
|
|
||||||
assert r["ok"], r
|
|
||||||
d = get(server, PATH, session_id=SID, type="bill", row_id=214)
|
|
||||||
assert d["ok"] and d["row"], d
|
|
||||||
assert d["row"]["tier"] == "溯源" and d["row"]["bill_id"] == 25552
|
|
||||||
assert d["row"]["price"] == 1432.9 and d["row"]["name"] == src1["name"]
|
|
||||||
# ② 重采纳覆盖:同键第二条来源 → get 回新值(一行只有一条在效采纳)
|
|
||||||
src2 = dict(src1, src_id=99, name="回填方", price=20.83)
|
|
||||||
post(server, PATH, {"act": "record", "type": "bill", "row_id": 214,
|
|
||||||
"session_id": SID, "src": src2})
|
|
||||||
d2 = get(server, PATH, session_id=SID, type="bill", row_id=214)
|
|
||||||
assert d2["row"]["name"] == "回填方" and d2["row"]["bill_id"] == 99, d2
|
|
||||||
# ③ clear → get None
|
|
||||||
post(server, PATH, {"act": "clear", "type": "bill", "row_id": 214, "session_id": SID})
|
|
||||||
d3 = get(server, PATH, session_id=SID, type="bill", row_id=214)
|
|
||||||
assert d3["ok"] and d3["row"] is None, d3
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_src_lme_shape_and_guards(server):
|
|
||||||
# 工料机形状:带 tax/price_tax/spec(src 透传)
|
|
||||||
r = post(server, PATH, {"act": "record", "type": "lme", "row_id": 7,
|
|
||||||
"session_id": SID,
|
|
||||||
"src": {"src": "info", "src_id": 42, "name": "柴油",
|
|
||||||
"spec": "0#", "unit": "kg", "price": 7.17,
|
|
||||||
"tax": 0.0, "price_tax": 7.17, "proj": "x", "period": "2026-11"}})
|
|
||||||
assert r["ok"], r
|
|
||||||
d = get(server, PATH, session_id=SID, type="lme", row_id=7)
|
|
||||||
assert d["row"]["spec"] == "0#" and d["row"]["price_tax"] == 7.17 and d["row"]["src"] == "info", d
|
|
||||||
# 守卫:type 非法 / row_id 缺 → 拒
|
|
||||||
r2 = post(server, PATH, {"act": "record", "type": "x", "row_id": 7,
|
|
||||||
"session_id": SID, "src": {"name": "y"}})
|
|
||||||
assert not r2["ok"], r2
|
|
||||||
d2 = get(server, PATH, session_id=SID, type="lme", row_id=999)
|
|
||||||
assert d2["ok"] and d2["row"] is None, d2
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""类似清单分组 v2 管线测试:条数守恒、名称层字集并组、关键词层(规则表)、
|
|
||||||
组价不一致。全部经真实接口(/api/session/similar、/api/session/inconsistent)。"""
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from api_harness import (drop_sessions, fixture_file, get, # noqa: F401
|
|
||||||
post, server)
|
|
||||||
|
|
||||||
BILLS = [
|
|
||||||
("010101001001", "镀锌钢管DN25", "1、螺纹连接", "m", 10, 100),
|
|
||||||
("010101002001", "镀锌钢管DN25", "1、螺纹连接", "m", 20, 150),
|
|
||||||
("010101003001", "镀锌钢管DN32", "1、螺纹连接", "m", 5, 120),
|
|
||||||
("020202001001", "钢筋混凝土", "C30泵送", "t", 3, 4000),
|
|
||||||
("020202002001", "混凝土钢筋", "C30泵送", "t", 2, 4200),
|
|
||||||
("030303001001", "欧姆龙PLC模块", "", "台", 1, 800),
|
|
||||||
] # 6 条可比(+1 条无定额措施项 → 被视图层排除)
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _setup(server):
|
|
||||||
# 决策 242:同名重导会被拒——先走真实删除清掉旧会话(等后台清完)再导
|
|
||||||
drop_sessions(server, "分组工程G")
|
|
||||||
pa = fixture_file(server, "grp.cos4", "分组工程G", BILLS)
|
|
||||||
sid = post(server, "/api/audit",
|
|
||||||
{"path": str(pa), "name": "分组工程G", "province": "广东省",
|
|
||||||
"city": "珠海市", "district": "香洲区",
|
|
||||||
"period_from": 2026 * 12 + 7, "file_kind": 1})["session_id"]
|
|
||||||
return sid
|
|
||||||
|
|
||||||
|
|
||||||
def _all_ids(resp):
|
|
||||||
return [row[0] for part in (resp["groups"] + resp["extra"])
|
|
||||||
for row in part["rows"]]
|
|
||||||
|
|
||||||
|
|
||||||
def test_group_conservation_and_name_layer(server):
|
|
||||||
sid = _setup(server)
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
assert rows["total"] == 7 # 6 可比 + 1 措施(单位=项被视图层滤掉)
|
|
||||||
resp = get(server, "/api/session/similar", session_id=sid)
|
|
||||||
ids = _all_ids(resp)
|
|
||||||
assert len(ids) == 6 and len(set(ids)) == 6 # 条数守恒:不多、不少、不重复
|
|
||||||
# 名称层:钢筋混凝土 与 混凝土钢筋(字集等价)同组
|
|
||||||
grp_rebar = [g for g in resp["groups"]
|
|
||||||
if any(r[2] == "钢筋混凝土" for r in g["rows"])]
|
|
||||||
assert len(grp_rebar) == 1 and grp_rebar[0]["n"] == 2
|
|
||||||
assert {r[2] for r in grp_rebar[0]["rows"]} == {"钢筋混凝土", "混凝土钢筋"}
|
|
||||||
# 名称近似的三条钢管并为一组(DN25×2 + DN32)
|
|
||||||
grp_pipe = [g for g in resp["groups"] if g["n"] == 3]
|
|
||||||
assert len(grp_pipe) == 1 and grp_pipe[0]["spread"] > 0
|
|
||||||
# 落单的 PLC 进「其他」组,固定殿后
|
|
||||||
assert resp["extra"] and resp["extra"][0]["cat"] == "其他"
|
|
||||||
assert resp["extra"][0]["n"] == 1
|
|
||||||
assert resp["extra"][0]["rows"][0][2] == "欧姆龙PLC模块"
|
|
||||||
# 组排序:按合计合价降序(钢筋组 8200 > 钢管组 370)
|
|
||||||
assert resp["groups"][0]["tsum"] >= resp["groups"][-1]["tsum"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_group_keyword_layer(server):
|
|
||||||
"""分组设置表(global.grp_rules):关键词首匹配 + 排除词 + <2 条不成组。"""
|
|
||||||
_setup(server) # 确保会话存在(同名原地续用)
|
|
||||||
con = sqlite3.connect(server["sessdb"]) # 直写设置表(设置无独立写接口)
|
|
||||||
try:
|
|
||||||
con.execute("""INSERT INTO s_settings(scope,k,v) VALUES('global','grp_rules',?)
|
|
||||||
ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v""",
|
|
||||||
(json.dumps([{"seq": 1, "name": "钢管组",
|
|
||||||
"keywords": "钢管 镀锌", "exclude": "塑料"}],
|
|
||||||
ensure_ascii=False),))
|
|
||||||
con.commit()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
resp = get(server, "/api/session/similar", session_id=_sid(server))
|
|
||||||
kw = [g for g in resp["groups"] if g.get("cat") == "钢管组"]
|
|
||||||
assert len(kw) == 1 and kw[0]["n"] == 3 # 关键词层优先收走三条钢管
|
|
||||||
assert {r[2] for r in kw[0]["rows"]} == {"镀锌钢管DN25", "镀锌钢管DN32"}
|
|
||||||
assert len(set(_all_ids(resp))) == len(_all_ids(resp)) == 6
|
|
||||||
# 清掉规则,不影响其他用例
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
try:
|
|
||||||
con.execute("DELETE FROM s_settings WHERE scope='global' AND k='grp_rules'")
|
|
||||||
con.commit()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _sid(server):
|
|
||||||
return _q(server["sessdb"], "SELECT id FROM sessions WHERE name='分组工程G'")[0][0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_inconsistent_same_spec_diff_price(server):
|
|
||||||
"""组价不一致:同名同特征、单价不同 → 一组,差% 按组统计。"""
|
|
||||||
sid = _setup(server)
|
|
||||||
resp = get(server, "/api/session/inconsistent", session_id=sid)
|
|
||||||
# 镀锌钢管DN25 两条同名同特征(100 vs 150)→ 一组,差 50%
|
|
||||||
g = [x for x in resp["groups"] if x["n"] == 2 and x["pmin"] == 100]
|
|
||||||
assert len(g) == 1 and g[0]["spread"] == 50.0
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""P0 接口回归:导入 / 会话 / 比对 / 检索 / 删除 / 行内编辑。
|
|
||||||
|
|
||||||
全部跑在一个隔离副本服务上(见 api_harness.py):生产库零接触;
|
|
||||||
库内断言用只读 sqlite 连接直查副本库,接口断言用 httpx。
|
|
||||||
"""
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from api_harness import (META, PERIOD_202607, drop_sessions, # noqa: F401
|
|
||||||
fixture_file, get, post, server)
|
|
||||||
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
METER = ("030405006001", "智能电度表", "1、三相;2、导轨式", "只", 20, 300)
|
|
||||||
LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
LME_CONC = ("000002", "C25混凝土", "泵送", "m3", "420", "474.6")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 只读查库
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _import(server, fname, name, bills, lmes, **kw):
|
|
||||||
fixture_file(server, fname, name, bills, lmes)
|
|
||||||
body = dict(META, path=str(server["src_dir"] / fname), name=name,
|
|
||||||
file_kind=kw.pop("file_kind", 1), **kw)
|
|
||||||
return post(server, "/api/admin/import", body)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 门禁放行
|
|
||||||
def test_gate_off_and_status(server):
|
|
||||||
st = get(server, "/api/license/status")
|
|
||||||
assert st["ok"] is True and st["data"]["enforce"] is False
|
|
||||||
d = get(server, "/api/dict")
|
|
||||||
assert isinstance(d, dict)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 导入
|
|
||||||
def test_import_project_ok(server):
|
|
||||||
r = _import(server, "proj_ok.cos4", "测试工程OK", [CAM, METER], [LME_CAM, LME_CONC])
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert r["schema"] == "2025标准"
|
|
||||||
assert r["n_bill"] == 3 # 2 分部分项 + 1 措施(导入不过滤,2026-10-07 决策)
|
|
||||||
assert r["n_lme"] == 2
|
|
||||||
row = _q(server["db"], "SELECT Name, x_rows_bill, x_rows_lme, x_total,"
|
|
||||||
" x_province, x_city, x_district, x_period_start_m"
|
|
||||||
" FROM batches WHERE id=?", (r["batch_id"],))[0]
|
|
||||||
assert row[0] == "测试工程OK" and row[1] == 3 and row[2] == 2
|
|
||||||
assert row[3] == 1234567.89 and row[4:7] == ("广东省", "珠海市", "香洲区")
|
|
||||||
assert row[7] == PERIOD_202607
|
|
||||||
# 层级:1 单项 + 1 单位工程 + 1 分部;措施清单 Kind=prelim
|
|
||||||
n_pre = _q(server["db"], "SELECT COUNT(*) FROM bills WHERE batch_id=? AND Kind='prelim'",
|
|
||||||
(r["batch_id"],))[0][0]
|
|
||||||
assert n_pre == 1
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM unit_works WHERE batch_id=?",
|
|
||||||
(r["batch_id"],))[0][0] == 1
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM norms WHERE bill_id IN"
|
|
||||||
" (SELECT id FROM bills WHERE batch_id=?)",
|
|
||||||
(r["batch_id"],))[0][0] >= 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_encrypted_rejected(server):
|
|
||||||
p = server["src_dir"] / "enc.cos4"
|
|
||||||
p.write_bytes(b"\x88\x7d" + b"\x00" * 64)
|
|
||||||
r = post(server, "/api/admin/import", dict(META, path=str(p), name="加密件T"))
|
|
||||||
assert r["ok"] is False and "加密" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_unknown_rejected(server):
|
|
||||||
p = server["src_dir"] / "garbage.cos4"
|
|
||||||
p.write_bytes(b"ABCDEF" + b"\x00" * 32)
|
|
||||||
r = post(server, "/api/admin/import", dict(META, path=str(p), name="乱码T"))
|
|
||||||
assert r["ok"] is False and "无法识别" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_xml_rejected(server):
|
|
||||||
# 2026-11-03:Projects 根现在是合法 ESCC2 格式(parse_esc),未知 XML 改用无名根
|
|
||||||
p = server["src_dir"] / "old.xml.cos4"
|
|
||||||
p.write_bytes(b'<?xml version="1.0" encoding="utf-8"?><UnknownRoot/>')
|
|
||||||
r = post(server, "/api/admin/import", dict(META, path=str(p), name="老xmlT"))
|
|
||||||
assert r["ok"] is False and "xml" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_outside_path_rejected(server):
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
dict(META, path="C:/Windows/win.ini", name="越权T"))
|
|
||||||
assert r["ok"] is False and "文件不存在" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_dup_rejected_and_fresh_after_delete(server):
|
|
||||||
"""决策 242:后台项目导入与工作台同规则——同文件/同名一律拒绝(无「仍要导入」),
|
|
||||||
删掉旧批次后才能再导。"""
|
|
||||||
b1 = _import(server, "dupA.cos4", "重复工程A", [CAM], [LME_CAM])
|
|
||||||
assert b1["ok"] is True
|
|
||||||
body = dict(META, path=str(server["src_dir"] / "dupA.cos4"),
|
|
||||||
name="重复工程A", file_kind=1)
|
|
||||||
r2 = post(server, "/api/admin/import", body)
|
|
||||||
assert r2["ok"] is False and r2.get("need_confirm") is None
|
|
||||||
assert "重复工程A" in r2["msg"] and ("请删除后再导入" in r2["msg"] or "请修改名称" in r2["msg"])
|
|
||||||
r3 = post(server, "/api/admin/import", dict(body, force=True)) # force 不再是通道
|
|
||||||
assert r3["ok"] is False
|
|
||||||
# 删批次 → 再导 = 全新(id 可能复用,看条数不看 id)
|
|
||||||
assert post(server, "/api/admin/batch/%d/delete" % b1["batch_id"], {})["ok"] is True
|
|
||||||
r4 = post(server, "/api/admin/import", body)
|
|
||||||
assert r4["ok"] is True
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE Name=?", ("重复工程A",))[0][0] == 1
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 会话(打开工程)
|
|
||||||
AUDIT_BODY = {"name": "审核工程A", "province": "广东省", "city": "珠海市",
|
|
||||||
"district": "香洲区", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607, "file_kind": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def test_audit_open_reuse_and_remark(server):
|
|
||||||
p = fixture_file(server, "auditA.cos4", "审核工程A", [CAM, METER],
|
|
||||||
[LME_CAM, LME_CONC])
|
|
||||||
body = dict(AUDIT_BODY, path=str(p))
|
|
||||||
r1 = post(server, "/api/audit", body)
|
|
||||||
assert r1["ok"] is True, r1
|
|
||||||
assert r1["n_bill"] == 3 and r1["n_uw"] == 1
|
|
||||||
sid = r1["session_id"]
|
|
||||||
# 清单行(8 列数组)与工料机行都能取到(GET,查询参数)
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
assert rows["total"] == 3 and all(len(r) == 8 for r in rows["rows"])
|
|
||||||
lmes = get(server, "/api/session/rows", session_id=sid, type="lme")
|
|
||||||
# 决策 209(2026-10-26 主人定):显示端与导出端一致——0 量行不显示。
|
|
||||||
# 夹具两条项目级汇总,C25混凝土无定额消耗现算 0 量 → 不出行,只剩网络摄像机(有消耗 1.5×量)。
|
|
||||||
assert lmes["total"] == 1 and lmes["rows"][0][1] == "000001"
|
|
||||||
# 写备注 → 同名/同文件重导一律拒绝(决策 242:导入入口按新文件处理,不再原地续用)
|
|
||||||
bill_id = [r[0] for r in rows["rows"] if r[1] == CAM[0]][0]
|
|
||||||
post(server, "/api/session/remark", {"bill_id": bill_id, "remark": "摄像机价格存疑"})
|
|
||||||
r2 = post(server, "/api/audit", body)
|
|
||||||
assert r2["ok"] is False and "名字重复" in r2["msg"] and "请修改名称" in r2["msg"]
|
|
||||||
# 删除(走真实接口,等后台清完)→ 再导同一份 = 全新工程:行数照旧、备注不复活
|
|
||||||
drop_sessions(server, "审核工程A")
|
|
||||||
r3 = post(server, "/api/audit", body)
|
|
||||||
assert r3["ok"] is True # id 可能复用,全新与否看下面数据
|
|
||||||
assert r3["n_bill"] == 3
|
|
||||||
sid3 = r3["session_id"]
|
|
||||||
recent = get(server, "/api/sessions")
|
|
||||||
assert recent["ok"] is True and isinstance(recent["items"], list)
|
|
||||||
item = next(x for x in recent["items"] if x["id"] == sid3)
|
|
||||||
assert item["all"] and item["all"][0]["id"] == sid3
|
|
||||||
rows3 = get(server, "/api/session/rows", session_id=sid3, type="bill")
|
|
||||||
assert rows3["total"] == 3 # 全新重写,无翻倍也无残留
|
|
||||||
remark = _q(server["sessdb"], "SELECT x_remark FROM s_bills"
|
|
||||||
" WHERE session_id=? AND Number=?", (sid3, CAM[0]))[0][0]
|
|
||||||
assert remark in (None, "") # 旧备注随删除清场,不带回新工程
|
|
||||||
n = _q(server["sessdb"], "SELECT COUNT(*) FROM s_remarks WHERE remark=?",
|
|
||||||
("摄像机价格存疑",))[0][0]
|
|
||||||
assert n == 0 # 持久表一并删净
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 比对
|
|
||||||
def test_search_bill_self_excluded(server):
|
|
||||||
# 被审工程自己也入库(同名同源)→ 比对结果必须排除自己,只出历史工程 B
|
|
||||||
pa = fixture_file(server, "searchA.cos4", "审核工程S", [CAM], [LME_CAM])
|
|
||||||
_import(server, "searchA.cos4", "审核工程S", [CAM], [LME_CAM]) # 自己入库
|
|
||||||
pb = fixture_file(server, "searchB.cos4", "历史工程B",
|
|
||||||
[(CAM[0], CAM[1], CAM[2], CAM[3], 8, 1800)],
|
|
||||||
[LME_CAM, LME_CONC])
|
|
||||||
_import(server, "searchB.cos4", "历史工程B",
|
|
||||||
[(CAM[0], CAM[1], CAM[2], CAM[3], 8, 1800)], [LME_CAM, LME_CONC])
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BODY, name="审核工程S",
|
|
||||||
path=str(pa)))["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
bill_id = [r[0] for r in rows["rows"] if r[1] == CAM[0]][0]
|
|
||||||
res = post(server, "/api/search", {"session_id": sid, "type": "bill",
|
|
||||||
"row_id": bill_id, "limit": 20})
|
|
||||||
assert res["ok"] is True and res["rows"], res
|
|
||||||
assert res["rows"][0]["tier"] == "精确"
|
|
||||||
assert res["rows"][0]["name"] == CAM[1]
|
|
||||||
assert all(r["proj"] != "审核工程S" for r in res["rows"]) # 自过滤:同名/同源不出现
|
|
||||||
|
|
||||||
|
|
||||||
def test_search_lme(server):
|
|
||||||
pa = fixture_file(server, "lmeA.cos4", "审核工程L", [CAM], [LME_CONC, LME_CAM]) # 决策 244:被搜码放 lmes[0]=定额消耗(剪枝后幸存)
|
|
||||||
_import(server, "lmeB.cos4", "历史工程LB", [METER], [LME_CAM, LME_CONC])
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BODY, name="审核工程L",
|
|
||||||
path=str(pa)))["session_id"]
|
|
||||||
lid = _q(server["sessdb"], "SELECT id FROM s_lme_proj WHERE session_id=?"
|
|
||||||
" AND name='C25混凝土'", (sid,))[0][0]
|
|
||||||
res = post(server, "/api/search", {"session_id": sid, "type": "lme",
|
|
||||||
"row_id": lid, "limit": 20})
|
|
||||||
assert res["ok"] is True and res["rows"], res
|
|
||||||
assert any(r.get("name") == "C25混凝土" for r in res["rows"])
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 独立检索
|
|
||||||
def test_hist_search_kw(server):
|
|
||||||
_import(server, "hist1.cos4", "检索工程H1",
|
|
||||||
[("030507009009", "红外热成像仪", "1、手持", "台", 2, 8000)],
|
|
||||||
[("000009", "热成像仪", "手持", "台", "7500", "8475")])
|
|
||||||
res = post(server, "/api/hist/search", {"target": "bill", "kw": "热成像"})
|
|
||||||
assert res["ok"] is True and res["total"] >= 1
|
|
||||||
assert any(r["name"] == "红外热成像仪" for r in res["rows"])
|
|
||||||
empty = post(server, "/api/hist/search", {"target": "bill", "kw": "不存在词zzz"})
|
|
||||||
assert empty["total"] == 0
|
|
||||||
lm = post(server, "/api/hist/search", {"target": "lme", "kw": "热成像"})
|
|
||||||
assert lm["ok"] is True and lm["total"] >= 1
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 删除级联
|
|
||||||
def test_delete_batch_cascade(server):
|
|
||||||
r = _import(server, "delme.cos4", "删除工程D", [CAM, METER], [LME_CAM])
|
|
||||||
bid = r["batch_id"]
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM bills WHERE batch_id=?",
|
|
||||||
(bid,))[0][0] == 3
|
|
||||||
d = post(server, "/api/admin/batch/%d/delete" % bid, {})
|
|
||||||
assert d.get("ok") is not False, d
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE id=?", (bid,))[0][0] == 0
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM bills WHERE batch_id=?", (bid,))[0][0] == 0
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM lmes WHERE batch_id=?", (bid,))[0][0] == 0
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM norms WHERE bill_id IN"
|
|
||||||
" (SELECT id FROM bills WHERE batch_id=?)", (bid,))[0][0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 行内编辑(白名单)
|
|
||||||
def test_batch_row_edit_whitelist(server):
|
|
||||||
r = _import(server, "editme.cos4", "编辑工程E", [CAM], [LME_CAM])
|
|
||||||
bid = r["batch_id"]
|
|
||||||
e = post(server, "/api/admin/batch/%d" % bid,
|
|
||||||
{"Name": "编辑工程E2", "BulidUnit": "新建设单位",
|
|
||||||
"x_period_start_m": 1}) # 期次不在白名单 → 忽略
|
|
||||||
assert e.get("ok") is not False, e
|
|
||||||
name, bu, p1 = _q(server["db"], "SELECT Name, BulidUnit, x_period_start_m"
|
|
||||||
" FROM batches WHERE id=?", (bid,))[0]
|
|
||||||
assert name == "编辑工程E2" and bu == "新建设单位"
|
|
||||||
assert p1 == PERIOD_202607 # 期次不可改(2026-09-28 定)
|
|
||||||
@@ -1,342 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""P1 接口回归:上传去重、价格原件挂接、询价附件全生命周期、采纳收集、
|
|
||||||
批次纳入/排除开关、清空模拟数据、数据源字典、信息价导入(一个块=一个批次)。"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import urllib.parse
|
|
||||||
|
|
||||||
from api_harness import (META, PERIOD_202607, fixture_file, price_xlsx_file, # noqa: F401
|
|
||||||
get, post, server)
|
|
||||||
|
|
||||||
LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 助手
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def raw_post(server, path, name, data):
|
|
||||||
"""二进制直传(application/octet-stream + X-File-Name),与服务端解析口径一致。"""
|
|
||||||
r = server["client"].post(
|
|
||||||
path, content=data,
|
|
||||||
headers={"Content-Type": "application/octet-stream",
|
|
||||||
"X-File-Name": urllib.parse.quote(name)})
|
|
||||||
assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:300])
|
|
||||||
return r.json()
|
|
||||||
|
|
||||||
|
|
||||||
def price_file(server, fname, blocks):
|
|
||||||
p = server["src_dir"] / fname
|
|
||||||
p.write_text('<html><head><meta charset="utf-8"></head><body>'
|
|
||||||
'<script>const DATA = %s;</script>'
|
|
||||||
% json.dumps(blocks, ensure_ascii=False), encoding="utf-8")
|
|
||||||
return str(p)
|
|
||||||
|
|
||||||
|
|
||||||
def import_project(server, fname, name, lmes=(LME_CAM,)):
|
|
||||||
fixture_file(server, fname, name,
|
|
||||||
[("030507008001", name + "清单项", "", "台", 1, 100)], lmes)
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=str(server["src_dir"] / fname), name=name, file_kind=1))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["batch_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def attach_dir(server):
|
|
||||||
return server["root"] / "CostReview" / "data" / "price_attachments"
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 上传设置
|
|
||||||
def test_settings_roundtrip(server):
|
|
||||||
r0 = get(server, "/api/admin/settings")
|
|
||||||
assert r0["ok"] is True and isinstance(r0["upload_max_mb"], int)
|
|
||||||
assert post(server, "/api/admin/settings", {"upload_max_mb": "abc"})["ok"] is False
|
|
||||||
assert post(server, "/api/admin/settings", {"upload_max_mb": -1})["ok"] is False
|
|
||||||
assert post(server, "/api/admin/settings", {"upload_max_mb": 100})["ok"] is True
|
|
||||||
assert get(server, "/api/admin/settings")["upload_max_mb"] == 100
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 公共上传(内容去重)
|
|
||||||
def test_upload_content_dedup(server):
|
|
||||||
data = b"%PDF-1.4 upload-dedup-test"
|
|
||||||
r1 = raw_post(server, "/api/admin/upload", "甲.pdf", data)
|
|
||||||
assert r1["ok"] is True and len(r1["sha256"]) == 64
|
|
||||||
r2 = raw_post(server, "/api/admin/upload", "乙.pdf", data) # 改名同内容
|
|
||||||
assert r2["ok"] is True and r2["sha256"] == r1["sha256"]
|
|
||||||
empty = raw_post(server, "/api/admin/upload", "空.pdf", b"")
|
|
||||||
assert empty["ok"] is False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 价格原件挂接
|
|
||||||
def test_attach_lifecycle(server):
|
|
||||||
b1 = import_project(server, "att1.cos4", "挂件工程一")
|
|
||||||
b2 = import_project(server, "att2.cos4", "挂件工程二")
|
|
||||||
data = b"%PDF-1.4 attach-test-bytes"
|
|
||||||
r = raw_post(server, "/api/admin/batch/%d/attach" % b1, "报价单.pdf", data)
|
|
||||||
assert r["ok"] is True and r["sha256"]
|
|
||||||
sha = r["sha256"]
|
|
||||||
fp = attach_dir(server) / ("%s_报价单.pdf" % sha)
|
|
||||||
assert fp.exists() # 磁盘只存一份
|
|
||||||
assert _q(server["db"], "SELECT x_attach_sha FROM batches WHERE id=?",
|
|
||||||
(b1,))[0][0] == sha
|
|
||||||
# 可执行文件拒收
|
|
||||||
bad = raw_post(server, "/api/admin/batch/%d/attach" % b1, "setup.exe", b"MZ...")
|
|
||||||
assert bad["ok"] is False and "可执行" in bad["msg"]
|
|
||||||
# 内容重复 → 不重复存盘,直接共享挂接
|
|
||||||
r2 = raw_post(server, "/api/admin/batch/%d/attach" % b2, "另一份.pdf", data)
|
|
||||||
assert r2["ok"] is True and "已有" in r2["msg"]
|
|
||||||
assert len(list(attach_dir(server).rglob(sha + "*"))) == 1
|
|
||||||
# 下载原样
|
|
||||||
dl = server["client"].get("/api/admin/file/%s" % sha)
|
|
||||||
assert dl.status_code == 200 and dl.content == data
|
|
||||||
# 删共享方 → 文件还在(b1 仍引用);删最后引用方 → 连记录带文件清掉
|
|
||||||
post(server, "/api/admin/batch/%d/delete" % b2, {})
|
|
||||||
assert fp.exists()
|
|
||||||
post(server, "/api/admin/batch/%d/delete" % b1, {})
|
|
||||||
assert not fp.exists()
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM attachments WHERE sha256=?",
|
|
||||||
(sha,))[0][0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 询价附件
|
|
||||||
def test_inq_lifecycle(server):
|
|
||||||
b1 = import_project(server, "inq1.cos4", "询价工程一")
|
|
||||||
b2 = import_project(server, "inq2.cos4", "询价工程二")
|
|
||||||
lme_b2 = _q(server["db"], "SELECT id FROM lmes WHERE batch_id=?", (b2,))[0][0]
|
|
||||||
data = b"PK\x03\x04" + b"inq-zip-bytes"
|
|
||||||
r = raw_post(server, "/api/admin/batch/%d/inq" % b1, "询价资料.zip", data)
|
|
||||||
assert r["ok"] is True and r["id"]
|
|
||||||
fid = r["id"]
|
|
||||||
# 同项目同内容 → 拒绝
|
|
||||||
dup = raw_post(server, "/api/admin/batch/%d/inq" % b1, "再传.zip", data)
|
|
||||||
assert dup["ok"] is False and "完全相同" in dup["msg"]
|
|
||||||
# 绑定:本项目的工料机可以;别家项目的工料机不行
|
|
||||||
lme_b1 = _q(server["db"], "SELECT id FROM lmes WHERE batch_id=?", (b1,))[0][0]
|
|
||||||
foreign = post(server, "/api/admin/batch/%d/inq/bind" % b1,
|
|
||||||
{"file_id": fid, "lme_ids": [lme_b2]})
|
|
||||||
assert foreign["ok"] is False and "不属于" in foreign["msg"]
|
|
||||||
bound = post(server, "/api/admin/batch/%d/inq/bind" % b1,
|
|
||||||
{"file_id": fid, "lme_ids": [lme_b1]})
|
|
||||||
assert bound["ok"] is True and bound["n"] == 1
|
|
||||||
lst = get(server, "/api/admin/batch/%d/inq" % b1)
|
|
||||||
assert lst["total_bound"] == 1 and lst["files"][0]["n"] == 1
|
|
||||||
# 解绑 → 附件保留;删附件 → 级联解绑 + 磁盘文件删除
|
|
||||||
un = post(server, "/api/admin/batch/%d/inq/unbind" % b1, {"lme_ids": [lme_b1]})
|
|
||||||
assert un["ok"] is True and un["n"] == 1
|
|
||||||
assert get(server, "/api/admin/batch/%d/inq" % b1)["total_bound"] == 0
|
|
||||||
post(server, "/api/admin/batch/%d/inq/bind" % b1, {"file_id": fid, "lme_ids": [lme_b1]})
|
|
||||||
# 决策 152:清单也能绑附件(bill_attach 同口径)+ /inq/bills 列表 + 附件角标含清单数
|
|
||||||
bill_b1 = _q(server["db"], "SELECT id FROM bills WHERE batch_id=?", (b1,))[0][0]
|
|
||||||
bb = post(server, "/api/admin/batch/%d/inq/bind" % b1, {"file_id": fid, "bill_ids": [bill_b1]})
|
|
||||||
assert bb["ok"] is True and bb["n"] == 1
|
|
||||||
bl = get(server, "/api/admin/batch/%d/inq/bills" % b1)
|
|
||||||
assert bl["ok"] is True and bl["rows"] and bl["rows"][0]["file_id"] == fid
|
|
||||||
lst2 = get(server, "/api/admin/batch/%d/inq" % b1)
|
|
||||||
assert lst2["files"][0]["n"] == 2 # 1 工料机 + 1 清单
|
|
||||||
unb = post(server, "/api/admin/batch/%d/inq/unbind" % b1, {"bill_ids": [bill_b1]})
|
|
||||||
assert unb["ok"] is True and unb["n"] == 1
|
|
||||||
stored = _q(server["db"], "SELECT stored_path FROM inquiry_files WHERE id=?", (fid,))[0][0]
|
|
||||||
fp = server["root"] / "CostReview" / "data" / stored
|
|
||||||
assert fp.exists()
|
|
||||||
dele = post(server, "/api/admin/batch/%d/inq/del" % b1, {"file_id": fid})
|
|
||||||
assert dele["ok"] is True and dele["n"] == 1
|
|
||||||
assert not fp.exists()
|
|
||||||
# 信息价批次不收询价附件(只服务项目)
|
|
||||||
px = price_xlsx_file(server, "inq_info.xlsx", [
|
|
||||||
("建筑材料/钢筋", "", "信息价2026年7月圆钢", "Φ12", "t", 4200, 3, 4326, "")])
|
|
||||||
info = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "询价测试信息价", "publisher": "测试发布"})
|
|
||||||
assert info["ok"] is True, info
|
|
||||||
info_bid = info["batches"][0] if info.get("batches") else _q(
|
|
||||||
server["db"], "SELECT id FROM batches WHERE Name='询价测试信息价'")[0][0]
|
|
||||||
rej = raw_post(server, "/api/admin/batch/%d/inq" % info_bid, "x.zip", data)
|
|
||||||
assert rej["ok"] is False and "只用于项目" in rej["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 采纳收集
|
|
||||||
def test_adopt_flow(server):
|
|
||||||
bid = import_project(server, "adopt.cos4", "采纳工程T")
|
|
||||||
fid = raw_post(server, "/api/admin/batch/%d/inq" % bid, "采纳附件.zip",
|
|
||||||
b"PK\x03\x04adopt")["id"]
|
|
||||||
pa = fixture_file(server, "adopt_a.cos4", "采纳工程T",
|
|
||||||
[("030507008001", "采纳工程T清单项", "", "台", 1, 100)], (LME_CAM,))
|
|
||||||
sid = post(server, "/api/audit",
|
|
||||||
dict(META, path=str(pa), name="采纳工程T"))["session_id"]
|
|
||||||
lmid = _q(server["sessdb"], "SELECT id FROM s_lme_proj WHERE session_id=? LIMIT 1",
|
|
||||||
(sid,))[0][0]
|
|
||||||
rec = post(server, "/api/adopt/record",
|
|
||||||
{"url": "/api/admin/inq/file/%d" % fid, "proj": "采纳工程T",
|
|
||||||
"session_id": sid, "lme_id": lmid})
|
|
||||||
assert rec["ok"] is True, rec
|
|
||||||
lst = get(server, "/api/adopt/list", sid=sid)
|
|
||||||
assert len(lst.get("atts") or []) == 1
|
|
||||||
assert any(a["id"] == lmid for a in (lst["atts"][0].get("lmes") or [])) \
|
|
||||||
if isinstance(lst["atts"][0], dict) and "lmes" in lst["atts"][0] else True
|
|
||||||
# 同行再采纳 = 换绑(旧事件先撤,不重复)
|
|
||||||
rec2 = post(server, "/api/adopt/record",
|
|
||||||
{"url": "/api/admin/inq/file/%d" % fid, "proj": "采纳工程T",
|
|
||||||
"session_id": sid, "lme_id": lmid})
|
|
||||||
assert rec2["ok"] is True
|
|
||||||
n = _q(server["db"], "SELECT COUNT(*) FROM adopt_hits WHERE sid=? AND lme_id=?",
|
|
||||||
(sid, lmid))[0][0]
|
|
||||||
assert n == 1
|
|
||||||
# 取消 → 事件撤 + 目录清
|
|
||||||
cac = post(server, "/api/adopt/cancel", {"session_id": sid, "lme_id": lmid})
|
|
||||||
assert cac["ok"] is True and cac["n_hit"] == 1
|
|
||||||
assert len(get(server, "/api/adopt/list", sid=sid).get("atts") or []) == 0
|
|
||||||
# 坏地址拒收
|
|
||||||
bad = post(server, "/api/adopt/record", {"url": "/x/y", "session_id": sid,
|
|
||||||
"lme_id": lmid})
|
|
||||||
assert bad["ok"] is False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 批次纳入/排除
|
|
||||||
def test_enabled_toggle(server):
|
|
||||||
bid = import_project(server, "enb.cos4", "开关工程G")
|
|
||||||
kw = {"target": "bill", "kw": "开关工程G清单项"}
|
|
||||||
assert post(server, "/api/hist/search", kw)["total"] == 1
|
|
||||||
post(server, "/api/admin/batch/%d/enabled" % bid, {"enabled": False})
|
|
||||||
assert post(server, "/api/hist/search", kw)["total"] == 0 # 排除后检索不见
|
|
||||||
post(server, "/api/admin/batch/%d/enabled" % bid, {"enabled": True})
|
|
||||||
assert post(server, "/api/hist/search", kw)["total"] == 1
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 清空模拟数据
|
|
||||||
def test_clear_mock_keeps_real(server):
|
|
||||||
real = import_project(server, "realmock.cos4", "真实保留工程R")
|
|
||||||
con = sqlite3.connect(server["db"]) # 直插一条模拟批次
|
|
||||||
try:
|
|
||||||
cur = con.execute("""INSERT INTO batches(kind, Name, is_mock, x_parser_ver)
|
|
||||||
VALUES('project', '模拟清空M', 1, 'test')""")
|
|
||||||
mock_id = cur.lastrowid
|
|
||||||
con.commit()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
r = post(server, "/api/admin/clear_mock", {})
|
|
||||||
assert r["ok"] is True and r["n_batch"] >= 1
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE id=?",
|
|
||||||
(mock_id,))[0][0] == 0
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE id=?",
|
|
||||||
(real,))[0][0] == 1 # 真实批次不受影响
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- Excel 价格导入
|
|
||||||
def test_price_xlsx_import(server):
|
|
||||||
"""2026-10-12 重设计:标准模板导入——名称默认文件名、目录建树、行挂叶子、Class=路径。"""
|
|
||||||
px = price_xlsx_file(server, "苗木2026年4-6月.xlsx", [
|
|
||||||
("苗木/乔木", "M1", "香樟", "胸径10cm", "株", 350, 0.03, 360.5, ""),
|
|
||||||
("苗木/灌木", "", "红花檵木", "高度80cm", "株", 25, 0.03, 25.75, "")])
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "publisher": "测试发布"}) # 不传 name → 默认文件名
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
bid = int(r["batches"][0])
|
|
||||||
row = _q(server["db"], "SELECT Name, x_period_start_m, x_period_end_m, x_rows_price"
|
|
||||||
" FROM batches WHERE id=?", (bid,))[0]
|
|
||||||
assert row[0] == "苗木2026年4-6月" # 名称默认 = 文件名(主人 2026-10-12 定)
|
|
||||||
assert row[1:3] == (24316, 24318) # 期次从文件名里认出
|
|
||||||
assert row[3] == 2
|
|
||||||
# 目录树:两个一级(苗木)+ 两个叶子(乔木/灌木);无未分类行(2026-10-14 主人定:导入不允许空目录)
|
|
||||||
d = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
assert d["ok"] is True and len(d["tree"]) == 1
|
|
||||||
top = d["tree"][0]
|
|
||||||
assert top["name"] == "苗木" and top["leaf"] is False and d["counts"][str(top["id"])] == 2
|
|
||||||
assert {c["name"] for c in top["children"]} == {"乔木", "灌木"}
|
|
||||||
assert all(c["leaf"] for c in top["children"])
|
|
||||||
assert d["n_uncat"] == 0
|
|
||||||
# 行挂叶子 + Class = 完整路径
|
|
||||||
pr = _q(server["db"], "SELECT p.Name, p.Class, p.dir_id FROM prices p"
|
|
||||||
" JOIN price_dirs d ON d.id=p.dir_id WHERE p.batch_id=?", (bid,))
|
|
||||||
assert ("香樟", "苗木/乔木", pr[0][2]) == (pr[0][0], pr[0][1], pr[0][2]) or pr[0][1] == "苗木/乔木"
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM prices WHERE batch_id=? AND (dir_id=0 OR dir_id IS NULL)",
|
|
||||||
(bid,))[0][0] == 0
|
|
||||||
# 与另一次导入同名称/规格/单位 → 同精确键(可互相比对)
|
|
||||||
px2 = price_xlsx_file(server, "另批.xlsx", [
|
|
||||||
("苗木/乔木", "M9", "香樟", "胸径10cm", "株", 999, 0.03, 999, "")])
|
|
||||||
post(server, "/api/admin/import", {"kind": "info", "path": px2, "name": "另批", "publisher": "测试发布"})
|
|
||||||
h = _q(server["db"], "SELECT COUNT(DISTINCT x_hash_exact), COUNT(*) FROM prices"
|
|
||||||
" WHERE Name='香樟' AND Specification='胸径10cm'")
|
|
||||||
assert h[0][0] == 1 and h[0][1] == 2
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 价格导入门禁(2026-10-14 主人定)
|
|
||||||
def test_price_import_rejects_empty_class(server):
|
|
||||||
"""整份校验:任意一行缺目录(Class)整份拒绝,不静默跳过(2026-10-14 主人定)。"""
|
|
||||||
px = price_xlsx_file(server, "缺目录2026年7月.xlsx", [
|
|
||||||
("建材/钢材", "C1", "圆钢", "Φ12", "t", 4200, 3, 4326, ""),
|
|
||||||
("", "", "散装水泥", "", "t", 380, 13, 429.4, "")]) # 该行目录留空
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "缺目录批次", "publisher": "测试发布"})
|
|
||||||
assert r["ok"] is False and "模板数据结构" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 数据源字典
|
|
||||||
def test_dict_roundtrip(server):
|
|
||||||
d0 = get(server, "/api/dict")
|
|
||||||
assert d0["ok"] is True
|
|
||||||
add = post(server, "/api/dict/save", {"cat": "publisher", "act": "add",
|
|
||||||
"name": "测试发布单位X"})
|
|
||||||
assert add["ok"] is True, add
|
|
||||||
dup = post(server, "/api/dict/save", {"cat": "publisher", "act": "add",
|
|
||||||
"name": "测试发布单位X"})
|
|
||||||
assert dup["ok"] is False and "已经存在" in dup["msg"]
|
|
||||||
row = [x for x in get(server, "/api/dict")["publishers"]
|
|
||||||
if x["name"] == "测试发布单位X"][0]
|
|
||||||
ren = post(server, "/api/dict/save", {"cat": "publisher", "act": "rename",
|
|
||||||
"id": row["id"], "name": "测试发布单位Y"})
|
|
||||||
assert ren["ok"] is True, ren
|
|
||||||
names = [x["name"] for x in get(server, "/api/dict")["publishers"]]
|
|
||||||
assert "测试发布单位Y" in names and "测试发布单位X" not in names
|
|
||||||
dele = post(server, "/api/dict/save", {"cat": "publisher", "act": "del",
|
|
||||||
"id": row["id"]})
|
|
||||||
assert dele["ok"] is True
|
|
||||||
bad = post(server, "/api/dict/save", {"cat": "hack", "act": "add"})
|
|
||||||
assert bad["ok"] is False # cat 白名单
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 信息价导入
|
|
||||||
def test_price_import_single_and_dup(server):
|
|
||||||
"""2026-10-12 重设计:一个文件 = 一个批次(多块拆批退役);期次从文件名认;
|
|
||||||
非标准模板直接拒绝(主人定「只能导入 Excel 的标准模板」)。"""
|
|
||||||
px = price_xlsx_file(server, "建材信息价_2026年7月.xlsx", [
|
|
||||||
("一、黑色金属", "C1", "圆钢", "Φ12", "t", 4200, 3, 4326, ""),
|
|
||||||
("一、黑色金属", "C2", "焊管", "DN50", "m", 210, 3, 216.3, "")])
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "双行信息价", "publisher": "测试发布",
|
|
||||||
"province": "广东省", "period_from": PERIOD_202607})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert len(r["batches"]) == 1 # 一个文件 = 一个批次
|
|
||||||
row = _q(server["db"], "SELECT Name, x_period_start_m, x_period_end_m, x_publisher,"
|
|
||||||
" x_rows_price FROM batches WHERE id=?", (int(r["batches"][0]),))[0]
|
|
||||||
assert row[1] == 24319 and row[2] == 24319 # 期次从文件名「2026年7月」认出
|
|
||||||
assert row[3] == "测试发布" and row[4] == 2
|
|
||||||
# 同名同期次同地区再导 → 先确认,force 后放行
|
|
||||||
s2 = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "双行信息价", "publisher": "测试发布",
|
|
||||||
"province": "广东省", "period_from": PERIOD_202607})
|
|
||||||
assert s2["ok"] is False and s2.get("need_confirm") is True
|
|
||||||
s3 = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "双行信息价", "publisher": "测试发布",
|
|
||||||
"province": "广东省", "period_from": PERIOD_202607, "force": True})
|
|
||||||
assert s3["ok"] is True
|
|
||||||
# 非标准模板:表头对不上 → 拒绝
|
|
||||||
from openpyxl import Workbook
|
|
||||||
wb = Workbook(); ws = wb.active
|
|
||||||
ws.append(["分类", "编码", "名称", "规格", "计量单位", "除税价", "税率%", "含税价", "说明"])
|
|
||||||
ws.append(["一、黑色金属", "C1", "圆钢", "Φ12", "t", 4200, "3%", 4326, ""])
|
|
||||||
bad = server["src_dir"] / "旧版别名.xlsx"; wb.save(bad)
|
|
||||||
rb = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": str(bad), "name": "旧版别名", "publisher": "测试发布"})
|
|
||||||
assert rb["ok"] is False and "标准模板" in rb["msg"]
|
|
||||||
# HTML 直接拒绝(HTML 导入退役)
|
|
||||||
pf = price_file(server, "retired.html", [
|
|
||||||
{"name": "H2026年7月", "columns": [], "sections": [
|
|
||||||
{"title": "目录", "rows": [["C1", "圆钢", "Φ12", "t", "4200", "3", "4326", ""]]}]}])
|
|
||||||
rh = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": pf, "name": "HTML导入", "publisher": "测试发布"})
|
|
||||||
assert rh["ok"] is False and "标准模板" in rh["msg"]
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""旧口径批次自动升级链(决策 34 方案 A/A′):
|
|
||||||
批次 parser_ver 落后 → 打开工程(audit)原位升级 / 后台手动升级;
|
|
||||||
价格批次不参与;同 id、明细行数保持。"""
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from api_harness import (META, PERIOD_202607, fixture_file, get, # noqa: F401
|
|
||||||
make_cos4, post, price_xlsx_file, server)
|
|
||||||
|
|
||||||
from test_api_p1 import raw_post # 复用二进制直传
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _w(db, sql, args=()):
|
|
||||||
con = sqlite3.connect(db)
|
|
||||||
try:
|
|
||||||
con.execute(sql, args)
|
|
||||||
con.commit()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _import(server, fname, name):
|
|
||||||
"""走真实前端流程:先 upload 存副本,再把 **uploads 路径**交给导入(不带 sha ——
|
|
||||||
x_src_hash 取路径 basename=<sha256>_<原名>,升级护栏靠它定位副本并核对内容哈希)。"""
|
|
||||||
fix = server["root"] / "fixsrc"
|
|
||||||
fix.mkdir(exist_ok=True)
|
|
||||||
make_cos4(str(fix / fname), name,
|
|
||||||
[("030507008001", name + "清单项", "", "台", 3, 500)],
|
|
||||||
[("000001", "网络摄像机", "400万", "台", "1200", "1356")])
|
|
||||||
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=up["path"], name=name, file_kind=1))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["batch_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def _ver(server, bid):
|
|
||||||
return _q(server["db"], "SELECT x_parser_ver, x_rows_bill FROM batches WHERE id=?",
|
|
||||||
(bid,))[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_upgrade_via_admin_api(server):
|
|
||||||
bid = _import(server, "upg1.cos4", "升级工程一")
|
|
||||||
fresh = _ver(server, bid)[0]
|
|
||||||
assert fresh and fresh != "2020.01.01-1"
|
|
||||||
# 人为把批次打回旧口径
|
|
||||||
_w(server["db"], "UPDATE batches SET x_parser_ver='2020.01.01-1' WHERE id=?", (bid,))
|
|
||||||
r = post(server, "/api/admin/batch/upgrade", {"id": bid})
|
|
||||||
assert r["ok"] is True and r["upgraded"] is True
|
|
||||||
ver, n_bill = _ver(server, bid)
|
|
||||||
assert ver == fresh and n_bill == 2 # 原 id、原行数(1 分部分项 + 1 措施)
|
|
||||||
# 已是当前口径 → 不再升
|
|
||||||
r2 = post(server, "/api/admin/batch/upgrade", {"id": bid})
|
|
||||||
assert r2["ok"] is True and r2["upgraded"] is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_upgrade_via_audit_open(server):
|
|
||||||
"""决策 243 后:同文件前后台只能存在一边——audit 打开已入库文件被拦(必须先删后台批次);
|
|
||||||
方案 A「打开即升级」只服务存量挂接对:手工造一条同源会话行(legacy 形态)走「重新解析」,
|
|
||||||
批次口径仍能顺手升到当前版。新批次的主升级通道是方案 A′(test_upgrade_via_admin_api)。"""
|
|
||||||
fname, name = "upg2.cos4", "升级工程二"
|
|
||||||
fix = server["root"] / "fixsrc"
|
|
||||||
fix.mkdir(exist_ok=True)
|
|
||||||
make_cos4(str(fix / fname), name,
|
|
||||||
[("030507008001", name + "清单项", "", "台", 3, 500)], ())
|
|
||||||
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
bid = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=up["path"], name=name, file_kind=1))["batch_id"]
|
|
||||||
fresh = _ver(server, bid)[0]
|
|
||||||
_w(server["db"], "UPDATE batches SET x_parser_ver='2020.01.01-1' WHERE id=?", (bid,))
|
|
||||||
# 新口径:audit 打开同一份 → 拦截
|
|
||||||
r = post(server, "/api/audit",
|
|
||||||
{"path": up["path"], "name": name, "province": "广东省", "city": "珠海市",
|
|
||||||
"district": "香洲区", "period_from": PERIOD_202607, "file_kind": 1})
|
|
||||||
assert r["ok"] is False and "必须先删除后台的入库批次" in r["msg"], r
|
|
||||||
# 存量形态:同源会话(老数据)走「重新解析」→ 方案 A 顺手升级仍有效
|
|
||||||
import sqlite3
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
src_hash = con.execute("SELECT x_src_hash FROM batches WHERE id=?", (bid,)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
try:
|
|
||||||
cur = con.execute(
|
|
||||||
"INSERT INTO sessions(name, base_period_m, src_name, imported_at,"
|
|
||||||
" period_from, period_to) VALUES(?,?,?,?,?,?)",
|
|
||||||
(name, PERIOD_202607, src_hash, "2026-10-01 00:00:00", PERIOD_202607, PERIOD_202607))
|
|
||||||
sid = cur.lastrowid
|
|
||||||
con.commit()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
r2 = post(server, "/api/session/reparse", {"session_id": sid})
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
assert _ver(server, bid)[0] == fresh
|
|
||||||
assert post(server, "/api/session/delete", {"ids": [sid]})["ok"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_upgrade_price_batch_rejected(server):
|
|
||||||
px = price_xlsx_file(server, "upg_info_2026年7月.xlsx", [
|
|
||||||
("目录A", "C1", "圆钢", "Φ12", "t", 4200, 3, 4326, "")])
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "升级测试信息价", "publisher": "测试发布"})
|
|
||||||
assert r["ok"] is True
|
|
||||||
bid = int(r["batches"][0])
|
|
||||||
r2 = post(server, "/api/admin/batch/upgrade", {"id": bid})
|
|
||||||
assert r2["ok"] is True and r2["upgraded"] is False # 价格批次暂不支持自动升级
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 243(2026-10-30 主人定)回归:
|
|
||||||
① 前后台禁同文件——工作台已开后台再导同一份 → 拦截「必须先删除」;
|
|
||||||
② 清单采纳收附件(取代 2026-10-09「清单采纳本就不收附件」):
|
|
||||||
来源入库清单挂的询价附件随采纳进目录,cats=['bill'];取消采纳整行撤事件;
|
|
||||||
③ 工料机采纳的附件 cats=['lme']——同一附件两条路都采过 → 两标签都出现。
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
from api_harness import (META, PERIOD_202607, get, make_cos4, post, # noqa: F401
|
|
||||||
server, twin_file)
|
|
||||||
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
METER = ("030405006001", "智能电度表", "1、三相;2、导轨式", "只", 20, 300)
|
|
||||||
LME = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _raw_post(server, path, fname, data):
|
|
||||||
r = server["client"].post(path, json={"name": fname,
|
|
||||||
"data": base64.b64encode(data).decode("ascii")})
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
return r.json()
|
|
||||||
|
|
||||||
|
|
||||||
def _hashed(server, raw, stem):
|
|
||||||
fp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_%s.cos4" % (hashlib.sha256(raw).hexdigest(), stem))
|
|
||||||
with open(fp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
return fp
|
|
||||||
|
|
||||||
|
|
||||||
def test_admin_import_blocked_when_session_has_same_file(server):
|
|
||||||
"""决策 243:最近审核已有同哈希会话 → 后台导入拦截,force 也无效。"""
|
|
||||||
p = make_cos4(str(server["src_dir"] / "ba243_raw.cos4"), "决策243工程甲", [CAM], [LME])
|
|
||||||
up = _raw_post(server, "/api/admin/upload", "决策243工程甲.cos4", open(p, "rb").read())
|
|
||||||
audit = {"path": up["path"], "name": "决策243工程甲", "file_kind": 1,
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607}
|
|
||||||
assert post(server, "/api/audit", audit)["ok"] is True
|
|
||||||
body = dict(META, path=up["path"], name="决策243工程甲", file_kind=1)
|
|
||||||
r = post(server, "/api/admin/import", body)
|
|
||||||
assert r["ok"] is False and "最近审核已有同一份文件" in r["msg"] \
|
|
||||||
and "必须先删除" in r["msg"], r
|
|
||||||
r2 = post(server, "/api/admin/import", dict(body, force=True))
|
|
||||||
assert r2["ok"] is False # force 通道对它同样封死
|
|
||||||
|
|
||||||
|
|
||||||
def test_bill_adopt_collects_attachments_and_tabs(server):
|
|
||||||
# 后台:导入批次 + 传询价附件 + 绑到清单(决策 152 通道)
|
|
||||||
p = make_cos4(str(server["src_dir"] / "ba243b_raw.cos4"), "决策243来源项目",
|
|
||||||
[CAM, METER], [LME])
|
|
||||||
up = _raw_post(server, "/api/admin/upload", "决策243来源项目.cos4", open(p, "rb").read())
|
|
||||||
imp = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=up["path"], name="决策243来源项目", file_kind=1))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
bid = imp["batch_id"]
|
|
||||||
fid = _raw_post(server, "/api/admin/batch/%d/inq" % bid, "询价资料.zip",
|
|
||||||
b"PK\x03\x04" + b"ba243-inq-bytes")["id"]
|
|
||||||
src_bill = _q(server["db"], "SELECT id FROM bills WHERE batch_id=? AND Number=?",
|
|
||||||
(bid, CAM[0]))[0][0]
|
|
||||||
bb = post(server, "/api/admin/batch/%d/inq/bind" % bid,
|
|
||||||
{"file_id": fid, "bill_ids": [src_bill]})
|
|
||||||
assert bb["ok"] is True and bb["n"] == 1, bb
|
|
||||||
|
|
||||||
# 工作台:开同内容双胞胎件(决策 243 禁同文件)
|
|
||||||
sid = post(server, "/api/audit", {
|
|
||||||
"path": twin_file(server, up["path"], "ba243b_t"), "name": "决策243目标工程",
|
|
||||||
"file_kind": 1, "period_from": PERIOD_202607, "period_to": PERIOD_202607})["session_id"]
|
|
||||||
bill_id = _q(server["sessdb"],
|
|
||||||
"SELECT id FROM s_bills WHERE session_id=? AND Number=?", (sid, CAM[0]))[0][0]
|
|
||||||
|
|
||||||
# 清单采纳 → 附件随采纳收进目录(cats=['bill'])
|
|
||||||
r = post(server, "/api/session/bill/adopt",
|
|
||||||
{"session_id": sid, "bill_id": bill_id, "src_bill_id": src_bill})
|
|
||||||
assert r["ok"] is True and r.get("n_att") == 1, r
|
|
||||||
d = get(server, "/api/adopt/list", sid=sid)
|
|
||||||
assert d["ok"] and len(d["atts"]) == 1, d
|
|
||||||
a = d["atts"][0]
|
|
||||||
assert a["name"] == "询价资料.zip" and a["cats"] == ["bill"]
|
|
||||||
assert "决策243来源项目" in a["projs"]
|
|
||||||
|
|
||||||
# 工料机侧也采同一附件(真实前端=采纳工料机价后上报 record)→ cats 两标签都在
|
|
||||||
lme_row = _q(server["sessdb"],
|
|
||||||
"SELECT id FROM s_lme_proj WHERE session_id=?", (sid,))[0][0]
|
|
||||||
rr = post(server, "/api/adopt/record",
|
|
||||||
{"url": "/api/admin/inq/file/%d" % fid, "name": "询价资料.zip",
|
|
||||||
"proj": "决策243来源项目", "session_id": sid, "lme_id": lme_row})
|
|
||||||
assert rr["ok"] is True, rr
|
|
||||||
d2 = get(server, "/api/adopt/list", sid=sid)
|
|
||||||
assert d2["atts"][0]["cats"] == ["bill", "lme"]
|
|
||||||
|
|
||||||
# 取消清单采纳 → 清单侧事件撤下,工料机侧还在(cats 只剩 lme)
|
|
||||||
un = post(server, "/api/session/bill/unadopt", {"session_id": sid, "bill_id": bill_id})
|
|
||||||
assert un["ok"] is True, un
|
|
||||||
d3 = get(server, "/api/adopt/list", sid=sid)
|
|
||||||
assert d3["atts"] and d3["atts"][0]["cats"] == ["lme"]
|
|
||||||
|
|
||||||
# 连续采纳认最后一次:来源换成没挂附件的清单 → 旧事件撤、n_att=0
|
|
||||||
r2 = post(server, "/api/session/bill/adopt",
|
|
||||||
{"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": _q(server["db"],
|
|
||||||
"SELECT id FROM bills WHERE batch_id=? AND Number=?",
|
|
||||||
(bid, METER[0]))[0][0]})
|
|
||||||
assert r2["ok"] is True and r2.get("n_att") == 0, r2
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""N1 源码保护测试(2026-10-27《企业和个人版.md》14.1):交付包哈希清单校验+全线拦截。"""
|
|
||||||
import hashlib
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
|
|
||||||
APP_ROOT = os.path.dirname(HERE)
|
|
||||||
if SERVER_DIR not in sys.path:
|
|
||||||
sys.path.insert(0, SERVER_DIR)
|
|
||||||
|
|
||||||
from license_client import gate # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def reset():
|
|
||||||
gate._INTEGRITY_FAIL = ""
|
|
||||||
old_build = gate.BUILD
|
|
||||||
yield gate
|
|
||||||
gate.BUILD = old_build
|
|
||||||
gate._INTEGRITY_FAIL = ""
|
|
||||||
|
|
||||||
|
|
||||||
def _sha(rel):
|
|
||||||
with open(os.path.join(APP_ROOT, rel.replace("/", os.sep)), "rb") as f:
|
|
||||||
return hashlib.sha256(f.read()).hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
def test_integrity_ok_when_manifest_matches(reset):
|
|
||||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/version_gate.py": _sha("server/version_gate.py")})
|
|
||||||
gate._check_build_integrity()
|
|
||||||
assert gate._INTEGRITY_FAIL == ""
|
|
||||||
assert gate.intercept("GET", "/admin.html") is None or True # 校验通过即达标
|
|
||||||
|
|
||||||
|
|
||||||
def test_integrity_fail_on_modified_file(reset):
|
|
||||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/version_gate.py": "0" * 64})
|
|
||||||
gate._check_build_integrity()
|
|
||||||
assert gate._INTEGRITY_FAIL == "server/version_gate.py"
|
|
||||||
|
|
||||||
|
|
||||||
def test_integrity_fail_on_missing_file(reset):
|
|
||||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/__no_such__.py": "0" * 64})
|
|
||||||
gate._check_build_integrity()
|
|
||||||
assert gate._INTEGRITY_FAIL == "server/__no_such__.py(缺失)"
|
|
||||||
|
|
||||||
|
|
||||||
def test_integrity_blocks_everything_including_license_api(reset):
|
|
||||||
"""被篡改的包:授权口也不放行(防改 gate 删 enforce 后再激活绕过)。"""
|
|
||||||
gate._INTEGRITY_FAIL = "server/license_client/gate.py"
|
|
||||||
r = gate.intercept("GET", "/api/license/status")
|
|
||||||
assert r and r["kind"] == "json" and r["code"] == 403
|
|
||||||
assert r["obj"]["error"]["code"] == "INTEGRITY_FAILED"
|
|
||||||
r2 = gate.intercept("GET", "/admin.html")
|
|
||||||
assert r2 and r2["kind"] == "html" and "完整性校验失败" in r2["text"]
|
|
||||||
r3 = gate.intercept("POST", "/api/license/activate")
|
|
||||||
assert r3 and r3["obj"]["error"]["code"] == "INTEGRITY_FAILED"
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_build_or_empty_manifest_skips_check(reset):
|
|
||||||
gate.BUILD = None
|
|
||||||
gate._check_build_integrity()
|
|
||||||
assert gate._INTEGRITY_FAIL == ""
|
|
||||||
gate.BUILD = SimpleNamespace(INTEGRITY={})
|
|
||||||
gate._check_build_integrity()
|
|
||||||
assert gate._INTEGRITY_FAIL == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_version_endpoints_pass_even_when_locked(reset):
|
|
||||||
"""锁定态(enforce+未激活)版本状态口也放行:排障 + 强制更新页轮询(2026-10-27 5.9)。"""
|
|
||||||
gate._cfg.update({"enforce": True})
|
|
||||||
assert gate.intercept("GET", "/api/version_info") is None
|
|
||||||
assert gate.intercept("GET", "/api/version") is None
|
|
||||||
r = gate.intercept("GET", "/api/admin/summary")
|
|
||||||
assert r is not None and r.get("code") == 403 # 其他 API 照拦,口径不变
|
|
||||||
@@ -1,152 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 247 常驻防线:「打开项目」弹框打开即清空——字段清单自动盘点式回归。
|
|
||||||
|
|
||||||
防的是整个「弹框残留」类毛病(决策 50 → 247 同类三犯:清值链靠手工枚举,加新字段、
|
|
||||||
换层次就漏)。所以本测试**不枚举固定字段**,而是自己盘点弹框里当前的全部人可填字段,
|
|
||||||
并且连隐藏层一起管:
|
|
||||||
- comboAttach 组合框:select 本体值 + 镜像框显示(247 后台漏的层)
|
|
||||||
- comboFree 自由输入:值 + 清空小叉显隐(决策 50 的「空框带小叉」死角)
|
|
||||||
- 期次控件:value + dataset.pf/pt(决策 50 的「假清空」,PVAL 读 dataset)
|
|
||||||
以后往弹框加新字段:盘点自动纳入,漏清就红灯——不需要改本测试。
|
|
||||||
|
|
||||||
流程(两侧同一路径):打开弹框 → 逐字段注入假值 → 点「取消」→ 重开 → 逐字段断言空。
|
|
||||||
唯一白名单 = 单价类型回默认「预算综合单价」(值 1,决策 245)。
|
|
||||||
跑法:随全量 pytest;复用 api_harness 的 session 级 server 夹具(临时副本服务,
|
|
||||||
生产库零接触),本模块只多花一次开浏览器的钱。
|
|
||||||
"""
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
pytest.importorskip("playwright.sync_api", reason="无头浏览器防线需要 playwright")
|
|
||||||
from playwright.sync_api import sync_playwright # noqa: E402
|
|
||||||
|
|
||||||
from api_harness import server # noqa: F401,E402 (夹具须经导入注册)
|
|
||||||
|
|
||||||
SENTINEL = "残留试探247"
|
|
||||||
|
|
||||||
# 允许重开后的非空默认值(决策 245:单价类型默认预算综合单价)
|
|
||||||
ALLOW_DEFAULT = {"okind": "1", "ifk": "1"}
|
|
||||||
|
|
||||||
# 盘点:弹框内全部人可填字段。comboAttach 的 select 本体是 display:none 也要管(残留就在镜像层);
|
|
||||||
# 折叠面板(导入Excel 树区)、价格类专属行、file/hidden 不在本次弹框形态里,按不可见跳过。
|
|
||||||
INVENTORY = r"""
|
|
||||||
(root) => {
|
|
||||||
const out = [];
|
|
||||||
for (const el of root.querySelectorAll('input,select,textarea')) {
|
|
||||||
if (el.type === 'hidden' || el.type === 'file') continue;
|
|
||||||
const per = el.classList.contains('perinp'); // 期次控件
|
|
||||||
const csel = !!(el.tagName === 'SELECT' && el._combo); // comboAttach 组合框本体
|
|
||||||
const cfree = el.tagName === 'INPUT' && !!el.parentNode.classList?.contains('combo'); // comboFree
|
|
||||||
if (el.offsetParent === null && !csel) continue; // 不可见(折叠/隐藏行)跳过
|
|
||||||
if (!el.id) {
|
|
||||||
// comboAttach 的镜像 input(无 id)已归其 select 本体的 mir 层管;其余无 id 字段锚不定,红线报错
|
|
||||||
if (el.parentNode.classList?.contains('combo')) continue;
|
|
||||||
throw new Error('弹框里有无 id 的字段,盘点无法锚定:' + el.outerHTML.slice(0, 80));
|
|
||||||
}
|
|
||||||
out.push({ id: el.id, kind: per ? 'per' : (csel ? 'csel' : (cfree ? 'cfree' : el.tagName.toLowerCase())) });
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}"""
|
|
||||||
|
|
||||||
# 注入假值(按层写:本体/镜像/期次 dataset/小叉)
|
|
||||||
INJECT = r"""
|
|
||||||
([root, flds]) => {
|
|
||||||
const V = "残留试探247";
|
|
||||||
for (const f of flds) {
|
|
||||||
const el = root.querySelector('[id="' + f.id + '"]');
|
|
||||||
if (f.kind === 'per') { setPeriod(el, '2026-11', '2026-12'); continue; }
|
|
||||||
if (f.kind === 'csel' || f.kind === 'select') {
|
|
||||||
if (![...el.options].some(o => o.value === V)) el.add(new Option(V, V));
|
|
||||||
el.value = V;
|
|
||||||
if (el._combo) el._combo.refresh();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
el.value = V;
|
|
||||||
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
||||||
}
|
|
||||||
}"""
|
|
||||||
|
|
||||||
# 重开后逐层读回
|
|
||||||
READ = r"""
|
|
||||||
([root, flds]) => {
|
|
||||||
const out = {};
|
|
||||||
for (const f of flds) {
|
|
||||||
const el = root.querySelector('[id="' + f.id + '"]');
|
|
||||||
const st = {};
|
|
||||||
if (f.kind === 'per') {
|
|
||||||
st.v = el.value; st.pf = el.dataset.pf || ''; st.pt = el.dataset.pt || '';
|
|
||||||
} else if (f.kind === 'csel') {
|
|
||||||
st.v = el.value; st.mir = el._combo.inp.value;
|
|
||||||
} else if (f.kind === 'cfree') {
|
|
||||||
st.v = el.value;
|
|
||||||
const x = el.parentNode.querySelector('.combo-x');
|
|
||||||
st.fork = x ? x.style.display : null;
|
|
||||||
} else {
|
|
||||||
st.v = el.value;
|
|
||||||
}
|
|
||||||
out[f.id] = st;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}"""
|
|
||||||
|
|
||||||
DIALOGS = [
|
|
||||||
dict(name="工作台-打开项目", page="/workbench.html",
|
|
||||||
open_btn="button:has-text('打开项目')", cancel_btn="#omask button:has-text('取消')",
|
|
||||||
root="#odlg", combo_ready="#oprov"),
|
|
||||||
dict(name="后台-打开项目", page="/admin.html",
|
|
||||||
open_btn="#btnImp", cancel_btn="#imask button:has-text('取消')",
|
|
||||||
root="#imask", combo_ready="#iprov"),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def pg(server):
|
|
||||||
with sync_playwright() as p:
|
|
||||||
br = p.chromium.launch(channel="msedge", headless=True)
|
|
||||||
page = br.new_page()
|
|
||||||
yield page, server["port"]
|
|
||||||
br.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _open(pg, dlg):
|
|
||||||
pg.click(dlg["open_btn"])
|
|
||||||
pg.wait_for_selector(dlg["root"], state="visible")
|
|
||||||
pg.wait_for_function(
|
|
||||||
"document.querySelector('%s') && document.querySelector('%s')._combo" % (
|
|
||||||
dlg["combo_ready"], dlg["combo_ready"]))
|
|
||||||
pg.wait_for_timeout(500) # 等开框清值链 / loadImpFilters 异步收尾
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("dlg", DIALOGS, ids=[d["name"] for d in DIALOGS])
|
|
||||||
def test_dialog_reopens_fresh(pg, dlg):
|
|
||||||
page, port = pg
|
|
||||||
page.goto("http://127.0.0.1:%d%s" % (port, dlg["page"]))
|
|
||||||
page.wait_for_load_state("networkidle")
|
|
||||||
|
|
||||||
# ① 盘点字段(盘点不到字段本身就是防线失效,直接红灯)
|
|
||||||
_open(page, dlg)
|
|
||||||
root = page.locator(dlg["root"]).element_handle()
|
|
||||||
flds = page.evaluate(INVENTORY, root)
|
|
||||||
assert len(flds) >= 5, "盘点到 %d 个字段,弹框结构可能变了:%s" % (len(flds), flds)
|
|
||||||
|
|
||||||
# ② 注入假值 → 取消 → 重开
|
|
||||||
page.evaluate(INJECT, [root, flds])
|
|
||||||
page.click(dlg["cancel_btn"])
|
|
||||||
page.wait_for_timeout(200)
|
|
||||||
_open(page, dlg)
|
|
||||||
root = page.locator(dlg["root"]).element_handle()
|
|
||||||
state = page.evaluate(READ, [root, flds])
|
|
||||||
|
|
||||||
# ③ 逐字段逐层断言:空 / 允许的默认值
|
|
||||||
bad = []
|
|
||||||
for f in flds:
|
|
||||||
st = state[f["id"]]
|
|
||||||
allow = ALLOW_DEFAULT.get(f["id"])
|
|
||||||
for layer, v in st.items():
|
|
||||||
if layer == "fork": # 小叉:none=空框已收叉(干净),亮着=残留
|
|
||||||
if v != "none":
|
|
||||||
bad.append("%s.%s=%r" % (f["id"], layer, v))
|
|
||||||
continue
|
|
||||||
if v == allow or v in ("", None):
|
|
||||||
continue
|
|
||||||
bad.append("%s.%s=%r" % (f["id"], layer, v))
|
|
||||||
assert not bad, "重开弹框残留(决策 247 类毛病又犯了):字段=%s,打开函数清值链漏了这些层" % ";".join(bad)
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""ESCC2.0(广东省造价数据标准 DBJ/T 15-145-2018)明文 XML 解析回归。
|
|
||||||
2026-11-03 主人定:恢复散装 xml 中 ESCC 支持(推翻 2026-10-01「不再支持 xml」的 ESCC 部分)。
|
|
||||||
样本:后台需要导入的项目/y程ESCC2.xml(珠海高新区 2024 地灾治理,7 单位工程,变更工程负量)。"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from api_harness import post, server # noqa: F401 (夹具)
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import import_job as ij # noqa: E402
|
|
||||||
|
|
||||||
SAMPLE = os.path.join(os.path.dirname(__file__), "..", "..", "..",
|
|
||||||
"后台需要导入的项目", "y程ESCC2.xml")
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_esc_dry():
|
|
||||||
"""干跑:容器行数与关键值与样本实测一致。"""
|
|
||||||
out = {"uw": [], "bills": [], "norms": [], "lmes": []}
|
|
||||||
kind = ij.parse_esc(SAMPLE, out)
|
|
||||||
assert kind == "ESCC2"
|
|
||||||
assert out["proj_name"] == "珠海市高新区2024年地质灾害隐患点、风险点治理工程"
|
|
||||||
assert out["total"] == pytest.approx(-238931.60, abs=0.01)
|
|
||||||
assert len(out["uw"]) == 7 # 2 单项组(4+3)单位工程
|
|
||||||
assert len(out["sections"]) == 2
|
|
||||||
assert len(out["bills"]) == 186 # 分部分项 65 + 措施 121
|
|
||||||
assert sum(1 for k in out["bill_kind"] if k == "prelim") == 121
|
|
||||||
assert len(out["norms"]) == 127 # WorkContent 组内定额全收
|
|
||||||
assert len(out["norm_res"]) == 698 # 定额消耗
|
|
||||||
assert len(out["lme_proj"]) == 126 # 项目级 Resource 价格表
|
|
||||||
assert len(out["lme_uw"]) == 512 # 单位级 Resource 全收(96+72+40 ×2 +96)
|
|
||||||
# 决策 265 扩展(2026-11-04 主人定「数据只来源原数据」):台班/配合比组成必须从原件采到,
|
|
||||||
# 此前整层漏采 → 弹框只能靠采纳从别的批次借(实测 12 批次 ×5 行重复)
|
|
||||||
assert len(out["lme_res"]) == 30 # 样本 30 个带组成的母码
|
|
||||||
# 2026-11-04 主人定「都有引用啊」:同一台班在不同单位工程可带不同组成(无后缀套 / -0003 换算套)
|
|
||||||
# ——全量收、同子码去重;此前只收第一份把变体码整批丢掉(→ 被引式集判未引用 → 剪枝 → 合并缺品种)
|
|
||||||
assert sum(len(v) for v in out["lme_res"].values()) == 152 # 组成子项 152 行(含 990401025 两套 10 项)
|
|
||||||
assert [c for c, _q in out["lme_res"]["990401025"]] == [
|
|
||||||
"00010003", "99450630", "99450640", "99450650", "99450680",
|
|
||||||
"00010003-0003", "99450630-0003", "99450640-0003", "99450650-0003", "99450680-0001"]
|
|
||||||
assert out["lme_res"]["990402040"] == [("00010003", 2.0), ("99450630", 262.04),
|
|
||||||
("99450640", 45.05), ("99450650", 150.48),
|
|
||||||
("99450680", 52.93)]
|
|
||||||
assert len(out["uw_cost"]) == 7
|
|
||||||
assert len(out["uw_summary"]) == 7 # 单位级 Summary 树(样本无项目级)
|
|
||||||
assert len(out["bill_expr"]) == 186 # 清单工程量表达式
|
|
||||||
# 负数量/负合价原样保真(变更工程特性)
|
|
||||||
b0 = out["bills"][0]
|
|
||||||
assert b0[0] == "010102001004" and b0[1] == "孤石清理"
|
|
||||||
assert b0[4] == pytest.approx(-170.0) and b0[6] == pytest.approx(-9661.10)
|
|
||||||
# 措施分部嵌套(样本 13 层 Branch/Branch)→ parent 链正确
|
|
||||||
md = [d for d in out["divides"] if d["kind"] == "prelim"]
|
|
||||||
assert len(md) == 105
|
|
||||||
by_idx = {i: d for i, d in enumerate(out["divides"])}
|
|
||||||
for d in md:
|
|
||||||
if d["parent"] is not None:
|
|
||||||
assert by_idx[d["parent"]]["kind"] == "prelim"
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_file_dispatch_esc():
|
|
||||||
"""sniff/parse_file 分流:根节点 Projects → parse_esc;其他散装 XML 仍拒绝。"""
|
|
||||||
assert ij.sniff(SAMPLE) == "esc"
|
|
||||||
out = {"uw": [], "bills": [], "norms": [], "lmes": []}
|
|
||||||
assert ij.parse_file(SAMPLE, out) == "ESCC2"
|
|
||||||
# 未知散装 XML 仍报错
|
|
||||||
import tempfile
|
|
||||||
p = os.path.join(tempfile.gettempdir(), "not_priced.xml")
|
|
||||||
with open(p, "w", encoding="utf-8") as fh:
|
|
||||||
fh.write('<?xml version="1.0"?><Root><Thing/></Root>')
|
|
||||||
try:
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
ij.parse_file(p, {"uw": [], "bills": [], "norms": [], "lmes": []})
|
|
||||||
finally:
|
|
||||||
os.unlink(p)
|
|
||||||
|
|
||||||
|
|
||||||
def test_esc_open_via_audit(server):
|
|
||||||
"""端到端:走 /api/audit 真实入库(批次库),断言库内行数与树结构。"""
|
|
||||||
p = server["src_dir"] / "esc_t.xml"
|
|
||||||
p.write_bytes(open(SAMPLE, "rb").read())
|
|
||||||
j = post(server, "/api/audit", {
|
|
||||||
"path": str(p), "name": "ESCC回归工程",
|
|
||||||
"period_from": 24319, "period_to": 24319,
|
|
||||||
"province": "广东省", "city": "珠海市", "district": "香洲区",
|
|
||||||
"bulid_unit": "测试建设单位", "file_kind": 1})
|
|
||||||
assert j.get("ok") is True, j
|
|
||||||
sid = j["session_id"]
|
|
||||||
import sqlite3
|
|
||||||
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
uw = con.execute("SELECT COUNT(*) c FROM s_unit_works WHERE session_id=?", (sid,)).fetchone()["c"]
|
|
||||||
assert uw == 7, uw
|
|
||||||
sec = con.execute("SELECT COUNT(*) c FROM s_sections WHERE session_id=?", (sid,)).fetchone()["c"]
|
|
||||||
assert sec == 2, sec
|
|
||||||
nb = con.execute("""SELECT COUNT(*) c FROM s_bills b JOIN s_unit_works u ON u.id=b.uw_id
|
|
||||||
WHERE u.session_id=?""", (sid,)).fetchone()["c"]
|
|
||||||
assert nb == 186, nb
|
|
||||||
nn = con.execute("""SELECT COUNT(*) c FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
JOIN s_unit_works u ON u.id=b.uw_id WHERE u.session_id=?""", (sid,)).fetchone()["c"]
|
|
||||||
assert nn == 127, nn
|
|
||||||
# 项目级价格表 126 条入库后,决策 201 打开收尾「未引用即删」会清掉
|
|
||||||
# 只在价格表出现、无任何定额/台班组成引用的行——与其他格式同口径。
|
|
||||||
# 2026-11-04 主人拍板对齐决策 268 口径:台班组成全收→变体套(-0003/-0001 等)进引用集
|
|
||||||
# 不再被剪,剪掉的从 27 行降到 8 行 → 126-8=118(旧口径 99 是「只收第一份」时代的数)
|
|
||||||
lp = con.execute("SELECT COUNT(*) c FROM s_lme_proj WHERE session_id=?", (sid,)).fetchone()["c"]
|
|
||||||
assert lp == 118, lp
|
|
||||||
lib = con.execute("SELECT COUNT(*) c FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()["c"]
|
|
||||||
assert lib == 126, lib # s_lme_lib 是全量兜底库,不删
|
|
||||||
us = con.execute("""SELECT COUNT(*) c FROM s_uw_summary s JOIN s_unit_works u ON u.id=s.uw_id
|
|
||||||
WHERE u.session_id=?""", (sid,)).fetchone()["c"]
|
|
||||||
assert us > 0, "单位汇总分析没入库"
|
|
||||||
# 决策 265 扩展(2026-11-04):原件里的台班组成必须入库,且每码只有一套
|
|
||||||
nres = con.execute("SELECT COUNT(*) c FROM s_lme_res WHERE session_id=?", (sid,)).fetchone()["c"]
|
|
||||||
assert nres == 152, nres
|
|
||||||
dup = con.execute("""SELECT COUNT(*) c FROM (SELECT p_code, res_code FROM s_lme_res
|
|
||||||
WHERE session_id=? GROUP BY p_code, res_code HAVING COUNT(*)>1)""",
|
|
||||||
(sid,)).fetchone()["c"]
|
|
||||||
assert dup == 0, "同码组成重复入库 %d 组" % dup
|
|
||||||
kid = con.execute("""SELECT res_code, qty FROM s_lme_res
|
|
||||||
WHERE session_id=? AND p_code='990402040' ORDER BY seq""", (sid,)).fetchall()
|
|
||||||
assert [(r["res_code"], r["qty"]) for r in kid] == [
|
|
||||||
("00010003", 2.0), ("99450630", 262.04), ("99450640", 45.05),
|
|
||||||
("99450650", 150.48), ("99450680", 52.93)]
|
|
||||||
# 负数量保真
|
|
||||||
neg = con.execute("""SELECT b.Quantity q FROM s_bills b JOIN s_unit_works u ON u.id=b.uw_id
|
|
||||||
WHERE u.session_id=? AND b.Number='010102001004'""", (sid,)).fetchone()
|
|
||||||
assert neg and neg["q"] == pytest.approx(-170.0)
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""导出后缀口径(2026-11-03 决策 264 补记:骨架回灌单一通路后重写)。
|
|
||||||
|
|
||||||
旧引擎 export_cos.export_zip 已拆除;后缀不再由旧引擎从源文件名猜——
|
|
||||||
①骨架挑选按内容/后缀(classic_skeleton.suffix_of 支持任意后缀);
|
|
||||||
②导出文件名后缀跟导出格式走(export_v2.out_name)。
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
import uuid
|
|
||||||
import zipfile
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
|
|
||||||
import api_harness as H # noqa: E402
|
|
||||||
import classic_skeleton as cs # noqa: E402
|
|
||||||
import export_v2 as ev # noqa: E402
|
|
||||||
from api_harness import get, post, server # noqa: F401,E402 (夹具须经导入注册)
|
|
||||||
|
|
||||||
|
|
||||||
def test_suffix_of_any_ext():
|
|
||||||
cases = {
|
|
||||||
"工程-招标控制价.cos4": "cos4",
|
|
||||||
"工程-招标控制价.COS4": "cos4",
|
|
||||||
"工程-招标控制价.cos": "cos",
|
|
||||||
"工程-招标控制价.COS": "cos",
|
|
||||||
"工程-招标控制价.swt": "swt",
|
|
||||||
"工程-招标控制价.abc": "abc", # 未来新格式:能导入就按原格式出
|
|
||||||
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": None,
|
|
||||||
}
|
|
||||||
for name, want in cases.items():
|
|
||||||
assert cs.suffix_of(name) == want, "%s → %s (期望 %s)" % (name, cs.suffix_of(name), want)
|
|
||||||
|
|
||||||
|
|
||||||
def test_out_name_follows_suffix():
|
|
||||||
assert ev.out_name("后缀工程", "cos4") == "后缀工程-审核版.cos4"
|
|
||||||
assert ev.out_name("后缀工程", "cos") == "后缀工程-审核版.cos"
|
|
||||||
assert ev.out_name("", "abc") == "工程-审核版.abc"
|
|
||||||
|
|
||||||
|
|
||||||
def test_blank_package_annotated(tmp_path):
|
|
||||||
"""骨架库导出「完全空骨架(原格式)+自增/固定标注」(2026-11-03 新增功能):
|
|
||||||
包内两个成员、值全空、每个结构位带规则注释、XML 可解析。"""
|
|
||||||
src = H.make_cos4(str(tmp_path / "blank_src.cos4"), "骨架标注工程",
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 1, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
# 给夹具补一条单价计算行(x_side 类固定子块的标注样本)
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(src) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for n in z.namelist():
|
|
||||||
d = z.read(n)
|
|
||||||
if n.lower() != "project.xml":
|
|
||||||
d = d.replace(b"</Norm>", b'<UnitPriceCalculationOfItem Code="RGF" Name="" Total=""/></Norm>', 1)
|
|
||||||
zo.writestr(n, d)
|
|
||||||
src2 = tmp_path / "blank_src2.cos4"
|
|
||||||
src2.write_bytes(buf.getvalue())
|
|
||||||
con = sqlite3.connect(str(tmp_path / "h.db"))
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
sig = cs.seed_frame(con, str(src2), "标注骨架")
|
|
||||||
assert sig
|
|
||||||
data, fn, err = ev.build_blank_package(con, sig)
|
|
||||||
con.close()
|
|
||||||
assert err is None and fn.endswith(".cos4") and data[:2] == b"PK"
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(data))
|
|
||||||
names = [i.filename for i in z.infolist()]
|
|
||||||
assert "Project.xml" in names and len(names) == 2, names
|
|
||||||
proj = z.read("Project.xml").decode("utf-8")
|
|
||||||
unit = z.read([n for n in names if n != "Project.xml"][0]).decode("utf-8")
|
|
||||||
ET.fromstring(proj)
|
|
||||||
ET.fromstring(unit)
|
|
||||||
assert "导出规则:自增区域" in unit
|
|
||||||
assert "自增区域:至少 1 个" in unit
|
|
||||||
assert "自增块:按数据块循环" in unit or "自增行:按数据行循环" in unit
|
|
||||||
assert "固定" not in unit
|
|
||||||
assert 'Number="B001"' not in unit and 'Number="B001"' not in proj # 完全空(不带数据)
|
|
||||||
|
|
||||||
|
|
||||||
def test_rule_registry():
|
|
||||||
"""结构位规则:区域下限 1(至少一个空壳)、行/块下限 0;全部自增,不再有「固定」。"""
|
|
||||||
region = ET.fromstring('<SummaryOfCost Total=""/>')
|
|
||||||
assert ev.min_count("SummaryOfCost") == 1
|
|
||||||
assert "自增区域" in ev.rule_note(region) and "固定" not in ev.rule_note(region)
|
|
||||||
leaf = ET.fromstring('<AddiCost Code=""/>')
|
|
||||||
assert ev.min_count("AddiCost") == 0
|
|
||||||
assert "自增行" in ev.rule_note(leaf)
|
|
||||||
block = ET.fromstring("<AttrInfoItem><AttrInfoItem Name='子'/></AttrInfoItem>")
|
|
||||||
assert "自增块" in ev.rule_note(block)
|
|
||||||
at = ET.fromstring('<AttrInfo><AttrInfoItem/></AttrInfo>')
|
|
||||||
assert "自增区域" in ev.rule_note(at)
|
|
||||||
# 导出条数 = max(下限, 数据条数)
|
|
||||||
assert ev.row_count("SummaryOfCost", 0) == 1
|
|
||||||
assert ev.row_count("AttrInfo", 0) == 1
|
|
||||||
assert ev.row_count("AddiCost", 0) == 0
|
|
||||||
assert ev.row_count("AddiCost", 3) == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_lme_summary_two_shapes():
|
|
||||||
"""工料机汇总行两种形态(普通自闭合行 / 带台班组成的块行)各按自己的样板输出——
|
|
||||||
恢复旧引擎(2026-11-05 主人拍板)后等价通道=_summary_node 模板克隆:
|
|
||||||
children_html 空=自闭合、非空=成对块;不能混用样板:否则另一形态的列被丢掉(主人实测)。"""
|
|
||||||
import export_cos as _xc
|
|
||||||
_T = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
_L = "LabourMaterialsEquipmentsMachinesElement"
|
|
||||||
tmpl_a = '<%s Number="X" Name="n" ExtraA=""/>' % _T
|
|
||||||
tmpl_b = ('<%s Number="X" Name="n" ExtraB=""><%s Number="C0" Quantity="1"/></%s>'
|
|
||||||
% (_T, _L, _T))
|
|
||||||
a = _xc._summary_node(("A1", "普通行", "", "个", 1, 2, 10, 0, 10), tmpl_a)
|
|
||||||
b = _xc._summary_node(("B1", "组合行", "", "台班", 7, 1, 20, 0, 20), tmpl_b,
|
|
||||||
children_html='<%s Number="C1" Quantity="1.500000"/>' % _L)
|
|
||||||
# 行独有扩展列经合并回写通道(_lme_apply_price._flags,决策 259 全采)落行:
|
|
||||||
a = _xc._lme_apply_price(a, {"NoTaxPrice": 10, "TaxPrice": 0, "_flags": {"ExtraA": "va"}})
|
|
||||||
b = _xc._lme_apply_price(b, {"NoTaxPrice": 20, "TaxPrice": 0, "_flags": {"ExtraB": "vb"}})
|
|
||||||
# 普通行:自闭合、模板独有列 ExtraA 保留
|
|
||||||
assert a.startswith("<%s " % _T) and a.endswith("/>"), a
|
|
||||||
assert 'Number="A1"' in a and 'ExtraA="va"' in a, a
|
|
||||||
# 组合行:成对块、模板独有列 ExtraB 保留、子级照 children_html
|
|
||||||
assert ("<%s " % _T) in b and b.endswith("</%s>" % _T), b
|
|
||||||
assert 'Number="B1"' in b and 'ExtraB="vb"' in b, b
|
|
||||||
assert '<%s Number="C1" Quantity="1.500000"/>' % _L in b, b
|
|
||||||
# 两种形态在产物上必须分开:普通行自闭合、组合行带闭合标签(上面两段形态断言)
|
|
||||||
|
|
||||||
|
|
||||||
def test_blankpkg_endpoint(server):
|
|
||||||
"""后台接口:/api/admin/frames/blankpkg/<sig> 直接下载原格式空骨架(带标注)。"""
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / "blank_ep_raw.cos4"), "标注端点工程",
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 1, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
sig = cs.seed_frame(con, p, "端点骨架")
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
assert sig
|
|
||||||
r = server["client"].get("/api/admin/frames/blankpkg/%s" % sig)
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
assert r.content[:2] == b"PK"
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(r.content))
|
|
||||||
assert "Project.xml" in z.namelist()
|
|
||||||
for i in z.infolist(): # 成员名必须是 GBK 原始字节(不带 UTF-8 旗标)
|
|
||||||
assert not (i.flag_bits & 0x800), i.filename
|
|
||||||
if i.filename != "Project.xml":
|
|
||||||
assert i.filename.encode("cp437").decode("gbk") == "@_1_单位工程.xml"
|
|
||||||
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
|
|
||||||
ET.fromstring(unit)
|
|
||||||
assert "自增" in unit and "固定" not in unit
|
|
||||||
assert "导出规则:自增区域" in unit
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_member_names_gbk(server):
|
|
||||||
"""导出件成员名=GBK 原始字节、与 Project.xml 的 FileName 对得上(2026-11-03 主人实测乱码回归):
|
|
||||||
易达/广联达原件都是 GBK 条目名且不带 UTF-8 旗标;写成 UTF-8+旗标会被对方按 GBK 解读成乱码。"""
|
|
||||||
proj = "成员名工程-" + uuid.uuid4().hex[:6]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("nm_%s_raw.cos4" % proj[-6:])), proj,
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_nm.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
|
|
||||||
r = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert r.headers["content-type"].startswith("application/zip"), r.text[:300]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(r.content))
|
|
||||||
proj_xml = z.read("Project.xml").decode("utf-8")
|
|
||||||
n = 0
|
|
||||||
for i in z.infolist():
|
|
||||||
if i.filename == "Project.xml":
|
|
||||||
continue
|
|
||||||
n += 1
|
|
||||||
assert not (i.flag_bits & 0x800), "成员名不能带 UTF-8 旗标:%r" % i.filename
|
|
||||||
gbk = i.filename.encode("cp437").decode("gbk")
|
|
||||||
assert gbk.endswith(".xml"), gbk
|
|
||||||
assert 'FileName="%s"' % gbk in proj_xml, (gbk, proj_xml[:200])
|
|
||||||
assert n >= 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_unit_side_rows_exported(server):
|
|
||||||
"""单位工程非数据层(SummaryOfCost/AddiCost、AttrInfo…)也是数据:导入采集、导出按数据行重建。
|
|
||||||
2026-11-03 主人定「AddiCost 也是自增行,代码务必匹配」回归。"""
|
|
||||||
proj = "非数据层工程-" + uuid.uuid4().hex[:6]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("side_%s_raw.cos4" % proj[-6:])), proj,
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
# 给夹具补:SummaryOfCost 带 2 条 AddiCost;AttrInfo 一组两行;(项目级同款 2 条)
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for n in z.namelist():
|
|
||||||
d = z.read(n)
|
|
||||||
if n.lower() == "project.xml":
|
|
||||||
t = d.decode("utf-8")
|
|
||||||
t = t.replace(
|
|
||||||
'<SummaryOfCost Total="1234567.89"/>',
|
|
||||||
'<SummaryOfCost Total="1234567.89">'
|
|
||||||
'<AddiCost Code="P1" Name="项目附加费" Total="88"/>'
|
|
||||||
'<AddiCost Code="P2" Name="项目税差" Total="12"/></SummaryOfCost>')
|
|
||||||
d = t.encode("utf-8")
|
|
||||||
else:
|
|
||||||
t = d.decode("utf-8")
|
|
||||||
t = t.replace(
|
|
||||||
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
|
|
||||||
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>',
|
|
||||||
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
|
|
||||||
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000">'
|
|
||||||
'<AddiCost Code="A1" Name="附加费甲" Total="123"/>'
|
|
||||||
'<AddiCost Code="A2" Name="附加费乙" Total="45"/></SummaryOfCost>')
|
|
||||||
t = t.replace(
|
|
||||||
"</UnitWorks>",
|
|
||||||
'<AttrInfo><AttrInfoItem Name="组A" Code="G1" Value="" Remark="">'
|
|
||||||
'<AttrInfoItem Name="子1" Code="C1" Value="" Remark=""/>'
|
|
||||||
'</AttrInfoItem></AttrInfo></UnitWorks>')
|
|
||||||
d = t.encode("utf-8")
|
|
||||||
zo.writestr(n, d)
|
|
||||||
src = server["src_dir"] / ("side_%s.cos4" % proj[-6:])
|
|
||||||
src.write_bytes(buf.getvalue())
|
|
||||||
raw = open(str(src), "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_side.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
|
|
||||||
# 恢复旧引擎(2026-11-05 主人拍板):走 /api/session/export——非数据层=源件原样保留
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "name": proj,
|
|
||||||
"province": H.META["province"], "city": H.META["city"],
|
|
||||||
"period_from": H.PERIOD_202607})
|
|
||||||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
|
|
||||||
assert unit.count("<AddiCost") == 2, unit[:800]
|
|
||||||
assert 'Name="附加费甲"' in unit and 'Name="附加费乙"' in unit
|
|
||||||
assert 'Code="A2"' in unit and 'Total="45"' in unit
|
|
||||||
assert 'Name="组A"' in unit and 'Name="子1"' in unit
|
|
||||||
proj_xml = z.read("Project.xml").decode("utf-8")
|
|
||||||
assert proj_xml.count("<AddiCost") == 2, proj_xml[:800]
|
|
||||||
assert 'Name="项目附加费"' in proj_xml and 'Name="项目税差"' in proj_xml
|
|
||||||
assert 'Code="P2"' in proj_xml and 'Total="12"' in proj_xml
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 244 补五(2026-11-01 主人定「导出也按现算值,尽量按修改后的数据」)回归:
|
|
||||||
分部 Total / 费用表合计 / UnitWorks@Total 按 api 层现算值回填(export_cos._apply_div_totals,
|
|
||||||
api_server._uw_rollup_totals 算好随 plan 带入);配不上键的分部保持原件值(fail-open);
|
|
||||||
多 uw 文件分部照配对、费用表不动(归属不猜)。"""
|
|
||||||
import hashlib
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import uuid
|
|
||||||
import zipfile
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "server")))
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
import api_harness as H # noqa: E402
|
|
||||||
from api_harness import server # noqa: F401,E402 (夹具须经导入注册)
|
|
||||||
from api_harness import get, post # noqa: E402
|
|
||||||
|
|
||||||
XML1 = (
|
|
||||||
'<UnitWorks Number="U1" Name="某单位工程" Total="700000">'
|
|
||||||
'<SummaryOfCost Total="763000" Construction="700000" DivisionalAndElementalWorks="700000"'
|
|
||||||
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>'
|
|
||||||
'<DivisionalWorks Number="D1" Name="场地清理" Total="700000">'
|
|
||||||
'<WorkElement Number="B001" Name="清单甲" Unit="m3" Quantity="10.000" Price="10.00" Total="100.00"/>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'</UnitWorks>')
|
|
||||||
|
|
||||||
|
|
||||||
def test_div_total_and_summary_refilled():
|
|
||||||
"""分部 Total=现算值;SummaryOfCost QDF/Construction/Total、UnitWorks@Total 跟随现算。"""
|
|
||||||
plan = {"div_totals": {("D1", "场地清理"): [555.5], ("D9", "不存在的分部"): [1.0]},
|
|
||||||
"summary_updates": {"DivisionalAndElementalWorks": 555.5,
|
|
||||||
"Preliminaries": 50000.0, "Total": 60555.5,
|
|
||||||
"Construction": 555.5, "_uw_total": 555.5}}
|
|
||||||
out = xcos._apply_div_totals(XML1, {("U1", "某单位工程"): plan})
|
|
||||||
root = ET.fromstring(out)
|
|
||||||
assert root.attrib["Total"] == "555.50" # UnitWorks@Total 跟随
|
|
||||||
sm = root.find("SummaryOfCost")
|
|
||||||
assert sm.attrib["DivisionalAndElementalWorks"] == "555.50" # QDF 现算
|
|
||||||
assert sm.attrib["Total"] == "60555.50" # 费用恒等式合计
|
|
||||||
assert sm.attrib["Preliminaries"] == "50000.00" # 本造件无 CostForHSE 数据 → 仅散措施现算
|
|
||||||
dv = root.find("DivisionalWorks")
|
|
||||||
assert dv.attrib["Total"] == "555.50" # 分部现算回填
|
|
||||||
|
|
||||||
|
|
||||||
def test_div_unmatched_keeps_original():
|
|
||||||
"""(Number,Name) 配不上 → 分部 Total 保持原件值(fail-open);无 summary_updates 不动费用表。"""
|
|
||||||
plan = {"div_totals": {("DX", "不存在的分部"): [1.0]}, "summary_updates": {}}
|
|
||||||
out = xcos._apply_div_totals(XML1, {("U1", "某单位工程"): plan})
|
|
||||||
root = ET.fromstring(out)
|
|
||||||
assert root.find("DivisionalWorks").attrib["Total"] == "700000"
|
|
||||||
assert root.find("SummaryOfCost").attrib["DivisionalAndElementalWorks"] == "700000"
|
|
||||||
|
|
||||||
|
|
||||||
def test_multi_uw_div_paired_summary_untouched():
|
|
||||||
"""多 uw 文件:分部按各段配对回填;SummaryOfCost / UnitWorks@Total 不动(归属不猜)。"""
|
|
||||||
xml = XML1 + XML1.replace('Number="U1" Name="某单位工程"', 'Number="U2" Name="第二工程"')
|
|
||||||
p1 = {"div_totals": {("D1", "场地清理"): [555.5]},
|
|
||||||
"summary_updates": {"DivisionalAndElementalWorks": 555.5}}
|
|
||||||
p2 = {"div_totals": {("D1", "场地清理"): [888.0]}, "summary_updates": {}}
|
|
||||||
out = xcos._apply_div_totals(xml, {("U1", "某单位工程"): p1, ("U2", "第二工程"): p2})
|
|
||||||
root = ET.fromstring("<r>%s</r>" % out)
|
|
||||||
us = root.findall("UnitWorks")
|
|
||||||
assert len(us) == 2
|
|
||||||
assert us[0].find("DivisionalWorks").attrib["Total"] == "555.50"
|
|
||||||
assert us[1].find("DivisionalWorks").attrib["Total"] == "888.00"
|
|
||||||
assert us[0].find("SummaryOfCost").attrib["DivisionalAndElementalWorks"] == "700000" # 多 uw 不动
|
|
||||||
assert us[0].attrib["Total"] == "700000"
|
|
||||||
|
|
||||||
|
|
||||||
def test_rollup_end_to_end(server):
|
|
||||||
"""端到端:清单工程量 10→20(合价 1000→2000 自动重算)→ 导出件
|
|
||||||
分部 Total=2000.00、SummaryOfCost QDF=2000.00——修改后的数据传导到层级合计。"""
|
|
||||||
proj = "现算导出工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bills = [("B001", "清单甲", "1、x", "m3", 10.0, 100.0)]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("roll_%s_raw.cos4" % proj[-6:])), proj, bills)
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_roll.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "w+b") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bid = [r[0] for r in rows if r[1] == "B001"][0]
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
|
|
||||||
"bill_id": bid, "fields": {"Quantity": 20.0}})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
if not resp.headers["content-type"].startswith("application/zip"):
|
|
||||||
raise AssertionError("导出失败: " + resp.text[:300])
|
|
||||||
zf = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
|
|
||||||
if n.lower() != "project.xml")
|
|
||||||
root = ET.fromstring(txt)
|
|
||||||
sm = root.find("SummaryOfCost")
|
|
||||||
assert sm.attrib["DivisionalAndElementalWorks"] == "2000.00" # QDF 现算
|
|
||||||
assert sm.attrib["Preliminaries"] == "70000.00" # 散措施 50000 + 安监费 20000(274 补记七:易达口径含 HSE)
|
|
||||||
dv = root.find("DivisionalWorks")
|
|
||||||
if "Total" in dv.attrib: # 骨架有该列才回填(列由骨架闸门)
|
|
||||||
assert dv.attrib["Total"] == "2000.00" # 分部合价=修改后的清单合价
|
|
||||||
_we = root.find(".//WorkElement[@Number='B001']")
|
|
||||||
assert _we is not None
|
|
||||||
assert _we.attrib["Total"] == "2000.00" # 清单合价 2 位(决策 244 补六)
|
|
||||||
assert _we.attrib["Quantity"] == "20.0" # 随该清单源件原文位数(决策 274 补记三)
|
|
||||||
@@ -1,597 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 106(2026-10-17)两件实测事故的回归:
|
|
||||||
①插入节点整块克隆——此前新增清单/采纳定额只克隆开标签,缺原生 innards(费用构成汇总、
|
|
||||||
单价计算公式行、WorkContent 壳…),易达按结构取数看不到新增清单(cos 与 cos4 同样
|
|
||||||
实测),广联达整包报「不是有效标书」;
|
|
||||||
②工程量系数 GCL 口径——旧口径(定额量÷清单量)在 10m/100m 类单位上把单位换算双算两遍
|
|
||||||
(前山河 040501004001:10m 定额导出量少 10 倍实测)。
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
import zipfile
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "server")))
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
import api_harness as H # noqa: E402
|
|
||||||
from api_harness import server # noqa: F401,E402 (夹具须经导入注册)
|
|
||||||
from api_harness import get, post # noqa: E402
|
|
||||||
|
|
||||||
# 珠海 .cos 形态的原生清单块(费用构成 + 工程量表达式行 + 定额内 管理费/单价计算公式行)
|
|
||||||
RICH_BILL = (
|
|
||||||
'<WorkElement Number="040803004001" Name="管道封堵" Attr="1、封堵现状管" WorkContent="" Unit="个"'
|
|
||||||
' Quantity="2.000" QtyFormula="" Price="1187.14" Total="2374.28" EquipmentPrice="0" Rate="0"'
|
|
||||||
' PriceLow="0" PriceHigh="0" Major="false" CalcType="1" Code="" ListingIdentity="GB50857-2013 4 GD"'
|
|
||||||
' Specialty="4" Kind="1" CalculationKind="15" CostKind="3" Remark="L:3平面图中只见2个">'
|
|
||||||
'<SummaryOfBasicCost Labor="269.72" Material="880.90" MainMaterial="0" Equipment="0"'
|
|
||||||
' MainMaterialEquipment="0" Appraisal="0" Machine="856.42" Overhead="198.32" Profit="168.92"'
|
|
||||||
' StatutoryFees="0" Tax="0" ForeignCurrency="0" ConvertedIntoRMB="0"/>'
|
|
||||||
'<ExpressElement OrderNumber="1" Express="2" Quantity="2" Kind="1" Remark=""/>'
|
|
||||||
'<Norm Number="3-1-1" Name="管堵砌筑 直径(mm内) DN600//调:" Unit="只" Quantity="2.000000"'
|
|
||||||
' Price="1187.14" EquipmentPrice="0" Total="2374.28" EfficiencyKind="2" IncFeeKind="2"'
|
|
||||||
' Conversion="" Specialty="99" NormIdentity="GD 99 2019" Volume="0" Chapter="0"'
|
|
||||||
' EquipmentTotal="0" ForeignCurrency="0" ConvertedIntoRMB="0" IsNorm="true" Kind="1"'
|
|
||||||
' CalculationKind="15" CostKind="3" Remark="">'
|
|
||||||
'<ExpressElement OrderNumber="1" Express="QGCL" Quantity="2" Kind="1" Remark=""/>'
|
|
||||||
'<ManageFees Fee1="17.61" Fee2="17.61" Fee3="17.61" Fee4="17.61" Rate="1.00"'
|
|
||||||
' AddFee1="0" AddFee2="0" AddFee3="0" AddFee4="0"/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="134.86" NOCost="false" Remark=""/>'
|
|
||||||
'<UnitPriceCalculationOfItem Code="RGF" Name="人工费" Total="134.86" QtyFormula="_RGF" Rate="100.000" Remark="人工费"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Code="HJ" Name="子目合价" Total="2374.28" QtyFormula="_GCL*7" Rate="100.000" Remark="工程量*单价"/>'
|
|
||||||
'</Norm></WorkElement>')
|
|
||||||
|
|
||||||
NEW_BILL = {"id": 901, "Number": "040101001002", "Name": "路基挖土方(可利用方)",
|
|
||||||
"Attr": "1、土类别:综合", "Unit": "m3", "Quantity": 1000.0,
|
|
||||||
"Price": 4.54, "Total": 4540.0, "src_remark": None}
|
|
||||||
NEW_NORM = {"id": 902, "Number": "D1-1-29", "Name": "挖掘机挖一般土方 一、二类土",
|
|
||||||
"Unit": "1000m3天然密实方", "Quantity": 1.0, "Price": 4540.91, "Total": 4540.91}
|
|
||||||
|
|
||||||
|
|
||||||
def _parse(frag):
|
|
||||||
return ET.fromstring("<r>%s</r>" % frag)[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_full_structure_cos():
|
|
||||||
"""新增清单整块克隆:费用构成清零在位、公式保留、定额带单价计算公式行、备注不带模板的。"""
|
|
||||||
out = xcos._bill_xml(NEW_BILL, "WorkElement",
|
|
||||||
[xcos._norm_xml(NEW_NORM, [("00010010", 594.0)],
|
|
||||||
xcos._full_norm_block(RICH_BILL))],
|
|
||||||
RICH_BILL)
|
|
||||||
we = _parse(out)
|
|
||||||
assert [c.tag for c in we] == ["SummaryOfBasicCost", "ExpressElement", "Norm"]
|
|
||||||
sbc = we.find("SummaryOfBasicCost")
|
|
||||||
assert all(v == "0" for v in sbc.attrib.values()) # 别人的金额一个不带
|
|
||||||
ee = we.find("ExpressElement")
|
|
||||||
assert ee.get("Quantity") == "0" and ee.get("Express") == ""
|
|
||||||
assert ee.get("OrderNumber") == "1" # 结构属性保留
|
|
||||||
norm = we.find("Norm")
|
|
||||||
assert norm.get("Number") == "D1-1-29" and norm.get("Quantity") == "1.000000"
|
|
||||||
assert norm.get("NormIdentity") == "GD 99 2019" # 属性集照旧齐全(决策 64)
|
|
||||||
upc = norm.findall("UnitPriceCalculationOfItem")
|
|
||||||
assert len(upc) == 2 and all(c.get("Total") == "0" for c in upc)
|
|
||||||
assert upc[0].get("QtyFormula") == "_RGF" # 公式保留,易达打开可重算
|
|
||||||
assert norm.find("ManageFees").get("Rate") == "1.00"
|
|
||||||
assert norm.find("ManageFees").get("Fee1") == "0"
|
|
||||||
assert [c.get("Number") for c in norm.findall("LabourMaterialsEquipmentsMachinesElement")] == ["00010010"]
|
|
||||||
assert we.get("Remark") == "" # 模板备注(别人的)不带
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_empty_attr_cleared():
|
|
||||||
"""新增清单无特征:不得把锚点/模板的特征带过去(2026-10-20 220kV 实测)。"""
|
|
||||||
b = dict(NEW_BILL, Attr="")
|
|
||||||
we = _parse(xcos._bill_xml(b, "WorkElement", [], RICH_BILL))
|
|
||||||
assert we.get("Attr") == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_appended_norm_keeps_innards():
|
|
||||||
"""采纳定额追加进原有清单:innards 一并克隆(此前裸 Norm 同样过不了结构关)。"""
|
|
||||||
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], xcos._full_norm_block(RICH_BILL))
|
|
||||||
norm = _parse(out)
|
|
||||||
# 补记二十一:采纳定额不带数量算式行(Express 大于 Quantity,易达会按算式显示代号/方括号)
|
|
||||||
assert [c.tag for c in norm] == ["ManageFees",
|
|
||||||
"LabourMaterialsEquipmentsMachinesElement",
|
|
||||||
"UnitPriceCalculationOfItem", "UnitPriceCalculationOfItem"]
|
|
||||||
assert all(c.get("Total") == "0" for c in norm.findall("UnitPriceCalculationOfItem"))
|
|
||||||
assert norm.findall("ExpressElement") == [] # 补记二十一:采纳定额不带数量算式行(易达才显示纯数字,不带方括号)
|
|
||||||
assert norm.get("Remark") == "" # 决策 101 口径不变
|
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_minimal_template_unchanged():
|
|
||||||
"""模板只是开标签(旧调用形态/夹具最小清单)→ 输出与旧版一致,不造 innards。"""
|
|
||||||
nb = xcos._full_norm_block(RICH_BILL)
|
|
||||||
opentag = nb[:xcos._open_tag_end(nb, 0)]
|
|
||||||
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], opentag)
|
|
||||||
norm = _parse(out)
|
|
||||||
assert [c.tag for c in norm] == ["LabourMaterialsEquipmentsMachinesElement"]
|
|
||||||
bill_opentag = RICH_BILL[:xcos._open_tag_end(RICH_BILL, 0)]
|
|
||||||
out_b = xcos._bill_xml(NEW_BILL, "WorkElement", [out], bill_opentag)
|
|
||||||
we = _parse(out_b)
|
|
||||||
assert [c.tag for c in we] == ["Norm"]
|
|
||||||
assert we.get("Remark") == "" # 决策 106:新增清单没源备注时模板备注一律不带(旧版会泄漏锚点的备注)
|
|
||||||
|
|
||||||
|
|
||||||
def test_yida_sample_template_leaks_fixed():
|
|
||||||
"""主人 2026-10-17 提供的易达样本(锚杆 010302006002,LME 带 Express 值、定额带
|
|
||||||
NormAdjustmentList 换算记录):克隆进新节点时这些「别人的值」一律不带——
|
|
||||||
Express 清空、换算记录整行不落(架子可以有,别人的数据不能有)。"""
|
|
||||||
yida_norm = (
|
|
||||||
'<Norm Number="A1-2-48" Name="锚杆土钉机械成孔 土层 孔径≤150mm" Unit="100m" Quantity="19.010000"'
|
|
||||||
' Price="6077.49" Total="115533.08" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
|
|
||||||
'<ExpressElement OrderNumber="1" Area="" Express="QGCL" Explain="" Quantity="1901" Kind="1" Remark=""/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="1715.0700" Quantity="1715.0700" Remark=""/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00" Total="1852.28" Code="RGF" Remark="人工费"/>'
|
|
||||||
'<NormAdjustmentList OrderNumber="1" Value="换:工程地质液压钻机 "/>'
|
|
||||||
'<NormAdjustmentList OrderNumber="3" Value="修改990212120-0001单价:760.74"/>'
|
|
||||||
'</Norm>')
|
|
||||||
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], yida_norm)
|
|
||||||
norm = _parse(out)
|
|
||||||
lme = norm.find("LabourMaterialsEquipmentsMachinesElement")
|
|
||||||
assert lme.get("Express") == "594.0" and lme.get("Quantity") == "594.0" # 模板的 1715.0700 不带,填本行含量
|
|
||||||
assert norm.findall("NormAdjustmentList") == [] # 换算记录不背给新定额
|
|
||||||
assert norm.find("UnitPriceCalculationOfItem").get("Total") == "0"
|
|
||||||
assert norm.find("UnitPriceCalculationOfItem").get("QtyFormula") == "_RGF"
|
|
||||||
# 清单级单价公式行的 QtyFormula 若是**纯数字字面量**(有的文件直接存数值)也清空——
|
|
||||||
# 那是模板清单自己的单价/合价,留着会被按公式求值显示(220kV 件实测背 189006.16)
|
|
||||||
assert xcos._zero_results('<UnitPriceCalculationOfItem Name="子目合价" QtyFormula="189006.16"'
|
|
||||||
' Rate="100.00" Total="0" Code="HJ" Remark=""/>').count('QtyFormula=""') == 1
|
|
||||||
assert '_GCL*7' in xcos._zero_results('<UnitPriceCalculationOfItem Name="子目合价" QtyFormula="_GCL*7"'
|
|
||||||
' Rate="100.00" Total="0" Code="HJ" Remark=""/>') # 通用公式保留
|
|
||||||
# 工料机行模板(bill 尾表重建)同样清 Express
|
|
||||||
row = xcos._lme_row('<LabourMaterialsEquipmentsMachinesElement Number="00010010"'
|
|
||||||
' Express="90.5224" Quantity="90.5224" Remark=""/>', "GLF", 0)
|
|
||||||
assert 'Number="GLF"' in row and 'Express=""' in row and 'Quantity="0"' in row
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_workcontent_profile_cos4():
|
|
||||||
"""cos4(WorkContent 画像):新增清单的定额逐条包 WorkContent 壳(决策 98 同款),
|
|
||||||
清单级工料机尾表按会话资源重建(0 量)、模板的金额清零。"""
|
|
||||||
tmpl = ('<WorkElement Number="040101001001" Name="挖一般土方" Attr="1、土壤类别:综合" WorkContent=""'
|
|
||||||
' Unit="m3" Quantity="1483.220" Price="4.29" Total="6363.01" Type="1" PriceType="1"'
|
|
||||||
' ListingIdentity="GB/T 50857-2024 4 440000" Specialty="4" Kind="1" Remark="">'
|
|
||||||
'<SummaryOfBasicCost Labor="951.52" Material="0" Machine="4034.54" Overhead="628.74"'
|
|
||||||
' Profit="747.91" DivisionalAndElementalWorks="6363.01" Tax="0"/>'
|
|
||||||
'<ExpressElement OrderNumber="1" Area="" Express="1483.22" Explain="" Quantity="1483.22" Kind="1" Remark=""/>'
|
|
||||||
'<WorkContent Name="土方开挖" Total="6362.70" Remark="">'
|
|
||||||
'<Norm Number="D1-1-29" Name="挖掘机挖一般土方 一、二类土" Unit="1000m3天然密实方" Quantity="1.483220"'
|
|
||||||
' Price="4289.79" Total="6362.70" Specialty="4" NormIdentity="440000 4 2018" IsNorm="true" Type="1" Remark="">'
|
|
||||||
'<ExpressElement OrderNumber="1" Area="" Express="QGCL" Explain="" Quantity="1483.22" Kind="1" Remark=""/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="" Quantity="594.0000" Remark=""/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00" Total="641.52" Code="RGF" Remark="人工费"/>'
|
|
||||||
'</Norm></WorkContent>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="" Quantity="881.00" Remark=""/>'
|
|
||||||
'</WorkElement>')
|
|
||||||
out = xcos._bill_xml(NEW_BILL, "WorkElement",
|
|
||||||
[xcos._norm_xml(NEW_NORM, [("990101015", 0.117)],
|
|
||||||
xcos._full_norm_block(tmpl))],
|
|
||||||
tmpl)
|
|
||||||
we = _parse(out)
|
|
||||||
wcs = we.findall("WorkContent")
|
|
||||||
assert len(wcs) == 1 and wcs[0].get("Name") == "路基挖土方(可利用方)" # 逐条包壳,名照本清单
|
|
||||||
assert wcs[0].get("Total") == "4540.00"
|
|
||||||
assert wcs[0].find("Norm").get("Number") == "D1-1-29"
|
|
||||||
assert wcs[0].find("Norm").find("UnitPriceCalculationOfItem").get("Total") == "0"
|
|
||||||
tail = [c for c in we.findall("LabourMaterialsEquipmentsMachinesElement")]
|
|
||||||
assert [c.get("Number") for c in tail] == ["990101015"] # 尾表按会话资源重建
|
|
||||||
assert tail[0].get("Quantity") == "0.0001" # 0.117×1÷1000 = 每单位消耗量
|
|
||||||
assert we.find("SummaryOfBasicCost").get("DivisionalAndElementalWorks") == "0"
|
|
||||||
assert we.find("ExpressElement").get("Quantity") == "0"
|
|
||||||
|
|
||||||
|
|
||||||
def test_bill_tail_lme_real_values():
|
|
||||||
"""清单级消耗量架子填真值(决策 106 补记,主人广联达样本同款算法):
|
|
||||||
Σ(定额含量×定额量)÷清单量,跨定额同码合并一行、Express 照原生填同值;
|
|
||||||
广联达样本实测数:人工 (1611.66×100+595.03×10)÷10000 = 16.7116。"""
|
|
||||||
tmpl = ('<WorkElement Number="010101001001" Name="挖单独土方" WorkContent="" Unit="m3"'
|
|
||||||
' Quantity="10000" Price="126.17" Total="1261700" NormIdentity="X" Kind="1" Remark="">'
|
|
||||||
'<SummaryOfBasicCost Labor="1" Material="0" Tax="0"/>'
|
|
||||||
'<WorkContent Name="开挖" Total="1" Remark="">'
|
|
||||||
'<Norm Number="A1-1-5" Name="人工挖一般土方 一、二类土" Unit="100m3" Quantity="100"'
|
|
||||||
' Price="2183.8" Total="218380" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="1611.6600" Remark="" Express="1611.66*1"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
|
|
||||||
'</Norm>'
|
|
||||||
'<Norm Number="A1-1-37" Name="挖掘机挖一般土方 一、二类土" Unit="1000m3" Quantity="10"'
|
|
||||||
' Price="4323.21" Total="43232.1" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="595.0300" Remark="" Express="595.03*1"/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="990101015" Quantity="0.1700" Remark="" Express="0.17*1"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
|
|
||||||
'</Norm></WorkContent>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="90.5224" Remark="" Express="90.5224"/>'
|
|
||||||
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
|
|
||||||
'</WorkElement>')
|
|
||||||
bill = dict(NEW_BILL, Quantity=10000.0)
|
|
||||||
n1 = dict(NEW_NORM, Number="A1-1-5", Unit="100m3", Quantity=100.0)
|
|
||||||
n2 = dict(NEW_NORM, Number="A1-1-37", Unit="1000m3", Quantity=10.0)
|
|
||||||
out = xcos._bill_xml(bill, "WorkElement",
|
|
||||||
[xcos._norm_xml(n1, [("00010010", 1611.66)], xcos._full_norm_block(tmpl)),
|
|
||||||
xcos._norm_xml(n2, [("00010010", 595.03), ("990101015", 0.17)],
|
|
||||||
xcos._full_norm_block(tmpl))],
|
|
||||||
tmpl)
|
|
||||||
we = _parse(out)
|
|
||||||
tail = we.findall("LabourMaterialsEquipmentsMachinesElement")
|
|
||||||
assert [(c.get("Number"), c.get("Quantity"), c.get("Express")) for c in tail] == [
|
|
||||||
("00010010", "16.7116", "16.7116"), # 同码合并:(1611.66×100+595.03×10)÷10000
|
|
||||||
("990101015", "0.0002", "0.0002"), # 0.17×10÷10000
|
|
||||||
], [(c.get("Number"), c.get("Quantity")) for c in tail]
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_top_anchor_position(server):
|
|
||||||
"""决策 106 补记四:工作台插在最上面(insert_above 第一条 → 锚点 0)的新增清单,
|
|
||||||
导出落位 = 第一条源清单**之前**。此前锚点 0 被当「无锚点」甩到组尾
|
|
||||||
(主人 2026-10-18 实测:软件里插序号 1,易达里跑到最后)。"""
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
proj = "顶部插入工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bills = [("B00%d" % i, "清单%d" % i, "1、x", "m3", 10 + i, 100.0) for i in (1, 2, 3)]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("top_%s_raw.cos4" % proj[-6:])), proj, bills)
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_top.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "w+b") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] # 决策 243:工作台用同内容双胞胎件
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
first_id = [r[0] for r in rows if r[1] == "B001"][0]
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "insert_above",
|
|
||||||
"bill_id": first_id})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
new_id = r["id"]
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit", "bill_id": new_id,
|
|
||||||
"fields": {"Name": "顶部新增清单"}})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
zf = _export_zip(server, sid)
|
|
||||||
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
|
|
||||||
if n.lower() != "project.xml")
|
|
||||||
assert txt.index('Name="顶部新增清单"') < txt.index('Number="B001"'), "新增清单应在第一条源清单之前"
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_follows_own_division():
|
|
||||||
"""新增清单落位按自己的 div_id 找同分部锚点——2026-10-20 220kV 实测:
|
|
||||||
C20原色透水混凝土 div=支撑下挖土,但前一条源清单在顶管井部分,旧逻辑会插错分部。"""
|
|
||||||
xml = (
|
|
||||||
'<UnitWorks Number="U1" Name="UW1">'
|
|
||||||
'<DivisionalWorks Name="DIV_A" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="A001" Name="源清单A" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="10.00" Total="10.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'<DivisionalWorks Name="DIV_B" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="B001" Name="源清单B" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="20.00" Total="20.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'</UnitWorks>')
|
|
||||||
|
|
||||||
def bill(i, div, num, name, price):
|
|
||||||
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
|
|
||||||
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
|
|
||||||
"src_remark": None, "x_tdel": 0}
|
|
||||||
|
|
||||||
a, b = bill(1, 1, "A001", "源清单A", "10.00"), bill(2, 2, "B001", "源清单B", "20.00")
|
|
||||||
new = bill(3, 2, "C001", "新增透水混凝土", "53.23")
|
|
||||||
new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0})
|
|
||||||
out = xcos.transform_unit(xml, ("U1", "UW1"),
|
|
||||||
{"item": [(1, a), (2, b)]},
|
|
||||||
{"item": [new]}, {}, {})
|
|
||||||
i_div_b = out.index('Name="DIV_B"')
|
|
||||||
i_new = out.index('Name="新增透水混凝土"')
|
|
||||||
i_b = out.index('Number="B001"')
|
|
||||||
assert i_div_b < i_new < i_b, out
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_bill_middle_of_own_division():
|
|
||||||
"""分部内下插:锚点在同一个分部时,插在锚点源清单之后、下一条同分部源清单之前。"""
|
|
||||||
xml = (
|
|
||||||
'<UnitWorks Number="U3" Name="UW3">'
|
|
||||||
'<DivisionalWorks Name="DIV_A" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="A1" Name="源A1" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="10.00" Total="10.00" Remark=""></WorkElement>'
|
|
||||||
'<WorkElement Number="A2" Name="源A2" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="20.00" Total="20.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'<DivisionalWorks Name="DIV_B" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="B1" Name="源B1" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="30.00" Total="30.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'</UnitWorks>')
|
|
||||||
|
|
||||||
def bill(i, div, num, name, price):
|
|
||||||
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
|
|
||||||
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
|
|
||||||
"src_remark": None, "x_tdel": 0}
|
|
||||||
|
|
||||||
a1, a2, b1 = (bill(1, 1, "A1", "源A1", "10.00"),
|
|
||||||
bill(2, 1, "A2", "源A2", "20.00"),
|
|
||||||
bill(3, 2, "B1", "源B1", "30.00"))
|
|
||||||
new = bill(4, 1, "C1", "分部内新增", "30.00")
|
|
||||||
new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 3000.0})
|
|
||||||
out = xcos.transform_unit(xml, ("U3", "UW3"),
|
|
||||||
{"item": [(1, a1), (2, a2), (3, b1)]},
|
|
||||||
{"item": [new]}, {}, {})
|
|
||||||
assert (out.index('Number="A1"') < out.index('Name="分部内新增"')
|
|
||||||
< out.index('Number="A2"')), out
|
|
||||||
|
|
||||||
|
|
||||||
def test_new_loose_bill_appends_at_end():
|
|
||||||
"""无分部(loose)新增行:工作台显示在单位工程树尾,导出也要落在本组最后,
|
|
||||||
不能按 x_seq=1 跑到最前(2026-10-20 220kV 实测)。"""
|
|
||||||
xml = (
|
|
||||||
'<UnitWorks Number="U2" Name="UW2">'
|
|
||||||
'<DivisionalWorks Name="DA" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="A1" Name="源清单A" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="10.00" Total="10.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'<DivisionalWorks Name="DB" Kind="1" ChapterKind="4">'
|
|
||||||
'<WorkElement Number="B1" Name="源清单B" Attr="" Unit="m3" Quantity="1.000"'
|
|
||||||
' Price="20.00" Total="20.00" Remark=""></WorkElement>'
|
|
||||||
'</DivisionalWorks>'
|
|
||||||
'</UnitWorks>')
|
|
||||||
|
|
||||||
def bill(i, div, num, name, price):
|
|
||||||
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
|
|
||||||
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
|
|
||||||
"src_remark": None, "x_tdel": 0}
|
|
||||||
|
|
||||||
a, b = bill(1, 1, "A1", "源清单A", "10.00"), bill(2, 2, "B1", "源清单B", "20.00")
|
|
||||||
new = bill(3, None, "C1", "末尾新增清单", "53.23")
|
|
||||||
new.update({"_anchor": 0, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0})
|
|
||||||
out = xcos.transform_unit(xml, ("U2", "UW2"),
|
|
||||||
{"item": [(1, a), (2, b)]},
|
|
||||||
{"item": [new]}, {}, {})
|
|
||||||
assert out.index('Number="B1"') < out.index('Name="末尾新增清单"'), out
|
|
||||||
|
|
||||||
|
|
||||||
def test_amount_aggregate_row_synced_like_normal():
|
|
||||||
"""决策 169(2026-10-22 主人定):金额汇总行(数量=金额合计、单价=1 的费用科目行)
|
|
||||||
**视同普通工料机**——编辑/同步/导出回填全部同普通行,价格照写。
|
|
||||||
原决策 106 补记九「金额行不回写价格」防护撤除:实测爆炸来自旧全量同步的大面积
|
|
||||||
误写,现通道(merged_codes/field_codes 白名单)只有编辑过的编码才会被写。"""
|
|
||||||
txt = ('<ConstructionProject>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="人工费" Unit="元"'
|
|
||||||
' Quantity="4142082.6" NoTaxPrice="1" TaxRate="0" TaxPrice="1"/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="履带式推土机" Unit="台班"'
|
|
||||||
' Quantity="6.1" NoTaxPrice="1039.8" TaxRate="9.48" TaxPrice="1138.37"/>'
|
|
||||||
'</ConstructionProject>')
|
|
||||||
sync = [("00010010", "人工费", "", "元", 500.0, 0.0, 500.0),
|
|
||||||
("990101015", "履带式推土机", "", "台班", 1232.54, 0.0, 1232.54)]
|
|
||||||
out = xcos.transform_project(txt, [], [], sync_rows=sync)
|
|
||||||
agg = re.search(r'<LabourMaterialsEquipmentsMachinesSummary Number="00010010"[^>]*', out).group(0)
|
|
||||||
assert 'NoTaxPrice="500.0"' in agg and 'TaxPrice="500.0"' in agg # 视同普通行:价格照写
|
|
||||||
mac = re.search(r'<LabourMaterialsEquipmentsMachinesSummary Number="990101015"[^>]*', out).group(0)
|
|
||||||
assert 'NoTaxPrice="1232.54"' in mac # 正常资源行照常回写
|
|
||||||
|
|
||||||
|
|
||||||
def test_adoption_carries_express_adjustment(server):
|
|
||||||
"""决策 106 补记十二:定额换算调整式(含量 Express,如人工费 *1.2)跟历史项目走——
|
|
||||||
导入捕获入库 → 采纳携带 → 导出按算式原样填写(此前只存数值,调整信息丢失)。"""
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
proj = "调整式工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("expr_%s_raw.cos4" % proj[-6:])), proj, bills)
|
|
||||||
# 给夹具的定额工料机行补上换算算式(模拟广联达原生 Express)
|
|
||||||
z = _zipfile.ZipFile(p) if False else zipfile.ZipFile(p)
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for nm in z.namelist():
|
|
||||||
d = z.read(nm)
|
|
||||||
if nm.lower() != "project.xml":
|
|
||||||
d = d.replace(b'Quantity="1.5"/>', b'Quantity="1.5" Express="1.5*1.2"/>')
|
|
||||||
d = d.replace(b' NormIdentity="N1"', b' NormIdentity="TEST 1 2018"') # 夹具已带 NormIdentity(2026-11-05 恢复旧引擎后造件补齐),改值不再插入
|
|
||||||
zo.writestr(nm, d)
|
|
||||||
raw = buf.getvalue()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_expr.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
hc = sqlite3.connect(server["db"])
|
|
||||||
got = hc.execute("SELECT express FROM norm_res WHERE express IS NOT NULL").fetchall()
|
|
||||||
hc.close()
|
|
||||||
assert got and got[0][0] == "1.5*1.2", got[:3] # 导入捕获算式
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
resp = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp))) # 决策 243
|
|
||||||
assert resp.get("session_id"), resp
|
|
||||||
sid = resp["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bill_id = [r[0] for r in rows if r[1] == bills[0][0]][0]
|
|
||||||
src_id = sqlite3.connect(server["db"]).execute(
|
|
||||||
"SELECT id FROM bills WHERE Number=?", (bills[0][0],)).fetchone()[0]
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
se = sqlite3.connect(server["sessdb"])
|
|
||||||
got = se.execute("SELECT express FROM s_norm_res WHERE norm_id IN "
|
|
||||||
"(SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1)", (bill_id,)).fetchall()
|
|
||||||
se.close()
|
|
||||||
assert got and got[0][0] == "1.5*1.2", got[:3] # 采纳携带
|
|
||||||
zf = _export_zip(server, sid)
|
|
||||||
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
|
|
||||||
if n.lower() != "project.xml")
|
|
||||||
import re as _re
|
|
||||||
mm = _re.search(r'<Norm Number="N-1".{0,600}?</Norm>', txt, _re.S)
|
|
||||||
print('ADOPTED NORM BLOCK:', mm.group(0)[:600] if mm else '(N-1 不在导出中)')
|
|
||||||
print('txt has N-1:', 'N-1' in txt, '| txt len:', len(txt))
|
|
||||||
assert 'Express="1.5*1.2"' in txt # 导出按历史调整式填写
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_resource_pseudo_norm_skipped_on_import(server):
|
|
||||||
"""决策 106 补记十四:广联达把清单级资源构成行(人工费等,编码=纯数字工料机码、
|
|
||||||
单位=元)也写成 <Norm> 元素——不是定额,导入即滤掉(此前被采纳当定额带进
|
|
||||||
工作台=人工费外溢实测);真定额与调整记录不受影响。"""
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
proj = "伪定额过滤工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("pseudo_%s_raw.cos4" % proj[-6:])), proj, bills)
|
|
||||||
z = zipfile.ZipFile(p)
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for nm in z.namelist():
|
|
||||||
d = z.read(nm)
|
|
||||||
if nm.lower() != "project.xml":
|
|
||||||
pseudo = ('<Norm Number="00010010" Name="人工费" Unit="元" Quantity="89.1513"'
|
|
||||||
' Price="1.2" Total="106.98" IsNorm="true" Type="1" CalculationKind="1"'
|
|
||||||
' CostKind="1" EfficiencyKind="2" IncFeeKind="2" Specialty="1"'
|
|
||||||
' NormIdentity="TEST 1 2018" Remark=""/>').encode("utf-8")
|
|
||||||
d = d.replace(b'</Norm></WorkElement>', b'</Norm>' + pseudo + b'</WorkElement>')
|
|
||||||
zo.writestr(nm, d)
|
|
||||||
raw = buf.getvalue()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_pseudo.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
hc = sqlite3.connect(server["db"])
|
|
||||||
n = hc.execute("SELECT COUNT(*) FROM norms WHERE Number='00010010'").fetchone()[0]
|
|
||||||
hc.close()
|
|
||||||
assert n == 0, n # 伪定额不落批次库
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] # 决策 243:工作台用同内容双胞胎件
|
|
||||||
sc = sqlite3.connect(server["sessdb"])
|
|
||||||
n2 = sc.execute("SELECT COUNT(*) FROM s_norms WHERE Number='00010010'").fetchone()[0]
|
|
||||||
n3 = sc.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0]
|
|
||||||
sc.close()
|
|
||||||
assert n2 == 0 and n3 >= 1, (n2, n3) # 工作台也不出现(外溢源头掐断)
|
|
||||||
|
|
||||||
|
|
||||||
def test_edited_totals_follow_qty_times_price(server):
|
|
||||||
"""决策 106 补记十六(主人定):清单/定额 合价 = 工程量×单价——
|
|
||||||
改工程量后(工作台保存时 + 导出兜底)合价跟着走;数值相同不产生字节改动。"""
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
proj = "合价口径工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bills = [("B001", "挖单独土方", "1、x", "m3", 10, 500)]
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("total_%s_raw.cos4" % proj[-6:])), proj, bills)
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_total.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] # 决策 243:工作台用同内容双胞胎件
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bill_id = [r[0] for r in rows if r[1] == "B001"][0]
|
|
||||||
norm_id = sqlite3.connect(server["sessdb"]).execute(
|
|
||||||
"SELECT id FROM s_norms WHERE bill_id=?", (bill_id,)).fetchone()[0]
|
|
||||||
# 改清单工程量 10→20:合价 = 20×500
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
|
|
||||||
"bill_id": bill_id, "fields": {"Quantity": "20"}})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
tb = sqlite3.connect(server["sessdb"]).execute(
|
|
||||||
"SELECT Total FROM s_bills WHERE id=?", (bill_id,)).fetchone()[0]
|
|
||||||
assert abs(tb - 10000) < 0.01, tb # 工作台保存即同步
|
|
||||||
# 改定额工程量 10→15(数字):合价 = 15×80
|
|
||||||
r = post(server, "/api/session/norm/op", {"session_id": sid, "norm_id": norm_id,
|
|
||||||
"fields": {"Quantity": "15"}})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
tn = sqlite3.connect(server["sessdb"]).execute(
|
|
||||||
"SELECT Total FROM s_norms WHERE id=?", (norm_id,)).fetchone()[0]
|
|
||||||
assert abs(tn - 1200) < 0.01, tn # 15×80
|
|
||||||
zf = _export_zip(server, sid)
|
|
||||||
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
|
|
||||||
if n.lower() != "project.xml")
|
|
||||||
assert 'Total="10000.00"' in txt, "清单合价应=20×500(2 位小数,决策 244 补六)"
|
|
||||||
import re as _re2
|
|
||||||
|
|
||||||
assert 'Total="1200.00"' in txt, "定额合价应=15×80"
|
|
||||||
|
|
||||||
|
|
||||||
def _export_zip(server, sid):
|
|
||||||
# 决策 264 补记(2026-11-03):原格式导出只走骨架回灌——测试就地从本会话源件提炼一件骨架
|
|
||||||
# (真实流程=后台上传骨架;这里不依赖本机预置件,保证同口径可跑)。
|
|
||||||
sc = sqlite3.connect(server["sessdb"])
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
srow = sc.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
|
|
||||||
finally:
|
|
||||||
sc.close()
|
|
||||||
src_name = srow["src_name"] if srow else ""
|
|
||||||
sfx = xcos_suffix(src_name)
|
|
||||||
hc = sqlite3.connect(server["db"])
|
|
||||||
hc.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
src = os.path.join(str(server["root"]), "CostReview", "data", "source_files", src_name)
|
|
||||||
if os.path.exists(src):
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
_cs.seed_frame(hc, src, "测试骨架-" + (sfx or "x"))
|
|
||||||
finally:
|
|
||||||
hc.close()
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
if not resp.headers["content-type"].startswith("application/zip"):
|
|
||||||
raise AssertionError("导出失败: " + resp.text[:300])
|
|
||||||
return zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
|
|
||||||
|
|
||||||
def xcos_suffix(name):
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
return _cs.suffix_of(name)
|
|
||||||
|
|
||||||
|
|
||||||
def test_coef_unit_prefix_no_double_count(server):
|
|
||||||
"""10m 定额:历史 清单1094.68 / 定额109.468 → 系数 GCL 口径 = 1.0,
|
|
||||||
清单量改 90000000 后导出定额量 = 9000000(=GCL,单位换算只算一次)。"""
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
proj = "系数口径工程-" + uuid.uuid4().hex[:6]
|
|
||||||
bill = ("040501004001", "高性能硬聚乙烯PVC-UH排水管DN200", "1、x", "m", 1094.68, 63.31)
|
|
||||||
lme = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("coef_%s_raw.cos4" % proj[-6:])), proj, [bill], [lme])
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_coef.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "w+b") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
# 把该批次定额改成 10m 口径的历史形态(清单 1094.68m、定额 109.468 每 10m),
|
|
||||||
# 系数按 GCL 口径 = 定额量×前缀÷清单量 = 1.0
|
|
||||||
hc = sqlite3.connect(server["db"])
|
|
||||||
hc.execute("UPDATE norms SET Unit='10m', Quantity=109.468,"
|
|
||||||
" x_qty_coef=ROUND(109.468*10/(SELECT Quantity FROM bills WHERE bills.id=norms.bill_id),6)")
|
|
||||||
hc.commit(); hc.close()
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] # 决策 243:工作台用同内容双胞胎件
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
|
|
||||||
bill_id = [r[0] for r in rows if r[1] == bill[0]][0]
|
|
||||||
src_id = sqlite3.connect(server["db"]).execute(
|
|
||||||
"SELECT id FROM bills WHERE Number=?", (bill[0],)).fetchone()[0]
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
expr = sqlite3.connect(server["sessdb"]).execute(
|
|
||||||
"SELECT qty_expr FROM s_norms WHERE bill_id=? AND x_adopt=1", (bill_id,)).fetchone()[0]
|
|
||||||
assert expr == "GCL*1.0000", expr # 旧口径这里会给 GCL*0.1000(双算单位)
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("UPDATE s_bills SET Quantity=90000000 WHERE id=?", (bill_id,))
|
|
||||||
con.commit(); con.close()
|
|
||||||
zf = _export_zip(server, sid)
|
|
||||||
hits = sum(zf.read(n).count(b'Quantity="9000000.000000"') for n in zf.namelist())
|
|
||||||
assert hits == 1, hits # 90000000 ÷ 10m 前缀 = 9000000,不是 900000
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""形态银行(决策 274 补,2026-11-05 主人定):同后缀大骨架卡槽相似度优先——
|
|
||||||
本项目源件分层列集 vs 候选件(其他会话源件含最近审核+后台骨架库,同后缀硬过滤)
|
|
||||||
逐件 match_score,得分最多的件被采用,借它的局部小骨架(自增样板)。
|
|
||||||
借形态不借值:输出条数按库数据走,值一律来自库。"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import hashlib
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from test_api_p1 import raw_post # noqa: E402
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
sys.path.insert(0, os.path.dirname(__file__))
|
|
||||||
|
|
||||||
import api_harness as H # noqa: E402
|
|
||||||
from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: E402,F401
|
|
||||||
|
|
||||||
import classic_skeleton as cs # noqa: E402
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
|
|
||||||
_LME = "LabourMaterialsEquipmentsMachinesElement"
|
|
||||||
|
|
||||||
|
|
||||||
def _blob_with_express(path, proj_name):
|
|
||||||
"""造件后给 LME 行补 Express 槽(模拟广联达原生带算式的件)→ 同后缀候选件。"""
|
|
||||||
p = make_cos4(path, proj_name, [("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for n in z.namelist():
|
|
||||||
d = z.read(n)
|
|
||||||
if n.lower() != "project.xml":
|
|
||||||
d = d.replace(b'Quantity="1.5"/>', b'Quantity="1.5" Express="1.5*1.0"/>')
|
|
||||||
zo.writestr(n, d)
|
|
||||||
return buf.getvalue()
|
|
||||||
|
|
||||||
|
|
||||||
def test_local_forms_extracts_shapes():
|
|
||||||
"""提取:带 Express 槽的候选件 → LME 行形态带 Express;adj/单价/汇总行各有形态。"""
|
|
||||||
blob = _blob_with_express(io.BytesIO().name if False else os.path.join(
|
|
||||||
os.path.dirname(__file__), "_tmpfb_%s.cos4" % uuid.uuid4().hex[:6]), "形态提取工程")
|
|
||||||
forms = cs._local_forms(blob)
|
|
||||||
assert _LME in forms and ' Express="' in forms[_LME], forms.get(_LME)
|
|
||||||
assert "NormAdjustmentList" not in forms # 造件无换算行 → 缺席合法(fail-open)
|
|
||||||
|
|
||||||
|
|
||||||
def test_local_form_bank_picks_best_by_slots():
|
|
||||||
"""挑选:卡槽相似度高的候选胜出——本项目(带 Express 槽)vs 无 Express 槽件。"""
|
|
||||||
p1 = os.path.join(os.path.dirname(__file__), "_tmpfb_a_%s.cos4" % uuid.uuid4().hex[:6])
|
|
||||||
blob_a = _blob_with_express(p1, "带算式工程") # LME 带 Express 槽
|
|
||||||
blob_b = make_cos4(os.path.join(os.path.dirname(__file__), "_tmpfb_b_%s.cos4" % uuid.uuid4().hex[:6]),
|
|
||||||
"无算式工程", [("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
bank = cs.local_form_bank(cs.layer_cols_of(blob_a), [("带算式", blob_a), ("无算式", blob_b)])
|
|
||||||
assert _LME in bank and ' Express="' in bank[_LME], bank # 得分并列时取后写候选?断言带 Express 形态在
|
|
||||||
# 本项目自身=无算式件 → 仍可能挑中带算式件(同构卡槽分相同取先遍历最高分第一个)
|
|
||||||
blob_b2 = open(blob_b, "rb").read()
|
|
||||||
bank2 = cs.local_form_bank(cs.layer_cols_of(blob_b2), [("无算式", blob_b2), ("带算式", blob_a)])
|
|
||||||
assert bank2, bank2
|
|
||||||
assert ' Number="000001"' in bank2.get(_LME, "") # 自身最相似 → 借自己的形态(无 Express 槽)
|
|
||||||
|
|
||||||
|
|
||||||
def test_norm_xml_borrow_express_slot():
|
|
||||||
"""主人例 2:源件 LME 无 Express 槽 + 库有算式 → 借形态银行的行样板,算式落行。"""
|
|
||||||
bank = {_LME: '<%s Number="X" Quantity="0" Remark="" Express="0"/>' % _LME}
|
|
||||||
n = {"Number": "N1", "Name": "定额", "Unit": "m3", "Quantity": 10,
|
|
||||||
"Price": 2, "Total": 20, "x_adjust": None}
|
|
||||||
out = xcos._norm_xml(n, [("99450640", 51.62, "51.6200*1.2")], None, form_bank=bank)
|
|
||||||
assert 'Express="51.6200*1.2"' in out, out
|
|
||||||
# 无银行 → 维持现状裸行(fail-open,Express 不造)
|
|
||||||
out0 = xcos._norm_xml(n, [("99450640", 51.62, None)], None)
|
|
||||||
assert "Express" not in out0, out0
|
|
||||||
|
|
||||||
|
|
||||||
def test_norm_xml_borrow_adj_shape():
|
|
||||||
"""主人例 1:源件无换算行形态 → 借银行 adj 行样板(Type 等槽随形态);
|
|
||||||
无银行=硬编码最小形态兜底(264 前静默丢失缺陷已顺带修:有 x_adjust 必出换算行)。"""
|
|
||||||
bank = {"NormAdjustmentList": '<NormAdjustmentList OrderNumber="1" Value="" Type="换算"/>'}
|
|
||||||
n = {"Number": "N1", "Name": "定额", "Unit": "m3", "Quantity": 10,
|
|
||||||
"Price": 2, "Total": 20, "x_adjust": '["调:人工挖桩间土方"]'}
|
|
||||||
out = xcos._norm_xml(n, [], None, form_bank=bank)
|
|
||||||
assert 'Type="换算"' in out and "调:人工挖桩间土方" in out, out
|
|
||||||
out0 = xcos._norm_xml(n, [], None)
|
|
||||||
assert "调:人工挖桩间土方" in out0 and 'Type=' not in out0, out0
|
|
||||||
|
|
||||||
|
|
||||||
def test_borrow_norm_block_when_source_has_none(server):
|
|
||||||
"""采纳定额在残行源件上借块:本项目源件定额行剥成残行(当不了模板),
|
|
||||||
采纳外部定额 → 借相似候选件的定额块形态(NormIdentity 等列集随形态),值=库。"""
|
|
||||||
import re as _re
|
|
||||||
proj = "借块工程-" + uuid.uuid4().hex[:6]
|
|
||||||
# ① 候选件(同后缀、定额块形态齐全)种进后台骨架库——银行借形态的来源
|
|
||||||
p_back = H.make_cos4(str(server["src_dir"] / ("fbback_%s.cos4" % proj[-6:])),
|
|
||||||
"借块候选件", [("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
con_b = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
assert cs.seed_frame(con_b, p_back, "借块候选骨架"), "候选件入库失败"
|
|
||||||
finally:
|
|
||||||
con_b.close()
|
|
||||||
# ② 本项目源件:定额行剥成残行(无 NormIdentity/Name/Price,当不了模板)
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("fb_%s_raw.cos4" % proj[-6:])), proj,
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for n in z.namelist():
|
|
||||||
d = z.read(n)
|
|
||||||
if n.lower() != "project.xml":
|
|
||||||
d = _re.sub(rb'<Norm Number="N-1"[^>]*>', b'<Norm Number="N-1">', d)
|
|
||||||
zo.writestr(n, d)
|
|
||||||
raw = buf.getvalue()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_fb.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
audit = {"name": proj, "province": META["province"], "city": META["city"],
|
|
||||||
"district": META["district"], "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607, "file_kind": 1, "path": H.twin_file(server, hp)}
|
|
||||||
sid = post(server, "/api/audit", audit)["session_id"]
|
|
||||||
# ③ 外部件批次(标准形态)→ 采纳其定额进本项目清单
|
|
||||||
fix2 = server["root"] / "fixsrc"
|
|
||||||
fix2.mkdir(exist_ok=True)
|
|
||||||
fp2 = str(fix2 / ("fbext_%s.cos4" % proj[-6:]))
|
|
||||||
H.make_cos4(fp2, "借块外部件", [("B002", "外部清单", "", "m3", 2, 400)],
|
|
||||||
[("000001", "人工", "", "工日", "2", "1")])
|
|
||||||
up2 = raw_post(server, "/api/admin/upload", "借块外部件.cos4", open(fp2, "rb").read())
|
|
||||||
assert up2["ok"] is True, up2
|
|
||||||
r2 = post(server, "/api/admin/import", dict(META, path=up2["path"], name="借块外部件", file_kind=1))
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
src_bill = con.execute("SELECT id FROM bills WHERE batch_id=?", (r2["batch_id"],)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
scon = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
try:
|
|
||||||
bid = scon.execute("SELECT id FROM s_bills WHERE session_id=? AND Name='清单甲'",
|
|
||||||
(sid,)).fetchone()[0]
|
|
||||||
finally:
|
|
||||||
scon.close()
|
|
||||||
post(server, "/api/session/bill/adopt",
|
|
||||||
{"session_id": sid, "bill_id": bid, "src_bill_id": src_bill})
|
|
||||||
# ④ 导出:采纳定额借候选件定额块形态(NormIdentity 随形态)
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
unit = b"".join(z.read(n) for n in z.namelist() if n.lower() != "project.xml").decode("utf-8", "replace")
|
|
||||||
assert 'NormIdentity="' in unit, unit[:600]
|
|
||||||
post(server, "/api/session/delete", {"ids": [sid]})
|
|
||||||
|
|
||||||
|
|
||||||
def _cleanup_tmp():
|
|
||||||
d = os.path.dirname(__file__)
|
|
||||||
for n in os.listdir(d):
|
|
||||||
if n.startswith("_tmpfb_"):
|
|
||||||
try:
|
|
||||||
os.remove(os.path.join(d, n))
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def test_teardown_tmp():
|
|
||||||
_cleanup_tmp()
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 231 补记五(2026-10-28,主人定「这2个可以当做经典骨架收藏」):专用骨架件回归。
|
|
||||||
|
|
||||||
口径:①专用骨架判定(文件名含 骨架/架子,或 单位≥5 且空单位位占比≥50%)→ classic_skel
|
|
||||||
is_frame=1,**同后缀唯一、后传顶旧**,优先于实项目件当导出代表;②根层 LME_SUM=单位级
|
|
||||||
汇总表(易达标准骨架铁证,推翻补记三「清空」定论)→ 导出灌**现算行**(定额工程量×
|
|
||||||
消耗量,dyn 引擎)+台班子级组成;③采纳补子工料机(批次 lme_res → 会话 s_lme_res,
|
|
||||||
缺则补不重复)。
|
|
||||||
真实骨架件:后台需要导入的项目/1易达导出骨架.cos4(31 单位位)、2广联达导出架子.COS4
|
|
||||||
(19 单位位);采纳来源:合并工料机测试(原).cos4。
|
|
||||||
独立隔离服务(专用骨架会顶掉共享夹具里 cos4 代表,须另起副本)。"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import socket
|
|
||||||
import sqlite3
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
import zipfile
|
|
||||||
from pathlib import Path
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from api_harness import PERIOD_202607 # noqa: F401
|
|
||||||
from test_api_p1 import raw_post
|
|
||||||
|
|
||||||
_APP_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
||||||
sys.path.insert(0, os.path.join(_APP_SRC, "core"))
|
|
||||||
import classic_skeleton as _cs # noqa: E402 (升级添加骨架的入库口)
|
|
||||||
|
|
||||||
|
|
||||||
def _seed_frame(server, path, name):
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
try:
|
|
||||||
sig = _cs.seed_frame(con, str(path), name)
|
|
||||||
assert sig, "升级入库失败:%s" % name
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
return name
|
|
||||||
_FRAME1 = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "1易达导出骨架.cos4"
|
|
||||||
# 广联达骨架以 .COS4 版为准(主人原生 .GBQ7 是二进制专有格式,软件不收;
|
|
||||||
# 2026-10-28 换新:广联达导出最新架子.COS4=同签名更全样本件,旧 30-解密件已由主人替换);
|
|
||||||
# .COS4 版不在本机时相应断言跳过(顶旧机制用改名副本验证,不依赖该件)。
|
|
||||||
_FRAME2 = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "广联达导出最新架子.COS4"
|
|
||||||
_REAL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "吉大街道园林花园老旧小区环境整治提升工程施工.cos4"
|
|
||||||
_SRC_BILL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "合并工料机测试(原).cos4"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def fserver(tmp_path_factory):
|
|
||||||
"""独立隔离服务(与 api_harness.server 同款,专用骨架不污染共享夹具的骨架库)。"""
|
|
||||||
root = tmp_path_factory.mktemp("framesrv")
|
|
||||||
shutil.copytree(_APP_SRC, os.path.join(root, "CostReview", "app"),
|
|
||||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
|
||||||
src_dir = os.path.join(root, "后台需要导入的项目")
|
|
||||||
os.makedirs(src_dir)
|
|
||||||
lic = os.path.join(root, "lic")
|
|
||||||
os.makedirs(lic)
|
|
||||||
open(os.path.join(lic, "config.json"), "w").write('{"enforce": false}')
|
|
||||||
s = socket.socket()
|
|
||||||
s.bind(("127.0.0.1", 0))
|
|
||||||
port = s.getsockname()[1]
|
|
||||||
s.close()
|
|
||||||
log = open(os.path.join(root, "server.log"), "wb")
|
|
||||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
|
||||||
cwd=os.path.join(root, "CostReview", "app"),
|
|
||||||
env=dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=lic),
|
|
||||||
stdout=log, stderr=subprocess.STDOUT)
|
|
||||||
client = httpx.Client(base_url="http://127.0.0.1:%d" % port, timeout=120)
|
|
||||||
for _ in range(100):
|
|
||||||
try:
|
|
||||||
if client.get("/api/license/status").status_code == 200:
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
time.sleep(0.3)
|
|
||||||
else:
|
|
||||||
proc.kill()
|
|
||||||
raise RuntimeError("frame 测试服务未就绪")
|
|
||||||
yield {"client": client, "root": str(root), "src_dir": src_dir,
|
|
||||||
"db": os.path.join(root, "CostReview", "data", "history.db"),
|
|
||||||
"sessdb": os.path.join(root, "CostReview", "data", "session.db")}
|
|
||||||
client.close()
|
|
||||||
proc.terminate()
|
|
||||||
try:
|
|
||||||
proc.wait(10)
|
|
||||||
except Exception:
|
|
||||||
proc.kill()
|
|
||||||
log.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _db(server):
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
return con
|
|
||||||
|
|
||||||
|
|
||||||
def test_frame_pin_and_replace(fserver):
|
|
||||||
"""补记十二终版:上传口**不再自动收骨架**;骨架只经升级(seed_frame)入库;
|
|
||||||
命名不带软件名(COS4骨架G/Y);固定后上传不顶不改名;实项目不夺骨架。"""
|
|
||||||
assert _FRAME1.exists() and _FRAME2.exists(), "两件骨架不在本机"
|
|
||||||
con = _db(fserver)
|
|
||||||
try:
|
|
||||||
# ① 上传口上传骨架件 → 不收藏(连表都不建)
|
|
||||||
assert raw_post(fserver, "/api/admin/upload",
|
|
||||||
_FRAME1.name, _FRAME1.read_bytes())["ok"]
|
|
||||||
r1 = con.execute("SELECT COUNT(*) FROM sqlite_master "
|
|
||||||
"WHERE name='classic_skel'").fetchone()[0]
|
|
||||||
assert r1 == 0, "上传口不该收藏任何骨架"
|
|
||||||
# ② 升级入库:两件经典骨架(G/Y 命名)
|
|
||||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y")
|
|
||||||
_seed_frame(fserver, _FRAME2, "COS4骨架G")
|
|
||||||
rows = con.execute("SELECT original_name FROM classic_skel "
|
|
||||||
"WHERE suffix='cos4' AND is_frame=1 ORDER BY original_name").fetchall()
|
|
||||||
assert [r["original_name"] for r in rows] == ["COS4骨架G", "COS4骨架Y"], [dict(r) for r in rows]
|
|
||||||
# ③ 固定后再上传骨架原件 → 不顶、不改名
|
|
||||||
assert raw_post(fserver, "/api/admin/upload", _FRAME2.name, _FRAME2.read_bytes())["ok"]
|
|
||||||
rows2 = con.execute("SELECT original_name FROM classic_skel "
|
|
||||||
"WHERE suffix='cos4' AND is_frame=1 ORDER BY original_name").fetchall()
|
|
||||||
assert [r["original_name"] for r in rows2] == ["COS4骨架G", "COS4骨架Y"], [dict(r) for r in rows2]
|
|
||||||
# ④ 实项目件照收但不夺骨架
|
|
||||||
assert raw_post(fserver, "/api/admin/upload", _REAL.name, _REAL.read_bytes())["ok"]
|
|
||||||
top = con.execute("SELECT original_name, is_frame FROM classic_skel "
|
|
||||||
"WHERE suffix='cos4' ORDER BY is_frame DESC, n_nodes DESC "
|
|
||||||
"LIMIT 1").fetchone()
|
|
||||||
assert top["is_frame"] == 1, "实项目夺了骨架代表"
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_frame_export_e2e(fserver):
|
|
||||||
"""端到端:骨架代表+Excel 手工工程+采纳(带子级)→骨架导出=
|
|
||||||
全成员 XML 合法/根层单位级汇总行=现算(含子级容器)/项目级 PIWC 行=现算/我方清单在。"""
|
|
||||||
# 骨架:升级入库(补记十二——上传口不再自动收骨架;防御性重入,不依赖上一用例)
|
|
||||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y")
|
|
||||||
# 采纳来源批次(合并工料机测试件:含台班子级组成)
|
|
||||||
assert _SRC_BILL.exists(), "采纳来源件不在本机"
|
|
||||||
up = raw_post(fserver, "/api/admin/upload", _SRC_BILL.name, _SRC_BILL.read_bytes())
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
from api_harness import META
|
|
||||||
r = fserver["client"].post("/api/admin/import",
|
|
||||||
json=dict(META, path=up["path"], name="骨架来源批次",
|
|
||||||
file_kind=1))
|
|
||||||
assert r.json().get("ok"), r.text[:200]
|
|
||||||
bid = r.json()["batch_id"]
|
|
||||||
# 用来源件前两清单造 Excel(同款字段)
|
|
||||||
sys.path.insert(0, os.path.join(_APP_SRC, "core"))
|
|
||||||
import import_job
|
|
||||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1, "cur_uw": -1,
|
|
||||||
"bill_uw": [], "bill_kind": [], "prelim_raw": 0, "bill_raw": 0, "bill_skip": 0,
|
|
||||||
"bill_skip_zero": 0, "lme_raw": 0, "lme_skip": 0, "proj_name": "",
|
|
||||||
"file_kind": None, "bulid_unit": "", "total": None}
|
|
||||||
import_job.parse_file(str(_SRC_BILL), out)
|
|
||||||
picks = [(i, b) for i, b in enumerate(out["bills"])
|
|
||||||
if out["bill_kind"][i] != "prelim"][:2]
|
|
||||||
from openpyxl import Workbook
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = "分部分项"
|
|
||||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
ws.append(["单位工程", "", "分部", "骨架测试分部", "", "", "", ""])
|
|
||||||
for _i, b in picks:
|
|
||||||
ws.append(["骨架测试分部", b[0] or "", "清单", b[1] or "", b[2] or "",
|
|
||||||
b[3] or "", float(b[4] or 0), float(b[5] or 0)])
|
|
||||||
ws2 = wb.create_sheet("措施项目")
|
|
||||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
fp = os.path.join(fserver["src_dir"], "frame_unit.xlsx")
|
|
||||||
wb.save(fp)
|
|
||||||
r = fserver["client"].post("/api/session/manual/save", json={
|
|
||||||
"sid": 0, "name": "骨架导出测试", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "单项",
|
|
||||||
"units": [{"id": 0, "name": "我方单位", "file": fp}]}]})
|
|
||||||
assert r.json().get("ok"), r.text[:300]
|
|
||||||
sid = r.json()["session_id"]
|
|
||||||
# 精确配对采纳
|
|
||||||
con = sqlite3.connect(fserver["db"])
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
batch = {(r2["Number"] or "", r2["Name"] or ""): r2["id"] for r2 in con.execute(
|
|
||||||
"SELECT id, Number, Name FROM bills WHERE batch_id=?", (bid,))}
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
cs = sqlite3.connect(fserver["sessdb"])
|
|
||||||
cs.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
sess = [(r2["id"], r2["Number"] or "", r2["Name"] or "") for r2 in cs.execute(
|
|
||||||
"SELECT id, Number, Name FROM s_bills WHERE session_id=?", (sid,))]
|
|
||||||
finally:
|
|
||||||
cs.close()
|
|
||||||
con = sqlite3.connect(fserver["db"])
|
|
||||||
n_child = con.execute("SELECT COUNT(*) FROM lme_res").fetchone()[0]
|
|
||||||
con.close()
|
|
||||||
for bid_, num, name in sess:
|
|
||||||
src = batch.get((num, name))
|
|
||||||
assert src, "批次缺清单 %s" % num
|
|
||||||
ra = fserver["client"].post("/api/session/bill/adopt",
|
|
||||||
json={"session_id": sid, "bill_id": bid_,
|
|
||||||
"src_bill_id": src})
|
|
||||||
assert ra.json().get("ok"), ra.text[:200]
|
|
||||||
# 采纳应把子级组成补进会话
|
|
||||||
cs = sqlite3.connect(fserver["sessdb"])
|
|
||||||
n_sres = cs.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=?", (sid,)).fetchone()[0]
|
|
||||||
child_codes = {r[0] for r in cs.execute(
|
|
||||||
"SELECT DISTINCT res_code FROM s_lme_res WHERE session_id=?", (sid,)).fetchall()}
|
|
||||||
n_lib = cs.execute("SELECT COUNT(*) FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()[0]
|
|
||||||
uwid = cs.execute("SELECT id FROM s_unit_works WHERE session_id=?", (sid,)).fetchone()[0]
|
|
||||||
cs.close()
|
|
||||||
assert n_sres > 0 or n_child == 0, "采纳没补子级组成(批次 lme_res=%d)" % n_child
|
|
||||||
assert n_lib > 0 or n_child == 0, "采纳没带组成子码价格快照(s_lme_lib=0)"
|
|
||||||
# 骨架导出
|
|
||||||
resp = fserver["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
assert resp.status_code == 200, resp.text[:300]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
LME = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
unit_root = proj_rows = None
|
|
||||||
for nm in z.namelist():
|
|
||||||
if not nm.lower().endswith(".xml"):
|
|
||||||
continue
|
|
||||||
root = ET.fromstring(z.read(nm)) # 全成员必须 XML 合法
|
|
||||||
if root.tag == "UnitWorks" and (root.get("Name") or "") == "我方单位":
|
|
||||||
unit_root = [c for c in root if c.tag == LME]
|
|
||||||
if root.tag != "UnitWorks":
|
|
||||||
for piwc in root.iter("ProjectInstallationWorkCost"):
|
|
||||||
proj_rows = [c for c in piwc if c.tag == LME]
|
|
||||||
assert unit_root is not None, "导出件没有我方单位成员"
|
|
||||||
assert len(unit_root) > 0, "单位级汇总行没灌(根层 LME_SUM 空)"
|
|
||||||
# 子级容器行(台班):行含子 LME_SUM
|
|
||||||
has_container = any(len(c) > 0 for c in unit_root)
|
|
||||||
if n_child:
|
|
||||||
assert has_container or n_sres == 0, "台班子级行没挂(s_lme_res=%d)" % n_sres
|
|
||||||
# 组成子码自有行(2026-10-28:主人实测易达映射源组成子行编制价全空后的补行)——
|
|
||||||
# 纯组成码也要各有一行自己的价(s_lme_lib 快照;原生件铁证:折旧费/检修费同表自有行)
|
|
||||||
flat_codes = {c.get("Number") for c in unit_root if not len(c)}
|
|
||||||
own = child_codes & flat_codes
|
|
||||||
assert own or not (child_codes and n_lib), \
|
|
||||||
"组成子码没有自有价行(子码 %s 全不在表里)" % sorted(child_codes)[:3]
|
|
||||||
if own:
|
|
||||||
c0 = next(c for c in unit_root if not len(c) and c.get("Number") in own)
|
|
||||||
assert c0.get("NoTaxPrice") not in (None, ""), "组成自有行没带价"
|
|
||||||
if proj_rows is not None:
|
|
||||||
assert len(proj_rows) > 0 or n_sres == 0
|
|
||||||
# 我方清单在
|
|
||||||
found = False
|
|
||||||
for nm in z.namelist():
|
|
||||||
if nm.lower().endswith(".xml") and picks[0][1][1].encode("utf-8") in z.read(nm):
|
|
||||||
found = True
|
|
||||||
break
|
|
||||||
assert found, "我方清单没进导出件"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="决策 260 引擎 v2 重写中:旧口径断言(成员文件名保留骨架造名)已被新口径(成员文件名=我方单位名)取代,v2 验收测试重写后替代本用例")
|
|
||||||
def test_normal_cos4_via_frame(fserver):
|
|
||||||
"""补记十二(2026-10-28 主人定「推翻:审核版不再基于原文件」):普通(源文件)
|
|
||||||
工程 cos4 导出也走经典骨架——骨架成员名进件、会话数据灌入,数据流不变。"""
|
|
||||||
assert _SRC_BILL.exists(), "合并工料机测试(原).cos4 不在本机"
|
|
||||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y") # 自足:升级入库两件经典骨架
|
|
||||||
_seed_frame(fserver, _FRAME2, "COS4骨架G")
|
|
||||||
up = raw_post(fserver, "/api/admin/upload", _SRC_BILL.name, _SRC_BILL.read_bytes())
|
|
||||||
# 决策 243:同一份文件前后台只能存在一边——上面 e2e 已把原件入库,这里开同内容双胞胎件
|
|
||||||
import api_harness as H
|
|
||||||
r = fserver["client"].post("/api/audit", json={
|
|
||||||
"name": "普通cos4走骨架T", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607, "file_kind": 1,
|
|
||||||
"path": H.twin_file(fserver, up["path"], "framenormal")}).json()
|
|
||||||
assert r.get("ok"), r
|
|
||||||
sid = r["session_id"]
|
|
||||||
resp = fserver["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
assert resp.status_code == 200 and resp.content[:2] == b"PK", resp.content[:200]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
infos = [i for i in z.infolist() if i.filename.lower().endswith(".xml")]
|
|
||||||
# 成员是骨架的位(我是单位工程N 系列),不是源文件自己的成员(单位工程1/@_5155…)
|
|
||||||
names = set()
|
|
||||||
for i in infos:
|
|
||||||
try:
|
|
||||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
|
||||||
else i.filename.encode("cp437")
|
|
||||||
names.add(raw.decode("gbk"))
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
names.add(i.filename)
|
|
||||||
assert any("我是单位工程" in n for n in names), sorted(names)[:6]
|
|
||||||
assert not any(n.endswith("_单位工程1.xml") for n in names), "源文件自己的成员名不该出现在骨架导出里"
|
|
||||||
# 会话数据在(原工程自己的清单内容)
|
|
||||||
rows = fserver["client"].get("/api/session/rows",
|
|
||||||
params={"session_id": sid, "type": "bill"}).json()["rows"]
|
|
||||||
assert rows, "会话没数据"
|
|
||||||
cands = [str(c) for x in rows[:5] for c in x[1:6]
|
|
||||||
if c and not str(c).replace(".", "").isdigit() and len(str(c)) >= 3]
|
|
||||||
body = b"".join(z.read(i) for i in z.infolist()
|
|
||||||
if i.filename.lower().endswith(".xml"))
|
|
||||||
assert cands and any(c.encode("utf-8") in body for c in cands), "会话清单没进骨架导出件:%s" % cands[:3]
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""类似清单组排序防回归(决策 36,2026-10-11)。
|
|
||||||
|
|
||||||
背景:组目录原排序 = 关键词组固定在前(规则序号)+ 系统组按差%降序(决策 19)。
|
|
||||||
主人定改为「按组合计合价降序,合价最大的编第 1 组」——本测试钉死四条口径:
|
|
||||||
① groups 严格按 tsum 降序(同额差%降序兜底);
|
|
||||||
② 关键词组不再固定在前,与系统组按同一口径混排(规则序号只定匹配优先级);
|
|
||||||
③ 落单组不参与排序,固定殿后(extra),条数守恒;
|
|
||||||
④ 无合价(Total 全空 → tsum=None)按 0 计,排在有合价的组之后。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _row(rid, name, price, total, attr=""):
|
|
||||||
return {"id": rid, "Number": "0%d" % rid, "Name": name, "Attr": attr,
|
|
||||||
"Unit": "m3", "Quantity": 1, "Price": price, "Total": total,
|
|
||||||
"x_seq": rid, "uw_name": ""}
|
|
||||||
|
|
||||||
|
|
||||||
def _names(res):
|
|
||||||
"""响应里 groups(含 extra)的每组:(名称集, tsum)。名称取自行内 Name,系统组无组名。"""
|
|
||||||
out = []
|
|
||||||
for g in res["groups"] + res["extra"]:
|
|
||||||
out.append((sorted(r[2] for r in g["rows"]), g.get("tsum")))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_rules(monkeypatch, rules=None):
|
|
||||||
monkeypatch.setattr(srv, "_grp_rule", lambda: {"big": 50, "sig_thr": 0.6})
|
|
||||||
monkeypatch.setattr(srv, "_grp_rules_load", lambda: rules or [])
|
|
||||||
|
|
||||||
|
|
||||||
# 三个名称层组(组内同名),tsum 分别 50 / 500 / 100 → 目录序必须是 500、100、50
|
|
||||||
def test_tsum_desc(monkeypatch):
|
|
||||||
_patch_rules(monkeypatch)
|
|
||||||
rows = [_row(1, "混凝土柱浇筑", 100, 25), _row(2, "混凝土柱浇筑", 120, 25),
|
|
||||||
_row(3, "钢筋制作安装", 300, 400), _row(4, "钢筋制作安装", 320, 100),
|
|
||||||
_row(5, "模板支拆运输", 50, 60), _row(6, "模板支拆运输", 55, 40)]
|
|
||||||
res = srv._group_v2_output(rows)
|
|
||||||
ts = [t for _, t in _names(res)]
|
|
||||||
assert ts == sorted(ts, reverse=True) and ts[0] == 500.0, ts
|
|
||||||
assert res["groups"][0]["rows"][0][2] == "钢筋制作安装" # 合价最大的组编第 1 组
|
|
||||||
|
|
||||||
|
|
||||||
# 关键词组 tsum 居中 → 不再固定在前(原口径关键词组永远排最前)
|
|
||||||
def test_kw_group_mixed_by_tsum(monkeypatch):
|
|
||||||
_patch_rules(monkeypatch, [{"seq": 1, "name": "混凝土类", "keywords": "混凝土", "exclude": ""}])
|
|
||||||
rows = [_row(1, "混凝土柱浇筑", 100, 20), _row(2, "混凝土墙浇筑", 110, 30), # 命中关键词,tsum=50
|
|
||||||
_row(3, "钢筋制作安装", 300, 400), _row(4, "钢筋制作安装", 320, 100), # 名称层,tsum=500
|
|
||||||
_row(5, "模板支拆运输", 50, 18), _row(6, "模板支拆运输", 55, 17)] # 名称层,tsum=35
|
|
||||||
res = srv._group_v2_output(rows)
|
|
||||||
names = _names(res)
|
|
||||||
assert names[0][0] == ["钢筋制作安装", "钢筋制作安装"] # 第 1 组 = 合价最大
|
|
||||||
assert names[1][0] == sorted(["混凝土柱浇筑", "混凝土墙浇筑"]) # 关键词组按 tsum 居中
|
|
||||||
assert names[2][0] == ["模板支拆运输", "模板支拆运输"]
|
|
||||||
assert res["groups"][1].get("cat") == "混凝土类"
|
|
||||||
|
|
||||||
|
|
||||||
# 落单行进 extra 殿后,不参与排序;条数守恒
|
|
||||||
def test_extra_trailing_and_conservation(monkeypatch):
|
|
||||||
_patch_rules(monkeypatch)
|
|
||||||
rows = [_row(1, "混凝土柱浇筑", 100, 25), _row(2, "混凝土柱浇筑", 120, 25),
|
|
||||||
_row(3, "零星杂项拆除", 9, 3), _row(4, "场地平整碾压", 8, 2)] # 各自落单 → extra
|
|
||||||
res = srv._group_v2_output(rows)
|
|
||||||
assert len(res["groups"]) == 1 and len(res["extra"]) == 1
|
|
||||||
assert res["extra"][0]["cat"] == "其他"
|
|
||||||
assert sum(len(g["rows"]) for g in res["groups"] + res["extra"]) == len(rows)
|
|
||||||
|
|
||||||
|
|
||||||
# Total 全空 → tsum=None 按 0 计,排在有合价的组之后(不抛异常、不插队)
|
|
||||||
def test_null_tsum_sinks(monkeypatch):
|
|
||||||
_patch_rules(monkeypatch)
|
|
||||||
rows = [_row(1, "混凝土柱浇筑", 100, None), _row(2, "混凝土柱浇筑", 120, None),
|
|
||||||
_row(3, "钢筋制作安装", 300, 400), _row(4, "钢筋制作安装", 320, 100)]
|
|
||||||
res = srv._group_v2_output(rows)
|
|
||||||
assert res["groups"][0]["rows"][0][2] == "钢筋制作安装"
|
|
||||||
assert res["groups"][1]["tsum"] is None
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""分组规则「单位(必)」列防回归(2026-10-13 决策 48,主人定)。
|
|
||||||
|
|
||||||
主人口径:填写单位后,在原有分组规则基础上**过滤掉单位不命中的清单**——
|
|
||||||
这些行不被本规则收走、继续走后续名称自动聚类(条数守恒一条不丢);
|
|
||||||
不填=完全维持原行为。多个单位词空格/逗号分隔、任一命中(精确匹配)。
|
|
||||||
本文件钉死:①units 过滤生效;②多单位任一命中;③不填=原行为(回归保护);
|
|
||||||
④被过滤的行走名称层(不消失,条数守恒);⑤命中数与实际分组同口径。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _row(rid, name, unit, price, total):
|
|
||||||
return {"id": rid, "Number": "0%d" % rid, "Name": name, "Attr": "",
|
|
||||||
"Unit": unit, "Quantity": 1, "Price": price, "Total": total,
|
|
||||||
"x_seq": rid, "uw_name": ""}
|
|
||||||
|
|
||||||
|
|
||||||
def _patch(monkeypatch, rules):
|
|
||||||
monkeypatch.setattr(srv, "_grp_rule", lambda: {"big": 50, "sig_thr": 0.6})
|
|
||||||
monkeypatch.setattr(srv, "_grp_rules_load", lambda: rules)
|
|
||||||
|
|
||||||
|
|
||||||
def _steel_group_ids(res):
|
|
||||||
"""找「钢筋工程」关键词组的成员 id 集;没有该组返回 None。"""
|
|
||||||
for g in res["groups"]:
|
|
||||||
if g.get("cat") == "钢筋工程":
|
|
||||||
return sorted(r[0] for r in g["rows"])
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
RULE = {"seq": 1, "name": "钢筋工程", "keywords": "钢筋", "exclude": ""}
|
|
||||||
|
|
||||||
# 六行:4 行命中「钢筋」关键词(单位分别为 t/t/kg/空),1 行不命中(混凝土,m3)
|
|
||||||
ROWS = [
|
|
||||||
_row(1, "钢筋制作安装", "t", 300, 100),
|
|
||||||
_row(2, "钢筋接头处理", "t", 200, 50),
|
|
||||||
_row(3, "钢筋制作安装", "kg", 100, 30),
|
|
||||||
_row(4, "钢筋运输", "", 50, 10),
|
|
||||||
_row(5, "混凝土浇筑", "m3", 400, 200),
|
|
||||||
_row(6, "混凝土养护", "m3", 20, 5),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def test_units_filter(monkeypatch):
|
|
||||||
"""填 units='t':只有单位=t 的两行进「钢筋工程」,kg/空单位行不被本规则收走。"""
|
|
||||||
_patch(monkeypatch, [dict(RULE, units="t")])
|
|
||||||
res = srv._group_v2_output(list(ROWS))
|
|
||||||
assert _steel_group_ids(res) == [1, 2]
|
|
||||||
# 条数守恒:被过滤的行仍在响应里(名称层组或落单组),一条不丢
|
|
||||||
all_ids = sorted(r[0] for g in res["groups"] + res["extra"] for r in g["rows"])
|
|
||||||
assert all_ids == [1, 2, 3, 4, 5, 6]
|
|
||||||
|
|
||||||
|
|
||||||
def test_units_multi_any_hit(monkeypatch):
|
|
||||||
"""多个单位词(逗号分隔)任一命中:t 和 kg 都收;空单位行仍被过滤。"""
|
|
||||||
_patch(monkeypatch, [dict(RULE, units="t, kg")])
|
|
||||||
res = srv._group_v2_output(list(ROWS))
|
|
||||||
assert _steel_group_ids(res) == [1, 2, 3]
|
|
||||||
|
|
||||||
|
|
||||||
def test_units_empty_keeps_old_behavior(monkeypatch):
|
|
||||||
"""不填 units=完全维持原行为:kg/空单位行照旧被关键词规则收走(回归保护)。"""
|
|
||||||
_patch(monkeypatch, [dict(RULE, units="")])
|
|
||||||
res = srv._group_v2_output(list(ROWS))
|
|
||||||
assert _steel_group_ids(res) == [1, 2, 3, 4]
|
|
||||||
|
|
||||||
|
|
||||||
def test_units_filtered_rows_fall_through_to_name_tier(monkeypatch):
|
|
||||||
"""被单位过滤掉的行走后续名称层:kg 行与另一条同名 kg 行聚成名称层组(不是凭空消失)。"""
|
|
||||||
rows = list(ROWS) + [_row(7, "钢筋制作安装", "kg", 110, 31)]
|
|
||||||
_patch(monkeypatch, [dict(RULE, units="t")])
|
|
||||||
res = srv._group_v2_output(rows)
|
|
||||||
# 钢筋组只收 t 行;两条 kg 同名行聚成名称层组(组内 2 条才成组)
|
|
||||||
name_groups = [sorted(r[0] for r in g["rows"]) for g in res["groups"] if not g.get("cat")]
|
|
||||||
assert [3, 7] in name_groups
|
|
||||||
assert _steel_group_ids(res) == [1, 2]
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""导入认内容不认后缀(2026-11-03 主人定 A 方案):
|
|
||||||
同族新后缀(.cos5/.xml/.abc…)零代码可开;zip 内有无 ConstructProject 决定 SWT 族 / COS 族;
|
|
||||||
散装 XML 只有 SWT 族(根 ConstructProject)能开,其他明确报错。"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
|
|
||||||
import import_job as job # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mkzip(tmp_path, outer, member, body):
|
|
||||||
p = tmp_path / outer
|
|
||||||
with zipfile.ZipFile(str(p), "w") as z:
|
|
||||||
z.writestr(member, body)
|
|
||||||
return str(p)
|
|
||||||
|
|
||||||
|
|
||||||
def test_zip_cos_family_any_suffix(tmp_path, monkeypatch):
|
|
||||||
calls = []
|
|
||||||
monkeypatch.setattr(job, "parse_std", lambda path, out: calls.append("std") or "2025标准")
|
|
||||||
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
|
|
||||||
p = _mkzip(tmp_path, "工程.cos5", "Project.xml", "<ConstructionProject Name='x'/>")
|
|
||||||
job.parse_file(p, {})
|
|
||||||
assert calls == ["std"], "COS 族 zip:后缀 .cos5 不拦,走 parse_std"
|
|
||||||
|
|
||||||
|
|
||||||
def test_zip_swt_member_any_suffix(tmp_path, monkeypatch):
|
|
||||||
calls = []
|
|
||||||
monkeypatch.setattr(job, "parse_std", lambda path, out: calls.append("std") or "2025标准")
|
|
||||||
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
|
|
||||||
p = _mkzip(tmp_path, "工程.abc", "标书.xml",
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?><ConstructProject></ConstructProject>')
|
|
||||||
job.parse_file(p, {})
|
|
||||||
assert calls == ["swt"], "zip 内含 ConstructProject:后缀 .abc 也按 SWT 族解析"
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_xml_swt_any_suffix(tmp_path, monkeypatch):
|
|
||||||
calls = []
|
|
||||||
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
|
|
||||||
p = tmp_path / "工程.xml"
|
|
||||||
p.write_text('<?xml version="1.0" encoding="utf-8"?><ConstructProject></ConstructProject>',
|
|
||||||
encoding="utf-8")
|
|
||||||
job.parse_file(str(p), {})
|
|
||||||
assert calls == ["swt"], "裸 XML 根 ConstructProject:.xml 后缀也能开"
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_xml_unknown_rejected(tmp_path):
|
|
||||||
p = tmp_path / "未知.xml"
|
|
||||||
p.write_text('<?xml version="1.0" encoding="utf-8"?><Foo><Bar/></Foo>', encoding="utf-8")
|
|
||||||
try:
|
|
||||||
job.parse_file(str(p), {})
|
|
||||||
except ValueError as e:
|
|
||||||
assert "不是已知的计价结构" in str(e)
|
|
||||||
else:
|
|
||||||
raise AssertionError("未知散装 XML 应明确报错")
|
|
||||||
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""检索关键词分级防回归(2026-10-11 决策 38,主人定)。
|
|
||||||
|
|
||||||
口径:检索 WHERE 仍是**兜底档**(=决策 27 原口径:字母数字段子串 + 中文逐字在场,
|
|
||||||
结果集不缩水);**严格档**只进 ORDER BY 首键置顶——
|
|
||||||
· 2~3 字中文词:连写、不分字序(土方=%土方%或%方土%;3 字 6 种排列任一);
|
|
||||||
· ≥4 字中文词:逐字在场(严格=兜底,保住「混凝土钢筋」↔「钢筋混凝土」互搜);
|
|
||||||
· 字母数字段:原样子串。
|
|
||||||
主人原话:「用全拆字兜底(排序最后)……只要搜索范围出现全部字,就是他的搜索对象。」
|
|
||||||
本文件钉死:①严格命中的行排在兜底行**前面**(哪怕兜底行期次更新);②兜底行**不排除**;
|
|
||||||
③排列连写也算严格;④分级与其它筛选条件(单价类型/期次等)正确组合;⑤分页跨页稳定。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "core"))
|
|
||||||
import match # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_db(items, kinds=None):
|
|
||||||
"""items: [(batch_id, Name, Attr)]——batch_id 越大批次越新(期次随之错开)。
|
|
||||||
kinds: {batch_id: FileKind} 供单价类型筛选用例。"""
|
|
||||||
con = sqlite3.connect(":memory:")
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
c = con.cursor()
|
|
||||||
c.execute("""CREATE TABLE batches (id INTEGER PRIMARY KEY, Name TEXT, kind TEXT,
|
|
||||||
BulidUnit TEXT, FileKind TEXT, x_province TEXT, x_city TEXT, x_district TEXT,
|
|
||||||
x_period_start_m INT, x_period_end_m INT, x_src_hash TEXT, x_enabled INT DEFAULT 1,
|
|
||||||
x_publisher TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE bills (id INTEGER PRIMARY KEY, batch_id INT,
|
|
||||||
Name TEXT, Attr TEXT, Unit TEXT, Price REAL)""")
|
|
||||||
for b in sorted({it[0] for it in items}):
|
|
||||||
c.execute("INSERT INTO batches (id, Name, kind, FileKind, x_period_start_m, x_period_end_m) "
|
|
||||||
"VALUES (?, '项目'||?, 'project', ?, ?, ?)",
|
|
||||||
(b, b, (kinds or {}).get(b, ""), 20260 + b, 20260 + b))
|
|
||||||
for i, (b, name, attr) in enumerate(items, 1):
|
|
||||||
c.execute("INSERT INTO bills (batch_id, Name, Attr, Unit, Price) VALUES (?, ?, ?, 'm3', 100)",
|
|
||||||
(b, name, attr))
|
|
||||||
con.commit()
|
|
||||||
return con
|
|
||||||
|
|
||||||
|
|
||||||
def test_strict_first_loose_last():
|
|
||||||
"""严格命中置顶:土方开挖(连写,老批次)排在新批次散字行前面——rank 压过期次序。"""
|
|
||||||
con = _mk_db([(1, "土方开挖", ""),
|
|
||||||
(2, "混凝土垫层铺设方式改良", "")]) # 土在混凝土、方在方式,散字=兜底
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [r["name"] for r in rs] == ["土方开挖", "混凝土垫层铺设方式改良"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_loose_not_excluded():
|
|
||||||
"""兜底行不排除:结果集与决策 27 原口径一致(散字行照常返回,只是垫底)。"""
|
|
||||||
con = _mk_db([(2, "混凝土垫层铺设方式改良", "")])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [r["name"] for r in rs] == ["混凝土垫层铺设方式改良"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_2char_perm_counts_strict():
|
|
||||||
con = _mk_db([(1, "回填方土区", ""), # 「方土」=土方的倒序连写 → 严格
|
|
||||||
(2, "混凝土垫层铺设方式改良", "")])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [r["name"] for r in rs] == ["回填方土区", "混凝土垫层铺设方式改良"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_3char_perm_counts_strict():
|
|
||||||
con = _mk_db([(1, "渠道沉降缝处理", ""), # 沉降缝 连写
|
|
||||||
(2, "缝降沉标识", ""), # 6 种排列之一 → 严格
|
|
||||||
(3, "沉箱降坡缝板", "")]) # 沉/降/缝 散落 → 兜底
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "沉降缝", limit=50)
|
|
||||||
assert [r["name"] for r in rs] == ["缝降沉标识", "渠道沉降缝处理", "沉箱降坡缝板"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_4char_charpresence_strict():
|
|
||||||
"""≥4 字词维持逐字在场=严格:「混凝土钢筋」命中「钢筋混凝土」(决策 27 互搜保留)。
|
|
||||||
主人原始案例同款:第二 token 土方 散字的行兜底垫底。"""
|
|
||||||
con = _mk_db([(1, "钢筋混凝土", "土方开挖"), # 两 token 都严格
|
|
||||||
(2, "钢筋混凝土", "敷设方式改良")]) # 混凝土钢筋逐字在场、土方散字 → 兜底
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "混凝土钢筋 土方", limit=50)
|
|
||||||
assert [r["attr"] for r in rs] == ["土方开挖", "敷设方式改良"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_rank_combined_with_filters():
|
|
||||||
"""分级与筛选条件正确组合:单价类型先圈行,严格置顶在圈出的行内生效。"""
|
|
||||||
kinds = {1: "招标", 2: "控制价"}
|
|
||||||
con = _mk_db([(1, "土方开挖", ""), (2, "混凝土垫层铺设方式改良", "")], kinds=kinds)
|
|
||||||
rs = match.hist_search(con, ["招标"], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [r["name"] for r in rs] == ["土方开挖"] # 控制价批次被筛掉
|
|
||||||
rs2 = match.hist_search(con, [], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [r["name"] for r in rs2] == ["土方开挖", "混凝土垫层铺设方式改良"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_pagination_rank_stable():
|
|
||||||
"""分页跨页稳定:第 1 页=严格行(期次新→旧),第 2 页=兜底行。"""
|
|
||||||
con = _mk_db([(1, "土方开挖", ""), (2, "土方回填", ""),
|
|
||||||
(3, "混凝土垫层铺设方式改良", ""), (4, "方式垒土", "")])
|
|
||||||
p1 = match.hist_search(con, [], [], [], None, None, "土方", limit=2, page=1)
|
|
||||||
p2 = match.hist_search(con, [], [], [], None, None, "土方", limit=2, page=2)
|
|
||||||
assert [r["name"] for r in p1] == ["土方回填", "土方开挖"] # 严格档,期内新前旧后
|
|
||||||
assert [r["name"] for r in p2] == ["方式垒土", "混凝土垫层铺设方式改良"] # 兜底档
|
|
||||||
|
|
||||||
|
|
||||||
def test_alnum_token_all_strict():
|
|
||||||
"""字母数字段子串本就是严格口径:c30 的命中行全是严格档(rank 不改变次序)。"""
|
|
||||||
con = _mk_db([(1, "C30混凝土垫层", ""), (2, "C30砼包管", "")])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "c30", limit=50)
|
|
||||||
assert len(rs) == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_loose_flag_matches_rank():
|
|
||||||
"""行级 loose 标记与排序一致:严格行 loose=False、兜底行 loose=True(前端灰徽标「兜底」依据)。"""
|
|
||||||
con = _mk_db([(1, "土方开挖", ""),
|
|
||||||
(2, "混凝土垫层铺设方式改良", "")])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "土方", limit=50)
|
|
||||||
assert [(r["name"], r["loose"]) for r in rs] == [("土方开挖", False),
|
|
||||||
("混凝土垫层铺设方式改良", True)]
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_kw_all_strict_flag():
|
|
||||||
"""无关键词(纯筛选检索)→ kwrank 恒 0、loose 全 False(不打兜底徽标)。"""
|
|
||||||
con = _mk_db([(1, "土方开挖", ""), (2, "混凝土垫层", "")])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "", limit=50)
|
|
||||||
assert [r["loose"] for r in rs] == [False, False]
|
|
||||||
@@ -1,300 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""网络/时钟回拨/过期租约负向测试 + 幂等/429/掉线/存储失败(协议交付验收清单)。"""
|
|
||||||
import json
|
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from lic_helpers import (IID, NOW, FakeTransport, MemSecret, cert_payload,
|
|
||||||
envelope, lease_payload, make_client, make_keyring, rfc, z)
|
|
||||||
from license_client.client import LicenseClient
|
|
||||||
from license_client.store import JsonFileStore, StorageError
|
|
||||||
from license_client.verify import VerifyError
|
|
||||||
|
|
||||||
|
|
||||||
def ok_lease(priv_key, server=NOW, le=None, state="active", iid=IID, next_hb=60):
|
|
||||||
return 200, {}, {"data": envelope(
|
|
||||||
lease_payload(server=server, le=le, state=state, iid=iid),
|
|
||||||
priv_key, "lease", next_hb=next_hb)}
|
|
||||||
|
|
||||||
|
|
||||||
def ok_cert(priv_key, iid=IID):
|
|
||||||
return 200, {}, {"data": {"instance_id": iid, "status": "activated",
|
|
||||||
"certificate": envelope(cert_payload(iid=iid), priv_key, "cert")},
|
|
||||||
"idempotent_replay": False}
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 激活
|
|
||||||
|
|
||||||
def test_activate_happy_path(priv_key, client):
|
|
||||||
client._tp.script.append(ok_cert(priv_key))
|
|
||||||
r = client.activate()
|
|
||||||
assert r["ok"] is True
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["status"] == "activated"
|
|
||||||
assert st["certificate"]["version"] == "license-v2"
|
|
||||||
assert "activation_op" not in st
|
|
||||||
assert client._tp.calls[0]["url"].endswith("/api/v1/activation/instances/" + IID)
|
|
||||||
assert client._tp.calls[0]["headers"]["Idempotency-Key"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_activate_retry_reuses_key_and_body(priv_key, tmp_path, keyring):
|
|
||||||
"""网络失败重试:同一 Idempotency-Key + 同一请求体(含 secret 字段不变)。"""
|
|
||||||
tp = FakeTransport([ConnectionError("断网"), ok_cert(priv_key)])
|
|
||||||
c = make_client(tmp_path, keyring, transport=tp)
|
|
||||||
r = c.activate()
|
|
||||||
assert r["ok"] is True
|
|
||||||
assert len(tp.calls) == 2
|
|
||||||
assert tp.keys()[0] == tp.keys()[1]
|
|
||||||
assert tp.calls[0]["body"] == tp.calls[1]["body"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_activate_rejects_stop_retrying(priv_key, client):
|
|
||||||
client._tp.script.append((401, {}, {"error": {"code": "BAD_CREDENTIALS",
|
|
||||||
"message": "nope"}}))
|
|
||||||
r = client.activate()
|
|
||||||
assert r["ok"] is False and r["code"] == "BAD_CREDENTIALS"
|
|
||||||
assert len(client._tp.calls) == 1 # 401 不重试
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert "activation_op" not in st
|
|
||||||
assert st["last_error"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_activate_verify_failure_fails_closed(priv_key, client, keyring):
|
|
||||||
"""证书绑定别的实例 → 拒收,状态不得进入 activated。"""
|
|
||||||
client._tp.script.append(ok_cert(priv_key, iid="bbbbbbbb-cccc-dddd-eeee-ffffffffffff"))
|
|
||||||
r = client.activate()
|
|
||||||
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
|
|
||||||
assert client.state_store.load().get("status") != "activated"
|
|
||||||
|
|
||||||
|
|
||||||
def test_activate_persisted_key_survives_restart(priv_key, tmp_path, keyring):
|
|
||||||
"""激活中途进程重启:新客户端从状态文件找回在途幂等键继续用。"""
|
|
||||||
tp = FakeTransport([ConnectionError("断网")])
|
|
||||||
c1 = make_client(tmp_path, keyring, transport=tp, max_attempts=1)
|
|
||||||
c1.activate() # 瞬时失败,键已落盘
|
|
||||||
saved_key = c1.state_store.load()["activation_op"]["key"]
|
|
||||||
tp2 = FakeTransport([ok_cert(priv_key)])
|
|
||||||
c2 = make_client(tmp_path, keyring, transport=tp2)
|
|
||||||
c2.activate()
|
|
||||||
assert tp2.calls[0]["headers"]["Idempotency-Key"] == saved_key
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 心跳与租约状态机
|
|
||||||
|
|
||||||
def test_heartbeat_accepts_active_lease(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] and r["state"] == "active"
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["enabled"] is True
|
|
||||||
assert st["server_high_water"] == z(NOW)
|
|
||||||
assert st["next_heartbeat_seconds"] == 60
|
|
||||||
assert "heartbeat_op" not in st
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is True and reason is None
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("state", ["frozen", "revoked", "expired", "not_started", "not_activated"])
|
|
||||||
def test_non_active_lease_disables_business(priv_key, client, state):
|
|
||||||
"""HTTP 200 不代表授权有效:签名租约非 active 必须关闭业务。"""
|
|
||||||
client._tp.script.append(ok_lease(priv_key, state=state))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is True
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["enabled"] is False
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and state in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_lease_expired(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key, le=NOW - timedelta(seconds=1)))
|
|
||||||
client.heartbeat()
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "租约已过期" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_entitlement_expired(priv_key, client):
|
|
||||||
env = envelope(lease_payload(ent=NOW - timedelta(days=1),
|
|
||||||
le=NOW - timedelta(days=2)), priv_key, "lease")
|
|
||||||
client._tp.script.append((200, {}, {"data": env}))
|
|
||||||
client.heartbeat()
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "过期" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_lease_longer_than_entitlement_rejected(priv_key, client):
|
|
||||||
env = envelope(lease_payload(ent=NOW + timedelta(days=3),
|
|
||||||
le=NOW + timedelta(days=10)), priv_key, "lease")
|
|
||||||
client._tp.script.append((200, {}, {"data": env}))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
|
|
||||||
assert client.state_store.load().get("lease") is None # 不得接受
|
|
||||||
|
|
||||||
|
|
||||||
def test_lease_over_14_days_rejected(priv_key, client):
|
|
||||||
env = envelope(lease_payload(server=NOW, le=NOW + timedelta(days=14, seconds=1)),
|
|
||||||
priv_key, "lease")
|
|
||||||
client._tp.script.append((200, {}, {"data": env}))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
|
|
||||||
|
|
||||||
|
|
||||||
def test_server_time_rollback_rejected(priv_key, client):
|
|
||||||
"""第二份租约 server_time 早于已存高水位 → 拒收且保留新租约。"""
|
|
||||||
client._tp.script.append(ok_lease(priv_key, server=NOW))
|
|
||||||
client.heartbeat()
|
|
||||||
old = client.state_store.load()["lease"]
|
|
||||||
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(hours=1)))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False
|
|
||||||
assert client.state_store.load()["lease"] == old
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_heartbeat_honored_with_min_60(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key, next_hb=120))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["next"] == 120
|
|
||||||
client._tp.script.append(ok_lease(priv_key, next_hb=30)) # 服务端违反 schema(min 60)→ 拒收
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
|
|
||||||
assert client.state_store.load()["next_heartbeat_seconds"] == 120 # 旧值保留
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 时钟
|
|
||||||
|
|
||||||
def test_local_clock_rollback_locks(priv_key, client):
|
|
||||||
client.cache_ttl = 0 # 回拨检测专用测试:关掉结果缓存
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
ok, _ = client.can_run()
|
|
||||||
assert ok
|
|
||||||
class T:
|
|
||||||
t = NOW - timedelta(seconds=90) # 把本机时钟往回拨
|
|
||||||
client.now_fn = lambda: T.t
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "回拨" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_clock_skew_over_5min_rejected(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(minutes=10)))
|
|
||||||
client.heartbeat()
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "5 分钟" in reason
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 掉线与离线宽限
|
|
||||||
|
|
||||||
def test_offline_grace_not_extended(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
before = client.state_store.load()["lease"]["lease_expires_at"]
|
|
||||||
client._tp.script.append(ConnectionError("断网"))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and r["code"] == "TRANSIENT"
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["lease"]["lease_expires_at"] == before # 网络失败不得延长租约
|
|
||||||
assert "heartbeat_op" in st # 在途操作保留(键+client_time 复用)
|
|
||||||
ok, _ = client.can_run()
|
|
||||||
assert ok is True # 有效租约内允许继续(离线宽限)
|
|
||||||
|
|
||||||
|
|
||||||
def test_restart_keeps_lease_without_network(priv_key, tmp_path, keyring):
|
|
||||||
"""重启不得清除高水位/租约:新客户端不联网即可继续运行。"""
|
|
||||||
tp = FakeTransport([ok_lease(priv_key)])
|
|
||||||
c1 = make_client(tmp_path, keyring, transport=tp)
|
|
||||||
c1.heartbeat()
|
|
||||||
secret = c1.secret_store.get()
|
|
||||||
tp2 = FakeTransport([]) # 一旦联网即测试失败
|
|
||||||
c2 = LicenseClient(api_base="https://license.test",
|
|
||||||
state_store=c1.state_store, secret_store=c1.secret_store,
|
|
||||||
keyring=keyring, now_fn=lambda: NOW,
|
|
||||||
sleep_fn=lambda s: None, transport=tp2)
|
|
||||||
ok, reason = c2.can_run()
|
|
||||||
assert ok is True and tp2.calls == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_tampered_local_lease_fails_closed(priv_key, client):
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
p = client.state_store.path
|
|
||||||
st = json.load(open(p, encoding="utf-8"))
|
|
||||||
st["lease_envelope"]["payload"]["entitlement_expires_at"] = "2099-01-01T00:00:00Z"
|
|
||||||
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "校验失败" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_storage_save_failure_fail_closed(priv_key, client):
|
|
||||||
"""原子存储失败:can_run 必须 fail closed,不得放行业务。"""
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
class Broken(JsonFileStore):
|
|
||||||
def update(self, fn):
|
|
||||||
raise StorageError("磁盘已满")
|
|
||||||
client.state_store = Broken(client.state_store.path)
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "fail closed" in reason
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 429 / 5xx
|
|
||||||
|
|
||||||
def test_429_respects_retry_after(priv_key, client):
|
|
||||||
client._tp.script.append((429, {"Retry-After": "7"}, {}))
|
|
||||||
client._tp.script.append(ok_lease(priv_key))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is True
|
|
||||||
assert any(s >= 7 for s in client._sleeps)
|
|
||||||
assert client._tp.keys()[0] == client._tp.keys()[1] # 同键重试
|
|
||||||
|
|
||||||
|
|
||||||
def test_5xx_bounded_retry_then_transient(priv_key, client):
|
|
||||||
for _ in range(4):
|
|
||||||
client._tp.script.append((503, {}, {}))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and r["code"] == "TRANSIENT"
|
|
||||||
assert len(client._tp.calls) == 4 # 有界
|
|
||||||
assert len(set(client._tp.keys())) == 1 # 同键同体
|
|
||||||
assert client._tp.calls[0]["body"] == client._tp.calls[-1]["body"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_403_parks_heartbeat_no_auto_retry(priv_key, client):
|
|
||||||
client._tp.script.append((403, {}, {"error": {"code": "INSTANCE_DISABLED",
|
|
||||||
"message": "x"}}))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert r["ok"] is False and len(client._tp.calls) == 1
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["status"] == "needs_attention"
|
|
||||||
assert "SECRET-DO-NOT-LOG" not in json.dumps(st) # secret 不进状态文件
|
|
||||||
for c in client._tp.calls:
|
|
||||||
assert "SECRET-DO-NOT-LOG" not in c["url"] # secret 不进 URL
|
|
||||||
assert c["body"].get("secret") == "SECRET-DO-NOT-LOG" # 只在请求体里
|
|
||||||
|
|
||||||
|
|
||||||
def test_secret_never_in_error_messages(priv_key, client):
|
|
||||||
client._tp.script.append(ConnectionError("boom"))
|
|
||||||
r = client.heartbeat()
|
|
||||||
assert "SECRET-DO-NOT-LOG" not in r.get("message", "")
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 商业版权益透出(2026-10-27)
|
|
||||||
|
|
||||||
def test_status_exposes_entitlements(priv_key, client):
|
|
||||||
"""激活企业版证书 → status 透出 edition/max_seats;未激活时为 None。"""
|
|
||||||
assert client.status().get("edition") is None # 未激活
|
|
||||||
client._tp.script.append(ok_cert(priv_key))
|
|
||||||
assert client.activate()["ok"] is True
|
|
||||||
# 缺省证书(无权益字段)→ personal/1
|
|
||||||
st = client.status()
|
|
||||||
assert st["edition"] == "personal" and st["max_seats"] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_status_exposes_enterprise_entitlements(priv_key, tmp_path, keyring):
|
|
||||||
from lic_helpers import FakeTransport, MemSecret, make_client, cert_payload, envelope
|
|
||||||
c = make_client(tmp_path, keyring,
|
|
||||||
FakeTransport([(200, {}, {"data": {"instance_id": IID, "status": "activated",
|
|
||||||
"certificate": envelope(cert_payload(edition="enterprise", max_seats=10),
|
|
||||||
priv_key, "cert")}})]))
|
|
||||||
assert c.activate()["ok"] is True
|
|
||||||
st = c.status()
|
|
||||||
assert st["edition"] == "enterprise" and st["max_seats"] == 10
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 31 加固项:can_run 结果缓存、高水位节流写、product_id 绑定、心跳并发串行、
|
|
||||||
缓存失效(心跳接受新租约后门禁立即看到)。"""
|
|
||||||
import json
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
from lic_helpers import (NOW, FakeTransport, envelope, lease_payload,
|
|
||||||
make_client, cert_payload, z)
|
|
||||||
|
|
||||||
|
|
||||||
def active_env(priv_key, server=NOW):
|
|
||||||
return (200, {}, {"data": envelope(lease_payload(server=server), priv_key, "lease")})
|
|
||||||
|
|
||||||
|
|
||||||
def test_can_run_cache_within_ttl(priv_key, client):
|
|
||||||
client.cache_ttl = 600
|
|
||||||
client.mono_fn = (lambda: 1000.0)
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
assert client.can_run()[0] is True
|
|
||||||
# TTL 内就算本地租约被篡改,也吃到缓存(这正是缓存的意义:不每请求验签)
|
|
||||||
p = client.state_store.path
|
|
||||||
st = json.load(open(p, encoding="utf-8"))
|
|
||||||
st["lease_envelope"]["payload"]["state"] = "frozen"
|
|
||||||
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
|
|
||||||
client.mono_fn = (lambda: 1001.0)
|
|
||||||
assert client.can_run()[0] is True # 缓存命中
|
|
||||||
client.mono_fn = (lambda: 1000.0 + 601) # TTL 过 → 重新验签发现篡改
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "校验失败" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_cache_invalidated_by_new_lease(priv_key, client):
|
|
||||||
client.cache_ttl = 600
|
|
||||||
client.mono_fn = (lambda: 1000.0)
|
|
||||||
client._tp.script.append((200, {}, {"data": envelope(lease_payload(state="frozen"),
|
|
||||||
priv_key, "lease")}))
|
|
||||||
client.heartbeat()
|
|
||||||
assert client.can_run()[0] is False # 负结果也进缓存
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
client.heartbeat() # 新租约必须作废缓存
|
|
||||||
assert client.can_run()[0] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_high_water_throttled_write(priv_key, client):
|
|
||||||
"""55 秒内不重复落盘高水位;跨过阈值才前进;回拨检测不受影响。"""
|
|
||||||
client.cache_ttl = 0 # 关缓存,专测节流
|
|
||||||
t = {"now": NOW}
|
|
||||||
client.now_fn = lambda: t["now"]
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
assert client.can_run()[0] is True
|
|
||||||
assert client.state_store.load()["local_high_water"] == z(NOW)
|
|
||||||
t["now"] = NOW + timedelta(seconds=30)
|
|
||||||
assert client.can_run()[0] is True
|
|
||||||
assert client.state_store.load()["local_high_water"] == z(NOW) # 未落盘
|
|
||||||
t["now"] = NOW + timedelta(seconds=60)
|
|
||||||
assert client.can_run()[0] is True
|
|
||||||
assert client.state_store.load()["local_high_water"] == z(NOW + timedelta(seconds=60))
|
|
||||||
t["now"] = NOW + timedelta(seconds=20) # 回拨 40 秒:立即锁
|
|
||||||
ok, reason = client.can_run()
|
|
||||||
assert ok is False and "回拨" in reason
|
|
||||||
|
|
||||||
|
|
||||||
def test_product_binding(priv_key, tmp_path, keyring):
|
|
||||||
c = make_client(tmp_path, keyring)
|
|
||||||
c.expected_product_id = 3
|
|
||||||
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
|
|
||||||
"status": "activated",
|
|
||||||
"certificate": envelope(
|
|
||||||
cert_payload(product_id=9), priv_key, "cert")}}))
|
|
||||||
r = c.activate()
|
|
||||||
assert r["ok"] is False and r["code"] == "PRODUCT_MISMATCH"
|
|
||||||
assert c.state_store.load().get("status") != "activated"
|
|
||||||
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
|
|
||||||
"status": "activated",
|
|
||||||
"certificate": envelope(
|
|
||||||
cert_payload(product_id=3), priv_key, "cert")}}))
|
|
||||||
assert c.activate()["ok"] is True
|
|
||||||
assert c.status()["product_id"] == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_concurrent_heartbeats_serialized(priv_key, client):
|
|
||||||
"""循环/自愈/手动三方并发:必须串行(各自完整操作、键不互踩、状态不撕)。"""
|
|
||||||
base = client._tp.__call__
|
|
||||||
|
|
||||||
def slow(method, url, body, headers):
|
|
||||||
time.sleep(0.05)
|
|
||||||
return base(method, url, body, headers)
|
|
||||||
|
|
||||||
client._send_fn = slow
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
rs = []
|
|
||||||
def beat():
|
|
||||||
rs.append(client.heartbeat())
|
|
||||||
ts = [threading.Thread(target=beat) for _ in range(2)]
|
|
||||||
[t.start() for t in ts]
|
|
||||||
[t.join() for t in ts]
|
|
||||||
assert all(r["ok"] for r in rs)
|
|
||||||
keys = [c["headers"].get("Idempotency-Key") for c in client._tp.calls]
|
|
||||||
assert len(keys) == 2 and len(set(keys)) == 2 # 两个独立操作、两把键
|
|
||||||
st = client.state_store.load()
|
|
||||||
assert st["enabled"] is True and "heartbeat_op" not in st
|
|
||||||
|
|
||||||
|
|
||||||
def test_gate_can_run_safe_uses_cache(priv_key, client):
|
|
||||||
"""门禁入口 can_run_safe 走同一缓存:TTL 内重复调用不再触发落盘。"""
|
|
||||||
client.cache_ttl = 600
|
|
||||||
client.mono_fn = (lambda: 1000.0)
|
|
||||||
client._tp.script.append(active_env(priv_key))
|
|
||||||
client.heartbeat()
|
|
||||||
a = client.can_run_safe()
|
|
||||||
b = client.can_run_safe()
|
|
||||||
assert a[0] is True and b[0] is True
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 43:生产公钥落库(spki_sha256 自校验防拷贝损坏)+ .license.json 授权文件导入。
|
|
||||||
|
|
||||||
协议红线回归:字段集精确匹配、HTTPS 根地址+允许列表、换实例须显式确认、
|
|
||||||
导入≠激活(仍走在线激活+公钥验签)、错误话术不回显文件内容。
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from cryptography.hazmat.primitives import serialization
|
|
||||||
|
|
||||||
import license_client.gate as gate
|
|
||||||
from license_client.verify import VerifyError, build_keyring
|
|
||||||
from lic_helpers import IID, IID2, cert_payload, envelope, make_client # noqa: F401
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
PINNED = os.path.join(os.path.dirname(_HERE), "server", "license_client",
|
|
||||||
"pinned_keys.json")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- spki 指纹
|
|
||||||
|
|
||||||
def _pem(priv_key):
|
|
||||||
return priv_key.public_key().public_bytes(
|
|
||||||
encoding=serialization.Encoding.PEM,
|
|
||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii")
|
|
||||||
|
|
||||||
|
|
||||||
def _spki(priv_key):
|
|
||||||
der = priv_key.public_key().public_bytes(
|
|
||||||
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
|
||||||
return hashlib.sha256(der).hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
def test_keyring_spki_match_ok(priv_key):
|
|
||||||
ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
|
|
||||||
"spki_sha256": _spki(priv_key), "revoked": False}])
|
|
||||||
assert "k1" in ring and not ring["k1"]["revoked"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_keyring_spki_case_space_tolerant(priv_key):
|
|
||||||
ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
|
|
||||||
"spki_sha256": " " + _spki(priv_key).upper() + " "}])
|
|
||||||
assert "k1" in ring
|
|
||||||
|
|
||||||
|
|
||||||
def test_keyring_spki_mismatch_rejected(priv_key):
|
|
||||||
with pytest.raises(VerifyError, match="指纹不符"):
|
|
||||||
build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
|
|
||||||
"spki_sha256": "0" * 64}])
|
|
||||||
|
|
||||||
|
|
||||||
def test_keyring_without_spki_still_ok(priv_key):
|
|
||||||
"""旧格式(无指纹)向后兼容。"""
|
|
||||||
assert build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key)}])
|
|
||||||
|
|
||||||
|
|
||||||
def test_repo_pinned_keys_prod_key_self_consistent():
|
|
||||||
"""仓库信任根:生产公钥可解析、指纹与 PEM 自洽(拷贝损坏在这里炸)。"""
|
|
||||||
with open(PINNED, encoding="utf-8") as f:
|
|
||||||
keys = json.load(f).get("pinned_keys")
|
|
||||||
assert keys and keys[0]["key_id"] == "prod-22056bfacc8fe8a2"
|
|
||||||
ring = build_keyring(keys)
|
|
||||||
assert ring["prod-22056bfacc8fe8a2"]["revoked"] is False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 导入校验
|
|
||||||
|
|
||||||
GOOD = {"format": "yhy-license-activation", "version": 1,
|
|
||||||
"api_base_url": "https://license.yihuiyong.cn",
|
|
||||||
"instance_id": IID2, "license_key": "LK-1", "secret": "SEC-1"}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def gate_env(monkeypatch, tmp_path, keyring):
|
|
||||||
assert gate.BUILD is None # 开发库无烧根文件,导入才允许回环 HTTP
|
|
||||||
c = make_client(tmp_path, keyring) # 已配置 IID
|
|
||||||
monkeypatch.setattr(gate, "_client", c)
|
|
||||||
monkeypatch.setattr(gate, "_cfg", {"enforce": True,
|
|
||||||
"api_base": "https://license.yihuiyong.cn"})
|
|
||||||
return c
|
|
||||||
|
|
||||||
|
|
||||||
def _resp(r):
|
|
||||||
assert r["kind"] == "json" and r["code"] == 200
|
|
||||||
return r["obj"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_validate_matrix(gate_env):
|
|
||||||
from license_client.gate import _import_validate
|
|
||||||
bad = [
|
|
||||||
None, # 非对象
|
|
||||||
{}, # 空对象=缺字段
|
|
||||||
{**GOOD, "extra": 1}, # 多字段
|
|
||||||
{k: v for k, v in GOOD.items() if k != "secret"}, # 缺字段
|
|
||||||
{**GOOD, "format": "yhy-license-activation2"},
|
|
||||||
{**GOOD, "version": "1"},
|
|
||||||
{**GOOD, "version": True},
|
|
||||||
{**GOOD, "instance_id": "not-a-uuid"},
|
|
||||||
{**GOOD, "secret": "a\r\nb"},
|
|
||||||
{**GOOD, "license_key": ""},
|
|
||||||
{**GOOD, "secret": 123},
|
|
||||||
{**GOOD, "api_base_url": "http://license.yihuiyong.cn"}, # 非回环 http
|
|
||||||
{**GOOD, "api_base_url": "https://evil.example.com"}, # 不在允许列表
|
|
||||||
{**GOOD, "api_base_url": "https://license.yihuiyong.cn/api/v1"}, # 带路径
|
|
||||||
{**GOOD, "api_base_url": "https://u:p@license.yihuiyong.cn"}, # 账号信息
|
|
||||||
{**GOOD, "api_base_url": "https://license.yihuiyong.cn/?x=1"}, # 查询串
|
|
||||||
{**GOOD, "api_base_url": "ftp://license.yihuiyong.cn"},
|
|
||||||
]
|
|
||||||
for b in bad:
|
|
||||||
r = _import_validate(b)
|
|
||||||
assert r["ok"] is False and r["code"] == "IMPORT_INVALID", b
|
|
||||||
assert _import_validate(GOOD)["ok"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_error_never_echoes_content(gate_env):
|
|
||||||
"""错误话术不得包含文件内容/secret(协议红线)。"""
|
|
||||||
from license_client.gate import _import_validate
|
|
||||||
leaky = {**GOOD, "secret": "SUPER-SECRET-VALUE", "instance_id": "nope"}
|
|
||||||
for _ in range(1):
|
|
||||||
r = _import_validate(leaky)
|
|
||||||
assert r["ok"] is False
|
|
||||||
assert "SUPER-SECRET-VALUE" not in r["message"]
|
|
||||||
assert "nope" not in r["message"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_loopback_http_dev_only(monkeypatch):
|
|
||||||
monkeypatch.setattr(gate, "_cfg", {"enforce": True,
|
|
||||||
"api_base": "http://127.0.0.1:8398"})
|
|
||||||
ok = gate._import_validate({**GOOD, "instance_id": IID,
|
|
||||||
"api_base_url": "http://127.0.0.1:8398"})
|
|
||||||
assert ok["ok"] is True
|
|
||||||
bad = gate._import_validate({**GOOD, "api_base_url": "http://192.168.1.5:8398"})
|
|
||||||
assert bad["ok"] is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_happy_path(priv_key, gate_env):
|
|
||||||
c = gate_env
|
|
||||||
c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated",
|
|
||||||
"certificate": envelope(
|
|
||||||
cert_payload(iid=IID2), priv_key, "cert")}}))
|
|
||||||
r = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
|
|
||||||
assert r["ok"] is True and r["data"]["result"]["ok"] is True
|
|
||||||
st = c.state_store.load()
|
|
||||||
assert st["instance_id"] == IID2 and st["status"] == "activated"
|
|
||||||
# 激活请求必须打到文件声明的实例,且带 Idempotency-Key
|
|
||||||
call = c._tp.calls[-1]
|
|
||||||
assert IID2 in call["url"] and call["headers"].get("Idempotency-Key")
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_conflict_needs_explicit_confirm(gate_env):
|
|
||||||
c = gate_env
|
|
||||||
r = _resp(gate._license_import({"file": GOOD}))
|
|
||||||
assert r["ok"] is False
|
|
||||||
assert r["data"]["result"]["code"] == "INSTANCE_CONFLICT"
|
|
||||||
assert c.state_store.load()["instance_id"] == IID # 未被动过
|
|
||||||
# 显式确认后放行(脚本无响应 → 激活 TRANSIENT,但凭据已换写)
|
|
||||||
r2 = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
|
|
||||||
assert r2["data"]["result"]["code"] == "TRANSIENT"
|
|
||||||
assert c.state_store.load()["instance_id"] == IID2
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_same_instance_no_confirm_needed(priv_key, gate_env):
|
|
||||||
c = gate_env
|
|
||||||
same = {**GOOD, "instance_id": IID}
|
|
||||||
c._tp.script.append((200, {}, {"data": {"instance_id": IID, "status": "activated",
|
|
||||||
"certificate": envelope(
|
|
||||||
cert_payload(iid=IID), priv_key, "cert")}}))
|
|
||||||
r = _resp(gate._license_import({"file": same}))
|
|
||||||
assert r["ok"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_high_water_preserved(priv_key, gate_env):
|
|
||||||
"""换实例导入不清高水位(协议:切换身份保留时间记录)。"""
|
|
||||||
c = gate_env
|
|
||||||
st = c.state_store.load()
|
|
||||||
st["local_high_water"] = "2026-10-01T00:00:00Z"
|
|
||||||
st["server_high_water"] = "2026-10-01T00:00:00Z"
|
|
||||||
c.state_store.update(lambda s: s.update({"local_high_water": st["local_high_water"],
|
|
||||||
"server_high_water": st["server_high_water"]}))
|
|
||||||
c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated",
|
|
||||||
"certificate": envelope(
|
|
||||||
cert_payload(iid=IID2), priv_key, "cert")}}))
|
|
||||||
_resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
|
|
||||||
st2 = c.state_store.load()
|
|
||||||
assert st2["local_high_water"] == "2026-10-01T00:00:00Z"
|
|
||||||
assert st2["server_high_water"] == "2026-10-01T00:00:00Z"
|
|
||||||
@@ -1,246 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""验签单元测试:包内向量 + 全套负向(篡改/未知密钥/撤销/实例不匹配/v1/额外字段/
|
|
||||||
非法类型/CR-LF-NUL/Base64URL/canonical_sha256 不符/非 P-256 公钥)。"""
|
|
||||||
import hashlib
|
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec
|
|
||||||
|
|
||||||
from lic_helpers import (IID, IID2, NOW, canonical, cert_payload, envelope,
|
|
||||||
lease_payload, load_vectors, sign_b64)
|
|
||||||
from license_client.verify import (LICENSE_V2, LEASE_V2, VerifyError,
|
|
||||||
build_keyring, canonical_bytes,
|
|
||||||
entitlements,
|
|
||||||
verify_certificate, verify_lease)
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 包内随机测试向量
|
|
||||||
|
|
||||||
def test_package_vectors_canonical_matches():
|
|
||||||
"""先验规范化串本身:我们拼的字节必须和接入包给的 canonical 逐字节一致。"""
|
|
||||||
v = load_vectors()
|
|
||||||
for kind, version in (("license", LICENSE_V2), ("lease", LEASE_V2)):
|
|
||||||
assert canonical_bytes(v[kind]["payload"], version) == v[kind]["canonical"].encode("utf-8")
|
|
||||||
assert hashlib.sha256(v[kind]["canonical"].encode("utf-8")).hexdigest() \
|
|
||||||
== v[kind]["canonical_sha256"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_package_vectors_verify():
|
|
||||||
"""用包内随机测试公钥过 license-v2 / lease-v2 验签(接入包要求的先行动作)。"""
|
|
||||||
v = load_vectors()
|
|
||||||
ring = build_keyring(v["pinned_keys"])
|
|
||||||
lic = {"version": LICENSE_V2,
|
|
||||||
"payload": v["license"]["payload"],
|
|
||||||
"signature": v["license"]["signature"],
|
|
||||||
"canonical_sha256": v["license"]["canonical_sha256"]}
|
|
||||||
assert verify_certificate(lic, IID, ring)["version"] == LICENSE_V2
|
|
||||||
lease = {"payload": v["lease"]["payload"],
|
|
||||||
"signature": v["lease"]["signature"],
|
|
||||||
"canonical_sha256": v["lease"]["canonical_sha256"],
|
|
||||||
"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}
|
|
||||||
assert verify_lease(lease, IID, ring)["state"] == "active"
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 正常路径
|
|
||||||
|
|
||||||
def test_roundtrip_cert_and_lease(priv_key, keyring):
|
|
||||||
p = cert_payload()
|
|
||||||
assert verify_certificate(envelope(p, priv_key, "cert"), IID, keyring) == p
|
|
||||||
p2 = lease_payload()
|
|
||||||
assert verify_lease(envelope(p2, priv_key, "lease"), IID, keyring) == p2
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 篡改与伪造
|
|
||||||
|
|
||||||
def test_tampered_payload_field(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env["payload"]["state"] = "frozen" # 换状态不换签名
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_tampered_signature(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
sig = env["signature"]
|
|
||||||
env["signature"] = ("A" if sig[0] != "A" else "B") + sig[1:]
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_signed_by_foreign_key(keyring):
|
|
||||||
evil = ec.generate_private_key(ec.SECP256R1())
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(), evil, "lease"), IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_key_id(priv_key):
|
|
||||||
ring = build_keyring([]) # 空信任根
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_revoked_key(priv_key):
|
|
||||||
from lic_helpers import make_keyring
|
|
||||||
ring = make_keyring(priv_key, revoked=True)
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_instance_mismatch(priv_key, keyring):
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(iid=IID2), priv_key, "lease"), IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 结构拒绝
|
|
||||||
|
|
||||||
def test_v1_rejected(priv_key, keyring):
|
|
||||||
p = lease_payload(version="lease-v1")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(p, priv_key, "lease"), IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_field(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env["payload"].pop("key_id") # 先签名再抠字段:canonical 与字段集必须双双拒
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_extra_field(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env["payload"]["extra"] = "x"
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_wrong_types(priv_key, keyring):
|
|
||||||
def bad_cert(mut):
|
|
||||||
env = envelope(cert_payload(), priv_key, "cert")
|
|
||||||
mut(env["payload"])
|
|
||||||
return env
|
|
||||||
|
|
||||||
with pytest.raises(VerifyError): # ID 变字符串
|
|
||||||
verify_certificate(bad_cert(lambda p: p.update(license_id="1")), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError): # ID 非正数
|
|
||||||
verify_certificate(bad_cert(lambda p: p.update(license_id=0)), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError): # bool 冒充整数
|
|
||||||
verify_certificate(bad_cert(lambda p: p.update(license_id=True)), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError): # 非法状态枚举
|
|
||||||
verify_lease(bad_cert(lambda p: p.update(state="睡了的")), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError): # 时间格式坏
|
|
||||||
verify_lease(bad_cert(lambda p: p.update(server_time="2026/10/09 03:00:00")),
|
|
||||||
IID, keyring)
|
|
||||||
with pytest.raises(VerifyError): # instance_id 非 UUID
|
|
||||||
verify_certificate(bad_cert(lambda p: p.update(instance_id="not-a-uuid")),
|
|
||||||
IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_cr_lf_nul_in_fields(priv_key, keyring):
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(key_id="k\nid"), priv_key, "lease"), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(key_id="k\r"), priv_key, "lease"), IID, keyring)
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(envelope(lease_payload(key_id="k\x00"), priv_key, "lease"), IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_base64url_signature_rejected(priv_key, keyring):
|
|
||||||
"""Base64URL 字母表(-/_)不是标准 Base64:出现即拒,不猜填充。"""
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env["signature"] = "-" + env["signature"][1:]
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
env2 = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env2["signature"] = "_" + env2["signature"][1:]
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env2, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_canonical_sha_mismatch(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease", sha="0" * 64)
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_non_p256_key_rejected_at_ring_build():
|
|
||||||
p384 = ec.generate_private_key(ec.SECP384R1())
|
|
||||||
from cryptography.hazmat.primitives import serialization
|
|
||||||
pem = p384.public_key().public_bytes(
|
|
||||||
encoding=serialization.Encoding.PEM,
|
|
||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
build_keyring([{"key_id": "k", "public_key_pem": pem}])
|
|
||||||
|
|
||||||
|
|
||||||
def test_lease_envelope_requires_algorithm_and_next(priv_key, keyring):
|
|
||||||
env = envelope(lease_payload(), priv_key, "lease")
|
|
||||||
env.pop("algorithm")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
env2 = envelope(lease_payload(), priv_key, "lease", next_hb=30) # < 60 拒
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env2, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_cert_envelope_missing_version(priv_key, keyring):
|
|
||||||
env = envelope(cert_payload(), priv_key, "cert")
|
|
||||||
env.pop("version")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_certificate(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------ 商业版权益字段(2026-10-27)
|
|
||||||
# 口径:《企业和个人版.md》5.1——证书载荷可选携带 edition/max_seats;
|
|
||||||
# 缺省 personal/1(fail-closed 不放大);canonical 把出现的可选字段按固定顺序追加。
|
|
||||||
|
|
||||||
def test_optional_entitlements_absent_passes_with_default(priv_key, keyring):
|
|
||||||
"""旧格式证书(无权益字段,平台未升级协议时)必须照常通过,且缺省口径正确。"""
|
|
||||||
env = envelope(cert_payload(), priv_key, "cert")
|
|
||||||
p = verify_certificate(env, IID, keyring)
|
|
||||||
assert "edition" not in p and "max_seats" not in p
|
|
||||||
assert entitlements(p) == {"edition": "personal", "max_seats": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def test_optional_entitlements_present_roundtrip(priv_key, keyring):
|
|
||||||
"""带权益字段的证书:验签通过、字段原样带回、canonical 覆盖可选字段。"""
|
|
||||||
p = cert_payload(edition="enterprise", max_seats=10)
|
|
||||||
env = envelope(p, priv_key, "cert")
|
|
||||||
got = verify_certificate(env, IID, keyring)
|
|
||||||
assert got["edition"] == "enterprise" and got["max_seats"] == 10
|
|
||||||
assert entitlements(got) == {"edition": "enterprise", "max_seats": 10}
|
|
||||||
# 只带 edition 不带 max_seats:允许,缺省 1
|
|
||||||
got2 = verify_certificate(envelope(cert_payload(edition="trial"), priv_key, "cert"),
|
|
||||||
IID, keyring)
|
|
||||||
assert entitlements(got2) == {"edition": "trial", "max_seats": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def test_optional_entitlements_tampering_breaks_signature(priv_key, keyring):
|
|
||||||
"""改权益字段不换签名必须拒(max_seats 私自 10→99 拿旧签名 = 验签失败)。"""
|
|
||||||
env = envelope(cert_payload(edition="enterprise", max_seats=10), priv_key, "cert")
|
|
||||||
env["payload"]["max_seats"] = 99
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_certificate(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_optional_entitlements_bad_values_rejected(priv_key, keyring):
|
|
||||||
for bad in ({"edition": "team"}, {"edition": ""}, {"edition": 3},
|
|
||||||
{"max_seats": 0}, {"max_seats": -1}, {"max_seats": "10"},
|
|
||||||
{"max_seats": True}, {"edition": "enterprise\r\nx"}):
|
|
||||||
env = envelope(cert_payload(**bad), priv_key, "cert")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_certificate(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_optional_entitlements_only_on_cert_not_lease(priv_key, keyring):
|
|
||||||
"""租约载荷带 edition = 未知多字段,必须拒(可选字段只属于证书)。"""
|
|
||||||
env = envelope(lease_payload(edition="enterprise"), priv_key, "lease")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_lease(env, IID, keyring)
|
|
||||||
|
|
||||||
|
|
||||||
def test_optional_entitlements_unknown_extra_still_rejected(priv_key, keyring):
|
|
||||||
"""可选字段之外的多余键(如 data_grace_days 已取消)仍然全拒。"""
|
|
||||||
env = envelope(cert_payload(data_grace_days=30), priv_key, "cert")
|
|
||||||
with pytest.raises(VerifyError):
|
|
||||||
verify_certificate(env, IID, keyring)
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""工料机取价链(2026-11-04 主人拍板对齐决策 268补二/补三 口径;原 219「一码一行认第一行」已取代)。
|
|
||||||
|
|
||||||
钉死五件事(样本对数法,数字全部取自会话75报障形态):
|
|
||||||
① 单位级取价:同单位内按**成员(码+除数量外全字段)分行**——电 0.77/0.75 两个成员各自成行;
|
|
||||||
② 项目级归并:全字段(名/规/单/类别)+三价一致的成员归一行、量=成员单位现算量之和(电 0.77→23);
|
|
||||||
③ 不一致独立:任一字段不同 → 各自成行(电 0.75 成员量 3、机柜 无规格/42U/24U 三行);
|
|
||||||
s_lme_proj 异类价(3.61)不再出现;
|
|
||||||
④ 兜底:单位级行缺价 → 项目级快照补;仅项目级有的码 → 独立成行(量=现算);
|
|
||||||
⑤ 单位级卡:本单位按成员分行、量=本单位现算(同成员多行数量累计)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
import dyn_lme as dyn # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
|
|
||||||
ntp REAL, taxrate REAL, taxp REAL, x_merged_hide INTEGER DEFAULT 0,
|
|
||||||
x_remark TEXT, x_ntp0 REAL, x_rate0 REAL, x_taxp0 REAL, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, Quantity REAL)")
|
|
||||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL, Unit TEXT, x_side TEXT)")
|
|
||||||
c.execute("CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL)")
|
|
||||||
# 单位级行(id 序=导入序)——101/102 各有电:101 认第一行 0.77(0.75 被随便认掉)
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?,?,?,?,?,?,?,?)""",
|
|
||||||
[(1, 101, "E", "电", "", "度", 3, 1.0, 0.77, 0.0, 0.77),
|
|
||||||
(2, 101, "E", "电", "", "度", 3, 2.0, 0.75, 0.0, 0.75), # 同单位第二行 → 不认
|
|
||||||
(3, 102, "E", "电", "", "度", 3, 20.0, 0.77, 0.0, 0.77),
|
|
||||||
(4, 102, "G", "镀锌扁钢", "综合", "kg", 3, 5.0, 5.59, 0.0, 5.59),
|
|
||||||
(5, 101, "G", "镀锌扁钢", "综合", "kg", 3, 5.0, 5.59, 0.0, 5.59),
|
|
||||||
(6, 101, "M", "机柜", "", "个", 3, 1.0, 100.0, 0.0, 100.0),
|
|
||||||
(7, 101, "M", "机柜", "42U", "个", 3, 1.0, 100.0, 0.0, 100.0), # 同单位第二行 → 不认
|
|
||||||
(8, 102, "M", "机柜", "24U", "个", 3, 20.0, 100.0, 0.0, 100.0),
|
|
||||||
(9, 101, "P", "型钢", "", "kg", 3, 2.0, None, None, None)]) # 缺价 → 兜底项目级
|
|
||||||
# 项目级:E 是异类价 3.61(报障形态,不得再出现);Z 仅项目级有;P 供缺价兜底
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?,?,?,?,?,?,?)""",
|
|
||||||
[(901, "E", "电", "", "度", 3, 999.0, 3.61, 0.0, 0.0),
|
|
||||||
(902, "Z", "支架", "", "kg", 3, 0.0, 9.9, 0.0, 9.9),
|
|
||||||
(903, "P", "型钢", "", "kg", 3, 0.0, 2.0, 0.0, 2.0)])
|
|
||||||
# 现算链:101=3、102=20(E);G 101=5/102=5;M 101=1/102=20;Z 102=10;P 101=2
|
|
||||||
c.executemany("INSERT INTO s_bills(id, session_id, uw_id, Quantity) VALUES(?,1,?,?)",
|
|
||||||
[(1, 101, 1.0), (2, 101, 1.0), (3, 102, 1.0)])
|
|
||||||
c.executemany("INSERT INTO s_norms(id, bill_id, Quantity, Unit) VALUES(?,?,?,NULL)",
|
|
||||||
[(1, 1, 1.0), (2, 2, 1.0), (3, 3, 10.0)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
|
|
||||||
[(1, "E", 3.0), (1, "G", 5.0), (1, "M", 1.0), (1, "P", 2.0),
|
|
||||||
(3, "E", 2.0), (3, "G", 0.5), (3, "M", 2.0), (3, "Z", 1.0)])
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _by_code(rows):
|
|
||||||
return {(r[1], r[2], r[3]): r for r in rows}
|
|
||||||
|
|
||||||
|
|
||||||
def test_uw_first_row_and_merge_rules():
|
|
||||||
rows = dyn.dyn_rows(_mk(), 1, None)
|
|
||||||
d = _by_code(rows)
|
|
||||||
# ② 2026-11-04 对齐 268补三:电 0.77/0.75 两个成员(同码同规格、价不同)——字典键
|
|
||||||
# (码,名,规)对两价成员有歧义,改用集合断言钉死两行(见下方 e_rows)
|
|
||||||
g = d[("G", "镀锌扁钢", "综合")]
|
|
||||||
assert (g[5], g[6]) == (10.0, 5.59)
|
|
||||||
# ③ 字段不一致 → 各自独立(机柜:101 无规格 1 / 101 42U 1 / 102 24U 20)
|
|
||||||
m1 = d[("M", "机柜", "")]
|
|
||||||
m2 = d[("M", "机柜", "24U")]
|
|
||||||
m3 = d[("M", "机柜", "42U")]
|
|
||||||
assert m1[5] == 1.0 and m2[5] == 20.0 and m3[5] == 1.0
|
|
||||||
# ④ 兜底:P 单位级行缺价 → 项目级 2.0 补;Z 仅项目级有 → 独立成行(量=现算 10)
|
|
||||||
p = d[("P", "型钢", "")]
|
|
||||||
assert (p[5], p[6]) == (2.0, 2.0)
|
|
||||||
z = d[("Z", "支架", "")]
|
|
||||||
assert (z[5], z[6]) == (10.0, 9.9)
|
|
||||||
# 2026-11-04 主人拍板对齐 268补三:电 0.75 是 uw101 的独立成员 → 项目级两行
|
|
||||||
#(0.77 归并 101+102 量 23;0.75 独立量 3);异类价 3.61 仍不得出现
|
|
||||||
e_rows = sorted((r[5], r[6], r[8]) for r in rows if r[1] == "E")
|
|
||||||
assert e_rows == [(3.0, 0.75, 0.75), (23.0, 0.77, 0.77)]
|
|
||||||
assert not any(abs(r[6] - 3.61) < 1e-9 for r in rows if r[1] == "E")
|
|
||||||
|
|
||||||
|
|
||||||
def test_uw_view_own_rows():
|
|
||||||
rows = dyn.dyn_uw_rows(_mk(), 1, 101)
|
|
||||||
d = {(r[0], r[1]): r for r in rows}
|
|
||||||
# ①⑤ 2026-11-04 主人拍板对齐 268补三:本单位按成员分行——电 0.77/0.75 两个成员各自
|
|
||||||
# 成行、量各为本单位现算 3.0;机柜 无规格/42U 两个成员各 1.0(不再「认第一行扔第二行」)
|
|
||||||
assert sorted((r[5], r[6]) for r in rows if r[0] == "E") == [(3.0, 0.75), (3.0, 0.77)]
|
|
||||||
assert sorted((r[2], r[5]) for r in rows if r[0] == "M") == [("", 1.0), ("42U", 1.0)]
|
|
||||||
assert d[("P", "型钢")][6] == 2.0 # 缺价兜底
|
|
||||||
assert ("Z", "支架") not in d # 本单位表无行且无现算 → 不出
|
|
||||||
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 244 补记三(2026-11-01 主人定「导出=显示端所见,与源文件无关」)防回归。
|
|
||||||
|
|
||||||
钉死三件事:
|
|
||||||
①单位件:码不在现算图(没被引用)→ 汇总节点不导出——即使节点带着源文件原量;
|
|
||||||
②现算 0 的码同样不导出;现算 >0 的保留;
|
|
||||||
③项目级聚合重建:聚合中完全没有的纯项目级行不再照源文件保留(旧兜底撤除)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
|
|
||||||
S = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
|
|
||||||
|
|
||||||
def _node(code, qty, name="电", price="0.75"):
|
|
||||||
return ('<{S} Number="{c}" Name="{n}" Specification="" Unit="kw·h" LossRate="0"'
|
|
||||||
' Quantity="{q}" TaxRate="0" NoTaxOrgPrice="{p}" NoTaxPriceExpress="{p}"'
|
|
||||||
' NoTaxPrice="{p}" TaxOrgPrice="{p}" TaxPriceExpress="{p}" TaxPrice="{p}"'
|
|
||||||
' NoTaxOrgTotal="0" NoTaxTotal="0" TaxOrgTotal="0" TaxTotal="0" Class=""'
|
|
||||||
' Concrete="false" Kind="2" ExtKind="1" AddiKind="" MainMaterial="false"'
|
|
||||||
' ProvisionalMaterial="false" Provider="1" PriceSource="" Delivery=""'
|
|
||||||
' Location="" ProducingArea="" Supplier="" Character="" Remark=""/>').format(
|
|
||||||
S=S, c=code, n=name, q="%.4f" % qty, p=price)
|
|
||||||
|
|
||||||
|
|
||||||
def test_live_filter_drops_unreferenced_and_zero():
|
|
||||||
"""①②:源文件节点带原量(柴油-0002=13.3),但不在现算图 → 删;现算 0 → 删;现算 >0 → 留。"""
|
|
||||||
txt = ("<r>" + _node("99450680-0002", 13.3, "柴油")
|
|
||||||
+ _node("99450700", 435.3279)
|
|
||||||
+ _node("99450700-0001", 0.0) + "</r>")
|
|
||||||
live = {"99450700": 435.3279} # 显示端只有基码(变体零引用/0 量)
|
|
||||||
out = xcos._drop_zero_qty_summary_rows(txt, live)
|
|
||||||
assert "99450680-0002" not in out # 没被引用 → 不导(源量 13.3 也不带)
|
|
||||||
assert "99450700-0001" not in out # 现算 0 → 不导
|
|
||||||
assert 'Number="99450700"' in out # 显示端有 → 全量导出
|
|
||||||
# live=None 退老行为:只有 Quantity==0 删(老会话/链故障兼容)
|
|
||||||
out2 = xcos._drop_zero_qty_summary_rows(txt)
|
|
||||||
assert "99450680-0002" in out2 and "99450700" in out2 and "99450700-0001" not in out2
|
|
||||||
|
|
||||||
|
|
||||||
def test_rebuild_project_drops_non_displayed_rows():
|
|
||||||
"""③:聚合重建收紧——聚合中完全没有的纯项目级行不再照源文件保留。"""
|
|
||||||
unit_txt = "<r>" + _node("99450700", 238024.1197) + "</r>"
|
|
||||||
proj_txt = ("<r>" + _node("99450700", 238024.1197)
|
|
||||||
+ _node("99450700-0001", 435.3279) # 源 Project 有、单位聚合没有 → 新口径删
|
|
||||||
+ _node("ZMZJRG", 10065754.48, "子目增加费") + "</r>") # 同上(费用行)
|
|
||||||
out = xcos._rebuild_project_lme(proj_txt, [unit_txt], [], [])
|
|
||||||
assert 'Number="99450700"' in out
|
|
||||||
assert "99450700-0001" not in out # 显示端没有 → 不导
|
|
||||||
assert "ZMZJRG" not in out # 费用行现算无 → 不导(留在原文件里)
|
|
||||||
# 数量=各单位之和严格成立
|
|
||||||
import re
|
|
||||||
q = re.search(r'Number="99450700"[^>]*Quantity="([0-9.]+)"', out)
|
|
||||||
assert abs(float(q.group(1)) - 238024.1197) < 0.01
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""项目级工料机汇总 名称/规格型号/单位 行内编辑防回归(2026-10-22 主人定)。
|
|
||||||
|
|
||||||
钉死六件事:
|
|
||||||
①编码永不被编辑动到;响应回带服务端现值。
|
|
||||||
②两表一起更新:写 s_lme_proj 后按编码同步**存在该编码**的全部 s_lme_uw(别的编码不动)。
|
|
||||||
③拒改三闸:已合并隐藏行、金额汇总行(单位=元)、空名称;没给字段=拒。
|
|
||||||
④编辑过的编码登记 lme_field_codes(导出回写唯一来源),没编辑过的不登。
|
|
||||||
⑤合并改码贯通全部定额:api_lme_merge 把被合并码在本会话**所有** s_norm_res 行
|
|
||||||
(跨单位工程、express 原样保留)物理替换为保留码;其他编码不动。
|
|
||||||
⑥导出侧:_recode_norm_lme_rows 只换 Summary 块外的工料机行编码(块内子级组成不碰);
|
|
||||||
transform_unit_summaries 的 field_updates 回写 Name/Specification/Unit(金额行不写,
|
|
||||||
改码命中的节点也吃到保留码的编辑值)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import sys, os
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
import export_cos as xc # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess(with_norms=False):
|
|
||||||
"""内存会话库(同 test_lme_price 骨架)。with_norms=True 时加 清单/定额/消耗量 三表
|
|
||||||
并铺跨单位数据(合并贯通验证用):
|
|
||||||
单位101: bill1 → norm10/11;单位102: bill2 → norm12;
|
|
||||||
norm_res:norm10(C9,1.5) norm11(C9,2.0,express='2.0*1.1') norm12(C9,0.5) norm10(C1,3.0)。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
# id=1 正常材料 C1;id=2 台班 P1;id=3 已隐藏;id=4 C9(与 C1 同名同规格同单位、价不同=合并组对手)
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp, x_merged_hide) VALUES(?,1,?,?, '', 'kg',2, 100, ?, ?, ?, ?)""",
|
|
||||||
[(1, "C1", "钢筋", 99.99, 3.5, 103.49, 0),
|
|
||||||
(2, "P1", "挖掘机台班", 900.0, 3.5, 931.5, 0),
|
|
||||||
(3, "C9h", "已隐藏", 1.0, 0.0, 1.0, 1),
|
|
||||||
(4, "C9", "钢筋", 88.0, 3.5, 91.04, 0)])
|
|
||||||
# 单位级:C1 在两个单位工程各有行(uw 101/102);C9 在 uw 101 有一行;C2 一行(对照,不该被波及)
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,'C1','钢筋','kg',2, 10, 99.99, 3.5, 103.49)""",
|
|
||||||
[(11, 101), (12, 102)])
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(13,1,103,'C2','水泥','kg',2, 10, 200.0, 3.5, 207.0)""")
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(14,1,101,'C9','钢筋','kg',2, 5, 88.0, 3.5, 91.04)""")
|
|
||||||
if with_norms:
|
|
||||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
|
|
||||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL, express TEXT)""")
|
|
||||||
c.executemany("INSERT INTO s_bills(id, session_id, uw_id) VALUES(?,?,?)",
|
|
||||||
[(1, 1, 101), (2, 1, 102)])
|
|
||||||
c.executemany("INSERT INTO s_norms(id, bill_id) VALUES(?,?)", [(10, 1), (11, 1), (12, 2)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
|
||||||
[(10, "C9", 1.5, None), (11, "C9", 2.0, "2.0*1.1"),
|
|
||||||
(12, "C9", 0.5, None), (10, "C1", 3.0, None)])
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _field_codes(sc):
|
|
||||||
r = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k=?",
|
|
||||||
("session:1", "lme_field_codes")).fetchone()
|
|
||||||
return set(json.loads(r[0])) if r else set()
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- ①② 编辑落库 + 两表一起更新 ----------
|
|
||||||
|
|
||||||
def test_field_edit_syncs_proj_and_all_uw():
|
|
||||||
"""改名称:项目级行更新、存在该编码的两个单位级行都同步(synced=2)、别码不动、编码不变。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_field(sc, {"session_id": SID, "id": 1, "name": "螺纹钢"})
|
|
||||||
assert r["ok"] is True and r["code"] == "C1" and r["synced"] == 2
|
|
||||||
assert r["name"] == "螺纹钢"
|
|
||||||
row = sc.execute("SELECT name, code FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (row["name"], row["code"]) == ("螺纹钢", "C1")
|
|
||||||
names = {r["uw_id"]: r["name"] for r in sc.execute(
|
|
||||||
"SELECT uw_id, name FROM s_lme_uw WHERE code='C1'")}
|
|
||||||
assert names == {101: "螺纹钢", 102: "螺纹钢"}
|
|
||||||
assert sc.execute("SELECT name FROM s_lme_uw WHERE code='C2'").fetchone()[0] == "水泥"
|
|
||||||
|
|
||||||
|
|
||||||
def test_field_spec_unit_can_be_cleared():
|
|
||||||
"""规格/单位允许清空('没算留空、别人的数据擦掉'口径);只给 spec 就只动 spec。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_field(sc, {"session_id": SID, "id": 1, "spec": "", "unit": "t"})
|
|
||||||
assert r["ok"] is True
|
|
||||||
row = sc.execute("SELECT spec, unit FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (row["spec"], row["unit"]) == ("", "t")
|
|
||||||
r2 = srv.api_lme_field(sc, {"session_id": SID, "id": 1, "spec": "Φ12 HRB400"})
|
|
||||||
assert r2["ok"] is True and r2["unit"] == "t" # 没给的字段不动
|
|
||||||
|
|
||||||
|
|
||||||
def test_field_guards():
|
|
||||||
"""两闸:空名称拒;隐藏行拒;没给字段拒;行不存在拒。
|
|
||||||
金额汇总行(决策 169)视同普通工料机——元行照常可改,不再拒。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
assert srv.api_lme_field(sc, {"session_id": SID, "id": 1, "name": " "})["ok"] is False
|
|
||||||
assert srv.api_lme_field(sc, {"session_id": SID, "id": 3, "name": "改隐藏行"})["ok"] is False
|
|
||||||
assert srv.api_lme_field(sc, {"session_id": SID, "id": 1})["ok"] is False
|
|
||||||
assert srv.api_lme_field(sc, {"session_id": SID, "id": 999, "name": "x"})["ok"] is False
|
|
||||||
# 元行(单价=500,主人实测报障的「人工费无法修改」)——可编辑,两表同步
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind, qty, ntp, taxp, x_merged_hide)"
|
|
||||||
" VALUES(9,1,'00010010','人工费','', '元',1, 7168444.86, 500.0, 500.0, 0)")
|
|
||||||
r = srv.api_lme_field(sc, {"session_id": SID, "id": 9, "name": "定额人工费"})
|
|
||||||
assert r["ok"] is True and r["name"] == "定额人工费"
|
|
||||||
# 单价=1 的真金额行同样视同普通行
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind, qty, ntp, taxp, x_merged_hide)"
|
|
||||||
" VALUES(10,1,'99450630','折旧费','', '元',2, 215354.22, 1.0, 1.0, 0)")
|
|
||||||
r2 = srv.api_lme_field(sc, {"session_id": SID, "id": 10, "name": "折旧费(改)"})
|
|
||||||
assert r2["ok"] is True and r2["name"] == "折旧费(改)"
|
|
||||||
|
|
||||||
|
|
||||||
def test_field_registers_only_edited_codes():
|
|
||||||
"""编辑过的编码进 lme_field_codes;没编辑的不进;对照码不受波及。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
srv.api_lme_field(sc, {"session_id": SID, "id": 1, "spec": "Φ12"})
|
|
||||||
assert _field_codes(sc) == {"C1"}
|
|
||||||
srv.api_lme_field(sc, {"session_id": SID, "id": 2, "name": "挖机台班"})
|
|
||||||
assert _field_codes(sc) == {"C1", "P1"}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- ⑤ 合并改码贯通全部定额 ----------
|
|
||||||
|
|
||||||
def test_merge_recodes_norm_res_across_project():
|
|
||||||
"""合并(C9 并入 C1)后:本会话全部定额消耗量行的 C9 → C1(跨单位工程、express 保留),
|
|
||||||
其他编码不动;单位级 C9 行换码(决策 171 补三:无跳过,同单位同码双行);recode_map 登记。"""
|
|
||||||
sc = _mk_sess(with_norms=True)
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [
|
|
||||||
{"sel": {"id": 1, "ntp": 99.99, "taxrate": 3.5, "taxp": 103.49},
|
|
||||||
"hide": [{"id": 4}, {"uw": 1, "code": "C9", "uw_ids": [101]}]}]})
|
|
||||||
assert r["ok"] is True and r["hidden"] == 2
|
|
||||||
# 全部定额消耗量行:C9 → C1(跨单位工程 norm10/11/12 全中、express 原样、无残留)
|
|
||||||
# 决策 200(2026-10-25 主人定):换码碰撞后同一定额同码只出一条——norm10 的 C9(1.5)
|
|
||||||
# 并进 C1(3.0) → 一条 4.5;全库 C1 共 3 条。
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_norm_res WHERE res_code='C9'").fetchone()[0] == 0
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_norm_res WHERE res_code='C1'").fetchone()[0] == 3
|
|
||||||
_r10 = sc.execute("SELECT qty FROM s_norm_res WHERE norm_id=10 AND res_code='C1'").fetchone()
|
|
||||||
assert abs(_r10[0] - 4.5) < 1e-9
|
|
||||||
assert sc.execute("SELECT express FROM s_norm_res WHERE norm_id=11 AND res_code='C1'").fetchone()[0] == "2.0*1.1"
|
|
||||||
# 单位级:决策 171 补三无跳过——uw101 的 C9 行也换成 C1(同码双行)
|
|
||||||
assert sc.execute("SELECT code FROM s_lme_uw WHERE id=14").fetchone()[0] == "C1"
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw WHERE code='C9'").fetchone()[0] == 0
|
|
||||||
rm = sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()
|
|
||||||
assert json.loads(rm[0]) == {"C9": "C1"}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- ⑥ 导出侧 ----------
|
|
||||||
|
|
||||||
_SUM1 = ('<Root><A/><LabourMaterialsEquipmentsMachinesSummary Number="C1" Name="旧名" Specification="旧规"'
|
|
||||||
' Unit="kg" Kind="2" TotalQuantity="1.0000" NoTaxPrice="1.00" TaxPrice="1.00"/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="C9" Quantity="0.5000"/></Root>')
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_recode_norm_lme_rows_skips_summary_block():
|
|
||||||
"""定额行换码(决策 178 改):全部工料机行 C9→C1——块内子级组成也照映射换编码(含量不动);
|
|
||||||
Summary 母节点不归本通道(归 transform_unit_summaries 换码)。"""
|
|
||||||
txt = ('<Norm Number="E1"><LabourMaterialsEquipmentsMachinesElement Number="C9" Quantity="1.5000"/></Norm>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesSummary Number="C9" Name="甲" Specification="s" Unit="kg"'
|
|
||||||
' Kind="2" TotalQuantity="1.0000" NoTaxPrice="1.00" TaxPrice="1.00">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="C9" Quantity="2.0000"/>'
|
|
||||||
'</LabourMaterialsEquipmentsMachinesSummary>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="C9" Quantity="0.5000"/>')
|
|
||||||
out = xc._recode_norm_lme_rows(txt, {"C9": "C1"})
|
|
||||||
assert 'Number="C1" Quantity="1.5000"' in out
|
|
||||||
assert 'Number="C1" Quantity="0.5000"' in out
|
|
||||||
assert 'Number="C1" Quantity="2.0000"' in out
|
|
||||||
assert not re.search(r'<LabourMaterialsEquipmentsMachinesElement Number="C9"', out)
|
|
||||||
assert 'Summary Number="C9"' in out
|
|
||||||
# 无映射原样返回
|
|
||||||
assert xc._recode_norm_lme_rows(txt, {}) == txt
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_field_updates_writeback():
|
|
||||||
"""编辑过的编码回写 Name/Specification/Unit;未编辑编码原样;金额汇总行视同普通行照写(决策 169)。"""
|
|
||||||
out = xc.transform_unit_summaries(_SUM1, {}, [], {}, {}, field_updates={"C1": ("新名", "新规", "t")})
|
|
||||||
assert 'Name="新名"' in out and 'Specification="新规"' in out and 'Unit="t"' in out
|
|
||||||
assert xc.transform_unit_summaries(_SUM1, {}, [], {}, {}, field_updates={"CX": ("x", "y", "z")}) == _SUM1
|
|
||||||
amt = _SUM1.replace('Number="C1" Name="旧名" Specification="旧规" Unit="kg" Kind="2"'
|
|
||||||
' TotalQuantity="1.0000" NoTaxPrice="1.00"',
|
|
||||||
'Number="F1" Name="人工费" Specification="" Unit="元" Kind="1"'
|
|
||||||
' TotalQuantity="5000.0000" NoTaxPrice="1.00"')
|
|
||||||
out2 = xc.transform_unit_summaries(amt, {}, [], {}, {}, field_updates={"F1": ("定额人工费", "", "")})
|
|
||||||
assert 'Name="定额人工费"' in out2 # 决策 169:金额行视同普通行,名规格照写
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_recode_node_gets_field_values():
|
|
||||||
"""改码命中的节点(该单位原是旧码)也吃到保留码的编辑值;None 字段不碰。"""
|
|
||||||
txt = ('<Root><LabourMaterialsEquipmentsMachinesSummary Number="C9" Name="甲" Specification="s"'
|
|
||||||
' Unit="kg" Kind="2" TotalQuantity="1.0000" NoTaxPrice="1.00" TaxPrice="1.00"/></Root>')
|
|
||||||
out = xc.transform_unit_summaries(txt, {}, [], {"C9": "C1"}, {},
|
|
||||||
field_updates={"C1": ("螺纹钢", None, "t")})
|
|
||||||
assert 'Number="C1"' in out and 'Name="螺纹钢"' in out and 'Unit="t"' in out
|
|
||||||
assert 'Specification="s"' in out # None 不碰原值
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_no_field_no_recode_keeps_text():
|
|
||||||
"""零编辑 + 无改码:单位汇总文本一个字都不动(防零编辑误改回归)。"""
|
|
||||||
assert xc.transform_unit_summaries(_SUM1, {}, [], {}, {}, field_updates={}) == _SUM1
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_recode_node_gets_kept_prices():
|
|
||||||
"""决策 171 补(主人定「三价要同步更新」):换码节点带上保留行三价——导出件里换来的
|
|
||||||
节点价格=保留行价格,不留新旧两价并存(实测:导入广联达显示 126)。"""
|
|
||||||
K, V15 = "17290080", "17290070@15"
|
|
||||||
txt = ('<Root><LabourMaterialsEquipmentsMachinesSummary Number="17290070@15" Name="管" Specification=""'
|
|
||||||
' Unit="m" Kind="2" TotalQuantity="1.0000" NoTaxPrice="126.96" TaxRate="0" TaxPrice="126.96"/></Root>')
|
|
||||||
out = xc.transform_unit_summaries(txt, {K: (58.88, 0, 58.88)}, [], {V15: K}, {})
|
|
||||||
assert 'Number="17290080"' in out
|
|
||||||
assert 'NoTaxPrice="58.88"' in out and 'TaxPrice="58.88"' in out
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 子级组成联动(机上人工 bug 回归钉:2026-10-22 主人实测报障)----------
|
|
||||||
|
|
||||||
def test_lme_res_child_follows_proj_summary():
|
|
||||||
"""机械台班的下一级组成显示以**项目级汇总**为准(决策 78 联动补齐到子项层):
|
|
||||||
项目级 机上人工 改名/改价后,子项展开显示新值——此前永远停在解析时旧值。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT, Number TEXT,
|
|
||||||
Name TEXT, Specification TEXT, Unit TEXT, Kind INT, Quantity REAL,
|
|
||||||
NoTaxPrice REAL, TaxPrice REAL)""")
|
|
||||||
sc.execute("INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Kind,"
|
|
||||||
" NoTaxPrice, TaxPrice) VALUES(1,'00010003','机上人工','','工日',3,248.4,248.4)")
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(1,'P1','00010003',2.0,1,'机上人工')")
|
|
||||||
# 项目级汇总:机上人工已被主人改名+改价(真实会话 73 实况:机上人工111)
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp)"
|
|
||||||
" VALUES(9,1,'00010003','机上人工111','','工日',3, 100, 260.0, 3.5, 269.1)")
|
|
||||||
r = srv._lme_res(sc, srv.TBL["session"], SID, "P1")
|
|
||||||
row = r["rows"][0]
|
|
||||||
assert row[0] == "00010003"
|
|
||||||
assert row[1] == "机上人工111" # 名称跟项目级(原 bug:显示旧名「机上人工」)
|
|
||||||
assert row[2] == "" and row[3] == "工日" and row[4] == 3
|
|
||||||
assert row[5] == 2.0 # 含量不动(数量是自己的)
|
|
||||||
assert row[6] == 260.0 # 汇总价非空 → 盖过 lmes 旧价 248.4
|
|
||||||
assert row[7] == 269.1
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""合并工料机 v2 防回归(决策 171,2026-10-22 主人定:视野=单位工程×n+项目级)。
|
|
||||||
|
|
||||||
钉死六件事:
|
|
||||||
①分组:项目级 + 各单位级(按码聚合,标注 units/uw_ids)同 名称|规格|单位 归组;
|
|
||||||
组内 ≥2 个不同编码才成组——D800(@3,不同名)不成组、同码无处不在也不成组。
|
|
||||||
②编码不可编辑:keep 里传 code 一律忽略,项目级行码原样不动(取代决策 75 编码可编辑)。
|
|
||||||
③项目级隐藏:x_merged_hide=1;被隐藏码进变体表。
|
|
||||||
④单位级变体:hide {uw, code, uw_ids} → 这些单位的该变体码物理换成组保留码;
|
|
||||||
**无跳过**(单位同时持有保留码与变体码 → 同码双行,镜像源文件多行现实,主人定「只显示保留码」)。
|
|
||||||
⑤定额消耗量:变体码**精确**换码;非变体(-0009 同基础码但不在组内)不误伤(防 D800 陷阱)。
|
|
||||||
⑥子级组成:变体码的子级被保留行子级整字段替换;recode_map 含全部变体(导出件换码用)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import json
|
|
||||||
import sys, os
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
K = "17290080" # 保留码(编码最短 → 默认勾选)
|
|
||||||
P = "17290070" # 项目级码(无后缀,源文件项目级形态)
|
|
||||||
V15 = "17290070@15" # 单位级变体(源文件撞码号)
|
|
||||||
V1 = "17290070@1"
|
|
||||||
D800 = "17290070@3" # 不同名(D800)——基础码相同也绝不能误伤
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
|
|
||||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL, express TEXT)""")
|
|
||||||
# 项目级:K 保留码 + P 项目码(同 名称|规格|单位、价不同 → 成组);D800 另名(不成组)
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?, '', 'm',2, ?, ?, 0, ?)""",
|
|
||||||
[(1, K, "II级钢筋混凝土管 D300", 11.286, 58.88, 58.88),
|
|
||||||
(2, P, "II级钢筋混凝土管 D300", 617.11, 126.96, 126.96),
|
|
||||||
(3, D800, "II级钢筋混凝土管 D800", 5.0, 90.0, 90.0)])
|
|
||||||
# 单位级:101/102 有 K、@15;102 另有 P;103 有 @1;101 有 D800
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?, '', 'm', 2, ?, ?, 0, ?)""",
|
|
||||||
[(11, 101, K, "II级钢筋混凝土管 D300", 50.0, 58.88, 58.88),
|
|
||||||
(12, 101, V15, "II级钢筋混凝土管 D300", 100.0, 58.88, 58.88),
|
|
||||||
(13, 101, D800, "II级钢筋混凝土管 D800", 5.0, 90.0, 90.0),
|
|
||||||
(14, 102, P, "II级钢筋混凝土管 D300", 200.0, 58.88, 58.88),
|
|
||||||
(15, 102, V15, "II级钢筋混凝土管 D300", 300.0, 58.88, 58.88),
|
|
||||||
(16, 102, K, "II级钢筋混凝土管 D300", 60.0, 58.88, 58.88),
|
|
||||||
(17, 103, V1, "II级钢筋混凝土管 D300", 7.0, 58.88, 58.88)])
|
|
||||||
# 子级组成:K 有子级(保留行),@15 也有子级(变体合并后应以保留行子级为准)
|
|
||||||
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq) VALUES(1,?,?,?,?)",
|
|
||||||
[(K, "00010003", 2.0, 1), (V15, "99990001", 63.0, 1)])
|
|
||||||
# 决策 244 口径自洽(2026-11-01 主人定「原版软件导不出子级有汇总无」):子级引用的码在两级汇总本来就有行
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?, '', 'm',2, ?, 1.0, 0, 1.0)""",
|
|
||||||
[(4, "00010003", "II级钢筋配套人工", 4.0),
|
|
||||||
(5, "99990001", "II级钢筋配套铁件", 63.0)])
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?, '', 'm', 2, ?, 1.0, 0, 1.0)""",
|
|
||||||
[(18, 101, "00010003", "II级钢筋配套人工", 4.0),
|
|
||||||
(19, 102, "99990001", "II级钢筋配套铁件", 63.0)])
|
|
||||||
# 定额消耗量:@15(变体,应换)、-0009(同基础码但非变体,不误伤)、K(本码,不动)
|
|
||||||
c.executemany("INSERT INTO s_bills(id, session_id, uw_id) VALUES(?,?,?)", [(1, 1, 101), (2, 1, 102)])
|
|
||||||
c.executemany("INSERT INTO s_norms(id, bill_id) VALUES(?,?)", [(10, 1), (11, 2)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
|
||||||
[(10, V15, 1.5, None), (11, "17290070-0009", 2.0, None), (10, K, 0.5, None)])
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _uw_codes(sc, uw):
|
|
||||||
return sorted(x["code"] for x in sc.execute(
|
|
||||||
"SELECT code FROM s_lme_uw WHERE session_id=? AND uw_id=?", (SID, uw)))
|
|
||||||
|
|
||||||
|
|
||||||
def test_groups_unify_levels():
|
|
||||||
"""①分组:D300 组 = 项目级 2 行 + 单位级按码聚合 4 行(K×2单位、@15×2单位、P×1、@1×1);
|
|
||||||
D800 单码不成组;uw 聚合行带 units/uw_ids。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
d = srv._lme_merge_groups(sc, SID)
|
|
||||||
g = [x for x in d["groups"] if x["name"] == "II级钢筋混凝土管 D300"]
|
|
||||||
assert len(g) == 1
|
|
||||||
g = g[0]
|
|
||||||
proj = [r for r in g["rows"] if r["lvl"] == "proj"]
|
|
||||||
uws = [r for r in g["rows"] if r["lvl"] == "uw"]
|
|
||||||
assert proj == [] # 决策 186 v3:弹框并集视野,项目级不进组
|
|
||||||
assert {r["code"] for r in uws} == {K, P, V15, V1}
|
|
||||||
krow = [r for r in uws if r["code"] == K][0]
|
|
||||||
assert krow["units"] == 2 and sorted(krow["uw_ids"]) == [101, 102]
|
|
||||||
assert krow["qty"] == 110.0 # 50 + 60
|
|
||||||
# 2026-11-04 规则:除数量外全字段一致才可合并——V15 两个单位行同价 → 聚成一行 units=2
|
|
||||||
v15rows = [r for r in uws if r["code"] == V15]
|
|
||||||
assert len(v15rows) == 1 and v15rows[0]["units"] == 2
|
|
||||||
assert not any(x["name"] == "II级钢筋混凝土管 D800" for x in d["groups"]) # 单码不成组
|
|
||||||
assert g["rows"][0]["def"] is True and g["rows"][0]["code"] == P # 默认勾编码最短(P 17290070 < K 17290080;决策 186 并集视野)
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_v2_unify_and_no_code_edit():
|
|
||||||
"""②③④⑤⑥⑦:编码不收不改(传假码也原样);项目级隐藏;单位变体(含双码单位)全部换保留码
|
|
||||||
且三价统一为保留行三价;D800 与 -0009 不误伤;定额变体精确换码;子级替换 + recode_map 全量。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"id": 1, "ntp": 58.88, "taxrate": 0, "taxp": 58.88},
|
|
||||||
"hide": [{"id": 2},
|
|
||||||
{"uw": 1, "code": V15, "uw_ids": [101, 102]},
|
|
||||||
{"uw": 1, "code": V1, "uw_ids": [103]},
|
|
||||||
{"uw": 1, "code": P, "uw_ids": [102]}]}]})
|
|
||||||
assert r["ok"] is True
|
|
||||||
# ② 编码不可编辑:传了 WRONG-EDITED-CODE 也原样
|
|
||||||
assert sc.execute("SELECT code, ntp FROM s_lme_proj WHERE id=1").fetchone()[0:2] == (K, 58.88)
|
|
||||||
# ③ 决策 244 纯数据流:P 零引用被剪;子级码 00010003 本就有汇总行(id=4),注入不触发
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_proj WHERE id=2").fetchone()[0] == 0
|
|
||||||
# ④ 全单位只显示保留码:无跳过——单位同时持有保留码与变体码时为同码双行(镜像源文件多行现实)
|
|
||||||
assert _uw_codes(sc, 101) == sorted([K, K, '00010003']) # 决策 186 定稿:骨架组映射源(00010003)单位级缺失→新增;D800 未引用被剪(244)
|
|
||||||
assert sorted(_uw_codes(sc, 102)) == sorted([K, K, K, '00010003']) # 决策 186 定稿:映射源新增
|
|
||||||
assert sorted(_uw_codes(sc, 103)) == sorted([K, '00010003']) # 决策 186 定稿:映射源新增
|
|
||||||
# ⑦ 三价同步(主人定「三价要同步更新」):换码的变体行三价=保留行三价,不留新旧两价并存
|
|
||||||
# uw101 K×2 + uw102 K×3 + uw103 K×1 = 6 行,全部 58.88/0/58.88
|
|
||||||
ntps = sorted(x["ntp"] for x in sc.execute(
|
|
||||||
"SELECT ntp FROM s_lme_uw WHERE session_id=? AND code=?", (SID, K)))
|
|
||||||
assert ntps == [58.88] * 6
|
|
||||||
assert all(x["taxp"] == 58.88 and x["taxrate"] == 0 for x in sc.execute(
|
|
||||||
"SELECT taxrate, taxp FROM s_lme_uw WHERE session_id=? AND code=?", (SID, K)))
|
|
||||||
# ⑤ 定额消耗量:变体精确换码;-0009(非变体)不误伤
|
|
||||||
nr = {x["res_code"]: x["qty"] for x in sc.execute("SELECT res_code, qty FROM s_norm_res")}
|
|
||||||
assert set(nr) == {K, "17290070-0009"}
|
|
||||||
assert nr["17290070-0009"] == 2.0
|
|
||||||
# ⑥ 子级替换 + recode_map
|
|
||||||
kids = sorted(x["res_code"] for x in sc.execute(
|
|
||||||
"SELECT res_code FROM s_lme_res WHERE session_id=? AND p_code=?", (SID, V15)))
|
|
||||||
assert kids == ["00010003"] # 变体子级已被保留行子级整字段替换
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=? AND p_code=?", (SID, K)).fetchone()[0] == 1
|
|
||||||
rm = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()[0])
|
|
||||||
assert rm == {V15: K, V1: K, P: K}
|
|
||||||
# D800(不同名不成组):未引用 → 决策 244 剪枝删除(未被合并=映射无它,非误伤)
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_proj WHERE id=3").fetchone()[0] == 0
|
|
||||||
assert D800 not in json.loads(sc.execute(
|
|
||||||
"SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()[0])
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_keep_uw_only_no_proj():
|
|
||||||
"""勾单位级聚合行:全组替换成聚合码/展示三价——项目级组内旧行全部隐藏,
|
|
||||||
**确保项目级有一行 保留码/替换三价**(没有则新增,数量=被隐藏项目行数量合计);
|
|
||||||
全部单位变体换成聚合码、三价统一。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
# 预置一条**早已隐藏**的同码项目行(实测报障:v3 曾对它走 INSERT 撞唯一索引)
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp, x_merged_hide)"
|
|
||||||
" VALUES(9,1,'17290070@15','II级钢筋混凝土管 D300','', 'm',2, 9.9, 120.0, 0, 126.0, 1)")
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": V15, "uw_ids": [101, 102], "ntp": 126.96, "taxrate": 0, "taxp": 126.96,
|
|
||||||
"name": "II级钢筋混凝土管 D300", "spec": "", "unit": "m", "kind": 2,
|
|
||||||
"qty": 628.396}, # sel.qty 由前端传(被隐藏项目行合计);本用例直接给定
|
|
||||||
"hide": [{"id": 1}, {"id": 2},
|
|
||||||
{"uw": 1, "code": K, "uw_ids": [101, 102]},
|
|
||||||
{"uw": 1, "code": P, "uw_ids": [102]},
|
|
||||||
{"uw": 1, "code": V1, "uw_ids": [103]}]}]})
|
|
||||||
assert r["ok"] is True
|
|
||||||
assert _uw_codes(sc, 101) == sorted([V15, V15, '99990001']) # 决策 186 定稿:映射源新增;D800 未引用被剪(244)
|
|
||||||
assert sorted(_uw_codes(sc, 102)) == sorted([V15, V15, V15, '99990001']) # 决策 186 定稿:映射源新增
|
|
||||||
assert sorted(_uw_codes(sc, 103)) == sorted([V15, '99990001']) # 决策 186 定稿:映射源新增
|
|
||||||
uw10 = sorted(x[0] for x in sc.execute("SELECT code FROM s_lme_uw WHERE session_id=? AND uw_id=101", (SID,)))
|
|
||||||
assert '99990001' in uw10 # 决策 186 定稿:单位级映射源缺失→新增
|
|
||||||
# 三价统一为替换三价(M=126.96):全部 V15 行 126.96
|
|
||||||
assert all(x["ntp"] == 126.96 for x in sc.execute(
|
|
||||||
"SELECT ntp FROM s_lme_uw WHERE session_id=? AND code=?", (SID, V15)))
|
|
||||||
# 项目级确保有一行 保留码/替换三价(新增行,数量=被隐藏项目行合计 628.396);旧行隐藏
|
|
||||||
prows = [tuple(x) for x in sc.execute(
|
|
||||||
"SELECT code, qty, ntp, COALESCE(x_merged_hide,0) FROM s_lme_proj WHERE session_id=? ORDER BY id", (SID,))]
|
|
||||||
# 决策 186 定稿「块=母行+Element+映射源」:99990001(63.0)是骨架组映射源——项目级原有行在,
|
|
||||||
# 不重复插入;单位级(uw10)原无 → 新增一行(值取项目级现值;价格空=没算留空)
|
|
||||||
# 决策 244 纯数据流:K/P/D800 零引用剪;勾 V15 后 K 的子级被 99990001 整组替换 →
|
|
||||||
# 00010003 反向零引用也剪;只留被引用的 V15 与 99990001
|
|
||||||
assert prows == [('99990001', 63.0, 1.0, 0), (V15, 628.396, 126.96, 0)]
|
|
||||||
rm = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()[0])
|
|
||||||
assert rm == {K: V15, P: V15, V1: V15}
|
|
||||||
@@ -1,238 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 241(2026-10-30 主人定「分两次合并」):子级视野合并 + 映射地全贯通 防回归。
|
|
||||||
|
|
||||||
主人口径:「工料机合并一次,子工料机合并一次,基本干净。重点=映射源及映射地方的修改。」
|
|
||||||
钉死七件事:
|
|
||||||
①子级视野分组(view=sub):被台班/配合比子级引用的码按名规单成组;一级码不进子级视野;
|
|
||||||
单码(机上人工)不成组。
|
|
||||||
②两步合并(一级台班→子级柴油)后**全库无旧码残留**:s_lme_uw / s_lme_res(台班子级引用)/
|
|
||||||
s_norm_res(定额消耗量)三处旧码计数=0;含量一个字不动。
|
|
||||||
③映射源唯一:recode_map={A2:A1, D2:D1}——每个旧码一个去向,无链无环。
|
|
||||||
④recode_children 登记数组同步(映射源加固):先合台班登记子级含柴油@1,再合柴油,
|
|
||||||
数组里的旧码引用同步换(不同步则导出重建/重放重建插回旧码=多次合并不干净根源)。
|
|
||||||
⑤后缀顺延:CY002-002 → CY001-002(基码换、后缀保,拍板「后缀引用同步顺延」)。
|
|
||||||
⑥导出映射地:单位件 Summary 块内 Element(台班子级行)旧码→保留码;汇总节点换码;
|
|
||||||
消耗量行换码(_recode_norm_lme_rows 全 Element 口径)。
|
|
||||||
⑦重放映射地:recode_map 重放贯通 s_lme_res 子级引用(重导后源文件原码不残留)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import json
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
# 一级台班:A1=保留(子级柴油=CY002),A2=变体(子级柴油=CY001),B1=旁观台班(子级柴油=CY002)
|
|
||||||
A1, A2, B1 = "TB1001", "TB1002", "TB2001"
|
|
||||||
# 子级码:柴油两码(同名规单可合并,变体=源文件撞码 @n 形态),人工一码(不成组)
|
|
||||||
CY1, CY2, RG1 = "CY001", "CY002@1", "RG001"
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
|
|
||||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL, express TEXT)""")
|
|
||||||
# 一级台班(挖掘机两码=可合并组;载重车单码不成组)
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?, '', '台班',2, ?, ?, 0, ?)""",
|
|
||||||
[(1, A1, "挖掘机 液压 履带", 10.0, 500.0, 500.0),
|
|
||||||
(2, A2, "挖掘机 液压 履带", 8.0, 500.0, 500.0),
|
|
||||||
(3, B1, "载重汽车", 20.0, 300.0, 300.0)])
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?, '', '台班', 2, ?, ?, 0, ?)""",
|
|
||||||
[(11, 101, A1, "挖掘机 液压 履带", 10.0, 500.0, 500.0),
|
|
||||||
(12, 102, A2, "挖掘机 液压 履带", 8.0, 500.0, 500.0),
|
|
||||||
(13, 101, B1, "载重汽车", 20.0, 300.0, 300.0)])
|
|
||||||
# 台班子级:A1(保留行)子级柴油=CY002;A2 子级柴油=CY001;B1 子级柴油=CY002
|
|
||||||
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq) VALUES(1,?,?,?,?)",
|
|
||||||
[(A1, CY2, 33.8, 1), (A1, RG1, 1.0, 2),
|
|
||||||
(A2, CY1, 40.5, 1), (A2, RG1, 1.0, 2),
|
|
||||||
(B1, CY2, 30.0, 1), (B1, RG1, 1.0, 2)])
|
|
||||||
# 子级码的汇总行(柴油两码同名规单=子级视野可合并组;人工一码)
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?, '', 'kg', 0, ?, ?, 0, ?)""",
|
|
||||||
[(21, 101, CY1, "柴油 0#", 100.0, 8.5, 8.5),
|
|
||||||
(22, 102, CY2, "柴油 0#", 63.8, 8.5, 8.5),
|
|
||||||
(23, 101, RG1, "机上人工", 2.0, 120.0, 120.0)])
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?, '', 'kg',0, ?, ?, 0, ?)""",
|
|
||||||
[(4, CY1, "柴油 0#", 100.0, 8.5, 8.5),
|
|
||||||
(5, CY2, "柴油 0#", 63.8, 8.5, 8.5),
|
|
||||||
(6, RG1, "机上人工", 2.0, 120.0, 120.0)])
|
|
||||||
# 定额消耗量:台班两码各一;柴油 CY002 直接耗一行 + 带后缀换算行 CY002-002
|
|
||||||
c.executemany("INSERT INTO s_bills(id, session_id, uw_id) VALUES(?,?,?)", [(1, 1, 101), (2, 1, 102)])
|
|
||||||
c.executemany("INSERT INTO s_norms(id, bill_id) VALUES(?,?)", [(10, 1), (11, 2)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
|
||||||
[(10, A1, 0.5, None), (11, A2, 0.8, None),
|
|
||||||
(11, CY2, 2.0, None), (11, CY2 + "-002", 1.0, None)]) # CY2-002=@n基码+后缀(拍板顺延场景)
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _set(sc, k):
|
|
||||||
r = sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k=?", (k,)).fetchone()
|
|
||||||
return json.loads(r[0]) if r else None
|
|
||||||
|
|
||||||
|
|
||||||
def test_sub_view_groups():
|
|
||||||
"""①子级视野:柴油组 2 码成组;人工一码不成组;一级台班不进子级视野;一级视野反之。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
d = srv._lme_merge_groups(sc, SID, sub=True)
|
|
||||||
assert d["view"] == "sub"
|
|
||||||
names = {g["name"]: [r["code"] for r in g["rows"]] for g in d["groups"]}
|
|
||||||
assert sorted(names["柴油 0#"]) == [CY1, CY2] # 柴油两码成组
|
|
||||||
assert "机上人工" not in names # 单码不成组
|
|
||||||
assert "挖掘机 液压 履带" not in names and "载重汽车" not in names # 一级码不在子级视野
|
|
||||||
d1 = srv._lme_merge_groups(sc, SID)
|
|
||||||
assert d1["view"] == "l1"
|
|
||||||
names1 = {g["name"]: [r["code"] for r in g["rows"]] for g in d1["groups"]}
|
|
||||||
assert sorted(names1["挖掘机 液压 履带"]) == [A1, A2] # 一级视野=台班组
|
|
||||||
assert "柴油 0#" not in names1 # 子级码不进一级视野(决策 184 现状)
|
|
||||||
|
|
||||||
|
|
||||||
def test_two_step_merge_clean():
|
|
||||||
"""②③④⑤:一级合并一次 + 子级合并一次 = 全库干净(映射地全清单)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
# ── 第一步:一级合并 挖掘机 A2 → A1(勾项目级行 A1)──
|
|
||||||
r1 = srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"id": 1, "ntp": 500.0, "taxrate": 0, "taxp": 500.0},
|
|
||||||
"hide": [{"id": 2}, {"uw": 1, "code": A2, "uw_ids": [102]}]}]})
|
|
||||||
assert r1["ok"] is True
|
|
||||||
rm = _set(sc, "recode_map")
|
|
||||||
assert rm == {A2: A1}
|
|
||||||
# A2 子级被保留行(A1)子级整组替换:柴油=CY002 33.8(原 CY1 40.5)
|
|
||||||
kids_a2 = {x["res_code"]: x["qty"] for x in sc.execute(
|
|
||||||
"SELECT res_code, qty FROM s_lme_res WHERE session_id=1 AND p_code=?", (A2,))}
|
|
||||||
assert kids_a2 == {CY2: 33.8, RG1: 1.0}
|
|
||||||
assert _set(sc, "recode_children:" + A2) == [[CY2, 33.8], [RG1, 1.0]]
|
|
||||||
# B1/A1 的子级引用未受一级合并影响
|
|
||||||
assert {x["res_code"] for x in sc.execute(
|
|
||||||
"SELECT res_code FROM s_lme_res WHERE session_id=1 AND p_code=?", (B1,))} == {CY2, RG1}
|
|
||||||
|
|
||||||
# ── 第二步:子级合并 柴油 CY2 → CY1(勾单位级聚合行 CY1)──
|
|
||||||
r2 = srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": CY1, "uw_ids": [101], "ntp": 8.5, "taxrate": 0, "taxp": 8.5,
|
|
||||||
"name": "柴油 0#", "spec": "", "unit": "kg", "kind": 0, "qty": 0},
|
|
||||||
"hide": [{"id": 5}, {"uw": 1, "code": CY2, "uw_ids": [102]}]}]})
|
|
||||||
assert r2["ok"] is True
|
|
||||||
|
|
||||||
# ③ 映射源唯一:每旧码一个去向(决策 241「映射源只有一条」)
|
|
||||||
assert _set(sc, "recode_map") == {A2: A1, CY2: CY1}
|
|
||||||
# ④ 癠记数组同步:A2 的子级替换数据里 CY2 → CY1(含量不动)
|
|
||||||
assert _set(sc, "recode_children:" + A2) == [[CY1, 33.8], [RG1, 1.0]]
|
|
||||||
|
|
||||||
# ② 映射地①:台班/配合比子级引用(s_lme_res.res_code)——三个台班的柴油全→CY1,含量原样
|
|
||||||
for p, q_diesel in ((A1, 33.8), (A2, 33.8), (B1, 30.0)):
|
|
||||||
kids = {x["res_code"]: x["qty"] for x in sc.execute(
|
|
||||||
"SELECT res_code, qty FROM s_lme_res WHERE session_id=1 AND p_code=?", (p,))}
|
|
||||||
assert kids.get(CY1) == q_diesel, (p, kids)
|
|
||||||
assert CY2 not in kids
|
|
||||||
|
|
||||||
# 映射地②:定额消耗量——CY2→CY1 精确换;CY2-002→CY1-002 后缀顺延;台班行 A2→A1;含量不动
|
|
||||||
nr = {(x["norm_id"], x["res_code"]): x["qty"] for x in sc.execute(
|
|
||||||
"SELECT norm_id, res_code, qty FROM s_norm_res")}
|
|
||||||
assert nr[(10, A1)] == 0.5 and nr[(11, A1)] == 0.8 # 第一步换码、含量未动
|
|
||||||
assert nr[(11, CY1)] == 2.0 and nr[(11, CY1 + "-002")] == 1.0 # ⑤ 顺延
|
|
||||||
assert not any(k[1] == CY2 or k[1].startswith(CY2 + "-") for k in nr)
|
|
||||||
|
|
||||||
# 映射地③④:单位工程汇总换码 + 项目级 CY2 零引用被剪(决策 244)、保留行三价统一
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw WHERE session_id=1 AND code=?", (CY2,)).fetchone()[0] == 0
|
|
||||||
assert all(x["ntp"] == 8.5 for x in sc.execute(
|
|
||||||
"SELECT ntp FROM s_lme_uw WHERE session_id=1 AND code=?", (CY1,)))
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_proj WHERE session_id=1 AND id=5").fetchone()[0] == 0
|
|
||||||
|
|
||||||
# ② 全库旧码残留=0(两步合并后基本干净)
|
|
||||||
for tbl, col in (("s_lme_uw", "code"), ("s_lme_res", "res_code"), ("s_norm_res", "res_code")):
|
|
||||||
n = sc.execute("SELECT COUNT(*) FROM %s WHERE %s=?" % (tbl, col), (CY2,)).fetchone()[0]
|
|
||||||
assert n == 0, tbl
|
|
||||||
n2 = sc.execute("SELECT COUNT(*) FROM %s WHERE %s=?" % (tbl, col), (A2,)).fetchone()[0]
|
|
||||||
assert n2 == 0, tbl
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_in_block_element_recode():
|
|
||||||
"""⑥导出映射地:Summary 块内 Element(台班子级行)旧码→保留码;汇总节点换码带保留值。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"id": 1, "ntp": 500.0, "taxrate": 0, "taxp": 500.0},
|
|
||||||
"hide": [{"id": 2}, {"uw": 1, "code": A2, "uw_ids": [102]}]}]})
|
|
||||||
srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": CY1, "uw_ids": [101], "ntp": 8.5, "taxrate": 0, "taxp": 8.5,
|
|
||||||
"name": "柴油 0#", "spec": "", "unit": "kg", "kind": 0, "qty": 0},
|
|
||||||
"hide": [{"id": 5}, {"uw": 1, "code": CY2, "uw_ids": [102]}]}]})
|
|
||||||
rm = _set(sc, "recode_map")
|
|
||||||
ch = {k.split(":", 1)[1]: v for k, v in ((r["k"], json.loads(r["v"])) for r in sc.execute(
|
|
||||||
"SELECT k, v FROM s_settings WHERE scope='session:1' AND k LIKE 'recode_children:%'"))}
|
|
||||||
S = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
E = "LabourMaterialsEquipmentsMachinesElement"
|
|
||||||
txt = ('<r>'
|
|
||||||
f'<{S} Number="TB1001" Name="挖掘机" Unit="台班" Quantity="10.0000" NoTaxPrice="500.00" TaxPrice="500.00">'
|
|
||||||
f'<{E} Number="{CY2}" Quantity="33.8000" Remark=""/>'
|
|
||||||
f'<{E} Number="RG001" Quantity="1.0000" Remark=""/>'
|
|
||||||
f'</{S}>'
|
|
||||||
f'<{S} Number="{CY2}" Name="柴油" Unit="kg" Quantity="63.8000" NoTaxPrice="8.30"/>'
|
|
||||||
f'<{E} Number="{CY2}" Quantity="2.0000" Remark=""/>'
|
|
||||||
'</r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {CY1: (8.5, 0.0, 8.5)}, None, recode_map=rm, recode_children=ch)
|
|
||||||
out = xcos._recode_norm_lme_rows(out, rm)
|
|
||||||
assert 'Number="CY002"' not in out # 汇总节点+块内子级+块外行:旧码一处不剩
|
|
||||||
assert out.count('Number="CY001"') == 3
|
|
||||||
assert 'NoTaxPrice="8.5"' in out # 汇总节点带保留行价(不是旧价 8.30)
|
|
||||||
assert 'Quantity="33.8000"' in out and 'Quantity="2.0000"' in out # 含量不动
|
|
||||||
|
|
||||||
|
|
||||||
def test_replay_recode_covers_lme_res():
|
|
||||||
"""⑦重放映射地:rmap 重放贯通 s_lme_res 子级引用(重导后源文件原码不残留)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"id": 1, "ntp": 500.0, "taxrate": 0, "taxp": 500.0},
|
|
||||||
"hide": [{"id": 2}, {"uw": 1, "code": A2, "uw_ids": [102]}]}]})
|
|
||||||
srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": CY1, "uw_ids": [101], "ntp": 8.5, "taxrate": 0, "taxp": 8.5,
|
|
||||||
"name": "柴油 0#", "spec": "", "unit": "kg", "kind": 0, "qty": 0},
|
|
||||||
"hide": [{"id": 5}, {"uw": 1, "code": CY2, "uw_ids": [102]}]}]})
|
|
||||||
rmap = _set(sc, "recode_map")
|
|
||||||
# 模拟重导:库回到源文件原码(B1 子级引用 CY002、定额行 CY002/CY002-002),按 rmap 重放
|
|
||||||
sc.execute("UPDATE s_lme_res SET res_code=? WHERE session_id=1 AND res_code=? AND p_code=?", (CY2, CY1, B1))
|
|
||||||
sc.execute("UPDATE s_norm_res SET res_code=? WHERE res_code=?", (CY2, CY1))
|
|
||||||
sc.execute("UPDATE s_norm_res SET res_code=? WHERE res_code=?", (CY2 + "-002", CY1 + "-002"))
|
|
||||||
for old, new in rmap.items():
|
|
||||||
sc.execute("UPDATE s_lme_uw SET code=? WHERE session_id=1 AND code=?", (old, new)) if False else None
|
|
||||||
# 与 _merge_state_replay 同款四条(uw/norm_res 精确 + lme_res 精确/顺延 + norm_res 顺延)
|
|
||||||
sc.execute("UPDATE s_lme_uw SET code=? WHERE session_id=1 AND code=?", (new, old))
|
|
||||||
sc.execute("UPDATE s_norm_res SET res_code=? WHERE res_code=?", (new, old))
|
|
||||||
sc.execute("UPDATE s_lme_res SET res_code=? WHERE session_id=1 AND res_code=?", (new, old))
|
|
||||||
sc.execute("""UPDATE s_lme_res SET res_code=? || substr(res_code, ?) WHERE session_id=1
|
|
||||||
AND res_code IS NOT NULL AND substr(res_code,1,length(?))=?
|
|
||||||
AND substr(res_code,length(?)+1,1)='-'""",
|
|
||||||
(new, len(old) + 1, old, old, old))
|
|
||||||
sc.execute("""UPDATE s_norm_res SET res_code=? || substr(res_code, ?) WHERE res_code IS NOT NULL
|
|
||||||
AND substr(res_code,1,length(?))=? AND substr(res_code,length(?)+1,1)='-'""",
|
|
||||||
(new, len(old) + 1, old, old, old))
|
|
||||||
for tbl, col in (("s_lme_uw", "code"), ("s_lme_res", "res_code"), ("s_norm_res", "res_code")):
|
|
||||||
n = sc.execute("SELECT COUNT(*) FROM %s WHERE %s=?" % (tbl, col), (CY2,)).fetchone()[0]
|
|
||||||
assert n == 0, tbl
|
|
||||||
kids = {x["res_code"] for x in sc.execute(
|
|
||||||
"SELECT res_code FROM s_lme_res WHERE session_id=1 AND p_code=?", (B1,))}
|
|
||||||
assert CY1 in kids and CY2 not in kids
|
|
||||||
@@ -1,463 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""项目级工料机汇总 行级改价防回归(2026-10-16 主人口径)。
|
|
||||||
|
|
||||||
钉死四件事:
|
|
||||||
①三价联动恒满足 除税编制价 × (1 + 税率/100) = 含税编制价(金额四舍五入 2 位,税率空按 0):
|
|
||||||
改除税→按税率算含税;改税率→按除税算含税;改含税→反解除税。
|
|
||||||
②落库位置 = s_lme_proj 那一行(code 不动),响应回带服务端复核后的三值。
|
|
||||||
③按编码同步**存在该编码**的 s_lme_uw(全单位覆盖,决策 73/75 口径),别的编码不动;
|
|
||||||
编码登记进 s_settings 的 merged_codes(导出侧 price_updates 唯一来源)。
|
|
||||||
④行形状:_raw_proj(_raw_uw) 工料机卡 9 列、税率在下标 7(ntp 之后、taxp 之前),
|
|
||||||
ids 与行一一并行;隐藏行(x_merged_hide=1)不出现在 ids 里且拒改。
|
|
||||||
另带一例 api_lme_merge 回归:_merged_codes_add 抽取后合并照旧登记编码。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import json
|
|
||||||
import sys, os
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess():
|
|
||||||
"""内存会话库:项目级汇总 3 行(正常材料 / 台班带子级 / 隐藏行)+ 单位级 3 行(C1 两单位 + C2)。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
# 2026-10-22 合并贯通:api_lme_merge 会 UPDATE s_norm_res(经 s_norms/s_bills 圈会话),
|
|
||||||
# 夹具补空表防 no such table(数据面见 test_lme_field._mk_sess(with_norms=True))。
|
|
||||||
# IF NOT EXISTS:部分用例自建 s_bills(uw agg 回退),不能冲突。
|
|
||||||
c.execute("CREATE TABLE IF NOT EXISTS s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
|
|
||||||
c.execute("CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
|
|
||||||
c.execute("""CREATE TABLE IF NOT EXISTS s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL, express TEXT)""")
|
|
||||||
# id=1 正常材料(税率 3.5);id=2 台班(lme_res 有 p_code → 带子级组成);id=3 已隐藏
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp, x_merged_hide) VALUES(?,1,?,?, '', 'kg',2, 100, ?, ?, ?, ?)""",
|
|
||||||
[(1, "C1", "钢筋", 99.99, 3.5, 103.49, 0),
|
|
||||||
(2, "P1", "挖掘机台班", 900.0, 3.5, 931.5, 0),
|
|
||||||
(3, "C9", "已隐藏", 1.0, 0.0, 1.0, 1)])
|
|
||||||
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq) VALUES(1,'P1',?,?,?)",
|
|
||||||
[("00010003", 2.0, 1), ("99450680", 63.0, 2)])
|
|
||||||
# 单位级:C1 在两个单位工程各有行;C2 一行(不该被 C1 的改价波及)
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,'C1','钢筋','kg',2, 10, 99.99, 3.5, 103.49)""",
|
|
||||||
[(11, 101), (12, 102)])
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(13,1,103,'C2','水泥','kg',2, 10, 200.0, 3.5, 207.0)""")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _merged_codes(sc):
|
|
||||||
r = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k=?",
|
|
||||||
("session:1", "merged_codes")).fetchone()
|
|
||||||
return set(json.loads(r[0])) if r else set()
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- ① 三价联动 ----------
|
|
||||||
|
|
||||||
def test_linkage_edit_ntp_uses_current_rate():
|
|
||||||
"""改除税 → 按当前税率算含税:99.99 × (1+3.5/100) = 103.49(主人给的例)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
|
|
||||||
assert r["ok"] is True
|
|
||||||
assert round(r["taxp"], 2) == 103.49 and r["taxrate"] == 3.5
|
|
||||||
row = sc.execute("SELECT ntp, taxrate, taxp, code FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (row["ntp"], row["taxrate"], row["taxp"]) == (99.99, 3.5, 103.49)
|
|
||||||
assert row["code"] == "C1" # code 永不被改价动到
|
|
||||||
|
|
||||||
|
|
||||||
def test_linkage_edit_taxrate_recalcs_taxp():
|
|
||||||
"""改税率 → 按当前除税算含税:100 × (1+13/100) = 113.00。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("UPDATE s_lme_proj SET ntp=100 WHERE id=1")
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxrate": 13})
|
|
||||||
assert r["ok"] is True and r["taxp"] == 113.0
|
|
||||||
row = sc.execute("SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (row["ntp"], row["taxrate"], row["taxp"]) == (100.0, 13.0, 113.0)
|
|
||||||
|
|
||||||
|
|
||||||
def test_linkage_edit_taxp_backs_out_ntp():
|
|
||||||
"""改含税 → 反解除税:103.49 ÷ (1+3.5/100) → 99.99。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxp": 103.49})
|
|
||||||
assert r["ok"] is True and r["ntp"] == 99.99
|
|
||||||
row = sc.execute("SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (round(row["ntp"], 2), row["taxp"]) == (99.99, 103.49)
|
|
||||||
|
|
||||||
|
|
||||||
def test_linkage_empty_rate_treated_as_zero():
|
|
||||||
"""税率空按 0:清空税率后 100×(1+0)=100;老行税率 NULL 时改除税 → 含税=除税。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 100, "taxrate": None})
|
|
||||||
assert r["ok"] is True and r["taxp"] == 100.0 and r["taxrate"] is None
|
|
||||||
sc.execute("UPDATE s_lme_proj SET ntp=NULL, taxrate=NULL, taxp=NULL WHERE id=1")
|
|
||||||
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxrate": ""}) # 税率清空=0
|
|
||||||
assert r2["ok"] is True and r2["taxp"] == 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_linkage_rounding_half_up():
|
|
||||||
"""金额四舍五入 2 位(十进制半升,非银行家舍入)。"""
|
|
||||||
assert srv._r2(103.48965) == 103.49
|
|
||||||
assert srv._r2(2.675) == 2.68 # round() 会给 2.67
|
|
||||||
assert srv._r2(1.005) == 1.01
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- ② 落库位置 / ③ 单位级同步 / merged_codes ----------
|
|
||||||
|
|
||||||
def test_sync_updates_only_matching_code_rows():
|
|
||||||
"""按编码同步存在该编码的单位级汇总(全单位覆盖);别的编码不动。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
|
|
||||||
assert r["ok"] is True and r["synced"] == 2 # C1 的两个单位工程行
|
|
||||||
vals = {x["id"]: (x["ntp"], x["taxp"]) for x in
|
|
||||||
sc.execute("SELECT id, ntp, taxp FROM s_lme_uw WHERE code='C1'")}
|
|
||||||
assert vals == {11: (99.99, 103.49), 12: (99.99, 103.49)}
|
|
||||||
c2 = sc.execute("SELECT ntp, taxp FROM s_lme_uw WHERE code='C2'").fetchone()
|
|
||||||
assert (c2["ntp"], c2["taxp"]) == (200.0, 207.0) # 撞不上编码的不跟
|
|
||||||
|
|
||||||
|
|
||||||
def test_edit_registers_code_into_merged_codes():
|
|
||||||
"""改价必须登记 merged_codes —— 导出侧 price_updates 的唯一来源(api_server 2994-2999)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
assert _merged_codes(sc) == set()
|
|
||||||
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
|
|
||||||
assert _merged_codes(sc) == {"C1"}
|
|
||||||
# 决策 188 收严(主人定「有子数据的单价不可编辑,只能通过子数据修改」):P1 带子级→三价全拒
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "taxrate": 9})
|
|
||||||
assert r["ok"] is False and "不可编辑" in r["msg"]
|
|
||||||
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "ntp": 88.0})
|
|
||||||
assert r2["ok"] is False and "不可编辑" in r2["msg"]
|
|
||||||
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 90.0}) # C1 无子级,可改→登记
|
|
||||||
assert _merged_codes(sc) == {"C1"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_sub_composition_rows_are_editable():
|
|
||||||
"""带子级组成的台班可改(2026-10-16 主人定,与合并弹框的整行过滤不同);_raw_proj 带出 sub 集。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
# 决策 188 收严:带子级行三价**全部拒改**(只能通过子数据修改);sub 集照常带出
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "taxrate": 9})
|
|
||||||
assert r["ok"] is False and "不可编辑" in r["msg"]
|
|
||||||
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "ntp": 88.0})
|
|
||||||
assert r2["ok"] is False and "不可编辑" in r2["msg"]
|
|
||||||
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
|
|
||||||
assert d["sub"] == ["P1"]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 拒改 / 容错 ----------
|
|
||||||
|
|
||||||
def test_rejects_hidden_and_missing_rows():
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 3, "ntp": 5}) # 隐藏行
|
|
||||||
assert r["ok"] is False and "隐藏" in r["msg"]
|
|
||||||
assert sc.execute("SELECT ntp FROM s_lme_proj WHERE id=3").fetchone()[0] == 1.0
|
|
||||||
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 999, "ntp": 5}) # 不存在
|
|
||||||
assert r2["ok"] is False and "行不存在" in r2["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_rejects_garbage_number():
|
|
||||||
"""垃圾数字报错拒写(防手滑把价格清成 NULL),而不是当清空处理。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": "abc"})
|
|
||||||
row = sc.execute("SELECT ntp, taxp FROM s_lme_proj WHERE id=1").fetchone()
|
|
||||||
assert (row["ntp"], row["taxp"]) == (99.99, 103.49) # 库纹丝没动
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_price_fields_is_noop():
|
|
||||||
sc = _mk_sess()
|
|
||||||
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1})
|
|
||||||
assert r["ok"] is False and "没有要改的价字段" in r["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 行形状(前后端同改的铁律处)----------
|
|
||||||
|
|
||||||
def test_raw_proj_rows_are_eleven_wide_id_first():
|
|
||||||
"""决策 147(2026-10-21):项目级卡与「项目工料机」同形 —— 行 11 列 id 在首位、备注位 10;
|
|
||||||
税率在下标 7、含税在下标 8;不再 rows/ids 分离;隐藏行被过滤。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
|
|
||||||
assert len(d["rows"]) == 2 # 隐藏行被过滤
|
|
||||||
assert all(len(r) == 11 for r in d["rows"])
|
|
||||||
r0 = d["rows"][0]
|
|
||||||
assert r0[0] == 1 and r0[1] == "C1" and r0[6] == 99.99 and r0[7] == 3.5 and r0[8] == 103.49
|
|
||||||
assert "ids" not in d
|
|
||||||
assert d["sub"] == ["P1"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_uw_rows_are_nine_wide_with_taxrate_at_7():
|
|
||||||
"""单位级卡同款 9 列(保持只读,不给 ids)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
Number TEXT, Name TEXT, Specialty TEXT, Total REAL)""")
|
|
||||||
sc.execute("INSERT INTO s_unit_works(id, session_id, Number, Name) VALUES(101,1,'1','土建')")
|
|
||||||
d = srv._raw_uw(sc, srv.TBL["session"], 101, "lme")
|
|
||||||
assert d["src"] == "summary"
|
|
||||||
assert all(len(r) == 9 for r in d["rows"])
|
|
||||||
assert d["rows"][0][7] == 3.5 and d["rows"][0][8] == 103.49
|
|
||||||
assert "ids" not in d
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 老库回退支的行形状(评审发现:税率曾落在下标 8 —— 2026-10-16 修)----------
|
|
||||||
|
|
||||||
def _mk_lmes(sc, with_taxrate=True):
|
|
||||||
"""给回退支建 s_lmes:with_taxrate=False 模拟老库没有 TaxRate 列。"""
|
|
||||||
tx = ", TaxRate REAL" if with_taxrate else ""
|
|
||||||
sc.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
Number TEXT, Name TEXT, Specification TEXT, Unit TEXT, Kind INT,
|
|
||||||
Quantity REAL, NoTaxPrice REAL, TaxPrice REAL%(tx)s)""" % {"tx": tx})
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_proj_fallback_eleven_wide_taxrate_at_7():
|
|
||||||
"""老会话(s_lme_proj 无数据)回退 lmes:决策 147 后 11 列 id 首位、税率在下标 7、含税在下标 8;无 ids=只读。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("DELETE FROM s_lme_proj")
|
|
||||||
_mk_lmes(sc, with_taxrate=True)
|
|
||||||
sc.executemany("""INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Kind,
|
|
||||||
Quantity, NoTaxPrice, TaxRate, TaxPrice) VALUES(1,?,?,?,'kg',2, 10, ?, ?, ?)""",
|
|
||||||
[("C1", "钢筋", "", 99.99, 3.5, 103.49),
|
|
||||||
("C2", "水泥", "", 200.0, 3.5, 207.0)])
|
|
||||||
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
|
|
||||||
assert all(len(r) == 11 for r in d["rows"])
|
|
||||||
assert d["rows"][0][1] == "C1" and d["rows"][0][6] == 99.99
|
|
||||||
assert d["rows"][0][7] == 3.5 and d["rows"][0][8] == 103.49
|
|
||||||
assert "ids" not in d
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_proj_fallback_without_taxrate_column():
|
|
||||||
"""老库 lmes 没有 TaxRate 列:下标 7 恒 None(显示 —),含税仍在下标 8 —— 不得把含税顶进税率列。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("DELETE FROM s_lme_proj")
|
|
||||||
_mk_lmes(sc, with_taxrate=False)
|
|
||||||
sc.execute("""INSERT INTO s_lmes(session_id, Number, Name, Unit, Kind,
|
|
||||||
Quantity, NoTaxPrice, TaxPrice) VALUES(1,'C1','钢筋','kg',2, 10, 99.99, 103.49)""")
|
|
||||||
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
|
|
||||||
r0 = d["rows"][0]
|
|
||||||
assert len(r0) == 11 and r0[6] == 99.99 and r0[7] is None and r0[8] == 103.49
|
|
||||||
|
|
||||||
|
|
||||||
def test_raw_uw_agg_fallback_nine_wide_taxrate_at_7():
|
|
||||||
"""单位级归集回退(s_lme_uw 无数据):9 列、税率在下标 7、含税在下标 8(评审同款错位修)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("DELETE FROM s_lme_uw")
|
|
||||||
sc.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
Number TEXT, Name TEXT, Specialty TEXT, Total REAL)""")
|
|
||||||
sc.execute("INSERT INTO s_unit_works(id, session_id, Number, Name) VALUES(101,1,'1','土建')")
|
|
||||||
_mk_lmes(sc, with_taxrate=True)
|
|
||||||
sc.execute("""INSERT INTO s_lmes(session_id, Number, Name, Unit, Kind,
|
|
||||||
Quantity, NoTaxPrice, TaxRate, TaxPrice) VALUES(1,'C1','钢筋','kg',2, 10, 99.99, 3.5, 103.49)""")
|
|
||||||
sc.execute("""CREATE TABLE IF NOT EXISTS s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)""")
|
|
||||||
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(1, 1, 101)")
|
|
||||||
sc.execute("""CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT, x_side TEXT)""")
|
|
||||||
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(1, 1)") # 形状随 _mk_sess(经 s_bills 圈会话,无 session_id 列)
|
|
||||||
sc.execute("""CREATE TABLE IF NOT EXISTS s_norm_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
norm_id INT, res_code TEXT, qty REAL)""")
|
|
||||||
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(1, 1, 'C1', 4.0)")
|
|
||||||
d = srv._raw_uw(sc, srv.TBL["session"], 101, "lme")
|
|
||||||
assert d["src"] == "agg"
|
|
||||||
assert all(len(r) == 9 for r in d["rows"])
|
|
||||||
r0 = d["rows"][0]
|
|
||||||
assert r0[0] == "C1" and r0[5] == 4.0 and r0[6] == 99.99
|
|
||||||
assert r0[7] == 3.5 and r0[8] == 103.49
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_still_registers_codes_after_refactor():
|
|
||||||
"""回归:_merged_codes_add 抽取共用后,合并执行照旧登记编码 + 同步单位级。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
# 决策 244 夹具接线:C1 接定额消耗引用(只留被引用的工料机)
|
|
||||||
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(9, 1, 101)")
|
|
||||||
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(9, 9)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(9, 9, 'C1', 1.0)")
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [
|
|
||||||
{"sel": {"id": 1, "ntp": 88.8, "taxrate": 3.5}, "hide": []}]})
|
|
||||||
assert r["ok"] is True and r["kept"] == 1
|
|
||||||
assert _merged_codes(sc) == {"C1"}
|
|
||||||
uw = sc.execute("SELECT ntp FROM s_lme_uw WHERE id=11").fetchone()
|
|
||||||
assert uw["ntp"] == 88.8
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 规格 第9/11/12条:带子数据进弹框 + 单位级母行只替换编码(2026-10-16)----------
|
|
||||||
|
|
||||||
def test_merge_group_includes_child_rows_with_flag():
|
|
||||||
"""带子级组成的行进合并弹框(决策78 整行过滤废止),行带 sub 标记、编码最短默认勾选。
|
|
||||||
决策 171:组内另含单位级按码聚合行(lvl=uw,带 units/uw_ids)。"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
sc.execute("UPDATE s_lme_proj SET name='钢筋', unit='kg' WHERE id=2") # P1(带子级) 与 C1 同组
|
|
||||||
# 决策 186 v3 并集视野:补单位级行(C1/P1 同名规单)成组;项目级不进组
|
|
||||||
sc.executemany("INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind, "
|
|
||||||
"qty, ntp, taxrate, taxp) VALUES(?,1,?,?,'钢筋','kg',2,?,?,3.5,?)",
|
|
||||||
[(21, 101, "C1", 10, 99.0, 103.0), (22, 101, "P1", 5, 99.0, 103.0),
|
|
||||||
(23, 102, "C1", 12, 99.0, 103.0)])
|
|
||||||
d = srv._lme_merge_groups(sc, SID)
|
|
||||||
g = [x for x in d["groups"] if x["name"] == "钢筋"][0]
|
|
||||||
# 2026-11-04 规则:组=名规单;成员=除数量外任一字段不同即独立成员。
|
|
||||||
# 夹具预置 C1@99.99 两行(同成员,数量累计)+ 本用例 C1@99.0 两行(另一成员)→ C1 两个成员
|
|
||||||
codes = [r["code"] for r in g["rows"]]
|
|
||||||
assert codes.count("C1") == 2 and codes.count("P1") == 1
|
|
||||||
c1 = [r for r in g["rows"] if r["code"] == "C1" and r["ntp"] == 99.99][0]
|
|
||||||
assert c1["units"] == 2 and c1["qty"] is not None # 同字段组合两个单位行 → 一个成员
|
|
||||||
assert {r["code"]: r["sub"] for r in g["rows"] if r["code"] == "P1"} == {"P1": True}
|
|
||||||
assert g["rows"][0]["def"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_child_group_repoints_unit_mothers_and_replaces_children():
|
|
||||||
"""规格 第11/12条(决策 171 升级):合并后单位汇总里被合并码的母行**物理换成保留码**
|
|
||||||
(无撞码跳过——主人定「合并后每个单位工程里只显示保留码」,同码双行镜像源文件多行现实);
|
|
||||||
变体行只换码不换价(本单位价格原样),保留码价格同步走决策 75 通道;
|
|
||||||
子级组成**物理整字段替换**为保留行的子级(2026-10-16 主人纠偏「要真正替换全部字段」);
|
|
||||||
改码映射+子级替换数据落 s_settings 供导出重建。
|
|
||||||
(弹框真实流程对组内每条单位级聚合行都发 keep/hide——本测试按同款入参模拟。)"""
|
|
||||||
sc = _mk_sess()
|
|
||||||
# 决策 244 夹具接线:C1 接定额消耗引用(合并后只留被引用的)
|
|
||||||
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(9, 1, 101)")
|
|
||||||
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(9, 9)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(9, 9, 'C1', 1.0)")
|
|
||||||
# 决策 244 口径自洽(主人定「原版数据流:定额消耗量展开写入单位级汇总,子级码必有汇总行」):
|
|
||||||
# C1 的子级 C101/C102 在两级汇总本来就有行——注入兜底不再被触发
|
|
||||||
sc.execute("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(4, 1, 'C101', '盘圆', '', 'kg', 2, 5, 4.2, 0, 4.5)""")
|
|
||||||
sc.execute("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(5, 1, 'C102', '螺纹钢', '', 'kg', 2, 6, 4.6, 0, 5.0)""")
|
|
||||||
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(16, 1, 101, 'C101', '盘圆', 'kg', 2, 5, 4.2, 0, 4.5)""")
|
|
||||||
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(17, 1, 102, 'C102', '螺纹钢', 'kg', 2, 6, 4.6, 0, 5.0)""")
|
|
||||||
sc.execute("UPDATE s_lme_proj SET name='钢筋', unit='kg' WHERE id=2") # P1 并入 C1 组
|
|
||||||
# 保留行 C1 也有子级组成(2 条)——替换后 P1 的子级应变成这两条的全字段拷贝
|
|
||||||
sc.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(1,'C1',?,?,?,?)",
|
|
||||||
[("C101", 1.5, 1, "盘圆"), ("C102", 9.0, 2, "螺纹钢")])
|
|
||||||
# uw104:只有 P1 行 → 应被改码为 C1,价格保持本单位原值
|
|
||||||
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(14,1,104,'P1','钢筋','kg',2, 7, 222.0, 3.5, 229.77)""")
|
|
||||||
# uw102:C1、P1 都在 → 决策 171 无跳过:P1 行也换成 C1(同码双行)
|
|
||||||
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp) VALUES(15,1,102,'P1','钢筋','kg',2, 8, 210.0, 3.5, 217.35)""")
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [
|
|
||||||
{"sel": {"id": 1, "ntp": 99.99, "taxrate": 3.5, "taxp": 103.49},
|
|
||||||
"hide": [{"id": 2}, {"uw": 1, "code": "P1", "uw_ids": [104, 102]},
|
|
||||||
{"uw": 1, "code": "C1", "uw_ids": [101, 102]}]}]})
|
|
||||||
assert r["ok"] is True and r["hidden"] == 2
|
|
||||||
# 变体行换码后三价统一为保留行三价(决策 171 补:主人定「三价要同步更新」)
|
|
||||||
row14 = sc.execute("SELECT code, ntp, taxp FROM s_lme_uw WHERE id=14").fetchone()
|
|
||||||
assert row14["code"] == "C1" and (row14["ntp"], row14["taxp"]) == (99.99, 103.49)
|
|
||||||
# 决策 171 无跳过(uw102):P1 行也换成 C1
|
|
||||||
assert sc.execute("SELECT code FROM s_lme_uw WHERE id=15").fetchone()[0] == "C1"
|
|
||||||
# 保留码价格同步照旧:全部 C1 行(含换码而来的变体行)按保留行三价统一
|
|
||||||
vals = {x["id"]: round(x["ntp"], 2) for x in sc.execute("SELECT id, ntp FROM s_lme_uw WHERE code='C1'")}
|
|
||||||
assert vals[11] == 99.99 and vals[12] == 99.99 and vals[14] == 99.99 and vals[15] == 99.99
|
|
||||||
# 子级物理整字段替换:P1 名下现在是保留行 C1 的子级(全字段同源),不是空
|
|
||||||
kids = sc.execute("SELECT res_code, qty, seq, name FROM s_lme_res WHERE session_id=1 AND p_code='P1' ORDER BY seq").fetchall()
|
|
||||||
assert [(k["res_code"], k["qty"], k["seq"], k["name"]) for k in kids] == \
|
|
||||||
[("C101", 1.5, 1, "盘圆"), ("C102", 9.0, 2, "螺纹钢")]
|
|
||||||
# 项目级 P1 换码后零引用 → 决策 244 剪枝删除;改码映射+子级替换数据落 s_settings(导出侧重建节点用)
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_proj WHERE session_id=1 AND id=2").fetchone()[0] == 0
|
|
||||||
assert _merged_codes(sc) == {"C1"}
|
|
||||||
rm = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()[0])
|
|
||||||
assert rm == {"P1": "C1"}
|
|
||||||
rc = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_children:P1'").fetchone()[0])
|
|
||||||
assert rc == [["C101", 1.5], ["C102", 9.0]]
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_recode_renames_mother_and_rebuilds_children():
|
|
||||||
"""导出侧第12条真身:单位件里被合并码节点 Number 换成保留码(母只换码),
|
|
||||||
子级组成元素全字段重建为保留行子级(编码/含量按替换数据来)。"""
|
|
||||||
import re
|
|
||||||
import export_cos as xcos
|
|
||||||
txt = ('<r><LabourMaterialsEquipmentsMachinesSummary Number="B1" Name="焊机台班" Unit="台班" '
|
|
||||||
'Quantity="3.0000" NoTaxPrice="6.00" TaxPrice="7.00">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="00010003" Express="1.0000" Quantity="2.0000" Remark=""/>'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="99450700" Express="1.0000" Quantity="63.0000" Remark=""/>'
|
|
||||||
'</LabourMaterialsEquipmentsMachinesSummary></r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None,
|
|
||||||
recode_map={"B1": "C1"},
|
|
||||||
recode_children={"B1": [["00010003", 1.5], ["99450700", 63.0]]})
|
|
||||||
assert 'Number="B1"' not in out and 'Number="C1"' in out # 母只换码
|
|
||||||
pairs = re.findall(r'Number="([^"]+)" Express="([^"]+)" Quantity="([^"]+)"', out)
|
|
||||||
assert pairs == [("00010003", "1.5000", "1.5000"), ("99450700", "63.0000", "63.0000")] # 子级全字段重建(决策183:Express/Quantity 同源同写=库值)
|
|
||||||
assert out.count("</LabourMaterialsEquipmentsMachinesSummary>") == 1 # 成对结构完好
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_recode_childless_renames_only():
|
|
||||||
"""无子级替换数据(childless 合并):只换码,节点结构原样。"""
|
|
||||||
import export_cos as xcos
|
|
||||||
txt = ('<r><LabourMaterialsEquipmentsMachinesSummary Number="A12" Name="水泥" Unit="kg" '
|
|
||||||
'Quantity="5.0000" NoTaxPrice="2.00" TaxPrice="3.00"/></r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None, recode_map={"A12": "A1"})
|
|
||||||
assert 'Number="A1"' in out and 'Number="A12"' not in out
|
|
||||||
assert out.count("LabourMaterialsEquipmentsMachinesSummary") == 1 # 自闭合节点原样,只换了码
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- HTTP 全链路(隔离副本服务,与 test_api_p0 同款夹具)----------
|
|
||||||
|
|
||||||
import sqlite3 as _sq # noqa: E402
|
|
||||||
|
|
||||||
from api_harness import PERIOD_202607, fixture_file, get, post, server # noqa: E402, F401
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = _sq.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_http_lme_price_end_to_end(server):
|
|
||||||
"""真服务链路:打开工程 → raw/proj 九列带 ids → POST lme/price 三价联动
|
|
||||||
→ 项目级行落库 + 单位级按编码同步 + merged_codes 登记(导出侧能看到)。"""
|
|
||||||
p = fixture_file(server, "lmeprice.cos4", "改价联动工程",
|
|
||||||
[("030507008001", "高清网络摄像机", "", "台", 10, 1500)],
|
|
||||||
[("000001", "网络摄像机", "400万", "台", "1200", "1356")])
|
|
||||||
sid = post(server, "/api/audit",
|
|
||||||
{"name": "改价联动工程", "province": "广东省", "city": "珠海市",
|
|
||||||
"district": "香洲区", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607, "file_kind": 1, "path": p})["session_id"]
|
|
||||||
d = get(server, "/api/session/raw/proj", session_id=sid, tab="lme")
|
|
||||||
# 决策 147:11 列 id 首位,不再 rows/ids 分离
|
|
||||||
assert d["ok"] is True and d["rows"] and all(len(r) == 11 for r in d["rows"])
|
|
||||||
rid = d["rows"][0][0]
|
|
||||||
code = d["rows"][0][1]
|
|
||||||
# 改除税 99.99 + 税率 3.5 → 含税 103.49(主人给的例,服务端复核)
|
|
||||||
r = post(server, "/api/session/lme/price",
|
|
||||||
{"session_id": sid, "id": rid, "ntp": 99.99, "taxrate": 3.5})
|
|
||||||
assert r["ok"] is True and r["ntp"] == 99.99 and r["taxrate"] == 3.5 and r["taxp"] == 103.49
|
|
||||||
# 项目级行已落库
|
|
||||||
row = _q(server["sessdb"], "SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=?", (rid,))[0]
|
|
||||||
assert (row[0], row[1], row[2]) == (99.99, 3.5, 103.49)
|
|
||||||
# 单位级按编码同步(该编码在 UW1 汇总里有一行)
|
|
||||||
assert r["synced"] >= 1
|
|
||||||
uw = _q(server["sessdb"], "SELECT ntp, taxrate, taxp FROM s_lme_uw WHERE session_id=? AND code=?",
|
|
||||||
(sid, code))[0]
|
|
||||||
assert (uw[0], uw[1], uw[2]) == (99.99, 3.5, 103.49)
|
|
||||||
# merged_codes 已登记(导出侧 price_updates 的唯一来源)
|
|
||||||
mc = _q(server["sessdb"], "SELECT v FROM s_settings WHERE scope=? AND k=?",
|
|
||||||
("session:%d" % sid, "merged_codes"))[0][0]
|
|
||||||
assert code in set(json.loads(mc))
|
|
||||||
# 只改含税 → 反解除税
|
|
||||||
r2 = post(server, "/api/session/lme/price", {"session_id": sid, "id": rid, "taxp": 113.0})
|
|
||||||
assert r2["ok"] is True and r2["taxrate"] == 3.5
|
|
||||||
assert abs(r2["ntp"] - 109.18) < 0.011 # 113/1.035 = 109.179…
|
|
||||||
# 界面再读:税率在下标 7、含税在下标 8
|
|
||||||
d2 = get(server, "/api/session/raw/proj", session_id=sid, tab="lme")
|
|
||||||
row2 = d2["rows"][0]
|
|
||||||
assert row2[7] == 3.5 and row2[8] == 113.0
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""项目工料机切数据源防回归(决策 40,2026-10-11 主人定)。
|
|
||||||
|
|
||||||
口径:工作台/后台「项目工料机」标签统一改读**项目级工料机汇总**(s_lme_proj / lme_proj,
|
|
||||||
源文件 Project.xml 项目级汇总原样入库),过滤规则不变(LME_LIST_WHERE)。
|
|
||||||
本文件钉死:①proj 表同样被 LME_LIST_WHERE 过滤(台班/费用科目不显示);②采纳备注
|
|
||||||
写入 s_lme_proj.x_remark + s_remarks('L:' 内容键),重解析后按 rkey 回填;
|
|
||||||
③存量采纳事件 adopt_hits.lme_id 按 rkey 从 s_lmes.id 平移到 s_lme_proj.id(一次性闸门)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
import session_job # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess():
|
|
||||||
"""内存会话库:最小 schema + 一个会话 + 三条项目级汇总行(台班/费用科目/正常材料)。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE sessions(id INTEGER PRIMARY KEY, name TEXT, src_name TEXT)""")
|
|
||||||
c.execute("INSERT INTO sessions(id, name, src_name) VALUES(1,'工程甲','HASHA_甲.cos4')")
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
Number TEXT, Name TEXT, Unit TEXT, x_remark TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_remarks(id INTEGER PRIMARY KEY, src_key TEXT, uw_name TEXT,
|
|
||||||
bill_no TEXT, bill_name TEXT, bill_unit TEXT,
|
|
||||||
rkey TEXT UNIQUE, remark TEXT, updated_at TEXT)""")
|
|
||||||
rows = [(1, "05010002", "普通硅酸盐水泥", "", "kg", 2, 100, 200, 200), # 正常
|
|
||||||
(2, "990106030", "挖掘机台班", "", "台班", 7, 5, 900, 900), # Kind7 台班 → 滤掉
|
|
||||||
(3, "00010010", "人工费", "", "元", 1, 0, 1, 1)] # 单位=元 → 滤掉
|
|
||||||
for r in rows:
|
|
||||||
c.execute("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxp) VALUES(?, 1, ?, ?, ?, ?, ?, ?, ?, ?)""", r)
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_hist():
|
|
||||||
hc = sqlite3.connect(":memory:")
|
|
||||||
hc.row_factory = sqlite3.Row
|
|
||||||
c = hc.cursor()
|
|
||||||
c.execute("""CREATE TABLE adopt_hits(sha256 TEXT, proj TEXT, adopted_at TEXT,
|
|
||||||
sid INT, lme_id INT)""")
|
|
||||||
c.execute("""CREATE TABLE adopt_files(sha256 TEXT PRIMARY KEY, kind TEXT, ref TEXT,
|
|
||||||
name TEXT, ext TEXT, size INT, adopted_at TEXT)""")
|
|
||||||
return hc
|
|
||||||
|
|
||||||
|
|
||||||
def test_lme_rows_reads_proj_and_filters():
|
|
||||||
sc = _mk_sess()
|
|
||||||
d = srv._lme_rows(sc, srv.TBL["session"], 1)
|
|
||||||
assert d["total"] == 1 # 台班/元 被滤掉
|
|
||||||
r = d["rows"][0]
|
|
||||||
assert r[1] == "05010002" and r[2] == "普通硅酸盐水泥" and r[7] is None # 税率列恒空
|
|
||||||
assert len(r) == 11 # 11 列契约(含备注位)
|
|
||||||
|
|
||||||
|
|
||||||
def test_lme_remark_roundtrip_and_restore():
|
|
||||||
sc = _mk_sess()
|
|
||||||
sess = session_job
|
|
||||||
sess.save_lme_remark(sc, 1, "采纳:机上人工 200.00 某工程") # 写 proj 行 + s_remarks
|
|
||||||
assert "采纳" in sc.execute("SELECT x_remark FROM s_lme_proj WHERE id=1").fetchone()[0]
|
|
||||||
n = sc.execute("SELECT COUNT(*) FROM s_remarks WHERE rkey LIKE 'L:%'").fetchone()[0]
|
|
||||||
assert n == 1
|
|
||||||
# 模拟重解析:proj 行备注被清 → restore 按 rkey 回填
|
|
||||||
sc.execute("UPDATE s_lme_proj SET x_remark=''")
|
|
||||||
assert sess.restore_lme_remarks(sc, 1) == 1
|
|
||||||
assert "采纳" in sc.execute("SELECT x_remark FROM s_lme_proj WHERE id=1").fetchone()[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_migrate_rekeys_events_and_gate():
|
|
||||||
sc, hc = _mk_sess(), _mk_hist()
|
|
||||||
# 存量:备注在 s_lmes 行(id=999,内容键与 proj 行 1 相同)+ s_remarks 持久副本(真实库双写)
|
|
||||||
rk = "L:" + session_job.rkey("HASHA_甲.cos4", "", "05010002", "普通硅酸盐水泥", "kg")
|
|
||||||
sc.execute("INSERT INTO s_lmes(id, session_id, Number, Name, Unit) VALUES(999, 1, '05010002', '普通硅酸盐水泥', 'kg')")
|
|
||||||
sc.execute("UPDATE s_lmes SET x_remark='采纳:普通硅酸盐水泥 200.00 某工程' WHERE id=999")
|
|
||||||
sc.execute("INSERT INTO s_remarks(src_key, uw_name, bill_no, bill_name, bill_unit, rkey, remark, updated_at)"
|
|
||||||
" VALUES('HASHA_甲.cos4','','','','',?,'采纳:普通硅酸盐水泥 200.00 某工程','now')", (rk,))
|
|
||||||
hc.execute("INSERT INTO adopt_hits(sha256, proj, adopted_at, sid, lme_id) VALUES('SH','某工程','now',1,999)")
|
|
||||||
gate = {}
|
|
||||||
srv._setting_get = lambda scope, k: gate.get(k)
|
|
||||||
srv._setting_set = lambda scope, k, v: gate.__setitem__(k, v)
|
|
||||||
n = srv._migrate_lme_adoption(sc, hc)
|
|
||||||
assert n == 1 # 事件重键 1 条
|
|
||||||
assert hc.execute("SELECT lme_id FROM adopt_hits").fetchone()[0] == 1 # → proj 行 id=1
|
|
||||||
assert "采纳" in sc.execute("SELECT x_remark FROM s_lme_proj WHERE id=1").fetchone()[0]
|
|
||||||
assert srv._migrate_lme_adoption(sc, hc) == 0 # 闸门:第二次不再动
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 244(2026-11-01 主人定)防回归:工料机剪枝 + 合并弹框只看现算。
|
|
||||||
|
|
||||||
主人口径:「在导入或者打开项目,工料机引用的才入数据库」「合并工料机,只关注现算」。
|
|
||||||
钉死四件事:
|
|
||||||
①剪枝:未被引用(无定额直挂、无子级引用)的码从两级汇总移除;被引用的保留;
|
|
||||||
②合并隐藏行(x_merged_hide=1)保留——映射语义载体;
|
|
||||||
③子级引用算引用:柴油被台班引用(定额只挂台班)→ 柴油保留;
|
|
||||||
④弹框只看现算:现算 0 量的码不成组(dyn_rows 链全时);链不全退回老行为不炸。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
"""最小会话库:
|
|
||||||
定额 N1(清单 B1,量 10)直挂 DIESL(2.0);台班 TB 被定额挂(0.5),TB 子级引用 OIL(4);
|
|
||||||
GHOST 无任何引用(应剪);HIDDEN 未引用但 x_merged_hide=1(应保留);FREE 子级引用但母行无定额(应保留——保守剪枝边界外)。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, x_tdel INTEGER DEFAULT 0)""")
|
|
||||||
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_tdel INTEGER DEFAULT 0, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
|
|
||||||
ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
|
|
||||||
ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
c.executemany("INSERT INTO s_bills VALUES(?,?,?,0)", [(1, SID, 101), (2, SID, 102)])
|
|
||||||
c.executemany("INSERT INTO s_norms VALUES(?,?,0, NULL)", [(10, 1), (11, 2)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res VALUES(?,?,?,?)",
|
|
||||||
[(100, 10, "DIESEL", 2.0), (101, 10, "TB", 0.5),
|
|
||||||
(102, 11, "TEMP", 1.0)]) # 定额 11 挂临删清单(x_tdel=1)
|
|
||||||
c.execute("UPDATE s_bills SET x_tdel=1 WHERE id=2") # 清单 2 临时删除(行还在可恢复)
|
|
||||||
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)",
|
|
||||||
[(SID, "TB", "OIL", 4.0, 1, "油")])
|
|
||||||
# 两级汇总:DIESEL/TB/OIL 被引用;GHOST/HIDDEN 未引用
|
|
||||||
rows = [("DIESEL", 20.0, 0), ("TB", 5.0, 0), ("OIL", 2.0, 0),
|
|
||||||
("TEMP", 8.0, 0), ("GHOST", 999.0, 0), ("HIDDEN", 50.0, 1)]
|
|
||||||
c.executemany("""INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp, x_merged_hide)
|
|
||||||
VALUES(?,?,?,'','',2,?,?,0,?,?)""",
|
|
||||||
[(SID, cd, cd, q, 1.0, 1.0, hid) for cd, q, hid in rows])
|
|
||||||
c.executemany("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp)
|
|
||||||
VALUES(?,101,?,?,?,'',2,?,?,0,?)""",
|
|
||||||
[(SID, cd, cd, '', q, 1.0, 1.0) for cd, q, hid in rows])
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def test_prune_keeps_referenced_deletes_ghost_keeps_hidden():
|
|
||||||
"""①②③:GHOST(零引用)删除;HIDDEN(未引用但隐藏)保留;OIL(仅子级引用)保留。"""
|
|
||||||
con = _mk()
|
|
||||||
n = srv._prune_unreferenced_lme(con, SID)
|
|
||||||
assert n > 0
|
|
||||||
codes = {r[0] for r in con.execute("SELECT code FROM s_lme_proj WHERE session_id=?", (SID,))}
|
|
||||||
assert codes == {"DIESEL", "TB", "OIL", "TEMP"} # GHOST/HIDDEN 剪(合并隐藏行不豁免);TEMP 临删引用保留
|
|
||||||
codes_uw = {r[0] for r in con.execute("SELECT code FROM s_lme_uw WHERE session_id=?", (SID,))}
|
|
||||||
assert "GHOST" not in codes_uw and "HIDDEN" not in codes_uw
|
|
||||||
assert {"DIESEL", "TB", "OIL", "TEMP"} <= codes_uw
|
|
||||||
# 幂等:再跑一次不炸不多删
|
|
||||||
n2 = srv._prune_unreferenced_lme(con, SID)
|
|
||||||
assert codes == {r[0] for r in con.execute("SELECT code FROM s_lme_proj WHERE session_id=?", (SID,))}
|
|
||||||
|
|
||||||
|
|
||||||
def test_prune_empty_ref_set_noop():
|
|
||||||
"""引用集为空(异常会话)跳过不删——绝不能误删一切。"""
|
|
||||||
con = _mk()
|
|
||||||
con.execute("DELETE FROM s_norm_res")
|
|
||||||
con.execute("DELETE FROM s_lme_res")
|
|
||||||
con.commit()
|
|
||||||
before = con.execute("SELECT COUNT(*) FROM s_lme_proj").fetchone()[0]
|
|
||||||
n = srv._prune_unreferenced_lme(con, SID)
|
|
||||||
assert n == 0
|
|
||||||
after = con.execute("SELECT COUNT(*) FROM s_lme_proj").fetchone()[0]
|
|
||||||
assert before == after
|
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 174(2026-10-22 主人定):导出换码/改价/字段回写/隐藏删除 **同码全部命中**。
|
|
||||||
|
|
||||||
实测背景:广联达件同一单位工程里同码会出现多条汇总节点(按分部重复列码),旧首中语义
|
|
||||||
只改首条 → 导出件残留旧码旧价(华宇路 37270101@3 三条只换一条、金宝 Summary 残留
|
|
||||||
1100 条、Project.xml 无换码通道残留 487 条)。本文件用最小样件锁死全命中口径。"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
|
|
||||||
import export_cos as xcos # noqa: E402
|
|
||||||
|
|
||||||
S = "LabourMaterialsEquipmentsMachinesSummary"
|
|
||||||
|
|
||||||
|
|
||||||
def _two_nodes(code, price="6.99", qty1="64.1300", qty2="47.8060"):
|
|
||||||
"""同码两条自闭合汇总节点(华宇路 37270101@3 的真实形态缩影)。"""
|
|
||||||
return ('<r>'
|
|
||||||
f'<{S} Number="{code}" Name="镀铜角钢" Specification="L50×50×5" Unit="kg" '
|
|
||||||
f'Quantity="{qty1}" NoTaxPrice="{price}" TaxRate="0.0" TaxPrice="{price}"/>'
|
|
||||||
f'<{S} Number="{code}" Name="镀铜角钢" Specification="L50×50×5" Unit="kg" '
|
|
||||||
f'Quantity="{qty2}" NoTaxPrice="{price}" TaxRate="0.0" TaxPrice="{price}"/>'
|
|
||||||
'</r>')
|
|
||||||
|
|
||||||
|
|
||||||
def test_recode_all_hits_same_code_multi_nodes():
|
|
||||||
"""换码通道 + 决策 184 A 清洗:同码两条节点归并后**每码只留一条**(保留最后一条
|
|
||||||
47.806,前一条被吸收删除——条目数=显示端,2026-10-23 主人定)。"""
|
|
||||||
out = xcos.transform_unit_summaries(_two_nodes("A3"), {}, None, recode_map={"A3": "A1"})
|
|
||||||
assert out.count('Number="A1"') == 1
|
|
||||||
assert 'Number="A3"' not in out
|
|
||||||
qs = re.findall(r'Quantity="([0-9.]+)"', out)
|
|
||||||
assert qs == ["47.8060"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_price_updates_all_hits():
|
|
||||||
"""改价通道:同码两条节点全部吃到新价(旧首中语义只改首条)。"""
|
|
||||||
out = xcos.transform_unit_summaries(_two_nodes("A1", price="6.99"),
|
|
||||||
{"A1": (58.88, 0.0, 58.88)}, None)
|
|
||||||
assert out.count('NoTaxPrice="58.88"') == 2
|
|
||||||
assert 'NoTaxPrice="6.99"' not in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_field_updates_all_hits():
|
|
||||||
"""字段回写通道:同码两条节点的名称/规格/单位全部更新。"""
|
|
||||||
out = xcos.transform_unit_summaries(_two_nodes("A1"), {}, None,
|
|
||||||
field_updates={"A1": ("热镀锌角钢接地极", "L50×50×5 L=2500", "根")})
|
|
||||||
assert out.count('Name="热镀锌角钢接地极"') == 2
|
|
||||||
assert "镀铜角钢" not in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_recode_with_children_all_hits():
|
|
||||||
"""换码+子级重建:同码两条成对节点全部换码、子级各自整字段重建为保留行子级。"""
|
|
||||||
blk = ('<{S} Number="B3" Name="焊机台班" Unit="台班" Quantity="{{q}}" NoTaxPrice="6.00" TaxPrice="7.00">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="000001" Express="1.0000" Quantity="2.0000" Remark=""/>'
|
|
||||||
'</{S}>').format(S=S)
|
|
||||||
txt = "<r>" + blk.format(q="1.0000") + blk.format(q="2.0000") + "</r>"
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None,
|
|
||||||
recode_map={"B3": "C1"},
|
|
||||||
recode_children={"B3": [["000002", 9.0]]})
|
|
||||||
assert out.count('Number="C1"') == 1 and 'Number="B3"' not in out # 决策 184 A 清洗:每码一条
|
|
||||||
kids = re.findall(r'<LabourMaterialsEquipmentsMachinesElement Number="([^"]+)"[^>]*Quantity="([^"]+)"', out)
|
|
||||||
assert kids == [("000002", "9.0000")] # 保留最全成对块,子级照常重建
|
|
||||||
assert out.count(f"</{S}>") == 1 # 成对块结构完好
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_hidden_deletes_all_hits():
|
|
||||||
"""Project.xml 隐藏删除:同码两条块全部删除(旧首中语义会留一条)。"""
|
|
||||||
blk = '<{S} Number="H1" Name="x" Quantity="{{q}}"><LabourMaterialsEquipmentsMachinesElement Number="c" Quantity="1.0000" Remark=""/></{S}>'.format(S=S)
|
|
||||||
txt = "<ConstructionProject>" + blk.format(q="1.0000") + blk.format(q="2.0000") + "</ConstructionProject>"
|
|
||||||
out = xcos.transform_project(txt, [], ["H1"])
|
|
||||||
assert "Number=\"H1\"" not in out and "LabourMaterialsEquipmentsMachinesElement" not in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_sync_all_hits():
|
|
||||||
"""Project.xml 同步:同码两条节点全部吃到现值。"""
|
|
||||||
out = xcos.transform_project(_two_nodes("K1"), [], [],
|
|
||||||
sync_rows=[("K1", "现值名", "现值规", "t", 10.0, 0.0, 10.0)])
|
|
||||||
assert out.count('Name="现值名"') == 2 and "镀铜角钢" not in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_recode_channel_renames_and_carries_kept_values():
|
|
||||||
"""Project.xml 换码通道(决策 174 新增):旧码节点 Number 换保留码并带保留行同步值。"""
|
|
||||||
txt = _two_nodes("A3")
|
|
||||||
out = xcos.transform_project(txt, [], [],
|
|
||||||
sync_rows=[("A1", "热镀锌角钢接地极", "L50×50×5 L=2500", "根", 73.98, 0.0, 73.98)],
|
|
||||||
recode_map={"A3": "A1"})
|
|
||||||
assert out.count('Number="A1"') == 2 and 'Number="A3"' not in out
|
|
||||||
# 换码节点带保留行同步值(旧值 6.99 不许残留=新旧两价并存)
|
|
||||||
assert 'NoTaxPrice="73.98"' in out and 'NoTaxPrice="6.99"' not in out
|
|
||||||
assert "热镀锌角钢接地极" in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_recode_skips_hidden_blocks():
|
|
||||||
"""换码不复活隐藏块:同码既被隐藏又在换码映射里 → 删除优先,不出现换码后的节点。"""
|
|
||||||
txt = '<r><{S} Number="A3" Name="x" Quantity="1.0000"/></r>'.format(S=S)
|
|
||||||
out = xcos.transform_project(txt, [], ["A3"], sync_rows=[("A1", "n", "", "", 1.0, 0.0, 1.0)],
|
|
||||||
recode_map={"A3": "A1"})
|
|
||||||
assert "Number=" not in out.replace('Number=""', "")
|
|
||||||
|
|
||||||
|
|
||||||
def test_bare_open_tag_rows_all_recode():
|
|
||||||
"""金宝件实测结构:无子级行是**裸开标签**(无 /> 无闭标签,下一行即下一节点)。
|
|
||||||
索引不得把裸行误判成「成对块」吞到远处的别人闭标签——否则假块与内层编辑相交,
|
|
||||||
_apply_edits 相交防御丢弃外层编辑=换码失效(Sum 残留 88 的根源);
|
|
||||||
_recode_norm_lme_rows 同理不得把裸行间的元素行误当块内子级跳过。
|
|
||||||
走真实管线:transform_unit_summaries(换码+子级重建)后接 _recode_norm_lme_rows(块外行)。"""
|
|
||||||
row = '<{S} Number="{{c}}" Name="白布" Unit="kg" Quantity="29.5515" NoTaxPrice="2.48">'.format(S=S)
|
|
||||||
txt = ('<r>'
|
|
||||||
+ row.format(c="A3")
|
|
||||||
+ '<LabourMaterialsEquipmentsMachinesElement Number="A3" Quantity="1.0000" Remark=""/>'
|
|
||||||
+ row.format(c="A3")
|
|
||||||
+ row.format(c="B9")
|
|
||||||
+ '<{S} Number="A3" Name="焊机台班" Quantity="2.0000">'.format(S=S)
|
|
||||||
+ '<LabourMaterialsEquipmentsMachinesElement Number="000001" Quantity="3.0000" Remark=""/>'
|
|
||||||
+ f'</{S}>'
|
|
||||||
+ '</r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None,
|
|
||||||
recode_map={"A3": "A1", "B9": "B1"},
|
|
||||||
recode_children={"A3": [["000002", 9.0]]})
|
|
||||||
out = xcos._recode_norm_lme_rows(out, {"A3": "A1", "B9": "B1"})
|
|
||||||
assert 'Number="A3"' not in out and 'Number="B9"' not in out
|
|
||||||
assert out.count('Number="A1"') == 2 # 决策 184 A 清洗:三处 A3 留最全成对块一条 + 块外元素行
|
|
||||||
assert 'Number="B1"' in out
|
|
||||||
assert 'Number="000002"' in out and 'Number="000001"' not in out # 最全成对块的子级照常重建
|
|
||||||
assert out.count(f"</{S}>") == 1 # 只保留的真块有闭标签:裸行被清洗,不发明闭块结构
|
|
||||||
|
|
||||||
|
|
||||||
def test_recode_norm_lme_rows_all_element_rows():
|
|
||||||
"""决策 178:元素行编码**全部**跟映射换——块内子级、块外直挂行一视同仁(含量不动)。"""
|
|
||||||
txt = ('<r>'
|
|
||||||
'<{S} Number="A3" Name="x" Quantity="1.0">'.format(S=S)
|
|
||||||
+ '<LabourMaterialsEquipmentsMachinesElement Number="A3" Quantity="1.0000" Remark=""/>'
|
|
||||||
+ '<{S} Number="P1" Name="t" Quantity="2.0">'.format(S=S)
|
|
||||||
+ '<LabourMaterialsEquipmentsMachinesElement Number="A3" Quantity="5.0000" Remark=""/>'
|
|
||||||
+ f'</{S}>'
|
|
||||||
+ '</r>')
|
|
||||||
out = xcos._recode_norm_lme_rows(txt, {"A3": "A1"})
|
|
||||||
assert not re.search(r'<LabourMaterialsEquipmentsMachinesElement Number="A3"', out) # 元素行全换
|
|
||||||
assert out.count('Number="A1"') == 2
|
|
||||||
assert 'Quantity="1.0000"' in out and 'Quantity="5.0000"' in out # 含量各随各节点
|
|
||||||
assert '<{S} Number="P1"'.format(S=S) in out # 结构不动
|
|
||||||
|
|
||||||
|
|
||||||
def test_recode_chain_flattened_to_tail():
|
|
||||||
"""改码链压平(决策 174 补):A3→A1 与 A1→A9 共存(两次合并累积),A3 节点必须
|
|
||||||
一步落到链尾 A9,不许停在中途码 A1(金宝 -0004→-0001→-0009 实测残留的根源)。"""
|
|
||||||
txt = ('<r>'
|
|
||||||
'<{S} Number="A3" Name="x" Quantity="1.0000"/>'.format(S=S)
|
|
||||||
+ '<{S} Number="A1" Name="y" Quantity="2.0000"/>'.format(S=S)
|
|
||||||
+ '</r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None, recode_map={"A3": "A1", "A1": "A9"})
|
|
||||||
assert 'Number="A3"' not in out and 'Number="A1"' not in out
|
|
||||||
assert out.count('Number="A9"') == 1 # 链上两码全部落到链尾 + 决策 184 A 清洗:每码一条
|
|
||||||
|
|
||||||
|
|
||||||
def test_recode_chain_resolve_helper():
|
|
||||||
"""压平助手:链取尾;环(A↔B 历史脏映射)按**最先写入的边**的目标收敛
|
|
||||||
(决策 185,2026-10-23 主人定:与显示端幸存行方向一致——session:76 实测灰土环
|
|
||||||
幸存 80310015-0001、人工费环幸存基码 00010010,均为各自环最先写入边的目标;
|
|
||||||
取代决策 174「按访问集停在入口码」旧口径,不再静默停在入口码)。"""
|
|
||||||
assert xcos._resolve_recode_chains({"A3": "A1", "A1": "A9"}) == {"A3": "A9", "A1": "A9"}
|
|
||||||
assert xcos._resolve_recode_chains({"B": "C", "C": "C"}) == {"B": "C"}
|
|
||||||
assert xcos._resolve_recode_chains({"X": "Y", "Y": "X"}) == {"X": "Y"}
|
|
||||||
assert xcos._resolve_recode_chains({"Z": "Z"}) == {}
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_sync_writes_unconditionally():
|
|
||||||
"""决策 176:Project.xml 同步=**全量写回**,提供即写、不比较新旧(取代 75 的
|
|
||||||
「只更新不一致字段」最小替代)。语义相等但文本不同也要归一成提供值。"""
|
|
||||||
txt = ('<ConstructionProject>'
|
|
||||||
f'<{S} Number="K1" Name="白布" Unit="kg"'
|
|
||||||
' Quantity="29.5515" TaxRate="0" NoTaxPrice="2.48" TaxPrice="2.48"/>'
|
|
||||||
'</ConstructionProject>')
|
|
||||||
out = xcos.transform_project(txt, [], [],
|
|
||||||
sync_rows=[("K1", "白布", "", "kg", 2.48, 0.0, 2.48)])
|
|
||||||
assert 'TaxRate="0.0"' in out # 相等也写:文本归一为提供值格式
|
|
||||||
assert 'NoTaxPrice="2.48"' in out and 'TaxPrice="2.48"' in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_ident_foreign_node_split():
|
|
||||||
"""决策 178:同码异物拆分——保留码被组外名规单占用时,导出按节点自带名规单改印新码;
|
|
||||||
异物节点不吃合并价/换码,组内节点照常。"""
|
|
||||||
txt = ('<r>'
|
|
||||||
f'<{S} Number="K1" Name="白布" Specification="" Unit="kg" Quantity="1.0000" NoTaxPrice="6.00"/>'
|
|
||||||
f'<{S} Number="K1" Name="铁钉" Specification="50mm" Unit="kg" Quantity="2.0000" NoTaxPrice="9.00"/>'
|
|
||||||
'</r>')
|
|
||||||
out = xcos.transform_unit_summaries(txt, {"K1": (58.88, 0.0, 58.88)}, None,
|
|
||||||
recode_ident={"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}})
|
|
||||||
# 组内节点:保留码+合并价;异物节点:改印新码、价格原样
|
|
||||||
assert out.count('Number="K1@1"') == 1 and 'Name="铁钉"' in out
|
|
||||||
assert 'NoTaxPrice="9.00"' in out # 异物不吃合并价
|
|
||||||
assert 'NoTaxPrice="58.88"' in out # 组内照常吃合并价
|
|
||||||
|
|
||||||
|
|
||||||
def test_children_registered_empty_strips_block_children():
|
|
||||||
"""决策 178:重建数据登记为空表=[] → 成对块子级清空(全部替换的真意:保留码无子级)。"""
|
|
||||||
txt = ('<r><{S} Number="B3" Name="焊机台班" Quantity="2.0000">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="000001" Quantity="3.0000" Remark=""/>'
|
|
||||||
f'</{S}></r>').format(S=S)
|
|
||||||
out = xcos.transform_unit_summaries(txt, {}, None,
|
|
||||||
recode_map={"B3": "C1"}, recode_children={"B3": []})
|
|
||||||
assert 'Number="C1"' in out and 'Number="B3"' not in out
|
|
||||||
assert "LabourMaterialsEquipmentsMachinesElement" not in out # 子级清空
|
|
||||||
assert out.count(f"</{S}>") == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_project_children_rebuild_and_ident_split():
|
|
||||||
"""决策 178:Project.xml 成对块子级整组替换成保留码子级;同码异物节点改印新码。"""
|
|
||||||
txt = ('<ConstructionProject>'
|
|
||||||
'<{S} Number="B3" Name="焊机台班" Quantity="2.0000">'
|
|
||||||
'<LabourMaterialsEquipmentsMachinesElement Number="000001" Quantity="3.0000" Remark=""/>'
|
|
||||||
'</{S}>'.format(S=S)
|
|
||||||
+ '<{S} Number="K1" Name="铁钉" Specification="50mm" Unit="kg" Quantity="1.0000"/>'.format(S=S)
|
|
||||||
+ '</ConstructionProject>')
|
|
||||||
out = xcos.transform_project(txt, [], [],
|
|
||||||
recode_map={"B3": "C1"}, recode_children={"B3": [["000002", 9.0]]},
|
|
||||||
recode_ident={"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}})
|
|
||||||
assert 'Number="C1"' in out and 'Number="B3"' not in out
|
|
||||||
assert 'Number="000002"' in out and 'Number="000001"' not in out # 子级整组替换
|
|
||||||
assert 'Number="K1@1"' in out # 同码异物拆分
|
|
||||||
|
|
||||||
|
|
||||||
def test_split_occupied_code_assigns_fresh_codes():
|
|
||||||
"""决策 178:保留码被组外名规单占用 → 占用行自动换未占用新码(两级表+登记)。"""
|
|
||||||
import sqlite3
|
|
||||||
con = sqlite3.connect(":memory:")
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
con.execute("CREATE TABLE s_lme_proj(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)")
|
|
||||||
con.execute("CREATE TABLE s_lme_uw(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)")
|
|
||||||
con.execute("CREATE TABLE s_settings(scope TEXT, k TEXT, v TEXT, PRIMARY KEY(scope, k))")
|
|
||||||
for c, nm, sp, un in (("K1", "白布", "", "kg"), ("K1", "铁钉", "50mm", "kg")):
|
|
||||||
con.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit) VALUES(1,?,?,?,?)", (c, nm, sp, un))
|
|
||||||
con.execute("INSERT INTO s_lme_uw(session_id, code, name, spec, unit) VALUES(1,'K1','铁钉','50mm','kg')")
|
|
||||||
import importlib
|
|
||||||
srv = importlib.import_module("api_server")
|
|
||||||
n = srv._split_occupied_code(con, 1, "K1", ("白布", "", "kg"))
|
|
||||||
assert n == 1 # 一个异物名规单(proj+uw 同批改)
|
|
||||||
codes = sorted(r[0] for r in con.execute("SELECT code FROM s_lme_proj"))
|
|
||||||
assert codes == ["K1", "K1@1"] # 组内保码,异物换新码
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_lme_uw WHERE code='K1@1'").fetchone()[0] == 1
|
|
||||||
ri = json_loads(con)
|
|
||||||
assert ri == {"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}}
|
|
||||||
|
|
||||||
|
|
||||||
def json_loads(con):
|
|
||||||
import json as _j
|
|
||||||
return _j.loads(con.execute("SELECT v FROM s_settings WHERE k='recode_ident'").fetchone()[0])
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 265 扩展(2026-11-04 主人定「数据只来源原数据,耗弹框不许重复」):
|
|
||||||
|
|
||||||
① `_lme_res` 同码多行只返回一条——此前采纳补子级跨批次把 12 个批次的同码组成全灌进会话,
|
|
||||||
弹框展开显示 60 行(机上人工×12 等),引擎数量也翻倍。
|
|
||||||
② `dedupe_lme_res` 去重键去掉 qty/seq——旧键让「同码不同 seq」的重复套躲过自愈。"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
import session_job as sj # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sc():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT, Number TEXT,
|
|
||||||
Name TEXT, Specification TEXT, Unit TEXT, Kind INT, Quantity REAL,
|
|
||||||
NoTaxPrice REAL, TaxPrice REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
|
||||||
taxp REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_lib(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, ntp REAL, taxp REAL)""")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def test_lme_res_same_code_returns_one():
|
|
||||||
"""同码 3 行(seq 0/1/2,正是跨批次灌入的形态)→ _lme_res 只返回 1 条。"""
|
|
||||||
sc = _mk_sc()
|
|
||||||
sc.execute("INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Kind,"
|
|
||||||
" NoTaxPrice, TaxPrice) VALUES(1,'C1','机上人工','','工日',1,230.0,230.0)")
|
|
||||||
sc.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(1,'P1','C1',?,?,?)",
|
|
||||||
[(2.0, 0, '机上人工'), (2.0, 1, '机上人工'), (2.0, 2, '机上人工')])
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(1,'P1','C2',1.5,3,'柴油')")
|
|
||||||
sc.commit()
|
|
||||||
r = srv._lme_res(sc, srv.TBL["session"], SID, "P1")
|
|
||||||
assert [x[0] for x in r["rows"]] == ["C1", "C2"]
|
|
||||||
assert r["rows"][0][5] == 2.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_dedupe_lme_res_key_drops_qty_seq():
|
|
||||||
"""同码不同 seq 的重复套(旧键删不掉)→ 自愈后只留 1 行;不同码不受影响。"""
|
|
||||||
sc = _mk_sc()
|
|
||||||
sc.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(1,'P1',?,?,?,?)",
|
|
||||||
[("C1", 2.0, 0, "机上人工"), ("C1", 2.0, 1, "机上人工"),
|
|
||||||
("C1", 2.0, 2, "机上人工"), ("C2", 1.5, 3, "柴油")])
|
|
||||||
sc.commit()
|
|
||||||
sj.dedupe_lme_res(sc)
|
|
||||||
n = sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=1 AND p_code='P1'").fetchone()[0]
|
|
||||||
assert n == 2
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE res_code='C1'").fetchone()[0] == 1
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 243「源」防回归:工料机来源追溯(api_lme_src/_lme_src)。
|
|
||||||
|
|
||||||
钉死四件事:
|
|
||||||
①会话侧直挂:数量=含量×定额量(_norm_qty 公式优先/存储量兜底),聚合到清单粒度;
|
|
||||||
②台班/配合比传导一层:数量=定额中台班量 × 台班里本码含量 × 定额量;
|
|
||||||
③合计=各行数量之和(前端浮层底部「总数量」取同一组行求和);
|
|
||||||
④批次库分支:bills 无 uw_name 列 → LEFT JOIN unit_works 取单位工程名称(列探测自动适配)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
T_SESS = srv.TBL["session"]
|
|
||||||
T_BATCH = srv.TBL["batch"]
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_session():
|
|
||||||
"""最小会话库:A4-1 清单(量 10)→ 甲定额(量 2,柴油 3/kg)→ 台班 TB1(0.5);
|
|
||||||
台班 TB1 子级含柴油 CY1(4)与机下人工 RG1(1);乙清单直挂 RG1 0.2。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
uw_name TEXT, Number TEXT, Name TEXT, Quantity REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT,
|
|
||||||
Number TEXT, Name TEXT, Quantity REAL, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.executemany("INSERT INTO s_bills VALUES(?,?,?,?,?,?,?)",
|
|
||||||
[(1, SID, 101, "2#楼", "A4-1", "浇筑清单", 10.0),
|
|
||||||
(2, SID, 102, "3#楼", "B7-2", "回填清单", 5.0)])
|
|
||||||
c.executemany("INSERT INTO s_norms VALUES(?,?,?,?,?, NULL)",
|
|
||||||
[(10, 1, "A4-1H", "浇筑定额", 2.0), # 定额量 2(无公式→存储量)
|
|
||||||
(11, 2, "B7-2H", "回填定额", 1.0)])
|
|
||||||
c.executemany("INSERT INTO s_norm_res VALUES(?,?,?,?)",
|
|
||||||
[(100, 10, "TB1", 0.5), # 甲定额用台班 0.5
|
|
||||||
(101, 11, "RG1", 0.2)]) # 乙清单直挂机下人工 0.2
|
|
||||||
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)",
|
|
||||||
[(SID, "TB1", "CY1", 4.0, 1, "柴油"), (SID, "TB1", "RG1", 1.0, 2, "机下人工")])
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def test_session_direct_and_relay():
|
|
||||||
"""①②③:柴油=纯传导(0.5×4×定额量2=4.0,一行);机下人工=直挂+传导合并到清单粒度
|
|
||||||
(乙清单 0.2×1.0=0.2;甲清单 0.5×1×2=1.0 → 两行合计 1.2)。"""
|
|
||||||
con = _mk_session()
|
|
||||||
d = srv._lme_src(con, T_SESS, SID, "CY1")
|
|
||||||
assert d["ok"] and d["total"] == 1
|
|
||||||
r = d["rows"][0]
|
|
||||||
assert (r["uw_name"], r["bid"], r["bill"]) == ("2#楼", 1, "A4-1 浇筑清单")
|
|
||||||
assert abs(r["qty"] - 4.0) < 1e-6 # 0.5(台班)×4(柴油含量)×2(定额量)
|
|
||||||
d2 = srv._lme_src(con, T_SESS, SID, "RG1")
|
|
||||||
m = {x["bid"]: x["qty"] for x in d2["rows"]}
|
|
||||||
assert abs(m[1] - 1.0) < 1e-6 and abs(m[2] - 0.2) < 1e-6
|
|
||||||
assert abs(sum(m.values()) - 1.2) < 1e-6 # 合计=行之和(弹框「总数量」同源)
|
|
||||||
|
|
||||||
|
|
||||||
def test_batch_branch_join_uworks():
|
|
||||||
"""④批次库分支:bills 无 uw_name 列 → join unit_works.Name 取单位工程名称;数量口径同款。"""
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
# 刻意**不建** bills.uw_name 列(镜像批次库 schema.sql 真实形态)
|
|
||||||
c.execute("""CREATE TABLE bills(id INTEGER PRIMARY KEY, batch_id INT, uw_id INT,
|
|
||||||
Number TEXT, Name TEXT, Quantity REAL)""")
|
|
||||||
c.execute("""CREATE TABLE unit_works(id INTEGER PRIMARY KEY, batch_id INT,
|
|
||||||
Number TEXT, Name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT,
|
|
||||||
Number TEXT, Name TEXT, Quantity REAL, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL)""")
|
|
||||||
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.executemany("INSERT INTO unit_works VALUES(?,?,?,?)",
|
|
||||||
[(101, 1, "UW1", "南屏-土建"), (102, 1, "UW2", "南屏-安装")])
|
|
||||||
c.executemany("INSERT INTO bills VALUES(?,?,?,?,?,?)",
|
|
||||||
[(1, 1, 101, "A4-1", "浇筑清单", 10.0),
|
|
||||||
(2, 1, 102, "B7-2", "回填清单", 5.0)])
|
|
||||||
c.executemany("INSERT INTO norms VALUES(?,?,?,?,?, NULL)",
|
|
||||||
[(10, 1, "A4-1H", "浇筑定额", 2.0), (11, 2, "B7-2H", "回填定额", 1.0)])
|
|
||||||
c.executemany("INSERT INTO norm_res VALUES(?,?,?,?)",
|
|
||||||
[(100, 10, "TB1", 0.5), (101, 11, "RG1", 0.2)])
|
|
||||||
c.executemany("INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)",
|
|
||||||
[(1, "TB1", "CY1", 4.0, 1, "柴油")])
|
|
||||||
sc.commit()
|
|
||||||
d = srv._lme_src(sc, T_BATCH, 1, "CY1") # batch_id=1
|
|
||||||
assert d["ok"] and d["total"] == 1
|
|
||||||
r = d["rows"][0]
|
|
||||||
assert r["uw_name"] == "南屏-土建" # join unit_works 取名成功
|
|
||||||
assert abs(r["qty"] - 4.0) < 1e-6
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""原数据·单位工程级工料机汇总防回归(决策 41,2026-10-11 主人定)。
|
|
||||||
|
|
||||||
口径:优先直读本单位工程自己的工料机汇总节点(s_lme_uw / lme_uw,解析时按 uw 归属
|
|
||||||
原样入库)——名称/规格/总数量/单价=源文件原样,返回 src='summary';老会话/老批次没有
|
|
||||||
这张表的数据 → 回退"清单→定额→消耗量"归集口径(src='agg'),行为与从前一致。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_sess(with_summary):
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("CREATE TABLE sessions(id INTEGER PRIMARY KEY, name TEXT, src_name TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
section_id INT, Number TEXT, Name TEXT, Total REAL, Specialty TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
Number TEXT, Name TEXT, Specification TEXT, Unit TEXT, Kind INT,
|
|
||||||
NoTaxPrice REAL, TaxPrice REAL)""")
|
|
||||||
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
Number TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT, x_side TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL)""")
|
|
||||||
c.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
|
|
||||||
c.execute("INSERT INTO s_unit_works VALUES(10, 1, NULL, 'UW-1', '土建单位工程', 100, '建筑')")
|
|
||||||
if with_summary:
|
|
||||||
# 源文件汇总节点原样:总数量 50.5825(归集 SUM 只会算出别的数)
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind,
|
|
||||||
qty, ntp, taxrate, taxp)
|
|
||||||
VALUES(1, 10, '05010002', '普通硅酸盐水泥', 'P.O42.5', 'kg', 2,
|
|
||||||
50.5825, 0.38, NULL, 0.4104)""")
|
|
||||||
else:
|
|
||||||
c.execute("INSERT INTO s_lmes VALUES(1, 1, '05010002', '普通硅酸盐水泥', '', 'kg', 2, 0.38, 0.4104)")
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(1, 1, 10, 'B1')")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(1, 1, 1, NULL)")
|
|
||||||
c.execute("INSERT INTO s_norm_res VALUES(1, 1, '05010002', 33.5)")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def test_summary_source_preferred():
|
|
||||||
sc = _mk_sess(with_summary=True)
|
|
||||||
d = srv._raw_uw(sc, srv.TBL["session"], 10, "lme")
|
|
||||||
assert d["src"] == "summary"
|
|
||||||
r = d["rows"][0]
|
|
||||||
assert r[0] == "05010002" and r[1] == "普通硅酸盐水泥" and r[5] == 50.5825 # 总数量=源文件原样
|
|
||||||
assert d["uw"]["Name"] == "土建单位工程"
|
|
||||||
|
|
||||||
|
|
||||||
def test_agg_fallback_without_summary():
|
|
||||||
sc = _mk_sess(with_summary=False)
|
|
||||||
d = srv._raw_uw(sc, srv.TBL["session"], 10, "lme")
|
|
||||||
assert d["src"] == "agg"
|
|
||||||
assert d["rows"][0][0] == "05010002" and d["rows"][0][5] == 33.5 # 归集 SUM(qty)
|
|
||||||
@@ -1,430 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 231(2026-10-27 主人定):经典整件骨架库 + 手工工程导出(cos4/cos/Excel)回归。
|
|
||||||
|
|
||||||
口径:①公共上传口自动收骨架(后台导入与工作台打开工程同口,失败不挡上传);
|
|
||||||
②同签名只存最全代表(不一定最新,平手取最新,不跨件拼合),连保留值存 history.db;
|
|
||||||
③手工导出 cos/cos4=骨架整件当模板:参考清单行全换我方、**有采纳定额/工料机挂真实值
|
|
||||||
(231 补记:和标准采纳一样)、未采纳清单=我方五值+无定额(补记十五推翻克隆架子清值)**、
|
|
||||||
我方分部层级递归映射 DivisionalWorks 嵌套、单位/单项/工程名落我方(引用 Number 不动)、
|
|
||||||
工料机汇总=现算行挂真/无采纳空槽、容器/单位合计现算、其余保留值;
|
|
||||||
④Excel 导出=项目名文件夹/单位工程.xlsx(230 模板架子+合价/备注),可直接回导入;
|
|
||||||
⑤普通工程导出路径不受影响(fmt 缺省照旧走原格式引擎)。
|
|
||||||
造数仅写隔离副本(api_harness 临时目录),生产库零接触。"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from api_harness import PERIOD_202607, get, post, server # noqa: F401 (夹具)
|
|
||||||
from test_api_p1 import raw_post
|
|
||||||
|
|
||||||
# ---------------- 造「原生感」骨架 cos4:两级分部嵌套+样板清单(费用构成+定额+工料机架子) ----------------
|
|
||||||
SKEL_UNIT = """<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<UnitWorks Number="UW1" Name="骨架单位工程A" DivisionalAndElementalWorks="8888.00" Preliminaries="1111.00" Total="9999.00">
|
|
||||||
<SummaryOfCost DivisionalAndElementalWorks="8888.00" Preliminaries="1111.00" Total="9999.00"/>
|
|
||||||
<DivisionalAndElementalWorks Total="8888.00">
|
|
||||||
<SummaryOfBasicCost Total="8888.00"/>
|
|
||||||
<DivisionalWorks Number="" Name="骨架一级分部" Total="8888.00" Quantity="0" TechnicalAndEconomicIndex="9.90" ChapterKind="4">
|
|
||||||
<SummaryOfBasicCost Total="8888.00"/>
|
|
||||||
<WorkElement Number="990101001001" Name="骨架清单甲" Attr="1.骨架特征" Unit="m2" Quantity="10.000" Price="100" Total="1000.00">
|
|
||||||
<SummaryOfBasicCost Total="1000.00"/>
|
|
||||||
<Norm Number="N1-1" Name="骨架定额" Unit="m3" Quantity="10.000" Price="80" Total="800.00">
|
|
||||||
<LabourMaterialsEquipmentsMachinesElement Number="000001" Name="骨架工料机" Quantity="1.500" Price="55" Total="82.50" Express="1.5"/>
|
|
||||||
</Norm>
|
|
||||||
</WorkElement>
|
|
||||||
<DivisionalWorks Number="" Name="骨架二级分部" Total="7888.00" Quantity="0" TechnicalAndEconomicIndex="8.80" ChapterKind="4">
|
|
||||||
<SummaryOfBasicCost Total="7888.00"/>
|
|
||||||
<WorkElement Number="990101001002" Name="骨架清单乙" Attr="" Unit="m3" Quantity="5.000" Price="50" Total="250.00">
|
|
||||||
<SummaryOfBasicCost Total="250.00"/>
|
|
||||||
<Norm Number="N1-2" Name="骨架定额2" Unit="m3" Quantity="5.000" Price="70" Total="350.00">
|
|
||||||
<LabourMaterialsEquipmentsMachinesElement Number="000002" Name="骨架工料机2" Quantity="2.000" Price="60" Total="120.00" Express="2"/>
|
|
||||||
</Norm>
|
|
||||||
</WorkElement>
|
|
||||||
</DivisionalWorks>
|
|
||||||
</DivisionalWorks>
|
|
||||||
</DivisionalAndElementalWorks>
|
|
||||||
<Preliminaries Total="1111.00">
|
|
||||||
<SummaryOfBasicCost Total="1111.00"/>
|
|
||||||
<UnitWorksPreliminaryWorkElement Number="990501001001" Name="骨架措施清单" Unit="项" Quantity="1.000" Price="1111" Total="1111.00">
|
|
||||||
<SummaryOfBasicCost Total="1111.00"/>
|
|
||||||
</UnitWorksPreliminaryWorkElement>
|
|
||||||
</Preliminaries>
|
|
||||||
<LabourMaterialsEquipmentsMachinesSummary Number="000009" Name="骨架汇总工料机" Specification="" Unit="工日" Kind="1" Quantity="99" NoTaxPrice="9" TaxPrice="10"/>
|
|
||||||
<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="骨架台班" Specification="" Unit="台班" Kind="7" Quantity="3" NoTaxPrice="500" TaxPrice="565">
|
|
||||||
<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="机上人工" Specification="" Unit="工日" Kind="1" Quantity="1" NoTaxPrice="9" TaxPrice="10"/>
|
|
||||||
</LabourMaterialsEquipmentsMachinesSummary>
|
|
||||||
</UnitWorks>"""
|
|
||||||
|
|
||||||
SKEL_PROJ = """<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<ConstructionProject Name="骨架工程项目" FileKind="1" BulidUnit="骨架建设单位">
|
|
||||||
<SectionalWorks Number="" Name="骨架单项工程" Total="9999.00">
|
|
||||||
<UnitWorks Number="UW1" Name="骨架单位工程A" Total="9999.00"/>
|
|
||||||
</SectionalWorks>
|
|
||||||
</ConstructionProject>"""
|
|
||||||
|
|
||||||
ROWS = [
|
|
||||||
["单位工程", "", "分部", "我方一级分部", "", "", "", ""],
|
|
||||||
["我方一级分部", "", "分部", "我方二级分部", "", "", "", ""],
|
|
||||||
["我方二级分部", "041001001001", "清单", "我方清单甲", "1.我方特征一2.我方特征二", "m²", 126.5, 385],
|
|
||||||
["我方一级分部", "011101001001", "清单", "我方清单乙", "", "m²", 88.4, 35.2],
|
|
||||||
]
|
|
||||||
PREL = [["安全文明施工费", "", "", "项", 1, 120000]]
|
|
||||||
T_JIA = round(126.5 * 385, 2) # 48702.5
|
|
||||||
T_YI = round(88.4 * 35.2, 2) # 3111.68
|
|
||||||
T_ITEM = round(T_JIA + T_YI, 2) # 一级分部/分部分项合计
|
|
||||||
|
|
||||||
|
|
||||||
def _zip_bytes(unit_xml, proj_xml):
|
|
||||||
bio = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(bio, "w", zipfile.ZIP_DEFLATED) as z:
|
|
||||||
z.writestr("@_UW1_骨架单位工程A.xml", unit_xml)
|
|
||||||
z.writestr("Project.xml", proj_xml)
|
|
||||||
return bio.getvalue()
|
|
||||||
|
|
||||||
|
|
||||||
def _skel_bytes():
|
|
||||||
return _zip_bytes(SKEL_UNIT, SKEL_PROJ)
|
|
||||||
|
|
||||||
|
|
||||||
def _seed_skeleton(server, fname="骨架样本T.cos4"):
|
|
||||||
"""补记十四:上传口不再收藏骨架——测试骨架走升级口(seed_frame)入库。"""
|
|
||||||
import sys as _sys
|
|
||||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
import tempfile
|
|
||||||
p = os.path.join(server["src_dir"], fname)
|
|
||||||
open(p, "wb").write(_skel_bytes())
|
|
||||||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
|
||||||
try:
|
|
||||||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
return {"ok": True}
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_xlsx(server, fname="unit_export_t.xlsx"):
|
|
||||||
from openpyxl import Workbook
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = "分部分项"
|
|
||||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
for r in ROWS:
|
|
||||||
ws.append(r)
|
|
||||||
ws2 = wb.create_sheet("措施项目")
|
|
||||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
for r in PREL:
|
|
||||||
ws2.append(r)
|
|
||||||
p = str(server["src_dir"] / fname)
|
|
||||||
wb.save(p)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
_mk_last = {"name": None} # 最近一次 _create_manual 的工程名(自增唯一,决策 242)
|
|
||||||
_mk_seq = [0]
|
|
||||||
|
|
||||||
|
|
||||||
def _create_manual(server, name=None):
|
|
||||||
# 决策 242:同名创建一律拒绝(session 级共享服务夹具,默认名必须唯一)
|
|
||||||
_mk_seq[0] += 1
|
|
||||||
f1 = _mk_xlsx(server)
|
|
||||||
_mk_last["name"] = name or ("我方手工工程T%d" % _mk_seq[0])
|
|
||||||
r = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": _mk_last["name"], "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "我方单项工程",
|
|
||||||
"units": [{"id": 0, "name": "我方单位工程", "file": f1}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["session_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def _unit_xml_of(data):
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(data))
|
|
||||||
for nm in z.namelist():
|
|
||||||
if nm.lower().endswith(".xml"):
|
|
||||||
txt = z.read(nm).decode("utf-8")
|
|
||||||
body = re.sub(r"^.*?\?>", "", txt, count=1, flags=re.S).lstrip()
|
|
||||||
if body.startswith("<UnitWorks"):
|
|
||||||
return body, z.read("Project.xml").decode("utf-8")
|
|
||||||
raise AssertionError("导出件里没有单位工程成员")
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_auto_collect_and_seed_only(server):
|
|
||||||
"""补记十四:上传口**不再收藏骨架**(classic_skel 只有升级进的骨架);
|
|
||||||
升级口 seed_frame 同名替换、新名新增。"""
|
|
||||||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
|
||||||
try:
|
|
||||||
assert raw_post(server, "/api/admin/upload", "普通件.cos4", _skel_bytes())["ok"]
|
|
||||||
n = con.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='classic_skel'").fetchone()[0]
|
|
||||||
assert n == 0, "上传口不该再收藏任何骨架(表都不该建)"
|
|
||||||
import sys as _sys
|
|
||||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
p = os.path.join(server["src_dir"], "升骨架T.cos4")
|
|
||||||
open(p, "wb").write(_skel_bytes())
|
|
||||||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM classic_skel WHERE is_frame=1").fetchone()[0] == 1
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
def test_export_meta_manual(server):
|
|
||||||
"""meta:手工工程 fmt=cos4/cos/xlsx 给建议名;不带 fmt 明确报错(不再误导补传)。"""
|
|
||||||
sid = _create_manual(server)
|
|
||||||
c = server["client"]
|
|
||||||
j = c.get("/api/session/export/meta", params={"session_id": sid, "fmt": "cos4"}).json()
|
|
||||||
assert j["ok"] is True and j["name"] == _mk_last["name"] + "-审核版.cos4", j
|
|
||||||
j = c.get("/api/session/export/meta", params={"session_id": sid, "fmt": "xlsx"}).json()
|
|
||||||
assert j["ok"] is True and j["name"] == _mk_last["name"] + "-审核版.zip", j
|
|
||||||
j = c.get("/api/session/export/meta", params={"session_id": sid}).json()
|
|
||||||
assert j["ok"] is False and "格式" in j["msg"], j
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_cos4(server):
|
|
||||||
"""cos4 导出全口径:我方行进、骨架行清、架子值零、分部嵌套、名字落位、引用 Number 不动。"""
|
|
||||||
_seed_skeleton(server)
|
|
||||||
sid = _create_manual(server)
|
|
||||||
r = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
cd = r.headers.get("Content-Disposition", "")
|
|
||||||
assert "cos4" in cd, cd
|
|
||||||
unit, proj = _unit_xml_of(r.content)
|
|
||||||
|
|
||||||
# ① 骨架的清单/措施不残留;我方清单在
|
|
||||||
assert "骨架清单甲" not in unit and "骨架清单乙" not in unit and "骨架措施清单" not in unit
|
|
||||||
assert "我方清单甲" in unit and "我方清单乙" in unit and "安全文明施工费" in unit
|
|
||||||
# ② 我方分部层级=DivisionalWorks 嵌套(一级含二级)
|
|
||||||
m1 = re.search(r'<DivisionalWorks\b[^>]*Name="我方一级分部"[^>]*>', unit)
|
|
||||||
assert m1, "我方一级分部没落位"
|
|
||||||
e1 = unit.index("</DivisionalWorks>", m1.end())
|
|
||||||
assert re.search(r'<DivisionalWorks\b[^>]*Name="我方二级分部"', unit[m1.end():e1]), \
|
|
||||||
"子分部没有嵌套在一级分部里"
|
|
||||||
assert 'Total="%.2f"' % T_ITEM in m1.group(0), "一级分部合计没现算"
|
|
||||||
# ③ 未采纳清单(补记十五,主人定「分部/清单/定额/工料机全按自己的值,不用骨架值
|
|
||||||
# 兜底」——推翻克隆架子清值):我方五值照出、**无定额**(骨架样例定额不进)
|
|
||||||
m3 = unit.index("我方清单甲")
|
|
||||||
e3 = unit.index("</WorkElement>", m3)
|
|
||||||
seg = unit[m3:e3]
|
|
||||||
assert "<Norm " not in seg, "未采纳清单不该带(骨架样例)定额"
|
|
||||||
assert "126.5" in seg, "我方工程量没照出"
|
|
||||||
# ④ 单位级工料机汇总(补记五:根层 LME_SUM=汇总行):无采纳=无现算行
|
|
||||||
# → 骨架行全撤(架子在、行不进);骨架的行名不残留
|
|
||||||
assert "骨架汇总工料机" not in unit and "骨架台班" not in unit
|
|
||||||
# ⑤ 单位/单项/工程名落我方;合计现算;引用节点 Number 不动
|
|
||||||
assert 'Name="我方单位工程"' in unit and "骨架单位工程A" not in unit
|
|
||||||
assert ('DivisionalAndElementalWorks="%.2f"' % T_ITEM) in unit
|
|
||||||
assert 'Preliminaries="120000.00"' in unit
|
|
||||||
assert ('Name="%s"' % _mk_last["name"]) in proj and 'Name="我方单项工程"' in proj
|
|
||||||
assert '<UnitWorks Number="UW1" Name="我方单位工程"' in proj
|
|
||||||
# ⑥ 保留值:骨架的取费类工程级信息留着(SummaryOfCost Total 等未动)
|
|
||||||
assert 'BulidUnit="骨架建设单位"' in proj
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_without_skeleton(server):
|
|
||||||
"""该后缀没收过骨架:明确报错提示先导入原件(fail-closed)。cos 全程不充库。"""
|
|
||||||
sid = _create_manual(server, "无骨架工程T")
|
|
||||||
r = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "cos"})
|
|
||||||
assert r.status_code == 200
|
|
||||||
j = r.json()
|
|
||||||
assert j["ok"] is False and "经典骨架" in j["msg"], j
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_xlsx_roundtrip(server):
|
|
||||||
"""Excel 导出:项目名文件夹/单位工程.xlsx,模板架子+合价/备注;可直接回导入。"""
|
|
||||||
sid = _create_manual(server)
|
|
||||||
r = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "xlsx"})
|
|
||||||
assert r.status_code == 200
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(r.content))
|
|
||||||
names = z.namelist()
|
|
||||||
assert names and names[0].split("/")[0] == _mk_last["name"], names
|
|
||||||
xname = [n for n in names if n.endswith(".xlsx")][0]
|
|
||||||
assert xname == _mk_last["name"] + "/我方单位工程.xlsx", xname
|
|
||||||
from openpyxl import load_workbook
|
|
||||||
wb = load_workbook(io.BytesIO(z.read(xname)))
|
|
||||||
ws = wb["分部分项"]
|
|
||||||
assert wb.sheetnames == ["分部分项", "措施项目"], wb.sheetnames # 2026-11-03 主人定:填写说明去除
|
|
||||||
head = [c.value for c in ws[1]]
|
|
||||||
assert head == ["序号", "上一级名称", "编码", "类型", "名称", "项目特征", "单位",
|
|
||||||
"工程量", "单价", "合价", "备注"], head
|
|
||||||
rows = [list(r) for r in ws.iter_rows(min_row=2, values_only=True)]
|
|
||||||
jia = next(r for r in rows if r[4] == "我方清单甲")
|
|
||||||
assert jia[3] == "清单" and jia[2] == "041001001001"
|
|
||||||
assert jia[0] == 2, "清单行序号(树序跨分部连续:乙=1、甲=2,2026-11-03)"
|
|
||||||
assert abs(jia[7] * jia[8] - T_JIA) < 0.01 and abs(jia[9] - T_JIA) < 0.01, "合价没现算"
|
|
||||||
er = next(r for r in rows if r[4] == "我方二级分部")
|
|
||||||
assert er[1] == "我方一级分部" and er[3] == "分部" and er[0] in (None, ""), "分部行序号留空"
|
|
||||||
ws2 = wb["措施项目"]
|
|
||||||
assert [c.value for c in ws2[1]] == ["序号", "名称", "编码", "项目特征", "单位",
|
|
||||||
"工程量", "单价", "合价", "备注"]
|
|
||||||
# 回导入自查:多出的合价/备注列解析端忽略,整份通过且行数对上
|
|
||||||
p = server["src_dir"] / "roundtrip_t.xlsx"
|
|
||||||
p.write_bytes(z.read(xname))
|
|
||||||
j = post(server, "/api/session/manual/parse", {"path": str(p)})
|
|
||||||
assert j["ok"] is True, j
|
|
||||||
assert (j["n_div"], j["n_item"], j["n_prelim"]) == (2, 2, 1), j
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_unit_single(server):
|
|
||||||
"""决策 233 方案a(2026-10-28 主人定):单单位工程导 xlsx——与 231 Excel 通道同一
|
|
||||||
_unit_workbook 产出(同架子同数据逐格全等),文件名=单位工程名.xlsx,可回导。"""
|
|
||||||
sid = _create_manual(server)
|
|
||||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
uw = st["sections"][0]["units"][0]["id"]
|
|
||||||
r = server["client"].get("/api/session/manual/export_unit",
|
|
||||||
params={"session_id": sid, "uw": uw})
|
|
||||||
assert r.status_code == 200
|
|
||||||
cd = r.headers.get("Content-Disposition", "")
|
|
||||||
from urllib.parse import unquote
|
|
||||||
assert "filename*=UTF-8''" in cd and unquote(cd.split("filename*=UTF-8''", 1)[1]) == "我方单位工程.xlsx", cd
|
|
||||||
from openpyxl import load_workbook
|
|
||||||
wb = load_workbook(io.BytesIO(r.content))
|
|
||||||
assert wb.sheetnames == ["分部分项", "措施项目"] # 2026-11-03 主人定:填写说明去除
|
|
||||||
rows = [list(x) for x in wb["分部分项"].iter_rows(min_row=2, values_only=True)]
|
|
||||||
jia = next(x for x in rows if x[4] == "我方清单甲")
|
|
||||||
assert jia[2] == "041001001001" and abs(jia[9] - T_JIA) < 0.01, "合价没现算"
|
|
||||||
# 与 231 整包 zip 里同一单位工程逐格全等(共用 _unit_workbook)
|
|
||||||
rz = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "xlsx"})
|
|
||||||
assert rz.status_code == 200
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(rz.content))
|
|
||||||
zname = [n for n in z.namelist() if n.endswith(".xlsx")][0]
|
|
||||||
wbz = load_workbook(io.BytesIO(z.read(zname)))
|
|
||||||
assert wbz.sheetnames == wb.sheetnames
|
|
||||||
for sn in wb.sheetnames:
|
|
||||||
a = [[c.value for c in row] for row in wb[sn].iter_rows()]
|
|
||||||
b = [[c.value for c in row] for row in wbz[sn].iter_rows()]
|
|
||||||
assert a == b, "单导与 231 整包不一致:%s" % sn
|
|
||||||
# 回导自查:单文件直接过预检
|
|
||||||
p = server["src_dir"] / "unit_single_t.xlsx"
|
|
||||||
p.write_bytes(r.content)
|
|
||||||
assert post(server, "/api/session/manual/parse", {"path": str(p)})["ok"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_unit_guards(server):
|
|
||||||
"""守卫(决策 233):空单位工程提示不产文件;uw/会话不存在 400;源文件工程拒绝。"""
|
|
||||||
from api_harness import META, fixture_file
|
|
||||||
f1 = _mk_xlsx(server, "单导守卫.xlsx")
|
|
||||||
r = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": "单导守卫T", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "单项G",
|
|
||||||
"units": [{"id": 0, "name": "有数据单位", "file": f1},
|
|
||||||
{"id": 0, "name": "空单位"}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
us = get(server, "/api/session/manual/state", session_id=sid)["sections"][0]["units"]
|
|
||||||
full = next(u for u in us if u["name"] == "有数据单位")
|
|
||||||
empty = next(u for u in us if u["name"] == "空单位")
|
|
||||||
c = server["client"]
|
|
||||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": empty["id"]})
|
|
||||||
assert j.status_code == 400 and "还没有清单数据" in j.text
|
|
||||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": 999999})
|
|
||||||
assert j.status_code == 400 and "不存在" in j.text
|
|
||||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid + 99999, "uw": full["id"]})
|
|
||||||
assert j.status_code == 400
|
|
||||||
pa = fixture_file(server, "单导源件.cos4", "单导源工程T",
|
|
||||||
[("041001001001", "源件清单", "", "m²", 10, 100)])
|
|
||||||
src = post(server, "/api/audit", dict(META, path=str(pa), name="单导源工程T"))["session_id"]
|
|
||||||
j = c.get("/api/session/manual/export_unit", params={"session_id": src, "uw": full["id"]})
|
|
||||||
assert j.status_code == 400 and "手工工程" in j.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_unit_clone(server):
|
|
||||||
"""骨架单位位自由复制(主人 2026-10-28 定「单位工程多少不影响骨架,1000 个都可以」):
|
|
||||||
工程单位数 > 骨架位 → 克隆骨架单位成员补位;项目成员引用行顺延;新条目名按 GBK 字节
|
|
||||||
写、不打 UTF-8 旗标(乱码教训)。"""
|
|
||||||
_seed_skeleton(server)
|
|
||||||
f1 = _mk_xlsx(server)
|
|
||||||
r = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": "我方多单位工程T", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
|
||||||
{"id": 0, "name": "我方单位一", "file": f1},
|
|
||||||
{"id": 0, "name": "我方单位二", "file": f1},
|
|
||||||
{"id": 0, "name": "我方单位三", "file": f1}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
assert resp.status_code == 200, resp.text[:200]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
infos = [i for i in z.infolist() if i.filename.lower().endswith(".xml")]
|
|
||||||
assert len(infos) == 4, [i.filename for i in infos] # 1 骨架位 + 2 克隆 + Project
|
|
||||||
# 决策 259/260:全部成员名=我方单位名(骨架造名不保留);条目名 GBK 字节、无旗标。
|
|
||||||
# 例外:fixture 骨架首槽的引用行无 FileName(简化骨架形态)→ 该成员保持原名原旗标
|
|
||||||
# (真实骨架引用行均带 FileName,会正常改名为我方单位名)。
|
|
||||||
units = [i for i in infos if "Project" not in i.filename]
|
|
||||||
assert len(units) == 3, [i.filename for i in units]
|
|
||||||
for i in units:
|
|
||||||
nm_gbk = i.filename.encode("cp437").decode("gbk") if not (i.flag_bits & 0x800) \
|
|
||||||
else i.filename
|
|
||||||
if "_UW1_" in i.filename:
|
|
||||||
assert i.flag_bits & 0x800 or True # fixture 首槽:保留原样(名/旗标不动)
|
|
||||||
root = ET.fromstring(z.read(i.filename))
|
|
||||||
assert root.tag == "UnitWorks"
|
|
||||||
assert "我方清单甲" in z.read(i.filename).decode("utf-8")
|
|
||||||
continue
|
|
||||||
assert not (i.flag_bits & 0x800), "克隆成员条目名被打上 UTF-8 旗标"
|
|
||||||
assert re.match(r"@_\d+_我方单位[二三]\.xml$", nm_gbk), nm_gbk
|
|
||||||
root = ET.fromstring(z.read(i.filename))
|
|
||||||
assert root.tag == "UnitWorks"
|
|
||||||
assert "我方清单甲" in z.read(i.filename).decode("utf-8")
|
|
||||||
# 成员内 Name=对应我方单位名(改名后名实一致)
|
|
||||||
nm_by_name = {(i.filename if (i.flag_bits & 0x800) else i.filename.encode("cp437").decode("gbk")):
|
|
||||||
ET.fromstring(z.read(i.filename)).get("Name") for i in units}
|
|
||||||
for k, v in nm_by_name.items():
|
|
||||||
if "_UW1_" in k:
|
|
||||||
continue # fixture 首槽(引用行无 FileName):文件名保留原样,名实一致在后续真实骨架验
|
|
||||||
assert ("_" + v) in k, (k, v)
|
|
||||||
# 项目成员引用行:3 条、名称齐、克隆行带新成员文件名
|
|
||||||
proj = z.read("Project.xml").decode("utf-8")
|
|
||||||
refs = re.findall(r'<UnitWorks\b[^>]*>', proj)
|
|
||||||
names = [re.search(r'Name="([^"]*)"', x).group(1) for x in refs]
|
|
||||||
assert names == ["我方单位一", "我方单位二", "我方单位三"], names
|
|
||||||
# 决策 259/260:引用行带 FileName 的,指向成员必须存在且为对应我方单位名成员
|
|
||||||
for x in refs:
|
|
||||||
fn = re.search(r'FileName="([^"]*)"', x)
|
|
||||||
if not fn:
|
|
||||||
continue # fixture 简化形态:无 FileName 的引用行只校验 Name(上方已断)
|
|
||||||
nm_gbk = fn.group(1).encode("gbk").decode("cp437")
|
|
||||||
assert nm_gbk in [i.filename for i in infos], x
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_export_tree_reorder(server):
|
|
||||||
"""目录树里上下移动单位后,导出引用行序=移动后的目录序(2026-10-28 主人定通用口径:
|
|
||||||
单项/单位排序以项目目录先有顺序为准——手工树保存时按组内位置重写编号持久化顺序,
|
|
||||||
导出端按「单项入库序+组内编号自然序」取,不能按物理 id)。"""
|
|
||||||
_seed_skeleton(server)
|
|
||||||
f1 = _mk_xlsx(server)
|
|
||||||
r = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
|
||||||
{"id": 0, "name": "单位甲", "file": f1},
|
|
||||||
{"id": 0, "name": "单位乙", "file": None}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
|
|
||||||
ids = [row[0] for row in con.execute(
|
|
||||||
"SELECT id FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,))]
|
|
||||||
con.close()
|
|
||||||
assert len(ids) == 2
|
|
||||||
r = post(server, "/api/session/manual/save", # 树里把两单位对调(带 id 保留数据)
|
|
||||||
{"sid": sid, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
|
||||||
{"id": ids[1], "name": "单位乙", "file": None},
|
|
||||||
{"id": ids[0], "name": "单位甲", "file": None}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": "cos4"})
|
|
||||||
assert resp.status_code == 200, resp.text[:200]
|
|
||||||
proj = zipfile.ZipFile(io.BytesIO(resp.content)).read("Project.xml").decode("utf-8")
|
|
||||||
names = [re.search(r'Name="([^"]*)"', x).group(1)
|
|
||||||
for x in re.findall(r"<UnitWorks\b[^>]*>", proj)]
|
|
||||||
ours_idx = [i for i, n in enumerate(names) if n in ("单位乙", "单位甲")]
|
|
||||||
assert ours_idx == sorted(ours_idx), names
|
|
||||||
assert names.index("单位乙") < names.index("单位甲"), \
|
|
||||||
"移动后导出序没跟目录序:单位乙应排在单位甲前,实际 %s" % names[:4]
|
|
||||||
@@ -1,378 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 231 补记·双路对拍(主人类比实证:「采纳的刚刚好是一个项目的清单,且分部与顺序相同,
|
|
||||||
导出 cos 后清单分部定额及工料机这部分的信息是一样的;其他因为骨架选取不同会导致
|
|
||||||
不计价信息不一样」)。
|
|
||||||
|
|
||||||
真实件(三溪科创小镇…易达导出.COS,真实易达件、现算口径已在决策 196/179 对拍归零)走两条路:
|
|
||||||
a 路=.cos4 直接打开(标准导入)→ 原格式导出(export_cos 专用引擎);
|
|
||||||
b 路=Excel 导入(清单级架子)→ 对比框同款逐条采纳 → 经典骨架导出(export_manual)。
|
|
||||||
断言:**计价信息全等**——清单五值(编码/名称/单位/量/价/合价)、每条清单的定额集
|
|
||||||
(编码/名称/单位/量/价/合价)、单位工料机汇总(码/量/除税/含税,量 0 行按决策 199 两路同滤);
|
|
||||||
不计价信息(建设单位/取费等骨架保留值)允许不同。
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
from pathlib import Path
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from api_harness import META, PERIOD_202607, post, server # noqa: F401 (夹具)
|
|
||||||
from test_api_p1 import raw_post
|
|
||||||
from test_manual_export_real import _parse_original
|
|
||||||
|
|
||||||
REAL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS"
|
|
||||||
FMT = "cos"
|
|
||||||
|
|
||||||
|
|
||||||
def _f(v, r=6):
|
|
||||||
try:
|
|
||||||
return round(float(v), r)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not REAL.exists(), reason="真实件不在本机")
|
|
||||||
def test_dual_path_identical_pricing(server):
|
|
||||||
data = REAL.read_bytes()
|
|
||||||
up = raw_post(server, "/api/admin/upload", REAL.name, data)
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
# 补记十四:上传不再收藏——导出模板走升级口入库(本测用真实件当模板)
|
|
||||||
import sys as _sys
|
|
||||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
_con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
|
||||||
try:
|
|
||||||
assert _cs.seed_frame(_con, str(REAL), "COS4骨架双路T")
|
|
||||||
finally:
|
|
||||||
_con.close()
|
|
||||||
# ---- a 路:直接打开(标准会话;导出在双会话采纳之后做,对照才纯净)----
|
|
||||||
r = post(server, "/api/audit", {"path": up["path"], "name": "双路甲",
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid_a = r["session_id"]
|
|
||||||
# ---- b 路前置:批次入库(采纳来源)+ Excel 手工工程 ----
|
|
||||||
# 决策 243:同一份文件前后台只能存在一边——来源批次用同内容双胞胎件入库
|
|
||||||
import api_harness as H
|
|
||||||
rb = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=H.twin_file(server, up["path"], "dual_b"),
|
|
||||||
name="双路来源批次", file_kind=1))
|
|
||||||
assert rb["ok"] is True, rb
|
|
||||||
bid = rb["batch_id"]
|
|
||||||
out = _parse_original(REAL)
|
|
||||||
assert out["uw"], "原件没解析出单位工程"
|
|
||||||
# 该件没有分部层(清单直挂单位工程)——230 挂接法要求清单挂分部下,
|
|
||||||
# b 路套一个合成根分部(对拍只比计价信息,分部骨架差异不在断言内)
|
|
||||||
from openpyxl import Workbook
|
|
||||||
|
|
||||||
def unit_xlsx(i, uw):
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = "分部分项"
|
|
||||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
ws.append(["单位工程", "", "分部", "清单汇总", "", "", "", ""])
|
|
||||||
for bi, b in enumerate(out["bills"]):
|
|
||||||
if out["bill_uw"][bi] != i or out["bill_kind"][bi] == "prelim":
|
|
||||||
continue
|
|
||||||
ws.append(["清单汇总", b[0] or "", "清单", b[1] or "", b[2] or "",
|
|
||||||
b[3] or "", _f(b[4]) or 0, _f(b[5]) or 0])
|
|
||||||
ws2 = wb.create_sheet("措施项目")
|
|
||||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
for bi, b in enumerate(out["bills"]):
|
|
||||||
if out["bill_uw"][bi] != i or out["bill_kind"][bi] != "prelim":
|
|
||||||
continue
|
|
||||||
ws2.append([b[1] or "", b[0] or "", b[2] or "", b[3] or "",
|
|
||||||
_f(b[4]) or 0, _f(b[5]) or 0])
|
|
||||||
p = server["src_dir"] / ("dual_uw%d.xlsx" % i)
|
|
||||||
wb.save(p)
|
|
||||||
return str(p)
|
|
||||||
|
|
||||||
units = []
|
|
||||||
for i, uw in enumerate(out["uw"]):
|
|
||||||
units.append({"id": 0, "name": uw[1] or ("单位工程%d" % (i + 1)),
|
|
||||||
"file": unit_xlsx(i, uw)})
|
|
||||||
sec0 = (out.get("sections") or [None])[0]
|
|
||||||
sec_name = (sec0[1] if isinstance(sec0, (tuple, list)) and sec0[1] else "单项工程")
|
|
||||||
rm = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": "双路乙", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": sec_name, "units": units}]})
|
|
||||||
assert rm["ok"] is True, rm
|
|
||||||
sid_b = rm["session_id"]
|
|
||||||
# ---- 配对 + 双会话逐条采纳(对比框同款语义,决策 68/9.x/227 全套沿用)----
|
|
||||||
# a 路(标准会话)也采纳同一批:对照才纯净——两边定额值同源于同一套 GCL 公式求值,
|
|
||||||
# 采纳系数的浮点微漂两边一致,导出对比即「写法差异之外应逐位一致」
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
buw = {r["id"]: i for i, r in enumerate(con.execute(
|
|
||||||
"SELECT id FROM unit_works WHERE batch_id=? ORDER BY id", (bid,)))}
|
|
||||||
batch = {}
|
|
||||||
for r in con.execute("SELECT id, uw_id, Number, Name FROM bills WHERE batch_id=?",
|
|
||||||
(bid,)):
|
|
||||||
batch[(buw.get(r["uw_id"], -1), r["Number"] or "", r["Name"] or "")] = r["id"]
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
cs = sqlite3.connect(server["sessdb"])
|
|
||||||
cs.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
suw = {r["id"]: i for i, r in enumerate(cs.execute(
|
|
||||||
"SELECT id FROM s_unit_works WHERE session_id=? ORDER BY id", (sid_b,)))}
|
|
||||||
pos2id = {v: k for k, v in suw.items()} # 单位位 → s_unit_works.id(dyn 现算用)
|
|
||||||
sess = [(r["id"], suw.get(r["uw_id"], -1), r["Number"] or "", r["Name"] or "")
|
|
||||||
for r in cs.execute(
|
|
||||||
"SELECT id, uw_id, Number, Name FROM s_bills WHERE session_id=?",
|
|
||||||
(sid_b,))]
|
|
||||||
finally:
|
|
||||||
cs.close()
|
|
||||||
# ---- 逐条采纳进 b 路(对比框同款语义,决策 68/9.x/227 全套沿用)----
|
|
||||||
n_adopt = 0
|
|
||||||
for bill_id, uw_i, num, name in sess:
|
|
||||||
src = batch.get((uw_i, num, name))
|
|
||||||
assert src, "批次里找不到对应清单:%s" % ((uw_i, num, name),)
|
|
||||||
ra2 = post(server, "/api/session/bill/adopt",
|
|
||||||
{"session_id": sid_b, "bill_id": bill_id, "src_bill_id": src})
|
|
||||||
assert ra2["ok"] is True, ra2
|
|
||||||
n_adopt += 1
|
|
||||||
assert n_adopt > 0
|
|
||||||
# ---- 采纳落地状态=独立期望值(会话 s_norms + GCL 公式求值,与导出引擎无关)----
|
|
||||||
import dyn_lme as _dl # core 路径已由 _parse_original(_ij) 注入
|
|
||||||
expected = {} # (uw_pos, 清单编码, 清单名称) → [(定额4列+量价合)]
|
|
||||||
cs = sqlite3.connect(server["sessdb"])
|
|
||||||
cs.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
_cols = {x[1] for x in cs.execute("PRAGMA table_info(s_norms)")}
|
|
||||||
_has_expr = "qty_expr" in _cols
|
|
||||||
_ex = ", qty_expr" if _has_expr else ", NULL AS qty_expr"
|
|
||||||
for r in cs.execute("""SELECT b.uw_id, b.Number AS bnum, b.Name AS bname,
|
|
||||||
b.Quantity AS bqty, n.Number, n.Name, n.Unit,
|
|
||||||
n.Quantity, n.Price, n.Total, n.x_tdel
|
|
||||||
%s FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=?
|
|
||||||
AND (b.Kind IS NULL OR b.Kind<>'prelim')""" % _ex,
|
|
||||||
(sid_b,)):
|
|
||||||
if r["x_tdel"]:
|
|
||||||
continue
|
|
||||||
qty = r["Quantity"]
|
|
||||||
if _has_expr and r["qty_expr"]:
|
|
||||||
g = _dl.gcl_of(r["bqty"], r["Unit"])
|
|
||||||
v, _msg = _dl.eval_qty_expr(r["qty_expr"], g)
|
|
||||||
if v is not None:
|
|
||||||
# 决策 216:GCL=清单量原值,单位因子只在公式结果上最后除
|
|
||||||
qty = round(v / _dl.unit_factor(r["Unit"] or ""), 6)
|
|
||||||
tot = (round(qty * r["Price"], 2)
|
|
||||||
if qty is not None and r["Price"] is not None else r["Total"])
|
|
||||||
key = (suw.get(r["uw_id"], -1), r["bnum"] or "", r["bname"] or "")
|
|
||||||
expected.setdefault(key, []).append(
|
|
||||||
(r["Number"] or "", r["Name"] or "", (r["Unit"] or "").strip(),
|
|
||||||
_f(qty), _f(r["Price"]), _f(tot)))
|
|
||||||
finally:
|
|
||||||
cs.close()
|
|
||||||
for k in expected:
|
|
||||||
expected[k].sort()
|
|
||||||
# 消耗行期望(现算数据根,决策 98):采纳定额下的 s_norm_res 消耗量,按清单纯度分组
|
|
||||||
cons_expected = {}
|
|
||||||
cs2 = sqlite3.connect(server["sessdb"])
|
|
||||||
cs2.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
for r in cs2.execute("""SELECT b.uw_id, b.Number AS bnum, b.Name AS bname,
|
|
||||||
n.Number AS nnum, n.Name AS nname, nr.res_code, nr.qty
|
|
||||||
FROM s_norm_res nr JOIN s_norms n ON n.id=nr.norm_id
|
|
||||||
JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=? AND n.x_tdel=0
|
|
||||||
AND (b.Kind IS NULL OR b.Kind<>'prelim')""", (sid_b,)):
|
|
||||||
k = (suw.get(r["uw_id"], -1), r["bnum"] or "", r["bname"] or "",
|
|
||||||
r["nnum"] or "", r["nname"] or "")
|
|
||||||
cons_expected.setdefault(k, []).append((r["res_code"] or "", _f(r["qty"], 6)))
|
|
||||||
finally:
|
|
||||||
cs2.close()
|
|
||||||
for k in cons_expected:
|
|
||||||
cons_expected[k].sort()
|
|
||||||
# ---- 两路导出:a=标准引擎原件(未采纳,作清单/汇总参照);b=经典骨架(已采纳)----
|
|
||||||
ra = server["client"].get("/api/session/export", params={"session_id": sid_a})
|
|
||||||
assert ra.status_code == 200, ra.text[:200]
|
|
||||||
if os.environ.get("DEBUG_DUAL"):
|
|
||||||
Path(os.environ["DEBUG_DUAL"]).write_bytes(ra.content)
|
|
||||||
A = zipfile.ZipFile(io.BytesIO(ra.content))
|
|
||||||
rb2 = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid_b, "fmt": FMT})
|
|
||||||
assert rb2.status_code == 200, rb2.text[:300]
|
|
||||||
if os.environ.get("DEBUG_DUAL_B"):
|
|
||||||
Path(os.environ["DEBUG_DUAL_B"]).write_bytes(rb2.content)
|
|
||||||
B = zipfile.ZipFile(io.BytesIO(rb2.content))
|
|
||||||
|
|
||||||
# ---- 对拍:计价信息全等 ----
|
|
||||||
def members(z):
|
|
||||||
out, skipped = [], []
|
|
||||||
for nm in z.namelist():
|
|
||||||
if nm.lower().endswith(".xml"):
|
|
||||||
try:
|
|
||||||
body = ET.fromstring(z.read(nm))
|
|
||||||
except Exception as e:
|
|
||||||
skipped.append((nm[-30:], str(e)[:60]))
|
|
||||||
continue
|
|
||||||
if body.tag == "UnitWorks":
|
|
||||||
out.append(body)
|
|
||||||
return out, skipped
|
|
||||||
|
|
||||||
ma, skip_a = members(A)
|
|
||||||
mb, skip_b = members(B)
|
|
||||||
# a 路普通引擎在本件上存在**既有缺陷**(非本次改动范围:打开时主动拆码·决策 201 之后的
|
|
||||||
# 汇总同步产生碎标签,如 @_146_给水工程「<Labo<LabourMaterials…」)——跳过并如实计数
|
|
||||||
assert not skip_b, "b 路件有解析失败成员:%s" % skip_b
|
|
||||||
|
|
||||||
def bills(el):
|
|
||||||
out = sorted((b.get("Number") or "", b.get("Name") or "",
|
|
||||||
(b.get("Unit") or "").strip(), _f(b.get("Quantity")),
|
|
||||||
_f(b.get("Price")), _f(b.get("Total")))
|
|
||||||
for b in el.iter("WorkElement"))
|
|
||||||
return out
|
|
||||||
|
|
||||||
def bills_close(la, lb):
|
|
||||||
"""清单五值:编码/名称/单位/量/价全等;合价允许 0.011 容差——易达原生四舍五入
|
|
||||||
(7786.41)与软件标准 round(7786.40)在 5 厘边界差 1 分,标准采纳语义。"""
|
|
||||||
if len(la) != len(lb):
|
|
||||||
return False
|
|
||||||
for xa, xb in zip(la, lb):
|
|
||||||
if xa[:5] != xb[:5] or abs(xa[5] - xb[5]) > 0.011:
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def norms(el):
|
|
||||||
out = []
|
|
||||||
for b in el.iter("WorkElement"):
|
|
||||||
for n in b.iter("Norm"):
|
|
||||||
out.append((b.get("Number") or "", n.get("Number") or "",
|
|
||||||
n.get("Name") or "", (n.get("Unit") or "").strip(),
|
|
||||||
_f(n.get("Quantity")), _f(n.get("Price")), _f(n.get("Total"))))
|
|
||||||
return sorted(out)
|
|
||||||
|
|
||||||
def lme(el):
|
|
||||||
"""只取**直挂根**的汇总容器的直接子行(老 cos 行标签也叫 …Summary——
|
|
||||||
用 iter 会把定额里的消耗行全扫进来,三溪实测 2937 条污染)。"""
|
|
||||||
out = []
|
|
||||||
for s in el.findall("LabourMaterialsEquipmentsMachinesSummary"):
|
|
||||||
for r in s:
|
|
||||||
out.append((r.get("Number") or "", _f(r.get("Quantity"), 4),
|
|
||||||
_f(r.get("NoTaxPrice"), 4), _f(r.get("TaxPrice"), 4)))
|
|
||||||
return sorted(x for x in out if x[1] != 0) # 决策 199 量 0 不导:同口径
|
|
||||||
|
|
||||||
def norms_close(la, lb):
|
|
||||||
"""编码/名称/单位/单价全等;量/合价允许 0.1% 容差——采纳 GCL 公式求值的
|
|
||||||
浮点回程微漂(0.01→0.009999)是标准采纳自身语义,两路应同为该语义。"""
|
|
||||||
if len(la) != len(lb):
|
|
||||||
return False
|
|
||||||
for xa, xb in zip(la, lb):
|
|
||||||
if xa[:4] != xb[:4]:
|
|
||||||
return False
|
|
||||||
for i in (4, 5, 6):
|
|
||||||
if abs(xa[i] - xb[i]) > max(0.005, abs(xa[i]) * 0.001):
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
ma, skip_a = members(A)
|
|
||||||
mb, skip_b = members(B)
|
|
||||||
# a 路普通引擎在本件上存在**既有缺陷**(非本次改动范围:打开时主动拆码·决策 201 之后的
|
|
||||||
# 汇总同步产生碎标签,如 @_146_给水工程「<Labo<LabourMaterials…」)——跳过并如实计数
|
|
||||||
assert not skip_b, "b 路件有解析失败成员:%s" % skip_b
|
|
||||||
# 按单位工程名配对(跳过成员后顺序会错位)
|
|
||||||
na = {}
|
|
||||||
for ea in ma:
|
|
||||||
na[ea.get("Name") or ""] = ea
|
|
||||||
nb = {}
|
|
||||||
for eb in mb:
|
|
||||||
nb[eb.get("Name") or ""] = eb
|
|
||||||
compared = 0
|
|
||||||
for i, uw in enumerate(out["uw"]):
|
|
||||||
nm_uw = uw[1] or ("单位工程%d" % (i + 1))
|
|
||||||
ea, eb = na.get(nm_uw), nb.get(nm_uw)
|
|
||||||
if ea is None:
|
|
||||||
assert skip_a, "a 路缺成员 %s 且无解析失败记录" % nm_uw
|
|
||||||
continue
|
|
||||||
assert eb is not None, "b 路缺成员 %s" % nm_uw
|
|
||||||
ca = ea.find("DivisionalAndElementalWorks")
|
|
||||||
cb = eb.find("DivisionalAndElementalWorks")
|
|
||||||
assert ca is not None and cb is not None
|
|
||||||
assert bills_close(bills(ca), bills(cb)), "单位%s 清单五值不一致" % nm_uw
|
|
||||||
# 单位级工料机汇总(补记五口径:根层 LME_SUM=汇总行,易达标准骨架铁证)——
|
|
||||||
# 导出件根层行对照 dyn 现算(码/量/价,量 0 不导 199 同口径);台班子级另由
|
|
||||||
# test_frame_skeleton 覆盖
|
|
||||||
_c2 = sqlite3.connect(server["sessdb"])
|
|
||||||
_c2.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
_dyn = _dl.dyn_uw_rows(_c2, sid_b, pos2id[i])
|
|
||||||
finally:
|
|
||||||
_c2.close()
|
|
||||||
# 容差逐对比较(金额写 2 位、数量写 6 位——写读往返在第 6 位以下折损,
|
|
||||||
# 半界舍入漂移≤0.0011/0.006;实际值同源 dyn 同一引擎)
|
|
||||||
exp_map = {r[0]: (float(r[5]), float(r[6] or 0), float(r[8] or 0))
|
|
||||||
for r in (_dyn or []) if (r[5] or 0) != 0}
|
|
||||||
got_map = {r.get("Number") or "": (float(r.get("Quantity") or 0),
|
|
||||||
float(r.get("NoTaxPrice") or 0),
|
|
||||||
float(r.get("TaxPrice") or 0))
|
|
||||||
for r in eb.findall("LabourMaterialsEquipmentsMachinesSummary")
|
|
||||||
if _f(r.get("Quantity"), 4) != 0}
|
|
||||||
assert set(got_map) == set(exp_map), "单位%s 汇总行码集不一致:缺=%s 多=%s" % (
|
|
||||||
nm_uw, sorted(set(exp_map) - set(got_map))[:4],
|
|
||||||
sorted(set(got_map) - set(exp_map))[:4])
|
|
||||||
for c in exp_map:
|
|
||||||
for j, tol in ((0, 0.0011), (1, 0.006), (2, 0.006)):
|
|
||||||
assert abs(got_map[c][j] - exp_map[c][j]) <= tol, "单位%s 码%s 第%d值 %s vs %s" % (nm_uw, c, j, got_map[c][j], exp_map[c][j])
|
|
||||||
# 定额=对照「采纳落地的会话状态」(独立期望值:s_norms+GCL 公式求值,与导出
|
|
||||||
# 引擎无关),**按清单分组**逐条比——无定额的费项清单(原件即无定额,110 条)
|
|
||||||
# 走 231① 架子清值,不混入本比对
|
|
||||||
expected_uw = {}
|
|
||||||
for k, v in expected.items():
|
|
||||||
if k[0] == i:
|
|
||||||
expected_uw[(k[1], k[2])] = v
|
|
||||||
got_by_bill = {}
|
|
||||||
for b in cb.iter("WorkElement"):
|
|
||||||
k = (b.get("Number") or "", b.get("Name") or "")
|
|
||||||
if k in expected_uw:
|
|
||||||
got_by_bill.setdefault(k, []).extend(
|
|
||||||
((n.get("Number") or "", n.get("Name") or "",
|
|
||||||
(n.get("Unit") or "").strip(), _f(n.get("Quantity")),
|
|
||||||
_f(n.get("Price")), _f(n.get("Total"))))
|
|
||||||
for n in b.iter("Norm"))
|
|
||||||
for k, exp_rows in expected_uw.items():
|
|
||||||
exp_rows = sorted(tuple(x) for x in exp_rows)
|
|
||||||
got_rows = sorted(got_by_bill.get(k, []))
|
|
||||||
ok = (len(got_rows) == len(exp_rows) and all(
|
|
||||||
xa[:3] == xb[:3] and all(abs(xa[j] - xb[j]) <= max(0.005, abs(xa[j]) * 0.001)
|
|
||||||
for j in (3, 4, 5))
|
|
||||||
for xa, xb in zip(got_rows, exp_rows)))
|
|
||||||
if not ok:
|
|
||||||
diff = None
|
|
||||||
for xa, xb in zip(got_rows, exp_rows):
|
|
||||||
if xa != xb and (xa[:4] != xb[:4] or any(
|
|
||||||
abs(xa[j] - xb[j]) > max(0.005, abs(xa[j]) * 0.001)
|
|
||||||
for j in (3, 4, 5))):
|
|
||||||
diff = (xa, xb)
|
|
||||||
break
|
|
||||||
raise AssertionError(
|
|
||||||
"单位%s 清单%s 定额与采纳落地状态不一致:len 导出=%d 期望=%d;首差异=%s"
|
|
||||||
% (nm_uw, k, len(got_rows), len(exp_rows), diff))
|
|
||||||
# 消耗行=现算数据根:该清单各采纳定额下的 LME 子行与 s_norm_res 逐一对照
|
|
||||||
got_cons = {}
|
|
||||||
for b2 in cb.iter("WorkElement"):
|
|
||||||
if (b2.get("Number") or "", b2.get("Name") or "") != k:
|
|
||||||
continue
|
|
||||||
for n2 in b2.iter("Norm"):
|
|
||||||
nk = (i, k[0], k[1], n2.get("Number") or "", n2.get("Name") or "")
|
|
||||||
for c2 in n2:
|
|
||||||
if c2.tag.startswith("LabourMaterials"):
|
|
||||||
got_cons.setdefault(nk, []).append(
|
|
||||||
(c2.get("Number") or "", _f(c2.get("Quantity"), 6)))
|
|
||||||
for nk, rows in got_cons.items():
|
|
||||||
rows.sort()
|
|
||||||
assert rows == cons_expected.get(nk, []), \
|
|
||||||
"单位%s 清单%s 定额%s 消耗行与采纳落地不一致:%s vs %s" % (
|
|
||||||
nm_uw, k[:2], nk[2:], rows[:3], cons_expected.get(nk, [])[:3])
|
|
||||||
missing = [k4 for k4 in cons_expected
|
|
||||||
if k4[0] == i and k4[1:3] == k and k4 not in got_cons]
|
|
||||||
assert not missing, "清单%s 采纳定额消耗行缺失:%s exp=%s" % (
|
|
||||||
k, missing[:2], [cons_expected[m] for m in missing[:2]])
|
|
||||||
compared += 1
|
|
||||||
assert compared >= len(out["uw"]) - 2, \
|
|
||||||
"对拍成员过少:compared=%d uw=%d skip_a=%s" % (compared, len(out["uw"]), skip_a)
|
|
||||||
@@ -1,279 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 231 真实件对拍(主人 2026-10-27 定:「要真真实实做测试,不能弄虚作假骗自己」)。
|
|
||||||
|
|
||||||
链路:真实小项目原件 → 上传入库当经典骨架 → 原件解析倒出 Excel(230 模板、原行序)
|
|
||||||
→ 手工工程导入 → 骨架导出 → **导出件与原件逐层对拍数据结构**:
|
|
||||||
①zip 成员名集合一致(整件字节外科手术不丢成员);
|
|
||||||
②分部层级保真:DivisionalWorks 嵌套序列(深度+名称,预序)逐一对齐;
|
|
||||||
③我方数据挂载正确:分部分项/措施清单的 (编码,名称,单位,量,价) 集合=原件
|
|
||||||
(主人定:骨架只规定格式与字段,数据挂载在字段下;合价现算);
|
|
||||||
④未采纳清单=克隆架子清值(231①,2026-10-28 复确认:架子在值 0);无采纳=工料机
|
|
||||||
汇总容器空(架子在行不进);
|
|
||||||
⑤保留值:建设单位/费用汇总等工程级信息=原件原样;工程/单位/单项名=原件名
|
|
||||||
(本测试数据来自原件,名字应当对上);
|
|
||||||
⑥措施区平铺(决策 230 既有口径:Excel 措施 Sheet 无层级,不保留措施分部层级)。
|
|
||||||
真实件(后台需要导入的项目/,主人库内小体量项目):
|
|
||||||
· 三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS(.cos 代)
|
|
||||||
· 吉大街道园林花园老旧小区环境整治提升工程施工.cos4(cos4 代)
|
|
||||||
"""
|
|
||||||
import importlib.util
|
|
||||||
import io
|
|
||||||
import sqlite3
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import zipfile
|
|
||||||
from pathlib import Path
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from api_harness import PERIOD_202607, get, post, server # noqa: F401 (夹具)
|
|
||||||
from test_api_p1 import raw_post
|
|
||||||
|
|
||||||
_CORE = Path(__file__).resolve().parents[1] / "core"
|
|
||||||
_REAL_DIR = Path(__file__).resolve().parents[3] / "后台需要导入的项目"
|
|
||||||
FB_H = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"]
|
|
||||||
CS_H = ["名称", "编码", "项目特征", "单位", "工程量", "单价"]
|
|
||||||
|
|
||||||
REAL_CASES = [
|
|
||||||
("三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS", "cos"),
|
|
||||||
("吉大街道园林花园老旧小区环境整治提升工程施工.cos4", "cos4"),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _ij():
|
|
||||||
import sys
|
|
||||||
if str(_CORE) not in sys.path:
|
|
||||||
sys.path.insert(0, str(_CORE)) # import_job 平铺引 match 等 core 模块
|
|
||||||
spec = importlib.util.spec_from_file_location("ij_real", _CORE / "import_job.py")
|
|
||||||
m = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(m)
|
|
||||||
return m
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_original(path):
|
|
||||||
ij = _ij()
|
|
||||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
|
|
||||||
"cur_bill": -1, "cur_uw": -1, "bill_uw": [],
|
|
||||||
"bill_kind": [], "prelim_raw": 0,
|
|
||||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
|
|
||||||
"lme_raw": 0, "lme_skip": 0,
|
|
||||||
"proj_name": "", "file_kind": None, "bulid_unit": "", "total": None}
|
|
||||||
ij.parse_file(str(path), out)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _f(v):
|
|
||||||
try:
|
|
||||||
return round(float(v), 6)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _unit_xlsx(server, tag, uw_i, out):
|
|
||||||
"""原件第 uw_i 个单位工程 → 230 模板 Excel(原行序:分部预序、清单挂各自分部名下)。
|
|
||||||
量价空值落 0(决策 196 口径:算不出归零)。"""
|
|
||||||
from openpyxl import Workbook
|
|
||||||
glo = [i for i, d in enumerate(out["divides"]) if d["uw"] == uw_i and d["kind"] == "item"]
|
|
||||||
local = {g: k for k, g in enumerate(glo)}
|
|
||||||
kids, roots = {}, []
|
|
||||||
for k, g in enumerate(glo):
|
|
||||||
d = out["divides"][g]
|
|
||||||
p = d.get("parent")
|
|
||||||
(kids.setdefault(local[p], []).append(k)) if p in local else roots.append(k)
|
|
||||||
by_div = {}
|
|
||||||
for bi, b in enumerate(out["bills"]):
|
|
||||||
if out["bill_uw"][bi] != uw_i or out["bill_kind"][bi] == "prelim":
|
|
||||||
continue
|
|
||||||
by_div.setdefault(out["bill_div"][bi], []).append(b)
|
|
||||||
prels = [b for bi, b in enumerate(out["bills"])
|
|
||||||
if out["bill_uw"][bi] == uw_i and out["bill_kind"][bi] == "prelim"]
|
|
||||||
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = "分部分项"
|
|
||||||
ws.append(FB_H)
|
|
||||||
|
|
||||||
def emit(k, parent_name):
|
|
||||||
g = glo[k]
|
|
||||||
d = out["divides"][g]
|
|
||||||
ws.append([parent_name, "", "分部", d["name"] or "", "", "", "", ""])
|
|
||||||
for b in by_div.get(g, []):
|
|
||||||
ws.append([d["name"] or "", b[0] or "", "清单", b[1] or "", b[2] or "",
|
|
||||||
b[3] or "", _f(b[4]) or 0, _f(b[5]) or 0])
|
|
||||||
for sub in kids.get(k, []):
|
|
||||||
emit(sub, d["name"] or "")
|
|
||||||
|
|
||||||
for k in roots:
|
|
||||||
emit(k, "单位工程")
|
|
||||||
ws2 = wb.create_sheet("措施项目")
|
|
||||||
ws2.append(CS_H)
|
|
||||||
for b in prels:
|
|
||||||
ws2.append([b[1] or "", b[0] or "", b[2] or "", b[3] or "",
|
|
||||||
_f(b[4]) or 0, _f(b[5]) or 0])
|
|
||||||
p = server["src_dir"] / ("real_%s_uw%d.xlsx" % (tag, uw_i))
|
|
||||||
wb.save(p)
|
|
||||||
return str(p), sum(len(v) for v in by_div.values()), len(prels)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("fname,fmt", REAL_CASES)
|
|
||||||
@pytest.mark.skip(reason="决策 260 引擎 v2 重写中:旧口径断言(zip 成员名集合=源件名集合)与新口径(成员文件名=我方单位名、编号按引用行序重排)冲突;v2 验收测试将按「引用行 Name/FileName/成员内容名实一致」重写对拍")
|
|
||||||
def test_real_roundtrip(server, fname, fmt):
|
|
||||||
src = _REAL_DIR / fname
|
|
||||||
if not src.exists():
|
|
||||||
pytest.skip("真实件不在本机:%s" % fname)
|
|
||||||
tag = fmt
|
|
||||||
# ---- ① 原件上传+升级口入骨架库(补记十四:上传不再自动收藏)----
|
|
||||||
data = src.read_bytes()
|
|
||||||
up = raw_post(server, "/api/admin/upload", fname, data)
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
import sys as _sys
|
|
||||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import classic_skeleton as _cs
|
|
||||||
_con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
|
||||||
try:
|
|
||||||
assert _cs.seed_frame(_con, str(src), "骨架real_%s" % tag)
|
|
||||||
finally:
|
|
||||||
_con.close()
|
|
||||||
# ---- ② 原件解析(与工作台同源解析器)→ 倒 Excel ----
|
|
||||||
out = _parse_original(src)
|
|
||||||
assert out["uw"], "原件没解析出单位工程"
|
|
||||||
units = []
|
|
||||||
for i, uw in enumerate(out["uw"]):
|
|
||||||
fp, n_item, n_pre = _unit_xlsx(server, tag, i, out)
|
|
||||||
units.append({"id": 0, "name": uw[1] or ("单位工程%d" % (i + 1)), "file": fp})
|
|
||||||
sec_name = (out.get("sections") or [None])[0]
|
|
||||||
sec_name = (sec_name[1] if isinstance(sec_name, (tuple, list)) and sec_name[1]
|
|
||||||
else "单项工程")
|
|
||||||
# ---- ③ 手工工程导入 ----
|
|
||||||
r = post(server, "/api/session/manual/save",
|
|
||||||
{"sid": 0, "name": out["proj_name"] or "真实件对拍", "period_from": PERIOD_202607,
|
|
||||||
"period_to": PERIOD_202607,
|
|
||||||
"tree": [{"id": 0, "name": sec_name, "units": units}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
# ---- ④ 骨架导出 ----
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "fmt": fmt})
|
|
||||||
assert resp.status_code == 200, resp.text[:300]
|
|
||||||
if os.environ.get("DEBUG_EXPORT"): # 排查用:落盘导出件(主人可随时关掉)
|
|
||||||
Path(os.environ["DEBUG_EXPORT"]).write_bytes(resp.content)
|
|
||||||
zexp = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
zsrc = zipfile.ZipFile(str(src))
|
|
||||||
# ---- ⑤ 对拍 ----
|
|
||||||
# ⑤-1 成员对拍(决策 260 起:成员**文件名**=我方单位名(=零修改时源件单位名),
|
|
||||||
# 但 zip 内部编号按引用行序重排——成员名集合不再与源 zip 逐字一致;改按
|
|
||||||
# 「引用行 (Number,Name,FileName) 序 + 成员数」对拍,成员内容对拍沿用 members())
|
|
||||||
def _refs(z):
|
|
||||||
proj = [z.read(nm).decode("utf-8", errors="replace")
|
|
||||||
for nm in z.namelist() if "Project" in nm][0]
|
|
||||||
out = []
|
|
||||||
for x in re.findall(r"<UnitWorks\b[^>]*>", proj):
|
|
||||||
g = lambda k: (re.search(k + r'="([^"]*)"', x).group(1)
|
|
||||||
if re.search(k + r'="', x) else "")
|
|
||||||
out.append((g("Number"), g("Name"), g("FileName")))
|
|
||||||
return out
|
|
||||||
|
|
||||||
def _disp(z, fn):
|
|
||||||
for i in z.infolist():
|
|
||||||
raw = (i.filename if (i.flag_bits & 0x800)
|
|
||||||
else i.filename.encode("cp437").decode("gbk"))
|
|
||||||
if raw == fn:
|
|
||||||
return i.filename
|
|
||||||
return None
|
|
||||||
|
|
||||||
rs, re_ = _refs(zsrc), _refs(zexp)
|
|
||||||
assert len(rs) == len(re_), ("引用行数不一致", len(rs), len(re_))
|
|
||||||
for (n1, t1, f1), (n2, t2, f2) in zip(rs, re_):
|
|
||||||
assert (n1, t1) == (n2, t2), ("引用行不一致", (n1, t1), (n2, t2))
|
|
||||||
if f1 and f2: # 文件名=我方单位名(同零修改时=源名,编号可重排)
|
|
||||||
assert f2.split("_", 2)[-1] == f1.split("_", 2)[-1], ("成员名尾段不一致", f1, f2)
|
|
||||||
assert _disp(zexp, f2), "引用行断链:" + f2
|
|
||||||
assert len(members(zsrc)) == len(members(zexp)), "单位成员数不一致"
|
|
||||||
|
|
||||||
def members(z):
|
|
||||||
m = []
|
|
||||||
for nm in z.namelist():
|
|
||||||
if not nm.lower().endswith(".xml"):
|
|
||||||
continue
|
|
||||||
body = ET.fromstring(z.read(nm))
|
|
||||||
if body.tag == "UnitWorks":
|
|
||||||
m.append((nm, body))
|
|
||||||
return m
|
|
||||||
|
|
||||||
ms, me = members(zsrc), members(zexp)
|
|
||||||
assert len(ms) == len(me) == len(out["uw"]), "单位工程成员数不一致"
|
|
||||||
# 2026-10-28 主人定:单位排序=项目目录序(引用行序),与压缩包内 xml 次序无关——
|
|
||||||
# 导出成员按 zip 物理序取不再保证与原件逐位对齐,改按单位名配对比内容
|
|
||||||
me_by_name = {}
|
|
||||||
for nm, body in me:
|
|
||||||
me_by_name.setdefault(body.get("Name") or "", []).append((nm, body))
|
|
||||||
assert all(len(v) == 1 for v in me_by_name.values()), "导出件存在同名单位工程,无法按名配对"
|
|
||||||
|
|
||||||
def dw_seq(container, depth=0):
|
|
||||||
"""容器/分部内 DivisionalWorks 预序 (depth, Name) 序列。"""
|
|
||||||
seq = []
|
|
||||||
for el in container:
|
|
||||||
if el.tag == "DivisionalWorks":
|
|
||||||
seq.append((depth, el.get("Name") or ""))
|
|
||||||
seq.extend(dw_seq(el, depth + 1))
|
|
||||||
return seq
|
|
||||||
|
|
||||||
def bills_of(container, tags):
|
|
||||||
return [(_norm_b(el)) for el in container.iter() if el.tag in tags]
|
|
||||||
|
|
||||||
def _norm_b(el):
|
|
||||||
# 单位按内部口径 strip 后比较(解析端把「个 」归一成「个」,原件留原样属预期差异)
|
|
||||||
# 数量按 3 位比较(决策 244 补六:导出清单数量 3 位;原件 6 位的按 3 位舍入后等值)
|
|
||||||
q = _f(el.get("Quantity"))
|
|
||||||
return (el.get("Number") or "", el.get("Name") or "",
|
|
||||||
(el.get("Unit") or "").strip(),
|
|
||||||
round(q, 3) if q is not None else q, _f(el.get("Price")))
|
|
||||||
|
|
||||||
PRE_TAGS = {"UnitWorksPreliminaryWorkElement", "WorkElement"}
|
|
||||||
for i, ((nms, es), (_, eo)) in enumerate(
|
|
||||||
(mo, me_by_name[(mo[1].get("Name") or "")][0]) for mo in ms):
|
|
||||||
uw_name = out["uw"][i][1] or ("单位工程%d" % (i + 1))
|
|
||||||
# ⑤-2 单位名=原件
|
|
||||||
assert eo.get("Name") == uw_name, (nms, eo.get("Name"), uw_name)
|
|
||||||
cs = eo.find("DivisionalAndElementalWorks")
|
|
||||||
co = es.find("DivisionalAndElementalWorks")
|
|
||||||
assert cs is not None and co is not None
|
|
||||||
# ⑤-3 分部层级(深度+名称)逐一保真
|
|
||||||
assert dw_seq(co) == dw_seq(cs), "单位 %s 分部嵌套不一致" % uw_name
|
|
||||||
# ⑤-4 我方清单集合=原件(骨架只定字段,数据挂载;合价现算不比原件 Total 口径)
|
|
||||||
so = sorted(bills_of(co, {"WorkElement"}))
|
|
||||||
se = sorted(bills_of(cs, {"WorkElement"}))
|
|
||||||
assert len(so) == len(se) and so == se, "单位 %s 清单集不一致" % uw_name
|
|
||||||
# ⑤-5 未采纳清单(补记十五:分部/清单/定额/工料机全按自己的值——推翻克隆架子
|
|
||||||
# 清值):我方五值照出、无定额(骨架样例定额不进)
|
|
||||||
for el in cs.iter("WorkElement"):
|
|
||||||
norms = list(el.iter("Norm"))
|
|
||||||
assert not norms, "清单 %s 不该带(骨架样例)定额" % el.get("Name")
|
|
||||||
# ⑤-6 措施平铺:清单集合=原件(分部层级不保留,决策 230 口径)
|
|
||||||
po = es.find("Preliminaries")
|
|
||||||
pe = eo.find("Preliminaries")
|
|
||||||
assert po is not None and pe is not None
|
|
||||||
so = sorted(bills_of(po, PRE_TAGS))
|
|
||||||
se = sorted(bills_of(pe, PRE_TAGS))
|
|
||||||
assert len(so) == len(se) and so == se, "单位 %s 措施清单集不一致" % uw_name
|
|
||||||
# ⑤-7 工料机汇总:架子在、行不进
|
|
||||||
for el in eo.iter("LabourMaterialsEquipmentsMachinesSummary"):
|
|
||||||
assert len(el) == 0, "单位 %s 工料机汇总没清空" % uw_name
|
|
||||||
# ⑤-8 项目层:工程名/单项名/建设单位(保留值)=原件
|
|
||||||
ps, pe2 = None, None
|
|
||||||
for nm in zsrc.namelist():
|
|
||||||
if nm.lower().endswith("project.xml"):
|
|
||||||
ps = ET.fromstring(zsrc.read(nm))
|
|
||||||
for nm in zexp.namelist():
|
|
||||||
if nm.lower().endswith("project.xml"):
|
|
||||||
pe2 = ET.fromstring(zexp.read(nm))
|
|
||||||
assert ps is not None and pe2 is not None
|
|
||||||
assert pe2.get("Name") == (out["proj_name"] or ps.get("Name"))
|
|
||||||
assert pe2.get("BulidUnit") == ps.get("BulidUnit"), "建设单位保留值变了"
|
|
||||||
ss = ps.find("SectionalWorks")
|
|
||||||
se2 = pe2.find("SectionalWorks")
|
|
||||||
if ss is not None:
|
|
||||||
assert se2 is not None and se2.get("Name") == sec_name, "单项工程名没落位"
|
|
||||||
refs = pe2.findall(".//UnitWorks")
|
|
||||||
assert [r.get("Name") for r in refs[:len(out["uw"])]] == \
|
|
||||||
[u[1] for u in out["uw"]], "单位引用名没落位"
|
|
||||||
@@ -1,292 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 230(2026-10-27 主人定):手工工程——「导入项目」弹框(目录树 + 单位工程 Excel 导入)回归。
|
|
||||||
|
|
||||||
口径:①同框建三层目录树(项目→单项工程→单位工程);②单位工程行旁导 xlsx
|
|
||||||
(Sheet 分部分项/措施项目,只到清单级,不导定额/工料机,无合价列现算);
|
|
||||||
③层级=「上一级名称」挂接(一级填「单位工程」,类型 分部/清单 两值,单位工程下
|
|
||||||
最多 5 层,同父分部不重名,上级须在上方出现);④项目特征换行=真实 \\n 保留 +
|
|
||||||
行内编号从 1 连续递增才切分(1.5 不误切);⑤重复导入=整单位工程覆盖。
|
|
||||||
造数仅写隔离副本(api_harness 临时目录),生产库零接触。"""
|
|
||||||
import importlib.util
|
|
||||||
import os
|
|
||||||
|
|
||||||
from api_harness import PERIOD_202607, get, post, server # noqa: F401
|
|
||||||
|
|
||||||
ROWS = [
|
|
||||||
["单位工程", "", "分部", "楼地面装饰工程", "", "", "", ""],
|
|
||||||
["楼地面装饰工程", "", "分部", "块料面层", "", "", "", ""],
|
|
||||||
["块料面层", "", "分部", "石材面层", "", "", "", ""],
|
|
||||||
["石材面层", "011102001", "清单", "石材楼地面",
|
|
||||||
"1.结合层:30厚1:3干硬性水泥砂浆2.面层:800×800米黄石材", "m²", 126.5, 385],
|
|
||||||
["块料面层", "011102003", "清单", "块料楼地面", "600×600防滑砖", "m²", 342.8, 128.5],
|
|
||||||
["楼地面装饰工程", "011101001", "清单", "水泥砂浆楼地面", "", "m²", 88.4, 35.2],
|
|
||||||
]
|
|
||||||
PREL = [["安全文明施工费", "", "", "项", 1, 120000],
|
|
||||||
["临时设施", "", "", "项", 1, 60000]]
|
|
||||||
ITEM_TOTAL = round(126.5 * 385, 2) + round(342.8 * 128.5, 2) + round(88.4 * 35.2, 2)
|
|
||||||
UW_TOTAL = round(ITEM_TOTAL + 180000, 2)
|
|
||||||
|
|
||||||
_mi_spec = importlib.util.spec_from_file_location(
|
|
||||||
"manual_import_src", os.path.join(os.path.dirname(__file__), "..", "core", "manual_import.py"))
|
|
||||||
mi = importlib.util.module_from_spec(_mi_spec)
|
|
||||||
_mi_spec.loader.exec_module(mi)
|
|
||||||
|
|
||||||
|
|
||||||
def _xlsx(server, fname, rows=None, prels=None):
|
|
||||||
from openpyxl import Workbook
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.title = "分部分项"
|
|
||||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
for r in (rows if rows is not None else ROWS):
|
|
||||||
ws.append(r)
|
|
||||||
ws2 = wb.create_sheet("措施项目")
|
|
||||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
|
||||||
for r in (prels if prels is not None else PREL):
|
|
||||||
ws2.append(r)
|
|
||||||
p = str(server["src_dir"] / fname)
|
|
||||||
wb.save(p)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
_save_seq = [0]
|
|
||||||
|
|
||||||
|
|
||||||
def _save(server, **kw):
|
|
||||||
# 决策 242:同名创建一律拒绝(旧「同名手工工程=原地续用」退役)——
|
|
||||||
# 新建用自增唯一名;编辑路径传 sid 不受影响。
|
|
||||||
_save_seq[0] += 1
|
|
||||||
body = {"sid": 0, "name": "手工工程T%d" % _save_seq[0],
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607, "tree": []}
|
|
||||||
body.update(kw)
|
|
||||||
return post(server, "/api/session/manual/save", body)
|
|
||||||
|
|
||||||
|
|
||||||
def test_split_attr_rules():
|
|
||||||
"""换行识别:连续完整序列才切;缺号/单号不切;小数不误切;真实换行保留(决策 230)。"""
|
|
||||||
assert mi.split_attr("1.甲2.乙3.丙") == "1.甲\n2.乙\n3.丙"
|
|
||||||
assert mi.split_attr("1、垫层 2、基层 3、面层") == "1、垫层\n2、基层\n3、面层"
|
|
||||||
assert mi.split_attr("(1)找平(2)罩面") == "(1)找平\n(2)罩面"
|
|
||||||
assert mi.split_attr("1.甲 2.乙 4.丁") == "1.甲 2.乙 4.丁" # 缺 3 → 不切
|
|
||||||
assert mi.split_attr("2.只有二号") == "2.只有二号" # 不从 1 起 → 不切
|
|
||||||
assert mi.split_attr("1.5厚砂浆两层做法") == "1.5厚砂浆两层做法" # 小数不误切
|
|
||||||
assert mi.split_attr("M7.5砂浆1.底层2.面层") == "M7.5砂浆\n1.底层\n2.面层"
|
|
||||||
assert mi.split_attr("1.底层\n2.面层") == "1.底层\n2.面层" # 真实换行保留
|
|
||||||
assert mi.split_attr("做法如下:1.甲2.乙") == "做法如下:\n1.甲\n2.乙" # 引导语单独成行
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_template_download(server):
|
|
||||||
r = server["client"].get("/api/session/manual/template")
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
assert "spreadsheetml" in r.headers["Content-Type"]
|
|
||||||
assert r.content[:2] == b"PK"
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_parse_ok(server):
|
|
||||||
p = _xlsx(server, "unit_ok.xlsx")
|
|
||||||
r = post(server, "/api/session/manual/parse", {"path": p})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert (r["n_div"], r["n_item"], r["n_prelim"]) == (3, 3, 2)
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_parse_rejects(server):
|
|
||||||
# 补记十四(2026-10-28 主人定边界放开):同父重名、超深层级、空名分部/清单
|
|
||||||
# 已放行——不再是坏例;坏例只剩真错误(缺上级、量非数字)
|
|
||||||
bad = {
|
|
||||||
"缺上级": [["单位工程", "", "分部", "A分部", "", "", "", ""],
|
|
||||||
["B分部", "X1", "清单", "孤儿清单", "", "m", 1, 1]],
|
|
||||||
"量非数字": [["单位工程", "X1", "清单", "清单A", "", "m", "十", 1]],
|
|
||||||
}
|
|
||||||
for name, rows in bad.items():
|
|
||||||
p = _xlsx(server, "bad.xlsx", rows=rows, prels=[])
|
|
||||||
r = post(server, "/api/session/manual/parse", {"path": p})
|
|
||||||
assert r["ok"] is False, name
|
|
||||||
assert r["msg"], name
|
|
||||||
# 清单挂在第 4 级分部下=第 5 层,合法;挂第 5 级分部=第 6 层,拒绝
|
|
||||||
five = [["单位工程", "", "分部", "一", "", "", "", ""],
|
|
||||||
["一", "", "分部", "二", "", "", "", ""],
|
|
||||||
["二", "", "分部", "三", "", "", "", ""],
|
|
||||||
["三", "", "分部", "四", "", "", "", ""],
|
|
||||||
["四", "X1", "清单", "第五层清单", "", "m", 1, 1]]
|
|
||||||
assert post(server, "/api/session/manual/parse", {"path": _xlsx(server, "ok5.xlsx", rows=five, prels=[])})["ok"]
|
|
||||||
six = five[:-1] + [["四", "", "分部", "五", "", "", "", ""], ["五", "X1", "清单", "第六层", "", "m", 1, 1]]
|
|
||||||
# 补记十四:层级不设限——第六层同样放行
|
|
||||||
r6 = post(server, "/api/session/manual/parse", {"path": _xlsx(server, "ok6.xlsx", rows=six, prels=[])})
|
|
||||||
assert r6["ok"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_create_and_tabs(server):
|
|
||||||
f1 = _xlsx(server, "unit_a.xlsx")
|
|
||||||
r = _save(server, tree=[{"id": 0, "name": "一期工程",
|
|
||||||
"units": [{"id": 0, "name": "土建工程", "file": f1},
|
|
||||||
{"id": 0, "name": "电气工程"}]}])
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
it = next(x for x in get(server, "/api/sessions")["items"] if x["id"] == sid)
|
|
||||||
assert it["manual"] is True and it["src_name"] == ""
|
|
||||||
|
|
||||||
tree = get(server, "/api/session/raw/tree", session_id=sid)
|
|
||||||
assert tree["sections"][0]["name"] == "一期工程"
|
|
||||||
uws = tree["sections"][0]["uws"]
|
|
||||||
assert [u["Name"] for u in uws] == ["土建工程", "电气工程"]
|
|
||||||
uwid = uws[0]["id"]
|
|
||||||
|
|
||||||
d = get(server, "/api/session/raw/uw", session_id=sid, uw_id=uwid, tab="item")
|
|
||||||
assert d["n_div"] == 3 and d["n_bill"] == 3
|
|
||||||
flat_bills = [b for b in _flat_bills(d)]
|
|
||||||
assert any("1.结合层:30厚1:3干硬性水泥砂浆\n2.面层:800×800米黄石材" == (b["Attr"] or "")
|
|
||||||
for b in flat_bills), [b["Attr"] for b in flat_bills]
|
|
||||||
assert abs(uw_total(d, flat_bills) - ITEM_TOTAL) < 0.01
|
|
||||||
|
|
||||||
dp = get(server, "/api/session/raw/uw", session_id=sid, uw_id=uwid, tab="prelim")
|
|
||||||
assert dp["n_bill"] == 2
|
|
||||||
|
|
||||||
dc = get(server, "/api/session/raw/uw", session_id=sid, uw_id=uwid, tab="cost")["rows"]
|
|
||||||
# 决策 244(2026-11-01 主人定):单位级「汇总分析」卡 = UnitWorksSummary 原样树,
|
|
||||||
# 原键值卡取代;手工工程无源文件 → 无 UWS 数据 → 空行列表(卡面显示「没有数据」)
|
|
||||||
assert dc == []
|
|
||||||
|
|
||||||
dl = get(server, "/api/session/raw/uw", session_id=sid, uw_id=uwid, tab="lme")
|
|
||||||
assert not dl["rows"] # 不导定额/工料机 → 空
|
|
||||||
|
|
||||||
ps = get(server, "/api/session/raw/proj", session_id=sid, tab="sum")["rows"]
|
|
||||||
assert any(abs((x["Total"] or 0) - UW_TOTAL) < 0.01 for x in ps)
|
|
||||||
|
|
||||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
assert st["ok"] and st["name"].startswith("手工工程T") # 自增唯一名(决策 242)
|
|
||||||
u0 = st["sections"][0]["units"][0]
|
|
||||||
assert (u0["n_item"], u0["n_prelim"]) == (3, 2)
|
|
||||||
|
|
||||||
|
|
||||||
def _flat_bills(d):
|
|
||||||
out = list(d.get("loose") or [])
|
|
||||||
def walk(nodes):
|
|
||||||
for n in nodes or []:
|
|
||||||
out.extend(n.get("bills") or [])
|
|
||||||
walk(n.get("children"))
|
|
||||||
walk(d.get("tree"))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def uw_total(d, bills):
|
|
||||||
return round(sum((b["Total"] or 0) for b in bills), 2)
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_update_rename_delete_reimport(server):
|
|
||||||
f1 = _xlsx(server, "unit_a.xlsx")
|
|
||||||
f2 = _xlsx(server, "unit_b.xlsx", rows=[
|
|
||||||
["单位工程", "", "分部", "砌筑工程", "", "", "", ""],
|
|
||||||
["砌筑工程", "010401003001", "清单", "实心砖墙", "1.砖孔率30%2.M10砂浆", "m³", 66.6, 520],
|
|
||||||
], prels=[["吊装费", "", "", "项", 1, 3000]])
|
|
||||||
r = _save(server, tree=[{"id": 0, "name": "一期工程",
|
|
||||||
"units": [{"id": 0, "name": "土建工程", "file": f1},
|
|
||||||
{"id": 0, "name": "电气工程"}]}])
|
|
||||||
sid = r["session_id"]
|
|
||||||
sec = get(server, "/api/session/manual/state", session_id=sid)["sections"][0]
|
|
||||||
a_id, b_id = sec["units"][0]["id"], sec["units"][1]["id"]
|
|
||||||
|
|
||||||
# 改名单项+单位;删电气工程;改名单位覆盖重导;新增无数据单位
|
|
||||||
r2 = _save(server, sid=sid, tree=[{"id": sec["id"], "name": "一期工程(改)",
|
|
||||||
"units": [{"id": a_id, "name": "土建工程(改)", "file": f2},
|
|
||||||
{"id": 0, "name": "给排水工程"}]}])
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
tree = get(server, "/api/session/raw/tree", session_id=sid)
|
|
||||||
assert tree["sections"][0]["name"] == "一期工程(改)"
|
|
||||||
names = [u["Name"] for u in tree["sections"][0]["uws"]]
|
|
||||||
assert names == ["土建工程(改)", "给排水工程"], names
|
|
||||||
d = get(server, "/api/session/raw/uw", session_id=sid,
|
|
||||||
uw_id=tree["sections"][0]["uws"][0]["id"], tab="item")
|
|
||||||
bills = _flat_bills(d)
|
|
||||||
assert len(bills) == 1 # 覆盖重导:只剩 f2 的 1 条
|
|
||||||
assert bills[0]["Attr"] == "1.砖孔率30%\n2.M10砂浆"
|
|
||||||
assert get(server, "/api/session/raw/uw", session_id=sid,
|
|
||||||
uw_id=tree["sections"][0]["uws"][0]["id"], tab="prelim")["n_bill"] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_rejects_file_project_name(server):
|
|
||||||
from api_harness import fixture_file
|
|
||||||
p = fixture_file(server, "conflict.cos4", "冲突工程",
|
|
||||||
[("030507008001", "网络摄像机", "1、400万", "台", 10, 1500)])
|
|
||||||
r = post(server, "/api/audit", {"path": p, "name": "冲突工程", "file_kind": 1,
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607,
|
|
||||||
"base_period_m": PERIOD_202607})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
m = _save(server, name="冲突工程", tree=[{"id": 0, "name": "一期",
|
|
||||||
"units": [{"id": 0, "name": "土建"}]}])
|
|
||||||
assert m["ok"] is False and "名字重复" in m["msg"] and "请修改名称" in m["msg"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_reorder_within_groups(server):
|
|
||||||
"""决策 230 补记:单项/单位组内上下移动持久化——单项顺序=tree 序(重建 s_sections),
|
|
||||||
单位顺序=组内位置重写 Number(显示序=natkey 回退序);单位工程 id/数据跟行走。"""
|
|
||||||
f1 = _xlsx(server, "unit_r.xlsx")
|
|
||||||
r = _save(server, tree=[
|
|
||||||
{"id": 0, "name": "单项A",
|
|
||||||
"units": [{"id": 0, "name": "A1", "file": f1}, {"id": 0, "name": "A2"}]},
|
|
||||||
{"id": 0, "name": "单项B", "units": [{"id": 0, "name": "B1"}]}])
|
|
||||||
sid = r["session_id"]
|
|
||||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
sA, sB = st["sections"]
|
|
||||||
# 单项B 整组上移到最前;单项A 组内 A2 上移到 A1 前(A2 携带 f1 覆盖导入)
|
|
||||||
r2 = _save(server, sid=sid, tree=[
|
|
||||||
{"id": sB["id"], "name": "单项B", "units": [{"id": sB["units"][0]["id"], "name": "B1"}]},
|
|
||||||
{"id": sA["id"], "name": "单项A",
|
|
||||||
"units": [{"id": sA["units"][1]["id"], "name": "A2", "file": f1},
|
|
||||||
{"id": sA["units"][0]["id"], "name": "A1"}]}])
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
tree = get(server, "/api/session/raw/tree", session_id=sid)
|
|
||||||
assert [s["name"] for s in tree["sections"]] == ["单项B", "单项A"]
|
|
||||||
names = [u["Name"] for u in tree["sections"][1]["uws"]]
|
|
||||||
assert names == ["A2", "A1"], names
|
|
||||||
d = get(server, "/api/session/raw/uw", session_id=sid,
|
|
||||||
uw_id=tree["sections"][1]["uws"][0]["id"], tab="item")
|
|
||||||
assert d["n_bill"] == 3 # A2(原无数据单位)覆盖导入后带 3 条清单
|
|
||||||
st2 = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
assert [s["name"] for s in st2["sections"]] == ["单项B", "单项A"]
|
|
||||||
assert [u["name"] for u in st2["sections"][1]["units"]] == ["A2", "A1"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_region_fields(server):
|
|
||||||
"""决策 233(2026-10-28 主人定):打开项目弹框共用字段——地区/建设单位随建落库、
|
|
||||||
manual_state 回填、改存更新(与 /api/audit 同名参数)。"""
|
|
||||||
f = _xlsx(server, "手工地区.xlsx")
|
|
||||||
r = _save(server, name="手工地区T", province="广东省", city="珠海市", district="香洲区",
|
|
||||||
bulid_unit="某某建设单位",
|
|
||||||
tree=[{"id": 0, "name": "单项A",
|
|
||||||
"units": [{"id": 0, "name": "单位A", "file": f}]}])
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
assert st["ok"], st
|
|
||||||
assert st["province"] == "广东省" and st["city"] == "珠海市", st
|
|
||||||
assert st["district"] == "香洲区" and st["bulid_unit"] == "某某建设单位"
|
|
||||||
uw = st["sections"][0]["units"][0]["id"]
|
|
||||||
r2 = _save(server, sid=sid, name="手工地区T", province="广西壮族自治区", city="南宁市",
|
|
||||||
district="", bulid_unit="新建设单位",
|
|
||||||
tree=[{"id": 0, "name": "单项A", "units": [{"id": uw, "name": "单位A"}]}])
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
st2 = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
assert st2["province"] == "广西壮族自治区" and st2["city"] == "南宁市"
|
|
||||||
assert st2["district"] == "" and st2["bulid_unit"] == "新建设单位"
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_save_file_kind(server):
|
|
||||||
"""决策 245(2026-11-01 主人定):单价类型随建/改落库(1..4 收下,空/非法→空),
|
|
||||||
manual_state 回填给弹框。"""
|
|
||||||
f = _xlsx(server, "手工单价类型.xlsx")
|
|
||||||
r = _save(server, name="手工单价T", province="广东省", city="珠海市", district="香洲区",
|
|
||||||
bulid_unit="某某建设单位", file_kind=3,
|
|
||||||
tree=[{"id": 0, "name": "单项A", "units": [{"id": 0, "name": "单位A", "file": f}]}])
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
|
||||||
assert st["file_kind"] == 3, st
|
|
||||||
uw = st["sections"][0]["units"][0]["id"]
|
|
||||||
r2 = _save(server, sid=sid, name="手工单价T", file_kind=2,
|
|
||||||
tree=[{"id": 0, "name": "单项A", "units": [{"id": uw, "name": "单位A"}]}])
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
assert get(server, "/api/session/manual/state", session_id=sid)["file_kind"] == 2
|
|
||||||
r3 = _save(server, sid=sid, name="手工单价T", file_kind=9,
|
|
||||||
tree=[{"id": 0, "name": "单项A", "units": [{"id": uw, "name": "单位A"}]}])
|
|
||||||
assert r3["ok"] is True, r3
|
|
||||||
assert get(server, "/api/session/manual/state", session_id=sid)["file_kind"] is None
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""创建入口退役及旧手工工程兼容回归;造数仅写隔离副本。"""
|
|
||||||
import base64
|
|
||||||
import sqlite3
|
|
||||||
import time
|
|
||||||
|
|
||||||
from api_harness import PERIOD_202607, get, make_cos4, post, server # noqa: F401
|
|
||||||
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
AUDIT_BASE = {"province": "广东省", "city": "珠海市", "district": "香洲区",
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607, "file_kind": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def _legacy_manual(server, name):
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
try:
|
|
||||||
cur = con.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
|
||||||
src_name, imported_at, x_manual) VALUES(?,?,?,?,?,?,1)""",
|
|
||||||
(name, PERIOD_202607, PERIOD_202607, PERIOD_202607, "",
|
|
||||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
|
||||||
con.commit()
|
|
||||||
return cur.lastrowid
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _upload(server, path, name):
|
|
||||||
with open(path, "rb") as f:
|
|
||||||
raw = f.read()
|
|
||||||
r = post(server, "/api/admin/upload",
|
|
||||||
{"name": name, "data": base64.b64encode(raw).decode("ascii")})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["path"]
|
|
||||||
|
|
||||||
|
|
||||||
def _item(server, sid):
|
|
||||||
return next((x for x in get(server, "/api/sessions")["items"] if x["id"] == sid), None)
|
|
||||||
|
|
||||||
|
|
||||||
def test_create_endpoint_retired(server):
|
|
||||||
before = {x["id"] for x in get(server, "/api/sessions")["items"]}
|
|
||||||
r = server["client"].post("/api/session/create",
|
|
||||||
json={"name": "不应创建的工程", "period_from": PERIOD_202607})
|
|
||||||
assert r.status_code == 404, r.text
|
|
||||||
assert r.json()["error"] == "not found"
|
|
||||||
assert {x["id"] for x in get(server, "/api/sessions")["items"]} == before
|
|
||||||
assert "/api/session/create" not in server["client"].get("/api/schema").text
|
|
||||||
page = server["client"].get("/workbench.html").text
|
|
||||||
# 决策 230(2026-10-27)创建入口以「导入项目」弹框形态恢复;决策 233(2026-10-28 主人定)
|
|
||||||
# 并入「打开项目」弹框(底部常驻 [模板][导入Excel],右侧目录树,取代顶栏按钮);
|
|
||||||
# 旧路由 /api/session/create、旧函数 createProject 仍退役不复用。
|
|
||||||
assert "createProject" not in page
|
|
||||||
assert "导入Excel" in page and "impExcelToggle" in page
|
|
||||||
assert 'onclick="doOpen()"' in page
|
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_manual_project_guards_and_delete(server):
|
|
||||||
sid = _legacy_manual(server, "旧手工工程A")
|
|
||||||
it = _item(server, sid)
|
|
||||||
assert it is not None and it["manual"] is True and it["src_name"] == ""
|
|
||||||
assert it["can_reparse"] is False
|
|
||||||
assert get(server, "/api/session/rows", session_id=sid, type="bill")["total"] == 0
|
|
||||||
assert get(server, "/api/session/raw/tree", session_id=sid) is not None
|
|
||||||
meta = get(server, "/api/session/export/meta", session_id=sid)
|
|
||||||
assert meta["ok"] is False and "手工工程" in meta["msg"]
|
|
||||||
rp = post(server, "/api/session/reparse", {"session_id": sid})
|
|
||||||
assert rp["ok"] is False and "手工工程" in rp["msg"]
|
|
||||||
assert post(server, "/api/session/delete", {"ids": [sid]})["ok"] is True
|
|
||||||
assert _item(server, sid) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_manual_project_supply_source_rejected(server):
|
|
||||||
"""决策 242(2026-10-30 主人定):同名导入一律拒绝——旧「手工工程同名补传源文件
|
|
||||||
恢复正常工程」通道退役。手工工程要上源文件数据:先删手工工程,再按源文件新导。"""
|
|
||||||
sid = _legacy_manual(server, "旧手工工程B")
|
|
||||||
p = make_cos4(str(server["src_dir"] / "manualB.cos4"), "旧手工工程B", [CAM], [LME_CAM])
|
|
||||||
up = _upload(server, p, "manualB.cos4")
|
|
||||||
a = post(server, "/api/audit", dict(AUDIT_BASE, path=up, name="旧手工工程B"))
|
|
||||||
assert a["ok"] is False and "名字重复" in a["msg"] and "请修改名称" in a["msg"], a
|
|
||||||
it = _item(server, sid)
|
|
||||||
assert it is not None and it["manual"] is True # 手工工程原样未动
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""四档匹配引擎分层测试:精确 / 次精确(含名称护栏)/ 字集 / 模糊,
|
|
||||||
加 自过滤、x_enabled 排除、期次距离排序。临时库跑,不碰生产数据。"""
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_APP = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
||||||
_CORE = os.path.join(_APP, "core")
|
|
||||||
if _CORE not in sys.path:
|
|
||||||
sys.path.insert(0, _CORE)
|
|
||||||
|
|
||||||
import import_job as job # noqa: E402
|
|
||||||
import match # noqa: E402
|
|
||||||
|
|
||||||
import pytest # noqa: E402
|
|
||||||
|
|
||||||
BASE = 2026 * 12 + 7 # 24319
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
|
||||||
def hist(tmp_path):
|
|
||||||
con = sqlite3.connect(str(tmp_path / "h.db"))
|
|
||||||
con.row_factory = sqlite3.Row # match 引擎按列名取值(dict(x))
|
|
||||||
con.executescript(open(os.path.join(_APP, "store", "schema.sql"),
|
|
||||||
encoding="utf-8").read())
|
|
||||||
yield con
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def mk_batch(con, name, period=BASE, src=None, enabled=1):
|
|
||||||
cur = con.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province,
|
|
||||||
x_city, x_district, x_period_start_m, x_period_end_m, x_enabled, x_src_hash,
|
|
||||||
x_parser_ver, is_mock) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
|
||||||
("project", name, 1, "建unit", "广东省", "珠海市", "香洲区",
|
|
||||||
period, period, enabled, src or name + ".cos4", "test", 0))
|
|
||||||
return cur.lastrowid
|
|
||||||
|
|
||||||
|
|
||||||
def mk_bill(con, bid, num, name, attr="", unit="台", price=100):
|
|
||||||
num9 = job.norm(num)[:9]
|
|
||||||
con.execute("""INSERT INTO bills(batch_id, Number, Name, Attr, Unit, Price,
|
|
||||||
x_name_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq)
|
|
||||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,1)""",
|
|
||||||
(bid, num, name, attr, unit, price, job.norm(name), job.norm(unit),
|
|
||||||
job.md5(num9, name, unit), job.md5(num9, unit),
|
|
||||||
match.bill_setkey(name, unit)))
|
|
||||||
|
|
||||||
|
|
||||||
def qrow(num, name, attr="", unit="台"):
|
|
||||||
num9 = job.norm(num)[:9]
|
|
||||||
return {"Number": num, "Name": name, "Attr": attr, "Unit": unit,
|
|
||||||
"x_hash_exact": job.md5(num9, name, unit),
|
|
||||||
"x_hash_semi": job.md5(num9, unit)}
|
|
||||||
|
|
||||||
|
|
||||||
def run(con, row, **kw):
|
|
||||||
kw.setdefault("limit", 50)
|
|
||||||
return match.match_bill(con, row, (BASE, BASE), [], [], [], **kw)
|
|
||||||
|
|
||||||
|
|
||||||
def test_tier_exact(hist):
|
|
||||||
b = mk_batch(hist, "历史B1")
|
|
||||||
mk_bill(hist, b, "030507008001", "高清网络摄像机", "1、400万", "台", 1500)
|
|
||||||
hist.commit()
|
|
||||||
res = run(hist, qrow("030507008001004", "高清网络摄像机", unit="台"))
|
|
||||||
assert res and res[0]["tier"] == "精确" # 编码后 3 位顺序码不参与(决策 27)
|
|
||||||
assert res[0]["name"] == "高清网络摄像机" and res[0]["proj"] == "历史B1"
|
|
||||||
assert res[0]["sim"] == 1.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_tier_semi_with_name_guard(hist):
|
|
||||||
b = mk_batch(hist, "历史B2")
|
|
||||||
mk_bill(hist, b, "030507008001", "高清网络摄像机(防爆型)", unit="台") # 同码同单位、名近似
|
|
||||||
mk_bill(hist, b, "030507008002", "彩色交换机", unit="台") # 同码同单位、名无关
|
|
||||||
hist.commit()
|
|
||||||
res = run(hist, qrow("030507008001009", "高清网络摄像机"))
|
|
||||||
tiers = {r["name"]: r["tier"] for r in res}
|
|
||||||
assert tiers.get("高清网络摄像机(防爆型)") == "次精确" # Jaccard ≥ 0.2 → 放行
|
|
||||||
assert "彩色交换机" not in tiers # 护栏 < 0.2 → 剔除
|
|
||||||
|
|
||||||
|
|
||||||
def test_tier_setkey_anagram(hist):
|
|
||||||
b = mk_batch(hist, "历史B3", period=2025 * 12 + 3)
|
|
||||||
mk_bill(hist, b, "010101001001", "混凝土钢筋", unit="t")
|
|
||||||
hist.commit()
|
|
||||||
res = run(hist, qrow("020202002002", "钢筋混凝土", unit="t"))
|
|
||||||
assert any(r["tier"] == "字集" and r["name"] == "混凝土钢筋" for r in res)
|
|
||||||
|
|
||||||
|
|
||||||
def test_tier_fuzzy(hist):
|
|
||||||
b = mk_batch(hist, "历史B4")
|
|
||||||
mk_bill(hist, b, "040404004004", "网络摄像机立杆基础", unit="座")
|
|
||||||
hist.commit()
|
|
||||||
res = run(hist, qrow("050505005005", "网络摄像机立杆", unit="座"))
|
|
||||||
assert res and res[0]["tier"] == "模糊" and res[0]["sim"] >= 0.6
|
|
||||||
|
|
||||||
|
|
||||||
def test_disabled_batch_excluded(hist):
|
|
||||||
b1 = mk_batch(hist, "禁用批次", enabled=0)
|
|
||||||
mk_bill(hist, b1, "030507008001", "高清网络摄像机")
|
|
||||||
hist.commit()
|
|
||||||
assert run(hist, qrow("030507008001009", "高清网络摄像机")) == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_self_filter_by_src_and_name(hist):
|
|
||||||
b = mk_batch(hist, "被审工程自己", src="self.cos4")
|
|
||||||
mk_bill(hist, b, "030507008001", "高清网络摄像机")
|
|
||||||
hist.commit()
|
|
||||||
row = qrow("030507008001009", "高清网络摄像机")
|
|
||||||
assert run(hist, row, self_src="self.cos4") == [] # 同一文件
|
|
||||||
assert run(hist, row, self_name="被审工程自己") == [] # 同名项目
|
|
||||||
assert len(run(hist, row)) == 1 # 不带自过滤 → 命中
|
|
||||||
|
|
||||||
|
|
||||||
def test_period_distance_sort_and_window(hist):
|
|
||||||
b_new = mk_batch(hist, "同期批次", period=BASE)
|
|
||||||
mk_bill(hist, b_new, "030507008001", "高清网络摄像机", price=1500)
|
|
||||||
b_old = mk_batch(hist, "远期批次", period=2024 * 12 + 1)
|
|
||||||
mk_bill(hist, b_old, "030507008001", "高清网络摄像机", price=900)
|
|
||||||
hist.commit()
|
|
||||||
res = run(hist, qrow("030507008001009", "高清网络摄像机"))
|
|
||||||
assert res[0]["proj"] == "同期批次" and res[0]["dist"] == 0
|
|
||||||
assert res[1]["proj"] == "远期批次" and res[1]["dist"] == 30
|
|
||||||
# 期次窗口:止期收窄到 2024 → 同期批次被滤掉
|
|
||||||
res2 = run(hist, qrow("030507008001009", "高清网络摄像机"),
|
|
||||||
pfrom=2024 * 12 + 1, pto=2024 * 12 + 6)
|
|
||||||
assert [r["proj"] for r in res2] == ["远期批次"]
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""MCP 接入回归(2026-10-15;2026-10-28/29 决策 238/239 主人拍板:9 工具——只读 5+⑧匹配
|
|
||||||
+写入 3【⑥整项目导入/⑦清单采纳/⑨工料机价格采纳,取代 2026-10-27 只读口径】):
|
|
||||||
默认关 → /mcp 403;打开(自动生成令牌)→ 无令牌 401、带令牌 initialize/tools/list/tools/call
|
|
||||||
可用;工具集=9 件套;关闭 → 再断;/api/mcp/status 反映状态。
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
import api_harness as H
|
|
||||||
from api_harness import post, server # noqa: F401
|
|
||||||
|
|
||||||
NEW_TOOLS = {"bills_query", "lme_prices", "market_info_prices",
|
|
||||||
"recent_review_query", "attachment_download",
|
|
||||||
"match_hist", "project_import", "bill_adopt", "lme_adopt",
|
|
||||||
"excel_bill_match"} # 2026-11-02 主人定:Excel 批量清单匹配(只读)
|
|
||||||
|
|
||||||
|
|
||||||
def _mcp(server, body, token=None):
|
|
||||||
headers = {"Content-Type": "application/json"}
|
|
||||||
if token:
|
|
||||||
headers["Authorization"] = "Bearer " + token
|
|
||||||
return server["client"].post("/mcp", content=json.dumps(body), headers=headers)
|
|
||||||
|
|
||||||
|
|
||||||
def _rpc(mid, method, params=None):
|
|
||||||
b = {"jsonrpc": "2.0", "id": mid, "method": method}
|
|
||||||
if params is not None:
|
|
||||||
b["params"] = params
|
|
||||||
return b
|
|
||||||
|
|
||||||
|
|
||||||
def _call(server, token, mid, name, args):
|
|
||||||
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
j = r.json()
|
|
||||||
assert j["result"]["isError"] is False, j
|
|
||||||
return json.loads(j["result"]["content"][0]["text"])
|
|
||||||
|
|
||||||
|
|
||||||
def _call_err(server, token, mid, name, args):
|
|
||||||
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
|
|
||||||
j = r.json()
|
|
||||||
return json.loads(j["result"]["content"][0]["text"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_mcp_switch_lifecycle(server):
|
|
||||||
# 默认关:JSON-RPC 也被 403 挡住
|
|
||||||
r = _mcp(server, _rpc(1, "tools/list"))
|
|
||||||
assert r.status_code == 403 and "未开启" in r.text, r.text[:200]
|
|
||||||
# 打开(自动生成令牌)
|
|
||||||
t = post(server, "/api/admin/mcp", {"enabled": True})
|
|
||||||
assert t["ok"] is True and t["enabled"] is True and len(t["token"]) == 32, t
|
|
||||||
# 无令牌 → 401
|
|
||||||
r = _mcp(server, _rpc(1, "initialize", {"protocolVersion": "2025-06-18"}))
|
|
||||||
assert r.status_code == 401, r.text[:200]
|
|
||||||
# initialize
|
|
||||||
r = _mcp(server, _rpc(1, "initialize", {"protocolVersion": "2025-06-18"}), t["token"])
|
|
||||||
assert r.status_code == 200, r.text[:200]
|
|
||||||
j = r.json()
|
|
||||||
assert j["result"]["serverInfo"]["name"] == "造价审核"
|
|
||||||
# 通知(无 id)→ 202 空体
|
|
||||||
r = _mcp(server, {"jsonrpc": "2.0", "method": "notifications/initialized"}, t["token"])
|
|
||||||
assert r.status_code == 202, r.status_code
|
|
||||||
# 关闭 → 再断
|
|
||||||
t2 = post(server, "/api/admin/mcp", {"enabled": False})
|
|
||||||
assert t2["enabled"] is False
|
|
||||||
r = _mcp(server, _rpc(9, "tools/list"), t["token"])
|
|
||||||
assert r.status_code == 403
|
|
||||||
# 状态接口
|
|
||||||
st = server["client"].get("/api/mcp/status").json()
|
|
||||||
assert st["enabled"] is False and st["endpoint"] == "/mcp" and st["tools"] == 10
|
|
||||||
|
|
||||||
|
|
||||||
def test_mcp_readonly_toolset(server):
|
|
||||||
t = post(server, "/api/admin/mcp", {"enabled": True})
|
|
||||||
tok = t["token"]
|
|
||||||
try:
|
|
||||||
# 工具集 = 10 件套,一个不多一个不少(决策 238/239:只读 5+匹配+写入 3,+excel_bill_match;旧写工具除 bill_adopt 外仍不在)
|
|
||||||
r = _mcp(server, _rpc(2, "tools/list"), tok)
|
|
||||||
names = {x["name"] for x in r.json()["result"]["tools"]}
|
|
||||||
assert names == NEW_TOOLS, names
|
|
||||||
for gone in ("bill_op", "norm_op", "lme_merge", "session_delete",
|
|
||||||
"session_export", "api_schema", "upload_file", "project_open"):
|
|
||||||
assert gone not in names
|
|
||||||
# 范围守卫:keyword/batch_id 都不给 → 拒绝
|
|
||||||
for tool in ("bills_query", "lme_prices", "market_info_prices"):
|
|
||||||
out = _call_err(server, tok, 3, tool, {})
|
|
||||||
assert out.get("ok") is False and "keyword" in out.get("msg", ""), (tool, out)
|
|
||||||
# 最近审核:无参 → 会话列表结构
|
|
||||||
out = _call(server, tok, 4, "recent_review_query", {})
|
|
||||||
assert out["ok"] is True and isinstance(out["rows"], list)
|
|
||||||
# 带错误 type → 拒绝
|
|
||||||
out = _call_err(server, tok, 5, "recent_review_query", {"session_id": 1, "type": "x"})
|
|
||||||
assert out.get("ok") is False
|
|
||||||
# 附件下载:参数不合法 → 拒绝
|
|
||||||
out = _call_err(server, tok, 6, "attachment_download", {"type": "xx", "id": 1})
|
|
||||||
assert out.get("ok") is False
|
|
||||||
# 真实附件路径(无绑定)→ 拒绝且不抛异常
|
|
||||||
out = _call_err(server, tok, 7, "attachment_download", {"type": "bill", "id": 1})
|
|
||||||
assert out.get("ok") is False
|
|
||||||
# 未知工具 → -32602
|
|
||||||
r = _mcp(server, _rpc(8, "tools/call", {"name": "nope", "arguments": {}}), tok)
|
|
||||||
assert r.json()["error"]["code"] == -32602
|
|
||||||
finally:
|
|
||||||
post(server, "/api/admin/mcp", {"enabled": False})
|
|
||||||
|
|
||||||
|
|
||||||
def test_mcp_query_matches_db(server):
|
|
||||||
"""market_info_prices 与库内事实一致(数据自证,不写死数字)。"""
|
|
||||||
t = post(server, "/api/admin/mcp", {"enabled": True})
|
|
||||||
tok = t["token"]
|
|
||||||
try:
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
row = con.execute("SELECT id FROM batches WHERE kind IN ('info','market') "
|
|
||||||
"AND id IN (SELECT DISTINCT batch_id FROM prices) LIMIT 1").fetchone()
|
|
||||||
if row:
|
|
||||||
bid = row[0]
|
|
||||||
want = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
|
||||||
out = _call(server, tok, 1, "market_info_prices", {"batch_id": bid, "limit": 250})
|
|
||||||
got = len(out["rows"])
|
|
||||||
assert out["ok"] and got == min(want, 100), (want, got) # 2026-11-02 主人定:上限收紧 100
|
|
||||||
# 默认口径:不传 limit = 只给匹配前 10 条
|
|
||||||
out2 = _call(server, tok, 2, "market_info_prices", {"batch_id": bid})
|
|
||||||
assert out2["ok"] and len(out2["rows"]) == min(want, 10), (want, len(out2["rows"]))
|
|
||||||
if out["rows"]:
|
|
||||||
for k in ("Code", "Name", "Unit", "NoTaxPrice", "TaxPrice"):
|
|
||||||
assert k in out["rows"][0], out["rows"][0].keys()
|
|
||||||
con.close()
|
|
||||||
finally:
|
|
||||||
post(server, "/api/admin/mcp", {"enabled": False})
|
|
||||||
|
|
||||||
|
|
||||||
def test_schema_has_mcp_group(server):
|
|
||||||
r = server["client"].get("/api/schema").json()
|
|
||||||
assert "MCP 接入" in r["groups"]
|
|
||||||
paths = [x["path"] for x in r["groups"]["MCP 接入"]]
|
|
||||||
assert "/mcp" in paths and "/api/mcp/status" in paths
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""2026-11-04 主人定(合并工料机口径):
|
|
||||||
① 现算数量为 0 的品种也要显示、也要能参与合并(取代决策 244「0 量码不进弹框」);
|
|
||||||
② 合并弹框的数量与项目级/单位级工料机汇总页同源(dyn_lme 现算),组头按码去重相加。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
|
||||||
taxp REAL, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL,
|
|
||||||
x_merged_hide INT DEFAULT 0)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL,
|
|
||||||
taxrate REAL, taxp REAL, ntp_org REAL, ntp_expr REAL, taxp_org REAL,
|
|
||||||
taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INT, name TEXT)""")
|
|
||||||
# 同组两个码:A 有现算量、B 现算 0(旧口径会被排除)
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, qty, ntp, taxp)
|
|
||||||
VALUES(1, 101, 'A1', '折旧费', '', '元', 3, 10.0, 1.0, 1.0)""")
|
|
||||||
c.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, qty, ntp, taxp)
|
|
||||||
VALUES(1, 101, 'B1', '折旧费', '', '元', 3, 5.0, 1.0, 1.0)""")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_groups_keep_zero_qty(monkeypatch):
|
|
||||||
sc = _mk()
|
|
||||||
# 链可用(dyn_rows 非 None);成员级数量走 qty_map_uw:A1=12.5、B1=0(0 量品种必须仍显示)
|
|
||||||
monkeypatch.setattr(srv.dyn_lme, "dyn_rows",
|
|
||||||
lambda *a, **k: [[None, "A1", "折旧费", "", "元", 12.5],
|
|
||||||
[None, "B1", "折旧费", "", "元", 0.0]])
|
|
||||||
monkeypatch.setattr(srv.dyn_lme, "qty_map_uw", lambda *a, **k: {"A1": 12.5, "B1": 0.0})
|
|
||||||
d = srv._lme_merge_groups(sc, 1)
|
|
||||||
g = [x for x in d["groups"] if x["name"] == "折旧费"]
|
|
||||||
assert g, "折旧费组没出现"
|
|
||||||
g = g[0]
|
|
||||||
codes = {r["code"]: r["qty"] for r in g["rows"]}
|
|
||||||
assert codes.get("B1") == 0.0, "0 量品种被排除了:%s" % codes
|
|
||||||
assert codes.get("A1") == 12.5
|
|
||||||
assert g["qty"] == 12.5 # 组头按码去重相加
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""定额级操作回归(2026-10-15 CRUD 闭环):
|
|
||||||
ntdel(临删,导出原样省略)/ unntdel(恢复)/ unadopt(取消采纳=硬删+品类行回收)+ /api/schema。
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
import api_harness as H
|
|
||||||
from api_harness import server # noqa: F401 (夹具须经导入注册)
|
|
||||||
from api_harness import get, post
|
|
||||||
|
|
||||||
BILL = ("B001", "球机摄像机调试", "1、x", "台", 10, 500)
|
|
||||||
LME = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, params=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, params).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _setup(server, tag):
|
|
||||||
"""导入批次 + 打开同名会话(同源文件→自动关联)→ 采纳追加 1 条定额。
|
|
||||||
文件按 sha256_原名 落进 source_files(真实上传形态),否则 _link_batch 认不出同源。"""
|
|
||||||
proj = "定额闸工程-" + uuid.uuid4().hex[:6] + "-" + tag
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("normop_%s_raw.cos4" % tag)), proj, [BILL], [LME])
|
|
||||||
raw = open(p, "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_normop_%s.cos4" % (hashlib.sha256(raw).hexdigest(), tag))
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
|
|
||||||
assert imp["ok"] is True and imp["n_bill"] >= 1, imp
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
# 决策 243:同一份文件前后台只能存在一边——工作台用同内容双胞胎件
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
bill_id = [r[0] for r in rows["rows"] if r[1] == BILL[0]][0]
|
|
||||||
hc = sqlite3.connect("file:%s?mode=ro" % server["db"], uri=True)
|
|
||||||
src_id = hc.execute("SELECT id FROM bills WHERE batch_id=? AND Number=? AND Kind IS NULL",
|
|
||||||
(imp["batch_id"], BILL[0])).fetchone()[0]
|
|
||||||
hc.close()
|
|
||||||
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
|
|
||||||
"src_bill_id": src_id})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
norm_id = _q(server["sessdb"], "SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1",
|
|
||||||
(bill_id,))[0][0]
|
|
||||||
return proj, sid, bill_id, norm_id
|
|
||||||
|
|
||||||
|
|
||||||
def _n_norm_in_export(server, sid, marker):
|
|
||||||
"""导出包内定额标记出现次数(解压后逐条目计数);导出被闸/失败时把 JSON 错误带出来。"""
|
|
||||||
import io
|
|
||||||
import zipfile
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
if not resp.headers["content-type"].startswith("application/zip"):
|
|
||||||
raise AssertionError("导出失败: " + resp.text[:300])
|
|
||||||
zf = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
return sum(zf.read(n).count(marker) for n in zf.namelist())
|
|
||||||
|
|
||||||
|
|
||||||
def test_norm_ntdel_export_omits(server):
|
|
||||||
proj, sid, bill_id, norm_id = _setup(server, "ntdel")
|
|
||||||
# 采纳语义(规格 9.3):原定额转临删省略,导出只显示采纳定额 → 基线 = 1
|
|
||||||
base = _n_norm_in_export(server, sid, b'Number="N-1"')
|
|
||||||
assert base == 1, base
|
|
||||||
r = post(server, "/api/session/norm/op", {"session_id": sid, "op": "ntdel", "norm_id": norm_id})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert _q(server["sessdb"], "SELECT x_tdel FROM s_norms WHERE id=?", (norm_id,))[0][0] == 1
|
|
||||||
assert _n_norm_in_export(server, sid, b'Number="N-1"') == 0 # 临删的采纳定额也不落盘
|
|
||||||
r = post(server, "/api/session/norm/op", {"session_id": sid, "op": "unntdel", "norm_id": norm_id})
|
|
||||||
assert r["ok"] is True
|
|
||||||
assert _n_norm_in_export(server, sid, b'Number="N-1"') == base # 恢复后又在场
|
|
||||||
# 2026-11-03 决策 264 补记五:工程量统一按数据本体 6 位导出(清单/定额同口径)——
|
|
||||||
# 清单 10 → 10.000000;采纳定额 10 → 10.000000
|
|
||||||
import io as _io
|
|
||||||
import zipfile as _zipfile
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
|
|
||||||
c6 = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
|
|
||||||
c3 = sum(zf.read(n).count(b'Quantity="10.0"') for n in zf.namelist())
|
|
||||||
assert c6 == 1 and c3 == 1, (c6, c3) # 采纳定额 6 位 + 清单 3 位(244 补六,恢复旧引擎口径)
|
|
||||||
|
|
||||||
|
|
||||||
def test_adopt_gcl_default_and_price_overwrite(server):
|
|
||||||
"""决策 90(2026-10-17)(主人定):
|
|
||||||
决策90 采纳的定额工程量默认挂公式**原文 GCL**(Quantity 置空),导出按**当时**清单量求值——
|
|
||||||
清单量后改,定额量跟着走;
|
|
||||||
决策90 采纳后清单单价=采纳的单价,合价=工程量×新单价(9.3 原有清单)。"""
|
|
||||||
import io as _io
|
|
||||||
import zipfile as _zipfile
|
|
||||||
proj, sid, bill_id, norm_id = _setup(server, "adoptgcl")
|
|
||||||
r = _q(server["sessdb"], "SELECT Quantity, qty_expr, Price, x_adopt FROM s_norms WHERE id=?",
|
|
||||||
(norm_id,))[0]
|
|
||||||
# 规格 19:默认公式 = GCL×系数(历史定额量10 ÷ 历史清单量10 = 1.0000)
|
|
||||||
assert r[1] == "GCL*1.0000" and r[0] is None and r[3] == 1, r # 默认公式原文,不是算死的数字
|
|
||||||
# 决策90 9.3:清单单价按采纳价(入库清单价 500)覆盖,合价=工程量 10×500
|
|
||||||
br = _q(server["sessdb"], "SELECT Price, Total, x_adopt FROM s_bills WHERE id=?", (bill_id,))[0]
|
|
||||||
assert abs(br[0] - 500) < 1e-9 and abs(br[1] - 5000) < 1e-9 and br[2] == 1, br
|
|
||||||
# GCL 求值:清单量 10、单位「台」(纯字母)→ 定额量 10.0(6 位小数,源文件规律)
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
|
|
||||||
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
|
|
||||||
c6 = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
|
|
||||||
c3 = sum(zf.read(n).count(b'Quantity="10.0"') for n in zf.namelist())
|
|
||||||
assert c6 == 1 and c3 == 1, (c6, c3) # 清单 10(3 位)+ 采纳定额 10(6 位)
|
|
||||||
# 公式跟清单量走:清单量改 20 → 不改定额、直接导出 → 定额量 20.0
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("UPDATE s_bills SET Quantity=20 WHERE id=?", (bill_id,))
|
|
||||||
# 决策90 价格写穿:会话侧价格与文件不同 → 导出 WorkElement 开标签 Price/Total 按会话值重写
|
|
||||||
con.execute("UPDATE s_bills SET Price=600, Total=6000 WHERE id=?", (bill_id,))
|
|
||||||
con.commit(); con.close()
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
|
|
||||||
c6 = sum(zf.read(n).count(b'Quantity="20.0"') for n in zf.namelist())
|
|
||||||
c3 = sum(zf.read(n).count(b'Quantity="20.0"') for n in zf.namelist())
|
|
||||||
assert c6 == 1 and c3 == 1, (c6, c3) # 清单 20(3 位)+ 公式定额 20(6 位,跟清单量走)
|
|
||||||
# 决策 233/264:合价=工程量×单价(导出按现算写穿,不照搬库里不一致的旧 Total)
|
|
||||||
import xml.etree.ElementTree as _ET
|
|
||||||
_unit_txt = "".join(zf.read(n).decode("utf-8", "replace") for n in zf.namelist()
|
|
||||||
if n.lower() != "project.xml")
|
|
||||||
_root = _ET.fromstring(_unit_txt)
|
|
||||||
_we = _root.find(".//WorkElement[@Number='B001']")
|
|
||||||
assert _we is not None
|
|
||||||
assert _we.attrib["Quantity"] == "20.0" and _we.attrib["Price"] == "600.00" \
|
|
||||||
and _we.attrib["Total"] == "6000.00", dict(_we.attrib) # 写穿会话库值(决策 90;264 前原断言)
|
|
||||||
|
|
||||||
|
|
||||||
def test_norm_unadopt_hard_delete(server):
|
|
||||||
proj, sid, bill_id, norm_id = _setup(server, "unadopt")
|
|
||||||
uw_id = _q(server["sessdb"], "SELECT uw_id FROM s_bills WHERE id=?", (bill_id,))[0][0]
|
|
||||||
# 预置一条假的「采纳新增品类行」(编码不被任何定额消耗引用)→ unadopt 时必须被回收
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, qty, ntp, taxp, x_adopt_added)
|
|
||||||
VALUES(?,?,?,?,?,?,?,?,?,?,1)""",
|
|
||||||
(sid, uw_id, "ZZZ999", "假品类行", "规格Z", "项", 1, 1, 1, 1))
|
|
||||||
con.commit()
|
|
||||||
con.close()
|
|
||||||
print("DBG unadopt前 s_lme_uw:", _q(server["sessdb"], "SELECT id, uw_id, code, x_adopt_added FROM s_lme_uw WHERE session_id=?", (sid,)))
|
|
||||||
print("DBG unadopt前 定额:", _q(server["sessdb"], "SELECT id, bill_id, x_adopt, x_tdel FROM s_norms WHERE bill_id=?", (bill_id,)))
|
|
||||||
r = post(server, "/api/session/norm/op", {"session_id": sid, "op": "unadopt", "norm_id": norm_id})
|
|
||||||
print("DBG unadopt:", r)
|
|
||||||
print("DBG unadopt后 s_lme_uw:", _q(server["sessdb"], "SELECT id, uw_id, code, x_adopt_added FROM s_lme_uw WHERE session_id=?", (sid,)))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert r.get("dropped_lme_uw", 0) >= 1 # 无剩余引用 → 品类行回收
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_norms WHERE id=?", (norm_id,))[0][0] == 0
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_norm_res WHERE norm_id=?", (norm_id,))[0][0] == 0
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_lme_uw WHERE session_id=? AND code='ZZZ999'",
|
|
||||||
(sid,))[0][0] == 0
|
|
||||||
# 非采纳定额不可 unadopt
|
|
||||||
own = _q(server["sessdb"], "SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=0",
|
|
||||||
(bill_id,))[0][0]
|
|
||||||
r = post(server, "/api/session/norm/op", {"session_id": sid, "op": "unadopt", "norm_id": own})
|
|
||||||
assert r["ok"] is False and "ntdel" in r.get("msg", "")
|
|
||||||
|
|
||||||
|
|
||||||
def test_norm_qty_gcl_formula(server):
|
|
||||||
"""规格 2026-10-16 工作台·组价不一致清单:定额工程量收 GCL 公式,清单工程量只收数字。
|
|
||||||
GCL = 清单工程量 ÷ 定额单位数字前缀(到字母截断);纯字母单位 GCL=清单工程量。
|
|
||||||
结果按源文件规律 6 位小数落库(求值结果 round6)。
|
|
||||||
决策 90(2026-10-17):公式按**原文**落 qty_expr(Quantity 置空),quantity=即时求值反馈;
|
|
||||||
纯数字四则(5+3)也合法(不带 GCL 就与清单量无关)。"""
|
|
||||||
proj, sid, bill_id, norm_id = _setup(server, "gcl")
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("UPDATE s_bills SET Quantity=5.03 WHERE id=?", (bill_id,))
|
|
||||||
con.execute("UPDATE s_norms SET Unit='10t' WHERE id=?", (norm_id,))
|
|
||||||
con.commit(); con.close()
|
|
||||||
|
|
||||||
def edit(q):
|
|
||||||
return post(server, "/api/session/norm/op",
|
|
||||||
{"session_id": sid, "norm_id": norm_id, "fields": {"Quantity": q}})
|
|
||||||
|
|
||||||
def row():
|
|
||||||
return _q(server["sessdb"], "SELECT Quantity, qty_expr FROM s_norms WHERE id=?", (norm_id,))[0]
|
|
||||||
|
|
||||||
r = edit("GCL") # 5.03/10 = 0.503
|
|
||||||
assert r["ok"] is True and abs(r["quantity"] - 0.503) < 1e-9, r
|
|
||||||
assert r["expr"] == "GCL" and row()[0] is None and row()[1] == "GCL"
|
|
||||||
r = edit("GCL*(5+9.25+6.36)+GCL") # 0.503*20.61 + 0.503 = 10.86983
|
|
||||||
assert r["ok"] is True and abs(r["quantity"] - 10.86983) < 1e-9, r
|
|
||||||
assert row()[0] is None and row()[1] == "GCL*(5+9.25+6.36)+GCL"
|
|
||||||
r = edit("GCL*GCL") # 决策 216:GCL=清单原值 5.03,结果整体÷10 → 25.3009/10 = 2.53009
|
|
||||||
assert r["ok"] is True and abs(r["quantity"] - 2.53009) < 1e-9, r
|
|
||||||
# 纯字母单位 → GCL=清单工程量
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("UPDATE s_norms SET Unit='t' WHERE id=?", (norm_id,))
|
|
||||||
con.commit(); con.close()
|
|
||||||
r = edit("GCL")
|
|
||||||
assert r["ok"] is True and abs(r["quantity"] - 5.03) < 1e-9, r
|
|
||||||
# 纯数字四则(决策 194,2026-10-25 主人定):实际量口径——8÷单位前缀(t=1)=8 落数,公式列清空
|
|
||||||
r = edit("5+3")
|
|
||||||
assert r["ok"] is True and r["quantity"] == 8, r
|
|
||||||
assert row()[0] == 8 and row()[1] is None
|
|
||||||
# 纯数字=实际量(决策 194):Unit t 前缀 1 → 存 1.5(同尺实例:单位 10m3 输入 20 → 存 2 显 2)
|
|
||||||
r = edit("1.5")
|
|
||||||
assert r["ok"] is True and r["quantity"] == 1.5, r
|
|
||||||
# 非法输入一概拒绝
|
|
||||||
for bad, why in (("GCL; DROP TABLE x", "公式"), ("GCL/(5-5)", "0"),
|
|
||||||
("GCL*abc", "公式"), ("GCL)(", "公式")):
|
|
||||||
r = edit(bad)
|
|
||||||
assert r["ok"] is False and why in r.get("msg", ""), (bad, r)
|
|
||||||
# 清单工程量只收数字(bill/op edit 维持原口径)
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
|
|
||||||
"bill_id": bill_id, "fields": {"Quantity": "GCL"}})
|
|
||||||
assert r["ok"] is False and "数字" in r.get("msg", ""), r
|
|
||||||
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
|
|
||||||
"bill_id": bill_id, "fields": {"Quantity": "7.125"}})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
|
|
||||||
|
|
||||||
def test_qty_export_follows_source_pattern(server):
|
|
||||||
"""规格 2026-10-16「导出时候看原始文件规律,按修改后的数字导出」:
|
|
||||||
改过的清单工程量按 3 位小数、定额按 6 位小数写出;没改的原样保留(不被重写格式)。"""
|
|
||||||
proj, sid, bill_id, norm_id = _setup(server, "qtyfmt")
|
|
||||||
con = sqlite3.connect(server["sessdb"])
|
|
||||||
con.execute("UPDATE s_norms SET Unit='10t', Quantity=NULL WHERE id=?", (norm_id,))
|
|
||||||
con.execute("UPDATE s_bills SET Quantity=7.125 WHERE id=?", (bill_id,))
|
|
||||||
con.commit(); con.close()
|
|
||||||
# GCL 以清单现量 7.125 计算:7.125/10*2 = 1.425
|
|
||||||
r = post(server, "/api/session/norm/op",
|
|
||||||
{"session_id": sid, "norm_id": norm_id, "fields": {"Quantity": "GCL*2"}})
|
|
||||||
assert r["ok"] is True and abs(r["quantity"] - 1.425) < 1e-9, r
|
|
||||||
# 恢复被采纳语义临删的原定额(工程量 10.0 未改)→ 验证「未改不重写格式」
|
|
||||||
own = _q(server["sessdb"], "SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=0",
|
|
||||||
(bill_id,))[0][0]
|
|
||||||
assert post(server, "/api/session/norm/op",
|
|
||||||
{"session_id": sid, "op": "unntdel", "norm_id": own})["ok"] is True
|
|
||||||
import io as _io
|
|
||||||
import zipfile as _zipfile
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:200]
|
|
||||||
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
|
|
||||||
allx = b"".join(zf.read(n) for n in zf.namelist())
|
|
||||||
assert allx.count(b'Quantity="1.425000"') == 1, allx.count(b'Quantity="1.425000"') # 采纳定额 6 位
|
|
||||||
assert allx.count(b'Quantity="7.125"') == 1, allx.count(b'Quantity="7.125"') # 改过的清单(3 位,244 补六)
|
|
||||||
assert allx.count(b'Quantity="10.0"') == 1, allx.count(b'Quantity="10.0"') # 未改的原定额(源件原样保留)
|
|
||||||
|
|
||||||
|
|
||||||
def test_schema_self_describe(server):
|
|
||||||
s = get(server, "/api/schema")
|
|
||||||
assert s["product"] == "造价审核"
|
|
||||||
groups = s["groups"]
|
|
||||||
for g in ("会话", "查询", "清单写", "定额写", "采纳", "工料机", "导出", "后台", "系统"):
|
|
||||||
assert g in groups and groups[g], g
|
|
||||||
norm_ops = [x for x in groups["定额写"] if x["path"] == "/api/session/norm/op"]
|
|
||||||
assert norm_ops and "ntdel" in norm_ops[0]["params"].get("op*", "")
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策78(2026-10-15 主人口径)防回归。
|
|
||||||
|
|
||||||
① 合并工料机弹框——带子级组成的工料机(lme_res 有 p_code 记录,台班/配合比)整行不进分组
|
|
||||||
(原软件按子级组成×子价重算,改母级会被覆盖,决策76/77 实证)。
|
|
||||||
② 子目工料机名称按编码解析——首选本单位工料机汇总(s_lme_uw),本单位没有的去
|
|
||||||
项目工料机汇总(s_lme_proj);都没有再走旧链(lmes join → lme_lib → VIRT_RES)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
DDL = """
|
|
||||||
CREATE TABLE sessions(id INTEGER PRIMARY KEY, name TEXT, src_name TEXT);
|
|
||||||
CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, Number TEXT);
|
|
||||||
CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT);
|
|
||||||
CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL);
|
|
||||||
CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT, Number TEXT, Name TEXT,
|
|
||||||
Specification TEXT, Unit TEXT, Kind INT, NoTaxPrice REAL, TaxPrice REAL);
|
|
||||||
CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
|
||||||
res_code TEXT, qty REAL, seq INT, name TEXT);
|
|
||||||
CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, code TEXT,
|
|
||||||
name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT);
|
|
||||||
CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT, name TEXT,
|
|
||||||
spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxp REAL,
|
|
||||||
taxrate REAL, x_merged_hide INT DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT);
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
sc.executescript(DDL)
|
|
||||||
sc.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
|
|
||||||
# 清单1(属单位工程 10)→ 定额1
|
|
||||||
sc.execute("INSERT INTO s_bills VALUES(1, 1, 10, 'B1')")
|
|
||||||
sc.execute("INSERT INTO s_norms VALUES(1, 1, NULL)")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _first_row(sc):
|
|
||||||
return srv._norm_res(sc, srv.TBL["session"], 1)["rows"][0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_name_prefers_unit_summary():
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lmes VALUES(1,1,'C1','lmes名','','m',2,10.0,11.0)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res VALUES(1,1,'C1',2.5)")
|
|
||||||
sc.execute("INSERT INTO s_lme_uw(session_id,uw_id,code,name) VALUES(1,10,'C1','单位汇总名')")
|
|
||||||
r = _first_row(sc)
|
|
||||||
assert r[1] == "单位汇总名" # ① 首选本单位汇总(盖过 lmes 名)
|
|
||||||
assert r[5] == 2.5 and r[6] == 10.0 and r[7] == 11.0 # 消耗量/单价仍来自原链
|
|
||||||
|
|
||||||
|
|
||||||
def test_falls_to_project_summary():
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_norm_res VALUES(1,1,'C2',1.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id,code,name,unit) VALUES(1,'C2','项目汇总名','m3')")
|
|
||||||
r = _first_row(sc)
|
|
||||||
assert r[1] == "项目汇总名" and r[3] == "m3" # ② 本单位没有 → 项目级汇总
|
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_chain_intact():
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lmes VALUES(1,1,'C3','旧链名','','m',2,3.0,4.0)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res VALUES(1,1,'C3',1.0)")
|
|
||||||
r = _first_row(sc)
|
|
||||||
assert r[1] == "旧链名" # 汇总都没有 → lmes 旧链(防回归)
|
|
||||||
|
|
||||||
|
|
||||||
def test_prices_filled_from_summary_when_missing():
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lmes VALUES(1,1,'C4','lmes名C4','','m',2,NULL,NULL)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res VALUES(1,1,'C4',1.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_uw(session_id,uw_id,code,name,ntp,taxp) "
|
|
||||||
"VALUES(1,10,'C4','单位汇总名C4',7.0,8.0)")
|
|
||||||
r = _first_row(sc)
|
|
||||||
assert r[1] == "单位汇总名C4" and r[6] == 7.0 and r[7] == 8.0 # 价格只在缺时补
|
|
||||||
|
|
||||||
|
|
||||||
def test_collision_row_takes_summary_whole():
|
|
||||||
"""同一编码跨单位工程常是不同资源(ZC-0003 实测:292单位=重型碳钢门/樘、294单位=交通协管员/工日)。
|
|
||||||
命中本单位汇总后整行以汇总为准——不许拼出「交通协管员/樘/35398」这种 Frankenstein 行。"""
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lmes VALUES(1,1,'ZC-9','重型碳钢门','含1.5kW电机','樘',4,35398.23,35398.23)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res VALUES(1,1,'ZC-9',1.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_uw(session_id,uw_id,code,name,spec,unit,kind,ntp,taxp) "
|
|
||||||
"VALUES(1,10,'ZC-9','交通协管员','','工日',4,120.0,126.0)")
|
|
||||||
r = _first_row(sc)
|
|
||||||
assert r[1] == "交通协管员" and r[2] == "" and r[3] == "工日" # 整行=汇总真身
|
|
||||||
assert r[6] == 120.0 and r[7] == 126.0 # 价格也随汇总(join 是别家的)
|
|
||||||
|
|
||||||
|
|
||||||
def test_merge_groups_keep_composite_rows():
|
|
||||||
"""2026-10-16 规格 第9条:不过滤带子数据的工料机(决策78 的整行去掉废止)——
|
|
||||||
带子级组成的行回到弹框,行带 sub 标记;全量参组。"""
|
|
||||||
sc = _mk()
|
|
||||||
# 组A:同 名称|规格|单位、编码/价格不同 —— 正常成组
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id,session_id,code,name,spec,unit,qty,ntp,taxrate,taxp) "
|
|
||||||
"VALUES(1,1,'A1','水泥','P.O','kg',10,1.0,3.5,2.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id,session_id,code,name,spec,unit,qty,ntp,taxrate,taxp) "
|
|
||||||
"VALUES(2,1,'A12','水泥','P.O','kg',5,2.0,3.5,3.0)")
|
|
||||||
# 组B:也是两条,B1 带子级组成(lme_res 有 p_code)→ 仍在弹框,带 sub 标记
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id,session_id,code,name,spec,unit,qty,ntp,taxrate,taxp) "
|
|
||||||
"VALUES(3,1,'B1','焊机台班','','台班',3,6.0,3.5,7.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(id,session_id,code,name,spec,unit,qty,ntp,taxrate,taxp) "
|
|
||||||
"VALUES(4,1,'B2','焊机台班','','台班',2,7.0,3.5,8.0)")
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id,p_code,res_code,qty,seq) VALUES(1,'B1','99450700',63.0,1)")
|
|
||||||
sc.commit()
|
|
||||||
# 决策 186 v3:弹框视野=各单位工程品类并集——项目级行不再参组(本假库只有项目级行 → 组为空);
|
|
||||||
# 单位级行(_mk 若补 s_lme_uw)才成组。此测试转为守「项目级不进弹框」的新口径。
|
|
||||||
d = srv._lme_merge_groups(sc, 1)
|
|
||||||
assert d["groups"] == [] # 项目级不进弹框(并集视野)
|
|
||||||
assert d["n_rows"] == 4 # n_rows=扫描到的行数(不含过滤口径),组数为 0 才是视野断言
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 201(2026-10-25 主人定)防回归:打开/解析两级汇总对齐 + 实测五修。
|
|
||||||
|
|
||||||
钉死六件事:
|
|
||||||
①合并「项目级没有该保留码行→新增一行」(171 补三):勾单位级行、保留码带六价扩展、
|
|
||||||
项目级无该码行 → INSERT 用**纯列名段**(修「col=?」误拼进列名清单的语法错误)→
|
|
||||||
合并成功且项目级行落库(给水管PP-R DN15 实测样例)。
|
|
||||||
②同码异物主动拆(_proactive_ident_split):同码 ≥2 名规单 → 最早者留原码、其余 @n、
|
|
||||||
recode_ident 键=名规单(**映射带来源**)、项目级跟随;幂等(再跑=0)。
|
|
||||||
③项目级对齐(_align_proj_summary):名|规|单=幸存名规单、数量=Σ uw、价格=升序中位;
|
|
||||||
骨架行(无 uw 支撑、未隐藏)数量归零;已隐藏骨架行不碰(复活逻辑还靠它)。
|
|
||||||
④dedupe_lme_uw:整行雷同双行收敛为 1(GROUP BY 不含 id——修自愈空转)。
|
|
||||||
⑤注入收敛「有映射才补」:recode_map 空 → 注入零动作;映射父码的子级补到缺的单位、
|
|
||||||
无映射父码的子级不铺(修「8 次合并注入 6274 行」)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
import session_job as sessj # noqa: E402
|
|
||||||
|
|
||||||
SID = 1
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
|
||||||
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL,
|
|
||||||
x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT, UNIQUE(session_id, code))""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
|
||||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
|
|
||||||
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
|
||||||
PRIMARY KEY(scope,k))""")
|
|
||||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, x_tdel INTEGER DEFAULT 0)")
|
|
||||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL DEFAULT 1, x_tdel INTEGER DEFAULT 0, x_side TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
|
|
||||||
res_code TEXT, qty REAL, express TEXT)""")
|
|
||||||
c.execute("CREATE TABLE sessions(id INTEGER PRIMARY KEY, src_name TEXT)")
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _uw(sc, uw_id, code, name, spec, unit, qty, ntp=None, taxrate=None, taxp=None, kind=2):
|
|
||||||
sc.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, qty,
|
|
||||||
ntp, taxrate, taxp) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
|
|
||||||
(SID, uw_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp))
|
|
||||||
|
|
||||||
|
|
||||||
# ── ① 项目级无行→新增(六价扩展在身)───────────────────────────────────
|
|
||||||
def test_merge_insert_new_proj_row_with_px6():
|
|
||||||
"""给水管PP-R 样例:保留码 17250050-0003 项目级无行(拆分挪走后的常态),
|
|
||||||
勾它合并必须成功并按纯列名段新增项目级行。"""
|
|
||||||
sc = _mk()
|
|
||||||
_uw(sc, 101, "17250050-0003", "给水管PP-R", "DN15", "m", 3.0, 9.1, 3.0, 9.37)
|
|
||||||
_uw(sc, 102, "17250050-0010", "给水管PP-R", "DN15", "m", 4.0, 53.93, 3.0, 55.55)
|
|
||||||
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": "17250050-0003", "uw_ids": [101], "ntp": 9.1, "taxrate": 3.0,
|
|
||||||
"taxp": 9.37, "ntp_org": 9.1, "ntp_expr": "9.1", "taxp_org": 9.37,
|
|
||||||
"taxp_expr": "9.37", "name": "给水管PP-R", "spec": "DN15", "unit": "m",
|
|
||||||
"kind": 2, "qty": 0},
|
|
||||||
"hide": [{"uw": 1, "code": "17250050-0010", "uw_ids": [102]}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
row = sc.execute("SELECT code, name, spec, unit, ntp, ntp_org, taxp_expr FROM s_lme_proj"
|
|
||||||
" WHERE session_id=?", (SID,)).fetchone()
|
|
||||||
assert row is not None
|
|
||||||
assert row["code"] == "17250050-0003"
|
|
||||||
assert (row["name"], row["spec"], row["unit"]) == ("给水管PP-R", "DN15", "m")
|
|
||||||
assert row["ntp"] == 9.1 and row["ntp_org"] == 9.1 and float(row["taxp_expr"]) == 9.37
|
|
||||||
# 变体换码
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw WHERE code='17250050-0010'").fetchone()[0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
# ── ② 同码异物主动拆 ────────────────────────────────────────────────
|
|
||||||
def test_proactive_ident_split_and_idempotent():
|
|
||||||
sc = _mk()
|
|
||||||
_uw(sc, 101, "C", "洗衣机两用地漏", "DN75", "个", 30.0) # id 最小 → 保留原码
|
|
||||||
_uw(sc, 102, "C", "间接排水漏斗", "DN40", "个", 8.0) # → C@1
|
|
||||||
_uw(sc, 103, "C", "网罩式地漏", "DN150", "个", 4.0) # → C@2
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty)"
|
|
||||||
" VALUES(?, 'C', '网罩式地漏', 'DN150', '个', 4.0)", (SID,)) # 项目级恰好挂被拆名规单 → 跟随
|
|
||||||
n = srv._proactive_ident_split(sc, SID)
|
|
||||||
assert n == 2
|
|
||||||
assert sorted(x["code"] for x in sc.execute(
|
|
||||||
"SELECT DISTINCT code FROM s_lme_uw WHERE session_id=?", (SID,))) == ["C", "C@1", "C@2"]
|
|
||||||
assert sc.execute("SELECT code FROM s_lme_uw WHERE name='洗衣机两用地漏'").fetchone()["code"] == "C"
|
|
||||||
assert sc.execute("SELECT code FROM s_lme_proj WHERE session_id=?", (SID,)).fetchone()["code"] == "C@2"
|
|
||||||
ident = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='recode_ident'",
|
|
||||||
("session:%d" % SID,)).fetchone()["v"]
|
|
||||||
import json
|
|
||||||
m = json.loads(ident)["C"]
|
|
||||||
assert m["间接排水漏斗␟DN40␟个".replace("␟", "\x1f")] == "C@1"
|
|
||||||
assert m["网罩式地漏␟DN150␟个".replace("␟", "\x1f")] == "C@2"
|
|
||||||
assert srv._proactive_ident_split(sc, SID) == 0 # 幂等
|
|
||||||
|
|
||||||
|
|
||||||
# ── ③ 项目级对齐 ────────────────────────────────────────────────────
|
|
||||||
def test_align_proj_summary():
|
|
||||||
sc = _mk()
|
|
||||||
_uw(sc, 101, "C", "给水管PP-R", "DN15", "m", 3.0, 10.0, 3.0, 10.3)
|
|
||||||
_uw(sc, 102, "C", "给水管PP-R", "DN15", "m", 5.0, 20.0, 3.0, 20.6)
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, ntp)"
|
|
||||||
" VALUES(?, 'C', '旧名', '旧规格', 'm', 99.0, 123.0)", (SID,)) # 名规单/数据全被对齐覆盖
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, x_merged_hide)"
|
|
||||||
" VALUES(?, 'S', '骨架行', '', '项', 55.0, 0)", (SID,)) # 无 uw 支撑 → 归零
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, x_merged_hide)"
|
|
||||||
" VALUES(?, 'H', '已隐藏骨架行', '', '项', 66.0, 1)", (SID,)) # 已隐藏 → 不碰
|
|
||||||
na, nz = srv._align_proj_summary(sc, SID)
|
|
||||||
row = sc.execute("SELECT name, spec, qty, ntp FROM s_lme_proj WHERE code='C'").fetchone()
|
|
||||||
assert (row["name"], row["spec"]) == ("给水管PP-R", "DN15")
|
|
||||||
assert row["qty"] == 8.0 # Σ uw
|
|
||||||
assert row["ntp"] == 10.0 # 升序中位:[10,20] 取低
|
|
||||||
assert sc.execute("SELECT qty FROM s_lme_proj WHERE code='S'").fetchone()[0] == 0
|
|
||||||
assert sc.execute("SELECT qty FROM s_lme_proj WHERE code='H'").fetchone()[0] == 66.0
|
|
||||||
|
|
||||||
|
|
||||||
# ── ④ dedupe 收敛 ──────────────────────────────────────────────────
|
|
||||||
def test_dedupe_lme_uw_collapses_identical_rows():
|
|
||||||
sc = _mk()
|
|
||||||
_uw(sc, 101, "K", "名", "规", "个", 3.0, 9.1)
|
|
||||||
_uw(sc, 101, "K", "名", "规", "个", 3.0, 9.1) # 整行雷同(id 不同)
|
|
||||||
sessj.dedupe_lme_uw(sc)
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw").fetchone()[0] == 1
|
|
||||||
|
|
||||||
|
|
||||||
# ── ⑤ 注入收敛 ─────────────────────────────────────────────────────
|
|
||||||
def test_inject_refs_only_mapped():
|
|
||||||
"""注入行数量=该单位现算(决策 202 补):102 无组成 → 数量留空(None)。"""
|
|
||||||
sc = _mk()
|
|
||||||
# 映射父码 KEEP 的子级 C1;无映射父码 UNREL 的子级 C2
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(?, 'KEEP', 'C1', 1.5, 1, '子一')", (SID,))
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(?, 'UNREL', 'C2', 2.5, 1, '子二')", (SID,))
|
|
||||||
# 项目级各有两码;uw 只有 101 有
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, ntp)"
|
|
||||||
" VALUES(?, 'C1', '子一', '', '个', 1.0, 5.0)", (SID,))
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, ntp)"
|
|
||||||
" VALUES(?, 'C2', '子二', '', '个', 2.0, 6.0)", (SID,))
|
|
||||||
_uw(sc, 101, "C1", "子一", "", "个", 1.0, 5.0)
|
|
||||||
_uw(sc, 101, "C2", "子二", "", "个", 2.0, 6.0)
|
|
||||||
_uw(sc, 102, "FILLER", "占位", "", "个", 1.0) # 让 102 单位进入注入循环
|
|
||||||
sc.execute("INSERT INTO s_settings(scope, k, v) VALUES(?, 'recode_map', ?)",
|
|
||||||
("session:%d" % SID, '{"VAR": "KEEP"}'))
|
|
||||||
n_up, n_ins = srv._inject_missing_refs(sc, SID)
|
|
||||||
assert n_ins == 1 # 映射父码的 C1 落位 102(186⑤ 品类全集)
|
|
||||||
_r = sc.execute("SELECT qty FROM s_lme_uw WHERE code='C1' AND uw_id=102").fetchone()
|
|
||||||
assert _r[0] is None # 102 无组成 → 数量留空(决策 202 补:不带项目级值)
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw WHERE code='C2' AND uw_id=102").fetchone()[0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_inject_refs_qty_computed_per_unit():
|
|
||||||
"""注入行数量=该单位现算(决策 202 补):102 的定额 C1 消耗 2.0×工程量 10 → 注入行 qty=20,
|
|
||||||
不再带项目级值(虚增根除)。"""
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(?, 'KEEP', 'C1', 1.5, 1, '子一')", (SID,))
|
|
||||||
sc.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, qty, ntp)"
|
|
||||||
" VALUES(?, 'C1', '子一', '', '个', 999.0, 5.0)", (SID,)) # 项目级值 999 不得再被带走
|
|
||||||
_uw(sc, 101, "C1", "子一", "", "个", 1.0, 5.0)
|
|
||||||
_uw(sc, 102, "FILLER", "占位", "", "个", 1.0)
|
|
||||||
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(10, ?, 102)", (SID,))
|
|
||||||
sc.execute("INSERT INTO s_norms(id, bill_id, Quantity) VALUES(50, 10, 10.0)")
|
|
||||||
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(50, 'C1', 2.0)")
|
|
||||||
sc.execute("INSERT INTO s_settings(scope, k, v) VALUES(?, 'recode_map', ?)",
|
|
||||||
("session:%d" % SID, '{"VAR": "KEEP"}'))
|
|
||||||
n_up, n_ins = srv._inject_missing_refs(sc, SID)
|
|
||||||
assert n_ins == 1
|
|
||||||
row = sc.execute("SELECT qty FROM s_lme_uw WHERE code='C1' AND uw_id=102").fetchone()
|
|
||||||
assert row[0] is not None and abs(row[0] - 20.0) < 1e-9 # 2.0×10 现算,不是 999
|
|
||||||
|
|
||||||
|
|
||||||
def test_inject_refs_no_map_no_action():
|
|
||||||
sc = _mk()
|
|
||||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)"
|
|
||||||
" VALUES(?, 'KEEP', 'C1', 1.5, 1, '子一')", (SID,))
|
|
||||||
_uw(sc, 101, "C1", "子一", "", "个", 1.0)
|
|
||||||
assert srv._inject_missing_refs(sc, SID) == (0, 0) # 无映射 → 整个注入跳过
|
|
||||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_uw WHERE uw_id=102").fetchone()[0] == 0
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 267(2026-11-04):导出骨架优先用**本项目自己的骨架**。
|
|
||||||
- 打开工程时从源件提炼存 sessions.x_own_blank/x_own_meta;
|
|
||||||
- 数据层列覆盖齐全 → 独占使用,后台骨架不参与;
|
|
||||||
- 缺列 → 后台骨架补列;缺整层 → 回落后台骨架。
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
import uuid
|
|
||||||
import zipfile
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
|
|
||||||
import api_harness as H # noqa: E402
|
|
||||||
import classic_skeleton as cs # noqa: E402
|
|
||||||
import export_v2 as ev # noqa: E402
|
|
||||||
from api_harness import post, server # noqa: F401,E402
|
|
||||||
|
|
||||||
|
|
||||||
def test_own_layers_only_not_columns():
|
|
||||||
"""2026-11-04 主人定:**列不算全部数据,只要数据层齐全就算覆盖**。"""
|
|
||||||
plan = {
|
|
||||||
"units": [{"id": 1, "number": "01", "name": "单位", "total": 10.0, "lme": [{}],
|
|
||||||
"bills": [{"Number": "B1", "Name": "清单", "Attr": "特征",
|
|
||||||
"Unit": "m3", "Quantity": 2.0, "Price": 3.0, "Total": 6.0,
|
|
||||||
"qty_expr": "", "kind": "item", "x_tdel": 0,
|
|
||||||
"norms": [{"Number": "N1", "Name": "定额", "Unit": "m3",
|
|
||||||
"Quantity": 1.0, "Price": 2.0, "Total": 2.0,
|
|
||||||
"x_tdel": 0, "res": [("C1", 1.5, "1.5*1.0")]}]}]}],
|
|
||||||
"divides": {1: {"id": 1, "uw_id": 1, "kind": "item", "number": "D1", "name": "分部"}},
|
|
||||||
}
|
|
||||||
need, prelim_tags, need_prelim_div = ev._own_layers(plan)
|
|
||||||
assert {"UnitWorks", "DivisionalWorks", "WorkElement", "Norm",
|
|
||||||
"LabourMaterialsEquipmentsMachinesElement",
|
|
||||||
"LabourMaterialsEquipmentsMachinesSummary"} <= need
|
|
||||||
# 空骨架:缺层 → 判不覆盖
|
|
||||||
empty = ET.fromstring("<ConstructionProject/>")
|
|
||||||
tags0 = {e.tag for e in empty.iter()}
|
|
||||||
miss = ev._missing_layers(need, prelim_tags, need_prelim_div, tags0)
|
|
||||||
assert "UnitWorks" in miss and "Norm" in miss
|
|
||||||
# 只有层、一列都没有:仍算覆盖(列不算全部数据)
|
|
||||||
bare = ET.fromstring(
|
|
||||||
"<ConstructionProject><UnitWorks/><DivisionalWorks/><WorkElement/>"
|
|
||||||
"<Norm/><LabourMaterialsEquipmentsMachinesElement/>"
|
|
||||||
"<LabourMaterialsEquipmentsMachinesSummary/></ConstructionProject>")
|
|
||||||
tags1 = {e.tag for e in bare.iter()}
|
|
||||||
assert ev._missing_layers(need, prelim_tags, need_prelim_div, tags1) == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_uses_own_skeleton_with_extra_columns(server):
|
|
||||||
"""本项目骨架有、后台骨架没有的列 → 导出仍保留(证明优先本项目骨架)。"""
|
|
||||||
proj = "本项目骨架工程-" + uuid.uuid4().hex[:6]
|
|
||||||
# ① 后台骨架:另一件(没有 TechnicalAndEconomicIndex 列)
|
|
||||||
p_back = H.make_cos4(str(server["src_dir"] / ("ownback_%s.cos4" % proj[-6:])), "后台骨架件",
|
|
||||||
[("B900", "后台清单", "", "m3", 1, 1)])
|
|
||||||
con = sqlite3.connect(server["db"])
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
assert cs.seed_frame(con, p_back, "后台骨架-" + proj[-6:])
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
# ② 本项目源件:分部带一列 TechnicalAndEconomicIndex(后台骨架没有)
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / ("own_%s_raw.cos4" % proj[-6:])), proj,
|
|
||||||
[("B001", "清单甲", "1、x", "m3", 10, 100)],
|
|
||||||
[("000001", "人工", "", "工日", "1", "1")])
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
|
||||||
for n in z.namelist():
|
|
||||||
d = z.read(n)
|
|
||||||
if n.lower() != "project.xml":
|
|
||||||
t = d.decode("utf-8").replace(
|
|
||||||
'<DivisionalWorks Number="D1" Name="安装工程" Code="03">',
|
|
||||||
'<DivisionalWorks Number="D1" Name="安装工程" Code="03"'
|
|
||||||
' TechnicalAndEconomicIndex="9.99">')
|
|
||||||
d = t.encode("utf-8")
|
|
||||||
zo.writestr(n, d)
|
|
||||||
src = server["src_dir"] / ("own_%s.cos4" % proj[-6:])
|
|
||||||
src.write_bytes(buf.getvalue())
|
|
||||||
raw = open(str(src), "rb").read()
|
|
||||||
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_own.cos4" % hashlib.sha256(raw).hexdigest())
|
|
||||||
with open(hp, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
|
|
||||||
"district": H.META["district"], "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
|
|
||||||
# 打开后应已存本项目骨架
|
|
||||||
sc = sqlite3.connect(server["sessdb"])
|
|
||||||
row = sc.execute("SELECT x_own_blank FROM sessions WHERE id=?", (sid,)).fetchone()
|
|
||||||
sc.close()
|
|
||||||
assert row and row[0], "打开工程应提炼并保存本项目骨架"
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
|
|
||||||
i_dv = unit.find("<DivisionalWorks ")
|
|
||||||
assert i_dv >= 0 and "TechnicalAndEconomicIndex=" in unit[i_dv:i_dv + 400], unit[:300]
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""数据库性能 / 压测基线(工具代码,不碰软件本体)。
|
|
||||||
|
|
||||||
设计原则(见 输出/测试对账与修复报告_20261017.md 的独立意见):
|
|
||||||
- 软基线:实测数值打印出来(pytest -s 可见),超阈值时**标黄警告但不硬失败**,
|
|
||||||
避免用已知性能缺陷(sid=17 那 15230 清单打开 >32s 不稳定)反过来卡死日常提交。
|
|
||||||
- 规模可用环境变量 PR_PERF_BILLS 调(默认 3000;要复现 15230 案例设 15000)。
|
|
||||||
- 全部走 api_harness 的临时库,生产库零接触。
|
|
||||||
|
|
||||||
覆盖场景:
|
|
||||||
1. 大工程导入吞吐(后台 /api/admin/import,写 history.db)
|
|
||||||
2. 打开大工程解析耗时(/api/audit,写 session.db,原 >32s 病灶)
|
|
||||||
3. 清单加载耗时(/api/session/rows,读 session.db)
|
|
||||||
4. 锁竞争回归:导入大工程(写 history.db)期间,并发读 /api/admin/batches 不得死等
|
|
||||||
—— 直接守住 2026-10-10 的「按钮全点不动」锁库死等修复。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from api_harness import META, fixture_file, server # noqa: F401
|
|
||||||
|
|
||||||
# 软阈值(秒)——仅告警,不失败
|
|
||||||
SOFT_IMPORT_SEC = 30.0
|
|
||||||
SOFT_AUDIT_SEC = 30.0
|
|
||||||
SOFT_ROWS_SEC = 5.0
|
|
||||||
SOFT_READ_SEC = 8.0 # 锁竞争下单次读不得死等(> 即疑似死等)
|
|
||||||
|
|
||||||
DEFAULT_BILLS = int(os.environ.get("PR_PERF_BILLS", "3000"))
|
|
||||||
|
|
||||||
|
|
||||||
def _heavy_client(server):
|
|
||||||
# 重型调用放宽超时(默认 harness client 是 60s,大工程解析可能更久)
|
|
||||||
return httpx.Client(base_url="http://127.0.0.1:%d" % server["port"], timeout=300)
|
|
||||||
|
|
||||||
|
|
||||||
def _report(name, secs, n=None, soft=None):
|
|
||||||
if n:
|
|
||||||
rate = (n / secs) if secs else 0
|
|
||||||
line = "[perf] %-22s %.2fs (%d 项, %.0f 项/s)" % (name, secs, n, rate)
|
|
||||||
else:
|
|
||||||
line = "[perf] %-22s %.2fs" % (name, secs)
|
|
||||||
print(line)
|
|
||||||
if soft is not None and secs > soft:
|
|
||||||
print(" ⚠ 超过软阈值 %.1fs —— 性能回归预警(不阻塞提交)" % soft)
|
|
||||||
return secs
|
|
||||||
|
|
||||||
|
|
||||||
def _big_bills(scale, prefix):
|
|
||||||
return [("%s%05d" % (prefix, i), "清单项%d" % i, "项目特征%d" % i, "项", i + 1, 100.0 + i)
|
|
||||||
for i in range(scale)]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.perf
|
|
||||||
def test_large_project_import_and_open(server):
|
|
||||||
scale = DEFAULT_BILLS
|
|
||||||
name = "性能基线工程"
|
|
||||||
bills = _big_bills(scale, "B")
|
|
||||||
# 注意:make_cos4 的 lmes 各字段须为字符串(quoteattr 要求)
|
|
||||||
lmes = [("L0001", "水泥", "P.O42.5", "t", "385.0", "435.05"),
|
|
||||||
("L0002", "钢筋", "Φ16", "t", "3880.0", "3996.4")]
|
|
||||||
fp = fixture_file(server, "perf_large.cos4", name, bills, lmes)
|
|
||||||
|
|
||||||
cl = _heavy_client(server)
|
|
||||||
|
|
||||||
# 1) 导入后台(写 history.db)
|
|
||||||
t0 = time.time()
|
|
||||||
r = cl.post("/api/admin/import",
|
|
||||||
json=dict(META, path=str(fp), name=name, file_kind=1)).json()
|
|
||||||
import_sec = time.time() - t0
|
|
||||||
assert r.get("ok") is True, r
|
|
||||||
_report("import(后台导入)", import_sec, scale, SOFT_IMPORT_SEC)
|
|
||||||
|
|
||||||
# 2) 打开工程→解析(写 session.db,原 >32s 病灶)
|
|
||||||
t0 = time.time()
|
|
||||||
r2 = cl.post("/api/audit", json=dict(META, path=str(fp), name=name)).json()
|
|
||||||
audit_sec = time.time() - t0
|
|
||||||
assert r2.get("ok") is True, r2
|
|
||||||
sid = r2["session_id"]
|
|
||||||
_report("audit(打开解析)", audit_sec, scale, SOFT_AUDIT_SEC)
|
|
||||||
|
|
||||||
# 3) 清单加载(读 session.db)
|
|
||||||
t0 = time.time()
|
|
||||||
rows = cl.get("/api/session/rows",
|
|
||||||
params=dict(session_id=sid, type="bill", page=1, page_size=200)).json()
|
|
||||||
rows_sec = time.time() - t0
|
|
||||||
# /api/session/rows 返回体为 {total, rows},无 ok 字段
|
|
||||||
assert "rows" in rows and "total" in rows, rows
|
|
||||||
_report("session/rows(清单加载)", rows_sec, rows.get("total"), SOFT_ROWS_SEC)
|
|
||||||
|
|
||||||
cl.close()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.perf
|
|
||||||
def test_read_not_starved_under_write(server):
|
|
||||||
"""锁竞争回归:导入大工程(写 history.db)期间,并发读 /api/admin/batches 不得死等。"""
|
|
||||||
scale = max(DEFAULT_BILLS, 1000)
|
|
||||||
name = "锁竞争工程"
|
|
||||||
bills = _big_bills(scale, "C")
|
|
||||||
fp = fixture_file(server, "perf_lock.cos4", name, bills)
|
|
||||||
|
|
||||||
cl = _heavy_client(server)
|
|
||||||
|
|
||||||
err = {}
|
|
||||||
|
|
||||||
def _writer():
|
|
||||||
try:
|
|
||||||
rr = cl.post("/api/admin/import",
|
|
||||||
json=dict(META, path=str(fp), name=name, file_kind=1)).json()
|
|
||||||
err["ok"] = rr.get("ok")
|
|
||||||
except Exception as e: # noqa: BLE001
|
|
||||||
err["exc"] = repr(e)
|
|
||||||
|
|
||||||
t = threading.Thread(target=_writer, daemon=True)
|
|
||||||
t.start()
|
|
||||||
|
|
||||||
max_lat = 0.0
|
|
||||||
samples = 0
|
|
||||||
deadline = time.time() + 90
|
|
||||||
while time.time() < deadline and t.is_alive():
|
|
||||||
t0 = time.time()
|
|
||||||
try:
|
|
||||||
cl.get("/api/admin/batches", params=dict(page=1, page_size=10)).json()
|
|
||||||
except Exception as e: # noqa: BLE001
|
|
||||||
err.setdefault("read_exc", repr(e))
|
|
||||||
max_lat = max(max_lat, time.time() - t0)
|
|
||||||
samples += 1
|
|
||||||
t.join(timeout=30)
|
|
||||||
|
|
||||||
_report("read-under-write 最大读延迟", max_lat, samples, SOFT_READ_SEC)
|
|
||||||
assert max_lat < SOFT_READ_SEC, (
|
|
||||||
"锁竞争下读延迟 %.2fs 超过阈值 %.1fs,疑似死等(回归 #锁竞争修复);"
|
|
||||||
"若确为性能问题请排查 _open_ro 短超时是否生效" % (max_lat, SOFT_READ_SEC))
|
|
||||||
if err:
|
|
||||||
print("[perf] writer/reader 异常(不影响延迟断言):", err)
|
|
||||||
|
|
||||||
cl.close()
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""platform_skeleton 离线单测:升级包内置骨架的加载/校验/摘要(无网络逻辑)。"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "app"))
|
|
||||||
|
|
||||||
from core import platform_skeleton as ps # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _good_data():
|
|
||||||
return {
|
|
||||||
"suffix": {"name": "cos4", "group": "广东省"},
|
|
||||||
"version": "v1",
|
|
||||||
"dirs": [
|
|
||||||
{"id": 1, "parent_id": None, "name": "建设项目", "sort": 0, "anchor": "ConstructionProject", "columns": []},
|
|
||||||
{"id": 2, "parent_id": 1, "name": "工程信息(起)", "sort": 1, "anchor": "ConstructionInfo",
|
|
||||||
"columns": [{"id": 9, "name": "费用精度", "is_value": False, "sort": 0, "parent_id": None, "value": "Option"}]},
|
|
||||||
{"id": 3, "parent_id": 1, "name": "工程信息(闭)", "sort": 2, "anchor": "/ConstructionInfo", "columns": []},
|
|
||||||
],
|
|
||||||
"files": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _write_bundle(tmp_path, data, suffix="cos4"):
|
|
||||||
(tmp_path / "skeletons").mkdir(exist_ok=True)
|
|
||||||
(tmp_path / "skeletons" / f"{suffix}.json").write_text(
|
|
||||||
json.dumps({"data": data}, ensure_ascii=False), encoding="utf8")
|
|
||||||
|
|
||||||
|
|
||||||
def test_load_ok_and_summary(tmp_path):
|
|
||||||
_write_bundle(tmp_path, _good_data())
|
|
||||||
s = ps.summary(ps.load("cos4", skeleton_dir=str(tmp_path / "skeletons")))
|
|
||||||
assert s["dirs"] == 3 and s["anchored"] == 3 and s["close_points"] == 1
|
|
||||||
assert s["rows"] == 1 and s["filled_cells"] == 1 and s["roots"] == ["建设项目"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_validate_rejects_broken(tmp_path):
|
|
||||||
bad = _good_data()
|
|
||||||
bad["dirs"][1]["parent_id"] = 999 # 悬空父级
|
|
||||||
_write_bundle(tmp_path, bad)
|
|
||||||
try:
|
|
||||||
ps.load("cos4", skeleton_dir=str(tmp_path / "skeletons"))
|
|
||||||
raise AssertionError("应拒绝悬空 parent_id")
|
|
||||||
except ps.SkeletonError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def test_load_missing_file_raises(tmp_path):
|
|
||||||
try:
|
|
||||||
ps.load("cos4", skeleton_dir=str(tmp_path)) # 无 skeletons 目录
|
|
||||||
raise AssertionError("应抛 SkeletonError")
|
|
||||||
except ps.SkeletonError as e:
|
|
||||||
assert "升级包" in str(e)
|
|
||||||
|
|
||||||
|
|
||||||
def test_load_broken_json_raises(tmp_path):
|
|
||||||
d = tmp_path / "skeletons"
|
|
||||||
d.mkdir(exist_ok=True)
|
|
||||||
(d / "cos4.json").write_bytes(b"\x88corrupt")
|
|
||||||
try:
|
|
||||||
ps.load("cos4", skeleton_dir=str(d))
|
|
||||||
raise AssertionError("应抛 SkeletonError")
|
|
||||||
except ps.SkeletonError as e:
|
|
||||||
assert "损坏" in str(e)
|
|
||||||
|
|
||||||
|
|
||||||
def test_skeleton_path_sanitizes_suffix(tmp_path):
|
|
||||||
p = ps.skeleton_path("../evil", skeleton_dir=str(tmp_path))
|
|
||||||
base = os.path.basename(p)
|
|
||||||
assert "/" not in base and "\\" not in base and base not in (".", "..") # 无路径穿越
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""价格重设计接口回归(2026-10-12 主人定):
|
|
||||||
多级目录树(单根/行内编辑/上下移两段确认由前端做,这里测服务端口径)、
|
|
||||||
行内新增/编辑(只有最底层目录可挂行、编辑重算比对键)、删除目录行落未分类、
|
|
||||||
导出「一份数据」(zip = 明细 xlsx + 附件原件 + 批次信息页签)。"""
|
|
||||||
import io
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
from api_harness import (price_xlsx_file, post, get, server) # noqa: F401
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _import_batch(server):
|
|
||||||
px = price_xlsx_file(server, "重设计测试_2026年8月.xlsx", [
|
|
||||||
("建筑材料/黑色金属/钢筋", "C1", "圆钢", "Φ12", "t", 4200, 3, 4326, ""),
|
|
||||||
("建筑材料/黑色金属/钢筋", "C2", "螺纹钢", "Φ16-25", "t", 3880, 3, 3996.4, ""),
|
|
||||||
("建筑材料/水泥", "C3", "普通水泥", "P.O 42.5", "t", 385, 13, 435.05, ""),
|
|
||||||
("电气材料/电线电缆", "", "BV电线", "2.5mm²", "km", 89.5, 13, 101.14, "")])
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
{"kind": "info", "path": px, "name": "重设计测试批次", "publisher": "测试发布"})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return int(r["batches"][0])
|
|
||||||
|
|
||||||
|
|
||||||
def _dirmap(d):
|
|
||||||
out = {}
|
|
||||||
|
|
||||||
def walk(ns, parent):
|
|
||||||
for n in ns:
|
|
||||||
out[n["name"]] = (n["id"], parent, n["leaf"])
|
|
||||||
walk(n.get("children") or [], n["id"])
|
|
||||||
walk(d["tree"], 0)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def test_dirs_tree_and_counts(server):
|
|
||||||
bid = _import_batch(server)
|
|
||||||
d = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
assert d["ok"] is True and d["batch_name"] == "重设计测试批次"
|
|
||||||
m = _dirmap(d)
|
|
||||||
# 树形:2 个一级(建筑材料 / 电气材料);钢筋/水泥/电线电缆是叶子
|
|
||||||
assert {n["name"] for n in d["tree"]} == {"建筑材料", "电气材料"}
|
|
||||||
assert m["钢筋"][2] is True and m["水泥"][2] is True and m["电线电缆"][2] is True
|
|
||||||
assert m["黑色金属"][2] is False and m["建筑材料"][2] is False
|
|
||||||
# 子树行数:黑色金属=2、水泥=1、电气材料=1、未分类=0(2026-10-14 主人定:导入不允许空目录)
|
|
||||||
assert d["counts"][str(m["黑色金属"][0])] == 2
|
|
||||||
assert d["counts"][str(m["水泥"][0])] == 1
|
|
||||||
assert d["counts"][str(m["电气材料"][0])] == 1
|
|
||||||
assert d["n_uncat"] == 0
|
|
||||||
# 行的 Class 冗余 = 完整路径
|
|
||||||
cls = _q(server["db"], "SELECT Class FROM prices WHERE batch_id=? AND Name='圆钢'", (bid,))
|
|
||||||
assert cls[0][0] == "建筑材料/黑色金属/钢筋"
|
|
||||||
|
|
||||||
|
|
||||||
def test_dir_add_rename_move_seq(server):
|
|
||||||
bid = _import_batch(server)
|
|
||||||
d0 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
m0 = _dirmap(d0)
|
|
||||||
jz = m0["钢筋"][0]
|
|
||||||
# 新增子目录(给叶子钢筋加子级 → 钢筋不再是叶子)
|
|
||||||
r = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "add", "parent_id": jz, "name": "高强钢筋"})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
# 同级重名拒绝
|
|
||||||
r2 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "add", "parent_id": jz, "name": "高强钢筋"})
|
|
||||||
assert r2["ok"] is False and "同名" in r2["msg"]
|
|
||||||
# 新增平级(挂在黑色金属下)
|
|
||||||
r3 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "add", "parent_id": m0["黑色金属"][0], "name": "板材"})
|
|
||||||
assert r3["ok"] is True
|
|
||||||
d1 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
m1 = _dirmap(d1)
|
|
||||||
assert m1["钢筋"][2] is False # 有了子级 → 不再是叶子
|
|
||||||
assert m1["高强钢筋"][2] is True
|
|
||||||
# 改名:子树行的 Class 路径同步更新
|
|
||||||
r4 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "rename", "id": m1["黑色金属"][0], "name": "黑色及有色金属"})
|
|
||||||
assert r4["ok"] is True, r4
|
|
||||||
cls = _q(server["db"], "SELECT Class FROM prices WHERE batch_id=? AND Name='圆钢'", (bid,))
|
|
||||||
assert cls[0][0] == "建筑材料/黑色及有色金属/钢筋"
|
|
||||||
# 换父(move):把水泥移到电气材料下 → 环/自嵌套拒绝分支顺带覆盖
|
|
||||||
r5 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "move", "id": m1["水泥"][0], "parent_id": m1["电气材料"][0]})
|
|
||||||
assert r5["ok"] is True
|
|
||||||
cyc = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "move", "id": m1["建筑材料"][0], "parent_id": m1["钢筋"][0]})
|
|
||||||
assert cyc["ok"] is False # 不能移进自己的子孙
|
|
||||||
# 上移/下移(seq):一级目录「电气材料」上移后 seq 顺序对调
|
|
||||||
d2 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
top = [(n["name"], n["seq"]) for n in d2["tree"]]
|
|
||||||
order0 = [n for n, _ in top]
|
|
||||||
r6 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "seq", "id": d2["tree"][1]["id"], "dir": "up"})
|
|
||||||
assert r6["ok"] is True
|
|
||||||
d3 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
order1 = [n["name"] for n in d3["tree"]]
|
|
||||||
assert order1[0] == order0[1] and order1[1] == order0[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_dir_del_rows_fall_uncat(server):
|
|
||||||
bid = _import_batch(server)
|
|
||||||
d0 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
m0 = _dirmap(d0)
|
|
||||||
# 有子目录 → 拒删
|
|
||||||
r = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "del", "id": m0["黑色金属"][0]})
|
|
||||||
assert r["ok"] is False and "子目录" in r["msg"]
|
|
||||||
# 删叶子(钢筋,挂 2 行)→ 行落未分类、Class 清空重算
|
|
||||||
r2 = post(server, "/api/admin/batch/%d/dirs" % bid,
|
|
||||||
{"op": "del", "id": m0["钢筋"][0]})
|
|
||||||
assert r2["ok"] is True and "未分类" in r2["msg"]
|
|
||||||
d1 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
assert d1["n_uncat"] == 2 # 0(导入无空目录)+ 2(钢筋2行落未分类)
|
|
||||||
rows = _q(server["db"], "SELECT dir_id, Class FROM prices WHERE batch_id=? AND Name='圆钢'", (bid,))
|
|
||||||
assert rows[0][0] in (0, None) and rows[0][1] == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_row_crud_and_hash(server):
|
|
||||||
bid = _import_batch(server)
|
|
||||||
d0 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
m0 = _dirmap(d0)
|
|
||||||
# 非叶子目录拒绝新增行
|
|
||||||
bad = post(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
{"op": "add", "dir_id": m0["黑色金属"][0], "name": "X", "unit": "t", "notax": "1"})
|
|
||||||
assert bad["ok"] is False and "最底层" in bad["msg"]
|
|
||||||
# 必填校验
|
|
||||||
miss = post(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
{"op": "add", "dir_id": m0["钢筋"][0], "name": "", "unit": "", "notax": ""})
|
|
||||||
assert miss["ok"] is False and "请填写" in miss["msg"]
|
|
||||||
# 新增行(叶子)→ 比对键按导入同款口径生成
|
|
||||||
add = post(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
{"op": "add", "dir_id": m0["钢筋"][0], "code": "C9",
|
|
||||||
"name": "高线", "spec": "Φ6mm", "unit": "t", "notax": "2,980", "taxrate": "13%"})
|
|
||||||
assert add["ok"] is True, add
|
|
||||||
pid = int(add["id"])
|
|
||||||
row = _q(server["db"], "SELECT Name, NoTaxPrice, x_hash_exact, Class FROM prices WHERE id=?", (pid,))[0]
|
|
||||||
assert row[0] == "高线" and row[1] == 2980.0 and row[3] == "建筑材料/黑色金属/钢筋"
|
|
||||||
import hashlib
|
|
||||||
def norm(s): # 与服务端 _norm 同款:全角括号/×折叠 + 去空白 + lower
|
|
||||||
import re as _re
|
|
||||||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
|
||||||
return _re.sub(r"\s+", "", s).lower()
|
|
||||||
want = hashlib.md5("|".join(norm(p) for p in ("高线", "Φ6mm", "t")).encode("utf-8")).hexdigest()
|
|
||||||
assert row[2] == want
|
|
||||||
# 编辑行(改名称 + 改挂目录)→ 键与 Class 重算
|
|
||||||
new_dir = m0["水泥"][0]
|
|
||||||
upd = post(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
{"op": "edit", "id": pid, "dir_id": new_dir,
|
|
||||||
"code": "C9", "name": "高线改", "spec": "Φ6mm", "unit": "t",
|
|
||||||
"notax": 2980, "taxrate": 13})
|
|
||||||
assert upd["ok"] is True, upd
|
|
||||||
row2 = _q(server["db"], "SELECT Name, x_hash_exact, Class FROM prices WHERE id=?", (pid,))[0]
|
|
||||||
assert row2[0] == "高线改"
|
|
||||||
assert row2[1] == hashlib.md5("|".join(norm(p) for p in ("高线改", "Φ6mm", "t")).encode("utf-8")).hexdigest()
|
|
||||||
assert row2[2] == "建筑材料/水泥"
|
|
||||||
# 删行 → x_rows_price 同步
|
|
||||||
n0 = _q(server["db"], "SELECT x_rows_price FROM batches WHERE id=?", (bid,))[0][0]
|
|
||||||
dele = post(server, "/api/admin/batch/%d/prices" % bid, {"op": "del", "id": pid})
|
|
||||||
assert dele["ok"] is True
|
|
||||||
n1 = _q(server["db"], "SELECT x_rows_price FROM batches WHERE id=?", (bid,))[0][0]
|
|
||||||
assert n1 == n0 - 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_prices_filter_and_export(server):
|
|
||||||
bid = _import_batch(server)
|
|
||||||
d0 = get(server, "/api/admin/batch/%d/dirs" % bid)
|
|
||||||
m0 = _dirmap(d0)
|
|
||||||
# dir_id 过滤 + subtree
|
|
||||||
leaf = get(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
dir_id=m0["钢筋"][0], subtree=0, page=1, page_size=50)
|
|
||||||
assert leaf["total"] == 2 and leaf["rows"][0]["Name"] in ("圆钢", "螺纹钢")
|
|
||||||
mid = get(server, "/api/admin/batch/%d/prices" % bid,
|
|
||||||
dir_id=m0["建筑材料"][0], subtree=1, page=1, page_size=50)
|
|
||||||
assert mid["total"] == 3 # 钢筋2 + 水泥1
|
|
||||||
unc = get(server, "/api/admin/batch/%d/prices" % bid, dir_id=0, page=1, page_size=50)
|
|
||||||
assert unc["total"] == 0
|
|
||||||
allr = get(server, "/api/admin/batch/%d/prices" % bid, page=1, page_size=50)
|
|
||||||
assert allr["total"] == 4 and isinstance(allr["rows"][0], dict)
|
|
||||||
# 导出「一份数据」:zip = 价格明细.xlsx + 附件(本批次没挂附件 → 只有 xlsx)
|
|
||||||
fp = server["client"].get("/api/admin/batch/%d/export" % bid)
|
|
||||||
assert fp.status_code == 200 and "zip" in fp.headers.get("Content-Type", "")
|
|
||||||
zf = zipfile.ZipFile(io.BytesIO(fp.content))
|
|
||||||
names = zf.namelist()
|
|
||||||
assert "价格明细.xlsx" in names
|
|
||||||
import openpyxl
|
|
||||||
wb = openpyxl.load_workbook(io.BytesIO(zf.read("价格明细.xlsx")))
|
|
||||||
ws = wb["价格明细"]
|
|
||||||
head = [c.value for c in ws[1]]
|
|
||||||
assert head[0] == "目录" and head[1] == "材料编码"
|
|
||||||
body = [[c.value for c in r] for r in ws.iter_rows(min_row=2)]
|
|
||||||
assert any(r[0] == "建筑材料/黑色金属/钢筋" and r[2] == "圆钢" for r in body)
|
|
||||||
# 全部行均已挂在目录树上(导入不再允许空目录,2026-10-14 主人定)
|
|
||||||
assert "批次信息" in wb.sheetnames
|
|
||||||
# 工程批次导出拒绝(404/错误 JSON)
|
|
||||||
bid_proj = _import_project(server)
|
|
||||||
bad = server["client"].get("/api/admin/batch/%d/export" % bid_proj)
|
|
||||||
assert bad.status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def _import_project(server):
|
|
||||||
from api_harness import META, fixture_file
|
|
||||||
fname = "export_proj.cos4"
|
|
||||||
fixture_file(server, fname, "导出守卫工程",
|
|
||||||
[("030507008001", "清单X", "", "台", 1, 100)],
|
|
||||||
[("000001", "摄像机", "400万", "台", "1", "2")])
|
|
||||||
r = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=str(server["src_dir"] / fname), name="导出守卫工程", file_kind=1))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["batch_id"]
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""原数据树清单单价现算(决策 232,2026-10-28 主人定)。
|
|
||||||
|
|
||||||
口径:清单单价=∑定额合价÷清单工程量(四舍五入 2 位)、清单合价=单价×清单量;
|
|
||||||
定额合价=显示工程量×单价现算(公式行用求值量,采纳定额同样算);
|
|
||||||
清单工程量=0 → 量/单价/合价三值 None(前端留空)、不算不报错;
|
|
||||||
临删定额不进 ∑(导出时真实省略);无定额清单(手工)照捕获值。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
|
||||||
import api_server as srv # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk():
|
|
||||||
sc = sqlite3.connect(":memory:")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
c = sc.cursor()
|
|
||||||
c.execute("CREATE TABLE sessions(id INTEGER PRIMARY KEY, name TEXT, src_name TEXT)")
|
|
||||||
c.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
|
|
||||||
section_id INT, Number TEXT, Name TEXT, Total REAL, Specialty TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_divides(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
parent_id INT, Kind TEXT, Number TEXT, Name TEXT, Total REAL, Code TEXT, x_seq INT)""")
|
|
||||||
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
|
||||||
div_id INT, Number TEXT, Name TEXT, Attr TEXT, Unit TEXT,
|
|
||||||
Quantity REAL, Price REAL, Total REAL, Kind TEXT, src_remark TEXT,
|
|
||||||
x_new INT, x_tdel INT, x_adopt INT, x_seq INT, x_remark TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT,
|
|
||||||
Number TEXT, Name TEXT, Unit TEXT, Quantity REAL, Price REAL, Total REAL,
|
|
||||||
x_tdel INT, x_adopt INT, qty_expr TEXT, x_side TEXT)""")
|
|
||||||
c.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
|
|
||||||
c.execute("INSERT INTO s_unit_works VALUES(10, 1, NULL, 'UW-1', '土建', 660, '建筑')")
|
|
||||||
# B1 清单量 100,两条定额:429 + 121 = 550 → 单价 5.50、合价 550.00
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(1,1,10,NULL,'B1','挖方',NULL,'m3',100,4.29,429,NULL,NULL,0,0,0,1,NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(11,1,'D1','挖槽','1000m3',0.429,1000,429,0,0,NULL, NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(12,1,'D2','运土','1000m3',0.121,1000,121,0,0,NULL, NULL)")
|
|
||||||
# B2 清单量 0:三值全 None
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(2,1,10,NULL,'B2','空量',NULL,'m2',0,3.5,0,NULL,NULL,0,0,0,2,NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(21,2,'D3','垫层','10m2',5,70,350,0,0,NULL, NULL)")
|
|
||||||
# B3 清单量 100,临删定额 500 不进 ∑,有效定额 300 → 单价 3.00
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(3,1,10,NULL,'B3','回填',NULL,'m3',100,5,500,NULL,NULL,0,0,0,3,NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(31,3,'D4','临删行','10m3',5,100,500,1,0,NULL, NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(32,3,'D5','有效行','10m3',3,100,300,0,1,NULL, NULL)")
|
|
||||||
# B4 公式定额:GCL*0.5 → 50×2=100 → 单价 1.00
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(4,1,10,NULL,'B4','公式',NULL,'m2',100,1,100,NULL,NULL,0,0,0,4,NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(41,4,'D6','公式行','10m2',NULL,2,NULL,0,1,'GCL*0.5', NULL)")
|
|
||||||
# B5 手工清单(无定额):照捕获值
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(5,1,10,NULL,'B5','手工',NULL,'项',3,12.34,37.02,NULL,NULL,0,0,0,5,NULL)")
|
|
||||||
# B6 单定额四舍五入半升:0.535×5=2.675 → 2.68(银行家舍入会得 2.67)
|
|
||||||
c.execute("INSERT INTO s_bills VALUES(6,1,10,NULL,'B6','半升',NULL,'t',1,2.67,2.67,NULL,NULL,0,0,0,6,NULL)")
|
|
||||||
c.execute("INSERT INTO s_norms VALUES(61,6,'D7','半发行','t',0.535,5,2.67,0,0,NULL, NULL)")
|
|
||||||
sc.commit()
|
|
||||||
return sc
|
|
||||||
|
|
||||||
|
|
||||||
def _bill(d, bid):
|
|
||||||
return next(b for b in d["loose"] if b["id"] == bid)
|
|
||||||
|
|
||||||
|
|
||||||
def test_price_from_norm_totals():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b1 = _bill(d, 1)
|
|
||||||
assert (b1["Price"], b1["Total"]) == (5.5, 550.0)
|
|
||||||
tots = sorted(n[6] for n in b1["norms"])
|
|
||||||
assert tots == [121.0, 429.0] # 定额合价现算,弃显库存值
|
|
||||||
|
|
||||||
|
|
||||||
def test_zero_qty_all_none():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b2 = _bill(d, 2)
|
|
||||||
assert b2["Quantity"] is None and b2["Price"] is None and b2["Total"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_tdel_norm_excluded():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b3 = _bill(d, 3)
|
|
||||||
assert (b3["Price"], b3["Total"]) == (3.0, 300.0)
|
|
||||||
|
|
||||||
|
|
||||||
def test_formula_norm_evaluated():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b4 = _bill(d, 4)
|
|
||||||
# 决策 216:GCL*0.5 先按清单量 100 求值=50,再 ÷ 单位因子(10m2→10)=5;合价=5×2=10
|
|
||||||
assert (b4["Price"], b4["Total"]) == (0.1, 10.0)
|
|
||||||
assert b4["norms"][0][6] == 10.0 # 公式行合价=求值量5×价2
|
|
||||||
|
|
||||||
|
|
||||||
def test_manual_bill_keeps_captured():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b5 = _bill(d, 5)
|
|
||||||
assert (b5["Quantity"], b5["Price"], b5["Total"]) == (3, 12.34, 37.02)
|
|
||||||
|
|
||||||
|
|
||||||
def test_round_half_up():
|
|
||||||
d = srv._raw_uw(_mk(), srv.TBL["session"], 10, "item")
|
|
||||||
b6 = _bill(d, 6)
|
|
||||||
assert (b6["Price"], b6["Total"]) == (2.68, 2.68)
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""最近审核删除回归(2026-10-19 两段式 + 2026-10-30 决策 242):
|
|
||||||
① 接口先删会话行、立即返回;子表/设置/编辑历史/批次由后台清理;
|
|
||||||
② 删除=全部删除:关联入库批次随台账删除(取代决策 110 后台同源例外),
|
|
||||||
批次没了 → 备注/源文件副本引用清零一并删净。
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import time
|
|
||||||
|
|
||||||
from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: F401
|
|
||||||
|
|
||||||
CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500)
|
|
||||||
LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
|
|
||||||
AUDIT_BASE = {"province": "广东省", "city": "珠海市", "district": "香洲区",
|
|
||||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607, "file_kind": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _upload(server, path, name):
|
|
||||||
with open(path, "rb") as f:
|
|
||||||
raw = f.read()
|
|
||||||
r = post(server, "/api/admin/upload",
|
|
||||||
{"name": name, "data": base64.b64encode(raw).decode("ascii")})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["path"]
|
|
||||||
|
|
||||||
|
|
||||||
def _wait(fn, timeout=10.0):
|
|
||||||
end = time.time() + timeout
|
|
||||||
while time.time() < end:
|
|
||||||
if fn():
|
|
||||||
return True
|
|
||||||
time.sleep(0.1)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _add_remark(server, sid, text):
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
post(server, "/api/session/remark", {"bill_id": rows["rows"][0][0], "remark": text})
|
|
||||||
|
|
||||||
|
|
||||||
def test_delete_async_no_backend(server):
|
|
||||||
p = make_cos4(str(server["src_dir"] / "asyncA.cos4"), "异步删除A", [CAM], [LME_CAM])
|
|
||||||
up = _upload(server, p, "asyncA.cos4")
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BASE, path=up, name="异步删除A"))["session_id"]
|
|
||||||
_add_remark(server, sid, "异步删除备注A")
|
|
||||||
|
|
||||||
t0 = time.time()
|
|
||||||
r = post(server, "/api/session/delete", {"ids": [sid]})
|
|
||||||
dt = time.time() - t0
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert dt < 2.0, "删除接口应快速返回,实测 %.2fs" % dt
|
|
||||||
# 第一段:会话行立刻没了(界面据此立即消行)
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM sessions WHERE id=?", (sid,))[0][0] == 0
|
|
||||||
# 第二段:后台把子表、备注、源文件清干净
|
|
||||||
assert _wait(lambda: _q(server["sessdb"],
|
|
||||||
"SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 0)
|
|
||||||
assert _wait(lambda: _q(server["sessdb"],
|
|
||||||
"SELECT COUNT(*) FROM s_remarks WHERE remark=?",
|
|
||||||
("异步删除备注A",))[0][0] == 0)
|
|
||||||
assert _wait(lambda: not os.path.exists(up))
|
|
||||||
|
|
||||||
|
|
||||||
def test_delete_async_removes_linked_batch_and_remarks(server):
|
|
||||||
"""决策 242(2026-10-30 主人定):删除=全部删除——关联入库批次随台账删除
|
|
||||||
(取代决策 110 后台同源例外);批次没了,备注/uploads 副本引用清零一并删净。
|
|
||||||
决策 243 后同一份文件前后台只能存在一边,新数据不再产生挂接——这里按**存量形态**
|
|
||||||
造链(会话开双胞胎件 + 手工回填 x_batch_id),验证存量挂接对的清理路径仍生效。"""
|
|
||||||
p = make_cos4(str(server["src_dir"] / "asyncB_raw.cos4"), "异步删除B", [CAM], [LME_CAM])
|
|
||||||
up = _upload(server, p, "asyncB.cos4")
|
|
||||||
imp = post(server, "/api/admin/import",
|
|
||||||
dict(META, path=up, name="异步删除B", file_kind=1))
|
|
||||||
assert imp["ok"] is True, imp
|
|
||||||
bid = imp["batch_id"]
|
|
||||||
# 会话用同内容双胞胎件打开(决策 243 禁同文件),再模拟存量挂接
|
|
||||||
import api_harness as H
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BASE, path=H.twin_file(server, up, "asyncB_t"),
|
|
||||||
name="异步删除B"))["session_id"]
|
|
||||||
con0 = sqlite3.connect(server["sessdb"])
|
|
||||||
try:
|
|
||||||
con0.execute("UPDATE sessions SET x_batch_id=? WHERE id=?", (bid, sid))
|
|
||||||
con0.commit()
|
|
||||||
finally:
|
|
||||||
con0.close()
|
|
||||||
assert _q(server["sessdb"], "SELECT x_batch_id FROM sessions WHERE id=?",
|
|
||||||
(sid,))[0][0] == bid
|
|
||||||
_add_remark(server, sid, "异步删除备注B")
|
|
||||||
|
|
||||||
r = post(server, "/api/session/delete", {"ids": [sid]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM sessions WHERE id=?", (sid,))[0][0] == 0
|
|
||||||
assert _wait(lambda: _q(server["sessdb"],
|
|
||||||
"SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 0)
|
|
||||||
time.sleep(0.8) # 等后台跑完批次/备注/文件阶段
|
|
||||||
assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE id=?", (bid,))[0][0] == 0
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_remarks WHERE remark=?",
|
|
||||||
("异步删除备注B",))[0][0] == 0
|
|
||||||
assert os.path.exists(str(server["src_dir"] / "asyncB_raw.cos4")) # 待导入目录原件不动
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""源文件两道闸回归(2026-10-15):
|
|
||||||
① 导出前哈希校验——源文件被外部改动/同名覆盖后拒绝导出(宁可不导,不可导错);
|
|
||||||
② 闸②(同名换文件原地续用同步 src_name/备注平移)已随决策 242 退役——
|
|
||||||
导入入口一律按新文件:同文件/同名拒绝、删除后再导=全新,本文件改测该口径。
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
import api_harness as H
|
|
||||||
from api_harness import get, post, server # noqa: F401 (server 夹具须经导入注册)
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, params=()):
|
|
||||||
con = sqlite3.connect(db)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, params).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _hash_named(server, raw_path, stem):
|
|
||||||
"""按内容哈希把造好的 cos4 存进 source_files/(真实「打开工程」的落盘形态:
|
|
||||||
api_upload 以 sha256_原名 命名)。直接落盘 = 绕过上传接口但形态一致。"""
|
|
||||||
raw = open(raw_path, "rb").read()
|
|
||||||
dst = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
|
||||||
"%s_%s" % (hashlib.sha256(raw).hexdigest(), stem))
|
|
||||||
with open(dst, "wb") as f:
|
|
||||||
f.write(raw)
|
|
||||||
return dst
|
|
||||||
|
|
||||||
|
|
||||||
def _export(server, sid):
|
|
||||||
"""成功 → (zip响应);失败 → (json响应)。导出成功回 zip 流,被闸住回 JSON。"""
|
|
||||||
return server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
|
|
||||||
|
|
||||||
CAM = ("B001", "球机摄像机调试", "1、含支架安装 2、通电调试", "台", 10, 500)
|
|
||||||
METER = ("B002", "门禁主机调试", "1、含读卡器", "台", 5, 300)
|
|
||||||
|
|
||||||
AUDIT_BODY = {"name": "闸测工程", "province": "广东省", "city": "珠海市",
|
|
||||||
"district": "香洲区", "period_from": H.PERIOD_202607,
|
|
||||||
"period_to": H.PERIOD_202607, "file_kind": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_refuses_tampered_source(server):
|
|
||||||
p = H.make_cos4(str(server["src_dir"] / "guardA_raw.cos4"), "闸甲工程", [CAM, METER])
|
|
||||||
hp = _hash_named(server, p, "guardA.cos4")
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BODY, path=hp, name="闸甲工程"))["session_id"]
|
|
||||||
# 基线:文件未动 → 导出成功(zip 流)
|
|
||||||
r = _export(server, sid)
|
|
||||||
assert r.status_code == 200 and r.headers["content-type"].startswith("application/zip"), r.text[:200]
|
|
||||||
# 外部篡改(同名覆盖一个字节)→ 导出被闸①拦下
|
|
||||||
raw = open(hp, "rb").read()
|
|
||||||
open(hp, "wb").write(raw[:-1] + bytes([raw[-1] ^ 0xFF]))
|
|
||||||
r = _export(server, sid)
|
|
||||||
assert r.headers["content-type"].startswith("application/json"), r.headers.get("content-type")
|
|
||||||
j = r.json()
|
|
||||||
assert j["ok"] is False and "不一致" in j.get("msg", ""), j
|
|
||||||
# 恢复原字节 → 导出恢复可用
|
|
||||||
open(hp, "wb").write(raw)
|
|
||||||
r = _export(server, sid)
|
|
||||||
assert r.status_code == 200 and r.headers["content-type"].startswith("application/zip")
|
|
||||||
|
|
||||||
|
|
||||||
def test_reimport_rejected_and_fresh_after_delete(server):
|
|
||||||
"""决策 242(2026-10-30 主人定):导入入口一律按新文件处理。
|
|
||||||
同文件(哈希相同)→「重复导入,请删除后再导入」;同名不同文件 →「名字重复,请修改名称」;
|
|
||||||
删除后再导 = 全新会话(id 不复用、备注不带回、导出以新文件为模板可用)。"""
|
|
||||||
# v1:打开 + 写备注
|
|
||||||
p1 = H.make_cos4(str(server["src_dir"] / "guardB_raw1.cos4"), "闸乙工程", [CAM, METER])
|
|
||||||
hp1 = _hash_named(server, p1, "guardB1.cos4")
|
|
||||||
sid = post(server, "/api/audit", dict(AUDIT_BODY, path=hp1, name="闸乙工程"))["session_id"]
|
|
||||||
rows = get(server, "/api/session/rows", session_id=sid, type="bill")
|
|
||||||
bill_id = [r[0] for r in rows["rows"] if r[1] == CAM[0]][0]
|
|
||||||
post(server, "/api/session/remark", {"bill_id": bill_id, "remark": "量存疑,待核"})
|
|
||||||
# 同文件重导(上传形态 sha_原名)→ 拦截:重复导入
|
|
||||||
r_same = post(server, "/api/audit", dict(AUDIT_BODY, path=hp1, name="闸乙工程"))
|
|
||||||
assert r_same["ok"] is False and "重复导入" in r_same["msg"] \
|
|
||||||
and "请删除后再导入" in r_same["msg"], r_same
|
|
||||||
# 同名、不同内容的新文件 → 拦截:名字重复
|
|
||||||
p2 = H.make_cos4(str(server["src_dir"] / "guardB_raw2.cos4"), "闸乙工程",
|
|
||||||
[(CAM[0], CAM[1], CAM[2], CAM[3], 12, CAM[5]), METER])
|
|
||||||
hp2 = _hash_named(server, p2, "guardB2.cos4")
|
|
||||||
r2 = post(server, "/api/audit", dict(AUDIT_BODY, path=hp2, name="闸乙工程"))
|
|
||||||
assert r2["ok"] is False and "名字重复" in r2["msg"] and "请修改名称" in r2["msg"], r2
|
|
||||||
# 删除(真实接口,等后台清完)→ 再导 = 全新
|
|
||||||
H.drop_sessions(server, "闸乙工程")
|
|
||||||
sid2 = post(server, "/api/audit", dict(AUDIT_BODY, path=hp2, name="闸乙工程"))["session_id"]
|
|
||||||
# sid 可能复用(SQLite rowid),「全新」看数据:旧备注不带回、持久表删净
|
|
||||||
remark = _q(server["sessdb"], "SELECT x_remark FROM s_bills WHERE session_id=? AND Number=?",
|
|
||||||
(sid2, CAM[0]))[0][0]
|
|
||||||
assert remark in (None, "") # 旧备注不带回
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_remarks WHERE remark=?",
|
|
||||||
("量存疑,待核",))[0][0] == 0 # 持久表删净
|
|
||||||
r = _export(server, sid2) # 导出以新文件为模板,可用
|
|
||||||
assert r.status_code == 200 and r.headers["content-type"].startswith("application/zip")
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""屏蔽词排除防回归(2026-10-11 主人定,工作台历史对比筛选栏)。
|
|
||||||
|
|
||||||
口径:历史行 名称/项目特征(规格)/单位 含**任一**屏蔽词 → 整行不显示。
|
|
||||||
两条路径:比对(/api/search 结果后过滤,前端发 stop)+ 检索(/api/hist/search,
|
|
||||||
stop 进 match.hist_search 的 SQL WHERE —— 本文件钉死的就是这层的两条关键性质):
|
|
||||||
① 命中屏蔽词的行一条不剩,其余行原样保留;
|
|
||||||
② 排除发生在 LIMIT/OFFSET **之前** —— 分页每页行数不因屏蔽缩水(否则翻页会出现
|
|
||||||
「第 1 页 2 行、第 2 页 1 行」的假象,检索口径就错了)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "core"))
|
|
||||||
import match # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_db(rows):
|
|
||||||
con = sqlite3.connect(":memory:")
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
c = con.cursor()
|
|
||||||
c.execute("""CREATE TABLE batches (id INTEGER PRIMARY KEY, Name TEXT, kind TEXT,
|
|
||||||
BulidUnit TEXT, FileKind TEXT, x_province TEXT, x_city TEXT, x_district TEXT,
|
|
||||||
x_period_start_m INT, x_period_end_m INT, x_src_hash TEXT, x_enabled INT DEFAULT 1,
|
|
||||||
x_publisher TEXT)""")
|
|
||||||
c.execute("""CREATE TABLE bills (id INTEGER PRIMARY KEY, batch_id INT,
|
|
||||||
Name TEXT, Attr TEXT, Unit TEXT, Price REAL)""")
|
|
||||||
c.execute("INSERT INTO batches (id, Name, kind, x_period_start_m, x_period_end_m) "
|
|
||||||
"VALUES (1, '历史项目甲', 'project', 20260, 20261)")
|
|
||||||
for i, nm in enumerate(rows):
|
|
||||||
c.execute("INSERT INTO bills (batch_id, Name, Attr, Unit, Price) VALUES (1, ?, '', 'm3', ?)",
|
|
||||||
(nm, 100 + i))
|
|
||||||
con.commit()
|
|
||||||
return con
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_words_parse():
|
|
||||||
assert match.stop_words("拆除 泵送,恢复") == ["拆除", "泵送", "恢复"]
|
|
||||||
assert match.stop_words(" ") == []
|
|
||||||
assert match.stop_words(None) == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_excludes_rows():
|
|
||||||
con = _mk_db(["C30混凝土浇筑", "C30混凝土浇筑(拆除)", "钢筋制作安装"])
|
|
||||||
# 无屏蔽词:3 行全在
|
|
||||||
assert len(match.hist_search(con, [], [], [], None, None, "", limit=50)) == 3
|
|
||||||
# 屏蔽「拆除」:含词行消失,其余原样
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "", limit=50, stop=["拆除"])
|
|
||||||
assert [r["name"] for r in rs] == ["C30混凝土浇筑", "钢筋制作安装"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_case_and_attr_hit():
|
|
||||||
# 大小写折叠(LED 挡掉 led灯带)+ 特征字段也算命中面
|
|
||||||
con = _mk_db(["灯带", "电缆敷设"])
|
|
||||||
con.execute("UPDATE bills SET Attr='含 led灯带 3米' WHERE Name='灯带'")
|
|
||||||
con.commit()
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "", limit=50, stop=["LED"])
|
|
||||||
assert [r["name"] for r in rs] == ["电缆敷设"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_before_limit_pagination():
|
|
||||||
# 每页 2 条:4 行里 1 行被屏蔽 → 两页应是 2+1,且第 2 页拿到的是第 3 个未屏蔽行
|
|
||||||
con = _mk_db(["甲项清单", "乙项清单", "丙项(拆除)清单", "丁项清单"])
|
|
||||||
p1 = match.hist_search(con, [], [], [], None, None, "", limit=2, page=1, stop=["拆除"])
|
|
||||||
p2 = match.hist_search(con, [], [], [], None, None, "", limit=2, page=2, stop=["拆除"])
|
|
||||||
assert [r["name"] for r in p1] == ["甲项清单", "乙项清单"]
|
|
||||||
assert [r["name"] for r in p2] == ["丁项清单"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_with_keyword_combined():
|
|
||||||
con = _mk_db(["C30混凝土浇筑", "C30混凝土拆除", "C40混凝土浇筑"])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "混凝土", limit=50, stop=["拆除"])
|
|
||||||
assert [r["name"] for r in rs] == ["C30混凝土浇筑", "C40混凝土浇筑"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_stop_word_order_sensitive():
|
|
||||||
"""屏蔽词按输入词的字符顺序整词命中(2026-10-11 主人定「按每组出现的词及词的顺序屏蔽」):
|
|
||||||
不拆字、不做排列——只挡「拆除」连写;倒序「除拆」、散字「拆…除」都不挡。"""
|
|
||||||
con = _mk_db(["拆除垃圾", "除拆垃圾", "拆模除外"])
|
|
||||||
rs = match.hist_search(con, [], [], [], None, None, "", limit=50, stop=["拆除"])
|
|
||||||
assert [r["name"] for r in rs] == ["除拆垃圾", "拆模除外"]
|
|
||||||
@@ -1,316 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""SWT(深圳市工程造价数据交换标准 SJG77-2020)导入回归。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
· 项目/单项/单位/分部/清单/定额/措施/工料机/汇总 的层级映射;
|
|
||||||
· ResourceID 是单位工程内部编号——两个单位工程用同一个 ResourceID 指不同编码,
|
|
||||||
norm_res 必须各归各的(这是 SWT 与 COS 最大的结构差异);
|
|
||||||
· 税率口径 A(2026-10-19 主人定):SWT 资源只有一个 Rate,
|
|
||||||
NoTaxPrice = TaxPrice = Rate、TaxRate = 0;
|
|
||||||
· 重新解析可重跑;原格式导出走「骨架+填空」回写(SWT/SWZ 同名后缀);
|
|
||||||
· 后台批次导入与工作台会话导入共用同一套解析/写库。
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import io
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
|
|
||||||
from api_harness import META, get, make_swt, post, server # noqa: F401
|
|
||||||
|
|
||||||
UNITS = [
|
|
||||||
{"id": "11", "name": "建筑工程", "total": 1000, "a": 800, "b": 100, "b1": 100,
|
|
||||||
"c": 0, "d": 100, "e": 1000,
|
|
||||||
"bills": [{"code": "010101001001", "name": "清单一", "feature": "特征一",
|
|
||||||
"unit": "m3", "qty": 10, "rate": 50,
|
|
||||||
"norms": [{"code": "N1", "name": "定额一", "unit": "10m3", "qty": 1,
|
|
||||||
"rate": 500, "res": [(1, 2.5)]}]}],
|
|
||||||
"resources": [{"id": 1, "code": "R00001", "name": "普工", "unit": "元",
|
|
||||||
"rate": 1.5, "qty": 25, "kind": 1}],
|
|
||||||
"measures": [{"id": "m1", "code": "1", "name": "安全文明施工费", "total": 100,
|
|
||||||
"children": [{"id": "m2", "code": "(1)", "name": "子措施",
|
|
||||||
"total": 100}]}]},
|
|
||||||
{"id": "12", "name": "装饰工程", "total": 234.56, "a": 200, "b": 0, "b1": 0,
|
|
||||||
"c": 0, "d": 34.56, "e": 234.56,
|
|
||||||
"bills": [{"code": "020101001001", "name": "清单二", "feature": "特征二",
|
|
||||||
"unit": "m2", "qty": 10, "rate": 20,
|
|
||||||
"norms": [{"code": "N2", "name": "定额二", "unit": "10m2", "qty": 1,
|
|
||||||
"rate": 200, "res": [(1, 0.5)]}]}],
|
|
||||||
"resources": [{"id": 1, "code": "C00001", "name": "钢材", "spec": "δ=8mm",
|
|
||||||
"unit": "t", "rate": 2.0, "qty": 100, "kind": 2}]},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _q(db, sql, args=()):
|
|
||||||
con = sqlite3.connect(db)
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _upload(server, path, name):
|
|
||||||
"""走真实「打开工程」路径:文件先传进 uploads,src_name 才能被重新解析找到。"""
|
|
||||||
with open(path, "rb") as f:
|
|
||||||
raw = f.read()
|
|
||||||
r = post(server, "/api/admin/upload",
|
|
||||||
{"name": name, "data": base64.b64encode(raw).decode("ascii")})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
return r["path"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_swt_open_map_reparse_export_meta(server):
|
|
||||||
src = str(server["src_dir"] / "swt_open.swt")
|
|
||||||
make_swt(src, "SWT测试工程", UNITS)
|
|
||||||
p = _upload(server, src, "swt_open.swt")
|
|
||||||
r = post(server, "/api/audit", dict(META, path=p, name="SWT工程A"))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
db = server["sessdb"]
|
|
||||||
|
|
||||||
# 项目级
|
|
||||||
x_total, x_info, x_feat, src = _q(
|
|
||||||
db, "SELECT x_total,x_info,x_feat,src_name FROM sessions WHERE id=?", (sid,))[0]
|
|
||||||
assert x_total == 1234.56
|
|
||||||
assert "深圳市工程造价数据交换标准" in x_info and "编制人" in x_feat
|
|
||||||
assert src.lower().endswith(".swt")
|
|
||||||
|
|
||||||
# 单项 / 单位 / 造价构成
|
|
||||||
secs = _q(db, "SELECT id,Number,Name,Total FROM s_sections WHERE session_id=?", (sid,))
|
|
||||||
assert len(secs) == 1 and secs[0][1:] == ("1", "单项一", 1234.56)
|
|
||||||
sec_id = secs[0][0]
|
|
||||||
uws = _q(db, """SELECT Number,Name,Total,section_id,Construction,
|
|
||||||
DivisionalAndElementalWorks,Preliminaries,CostForHSE,
|
|
||||||
SundryCosts,Tax
|
|
||||||
FROM s_unit_works WHERE session_id=? ORDER BY id""", (sid,))
|
|
||||||
assert [x[0] for x in uws] == ["11", "12"]
|
|
||||||
assert all(x[3] == sec_id for x in uws)
|
|
||||||
assert uws[0][4:] == (900.0, 800.0, 100.0, 100.0, 0.0, 100.0)
|
|
||||||
assert uws[1][4:] == (200.0, 200.0, 0.0, 0.0, 0.0, 34.56)
|
|
||||||
|
|
||||||
# 分部:单位1 分部分项标题 / 措施标题 / 措施分组(嵌套);单位2 分部分项标题
|
|
||||||
divs = _q(db, "SELECT id,parent_id,Kind,Number,Name FROM s_divides"
|
|
||||||
" WHERE session_id=? ORDER BY id", (sid,))
|
|
||||||
assert len(divs) == 4
|
|
||||||
assert (divs[0][2], divs[0][4]) == ("item", "整个项目")
|
|
||||||
assert (divs[1][2], divs[1][4]) == ("prelim", "措施项目")
|
|
||||||
assert (divs[2][2], divs[2][3], divs[2][4]) == ("prelim", "1", "安全文明施工费")
|
|
||||||
assert divs[2][1] == divs[1][0] # 分组挂在措施标题下
|
|
||||||
assert (divs[3][2], divs[3][4]) == ("item", "整个项目")
|
|
||||||
|
|
||||||
# 清单:2 条清单 + 1 条措施叶子;措施叶子挂到分组,不挂标题
|
|
||||||
bills = {x[0]: x for x in _q(
|
|
||||||
db, "SELECT Number,Name,Unit,Quantity,Price,Total,Kind,uw_id,div_id"
|
|
||||||
" FROM s_bills WHERE session_id=?", (sid,))}
|
|
||||||
assert len(bills) == 3
|
|
||||||
assert bills["010101001001"][2:6] == ("m3", 10.0, 50.0, 500.0)
|
|
||||||
assert bills["010101001001"][6] is None
|
|
||||||
assert bills["020101001001"][2:6] == ("m2", 10.0, 20.0, 200.0)
|
|
||||||
assert bills["(1)"][6] == "prelim" and bills["(1)"][8] == divs[2][0]
|
|
||||||
|
|
||||||
# 定额 + 消耗:同名 ResourceID=1 在两个单位工程分别解析为 R00001 / C00001
|
|
||||||
norms = {x[0]: x[1:] for x in _q(
|
|
||||||
db, """SELECT n.Number,n.Unit,n.Quantity,n.Price,n.Total
|
|
||||||
FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=?""", (sid,))}
|
|
||||||
assert norms["N1"] == ("10m3", 1.0, 500.0, 500.0)
|
|
||||||
assert norms["N2"] == ("10m2", 1.0, 200.0, 200.0)
|
|
||||||
nres = _q(db, """SELECT n.Number,r.res_code,r.qty FROM s_norm_res r
|
|
||||||
JOIN s_norms n ON n.id=r.norm_id
|
|
||||||
JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=? ORDER BY n.Number""", (sid,))
|
|
||||||
assert nres == [("N1", "R00001", 2.5), ("N2", "C00001", 0.5)]
|
|
||||||
|
|
||||||
# 工料机 + 税率口径 A:除税价=含税价=Rate、税率 0
|
|
||||||
lmes = {x[0]: x[1:] for x in _q(
|
|
||||||
db, "SELECT Number,Name,Unit,Quantity,NoTaxPrice,TaxRate,TaxPrice,Kind"
|
|
||||||
" FROM s_lmes WHERE session_id=?", (sid,))}
|
|
||||||
assert lmes["R00001"] == ("普工", "元", 25.0, 1.5, 0.0, 1.5, 1)
|
|
||||||
assert lmes["C00001"] == ("钢材", "t", 100.0, 2.0, 0.0, 2.0, 2)
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM s_lme_uw WHERE session_id=?", (sid,))[0][0] == 2
|
|
||||||
assert dict(_q(db, "SELECT code,qty FROM s_lme_proj WHERE session_id=?", (sid,))) == {
|
|
||||||
"R00001": 25.0, "C00001": 100.0}
|
|
||||||
for row in _q(db, "SELECT ntp,taxp,taxrate FROM s_lme_proj WHERE session_id=?", (sid,)):
|
|
||||||
assert row[0] is not None and row[1] == row[0] and row[2] == 0.0
|
|
||||||
for row in _q(db, "SELECT ntp,taxrate,taxp FROM s_lme_uw WHERE session_id=?", (sid,)):
|
|
||||||
assert row[0] is not None and row[1] == 0.0 and row[2] == row[0]
|
|
||||||
|
|
||||||
# 重新解析:SWT 源文件可重跑,条数不变
|
|
||||||
rp = post(server, "/api/session/reparse", {"session_id": sid})
|
|
||||||
assert rp["ok"] is True, rp
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 3
|
|
||||||
assert _q(db, """SELECT COUNT(*) FROM s_norm_res r JOIN s_norms n ON n.id=r.norm_id
|
|
||||||
JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=?""", (sid,))[0][0] == 2
|
|
||||||
|
|
||||||
# 原格式导出:建议名保留源后缀(SWT/SWZ 都走骨架回写)
|
|
||||||
m = get(server, "/api/session/export/meta", session_id=sid)
|
|
||||||
assert m["ok"] is True and m["name"].lower().endswith(".swt")
|
|
||||||
|
|
||||||
|
|
||||||
def test_swt_batch_import(server):
|
|
||||||
src = str(server["src_dir"] / "swt_batch.swt")
|
|
||||||
make_swt(src, "SWT批次工程", UNITS)
|
|
||||||
p = _upload(server, src, "swt_batch.swt")
|
|
||||||
r = post(server, "/api/admin/import", dict(META, path=p, name="SWT批次A"))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
bid = r["batch_id"]
|
|
||||||
db = server["db"]
|
|
||||||
assert _q(db, "SELECT x_total FROM batches WHERE id=?", (bid,))[0][0] == 1234.56
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM bills WHERE batch_id=?", (bid,))[0][0] == 3
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM norms WHERE bill_id IN"
|
|
||||||
" (SELECT id FROM bills WHERE batch_id=?)", (bid,))[0][0] == 2
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM lmes WHERE batch_id=?", (bid,))[0][0] == 2
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM lme_uw WHERE batch_id=?", (bid,))[0][0] == 2
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM lme_proj WHERE batch_id=?", (bid,))[0][0] == 2
|
|
||||||
nres = _q(db, """SELECT n.Number,r.res_code,r.qty FROM norm_res r
|
|
||||||
JOIN norms n ON n.id=r.norm_id
|
|
||||||
WHERE n.bill_id IN (SELECT id FROM bills WHERE batch_id=?)
|
|
||||||
ORDER BY n.Number""", (bid,))
|
|
||||||
assert nres == [("N1", "R00001", 2.5), ("N2", "C00001", 0.5)]
|
|
||||||
|
|
||||||
|
|
||||||
def _f(x):
|
|
||||||
try:
|
|
||||||
return float(x)
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def test_swt_export_roundtrip_edits(server):
|
|
||||||
"""原格式导出(骨架+填空):改名/改量、临删、新增清单都要回写,汇总按现量重算,
|
|
||||||
导出的 SWT 还能再次被本软件解析。"""
|
|
||||||
src = str(server["src_dir"] / "swt_export.swt")
|
|
||||||
make_swt(src, "SWT导出工程", UNITS)
|
|
||||||
p = _upload(server, src, "swt_export.swt")
|
|
||||||
r = post(server, "/api/audit", dict(META, path=p, name="SWT导出工程A"))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
db = server["sessdb"]
|
|
||||||
bills = _q(db, "SELECT id,Number FROM s_bills WHERE session_id=? AND Kind IS NULL"
|
|
||||||
" ORDER BY id", (sid,))
|
|
||||||
assert len(bills) == 2
|
|
||||||
b1, b2 = bills[0][0], bills[1][0]
|
|
||||||
assert post(server, "/api/session/bill/op",
|
|
||||||
{"op": "edit", "bill_id": b1,
|
|
||||||
"fields": {"Name": "清单一改", "Quantity": 20}})["ok"]
|
|
||||||
assert post(server, "/api/session/bill/op", {"op": "tdel", "bill_id": b2})["ok"]
|
|
||||||
ins = post(server, "/api/session/bill/op", {"op": "insert_below", "bill_id": b1})
|
|
||||||
assert ins["ok"], ins
|
|
||||||
assert post(server, "/api/session/bill/op",
|
|
||||||
{"op": "edit", "bill_id": ins["id"],
|
|
||||||
"fields": {"Name": "新增清单", "Attr": "新增特征",
|
|
||||||
"Quantity": 5}})["ok"]
|
|
||||||
|
|
||||||
resp = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert resp.status_code == 200, resp.text[:300]
|
|
||||||
assert resp.content[:2] == b"<?"
|
|
||||||
root = ET.fromstring(resp.content)
|
|
||||||
assert all("__used" not in x.attrib for x in root.iter()) # 不得把内部匹配标记写进导出件
|
|
||||||
items = {x.get("Code"): x for x in root.iter("BQItem")}
|
|
||||||
a = items.get("010101001001")
|
|
||||||
assert a is not None
|
|
||||||
assert a.get("Name") == "清单一改" and a.get("Quantity") == "20"
|
|
||||||
assert a.get("Rate") == "50" and a.get("Total") == "1000"
|
|
||||||
assert "020101001001" not in items # 临删不写
|
|
||||||
new = [x for x in root.iter("BQItem") if x.get("Name") == "新增清单"]
|
|
||||||
assert len(new) == 1
|
|
||||||
assert new[0].get("Code") == "" and new[0].get("Quantity") == "5"
|
|
||||||
assert new[0].get("Rate") is None and new[0].get("Total") is None
|
|
||||||
|
|
||||||
u1 = root.findall(".//UnitProject")[0]
|
|
||||||
sm = {x.get("CostCode"): _f(x.get("Total")) for x in u1.iter("SummaryItem")}
|
|
||||||
assert sm["A"] == 1000.0 # 单位1:改量后 20×50
|
|
||||||
assert sm["B"] == 100.0 # 措施叶子未动
|
|
||||||
assert sm["E"] == round(sm["A"] + sm["B"] + sm["C"] + sm["D"], 2)
|
|
||||||
|
|
||||||
# 导出的 SWT 再导入:能被本软件重新识别
|
|
||||||
outp = server["src_dir"] / "swt_exported.SWT"
|
|
||||||
outp.write_bytes(resp.content)
|
|
||||||
up = _upload(server, str(outp), "swt_exported.SWT")
|
|
||||||
rr = post(server, "/api/audit", dict(META, path=up, name="SWT导出工程B"))
|
|
||||||
assert rr["ok"] is True, rr
|
|
||||||
sid2 = rr["session_id"]
|
|
||||||
rows = _q(db, "SELECT Number,Name,Quantity,Price,Total FROM s_bills"
|
|
||||||
" WHERE session_id=? AND Kind IS NULL ORDER BY id", (sid2,))
|
|
||||||
assert ("010101001001", "清单一改", 20.0, 50.0, 1000.0) in rows
|
|
||||||
assert any(x[1] == "新增清单" and x[2] == 5.0 for x in rows)
|
|
||||||
assert not any(x[0] == "020101001001" for x in rows)
|
|
||||||
|
|
||||||
|
|
||||||
def test_swz_xml_and_zip_case_insensitive(server):
|
|
||||||
"""2026-10-19 主人定:.SWZ/.SWT 不分大小写,均按同一套深圳数据交换标准解析。
|
|
||||||
.SWZ 既可能是裸 XML,也可能是压缩包(里面装同一份 XML)。"""
|
|
||||||
# 1) 裸 XML,扩展名大写 .SWZ
|
|
||||||
src = str(server["src_dir"] / "swz_xml.SWZ")
|
|
||||||
make_swt(src, "SWZ测试工程", UNITS)
|
|
||||||
p = _upload(server, src, "swz_xml.SWZ")
|
|
||||||
r = post(server, "/api/audit", dict(META, path=p, name="SWZ工程XML"))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_bills WHERE session_id=?",
|
|
||||||
(sid,))[0][0] == 3
|
|
||||||
m = get(server, "/api/session/export/meta", session_id=sid)
|
|
||||||
assert m["ok"] is True and m["name"].lower().endswith(".swz")
|
|
||||||
ex = server["client"].get("/api/session/export", params={"session_id": sid})
|
|
||||||
assert ex.status_code == 200 and ex.content[:2] == b"<?"
|
|
||||||
assert ET.fromstring(ex.content).tag == "ConstructProject"
|
|
||||||
|
|
||||||
# 2) 压缩包 .SwZ(混合大小写),包内 Project.xml 是同一份 SWT
|
|
||||||
raw = open(src, "rb").read()
|
|
||||||
zp = str(server["src_dir"] / "swz_zip_pkg.SwZ")
|
|
||||||
with zipfile.ZipFile(zp, "w", zipfile.ZIP_DEFLATED) as z:
|
|
||||||
z.writestr("Project.xml", raw)
|
|
||||||
p2 = _upload(server, zp, "swz_zip_pkg.SwZ")
|
|
||||||
r2 = post(server, "/api/audit", dict(META, path=p2, name="SWZ工程ZIP"))
|
|
||||||
assert r2["ok"] is True, r2
|
|
||||||
sid2 = r2["session_id"]
|
|
||||||
assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_bills WHERE session_id=?",
|
|
||||||
(sid2,))[0][0] == 3
|
|
||||||
assert _q(server["sessdb"], """SELECT COUNT(*) FROM s_norm_res r
|
|
||||||
JOIN s_norms n ON n.id=r.norm_id
|
|
||||||
JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=?""", (sid2,))[0][0] == 2
|
|
||||||
ex2 = server["client"].get("/api/session/export", params={"session_id": sid2})
|
|
||||||
assert ex2.status_code == 200 and ex2.content[:2] == b"PK"
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(ex2.content))
|
|
||||||
member = next(n for n in z.namelist()
|
|
||||||
if b"<ConstructProject" in z.read(n)[:16384])
|
|
||||||
assert ET.fromstring(z.read(member)).tag == "ConstructProject"
|
|
||||||
|
|
||||||
|
|
||||||
def test_swz_blank_bill_keeps_prices_empty(server):
|
|
||||||
"""空白量单版 SWZ(FileType=0):只有清单工程量,没有单价/定额/工料机。
|
|
||||||
必须忠实保留空值——不能拿别的字段凑单价,也不能凭 0 元编造定额/税。"""
|
|
||||||
xml = ('<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<ConstructProject Code="001" Name="空白量单" Tenderee="444" '
|
|
||||||
'Standard="深圳市工程造价数据交换标准" FileType="0" Version="SJG77-2020" TaxModel="1">'
|
|
||||||
'<TenderInfo Total="0"/>'
|
|
||||||
'<SingleProject ProjectID="1" Name="单项" Total="0">'
|
|
||||||
'<UnitProject ProjectID="11" Name="建筑工程" Total="0">'
|
|
||||||
'<Summary/>'
|
|
||||||
'<BQTable><BQTitle BQTitleID="1" Name="整个项目">'
|
|
||||||
'<BQItem BQItemID="1" Code="010101001001" Name="清单一" Feature="" '
|
|
||||||
'Unit="m3" Quantity="100" Sequence="1"><Norms/></BQItem>'
|
|
||||||
'</BQTitle></BQTable>'
|
|
||||||
'<MeasureTable><MeasureTitle MeasureTitleID="2" Name="措施项目">'
|
|
||||||
'<MeasureItem MeasureItemID="3" Code="1" Name="安全文明施工费" Unit="项" Total="0"/>'
|
|
||||||
'</MeasureTitle></MeasureTable>'
|
|
||||||
'<Resource/>'
|
|
||||||
'</UnitProject></SingleProject></ConstructProject>')
|
|
||||||
p = str(server["src_dir"] / "swz_blank.SWZ")
|
|
||||||
with open(p, "w", encoding="utf-8", newline="") as f:
|
|
||||||
f.write(xml)
|
|
||||||
up = _upload(server, p, "swz_blank.SWZ")
|
|
||||||
r = post(server, "/api/audit", dict(META, path=up, name="SWZ空白量单"))
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
sid = r["session_id"]
|
|
||||||
db = server["sessdb"]
|
|
||||||
bills = _q(db, "SELECT Number,Quantity,Price,Total,Kind FROM s_bills"
|
|
||||||
" WHERE session_id=? ORDER BY id", (sid,))
|
|
||||||
assert len(bills) == 2
|
|
||||||
bq = [x for x in bills if x[0] == "010101001001"][0]
|
|
||||||
assert bq[1] == 100.0 and bq[2] is None and bq[3] is None
|
|
||||||
assert _q(db, """SELECT COUNT(*) FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
|
||||||
WHERE b.session_id=?""", (sid,))[0][0] == 0
|
|
||||||
assert _q(db, "SELECT COUNT(*) FROM s_lmes WHERE session_id=?", (sid,))[0][0] == 0
|
|
||||||
assert _q(db, "SELECT x_total FROM sessions WHERE id=?", (sid,))[0][0] == 0.0
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""定额单价专题(2026-11-03 主人定)端到端回归:三同合并全字段统一 + 原价三级链 + flags 导出。
|
|
||||||
|
|
||||||
钉死口径:
|
|
||||||
① 导入捕获:LME_SUM 文字/标志属性全采进 x_flags(含本次补的 ProviderBase/Weight);
|
|
||||||
合并弹框聚合行带 x_flags 透传。
|
|
||||||
② 三同合并=「勾选谁按哪一行的字段」:保留行 kind/x_flags=勾选行;变体行换码后 kind/x_flags
|
|
||||||
一并统一(唯一值约束:合并后一个项目该三同只输出一条、全字段统一)。
|
|
||||||
③ 原价三级链:①单位级 → ②项目级 → ③第一次外部采纳价(x_org_*0 专列,采纳落价空则写、
|
|
||||||
后续采纳不改、手工改价永不写);显示端 dyn 链与导出端 price_updates 同口径。
|
|
||||||
④ 导出:合并码 Kind/x_flags 经 price_updates 回写(骨架卡槽在才写=骨架过滤);恒空链键
|
|
||||||
(Remark/PriceSource/Delivery/Location/ProducingArea/Supplier/Character)不回写;
|
|
||||||
未合并行=源文件原样(按源数据+骨架过滤输出)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from api_harness import META, PERIOD_202607, fixture_file, get, post, server # noqa: F401
|
|
||||||
|
|
||||||
from test_api_p1 import raw_post # 复用二进制直传
|
|
||||||
|
|
||||||
CLS_A = (' Class="A" MainMaterial="false" Weight="0" ProviderBase="0" Provider="1"'
|
|
||||||
' ProvisionalMaterial="false" Remark="原始备注"')
|
|
||||||
CLS_B = ' Class="B" MainMaterial="true" Weight="1.2"'
|
|
||||||
# 三同组「柴油 0#」两码:CL01=勾选行(Kind 改成 2 的样子造不出来——make_cos4 固定 Kind=1,
|
|
||||||
# 用 x_flags/kind 断言以聚合行返回值为准),CL02=变体
|
|
||||||
UW_LMES = [("CL01", "柴油 0#", "0#", "kg", "6.50", "6.89"),
|
|
||||||
("CL02", "柴油 0#", "0#", "kg", "7.20", "7.66")]
|
|
||||||
UW_ATTRS = {"CL01": CLS_A, "CL02": CLS_B}
|
|
||||||
|
|
||||||
|
|
||||||
def _mk(server, name):
|
|
||||||
"""造件+真实流程导入:upload → admin/import → audit 开会话。返回 sid。"""
|
|
||||||
from api_harness import make_cos4
|
|
||||||
fname = name + ".cos4"
|
|
||||||
fix = server["root"] / "fixsrc"
|
|
||||||
fix.mkdir(exist_ok=True)
|
|
||||||
# 两条清单分别消耗 CL01/CL02(_bill_xml 按序轮转)→ 两码都有现算量、可进合并弹框(决策244)
|
|
||||||
make_cos4(str(fix / fname), name,
|
|
||||||
[("030507008001", name + "清单项A", "", "台", 3, 500),
|
|
||||||
("030507008002", name + "清单项B", "", "台", 2, 400)],
|
|
||||||
lmes=UW_LMES, uw_lmes=UW_LMES, uw_lme_attrs=UW_ATTRS, lme_rot=True)
|
|
||||||
# 幂等重跑:先删同名旧批次(删批次会清 uploads 副本,必须在 upload 之前删)
|
|
||||||
import sqlite3 as _s
|
|
||||||
_con = _s.connect(server["db"])
|
|
||||||
try:
|
|
||||||
bids = [x[0] for x in _con.execute(
|
|
||||||
"SELECT id FROM batches WHERE name=?", (name,)).fetchall()]
|
|
||||||
finally:
|
|
||||||
_con.close()
|
|
||||||
for b in bids:
|
|
||||||
post(server, "/api/admin/batch/%d/delete" % b, {})
|
|
||||||
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
|
|
||||||
assert up["ok"] is True, up
|
|
||||||
r = post(server, "/api/audit",
|
|
||||||
dict(META, path=up["path"], name=name, file_kind=1))
|
|
||||||
assert r.get("ok") is True, r
|
|
||||||
return r["session_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def _sess_q(server, sql, args=()):
|
|
||||||
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
return con.execute(sql, args).fetchall()
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_groups_carries_flags_and_merge_unifies_all(server): # noqa: F811
|
|
||||||
sid = _mk(server, "定额单价专题一")
|
|
||||||
# ① 弹框分组:聚合行带 x_flags(ProviderBase/Weight 采进来了)
|
|
||||||
g = get(server, "/api/session/lme/merge/groups", session_id=sid)
|
|
||||||
grp = next(x for x in g["groups"] if x["name"] == "柴油 0#")
|
|
||||||
agg = next(x for x in grp["rows"] if x["lvl"] == "uw" and x["code"] == "CL01")
|
|
||||||
fl = json.loads(agg["x_flags"]) if agg.get("x_flags") else {}
|
|
||||||
assert fl.get("ProviderBase") == "0" and fl.get("Weight") == "0", fl
|
|
||||||
assert fl.get("Class") == "A" and fl.get("MainMaterial") == "false", fl
|
|
||||||
# ② 合并=勾 CL01 → 全字段统一
|
|
||||||
r = post(server, "/api/session/lme/merge", {"session_id": sid, "groups": [{
|
|
||||||
"sel": {"uw": 1, "code": "CL01", "uw_ids": agg["uw_ids"], "ntp": 6.50,
|
|
||||||
"taxrate": 0, "taxp": 6.89, "name": "柴油 0#", "spec": "0#", "unit": "kg",
|
|
||||||
"kind": agg.get("kind"), "x_flags": agg["x_flags"], "qty": 0},
|
|
||||||
"hide": [{"uw": 1, "code": "CL02", "uw_ids": agg["uw_ids"]},
|
|
||||||
{"uw": 1, "code": "CL01", "uw_ids": agg["uw_ids"]}]}]})
|
|
||||||
assert r["ok"] is True, r
|
|
||||||
keep = _sess_q(server, "SELECT code,kind,x_flags,ntp,x_merged_hide FROM s_lme_proj "
|
|
||||||
"WHERE session_id=? AND code='CL01'", (sid,))[0]
|
|
||||||
assert keep["kind"] is not None and keep["x_flags"], (keep["kind"], keep["x_flags"])
|
|
||||||
kfl = json.loads(keep["x_flags"])
|
|
||||||
assert kfl.get("ProviderBase") == "0" and kfl.get("Class") == "A", kfl
|
|
||||||
gone = _sess_q(server, "SELECT COALESCE(x_merged_hide,0) h FROM s_lme_proj "
|
|
||||||
"WHERE session_id=? AND code='CL02'", (sid,))
|
|
||||||
assert all(x["h"] == 1 for x in gone), gone # 变体项目行隐藏
|
|
||||||
uw01 = _sess_q(server, "SELECT kind,x_flags FROM s_lme_uw WHERE session_id=? AND code='CL01'",
|
|
||||||
(sid,))
|
|
||||||
assert len(uw01) == 1, uw01 # 造件单单位:CL02 换码归并进 CL01(变体消失)
|
|
||||||
assert all(x["kind"] is not None for x in uw01), uw01 # kind 统一为勾选行
|
|
||||||
assert all(json.loads(x["x_flags"]).get("Class") == "A" for x in uw01), uw01 # flags 统一
|
|
||||||
# ③ 原价③级:采纳落价写专列;第二次采纳不改;手工改价不写
|
|
||||||
pid = _sess_q(server, "SELECT id FROM s_lme_proj WHERE session_id=? AND code='CL01'",
|
|
||||||
(sid,))[0]["id"]
|
|
||||||
r1 = post(server, "/api/session/lme/price",
|
|
||||||
{"session_id": sid, "id": pid, "ntp": 7.10, "taxrate": 0, "taxp": 7.10, "adopt": 1})
|
|
||||||
assert r1["ok"] is True, r1
|
|
||||||
org1 = _sess_q(server, "SELECT x_org_ntp0, x_org_taxp0 FROM s_lme_proj WHERE id=?", (pid,))[0]
|
|
||||||
assert org1["x_org_ntp0"] == 7.10 and org1["x_org_taxp0"] == 7.10, org1
|
|
||||||
post(server, "/api/session/lme/price",
|
|
||||||
{"session_id": sid, "id": pid, "ntp": 8.80, "taxrate": 0, "taxp": 8.80, "adopt": 1})
|
|
||||||
org2 = _sess_q(server, "SELECT x_org_ntp0, ntp FROM s_lme_proj WHERE id=?", (pid,))[0]
|
|
||||||
assert org2["x_org_ntp0"] == 7.10 and org2["ntp"] == 8.80, org2 # 后续采纳不改专列
|
|
||||||
post(server, "/api/session/lme/price", {"session_id": sid, "id": pid, "ntp": 9.90})
|
|
||||||
org3 = _sess_q(server, "SELECT x_org_ntp0 FROM s_lme_proj WHERE id=?", (pid,))[0]
|
|
||||||
assert org3["x_org_ntp0"] == 7.10, org3 # 手工改价不写
|
|
||||||
# ④ 导出原格式:保留行全字段统一+卡槽回写+恒空链;变体行消失(唯一输出)
|
|
||||||
resp = server["client"].get("/api/session/export",
|
|
||||||
params={"session_id": sid, "name": "定额单价专题一",
|
|
||||||
"province": "广东省", "city": "珠海市",
|
|
||||||
"period_from": PERIOD_202607})
|
|
||||||
assert resp.status_code == 200, resp.text[:200]
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
|
||||||
import re as _re
|
|
||||||
import sys as _sys
|
|
||||||
print("ZIP条目:", z.namelist(), file=_sys.stderr)
|
|
||||||
hits = []
|
|
||||||
for n in z.namelist():
|
|
||||||
if n.endswith(".xml") and n != "Project.xml":
|
|
||||||
txt = z.read(n).decode("utf-8", "replace")
|
|
||||||
for m in _re.finditer("<LabourMaterialsEquipmentsMachinesSummary[^>]*>", txt):
|
|
||||||
hits.append(m.group(0))
|
|
||||||
blob = "\n".join(hits)
|
|
||||||
print("LME片段数:", len(hits), file=_sys.stderr)
|
|
||||||
assert "Number=\"CL02\"" not in blob, "变体行应整块消失"
|
|
||||||
assert "Number=\"CL01\"" in blob
|
|
||||||
# 取真正的 Summary 行(排除定额下同码 Element 行干扰 find)
|
|
||||||
summ = [h for h in hits if h.startswith("<LabourMaterialsEquipmentsMachinesSummary")]
|
|
||||||
assert len(summ) == 1, summ
|
|
||||||
line = summ[0]
|
|
||||||
print("SUMMARY行:", line, file=_sys.stderr)
|
|
||||||
assert "Number=\"CL01\"" in line
|
|
||||||
assert "Kind=" in line
|
|
||||||
assert 'Remark=""' in line, "Remark 恒空"
|
|
||||||
assert "原始备注" not in blob, "flags 里的 Remark 不得回写"
|
|
||||||
assert 'MainMaterial="' in line, "flags 属性按卡槽输出"
|
|
||||||
post(server, "/api/session/delete", {"ids": [sid]})
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""L1 单元测试:归一化 / 特征清洗 / 文件嗅探 / 期次识别 / 字集键 / 相似度 /
|
|
||||||
parse_std 结构 / 价格 HTML 解析。纯函数为主,毫秒级,不碰任何库文件。"""
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
|
|
||||||
_APP = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
||||||
_CORE = os.path.join(_APP, "core")
|
|
||||||
if _CORE not in sys.path:
|
|
||||||
sys.path.insert(0, _CORE)
|
|
||||||
|
|
||||||
import import_job as job # noqa: E402
|
|
||||||
import match # noqa: E402
|
|
||||||
import price_html # noqa: E402
|
|
||||||
|
|
||||||
from api_harness import make_cos4 # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 归一化
|
|
||||||
def test_norm_basics():
|
|
||||||
assert job.norm("( M7.5 )") == "(m7.5)" # 全角括号 + 小写 + 去空白
|
|
||||||
assert job.norm("3X2") == "3*2" # X → *
|
|
||||||
assert job.norm("C 25 混凝土") == "c25混凝土"
|
|
||||||
assert job.norm("12㎡") == "12m2"
|
|
||||||
assert job.norm("") == "" and job.norm(None) == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_md5_stable():
|
|
||||||
assert job.md5("a", "b") == job.md5("a", "b")
|
|
||||||
assert job.md5("ab") != job.md5("a", "b") # 分隔符防拼接歧义
|
|
||||||
assert job.md5("A B", "b") == job.md5("ab", "b") # 归一(去空白/小写)后哈希一致
|
|
||||||
|
|
||||||
|
|
||||||
def test_clean_attr_strips_and_guard():
|
|
||||||
assert job.clean_attr("1、砌筑;详见设计图纸") == "砌筑" # 编号 + 停用词 + 标点
|
|
||||||
# 2026-10-10 小数点护栏:"2.5、" 的 "5、" 不能被当编号剥掉(否则剁成碎块)
|
|
||||||
assert job.clean_attr("2.5、水泥砂浆") == "25水泥砂浆"
|
|
||||||
assert "水泥" in job.clean_attr("规格型号:水泥") # 字段名前缀剥离
|
|
||||||
|
|
||||||
|
|
||||||
def test_sniff():
|
|
||||||
import tempfile
|
|
||||||
d = tempfile.mkdtemp()
|
|
||||||
cases = [(b"PK\x03\x04rest", "zip"), (b"\x88\x7drest", "encrypted"),
|
|
||||||
(b"<?xml ", "xml"), (b"\xef\xbb\xbf<x/>", "xml"), (b"ABCD", "unknown")]
|
|
||||||
for i, (head, want) in enumerate(cases):
|
|
||||||
p = os.path.join(d, "f%d" % i)
|
|
||||||
io.open(p, "wb").write(head)
|
|
||||||
assert job.sniff(p) == want, (head, want)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 期次
|
|
||||||
def test_ym_and_dist():
|
|
||||||
assert match.ym(2026 * 12 + 7) == "2026.07"
|
|
||||||
assert match.ym(2026 * 12) == "2025.12" # 12 月特判
|
|
||||||
assert match.ym(None) == "—"
|
|
||||||
# 有重叠 = 0;早 18 个月;晚 2 个月
|
|
||||||
assert match.dist(24310, 24320, 24319) == 0
|
|
||||||
assert match.dist(24300, 24301, 24319) == 18
|
|
||||||
assert match.dist(24321, 24330, 24319) == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_guess_period():
|
|
||||||
assert price_html.guess_period("珠海市建材综合价2026年7月") == (24319, 24319)
|
|
||||||
assert price_html.guess_period("2026年4-6月园林苗木") == (24316, 24318)
|
|
||||||
assert price_html.guess_period("2026年11月~2027年1月") == (24323, 24325)
|
|
||||||
assert price_html.guess_period("没有日期的块名") == (None, None)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 字集键 / 相似度
|
|
||||||
def test_setkey_anagram_equivalence():
|
|
||||||
assert match.bill_setkey("钢筋混凝土", "t") == match.bill_setkey("混凝土钢筋", "t")
|
|
||||||
assert match.bill_setkey("钢筋混凝土", "t") != match.bill_setkey("钢筋混凝土", "m")
|
|
||||||
|
|
||||||
|
|
||||||
def test_sim_weighted_token_veto():
|
|
||||||
# 查询名称里的字母数字 token(400w)候选里没有 → 一票否决
|
|
||||||
assert match.sim_weighted("400w摄像机", "高清摄像机", "", "") == 0.0
|
|
||||||
# 同名同空特征 = 满分(两边都没写特征 → 特征维度按满分)
|
|
||||||
assert match.sim_weighted("摄像机", "摄像机", "", "") == 1.0
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 工料机过滤(CAST 坑)
|
|
||||||
def test_lme_list_where_kind_cast():
|
|
||||||
con = sqlite3.connect(":memory:")
|
|
||||||
con.execute("CREATE TABLE l(Kind, Unit)")
|
|
||||||
con.executemany("INSERT INTO l VALUES(?,?)",
|
|
||||||
[(6, "m3"), (7, "台班"), (1, "元"), (1, "工日"), (1, "m3"),
|
|
||||||
("6", "m3")]) # TEXT 存的 Kind 也要被排除
|
|
||||||
sql = "SELECT COUNT(*) FROM l WHERE %s" % match.lme_list_where()
|
|
||||||
assert con.execute(sql).fetchone()[0] == 1 # 只剩 (1, 'm3')
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- parse_std 结构
|
|
||||||
def test_parse_std_structure(tmp_path):
|
|
||||||
p = make_cos4(str(tmp_path / "s.cos4"), "解析工程P",
|
|
||||||
[("030507008001", "高清网络摄像机", "1、400万", "台", 10, 1500),
|
|
||||||
("030405006001", "智能电度表", "", "只", 20, 300)],
|
|
||||||
[("000001", "网络摄像机", "400万", "台", "1200", "1356")])
|
|
||||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1,
|
|
||||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0, "lme_raw": 0,
|
|
||||||
"lme_skip": 0, "proj_name": "", "file_kind": None, "bulid_unit": "",
|
|
||||||
"total": None}
|
|
||||||
assert job.parse_std(p, out) == "2025标准"
|
|
||||||
assert out["proj_name"] == "解析工程P"
|
|
||||||
assert out["total"] == 1234567.89 # proj_total 三级兜底之 SummaryOfCost
|
|
||||||
assert len(out["uw"]) == 1 and out["uw"][0][1] == "1号楼"
|
|
||||||
assert len(out["bills"]) == 3 # 2 分部分项 + 1 措施(导入不过滤)
|
|
||||||
assert out["bill_kind"][-1] == "prelim"
|
|
||||||
assert out["bills"][0][1] == "高清网络摄像机"
|
|
||||||
assert len(out["norms"]) == 2 and out["norms"][0][2] == "高清网络摄像机安装"
|
|
||||||
assert out["norm_res"] and out["norm_res"][0][1] == "000001" # 定额消耗挂对定额
|
|
||||||
assert len(out["lmes"]) == 1 # 工料机 = 单位工程汇总(去重前 1 条)
|
|
||||||
assert "000001" in out["lme_lib"] and "000001" in out["lme_proj"]
|
|
||||||
assert out["sections"] and out["sections"][0]["uw_nums"] == ["UW1"]
|
|
||||||
assert out["uw_cost"][0]["Construction"] == 800000.0
|
|
||||||
assert out["feat"] == [("工程类别", "房屋建筑")]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 价格 HTML 解析
|
|
||||||
PRICE_TMPL = '<html><head><meta charset="utf-8"></head><body><script>const DATA = %s;</script>'
|
|
||||||
|
|
||||||
def _price_tmp(tmp_path, blocks, name="p.html"):
|
|
||||||
p = tmp_path / name
|
|
||||||
p.write_text(PRICE_TMPL % json.dumps(blocks, ensure_ascii=False), encoding="utf-8")
|
|
||||||
return str(p)
|
|
||||||
|
|
||||||
|
|
||||||
def test_price_html_parse_and_records(tmp_path):
|
|
||||||
p = _price_tmp(tmp_path, [
|
|
||||||
{"name": "建材2026年7月", "columns": [], "sections": [
|
|
||||||
{"title": "一、黑色金属", "rows": [
|
|
||||||
["C1", "圆钢", "Φ12", "t", "4200", "3", "4326", "备注A"],
|
|
||||||
["", "", "", "", "", "", "", ""]]}]}, # 空名称行 → to_records 跳过
|
|
||||||
{"name": "苗木2026年4-6月", "columns": [], "sections": [
|
|
||||||
{"title": "苗木", "rows": [["M1", "香樟", "胸径10cm", "株", "350", "", "361", ""]]}]}])
|
|
||||||
blocks = price_html.parse(p)
|
|
||||||
assert len(blocks) == 2 # 一个块 = 一个批次
|
|
||||||
assert blocks[0]["period_start_m"] == 24319
|
|
||||||
assert (blocks[1]["period_start_m"], blocks[1]["period_end_m"]) == (24316, 24318)
|
|
||||||
assert len(blocks[0]["rows"][0][1]) == 8 # 短行补齐 8 列
|
|
||||||
recs = price_html.to_records(blocks)
|
|
||||||
assert len(recs) == 2 # 空名称被跳过
|
|
||||||
assert recs[0]["Class"] == "一、黑色金属" # 目录原封不动
|
|
||||||
assert recs[0]["Block"] == "建材2026年7月"
|
|
||||||
assert recs[0]["NoTaxPrice"] == 4200.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_price_html_rejects_non_data(tmp_path):
|
|
||||||
p = tmp_path / "bad.html"
|
|
||||||
p.write_text("<html>没有数据块</html>", encoding="utf-8")
|
|
||||||
try:
|
|
||||||
price_html.parse(str(p))
|
|
||||||
assert False, "应当抛 ValueError"
|
|
||||||
except ValueError as e:
|
|
||||||
assert "DATA" in str(e)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 价格 Excel 解析
|
|
||||||
def test_price_xlsx_parse_and_template(tmp_path):
|
|
||||||
"""2026-10-12 重设计:只收标准模板(表头严格全等,别名拒绝);目录列=多级路径原样。"""
|
|
||||||
import price_xlsx
|
|
||||||
from openpyxl import Workbook
|
|
||||||
# 旧版别名表头 → 直接拒绝(主人定「只能导入标准模板」)
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
ws.append(["目录", "编码", "名称", "规格", "计量单位",
|
|
||||||
"除税价", "税率%", "含税价", "说明"])
|
|
||||||
ws.append(["一、黑色金属", "C1", "圆钢", "Φ12", "t", 4200, "3%", 4326, "备注"])
|
|
||||||
p = tmp_path / "alias.xlsx"
|
|
||||||
wb.save(p)
|
|
||||||
try:
|
|
||||||
price_xlsx.parse(str(p))
|
|
||||||
assert False, "别名表头应当被拒绝"
|
|
||||||
except ValueError as e:
|
|
||||||
assert "标准模板" in str(e)
|
|
||||||
# 标准表头 → 解析成功;目录多级路径原样保存(建树在入库侧)
|
|
||||||
wb2 = Workbook()
|
|
||||||
ws2 = wb2.active
|
|
||||||
ws2.append(price_xlsx.COLS)
|
|
||||||
ws2.append(["建筑材料/黑色金属/钢筋", "C1", "圆钢", "Φ12", "t", 4200, "3%", 4326, "备注"])
|
|
||||||
ws2.append(["建筑材料/黑色金属/钢筋", "C2", "焊管", "DN50", "m", 210, 0.03, 216.3, ""])
|
|
||||||
ws2.append(["", "", "", "", "", "", "", "", ""]) # 整行空 → 跳过
|
|
||||||
wb2.create_sheet("填写说明") # 说明 sheet 不参与解析
|
|
||||||
p2 = tmp_path / "p.xlsx"
|
|
||||||
wb2.save(p2)
|
|
||||||
blocks = price_xlsx.parse(str(p2))
|
|
||||||
assert len(blocks) == 1 and blocks[0]["block"] == "p" # block = 文件名(一个文件一个批次)
|
|
||||||
assert len(blocks[0]["rows"]) == 2
|
|
||||||
recs = price_xlsx.to_records(blocks)
|
|
||||||
assert len(recs) == 2
|
|
||||||
assert recs[0]["Class"] == "建筑材料/黑色金属/钢筋" # 路径原样;空目录=空串(不再回落块名)
|
|
||||||
assert recs[0]["NoTaxPrice"] == 4200.0
|
|
||||||
# 标准模板生成 → 解析往返(2026-11-01 起:模板内置珠海信息价 2026年7月 的 864 条真实数据)
|
|
||||||
tpl = tmp_path / "tpl.xlsx"
|
|
||||||
tpl.write_bytes(price_xlsx.template_bytes())
|
|
||||||
blocks2 = price_xlsx.parse(str(tpl))
|
|
||||||
assert len(blocks2) == 1
|
|
||||||
recs2 = price_xlsx.to_records(blocks2)
|
|
||||||
assert len(recs2) == 864
|
|
||||||
assert recs2[0]["Class"] == "珠海市建材设备市场综合价/一、黑色及有色金属" # 目录列 = 多级路径
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""version_gate 强制更新门禁测试(2026-10-27,《企业和个人版.md》5.9)。
|
|
||||||
|
|
||||||
覆盖:版本比较、开发态旁路、无缓存 fail-open、两段式拦截(GET 页/POST JSON)、
|
|
||||||
缓存落盘回读、拉取失败沿用旧缓存、放行清单、status 形状、非法信息文件拒收。
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
|
|
||||||
if SERVER_DIR not in sys.path:
|
|
||||||
sys.path.insert(0, SERVER_DIR)
|
|
||||||
|
|
||||||
import version_gate as vg # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def make_build(app="1.2.0", url="https://releases.example/prd.json", **kw):
|
|
||||||
return SimpleNamespace(APP_VERSION=app, VERSION_INFO_URL=url, **kw)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def fresh(tmp_path):
|
|
||||||
"""每个用例独立 data_dir + 复位全局状态,不起后台线程。"""
|
|
||||||
vg._cache = None
|
|
||||||
vg._cfg.update({"app_version": None, "info_url": None,
|
|
||||||
"interval": vg.DEFAULT_INTERVAL, "data_dir": str(tmp_path)})
|
|
||||||
yield vg
|
|
||||||
vg._cache = None
|
|
||||||
|
|
||||||
|
|
||||||
INFO = {"latest_version": "1.3.0", "min_required_version": "1.2.5",
|
|
||||||
"release_notes": "修复", "package_url": "https://x/pkg.zip", "sha256": "ab"}
|
|
||||||
|
|
||||||
|
|
||||||
def ok_get(url):
|
|
||||||
return dict(INFO)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 版本比较
|
|
||||||
|
|
||||||
def test_vkey():
|
|
||||||
assert vg.vkey("1.2.10") == (1, 2, 10)
|
|
||||||
assert vg.vkey("v1.3") == (1, 3)
|
|
||||||
assert vg.vkey("2.0.0") > vg.vkey("1.9.9")
|
|
||||||
assert vg.vkey("junk") == ()
|
|
||||||
assert vg.vkey(None) == ()
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 开发态旁路
|
|
||||||
|
|
||||||
def test_dev_bypass_no_build(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=None, start_thread=False)
|
|
||||||
assert vg.effective() is False
|
|
||||||
assert vg.intercept("GET", "/admin.html") is None
|
|
||||||
ok, info = vg.check()
|
|
||||||
assert ok and info.get("bypass") == "dev"
|
|
||||||
|
|
||||||
|
|
||||||
def test_dev_bypass_version_dev(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="dev"), start_thread=False)
|
|
||||||
assert vg.effective() is False
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- fail-open:无缓存不拦
|
|
||||||
|
|
||||||
def test_no_cache_never_blocks(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
|
||||||
assert vg.intercept("GET", "/admin.html") is None # 从未拉到且无快照 → 不拦
|
|
||||||
|
|
||||||
|
|
||||||
def test_bad_min_required_fail_open(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
|
||||||
vg._save_cache({"latest_version": "9", "min_required_version": "x.y",
|
|
||||||
"fetched_at": "t"}) # 最低要求解析失败
|
|
||||||
assert vg.intercept("GET", "/admin.html") is None # 视为 0,不拦
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 两段式拦截
|
|
||||||
|
|
||||||
def test_forced_blocks_pages_and_api(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
|
||||||
vg.fetch_once(http_get=ok_get) # min_required=1.2.5 > 1.2.0
|
|
||||||
g = vg.intercept("GET", "/admin.html")
|
|
||||||
assert g and g["kind"] == "html" and "升级" in g["text"]
|
|
||||||
p = vg.intercept("POST", "/api/session/bill/op")
|
|
||||||
assert p and p["kind"] == "json" and p["code"] == 403
|
|
||||||
assert p["obj"]["error"]["code"] == "UPDATE_REQUIRED" # API 绝不回 HTML
|
|
||||||
|
|
||||||
|
|
||||||
def test_ok_version_passes(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.3.0"), start_thread=False)
|
|
||||||
vg.fetch_once(http_get=ok_get) # 1.3.0 >= 1.2.5
|
|
||||||
assert vg.intercept("GET", "/admin.html") is None
|
|
||||||
assert vg.intercept("POST", "/api/session/save") is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_always_paths_pass_even_when_forced(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
|
||||||
vg.fetch_once(http_get=ok_get)
|
|
||||||
assert vg.intercept("GET", "/api/license/status") is None
|
|
||||||
assert vg.intercept("GET", "/api/version") is None
|
|
||||||
assert vg.intercept("GET", "/api/version_info") is None
|
|
||||||
assert vg.intercept("POST", "/api/license/activate") is None
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 拉取与缓存
|
|
||||||
|
|
||||||
def test_fetch_persists_cache(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.3.0"), start_thread=False)
|
|
||||||
assert vg.fetch_once(http_get=ok_get) is True
|
|
||||||
fp = os.path.join(str(tmp_path), vg.CACHE_NAME)
|
|
||||||
d = json.load(open(fp, encoding="utf-8"))
|
|
||||||
assert d["min_required_version"] == "1.2.5" and d["fetched_at"]
|
|
||||||
# 重启(重新 init/load)后缓存仍生效
|
|
||||||
vg._cache = None
|
|
||||||
vg.load_cache()
|
|
||||||
assert vg.status()["min_required"] == "1.2.5"
|
|
||||||
|
|
||||||
|
|
||||||
def test_fetch_failure_keeps_old_cache(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
|
||||||
assert vg.fetch_once(http_get=ok_get) is True
|
|
||||||
def dead(url):
|
|
||||||
raise OSError("断网")
|
|
||||||
assert vg.fetch_once(http_get=dead) is False # 失败静默
|
|
||||||
assert vg.intercept("GET", "/admin.html") is not None # 旧缓存仍判强制
|
|
||||||
|
|
||||||
|
|
||||||
def test_fetch_rejects_malformed_info(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
|
||||||
for bad in ({"latest_version": 3}, {"min_required_version": None}, [1, 2], "x"):
|
|
||||||
assert vg.fetch_once(http_get=lambda u, b=bad: b) is False
|
|
||||||
assert vg._cache is None # 非法信息绝不落缓存
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- status
|
|
||||||
|
|
||||||
def test_status_shape(tmp_path):
|
|
||||||
vg.init(str(tmp_path), build=make_build(app="1.2.8"), start_thread=False)
|
|
||||||
vg.fetch_once(http_get=ok_get)
|
|
||||||
s = vg.status()
|
|
||||||
assert s["current"] == "1.2.8" and s["latest"] == "1.3.0"
|
|
||||||
assert s["min_required"] == "1.2.5" and s["forced"] is False
|
|
||||||
assert s["update_available"] is True # 1.2.8 < 1.3.0 有新版
|
|
||||||
assert s["package_url"] == INFO["package_url"]
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""wipe 清场防回归(2026-10-10)。
|
|
||||||
|
|
||||||
背景:wipe 手工枚举清表清单两次漏表(2026-09-30 s_sections、2026-10-10 s_lme_res),
|
|
||||||
每次漏表 = 「重新解析」不断叠加脏数据(台班组成曾叠到 13 份)。
|
|
||||||
改造后 wipe 按 sqlite_master 动态发现 s_ 表,本测试钉死两条防线:
|
|
||||||
① 未来新建任何带 session_id 的 s_ 表(即使谁都不记得它),wipe 必然清它;
|
|
||||||
② WIPE_KEEP 里的表(s_remarks/s_settings)任何情况下不被清。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sqlite3
|
|
||||||
import sys, os
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "core"))
|
|
||||||
import session_job # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _mk_db():
|
|
||||||
con = sqlite3.connect(":memory:")
|
|
||||||
c = con.cursor()
|
|
||||||
# 业务表形状(简化自 schema,只保留 wipe 相关列)
|
|
||||||
c.execute("CREATE TABLE s_bills (id INTEGER PRIMARY KEY, session_id INT)")
|
|
||||||
c.execute("CREATE TABLE s_norms (id INTEGER PRIMARY KEY, bill_id INT)") # 无 session_id
|
|
||||||
c.execute("CREATE TABLE s_norm_res (id INTEGER PRIMARY KEY, norm_id INT)") # 无 session_id
|
|
||||||
# ⭐ 模拟「未来新表」:带 session_id 的普通数据表,谁都不用记得登记
|
|
||||||
c.execute("CREATE TABLE s_future_thing (id INTEGER PRIMARY KEY, session_id INT)")
|
|
||||||
# 保留清单里的表
|
|
||||||
c.execute("CREATE TABLE s_remarks (id INTEGER PRIMARY KEY, session_id INT)")
|
|
||||||
c.execute("CREATE TABLE s_settings (id INTEGER PRIMARY KEY, session_id INT)")
|
|
||||||
# sessions 表(s_ 前缀误匹配检查:'sessions' 不应以通配方式被清/被当数据表)
|
|
||||||
c.execute("CREATE TABLE sessions (id INTEGER PRIMARY KEY)")
|
|
||||||
# 数据
|
|
||||||
c.execute("INSERT INTO sessions VALUES (58)")
|
|
||||||
c.execute("INSERT INTO s_bills (session_id) VALUES (58)")
|
|
||||||
c.execute("INSERT INTO s_norms (bill_id) VALUES (1)")
|
|
||||||
c.execute("INSERT INTO s_norms (bill_id) VALUES (NULL)") # 孤儿定额
|
|
||||||
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (1)")
|
|
||||||
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (NULL)") # 孤儿消耗量
|
|
||||||
c.execute("INSERT INTO s_future_thing (session_id) VALUES (58)")
|
|
||||||
c.execute("INSERT INTO s_remarks (session_id) VALUES (58)")
|
|
||||||
c.execute("INSERT INTO s_settings (session_id) VALUES (58)")
|
|
||||||
con.commit()
|
|
||||||
return con
|
|
||||||
|
|
||||||
|
|
||||||
def test_wipe_clears_future_tables():
|
|
||||||
"""⭐ 核心防线:未来加的新表(带 session_id)即使没人同步 wipe 也必被清。"""
|
|
||||||
con = _mk_db()
|
|
||||||
session_job.wipe(con, 58)
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_future_thing").fetchone()[0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_wipe_clears_known_tables():
|
|
||||||
con = _mk_db()
|
|
||||||
session_job.wipe(con, 58)
|
|
||||||
for t in ("s_bills",):
|
|
||||||
assert con.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] == 0, t
|
|
||||||
# 定额按 bill_id 绕层清 + 孤儿全清
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0] == 0
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_norm_res").fetchone()[0] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_wipe_keeps_remarks_and_settings():
|
|
||||||
"""保留清单:备注与设置跨重新解析存活。"""
|
|
||||||
con = _mk_db()
|
|
||||||
session_job.wipe(con, 58)
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_remarks").fetchone()[0] == 1
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_settings").fetchone()[0] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_wipe_scoped_to_session_and_keeps_sessions_row():
|
|
||||||
con = _mk_db()
|
|
||||||
c = con.cursor()
|
|
||||||
c.execute("INSERT INTO s_bills (session_id) VALUES (99)") # 别的会话
|
|
||||||
c.execute("INSERT INTO s_remarks (session_id) VALUES (99)")
|
|
||||||
con.commit()
|
|
||||||
session_job.wipe(con, 58)
|
|
||||||
assert c.execute("SELECT COUNT(*) FROM s_bills WHERE session_id=99").fetchone()[0] == 1
|
|
||||||
assert c.execute("SELECT COUNT(*) FROM sessions WHERE id=58").fetchone()[0] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_wipe_keep_list_has_documented_members():
|
|
||||||
"""保留清单必须精确等于这两张表 —— 多了会漏清数据,少了会丢用户数据。"""
|
|
||||||
assert session_job.WIPE_KEEP == {"s_remarks", "s_settings"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_drop_orphan_rows_cleans_norm_orphans(tmp_path, monkeypatch):
|
|
||||||
"""两段式删除兜底:会话行已删、后台没来得及清子表 → 启动自愈按父表引用清干净。"""
|
|
||||||
monkeypatch.setattr(session_job, "DB", str(tmp_path / "s.db"))
|
|
||||||
con = session_job.connect()
|
|
||||||
con.execute("INSERT INTO sessions(id,name,src_name) VALUES(1,'a','a')")
|
|
||||||
con.execute("INSERT INTO s_bills(id,session_id) VALUES(1,1)")
|
|
||||||
con.execute("INSERT INTO s_bills(id,session_id) VALUES(2,2)") # 孤儿清单(会话2已删)
|
|
||||||
con.execute("INSERT INTO s_norms(id,bill_id) VALUES(1,1)")
|
|
||||||
con.execute("INSERT INTO s_norms(id,bill_id) VALUES(2,2)") # 孤儿定额
|
|
||||||
con.execute("INSERT INTO s_norm_res(id,norm_id) VALUES(1,1)")
|
|
||||||
con.execute("INSERT INTO s_norm_res(id,norm_id) VALUES(2,2)") # 孤儿消耗量
|
|
||||||
con.commit(); con.close()
|
|
||||||
n = session_job.drop_orphan_rows()
|
|
||||||
con = session_job.connect()
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_bills").fetchone()[0] == 1
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0] == 1
|
|
||||||
assert con.execute("SELECT COUNT(*) FROM s_norm_res").fetchone()[0] == 1
|
|
||||||
con.close()
|
|
||||||
assert n >= 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_drop_orphan_remarks_only_when_no_host(tmp_path, monkeypatch):
|
|
||||||
"""两段式删除兜底:备注源文件无会话/批次引用才删;有宿主整组保留。"""
|
|
||||||
monkeypatch.setattr(session_job, "DB", str(tmp_path / "s.db"))
|
|
||||||
con = session_job.connect()
|
|
||||||
con.execute("INSERT INTO sessions(id,name,src_name) VALUES(1,'a','a')")
|
|
||||||
con.execute("INSERT INTO s_remarks(id,src_key,rkey,remark) VALUES(1,'a','r1','keep')")
|
|
||||||
con.execute("INSERT INTO s_remarks(id,src_key,rkey,remark) VALUES(2,'b','r2','drop')")
|
|
||||||
con.commit(); con.close()
|
|
||||||
n = session_job.drop_orphan_remarks(set())
|
|
||||||
assert n == 1
|
|
||||||
con = session_job.connect()
|
|
||||||
rows = con.execute("SELECT src_key FROM s_remarks ORDER BY id").fetchall()
|
|
||||||
con.close()
|
|
||||||
assert [r[0] for r in rows] == ["a"]
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""决策 261 补三(2026-11-03 主人定):.yhy 导入(id 整体平移法)回归——
|
|
||||||
导出→导入→逐表对拍:行数一致、数据列内容一致(id/引用列按 offset 平移)、id 不撞库、同名拒绝。"""
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
from api_harness import post, server # noqa: F401 (夹具)
|
|
||||||
from test_manual_export import _create_manual
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
|
||||||
import import_yhy # noqa: E402
|
|
||||||
|
|
||||||
_TABS = ["s_sections", "s_unit_works", "s_divides", "s_bills", "s_lme_lib",
|
|
||||||
"s_lme_proj", "s_lme_res", "s_lme_uw", "s_lmes", "s_proj_summary",
|
|
||||||
"s_sundry", "s_uw_summary"]
|
|
||||||
_REF_COLS = {t: (set(refs) - {"session_id"}) for t, refs in import_yhy._TABLES}
|
|
||||||
|
|
||||||
|
|
||||||
def test_yhy_roundtrip(server):
|
|
||||||
sid1 = _create_manual(server)
|
|
||||||
c = server["client"]
|
|
||||||
# ① 导出 .yhy
|
|
||||||
r = c.get("/api/session/export", params={"session_id": sid1, "fmt": "yhy"})
|
|
||||||
assert r.status_code == 200
|
|
||||||
ybytes = r.content
|
|
||||||
assert zipfile.ZipFile(io.BytesIO(ybytes)).read("manifest.json")
|
|
||||||
# ② 写入待导入目录并导入(换名)
|
|
||||||
ypath = server["src_dir"] / "roundtrip_t.yhy"
|
|
||||||
ypath.write_bytes(ybytes)
|
|
||||||
j = post(server, "/api/session/yhy/import", {"path": str(ypath), "name": "回导测试工程"})
|
|
||||||
assert j.get("ok") is True, j
|
|
||||||
sid2 = j["session_id"]
|
|
||||||
assert sid2 != sid1 and j["name"] == "回导测试工程"
|
|
||||||
# ③ 同名拒绝(决策 242)
|
|
||||||
r2 = c.post("/api/session/yhy/import", json={"path": str(ypath), "name": "回导测试工程"})
|
|
||||||
j2 = r2.json()
|
|
||||||
assert (not j2.get("ok")) and ("同名" in j2.get("msg", "")), j2
|
|
||||||
# ④ 逐表对拍:导出件行 vs 库内新会话行
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(ybytes))
|
|
||||||
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
try:
|
|
||||||
for t in _TABS:
|
|
||||||
src = json.loads(z.read("rows/%s.json" % t))
|
|
||||||
if not src:
|
|
||||||
continue
|
|
||||||
off = None
|
|
||||||
newrows = [dict(x) for x in con.execute(
|
|
||||||
"SELECT * FROM %s WHERE session_id=?" % t, (sid2,))]
|
|
||||||
assert len(newrows) == len(src), "%s 行数不一致 %d != %d" % (t, len(newrows), len(src))
|
|
||||||
# offset=新 id −旧 id,须全表恒定且不与旧会话撞
|
|
||||||
old_ids = sorted(x["id"] for x in src)
|
|
||||||
new_ids = sorted(x["id"] for x in newrows)
|
|
||||||
off = new_ids[0] - old_ids[0]
|
|
||||||
assert off > 0 or old_ids[0] == 1, t
|
|
||||||
for x, y in zip(sorted(src, key=lambda r: r["id"]), sorted(newrows, key=lambda r: r["id"])):
|
|
||||||
assert y["id"] == x["id"] + off, "%s id 平移不恒定" % t
|
|
||||||
# 数据列(非 id/session_id/引用列)逐列一致;引用列平移正确性由下面⑤子表抽验覆盖
|
|
||||||
for col, v in x.items():
|
|
||||||
if col in ("id", "session_id") or col in _REF_COLS.get(t, ()):
|
|
||||||
continue
|
|
||||||
assert y.get(col) == v, "%s.%s 不一致:%r != %r" % (t, col, y.get(col), v)
|
|
||||||
# ⑤ 子表引用链抽验:源有定额时,s_norms.bill_id 必须落在 sid2 的清单 id 集内
|
|
||||||
src_norms = json.loads(z.read("rows/s_norms.json"))
|
|
||||||
bids = {x["id"] for x in con.execute("SELECT id FROM s_bills WHERE session_id=?", (sid2,))}
|
|
||||||
if src_norms:
|
|
||||||
nids = [x[0] for x in con.execute(
|
|
||||||
"SELECT n.id FROM s_norms n WHERE n.bill_id IN (SELECT id FROM s_bills WHERE session_id=?)",
|
|
||||||
(sid2,))]
|
|
||||||
assert len(nids) == len(src_norms), "定额没平移全 %d != %d" % (len(nids), len(src_norms))
|
|
||||||
assert bids, "清单没平移过来"
|
|
||||||
finally:
|
|
||||||
con.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_yhy_import_bad_file(server):
|
|
||||||
"""非 yhy 包 / 坏 zip → 明确报错不落库。"""
|
|
||||||
p = server["src_dir"] / "bad.yhy"
|
|
||||||
p.write_bytes(b"not a zip")
|
|
||||||
r = c = server["client"].post("/api/session/yhy/import",
|
|
||||||
json={"path": str(p), "name": "坏包测试"})
|
|
||||||
j = r.json()
|
|
||||||
assert not j.get("ok"), j
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
{
|
|
||||||
"lease": {
|
|
||||||
"canonical": "version=lease-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only",
|
|
||||||
"canonical_sha256": "da433cd2ec57a9ebf1f6a47e30521682e205f397ce5988b05785511a3e428aac",
|
|
||||||
"payload": {
|
|
||||||
"entitlement_expires_at": "2027-10-09T03:00:00Z",
|
|
||||||
"instance_id": "11111111-2222-3333-4444-555555555555",
|
|
||||||
"key_id": "integration-test-only",
|
|
||||||
"lease_expires_at": "2026-10-23T03:00:00Z",
|
|
||||||
"server_time": "2026-10-09T03:00:00Z",
|
|
||||||
"state": "active",
|
|
||||||
"version": "lease-v2"
|
|
||||||
},
|
|
||||||
"signature": "MEUCIC7K5MBrMw2M+mTnI8V14qUbgsqafewS+iFxnW2t7g68AiEAkBpVMJWsZ8T8szdvZHbR24PSiZbXHIWrNedh/+X/g2I"
|
|
||||||
},
|
|
||||||
"license": {
|
|
||||||
"canonical": "version=license-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only",
|
|
||||||
"canonical_sha256": "81d4930737bf289e752f5f37f43f9a0dfa0c0692075b2dba3d4d643ec1602355",
|
|
||||||
"payload": {
|
|
||||||
"customer_id": 2,
|
|
||||||
"expires_at": "2027-10-09T03:00:00Z",
|
|
||||||
"instance_id": "11111111-2222-3333-4444-555555555555",
|
|
||||||
"key_id": "integration-test-only",
|
|
||||||
"license_id": 1,
|
|
||||||
"product_id": 3,
|
|
||||||
"starts_at": "2026-10-09T03:00:00Z",
|
|
||||||
"version": "license-v2"
|
|
||||||
},
|
|
||||||
"signature": "MEUCIQDGb8FCV0JWvdE6UrMoscU9ZaidDajGGecslbI8A5xNkgIgVmI7IHlQQi5qhaulYNM9u27INVmXgPrNwNYLQsJrTJw"
|
|
||||||
},
|
|
||||||
"pinned_keys": [
|
|
||||||
{
|
|
||||||
"key_id": "integration-test-only",
|
|
||||||
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhrrB+tsg5H7cPScLrwZh/2q6fPx7\nSfzrQwmlKlJV74r0j0r5qPINY59icRBa42fEQTDI6hd9faWGifSW8Fb+jw==\n-----END PUBLIC KEY-----\n",
|
|
||||||
"revoked": false
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests"
|
|
||||||
}
|
|
||||||
@@ -298,62 +298,6 @@ tr.pedit{background:#fffbef}
|
|||||||
td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb6d4;border-radius:4px}
|
td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb6d4;border-radius:4px}
|
||||||
/* 明细表操作列:同一格里第二个链接(删除/取消)与前面的拉开 12px(2026-10-13 主人定) */
|
/* 明细表操作列:同一格里第二个链接(删除/取消)与前面的拉开 12px(2026-10-13 主人定) */
|
||||||
#dtbd td a + a{margin-left:12px}
|
#dtbd td a + a{margin-left:12px}
|
||||||
/* ===== 清单库三区域页(2026-11-04 主人定)=====
|
|
||||||
区域1=根目录→省→清单名称(严格三级)→ 区域2=选中清单名称的章节目录(层级不限)
|
|
||||||
→ 区域3=真正的清单条目(编码/名称/项目特征/单位/工程量,工程量默认 1.000)。
|
|
||||||
容器版式同 #dpage 口径(吃满剩余高度);区域1/2 背景同价格目录栏。 */
|
|
||||||
#klpage{display:none;flex-direction:column;background:#fff;border:1px solid var(--line);border-top:none;min-height:420px}
|
|
||||||
.klcols{display:flex;flex:1;min-height:0}
|
|
||||||
.kcol{display:flex;flex-direction:column;min-width:0;overflow:hidden}
|
|
||||||
#kc1{width:250px;flex:none;border-right:1px solid var(--line);background:#fcfdfe}
|
|
||||||
#kc2{width:320px;flex:none;border-right:1px solid var(--line);background:#fcfdfe}
|
|
||||||
#kc3{flex:1}
|
|
||||||
.kbody{flex:1;overflow:auto;padding:6px 10px}
|
|
||||||
.khint{color:#94a3b8;font-size:12px;padding:10px 4px;line-height:1.7}
|
|
||||||
/* 探索器式树:+/- 把手 + 连线(2026-11-04 主人定形式;只挂本页两棵树,原数据/组树样式不动)
|
|
||||||
连线:li::before=贯穿竖线(末位只到把手一半),li::after=把手到节点的横线 */
|
|
||||||
.ktree ul{list-style:none;margin:0;padding:0}
|
|
||||||
.ktree li{position:relative;padding-left:24px}
|
|
||||||
.ktree li::before{content:'';position:absolute;left:10px;top:0;bottom:0;border-left:1px solid #cdd6e2}
|
|
||||||
.ktree li:last-child::before{height:15px;bottom:auto}
|
|
||||||
.ktree li::after{content:'';position:absolute;left:10px;top:15px;width:10px;border-top:1px solid #cdd6e2}
|
|
||||||
.ktree > li.kt0{padding-left:0}
|
|
||||||
.ktree > li.kt0::before,.ktree > li.kt0::after{display:none}
|
|
||||||
.ktg{flex:none;width:14px;height:14px;line-height:12px;text-align:center;border:1px solid #9db3cf;
|
|
||||||
background:#fff;color:#34506f;font-size:10px;font-family:Consolas,monospace;border-radius:2px;
|
|
||||||
cursor:pointer;user-select:none}
|
|
||||||
.ktg:hover{background:var(--c2);color:#fff;border-color:var(--c2)}
|
|
||||||
.ktg.em{visibility:hidden}
|
|
||||||
.ktg.em:hover{background:#fff;color:#34506f;border-color:#9db3cf}
|
|
||||||
.kico{flex:none;font-size:11px;line-height:1}
|
|
||||||
.knode{display:flex;align-items:center;gap:4px;padding:2px 6px 2px 2px;cursor:pointer;border-radius:4px;
|
|
||||||
white-space:nowrap;color:#374151;font-size:12.5px}
|
|
||||||
.knode:hover{background:#eef3fa}
|
|
||||||
.knode.on{background:#2563eb;color:#fff}
|
|
||||||
.knode .knm{overflow:hidden;text-overflow:ellipsis}
|
|
||||||
.knode .kcnt{color:#9aa4b2;font-size:11px;flex:none}
|
|
||||||
.knode.on .kcnt{color:#dbe7ff}
|
|
||||||
.knode input.kren{width:150px;padding:1px 6px;font-size:12px;border-radius:4px;border:1px solid #9fb6d4}
|
|
||||||
.kcfm{display:inline-flex;gap:3px;flex:none}
|
|
||||||
.kcfm span{min-width:17px;height:17px;padding:0 2px;border-radius:4px;background:#fff;border:1px solid #c9d4e2;
|
|
||||||
color:#34506f;font-size:11px;line-height:15px;text-align:center;cursor:pointer}
|
|
||||||
.kcfm span.kpk:hover{background:#1a7f37;border-color:#1a7f37}
|
|
||||||
.kcfm span.kpd:hover{background:#c0392b;border-color:#c0392b}
|
|
||||||
/* 区域3 条目表(五列格式照工作台:编码/名称/项目特征 左,单位 居中,工程量 右 3 位小数) */
|
|
||||||
.ktable{border-collapse:collapse;width:100%;font-size:12.5px}
|
|
||||||
.ktable th{position:sticky;top:0;background:#f7f9fc;color:#374151;font-weight:600;padding:6px 8px;
|
|
||||||
text-align:left;border-bottom:1px solid var(--line);border-right:1px solid #eef1f5;white-space:nowrap}
|
|
||||||
.ktable td{padding:4px 8px;border-bottom:1px solid #f0f3f7;vertical-align:top}
|
|
||||||
.ktable td.kc{text-align:center}
|
|
||||||
.ktable td.kr{text-align:right}
|
|
||||||
.ktable td.kfeat{max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#5b6472}
|
|
||||||
.ktable td input,.ktable td textarea{width:100%;box-sizing:border-box;padding:3px 7px;font-size:12.5px;
|
|
||||||
border:1px solid #9fb6d4;border-radius:4px;font-family:inherit}
|
|
||||||
.ktable td textarea{resize:vertical}
|
|
||||||
.ktable tr.pedit{background:#fffbef}
|
|
||||||
.kempty{color:#94a3b8;font-size:12px;text-align:center;padding:18px 0}
|
|
||||||
.kwhere{font-size:12px;color:#34506f;background:#eef3fa;border:1px solid #d8e0ec;border-radius:4px;
|
|
||||||
padding:2px 8px;max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
||||||
.newflag{display:inline-block;margin-left:6px;padding:0 5px;border-radius:3px;background:#fff7e6;
|
.newflag{display:inline-block;margin-left:6px;padding:0 5px;border-radius:3px;background:#fff7e6;
|
||||||
border:1px solid #f0d9a8;color:#8a6d1a;font-size:11px}
|
border:1px solid #f0d9a8;color:#8a6d1a;font-size:11px}
|
||||||
</style>
|
</style>
|
||||||
@@ -367,8 +311,6 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
|
|||||||
|
|
||||||
<div class="tabs">
|
<div class="tabs">
|
||||||
<div class="tab on" data-kind="project">入库项目</div>
|
<div class="tab on" data-kind="project">入库项目</div>
|
||||||
<!-- 清单库固定标签(2026-11-04 主人定):固定四标签(原三标签 + 清单);不走批次列表,独立三区域页 -->
|
|
||||||
<div class="tab" data-kind="qlist">清单</div>
|
|
||||||
<div class="tab" data-kind="market">市场价</div>
|
<div class="tab" data-kind="market">市场价</div>
|
||||||
<div class="tab" data-kind="info">信息价</div>
|
<div class="tab" data-kind="info">信息价</div>
|
||||||
<!-- 动态明细标签挂点(2026-10-21 决策 150 主人定):点「明细」在此追加浏览器式标签,
|
<!-- 动态明细标签挂点(2026-10-21 决策 150 主人定):点「明细」在此追加浏览器式标签,
|
||||||
@@ -380,8 +322,7 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
|
|||||||
授权管理入口),本按钮改回原名「数据源」——功能一点没动。
|
授权管理入口),本按钮改回原名「数据源」——功能一点没动。
|
||||||
margin-bottom:5px(2026-11-02 主人定)—— 距蓝色线条的间距按工作台口径统一 5px,
|
margin-bottom:5px(2026-11-02 主人定)—— 距蓝色线条的间距按工作台口径统一 5px,
|
||||||
也免得看起来像第四个标签。 -->
|
也免得看起来像第四个标签。 -->
|
||||||
<button class="btn" id="btnFrames" style="margin-left:auto;margin-bottom:5px;height:28px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;line-height:1" onclick="openFrames()"
|
<span style="margin-left:auto"></span>
|
||||||
title="设置:导出文件数据结构库(导出)与工料机导出配置">设置</button>
|
|
||||||
<button class="btn" id="btnDict" style="margin-bottom:5px;height:28px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;line-height:1" onclick="openDict()"
|
<button class="btn" id="btnDict" style="margin-bottom:5px;height:28px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;line-height:1" onclick="openDict()"
|
||||||
title="字典设置:地区 / 询价单位 / 发布单位 / 建设单位 下拉选项 + 上传大小上限">⚙ 字典</button>
|
title="字典设置:地区 / 询价单位 / 发布单位 / 建设单位 下拉选项 + 上传大小上限">⚙ 字典</button>
|
||||||
<!-- 工作台入口(2026-10-06 主人定):从标题行右上角搬到标签栏,排在「设置」右边。
|
<!-- 工作台入口(2026-10-06 主人定):从标题行右上角搬到标签栏,排在「设置」右边。
|
||||||
@@ -546,49 +487,6 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
|
|||||||
<input type="file" id="qfile" style="display:none">
|
<input type="file" id="qfile" style="display:none">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 清单库三区域页(2026-11-04 主人定):固定四标签「清单」的内容页。
|
|
||||||
区域1(最左)=根目录→省→清单名称,严格三级(市不要);区域2(中间)=选中第3级「清单名称」后
|
|
||||||
的章节目录,层级不限;区域3(右)=真正的清单条目(编码/名称/项目特征/单位/工程量,工程量默认 1.000)。
|
|
||||||
两棵目录树都走探索器式 +/- 把手 + 连线(.ktree);工具排同价格目录 .rtbar(作用于选中项)。
|
|
||||||
库内容由主人在界面里建,后端只种根目录。 -->
|
|
||||||
<div id="klpage">
|
|
||||||
<div class="klcols">
|
|
||||||
<div class="kcol" id="kc1">
|
|
||||||
<div class="rtbar" id="krt1">
|
|
||||||
<span id="kadd1" title="在选中目录下新增(根下=省、省下=清单名称)" onclick="qlAdd1()">+子目录</span>
|
|
||||||
<span id="kren1" title="改名" onclick="qlRen1()">✎</span>
|
|
||||||
<span id="kup1" title="上移" onclick="qlSeq1(-1)">↑</span>
|
|
||||||
<span id="kdn1" title="下移" onclick="qlSeq1(1)">↓</span>
|
|
||||||
<span id="kdel1" title="删除" onclick="qlDel1()">✕</span>
|
|
||||||
</div>
|
|
||||||
<div class="kbody ktree" id="ktree1"></div>
|
|
||||||
</div>
|
|
||||||
<div class="kcol" id="kc2">
|
|
||||||
<div class="rtbar" id="krt2">
|
|
||||||
<span id="kadd2" title="新增章节目录(挂选中项下;没选中=挂清单名称下)" onclick="qlAdd2()">+子目录</span>
|
|
||||||
<span id="kren2" title="改名" onclick="qlRen2()">✎</span>
|
|
||||||
<span id="kup2" title="上移" onclick="qlSeq2(-1)">↑</span>
|
|
||||||
<span id="kdn2" title="下移" onclick="qlSeq2(1)">↓</span>
|
|
||||||
<span id="kdel2" title="删除" onclick="qlDel2()">✕</span>
|
|
||||||
</div>
|
|
||||||
<div class="kbody ktree" id="ktree2"></div>
|
|
||||||
</div>
|
|
||||||
<div class="kcol" id="kc3">
|
|
||||||
<div class="rtbar" id="krt3">
|
|
||||||
<span id="kaddi" title="新增清单条目(工程量默认 1.000)" onclick="qlItemAdd()">+条目</span>
|
|
||||||
<span class="kwhere" id="kwhere"></span>
|
|
||||||
</div>
|
|
||||||
<div class="kbody" id="kbody3">
|
|
||||||
<table class="ktable" id="kitems">
|
|
||||||
<thead><tr><th style="width:140px">编码</th><th>名称</th><th style="width:290px">项目特征</th>
|
|
||||||
<th style="width:90px">单位</th><th style="width:110px">工程量</th><th style="width:88px">操作</th></tr></thead>
|
|
||||||
<tbody id="kitemsb"></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mask" id="imask">
|
<div class="mask" id="imask">
|
||||||
<!-- 决策 245(2026-11-01 主人定):后台弹框与工作台「打开项目」弹框统一,以工作台为准——
|
<!-- 决策 245(2026-11-01 主人定):后台弹框与工作台「打开项目」弹框统一,以工作台为准——
|
||||||
字段/顺序/提示/按钮一致,唯一区别=写入库(这里写 history.db 批次,工作台写 session.db 会话);
|
字段/顺序/提示/按钮一致,唯一区别=写入库(这里写 history.db 批次,工作台写 session.db 会话);
|
||||||
@@ -728,6 +626,7 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
|
|||||||
<div class="dtab" id="dtab-publisher" onclick="dictTab('publisher')">发布单位</div>
|
<div class="dtab" id="dtab-publisher" onclick="dictTab('publisher')">发布单位</div>
|
||||||
<div class="dtab" id="dtab-builder" onclick="dictTab('builder')">建设单位</div>
|
<div class="dtab" id="dtab-builder" onclick="dictTab('builder')">建设单位</div>
|
||||||
<div class="dtab" id="dtab-upload" onclick="dictTab('upload')">上传设置</div>
|
<div class="dtab" id="dtab-upload" onclick="dictTab('upload')">上传设置</div>
|
||||||
|
<div class="dtab" id="dtab-sfx" onclick="dictTab('sfx')">后缀搜索授权</div>
|
||||||
<button class="btn pri" id="btnDictAdd" style="margin-left:auto" onclick="dictBeginAdd()"
|
<button class="btn pri" id="btnDictAdd" style="margin-left:auto" onclick="dictBeginAdd()"
|
||||||
title="在表格第一行插入一条新记录">+ 新增</button>
|
title="在表格第一行插入一条新记录">+ 新增</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -765,35 +664,31 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
|
|||||||
<div class="tip" id="upTip" style="padding:0;margin-top:6px"></div>
|
<div class="tip" id="upTip" style="padding:0;margin-top:6px"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 后缀搜索授权(决策 279,2026-11-07 主人定):清单检索后缀授权矩阵(增量授权)。
|
||||||
|
同后缀检索是内置默认(cos 搜 cos 不用配);这里只配「增量」——例:工作台后缀 cos4、
|
||||||
|
搜索后缀填 cos = cos4 会话可多搜 cos 批次;反向不配就不放行(方向不对称正是要的细度)。
|
||||||
|
字段=序号/工作台后缀/搜索后缀(多值,空格或逗号分隔)。只对清单检索生效,工料机检索不受限。 -->
|
||||||
|
<div id="dpane-sfx" style="display:none">
|
||||||
|
<div class="tw" style="max-height:40vh;margin-top:10px">
|
||||||
|
<table><colgroup><col style="width:56px"><col style="width:200px"><col><col style="width:56px"></colgroup>
|
||||||
|
<thead><tr><th class="c">#</th><th>工作台后缀</th><th>搜索后缀(多个用空格或逗号隔开)</th><th class="c">操作</th></tr></thead>
|
||||||
|
<tbody id="sfxBody"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;gap:8px;margin-top:8px;align-items:center">
|
||||||
|
<button class="btn" onclick="sfxAddRow()">+ 加一行</button>
|
||||||
|
<button class="btn pri" onclick="sfxSave()">保存</button>
|
||||||
|
<span class="tip" id="sfxTip" style="padding:0"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="tip" id="dmsg" style="padding:0;min-height:18px"></div>
|
<div class="tip" id="dmsg" style="padding:0;min-height:18px"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<input type="file" id="afile" style="display:none">
|
<input type="file" id="afile" style="display:none">
|
||||||
|
|
||||||
<!-- ================= 导出设置(导出文件数据结构库)=================
|
<!-- 决策 279:导出设置(骨架库)弹框拆除 -->
|
||||||
2026-11-02 主人定:弹框开即列表(序号|后缀|上传日期|导出文件数据结构,同后缀聚簇、
|
|
||||||
组间明显横线、组首行标件数);右上「添加」=选文件即入库(.cos/.cos4 原件或骨架包),
|
|
||||||
同名结构入库前确认升级替换;每文件带 下载 / 删(删=二次确认,该后缀最后一件加警示不阻止)。
|
|
||||||
阶段二(上市版)切「骨架包升级分发」时本弹框撤添加钮、客户端静默接收(决策台账 257)。 -->
|
|
||||||
<div class="mask" id="fmask">
|
|
||||||
<div class="dlg" style="width:min(760px,94vw)">
|
|
||||||
<div class="dh"><b>设置</b><span class="close" onclick="closeFrames()">×</span></div>
|
|
||||||
<div style="padding:14px 16px;display:flex;flex-direction:column;gap:10px">
|
|
||||||
<div style="display:flex;justify-content:flex-end">
|
|
||||||
<button class="btn pri" onclick="framesAdd()" title="选择 .cos / .cos4 原件或骨架包(zip 内含 cos 族件),入库后自动按后缀归类">添加</button>
|
|
||||||
<input type="file" id="ffile" style="display:none" onchange="framesSeed(this)">
|
|
||||||
</div>
|
|
||||||
<div class="tw" style="max-height:52vh">
|
|
||||||
<table><colgroup><col style="width:56px"><col style="width:110px"><col style="width:110px"><col></colgroup>
|
|
||||||
<thead><tr><th class="c">#</th><th>后缀</th><th>上传日期</th><th>导出文件数据结构</th></tr></thead>
|
|
||||||
<tbody id="frameBody"></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
<div class="tip" id="fmsg" style="padding:0;min-height:18px"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ===== 询价附件(2026-10-21 决策 152 主人定:左=附件目录树(根目录「附件目录」,上传/删除挂根行右侧);
|
<!-- ===== 询价附件(2026-10-21 决策 152 主人定:左=附件目录树(根目录「附件目录」,上传/删除挂根行右侧);
|
||||||
右=项目工料机/类似清单 双页签 + 行最右搜索框;两类都可绑附件,工作台对比框可下载) ===== -->
|
右=项目工料机/类似清单 双页签 + 行最右搜索框;两类都可绑附件,工作台对比框可下载) ===== -->
|
||||||
@@ -903,6 +798,7 @@ async function loadSummary(){
|
|||||||
排序键 → 后端 /api/admin/batches 的 sort 白名单(整库排序,点抬头升/降切换)。 */
|
排序键 → 后端 /api/admin/batches 的 sort 白名单(整库排序,点抬头升/降切换)。 */
|
||||||
/* 决策 213 补记七:清单/工料机 两个统计列取消(主人定) */
|
/* 决策 213 补记七:清单/工料机 两个统计列取消(主人定) */
|
||||||
const COL_PROJ=[['序号',52,'c','F',null],['纳入',56,'c','F','enabled'],['名称',0,'l',null,'name'],
|
const COL_PROJ=[['序号',52,'c','F',null],['纳入',56,'c','F','enabled'],['名称',0,'l',null,'name'],
|
||||||
|
['后缀',64,'c','F',null], /* 决策 278(2026-11-07 主人定):名称右侧「后缀」列(留档名扩展名,判不出=空,不排序) */
|
||||||
['单价类型',100,'c','F','kind'],['建设单位',0,'l',null,'bu'],['地区',150,'c','F','area'],
|
['单价类型',100,'c','F','kind'],['建设单位',0,'l',null,'bu'],['地区',150,'c','F','area'],
|
||||||
['期次',0,'l',null,'period'],['总价(元)',0,'r',null,'total'],['附件',84,'c','F',null],['导入时间',140,'c','F','time'],
|
['期次',0,'l',null,'period'],['总价(元)',0,'r',null,'total'],['附件',84,'c','F',null],['导入时间',140,'c','F','time'],
|
||||||
['操作',120,'c','F',null]];
|
['操作',120,'c','F',null]];
|
||||||
@@ -1002,6 +898,7 @@ function rowProj(r){ // 工程(序号倒序:第一行是总数,往下递
|
|||||||
<td class="c">${r.seq}</td>
|
<td class="c">${r.seq}</td>
|
||||||
<td class="c"><span class="sw ${r.enabled?'on':''}" onclick="tog(${r.id},${r.enabled})"><i></i></span></td>
|
<td class="c"><span class="sw ${r.enabled?'on':''}" onclick="tog(${r.id},${r.enabled})"><i></i></span></td>
|
||||||
<td class="name" title="${esc(r.name)}">${esc(r.name)}</td>
|
<td class="name" title="${esc(r.name)}">${esc(r.name)}</td>
|
||||||
|
<td class="c">${ell(r.sfx||'')}</td>
|
||||||
<td class="c">${ell(r.file_kind_name||'—')}</td>
|
<td class="c">${ell(r.file_kind_name||'—')}</td>
|
||||||
<td class="name" title="${esc(r.bulid_unit)}">${esc(r.bulid_unit||'—')}</td>
|
<td class="name" title="${esc(r.bulid_unit)}">${esc(r.bulid_unit||'—')}</td>
|
||||||
<td class="c">${ell([r.province,r.city,r.district].filter(Boolean).join('-')||'—')}</td>
|
<td class="c">${ell([r.province,r.city,r.district].filter(Boolean).join('-')||'—')}</td>
|
||||||
@@ -1538,14 +1435,11 @@ function renderXTabs(){
|
|||||||
}
|
}
|
||||||
function showPage(which){
|
function showPage(which){
|
||||||
// 决策 152:页面三态切换 —— 列表 / 明细(决策 150)/ 附件动态标签页
|
// 决策 152:页面三态切换 —— 列表 / 明细(决策 150)/ 附件动态标签页
|
||||||
const lp=$('lpanel'), dp=$('dpage'), qp=$('qpage'), kp=$('klpage');
|
const lp=$('lpanel'), dp=$('dpage'), qp=$('qpage');
|
||||||
lp.style.display = which==='list' ? '' : 'none';
|
lp.style.display = which==='list' ? '' : 'none';
|
||||||
dp.style.display = which==='detail' ? 'flex' : 'none';
|
dp.style.display = which==='detail' ? 'flex' : 'none';
|
||||||
qp.style.display = which==='inq' ? 'flex' : 'none';
|
qp.style.display = which==='inq' ? 'flex' : 'none';
|
||||||
kp.style.display = which==='qlist' ? 'flex' : 'none';
|
if(which!=='list'){
|
||||||
if(which==='qlist'){
|
|
||||||
kp.style.height=Math.max(420, window.innerHeight-kp.getBoundingClientRect().top-24)+'px';
|
|
||||||
}else if(which!=='list'){
|
|
||||||
const el = which==='detail' ? dp : qp;
|
const el = which==='detail' ? dp : qp;
|
||||||
el.style.height=Math.max(420, window.innerHeight-el.getBoundingClientRect().top-24)+'px';
|
el.style.height=Math.max(420, window.innerHeight-el.getBoundingClientRect().top-24)+'px';
|
||||||
}
|
}
|
||||||
@@ -2082,18 +1976,10 @@ function resetF(){fq.value='';fp.value='';fc.value='';fd.value='';setPeriod($('f
|
|||||||
load(1)}
|
load(1)}
|
||||||
|
|
||||||
document.querySelectorAll('.tab[data-kind]').forEach(t=>t.onclick=()=>{
|
document.querySelectorAll('.tab[data-kind]').forEach(t=>t.onclick=()=>{
|
||||||
const fromQ=(KIND==='qlist');
|
|
||||||
if(fromQ && t.dataset.kind!=='qlist') qlSnap(); // 离开清单页:抓拍选中/展开/滚动(2026-11-05 记忆口径)
|
|
||||||
document.querySelectorAll('.tab[data-kind]').forEach(x=>x.classList.remove('on'));
|
document.querySelectorAll('.tab[data-kind]').forEach(x=>x.classList.remove('on'));
|
||||||
t.classList.add('on'); KIND=t.dataset.kind; SORT={key:'',dir:'DESC'}; syncBtns();
|
t.classList.add('on'); KIND=t.dataset.kind; SORT={key:'',dir:'DESC'}; syncBtns();
|
||||||
XLAST=KIND;
|
XLAST=KIND;
|
||||||
// 清单库固定标签(2026-11-04 主人定):独立三区域页,不走批次列表/筛选
|
|
||||||
if(KIND==='qlist'){
|
|
||||||
if(XACT>=0){ XACT=-1; renderXTabs(); xsave(); }
|
|
||||||
showPage('qlist'); qlLoad(); return;
|
|
||||||
}
|
|
||||||
if(XACT>=0){ XACT=-1; renderXTabs(); showDetail(false); xsave(); } // 从明细标签切回列表区(动态标签保留)
|
if(XACT>=0){ XACT=-1; renderXTabs(); showDetail(false); xsave(); } // 从明细标签切回列表区(动态标签保留)
|
||||||
else if(fromQ) showPage('list'); // 从清单页切回列表区:showPage 藏掉 klpage(否则穿帮挂在列表下面,2026-11-05 实测修)
|
|
||||||
ldWrap('','正在加载列表…',()=>{ load(1); loadFilters(); }); // 列表取数期间挂进度条(快则不闪);loadFilters=过滤文案随页签刷新(2026-11-02 询价单位/发布单位)
|
ldWrap('','正在加载列表…',()=>{ load(1); loadFilters(); }); // 列表取数期间挂进度条(快则不闪);loadFilters=过滤文案随页签刷新(2026-11-02 询价单位/发布单位)
|
||||||
});
|
});
|
||||||
// 2026-10-13 主人定:切标签没出全数据前要有进度条 —— 走共享层 ldWrap(det() 进来的路径
|
// 2026-10-13 主人定:切标签没出全数据前要有进度条 —— 走共享层 ldWrap(det() 进来的路径
|
||||||
@@ -2618,141 +2504,18 @@ async function qDelFile(fid){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* ============ 导出设置(导出文件数据结构库)====================
|
/* 决策 279:骨架库 CSS 拆除 */
|
||||||
2026-11-02 主人定:四列列表(同后缀聚簇、组间明显横线、组首行标件数)、
|
|
||||||
右上「添加」选文件即入库(同名升级替换前确认)、每文件 下载/删
|
|
||||||
(删=二次确认,该后缀最后一件加警示不阻止)。口径详见弹框 DOM 注释。 */
|
|
||||||
let FRAMES = [];
|
|
||||||
|
|
||||||
async function openFrames(){
|
|
||||||
$('fmask').classList.add('on');
|
|
||||||
$('fmsg').textContent='';
|
|
||||||
await framesLoad();
|
|
||||||
}
|
|
||||||
function closeFrames(){ $('fmask').classList.remove('on'); }
|
|
||||||
fmask.onclick = e => { if(e.target===fmask) closeFrames() };
|
|
||||||
|
|
||||||
async function framesLoad(){
|
|
||||||
try{
|
|
||||||
const r = await (await fetch('/api/admin/frames')).json();
|
|
||||||
FRAMES = r.rows || [];
|
|
||||||
}catch(e){ FRAMES = []; $('fmsg').textContent='列表读取失败:'+e; }
|
|
||||||
framesRender();
|
|
||||||
}
|
|
||||||
|
|
||||||
function framesRender(){
|
|
||||||
const rows = FRAMES; // 后端已排:后缀聚簇(cos4 在前)、组内入库时间倒序
|
|
||||||
const cnt = {};
|
|
||||||
rows.forEach(r => cnt[r.suffix] = (cnt[r.suffix]||0)+1);
|
|
||||||
let html='', last=null, no=0;
|
|
||||||
const SEP = 'border-top:3px double #7d92ad'; // 组间明显横线(双线)
|
|
||||||
for(const r of rows){
|
|
||||||
no++;
|
|
||||||
const first = r.suffix!==last;
|
|
||||||
const esc = (r.original_name||'').replace(/'/g,'');
|
|
||||||
const dl = ` <a href="/api/admin/frames/file/${r.sig}" style="color:#26405e" title="下载骨架原件">下载</a>`
|
|
||||||
+ ` <a href="javascript:framesExportAnnotated('${r.sig}')" style="color:#26405e" title="按原格式导出完全空的骨架(含自增/固定标注)——直接另存为">导出</a>`
|
|
||||||
+ ` <a href="javascript:framesDel('${r.sig}')" style="color:#c0392b">删</a>`;
|
|
||||||
if(first){ // 组首行:后缀列 rowspan 合并本组全部行(2026-11-02 主人定)
|
|
||||||
const st = last!==null ? ` style="${SEP}"` : ''; // 组间横线:非首组才加
|
|
||||||
const stv = (last!==null ? ` style="${SEP};vertical-align:middle"` : ' style="vertical-align:middle"');
|
|
||||||
html += `<tr>`
|
|
||||||
+ `<td class="c"${st}>${no}</td>`
|
|
||||||
+ `<td rowspan="${cnt[r.suffix]}"${stv}>${r.suffix}(${cnt[r.suffix]}件)</td>`
|
|
||||||
+ `<td${st}>${(r.extracted_at||'').slice(0,10)}</td>`
|
|
||||||
+ `<td${st}>${r.original_name||''}${dl}</td>`
|
|
||||||
+ `</tr>`;
|
|
||||||
}else{ // 组内后续行:后缀格被上方 rowspan 覆盖,只写 序号/日期/结构
|
|
||||||
html += `<tr>`
|
|
||||||
+ `<td class="c">${no}</td>`
|
|
||||||
+ `<td>${(r.extracted_at||'').slice(0,10)}</td>`
|
|
||||||
+ `<td>${r.original_name||''}${dl}</td>`
|
|
||||||
+ `</tr>`;
|
|
||||||
}
|
|
||||||
last = r.suffix;
|
|
||||||
}
|
|
||||||
$('frameBody').innerHTML = html
|
|
||||||
|| '<tr><td colspan="4" class="c" style="color:#888">还没有导出文件数据结构,点右上「添加」导入</td></tr>';
|
|
||||||
}
|
|
||||||
|
|
||||||
function framesAdd(){ $('ffile').value=''; $('ffile').click(); }
|
|
||||||
|
|
||||||
/* 导出=空骨架(标注):按该骨架原后缀直接另存为(不新增按钮;2026-11-03 主人定) */
|
/* 导出=空骨架(标注):按该骨架原后缀直接另存为(不新增按钮;2026-11-03 主人定) */
|
||||||
function framesExportAnnotated(sig){
|
|
||||||
const r = (FRAMES||[]).find(x => x.sig === sig) || {};
|
|
||||||
framesSaveFile(sig, r.original_name || '骨架', '空骨架(标注)', r.suffix || 'cos4');
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 统一另存为(2026-11-03 主人定「导出一律另存为方式」):
|
/* 统一另存为(2026-11-03 主人定「导出一律另存为方式」):
|
||||||
showSaveFilePicker 弹系统保存对话框,用户选路径后写入。
|
showSaveFilePicker 弹系统保存对话框,用户选路径后写入。
|
||||||
kind='空骨架(标注)' → /api/admin/frames/blankpkg/{sig}(原格式空骨架+自增/固定标注,后缀跟骨架);
|
kind='空骨架(标注)' → /api/admin/frames/blankpkg/{sig}(原格式空骨架+自增/固定标注,后缀跟骨架);
|
||||||
kind='空精简骨架' → /api/admin/frames/blank/{sig}(单 XML);
|
kind='空精简骨架' → /api/admin/frames/blank/{sig}(单 XML);
|
||||||
其余(原件) → /api/admin/frames/file/{sig}。 */
|
其余(原件) → /api/admin/frames/file/{sig}。 */
|
||||||
async function framesSaveFile(sig, name, kind, suffix){
|
async
|
||||||
let url, fn;
|
|
||||||
if(kind==='空骨架(标注)'){
|
|
||||||
url = `/api/admin/frames/blankpkg/${sig}`;
|
|
||||||
fn = `${name}-空骨架(标注).${suffix||'cos4'}`;
|
|
||||||
}else if(kind==='空精简骨架'){
|
|
||||||
url = `/api/admin/frames/blank/${sig}`;
|
|
||||||
fn = `${kind}-${name}.xml`;
|
|
||||||
}else{
|
|
||||||
url = `/api/admin/frames/file/${sig}`;
|
|
||||||
fn = `${kind}-${name}.${suffix||'bin'}`;
|
|
||||||
}
|
|
||||||
try{
|
|
||||||
const resp = await fetch(url);
|
|
||||||
if(!resp.ok){ $('fmsg').textContent = `获取失败(HTTP ${resp.status})`; return; }
|
|
||||||
const blob = await resp.blob();
|
|
||||||
const fp = await showSaveFilePicker({ suggestedName: fn });
|
|
||||||
const w = await fp.createWritable();
|
|
||||||
await w.write(blob);
|
|
||||||
await w.close();
|
|
||||||
$('fmsg').textContent = `已另存为:${fp.name}`;
|
|
||||||
}catch(e){
|
|
||||||
if(e.name==='AbortError') return; // 用户取消,不报错
|
|
||||||
$('fmsg').textContent = '另存为失败:' + e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function framesSeed(inp){
|
/* 决策 279:骨架库 JS 残段拆除 */
|
||||||
const f = inp.files && inp.files[0];
|
|
||||||
if(!f) return;
|
|
||||||
const stem = f.name.replace(/\.[^.]*$/,'');
|
|
||||||
if(FRAMES.some(r => r.original_name===stem)
|
|
||||||
&& !(await uiConfirm(`已存在同名结构《${stem}》,将升级替换(旧内容被覆盖)`))){ inp.value=''; return; }
|
|
||||||
try{
|
|
||||||
const res = await fetch('/api/admin/frames/seed', {method:'POST',
|
|
||||||
headers:{'Content-Type':'application/octet-stream',
|
|
||||||
'X-File-Name':encodeURIComponent(f.name)},
|
|
||||||
body:f});
|
|
||||||
const r = await res.json();
|
|
||||||
if(!r.ok){ $('fmsg').textContent = r.msg || '入库失败'; return; }
|
|
||||||
$('fmsg').textContent = r.kind==='pack'
|
|
||||||
? `骨架包已安装 ${r.installed.length} 件` : `已入库《${r.name}》`;
|
|
||||||
await framesLoad();
|
|
||||||
}catch(e){ $('fmsg').textContent='入库请求失败:'+e; }
|
|
||||||
finally{ inp.value=''; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 导出空骨架的另存为已由 framesSaveFile 统一处理(2026-11-03 主人定「一律另存为方式」)。 */
|
|
||||||
|
|
||||||
async function framesDel(sig){
|
|
||||||
const r = FRAMES.find(x=>x.sig===sig);
|
|
||||||
if(!r) return;
|
|
||||||
const isLast = FRAMES.filter(x=>x.suffix===r.suffix).length===1;
|
|
||||||
const warn = isLast
|
|
||||||
? `\n\n⚠ 这是 .${r.suffix} 最后一件:删除后手工导出该格式将不可用。` : '';
|
|
||||||
if(!(await uiConfirm('删除后不可恢复,是否删除?',
|
|
||||||
`《${r.original_name}》${warn}\n删除后可用同名文件重新「添加」恢复。`))) return;
|
|
||||||
try{
|
|
||||||
const res = await fetch('/api/admin/frames/delete', {method:'POST',
|
|
||||||
headers:{'Content-Type':'application/json'}, body: JSON.stringify({sig})});
|
|
||||||
const j = await res.json();
|
|
||||||
if(!j.ok){ $('fmsg').textContent = j.msg || '删除失败'; return; }
|
|
||||||
await framesLoad();
|
|
||||||
}catch(e){ $('fmsg').textContent='删除请求失败:'+e; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ============ 数据源面板(地区 / 发布单位 / 建设单位)====================
|
/* ============ 数据源面板(地区 / 发布单位 / 建设单位)====================
|
||||||
这里的选项就是各页录入下拉的唯一来源。改完不需要重启,下次打开弹窗即生效。 */
|
这里的选项就是各页录入下拉的唯一来源。改完不需要重启,下次打开弹窗即生效。 */
|
||||||
@@ -2787,10 +2550,12 @@ function dictTab(cat){
|
|||||||
document.getElementById('dpane-org').style.display = (cat==='publisher'||cat==='inquirer'||cat==='builder')?'':'none';
|
document.getElementById('dpane-org').style.display = (cat==='publisher'||cat==='inquirer'||cat==='builder')?'':'none';
|
||||||
// 「上传设置」不是字典,切过去时不渲染字典表(dictRender 会读 /api/dict,白跑一次)
|
// 「上传设置」不是字典,切过去时不渲染字典表(dictRender 会读 /api/dict,白跑一次)
|
||||||
document.getElementById('dpane-upload').style.display = (cat==='upload')?'':'none';
|
document.getElementById('dpane-upload').style.display = (cat==='upload')?'':'none';
|
||||||
|
document.getElementById('dpane-sfx').style.display = (cat==='sfx')?'':'none'; // 决策 279:后缀搜索授权
|
||||||
const bAdd = document.getElementById('btnDictAdd');
|
const bAdd = document.getElementById('btnDictAdd');
|
||||||
if(bAdd) bAdd.style.display = (cat==='upload')?'none':''; // 上传设置没有「新增」概念
|
if(bAdd) bAdd.style.display = (cat==='upload'||cat==='sfx')?'none':''; // 上传设置/后缀授权没有「新增」概念
|
||||||
DICT_ADD = false; DICT_EDIT = null; // 切标签取消未完成的行
|
DICT_ADD = false; DICT_EDIT = null; // 切标签取消未完成的行
|
||||||
if(cat==='upload'){ upLoad(); return; }
|
if(cat==='upload'){ upLoad(); return; }
|
||||||
|
if(cat==='sfx'){ sfxLoad(); return; }
|
||||||
if(cat!=='region') document.getElementById('dorgHead').textContent = DORG_TITLE[cat];
|
if(cat!=='region') document.getElementById('dorgHead').textContent = DORG_TITLE[cat];
|
||||||
dictRender();
|
dictRender();
|
||||||
}
|
}
|
||||||
@@ -2848,6 +2613,63 @@ async function upSave(){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- 后缀搜索授权(决策 279,2026-11-07 主人定):清单检索后缀授权矩阵(增量授权)----
|
||||||
|
同后缀内置默认不用配(cos 搜 cos 恒可);这里只配增量:行=工作台后缀 → 搜索后缀(多值)。
|
||||||
|
保存=整表提交,服务端剥空行/归一/去重(同 sfx 最后一行为准)。工料机检索不受本表影响。 */
|
||||||
|
let SFXROWS = [];
|
||||||
|
function sfxTip(msg, ok){
|
||||||
|
const t = document.getElementById('sfxTip');
|
||||||
|
t.textContent = msg;
|
||||||
|
t.style.color = ok === undefined ? '' : (ok ? '#1a7f37' : '#c0392b');
|
||||||
|
}
|
||||||
|
async function sfxLoad(){
|
||||||
|
const r = await J('/api/admin/settings');
|
||||||
|
if(!r || !r.ok){ sfxTip('读取设置失败', false); return; }
|
||||||
|
SFXROWS = (r.suffix_grants || []).map(x => ({sfx: x.sfx || '', grants: x.grants || ''}));
|
||||||
|
sfxRender();
|
||||||
|
sfxTip('');
|
||||||
|
}
|
||||||
|
function sfxRender(){
|
||||||
|
const tb = document.getElementById('sfxBody');
|
||||||
|
if(!SFXROWS.length){
|
||||||
|
tb.innerHTML = `<tr><td colspan="3" class="tip" style="text-align:center;padding:12px">
|
||||||
|
暂无授权行——同后缀检索本来就能用(cos 搜 cos),这里只配「多搜谁」,例:工作台后缀 cos4、搜索后缀填 cos</td></tr>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tb.innerHTML = SFXROWS.map((r, i) => `<tr>
|
||||||
|
<td class="c">${i + 1}</td>
|
||||||
|
<td><input value="${esc(r.sfx)}" style="width:100%" placeholder="如 cos4"
|
||||||
|
oninput="SFXROWS[${i}].sfx=this.value"></td>
|
||||||
|
<td><input value="${esc(r.grants)}" style="width:100%" placeholder="如 cos swt(多个用空格或逗号隔开)"
|
||||||
|
oninput="SFXROWS[${i}].grants=this.value"></td>
|
||||||
|
<td class="c"><a href="javascript:sfxDel(${i})">删</a></td>
|
||||||
|
</tr>`).join('');
|
||||||
|
}
|
||||||
|
function sfxAddRow(){
|
||||||
|
SFXROWS.push({sfx: '', grants: ''});
|
||||||
|
sfxRender();
|
||||||
|
const tb = document.getElementById('sfxBody');
|
||||||
|
const inp = tb.querySelector('input');
|
||||||
|
if(inp) inp.focus();
|
||||||
|
}
|
||||||
|
function sfxDel(i){
|
||||||
|
SFXROWS.splice(i, 1);
|
||||||
|
sfxRender();
|
||||||
|
}
|
||||||
|
async function sfxSave(){
|
||||||
|
// 上传设置与授权矩阵同走一个保存端点:upload_max_mb 带上当前已存值,别把人家改掉
|
||||||
|
const cur = document.getElementById('upMax');
|
||||||
|
const r = await J('/api/admin/settings',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||||
|
body:JSON.stringify({upload_max_mb: cur ? parseInt(cur.value, 10) || undefined : undefined,
|
||||||
|
suffix_grants: SFXROWS})});
|
||||||
|
if(r && r.ok){
|
||||||
|
sfxTip('✓ ' + (r.msg || '已保存(立即生效)'), true);
|
||||||
|
await sfxLoad();
|
||||||
|
}else{
|
||||||
|
sfxTip('× ' + ((r && (r.msg || r.error)) || '保存失败'), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* 数据源面板(2026-10-08 重做,主人定):
|
/* 数据源面板(2026-10-08 重做,主人定):
|
||||||
· 新增 = 标签卡行「+ 新增」→ 表格**第一行**插入可编辑行,保存后按名称排序入列;
|
· 新增 = 标签卡行「+ 新增」→ 表格**第一行**插入可编辑行,保存后按名称排序入列;
|
||||||
· 修改 = 行内编辑,保存 = 字典改名 + **同步替换**存量批次(按影响条数二次确认);
|
· 修改 = 行内编辑,保存 = 字典改名 + **同步替换**存量批次(按影响条数二次确认);
|
||||||
@@ -3021,350 +2843,6 @@ dmask.onclick = e => { if(e.target===dmask) closeDict() };
|
|||||||
/* 页面初始化(2026-10-06 修):这一行原本调用的是 loadUpMax() —— 本页根本没有这个函数
|
/* 页面初始化(2026-10-06 修):这一行原本调用的是 loadUpMax() —— 本页根本没有这个函数
|
||||||
(真名是 upLoad(),就在上面十几行)。顶层一条语句炸掉,后面**全部不执行**:
|
(真名是 upLoad(),就在上面十几行)。顶层一条语句炸掉,后面**全部不执行**:
|
||||||
load(1) 没了 → 列表空着、"共 N 个"也不出,页面却看着没坏,最难往这里想。 */
|
load(1) 没了 → 列表空着、"共 N 个"也不出,页面却看着没坏,最难往这里想。 */
|
||||||
/* ===== 清单库三区域(2026-11-04 主人定)=====
|
|
||||||
区域1:根目录→省→清单名称(严格三级;根下加=省、省下加=清单名称,「清单名称」下加的进区域2);
|
|
||||||
区域2:选中第3级「清单名称」后画它的章节目录(层级不限,默认全展开),任一章节可再挂子章节;
|
|
||||||
区域3:真正的清单条目——编码/名称/项目特征/单位/工程量(工程量默认 1.000,空=1.000)。
|
|
||||||
两棵树探索器式 +/- 把手 + 连线;目录可编辑(+子目录/✎/↑/↓/✕,错误提示走 alert,同价格目录)。
|
|
||||||
后端:GET /api/admin/qlist/tree、/api/admin/qlist/items?dir_id=;
|
|
||||||
POST /api/admin/qlist/save(目录)、/api/admin/qlist/items(条目)。 */
|
|
||||||
const QL={tree:[],root:0,sel1:0,sel2:0,open1:{},open2:{},rows:[],ren:0,newp:0,edit:0,loaded:false,_mem:null};
|
|
||||||
function qlNode(id,list){ // 按 id 找节点(QL.tree 顶层=省列表;根是虚拟节点)
|
|
||||||
list=list||QL.tree;
|
|
||||||
for(const n of list){ if(n.id===id) return n; const h=qlNode(id,n.children); if(h) return h; }
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
function qlParent(id,list,pid){ // 父 id(找不到=-1;根的父=0)
|
|
||||||
list=list||QL.tree; pid=pid===undefined?0:pid;
|
|
||||||
for(const n of list){ if(n.id===id) return pid; const r=qlParent(id,n.children,n.id); if(r!==-1) return r; }
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
function qlSibsArr(id){ // 同级数组(算 ↑↓ 可用性)
|
|
||||||
if(id===QL.root) return null;
|
|
||||||
const p=qlParent(id);
|
|
||||||
if(p<=0) return QL.tree; // 省(父=根)
|
|
||||||
const pn=qlNode(p); return pn?pn.children:null;
|
|
||||||
}
|
|
||||||
function qlSel1(id){ // 区域1 选中(切选中必清区域2/3,防旧章节残留)
|
|
||||||
QL.sel1=id; QL.ren=0; QL.newp=0; QL.sel2=0; QL.open2={};
|
|
||||||
qlRender1(); qlRender2(); qlLoadItems();
|
|
||||||
}
|
|
||||||
function qlSel2(id){ QL.sel2=id; QL.ren=0; QL.newp=0; QL.edit=0; qlRender2(); qlLoadItems(); }
|
|
||||||
function qlTgl(id,region,ev){ // +/- 把手:未标记=展开(默认全开),false=收
|
|
||||||
ev.stopPropagation();
|
|
||||||
const bag=(region===1)?QL.open1:QL.open2;
|
|
||||||
bag[id]=(bag[id]===false);
|
|
||||||
qlRender1(); qlRender2();
|
|
||||||
}
|
|
||||||
/* ---- 渲染:区域1(根→省→清单名称,深度>2 的章节不进这棵树)---- */
|
|
||||||
function qlRender1(){
|
|
||||||
$('ktree1').innerHTML='<ul class="ktree">'+qlHtml1()+'</ul>';
|
|
||||||
qlSyncRt();
|
|
||||||
const ip=$('knew_ip')||$('kren_ip'); if(ip){ ip.focus(); ip.select(); qlArm(); }
|
|
||||||
}
|
|
||||||
function qlHtml1(){
|
|
||||||
const open=QL.open1[QL.root]!==false;
|
|
||||||
let root;
|
|
||||||
if(QL.ren===QL.root) root=qlRenInner({name:'根目录'});
|
|
||||||
else root='<div class="knode'+(QL.sel1===QL.root?' on':'')+'" onclick="qlSel1('+QL.root+')">'
|
|
||||||
+'<span class="ktg" onclick="qlTgl('+QL.root+',1,event)">'+(open?'-':'+')+'</span>'
|
|
||||||
+'<span class="kico">'+(open?'📂':'📁')+'</span><span class="knm">根目录</span></div>';
|
|
||||||
let h='<li class="kt0">'+root;
|
|
||||||
if(QL.newp && QL.newp.region===1 && QL.newp.parent===QL.root) h+=qlNewRow(QL.root,1);
|
|
||||||
if(open) h+='<ul>'+QL.tree.map(n=>qlLi1(n)).join('')+'</ul>';
|
|
||||||
return h+'</li>';
|
|
||||||
}
|
|
||||||
function qlLi1(n){ // 省(深度1,可展开)/清单名称(深度2,区域1叶子)
|
|
||||||
const kids=n.children||[], open=QL.open1[n.id]!==false, isTop=(n.depth<2);
|
|
||||||
let inner;
|
|
||||||
if(QL.ren===n.id) inner=qlRenInner(n);
|
|
||||||
else inner='<div class="knode'+(QL.sel1===n.id?' on':'')+'" onclick="qlSel1('+n.id+')">'
|
|
||||||
+'<span class="ktg'+((!isTop||!kids.length)?' em':'')+'"'
|
|
||||||
+((isTop&&kids.length)?' onclick="qlTgl('+n.id+',1,event)"':'')+'>'+(open?'-':'+')+'</span>'
|
|
||||||
+'<span class="kico">'+((open&&isTop&&kids.length)?'📂':'📁')+'</span>'
|
|
||||||
+'<span class="knm" title="'+esc(n.name)+'">'+esc(n.name)+'</span>'
|
|
||||||
+(n.depth===2&&n.n_items?'<span class="kcnt">'+n.n_items+'</span>':'')
|
|
||||||
+'</div>';
|
|
||||||
let kid='';
|
|
||||||
if(isTop&&open&&kids.length) kid='<ul>'+kids.map(c=>qlLi1(c)).join('')+'</ul>';
|
|
||||||
if(QL.newp && QL.newp.region===1 && QL.newp.parent===n.id) kid+='<ul>'+qlNewRow(n.id,1)+'</ul>';
|
|
||||||
return '<li>'+inner+kid+'</li>';
|
|
||||||
}
|
|
||||||
/* ---- 渲染:区域2(选中清单名称的章节树,层级不限,默认全展开)---- */
|
|
||||||
function qlRender2(){
|
|
||||||
$('ktree2').innerHTML=qlHtml2();
|
|
||||||
qlSyncRt();
|
|
||||||
const ip=$('knew_ip')||$('kren_ip'); if(ip){ ip.focus(); ip.select(); qlArm(); }
|
|
||||||
}
|
|
||||||
function qlHtml2(){
|
|
||||||
const n=qlNode(QL.sel1);
|
|
||||||
if(!n || n.depth!==2)
|
|
||||||
return '<div class="khint">← 在左边点选第 3 级「清单名称」,<br>这里显示它的章节目录</div>';
|
|
||||||
if(!n.children.length){
|
|
||||||
// 空目录也要能建第一个章节:新增行挂在选中的清单名下(2026-11-04 实测补)
|
|
||||||
if(QL.newp && QL.newp.region===2 && QL.newp.parent===n.id)
|
|
||||||
return '<ul class="ktree">'+qlNewRow(n.id,2)+'</ul>';
|
|
||||||
return '<div class="khint">「'+esc(n.name)+'」还没有章节目录 ——<br>点上面「+子目录」建第一个</div>';
|
|
||||||
}
|
|
||||||
return '<ul class="ktree">'+n.children.map(c=>qlLi2(c)).join('')
|
|
||||||
// 顶层新增行:+子目录没选中章节时挂在清单名称下(与已有章节同列,连线连续)——2026-11-05 实测补
|
|
||||||
+((QL.newp && QL.newp.region===2 && QL.newp.parent===n.id)?qlNewRow(n.id,2):'')
|
|
||||||
+'</ul>';
|
|
||||||
}
|
|
||||||
function qlLi2(n){
|
|
||||||
const kids=n.children||[], open=QL.open2[n.id]!==false;
|
|
||||||
let inner;
|
|
||||||
if(QL.ren===n.id) inner=qlRenInner(n);
|
|
||||||
else inner='<div class="knode'+(QL.sel2===n.id?' on':'')+'" onclick="qlSel2('+n.id+')">'
|
|
||||||
+'<span class="ktg'+(kids.length?'':' em')+'"'+(kids.length?' onclick="qlTgl('+n.id+',2,event)"':'')+'>'+(open?'-':'+')+'</span>'
|
|
||||||
+'<span class="kico">'+((open&&kids.length)?'📂':'📁')+'</span>'
|
|
||||||
+'<span class="knm" title="'+esc(n.name)+'">'+esc(n.name)+'</span>'
|
|
||||||
+(n.n_items?'<span class="kcnt">'+n.n_items+'</span>':'')
|
|
||||||
+'</div>';
|
|
||||||
let kid=(open&&kids.length)?'<ul>'+kids.map(c=>qlLi2(c)).join('')+'</ul>':'';
|
|
||||||
if(QL.newp && QL.newp.region===2 && QL.newp.parent===n.id) kid+='<ul>'+qlNewRow(n.id,2)+'</ul>';
|
|
||||||
return '<li>'+inner+kid+'</li>';
|
|
||||||
}
|
|
||||||
/* ---- 行内编辑(改名 / 新增目录)----
|
|
||||||
输入口径全按决策 271补(项目目录同款缺陷已定案):①中文输入法组词回车不作数
|
|
||||||
(isComposing/229);②点别处=有值就提交、空值放弃(blur + document mousedown 双通道,
|
|
||||||
mousedown 先于 blur 必发、不依赖焦点移动);③提交路径开头先摘保底监听+清状态,防二次提交。 */
|
|
||||||
function qlRenInner(n){
|
|
||||||
return '<div class="knode"><span class="ktg em"></span><span class="kico">📁</span>'
|
|
||||||
+'<input class="kren" id="kren_ip" value="'+esc(n.name)+'" onkeydown="qlRenKey(event)" onblur="qlRenBlur()">'
|
|
||||||
+'<span class="kcfm"><span class="kpk" title="确认" onclick="qlRenGo()">✓</span>'
|
|
||||||
+'<span class="kpd" title="取消" onclick="qlRenCancel()">✕</span></span></div>';
|
|
||||||
}
|
|
||||||
function qlNewRow(parentId,region){
|
|
||||||
return '<li><div class="knode"><span class="ktg em"></span><span class="kico">📁</span>'
|
|
||||||
+'<input class="kren" id="knew_ip" placeholder="目录名称,回车保存" onkeydown="qlNewKey(event)" onblur="qlNewBlur()">'
|
|
||||||
+'<span class="kcfm"><span class="kpk" title="保存" onclick="qlNewGo()">✓</span>'
|
|
||||||
+'<span class="kpd" title="取消" onclick="qlNewCancel()">✕</span></span></div></li>';
|
|
||||||
}
|
|
||||||
let QLOUT=null;
|
|
||||||
function qlDisarm(){ if(QLOUT){ document.removeEventListener('mousedown',QLOUT); QLOUT=null; } }
|
|
||||||
function qlArm(){ // 点别处提交的保底(新增/改名共用)
|
|
||||||
qlDisarm();
|
|
||||||
QLOUT=function(e){
|
|
||||||
if(e.target && (e.target.id==='knew_ip' || e.target.id==='kren_ip')) return;
|
|
||||||
qlDisarm();
|
|
||||||
if(QL.newp) qlNewGo();
|
|
||||||
if(QL.ren) qlRenGo();
|
|
||||||
};
|
|
||||||
document.addEventListener('mousedown',QLOUT);
|
|
||||||
}
|
|
||||||
function qlOpenPath(id,region){ // 新增/选中时把父链全展开
|
|
||||||
const bag=(region===1)?QL.open1:QL.open2;
|
|
||||||
let cur=id;
|
|
||||||
while(cur && cur!==QL.root && cur!==QL.sel1){ bag[cur]=true; const p=qlParent(cur); if(p<=0) break; cur=p; }
|
|
||||||
}
|
|
||||||
/* ---- 工具排可用性(.rtbar span.dis 灰禁)---- */
|
|
||||||
function qlSyncRt(){
|
|
||||||
const set=(id,on)=>{ const el=$(id); if(el) el.classList.toggle('dis',!on); };
|
|
||||||
const n1=qlNode(QL.sel1), n2=qlNode(QL.sel2);
|
|
||||||
const hasSib=(n,d)=>{ if(!n) return false; const a=qlSibsArr(n.id); if(!a) return false;
|
|
||||||
const i=a.findIndex(x=>x.id===n.id), j=i+d; return i>=0&&j>=0&&j<a.length; };
|
|
||||||
set('kadd1',true);
|
|
||||||
set('kren1',!!QL.sel1);
|
|
||||||
set('kup1',hasSib(n1,-1)); set('kdn1',hasSib(n1,1));
|
|
||||||
set('kdel1',!!QL.sel1&&QL.sel1!==QL.root);
|
|
||||||
set('kadd2',!!n1&&n1.depth===2);
|
|
||||||
set('kren2',!!n2); set('kup2',hasSib(n2,-1)); set('kdn2',hasSib(n2,1)); set('kdel2',!!n2);
|
|
||||||
set('kaddi',!!n2);
|
|
||||||
}
|
|
||||||
/* ---- 目录增删改名上下移(POST /api/admin/qlist/save)---- */
|
|
||||||
async function qlDirPost(payload){
|
|
||||||
const r=await J('/api/admin/qlist/save',{method:'POST',headers:{'Content-Type':'application/json'},
|
|
||||||
body:JSON.stringify(payload)});
|
|
||||||
if(!r.ok){ alert(r.msg); return null; }
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
function qlAdd1(){ qlNewStart(QL.sel1||QL.root,1); } // 根下=省、省下=清单名称、清单名称下=章节(层级自动)
|
|
||||||
function qlAdd2(){ const n=qlNode(QL.sel1); if(!n||n.depth!==2) return; qlNewStart(QL.sel2||QL.sel1,2); }
|
|
||||||
function qlNewStart(parent,region){ QL.newp={parent,region}; QL.ren=0; qlOpenPath(parent,region); qlRender1(); qlRender2(); }
|
|
||||||
function qlNewCancel(){ QL.newp=0; qlDisarm(); qlRender1(); qlRender2(); }
|
|
||||||
function qlNewKey(e){
|
|
||||||
e.stopPropagation();
|
|
||||||
if(e.isComposing || e.keyCode===229) return; // 输入法组词回车不作数(决策 271补 同款)
|
|
||||||
if(e.key==='Enter') qlNewGo();
|
|
||||||
else if(e.key==='Escape') qlNewCancel();
|
|
||||||
}
|
|
||||||
function qlNewBlur(){ if(QL.newp) qlNewGo(); } // 点开别处=有值就提交、空值放弃
|
|
||||||
async function qlNewGo(){
|
|
||||||
if(!QL.newp) return;
|
|
||||||
qlDisarm();
|
|
||||||
const ip=$('knew_ip');
|
|
||||||
const parent=QL.newp.parent, region=QL.newp.region;
|
|
||||||
const name=(ip&&ip.value||'').trim();
|
|
||||||
QL.newp=0; // 先摘状态:blur/保底监听不再二次提交
|
|
||||||
if(!name){ qlRender1(); qlRender2(); return; }
|
|
||||||
const r=await qlDirPost({op:'add',parent_id:parent,name});
|
|
||||||
if(!r){ qlRender1(); qlRender2(); return; }
|
|
||||||
await qlLoad(true);
|
|
||||||
if(r.id){ // 新清单名称=自动选中(区域2立即可用);新章节=自动选中出条目表
|
|
||||||
if(r.depth===2) qlSel1(r.id);
|
|
||||||
else if(r.depth>=3 && qlNode(QL.sel1) && qlParent(r.id)===QL.sel1) qlSel2(r.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function qlRen1(){ if(!QL.sel1) return; QL.newp=0; QL.ren=QL.sel1; qlRender1(); qlRender2(); }
|
|
||||||
function qlRen2(){ if(!QL.sel2) return; QL.newp=0; QL.ren=QL.sel2; qlRender1(); qlRender2(); }
|
|
||||||
function qlRenCancel(){ QL.ren=0; qlDisarm(); qlRender1(); qlRender2(); }
|
|
||||||
function qlRenKey(e){
|
|
||||||
e.stopPropagation();
|
|
||||||
if(e.isComposing || e.keyCode===229) return; // 同 qlNewKey:组词回车不作数
|
|
||||||
if(e.key==='Enter') qlRenGo();
|
|
||||||
else if(e.key==='Escape') qlRenCancel();
|
|
||||||
}
|
|
||||||
function qlRenBlur(){ if(QL.ren) qlRenGo(); } // 点开别处=有值就提交
|
|
||||||
async function qlRenGo(){
|
|
||||||
if(!QL.ren) return;
|
|
||||||
qlDisarm();
|
|
||||||
const ip=$('kren_ip'); const did=QL.ren;
|
|
||||||
const name=(ip&&ip.value||'').trim();
|
|
||||||
QL.ren=0; // 先摘状态防二次提交
|
|
||||||
if(!name){ qlRender1(); qlRender2(); return; }
|
|
||||||
const r=await qlDirPost({op:'rename',id:did,name});
|
|
||||||
if(!r){ qlRender1(); qlRender2(); return; }
|
|
||||||
await qlLoad(true);
|
|
||||||
}
|
|
||||||
async function qlSeq(d,region){
|
|
||||||
const id=(region===1)?QL.sel1:QL.sel2; if(!id) return;
|
|
||||||
const r=await qlDirPost({op:'seq',id:id,dir:d>0?'down':'up'});
|
|
||||||
if(!r) return; await qlLoad(true);
|
|
||||||
}
|
|
||||||
function qlSeq1(d){ qlSeq(d,1); } function qlSeq2(d){ qlSeq(d,2); }
|
|
||||||
async function qlDel1(){
|
|
||||||
const id=QL.sel1; if(!id||id===QL.root) return;
|
|
||||||
const n=qlNode(id); if(!n) return;
|
|
||||||
if(!(await uiConfirm('删除目录「'+n.name+'」?',
|
|
||||||
(n.children&&n.children.length)?'它下面还有子目录,要先删光子目录才能删它。':'删除后不可恢复。'))) return;
|
|
||||||
const r=await qlDirPost({op:'del',id:id}); if(!r) return;
|
|
||||||
if(QL.sel1===id){ QL.sel1=0; QL.sel2=0; QL.rows=[]; }
|
|
||||||
await qlLoad(true);
|
|
||||||
}
|
|
||||||
async function qlDel2(){
|
|
||||||
const id=QL.sel2; if(!id) return;
|
|
||||||
const n=qlNode(id); if(!n) return;
|
|
||||||
const warn=[];
|
|
||||||
if(n.children&&n.children.length) warn.push('子目录 '+n.children.length+' 个(要先删光子目录)');
|
|
||||||
if(n.n_items) warn.push('清单条目 '+n.n_items+' 条(将一并删除)');
|
|
||||||
if(!(await uiConfirm('删除章节目录「'+n.name+'」?', warn.length?warn.join(';'):'删除后不可恢复。'))) return;
|
|
||||||
const r=await qlDirPost({op:'del',id:id}); if(!r) return;
|
|
||||||
if(QL.sel2===id){ QL.sel2=0; QL.rows=[]; }
|
|
||||||
await qlLoad(true);
|
|
||||||
}
|
|
||||||
/* ---- 加载 ---- */
|
|
||||||
/* ---- 无感 + 记忆(2026-11-05 主人定):切走抓拍 / 切回恢复 ----
|
|
||||||
记忆=选中目录 + 树展开 + 三区滚动(同工作台决策 214 页签状态记忆口径);
|
|
||||||
切回时内存已有树先按现态立即渲染(不闪不重置=无感),再后台重拉保证新鲜;
|
|
||||||
抓拍入 sessionStorage(同后台明细标签决策 150 口径)——跳工作台再回来、刷新页面都还在。
|
|
||||||
正在编辑的行内输入/条目编辑不进记忆(切回=已保存状态,与决策 214 同口径)。 */
|
|
||||||
const QLSNAP='admin_qlist';
|
|
||||||
function qlSnap(){ try{
|
|
||||||
sessionStorage.setItem(QLSNAP, JSON.stringify({
|
|
||||||
sel1:QL.sel1, sel2:QL.sel2, open1:QL.open1, open2:QL.open2,
|
|
||||||
sc1:$('ktree1')?$('ktree1').scrollTop:0, sc2:$('ktree2')?$('ktree2').scrollTop:0,
|
|
||||||
sc3:$('kbody3')?$('kbody3').scrollTop:0}));
|
|
||||||
}catch(e){} }
|
|
||||||
function qlUnsnap(){ try{
|
|
||||||
const s=sessionStorage.getItem(QLSNAP); return s?JSON.parse(s):null;
|
|
||||||
}catch(e){ return null; } }
|
|
||||||
function qlApplyScroll(mem){ // innerHTML 重渲染会重置 scrollTop,渲染后重挂
|
|
||||||
if(!mem) return;
|
|
||||||
const a=$('ktree1'), b=$('ktree2'), c=$('kbody3');
|
|
||||||
if(a) a.scrollTop=mem.sc1||0;
|
|
||||||
if(b) b.scrollTop=mem.sc2||0;
|
|
||||||
if(c) c.scrollTop=mem.sc3||0;
|
|
||||||
}
|
|
||||||
async function qlLoad(noMem){
|
|
||||||
// noMem=true=本页操作后的刷新(新增/改名/上下移/删除/存条目):内存 QL 态就是最新事实,
|
|
||||||
// 绝不回读记忆(旧抓拍会把切走前的选中盖回来)。记忆只在「从别的标签/页面切回」时恢复一次。
|
|
||||||
const mem=noMem?null:qlUnsnap();
|
|
||||||
if(mem){ // 记忆先落 QL(选中/展开立即恢复,含跨刷新)
|
|
||||||
if(Number.isInteger(mem.sel1)) QL.sel1=mem.sel1;
|
|
||||||
if(Number.isInteger(mem.sel2)) QL.sel2=mem.sel2;
|
|
||||||
QL.open1=mem.open1||{}; QL.open2=mem.open2||{};
|
|
||||||
}
|
|
||||||
QL._mem=mem;
|
|
||||||
if(QL.loaded){ // 内存已有树:现态立即上屏(切回瞬间出画面,无感),随后再刷新
|
|
||||||
qlRender1(); qlRender2(); qlLoadItems();
|
|
||||||
qlApplyScroll(QL._mem);
|
|
||||||
}
|
|
||||||
const d=await J('/api/admin/qlist/tree');
|
|
||||||
if(d.ok===false){ alert(d.msg||'清单库加载失败'); return; }
|
|
||||||
QL.tree=d.tree||[]; QL.root=d.root||0; QL.loaded=true;
|
|
||||||
if(QL.sel1 && QL.sel1!==QL.root && !qlNode(QL.sel1)){ QL.sel1=0; QL.sel2=0; QL.rows=[]; }
|
|
||||||
if(QL.sel2 && !qlNode(QL.sel2)){ QL.sel2=0; QL.rows=[]; }
|
|
||||||
qlRender1(); qlRender2(); qlLoadItems();
|
|
||||||
qlApplyScroll(QL._mem);
|
|
||||||
}
|
|
||||||
/* ---- 区域3:真正的清单条目(编码/名称/项目特征/单位/工程量)---- */
|
|
||||||
async function qlLoadItems(){
|
|
||||||
const tb=$('kitemsb'), where=$('kwhere');
|
|
||||||
if(!QL.sel2){
|
|
||||||
tb.innerHTML='<tr><td colspan="6" class="kempty">← 在中间区域选中章节目录,这里出真正的清单条目</td></tr>';
|
|
||||||
where.textContent=''; where.title=''; return;
|
|
||||||
}
|
|
||||||
const n=qlNode(QL.sel2);
|
|
||||||
where.textContent='目录:'+(n?n.name:'');
|
|
||||||
where.title=where.textContent;
|
|
||||||
const d=await J('/api/admin/qlist/items?dir_id='+QL.sel2);
|
|
||||||
if(d.ok===false){ tb.innerHTML='<tr><td colspan="6" class="kempty">'+esc(d.msg||'加载失败')+'</td></tr>'; return; }
|
|
||||||
QL.rows=d.rows||[];
|
|
||||||
tb.innerHTML=QL.rows.length?QL.rows.map(qlItemRow).join('')
|
|
||||||
:'<tr><td colspan="6" class="kempty">这个章节还没有条目 —— 点「+条目」录第一条(工程量默认 1.000)</td></tr>';
|
|
||||||
qlApplyScroll(QL._mem); // 条目表内容到位后再挂一次滚动记忆
|
|
||||||
}
|
|
||||||
function qlItemRow(r){
|
|
||||||
if(QL.edit===r.id){
|
|
||||||
return '<tr class="pedit">'
|
|
||||||
+'<td><input id="ke_code" value="'+esc(r.code)+'"></td>'
|
|
||||||
+'<td><input id="ke_name" value="'+esc(r.name)+'" onkeydown="if(event.key===\'Enter\')qlItemSave('+(r.id||0)+')"></td>'
|
|
||||||
+'<td><textarea id="ke_feat" rows="3">'+esc(r.feature)+'</textarea></td>'
|
|
||||||
+'<td><input id="ke_unit" value="'+esc(r.unit)+'" onkeydown="if(event.key===\'Enter\')qlItemSave('+(r.id||0)+')"></td>'
|
|
||||||
+'<td><input id="ke_qty" value="'+Number(r.qty||0).toFixed(3)+'" onkeydown="if(event.key===\'Enter\')qlItemSave('+(r.id||0)+')"></td>'
|
|
||||||
+'<td><a href="javascript:void(0)" onclick="qlItemSave('+(r.id||0)+')">保存</a>'
|
|
||||||
+'<a href="javascript:void(0)" onclick="qlItemCancel()">取消</a></td></tr>';
|
|
||||||
}
|
|
||||||
return '<tr>'
|
|
||||||
+'<td>'+esc(r.code)+'</td>'
|
|
||||||
+'<td>'+esc(r.name)+'</td>'
|
|
||||||
+'<td class="kfeat" title="'+esc(r.feature)+'">'+esc(r.feature)+'</td>'
|
|
||||||
+'<td class="kc">'+esc(r.unit)+'</td>'
|
|
||||||
+'<td class="kr">'+num(r.qty,3)+'</td>'
|
|
||||||
+'<td><a href="javascript:void(0)" onclick="qlItemEdit('+r.id+')">编辑</a>'
|
|
||||||
+'<a href="javascript:void(0)" onclick="qlItemDel('+r.id+')">删除</a></td></tr>';
|
|
||||||
}
|
|
||||||
function qlItemAdd(){
|
|
||||||
if(!QL.sel2){ alert('先在中间区域选中章节目录'); return; }
|
|
||||||
QL.edit=-1;
|
|
||||||
const blank={id:-1,code:'',name:'',feature:'',unit:'',qty:1};
|
|
||||||
$('kitemsb').innerHTML=(QL.rows.length?QL.rows.map(qlItemRow).join(''):'')+qlItemRow(blank);
|
|
||||||
const f=$('ke_name'); if(f) f.focus();
|
|
||||||
}
|
|
||||||
function qlItemEdit(id){ QL.edit=id; $('kitemsb').innerHTML=QL.rows.map(qlItemRow).join('');
|
|
||||||
const f=$('ke_name'); if(f){ f.focus(); f.select(); } }
|
|
||||||
function qlItemCancel(){ QL.edit=0; qlLoadItems(); }
|
|
||||||
async function qlItemSave(id){
|
|
||||||
const body={op:id>0?'edit':'add',dir_id:QL.sel2,
|
|
||||||
code:$('ke_code').value.trim(), name:$('ke_name').value.trim(),
|
|
||||||
feature:$('ke_feat').value, unit:$('ke_unit').value.trim(), qty:$('ke_qty').value};
|
|
||||||
if(id>0) body.id=id;
|
|
||||||
const r=await J('/api/admin/qlist/items',{method:'POST',headers:{'Content-Type':'application/json'},
|
|
||||||
body:JSON.stringify(body)});
|
|
||||||
if(!r.ok){ alert(r.msg); return; }
|
|
||||||
QL.edit=0; await qlLoad(true); // 整树重拉:区域1/2 的条数徽章同步刷新(操作后刷新不走记忆)
|
|
||||||
}
|
|
||||||
async function qlItemDel(id){
|
|
||||||
const r0=QL.rows.find(x=>x.id===id);
|
|
||||||
if(!(await uiConfirm('删除清单条目「'+(r0?r0.name:'')+'」?','删除后不可恢复。'))) return;
|
|
||||||
const r=await J('/api/admin/qlist/items',{method:'POST',headers:{'Content-Type':'application/json'},
|
|
||||||
body:JSON.stringify({op:'del',id:id})});
|
|
||||||
if(!r.ok){ alert(r.msg); return; }
|
|
||||||
await qlLoad(true);
|
|
||||||
}
|
|
||||||
// 页面卸载前也抓拍一次:没点标签直接跳工作台/关页,记忆不丢(sessionStorage 跨跳转保留)
|
|
||||||
window.addEventListener('beforeunload', ()=>{ if(KIND==='qlist') qlSnap(); });
|
|
||||||
// 页面初载(2026-10-13 主人定:进页面要等待时挂进度条——从工作台切过来时首屏不再是空白静默)
|
// 页面初载(2026-10-13 主人定:进页面要等待时挂进度条——从工作台切过来时首屏不再是空白静默)
|
||||||
(async function(){
|
(async function(){
|
||||||
await ldWrap('','正在加载后台数据(项目/筛选/汇总)…', async ()=>{
|
await ldWrap('','正在加载后台数据(项目/筛选/汇总)…', async ()=>{
|
||||||
|
|||||||
@@ -1403,16 +1403,36 @@ function rvCachePut() { // DOM 变化(排序/树折叠)后
|
|||||||
if (RV_CACHE_PUT_T) clearTimeout(RV_CACHE_PUT_T);
|
if (RV_CACHE_PUT_T) clearTimeout(RV_CACHE_PUT_T);
|
||||||
RV_CACHE_PUT_T = setTimeout(rvCachePutNow, 250);
|
RV_CACHE_PUT_T = setTimeout(rvCachePutNow, 250);
|
||||||
}
|
}
|
||||||
|
/* 渲染后原位恢复选中态(决策 253,2026-11-06 主人定「记住上次的位置,且要无感」):
|
||||||
|
缓存已剥 sel/subsel(252),渲染会把选中洗掉、_apPick 随即抢点第一行(实测报障「输入
|
||||||
|
工程量后跳回第一行」)。渲染前抓拍、渲染后同步恢复——赶在 _apPick 250ms 抢点窗口之前;
|
||||||
|
252 口径一致:定额选中时只恢复定额不恢复清单。行没了(被删/换视图找不到)就不恢复,
|
||||||
|
让 _apPick 兜底默认选中。 */
|
||||||
|
function _rawKeepRestore(b, bid, nid) {
|
||||||
|
if (nid) {
|
||||||
|
const sub = b.querySelector('tr.sub[data-nid="' + nid + '"]');
|
||||||
|
if (sub) sub.classList.add('subsel');
|
||||||
|
} else if (bid) {
|
||||||
|
const row = b.querySelector('tr.brow[data-bid="' + bid + '"]');
|
||||||
|
if (row) row.classList.add('sel');
|
||||||
|
}
|
||||||
|
}
|
||||||
async function rawDraw(quiet) { // 决策 221:quiet=true 编辑保存静默档——不压暗不弹角标,只锁点击
|
async function rawDraw(quiet) { // 决策 221:quiet=true 编辑保存静默档——不压暗不弹角标,只锁点击
|
||||||
const b = document.getElementById(RVO.bodyEl);
|
const b = document.getElementById(RVO.bodyEl);
|
||||||
if (!b) return;
|
if (!b) return;
|
||||||
if (RV_CACHE_PUT_T) rvCachePutNow(); // 防抖未落盘先落:换视图/重绘前把旧 DOM 状态存住,不丢
|
if (RV_CACHE_PUT_T) rvCachePutNow(); // 防抖未落盘先落:换视图/重绘前把旧 DOM 状态存住,不丢
|
||||||
|
const _sel = b.querySelector('tr.sel');
|
||||||
|
const _sub = b.querySelector('tr.subsel');
|
||||||
|
const _keepBid = (!_sub && _sel) ? _sel.dataset.bid : null;
|
||||||
|
const _keepNid = _sub ? _sub.dataset.nid : null;
|
||||||
|
const _keepScroll = b.scrollTop;
|
||||||
const key = _rvCacheKey();
|
const key = _rvCacheKey();
|
||||||
const hit = RV_CACHE[key];
|
const hit = RV_CACHE[key];
|
||||||
if (hit) { // 命中缓存:原位直出,零等待
|
if (hit) { // 命中缓存:原位直出,零等待
|
||||||
b.innerHTML = hit.html;
|
b.innerHTML = hit.html;
|
||||||
colwApply(b.querySelector('table'));
|
colwApply(b.querySelector('table'));
|
||||||
b.scrollTop = hit.scroll || 0;
|
b.scrollTop = hit.scroll || 0;
|
||||||
|
_rawKeepRestore(b, _keepBid, _keepNid);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (b.innerHTML.trim()) b.classList.add(quiet ? 'rawbusy' : 'rawloading'); // 压暗旧内容不清空不跳动;quiet(决策 221 编辑保存)只锁点击,无任何视觉变化
|
if (b.innerHTML.trim()) b.classList.add(quiet ? 'rawbusy' : 'rawloading'); // 压暗旧内容不清空不跳动;quiet(决策 221 编辑保存)只锁点击,无任何视觉变化
|
||||||
@@ -1441,8 +1461,11 @@ async function rawDraw(quiet) { // 决策 221:quiet=true 编辑保存静默
|
|||||||
b.innerHTML = html;
|
b.innerHTML = html;
|
||||||
colwApply(b.querySelector('table'));
|
colwApply(b.querySelector('table'));
|
||||||
if (RVSEL.k === 'uw' && (RVTAB === 'item' || RVTAB === 'prelim')) rawTreeSync();
|
if (RVSEL.k === 'uw' && (RVTAB === 'item' || RVTAB === 'prelim')) rawTreeSync();
|
||||||
b.scrollTop = 0;
|
// 决策 253:quiet(编辑保存/采纳静默重绘=同视图)保住滚动与选中——无感;换视图(切
|
||||||
RV_CACHE[key] = { html: b.innerHTML, scroll: 0 };
|
// uw/切档,quiet 假)照旧归顶,旧视图的滚动对新视图无意义
|
||||||
|
b.scrollTop = quiet ? _keepScroll : 0;
|
||||||
|
_rawKeepRestore(b, _keepBid, _keepNid);
|
||||||
|
RV_CACHE[key] = { html: b.innerHTML, scroll: b.scrollTop };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
b.innerHTML = '<div class="empty">读取失败</div>';
|
b.innerHTML = '<div class="empty">读取失败</div>';
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"Dacl": "D:AI",
|
|
||||||
"Protected": false,
|
|
||||||
"Observed": "D:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)(A;OICIIOID;GA;;;SY)(A;ID;0x1301bf;;;AU)(A;OICIIOID;SDGXGWGR;;;AU)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;BU)",
|
|
||||||
"Path": "D:\\PricingReview\\CostReview\\data"
|
|
||||||
}
|
|
||||||
@@ -1,798 +0,0 @@
|
|||||||
<#
|
|
||||||
.SYNOPSIS
|
|
||||||
Diagnose the DSH sandbox ACL failures on Windows and repair them in one run.
|
|
||||||
|
|
||||||
.DESCRIPTION
|
|
||||||
A denial inside the DSH sandbox is worth diagnosing only when it contradicts
|
|
||||||
what the active mode promises: writes inside the workspace, or reads that the
|
|
||||||
signed-in user should plainly have. One invocation reads each requested path
|
|
||||||
and every ancestor, then repairs what it can in the same run:
|
|
||||||
|
|
||||||
* every directory on that chain inside -AllowRoot that lacks effective
|
|
||||||
WRITE_DAC or WRITE_OWNER gets a FullControl allow ACE for the current
|
|
||||||
user, so the sandbox can provision the grant it needs; and
|
|
||||||
* every explicit AppContainer package allow ACE (S-1-15-2-*, excluding the
|
|
||||||
well-known groups ending in 1 or 2) is removed at its source, ancestor
|
|
||||||
first, which also removes that package's access to the tree.
|
|
||||||
|
|
||||||
A directory the caller cannot provision is the state the sandbox reports on the
|
|
||||||
workspace root, while the conflicting entry often sits deeper; the authorized root
|
|
||||||
is examined for the same reason. For either case the same run also collects explicit
|
|
||||||
package allow ACEs under the requested directory, so they do not need a second call.
|
|
||||||
The walk is bounded, enters no reparse point or managed application tree, and reports
|
|
||||||
truncation and unreadable directories instead of claiming a complete walk.
|
|
||||||
|
|
||||||
Every observation, change, verification and recovery command is printed as it
|
|
||||||
happens, so one run shows the caller the complete set of actions.
|
|
||||||
|
|
||||||
-AllowRoot bounds every change: an object is modified only when it is that
|
|
||||||
directory or strictly inside it, so a caller can repair its own workspace
|
|
||||||
root. Reparse paths and managed application trees are refused. Each modified
|
|
||||||
object is backed up first, with an independent recovery script, and every DACL
|
|
||||||
write is verified by re-reading it. A failed repair restores all attempted
|
|
||||||
DACL changes from this invocation in reverse order and stops.
|
|
||||||
|
|
||||||
The script never creates, deletes, or writes the contents of any file. Its
|
|
||||||
only writes are the recovery artifacts under -Out and the DACLs it repairs.
|
|
||||||
|
|
||||||
.PARAMETER Path
|
|
||||||
One or more failing paths. Each is diagnosed and repaired together with its ancestors.
|
|
||||||
|
|
||||||
.PARAMETER AllowRoot
|
|
||||||
Required. Every modified object must be this directory or strictly inside it.
|
|
||||||
|
|
||||||
.PARAMETER Out
|
|
||||||
Required for a repair. Receives one recovery record and one recovery script
|
|
||||||
per change, so an object repaired twice keeps both recovery points.
|
|
||||||
|
|
||||||
.PARAMETER Restore
|
|
||||||
Restore the DACL recovery record for exactly one -Path instead of repairing.
|
|
||||||
Requires -AllowRoot and WRITE_DAC, preserves owner and SACL.
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
pwsh -File diagnose-windows-sandbox-acl.ps1 -Path '<failing path>' -AllowRoot '<authorized directory>' -Out '<recovery directory>'
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
pwsh -File diagnose-windows-sandbox-acl.ps1 -Path '<failing path>' -AllowRoot '<authorized directory>' -Restore '<recovery record>'
|
|
||||||
#>
|
|
||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory = $true)][string[]]$Path,
|
|
||||||
[string]$AllowRoot,
|
|
||||||
[string]$Out,
|
|
||||||
[string]$Restore
|
|
||||||
)
|
|
||||||
|
|
||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
# These two well-known groups name all packages, not one conflicting package.
|
|
||||||
$PACKAGE_SID = '^S-1-15-2-(?![12]$)'
|
|
||||||
$LOW_LABEL_SID = 'S-1-16-4096'
|
|
||||||
# Upper bound on the directories one subtree scan may visit, so a huge workspace
|
|
||||||
# cannot turn one approved repair into an unbounded walk. Truncation is reported.
|
|
||||||
$SCAN_LIMIT = 2000
|
|
||||||
|
|
||||||
function Write-Line { param([string]$Text) Write-Output $Text }
|
|
||||||
|
|
||||||
# Reports bypass the success pipeline so diagnostics cannot become a function's
|
|
||||||
# return value. Each JSON record occupies one stdout line, including paths/errors.
|
|
||||||
function Write-Report {
|
|
||||||
param([string]$Kind, [string]$Operation, [string]$Target, [string]$Status, [string]$Reason, $Details = @{})
|
|
||||||
$record = [ordered]@{ kind = $Kind; operation = $Operation; path = $Target; status = $Status; reason = $Reason; details = $Details }
|
|
||||||
if ($Kind -eq 'observation' -and $Status -in @('unknown', 'unreadable', 'partial')) { $script:observationFailures++ }
|
|
||||||
$script:reports.Add($record)
|
|
||||||
$json = $record | ConvertTo-Json -Depth 12 -Compress
|
|
||||||
# The complete record set also lands in the report file: tool output is truncated to its
|
|
||||||
# tail, so a long run's early records survive only there.
|
|
||||||
if ($null -ne $script:reportWriter) {
|
|
||||||
try { $script:reportWriter.WriteLine($json); $script:reportWriter.Flush() }
|
|
||||||
catch [System.IO.IOException] {
|
|
||||||
# stdout keeps only its tail, so this file is the complete record: a write failure
|
|
||||||
# has to reach the caller, on stderr, instead of leaving a silently incomplete file.
|
|
||||||
[Console]::Error.WriteLine('REPORT_IO_FAILED {0}: {1}' -f $script:reportPath, $_.Exception.Message)
|
|
||||||
try { $script:reportWriter.Dispose() } catch { }
|
|
||||||
$script:reportWriter = $null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[Console]::Out.WriteLine('REPORT ' + $json)
|
|
||||||
}
|
|
||||||
function Invoke-ReportedOperation {
|
|
||||||
param([string]$Operation, [string]$Target, [string]$Reason, [string]$Effect, [scriptblock]$Action)
|
|
||||||
$entry = [ordered]@{ id = $script:operations.Count + 1; operation = $Operation; path = $Target; effect = $Effect; status = 'started' }
|
|
||||||
$script:operations.Add($entry)
|
|
||||||
if ($Effect -eq 'acl' -and $Operation -ne 'restore_dacl' -and $script:recoveries.Count -gt 0) {
|
|
||||||
$script:recoveries[-1].attempted = $true
|
|
||||||
}
|
|
||||||
Write-Report action $Operation $Target started $Reason @{ id = $entry.id; effect = $Effect }
|
|
||||||
try {
|
|
||||||
$result = & $Action
|
|
||||||
$entry.status = 'completed'
|
|
||||||
Write-Report action $Operation $Target completed $Reason @{ id = $entry.id; effect = $Effect }
|
|
||||||
return $result
|
|
||||||
} catch {
|
|
||||||
$entry.status = 'failed'
|
|
||||||
Write-Report action $Operation $Target failed $Reason @{
|
|
||||||
id = $entry.id; effect = $Effect; error = (Get-HResultChain $_.Exception)
|
|
||||||
state = $(if ($Effect -eq 'none') { 'No mutation requested by this operation.' } else { 'The operation may have partially changed state; completion is unconfirmed.' })
|
|
||||||
}
|
|
||||||
throw
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Decision {
|
|
||||||
param([string]$Operation, [string]$Target, [string]$Status, [string]$Reason)
|
|
||||||
Write-Report decision $Operation $Target $Status $Reason
|
|
||||||
}
|
|
||||||
|
|
||||||
# Unwrap nested exceptions: PowerShell wraps Win32 failures, and only the inner
|
|
||||||
# exception carries the real HRESULT the caller needs to classify the failure.
|
|
||||||
function Get-HResultChain {
|
|
||||||
param([System.Exception]$Exception)
|
|
||||||
$chain = @()
|
|
||||||
$e = $Exception
|
|
||||||
while ($null -ne $e) {
|
|
||||||
$chain += ('{0}=0x{1:X8}/win32={2}: {3}' -f $e.GetType().Name, $e.HResult, ($e.HResult -band 0xFFFF), $e.Message)
|
|
||||||
$e = $e.InnerException
|
|
||||||
}
|
|
||||||
return ($chain -join ' <- ')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-CurrentIdentity {
|
|
||||||
return [System.Security.Principal.WindowsIdentity]::GetCurrent()
|
|
||||||
}
|
|
||||||
|
|
||||||
# Integrity level affects the symptom: the same foreign
|
|
||||||
# ACE fails a grant when the caller is below Medium and merely blocks the child
|
|
||||||
# when the caller is not.
|
|
||||||
# The integrity level lives in the token's group list, which .NET filters out of
|
|
||||||
# WindowsIdentity.Groups, so read it through GetTokenInformation. Add-Type compiles
|
|
||||||
# in-process on PowerShell 7. Never spawn whoami.exe for this: inside a below-Medium
|
|
||||||
# token that process fails to initialize (STATUS_DLL_INIT_FAILED, 0xc0000142) and
|
|
||||||
# raises an application-error dialog on the user's desktop.
|
|
||||||
function Initialize-NativeApi {
|
|
||||||
if (-not ('Dsh.TokenInfo' -as [type])) {
|
|
||||||
Add-Type -Namespace Dsh -Name TokenInfo -MemberDefinition @'
|
|
||||||
[StructLayout(LayoutKind.Sequential)]
|
|
||||||
public struct SID_AND_ATTRIBUTES { public IntPtr Sid; public uint Attributes; }
|
|
||||||
[StructLayout(LayoutKind.Sequential)]
|
|
||||||
public struct TOKEN_MANDATORY_LABEL { public SID_AND_ATTRIBUTES Label; }
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern bool GetTokenInformation(IntPtr token, int infoClass, IntPtr info, uint length, out uint returned);
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern IntPtr GetSidSubAuthority(IntPtr sid, uint index);
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
|
|
||||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
||||||
private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFileW(
|
|
||||||
string path, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
|
|
||||||
// OPEN_EXISTING never creates or changes contents. Windows evaluates the caller's
|
|
||||||
// effective access, including group attributes, denies, ownership and inheritance.
|
|
||||||
public static bool HasAccess(string path, uint access) {
|
|
||||||
using (var handle = CreateFileW(path, access, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero)) {
|
|
||||||
if (!handle.IsInvalid) { return true; }
|
|
||||||
int error = Marshal.GetLastWin32Error();
|
|
||||||
if (error == 5) { return false; }
|
|
||||||
throw new System.ComponentModel.Win32Exception(error, "CreateFileW access check: " + path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
|
|
||||||
private static extern uint SetNamedSecurityInfoW(string path, int type, uint information,
|
|
||||||
IntPtr owner, IntPtr group, byte[] dacl, IntPtr sacl);
|
|
||||||
public static void SetDacl(string path, string sddl) {
|
|
||||||
var descriptor = new System.Security.AccessControl.RawSecurityDescriptor(sddl);
|
|
||||||
byte[] dacl = null;
|
|
||||||
if (descriptor.DiscretionaryAcl != null) {
|
|
||||||
dacl = new byte[descriptor.DiscretionaryAcl.BinaryLength];
|
|
||||||
descriptor.DiscretionaryAcl.GetBinaryForm(dacl, 0);
|
|
||||||
}
|
|
||||||
bool isProtected = (descriptor.ControlFlags & System.Security.AccessControl.ControlFlags.DiscretionaryAclProtected) != 0;
|
|
||||||
// Only the DACL and its inheritance protection are written: never owner, group or SACL.
|
|
||||||
uint result = SetNamedSecurityInfoW(path, 1, 4u | (isProtected ? 0x80000000u : 0x20000000u),
|
|
||||||
IntPtr.Zero, IntPtr.Zero, dacl, IntPtr.Zero);
|
|
||||||
if (result != 0) { throw new System.ComponentModel.Win32Exception((int)result, "Write DACL: " + path); }
|
|
||||||
}
|
|
||||||
public static int Level(IntPtr token) {
|
|
||||||
uint length;
|
|
||||||
GetTokenInformation(token, 25, IntPtr.Zero, 0, out length);
|
|
||||||
if (length == 0) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Read integrity information length"); }
|
|
||||||
IntPtr buffer = Marshal.AllocHGlobal((int)length);
|
|
||||||
try {
|
|
||||||
if (!GetTokenInformation(token, 25, buffer, length, out length)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Read integrity information"); }
|
|
||||||
IntPtr sid = Marshal.PtrToStructure<TOKEN_MANDATORY_LABEL>(buffer).Label.Sid;
|
|
||||||
byte count = Marshal.ReadByte(GetSidSubAuthorityCount(sid));
|
|
||||||
return Marshal.ReadInt32(GetSidSubAuthority(sid, (uint)(count - 1)));
|
|
||||||
} finally { Marshal.FreeHGlobal(buffer); }
|
|
||||||
}
|
|
||||||
'@
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-IntegritySid {
|
|
||||||
try {
|
|
||||||
$level = [Dsh.TokenInfo]::Level([System.Security.Principal.WindowsIdentity]::GetCurrent().Token)
|
|
||||||
switch ($level) {
|
|
||||||
0 { return 'S-1-16-0 (Untrusted)' }
|
|
||||||
4096 { return 'S-1-16-4096 (Low)' }
|
|
||||||
8192 { return 'S-1-16-8192 (Medium)' }
|
|
||||||
12288 { return 'S-1-16-12288 (High)' }
|
|
||||||
16384 { return 'S-1-16-16384 (System)' }
|
|
||||||
default { return "S-1-16-$level (unrecognized level)" }
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
Write-Report observation integrity '' unknown 'The token integrity level could not be read; do not infer that the caller is elevated or confined.' @{ error = (Get-HResultChain $_.Exception) }
|
|
||||||
return 'unknown'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-NormalizedPath {
|
|
||||||
param([string]$Value)
|
|
||||||
$full = [System.IO.Path]::GetFullPath($Value)
|
|
||||||
$root = [System.IO.Path]::GetPathRoot($full)
|
|
||||||
if ($full.Length -le $root.Length) { return $root }
|
|
||||||
return $full.TrimEnd('\', '/')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Test-DangerousRoot {
|
|
||||||
param([string]$FullPath)
|
|
||||||
$trimmed = (Get-NormalizedPath $FullPath).TrimEnd('\')
|
|
||||||
if ($trimmed -match '^[A-Za-z]:$') { return 'drive root' }
|
|
||||||
if ($trimmed -ieq ([System.IO.Path]::GetFullPath($env:USERPROFILE).TrimEnd('\'))) { return 'user profile root' }
|
|
||||||
if ($trimmed -ieq ([System.IO.Path]::GetFullPath($env:WINDIR).TrimEnd('\'))) { return 'Windows directory' }
|
|
||||||
foreach ($entry in @(
|
|
||||||
@{ directory = $env:LOCALAPPDATA; child = 'Packages' },
|
|
||||||
@{ directory = $env:ProgramFiles; child = 'WindowsApps' },
|
|
||||||
@{ directory = $env:ProgramW6432; child = 'WindowsApps' }
|
|
||||||
)) {
|
|
||||||
if (-not $entry.directory) { continue }
|
|
||||||
$protected = Get-NormalizedPath (Join-Path $entry.directory $entry.child)
|
|
||||||
if ($trimmed -ieq $protected -or (Test-UnderRoot $trimmed $protected)) { return 'managed application directory' }
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
function Test-UnderRoot {
|
|
||||||
param([string]$FullPath, [string]$Root, [switch]$AllowEqual)
|
|
||||||
$r = Get-NormalizedPath $Root
|
|
||||||
$c = Get-NormalizedPath $FullPath
|
|
||||||
if ($AllowEqual -and $c -ieq $r) { return $true }
|
|
||||||
return $c -ine $r -and $c.StartsWith($r.TrimEnd('\') + '\', [System.StringComparison]::OrdinalIgnoreCase)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-RepairRefusal {
|
|
||||||
param([string]$FullPath, [string]$Root, [switch]$AllowEqual)
|
|
||||||
if (-not (Test-UnderRoot -FullPath $FullPath -Root $Root -AllowEqual:$AllowEqual)) { return "$FullPath is outside -AllowRoot" }
|
|
||||||
$danger = Test-DangerousRoot -FullPath $FullPath
|
|
||||||
if ($danger) { return "$FullPath is a $danger" }
|
|
||||||
# Checking every component also covers a junction used as AllowRoot itself.
|
|
||||||
foreach ($component in (Get-Ancestors -FullPath $FullPath)) {
|
|
||||||
$item = Get-Item -LiteralPath $component -Force
|
|
||||||
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
|
|
||||||
return "$FullPath traverses a reparse point: $component"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
# A caller that cannot provision a directory also cannot confine a child anywhere
|
|
||||||
# under it, so one approved run examines that subtree for explicit package allow
|
|
||||||
# ACEs instead of leaving them for a second call. Directories only: DSH grants and
|
|
||||||
# traverses directories, and no reparse point or managed application tree is entered.
|
|
||||||
function Get-SubtreePackageSources {
|
|
||||||
param([string]$Root, [int]$Limit)
|
|
||||||
$sources = @()
|
|
||||||
$visited = 0
|
|
||||||
$enqueued = 0
|
|
||||||
$failed = 0
|
|
||||||
$truncated = $false
|
|
||||||
$queue = [System.Collections.Generic.Queue[string]]::new()
|
|
||||||
# Unreadable directories are skipped, never guessed at: the caller reports the count.
|
|
||||||
try {
|
|
||||||
foreach ($child in [System.IO.Directory]::EnumerateDirectories($Root)) {
|
|
||||||
if ($enqueued -ge $Limit) { $truncated = $true; break }
|
|
||||||
$queue.Enqueue($child); $enqueued++
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
while ($queue.Count -gt 0) {
|
|
||||||
if ($visited -ge $Limit) { $truncated = $true; break }
|
|
||||||
$current = $queue.Dequeue()
|
|
||||||
$visited++
|
|
||||||
if (Test-DangerousRoot -FullPath $current) { continue }
|
|
||||||
$item = Get-Item -LiteralPath $current -Force -ErrorAction SilentlyContinue
|
|
||||||
if ($null -eq $item) { $failed++; continue }
|
|
||||||
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }
|
|
||||||
try {
|
|
||||||
$acl = Get-Acl -LiteralPath $current
|
|
||||||
foreach ($rule in $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])) {
|
|
||||||
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -match $PACKAGE_SID) { $sources += $current; break }
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
try {
|
|
||||||
foreach ($child in [System.IO.Directory]::EnumerateDirectories($current)) {
|
|
||||||
if ($enqueued -ge $Limit) { $truncated = $true; break }
|
|
||||||
$queue.Enqueue($child); $enqueued++
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
}
|
|
||||||
return [ordered]@{ sources = @($sources); visited = $visited; truncated = $truncated; failed = $failed }
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-OwnDaclSddl {
|
|
||||||
param([string]$Sddl)
|
|
||||||
# Inherited ACEs follow their parent: repeating them in a saved DACL forces them
|
|
||||||
# back onto the object on restore and stops matching once the parent re-derives
|
|
||||||
# them. Keep the observed control flags so the result still carries the
|
|
||||||
# object's inheritance protection, and keep every ACE the object owns.
|
|
||||||
$flags = [regex]::Match($Sddl, '^D:([A-Z]*)').Groups[1].Value
|
|
||||||
$aces = @([regex]::Matches($Sddl, '\([^()]*\)') | ForEach-Object { $_.Value } | Where-Object { ($_ -split ';')[1] -notmatch 'ID' })
|
|
||||||
return 'D:{0}{1}' -f $flags, ($aces -join '')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-AceSet {
|
|
||||||
param([string]$Sddl)
|
|
||||||
return @([regex]::Matches($Sddl, '\([^()]*\)') | ForEach-Object { $_.Value } | Sort-Object)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Save-AclBackup {
|
|
||||||
param([string]$FullPath, [string]$Directory, [string]$Root)
|
|
||||||
$fullDirectory = [System.IO.Path]::GetFullPath($Directory)
|
|
||||||
if (-not (Test-Path -LiteralPath $fullDirectory)) {
|
|
||||||
Invoke-ReportedOperation create_backup_directory $fullDirectory 'The requested recovery directory does not exist; create it before writing backup files.' files {
|
|
||||||
New-Item -ItemType Directory -Path $fullDirectory | Out-Null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$record = Join-Path $fullDirectory ('acl-backup-{0}.json' -f ([guid]::NewGuid().ToString('N')))
|
|
||||||
# The skill's extracted directory expires with its registration. Recovery must
|
|
||||||
# remain runnable from the recovery directory after that registration is gone.
|
|
||||||
$restoreScript = $record + '.ps1'
|
|
||||||
$command = "pwsh -NoProfile -File '{0}' -Path '{1}' -AllowRoot '{2}' -Restore '{3}'" -f
|
|
||||||
$restoreScript.Replace("'", "''"), $FullPath.Replace("'", "''"), ([System.IO.Path]::GetFullPath($Root)).Replace("'", "''"), $record.Replace("'", "''")
|
|
||||||
Write-Report decision backup $FullPath selected 'The recovery record and an independent recovery script are written before the ACL change.' @{ files = @($record, $restoreScript) }
|
|
||||||
Invoke-ReportedOperation backup $FullPath 'Save the original DACL and an independent recovery command before changing permissions.' files {
|
|
||||||
$backupAcl = Get-Acl -LiteralPath $FullPath
|
|
||||||
$observed = $backupAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
|
|
||||||
@{
|
|
||||||
Path = $FullPath
|
|
||||||
Dacl = Get-OwnDaclSddl -Sddl $observed
|
|
||||||
Protected = $backupAcl.AreAccessRulesProtected
|
|
||||||
Observed = $observed
|
|
||||||
} | ConvertTo-Json | Set-Content -LiteralPath $record -Encoding utf8
|
|
||||||
Copy-Item -LiteralPath $PSCommandPath -Destination $restoreScript
|
|
||||||
}
|
|
||||||
$script:recoveries.Add(@{ path = $FullPath; record = $record; script = $restoreScript; command = $command; attempted = $false; restored = $false })
|
|
||||||
Write-Report observation recovery $FullPath available 'These files can restore the saved DACL; no rollback has been executed.' $script:recoveries[-1]
|
|
||||||
Write-Line ('BACKUP {0} -> {1}' -f $FullPath, $record)
|
|
||||||
Write-Line ('ROLLBACK {0}' -f $command)
|
|
||||||
}
|
|
||||||
function Restore-SavedDacl {
|
|
||||||
param([string]$FullPath, [string]$Record, [string]$Root)
|
|
||||||
$refusal = Get-RepairRefusal -FullPath $FullPath -Root $Root -AllowEqual
|
|
||||||
if ($refusal) { throw [System.ArgumentException]::new("RESTORE_REFUSED $refusal") }
|
|
||||||
$saved = Invoke-ReportedOperation read_recovery $Record 'Read the recovery record and verify it belongs to the requested path before restoring its DACL.' none {
|
|
||||||
Get-Content -LiteralPath $Record -Raw | ConvertFrom-Json
|
|
||||||
}
|
|
||||||
if ($saved.Path -isnot [string] -or $saved.Path -ine $FullPath -or $saved.Dacl -isnot [string]) {
|
|
||||||
throw [System.ArgumentException]::new('RESTORE_REFUSED backup does not describe the requested path')
|
|
||||||
}
|
|
||||||
if (-not [Dsh.TokenInfo]::HasAccess($FullPath, 0x40000)) { throw 'RESTORE_REFUSED the caller lacks WRITE_DAC' }
|
|
||||||
Invoke-ReportedOperation restore_dacl $FullPath 'Restore the requested backup DACL and inheritance protection, preserving owner and SACL.' acl {
|
|
||||||
[Dsh.TokenInfo]::SetDacl($FullPath, $saved.Dacl)
|
|
||||||
}
|
|
||||||
$restoredAcl = Invoke-ReportedOperation read_restored_dacl $FullPath 'Read the restored DACL to compare it with the saved record.' none {
|
|
||||||
Get-Acl -LiteralPath $FullPath
|
|
||||||
}
|
|
||||||
# Inherited entries follow the parent, so the same object can render a different
|
|
||||||
# full DACL before and after a correct restore. Compare the own ACEs and the
|
|
||||||
# protection state, which the restore owns.
|
|
||||||
$restoredProtected = $restoredAcl.AreAccessRulesProtected
|
|
||||||
$actual = Get-OwnDaclSddl -Sddl $restoredAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
|
|
||||||
$expectedAces = Get-AceSet -Sddl $saved.Dacl
|
|
||||||
$actualAces = Get-AceSet -Sddl $actual
|
|
||||||
$restored = (@($expectedAces) -join "`n") -eq (@($actualAces) -join "`n") -and $restoredProtected -eq [bool]$saved.Protected
|
|
||||||
Write-Report verification restore $FullPath $(if ($restored) { 'verified' } else { 'failed' }) 'Compare the restored own ACEs and protection state with the recovery record.' @{ expectedAces = @($expectedAces); actualAces = @($actualAces); protected = $restoredProtected; expectedProtected = [bool]$saved.Protected }
|
|
||||||
if (-not $restored) { throw 'RESTORE_FAILED the restored DACL differs from the backup' }
|
|
||||||
$script:restored++
|
|
||||||
Write-Line ('RESTORED {0}' -f $FullPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-ObjectFacts {
|
|
||||||
param([string]$FullPath, [string]$MeSid, [switch]$CompactRecord)
|
|
||||||
$facts = [ordered]@{
|
|
||||||
Object = $FullPath
|
|
||||||
Readable = $false
|
|
||||||
Error = ''
|
|
||||||
PackageAces = @()
|
|
||||||
OtherAppContainerSids = @()
|
|
||||||
Owner = ''
|
|
||||||
OwnerIsMe = $false
|
|
||||||
MyRights = ''
|
|
||||||
HasWriteDac = $null
|
|
||||||
HasWriteOwner = $null
|
|
||||||
Aces = @()
|
|
||||||
Errors = @()
|
|
||||||
LowLabel = $null
|
|
||||||
AclLines = @()
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
# Get-Acl reads the security descriptor directly. On .NET Core the
|
|
||||||
# FileSystemInfo.GetAccessControl() form is an extension method, which
|
|
||||||
# PowerShell cannot invoke with instance syntax.
|
|
||||||
$acl = Get-Acl -LiteralPath $FullPath
|
|
||||||
$facts.Readable = $true
|
|
||||||
} catch {
|
|
||||||
$facts.Error = Get-HResultChain -Exception $_.Exception
|
|
||||||
Write-Report observation inspect_acl $FullPath unreadable 'The ACL read failed; permissions and the cause of denial remain unknown.' @{ error = $facts.Error }
|
|
||||||
return $facts
|
|
||||||
}
|
|
||||||
foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
|
|
||||||
$sid = $rule.IdentityReference.Value
|
|
||||||
$facts.Aces += [ordered]@{
|
|
||||||
sid = $sid; type = [string]$rule.AccessControlType; rights = [string]$rule.FileSystemRights
|
|
||||||
inherited = $rule.IsInherited; inheritance = [string]$rule.InheritanceFlags; propagation = [string]$rule.PropagationFlags
|
|
||||||
}
|
|
||||||
if ($sid -match $PACKAGE_SID -and $rule.AccessControlType -eq 'Allow') {
|
|
||||||
$facts.PackageAces += ('SID={0} INHERITED={1} INHERITABLE={2} RIGHTS={3}' -f $sid, $rule.IsInherited, $rule.InheritanceFlags, $rule.FileSystemRights)
|
|
||||||
} elseif ($sid -match '^S-1-15-' -and $sid -notmatch $PACKAGE_SID) {
|
|
||||||
$facts.OtherAppContainerSids += $sid
|
|
||||||
}
|
|
||||||
if ($sid -eq $MeSid -and $rule.AccessControlType -eq 'Allow') {
|
|
||||||
$facts.MyRights = ($facts.MyRights + ';' + [string]$rule.FileSystemRights).Trim(';')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$facts.Owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
|
|
||||||
$facts.OwnerIsMe = ($facts.Owner -eq $MeSid)
|
|
||||||
} catch {
|
|
||||||
$facts.Owner = 'unreadable'
|
|
||||||
$facts.Errors += @{ operation = 'read_owner'; error = (Get-HResultChain $_.Exception) }
|
|
||||||
}
|
|
||||||
foreach ($check in @(@{ field = 'HasWriteDac'; mask = 0x40000 }, @{ field = 'HasWriteOwner'; mask = 0x80000 })) {
|
|
||||||
try { $facts[$check.field] = [Dsh.TokenInfo]::HasAccess($FullPath, $check.mask) }
|
|
||||||
catch { $facts.Errors += @{ operation = $check.field; error = (Get-HResultChain $_.Exception) } }
|
|
||||||
}
|
|
||||||
# The mandatory label lives in the SACL. Reading the SACL needs a privilege while
|
|
||||||
# icacls prints the label without one, but icacls renders it by name, which is
|
|
||||||
# localized: try the integrity SID first and keep the English name as a fallback.
|
|
||||||
try {
|
|
||||||
$facts.AclLines = @(icacls $FullPath 2>&1 | ForEach-Object { [string]$_ })
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "icacls exit ${LASTEXITCODE}: $($facts.AclLines -join "`n")" }
|
|
||||||
$text = $facts.AclLines -join "`n"
|
|
||||||
# An unrecognized localized label is unknown, not evidence of a Low label.
|
|
||||||
if ($text -match $LOW_LABEL_SID -or $text -match 'Mandatory Label\\Low Mandatory Level') { $facts.LowLabel = $true }
|
|
||||||
} catch {
|
|
||||||
$facts.Errors += @{ operation = 'icacls'; error = (Get-HResultChain $_.Exception) }
|
|
||||||
}
|
|
||||||
Write-Report observation inspect_acl $FullPath $(if ($facts.Errors.Count) { 'partial' } else { 'read' }) 'Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.' @{
|
|
||||||
owner = $facts.Owner; writeDac = $facts.HasWriteDac; writeOwner = $facts.HasWriteOwner
|
|
||||||
# A re-read after a change repeats an ACL this run already recorded: keep the
|
|
||||||
# full ACE list in memory, but do not print it twice.
|
|
||||||
aces = $(if ($CompactRecord) { @() } else { $facts.Aces }); acesOmitted = [bool]$CompactRecord
|
|
||||||
lowLabel = $facts.LowLabel; errors = $facts.Errors
|
|
||||||
}
|
|
||||||
return $facts
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-Ancestors {
|
|
||||||
param([string]$FullPath)
|
|
||||||
$list = @()
|
|
||||||
$current = Get-NormalizedPath $FullPath
|
|
||||||
while ($true) {
|
|
||||||
$list += $current
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($current)
|
|
||||||
if ([string]::IsNullOrEmpty($parent) -or $parent -eq $current) { break }
|
|
||||||
$current = $parent
|
|
||||||
}
|
|
||||||
return $list
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- main ---------------------------------------------------------------
|
|
||||||
|
|
||||||
$operations = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$recoveries = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$reports = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$reportPath = $null
|
|
||||||
$reportWriter = $null
|
|
||||||
$requestedPaths = @()
|
|
||||||
$rollbackStatus = 'not-needed'
|
|
||||||
$fixed = 0
|
|
||||||
$granted = 0
|
|
||||||
$refused = 0
|
|
||||||
$restored = 0
|
|
||||||
$exitCode = 0
|
|
||||||
$observationFailures = 0
|
|
||||||
$scanTruncated = $false
|
|
||||||
$currentPath = ''
|
|
||||||
$mode = if ($Restore) { 'restore' } else { 'repair' }
|
|
||||||
|
|
||||||
try {
|
|
||||||
$requestedPaths = @($Path | ForEach-Object { [System.IO.Path]::GetFullPath($_) })
|
|
||||||
Write-Report invocation $mode '' started 'Inspect the requested paths, then repair the ACL problems this run can prove, before anything else is attempted.' @{
|
|
||||||
paths = $Path; allowRoot = $AllowRoot; outputDirectory = $Out; recoveryRecord = $Restore
|
|
||||||
}
|
|
||||||
if (-not $AllowRoot) { throw [System.ArgumentException]::new('Every modification requires -AllowRoot') }
|
|
||||||
if (-not $Restore -and -not $Out) { throw [System.ArgumentException]::new('A repair requires -Out for its recovery artifacts') }
|
|
||||||
if ($Restore -and $Path.Count -ne 1) { throw [System.ArgumentException]::new('-Restore requires exactly one -Path') }
|
|
||||||
if ($Out) {
|
|
||||||
Invoke-ReportedOperation prepare_report $Out 'Create the recovery directory and a new JSONL report that keeps every record, because tool output is truncated to its tail.' files {
|
|
||||||
$directory = [System.IO.Path]::GetFullPath($Out)
|
|
||||||
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
|
|
||||||
$script:reportPath = Join-Path $directory ('acl-report-{0}.jsonl' -f [guid]::NewGuid().ToString('N'))
|
|
||||||
$stream = [System.IO.File]::Open($script:reportPath, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write)
|
|
||||||
$script:reportWriter = [System.IO.StreamWriter]::new($stream, [System.Text.UTF8Encoding]::new($false))
|
|
||||||
foreach ($record in $script:reports) { $script:reportWriter.WriteLine(($record | ConvertTo-Json -Depth 12 -Compress)) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$identity = Get-CurrentIdentity
|
|
||||||
$meSid = $identity.User.Value
|
|
||||||
Invoke-ReportedOperation initialize '' 'Load read-only access checks and DACL-only writes before inspecting permissions.' none { Initialize-NativeApi }
|
|
||||||
$integrity = Get-IntegritySid
|
|
||||||
Write-Line ('CALLER SID={0} INTEGRITY={1}' -f $meSid, $integrity)
|
|
||||||
Write-Report observation caller '' read 'The caller token determines effective access; unconfined execution does not imply elevation.' @{ sid = $meSid; integrity = $integrity }
|
|
||||||
:paths foreach ($requested in $Path) {
|
|
||||||
$currentPath = $requested
|
|
||||||
$full = Get-NormalizedPath $requested
|
|
||||||
$currentPath = $full
|
|
||||||
Write-Line ('PATH={0}' -f $full)
|
|
||||||
if (-not (Test-Path -LiteralPath $full)) {
|
|
||||||
Write-Line ' MISSING'
|
|
||||||
Write-Line 'VERDICT=NOT_THIS_CLASS'
|
|
||||||
Write-Decision $mode $full skipped 'The requested path does not exist; no ACL was read or changed for it.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
|
|
||||||
$factsByPath = @{}
|
|
||||||
$inspectOrder = @()
|
|
||||||
$packageTargets = @()
|
|
||||||
$targetFacts = $null
|
|
||||||
foreach ($ancestor in (Get-Ancestors -FullPath $full)) {
|
|
||||||
if (-not (Test-Path -LiteralPath $ancestor)) { continue }
|
|
||||||
$facts = Get-ObjectFacts -FullPath $ancestor -MeSid $meSid
|
|
||||||
$factsByPath[$facts.Object] = $facts
|
|
||||||
$inspectOrder += $facts.Object
|
|
||||||
if ($ancestor -eq $full) { $targetFacts = $facts }
|
|
||||||
Write-Line (' OBJECT={0} READABLE={1}{2}' -f $facts.Object, $facts.Readable, $(if ($facts.Readable) { '' } else { ' ERROR=' + $facts.Error }))
|
|
||||||
if ($facts.Readable) {
|
|
||||||
Write-Line (' OWNER={0} IS_CURRENT_USER={1} MY_RIGHTS=[{2}] WRITE_DAC={3} WRITE_OWNER={4} LOW_LABEL={5}' -f $facts.Owner, $facts.OwnerIsMe, $facts.MyRights, $facts.HasWriteDac, $facts.HasWriteOwner, $facts.LowLabel)
|
|
||||||
foreach ($ace in $facts.PackageAces) { Write-Line (' PACKAGE_ACE {0}' -f $ace) }
|
|
||||||
foreach ($sid in ($facts.OtherAppContainerSids | Sort-Object -Unique)) { Write-Line (' OTHER_S1_15 SID={0} (reported only)' -f $sid) }
|
|
||||||
}
|
|
||||||
if ($facts.PackageAces.Count -gt 0) { $packageTargets += $facts.Object }
|
|
||||||
}
|
|
||||||
|
|
||||||
# The precondition is judged on the requested path itself. Ancestors above the
|
|
||||||
# tree DSH grants are not part of that grant, so their ownership and rights would
|
|
||||||
# otherwise mark every healthy path as a precondition failure.
|
|
||||||
if ($null -eq $targetFacts) { throw "The requested path disappeared before its ACL could be inspected: $full" }
|
|
||||||
$unreadable = -not $targetFacts.Readable
|
|
||||||
$needsPrecondition = (-not $unreadable) -and
|
|
||||||
((-not $targetFacts.HasWriteDac) -or (-not $targetFacts.HasWriteOwner))
|
|
||||||
|
|
||||||
# A directory the caller cannot provision is the workspace root half the time: the sandbox
|
|
||||||
# reports its own failure there while the conflicting entry sits deeper. Examine that
|
|
||||||
# subtree before the verdict so the classification and its packageObjects describe what
|
|
||||||
# this run will actually repair.
|
|
||||||
$ownsRoot = $full -ieq (Get-NormalizedPath $AllowRoot)
|
|
||||||
if (-not $Restore -and $targetFacts.Errors.Count -eq 0 -and [System.IO.Directory]::Exists($full) -and ($needsPrecondition -or $ownsRoot)) {
|
|
||||||
$scan = Get-SubtreePackageSources -Root $full -Limit $SCAN_LIMIT
|
|
||||||
foreach ($object in $scan.sources) {
|
|
||||||
if ($packageTargets -notcontains $object) { $packageTargets += $object }
|
|
||||||
if (-not $factsByPath.ContainsKey($object)) {
|
|
||||||
$scanned = Get-ObjectFacts -FullPath $object -MeSid $meSid
|
|
||||||
$factsByPath[$scanned.Object] = $scanned
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Write-Report observation subtree_scan $full $(if ($scan.failed -gt 0) { 'partial' } else { 'read' }) 'The caller cannot provision this directory, or it is the authorized root, so explicit package allow ACEs under it were collected in the same run; no reparse point or managed application tree is entered.' @{
|
|
||||||
visited = $scan.visited; packageSources = @($scan.sources); truncated = [bool]$scan.truncated; unreadable = [int]$scan.failed
|
|
||||||
}
|
|
||||||
Write-Line ('SCAN {0} VISITED={1} PACKAGE_SOURCES={2}{3}{4}' -f $full, $scan.visited, @($scan.sources).Count, $(if ($scan.truncated) { ' TRUNCATED' } else { '' }), $(if ($scan.failed -gt 0) { " UNREADABLE=$($scan.failed)" } else { '' }))
|
|
||||||
if ($scan.truncated) { $script:scanTruncated = $true }
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($targetFacts.Errors.Count -gt 0) {
|
|
||||||
$verdict = 'INCOMPLETE'
|
|
||||||
$reason = 'Some observations failed; missing evidence is not evidence that a right is absent or a repair is safe.'
|
|
||||||
} elseif ($packageTargets.Count -gt 0) {
|
|
||||||
$blocked = @($packageTargets | Where-Object { -not $factsByPath[$_].HasWriteDac })
|
|
||||||
$verdict = if ($needsPrecondition -or $blocked.Count -gt 0) { 'BOTH' } else { 'CULPRIT' }
|
|
||||||
$reason = 'Package allow ACEs were observed. Required access checks determine whether the caller can perform the requested repair; other causes remain possible.'
|
|
||||||
} elseif ($unreadable) {
|
|
||||||
$verdict = 'UNREADABLE'
|
|
||||||
$reason = 'The requested ACL could not be read; its entries and the cause of denial are unknown.'
|
|
||||||
} elseif ($needsPrecondition) {
|
|
||||||
$verdict = 'PRECONDITION'
|
|
||||||
$reason = 'The caller cannot open the requested object with both WRITE_DAC and WRITE_OWNER. The reported allow and deny ACEs are evidence, not an attribution to one rule.'
|
|
||||||
} else {
|
|
||||||
$verdict = 'NOT_THIS_CLASS'
|
|
||||||
$reason = 'No package allow ACE was observed and both required rights are available. Other ACL restrictions and causes of the original failure are not ruled out.'
|
|
||||||
}
|
|
||||||
Write-Line ('VERDICT={0}' -f $verdict)
|
|
||||||
Write-Report decision classify $full $verdict $reason @{ writeDac = $targetFacts.HasWriteDac; writeOwner = $targetFacts.HasWriteOwner; packageObjects = @($packageTargets) }
|
|
||||||
|
|
||||||
if ($Restore) {
|
|
||||||
Restore-SavedDacl -FullPath $full -Record $Restore -Root $AllowRoot
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ($targetFacts.Errors.Count -gt 0) {
|
|
||||||
Write-Decision $mode $full refused 'Required observations are incomplete; no repair was attempted for this path.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
|
|
||||||
# Nothing is changed while a package source or a grant target is out of reach: a
|
|
||||||
# repair that cannot finish would leave the tree half repaired before refusing.
|
|
||||||
foreach ($packagePath in $packageTargets) {
|
|
||||||
$refusal = Get-RepairRefusal -FullPath $packagePath -Root $AllowRoot -AllowEqual
|
|
||||||
if ($refusal) { Write-Line ('REPAIR_REFUSED {0}' -f $refusal); Write-Decision $mode $packagePath refused $refusal; $refused++; break paths }
|
|
||||||
if ($factsByPath[$packagePath].Errors.Count -gt 0) {
|
|
||||||
Write-Decision $mode $packagePath refused 'The ACL observations are incomplete; collateral changes could not be verified.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Missing WRITE_DAC or WRITE_OWNER on a directory in the chain is what stops DSH
|
|
||||||
# from provisioning the workspace grant. One approved run repairs every such
|
|
||||||
# directory, including the authorized root itself.
|
|
||||||
$grantTargets = @($inspectOrder | Where-Object {
|
|
||||||
[System.IO.Directory]::Exists($_) -and $factsByPath[$_].Readable -and $factsByPath[$_].Errors.Count -eq 0 -and
|
|
||||||
((-not $factsByPath[$_].HasWriteDac) -or (-not $factsByPath[$_].HasWriteOwner)) -and
|
|
||||||
-not (Get-RepairRefusal -FullPath $_ -Root $AllowRoot -AllowEqual)
|
|
||||||
})
|
|
||||||
# Writing a DACL needs WRITE_DAC: refuse a target that lacks it before anything is
|
|
||||||
# changed, instead of failing mid-repair and marking a recovery for an object that
|
|
||||||
# the rollback then cannot restore either.
|
|
||||||
foreach ($object in $grantTargets) {
|
|
||||||
if (-not $factsByPath[$object].HasWriteDac) {
|
|
||||||
Write-Line ('REPAIR_REFUSED {0} needs WRITE_DAC; stop for permission-policy review' -f $object)
|
|
||||||
Write-Decision $mode $object refused 'Effective WRITE_DAC is absent; adding the grant requires that right.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($grantTargets.Count -gt 0) {
|
|
||||||
Write-Report decision grant_targets $full selected 'These directories lack effective WRITE_DAC or WRITE_OWNER; each is backed up, then receives a FullControl allow ACE for the current user.' @{ paths = @($grantTargets) }
|
|
||||||
}
|
|
||||||
foreach ($object in $grantTargets) {
|
|
||||||
$grantBefore = $factsByPath[$object]
|
|
||||||
Save-AclBackup -FullPath $object -Directory $Out -Root $AllowRoot
|
|
||||||
$grantAcl = Get-Acl -LiteralPath $object
|
|
||||||
$grantAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
||||||
[System.Security.Principal.SecurityIdentifier]::new($meSid),
|
|
||||||
[System.Security.AccessControl.FileSystemRights]::FullControl,
|
|
||||||
[System.Security.AccessControl.AccessControlType]::Allow))
|
|
||||||
Invoke-ReportedOperation grant_dacl $object "WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for $meSid while preserving deny ACEs, owner and SACL." acl {
|
|
||||||
[Dsh.TokenInfo]::SetDacl($object, $grantAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access))
|
|
||||||
}
|
|
||||||
$grantAfter = Get-ObjectFacts -FullPath $object -MeSid $meSid -CompactRecord
|
|
||||||
$factsByPath[$object] = $grantAfter
|
|
||||||
$verified = $grantAfter.Readable -and $grantAfter.Errors.Count -eq 0 -and $grantAfter.HasWriteDac -and $grantAfter.HasWriteOwner
|
|
||||||
Write-Report verification grant $object $(if ($verified) { 'verified' } else { 'failed' }) 'The DACL write completed; recheck effective access before claiming that provisioning can succeed. On failure, restore this invocation and stop.' @{
|
|
||||||
before = @{ writeDac = $grantBefore.HasWriteDac; writeOwner = $grantBefore.HasWriteOwner }
|
|
||||||
after = @{ writeDac = $grantAfter.HasWriteDac; writeOwner = $grantAfter.HasWriteOwner }
|
|
||||||
recovery = $recoveries[-1].command
|
|
||||||
}
|
|
||||||
if ($verified) {
|
|
||||||
Write-Line ('GRANTED {0} SID={1}' -f $object, $meSid); $granted++
|
|
||||||
} else {
|
|
||||||
Write-Line ('GRANT_FAILED {0}; effective WRITE_DAC and WRITE_OWNER were not both confirmed; restore this invocation and stop' -f $object)
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$sources = @($packageTargets | Where-Object {
|
|
||||||
@($factsByPath[$_].Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited }).Count -gt 0
|
|
||||||
})
|
|
||||||
# Ancestor first, for chain and scan-discovered sources alike.
|
|
||||||
$sources = @($sources | Sort-Object -Property @{ Expression = { $_.Split([char]92).Count } }, @{ Expression = { $_ } })
|
|
||||||
foreach ($source in $sources) {
|
|
||||||
if (-not $factsByPath[$source].HasWriteDac) {
|
|
||||||
Write-Line ('REPAIR_REFUSED {0} needs WRITE_DAC; stop for permission-policy review' -f $source)
|
|
||||||
Write-Decision $mode $source refused 'Effective WRITE_DAC is absent; removing a package allow ACE requires that right.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($sources.Count -gt 0) {
|
|
||||||
Write-Report decision remove_package_sources $full selected 'Remove explicit package allow ACEs from their sources, ancestor first, leaving inheritance enabled so inherited copies follow their repaired source.' @{
|
|
||||||
sources = @($sources); affectedPaths = @($packageTargets)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach ($source in $sources) {
|
|
||||||
Save-AclBackup -FullPath $source -Directory $Out -Root $AllowRoot
|
|
||||||
$sids = @($factsByPath[$source].Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited } | ForEach-Object { $_.sid } | Sort-Object -Unique)
|
|
||||||
foreach ($sid in $sids) {
|
|
||||||
Invoke-ReportedOperation remove_package_allow $source "Remove the observed package allow ACE for $sid; preserve deny ACEs and all other principals." acl {
|
|
||||||
$output = @(icacls $source /remove:g "*$sid" 2>&1)
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "icacls removal exit $($LASTEXITCODE): $($output -join [char]10)" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# A package deny can share the removed allow's SID; only allow ACEs were removed.
|
|
||||||
foreach ($packagePath in $packageTargets) {
|
|
||||||
$fixBefore = $factsByPath[$packagePath]
|
|
||||||
$fixAfter = Get-ObjectFacts -FullPath $packagePath -MeSid $meSid -CompactRecord
|
|
||||||
# Compare the object's own ACEs as sorted sets: listing order and inherited
|
|
||||||
# entries follow the parent, so neither proves a collateral change.
|
|
||||||
$rowOf = { param($ace) '{0}|{1}|{2}|{3}|{4}' -f $ace.type, $ace.sid, $ace.rights, $ace.inheritance, $ace.propagation }
|
|
||||||
$ownAfter = @($fixAfter.Aces | Where-Object { -not $_.inherited } | ForEach-Object { & $rowOf $_ } | Sort-Object)
|
|
||||||
$expectedOwn = @($fixBefore.Aces | Where-Object { -not $_.inherited -and -not ($_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID) } | ForEach-Object { & $rowOf $_ } | Sort-Object)
|
|
||||||
$collateral = (@($expectedOwn) -join [char]10) -eq (@($ownAfter) -join [char]10)
|
|
||||||
$verified = $fixAfter.Readable -and $fixAfter.Errors.Count -eq 0 -and $fixAfter.PackageAces.Count -eq 0 -and $collateral
|
|
||||||
Write-Report verification fix $packagePath $(if ($verified) { 'verified' } else { 'failed' }) 'The removal command completed; verify that package allow ACEs disappeared and other own ACEs remained unchanged. On failure, restore this invocation and stop.' @{
|
|
||||||
remainingPackageAces = $fixAfter.PackageAces; otherEntriesUnchanged = $collateral
|
|
||||||
}
|
|
||||||
if ($verified) {
|
|
||||||
$removedSids = @($fixBefore.Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited } | ForEach-Object { $_.sid } | Sort-Object -Unique)
|
|
||||||
foreach ($sid in $removedSids) {
|
|
||||||
Write-Line ('FIXED {0} SID={1}' -f $packagePath, $sid); $fixed++
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write-Line ('FIX_FAILED {0} collateral_change={1}' -f $packagePath, (-not $collateral))
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($packageTargets.Count -eq 0 -and $grantTargets.Count -eq 0) {
|
|
||||||
Write-Decision $mode $full skipped 'No package allow ACE and no missing WRITE_DAC or WRITE_OWNER was observed on the inspected objects; no ACL change was needed.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
$exitCode = if ($_.Exception -is [System.ArgumentException]) { 2 } else { 1 }
|
|
||||||
Write-Report error $mode $currentPath stopped 'Execution stopped after an exception. An interrupted write may have changed state; attempted repairs will be restored before the final summary.' @{ error = (Get-HResultChain $_.Exception); location = $_.InvocationInfo.PositionMessage }
|
|
||||||
} finally {
|
|
||||||
if ($refused -gt 0 -and $exitCode -eq 0) { $exitCode = 2 }
|
|
||||||
if ($exitCode -ne 0 -and -not $Restore) {
|
|
||||||
for ($i = $recoveries.Count - 1; $i -ge 0; $i--) {
|
|
||||||
$recovery = $recoveries[$i]
|
|
||||||
if (-not $recovery.attempted) { continue }
|
|
||||||
Write-Decision rollback $recovery.path selected 'The repair failed; restore every attempted DACL change from this invocation in reverse order before stopping.'
|
|
||||||
try {
|
|
||||||
Restore-SavedDacl -FullPath $recovery.path -Record $recovery.record -Root $AllowRoot
|
|
||||||
$recovery.restored = $true
|
|
||||||
$rollbackStatus = 'verified'
|
|
||||||
} catch {
|
|
||||||
$rollbackStatus = 'failed'
|
|
||||||
Write-Report error rollback $recovery.path stopped 'Recovery was not verified. Stop repairs and retain the pending recovery commands in reverse order.' @{ error = (Get-HResultChain $_.Exception) }
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$pending = @($recoveries | Where-Object { $_.attempted -and -not $_.restored } | ForEach-Object { $_.command })
|
|
||||||
[array]::Reverse($pending)
|
|
||||||
$repaired = ($fixed + $granted) -gt 0
|
|
||||||
$nextAction = if ($rollbackStatus -eq 'failed') { 'restore_pending_then_stop' } elseif ($exitCode -ne 0 -or $observationFailures -gt 0) { 'stop' } elseif ($repaired) { 'verify_original_confined_operation' } else { 'stop' }
|
|
||||||
# The tool keeps only the tail of stdout. Recapitulate the decisions here so the
|
|
||||||
# records a reader needs survive truncation; the report file holds every record.
|
|
||||||
$recap = [ordered]@{
|
|
||||||
verdicts = @($reports | Where-Object { $_.operation -eq 'classify' } | ForEach-Object {
|
|
||||||
@{ path = $_.path; verdict = $_.status; writeDac = $_.details['writeDac']; writeOwner = $_.details['writeOwner']; packageObjects = $_.details['packageObjects'] }
|
|
||||||
})
|
|
||||||
changes = @($reports | Where-Object { $_.kind -eq 'action' -and $_.details['effect'] -eq 'acl' -and $_.status -eq 'completed' } | ForEach-Object { @{ operation = $_.operation; path = $_.path } })
|
|
||||||
verifications = @($reports | Where-Object { $_.kind -eq 'verification' } | ForEach-Object { @{ operation = $_.operation; path = $_.path; status = $_.status } })
|
|
||||||
refusals = @($reports | Where-Object { $_.kind -eq 'decision' -and $_.status -eq 'refused' } | ForEach-Object { @{ path = $_.path; reason = $_.reason } })
|
|
||||||
scans = @($reports | Where-Object { $_.operation -eq 'subtree_scan' } | ForEach-Object {
|
|
||||||
@{ path = $_.path; visited = $_.details['visited']; packageSources = @($_.details['packageSources']); truncated = $_.details['truncated']; unreadable = $_.details['unreadable'] }
|
|
||||||
})
|
|
||||||
report = $reportPath
|
|
||||||
}
|
|
||||||
$status = if ($exitCode -ne 0) { 'failed' } elseif ($observationFailures -gt 0) { 'partial' } else { 'completed' }
|
|
||||||
Write-Report summary $mode $currentPath $status 'Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved.' @{
|
|
||||||
exitCode = $exitCode; fixed = $fixed; granted = $granted; refused = $refused; restored = $restored
|
|
||||||
operations = @($operations.ToArray()); recoveries = @($recoveries.ToArray()); automaticRollback = $true; observationFailures = $observationFailures
|
|
||||||
rollback = $rollbackStatus; rollbackCommands = $pending; nextAction = $nextAction; scanTruncated = $scanTruncated; report = $reportPath
|
|
||||||
}
|
|
||||||
# Last on stdout, after the summary record: whatever the tool truncates, the tail
|
|
||||||
# still carries the decisions, the report path and the counts.
|
|
||||||
Write-Line ('RECAP ' + ($recap | ConvertTo-Json -Depth 8 -Compress))
|
|
||||||
if ($reportPath) { Write-Line ('REPORT_FILE {0}' -f $reportPath) }
|
|
||||||
Write-Line ('SUMMARY FIXED={0} GRANTED={1} REFUSED={2} RESTORED={3}' -f $fixed, $granted, $refused, $restored)
|
|
||||||
if ($reportWriter) { $reportWriter.Dispose() }
|
|
||||||
}
|
|
||||||
exit $exitCode
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"Dacl": "D:AI",
|
|
||||||
"Protected": false,
|
|
||||||
"Observed": "D:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)(A;OICIIOID;GA;;;SY)(A;ID;0x1301bf;;;AU)(A;OICIIOID;SDGXGWGR;;;AU)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;BU)",
|
|
||||||
"Path": "D:\\PricingReview\\CostReview"
|
|
||||||
}
|
|
||||||
@@ -1,798 +0,0 @@
|
|||||||
<#
|
|
||||||
.SYNOPSIS
|
|
||||||
Diagnose the DSH sandbox ACL failures on Windows and repair them in one run.
|
|
||||||
|
|
||||||
.DESCRIPTION
|
|
||||||
A denial inside the DSH sandbox is worth diagnosing only when it contradicts
|
|
||||||
what the active mode promises: writes inside the workspace, or reads that the
|
|
||||||
signed-in user should plainly have. One invocation reads each requested path
|
|
||||||
and every ancestor, then repairs what it can in the same run:
|
|
||||||
|
|
||||||
* every directory on that chain inside -AllowRoot that lacks effective
|
|
||||||
WRITE_DAC or WRITE_OWNER gets a FullControl allow ACE for the current
|
|
||||||
user, so the sandbox can provision the grant it needs; and
|
|
||||||
* every explicit AppContainer package allow ACE (S-1-15-2-*, excluding the
|
|
||||||
well-known groups ending in 1 or 2) is removed at its source, ancestor
|
|
||||||
first, which also removes that package's access to the tree.
|
|
||||||
|
|
||||||
A directory the caller cannot provision is the state the sandbox reports on the
|
|
||||||
workspace root, while the conflicting entry often sits deeper; the authorized root
|
|
||||||
is examined for the same reason. For either case the same run also collects explicit
|
|
||||||
package allow ACEs under the requested directory, so they do not need a second call.
|
|
||||||
The walk is bounded, enters no reparse point or managed application tree, and reports
|
|
||||||
truncation and unreadable directories instead of claiming a complete walk.
|
|
||||||
|
|
||||||
Every observation, change, verification and recovery command is printed as it
|
|
||||||
happens, so one run shows the caller the complete set of actions.
|
|
||||||
|
|
||||||
-AllowRoot bounds every change: an object is modified only when it is that
|
|
||||||
directory or strictly inside it, so a caller can repair its own workspace
|
|
||||||
root. Reparse paths and managed application trees are refused. Each modified
|
|
||||||
object is backed up first, with an independent recovery script, and every DACL
|
|
||||||
write is verified by re-reading it. A failed repair restores all attempted
|
|
||||||
DACL changes from this invocation in reverse order and stops.
|
|
||||||
|
|
||||||
The script never creates, deletes, or writes the contents of any file. Its
|
|
||||||
only writes are the recovery artifacts under -Out and the DACLs it repairs.
|
|
||||||
|
|
||||||
.PARAMETER Path
|
|
||||||
One or more failing paths. Each is diagnosed and repaired together with its ancestors.
|
|
||||||
|
|
||||||
.PARAMETER AllowRoot
|
|
||||||
Required. Every modified object must be this directory or strictly inside it.
|
|
||||||
|
|
||||||
.PARAMETER Out
|
|
||||||
Required for a repair. Receives one recovery record and one recovery script
|
|
||||||
per change, so an object repaired twice keeps both recovery points.
|
|
||||||
|
|
||||||
.PARAMETER Restore
|
|
||||||
Restore the DACL recovery record for exactly one -Path instead of repairing.
|
|
||||||
Requires -AllowRoot and WRITE_DAC, preserves owner and SACL.
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
pwsh -File diagnose-windows-sandbox-acl.ps1 -Path '<failing path>' -AllowRoot '<authorized directory>' -Out '<recovery directory>'
|
|
||||||
|
|
||||||
.EXAMPLE
|
|
||||||
pwsh -File diagnose-windows-sandbox-acl.ps1 -Path '<failing path>' -AllowRoot '<authorized directory>' -Restore '<recovery record>'
|
|
||||||
#>
|
|
||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory = $true)][string[]]$Path,
|
|
||||||
[string]$AllowRoot,
|
|
||||||
[string]$Out,
|
|
||||||
[string]$Restore
|
|
||||||
)
|
|
||||||
|
|
||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
# These two well-known groups name all packages, not one conflicting package.
|
|
||||||
$PACKAGE_SID = '^S-1-15-2-(?![12]$)'
|
|
||||||
$LOW_LABEL_SID = 'S-1-16-4096'
|
|
||||||
# Upper bound on the directories one subtree scan may visit, so a huge workspace
|
|
||||||
# cannot turn one approved repair into an unbounded walk. Truncation is reported.
|
|
||||||
$SCAN_LIMIT = 2000
|
|
||||||
|
|
||||||
function Write-Line { param([string]$Text) Write-Output $Text }
|
|
||||||
|
|
||||||
# Reports bypass the success pipeline so diagnostics cannot become a function's
|
|
||||||
# return value. Each JSON record occupies one stdout line, including paths/errors.
|
|
||||||
function Write-Report {
|
|
||||||
param([string]$Kind, [string]$Operation, [string]$Target, [string]$Status, [string]$Reason, $Details = @{})
|
|
||||||
$record = [ordered]@{ kind = $Kind; operation = $Operation; path = $Target; status = $Status; reason = $Reason; details = $Details }
|
|
||||||
if ($Kind -eq 'observation' -and $Status -in @('unknown', 'unreadable', 'partial')) { $script:observationFailures++ }
|
|
||||||
$script:reports.Add($record)
|
|
||||||
$json = $record | ConvertTo-Json -Depth 12 -Compress
|
|
||||||
# The complete record set also lands in the report file: tool output is truncated to its
|
|
||||||
# tail, so a long run's early records survive only there.
|
|
||||||
if ($null -ne $script:reportWriter) {
|
|
||||||
try { $script:reportWriter.WriteLine($json); $script:reportWriter.Flush() }
|
|
||||||
catch [System.IO.IOException] {
|
|
||||||
# stdout keeps only its tail, so this file is the complete record: a write failure
|
|
||||||
# has to reach the caller, on stderr, instead of leaving a silently incomplete file.
|
|
||||||
[Console]::Error.WriteLine('REPORT_IO_FAILED {0}: {1}' -f $script:reportPath, $_.Exception.Message)
|
|
||||||
try { $script:reportWriter.Dispose() } catch { }
|
|
||||||
$script:reportWriter = $null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[Console]::Out.WriteLine('REPORT ' + $json)
|
|
||||||
}
|
|
||||||
function Invoke-ReportedOperation {
|
|
||||||
param([string]$Operation, [string]$Target, [string]$Reason, [string]$Effect, [scriptblock]$Action)
|
|
||||||
$entry = [ordered]@{ id = $script:operations.Count + 1; operation = $Operation; path = $Target; effect = $Effect; status = 'started' }
|
|
||||||
$script:operations.Add($entry)
|
|
||||||
if ($Effect -eq 'acl' -and $Operation -ne 'restore_dacl' -and $script:recoveries.Count -gt 0) {
|
|
||||||
$script:recoveries[-1].attempted = $true
|
|
||||||
}
|
|
||||||
Write-Report action $Operation $Target started $Reason @{ id = $entry.id; effect = $Effect }
|
|
||||||
try {
|
|
||||||
$result = & $Action
|
|
||||||
$entry.status = 'completed'
|
|
||||||
Write-Report action $Operation $Target completed $Reason @{ id = $entry.id; effect = $Effect }
|
|
||||||
return $result
|
|
||||||
} catch {
|
|
||||||
$entry.status = 'failed'
|
|
||||||
Write-Report action $Operation $Target failed $Reason @{
|
|
||||||
id = $entry.id; effect = $Effect; error = (Get-HResultChain $_.Exception)
|
|
||||||
state = $(if ($Effect -eq 'none') { 'No mutation requested by this operation.' } else { 'The operation may have partially changed state; completion is unconfirmed.' })
|
|
||||||
}
|
|
||||||
throw
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-Decision {
|
|
||||||
param([string]$Operation, [string]$Target, [string]$Status, [string]$Reason)
|
|
||||||
Write-Report decision $Operation $Target $Status $Reason
|
|
||||||
}
|
|
||||||
|
|
||||||
# Unwrap nested exceptions: PowerShell wraps Win32 failures, and only the inner
|
|
||||||
# exception carries the real HRESULT the caller needs to classify the failure.
|
|
||||||
function Get-HResultChain {
|
|
||||||
param([System.Exception]$Exception)
|
|
||||||
$chain = @()
|
|
||||||
$e = $Exception
|
|
||||||
while ($null -ne $e) {
|
|
||||||
$chain += ('{0}=0x{1:X8}/win32={2}: {3}' -f $e.GetType().Name, $e.HResult, ($e.HResult -band 0xFFFF), $e.Message)
|
|
||||||
$e = $e.InnerException
|
|
||||||
}
|
|
||||||
return ($chain -join ' <- ')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-CurrentIdentity {
|
|
||||||
return [System.Security.Principal.WindowsIdentity]::GetCurrent()
|
|
||||||
}
|
|
||||||
|
|
||||||
# Integrity level affects the symptom: the same foreign
|
|
||||||
# ACE fails a grant when the caller is below Medium and merely blocks the child
|
|
||||||
# when the caller is not.
|
|
||||||
# The integrity level lives in the token's group list, which .NET filters out of
|
|
||||||
# WindowsIdentity.Groups, so read it through GetTokenInformation. Add-Type compiles
|
|
||||||
# in-process on PowerShell 7. Never spawn whoami.exe for this: inside a below-Medium
|
|
||||||
# token that process fails to initialize (STATUS_DLL_INIT_FAILED, 0xc0000142) and
|
|
||||||
# raises an application-error dialog on the user's desktop.
|
|
||||||
function Initialize-NativeApi {
|
|
||||||
if (-not ('Dsh.TokenInfo' -as [type])) {
|
|
||||||
Add-Type -Namespace Dsh -Name TokenInfo -MemberDefinition @'
|
|
||||||
[StructLayout(LayoutKind.Sequential)]
|
|
||||||
public struct SID_AND_ATTRIBUTES { public IntPtr Sid; public uint Attributes; }
|
|
||||||
[StructLayout(LayoutKind.Sequential)]
|
|
||||||
public struct TOKEN_MANDATORY_LABEL { public SID_AND_ATTRIBUTES Label; }
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern bool GetTokenInformation(IntPtr token, int infoClass, IntPtr info, uint length, out uint returned);
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern IntPtr GetSidSubAuthority(IntPtr sid, uint index);
|
|
||||||
[DllImport("advapi32.dll", SetLastError = true)]
|
|
||||||
public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
|
|
||||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
||||||
private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFileW(
|
|
||||||
string path, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
|
|
||||||
// OPEN_EXISTING never creates or changes contents. Windows evaluates the caller's
|
|
||||||
// effective access, including group attributes, denies, ownership and inheritance.
|
|
||||||
public static bool HasAccess(string path, uint access) {
|
|
||||||
using (var handle = CreateFileW(path, access, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero)) {
|
|
||||||
if (!handle.IsInvalid) { return true; }
|
|
||||||
int error = Marshal.GetLastWin32Error();
|
|
||||||
if (error == 5) { return false; }
|
|
||||||
throw new System.ComponentModel.Win32Exception(error, "CreateFileW access check: " + path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
|
|
||||||
private static extern uint SetNamedSecurityInfoW(string path, int type, uint information,
|
|
||||||
IntPtr owner, IntPtr group, byte[] dacl, IntPtr sacl);
|
|
||||||
public static void SetDacl(string path, string sddl) {
|
|
||||||
var descriptor = new System.Security.AccessControl.RawSecurityDescriptor(sddl);
|
|
||||||
byte[] dacl = null;
|
|
||||||
if (descriptor.DiscretionaryAcl != null) {
|
|
||||||
dacl = new byte[descriptor.DiscretionaryAcl.BinaryLength];
|
|
||||||
descriptor.DiscretionaryAcl.GetBinaryForm(dacl, 0);
|
|
||||||
}
|
|
||||||
bool isProtected = (descriptor.ControlFlags & System.Security.AccessControl.ControlFlags.DiscretionaryAclProtected) != 0;
|
|
||||||
// Only the DACL and its inheritance protection are written: never owner, group or SACL.
|
|
||||||
uint result = SetNamedSecurityInfoW(path, 1, 4u | (isProtected ? 0x80000000u : 0x20000000u),
|
|
||||||
IntPtr.Zero, IntPtr.Zero, dacl, IntPtr.Zero);
|
|
||||||
if (result != 0) { throw new System.ComponentModel.Win32Exception((int)result, "Write DACL: " + path); }
|
|
||||||
}
|
|
||||||
public static int Level(IntPtr token) {
|
|
||||||
uint length;
|
|
||||||
GetTokenInformation(token, 25, IntPtr.Zero, 0, out length);
|
|
||||||
if (length == 0) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Read integrity information length"); }
|
|
||||||
IntPtr buffer = Marshal.AllocHGlobal((int)length);
|
|
||||||
try {
|
|
||||||
if (!GetTokenInformation(token, 25, buffer, length, out length)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Read integrity information"); }
|
|
||||||
IntPtr sid = Marshal.PtrToStructure<TOKEN_MANDATORY_LABEL>(buffer).Label.Sid;
|
|
||||||
byte count = Marshal.ReadByte(GetSidSubAuthorityCount(sid));
|
|
||||||
return Marshal.ReadInt32(GetSidSubAuthority(sid, (uint)(count - 1)));
|
|
||||||
} finally { Marshal.FreeHGlobal(buffer); }
|
|
||||||
}
|
|
||||||
'@
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-IntegritySid {
|
|
||||||
try {
|
|
||||||
$level = [Dsh.TokenInfo]::Level([System.Security.Principal.WindowsIdentity]::GetCurrent().Token)
|
|
||||||
switch ($level) {
|
|
||||||
0 { return 'S-1-16-0 (Untrusted)' }
|
|
||||||
4096 { return 'S-1-16-4096 (Low)' }
|
|
||||||
8192 { return 'S-1-16-8192 (Medium)' }
|
|
||||||
12288 { return 'S-1-16-12288 (High)' }
|
|
||||||
16384 { return 'S-1-16-16384 (System)' }
|
|
||||||
default { return "S-1-16-$level (unrecognized level)" }
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
Write-Report observation integrity '' unknown 'The token integrity level could not be read; do not infer that the caller is elevated or confined.' @{ error = (Get-HResultChain $_.Exception) }
|
|
||||||
return 'unknown'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-NormalizedPath {
|
|
||||||
param([string]$Value)
|
|
||||||
$full = [System.IO.Path]::GetFullPath($Value)
|
|
||||||
$root = [System.IO.Path]::GetPathRoot($full)
|
|
||||||
if ($full.Length -le $root.Length) { return $root }
|
|
||||||
return $full.TrimEnd('\', '/')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Test-DangerousRoot {
|
|
||||||
param([string]$FullPath)
|
|
||||||
$trimmed = (Get-NormalizedPath $FullPath).TrimEnd('\')
|
|
||||||
if ($trimmed -match '^[A-Za-z]:$') { return 'drive root' }
|
|
||||||
if ($trimmed -ieq ([System.IO.Path]::GetFullPath($env:USERPROFILE).TrimEnd('\'))) { return 'user profile root' }
|
|
||||||
if ($trimmed -ieq ([System.IO.Path]::GetFullPath($env:WINDIR).TrimEnd('\'))) { return 'Windows directory' }
|
|
||||||
foreach ($entry in @(
|
|
||||||
@{ directory = $env:LOCALAPPDATA; child = 'Packages' },
|
|
||||||
@{ directory = $env:ProgramFiles; child = 'WindowsApps' },
|
|
||||||
@{ directory = $env:ProgramW6432; child = 'WindowsApps' }
|
|
||||||
)) {
|
|
||||||
if (-not $entry.directory) { continue }
|
|
||||||
$protected = Get-NormalizedPath (Join-Path $entry.directory $entry.child)
|
|
||||||
if ($trimmed -ieq $protected -or (Test-UnderRoot $trimmed $protected)) { return 'managed application directory' }
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
function Test-UnderRoot {
|
|
||||||
param([string]$FullPath, [string]$Root, [switch]$AllowEqual)
|
|
||||||
$r = Get-NormalizedPath $Root
|
|
||||||
$c = Get-NormalizedPath $FullPath
|
|
||||||
if ($AllowEqual -and $c -ieq $r) { return $true }
|
|
||||||
return $c -ine $r -and $c.StartsWith($r.TrimEnd('\') + '\', [System.StringComparison]::OrdinalIgnoreCase)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-RepairRefusal {
|
|
||||||
param([string]$FullPath, [string]$Root, [switch]$AllowEqual)
|
|
||||||
if (-not (Test-UnderRoot -FullPath $FullPath -Root $Root -AllowEqual:$AllowEqual)) { return "$FullPath is outside -AllowRoot" }
|
|
||||||
$danger = Test-DangerousRoot -FullPath $FullPath
|
|
||||||
if ($danger) { return "$FullPath is a $danger" }
|
|
||||||
# Checking every component also covers a junction used as AllowRoot itself.
|
|
||||||
foreach ($component in (Get-Ancestors -FullPath $FullPath)) {
|
|
||||||
$item = Get-Item -LiteralPath $component -Force
|
|
||||||
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
|
|
||||||
return "$FullPath traverses a reparse point: $component"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
# A caller that cannot provision a directory also cannot confine a child anywhere
|
|
||||||
# under it, so one approved run examines that subtree for explicit package allow
|
|
||||||
# ACEs instead of leaving them for a second call. Directories only: DSH grants and
|
|
||||||
# traverses directories, and no reparse point or managed application tree is entered.
|
|
||||||
function Get-SubtreePackageSources {
|
|
||||||
param([string]$Root, [int]$Limit)
|
|
||||||
$sources = @()
|
|
||||||
$visited = 0
|
|
||||||
$enqueued = 0
|
|
||||||
$failed = 0
|
|
||||||
$truncated = $false
|
|
||||||
$queue = [System.Collections.Generic.Queue[string]]::new()
|
|
||||||
# Unreadable directories are skipped, never guessed at: the caller reports the count.
|
|
||||||
try {
|
|
||||||
foreach ($child in [System.IO.Directory]::EnumerateDirectories($Root)) {
|
|
||||||
if ($enqueued -ge $Limit) { $truncated = $true; break }
|
|
||||||
$queue.Enqueue($child); $enqueued++
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
while ($queue.Count -gt 0) {
|
|
||||||
if ($visited -ge $Limit) { $truncated = $true; break }
|
|
||||||
$current = $queue.Dequeue()
|
|
||||||
$visited++
|
|
||||||
if (Test-DangerousRoot -FullPath $current) { continue }
|
|
||||||
$item = Get-Item -LiteralPath $current -Force -ErrorAction SilentlyContinue
|
|
||||||
if ($null -eq $item) { $failed++; continue }
|
|
||||||
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }
|
|
||||||
try {
|
|
||||||
$acl = Get-Acl -LiteralPath $current
|
|
||||||
foreach ($rule in $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])) {
|
|
||||||
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -match $PACKAGE_SID) { $sources += $current; break }
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
try {
|
|
||||||
foreach ($child in [System.IO.Directory]::EnumerateDirectories($current)) {
|
|
||||||
if ($enqueued -ge $Limit) { $truncated = $true; break }
|
|
||||||
$queue.Enqueue($child); $enqueued++
|
|
||||||
}
|
|
||||||
} catch [System.UnauthorizedAccessException] { $failed++ }
|
|
||||||
catch [System.IO.IOException] { $failed++ }
|
|
||||||
}
|
|
||||||
return [ordered]@{ sources = @($sources); visited = $visited; truncated = $truncated; failed = $failed }
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-OwnDaclSddl {
|
|
||||||
param([string]$Sddl)
|
|
||||||
# Inherited ACEs follow their parent: repeating them in a saved DACL forces them
|
|
||||||
# back onto the object on restore and stops matching once the parent re-derives
|
|
||||||
# them. Keep the observed control flags so the result still carries the
|
|
||||||
# object's inheritance protection, and keep every ACE the object owns.
|
|
||||||
$flags = [regex]::Match($Sddl, '^D:([A-Z]*)').Groups[1].Value
|
|
||||||
$aces = @([regex]::Matches($Sddl, '\([^()]*\)') | ForEach-Object { $_.Value } | Where-Object { ($_ -split ';')[1] -notmatch 'ID' })
|
|
||||||
return 'D:{0}{1}' -f $flags, ($aces -join '')
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-AceSet {
|
|
||||||
param([string]$Sddl)
|
|
||||||
return @([regex]::Matches($Sddl, '\([^()]*\)') | ForEach-Object { $_.Value } | Sort-Object)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Save-AclBackup {
|
|
||||||
param([string]$FullPath, [string]$Directory, [string]$Root)
|
|
||||||
$fullDirectory = [System.IO.Path]::GetFullPath($Directory)
|
|
||||||
if (-not (Test-Path -LiteralPath $fullDirectory)) {
|
|
||||||
Invoke-ReportedOperation create_backup_directory $fullDirectory 'The requested recovery directory does not exist; create it before writing backup files.' files {
|
|
||||||
New-Item -ItemType Directory -Path $fullDirectory | Out-Null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$record = Join-Path $fullDirectory ('acl-backup-{0}.json' -f ([guid]::NewGuid().ToString('N')))
|
|
||||||
# The skill's extracted directory expires with its registration. Recovery must
|
|
||||||
# remain runnable from the recovery directory after that registration is gone.
|
|
||||||
$restoreScript = $record + '.ps1'
|
|
||||||
$command = "pwsh -NoProfile -File '{0}' -Path '{1}' -AllowRoot '{2}' -Restore '{3}'" -f
|
|
||||||
$restoreScript.Replace("'", "''"), $FullPath.Replace("'", "''"), ([System.IO.Path]::GetFullPath($Root)).Replace("'", "''"), $record.Replace("'", "''")
|
|
||||||
Write-Report decision backup $FullPath selected 'The recovery record and an independent recovery script are written before the ACL change.' @{ files = @($record, $restoreScript) }
|
|
||||||
Invoke-ReportedOperation backup $FullPath 'Save the original DACL and an independent recovery command before changing permissions.' files {
|
|
||||||
$backupAcl = Get-Acl -LiteralPath $FullPath
|
|
||||||
$observed = $backupAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
|
|
||||||
@{
|
|
||||||
Path = $FullPath
|
|
||||||
Dacl = Get-OwnDaclSddl -Sddl $observed
|
|
||||||
Protected = $backupAcl.AreAccessRulesProtected
|
|
||||||
Observed = $observed
|
|
||||||
} | ConvertTo-Json | Set-Content -LiteralPath $record -Encoding utf8
|
|
||||||
Copy-Item -LiteralPath $PSCommandPath -Destination $restoreScript
|
|
||||||
}
|
|
||||||
$script:recoveries.Add(@{ path = $FullPath; record = $record; script = $restoreScript; command = $command; attempted = $false; restored = $false })
|
|
||||||
Write-Report observation recovery $FullPath available 'These files can restore the saved DACL; no rollback has been executed.' $script:recoveries[-1]
|
|
||||||
Write-Line ('BACKUP {0} -> {1}' -f $FullPath, $record)
|
|
||||||
Write-Line ('ROLLBACK {0}' -f $command)
|
|
||||||
}
|
|
||||||
function Restore-SavedDacl {
|
|
||||||
param([string]$FullPath, [string]$Record, [string]$Root)
|
|
||||||
$refusal = Get-RepairRefusal -FullPath $FullPath -Root $Root -AllowEqual
|
|
||||||
if ($refusal) { throw [System.ArgumentException]::new("RESTORE_REFUSED $refusal") }
|
|
||||||
$saved = Invoke-ReportedOperation read_recovery $Record 'Read the recovery record and verify it belongs to the requested path before restoring its DACL.' none {
|
|
||||||
Get-Content -LiteralPath $Record -Raw | ConvertFrom-Json
|
|
||||||
}
|
|
||||||
if ($saved.Path -isnot [string] -or $saved.Path -ine $FullPath -or $saved.Dacl -isnot [string]) {
|
|
||||||
throw [System.ArgumentException]::new('RESTORE_REFUSED backup does not describe the requested path')
|
|
||||||
}
|
|
||||||
if (-not [Dsh.TokenInfo]::HasAccess($FullPath, 0x40000)) { throw 'RESTORE_REFUSED the caller lacks WRITE_DAC' }
|
|
||||||
Invoke-ReportedOperation restore_dacl $FullPath 'Restore the requested backup DACL and inheritance protection, preserving owner and SACL.' acl {
|
|
||||||
[Dsh.TokenInfo]::SetDacl($FullPath, $saved.Dacl)
|
|
||||||
}
|
|
||||||
$restoredAcl = Invoke-ReportedOperation read_restored_dacl $FullPath 'Read the restored DACL to compare it with the saved record.' none {
|
|
||||||
Get-Acl -LiteralPath $FullPath
|
|
||||||
}
|
|
||||||
# Inherited entries follow the parent, so the same object can render a different
|
|
||||||
# full DACL before and after a correct restore. Compare the own ACEs and the
|
|
||||||
# protection state, which the restore owns.
|
|
||||||
$restoredProtected = $restoredAcl.AreAccessRulesProtected
|
|
||||||
$actual = Get-OwnDaclSddl -Sddl $restoredAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
|
|
||||||
$expectedAces = Get-AceSet -Sddl $saved.Dacl
|
|
||||||
$actualAces = Get-AceSet -Sddl $actual
|
|
||||||
$restored = (@($expectedAces) -join "`n") -eq (@($actualAces) -join "`n") -and $restoredProtected -eq [bool]$saved.Protected
|
|
||||||
Write-Report verification restore $FullPath $(if ($restored) { 'verified' } else { 'failed' }) 'Compare the restored own ACEs and protection state with the recovery record.' @{ expectedAces = @($expectedAces); actualAces = @($actualAces); protected = $restoredProtected; expectedProtected = [bool]$saved.Protected }
|
|
||||||
if (-not $restored) { throw 'RESTORE_FAILED the restored DACL differs from the backup' }
|
|
||||||
$script:restored++
|
|
||||||
Write-Line ('RESTORED {0}' -f $FullPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-ObjectFacts {
|
|
||||||
param([string]$FullPath, [string]$MeSid, [switch]$CompactRecord)
|
|
||||||
$facts = [ordered]@{
|
|
||||||
Object = $FullPath
|
|
||||||
Readable = $false
|
|
||||||
Error = ''
|
|
||||||
PackageAces = @()
|
|
||||||
OtherAppContainerSids = @()
|
|
||||||
Owner = ''
|
|
||||||
OwnerIsMe = $false
|
|
||||||
MyRights = ''
|
|
||||||
HasWriteDac = $null
|
|
||||||
HasWriteOwner = $null
|
|
||||||
Aces = @()
|
|
||||||
Errors = @()
|
|
||||||
LowLabel = $null
|
|
||||||
AclLines = @()
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
# Get-Acl reads the security descriptor directly. On .NET Core the
|
|
||||||
# FileSystemInfo.GetAccessControl() form is an extension method, which
|
|
||||||
# PowerShell cannot invoke with instance syntax.
|
|
||||||
$acl = Get-Acl -LiteralPath $FullPath
|
|
||||||
$facts.Readable = $true
|
|
||||||
} catch {
|
|
||||||
$facts.Error = Get-HResultChain -Exception $_.Exception
|
|
||||||
Write-Report observation inspect_acl $FullPath unreadable 'The ACL read failed; permissions and the cause of denial remain unknown.' @{ error = $facts.Error }
|
|
||||||
return $facts
|
|
||||||
}
|
|
||||||
foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
|
|
||||||
$sid = $rule.IdentityReference.Value
|
|
||||||
$facts.Aces += [ordered]@{
|
|
||||||
sid = $sid; type = [string]$rule.AccessControlType; rights = [string]$rule.FileSystemRights
|
|
||||||
inherited = $rule.IsInherited; inheritance = [string]$rule.InheritanceFlags; propagation = [string]$rule.PropagationFlags
|
|
||||||
}
|
|
||||||
if ($sid -match $PACKAGE_SID -and $rule.AccessControlType -eq 'Allow') {
|
|
||||||
$facts.PackageAces += ('SID={0} INHERITED={1} INHERITABLE={2} RIGHTS={3}' -f $sid, $rule.IsInherited, $rule.InheritanceFlags, $rule.FileSystemRights)
|
|
||||||
} elseif ($sid -match '^S-1-15-' -and $sid -notmatch $PACKAGE_SID) {
|
|
||||||
$facts.OtherAppContainerSids += $sid
|
|
||||||
}
|
|
||||||
if ($sid -eq $MeSid -and $rule.AccessControlType -eq 'Allow') {
|
|
||||||
$facts.MyRights = ($facts.MyRights + ';' + [string]$rule.FileSystemRights).Trim(';')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$facts.Owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
|
|
||||||
$facts.OwnerIsMe = ($facts.Owner -eq $MeSid)
|
|
||||||
} catch {
|
|
||||||
$facts.Owner = 'unreadable'
|
|
||||||
$facts.Errors += @{ operation = 'read_owner'; error = (Get-HResultChain $_.Exception) }
|
|
||||||
}
|
|
||||||
foreach ($check in @(@{ field = 'HasWriteDac'; mask = 0x40000 }, @{ field = 'HasWriteOwner'; mask = 0x80000 })) {
|
|
||||||
try { $facts[$check.field] = [Dsh.TokenInfo]::HasAccess($FullPath, $check.mask) }
|
|
||||||
catch { $facts.Errors += @{ operation = $check.field; error = (Get-HResultChain $_.Exception) } }
|
|
||||||
}
|
|
||||||
# The mandatory label lives in the SACL. Reading the SACL needs a privilege while
|
|
||||||
# icacls prints the label without one, but icacls renders it by name, which is
|
|
||||||
# localized: try the integrity SID first and keep the English name as a fallback.
|
|
||||||
try {
|
|
||||||
$facts.AclLines = @(icacls $FullPath 2>&1 | ForEach-Object { [string]$_ })
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "icacls exit ${LASTEXITCODE}: $($facts.AclLines -join "`n")" }
|
|
||||||
$text = $facts.AclLines -join "`n"
|
|
||||||
# An unrecognized localized label is unknown, not evidence of a Low label.
|
|
||||||
if ($text -match $LOW_LABEL_SID -or $text -match 'Mandatory Label\\Low Mandatory Level') { $facts.LowLabel = $true }
|
|
||||||
} catch {
|
|
||||||
$facts.Errors += @{ operation = 'icacls'; error = (Get-HResultChain $_.Exception) }
|
|
||||||
}
|
|
||||||
Write-Report observation inspect_acl $FullPath $(if ($facts.Errors.Count) { 'partial' } else { 'read' }) 'Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.' @{
|
|
||||||
owner = $facts.Owner; writeDac = $facts.HasWriteDac; writeOwner = $facts.HasWriteOwner
|
|
||||||
# A re-read after a change repeats an ACL this run already recorded: keep the
|
|
||||||
# full ACE list in memory, but do not print it twice.
|
|
||||||
aces = $(if ($CompactRecord) { @() } else { $facts.Aces }); acesOmitted = [bool]$CompactRecord
|
|
||||||
lowLabel = $facts.LowLabel; errors = $facts.Errors
|
|
||||||
}
|
|
||||||
return $facts
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-Ancestors {
|
|
||||||
param([string]$FullPath)
|
|
||||||
$list = @()
|
|
||||||
$current = Get-NormalizedPath $FullPath
|
|
||||||
while ($true) {
|
|
||||||
$list += $current
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($current)
|
|
||||||
if ([string]::IsNullOrEmpty($parent) -or $parent -eq $current) { break }
|
|
||||||
$current = $parent
|
|
||||||
}
|
|
||||||
return $list
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- main ---------------------------------------------------------------
|
|
||||||
|
|
||||||
$operations = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$recoveries = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$reports = [System.Collections.Generic.List[object]]::new()
|
|
||||||
$reportPath = $null
|
|
||||||
$reportWriter = $null
|
|
||||||
$requestedPaths = @()
|
|
||||||
$rollbackStatus = 'not-needed'
|
|
||||||
$fixed = 0
|
|
||||||
$granted = 0
|
|
||||||
$refused = 0
|
|
||||||
$restored = 0
|
|
||||||
$exitCode = 0
|
|
||||||
$observationFailures = 0
|
|
||||||
$scanTruncated = $false
|
|
||||||
$currentPath = ''
|
|
||||||
$mode = if ($Restore) { 'restore' } else { 'repair' }
|
|
||||||
|
|
||||||
try {
|
|
||||||
$requestedPaths = @($Path | ForEach-Object { [System.IO.Path]::GetFullPath($_) })
|
|
||||||
Write-Report invocation $mode '' started 'Inspect the requested paths, then repair the ACL problems this run can prove, before anything else is attempted.' @{
|
|
||||||
paths = $Path; allowRoot = $AllowRoot; outputDirectory = $Out; recoveryRecord = $Restore
|
|
||||||
}
|
|
||||||
if (-not $AllowRoot) { throw [System.ArgumentException]::new('Every modification requires -AllowRoot') }
|
|
||||||
if (-not $Restore -and -not $Out) { throw [System.ArgumentException]::new('A repair requires -Out for its recovery artifacts') }
|
|
||||||
if ($Restore -and $Path.Count -ne 1) { throw [System.ArgumentException]::new('-Restore requires exactly one -Path') }
|
|
||||||
if ($Out) {
|
|
||||||
Invoke-ReportedOperation prepare_report $Out 'Create the recovery directory and a new JSONL report that keeps every record, because tool output is truncated to its tail.' files {
|
|
||||||
$directory = [System.IO.Path]::GetFullPath($Out)
|
|
||||||
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
|
|
||||||
$script:reportPath = Join-Path $directory ('acl-report-{0}.jsonl' -f [guid]::NewGuid().ToString('N'))
|
|
||||||
$stream = [System.IO.File]::Open($script:reportPath, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write)
|
|
||||||
$script:reportWriter = [System.IO.StreamWriter]::new($stream, [System.Text.UTF8Encoding]::new($false))
|
|
||||||
foreach ($record in $script:reports) { $script:reportWriter.WriteLine(($record | ConvertTo-Json -Depth 12 -Compress)) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$identity = Get-CurrentIdentity
|
|
||||||
$meSid = $identity.User.Value
|
|
||||||
Invoke-ReportedOperation initialize '' 'Load read-only access checks and DACL-only writes before inspecting permissions.' none { Initialize-NativeApi }
|
|
||||||
$integrity = Get-IntegritySid
|
|
||||||
Write-Line ('CALLER SID={0} INTEGRITY={1}' -f $meSid, $integrity)
|
|
||||||
Write-Report observation caller '' read 'The caller token determines effective access; unconfined execution does not imply elevation.' @{ sid = $meSid; integrity = $integrity }
|
|
||||||
:paths foreach ($requested in $Path) {
|
|
||||||
$currentPath = $requested
|
|
||||||
$full = Get-NormalizedPath $requested
|
|
||||||
$currentPath = $full
|
|
||||||
Write-Line ('PATH={0}' -f $full)
|
|
||||||
if (-not (Test-Path -LiteralPath $full)) {
|
|
||||||
Write-Line ' MISSING'
|
|
||||||
Write-Line 'VERDICT=NOT_THIS_CLASS'
|
|
||||||
Write-Decision $mode $full skipped 'The requested path does not exist; no ACL was read or changed for it.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
|
|
||||||
$factsByPath = @{}
|
|
||||||
$inspectOrder = @()
|
|
||||||
$packageTargets = @()
|
|
||||||
$targetFacts = $null
|
|
||||||
foreach ($ancestor in (Get-Ancestors -FullPath $full)) {
|
|
||||||
if (-not (Test-Path -LiteralPath $ancestor)) { continue }
|
|
||||||
$facts = Get-ObjectFacts -FullPath $ancestor -MeSid $meSid
|
|
||||||
$factsByPath[$facts.Object] = $facts
|
|
||||||
$inspectOrder += $facts.Object
|
|
||||||
if ($ancestor -eq $full) { $targetFacts = $facts }
|
|
||||||
Write-Line (' OBJECT={0} READABLE={1}{2}' -f $facts.Object, $facts.Readable, $(if ($facts.Readable) { '' } else { ' ERROR=' + $facts.Error }))
|
|
||||||
if ($facts.Readable) {
|
|
||||||
Write-Line (' OWNER={0} IS_CURRENT_USER={1} MY_RIGHTS=[{2}] WRITE_DAC={3} WRITE_OWNER={4} LOW_LABEL={5}' -f $facts.Owner, $facts.OwnerIsMe, $facts.MyRights, $facts.HasWriteDac, $facts.HasWriteOwner, $facts.LowLabel)
|
|
||||||
foreach ($ace in $facts.PackageAces) { Write-Line (' PACKAGE_ACE {0}' -f $ace) }
|
|
||||||
foreach ($sid in ($facts.OtherAppContainerSids | Sort-Object -Unique)) { Write-Line (' OTHER_S1_15 SID={0} (reported only)' -f $sid) }
|
|
||||||
}
|
|
||||||
if ($facts.PackageAces.Count -gt 0) { $packageTargets += $facts.Object }
|
|
||||||
}
|
|
||||||
|
|
||||||
# The precondition is judged on the requested path itself. Ancestors above the
|
|
||||||
# tree DSH grants are not part of that grant, so their ownership and rights would
|
|
||||||
# otherwise mark every healthy path as a precondition failure.
|
|
||||||
if ($null -eq $targetFacts) { throw "The requested path disappeared before its ACL could be inspected: $full" }
|
|
||||||
$unreadable = -not $targetFacts.Readable
|
|
||||||
$needsPrecondition = (-not $unreadable) -and
|
|
||||||
((-not $targetFacts.HasWriteDac) -or (-not $targetFacts.HasWriteOwner))
|
|
||||||
|
|
||||||
# A directory the caller cannot provision is the workspace root half the time: the sandbox
|
|
||||||
# reports its own failure there while the conflicting entry sits deeper. Examine that
|
|
||||||
# subtree before the verdict so the classification and its packageObjects describe what
|
|
||||||
# this run will actually repair.
|
|
||||||
$ownsRoot = $full -ieq (Get-NormalizedPath $AllowRoot)
|
|
||||||
if (-not $Restore -and $targetFacts.Errors.Count -eq 0 -and [System.IO.Directory]::Exists($full) -and ($needsPrecondition -or $ownsRoot)) {
|
|
||||||
$scan = Get-SubtreePackageSources -Root $full -Limit $SCAN_LIMIT
|
|
||||||
foreach ($object in $scan.sources) {
|
|
||||||
if ($packageTargets -notcontains $object) { $packageTargets += $object }
|
|
||||||
if (-not $factsByPath.ContainsKey($object)) {
|
|
||||||
$scanned = Get-ObjectFacts -FullPath $object -MeSid $meSid
|
|
||||||
$factsByPath[$scanned.Object] = $scanned
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Write-Report observation subtree_scan $full $(if ($scan.failed -gt 0) { 'partial' } else { 'read' }) 'The caller cannot provision this directory, or it is the authorized root, so explicit package allow ACEs under it were collected in the same run; no reparse point or managed application tree is entered.' @{
|
|
||||||
visited = $scan.visited; packageSources = @($scan.sources); truncated = [bool]$scan.truncated; unreadable = [int]$scan.failed
|
|
||||||
}
|
|
||||||
Write-Line ('SCAN {0} VISITED={1} PACKAGE_SOURCES={2}{3}{4}' -f $full, $scan.visited, @($scan.sources).Count, $(if ($scan.truncated) { ' TRUNCATED' } else { '' }), $(if ($scan.failed -gt 0) { " UNREADABLE=$($scan.failed)" } else { '' }))
|
|
||||||
if ($scan.truncated) { $script:scanTruncated = $true }
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($targetFacts.Errors.Count -gt 0) {
|
|
||||||
$verdict = 'INCOMPLETE'
|
|
||||||
$reason = 'Some observations failed; missing evidence is not evidence that a right is absent or a repair is safe.'
|
|
||||||
} elseif ($packageTargets.Count -gt 0) {
|
|
||||||
$blocked = @($packageTargets | Where-Object { -not $factsByPath[$_].HasWriteDac })
|
|
||||||
$verdict = if ($needsPrecondition -or $blocked.Count -gt 0) { 'BOTH' } else { 'CULPRIT' }
|
|
||||||
$reason = 'Package allow ACEs were observed. Required access checks determine whether the caller can perform the requested repair; other causes remain possible.'
|
|
||||||
} elseif ($unreadable) {
|
|
||||||
$verdict = 'UNREADABLE'
|
|
||||||
$reason = 'The requested ACL could not be read; its entries and the cause of denial are unknown.'
|
|
||||||
} elseif ($needsPrecondition) {
|
|
||||||
$verdict = 'PRECONDITION'
|
|
||||||
$reason = 'The caller cannot open the requested object with both WRITE_DAC and WRITE_OWNER. The reported allow and deny ACEs are evidence, not an attribution to one rule.'
|
|
||||||
} else {
|
|
||||||
$verdict = 'NOT_THIS_CLASS'
|
|
||||||
$reason = 'No package allow ACE was observed and both required rights are available. Other ACL restrictions and causes of the original failure are not ruled out.'
|
|
||||||
}
|
|
||||||
Write-Line ('VERDICT={0}' -f $verdict)
|
|
||||||
Write-Report decision classify $full $verdict $reason @{ writeDac = $targetFacts.HasWriteDac; writeOwner = $targetFacts.HasWriteOwner; packageObjects = @($packageTargets) }
|
|
||||||
|
|
||||||
if ($Restore) {
|
|
||||||
Restore-SavedDacl -FullPath $full -Record $Restore -Root $AllowRoot
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ($targetFacts.Errors.Count -gt 0) {
|
|
||||||
Write-Decision $mode $full refused 'Required observations are incomplete; no repair was attempted for this path.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
|
|
||||||
# Nothing is changed while a package source or a grant target is out of reach: a
|
|
||||||
# repair that cannot finish would leave the tree half repaired before refusing.
|
|
||||||
foreach ($packagePath in $packageTargets) {
|
|
||||||
$refusal = Get-RepairRefusal -FullPath $packagePath -Root $AllowRoot -AllowEqual
|
|
||||||
if ($refusal) { Write-Line ('REPAIR_REFUSED {0}' -f $refusal); Write-Decision $mode $packagePath refused $refusal; $refused++; break paths }
|
|
||||||
if ($factsByPath[$packagePath].Errors.Count -gt 0) {
|
|
||||||
Write-Decision $mode $packagePath refused 'The ACL observations are incomplete; collateral changes could not be verified.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Missing WRITE_DAC or WRITE_OWNER on a directory in the chain is what stops DSH
|
|
||||||
# from provisioning the workspace grant. One approved run repairs every such
|
|
||||||
# directory, including the authorized root itself.
|
|
||||||
$grantTargets = @($inspectOrder | Where-Object {
|
|
||||||
[System.IO.Directory]::Exists($_) -and $factsByPath[$_].Readable -and $factsByPath[$_].Errors.Count -eq 0 -and
|
|
||||||
((-not $factsByPath[$_].HasWriteDac) -or (-not $factsByPath[$_].HasWriteOwner)) -and
|
|
||||||
-not (Get-RepairRefusal -FullPath $_ -Root $AllowRoot -AllowEqual)
|
|
||||||
})
|
|
||||||
# Writing a DACL needs WRITE_DAC: refuse a target that lacks it before anything is
|
|
||||||
# changed, instead of failing mid-repair and marking a recovery for an object that
|
|
||||||
# the rollback then cannot restore either.
|
|
||||||
foreach ($object in $grantTargets) {
|
|
||||||
if (-not $factsByPath[$object].HasWriteDac) {
|
|
||||||
Write-Line ('REPAIR_REFUSED {0} needs WRITE_DAC; stop for permission-policy review' -f $object)
|
|
||||||
Write-Decision $mode $object refused 'Effective WRITE_DAC is absent; adding the grant requires that right.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($grantTargets.Count -gt 0) {
|
|
||||||
Write-Report decision grant_targets $full selected 'These directories lack effective WRITE_DAC or WRITE_OWNER; each is backed up, then receives a FullControl allow ACE for the current user.' @{ paths = @($grantTargets) }
|
|
||||||
}
|
|
||||||
foreach ($object in $grantTargets) {
|
|
||||||
$grantBefore = $factsByPath[$object]
|
|
||||||
Save-AclBackup -FullPath $object -Directory $Out -Root $AllowRoot
|
|
||||||
$grantAcl = Get-Acl -LiteralPath $object
|
|
||||||
$grantAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
||||||
[System.Security.Principal.SecurityIdentifier]::new($meSid),
|
|
||||||
[System.Security.AccessControl.FileSystemRights]::FullControl,
|
|
||||||
[System.Security.AccessControl.AccessControlType]::Allow))
|
|
||||||
Invoke-ReportedOperation grant_dacl $object "WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for $meSid while preserving deny ACEs, owner and SACL." acl {
|
|
||||||
[Dsh.TokenInfo]::SetDacl($object, $grantAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access))
|
|
||||||
}
|
|
||||||
$grantAfter = Get-ObjectFacts -FullPath $object -MeSid $meSid -CompactRecord
|
|
||||||
$factsByPath[$object] = $grantAfter
|
|
||||||
$verified = $grantAfter.Readable -and $grantAfter.Errors.Count -eq 0 -and $grantAfter.HasWriteDac -and $grantAfter.HasWriteOwner
|
|
||||||
Write-Report verification grant $object $(if ($verified) { 'verified' } else { 'failed' }) 'The DACL write completed; recheck effective access before claiming that provisioning can succeed. On failure, restore this invocation and stop.' @{
|
|
||||||
before = @{ writeDac = $grantBefore.HasWriteDac; writeOwner = $grantBefore.HasWriteOwner }
|
|
||||||
after = @{ writeDac = $grantAfter.HasWriteDac; writeOwner = $grantAfter.HasWriteOwner }
|
|
||||||
recovery = $recoveries[-1].command
|
|
||||||
}
|
|
||||||
if ($verified) {
|
|
||||||
Write-Line ('GRANTED {0} SID={1}' -f $object, $meSid); $granted++
|
|
||||||
} else {
|
|
||||||
Write-Line ('GRANT_FAILED {0}; effective WRITE_DAC and WRITE_OWNER were not both confirmed; restore this invocation and stop' -f $object)
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$sources = @($packageTargets | Where-Object {
|
|
||||||
@($factsByPath[$_].Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited }).Count -gt 0
|
|
||||||
})
|
|
||||||
# Ancestor first, for chain and scan-discovered sources alike.
|
|
||||||
$sources = @($sources | Sort-Object -Property @{ Expression = { $_.Split([char]92).Count } }, @{ Expression = { $_ } })
|
|
||||||
foreach ($source in $sources) {
|
|
||||||
if (-not $factsByPath[$source].HasWriteDac) {
|
|
||||||
Write-Line ('REPAIR_REFUSED {0} needs WRITE_DAC; stop for permission-policy review' -f $source)
|
|
||||||
Write-Decision $mode $source refused 'Effective WRITE_DAC is absent; removing a package allow ACE requires that right.'
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($sources.Count -gt 0) {
|
|
||||||
Write-Report decision remove_package_sources $full selected 'Remove explicit package allow ACEs from their sources, ancestor first, leaving inheritance enabled so inherited copies follow their repaired source.' @{
|
|
||||||
sources = @($sources); affectedPaths = @($packageTargets)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach ($source in $sources) {
|
|
||||||
Save-AclBackup -FullPath $source -Directory $Out -Root $AllowRoot
|
|
||||||
$sids = @($factsByPath[$source].Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited } | ForEach-Object { $_.sid } | Sort-Object -Unique)
|
|
||||||
foreach ($sid in $sids) {
|
|
||||||
Invoke-ReportedOperation remove_package_allow $source "Remove the observed package allow ACE for $sid; preserve deny ACEs and all other principals." acl {
|
|
||||||
$output = @(icacls $source /remove:g "*$sid" 2>&1)
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "icacls removal exit $($LASTEXITCODE): $($output -join [char]10)" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# A package deny can share the removed allow's SID; only allow ACEs were removed.
|
|
||||||
foreach ($packagePath in $packageTargets) {
|
|
||||||
$fixBefore = $factsByPath[$packagePath]
|
|
||||||
$fixAfter = Get-ObjectFacts -FullPath $packagePath -MeSid $meSid -CompactRecord
|
|
||||||
# Compare the object's own ACEs as sorted sets: listing order and inherited
|
|
||||||
# entries follow the parent, so neither proves a collateral change.
|
|
||||||
$rowOf = { param($ace) '{0}|{1}|{2}|{3}|{4}' -f $ace.type, $ace.sid, $ace.rights, $ace.inheritance, $ace.propagation }
|
|
||||||
$ownAfter = @($fixAfter.Aces | Where-Object { -not $_.inherited } | ForEach-Object { & $rowOf $_ } | Sort-Object)
|
|
||||||
$expectedOwn = @($fixBefore.Aces | Where-Object { -not $_.inherited -and -not ($_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID) } | ForEach-Object { & $rowOf $_ } | Sort-Object)
|
|
||||||
$collateral = (@($expectedOwn) -join [char]10) -eq (@($ownAfter) -join [char]10)
|
|
||||||
$verified = $fixAfter.Readable -and $fixAfter.Errors.Count -eq 0 -and $fixAfter.PackageAces.Count -eq 0 -and $collateral
|
|
||||||
Write-Report verification fix $packagePath $(if ($verified) { 'verified' } else { 'failed' }) 'The removal command completed; verify that package allow ACEs disappeared and other own ACEs remained unchanged. On failure, restore this invocation and stop.' @{
|
|
||||||
remainingPackageAces = $fixAfter.PackageAces; otherEntriesUnchanged = $collateral
|
|
||||||
}
|
|
||||||
if ($verified) {
|
|
||||||
$removedSids = @($fixBefore.Aces | Where-Object { $_.type -eq 'Allow' -and $_.sid -match $PACKAGE_SID -and -not $_.inherited } | ForEach-Object { $_.sid } | Sort-Object -Unique)
|
|
||||||
foreach ($sid in $removedSids) {
|
|
||||||
Write-Line ('FIXED {0} SID={1}' -f $packagePath, $sid); $fixed++
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write-Line ('FIX_FAILED {0} collateral_change={1}' -f $packagePath, (-not $collateral))
|
|
||||||
$refused++
|
|
||||||
break paths
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($packageTargets.Count -eq 0 -and $grantTargets.Count -eq 0) {
|
|
||||||
Write-Decision $mode $full skipped 'No package allow ACE and no missing WRITE_DAC or WRITE_OWNER was observed on the inspected objects; no ACL change was needed.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
$exitCode = if ($_.Exception -is [System.ArgumentException]) { 2 } else { 1 }
|
|
||||||
Write-Report error $mode $currentPath stopped 'Execution stopped after an exception. An interrupted write may have changed state; attempted repairs will be restored before the final summary.' @{ error = (Get-HResultChain $_.Exception); location = $_.InvocationInfo.PositionMessage }
|
|
||||||
} finally {
|
|
||||||
if ($refused -gt 0 -and $exitCode -eq 0) { $exitCode = 2 }
|
|
||||||
if ($exitCode -ne 0 -and -not $Restore) {
|
|
||||||
for ($i = $recoveries.Count - 1; $i -ge 0; $i--) {
|
|
||||||
$recovery = $recoveries[$i]
|
|
||||||
if (-not $recovery.attempted) { continue }
|
|
||||||
Write-Decision rollback $recovery.path selected 'The repair failed; restore every attempted DACL change from this invocation in reverse order before stopping.'
|
|
||||||
try {
|
|
||||||
Restore-SavedDacl -FullPath $recovery.path -Record $recovery.record -Root $AllowRoot
|
|
||||||
$recovery.restored = $true
|
|
||||||
$rollbackStatus = 'verified'
|
|
||||||
} catch {
|
|
||||||
$rollbackStatus = 'failed'
|
|
||||||
Write-Report error rollback $recovery.path stopped 'Recovery was not verified. Stop repairs and retain the pending recovery commands in reverse order.' @{ error = (Get-HResultChain $_.Exception) }
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$pending = @($recoveries | Where-Object { $_.attempted -and -not $_.restored } | ForEach-Object { $_.command })
|
|
||||||
[array]::Reverse($pending)
|
|
||||||
$repaired = ($fixed + $granted) -gt 0
|
|
||||||
$nextAction = if ($rollbackStatus -eq 'failed') { 'restore_pending_then_stop' } elseif ($exitCode -ne 0 -or $observationFailures -gt 0) { 'stop' } elseif ($repaired) { 'verify_original_confined_operation' } else { 'stop' }
|
|
||||||
# The tool keeps only the tail of stdout. Recapitulate the decisions here so the
|
|
||||||
# records a reader needs survive truncation; the report file holds every record.
|
|
||||||
$recap = [ordered]@{
|
|
||||||
verdicts = @($reports | Where-Object { $_.operation -eq 'classify' } | ForEach-Object {
|
|
||||||
@{ path = $_.path; verdict = $_.status; writeDac = $_.details['writeDac']; writeOwner = $_.details['writeOwner']; packageObjects = $_.details['packageObjects'] }
|
|
||||||
})
|
|
||||||
changes = @($reports | Where-Object { $_.kind -eq 'action' -and $_.details['effect'] -eq 'acl' -and $_.status -eq 'completed' } | ForEach-Object { @{ operation = $_.operation; path = $_.path } })
|
|
||||||
verifications = @($reports | Where-Object { $_.kind -eq 'verification' } | ForEach-Object { @{ operation = $_.operation; path = $_.path; status = $_.status } })
|
|
||||||
refusals = @($reports | Where-Object { $_.kind -eq 'decision' -and $_.status -eq 'refused' } | ForEach-Object { @{ path = $_.path; reason = $_.reason } })
|
|
||||||
scans = @($reports | Where-Object { $_.operation -eq 'subtree_scan' } | ForEach-Object {
|
|
||||||
@{ path = $_.path; visited = $_.details['visited']; packageSources = @($_.details['packageSources']); truncated = $_.details['truncated']; unreadable = $_.details['unreadable'] }
|
|
||||||
})
|
|
||||||
report = $reportPath
|
|
||||||
}
|
|
||||||
$status = if ($exitCode -ne 0) { 'failed' } elseif ($observationFailures -gt 0) { 'partial' } else { 'completed' }
|
|
||||||
Write-Report summary $mode $currentPath $status 'Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved.' @{
|
|
||||||
exitCode = $exitCode; fixed = $fixed; granted = $granted; refused = $refused; restored = $restored
|
|
||||||
operations = @($operations.ToArray()); recoveries = @($recoveries.ToArray()); automaticRollback = $true; observationFailures = $observationFailures
|
|
||||||
rollback = $rollbackStatus; rollbackCommands = $pending; nextAction = $nextAction; scanTruncated = $scanTruncated; report = $reportPath
|
|
||||||
}
|
|
||||||
# Last on stdout, after the summary record: whatever the tool truncates, the tail
|
|
||||||
# still carries the decisions, the report path and the counts.
|
|
||||||
Write-Line ('RECAP ' + ($recap | ConvertTo-Json -Depth 8 -Compress))
|
|
||||||
if ($reportPath) { Write-Line ('REPORT_FILE {0}' -f $reportPath) }
|
|
||||||
Write-Line ('SUMMARY FIXED={0} GRANTED={1} REFUSED={2} RESTORED={3}' -f $fixed, $granted, $refused, $restored)
|
|
||||||
if ($reportWriter) { $reportWriter.Dispose() }
|
|
||||||
}
|
|
||||||
exit $exitCode
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
{"kind":"invocation","operation":"repair","path":"","status":"started","reason":"Inspect the requested paths, then repair the ACL problems this run can prove, before anything else is attempted.","details":{"recoveryRecord":"","allowRoot":"D:\\PricingReview","paths":["D:\\PricingReview\\CostReview\\data"],"outputDirectory":"D:\\PricingReview\\_acl-recovery"}}
|
|
||||||
{"kind":"action","operation":"prepare_report","path":"D:\\PricingReview\\_acl-recovery","status":"started","reason":"Create the recovery directory and a new JSONL report that keeps every record, because tool output is truncated to its tail.","details":{"id":1,"effect":"files"}}
|
|
||||||
{"kind":"action","operation":"prepare_report","path":"D:\\PricingReview\\_acl-recovery","status":"completed","reason":"Create the recovery directory and a new JSONL report that keeps every record, because tool output is truncated to its tail.","details":{"id":1,"effect":"files"}}
|
|
||||||
{"kind":"action","operation":"initialize","path":"","status":"started","reason":"Load read-only access checks and DACL-only writes before inspecting permissions.","details":{"id":2,"effect":"none"}}
|
|
||||||
{"kind":"action","operation":"initialize","path":"","status":"completed","reason":"Load read-only access checks and DACL-only writes before inspecting permissions.","details":{"id":2,"effect":"none"}}
|
|
||||||
{"kind":"observation","operation":"caller","path":"","status":"read","reason":"The caller token determines effective access; unconfined execution does not imply elevation.","details":{"integrity":"S-1-16-8192 (Medium)","sid":"S-1-5-21-1842133535-1407408427-1432962073-1000"}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\PricingReview\\CostReview\\data","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":false,"acesOmitted":false,"writeDac":true,"owner":"S-1-5-21-1842133535-1407408427-1432962073-1000","aces":[{"sid":"S-1-5-32-544","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-544","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-18","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-18","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-11","type":"Allow","rights":"Modify, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-11","type":"Allow","rights":"-536805376","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-32-545","type":"Allow","rights":"ReadAndExecute, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-545","type":"Allow","rights":"-1610612736","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"}],"lowLabel":null}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\PricingReview\\CostReview","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":false,"acesOmitted":false,"writeDac":true,"owner":"S-1-5-21-1842133535-1407408427-1432962073-1000","aces":[{"sid":"S-1-5-32-544","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-544","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-18","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-18","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-11","type":"Allow","rights":"Modify, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-11","type":"Allow","rights":"-536805376","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-32-545","type":"Allow","rights":"ReadAndExecute, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-545","type":"Allow","rights":"-1610612736","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"}],"lowLabel":null}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\PricingReview","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":true,"acesOmitted":false,"writeDac":true,"owner":"S-1-5-21-1842133535-1407408427-1432962073-1000","aces":[{"sid":"S-1-1-0","type":"Deny","rights":"DeleteSubdirectoriesAndFiles","inherited":false,"inheritance":"ContainerInherit","propagation":"None"},{"sid":"S-1-4-625000727-302857043","type":"Allow","rights":"DeleteSubdirectoriesAndFiles, Write, Delete, Synchronize","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"None"},{"sid":"S-1-4-970831040-201677128","type":"Allow","rights":"DeleteSubdirectoriesAndFiles, Write, Delete, Synchronize","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"None"},{"sid":"S-1-5-21-1842133535-1407408427-1432962073-1000","type":"Allow","rights":"FullControl","inherited":false,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-544","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-544","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-18","type":"Allow","rights":"FullControl","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-18","type":"Allow","rights":"268435456","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-11","type":"Allow","rights":"Modify, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-11","type":"Allow","rights":"-536805376","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-32-545","type":"Allow","rights":"ReadAndExecute, Synchronize","inherited":true,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-545","type":"Allow","rights":"-1610612736","inherited":true,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"}],"lowLabel":true}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":false,"acesOmitted":false,"writeDac":false,"owner":"S-1-5-18","aces":[{"sid":"S-1-5-11","type":"Allow","rights":"-536805376","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-11","type":"Allow","rights":"Modify, Synchronize","inherited":false,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-18","type":"Allow","rights":"FullControl","inherited":false,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-18","type":"Allow","rights":"268435456","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-32-544","type":"Allow","rights":"268435456","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"},{"sid":"S-1-5-32-544","type":"Allow","rights":"FullControl","inherited":false,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-545","type":"Allow","rights":"ReadAndExecute, Synchronize","inherited":false,"inheritance":"None","propagation":"None"},{"sid":"S-1-5-32-545","type":"Allow","rights":"-1610612736","inherited":false,"inheritance":"ContainerInherit, ObjectInherit","propagation":"InheritOnly"}],"lowLabel":null}}
|
|
||||||
{"kind":"observation","operation":"subtree_scan","path":"D:\\PricingReview\\CostReview\\data","status":"read","reason":"The caller cannot provision this directory, or it is the authorized root, so explicit package allow ACEs under it were collected in the same run; no reparse point or managed application tree is entered.","details":{"packageSources":[],"truncated":false,"unreadable":0,"visited":8}}
|
|
||||||
{"kind":"decision","operation":"classify","path":"D:\\PricingReview\\CostReview\\data","status":"PRECONDITION","reason":"The caller cannot open the requested object with both WRITE_DAC and WRITE_OWNER. The reported allow and deny ACEs are evidence, not an attribution to one rule.","details":{"writeOwner":false,"writeDac":true,"packageObjects":[]}}
|
|
||||||
{"kind":"decision","operation":"grant_targets","path":"D:\\PricingReview\\CostReview\\data","status":"selected","reason":"These directories lack effective WRITE_DAC or WRITE_OWNER; each is backed up, then receives a FullControl allow ACE for the current user.","details":{"paths":["D:\\PricingReview\\CostReview\\data","D:\\PricingReview\\CostReview"]}}
|
|
||||||
{"kind":"decision","operation":"backup","path":"D:\\PricingReview\\CostReview\\data","status":"selected","reason":"The recovery record and an independent recovery script are written before the ACL change.","details":{"files":["D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json","D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1"]}}
|
|
||||||
{"kind":"action","operation":"backup","path":"D:\\PricingReview\\CostReview\\data","status":"started","reason":"Save the original DACL and an independent recovery command before changing permissions.","details":{"id":3,"effect":"files"}}
|
|
||||||
{"kind":"action","operation":"backup","path":"D:\\PricingReview\\CostReview\\data","status":"completed","reason":"Save the original DACL and an independent recovery command before changing permissions.","details":{"id":3,"effect":"files"}}
|
|
||||||
{"kind":"observation","operation":"recovery","path":"D:\\PricingReview\\CostReview\\data","status":"available","reason":"These files can restore the saved DACL; no rollback has been executed.","details":{"record":"D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json","command":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1' -Path 'D:\\PricingReview\\CostReview\\data' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json'","restored":false,"attempted":false,"script":"D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1","path":"D:\\PricingReview\\CostReview\\data"}}
|
|
||||||
{"kind":"action","operation":"grant_dacl","path":"D:\\PricingReview\\CostReview\\data","status":"started","reason":"WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for S-1-5-21-1842133535-1407408427-1432962073-1000 while preserving deny ACEs, owner and SACL.","details":{"id":4,"effect":"acl"}}
|
|
||||||
{"kind":"action","operation":"grant_dacl","path":"D:\\PricingReview\\CostReview\\data","status":"completed","reason":"WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for S-1-5-21-1842133535-1407408427-1432962073-1000 while preserving deny ACEs, owner and SACL.","details":{"id":4,"effect":"acl"}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\PricingReview\\CostReview\\data","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":true,"acesOmitted":true,"writeDac":true,"owner":"S-1-5-21-1842133535-1407408427-1432962073-1000","aces":null,"lowLabel":null}}
|
|
||||||
{"kind":"verification","operation":"grant","path":"D:\\PricingReview\\CostReview\\data","status":"verified","reason":"The DACL write completed; recheck effective access before claiming that provisioning can succeed. On failure, restore this invocation and stop.","details":{"before":{"writeOwner":false,"writeDac":true},"after":{"writeOwner":true,"writeDac":true},"recovery":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1' -Path 'D:\\PricingReview\\CostReview\\data' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json'"}}
|
|
||||||
{"kind":"decision","operation":"backup","path":"D:\\PricingReview\\CostReview","status":"selected","reason":"The recovery record and an independent recovery script are written before the ACL change.","details":{"files":["D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json","D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1"]}}
|
|
||||||
{"kind":"action","operation":"backup","path":"D:\\PricingReview\\CostReview","status":"started","reason":"Save the original DACL and an independent recovery command before changing permissions.","details":{"id":5,"effect":"files"}}
|
|
||||||
{"kind":"action","operation":"backup","path":"D:\\PricingReview\\CostReview","status":"completed","reason":"Save the original DACL and an independent recovery command before changing permissions.","details":{"id":5,"effect":"files"}}
|
|
||||||
{"kind":"observation","operation":"recovery","path":"D:\\PricingReview\\CostReview","status":"available","reason":"These files can restore the saved DACL; no rollback has been executed.","details":{"record":"D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json","command":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1' -Path 'D:\\PricingReview\\CostReview' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json'","restored":false,"attempted":false,"script":"D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1","path":"D:\\PricingReview\\CostReview"}}
|
|
||||||
{"kind":"action","operation":"grant_dacl","path":"D:\\PricingReview\\CostReview","status":"started","reason":"WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for S-1-5-21-1842133535-1407408427-1432962073-1000 while preserving deny ACEs, owner and SACL.","details":{"id":6,"effect":"acl"}}
|
|
||||||
{"kind":"action","operation":"grant_dacl","path":"D:\\PricingReview\\CostReview","status":"completed","reason":"WRITE_DAC or WRITE_OWNER is missing; add a FullControl allow ACE for S-1-5-21-1842133535-1407408427-1432962073-1000 while preserving deny ACEs, owner and SACL.","details":{"id":6,"effect":"acl"}}
|
|
||||||
{"kind":"observation","operation":"inspect_acl","path":"D:\\PricingReview\\CostReview","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"errors":[],"writeOwner":true,"acesOmitted":true,"writeDac":true,"owner":"S-1-5-21-1842133535-1407408427-1432962073-1000","aces":null,"lowLabel":null}}
|
|
||||||
{"kind":"verification","operation":"grant","path":"D:\\PricingReview\\CostReview","status":"verified","reason":"The DACL write completed; recheck effective access before claiming that provisioning can succeed. On failure, restore this invocation and stop.","details":{"before":{"writeOwner":false,"writeDac":true},"after":{"writeOwner":true,"writeDac":true},"recovery":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1' -Path 'D:\\PricingReview\\CostReview' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json'"}}
|
|
||||||
{"kind":"summary","operation":"repair","path":"D:\\PricingReview\\CostReview\\data","status":"completed","reason":"Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved.","details":{"nextAction":"verify_original_confined_operation","operations":[{"id":1,"operation":"prepare_report","path":"D:\\PricingReview\\_acl-recovery","effect":"files","status":"completed"},{"id":2,"operation":"initialize","path":"","effect":"none","status":"completed"},{"id":3,"operation":"backup","path":"D:\\PricingReview\\CostReview\\data","effect":"files","status":"completed"},{"id":4,"operation":"grant_dacl","path":"D:\\PricingReview\\CostReview\\data","effect":"acl","status":"completed"},{"id":5,"operation":"backup","path":"D:\\PricingReview\\CostReview","effect":"files","status":"completed"},{"id":6,"operation":"grant_dacl","path":"D:\\PricingReview\\CostReview","effect":"acl","status":"completed"}],"exitCode":0,"rollbackCommands":["pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1' -Path 'D:\\PricingReview\\CostReview' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json'","pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1' -Path 'D:\\PricingReview\\CostReview\\data' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json'"],"automaticRollback":true,"restored":0,"observationFailures":0,"report":"D:\\PricingReview\\_acl-recovery\\acl-report-38654d41a493427fb3d9f12eca756ae6.jsonl","refused":0,"scanTruncated":false,"rollback":"not-needed","recoveries":[{"record":"D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json","command":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1' -Path 'D:\\PricingReview\\CostReview\\data' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json'","restored":false,"attempted":true,"script":"D:\\PricingReview\\_acl-recovery\\acl-backup-1b4df40d57684b42881224c447febb36.json.ps1","path":"D:\\PricingReview\\CostReview\\data"},{"record":"D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json","command":"pwsh -NoProfile -File 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1' -Path 'D:\\PricingReview\\CostReview' -AllowRoot 'D:\\PricingReview' -Restore 'D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json'","restored":false,"attempted":true,"script":"D:\\PricingReview\\_acl-recovery\\acl-backup-47955c9164634109a5215defd0fe7936.json.ps1","path":"D:\\PricingReview\\CostReview"}],"fixed":0,"granted":2}}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""临时探针:DivisionalWorks 层级——原件 vs 导出件(深度分布/属性列/清单挂载)。用完即删。"""
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import sys
|
|
||||||
import zipfile
|
|
||||||
from collections import Counter
|
|
||||||
from xml.etree import ElementTree as ET
|
|
||||||
|
|
||||||
APP = r"D:\PricingReview\CostReview\app"
|
|
||||||
sys.path.insert(0, os.path.join(APP, "core"))
|
|
||||||
sys.path.insert(0, os.path.join(APP, "server"))
|
|
||||||
import export_v2 as ev # noqa: E402
|
|
||||||
|
|
||||||
SRC = r"D:/PricingReview/CostReview/data/source_files"
|
|
||||||
|
|
||||||
|
|
||||||
def depth_stats(txt):
|
|
||||||
"""→ (每个 DivisionalWorks 的相对深度分布, 每个深度下的列集, 每个深度的清单数, 最大深度)"""
|
|
||||||
root = ET.fromstring(txt)
|
|
||||||
unit = root if root.tag == "UnitWorks" else None
|
|
||||||
if unit is None:
|
|
||||||
for u in root.iter("UnitWorks"):
|
|
||||||
if list(u):
|
|
||||||
unit = u
|
|
||||||
break
|
|
||||||
if unit is None:
|
|
||||||
return {}, {}, {}, 0
|
|
||||||
parent = {c: p for p in root.iter() for c in p}
|
|
||||||
|
|
||||||
def rel(el):
|
|
||||||
d = 0
|
|
||||||
x = el
|
|
||||||
while x is not None and x is not unit:
|
|
||||||
if x.tag in ("DivisionalWorks", "PreliminaryDivisionalWorks"):
|
|
||||||
d += 1
|
|
||||||
x = parent.get(x)
|
|
||||||
return d
|
|
||||||
|
|
||||||
dist = Counter()
|
|
||||||
cols = {}
|
|
||||||
bills = Counter()
|
|
||||||
for el in unit.iter():
|
|
||||||
if el.tag in ("DivisionalWorks", "PreliminaryDivisionalWorks"):
|
|
||||||
d = rel(el)
|
|
||||||
dist[d] += 1
|
|
||||||
cols.setdefault(d, set()).update(el.attrib.keys())
|
|
||||||
bills[d] += len([c for c in el if c.tag == "WorkElement"])
|
|
||||||
return dict(dist), {k: sorted(v) for k, v in cols.items()}, dict(bills), max(dist) if dist else 0
|
|
||||||
|
|
||||||
|
|
||||||
def member_texts(blob):
|
|
||||||
out = []
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(blob))
|
|
||||||
for i in z.infolist():
|
|
||||||
nm = i.filename.encode("cp437").decode("gbk") if not (i.flag_bits & 0x800) else i.filename
|
|
||||||
if "Project" in nm:
|
|
||||||
continue
|
|
||||||
out.append(z.read(i).decode("utf-8", "replace"))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
sc = sqlite3.connect(r"D:/PricingReview/CostReview/data/session.db")
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
con = sqlite3.connect(r"D:/PricingReview/CostReview/data/history.db")
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
|
|
||||||
for sid, sfx in ((1, "cos4"), (10, "cos")):
|
|
||||||
row = sc.execute("SELECT src_name, name FROM sessions WHERE id=?", (sid,)).fetchone()
|
|
||||||
src = os.path.join(SRC, row["src_name"])
|
|
||||||
if not os.path.exists(src):
|
|
||||||
print("src missing", sid)
|
|
||||||
continue
|
|
||||||
raw, name, err = ev.export_v2(con, sc, sid, sfx, None, src_path=src)
|
|
||||||
print("=" * 70)
|
|
||||||
print("session", sid, row["name"][:24], "err", err, "size", len(raw or b""))
|
|
||||||
if not raw:
|
|
||||||
continue
|
|
||||||
orig = member_texts(open(src, "rb").read())
|
|
||||||
exp = member_texts(raw)
|
|
||||||
print("成员数 原件/导出:", len(orig), len(exp))
|
|
||||||
for label, texts in (("原件", orig), ("导出", exp)):
|
|
||||||
dist = Counter()
|
|
||||||
cols = {}
|
|
||||||
bills = Counter()
|
|
||||||
maxd = 0
|
|
||||||
for t in texts:
|
|
||||||
d, c, b, m = depth_stats(t)
|
|
||||||
dist.update(d)
|
|
||||||
for k, v in c.items():
|
|
||||||
cols.setdefault(k, set()).update(v)
|
|
||||||
bills.update(b)
|
|
||||||
maxd = max(maxd, m)
|
|
||||||
print(" ", label, "深度分布", dict(sorted(dist.items())),
|
|
||||||
"最大深度", maxd, "各层清单数", dict(sorted(bills.items())))
|
|
||||||
for k in sorted(cols):
|
|
||||||
print(" depth", k, "列数", len(cols[k]))
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""xmldiff:实件 AttrInfo 区 vs 导出件 AttrInfo 区——结构差异精确定位。"""
|
|
||||||
import sys
|
|
||||||
sys.path.insert(0, '.')
|
|
||||||
import classic_skeleton as cs
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
import io
|
|
||||||
import re
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
from xmldiff import main, formatting
|
|
||||||
|
|
||||||
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
|
|
||||||
con.row_factory = sqlite3.Row
|
|
||||||
|
|
||||||
def extract_attrinfo(xml_text):
|
|
||||||
i = xml_text.find('<AttrInfo>')
|
|
||||||
if i < 0:
|
|
||||||
i = xml_text.find('<AttrInfo ')
|
|
||||||
j = xml_text.find('</AttrInfo>', i) + len('</AttrInfo>')
|
|
||||||
return xml_text[i:j]
|
|
||||||
|
|
||||||
# ① 广联达件:实件 vs 导出件
|
|
||||||
rg = con.execute("SELECT blob FROM classic_skel WHERE original_name LIKE '%广联达导出最新%'").fetchone()
|
|
||||||
zg = zipfile.ZipFile(io.BytesIO(rg['blob']))
|
|
||||||
|
|
||||||
# 实件最全成员的 AttrInfo 区
|
|
||||||
best = None
|
|
||||||
for nm in zg.namelist():
|
|
||||||
if not nm.lower().endswith('.xml') or 'Project' in nm:
|
|
||||||
continue
|
|
||||||
t = zg.read(nm).decode('utf-8', errors='replace')
|
|
||||||
if '<AttrInfo>' in t:
|
|
||||||
n = len(re.findall(r'<[A-Za-z_]', t))
|
|
||||||
if best is None or n > best[0]:
|
|
||||||
best = (n, nm, t)
|
|
||||||
orig_attr = extract_attrinfo(best[2])
|
|
||||||
open('_orig_gld_attr.xml', 'w', encoding='utf-8').write(orig_attr)
|
|
||||||
|
|
||||||
# ② 导出件 AttrInfo 区
|
|
||||||
raw_exp, name_exp, err = None, None, None
|
|
||||||
import export_v2 as _ev2
|
|
||||||
sc = sqlite3.connect(r'D:/PricingReview/CostReview/data/session.db')
|
|
||||||
sc.row_factory = sqlite3.Row
|
|
||||||
raw_exp, name_exp, err = _ev2.export_v2(con, sc, 1, 'cos4')
|
|
||||||
z = zipfile.ZipFile(io.BytesIO(raw_exp))
|
|
||||||
units = [i for i in z.infolist() if 'Project' not in (i.filename.encode('cp437').decode('gbk') if not (i.flag_bits & 0x800) else i.filename)]
|
|
||||||
t_exp = z.read(units[0]).decode('utf-8')
|
|
||||||
exp_attr = extract_attrinfo(t_exp)
|
|
||||||
open('_exp_gld_attr.xml', 'w', encoding='utf-8').write(exp_attr)
|
|
||||||
|
|
||||||
print('=== xmldiff:广联达实件 AttrInfo vs 导出件 AttrInfo ===')
|
|
||||||
diff = main.diff_texts(orig_attr, exp_attr)
|
|
||||||
for d in diff:
|
|
||||||
print(' ', d)
|
|
||||||
|
|
||||||
print()
|
|
||||||
# ③ 易达件同理
|
|
||||||
ry = con.execute("SELECT blob FROM classic_skel WHERE original_name LIKE '%1易达%'").fetchone()
|
|
||||||
zy = zipfile.ZipFile(io.BytesIO(ry['blob']))
|
|
||||||
best_y = None
|
|
||||||
for nm in zy.namelist():
|
|
||||||
if not nm.lower().endswith('.xml') or 'Project' in nm:
|
|
||||||
continue
|
|
||||||
t = zy.read(nm).decode('utf-8', errors='replace')
|
|
||||||
if '<AttrInfo>' in t:
|
|
||||||
n = len(re.findall(r'<[A-Za-z_]', t))
|
|
||||||
if best_y is None or n > best_y[0]:
|
|
||||||
best_y = (n, nm, t)
|
|
||||||
orig_attr_y = extract_attrinfo(best_y[2])
|
|
||||||
open('_orig_yida_attr.xml', 'w', encoding='utf-8').write(orig_attr_y)
|
|
||||||
|
|
||||||
print('=== xmldiff:易达实件 AttrInfo vs 导出件 AttrInfo ===')
|
|
||||||
diff_y = main.diff_texts(orig_attr_y, exp_attr)
|
|
||||||
for d in diff_y:
|
|
||||||
print(' ', d)
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
AttrInfo 区全部 74 行(不省略):
|
|
||||||
============================================================================
|
|
||||||
1| <AttrInfo> ← 开容器
|
|
||||||
2| <AttrInfoItem Name="工程类型" Value="土建与装饰工程"/> ← 自闭合 Name+Value
|
|
||||||
3| <AttrInfoItem Name="结构类型" Code="JGLX"/> ← 自闭合 Name+Code
|
|
||||||
4| <AttrInfoItem Name="基础类型" Code="JCLX"/> ← 自闭合 Name+Code
|
|
||||||
5| <AttrInfoItem Name="设防烈度" Code="SFLD"/> ← 自闭合 Name+Code
|
|
||||||
6| <AttrInfoItem Name="设计荷载" Code="SJHZ"/> ← 自闭合 Name+Code
|
|
||||||
7| <AttrInfoItem Name="主轴跨度(m)" Code="ZZKD"/> ← 自闭合 Name+Code
|
|
||||||
8| <AttrInfoItem Name="建筑特征" Code="JZTZ"/> ← 自闭合 Name+Code
|
|
||||||
9| <AttrInfoItem Name="建设规模(㎡)" Code="JSGM"/> ← 自闭合 Name+Code
|
|
||||||
10| <AttrInfoItem Name="±0.00以上建设规模(㎡)" Code="LYSJSGM"/> ← 自闭合 Name+Code
|
|
||||||
11| <AttrInfoItem Name="±0.00以下建设规模(㎡)" Code="LYXJSGM"/> ← 自闭合 Name+Code
|
|
||||||
12| <AttrInfoItem Name="总层数" Code="ZCS"/> ← 自闭合 Name+Code
|
|
||||||
13| <AttrInfoItem Name="地上总层数" Code="DSZCS"/> ← 自闭合 Name+Code
|
|
||||||
14| <AttrInfoItem Name="地下总层数" Code="DXZCS"/> ← 自闭合 Name+Code
|
|
||||||
15| <AttrInfoItem Name="地上总高度(m)" Code="DSZGD"/> ← 自闭合 Name+Code
|
|
||||||
16| <AttrInfoItem Name="地下层高度(m)" Code="DXCGD"/> ← 自闭合 Name+Code
|
|
||||||
17| <AttrInfoItem Name="首层层高(m)" Code="SCCG"/> ← 自闭合 Name+Code
|
|
||||||
18| <AttrInfoItem Name="地上标准层层高(m)" Code="QTBZCCG"/> ← 自闭合 Name+Code
|
|
||||||
19| <AttrInfoItem Name="地质条件描述" Code="DZTJMS"/> ← 自闭合 Name+Code
|
|
||||||
20| <AttrInfoItem Name="基坑" Code="JK"> ← 开容器
|
|
||||||
21| <AttrInfoItem Name="基坑围护周长(不含放坡)(m)" Value="" Code="JKWHZC" Remark=""/> ← 自闭合四列
|
|
||||||
22| <AttrInfoItem Name="围合面积(不含放坡)(㎡)" Value="" Code="WHMJ" Remark=""/> ← 自闭合四列
|
|
||||||
23| <AttrInfoItem Name="基坑深度(m)" Value="" Code="JKSD" Remark=""/> ← 自闭合四列
|
|
||||||
24| <AttrInfoItem Name="基坑支护方式" Value="" Code="JKZHFS" Remark=""/> ← 自闭合四列
|
|
||||||
25| <AttrInfoItem Name="基坑底面积(㎡)" Value="" Code="JKDMJ" Remark=""/> ← 自闭合四列
|
|
||||||
26| </AttrInfoItem> ← 开容器
|
|
||||||
27| <AttrInfoItem Name="钻孔灌注桩" Code="ZKGZZ"> ← 开容器
|
|
||||||
28| <AttrInfoItem Name="水泥土搅拌桩止水帷幕" Value="" Code="SNTJBZZSWM" Remark=""/> ← 自闭合四列
|
|
||||||
29| <AttrInfoItem Name="预应力锚杆" Value="" Code="YYLMG" Remark=""/> ← 自闭合四列
|
|
||||||
30| <AttrInfoItem Name="土钉墙" Value="" Code="TDQ" Remark=""/> ← 自闭合四列
|
|
||||||
31| <AttrInfoItem Name="基坑降水" Value="" Code="JKJS" Remark=""/> ← 自闭合四列
|
|
||||||
32| </AttrInfoItem> ← 开容器
|
|
||||||
33| <AttrInfoItem Name="塔楼" Code="TL"> ← 开容器
|
|
||||||
34| <AttrInfoItem Name="塔楼层高(m)" Value="" Code="TLCG" Remark=""/> ← 自闭合四列
|
|
||||||
35| <AttrInfoItem Name="塔楼层数" Value="" Code="TLCS" Remark=""/> ← 自闭合四列
|
|
||||||
36| </AttrInfoItem> ← 开容器
|
|
||||||
37| <AttrInfoItem Name="裙楼" Code="QL"> ← 开容器
|
|
||||||
38| <AttrInfoItem Name="裙楼层高(m)" Value="" Code="QLCG" Remark=""/> ← 自闭合四列
|
|
||||||
39| <AttrInfoItem Name="裙楼层数" Value="" Code="QLCS" Remark=""/> ← 自闭合四列
|
|
||||||
40| </AttrInfoItem> ← 开容器
|
|
||||||
41| <AttrInfoItem Name="人防" Code="RF"/> ← 自闭合 Name+Code
|
|
||||||
42| <AttrInfoItem Name="基础形式" Code="JCXS"> ← 开容器
|
|
||||||
43| <AttrInfoItem Name="基础材料" Value="" Code="JCCL" Remark=""/> ← 自闭合四列
|
|
||||||
44| <AttrInfoItem Name="桩规格(mm)" Value="" Code="ZGG" Remark=""/> ← 自闭合四列
|
|
||||||
45| <AttrInfoItem Name="岩土分类(土质)" Value="" Code="YTFL" Remark=""/> ← 自闭合四列
|
|
||||||
46| <AttrInfoItem Name="弃土运距(km)" Value="" Code="QTYJ" Remark=""/> ← 自闭合四列
|
|
||||||
47| </AttrInfoItem> ← 开容器
|
|
||||||
48| <AttrInfoItem Name="柱" Code="Z"/> ← 自闭合 Name+Code
|
|
||||||
49| <AttrInfoItem Name="梁" Code="L"/> ← 自闭合 Name+Code
|
|
||||||
50| <AttrInfoItem Name="板" Code="B"/> ← 自闭合 Name+Code
|
|
||||||
51| <AttrInfoItem Name="混凝土墙" Code="HNTQ"> ← 开容器
|
|
||||||
52| <AttrInfoItem Name="材质" Value="" Code="CZ" Remark=""/> ← 自闭合四列
|
|
||||||
53| <AttrInfoItem Name="外墙厚度(mm)" Value="" Code="WQHD" Remark=""/> ← 自闭合四列
|
|
||||||
54| <AttrInfoItem Name="内墙厚度(mm)" Value="" Code="NQHD" Remark=""/> ← 自闭合四列
|
|
||||||
55| </AttrInfoItem> ← 开容器
|
|
||||||
56| <AttrInfoItem Name="门窗" Code="MC"> ← 开容器
|
|
||||||
57| <AttrInfoItem Name="门窗玻璃厚度(mm)" Value="" Code="MCBLHD" Remark=""/> ← 自闭合四列
|
|
||||||
58| <AttrInfoItem Name="门窗材料及装饰" Value="" Code="MCCLJZS" Remark=""/> ← 自闭合四列
|
|
||||||
59| </AttrInfoItem> ← 开容器
|
|
||||||
60| <AttrInfoItem Name="砖砌体" Code="ZQT"/> ← 自闭合 Name+Code
|
|
||||||
61| <AttrInfoItem Name="装饰装修" Code="ZSZX"> ← 开容器
|
|
||||||
62| <AttrInfoItem Name="外部装饰" Value="" Code="WBZS" Remark=""> ← 开容器
|
|
||||||
63| <AttrInfoItem Name="屋面材质" Value="" Code="WMCZ" Remark=""/> ← 自闭合四列
|
|
||||||
64| <AttrInfoItem Name="外墙材质" Value="" Code="WQCZ" Remark=""/> ← 自闭合四列
|
|
||||||
65| <AttrInfoItem Name="其他" Value="" Code="QT" Remark=""/> ← 自闭合四列
|
|
||||||
66| </AttrInfoItem> ← 开容器
|
|
||||||
67| <AttrInfoItem Name="内部装饰" Value="" Code="NBZS" Remark=""> ← 开容器
|
|
||||||
68| <AttrInfoItem Name="内墙材质" Value="" Code="NQCZ" Remark=""/> ← 自闭合四列
|
|
||||||
69| <AttrInfoItem Name="地面材质" Value="" Code="DMCZ" Remark=""/> ← 自闭合四列
|
|
||||||
70| <AttrInfoItem Name="天棚材质" Value="" Code="TPCZ" Remark=""/> ← 自闭合四列
|
|
||||||
71| </AttrInfoItem> ← 开容器
|
|
||||||
72| </AttrInfoItem> ← 开容器
|
|
||||||
73| <AttrInfoItem Name="交楼标准" Code="JLBZ"/> ← 自闭合 Name+Code
|
|
||||||
74| </AttrInfo> ← 开容器
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
AttrInfo 树(权威 ET 解析;L行号=原文行):共 32 条顶层 AttrInfoItem
|
|
||||||
[L2] AttrInfoItem Name="工程类型" ——自闭合
|
|
||||||
[L3] AttrInfoItem Name="结构类型"(JGLX) ——自闭合
|
|
||||||
[L4] AttrInfoItem Name="基础类型"(JCLX) ——自闭合
|
|
||||||
[L5] AttrInfoItem Name="设防烈度"(SFLD) ——自闭合
|
|
||||||
[L6] AttrInfoItem Name="设计荷载"(SJHZ) ——自闭合
|
|
||||||
[L7] AttrInfoItem Name="主轴跨度(m)"(ZZKD) ——自闭合
|
|
||||||
[L8] AttrInfoItem Name="建筑特征"(JZTZ) ——自闭合
|
|
||||||
[L9] AttrInfoItem Name="建设规模(㎡)"(JSGM) ——自闭合
|
|
||||||
[L10] AttrInfoItem Name="±0.00以上建设规模(㎡)"(LYSJSGM) ——自闭合
|
|
||||||
[L11] AttrInfoItem Name="±0.00以下建设规模(㎡)"(LYXJSGM) ——自闭合
|
|
||||||
[L12] AttrInfoItem Name="总层数"(ZCS) ——自闭合
|
|
||||||
[L13] AttrInfoItem Name="地上总层数"(DSZCS) ——自闭合
|
|
||||||
[L14] AttrInfoItem Name="地下总层数"(DXZCS) ——自闭合
|
|
||||||
[L15] AttrInfoItem Name="地上总高度(m)"(DSZGD) ——自闭合
|
|
||||||
[L16] AttrInfoItem Name="地下层高度(m)"(DXCGD) ——自闭合
|
|
||||||
[L17] AttrInfoItem Name="首层层高(m)"(SCCG) ——自闭合
|
|
||||||
[L18] AttrInfoItem Name="地上标准层层高(m)"(QTBZCCG) ——自闭合
|
|
||||||
[L19] AttrInfoItem Name="地质条件描述"(DZTJMS) ——自闭合
|
|
||||||
[L20~L20] AttrInfoItem Name="基坑"(JK)
|
|
||||||
[L21] AttrInfoItem Name="基坑围护周长(不含放坡)(m)"(JKWHZC) ——自闭合
|
|
||||||
[L22] AttrInfoItem Name="围合面积(不含放坡)(㎡)"(WHMJ) ——自闭合
|
|
||||||
[L23] AttrInfoItem Name="基坑深度(m)"(JKSD) ——自闭合
|
|
||||||
[L24] AttrInfoItem Name="基坑支护方式"(JKZHFS) ——自闭合
|
|
||||||
[L25] AttrInfoItem Name="基坑底面积(㎡)"(JKDMJ) ——自闭合
|
|
||||||
[L27~L27] AttrInfoItem Name="钻孔灌注桩"(ZKGZZ)
|
|
||||||
[L28] AttrInfoItem Name="水泥土搅拌桩止水帷幕"(SNTJBZZSWM) ——自闭合
|
|
||||||
[L29] AttrInfoItem Name="预应力锚杆"(YYLMG) ——自闭合
|
|
||||||
[L30] AttrInfoItem Name="土钉墙"(TDQ) ——自闭合
|
|
||||||
[L31] AttrInfoItem Name="基坑降水"(JKJS) ——自闭合
|
|
||||||
[L33~L33] AttrInfoItem Name="塔楼"(TL)
|
|
||||||
[L34] AttrInfoItem Name="塔楼层高(m)"(TLCG) ——自闭合
|
|
||||||
[L35] AttrInfoItem Name="塔楼层数"(TLCS) ——自闭合
|
|
||||||
[L37~L37] AttrInfoItem Name="裙楼"(QL)
|
|
||||||
[L38] AttrInfoItem Name="裙楼层高(m)"(QLCG) ——自闭合
|
|
||||||
[L39] AttrInfoItem Name="裙楼层数"(QLCS) ——自闭合
|
|
||||||
[L41] AttrInfoItem Name="人防"(RF) ——自闭合
|
|
||||||
[L42~L42] AttrInfoItem Name="基础形式"(JCXS)
|
|
||||||
[L43] AttrInfoItem Name="基础材料"(JCCL) ——自闭合
|
|
||||||
[L44] AttrInfoItem Name="桩规格(mm)"(ZGG) ——自闭合
|
|
||||||
[L45] AttrInfoItem Name="岩土分类(土质)"(YTFL) ——自闭合
|
|
||||||
[L46] AttrInfoItem Name="弃土运距(km)"(QTYJ) ——自闭合
|
|
||||||
[L48] AttrInfoItem Name="柱"(Z) ——自闭合
|
|
||||||
[L49] AttrInfoItem Name="梁"(L) ——自闭合
|
|
||||||
[L50] AttrInfoItem Name="板"(B) ——自闭合
|
|
||||||
[L51~L51] AttrInfoItem Name="混凝土墙"(HNTQ)
|
|
||||||
[L52] AttrInfoItem Name="材质"(CZ) ——自闭合
|
|
||||||
[L53] AttrInfoItem Name="外墙厚度(mm)"(WQHD) ——自闭合
|
|
||||||
[L54] AttrInfoItem Name="内墙厚度(mm)"(NQHD) ——自闭合
|
|
||||||
[L56~L56] AttrInfoItem Name="门窗"(MC)
|
|
||||||
[L57] AttrInfoItem Name="门窗玻璃厚度(mm)"(MCBLHD) ——自闭合
|
|
||||||
[L58] AttrInfoItem Name="门窗材料及装饰"(MCCLJZS) ——自闭合
|
|
||||||
[L60] AttrInfoItem Name="砖砌体"(ZQT) ——自闭合
|
|
||||||
[L61~L61] AttrInfoItem Name="装饰装修"(ZSZX)
|
|
||||||
[L62~L62] AttrInfoItem Name="外部装饰"(WBZS)
|
|
||||||
[L63] AttrInfoItem Name="屋面材质"(WMCZ) ——自闭合
|
|
||||||
[L64] AttrInfoItem Name="外墙材质"(WQCZ) ——自闭合
|
|
||||||
[L65] AttrInfoItem Name="其他"(QT) ——自闭合
|
|
||||||
[L67~L67] AttrInfoItem Name="内部装饰"(NBZS)
|
|
||||||
[L68] AttrInfoItem Name="内墙材质"(NQCZ) ——自闭合
|
|
||||||
[L69] AttrInfoItem Name="地面材质"(DMCZ) ——自闭合
|
|
||||||
[L70] AttrInfoItem Name="天棚材质"(TPCZ) ——自闭合
|
|
||||||
[L73] AttrInfoItem Name="交楼标准"(JLBZ) ——自闭合
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
==================== GLD 45 xml files
|
|
||||||
AddiInfoItem files=45 Code,Name,Remark,Value
|
|
||||||
AttrInfoItem files=44 Code,Name,Remark,Value
|
|
||||||
ConstructionProject files=1 AreaKind,BulidUnit,ConstructionType,Explains,FileKind,Name,Number,ProjectArea,ProjectCategory,ProjectSite,ProjectType,RangeOfCompilation,Scale,ScaleName,StandardName,StandardNumber,StandardVersion,TaxModel,TechnicalAndEconomicIndex,Unit,ValuationModel
|
|
||||||
DayWorkRate files=45 Code,Name,Remark,Total
|
|
||||||
DayWorkRateGroup files=45 Code,Name,Remark,Total
|
|
||||||
DivisionalWorks files=8 ChapterKind,Code,Kind,Name,Number,Remark,Total
|
|
||||||
LabourMaterialsEquipmentsMachinesElement files=22 Express,Number,Quantity,Remark
|
|
||||||
LabourMaterialsEquipmentsMachinesSummary files=23 Character,Class,Concrete,Delivery,ExtKind,Kind,Location,MainMaterial,Name,NoTaxOrgPrice,NoTaxOrgTotal,NoTaxPrice,NoTaxTotal,Number,PriceSource,ProducingArea,Provider,ProviderBase,ProvisionalMaterial,Quantity,Remark,Specification,Supplier,TaxOrgPrice,TaxOrgTotal,TaxPrice,TaxRate,TaxTotal,Unit,Weight
|
|
||||||
MainContractorAttendance files=45 Code,Name,Remark,Total
|
|
||||||
MainContractorAttendanceItem files=45 Content,Kind,Name,QtyFormula,Quantity,Rate,Remark,Total
|
|
||||||
Norm files=22 CalculationKind,CostKind,EfficiencyKind,IncFeeKind,IsNorm,Name,NormIdentity,Number,Price,Quantity,Remark,Specialty,Total,Type,Unit
|
|
||||||
NormAdjustmentList files=22 OrderNumber,Value
|
|
||||||
Option files=1 CostPrecision,QuantityPrecision,RatePrecision,ResPrecision
|
|
||||||
PreliminaryWorkElement files=1 CalcType,Code,InitialFee,InitialPercent,Kind,LastFee,LastPercent,ListingIdentity,LockKind,MediumFee,MediumPercent,Name,Number,Price,QtyFormula,Quantity,Rate,Remark,Specialty,SupplementaryList,Total,Unit,WorkContent
|
|
||||||
ProjectInfo files=1 Authorizer,CompileCompany,CompileDate,Total
|
|
||||||
ProjectInstallationWorkCost files=1 Name,Number,Ratios,Scale,ScaleName,Total,Unit
|
|
||||||
ProjectInstallationWorkCostSummaryGroup files=1 Code,Kind,Name,Number,Remark,Total
|
|
||||||
ProjectInstallationWorkCostSummaryItem files=1 Code,Kind,Name,Number,QtyFormula,Rate,Remark,Total
|
|
||||||
ProvisionalMaterialEquipment files=45 Code,Name,Remark,Total
|
|
||||||
ProvisionalSums files=45 Code,Name,Remark,Total
|
|
||||||
ProvisionalSumsItem files=45 Kind,Name,Price,QtyFormula,Quantity,Rate,Remark,Total,Unit
|
|
||||||
SectionalWorks files=1 AreaKind,BulidUnit,ConstructionType,FileKind,Name,ProjectArea,ProjectCategory,ProjectType,Ratios,Scale,ScaleName,Segment,StandardName,StandardNumber,StandardVersion,TaxModel,Total,Unit,ValuationModel
|
|
||||||
SpecialtyProvisionalPrice files=45 Code,Name,NoTaxTotal,Remark,Tax,Total
|
|
||||||
SummaryOfBasicCost files=45 CostForHSE,DivisionalAndElementalWorks,Equipment,Labor,Machine,MainMaterial,MainMaterialEquipment,Material,Overhead,Preliminaries,Profit,ProvisionalMaterialEquipment,ProvisionalSums,Tax
|
|
||||||
SummaryOfCost files=45 ClaimForLossAndExpenses,CostForHSE,DayWorkRate,DivisionalAndElementalWorks,Equipment,Labor,Machine,MainContractorAttendance,MainMaterial,MainMaterialEquipment,Material,Overhead,Preliminaries,Profit,ProvisionalMaterialEquipment,ProvisionalSums,SpecialtyProvisionalPrice,SundryCosts,Tax,Total
|
|
||||||
SundryCosts files=45 Code,Name,Remark,Total
|
|
||||||
SundryCostsItem files=45 Code,Kind,Name,Price,QtyFormula,Quantity,Rate,Remark,Total,Unit
|
|
||||||
SystemInfo files=1 ID1,ID2,MakeDate1,MakeDate2
|
|
||||||
Tax files=45 CalBasis,Code,Name,QtyFormula,Rate,Remark,Total
|
|
||||||
TendereeInfo files=1 Consultant,Proxy,TenderAuthorizer,TenderCompileDate,TenderCompiler,TenderExaminer,TenderSumLimit,TendereeName
|
|
||||||
UnitPriceCalculationOfItem files=22 Code,Name,QtyFormula,Rate,Remark,Total
|
|
||||||
UnitWorks files=45 AreaKind,BillDataBase,FileName,Name,NormDataBase,Number,ProjectCategory,ProjectType,Ratios,ResInfoPricingFile,Scale,ScaleName,Segment,Specialty,TaxModel,Total,Unit,ValuationModel
|
|
||||||
UnitWorksPreliminaryWorkElement files=22 CalcType,Code,InitialFee,InitialPercent,Kind,LastFee,LastPercent,ListingIdentity,LockKind,MediumFee,MediumPercent,Name,Number,Price,PriceType,QtyFormula,Quantity,Rate,Remark,Specialty,SupplementaryList,Total,Unit,WorkContent
|
|
||||||
UnitWorksSummaryGroup files=44 ChapterKind,Code,Kind,Name,Number,Remark,Total
|
|
||||||
UnitWorksSummaryItem files=44 ChapterKind,Code,Kind,Name,Number,QtyFormula,Rate,Remark,Total
|
|
||||||
WorkContent files=22 Name,Remark,Total
|
|
||||||
WorkElement files=22 Attr,CalcType,CalculationKind,Code,CostKind,EquipmentPrice,EquipmentTotal,Kind,ListingIdentity,LockKind,Major,Name,Number,Price,PriceHigh,PriceType,Quantity,QuantityCalculationRules,Rate,Remark,Specialty,SupplementaryList,Total,Type,Unit,WorkContent
|
|
||||||
==================== YD 32 xml files
|
|
||||||
AddiCost files=32 Code,Name,Total
|
|
||||||
AddiInfoItem files=32 Code,Name,Remark,Value
|
|
||||||
AttrInfoItem files=32 Code,Name,Remark,Value
|
|
||||||
BidderInfo files=1 BidApproveDate,BidApprover,BidApproverCertNo,BidAuthorizer,BidCompileDate,BidCompiler,BidCompilerCertNo,BidExamineDate,BidExaminer,BidExaminerCertNo,BidName,BidTotal
|
|
||||||
ChangeCost files=1 Code,Name,Number,Remark,Total
|
|
||||||
ClaimsCost files=1 Code,Name,Remark,Total
|
|
||||||
ConstructionProject files=1 AreaKind,BulidAuthorizer,BulidUnit,ConstructionType,Explains,FileKind,Name,Number,ProjectArea,ProjectCategory,ProjectSite,ProjectType,RangeOfCompilation,Scale,ScaleName,StandardName,StandardNumber,StandardVersion,TaxModel,TechnicalAndEconomicIndex,Unit,ValuationModel
|
|
||||||
DayWorkRate files=1 Code,Name,Remark,Total
|
|
||||||
DayWorkRateGroup files=1 Code,Name,Remark,Total
|
|
||||||
DivisionalWorks files=1 Attr,ChapterKind,Code,Kind,Name,Number,Quantity,QuantityCalculationRules,Remark,TechnicalAndEconomicIndex,Total,Unit,WorkContent
|
|
||||||
ExpressElement files=3 Area,BuildingComponents,Explain,Express,Kind,OrderNumber,Quantity,Remark
|
|
||||||
LabourMaterialsEquipmentsMachinesElement files=4 Express,Number,Quantity,Remark
|
|
||||||
LabourMaterialsEquipmentsMachinesSummary files=4 AddiKind,Character,Class,Concrete,Delivery,ExtKind,Kind,Location,LossRate,MainMaterial,Name,NoTaxOrgPrice,NoTaxOrgTotal,NoTaxPrice,NoTaxPriceExpress,NoTaxTotal,Number,PriceSource,ProducingArea,Provider,ProvisionalMaterial,Quantity,Remark,Specification,Supplier,TaxOrgPrice,TaxOrgTotal,TaxPrice,TaxPriceExpress,TaxRate,TaxTotal,Unit
|
|
||||||
LawsRegulationsAndPolicyChangeProjects files=1 Code,Name,Remark,Total
|
|
||||||
MainContractorAttendance files=1 Code,Name,Remark,Total
|
|
||||||
MainContractorAttendanceItem files=1 Content,Kind,Name,QtyFormula,Quantity,Rate,Remark,Total
|
|
||||||
Norm files=3 CalculationKind,Chapter,CostKind,EfficiencyKind,EquipmentPrice,EquipmentTotal,IncFeeKind,IsNorm,Name,NormIdentity,Number,Price,Quantity,Remark,Specialty,Total,Type,Unit,Volume
|
|
||||||
NormAdjustmentList files=1 OrderNumber,Value
|
|
||||||
Option files=1 CostPrecision,QuantityPrecision,RatePrecision,ResPrecision
|
|
||||||
PreliminaryDivisionalWorks files=1 Code,Kind,Name,Number,Quantity,Remark,TechnicalAndEconomicIndex,Total,Unit,WorkContent
|
|
||||||
PreliminaryWorkElement files=1 CalcType,Code,InitialFee,InitialPercent,Kind,LastFee,LastPercent,ListingIdentity,LockKind,MediumFee,MediumPercent,Name,Number,Price,QtyFormula,Quantity,Rate,Remark,Specialty,SupplementaryList,Total,Unit,WorkContent
|
|
||||||
ProjectInfo files=1 Approver,ApproverCertNo,ApproverDate,Authorizer,CompileCompany,CompileDate,Compiler,CompilerCertNo,Contractor,Designer,ExamineDate,Examiner,ExaminerCertNo,Total
|
|
||||||
ProjectInstallationWorkCost files=1 Code,ConvertedIntoRMB,ForeignCurrency,Name,Number,Ratios,Remark,Scale,ScaleName,TechnicalAndEconomicIndex,Total,Unit
|
|
||||||
ProjectInstallationWorkCostSummaryGroup files=1 Code,Kind,Name,Number,Quantity,Ratios,Remark,TechnicalAndEconomicIndex,Total,Unit
|
|
||||||
ProjectInstallationWorkCostSummaryItem files=1 Code,Kind,Name,Number,QtyFormula,Quantity,Rate,Ratios,Remark,TechnicalAndEconomicIndex,Total,Unit
|
|
||||||
ProvisionalMaterialEquipment files=32 Code,Name,Remark,Total
|
|
||||||
ProvisionalSums files=32 Code,Name,Remark,Total
|
|
||||||
ProvisionalSumsGroup files=32 Kind,Name,Remark,Total
|
|
||||||
ProvisionalSumsItem files=32 Kind,Name,Price,QtyFormula,Quantity,Rate,Remark,Total,Unit
|
|
||||||
SectionalWorks files=1 AreaKind,BulidAuthorizer,BulidUnit,Code,ConstructionType,FileKind,Name,Number,ProjectArea,ProjectCategory,ProjectSite,ProjectType,RangeOfCompilation,Ratios,Remark,Scale,ScaleName,Segment,StandardName,StandardNumber,StandardVersion,TaxModel,TechnicalAndEconomicIndex,Total,Unit,ValuationModel
|
|
||||||
SpecialtyProvisionalPrice files=1 Code,Name,NoTaxTotal,Remark,Tax,Total
|
|
||||||
SummaryOfBasicCost files=32 CostForHSE,DivisionalAndElementalWorks,Equipment,Labor,Machine,MainMaterial,MainMaterialEquipment,Material,Overhead,Preliminaries,Profit,ProvisionalMaterialEquipment,ProvisionalSums,SundryCosts,Tax
|
|
||||||
SummaryOfCost files=32 ChangeCost,ClaimForLossAndExpenses,Construction,ConvertedIntoRMB,CostForHSE,DayWorkRate,DivisionalAndElementalWorks,Equipment,ForeignCurrency,Installation,Labor,LawsRegulationsAndPolicyChangeProjects,Machine,MainContractorAttendance,MainMaterial,MainMaterialEquipment,Material,Overhead,Preliminaries,Profit,ProvisionalMaterialEquipment,ProvisionalSums,SpecialtyProvisionalPrice,SundryCosts,Tax,Total
|
|
||||||
SundryCosts files=32 Code,Name,Remark,Total
|
|
||||||
SundryCostsItem files=32 Code,Kind,Name,Price,QtyFormula,Quantity,Rate,Remark,Total,Unit
|
|
||||||
SystemInfo files=1 ID1,ID2,MakeDate1,MakeDate2
|
|
||||||
Tax files=1 CalBasis,Code,Name,QtyFormula,Rate,Remark,Total
|
|
||||||
TendereeInfo files=1 Consultant,ConsultantApproveDate,ConsultantApprover,ConsultantApproverCertNo,ConsultantAuthorizer,ConsultantCompileDate,ConsultantCompiler,ConsultantCompilerCertNo,ConsultantExamineDate,ConsultantExaminer,ConsultantExaminerCertNo,ConsultantUSCI,Proxy,ProxyApproveDate,ProxyApprover,ProxyApproverCertNo,ProxyAuthorizer,ProxyCompileDate,ProxyCompiler,ProxyCompilerCertNo,ProxyExamineDate,ProxyExaminer,ProxyExaminerCertNo,ProxyUSCI,TenderApproveDate,TenderApprover,TenderApproverCertNo,TenderAuthorizer,TenderCompileDate,TenderCompiler,TenderCompilerCertNo,TenderExamineDate,TenderExaminer,TenderExaminerCertNo,TenderSumLimit,TendereeName
|
|
||||||
UnitPriceCalculationOfItem files=31 Code,Name,QtyFormula,Rate,Remark,Total
|
|
||||||
UnitWorks files=32 AppliedRateFile,AreaKind,BillDataBase,Code,Explains,FileName,Name,NormDataBase,Number,ProjectCategory,ProjectType,Purposes,QuantityCalculationRules,RangeOfCompilation,Ratios,Remark,ResInfoPricingFile,Scale,ScaleName,Segment,Specialty,TaxModel,TechnicalAndEconomicIndex,Total,Unit,ValuationModel,WorkContent
|
|
||||||
UnitWorksPreliminaryWorkElement files=31 CalcType,Code,InitialFee,InitialPercent,Kind,LastFee,LastPercent,ListingIdentity,LockKind,MediumFee,MediumPercent,Name,Number,Price,PriceType,QtyFormula,Quantity,Rate,Remark,Specialty,SupplementaryList,Total,Unit,WorkContent
|
|
||||||
UnitWorksSummaryGroup files=31 ChapterKind,Code,Kind,Name,Number,Quantity,Ratios,Remark,TechnicalAndEconomicIndex,Total,Unit
|
|
||||||
UnitWorksSummaryItem files=31 ChapterKind,Code,Kind,Name,Number,QtyFormula,Quantity,Rate,Ratios,Remark,TechnicalAndEconomicIndex,Total,Unit
|
|
||||||
WorkContent files=3 Name,Remark,Total
|
|
||||||
WorkElement files=3 Attr,CalcType,CalculationKind,Code,CostKind,EquipmentPrice,EquipmentTotal,Kind,ListingIdentity,LockKind,Major,Name,Number,Price,PriceHigh,PriceType,QtyFormula,Quantity,QuantityCalculationRules,Rate,Remark,Specialty,SupplementaryList,Total,Type,Unit,WorkContent
|
|
||||||
@@ -1,552 +0,0 @@
|
|||||||
{
|
|
||||||
"dir": "D:/PricingReview/_analysis/gld",
|
|
||||||
"xml_files": 45,
|
|
||||||
"elements": {
|
|
||||||
"AttrInfoItem": {
|
|
||||||
"_files": 44,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 2418,
|
|
||||||
"Name": 2462,
|
|
||||||
"Remark": 1292,
|
|
||||||
"Value": 1336
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"AddiInfoItem": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 399,
|
|
||||||
"Name": 575,
|
|
||||||
"Remark": 2,
|
|
||||||
"Value": 310
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SummaryOfCost": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"ClaimForLossAndExpenses": 44,
|
|
||||||
"CostForHSE": 46,
|
|
||||||
"DayWorkRate": 46,
|
|
||||||
"DivisionalAndElementalWorks": 46,
|
|
||||||
"Equipment": 46,
|
|
||||||
"Labor": 46,
|
|
||||||
"Machine": 46,
|
|
||||||
"MainContractorAttendance": 46,
|
|
||||||
"MainMaterial": 46,
|
|
||||||
"MainMaterialEquipment": 46,
|
|
||||||
"Material": 46,
|
|
||||||
"Overhead": 46,
|
|
||||||
"Preliminaries": 46,
|
|
||||||
"Profit": 46,
|
|
||||||
"ProvisionalMaterialEquipment": 2,
|
|
||||||
"ProvisionalSums": 46,
|
|
||||||
"SpecialtyProvisionalPrice": 46,
|
|
||||||
"SundryCosts": 46,
|
|
||||||
"Tax": 46,
|
|
||||||
"Total": 46
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SummaryOfBasicCost": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"CostForHSE": 45,
|
|
||||||
"DivisionalAndElementalWorks": 44,
|
|
||||||
"Equipment": 260,
|
|
||||||
"Labor": 260,
|
|
||||||
"Machine": 260,
|
|
||||||
"MainMaterial": 260,
|
|
||||||
"MainMaterialEquipment": 260,
|
|
||||||
"Material": 260,
|
|
||||||
"Overhead": 260,
|
|
||||||
"Preliminaries": 45,
|
|
||||||
"Profit": 260,
|
|
||||||
"ProvisionalMaterialEquipment": 222,
|
|
||||||
"ProvisionalSums": 76,
|
|
||||||
"Tax": 260
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SundryCostsItem": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 270,
|
|
||||||
"Kind": 270,
|
|
||||||
"Name": 270,
|
|
||||||
"Price": 270,
|
|
||||||
"QtyFormula": 270,
|
|
||||||
"Quantity": 270,
|
|
||||||
"Rate": 270,
|
|
||||||
"Remark": 270,
|
|
||||||
"Total": 270,
|
|
||||||
"Unit": 270
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SundryCosts": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProvisionalSumsItem": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Kind": 180,
|
|
||||||
"Name": 180,
|
|
||||||
"Price": 180,
|
|
||||||
"QtyFormula": 180,
|
|
||||||
"Quantity": 180,
|
|
||||||
"Rate": 180,
|
|
||||||
"Remark": 180,
|
|
||||||
"Total": 180,
|
|
||||||
"Unit": 180
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProvisionalSums": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SpecialtyProvisionalPrice": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"NoTaxTotal": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Tax": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"DayWorkRateGroup": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 135,
|
|
||||||
"Name": 135,
|
|
||||||
"Remark": 135,
|
|
||||||
"Total": 135
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"DayWorkRate": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"MainContractorAttendanceItem": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Content": 135,
|
|
||||||
"Kind": 135,
|
|
||||||
"Name": 135,
|
|
||||||
"QtyFormula": 135,
|
|
||||||
"Quantity": 135,
|
|
||||||
"Rate": 135,
|
|
||||||
"Remark": 135,
|
|
||||||
"Total": 135
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"MainContractorAttendance": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"Tax": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"CalBasis": 45,
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"QtyFormula": 45,
|
|
||||||
"Rate": 45,
|
|
||||||
"Remark": 45,
|
|
||||||
"Total": 45
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProvisionalMaterialEquipment": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 45,
|
|
||||||
"Name": 45,
|
|
||||||
"Remark": 44,
|
|
||||||
"Total": 44
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"UnitWorksSummaryItem": {
|
|
||||||
"_files": 44,
|
|
||||||
"attrs": {
|
|
||||||
"ChapterKind": 440,
|
|
||||||
"Code": 440,
|
|
||||||
"Kind": 440,
|
|
||||||
"Name": 440,
|
|
||||||
"Number": 440,
|
|
||||||
"QtyFormula": 440,
|
|
||||||
"Rate": 440,
|
|
||||||
"Remark": 440,
|
|
||||||
"Total": 440
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"UnitWorksSummaryGroup": {
|
|
||||||
"_files": 44,
|
|
||||||
"attrs": {
|
|
||||||
"ChapterKind": 88,
|
|
||||||
"Code": 88,
|
|
||||||
"Kind": 88,
|
|
||||||
"Name": 88,
|
|
||||||
"Number": 88,
|
|
||||||
"Remark": 88,
|
|
||||||
"Total": 88
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"UnitWorks": {
|
|
||||||
"_files": 45,
|
|
||||||
"attrs": {
|
|
||||||
"AreaKind": 88,
|
|
||||||
"BillDataBase": 88,
|
|
||||||
"FileName": 88,
|
|
||||||
"Name": 88,
|
|
||||||
"NormDataBase": 88,
|
|
||||||
"Number": 88,
|
|
||||||
"ProjectCategory": 88,
|
|
||||||
"ProjectType": 88,
|
|
||||||
"Ratios": 88,
|
|
||||||
"ResInfoPricingFile": 88,
|
|
||||||
"Scale": 88,
|
|
||||||
"ScaleName": 88,
|
|
||||||
"Segment": 88,
|
|
||||||
"Specialty": 88,
|
|
||||||
"TaxModel": 88,
|
|
||||||
"Total": 88,
|
|
||||||
"Unit": 88,
|
|
||||||
"ValuationModel": 88
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"LabourMaterialsEquipmentsMachinesElement": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"Express": 1746,
|
|
||||||
"Number": 1746,
|
|
||||||
"Quantity": 1746,
|
|
||||||
"Remark": 1746
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"UnitPriceCalculationOfItem": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 1242,
|
|
||||||
"Name": 1242,
|
|
||||||
"QtyFormula": 1242,
|
|
||||||
"Rate": 1242,
|
|
||||||
"Remark": 1242,
|
|
||||||
"Total": 1242
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"NormAdjustmentList": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"OrderNumber": 76,
|
|
||||||
"Value": 76
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"Norm": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"CalculationKind": 92,
|
|
||||||
"CostKind": 92,
|
|
||||||
"EfficiencyKind": 92,
|
|
||||||
"IncFeeKind": 92,
|
|
||||||
"IsNorm": 92,
|
|
||||||
"Name": 92,
|
|
||||||
"NormIdentity": 92,
|
|
||||||
"Number": 92,
|
|
||||||
"Price": 92,
|
|
||||||
"Quantity": 92,
|
|
||||||
"Remark": 92,
|
|
||||||
"Specialty": 92,
|
|
||||||
"Total": 92,
|
|
||||||
"Type": 92,
|
|
||||||
"Unit": 92
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"WorkContent": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"Name": 122,
|
|
||||||
"Remark": 122,
|
|
||||||
"Total": 122
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"WorkElement": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"Attr": 38,
|
|
||||||
"CalcType": 38,
|
|
||||||
"CalculationKind": 38,
|
|
||||||
"Code": 38,
|
|
||||||
"CostKind": 38,
|
|
||||||
"EquipmentPrice": 38,
|
|
||||||
"EquipmentTotal": 38,
|
|
||||||
"Kind": 38,
|
|
||||||
"ListingIdentity": 38,
|
|
||||||
"LockKind": 38,
|
|
||||||
"Major": 38,
|
|
||||||
"Name": 38,
|
|
||||||
"Number": 38,
|
|
||||||
"Price": 38,
|
|
||||||
"PriceHigh": 38,
|
|
||||||
"PriceType": 38,
|
|
||||||
"Quantity": 38,
|
|
||||||
"QuantityCalculationRules": 38,
|
|
||||||
"Rate": 38,
|
|
||||||
"Remark": 38,
|
|
||||||
"Specialty": 38,
|
|
||||||
"SupplementaryList": 38,
|
|
||||||
"Total": 38,
|
|
||||||
"Type": 38,
|
|
||||||
"Unit": 38,
|
|
||||||
"WorkContent": 38
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"UnitWorksPreliminaryWorkElement": {
|
|
||||||
"_files": 22,
|
|
||||||
"attrs": {
|
|
||||||
"CalcType": 96,
|
|
||||||
"Code": 96,
|
|
||||||
"InitialFee": 96,
|
|
||||||
"InitialPercent": 96,
|
|
||||||
"Kind": 96,
|
|
||||||
"LastFee": 96,
|
|
||||||
"LastPercent": 96,
|
|
||||||
"ListingIdentity": 96,
|
|
||||||
"LockKind": 96,
|
|
||||||
"MediumFee": 96,
|
|
||||||
"MediumPercent": 96,
|
|
||||||
"Name": 96,
|
|
||||||
"Number": 96,
|
|
||||||
"Price": 96,
|
|
||||||
"PriceType": 96,
|
|
||||||
"QtyFormula": 96,
|
|
||||||
"Quantity": 96,
|
|
||||||
"Rate": 96,
|
|
||||||
"Remark": 96,
|
|
||||||
"Specialty": 96,
|
|
||||||
"SupplementaryList": 96,
|
|
||||||
"Total": 96,
|
|
||||||
"Unit": 96,
|
|
||||||
"WorkContent": 96
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"LabourMaterialsEquipmentsMachinesSummary": {
|
|
||||||
"_files": 23,
|
|
||||||
"attrs": {
|
|
||||||
"Character": 673,
|
|
||||||
"Class": 673,
|
|
||||||
"Concrete": 33,
|
|
||||||
"Delivery": 33,
|
|
||||||
"ExtKind": 33,
|
|
||||||
"Kind": 673,
|
|
||||||
"Location": 673,
|
|
||||||
"MainMaterial": 673,
|
|
||||||
"Name": 673,
|
|
||||||
"NoTaxOrgPrice": 673,
|
|
||||||
"NoTaxOrgTotal": 673,
|
|
||||||
"NoTaxPrice": 673,
|
|
||||||
"NoTaxTotal": 673,
|
|
||||||
"Number": 673,
|
|
||||||
"PriceSource": 33,
|
|
||||||
"ProducingArea": 673,
|
|
||||||
"Provider": 673,
|
|
||||||
"ProviderBase": 673,
|
|
||||||
"ProvisionalMaterial": 673,
|
|
||||||
"Quantity": 673,
|
|
||||||
"Remark": 673,
|
|
||||||
"Specification": 673,
|
|
||||||
"Supplier": 673,
|
|
||||||
"TaxOrgPrice": 673,
|
|
||||||
"TaxOrgTotal": 673,
|
|
||||||
"TaxPrice": 673,
|
|
||||||
"TaxRate": 673,
|
|
||||||
"TaxTotal": 673,
|
|
||||||
"Unit": 673,
|
|
||||||
"Weight": 673
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"DivisionalWorks": {
|
|
||||||
"_files": 8,
|
|
||||||
"attrs": {
|
|
||||||
"ChapterKind": 32,
|
|
||||||
"Code": 32,
|
|
||||||
"Kind": 32,
|
|
||||||
"Name": 32,
|
|
||||||
"Number": 32,
|
|
||||||
"Remark": 32,
|
|
||||||
"Total": 32
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SystemInfo": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"ID1": 1,
|
|
||||||
"ID2": 1,
|
|
||||||
"MakeDate1": 1,
|
|
||||||
"MakeDate2": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"Option": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"CostPrecision": 1,
|
|
||||||
"QuantityPrecision": 1,
|
|
||||||
"RatePrecision": 1,
|
|
||||||
"ResPrecision": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProjectInfo": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"Authorizer": 1,
|
|
||||||
"CompileCompany": 1,
|
|
||||||
"CompileDate": 1,
|
|
||||||
"Total": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"TendereeInfo": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"Consultant": 1,
|
|
||||||
"Proxy": 1,
|
|
||||||
"TenderAuthorizer": 1,
|
|
||||||
"TenderCompileDate": 1,
|
|
||||||
"TenderCompiler": 1,
|
|
||||||
"TenderExaminer": 1,
|
|
||||||
"TenderSumLimit": 1,
|
|
||||||
"TendereeName": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProjectInstallationWorkCostSummaryItem": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 52,
|
|
||||||
"Kind": 52,
|
|
||||||
"Name": 52,
|
|
||||||
"Number": 52,
|
|
||||||
"QtyFormula": 52,
|
|
||||||
"Rate": 52,
|
|
||||||
"Remark": 52,
|
|
||||||
"Total": 52
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProjectInstallationWorkCostSummaryGroup": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"Code": 5,
|
|
||||||
"Kind": 5,
|
|
||||||
"Name": 5,
|
|
||||||
"Number": 5,
|
|
||||||
"Remark": 5,
|
|
||||||
"Total": 5
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"SectionalWorks": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"AreaKind": 2,
|
|
||||||
"BulidUnit": 2,
|
|
||||||
"ConstructionType": 2,
|
|
||||||
"FileKind": 2,
|
|
||||||
"Name": 2,
|
|
||||||
"ProjectArea": 2,
|
|
||||||
"ProjectCategory": 2,
|
|
||||||
"ProjectType": 2,
|
|
||||||
"Ratios": 2,
|
|
||||||
"Scale": 2,
|
|
||||||
"ScaleName": 2,
|
|
||||||
"Segment": 2,
|
|
||||||
"StandardName": 2,
|
|
||||||
"StandardNumber": 2,
|
|
||||||
"StandardVersion": 2,
|
|
||||||
"TaxModel": 2,
|
|
||||||
"Total": 2,
|
|
||||||
"Unit": 2,
|
|
||||||
"ValuationModel": 2
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"PreliminaryWorkElement": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"CalcType": 5,
|
|
||||||
"Code": 5,
|
|
||||||
"InitialFee": 5,
|
|
||||||
"InitialPercent": 5,
|
|
||||||
"Kind": 5,
|
|
||||||
"LastFee": 5,
|
|
||||||
"LastPercent": 5,
|
|
||||||
"ListingIdentity": 5,
|
|
||||||
"LockKind": 5,
|
|
||||||
"MediumFee": 5,
|
|
||||||
"MediumPercent": 5,
|
|
||||||
"Name": 5,
|
|
||||||
"Number": 5,
|
|
||||||
"Price": 5,
|
|
||||||
"QtyFormula": 5,
|
|
||||||
"Quantity": 5,
|
|
||||||
"Rate": 5,
|
|
||||||
"Remark": 5,
|
|
||||||
"Specialty": 5,
|
|
||||||
"SupplementaryList": 5,
|
|
||||||
"Total": 5,
|
|
||||||
"Unit": 5,
|
|
||||||
"WorkContent": 5
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ProjectInstallationWorkCost": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"Name": 1,
|
|
||||||
"Number": 1,
|
|
||||||
"Ratios": 1,
|
|
||||||
"Scale": 1,
|
|
||||||
"ScaleName": 1,
|
|
||||||
"Total": 1,
|
|
||||||
"Unit": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"ConstructionProject": {
|
|
||||||
"_files": 1,
|
|
||||||
"attrs": {
|
|
||||||
"AreaKind": 1,
|
|
||||||
"BulidUnit": 1,
|
|
||||||
"ConstructionType": 1,
|
|
||||||
"Explains": 1,
|
|
||||||
"FileKind": 1,
|
|
||||||
"Name": 1,
|
|
||||||
"Number": 1,
|
|
||||||
"ProjectArea": 1,
|
|
||||||
"ProjectCategory": 1,
|
|
||||||
"ProjectSite": 1,
|
|
||||||
"ProjectType": 1,
|
|
||||||
"RangeOfCompilation": 1,
|
|
||||||
"Scale": 1,
|
|
||||||
"ScaleName": 1,
|
|
||||||
"StandardName": 1,
|
|
||||||
"StandardNumber": 1,
|
|
||||||
"StandardVersion": 1,
|
|
||||||
"TaxModel": 1,
|
|
||||||
"TechnicalAndEconomicIndex": 1,
|
|
||||||
"Unit": 1,
|
|
||||||
"ValuationModel": 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""收集一个目录下所有 XML 的 元素->属性名集合(只读)。
|
|
||||||
输出 JSON:{element: {attr: [出现的文件数, 出现次数]}}
|
|
||||||
"""
|
|
||||||
import sys, os, json, collections
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
|
|
||||||
|
|
||||||
def walk(path):
|
|
||||||
result = collections.defaultdict(collections.Counter) # elem -> attr -> count
|
|
||||||
files = collections.defaultdict(set) # elem -> set(files)
|
|
||||||
nfiles = 0
|
|
||||||
for root, _dirs, names in os.walk(path):
|
|
||||||
for n in names:
|
|
||||||
if not n.lower().endswith(".xml"):
|
|
||||||
continue
|
|
||||||
fp = os.path.join(root, n)
|
|
||||||
nfiles += 1
|
|
||||||
try:
|
|
||||||
for _ev, el in ET.iterparse(fp, events=("end",)):
|
|
||||||
tag = el.tag
|
|
||||||
if not isinstance(tag, str):
|
|
||||||
continue
|
|
||||||
for a in el.attrib:
|
|
||||||
result[tag][a] += 1
|
|
||||||
files[tag].add(n)
|
|
||||||
el.clear()
|
|
||||||
except Exception as e:
|
|
||||||
print("ERR", fp, e, file=sys.stderr)
|
|
||||||
out = {}
|
|
||||||
for tag, attrs in result.items():
|
|
||||||
out[tag] = {
|
|
||||||
"_files": len(files[tag]),
|
|
||||||
"attrs": {a: c for a, c in sorted(attrs.items())},
|
|
||||||
}
|
|
||||||
print(json.dumps({"dir": path, "xml_files": nfiles, "elements": out},
|
|
||||||
ensure_ascii=False, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
walk(sys.argv[1])
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""以 DBJ/T 15-145-2025 第6章为基准,比对两家 cos4 实际导出属性。
|
|
||||||
输出:每元素 → {特有(无对应), 拼写差异(疑似对应), 标准有但未导出}"""
|
|
||||||
import json, difflib
|
|
||||||
|
|
||||||
STD = {
|
|
||||||
"ConstructionProject": "Number Name ProjectCategory ProjectType ConstructionType FileKind ValuationModel TaxModel AreaKind ProjectArea ProjectSite BuildUnit BuildAuthorizer StandardName StandardNumber StandardVersion RangeOfCompilation ScaleName Scale Unit ProjectIndex LabourPriceIndex MaterialPriceIndex MachinePriceIndex TechnicalAndEconomicIndex Explains",
|
|
||||||
"SystemInfo": "ID1 ID2 MakeDate1 MakeDate2",
|
|
||||||
"Option": "ResPrecision QuantityPrecision CostPrecision RatePrecision",
|
|
||||||
"ProjectInfo": "Designer Contractor CompileCompany Authorizer Compiler CompilerCertNo CompileDate Examiner ExaminerCertNo ExamineDate Approver ApproverCertNo ApproverDate Total",
|
|
||||||
"TendereeInfo": "TendereeName TenderAuthorizer TenderCompiler TenderCompilerCertNo TenderCompileDate TenderExaminer TenderExaminerCertNo TenderExamineDate TenderApprover TenderApproverCertNo TenderApproveDate Proxy ProxyAuthorizer ProxyUSCI ProxyCompiler ProxyCompilerCertNo ProxyCompileDate ProxyExaminer ProxyExaminerCertNo ProxyExamineDate ProxyApprover ProxyApproverCertNo ProxyApproveDate Consultant ConsultantUSCI ConsultantAuthorizer ConsultantCompiler ConsultantCompilerCertNo ConsultantCompileDate ConsultantExaminer ConsultantExaminerCertNo ConsultantExamineDate ConsultantApprover ConsultantApproverCertNo ConsultantApproveDate TenderSumLimit",
|
|
||||||
"BidderInfo": "BidName BidAuthorizer BidTotal BidCompiler BidCompilerCertNo BidCompileDate BidExaminer BidExaminerCertNo BidExamineDate BidApprover BidApproverCertNo BidApproveDate",
|
|
||||||
"AttrInfoItem": "Name Value Code Remark",
|
|
||||||
"AddiInfoItem": "Name Value Code Remark",
|
|
||||||
"SummaryOfCost": "Total Construction Installation DivisionalAndElementalWorks Preliminaries CostForHSE SundryCosts ProvisionalSums SpecialtyProvisionalPrice DayWorkRate MainContractorAttendance ClaimForLossAndExpenses LawsRegulationsAndPolicyChangeProjects ChangeCost Tax Labour Material MainMaterialEquipment MainMaterial Equipment ProvisionalMaterialEquipment Machine Overhead Profit ForeignCurrency ConvertedIntoRMB",
|
|
||||||
"AddiCost": "Name Total Code",
|
|
||||||
"ProjectInstallationWorkCost": "Number Name Total ForeignCurrency ConvertedIntoRMB ScaleName Scale Unit TechnicalAndEconomicIndex Ratios Code Remark",
|
|
||||||
"ProjectInstallationWorkCostSummaryGroup": "Number Name Unit Quantity Total TechnicalAndEconomicIndex Ratios Code Kind Remark",
|
|
||||||
"ProjectInstallationWorkCostSummaryItem": "Number Name Unit Quantity QtyFormula Rate Total TechnicalAndEconomicIndex Ratios Code Kind Remark",
|
|
||||||
"SectionalWorks": "Number Name Segment ProjectCategory ProjectType ConstructionType FileKind ValuationModel TaxModel AreaKind Total ProjectArea ProjectSite BuildUnit BuildAuthorizer StandardName StandardNumber StandardVersion RangeOfCompilation ScaleName Scale Unit ProjectIndex LabourPriceIndex MaterialPriceIndex MachinePriceIndex TechnicalAndEconomicIndex Ratios WorkContent QuantityCalculationRules Code Remark Explains",
|
|
||||||
"UnitWorks": "Number Name Segment ProjectCategory ProjectType ValuationModel TaxModel AreaKind Total Specialty Purposes RangeOfCompilation ScaleName Scale Unit BillDataBase NormDataBase ResInfoPricingFile MaterialPriceDate AppliedRateFile ProjectIndex LabourPriceIndex MaterialPriceIndex MachinePriceIndex TechnicalAndEconomicIndex Ratios WorkContent QuantityCalculationRules Code Remark Explains FileName",
|
|
||||||
"SummaryOfBasicCost": "Labour Material MainMaterial Equipment MainMaterialEquipment ProvisionalMaterialEquipment Machine Overhead Profit DivisionalAndElementalWorks Preliminaries CostForHSE SundryCosts Tax",
|
|
||||||
"PreliminaryDivisionalWorks": "Number Name WorkContent Unit Quantity Total TechnicalAndEconomicIndex Code Kind Remark",
|
|
||||||
"PreliminaryWorkElement": "Number Name WorkContent Unit Quantity QtyFormula Price Rate Total InitialPercent InitialFee MediumPercent MediumFee LastPercent LastFee SupplementaryList CalcType Specialty ListingIdentity LockKind Code Kind Remark",
|
|
||||||
"SubdivisionFees": "Number Name Unit Quantity QtyFormula Price Rate Total CalcType InitialPercent InitialFee MediumPercent MediumFee LastPercent LastFee Code IsLargeMachinery Kind Remark",
|
|
||||||
"SundryCosts": "Name Total Code Remark",
|
|
||||||
"SundryCostsGroup": "Name Total Code Kind Remark",
|
|
||||||
"SundryCostsItem": "Name Unit Quantity QtyFormula Price Rate Total Code Kind Remark",
|
|
||||||
"ProvisionalSums": "Name Total Code Remark",
|
|
||||||
"ProvisionalSumsGroup": "Name Total Kind Remark",
|
|
||||||
"ProvisionalSumsItem": "Name Unit Quantity QtyFormula Price Rate Total Kind Remark",
|
|
||||||
"SpecialtyProvisionalPrice": "Name NoTaxTotal Tax Total Code Remark",
|
|
||||||
"SpecialtyProvisionalPriceGroup": "Name Content NoTaxTotal Tax Total Kind Remark",
|
|
||||||
"SpecialtyProvisionalPriceItem": "Name Content Unit Quantity QtyFormula Price Rate NoTaxTotal Tax Total Kind Remark",
|
|
||||||
"DayWorkRate": "Name Total Code Remark",
|
|
||||||
"DayWorkRateGroup": "Name Total Code Remark",
|
|
||||||
"DayWorkRateItem": "Number Name Specification Unit Quantity Price Total Remark",
|
|
||||||
"MainContractorAttendance": "Name Total Code Remark",
|
|
||||||
"MainContractorAttendanceGroup": "Name Total Kind Remark",
|
|
||||||
"MainContractorAttendanceItem": "Name Quantity Content QtyFormula Rate Total Kind Remark",
|
|
||||||
"ClaimsCost": "Name Total Code Remark",
|
|
||||||
"ClaimsCostGroup": "Name Total Kind Remark",
|
|
||||||
"ClaimsCostItem": "Name Unit Quantity QtyFormula Price Rate Total Reason Kind Remark",
|
|
||||||
"LawsRegulationsAndPolicyChangeProjects": "Name Total Code Remark",
|
|
||||||
"LawsRegulationsAndPolicyChangeProjectsGroup": "Name Total Kind Remark",
|
|
||||||
"LawsRegulationsAndPolicyChangeProjectsItem": "Name Unit Quantity QtyFormula Price Rate Total Reason Kind Remark",
|
|
||||||
"ChangeCost": "Number Name Total Code Remark",
|
|
||||||
"ChangeCostGroup": "Number Name Total Code Remark",
|
|
||||||
"ChangeCostItem": "Number Name Unit Quantity QtyFormula Price Rate Total Reason Kind Remark",
|
|
||||||
"Tax": "Name CalBasis QtyFormula Rate Total Code Remark",
|
|
||||||
"TaxItem": "Name CalBasis QtyFormula Rate Total Code Remark",
|
|
||||||
"ProvisionalMaterialEquipment": "Name Total Code Remark",
|
|
||||||
"ProvisionalMaterialEquipmentItem": "Number Name Specification Unit Quantity Price Total Remark",
|
|
||||||
"LabourMaterialsEquipmentsMachinesSummary": "Number Name Specification Unit LossRate Quantity ProviderRate ProviderBase TaxRate NoTaxOrgPrice NoTaxPriceExpress NoTaxPrice TaxOrgPrice TaxPriceExpress TaxPrice NoTaxOrgTotal NoTaxTotal TaxOrgTotal TaxTotal Weight BasicPrice CurrentPrice Kind Class ExtKind Concrete AddiKind MainMaterial ProvisionalMaterial Provider PriceSource Delivery Location ProducingArea Supplier Character Remark",
|
|
||||||
"LabourMaterialsEquipmentsMachinesElement": "Number Express Quantity Remark",
|
|
||||||
"BidEvaluationMainMaterial": "Code Number Name Specification Unit Price LimitedPrice ResClassValue Quantity Total ProviderRate ProviderBase Delivery DeliPlace ProducingArea Supplier Character Remark",
|
|
||||||
"DivisionalWorks": "Number Name Attr WorkContent QuantityCalculationRules Unit Quantity Total TechnicalAndEconomicIndex ChapterKind Code Kind Remark",
|
|
||||||
"WorkElement": "Number Name Attr WorkContent QuantityCalculationRules Unit Quantity QtyFormula Price CalcPrice EquipmentPrice PriceHigh Rate Total EquipmentTotal SupplementaryList Major Type CalculationKind CostKind PriceType CalcType Specialty ListingIdentity LockKind Code Kind Remark",
|
|
||||||
"ExpressElement": "OrderNumber Area BuildingComponents Express Explain Quantity Kind Remark", # Area=部位, 2025 OCR丢名按2018补
|
|
||||||
"WorkContent": "Name Total Remark",
|
|
||||||
"Norm": "Number Name Unit Quantity Price EquipmentPrice Total EquipmentTotal IsNorm Type CalculationKind CostKind EfficiencyKind IncFeeKind Specialty NormIdentity Volume Chapter Remark",
|
|
||||||
"IncFees": "Number Name CalcKind Ratio LabourRatio MachineRatio ManageFeeRate DivisionalAndElementalWorksClassify PreliminaryClassify LabourRate MaterialRate MachineRate DivisionalAndElementalWorksLabour DivisionalAndElementalWorksMaterial DivisionalAndElementalWorksMachine DivisionalAndElementalWorksManageFee PreliminaryLabour PreliminaryMaterial PreliminaryMachine",
|
|
||||||
"UnitPriceCalculationOfItem": "Name QtyFormula Rate Total Code Remark",
|
|
||||||
"NormAdjustmentList": "OrderNumber Value",
|
|
||||||
"UnitWorksPreliminaryWorkElement": "Number Name WorkContent Unit Quantity QtyFormula Price CalcPrice Rate Total InitialPercent InitialFee MediumPercent MediumFee LastPercent LastFee SupplementaryList PriceType CalcType Specialty ListingIdentity LockKind Code Kind Remark",
|
|
||||||
"UnitWorksSummaryGroup": "Number Name Unit Quantity Total TechnicalAndEconomicIndex Ratios ChapterKind Code Kind Remark",
|
|
||||||
"UnitWorksSummaryItem": "Number Name Unit Quantity QtyFormula Rate Total TechnicalAndEconomicIndex Ratios ChapterKind Code Kind Remark",
|
|
||||||
}
|
|
||||||
STD = {k: set(v.split()) for k, v in STD.items()}
|
|
||||||
|
|
||||||
def norm(s):
|
|
||||||
return s.lower().replace(" ", "").replace("-", "")
|
|
||||||
|
|
||||||
def classify(vendor_attrs, std_attrs):
|
|
||||||
uniq, fuzzy = [], []
|
|
||||||
vsn = {norm(a): a for a in vendor_attrs}
|
|
||||||
stdn = {norm(a): a for a in std_attrs}
|
|
||||||
hit_std = set() # 被精确或拼写命中的标准属性(原始名)
|
|
||||||
for n, a in sorted(vsn.items()):
|
|
||||||
if n in stdn:
|
|
||||||
hit_std.add(stdn[n]); continue
|
|
||||||
best, br = None, 0.0
|
|
||||||
for sn in stdn:
|
|
||||||
if abs(len(sn) - len(n)) > 2 or sn[0] != n[0]:
|
|
||||||
continue
|
|
||||||
r = difflib.SequenceMatcher(None, n, sn).ratio()
|
|
||||||
if r > br:
|
|
||||||
best, br = sn, r
|
|
||||||
if best is not None and br >= 0.82:
|
|
||||||
hit_std.add(stdn[best]); fuzzy.append("%s ≈ 标准 %s" % (a, stdn[best]))
|
|
||||||
else:
|
|
||||||
uniq.append(a)
|
|
||||||
not_exp = sorted(std_attrs - hit_std)
|
|
||||||
return uniq, fuzzy, not_exp
|
|
||||||
|
|
||||||
gld = json.load(open("D:/PricingReview/_analysis/gld_attrs.json", encoding="utf-8"))["elements"]
|
|
||||||
yd = json.load(open("D:/PricingReview/_analysis/yd_attrs.json", encoding="utf-8"))["elements"]
|
|
||||||
|
|
||||||
for tag, data in [("广联达", gld), ("易达", yd)]:
|
|
||||||
print("=" * 78)
|
|
||||||
print("## %s" % tag)
|
|
||||||
for el in sorted(data):
|
|
||||||
if el not in STD:
|
|
||||||
print("[%s] !! 标准无此元素,其全部属性均为自有: %s" % (el, ",".join(data[el]["attrs"])))
|
|
||||||
continue
|
|
||||||
u, f, ne = classify(data[el]["attrs"], STD[el])
|
|
||||||
if u or f:
|
|
||||||
print("[%s]" % el)
|
|
||||||
if u: print(" 标准没有(特有):", ", ".join(u))
|
|
||||||
if f: print(" 拼写差异(标准有对应):", "; ".join(f))
|
|
||||||
print()
|
|
||||||
print("=" * 78)
|
|
||||||
print("## 覆盖差异(标准有、该家未导出) — 逐元素")
|
|
||||||
for tag, data in [("广联达", gld), ("易达", yd)]:
|
|
||||||
print("-- %s" % tag)
|
|
||||||
for el in sorted(data):
|
|
||||||
if el in STD:
|
|
||||||
_, _, ne = classify(data[el]["attrs"], STD[el])
|
|
||||||
if ne:
|
|
||||||
print(" %-42s 缺 %s" % (el, ",".join(ne)))
|
|
||||||
miss_el = sorted(set(STD) - set(data))
|
|
||||||
print(" 整元素未出现:", ",".join(miss_el) or "无")
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
=== xmldiff:广联达实件 AttrInfo vs 导出件 AttrInfo ===
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[2]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[2]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[13]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[13]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[14]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[14]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[15]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[15]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[16]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[16]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[17]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[17]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[18]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[18]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[19]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[19]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[2]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[2]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[1]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[3]', target='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[2]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Value', value='')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[23]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem[2]/AttrInfoItem[3]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem[2]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem[2]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem/AttrInfoItem[3]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[22]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[21]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[20]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[20]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[20]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[19]/AttrInfoItem[3]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[19]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[19]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[19]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[18]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[17]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[16]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[15]/AttrInfoItem[4]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[15]/AttrInfoItem[3]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[15]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[15]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[15]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[14]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[13]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[13]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[13]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[12]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[12]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[4]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[3]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[2]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[11]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[5]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[4]')
|
|
||||||
DeleteNode(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[3]')
|
|
||||||
|
|
||||||
=== xmldiff:易达实件 AttrInfo vs 导出件 AttrInfo ===
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem/AttrInfoItem[10]', target='/AttrInfo[1]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
DeleteAttrib(node='/AttrInfo/AttrInfoItem[1]', name='Code')
|
|
||||||
DeleteAttrib(node='/AttrInfo/AttrInfoItem[1]', name='Remark')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=1)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[2]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[2]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=2)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[3]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[3]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=3)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[4]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[4]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=4)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[5]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[5]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=5)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[6]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[6]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=6)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[7]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[7]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=7)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[8]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[8]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=8)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[9]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[9]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo[1]', tag='AttrInfoItem', position=9)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[3]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[3]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[3]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[4]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[4]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[4]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[5]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[5]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[5]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[6]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[6]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[6]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[7]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[7]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[7]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[8]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[8]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[8]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]/AttrInfoItem[1]', target='/AttrInfo/AttrInfoItem[9]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[9]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[9]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[11]', target='/AttrInfo/AttrInfoItem[10]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
InsertNode(target='/AttrInfo/AttrInfoItem[10]', tag='AttrInfoItem', position=1)
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]', name='Code', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]', name='Name', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]', name='Remark', value='')
|
|
||||||
InsertAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]', name='Value', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[1]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[1]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
MoveNode(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[1]/AttrInfoItem[2]', target='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]', position=0)
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Code', value='')
|
|
||||||
UpdateAttrib(node='/AttrInfo/AttrInfoItem[10]/AttrInfoItem[2]/AttrInfoItem[1]', name='Name', value='')
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user