feat(price): 信息价/市场价重设计——目录树+行内编辑+只收标准模板+导出一份数据(决策42)
- schema: 新增 price_dirs 目录树(批次级单根/多级/仅叶挂行),prices.dir_id;Class 冗余完整路径文本 - 导入只收标准模板 xlsx:表头严格校验(HTML/别名/多sheet拆批退役);名称默认=文件名可改;期次从文件名认 - 后台明细页重做:左树行内增删改名/上下移(↑↓✕两段式确认、选中按钮常显),右表行内新增/编辑(重算比对键即刻生效) - 导出 zip = 价格明细.xlsx(目录路径+批次信息页签)+ 附件原件,导入可复原 - 壳/跨页跳转带版本参数根治 WebView2 旧缓存;导入弹框文件框只收 .xlsx - 附 P0/P1 接口测试夹具与价格重设计回归(新增 test_price_redesign 等 8 件,全套 148 项绿)
This commit is contained in:
@@ -17,7 +17,8 @@
|
||||
import io, os, re, json
|
||||
|
||||
# 解析器版本(与 import_job.PARSER_VER 同机制,见那里的说明):改了入库口径才升号
|
||||
PARSER_VER = "2026.10.02-1"
|
||||
# ⚠️ 2026-10-12 价格重设计:只收标准模板 Excel(HTML 导入退役),与 price_xlsx.PARSER_VER 同步升号
|
||||
PARSER_VER = "2026.10.12-1"
|
||||
|
||||
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
|
||||
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
|
||||
|
||||
@@ -1,67 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
信息价 / 市场价 Excel 解析器(2026-10-06 新增)
|
||||
信息价 / 市场价 Excel 解析器(2026-10-12 重设计版,主人定「只能导入 Excel 标准模板」)
|
||||
|
||||
与 price_html 的关系:**只换解析前端,共用后半段**。
|
||||
price_html.parse(path) ─┐
|
||||
├─→ 同一种 blocks 结构 ─→ price_html.to_records() ─→ 入库
|
||||
price_xlsx.parse(path) ─┘
|
||||
**只收标准模板 .xlsx**:第 1 行表头必须与模板列名一致(去空格后全等,顺序不限),
|
||||
不是标准模板 → 抛 ValueError,调用方直接把提示给到界面(不做任何宽容解析)。
|
||||
|
||||
这样保证两种来源进库后 x_name_norm / x_hash_exact 口径完全一致,
|
||||
HTML 导入的价格和 Excel 导入的价格能互相命中、放在一起比对。
|
||||
**模板结构**(template_bytes() 生成,9 列):
|
||||
目录 | 材料编码 | 材料名称 | 规格型号 | 单位 | 不含税单价 | 税率 | 含税单价 | 备注
|
||||
· 第 1 列「目录」= 多级路径,用「/」分隔(如「建筑材料/黑色及有色金属/钢筋」),
|
||||
层级不限;留空 = 未分类。导入时按路径逐级建目录(price_dirs),行挂在最底层目录。
|
||||
· 其余 8 列 = 一行材料。
|
||||
· 一个文件 = 一个批次(只读第 1 个工作表;「填写说明」页不参与解析)。
|
||||
|
||||
**Excel 模板结构**(由 template_bytes() 生成,9 列):
|
||||
分类 | 材料编码 | 材料名称 | 规格型号 | 单位 | 不含税单价 | 税率 | 含税单价 | 备注
|
||||
· 第 1 列「分类」= 目录(对应 HTML 里的 section title),连续的相同分类自动归为一段
|
||||
· 其余 8 列 = 一行材料,顺序与 price_html 的 8 列一一对应
|
||||
· 第 2 个 sheet「填写说明」不参与解析
|
||||
|
||||
**块名(Block)**:优先用第 1 个 sheet 名;若用了默认的「价格明细」,则回退为文件名。
|
||||
想指定块名就把 sheet 改名,例如「珠海市建材设备市场综合价」。
|
||||
|
||||
口径(沿用 price_html 的两条):
|
||||
1. 目录(Class)=「分类」列原封不动,含序号,不剥「一、」。
|
||||
2. 一个 Excel 文件 = 一个批次,不按块拆分;期次统一用导入弹框里填的那个。
|
||||
与旧版(2026-10-06)的差异:
|
||||
· 旧版接受任意列名别名 + 「分类」单列 —— 全部退役(主人 2026-10-12 定:新软件,
|
||||
不做兼容)。HTML 导入同步退役(api_server._price_parse 只分派 xlsx)。
|
||||
· PARSER_VER 升号必须与 price_html.PARSER_VER 同步(stale_batches 对价格类
|
||||
只有一条判定线,见下方历史注释)。
|
||||
"""
|
||||
|
||||
import io, os, re
|
||||
|
||||
# ⚠️ 版本号**故意与 price_html.PARSER_VER 保持一致**,不要各编各的。
|
||||
# 原因:两条入口写的是同一张 prices 表、同一套 x_hash_exact 口径;而 stale_batches()
|
||||
# 对价格类只有「一条」判定线(price_html.PARSER_VER)。如果 Excel 用自己的版本号,
|
||||
# Excel 导入的批次会被永久误报成「数据过期需重导」。
|
||||
# 所以:口径一变 → 两个文件一起升号 → 两种来源的数据一起重导。这正是我们要的。
|
||||
PARSER_VER = "2026.10.02-1" # == price_html.PARSER_VER,改那边时同步改这里
|
||||
# ⚠️ 版本号与 price_html.PARSER_VER 保持一致(历史约定,见文件头);改这里同步改那边。
|
||||
PARSER_VER = "2026.10.12-1"
|
||||
|
||||
SHEET_DATA = "价格明细" # 数据 sheet 名(模板默认)
|
||||
SHEET_DATA = "价格明细" # 数据 sheet 名(模板默认;只读第 1 个工作表,名字不校验)
|
||||
SHEET_HELP = "填写说明" # 说明 sheet 名(不解析)
|
||||
|
||||
# 列名别名:左边是模板标准名,右边是允许的各种写法(去空格/全角后不区分大小写匹配)
|
||||
_ALIAS = {
|
||||
"分类": ("分类", "目录", "类别", "材料类别", "分部", "章节"),
|
||||
"材料编码": ("材料编码", "编码", "代码", "材料代码", "编号"),
|
||||
"材料名称": ("材料名称", "名称", "材料名", "品名"),
|
||||
"规格型号": ("规格型号", "规格", "型号", "规格及型号"),
|
||||
"单位": ("单位", "计量单位"),
|
||||
"不含税单价": ("不含税单价", "除税单价", "不含税价", "除税价", "除税编制价", "不含税单价(元)"),
|
||||
"税率": ("税率", "税率(%)", "税率%"),
|
||||
"含税单价": ("含税单价", "含税价", "含税编制价", "含税单价(元)"),
|
||||
"备注": ("备注", "说明", "附注", "Remark"),
|
||||
}
|
||||
# 模板固定列序(生成与解析共用,改这里两边一起变)
|
||||
COLS = ["分类", "材料编码", "材料名称", "规格型号", "单位",
|
||||
# 模板固定列名(生成与解析共用,改这里两边一起变)
|
||||
COLS = ["目录", "材料编码", "材料名称", "规格型号", "单位",
|
||||
"不含税单价", "税率", "含税单价", "备注"]
|
||||
DIR_SEP = "/" # 目录多级路径分隔符
|
||||
|
||||
_HELP = [
|
||||
("造价审核 · 信息价/市场价导入模板", ""),
|
||||
("", ""),
|
||||
("怎么用", "1) 在【价格明细】页按列填写,从第 2 行开始(第 1 行是表头,不要改列名)"),
|
||||
("怎么用", "1) 在【价格明细】页按列填写,从第 2 行开始(第 1 行是表头,列名不要改)"),
|
||||
("", "2) 存成 .xlsx,回到后台「信息价」或「市场价」标签 → 导入 → 选这个文件"),
|
||||
("", "3) 名称 / 单位 / 不含税单价 必填;其余选填"),
|
||||
("", "4) 一个块 = 一个批次。想一次导多个市场,就建多个 sheet,每个 sheet 一个市场"),
|
||||
("", "4) 一个文件 = 一个批次(只读第 1 个工作表)"),
|
||||
("", ""),
|
||||
("列说明", ""),
|
||||
("分类", "目录,原样保存(如「一、黑色及有色金属」)。连续相同的行自动归为同一段"),
|
||||
("目录", "多级路径用「/」分隔,如「建筑材料/黑色及有色金属/钢筋」,层级不限;"),
|
||||
("", "只填一段 = 一级目录;留空 = 未分类。只有最底层目录挂内容。"),
|
||||
("", "导入后目录仍可在后台明细页继续编辑(改名 / 增删 / 上移下移),不必回来改表重导"),
|
||||
("材料编码", "选填。没有就留空,不影响比对(精确键只用 名称+规格+单位)"),
|
||||
("材料名称", "必填。留空的行会被跳过"),
|
||||
("规格型号", "选填,但建议填——参与相似度计算,填了比对更准"),
|
||||
@@ -71,32 +53,91 @@ _HELP = [
|
||||
("含税单价", "选填。留空时界面显示「—」"),
|
||||
("备注", "选填,如「2956 ~ 3076(均值:3016)」"),
|
||||
("", ""),
|
||||
("块名(Block)", "默认取文件名。想改就把【价格明细】这个 sheet 改名,例如「珠海市建材设备市场综合价」"),
|
||||
("", "改名不只是换标题:**一个块 = 一个批次**,多个 sheet 会拆成多个批次分别入库"),
|
||||
("期次", "不用在表里填。块名里写了「2026年7月」「2026年4-6月」这种会自动认出来;"),
|
||||
("", "认不出才用导入弹框里填的那个。所以块名尽量带上年月,比手填更准"),
|
||||
("批次 / 期次", "一个文件 = 一个批次。期次从文件名里自动认(如「珠海信息价_2026年7月」),"),
|
||||
("", "认不出才用导入弹框里填的那个。所以文件名尽量带上年月,比手填更准"),
|
||||
]
|
||||
|
||||
|
||||
def _clean(s):
|
||||
"""表头归一化:去空白、全角空格、冒号、星号,便于别名匹配"""
|
||||
"""表头归一化:去空白、全角空格、冒号、星号,便于严格比对"""
|
||||
return (str(s or "")).strip().replace(" ", "").replace(" ", "").replace(":", "").replace("*", "")
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""解析标准模板 .xlsx → blocks 结构(与 api_server 的入库流程对接)。
|
||||
|
||||
返回 [{block, columns, n_sections, rows:[(目录路径, [8列])], period_start_m, period_end_m}, ...]
|
||||
· block = 文件名去扩展名(剥掉「sha256_」存储前缀)——一个文件一个批次
|
||||
· rows[i] = (目录路径原样或 '',[材料编码, 名称, 规格, 单位, 不含税, 税率, 含税, 备注])
|
||||
· 表头严格校验:_clean 后必须与 COLS 全等(顺序不限),否则 ValueError
|
||||
只读第 1 个工作表(模板结构里它就是「价格明细」;「填写说明」等其余 sheet 不看)。
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("文件不存在:%s" % path)
|
||||
if not (path or "").lower().endswith(".xlsx"):
|
||||
raise ValueError("只支持标准模板 .xlsx(请用「标准模板」按钮下载后填写)")
|
||||
import openpyxl
|
||||
try:
|
||||
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
|
||||
except Exception as e:
|
||||
raise ValueError("打不开这个 Excel(%s)。请用「标准模板」按钮下载模板后填写" % e)
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
header, rows = _scan_rows(ws.iter_rows(values_only=True))
|
||||
finally:
|
||||
wb.close()
|
||||
if header is None:
|
||||
raise ValueError("这不是标准模板:第 1 行必须是模板的 9 个列名"
|
||||
"(目录 / 材料编码 / 材料名称 / 规格型号 / 单位 / 不含税单价 / 税率 / 含税单价 / 备注)。"
|
||||
"请点「标准模板」按钮下载后填写")
|
||||
fn = os.path.splitext(os.path.basename(path))[0]
|
||||
block = fn[65:] if re.match(r"^[0-9a-f]{64}_", fn) and len(fn) > 65 else fn
|
||||
import price_html
|
||||
ps, pe = price_html.guess_period(block)
|
||||
return [{
|
||||
"block": block,
|
||||
"columns": COLS[1:],
|
||||
"n_sections": len({r[0] for r in rows if r[0]}),
|
||||
"rows": rows,
|
||||
"period_start_m": ps,
|
||||
"period_end_m": pe,
|
||||
}]
|
||||
|
||||
|
||||
def _scan_rows(iter_rows):
|
||||
"""逐行扫描:先严格认表头(最多容忍 10 行废话),之后按模板 9 列取值。
|
||||
返回 (header|None, rows)。header=None = 表头对不上 = 不是标准模板。"""
|
||||
header, rows = None, []
|
||||
for r in iter_rows:
|
||||
if header is None:
|
||||
m = _map_header(r)
|
||||
if m:
|
||||
header = m
|
||||
continue
|
||||
# 表头行前面允许有空行,但出现非空内容仍对不上 → 直接判非模板
|
||||
if any(str(v or "").strip() for v in r):
|
||||
return None, []
|
||||
continue
|
||||
vals = [r[header.get(c, -1)] if 0 <= header.get(c, -1) < len(r) else "" for c in COLS]
|
||||
# ⚠️ openpyxl 只读模式把空单元格读成 None —— str(None)="None" 会被当非空,
|
||||
# 整行空就跳不过去了。None 一律视作空(2026-10-12 修,老口径靠 to_records 兜底)。
|
||||
if not any((str(v).strip() if v is not None else "") for v in vals):
|
||||
continue # 整行空 → 跳过
|
||||
rows.append((_cell(vals[0]), [_cell(v) for v in vals[1:]]))
|
||||
return header, rows
|
||||
|
||||
|
||||
def _map_header(row):
|
||||
"""表头行 → {标准列名: 列下标}。认不出的列忽略(返回 None 表示没找到必填列)"""
|
||||
"""表头行 → {标准列名: 列下标};**严格模式**:_clean 后必须与标准列名全等,
|
||||
9 列必须一个不缺。对不上返回 None。"""
|
||||
idx = {}
|
||||
for i, v in enumerate(row):
|
||||
k = _clean(v)
|
||||
if not k:
|
||||
continue
|
||||
for std, names in _ALIAS.items():
|
||||
if std in idx:
|
||||
continue
|
||||
if k in names or any(k == _clean(n) for n in names):
|
||||
idx[std] = i
|
||||
break
|
||||
return idx if "材料名称" in idx else None
|
||||
if k in COLS and k not in idx:
|
||||
idx[k] = i
|
||||
if len(idx) != len(COLS):
|
||||
return None
|
||||
return idx
|
||||
|
||||
|
||||
def _cell(v):
|
||||
@@ -107,119 +148,46 @@ def _cell(v):
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def _block_name(path, sheet_title):
|
||||
"""块名:sheet 名被改过就用 sheet 名,否则用文件名"""
|
||||
sname = (sheet_title or "").strip()
|
||||
if sname and sname != SHEET_DATA:
|
||||
return sname
|
||||
# 上传的文件在软件里存成「sha256_原名.xlsx」(_save_to 的固定格式),
|
||||
# 直接 basename 会得到一串 hash 开头的丑名字,这里剥掉 sha_ 前缀取回原名。
|
||||
fn = os.path.splitext(os.path.basename(path))[0]
|
||||
return fn[65:] if re.match(r"^[0-9a-f]{64}_", fn) and len(fn) > 65 else fn
|
||||
|
||||
|
||||
def _mk_block(path, block, header, rows):
|
||||
"""把 (分类, 8列) 序列收成一个块。header 为 None 表示这张表没认出表头 → 返回 None 跳过。"""
|
||||
if header is None or not rows:
|
||||
return None
|
||||
import price_html
|
||||
ps, pe = price_html.guess_period(block)
|
||||
return {
|
||||
"block": block,
|
||||
"columns": COLS[1:],
|
||||
"n_sections": len(set(s for s, _ in rows)),
|
||||
"rows": rows,
|
||||
"period_start_m": ps,
|
||||
"period_end_m": pe,
|
||||
}
|
||||
|
||||
|
||||
def _scan_rows(iter_rows):
|
||||
"""逐行扫描一张表:先认表头(最多容忍 10 行废话),之后按模板 9 列取值。
|
||||
返回 (header, rows)。"""
|
||||
header, rows, skipped = None, [], 0
|
||||
for r in iter_rows:
|
||||
if header is None:
|
||||
header = _map_header(r)
|
||||
if header is not None:
|
||||
continue
|
||||
skipped += 1
|
||||
if skipped > 10:
|
||||
break
|
||||
continue
|
||||
vals = [r[header.get(c, -1)] if 0 <= header.get(c, -1) < len(r) else "" for c in COLS]
|
||||
if not any(str(v).strip() for v in vals):
|
||||
continue # 整行空 → 跳过
|
||||
rows.append((_cell(vals[0]), [_cell(v) for v in vals[1:]])) # 去掉「分类」,留 8 列
|
||||
return header, rows
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""→ [{block, columns, n_sections, rows:[(分类, [8列])], period_start_m, period_end_m}, ...]
|
||||
结构与 price_html.parse 完全一致。.xlsx 走 openpyxl,.xls(老格式)走 xlrd。
|
||||
|
||||
**一个 sheet = 一个块**(2026-10-06):想一次导入多个市场,就建多个 sheet,
|
||||
每个 sheet 用自己的市场名命名 —— 与 HTML 里「一个块 = 一个市场」对齐,
|
||||
导入后每个块单独建一个批次、各自带自己的期次。
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("文件不存在:%s" % path)
|
||||
if (path or "").lower().endswith(".xls"):
|
||||
return _parse_xls(path)
|
||||
|
||||
import openpyxl
|
||||
try:
|
||||
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
|
||||
except Exception as e:
|
||||
raise ValueError("打不开这个 Excel(%s)。请另存为 .xlsx 后再导入" % e)
|
||||
out = []
|
||||
for ws in wb.worksheets:
|
||||
if (ws.title or "").strip() == SHEET_HELP:
|
||||
continue
|
||||
header, rows = _scan_rows(ws.iter_rows(values_only=True))
|
||||
b = _mk_block(path, _block_name(path, ws.title), header, rows)
|
||||
if b:
|
||||
out.append(b)
|
||||
wb.close()
|
||||
if not out:
|
||||
raise ValueError("没找到表头行或没有数据行。请下载标准模板,第 1 行保持模板的列名不要改")
|
||||
return out
|
||||
|
||||
|
||||
def _parse_xls(path):
|
||||
"""老格式 .xls(Excel 97-2003)。openpyxl 读不了,走 xlrd。
|
||||
逻辑与 .xlsx 分支完全一致:同样一个 sheet = 一个块、同样复用 _scan_rows / _mk_block。"""
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
raise ValueError("读 .xls 需要 xlrd(pip install xlrd)。也可以把文件另存为 .xlsx 后再导入")
|
||||
try:
|
||||
bk = xlrd.open_workbook(path)
|
||||
except Exception as e:
|
||||
raise ValueError("打不开这个 .xls(%s)。确认不是改名骗人的 csv/html" % e)
|
||||
out = []
|
||||
for si in range(bk.nsheets):
|
||||
sh = bk.sheet_by_index(si)
|
||||
if (sh.name or "").strip() == SHEET_HELP:
|
||||
continue
|
||||
header, rows = _scan_rows([sh.cell_value(i, j) for j in range(sh.ncols)]
|
||||
for i in range(sh.nrows))
|
||||
b = _mk_block(path, _block_name(path, sh.name), header, rows)
|
||||
if b:
|
||||
out.append(b)
|
||||
if not out:
|
||||
raise ValueError("没找到表头行或没有数据行。请下载标准模板,第 1 行保持模板的列名不要改")
|
||||
return out
|
||||
|
||||
|
||||
def to_records(blocks):
|
||||
"""直接复用 price_html 的入库转换:两种来源口径必须一致,不容许各写一份"""
|
||||
import price_html
|
||||
return price_html.to_records(blocks)
|
||||
"""入库记录(2026-10-12 新口径,**不再复用 price_html.to_records**):
|
||||
· Class = 目录路径原样(留空就是空 = 未分类;旧实现会回落成块名,与新设计冲突)
|
||||
· 数字列走 _num(去千分位;读不出数字=None,界面显示「—」)
|
||||
"""
|
||||
def _num(v):
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip().replace(",", "")
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
recs = []
|
||||
for b in blocks:
|
||||
blk = (b.get("block") or "").strip()
|
||||
for sec_title, r in b["rows"]:
|
||||
name = (r[1] or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
recs.append({
|
||||
"Code": (r[0] or "").strip(),
|
||||
"Name": name,
|
||||
"Specification": (r[2] or "").strip(),
|
||||
"Unit": (r[3] or "").strip(),
|
||||
"NoTaxPrice": _num(r[4]),
|
||||
"TaxRate": _num(r[5]),
|
||||
"TaxPrice": _num(r[6]),
|
||||
"Class": (sec_title or "").strip(),
|
||||
"Note": (r[7] or "").strip(),
|
||||
"Block": blk,
|
||||
})
|
||||
return recs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 标准模板生成
|
||||
# 标准模板生成(v2:目录列 = 多级路径)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def template_bytes():
|
||||
@@ -242,17 +210,19 @@ def template_bytes():
|
||||
c.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
# 两行示例(照珠海信息价的实际写法,用户一眼知道填什么)
|
||||
# 示例行(多级路径 + 未分类各来一条,一眼看懂目录列怎么填)
|
||||
demo = [
|
||||
["一、黑色及有色金属", "", "圆钢(HPB300)", "Φ6.5mm", "t", 2956.0, 0.13, 3340.28, "2956 ~ 3076(均值:3016)"],
|
||||
["一、黑色及有色金属", "", "圆钢(HPB300)", "Φ8-10mm", "t", 2902.0, 0.13, 3279.26, "2902 ~ 3021(均值:2961)"],
|
||||
["建筑材料/黑色及有色金属/钢筋", "", "圆钢(HPB300)", "Φ6.5mm", "t", 2956.0, 0.13, 3340.28, "2956 ~ 3076(均值:3016)"],
|
||||
["建筑材料/黑色及有色金属/钢筋", "", "螺纹钢(HRB400E)", "Φ12-14mm", "t", 3180.0, 0.13, 3593.40, ""],
|
||||
["建筑材料/水泥、砖、砂石", "", "普通硅酸盐水泥 P.O 42.5", "散装", "t", 385.0, 0.13, 435.05, ""],
|
||||
["", "0101035", "高线(HPB300)", "Φ6mm", "t", 2980.0, 0.13, 3367.40, "留空目录 = 未分类"],
|
||||
]
|
||||
for d in demo:
|
||||
ws.append(d)
|
||||
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
|
||||
for c in row:
|
||||
c.border = bd
|
||||
ws.column_dimensions["A"].width = 22
|
||||
ws.column_dimensions["A"].width = 32
|
||||
ws.column_dimensions["B"].width = 12
|
||||
ws.column_dimensions["C"].width = 30
|
||||
ws.column_dimensions["D"].width = 22
|
||||
@@ -290,7 +260,7 @@ if __name__ == "__main__":
|
||||
else:
|
||||
blocks = parse(p)
|
||||
for b in blocks:
|
||||
print("块:%s 分类数=%d 行数=%d" % (b["block"], b["n_sections"], len(b["rows"])))
|
||||
print("块:%s 目录数=%d 行数=%d" % (b["block"], b["n_sections"], len(b["rows"])))
|
||||
recs = to_records(blocks)
|
||||
print("记录数:", len(recs))
|
||||
print("样例:", recs[0] if recs else "")
|
||||
|
||||
@@ -114,6 +114,8 @@ def ensure_attach_schema():
|
||||
pcols = [r[1] for r in con.execute("PRAGMA table_info(prices)")]
|
||||
if "Block" not in pcols: # 块名(三级目录:批次→块→分类,2026-09-28 定)
|
||||
con.execute("ALTER TABLE prices ADD COLUMN Block TEXT")
|
||||
if "dir_id" not in pcols: # 挂在哪个目录(price_dirs.id;0/NULL=未分类,2026-10-12)
|
||||
con.execute("ALTER TABLE prices ADD COLUMN dir_id INTEGER")
|
||||
# 2026-10-08:次精确档 md5(名称归一+单位归一)——lmes/prices 同口径(老库补列+回填见 backfill_hash_semi)
|
||||
lcols = [r[1] for r in con.execute("PRAGMA table_info(lmes)")]
|
||||
if "x_hash_semi" not in lcols:
|
||||
@@ -1251,8 +1253,16 @@ def api_audit(body):
|
||||
if nm:
|
||||
row = con.execute("SELECT id FROM sessions WHERE TRIM(name)=? ORDER BY id DESC LIMIT 1",
|
||||
(nm,)).fetchone()
|
||||
sid = row["id"] if row else None
|
||||
if sid is not None:
|
||||
# 原地续用 = wipe 后重写(与「重新解析」/open_project 注释同口径)。
|
||||
# ⚠️ 此前漏了 wipe:二次打开同名工程会在旧清单上**叠加翻倍**,分组/检索/比对
|
||||
# 全部失真(2026-10-12 接口测试抓到,test_api_p0 防翻倍回归兜住)。
|
||||
# 事务安全:wipe 与 open_project 同连接同事务,解析抛异常时 con.close()
|
||||
# 回滚,旧数据原样保留;成功则备注由 restore_remarks 按 rkey 回填到新行。
|
||||
sess.wipe(con, sid)
|
||||
sid, stat = sess.open_project(con, [(path, os.path.basename(path))], body, job,
|
||||
sid=row["id"] if row else None)
|
||||
sid=sid)
|
||||
# 2026-10-06:关联后台项目批次(同源文件),工作台才能只读展示该项目的询价附件
|
||||
_link_batch(con, sid, os.path.basename(path), body.get("name"))
|
||||
except Exception as e:
|
||||
@@ -2555,16 +2565,29 @@ def _sweep_orphan_attach(con, result):
|
||||
"n_bill": n_bill, "n_norm": n_norm, "n_lme": n_lme, "n_price": n_price, "n_inq": n_inq}
|
||||
|
||||
|
||||
def api_prices(bid, page, size):
|
||||
"""价格批次的明细(信息价 / 市场价的每条材料价格)"""
|
||||
def api_prices(bid, page, size, dir_id=None, subtree=0):
|
||||
"""价格批次的明细(信息价 / 市场价的每条材料价格)。
|
||||
|
||||
2026-10-12 明细页重做:行改 **dict**(前端不再按脆弱下标取列),
|
||||
dir_id 只取该目录的行(subtree=1 含子孙子树,目录树点击汇总用);不传 = 全部。
|
||||
"""
|
||||
c = conn()
|
||||
total = c.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
rows = c.execute("""SELECT Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Class, Note, Block
|
||||
FROM prices WHERE batch_id=? ORDER BY id LIMIT ? OFFSET ?""",
|
||||
(bid, size, (page - 1) * size)).fetchall()
|
||||
w, args = ["batch_id=?"], [bid]
|
||||
if dir_id is not None and str(dir_id) != "":
|
||||
d = int(dir_id)
|
||||
if d > 0:
|
||||
ids = _dir_subtree_ids(c, bid, d) if int(subtree) else [d]
|
||||
w.append("dir_id IN (%s)" % ",".join(map(str, ids)))
|
||||
else: # 0 = 未分类
|
||||
w.append("(dir_id=0 OR dir_id IS NULL)")
|
||||
where = " AND ".join(w)
|
||||
total = c.execute("SELECT COUNT(*) FROM prices WHERE %s" % where, args).fetchone()[0]
|
||||
rows = c.execute("""SELECT id, Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Note, dir_id, Class
|
||||
FROM prices WHERE %s ORDER BY dir_id, id LIMIT ? OFFSET ?""" % where,
|
||||
args + [size, (page - 1) * size]).fetchall()
|
||||
c.close()
|
||||
return {"total": total, "rows": [list(r) for r in rows]}
|
||||
return {"total": total, "rows": [dict(r) for r in rows]}
|
||||
|
||||
|
||||
def _norm(s):
|
||||
@@ -2595,33 +2618,388 @@ def find_dup(con, kind, body):
|
||||
|
||||
|
||||
def _price_parse(path):
|
||||
"""价格文件解析分派:按扩展名选 HTML / Excel 解析器。
|
||||
"""价格文件解析分派(2026-10-12 重设计):**只收标准模板 .xlsx**,其余直接报错。
|
||||
|
||||
两条入口共用后半段(price_html.to_records)与同一套 hash 口径,
|
||||
所以进库后 HTML 导入的价格和 Excel 导入的价格能互相命中。
|
||||
HTML 导入退役(主人定「只能导入 Excel 的标准模板」);price_html 解析器留档不删,
|
||||
guess_period(文件名认期次)等工具函数仍从它引用。
|
||||
"""
|
||||
low = os.path.splitext(path)[1].lower()
|
||||
if low in (".xlsx", ".xls"):
|
||||
if low == ".xlsx":
|
||||
return price_xlsx.parse(path)
|
||||
return price.parse(path)
|
||||
raise ValueError("只支持标准模板 Excel(.xlsx)。请点「标准模板」按钮下载后填写导入")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 价格目录树(2026-10-12 重设计):单根(批次名,不落库)+ 多级 price_dirs;
|
||||
# 行挂叶子(prices.dir_id),prices.Class 冗余完整路径文本;dir_id=0/NULL=未分类。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _dir_path(con, dir_id):
|
||||
"""目录 id → 完整路径文本('a/b/c');0/None → ''(未分类)"""
|
||||
parts, cur = [], dir_id
|
||||
while cur:
|
||||
row = con.execute("SELECT id, parent_id, name FROM price_dirs WHERE id=?", (cur,)).fetchone()
|
||||
if not row:
|
||||
break
|
||||
parts.append(row["name"])
|
||||
cur = row["parent_id"]
|
||||
return price_xlsx.DIR_SEP.join(reversed(parts))
|
||||
|
||||
|
||||
def _dir_ensure_path(con, bid, path):
|
||||
"""按 'a/b/c' 逐级建目录(缺才建),返回叶子目录 id;空路径 → 0(未分类)"""
|
||||
parent = 0
|
||||
for seg in [s.strip() for s in (path or "").split(price_xlsx.DIR_SEP) if s.strip()]:
|
||||
row = con.execute("SELECT id FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=?",
|
||||
(bid, parent, seg)).fetchone()
|
||||
if row:
|
||||
parent = row["id"]
|
||||
else:
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
parent = con.execute("INSERT INTO price_dirs(batch_id, parent_id, name, seq) VALUES(?,?,?,?)",
|
||||
(bid, parent, seg, seq)).lastrowid
|
||||
return parent
|
||||
|
||||
|
||||
def _dir_children(con, bid, parent_id):
|
||||
"""同级目录(排序输出)"""
|
||||
return con.execute("""SELECT id, parent_id, name, seq FROM price_dirs
|
||||
WHERE batch_id=? AND parent_id=? ORDER BY seq, id""",
|
||||
(bid, parent_id)).fetchall()
|
||||
|
||||
|
||||
def _dir_subtree_ids(con, bid, dir_id):
|
||||
"""目录 + 全部子孙 id(含自身)——统计/展示用"""
|
||||
out, stack = [], [dir_id]
|
||||
while stack:
|
||||
d = stack.pop()
|
||||
out.append(d)
|
||||
stack.extend(r["id"] for r in _dir_children(con, bid, d))
|
||||
return out
|
||||
|
||||
|
||||
def _dir_is_leaf(con, bid, dir_id):
|
||||
return not _dir_children(con, bid, dir_id)
|
||||
|
||||
|
||||
def _price_recalc_row(con, pid):
|
||||
"""行内容变化后重算归一键 + 同步 Class 路径(与导入同一套口径,api_import_price 共用)"""
|
||||
r = con.execute("""SELECT Name, Specification, Unit, dir_id FROM prices WHERE id=?""", (pid,)).fetchone()
|
||||
if not r:
|
||||
return
|
||||
cls = _dir_path(con, r["dir_id"])
|
||||
h = _md5(r["Name"], r["Specification"], r["Unit"])
|
||||
con.execute("""UPDATE prices SET x_name_norm=?, x_spec_norm=?, x_unit_norm=?,
|
||||
x_hash_exact=?, x_hash_semi=?, Class=? WHERE id=?""",
|
||||
(_norm(r["Name"]), _norm(r["Specification"]), _norm(r["Unit"]),
|
||||
h, _md5(r["Name"], r["Unit"]), cls, pid))
|
||||
|
||||
|
||||
def _price_dir_counts(con, bid):
|
||||
"""每个目录 id 的**子树行数**(含未分类 dir=0);树节点计数用"""
|
||||
counts = {0: 0}
|
||||
for r in con.execute("SELECT dir_id, COUNT(*) n FROM prices WHERE batch_id=? GROUP BY dir_id",
|
||||
(bid,)):
|
||||
counts[r["dir_id"] or 0] = r["n"]
|
||||
agg = {}
|
||||
for d in [r["id"] for r in con.execute("SELECT id FROM price_dirs WHERE batch_id=?", (bid,))]:
|
||||
agg[d] = sum(counts.get(x, 0) for x in _dir_subtree_ids(con, bid, d))
|
||||
agg[0] = counts.get(0, 0)
|
||||
return agg
|
||||
|
||||
|
||||
def api_price_dirs(con, bid):
|
||||
"""目录树(含每节点子树行数、是否叶子);批次不存在返回空树"""
|
||||
b = con.execute("SELECT id, Name FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
rows = [{"id": r["id"], "parent_id": r["parent_id"], "name": r["name"], "seq": r["seq"]}
|
||||
for r in _dir_children(con, bid, 0)]
|
||||
def build(parent):
|
||||
return [{"id": r["id"], "name": r["name"], "seq": r["seq"],
|
||||
"leaf": _dir_is_leaf(con, bid, r["id"]),
|
||||
"children": build(r["id"])}
|
||||
for r in _dir_children(con, bid, parent)]
|
||||
counts = _price_dir_counts(con, bid)
|
||||
return {"ok": True, "batch_id": bid, "batch_name": b["Name"],
|
||||
"tree": build(0), "counts": counts,
|
||||
"n_uncat": counts.get(0, 0)}
|
||||
|
||||
|
||||
def api_price_dir_save(con, bid, body):
|
||||
"""目录增/改名/移动/上下移/删除。op: add|rename|move|seq|del"""
|
||||
op = body.get("op")
|
||||
b = con.execute("SELECT id FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
if op == "add":
|
||||
parent = int(body.get("parent_id") or 0)
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "目录名称不能为空"}
|
||||
if parent and not con.execute("SELECT 1 FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(parent, bid)).fetchone():
|
||||
return {"ok": False, "msg": "上级目录不存在"}
|
||||
dup = con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=?",
|
||||
(bid, parent, name)).fetchone()
|
||||
if dup:
|
||||
return {"ok": False, "msg": "同级已有同名目录「%s」" % name}
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
did = con.execute("INSERT INTO price_dirs(batch_id, parent_id, name, seq) VALUES(?,?,?,?)",
|
||||
(bid, parent, name, seq)).lastrowid
|
||||
con.commit()
|
||||
return {"ok": True, "id": did, "msg": "已新增目录「%s」" % name}
|
||||
|
||||
did = int(body.get("id") or 0)
|
||||
d = con.execute("SELECT id, parent_id, name, seq FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(did, bid)).fetchone()
|
||||
if not d:
|
||||
return {"ok": False, "msg": "目录不存在"}
|
||||
|
||||
if op == "rename":
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "目录名称不能为空"}
|
||||
dup = con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=? AND id<>?",
|
||||
(bid, d["parent_id"], name, did)).fetchone()
|
||||
if dup:
|
||||
return {"ok": False, "msg": "同级已有同名目录「%s」" % name}
|
||||
con.execute("UPDATE price_dirs SET name=? WHERE id=?", (name, did))
|
||||
sub = ",".join(map(str, _dir_subtree_ids(con, bid, did)))
|
||||
pids = [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id IN (%s)" % sub, (bid,))]
|
||||
for pid in pids:
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已改名「%s」(%d 条行路径同步更新)" % (name, len(pids))}
|
||||
|
||||
if op == "move": # 换父(子树整枝跟动)
|
||||
parent = int(body.get("parent_id") or 0)
|
||||
if parent:
|
||||
p = con.execute("SELECT id, parent_id FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(parent, bid)).fetchone()
|
||||
if not p:
|
||||
return {"ok": False, "msg": "上级目录不存在"}
|
||||
cur, cyc = p["id"], False
|
||||
while cur: # 不能移到自己的子孙下面
|
||||
if cur == did:
|
||||
cyc = True
|
||||
break
|
||||
row = con.execute("SELECT parent_id FROM price_dirs WHERE id=?", (cur,)).fetchone()
|
||||
cur = row["parent_id"] if row else 0
|
||||
if cyc:
|
||||
return {"ok": False, "msg": "不能移动到自己的子目录下面"}
|
||||
if con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=? AND id<>?",
|
||||
(bid, parent, d["name"], did)).fetchone():
|
||||
return {"ok": False, "msg": "目标位置已有同名目录「%s」" % d["name"]}
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
con.execute("UPDATE price_dirs SET parent_id=?, seq=? WHERE id=?", (parent, seq, did))
|
||||
for pid in [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id IN (%s)"
|
||||
% ",".join(map(str, _dir_subtree_ids(con, bid, did))), (bid,))]:
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已移动(子目录整枝跟动)"}
|
||||
|
||||
if op == "seq": # 上移 / 下移:与相邻同级交换 seq
|
||||
delta = 1 if body.get("dir") == "down" else -1
|
||||
sibs = _dir_children(con, bid, d["parent_id"])
|
||||
i = next((k for k, r in enumerate(sibs) if r["id"] == did), -1)
|
||||
j = i + delta
|
||||
if i < 0 or j < 0 or j >= len(sibs):
|
||||
return {"ok": False, "msg": "已经到头了"}
|
||||
other = sibs[j]
|
||||
con.execute("UPDATE price_dirs SET seq=? WHERE id=?", (other["seq"], did))
|
||||
con.execute("UPDATE price_dirs SET seq=? WHERE id=?", (d["seq"], other["id"]))
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已%s(子目录整枝跟动)" % ("下移" if delta > 0 else "上移")}
|
||||
|
||||
if op == "del":
|
||||
kids = _dir_children(con, bid, did)
|
||||
if kids:
|
||||
return {"ok": False, "msg": "先处理子目录(%d 个)再删除" % len(kids)}
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=? AND dir_id=?",
|
||||
(bid, did)).fetchone()[0]
|
||||
if n: # 挂着的行落「未分类」(防误删数据)
|
||||
con.execute("UPDATE prices SET dir_id=0 WHERE batch_id=? AND dir_id=?", (bid, did))
|
||||
for pid in [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id=0", (bid,))]:
|
||||
_price_recalc_row(con, pid)
|
||||
con.execute("DELETE FROM price_dirs WHERE id=?", (did,))
|
||||
con.commit()
|
||||
msg = "已删除目录「%s」" % d["name"] + ("(%d 条行已移入「未分类」)" % n if n else "")
|
||||
return {"ok": True, "msg": msg}
|
||||
|
||||
return {"ok": False, "msg": "未知操作:%s" % op}
|
||||
|
||||
|
||||
def api_price_row_save(con, bid, body):
|
||||
"""价格行新增 / 编辑(行内编辑)。op: add|edit|del
|
||||
|
||||
约束(主人 2026-10-12 定):只有**最底层目录**可以新增行;
|
||||
编辑改了 名称/规格/单位 → 重算比对键(与导入同口径),工作台比对即刻生效。
|
||||
"""
|
||||
op = body.get("op")
|
||||
b = con.execute("SELECT id FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
|
||||
if op == "del":
|
||||
pid = int(body.get("id") or 0)
|
||||
if not con.execute("SELECT 1 FROM prices WHERE id=? AND batch_id=?", (pid, bid)).fetchone():
|
||||
return {"ok": False, "msg": "行不存在"}
|
||||
con.execute("DELETE FROM prices WHERE id=?", (pid,))
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
con.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n, bid))
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已删除该行(本批次剩 %d 条)" % n}
|
||||
|
||||
dir_id = int(body.get("dir_id") or 0)
|
||||
if dir_id:
|
||||
d = con.execute("SELECT id FROM price_dirs WHERE id=? AND batch_id=?", (dir_id, bid)).fetchone()
|
||||
if not d:
|
||||
return {"ok": False, "msg": "所属目录不存在"}
|
||||
if not _dir_is_leaf(con, bid, dir_id):
|
||||
return {"ok": False, "msg": "只有最底层目录才可以挂价格行(该目录还有子目录)"}
|
||||
vals = {
|
||||
"Code": (body.get("code") or "").strip(),
|
||||
"Name": (body.get("name") or "").strip(),
|
||||
"Specification": (body.get("spec") or "").strip(),
|
||||
"Unit": (body.get("unit") or "").strip(),
|
||||
"NoTaxPrice": body.get("notax"),
|
||||
"TaxRate": body.get("taxrate"),
|
||||
"TaxPrice": body.get("taxprice"),
|
||||
"Note": (body.get("note") or "").strip(),
|
||||
}
|
||||
def _fnum(v):
|
||||
try:
|
||||
return float(str(v).replace(",", "").replace("¥", "")) if str(v or "").strip() else None
|
||||
except Exception:
|
||||
return None
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"] = (
|
||||
_fnum(vals["NoTaxPrice"]), _fnum(vals["TaxRate"]), _fnum(vals["TaxPrice"]))
|
||||
miss = [k for k, klabel in (("Name", "材料名称"), ("Unit", "单位")) if not vals[k]]
|
||||
if vals["NoTaxPrice"] is None:
|
||||
miss.append("不含税单价")
|
||||
if miss:
|
||||
return {"ok": False, "msg": "请填写:" + "、".join(miss)}
|
||||
|
||||
if op == "add":
|
||||
if not dir_id:
|
||||
return {"ok": False, "msg": "请选择所属目录(最底层目录或「未分类」)"}
|
||||
cur = con.execute("""INSERT INTO prices(batch_id, Code, Name, Specification, Unit,
|
||||
NoTaxPrice, TaxRate, TaxPrice, Note, Class, dir_id, Block,
|
||||
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi,
|
||||
x_period_start_m, x_period_end_m)
|
||||
SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, x_period_start_m, x_period_end_m
|
||||
FROM batches WHERE id=?""",
|
||||
(bid, vals["Code"], vals["Name"], vals["Specification"], vals["Unit"],
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"], vals["Note"],
|
||||
"", dir_id, "", "", "", "", "", "", bid))
|
||||
_price_recalc_row(con, cur.lastrowid)
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
con.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n, bid))
|
||||
con.commit()
|
||||
return {"ok": True, "id": cur.lastrowid, "msg": "已新增(%s)" % vals["Name"]}
|
||||
|
||||
if op == "edit":
|
||||
pid = int(body.get("id") or 0)
|
||||
if not con.execute("SELECT 1 FROM prices WHERE id=? AND batch_id=?", (pid, bid)).fetchone():
|
||||
return {"ok": False, "msg": "行不存在"}
|
||||
if not dir_id:
|
||||
return {"ok": False, "msg": "请选择所属目录(最底层目录或「未分类」)"}
|
||||
con.execute("""UPDATE prices SET Code=?, Name=?, Specification=?, Unit=?,
|
||||
NoTaxPrice=?, TaxRate=?, TaxPrice=?, Note=?, dir_id=? WHERE id=?""",
|
||||
(vals["Code"], vals["Name"], vals["Specification"], vals["Unit"],
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"], vals["Note"],
|
||||
dir_id, pid))
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已保存(比对键已按新内容重算)"}
|
||||
|
||||
return {"ok": False, "msg": "未知操作:%s" % op}
|
||||
|
||||
|
||||
def api_price_export(con, bid):
|
||||
"""导出「一份数据」:zip(价格明细.xlsx [模板 v2 格式,含目录层级] + 附件原件 + 批次信息页签)。
|
||||
|
||||
返回 (bytes, 文件名);调用方按 Content-Disposition 吐给浏览器。
|
||||
"""
|
||||
import io as _io, zipfile
|
||||
b = con.execute("""SELECT id, kind, Name, x_publisher, x_province, x_city, x_district,
|
||||
x_period_start_m, x_period_end_m, x_note, x_attach_sha
|
||||
FROM batches WHERE id=? AND kind<>'project'""", (bid,)).fetchone()
|
||||
if not b:
|
||||
raise ValueError("批次不存在或不是价格批次")
|
||||
att = None
|
||||
if b["x_attach_sha"]:
|
||||
att = con.execute("SELECT stored_path, original_name FROM attachments WHERE sha256=?",
|
||||
(b["x_attach_sha"],)).fetchone()
|
||||
|
||||
buf = _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr("价格明细.xlsx", _price_export_xlsx(con, b))
|
||||
if att:
|
||||
fp = os.path.join(DATA_DIR, (att["stored_path"] or "").replace("/", os.sep))
|
||||
if os.path.exists(fp):
|
||||
z.write(fp, att["original_name"] or "附件原件")
|
||||
fn = ("%s.zip" % (b["Name"] or "价格批次")).replace("/", "_")
|
||||
return buf.getvalue(), fn
|
||||
|
||||
|
||||
def _price_export_xlsx(con, b):
|
||||
"""批次 → 标准模板 v2 格式的 xlsx bytes(目录=多级路径;附「批次信息」页签)"""
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment
|
||||
bid = b["id"]
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "价格明细"
|
||||
head_fill, head_font = PatternFill("solid", fgColor="1F5FAE"), Font(color="FFFFFF", bold=True, size=11)
|
||||
ws.append(price_xlsx.COLS)
|
||||
for c in ws[1]:
|
||||
c.fill, c.font = head_fill, head_font
|
||||
c.alignment = Alignment(horizontal="center", vertical="center")
|
||||
rows = con.execute("""SELECT Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Note, Class FROM prices WHERE batch_id=? ORDER BY dir_id, id""", (bid,)).fetchall()
|
||||
for r in rows:
|
||||
ws.append([r["Class"], r["Code"], r["Name"], r["Specification"], r["Unit"],
|
||||
r["NoTaxPrice"], (("%g" % r["TaxRate"]) if r["TaxRate"] is not None else ""),
|
||||
r["TaxPrice"], r["Note"]])
|
||||
for col, w in zip("ABCDEFGHI", (32, 12, 30, 22, 8, 14, 9, 14, 28)):
|
||||
ws.column_dimensions[col].width = w
|
||||
ws.freeze_panes = "A2"
|
||||
hb = wb.create_sheet("批次信息")
|
||||
for k, v in [("名称", b["Name"]), ("类型", {"info": "信息价", "market": "市场价"}.get(b["kind"], b["kind"])),
|
||||
("发布单位", b["x_publisher"] or ""), ("地区", "-".join(x for x in
|
||||
[b["x_province"], b["x_city"], b["x_district"]] if x)),
|
||||
("期次起", ym2str(b["x_period_start_m"])), ("期次止", ym2str(b["x_period_end_m"])),
|
||||
("备注", b["x_note"] or "")]:
|
||||
hb.append([k, v])
|
||||
hb.column_dimensions["A"].width = 14
|
||||
hb.column_dimensions["B"].width = 60
|
||||
bio = io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
def api_import_price(con, body):
|
||||
"""信息价 / 市场价导入:HTML 或 Excel。
|
||||
"""信息价 / 市场价导入(2026-10-12 重设计):**只收标准模板 .xlsx,一个文件 = 一个批次**。
|
||||
|
||||
**一个块 = 一个批次**(2026-10-06 改,2026-09-28 定的「一个文件 = 一个批次」作废)。
|
||||
理由:一个价格文件常含多个市场(建材 / 苗木 / 横琴 / 万山),期次还各不相同
|
||||
(2026年7月 vs 2026年4-6月)。挤在一个批次里,批次只能有一个期次 → 只能留空
|
||||
→ ym2str('') 抛 ValueError → 信息价列表整页 500(审查报告里的 DB-1)。
|
||||
拆块之后每个批次有自己的期次:块名里认得出就用块自己的,认不出才用弹框填的。
|
||||
· 名称:弹框填的优先;留空 = 文件名(去扩展名,主人定「名称和附件名称一致(默认),可修改」)
|
||||
· 目录:模板「目录」列按 'a/b/c' 逐级建树,行挂最底层目录;留空 = 未分类
|
||||
· 期次:文件名里认得出的优先(如「珠海信息价_2026年7月」),认不出用弹框填的
|
||||
· 旧版「一个块 = 一个批次」多块循环退役(新模板单 sheet 单批次)
|
||||
"""
|
||||
paths = [p for p in (body.get("path") and [body.get("path")] or []) if p and os.path.exists(p)]
|
||||
if not paths:
|
||||
return {"ok": False, "msg": "请先选择文件(HTML 或 Excel,每次只能导入一个)"}
|
||||
return {"ok": False, "msg": "请先选择文件(标准模板 Excel,每次只能导入一个)"}
|
||||
kind = body.get("kind", "info")
|
||||
if kind not in ("market", "info"):
|
||||
kind = "info"
|
||||
# #4 查重:同名 + 同期次 + 同地区 已存在 → 先让用户确认
|
||||
dup = find_dup(con, kind, body)
|
||||
if dup and not body.get("force"):
|
||||
return {"ok": False, "need_confirm": True, "dup": dup,
|
||||
@@ -2633,8 +3011,8 @@ def api_import_price(con, body):
|
||||
dist = body.get("district") or ""
|
||||
p1 = _period(body.get("period_from"))
|
||||
p2 = _period(body.get("period_to")) or p1
|
||||
note = (body.get("note") or "").strip() # 备注(唯一选填项)
|
||||
pub = (body.get("publisher") or "").strip() # 发布单位(必填,2026-09-28 定)
|
||||
note = (body.get("note") or "").strip()
|
||||
pub = (body.get("publisher") or "").strip()
|
||||
|
||||
cur = con.cursor()
|
||||
created, total_rows, blocks_info = [], 0, []
|
||||
@@ -2642,29 +3020,20 @@ def api_import_price(con, body):
|
||||
try:
|
||||
blocks = _price_parse(path)
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": "解析失败(%s):%s" % (os.path.basename(path), e)}
|
||||
return {"ok": False, "msg": "导入失败:%s" % e}
|
||||
fname = os.path.splitext(os.path.basename(path))[0]
|
||||
# 文件名里的期次(如「珠海信息价_2026年7月」)—— 块名里没写年月时用它兜底,
|
||||
# 比让用户在弹框里手填更准,也避免同一个文件里的 4 个市场被塞成同一个「空期次」
|
||||
fp1, fp2 = price.guess_period(fname)
|
||||
for b in blocks:
|
||||
recs = price.to_records([b]) # 只取这一个块的行
|
||||
recs = price_xlsx.to_records([b])
|
||||
if not recs:
|
||||
continue
|
||||
# 期次优先顺序:块名里认出来的 → 文件名里认出来的 → 导入弹框里填的
|
||||
bp1 = b.get("period_start_m")
|
||||
bp2 = b.get("period_end_m")
|
||||
s1 = bp1 if bp1 is not None else (fp1 if fp1 is not None else p1)
|
||||
s2 = bp2 if bp2 is not None else (fp2 if fp2 is not None else p2)
|
||||
s1 = b.get("period_start_m") if b.get("period_start_m") is not None else (fp1 if fp1 is not None else p1)
|
||||
s2 = b.get("period_end_m") if b.get("period_end_m") is not None else (fp2 if fp2 is not None else p2)
|
||||
if s1 is None:
|
||||
s1 = s2
|
||||
if s2 is None:
|
||||
s2 = s1
|
||||
blk = (b.get("block") or "").strip()
|
||||
# 名称:多块时用块名(块名本身就是市场名,最清楚);单块时用弹框填的名称
|
||||
bname = blk if len(blocks) > 1 else (base_name or blk or fname)
|
||||
if not bname:
|
||||
bname = fname
|
||||
bname = base_name or b.get("block") or fname # 名称默认=文件名(block 即文件名)
|
||||
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_src_hash, x_note, x_publisher,
|
||||
@@ -2675,23 +3044,24 @@ def api_import_price(con, body):
|
||||
price.PARSER_VER))
|
||||
bid = cur.lastrowid
|
||||
for r in recs:
|
||||
dir_id = _dir_ensure_path(cur, bid, r["Class"])
|
||||
h = _md5(r["Name"], r["Specification"], r["Unit"])
|
||||
cur.execute("""INSERT INTO prices(batch_id, Code, Name, Specification, Unit,
|
||||
NoTaxPrice, TaxRate, TaxPrice, Class, Note, Block, x_name_norm, x_spec_norm, x_unit_norm,
|
||||
x_hash_exact, x_hash_semi, x_period_start_m, x_period_end_m)
|
||||
NoTaxPrice, TaxRate, TaxPrice, Class, Note, dir_id,
|
||||
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi,
|
||||
x_period_start_m, x_period_end_m)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, r["Code"], r["Name"], r["Specification"], r["Unit"], r["NoTaxPrice"],
|
||||
r["TaxRate"], r["TaxPrice"], r["Class"], r["Note"], r.get("Block", ""),
|
||||
r["TaxRate"], r["TaxPrice"], _dir_path(cur, dir_id), r["Note"], dir_id,
|
||||
_norm(r["Name"]), _norm(r["Specification"]), _norm(r["Unit"]), h,
|
||||
_md5(r["Name"], r["Unit"]), s1, s2))
|
||||
# 2026-10-06:价格条数写 x_rows_price(不写 x_rows_lme —— 那是工料机专用列)
|
||||
cur.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (len(recs), bid))
|
||||
created.append(bid); total_rows += len(recs)
|
||||
blocks_info.append({"batch_id": bid, "name": bname[:80], "rows": len(recs),
|
||||
"period": "%s~%s" % (s1, s2) if s1 is not None else "",
|
||||
"block": blk[:80]})
|
||||
"block": ""})
|
||||
if not created:
|
||||
return {"ok": False, "msg": "这个文件里没有可导入的数据行"}
|
||||
return {"ok": False, "msg": "这个文件里没有可导入的数据行(名称列全空?)"}
|
||||
con.commit()
|
||||
return {"ok": True, "batches": created, "blocks": blocks_info, "n_rows": total_rows,
|
||||
"msg": "导入完成:%d 个价格批次、共 %d 条材料价格" % (len(created), total_rows)}
|
||||
@@ -3566,6 +3936,30 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _export_zip(self, bid):
|
||||
"""导出价格批次「一份数据」:zip = 价格明细.xlsx(含目录层级)+ 附件原件 + 批次信息页签"""
|
||||
c = conn()
|
||||
try:
|
||||
raw, fn = api_price_export(c, bid)
|
||||
except ValueError as e:
|
||||
c.close()
|
||||
return self._json({"error": str(e)}, 404)
|
||||
except ImportError:
|
||||
c.close()
|
||||
return self._json({"error": "缺少 openpyxl,无法导出(pip install openpyxl)"}, 500)
|
||||
finally:
|
||||
try:
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._allow_cache = True
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/zip")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Content-Disposition", self._cd(fn, "price_export.zip"))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _gate_send(self, r):
|
||||
"""发送门禁拦截响应:授权页(自包含 HTML)或 JSON 错误。"""
|
||||
if r.get("kind") == "html":
|
||||
@@ -3673,7 +4067,19 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
return self._json(api_similar(int(m.group(1)), one.get("profession")))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/prices$", p)
|
||||
if m:
|
||||
return self._json(api_prices(int(m.group(1)), int(one.get("page", 1)), int(one.get("page_size", 50))))
|
||||
return self._json(api_prices(int(m.group(1)), int(one.get("page", 1)),
|
||||
int(one.get("page_size", 50)),
|
||||
one.get("dir_id"), int(one.get("subtree", 0) or 0)))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/dirs$", p) # 价格目录树(2026-10-12)
|
||||
if m:
|
||||
c = conn()
|
||||
try:
|
||||
return self._json(api_price_dirs(c, int(m.group(1))))
|
||||
finally:
|
||||
c.close()
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/export$", p) # 导出一份数据(zip,2026-10-12)
|
||||
if m:
|
||||
return self._export_zip(int(m.group(1)))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/attach$", p)
|
||||
if m:
|
||||
c = conn(); r = api_attach_info(c, int(m.group(1))); c.close()
|
||||
@@ -3868,6 +4274,28 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/dirs$", u.path) # 价格目录:增/改名/移动/上下移/删(2026-10-12)
|
||||
if m:
|
||||
with WRITE_LOCK:
|
||||
c = conn()
|
||||
try:
|
||||
r = api_price_dir_save(c, int(m.group(1)), body)
|
||||
except Exception as e:
|
||||
c.rollback(); r = {"ok": False, "msg": "目录操作失败:%s" % e}
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/prices$", u.path) # 价格行:新增/编辑/删(行内编辑,2026-10-12)
|
||||
if m:
|
||||
with WRITE_LOCK:
|
||||
c = conn()
|
||||
try:
|
||||
r = api_price_row_save(c, int(m.group(1)), body)
|
||||
except Exception as e:
|
||||
c.rollback(); r = {"ok": False, "msg": "保存失败:%s" % e}
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
if u.path == "/api/session/remark": # 审核备注(双写:界面 + 持久表)
|
||||
# ⚠️ 2026-09-30:以前只写 s_bills.x_remark —— 删除会话 / 重新解析(wipe)会连备注一起没。
|
||||
# 现在同时写 s_remarks(不参与 wipe),重新解析后由 restore_remarks() 按 rkey 回填。
|
||||
|
||||
@@ -16,8 +16,20 @@ sys.path.insert(0, os.path.join(HERE, "core"))
|
||||
import api_server
|
||||
|
||||
PORT = api_server.PORT
|
||||
URL = "http://127.0.0.1:%d/workbench.html" % PORT
|
||||
ADMIN_URL = "http://127.0.0.1:%d/admin.html" % PORT
|
||||
|
||||
|
||||
def _page_ver(name):
|
||||
"""页面文件 mtime 作版本参数(2026-10-12):文件一更新 URL 就变,任何内核的
|
||||
磁盘缓存都必然失配。起因:主人的 WebView2 对静态响应的 no-store 不完全遵守,
|
||||
价格库重设计后壳里一直显示旧界面(IAB/新浏览器带 ?v= 才是新的)。"""
|
||||
try:
|
||||
return str(int(os.path.getmtime(os.path.join(api_server.ROOT, name))))
|
||||
except Exception:
|
||||
return "0"
|
||||
|
||||
|
||||
URL = "http://127.0.0.1:%d/workbench.html?v=%s" % (PORT, _page_ver("workbench.html"))
|
||||
ADMIN_URL = "http://127.0.0.1:%d/admin.html?v=%s" % (PORT, _page_ver("admin.html"))
|
||||
LOG = os.path.join(ROOT, "data", "launch.log")
|
||||
|
||||
|
||||
|
||||
@@ -269,7 +269,8 @@ CREATE TABLE IF NOT EXISTS prices(
|
||||
x_unit_norm TEXT,
|
||||
x_hash_exact TEXT, -- md5(名称归一 + 规格归一 + 单位归一)
|
||||
x_hash_semi TEXT, -- md5(名称归一 + 单位归一) 次精确档(2026-10-08,与 lmes 同口径)
|
||||
Block TEXT, -- 区块/大类(信息价 HTML 里的一级分组)
|
||||
Block TEXT, -- 区块/大类(信息价 HTML 里的一级分组;2026-10-12 起新导入不再写,留供旧数据)
|
||||
dir_id INTEGER, -- 挂在哪个目录(price_dirs.id;0/NULL=未分类;2026-10-12 新增)
|
||||
x_period_start_m INTEGER,
|
||||
x_period_end_m INTEGER
|
||||
);
|
||||
@@ -278,6 +279,26 @@ CREATE INDEX IF NOT EXISTS ix_price_exact ON prices(x_hash_exact);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_semi ON prices(x_hash_semi); -- 次精确档(2026-10-08)
|
||||
CREATE INDEX IF NOT EXISTS ix_price_key ON prices(x_name_norm, x_spec_norm, x_unit_norm);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 价格目录树(2026-10-12 重设计,主人定)
|
||||
--
|
||||
-- 每个价格批次(kind='info'/'market')一棵自己的树:单根=批次名(根不落库,
|
||||
-- parent_id=0 即一级目录),层级不限。只有**最底层目录(叶子)**可以挂价格行
|
||||
-- (prices.dir_id 指到叶子;中间层目录只是路径节点,新增行由应用层拒绝)。
|
||||
-- prices.Class 同步冗余完整路径文本(「建筑材料/黑色及有色金属/钢筋」),
|
||||
-- 供导出 Excel 与检索展示直接取用,不用回溯 join。
|
||||
-- 「(未分类)」不落库:dir_id=0 即未分类,由界面渲染固定节点。
|
||||
-- ===========================================================================
|
||||
CREATE TABLE IF NOT EXISTS price_dirs(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER NOT NULL,
|
||||
parent_id INTEGER NOT NULL DEFAULT 0, -- 0=挂在批次根下的 一级目录;否则=父目录 id
|
||||
name TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL DEFAULT 0, -- 同级排序(小在前)
|
||||
UNIQUE(batch_id, parent_id, name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_pdir_batch ON price_dirs(batch_id, parent_id);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 询价附件(2026-10-06 新增)
|
||||
--
|
||||
|
||||
180
CostReview/app/tests/api_harness.py
Normal file
180
CostReview/app/tests/api_harness.py
Normal file
@@ -0,0 +1,180 @@
|
||||
# -*- 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="测试建设单位"):
|
||||
"""构造最小可解析的 .cos4(zip 内 Project.xml + 单位工程 xml)。
|
||||
|
||||
bills: [(编码, 名称, 特征, 单位, 工程量, 单价)] —— 分部分项清单(自动配 1 条定额 + 定额消耗)
|
||||
lmes: [(编码, 名称, 规格, 单位, 不含税价, 含税价)] —— 工料机(会进 lmes 与项目级汇总)
|
||||
另固定带:1 条措施清单(安全文明施工费)、项目特征 1 条、总造价 1234567.89。
|
||||
"""
|
||||
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)
|
||||
proj = (
|
||||
'<ConstructionProject Name=%s FileKind="1" BulidUnit=%s>'
|
||||
'<SummaryOfCost Total="1234567.89"/>'
|
||||
'<InfoItem Name="工程类别" Value="房屋建筑"/>'
|
||||
'<DivisionalAndElementalProject Number="SEC1" Name="主体工程">'
|
||||
'<UnitWorks Number="UW1"/></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[0][0] if lmes else "000001"
|
||||
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>'
|
||||
'<LabourMaterialsEquipmentsMachinesElement Number=%s Quantity="1.5"/>'
|
||||
'</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)), quoteattr(lme0)))
|
||||
|
||||
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/>'
|
||||
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
|
||||
quoteattr(it[4]), quoteattr(it[5]))
|
||||
for it in lmes)))
|
||||
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr("Project.xml", proj.encode("utf-8"))
|
||||
z.writestr("UW1.xml", uw.encode("utf-8"))
|
||||
return 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 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}
|
||||
101
CostReview/app/tests/test_api_group.py
Normal file
101
CostReview/app/tests/test_api_group.py
Normal file
@@ -0,0 +1,101 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""类似清单分组 v2 管线测试:条数守恒、名称层字集并组、关键词层(规则表)、
|
||||
组价不一致。全部经真实接口(/api/session/similar、/api/session/inconsistent)。"""
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from api_harness import fixture_file, get, post, server # noqa: F401
|
||||
|
||||
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):
|
||||
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
|
||||
214
CostReview/app/tests/test_api_p0.py
Normal file
214
CostReview/app/tests/test_api_p0.py
Normal file
@@ -0,0 +1,214 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""P0 接口回归:导入 / 会话 / 比对 / 检索 / 删除 / 行内编辑。
|
||||
|
||||
全部跑在一个隔离副本服务上(见 api_harness.py):生产库零接触;
|
||||
库内断言用只读 sqlite 连接直查副本库,接口断言用 httpx。
|
||||
"""
|
||||
import sqlite3
|
||||
|
||||
from api_harness import (META, PERIOD_202607, fixture_file, get, # noqa: F401
|
||||
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):
|
||||
p = server["src_dir"] / "old.xml.cos4"
|
||||
p.write_bytes(b'<?xml version="1.0" encoding="utf-8"?><Projects/>')
|
||||
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_confirm_then_force(server):
|
||||
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 True
|
||||
r3 = post(server, "/api/admin/import", dict(body, force=True))
|
||||
assert r3["ok"] is True and r3["batch_id"] != b1["batch_id"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 会话(打开工程)
|
||||
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")
|
||||
assert lmes["total"] == 2
|
||||
# 写备注 → 同名重开(原地续用,wipe 后重写)→ 行数不翻倍 + 备注按 rkey 回填
|
||||
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 True and r2["session_id"] == sid # 同名只留一个会话
|
||||
assert r2["n_bill"] == 3 # 重写后的条数
|
||||
rows2 = get(server, "/api/session/rows", session_id=sid, type="bill")
|
||||
assert rows2["total"] == 3 # ⚠️ 防翻倍回归:旧数据必须被清场
|
||||
remark = _q(server["sessdb"], "SELECT x_remark FROM s_bills"
|
||||
" WHERE session_id=? AND Number=?", (sid, CAM[0]))[0][0]
|
||||
assert remark == "摄像机价格存疑" # rkey 回填到重写后的新行
|
||||
n = _q(server["sessdb"], "SELECT COUNT(*) FROM s_remarks WHERE remark=?",
|
||||
("摄像机价格存疑",))[0][0]
|
||||
assert n >= 1 # 持久表双写
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 比对
|
||||
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_CAM, LME_CONC])
|
||||
_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 定)
|
||||
322
CostReview/app/tests/test_api_p1.py
Normal file
322
CostReview/app/tests/test_api_p1.py
Normal file
@@ -0,0 +1,322 @@
|
||||
# -*- 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" / "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) / sha[:2] / ("%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]})
|
||||
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, ""),
|
||||
("", "", "散装水泥", "", "t", 380, 0.13, 429.4, "")]) # 目录留空 = 未分类
|
||||
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] == 3
|
||||
# 目录树:两个一级(苗木)+ 两个叶子(乔木/灌木);未分类 1 行
|
||||
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"] == 1
|
||||
# 行挂叶子 + 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] == 1
|
||||
# 与另一次导入同名称/规格/单位 → 同精确键(可互相比对)
|
||||
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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 数据源字典
|
||||
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"]
|
||||
95
CostReview/app/tests/test_api_upgrade.py
Normal file
95
CostReview/app/tests/test_api_upgrade.py
Normal file
@@ -0,0 +1,95 @@
|
||||
# -*- 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):
|
||||
"""打开即升级(方案 A):audit 同源文件 → 响应带升级提示,批次口径回到当前版。
|
||||
走 uploads 流程:升级按 x_src_hash(=uploads 文件名)匹配同源批次。"""
|
||||
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,))
|
||||
r = post(server, "/api/audit",
|
||||
{"path": up["path"], "name": name, "province": "广东省", "city": "珠海市",
|
||||
"district": "香洲区", "period_from": PERIOD_202607, "file_kind": 1})
|
||||
assert r["ok"] is True and "自动升级" in r["msg"], r
|
||||
assert _ver(server, bid)[0] == fresh
|
||||
|
||||
|
||||
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 # 价格批次暂不支持自动升级
|
||||
128
CostReview/app/tests/test_match_tiers.py
Normal file
128
CostReview/app/tests/test_match_tiers.py
Normal file
@@ -0,0 +1,128 @@
|
||||
# -*- 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] == ["远期批次"]
|
||||
219
CostReview/app/tests/test_price_redesign.py
Normal file
219
CostReview/app/tests/test_price_redesign.py
Normal file
@@ -0,0 +1,219 @@
|
||||
# -*- 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, ""),
|
||||
("", "", "散装水泥", "", "t", 380, 13, 429.4, "")])
|
||||
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、未分类=1
|
||||
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"] == 1
|
||||
# 行的 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"] == 3 # 1 + 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"] == 1
|
||||
allr = get(server, "/api/admin/batch/%d/prices" % bid, page=1, page_size=50)
|
||||
assert allr["total"] == 5 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)
|
||||
assert any((r[0] in (None, "")) and r[2] == "散装水泥" for r in body) # 未分类导出留空
|
||||
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"]
|
||||
204
CostReview/app/tests/test_unit_core.py
Normal file
204
CostReview/app/tests/test_unit_core.py
Normal file
@@ -0,0 +1,204 @@
|
||||
# -*- 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
|
||||
# 标准模板生成 → 解析往返(模板自带 4 行示例,其中 1 行未分类)
|
||||
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) == 4
|
||||
assert sum(1 for r in recs2 if not r["Class"]) == 1 # 未分类示例 1 条
|
||||
@@ -168,6 +168,38 @@ a:hover{text-decoration:underline}
|
||||
#dright{flex:1;overflow:auto;min-width:0}
|
||||
#dright .secH{padding:10px 14px;font-size:14px;font-weight:700;color:#111827;background:#fafbfc;
|
||||
border-bottom:1px solid var(--line);position:sticky;top:0}
|
||||
/* ===== 价格明细重做(2026-10-12):多级目录树 + 行内编辑 ===== */
|
||||
.pnode{padding:4px 6px;margin:1px 0;cursor:pointer;border-radius:6px;color:#374151;font-size:12.5px;
|
||||
display:flex;align-items:center;gap:5px;white-space:nowrap}
|
||||
.pnode .nm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
.pnode .cnt{color:#9aa4b2;font-size:11px;flex:none}
|
||||
.pnode:hover{background:#f3f4f6}
|
||||
.pnode.on{background:#2563eb;color:#fff}
|
||||
.pnode.on .cnt{color:#dbe7ff}
|
||||
.pnode .ops{display:none;flex:none;gap:2px}
|
||||
.pnode:hover .ops,.pnode.ops-on .ops,.pnode.on .ops{display:inline-flex}
|
||||
/* ↑ 选中目录的按钮排常显(2026-10-13 主人找不到"+子目录"入口):
|
||||
悬停可见照旧,选中的那一行不用悬停也能看到全部按钮 */
|
||||
.pnode .ops 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;white-space:nowrap}
|
||||
.pnode .ops span:hover{background:var(--c2);color:#fff;border-color:var(--c2)}
|
||||
.pnode .ops span.pd:hover{background:#c0392b;border-color:#c0392b} /* 删除 / 取消:红 */
|
||||
.pnode .ops span.pk:hover{background:#1a7f37;border-color:#1a7f37} /* 确认:绿 */
|
||||
.pnode input.ren{width:120px;padding:1px 6px;font-size:12px;border-radius:4px;border:1px solid #9fb6d4}
|
||||
.pnode .cfm{display:inline-flex;gap:3px;align-items:center;background:#fff7e6;border:1px solid #f0d9a8;
|
||||
border-radius:4px;padding:1px 4px;font-size:11px;color:#8a6d1a;flex:none}
|
||||
.pkids{margin-left:12px;border-left:1px dotted #cbd5e1;padding-left:4px}
|
||||
#ptool{display:flex;align-items:center;gap:8px;padding:9px 14px;background:#fafcff;
|
||||
border-bottom:1px solid var(--line);flex-wrap:wrap}
|
||||
#ptool .where{font-size:12px;color:#34506f;background:#eef3fa;border:1px solid #d8e0ec;border-radius:4px;padding:2px 8px}
|
||||
#ptool .tgt{display:none;align-items:center;gap:6px;font-size:12px;color:#8a6d1a;
|
||||
background:#fff7e6;border:1px solid #f0d9a8;border-radius:4px;padding:2px 8px}
|
||||
#ptool.editing .tgt{display:inline-flex}
|
||||
.btn.dis{color:#9aa4b2;background:#f4f6f9;cursor:not-allowed;border-color:#d8e0ec}
|
||||
tr.pedit{background:#fffbef}
|
||||
td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb6d4;border-radius:4px}
|
||||
.newflag{display:inline-block;margin-left:6px;padding:0 5px;border-radius:3px;background:#fff7e6;
|
||||
border:1px solid #f0d9a8;color:#8a6d1a;font-size:11px}
|
||||
</style>
|
||||
<link rel="stylesheet" href="common.css">
|
||||
</head>
|
||||
@@ -191,7 +223,8 @@ a:hover{text-decoration:underline}
|
||||
<!-- 工作台入口(2026-10-06 主人定):从标题行右上角搬到标签栏,排在「设置」右边。
|
||||
图标 ▶ = 进入另一个页面(⚙ = 当前页设置);两者底部对齐、圆角一致,
|
||||
按钮比标签矮约 3px,只靠颜色区分主动作(蓝=进入,灰=设置)。 -->
|
||||
<a class="btn pri" style="text-decoration:none" href="/workbench.html"
|
||||
<!-- 时间戳参数:老 WebView2 对 no-store 不完全遵守,跨页跳转带新 URL 强制绕缓存(2026-10-12) -->
|
||||
<a class="btn pri" style="text-decoration:none" href="javascript:location.href='/workbench.html?v='+Date.now()"
|
||||
title="打开工作台:导入工程、做历史比对与审核">▶ 工作台</a>
|
||||
</div>
|
||||
|
||||
@@ -249,6 +282,14 @@ a:hover{text-decoration:underline}
|
||||
<!-- 类似清单(p2)的左组目录树(2026-10-08 主人定:后台同工作台;仅该标签显示) -->
|
||||
<div id="simtree" style="display:none"></div>
|
||||
<div id="dright">
|
||||
<!-- 价格明细工具行(2026-10-12 重做):只有价格批次显示;行编辑/新增时出现「所属目录」下拉 -->
|
||||
<div id="ptool" style="display:none">
|
||||
<button class="btn pri" id="padd" onclick="rowNew()">+ 新增行</button>
|
||||
<span class="where" id="pwhere"></span>
|
||||
<span class="tgt">所属目录:<select id="pdirsel" style="max-width:260px"></select></span>
|
||||
<button class="btn" onclick="pdExport()">⤓ 导出</button>
|
||||
<button class="btn" onclick="att(DID)">📎 附件</button>
|
||||
</div>
|
||||
<div id="dsecH" class="secH" style="display:none"></div>
|
||||
<!-- 原数据(p3):结构与工作台一致(左树 + 右标签卡),渲染由 common.js 的 RawView 提供 -->
|
||||
<div id="drawbox" class="rawbox" style="display:none">
|
||||
@@ -721,59 +762,272 @@ function rowPrice(r){ // 信息价 / 市场价:序号/纳入/名称/发布单
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
// 价格明细:左侧目录(一级:批次名 → 分类),右侧只显示当前选中的分类
|
||||
let PORDER=[], PGROUP={}, PATT={has:false}, PTITLE='', CURSEC=-1;
|
||||
// 左侧目录树的根(批次名)折叠状态:这两个必须定义,否则 renderPrice() 里引用会抛 ReferenceError,
|
||||
// 整个「价格明细」(表头 + 表体 + 统计)都会渲染不出来(2026-09-29 修)
|
||||
let TREE_FOLD=false;
|
||||
function toggleTree(){
|
||||
TREE_FOLD=!TREE_FOLD;
|
||||
const r=document.getElementById('treeRoot');
|
||||
if(r) r.classList.toggle('collapsed', TREE_FOLD);
|
||||
/* =========================================================================
|
||||
价格明细(2026-10-12 重做,主人定):
|
||||
左 = 本批次自己的多级目录树(单根=批次名;行内增删改名/上下移,↑↓✕ 两段式确认);
|
||||
右 = 选中目录的价格行(行内编辑/新增;**只有最底层目录可新增行**)。
|
||||
接口:GET /api/admin/batch/{id}/dirs 树 + 子树行数
|
||||
GET /api/admin/batch/{id}/prices?dir_id&subtree 行(dict,subtree=1 含子孙)
|
||||
POST /api/admin/batch/{id}/dirs {op:add|rename|move|seq|del, ...}
|
||||
POST /api/admin/batch/{id}/prices {op:add|edit|del, ...}
|
||||
行编辑改 名称/规格/单位 后,服务端按导入同款口径重算比对键,工作台比对即刻生效。
|
||||
========================================================================= */
|
||||
const COL_PRICE=[
|
||||
{t:'材料编码',a:'c',w:100},
|
||||
{t:'材料名称',a:'l',w:180},
|
||||
{t:'规格型号',a:'l',w:150},
|
||||
{t:'单位',a:'c',w:56},
|
||||
{t:'不含税单价',a:'r',w:96,num:1},
|
||||
{t:'税率',a:'r',w:64,num:1},
|
||||
{t:'含税单价',a:'r',w:96,num:1},
|
||||
{t:'备注',a:'l',w:180},
|
||||
{t:'操作',a:'c',w:100}
|
||||
];
|
||||
// 树 + 行的全部界面状态(换批次/换标签在 loadTab 价格分支复位)
|
||||
let PD={tree:[],counts:{},nUncat:0,cur:0,curName:'',curPath:'',curLeaf:true,picked:false,
|
||||
rows:[],total:0,att:{has:false},
|
||||
ren:0, // 正在改名的目录 id(0=无)
|
||||
adding:null, // 新建目录:{parent, mode:'child'|'sib', sib}(sib=-1=插同级末尾)
|
||||
cfm:null, // 待二次确认:{id, op:'up'|'down'|'del'}
|
||||
cfmRow:0, // 待确认删除的行 id
|
||||
editId:0, // 正在行内编辑的行 id(0=无)
|
||||
addingRow:false}; // 底部新增行
|
||||
let PDMAP={}; // 目录 id → {name, leaf, parent, path}(渲染/取值用,renderTree 时重建)
|
||||
function pdClear(){ PD.ren=0; PD.adding=null; PD.cfm=null; PD.cfmRow=0; }
|
||||
|
||||
async function loadPrice(){
|
||||
$('ptool').style.display='flex';
|
||||
const [d,a]=await Promise.all([J(`/api/admin/batch/${DID}/dirs`),
|
||||
J(`/api/admin/batch/${DID}/attach`)]);
|
||||
PD.tree=d.tree||[]; PD.counts=d.counts||{}; PD.nUncat=d.n_uncat||0; PD.att=a;
|
||||
renderTree(); // 先建 PDMAP(名称/路径/叶子都从它取)
|
||||
// 没选过(首次打开/换批次)→ 默认选第一个一级目录;选过的目录被删了 → 也落回第一个
|
||||
if((!PD.picked || (PD.cur!==0 && !PDMAP[PD.cur])))
|
||||
PD.cur = PD.tree.length ? PD.tree[0].id : 0;
|
||||
const m=PDMAP[PD.cur];
|
||||
PD.curName=m?m.name:'(未分类)';
|
||||
PD.curPath=m?m.path:'';
|
||||
PD.curLeaf=PD.cur===0?true:!!m.leaf;
|
||||
await loadPriceRows();
|
||||
}
|
||||
function renderPrice(){
|
||||
const cg=document.getElementById('dcg'), th=document.getElementById('dth'), tb=document.getElementById('dtbd');
|
||||
const head=document.getElementById('dsecH');
|
||||
// 三级:根(批次名) → 块 → 分类
|
||||
const byBlock={}, blocks=[];
|
||||
PORDER.forEach((s,i)=>{
|
||||
if(!(s.block in byBlock)){ byBlock[s.block]=[]; blocks.push(s.block); }
|
||||
byBlock[s.block].push({cls:s.cls, i:i, n:(PGROUP[s.key]||[]).length});
|
||||
});
|
||||
const kids = blocks.map(b=>{
|
||||
const secs = byBlock[b].map(x=>
|
||||
`<div class="secT ${x.i===CURSEC?'on':''}" onclick="pickSec(${x.i})" title="${esc(x.cls)}">${esc(x.cls||'(未分类)')}</div>`
|
||||
).join('');
|
||||
return `<div class="blk"><div class="blab" onclick="this.parentNode.classList.toggle('fold')">
|
||||
<span class="ar">▾</span>${esc(b||'(未分块)')}</div><div class="bkids">${secs}</div></div>`;
|
||||
}).join('');
|
||||
dside.innerHTML = PORDER.length
|
||||
? `<div class="tot${TREE_FOLD?' collapsed':''}" id="treeRoot">
|
||||
<div class="lab" onclick="toggleTree()"><span class="ar">▾</span>${esc(PTITLE)}
|
||||
<span style="font-weight:400;color:#6b7280">(${blocks.length} 块 · ${PORDER.length} 分类)</span></div>
|
||||
<div class="children">${kids}</div>
|
||||
</div>`
|
||||
: '<div class="treeT">(没有数据)</div>';
|
||||
cg.innerHTML=COL_PRICE.map(c=>`<col style="width:${c.w}px">`).join('');
|
||||
sumw($('dtb')); colwApply($('dtb'));
|
||||
th.innerHTML=headHTML(COL_PRICE);
|
||||
const cur=PORDER[CURSEC];
|
||||
const rows = cur ? (PGROUP[cur.key]||[]) : [];
|
||||
head.textContent = (cur ? (cur.block?cur.block+' / ':'') + (cur.cls||'(未分类)') : '(未分类)')
|
||||
+ (rows.length?` 共 ${rows.length} 条`:'');
|
||||
tb.innerHTML = rows.map(r=>'<tr>'+COL_PRICE.map(c=>cellHTML(c, r[c.k])).join('')+'</tr>').join('')
|
||||
|| `<tr><td colspan="${COL_PRICE.length}" class="tip" style="text-align:center;padding:16px">没有数据</td></tr>`;
|
||||
dcnt.innerHTML = `价格 ${PORDER.reduce((s,x)=>s+(PGROUP[x.key]||[]).length,0)} 条 · ${PORDER.length} 个分类` +
|
||||
(PATT.has ? ` · 原件:<a href="/api/admin/file/${PATT.sha256}" data-n="${esc(PATT.name)}"
|
||||
onclick="return dlFile('${PATT.sha256}', this.getAttribute('data-n'))"
|
||||
title="另存为(自己选保存位置)">${esc(PATT.name)}</a>` : ' · 未挂附件');
|
||||
function dirExists(id){
|
||||
return id===0 || !!PDMAP[id];
|
||||
}
|
||||
function pickSec(i){
|
||||
CURSEC=i;
|
||||
dside.querySelectorAll('.secT').forEach((el,j)=>el.classList.toggle('on', j===i));
|
||||
renderPrice();
|
||||
async function loadPriceRows(){
|
||||
renderTree();
|
||||
const d=await J(`/api/admin/batch/${DID}/prices?page=1&page_size=5000&dir_id=${PD.cur}&subtree=1`);
|
||||
PD.rows=d.rows||[]; PD.total=d.total||0;
|
||||
renderRows();
|
||||
document.getElementById('dright').scrollTop=0;
|
||||
}
|
||||
async function pickDir(id){
|
||||
PD.cur=id; PD.picked=true; PD.editId=0; PD.addingRow=false; pdClear();
|
||||
const m=PDMAP[id];
|
||||
PD.curName=m?m.name:'(未分类)';
|
||||
PD.curPath=m?m.path:'';
|
||||
PD.curLeaf=id===0?true:!!m.leaf;
|
||||
await loadPriceRows();
|
||||
}
|
||||
function buildMap(ns,parent,path){
|
||||
ns.forEach(n=>{
|
||||
const p=path?path+' / '+n.name:n.name;
|
||||
PDMAP[n.id]={name:n.name,leaf:!!n.leaf,parent:parent,path:p};
|
||||
if(n.children&&n.children.length) buildMap(n.children,n.id,p);
|
||||
});
|
||||
}
|
||||
function leavesHTML(sel){
|
||||
const out=[];
|
||||
(function walk(ns,p){ ns.forEach(n=>{
|
||||
if(n.leaf) out.push({id:n.id,name:p?p+' / '+n.name:n.name});
|
||||
if(n.children&&n.children.length) walk(n.children,p?p+' / '+n.name:n.name);
|
||||
});})(PD.tree,'');
|
||||
return '<option value="0">(未分类)</option>'
|
||||
+ out.map(o=>`<option value="${o.id}"${o.id===sel?' selected':''}>${esc(o.name)}</option>`).join('');
|
||||
}
|
||||
/* ---- 树渲染:编辑态(改名/新建)与确认态(↑↓✕)都整树重画,状态在 PD ---- */
|
||||
function renderTree(){
|
||||
PDMAP={}; buildMap(PD.tree,0,'');
|
||||
const grand = PD.tree.length
|
||||
? PD.tree.reduce((s,n)=>s+(PD.counts[n.id]||0),0)+PD.nUncat
|
||||
: PD.nUncat;
|
||||
dside.innerHTML=`
|
||||
<div class="tot">
|
||||
<div class="lab"><span class="ar">▾</span>${esc(dt.textContent)}
|
||||
<span style="font-weight:400;color:#6b7280;font-size:11.5px">(${grand} 条)</span>
|
||||
<span class="ops" style="display:inline-flex"><span onclick="event.stopPropagation();dirAddRoot()" title="新增一级目录">+子目录</span></span>
|
||||
</div>
|
||||
<div class="children">${renderNodes(PD.tree,0,0)}
|
||||
<div class="pnode${PD.cur===0?' on':''}" style="${PD.cur===0?'':'color:#9aa4b2'}" onclick="pickDir(0)">
|
||||
<span class="nm">(未分类)</span><span class="cnt">${PD.nUncat}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="treefoot"><div class="tipp">
|
||||
悬停目录出按钮:+子 +平级 ✎ ↑ ↓ ✕(↑↓✕ 均需行内二次确认;↑↓ 子目录整枝跟动)。<br>
|
||||
只有最底层目录(没有子目录)可以挂价格行、新增行。
|
||||
</div></div>`;
|
||||
}
|
||||
function renderNodes(ns,parent,depth){
|
||||
let h='';
|
||||
ns.forEach(n=>{
|
||||
h+=nodeHTML(n);
|
||||
if(PD.adding&&PD.adding.mode==='sib'&&PD.adding.sib===n.id) h+=newNodeHTML(parent);
|
||||
if(n.children&&n.children.length){
|
||||
h+=`<div class="pkids">${renderNodes(n.children,n.id,depth+1)}</div>`;
|
||||
if(PD.adding&&PD.adding.mode==='child'&&PD.adding.parent===n.id) h+=`<div class="pkids">${newNodeHTML(n.id)}</div>`;
|
||||
}
|
||||
});
|
||||
if(PD.adding&&PD.adding.mode==='sib'&&PD.adding.sib===-1&&PD.adding.parent===parent) h+=newNodeHTML(parent);
|
||||
return h;
|
||||
}
|
||||
function nodeHTML(n){
|
||||
const cnt=PD.counts[n.id]||0, cur=PD.cur===n.id;
|
||||
const stop='event.stopPropagation();';
|
||||
let mid;
|
||||
if(PD.ren===n.id){
|
||||
mid=`<input class="ren" id="pren" value="${esc(n.name)}" onclick="${stop}">
|
||||
<span class="ops ops-on"><span class="pk" title="保存改名" onclick="${stop}dirRenSave(${n.id})">✓</span>
|
||||
<span class="pd" title="取消" onclick="${stop}pdClear();renderTree()">✕</span></span>`;
|
||||
} else if(PD.cfm&&PD.cfm.id===n.id){
|
||||
const lbl=PD.cfm.op==='del'?'确认删除?':(PD.cfm.op==='up'?'确认上移?':'确认下移?');
|
||||
mid=`<span class="nm" title="${esc(PDMAP[n.id].path)}">${esc(n.name)}</span><span class="cnt">${cnt}</span>
|
||||
<span class="cfm">${lbl}<span class="pk" onclick="${stop}dirGo(${n.id},'${PD.cfm.op}')">确认</span>
|
||||
<span class="pd" onclick="${stop}pdClear();renderTree()">取消</span></span>`;
|
||||
} else {
|
||||
mid=`<span class="nm" title="${esc(PDMAP[n.id].path)}">${esc(n.name)}</span><span class="cnt">${cnt}</span>
|
||||
<span class="ops">
|
||||
<span title="新增子目录" onclick="${stop}dirAddChild(${n.id})">+子</span>
|
||||
<span title="新增平级目录" onclick="${stop}dirAddSib(${n.id})">+平级</span>
|
||||
<span title="改名" onclick="${stop}dirRen(${n.id})">✎</span>
|
||||
<span title="上移(需确认)" onclick="${stop}dirCfm(${n.id},'up')">↑</span>
|
||||
<span title="下移(需确认)" onclick="${stop}dirCfm(${n.id},'down')">↓</span>
|
||||
<span class="pd" title="删除(需确认)" onclick="${stop}dirCfm(${n.id},'del')">✕</span>
|
||||
</span>`;
|
||||
}
|
||||
return `<div class="pnode${cur?' on':''}" onclick="pickDir(${n.id})">${mid}</div>`;
|
||||
}
|
||||
function newNodeHTML(parent){
|
||||
const stop='event.stopPropagation();';
|
||||
return `<div class="pnode ops-on" onclick="${stop}">
|
||||
<input class="ren" id="pnew" placeholder="目录名称">
|
||||
<span class="ops ops-on"><span class="pk" title="保存" onclick="${stop}dirAddSave(${parent})">✓</span>
|
||||
<span class="pd" title="取消" onclick="${stop}pdClear();renderTree()">✕</span></span></div>`;
|
||||
}
|
||||
/* ---- 目录操作(全部走 POST /dirs;成功后刷新树 + 当前行表)---- */
|
||||
async function dirPost(body){
|
||||
const r=await J(`/api/admin/batch/${DID}/dirs`,{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify(body)});
|
||||
if(!r.ok){ alert(r.msg); return false; }
|
||||
pdClear();
|
||||
const d=await J(`/api/admin/batch/${DID}/dirs`);
|
||||
PD.tree=d.tree||[]; PD.counts=d.counts||{}; PD.nUncat=d.n_uncat||0;
|
||||
if(!dirExists(PD.cur)) PD.cur = PD.tree.length ? PD.tree[0].id : 0;
|
||||
const m=PDMAP[PD.cur];
|
||||
PD.curName=m?m.name:'(未分类)'; PD.curPath=m?m.path:''; PD.curLeaf=PD.cur===0?true:!!m.leaf;
|
||||
await loadPriceRows();
|
||||
return true;
|
||||
}
|
||||
function dirAddRoot(){ PD.ren=0; PD.cfm=null; PD.adding={parent:0,mode:'sib',sib:-1}; renderTree(); const i=$('pnew'); if(i) i.focus(); }
|
||||
function dirAddChild(id){ PD.ren=0; PD.cfm=null; PD.adding={parent:id,mode:'child',sib:0}; renderTree(); const i=$('pnew'); if(i) i.focus(); }
|
||||
function dirAddSib(id){ PD.ren=0; PD.cfm=null; const p=PDMAP[id].parent; PD.adding={parent:p,mode:'sib',sib:id}; renderTree(); const i=$('pnew'); if(i) i.focus(); }
|
||||
function dirRen(id){ PD.adding=null; PD.cfm=null; PD.ren=id; renderTree(); const i=$('pren'); if(i){ i.focus(); i.select(); } }
|
||||
function dirCfm(id,op){ PD.ren=0; PD.adding=null; PD.cfm={id:id,op:op}; renderTree(); }
|
||||
function dirRenSave(id){
|
||||
const i=$('pren'); if(!i||!i.value.trim()){ alert('目录名称不能为空'); return; }
|
||||
dirPost({op:'rename',id:id,name:i.value.trim()});
|
||||
}
|
||||
function dirAddSave(parent){
|
||||
const i=$('pnew'); if(!i||!i.value.trim()){ alert('目录名称不能为空'); return; }
|
||||
dirPost({op:'add',parent:parent,name:i.value.trim()}).then(ok=>{ if(ok) pickDir(PD.cur); });
|
||||
}
|
||||
async function dirGo(id,op){
|
||||
// ↑↓ 在服务端是同一个 op=seq(dir=up/down),rename/add/move/del 同名同参
|
||||
const body = (op==='up'||op==='down') ? {op:'seq', id:id, dir:op} : {op:op, id:id};
|
||||
return dirPost(body);
|
||||
}
|
||||
/* ---- 右侧行表 ---- */
|
||||
function renderRows(){
|
||||
const cg=$('dcg'), th=$('dth'), tb=$('dtbd');
|
||||
cg.innerHTML=COL_PRICE.map(c=>`<col style="width:${c.w}px">`).join('');
|
||||
th.innerHTML='<tr>'+COL_PRICE.map(c=>`<th>${c.t}</th>`).join('')+'</tr>';
|
||||
// 工具行状态:新增行只在最底层目录可用;编辑/新增时显示「所属目录」下拉
|
||||
const b=$('padd');
|
||||
if(PD.curLeaf){ b.classList.remove('dis'); b.disabled=false; b.title=''; }
|
||||
else { b.classList.add('dis'); b.disabled=true; b.title='请选择最底层目录(没有子目录的目录)再新增行'; }
|
||||
const editing=PD.editId||PD.addingRow;
|
||||
$('ptool').classList.toggle('editing', !!editing);
|
||||
if(editing) $('pdirsel').innerHTML=leavesHTML(PD.editId?curEditDir():PD.cur);
|
||||
$('pwhere').textContent = PD.curLeaf ? `当前:${PD.curName}(最底层目录,可挂价格行)`
|
||||
: `当前:${PD.curName}(含子目录,仅查看)`;
|
||||
$('dsecH').style.display='block';
|
||||
$('dsecH').innerHTML = esc(PD.curPath || PD.curName)
|
||||
+ `<span class="crumb">${PD.curLeaf?'':'(含子目录汇总) '}共 ${PD.total} 条</span>`;
|
||||
tb.innerHTML=PD.rows.map(rowHTML).join('')
|
||||
+ (PD.addingRow?newRowHTML():'');
|
||||
if(!PD.rows.length&&!PD.addingRow)
|
||||
tb.innerHTML=`<tr><td colspan="${COL_PRICE.length}" class="tip" style="text-align:center;padding:16px">没有数据</td></tr>`;
|
||||
// 底部统计(.pager 的 #dcnt):批次总条数 + 原件
|
||||
const grand=PD.tree.reduce((s,n)=>s+(PD.counts[n.id]||0),0)+PD.nUncat;
|
||||
dcnt.innerHTML=`价格 ${grand} 条` +
|
||||
(PD.att.has ? ` · 原件:<a href="/api/admin/file/${PD.att.sha256}" data-n="${esc(PD.att.name)}"
|
||||
onclick="return dlFile('${PD.att.sha256}', this.getAttribute('data-n'))"
|
||||
title="另存为(自己选保存位置)">${esc(PD.att.name)}</a>` : ' · 未挂附件');
|
||||
}
|
||||
function curEditDir(){
|
||||
const r=PD.rows.find(x=>x.id===PD.editId);
|
||||
return r?(r.dir_id||0):PD.cur;
|
||||
}
|
||||
function cellOut(v,cls){
|
||||
return `<td class="${cls}">${(v===null||v===undefined||v==='')?'—':esc(v)}</td>`;
|
||||
}
|
||||
function rowHTML(r){
|
||||
if(PD.editId===r.id){
|
||||
const v=['Code','Name','Specification','Unit','NoTaxPrice','TaxRate','TaxPrice','Note'].map(k=>r[k]==null?'':r[k]);
|
||||
return `<tr class="pedit">${['编码(选填)','名称(必填)','规格','单位','不含税价','税率','含税价','备注'].map((ph,i)=>
|
||||
`<td class="pcell"><input id="pe${i}" value="${esc(String(v[i]))}" placeholder="${ph}"></td>`).join('')}
|
||||
<td class="c"><a href="javascript:rowSave()" style="color:#1a7f37">✓ 保存</a>
|
||||
<a href="javascript:rowCancel()" style="color:#c0392b">✕ 取消</a></td></tr>`;
|
||||
}
|
||||
const del = PD.cfmRow===r.id
|
||||
? `<a href="javascript:rowDelGo(${r.id})" style="color:#c0392b">确认删除?</a><a href="javascript:pdClear();renderRows()">取消</a>`
|
||||
: `<a href="javascript:rowEdit(${r.id})">编辑</a><a href="javascript:rowDel(${r.id})" style="color:#c0392b">删除</a>`;
|
||||
return `<tr>${cellOut(r.Code,'c')}${cellOut(r.Name,'l')}${cellOut(r.Specification,'l')}${cellOut(r.Unit,'c')}
|
||||
${cellOut(r.NoTaxPrice,'r')}${cellOut(r.TaxRate,'r')}${cellOut(r.TaxPrice,'r')}${cellOut(r.Note,'l')}
|
||||
<td class="c">${del}</td></tr>`;
|
||||
}
|
||||
function newRowHTML(){
|
||||
const ph=['编码(选填)','名称(必填)','规格','单位','不含税价','税率','含税价','备注'];
|
||||
return `<tr class="pedit">${ph.map((p,i)=>`<td class="pcell"><input id="pe${i}" placeholder="${p}"></td>`).join('')}
|
||||
<td class="c"><a href="javascript:rowSave()" style="color:#1a7f37">✓ 保存</a>
|
||||
<a href="javascript:rowCancel()" style="color:#c0392b">✕ 取消</a></td></tr>`;
|
||||
}
|
||||
function rowNew(){
|
||||
if(!PD.curLeaf){ alert('只有最底层目录才可以挂价格行。请先选择(或新建)最底层目录。'); return; }
|
||||
PD.editId=0; PD.addingRow=true; PD.cfmRow=0; renderRows();
|
||||
const i=$('pe1'); if(i) i.focus();
|
||||
}
|
||||
function rowEdit(id){ PD.editId=id; PD.addingRow=false; PD.cfmRow=0; renderRows(); }
|
||||
function rowCancel(){ PD.editId=0; PD.addingRow=false; renderRows(); }
|
||||
function rowDel(id){ PD.cfmRow=id; PD.editId=0; PD.addingRow=false; renderRows(); }
|
||||
async function rowDelGo(id){
|
||||
const r=await J(`/api/admin/batch/${DID}/prices`,{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({op:'del',id:id})});
|
||||
if(!r.ok){ alert(r.msg); return; }
|
||||
PD.cfmRow=0; await loadPrice();
|
||||
}
|
||||
async function rowSave(){
|
||||
const g=i=>{ const e=$('pe'+i); return e?e.value.trim():''; };
|
||||
const body={ op: PD.editId?'edit':'add',
|
||||
id: PD.editId||undefined,
|
||||
code:g(0),name:g(1),spec:g(2),unit:g(3),
|
||||
notax:g(4),taxrate:g(5),taxprice:g(6),note:g(7),
|
||||
dir_id: parseInt(($('pdirsel')&&$('pdirsel').value)||PD.cur||0,10) };
|
||||
const r=await J(`/api/admin/batch/${DID}/prices`,{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify(body)});
|
||||
if(!r.ok){ alert(r.msg); return; }
|
||||
PD.editId=0; PD.addingRow=false;
|
||||
await loadPrice();
|
||||
}
|
||||
function pdExport(){ saveAs(`/api/admin/batch/${DID}/export`, (dt.textContent||'价格批次')+'.zip'); }
|
||||
|
||||
async function tog(id,cur){
|
||||
await J(`/api/admin/batch/${id}/enabled`,{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
@@ -812,31 +1066,11 @@ function almeRender(){
|
||||
document.getElementById('dtbd').innerHTML=renderLme(view, WB_OPTS)
|
||||
||`<tr><td colspan="${COLS.lme.length}" class="tip" style="text-align:center;padding:16px">没有数据</td></tr>`;
|
||||
}
|
||||
// 价格明细:**与上传的 HTML 一模一样**——按分类分组(分类标题=目录),列为 HTML 那 8 列
|
||||
const COL_PRICE=[
|
||||
{t:'材料编码',a:'c',w:110,k:0},
|
||||
{t:'材料名称',a:'l',w:210,k:1},
|
||||
{t:'规格型号',a:'l',w:200,k:2},
|
||||
{t:'单位',a:'c',w:64,k:3},
|
||||
{t:'不含税单价',a:'r',w:106,num:1,k:4},
|
||||
{t:'税率',a:'r',w:76,num:1,k:5},
|
||||
{t:'含税单价',a:'r',w:106,num:1,k:6},
|
||||
{t:'备注',a:'l',w:230,k:8} // k = 接口返回行里的下标(0..6 前七列,8=备注;7=目录,用作分组标题)
|
||||
];
|
||||
// 定额(挂在清单下):定额编码 / 定额名称 / 单位 / 单价
|
||||
// 定额(挂在清单下):定额编码 / 定额名称 / 单位 / 单价(COL_PRICE 已上移进价格明细模块,2026-10-12)
|
||||
const COL_NORM=[{t:'定额编码',a:'c',w:130},{t:'定额名称',a:'l',w:300},
|
||||
{t:'单位',a:'c',w:64},{t:'单价',a:'r',w:110,num:1}];
|
||||
|
||||
// headHTML / colgHTML 由 common.js 提供(数组式与对象式列定义都支持)
|
||||
// cellHTML 仅价格明细(对象式 k 下标映射)用到,保留在本页
|
||||
function cellHTML(c,v){
|
||||
if(c.a==='tg') return '<td class="tg"></td>';
|
||||
if(c.dash) return '<td class="'+(c.a||'l')+'">—</td>';
|
||||
if(c.a==='attr') return `<td class="attr">${esc(fmtAttr(v))}</td>`;
|
||||
if(c.num) return `<td class="r">${num(v)}</td>`;
|
||||
if(c.a==='c') return `<td class="c">${esc(v)}</td>`;
|
||||
return `<td class="l">${esc(v)}</td>`;
|
||||
}
|
||||
|
||||
// 4 个标签:与工作台同一份(common.js TABS),默认停在「原数据」
|
||||
document.addEventListener('DOMContentLoaded', function(){ $('dtabs').innerHTML = tabsHTML(); });
|
||||
@@ -867,7 +1101,6 @@ async function det(id,name){
|
||||
dbody.classList.toggle('fx', isPrice);
|
||||
dside.style.display = isPrice?'block':'none';
|
||||
document.getElementById('dsecH').style.display = isPrice?'block':'none';
|
||||
CURSEC = isPrice ? 0 : -1;
|
||||
// 注:后台类似清单已固定走「系统默认(按名称聚类)」分组,不再读专业 / 不再显示专业下拉
|
||||
// (2026-10-01 主人定:后台是历史检索口,统一自动聚类比让操作者选专业更稳)
|
||||
mask.classList.add('on');
|
||||
@@ -901,22 +1134,12 @@ async function loadTab(pid){
|
||||
document.querySelectorAll('#mask .tab').forEach(x=>x.classList.toggle('on',x.dataset.p===pid));
|
||||
const cg=document.getElementById('dcg'), th=document.getElementById('dth'), tb=document.getElementById('dtbd');
|
||||
if(KIND!=='project'){
|
||||
// 面板复位(兜底,见 det() 里的注释):价格明细只有左目录 + 右一张表,
|
||||
// 面板复位(兜底,见 det() 里的注释):价格明细只有左目录树 + 右一张表,
|
||||
// 「原数据」的写树 / 四个标签卡必须关掉,否则会和价格表抢同一个 dright 的高度。
|
||||
$('drawbox').style.display='none';
|
||||
$('dtb').style.display='';
|
||||
const [d,a]=await Promise.all([J(`/api/admin/batch/${DID}/prices?page=1&page_size=5000`),
|
||||
J(`/api/admin/batch/${DID}/attach`)]);
|
||||
document.getElementById('n0').textContent=d.total+' 条';
|
||||
// 按「目录(=分类标题)」分组,保持入库顺序
|
||||
const order=[], g={};
|
||||
d.rows.forEach(r=>{
|
||||
const blk=(r[9]||'').trim(), cls=(r[7]||'').trim(), key=blk+'||'+cls;
|
||||
if(!(key in g)){ g[key]=[]; order.push({block:blk, cls:cls, key:key}); }
|
||||
g[key].push(r);
|
||||
});
|
||||
PORDER=order; PGROUP=g; PATT=a; PTITLE=dt.textContent;
|
||||
renderPrice();
|
||||
PD.editId=0; PD.addingRow=false; pdClear(); // PD.cur 不复位:换批次由 loadPrice 自愈落首个一级目录
|
||||
await loadPrice(); // 2026-10-12 重做:多级目录树 + 行内编辑(见 loadPrice/renderTree/renderRows)
|
||||
return;
|
||||
}
|
||||
// ---- 原数据(p3):与工作台同一套结构 + 同一份 RawView 渲染,只换接口 ----
|
||||
@@ -984,19 +1207,17 @@ async function openImp(){
|
||||
document.getElementById('irowNote').style.display = isPrice?'flex':'none';
|
||||
document.getElementById('irowPub').style.display = isPrice?'flex':'none';
|
||||
document.getElementById('irowPdf').style.display = isPrice?'flex':'none';
|
||||
ipdf.value=
|
||||
ipdf.value='';
|
||||
// 每次只能导入一个文件:从你自己电脑的任意位置选,选完会传进软件目录
|
||||
ifile.value=''; UPF=null;
|
||||
iname.value=''; iname.dataset.auto=''; // 每次重新带出文件名
|
||||
// 价格类三种都收:HTML 原件 + Excel(.xlsx 新格式 / .xls 老格式)
|
||||
// 工程类只认计价文件 **.cos4 / .cos**(主人 2026-10-06):原来的 .xml 一并去掉,
|
||||
// 因为服务端 EXT_OK 里也没有 .xml,收进来同样是"打不开",等于给用户一个假选项。
|
||||
ifile.accept = isPrice ? '.html,.htm,.xlsx,.xls' : '.cos4,.cos';
|
||||
// 2026-10-12 重设计(主人定):价格类**只收标准模板 .xlsx**(HTML 导入退役);
|
||||
// 工程类只认计价文件 **.cos4 / .cos**(主人 2026-10-06)。
|
||||
ifile.accept = isPrice ? '.xlsx' : '.cos4,.cos';
|
||||
document.getElementById('ifileInfo').textContent='';
|
||||
document.getElementById('irowTip').textContent = isPrice
|
||||
? '信息价/市场价:HTML 原件 或 Excel(.xlsx / .xls,每次一个)+ 附件(任意格式,选填)。'
|
||||
+ '名称 / 地区 必填;期次留空时会自动从块名或文件名里认(如「珠海信息价_2026年7月」→ 2026-07)。'
|
||||
+ '一个文件含多个市场(多个 sheet / 多个块)时会拆成多个批次,各带各的期次。'
|
||||
? '信息价/市场价:只收「标准模板」Excel(.xlsx,每次一个)+ 附件原件(任意格式,选填)。'
|
||||
+ '名称留空或点文件后自动带出文件名(可改);期次留空时自动从文件名里认(如「珠海信息价_2026年7月」→ 2026-07)。'
|
||||
: '工程:选择一个 .cos4 或 .cos 文件(可从电脑任意位置选,每次只能一个)。全部必填。';
|
||||
imsg.textContent='';
|
||||
await loadImpFilters();
|
||||
@@ -1009,14 +1230,12 @@ async function pickFile(inp){
|
||||
const r = await uploadFile('/api/admin/upload', f);
|
||||
if(!r.ok){ info.textContent='× '+r.msg; UPF=null; return; }
|
||||
UPF=r;
|
||||
// 价格类三种都收:HTML 原件 + Excel(.xlsx 新格式 / .xls 老格式)
|
||||
// ⚠️ 之前这里只认 price_html,Excel 选完直接被判「不是信息价 HTML」——导入功能等于没有。
|
||||
const ok = (KIND!=='project')
|
||||
? (r.state==='price_html' || r.state==='price_xlsx')
|
||||
: (r.state==='zip'||r.state==='xml');
|
||||
// 2026-10-12 重设计:价格类只认标准模板 Excel;工程类只认 .cos4/.cos
|
||||
const ok = (KIND!=='project') ? (r.state==='price_xlsx')
|
||||
: (r.state==='zip'||r.state==='xml');
|
||||
info.textContent = ok
|
||||
? `已选:${r.name}(${(r.size/1048576).toFixed(2)} MB)· 已存进软件目录`
|
||||
: `已选:${r.name},但这不是${KIND!=='project'?'信息价/市场价文件(HTML 或 Excel)':'计价工程文件'},无法导入`;
|
||||
: `已选:${r.name},但这不是${KIND!=='project'?'标准模板 Excel(请点「标准模板」按钮下载后填写)':'计价工程文件'},无法导入`;
|
||||
// 名称默认 = 文件名(去掉扩展名),与工作台「打开工程」一致;手动改过就不再覆盖
|
||||
const stem = f.name.replace(/\.[^.]+$/,'');
|
||||
if(!iname.value.trim() || iname.dataset.auto==='1') iname.value = stem;
|
||||
@@ -1055,7 +1274,7 @@ function kindOptions(kinds, cur){
|
||||
async function doImport(){
|
||||
const isPrice = (KIND!=='project');
|
||||
const miss=[];
|
||||
if(!UPF) miss.push(isPrice?'HTML 文件(每次只能一个)':'文件(每次只能一个)');
|
||||
if(!UPF) miss.push(isPrice?'标准模板 Excel 文件(每次只能一个)':'文件(每次只能一个)');
|
||||
if(!iname.value.trim()) miss.push('名称');
|
||||
if(!iprov.value||!icity.value||!idist.value) miss.push('地区(省/市/区)');
|
||||
const pv=PVAL($('iper'));
|
||||
|
||||
@@ -39,7 +39,8 @@ a:hover{text-decoration:underline}
|
||||
<div class="wrap">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:6px">
|
||||
<h1 style="margin:0">造价审核 · 最近审核</h1>
|
||||
<a class="btn pri" style="text-decoration:none;flex:none" href="/workbench.html"
|
||||
<!-- 时间戳参数:老 WebView2 对 no-store 不完全遵守,跨页跳转带新 URL 强制绕缓存(2026-10-12) -->
|
||||
<a class="btn pri" style="text-decoration:none;flex:none" href="javascript:location.href='/workbench.html?v='+Date.now()"
|
||||
title="打开工作台:导入工程、做历史比对与审核">▶ 工作台</a>
|
||||
</div>
|
||||
<div class="panel">
|
||||
@@ -144,7 +145,7 @@ function delSel(){
|
||||
del(ITEMS.filter(x=>rep.includes(x.id)).flatMap(x=>(x.all||[]).map(a=>a.id)));
|
||||
}
|
||||
|
||||
function go(id){ location.href='/workbench.html?sid='+id; }
|
||||
function go(id){ location.href='/workbench.html?sid='+id+'&t='+Date.now(); }
|
||||
/* 2026-09-30 主人定:落地页每行**只留「打开」+「删除」**,去掉「重新解析」按钮。
|
||||
它只在解析器更新后才需要,不该占日常位置。
|
||||
⚠️ 去掉之后的替代路径:**删掉这个会话 → 重新打开工程**(走一遍全新解析,数据就是新的),
|
||||
|
||||
@@ -261,7 +261,8 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
|
||||
<!-- 2026-10-10 主人定:右上按钮一字排开,从左到右 =
|
||||
分组/匹配 → 后台管理 → 询价附件 → 最近审核 → 打开项目。 -->
|
||||
<button class="btn" onclick="cfgOpen()" title="类似清单分组 / 历史匹配过滤词">⚙ 分组&过滤</button>
|
||||
<a class="btn" href="/admin.html" data-page-node-id="soJGFd2PWIpS6Hbp6B2s0w">后台管理</a>
|
||||
<!-- 时间戳参数:老 WebView2 对 no-store 不完全遵守,跨页跳转带新 URL 强制绕缓存(2026-10-12) -->
|
||||
<a class="btn" href="javascript:location.href='/admin.html?v='+Date.now()" data-page-node-id="soJGFd2PWIpS6Hbp6B2s0w">后台管理</a>
|
||||
<!-- 询价附件(2026-10-09 改版;2026-10-10 决策 28 改会话级 主人定):**常驻按钮**。
|
||||
数据 = 当前会话在对比框点「采纳」收进来的附件(按内容去重;切会话跟着切,删会话才清,
|
||||
没打开项目=空),不再是后台绑定关系的只读展示。 -->
|
||||
|
||||
Reference in New Issue
Block a user