From a2a1d81440d5990f69e9294c6c336e5cd6cfba79 Mon Sep 17 00:00:00 2001 From: lianjianwei2024 <168657369+lianjianwei2024@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:34:57 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=86=B3=E7=AD=96=20237/238/239?= =?UTF-8?q?=E2=80=94=E2=80=94=E9=99=84=E4=BB=B6=E9=A1=B5=E7=BB=91=E5=AE=9A?= =?UTF-8?q?/=E4=B8=8A=E4=BC=A0/=E7=AD=9B=E9=80=89=E9=98=B2=E9=97=AA?= =?UTF-8?q?=E8=B7=B3=E5=B0=B1=E5=9C=B0=E6=9B=B4=E6=96=B0+=E5=AE=9A?= =?UTF-8?q?=E9=A2=9D=E5=AD=90=E8=A1=8C=E5=AF=B9=E9=BD=90+=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E9=BB=98=E8=AE=A4300px=EF=BC=9B=E7=BB=84=E6=A0=91?= =?UTF-8?q?=E7=82=B9=E9=80=89=E5=B0=B1=E5=9C=B0=E5=8C=96=E9=93=BA=E5=9B=9B?= =?UTF-8?q?=E5=A4=84+=E5=8F=96=E6=95=B0=E7=AD=89=E5=BE=85=E5=8D=A0?= =?UTF-8?q?=E4=BD=8D=EF=BC=9B=E6=95=B4=E9=A1=B9=E7=9B=AE=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E4=B8=8E=E4=B8=80=E6=8A=8A=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=BB=BA=E6=89=8B=E5=B7=A5=E5=B7=A5=E7=A8=8B=EF=BC=9BMCP=20?= =?UTF-8?q?=E4=B9=9D=E5=B7=A5=E5=85=B7=EF=BC=88project=5Fimport/bill=5Fado?= =?UTF-8?q?pt/match=5Fhist/lme=5Fadopt=EF=BC=8Cref=20=E7=A5=A8=E6=8D=AE?= =?UTF-8?q?=E9=98=B2=E8=BD=AC=E5=BD=95=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CostReview/app/core/manual_import.py | 403 +++++++++++++++++++++------ CostReview/app/server/api_server.py | 53 +++- CostReview/app/server/mcp_server.py | 313 ++++++++++++++++++++- CostReview/app/ui/admin.html | 198 +++++++++++-- CostReview/app/ui/common.css | 1 + CostReview/app/ui/common.js | 70 +++-- CostReview/app/ui/workbench.html | 27 ++ 7 files changed, 934 insertions(+), 131 deletions(-) diff --git a/CostReview/app/core/manual_import.py b/CostReview/app/core/manual_import.py index 4eba1de..500e070 100644 --- a/CostReview/app/core/manual_import.py +++ b/CostReview/app/core/manual_import.py @@ -48,6 +48,7 @@ ROOT_MARK = "单位工程" # 一级分部的「上一级名称」固定写法 FB_SHEET = "分部分项" CS_SHEET = "措施项目" +DIR_SHEET = "项目目录" # 决策 238:整项目模板——目录 Sheet 序号 ↔ Sheet 对(分部分项N/措施项目N) # --------------------------------------------------------------------------- @@ -210,6 +211,95 @@ def _num(v, r, col, errors): return None +def _parse_pair(wb, fb_name, cs_name, tag, errors): + """一对 Sheet(分部分项+措施项目)→ {divides,bills,prelim};错误带 tag 前缀报行号。 + 决策 238:从 parse_workbook 抽出——单单位工程(旧)与整项目多对 Sheet(新)共用一份解析。""" + divides, bills, prelim = [], [], [] + + # ---- Sheet 分部分项 ---- + if fb_name not in wb.sheetnames: + errors.append("%s缺少「%s」Sheet" % (tag, fb_name)) + else: + rows = list(wb[fb_name].iter_rows(values_only=True)) + head = {_cell(v): i for i, v in enumerate(rows[0]) if _cell(v)} if rows else {} + for k in ("上一级名称", "类型", "名称", "单位", "工程量", "单价"): + if k not in head: + errors.append("「%s」缺列:%s" % (fb_name, k)) + if not errors: + def col(key): + return head.get(key) + for ri, row in enumerate(rows[1:], 2): + if row is None or not any(_cell(v) for v in row): + continue + get = lambda key: row[col(key)] if col(key) is not None and col(key) < len(row) else None + parent = _cell(get("上一级名称")) + typ = _cell(get("类型")) + name = _cell(get("名称")) or "" + # 补记十四(2026-10-28 主人定边界放开):分部/清单**空名称放行** + #(原文件存在空名分部/空名清单);层级**不设限**;同上级**同名分部放行** + if typ == "分部": + if parent == ROOT_MARK: + level, pidx = 1, -1 + else: + hit = next((i for i in range(len(divides) - 1, -1, -1) + if divides[i]["name"] == parent), None) + if hit is None: + errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)")) + continue + level, pidx = divides[hit]["level"] + 1, hit + divides.append({"name": name, "pidx": pidx, "level": level}) + elif typ == "清单": + if parent == ROOT_MARK: + didx = None + else: + didx = next((i for i in range(len(divides) - 1, -1, -1) + if divides[i]["name"] == parent), None) + if didx is None: + errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)")) + continue + qty = _num(get("工程量"), ri, "工程量", errors) + price = _num(get("单价"), ri, "单价", errors) + unit = _cell(get("单位")) + if not unit: + errors.append("第 %d 行:单位必填" % ri) + if qty is None or price is None or not unit: + continue + bills.append({"didx": didx, "num": _cell(get("编码")), "name": name, + "attr": split_attr(get("项目特征")), "unit": unit, + "qty": qty, "price": price, + "total": round(qty * price, 2)}) + else: + errors.append("第 %d 行:类型应填 分部 或 清单(实际「%s」)" % (ri, typ or "(空)")) + + # ---- Sheet 措施项目(可缺省=没有措施数据)---- + if cs_name in wb.sheetnames: + rows = list(wb[cs_name].iter_rows(values_only=True)) + head = {_cell(v): i for i, v in enumerate(rows[0]) if _cell(v)} if rows else {} + if "名称" not in head or "单位" not in head: + errors.append("「%s」缺列:名称 / 单位" % cs_name) + else: + for ri, row in enumerate(rows[1:], 2): + if row is None or not any(_cell(v) for v in row): + continue + name = _cell(row[head["名称"]]) if head["名称"] < len(row) else "" + # 措施空名同样放行(补记十四) + qty = _num(row[head["工程量"]] if "工程量" in head and head["工程量"] < len(row) else None, + ri, "工程量", errors) + price = _num(row[head["单价"]] if "单价" in head and head["单价"] < len(row) else None, + ri, "单价", errors) + unit = _cell(row[head["单位"]]) if head["单位"] < len(row) else "" + if not unit: + errors.append("措施 第 %d 行:单位必填" % ri) + if qty is None or price is None or not unit: + continue + prelim.append({"num": _cell(row[head["编码"]]) if "编码" in head and head["编码"] < len(row) else "", + "name": name, + "attr": split_attr(row[head["项目特征"]] if "项目特征" in head and head["项目特征"] < len(row) else None), + "unit": unit, "qty": qty, "price": price, + "total": round(qty * price, 2)}) + return {"divides": divides, "bills": bills, "prelim": prelim} + + def parse_workbook(path): """单位工程导入 xlsx → 结构化结果;任何校验不过整份拒绝(errors 带行号)。""" if load_workbook is None: @@ -217,96 +307,241 @@ def parse_workbook(path): wb = load_workbook(path, data_only=True, read_only=True) try: errors = [] - divides, bills, prelim = [], [], [] - - # ---- Sheet 分部分项 ---- - if FB_SHEET not in wb.sheetnames: - errors.append("缺少「%s」Sheet" % FB_SHEET) - else: - rows = list(wb[FB_SHEET].iter_rows(values_only=True)) - head = {_cell(v): i for i, v in enumerate(rows[0]) if _cell(v)} if rows else {} - for k in ("上一级名称", "类型", "名称", "单位", "工程量", "单价"): - if k not in head: - errors.append("「%s」缺列:%s" % (FB_SHEET, k)) - if not errors: - def col(key): - return head.get(key) - for ri, row in enumerate(rows[1:], 2): - if row is None or not any(_cell(v) for v in row): - continue - get = lambda key: row[col(key)] if col(key) is not None and col(key) < len(row) else None - parent = _cell(get("上一级名称")) - typ = _cell(get("类型")) - name = _cell(get("名称")) or "" - # 补记十四(2026-10-28 主人定边界放开):分部/清单**空名称放行** - #(原文件存在空名分部/空名清单);层级**不设限**;同上级**同名分部放行** - if typ == "分部": - if parent == ROOT_MARK: - level, pidx = 1, -1 - else: - hit = next((i for i in range(len(divides) - 1, -1, -1) - if divides[i]["name"] == parent), None) - if hit is None: - errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)")) - continue - level, pidx = divides[hit]["level"] + 1, hit - divides.append({"name": name, "pidx": pidx, "level": level}) - elif typ == "清单": - if parent == ROOT_MARK: - didx = None - else: - didx = next((i for i in range(len(divides) - 1, -1, -1) - if divides[i]["name"] == parent), None) - if didx is None: - errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)")) - continue - qty = _num(get("工程量"), ri, "工程量", errors) - price = _num(get("单价"), ri, "单价", errors) - unit = _cell(get("单位")) - if not unit: - errors.append("第 %d 行:单位必填" % ri) - if qty is None or price is None or not unit: - continue - bills.append({"didx": didx, "num": _cell(get("编码")), "name": name, - "attr": split_attr(get("项目特征")), "unit": unit, - "qty": qty, "price": price, - "total": round(qty * price, 2)}) - else: - errors.append("第 %d 行:类型应填 分部 或 清单(实际「%s」)" % (ri, typ or "(空)")) - - # ---- Sheet 措施项目(可缺省=没有措施数据)---- - if CS_SHEET in wb.sheetnames: - rows = list(wb[CS_SHEET].iter_rows(values_only=True)) - head = {_cell(v): i for i, v in enumerate(rows[0]) if _cell(v)} if rows else {} - if "名称" not in head or "单位" not in head: - errors.append("「%s」缺列:名称 / 单位" % CS_SHEET) - else: - for ri, row in enumerate(rows[1:], 2): - if row is None or not any(_cell(v) for v in row): - continue - name = _cell(row[head["名称"]]) if head["名称"] < len(row) else "" - # 措施空名同样放行(补记十四) - qty = _num(row[head["工程量"]] if "工程量" in head and head["工程量"] < len(row) else None, - ri, "工程量", errors) - price = _num(row[head["单价"]] if "单价" in head and head["单价"] < len(row) else None, - ri, "单价", errors) - unit = _cell(row[head["单位"]]) if head["单位"] < len(row) else "" - if not unit: - errors.append("措施 第 %d 行:单位必填" % ri) - if qty is None or price is None or not unit: - continue - prelim.append({"num": _cell(row[head["编码"]]) if "编码" in head and head["编码"] < len(row) else "", - "name": name, - "attr": split_attr(row[head["项目特征"]] if "项目特征" in head and head["项目特征"] < len(row) else None), - "unit": unit, "qty": qty, "price": price, - "total": round(qty * price, 2)}) + pair = _parse_pair(wb, FB_SHEET, CS_SHEET, "", errors) if errors: return {"ok": False, "errors": errors[:30]} - return {"ok": True, "divides": divides, "bills": bills, "prelim": prelim} + return {"ok": True, **pair} finally: wb.close() +def _fb_cs_names(seq): + """目录序号 → (分部分项 Sheet 名, 措施项目 Sheet 名)。 + 序号 1 兼容旧文件的无序号名(「分部分项」)与带序号名(「分部分项1」)都认。""" + fb = FB_SHEET if seq == 1 else "%s%d" % (FB_SHEET, seq) + cs = CS_SHEET if seq == 1 else "%s%d" % (CS_SHEET, seq) + alt = (f"%s%d" % (FB_SHEET, seq), f"%s%d" % (CS_SHEET, seq)) if seq == 1 else None + return fb, cs, alt + + +def parse_project_workbook(path): + """决策 238:整项目导入 xlsx → 各单位工程结构化结果。 + 「项目目录」Sheet:列=序号 / 单项工程 / 单位工程(序号 1..N 以单位工程排序, + Sheet 对按序号对应:1=分部分项[1]/措施项目[1],2=分部分项2/措施项目2 …)。 + 无「项目目录」Sheet = 旧单单位工程文件(single=True,走 parse_workbook 口径)。""" + if load_workbook is None: + return {"ok": False, "errors": ["缺少 openpyxl,无法解析"]} + wb = load_workbook(path, data_only=True, read_only=True) + try: + if DIR_SHEET not in wb.sheetnames: + base = parse_workbook(path) + base["single"] = True + return base + errors = [] + rows = list(wb[DIR_SHEET].iter_rows(values_only=True)) + head = {_cell(v): i for i, v in enumerate(rows[0]) if _cell(v)} if rows else {} + for k in ("序号", "单项工程", "单位工程"): + if k not in head: + return {"ok": False, "errors": ["「%s」缺列:%s" % (DIR_SHEET, k)]} + units = [] + seen_seq = set() + for ri, row in enumerate(rows[1:], 2): + if row is None or not any(_cell(v) for v in row): + continue + def _g(key): + c = head.get(key) + return row[c] if c is not None and c < len(row) else None + try: + seq = int(float(_cell(_g("序号")))) + except ValueError: + errors.append("「%s」第 %d 行:序号必填(数字)" % (DIR_SHEET, ri)) + continue + sec = _cell(_g("单项工程")) + uw = _cell(_g("单位工程")) + if not sec: + errors.append("「%s」第 %d 行:单项工程必填" % (DIR_SHEET, ri)) + continue + if not uw: + errors.append("「%s」第 %d 行:单位工程必填" % (DIR_SHEET, ri)) + continue + if seq in seen_seq: + errors.append("「%s」第 %d 行:序号 %d 重复" % (DIR_SHEET, ri, seq)) + continue + seen_seq.add(seq) + units.append({"seq": seq, "section": sec, "uw": uw, "row": ri}) + if not units: + errors.append("「%s」没有有效目录行" % DIR_SHEET) + if errors: + return {"ok": False, "errors": errors[:30]} + for u in units: + fb, cs, alt = _fb_cs_names(u["seq"]) + if fb not in wb.sheetnames and alt and alt[0] in wb.sheetnames: + fb = alt[0] # 序号 1:旧式无序号名也认 + if cs not in wb.sheetnames and alt and alt[1] in wb.sheetnames: + cs = alt[1] + tag = "目录序号 %d(%s)" % (u["seq"], u["uw"]) + if fb not in wb.sheetnames and cs not in wb.sheetnames: + errors.append("%s:缺数据 Sheet(应有「%s」「%s」)" % (tag, + FB_SHEET if u["seq"] == 1 else FB_SHEET + str(u["seq"]), + CS_SHEET if u["seq"] == 1 else CS_SHEET + str(u["seq"]))) + continue + u["data"] = _parse_pair(wb, fb if fb in wb.sheetnames else "__none__", + cs if cs in wb.sheetnames else "__none__", tag + " ", errors) + if errors: + return {"ok": False, "errors": errors[:30]} + units.sort(key=lambda x: x["seq"]) + return {"ok": True, "single": False, "units": units} + finally: + wb.close() + + +def template_project_bytes(): + """决策 238:整项目导入模板。每对 Sheet(分部分项N + 措施项目N)=「项目目录」里 + 序号 N 的单位工程;旧单单位工程模板(template_bytes)保留不动,两模板并存。""" + if Workbook is None: + raise ImportError("缺少 openpyxl") + wb = Workbook() + + def _head(ws, headers): + for c, h in enumerate(headers, 1): + cell = ws.cell(row=1, column=c, value=h) + cell.font = Font(bold=True) + cell.fill = PatternFill("solid", fgColor="DCE6F1") + cell.alignment = Alignment(horizontal="center", vertical="center") + ws.freeze_panes = "A2" + + ws0 = wb.active + ws0.title = "填写说明" + ws0.column_dimensions["A"].width = 100 + for i, (t, b) in enumerate([ + ("整项目导入模板 · 填写说明", True), + ("", False), + ("一、项目目录(第一个数据 Sheet)", True), + (" 三列:序号 / 单项工程 / 单位工程。每行=一个单位工程,序号 1、2、3… 以单位工程排序。", False), + (" 序号 N 对应一对数据 Sheet:「分部分项N」+「措施项目N」(序号 1 的对写「分部分项」「措施项目」也可以)。", False), + (" 要加单位工程=在项目目录加一行,再复制一对数据 Sheet 改名成对应序号。", False), + ("", False), + ("二、每对数据 Sheet 的填法(与单位工程导入模板完全同款)", True), + (" 分部分项:分部行/清单行都填「上一级名称」;一级分部填「单位工程」;类型只填 分部 或 清单。", False), + (" 单位工程下最多 5 层(4 级分部+清单);项目特征支持 Alt+Enter 换行或行内编号 1. 2. 3.。", False), + (" 措施项目:平铺(名称/编码/项目特征/单位/工程量/单价),全部直接挂单位工程下。", False), + ("", False), + ("三、其他", True), + (" 1. 只填到清单级:不导定额、不导工料机;合价=工程量×单价由软件现算。", False), + (" 2. 必填:目录三列;数据行 类型、名称;清单行 单位、工程量(数字)、单价(数字)。", False), + (" 3. 导入即创建整项目(目录树+清单一次到位);同名手工工程再次导入=整项目覆盖。", False), + (" 4. 单位工程旧模板(只有 分部分项/措施项目 两个 Sheet、无项目目录)仍可在目录树行内导入,不受影响。", False), + ], 1): + c = ws0.cell(row=i, column=1, value=t) + if b: + c.font = Font(bold=True) + c.alignment = Alignment(vertical="top") + + # ---- 项目目录 ---- + hd = ["序号", "单项工程", "单位工程"] + wsd = wb.create_sheet(DIR_SHEET) + wsd.append(hd) + for r in [[1, "1#单项工程", "1#楼"], [2, "1#单项工程", "2#楼"]]: + wsd.append(r) + for i, w in enumerate([8, 20, 24], 1): + wsd.column_dimensions[get_column_letter(i)].width = w + _head(wsd, hd) + + # ---- 第 1 对:分部分项 / 措施项目(示例数据与旧模板同款) ---- + ws1 = wb.create_sheet(FB_SHEET) + h1 = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"] + ws1.append(h1) + for r in [ + ["单位工程", "", "分部", "楼地面装饰工程", "", "", "", ""], + ["楼地面装饰工程", "", "分部", "块料面层", "", "", "", ""], + ["块料面层", "011102001", "清单", "石材楼地面", + "1.结合层:30厚1:3干硬性水泥砂浆\n2.面层:800×800米黄石材\n3.酸洗打蜡、成品保护", "m²", 126.5, 385], + ["块料面层", "011102003", "清单", "块料楼地面", "600×600防滑砖、白水泥擦缝", "m²", 342.8, 128.5], + ]: + ws1.append(r) + for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1): + ws1.column_dimensions[get_column_letter(i)].width = w + _head(ws1, h1) + for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5): + for cell in row: + cell.alignment = Alignment(wrap_text=True, vertical="top") + + ws2 = wb.create_sheet(CS_SHEET) + h2 = ["名称", "编码", "项目特征", "单位", "工程量", "单价"] + ws2.append(h2) + ws2.append(["安全文明施工费", "", "", "项", 1, 120000]) + ws2.append(["临时设施", "", "现场办公室、仓库、加工棚搭设", "项", 1, 60000]) + for i, w in enumerate([20, 11, 36, 7, 9, 10], 1): + ws2.column_dimensions[get_column_letter(i)].width = w + _head(ws2, h2) + + # ---- 第 2 对:分部分项2 / 措施项目2(小示例,示范多单位工程) ---- + ws3 = wb.create_sheet(FB_SHEET + "2") + ws3.append(h1) + ws3.append(["单位工程", "", "分部", "给排水管道", "", "", "", ""]) + ws3.append(["给排水管道", "031001001", "清单", "镀锌钢管", "DN65、螺纹连接", "m", 120, 58.5]) + for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1): + ws3.column_dimensions[get_column_letter(i)].width = w + _head(ws3, h1) + + ws4 = wb.create_sheet(CS_SHEET + "2") + ws4.append(h2) + ws4.append(["二次搬运费", "", "", "项", 1, 5000]) + for i, w in enumerate([20, 11, 36, 7, 9, 10], 1): + ws4.column_dimensions[get_column_letter(i)].width = w + _head(ws4, h2) + + import io + bio = io.BytesIO() + wb.save(bio) + return bio.getvalue() + + +def import_project(con, body): + """决策 238:整项目一把导入——「项目目录」+多对 Sheet → 建手工工程(目录树+清单)。 + body = {path, name, period_from, period_to, province?/city?/district?/bulid_unit?} + 同名手工工程再次导入=整项目覆盖(save_tree 同名续用 + 无 id 全删重建);返回 sid + 各单位工程条数。""" + p = (body.get("path") or "").strip() + if not p: + return {"ok": False, "msg": "缺少导入文件路径"} + parsed = parse_project_workbook(p) + if not parsed.get("ok"): + return {"ok": False, "msg": ";".join(parsed["errors"][:5])} + if parsed.get("single"): + return {"ok": False, "msg": "这是单位工程模板(无「项目目录」Sheet)——请在目录树行内按单位工程导入,或改用整项目模板"} + # 组装目录树(保存对象引用:save_tree 会给每个单位工程回填 id,按展开顺序对位目录序号) + tree = [] + by_sec = {} + for u in parsed["units"]: + sec = by_sec.get(u["section"]) + if sec is None: + sec = {"name": u["section"], "units": []} + by_sec[u["section"]] = sec + tree.append(sec) + u["_ref"] = {"name": u["uw"]} + sec["units"].append(u["_ref"]) + r = save_tree(con, { + "name": body.get("name"), "period_from": body.get("period_from"), + "period_to": body.get("period_to"), "province": body.get("province"), + "city": body.get("city"), "district": body.get("district"), + "bulid_unit": body.get("bulid_unit"), "tree": tree, + }) + if not r.get("ok"): + return r + sid = r.get("sid") or r.get("session_id") or body.get("sid") + cur = con.cursor() + counts = [] + for u in parsed["units"]: + uwid = u["_ref"].get("id") + if not uwid: + counts.append({"uw": u["uw"], "err": "目录树创建异常"}) + continue + counts.append({"uw": u["uw"], "seq": u["seq"], **_import_unit(cur, sid, uwid, u["data"])}) + con.commit() + return {"ok": True, "sid": sid, "units": counts, + "msg": "已导入 %d 个单位工程:%s" % (len(counts), "、".join("%s(%d条)" % (c["uw"], c.get("n_item", 0)) for c in counts))} + + # --------------------------------------------------------------------------- # 会话结构:查现状 / 保存(建+改+导) # --------------------------------------------------------------------------- diff --git a/CostReview/app/server/api_server.py b/CostReview/app/server/api_server.py index 86b16e1..baa65dc 100644 --- a/CostReview/app/server/api_server.py +++ b/CostReview/app/server/api_server.py @@ -2369,20 +2369,38 @@ def _raw_uw(con, T, uwid, tab): nextra = ", x_tdel, x_adopt" if T.get("normstate") else ", 0 AS x_tdel, 0 AS x_adopt" nextra += ", qty_expr" if T.get("normstate") else ", NULL AS qty_expr" # 决策 90:工程量公式原文(尾位) _bq = {b["id"]: b["Quantity"] for b in bills} # 决策 96:公式按所属清单工程量求值 + _nsum, _nhas = {}, {} # 决策 232:bill_id → ∑定额合价 / 有无未临删定额 for n in con.execute("""SELECT id, bill_id, Number, Name, Unit, Quantity, Price, Total%s FROM %s WHERE bill_id IN (%s) ORDER BY id""" % (nextra, T["norms"], ph), ids): # 第 0 位 = 定额 id:前端点定额行要拿它去取工料机(2026-10-01 加) _eval = None if n["qty_expr"]: _eval, _msg = _formula_qty(n["qty_expr"], _bq.get(n["bill_id"]), n["Unit"]) # 决策 216 + # 决策 232(2026-10-28 主人定):定额合价=显示工程量×单价(四舍五入 2 位)现算—— + # 公式行用求值量,采纳进来的定额(含公式)同样算;没价不算留空,不报错 + _nq = _eval if n["qty_expr"] else n["Quantity"] + _nt = _r2(_nq * n["Price"]) if (_nq is not None and n["Price"] is not None) else None norms.setdefault(n["bill_id"], []).append( - [n["id"], n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], n["Total"], + [n["id"], n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], _nt, n["x_tdel"], n["x_adopt"], n["qty_expr"], _eval]) + if not n["x_tdel"]: # 临删定额导出时真实省略,不进 ∑ + _nhas[n["bill_id"]] = True + _nsum[n["bill_id"]] = _nsum.get(n["bill_id"], 0.0) + (_nt or 0.0) by_div, loose = {}, [] for b in bills: + # 决策 232(2026-10-28 主人定):清单单价=∑定额合价÷清单工程量(2 位)、合价=单价×量; + # 清单工程量=0 → 量/单价/合价不算不显(None,前端留空)、不报错;无定额清单(手工)照捕获值 + if b["Quantity"] == 0: + _bq_show = _bp = _bt = None + elif b["Quantity"] and _nhas.get(b["id"]): + _bp = _r2(_nsum[b["id"]] / b["Quantity"]) + _bt = _r2(_bp * b["Quantity"]) + _bq_show = b["Quantity"] + else: + _bq_show, _bp, _bt = b["Quantity"], b["Price"], b["Total"] it = {"type": "bill", "id": b["id"], "div": b["div_id"], "Number": b["Number"], "Name": b["Name"], "Attr": b["Attr"], "Unit": b["Unit"], - "Quantity": b["Quantity"], "Price": b["Price"], "Total": b["Total"], + "Quantity": _bq_show, "Price": _bp, "Total": _bt, "X_Remark": b["x_remark"], # 决策 203:软件自有备注(采纳/手工共此字段,s_remarks 持久回填) "x_new": b["x_new"], "x_tdel": b["x_tdel"], "x_adopt": b["x_adopt"], "norms": norms.get(b["id"], [])} @@ -5239,6 +5257,12 @@ def api_schema(): r("GET", "/api/session/manual/state", "手工工程目录树回填(导入项目弹框,决策 230)", {"session_id*": "会话id"}), r("GET", "/api/session/manual/template", "单位工程导入模板 xlsx(填写说明/分部分项/措施项目)"), + r("GET", "/api/session/manual/project_template", "整项目导入模板 xlsx(决策 238:项目目录+多对 Sheet,每对=1 个单位工程)"), + r("POST", "/api/session/manual/import_project", "整项目一把导入:建手工工程(目录树+清单一次到位,决策 238)", + {"name*": "工程名", "period_from*": "年*12+月", "period_to*": "止期次", + "path*": "整项目模板 xlsx 上传后的路径", "province?": "省", "city?": "市", + "district?": "区", "bulid_unit?": "建设单位"}, + {"ok": True, "sid": 5, "units": "[{uw,seq,n_div,n_item,n_prelim}]"}), r("POST", "/api/session/manual/parse", "单位工程 Excel 预检(挂接/重名/5层/换行识别)", {"path*": "上传返回的 path"}, {"n_div": 4, "n_item": 6, "n_prelim": 3}), @@ -7862,6 +7886,21 @@ class Handler(SimpleHTTPRequestHandler): self.send_header("Content-Disposition", self._cd(fn, "manual_import_template.xlsx")) self.end_headers() self.wfile.write(raw) + if p == "/api/session/manual/project_template": # 手工工程:整项目导入模板(决策 238) + try: + raw = mimp.template_project_bytes() + except ImportError: + return self._json({"error": "缺少 openpyxl,无法生成模板"}, 500) + except Exception as e: + return self._json({"error": "模板生成失败:%s" % e}, 500) + fn = "整项目导入模板.xlsx" + self._allow_cache = True # 下载不能带 no-store(同价格模板) + self.send_response(200) + self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Content-Disposition", self._cd(fn, "manual_project_template.xlsx")) + self.end_headers() + self.wfile.write(raw) if p == "/api/session/manual/export_unit": # 手工工程:单单位工程导 xlsx(决策 233 方案a) con = sess.connect() try: @@ -7977,6 +8016,16 @@ class Handler(SimpleHTTPRequestHandler): if u.path == "/api/session/manual/save": # 手工工程:建/改目录树+按单位工程导Excel(决策230) with WRITE_LOCK: return self._json(api_manual_save(body)) + if u.path == "/api/session/manual/import_project": # 手工工程:整项目一把导入(决策238) + with WRITE_LOCK: + c = sess.connect() + try: + r = mimp.import_project(c, body); c.commit() + except Exception as e: + r = {"ok": False, "msg": "导入异常:%s" % e} + finally: + c.close() + return self._json(r) if u.path == "/api/session/manual/parse": # 手工工程:单位工程Excel预检(决策230) return self._json(api_manual_parse(body)) if u.path == "/api/session/reparse": # 最近审核 → 重新解析(原地覆盖,id 不变) diff --git a/CostReview/app/server/mcp_server.py b/CostReview/app/server/mcp_server.py index 0473209..e0f3ba5 100644 --- a/CostReview/app/server/mcp_server.py +++ b/CostReview/app/server/mcp_server.py @@ -6,7 +6,8 @@ (首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查) - 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点 403 LICENSE_REQUIRED(开关开了也断) -- 工具(2026-10-27 主人定,共 5 个,**全部只读,无任何增删改/导出**): +- 工具(2026-10-29 决策 238/239 起 9 个;①~⑤⑧ 只读,⑥⑦⑨ 写入为**主人拍板新增**, + 取代 2026-10-27「只读、无任何增删改」旧口径): ① bills_query 入库项目清单:编号/名称/项目特征/单价 ② lme_prices 工料机单价 ③ market_info_prices 市场价/信息价数据 @@ -14,12 +15,22 @@ ⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律 不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch (价格批次原件);不支持枚举、不支持全量下载 + ⑥ project_import 整项目导入(写入):整项目模板 xlsx(项目目录+多对 Sheet)→ 建手工工程 + ⑦ bill_adopt 清单采纳(写入):走软件采纳同一条 API,整套术语表口径,可取消可追溯; + 仅在用户明确要求采纳时调用 + ⑧ match_hist 历史价匹配 top-N:对会话一行找最像的历史价(match.py 同一管线), + 行带 ref 票据供 ⑦⑨ 采纳 + ⑨ lme_adopt 工料机价格采纳(写入):采纳即改价(页面同一条通道),价格数字来自 + ⑧ 的服务端快照,不接受调用方传数字;仅在用户明确要求采纳时调用 - 零新增依赖:JSON-RPC 手写,只依赖标准库 """ import base64 import json import os +import re import secrets +import time +import uuid PROTO_VERSION = "2025-06-18" _API = None # api_server 模块(bind 注入,避免循环导入) @@ -217,6 +228,262 @@ def _t_recent_review_query(args): return {"ok": True, "total": len(rows), "rows": rows} +# ---------------------------------------------------------------- 工具实现(写入,决策 238) + +def _period_to_m(v): + """'YYYY-MM' 或 'YYYY/MM' 或 月序号 → 月序号(年*12+月);非法返回 None。""" + if v is None: + return None + s = str(v).strip() + m = re.match(r"^(\d{4})[-/年](\d{1,2})", s) + if m: + return int(m.group(1)) * 12 + int(m.group(2)) + try: + n = int(float(s)) + return n if n > 0 else None + except ValueError: + return None + + +def _t_project_import(args): + """⑥ 整项目导入(决策 238,写入):整项目模板 xlsx(项目目录+多对 Sheet,每对=1 个单位工程) + → 建手工工程(目录树+清单一次到位)。file_b64=xlsx 内容(base64)。同名手工工程再次导入=整项目覆盖。 + 导入后可用 recent_review_query 查该工程(session_id),再用 bill_adopt 采纳。""" + a = _api() + name = (args.get("name") or "").strip() + if not name: + return {"ok": False, "msg": "name(工程名称)必填"} + pf = _period_to_m(args.get("period_from")) + pt = _period_to_m(args.get("period_to") or args.get("period_from")) + if pf is None or pt is None: + return {"ok": False, "msg": "period_from(YYYY-MM)必填;period_to 缺省=同 period_from"} + b64 = (args.get("file_b64") or "").strip() + if not b64: + return {"ok": False, "msg": "file_b64(整项目模板 xlsx 的 base64 内容)必填——先向用户要 Excel 或按 template 说明生成"} + import base64 as _b64 + try: + raw = _b64.b64decode(b64, validate=True) + except Exception: + return {"ok": False, "msg": "file_b64 不是合法 base64"} + d = os.path.join(a.DATA_DIR, "manual_projects") + os.makedirs(d, exist_ok=True) + path = os.path.join(d, "mcp_%s.xlsx" % time.strftime("%Y%m%d_%H%M%S")) + with open(path, "wb") as f: + f.write(raw) + body = {"name": name, "period_from": pf, "period_to": pt, "path": path, + "province": (args.get("province") or "").strip(), + "city": (args.get("city") or "").strip(), + "district": (args.get("district") or "").strip(), + "bulid_unit": (args.get("bulid_unit") or "").strip()} + with a.WRITE_LOCK: + con = a.sess.connect() + try: + r = a.mimp.import_project(con, body) + con.commit() + except Exception as e: + r = {"ok": False, "msg": "导入异常:%s" % e} + finally: + con.close() + if r.get("ok"): + r["next"] = "recent_review_query(session_id=%s) 查清单;bill_adopt(session_id, bill_id, src_bill_id) 采纳" % r.get("sid") + return r + + +def _t_bill_adopt(args): + """⑦ 清单采纳(决策 238,写入):把入库项目清单的定额+消耗量落到工作台会话。 + bill_id=会话清单 id、src_bill_id=入库项目清单 id(都来自查询结果);走软件采纳同一条 + API(术语表整套口径:新行覆盖/已有行追加、取价锚、可取消可追溯)。仅在用户明确要求 + 采纳时调用;每次一条,采纳后把结果如实告诉用户。""" + a = _api() + try: + sid = int(args.get("session_id") or 0) + bid = int(args.get("bill_id") or 0) + except (TypeError, ValueError): + return {"ok": False, "msg": "session_id / bill_id 都必须是整数 id"} + src = 0 + snap = None + if args.get("ref"): + snap = _MATCH_CACHE.get((args.get("ref") or "").strip()) + if not snap or snap.get("type") != "bill": + return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist(type=bill)重新匹配"} + try: + src = int(snap.get("bill_id") or 0) + except (TypeError, ValueError): + src = 0 + if not src: + return {"ok": False, "msg": "该匹配行缺少来源清单 id,无法采纳"} + else: + try: + src = int(args.get("src_bill_id") or 0) + except (TypeError, ValueError): + return {"ok": False, "msg": "src_bill_id 必须是整数 id(或改传 ref 票据)"} + if not sid or not bid or not src: + return {"ok": False, "msg": "参数:session_id(工作台会话)+ bill_id(会话清单)+ src_bill_id(或 ref 票据)"} + with a.WRITE_LOCK: # 会话写库统一串行;采纳后分组缓存必撤(与页面路由同口径) + sc = a.sess.connect() + hc = a.conn() + try: + r = a.api_bill_adopt(sc, hc, {"session_id": sid, "bill_id": bid, "src_bill_id": src}) + sc.commit() + if r.get("ok"): + try: + a._grp_cache_drop("session", sid) + except Exception: + pass + except Exception as e: + try: + sc.rollback() + except Exception: + pass + r = {"ok": False, "msg": "采纳失败:%s" % e} + finally: + sc.close() + hc.close() + return r + + +# ---- 决策 239(2026-10-29 主人定):历史价匹配 top-N + 工料机价格采纳 ---- +# match_hist 返回行带 ref 票据:行数据快照(三价/名称/项目名)存本进程缓存,lme_adopt 只传 +# ref——被采纳的数字全部由服务端快照取,智能体零转录、改不了价。缓存仅进程内,超限整体清空 +#(语义=ref 失效请重新 match),不落盘、无泄漏面。 +_MATCH_CACHE = {} +_MATCH_CACHE_MAX = 2000 + + +def _match_ref(row): + if len(_MATCH_CACHE) >= _MATCH_CACHE_MAX: + _MATCH_CACHE.clear() + ref = uuid.uuid4().hex[:12] + _MATCH_CACHE[ref] = row + return ref + + +def _sess_row_ctx(sc, sid): + """会话元信息 + 匹配停用词(与工作台比对路由同口径)。""" + a = _api() + s = sc.execute("SELECT name, src_name, base_period_m, period_from, period_to FROM sessions WHERE id=?", + (sid,)).fetchone() + if not s: + return None + pf = (s["period_from"] if "period_from" in s.keys() else None) or s["base_period_m"] or 0 + pt = (s["period_to"] if "period_to" in s.keys() else None) or pf + sw = a._setting_get("global", "match_stopwords") + try: + a.match.set_stopwords(json.loads(sw)) if sw else a.match.set_stopwords([]) + except Exception: + a.match.set_stopwords([]) + return {"base": (pf, pt), + "self_name": (s["name"] or "").strip(), + "self_src": (s["src_name"] or "").split(";")[0].strip()} + + +def _t_match_hist(args): + """⑧ 历史价匹配 top-N(决策 239,只读):对工作台的一行(清单或工料机)在全部入库项目/ + 信息价/市场价里找最像的历史价,按 档位+期次距离 排序返回 top-N。每行带 ref 票据—— + bill_adopt / lme_adopt 用它采纳,不需要再传价格数字。""" + a = _api() + try: + sid = int(args.get("session_id") or 0) + rid = int(args.get("row_id") or 0) + except (TypeError, ValueError): + return {"ok": False, "msg": "session_id / row_id 必须是整数 id"} + typ = (args.get("type") or "bill").strip().lower() + if typ not in ("bill", "lme"): + return {"ok": False, "msg": "type 必须是 bill(清单)或 lme(工料机)"} + if not sid or not rid: + return {"ok": False, "msg": "参数:session_id + row_id(来自 recent_review_query 的行 id)"} + try: + limit = min(max(int(args.get("limit") or 5), 1), 20) + except (TypeError, ValueError): + limit = 5 + sc = a.sess.connect() + hc = a.conn() + try: + ctx = _sess_row_ctx(sc, sid) + if ctx is None: + return {"ok": False, "msg": "会话不存在(%d)" % sid} + if typ == "lme": + row = sc.execute("SELECT * FROM s_lmes WHERE id=? AND session_id=?", (rid, sid)).fetchone() + if not row: + return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"} + res = a.match.match_lme(hc, row, ctx["base"], limit=limit, + self_name=ctx["self_name"], self_src=ctx["self_src"]) + else: + row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone() + if not row: + return {"ok": False, "msg": "清单行不存在(可能已被删除,请刷新)"} + res = a.match.match_bill(hc, row, ctx["base"], [], [], [], limit, + self_name=ctx["self_name"], self_src=ctx["self_src"]) + finally: + sc.close() + hc.close() + out = [] + for r in res: + ref = _match_ref({"type": typ, **{k: r.get(k) for k in + ("name", "attr", "spec", "unit", "price", "tax", "price_tax", "proj", "src", "src_id", "bill_id")}}) + out.append({"ref": ref, "tier": r.get("tier"), "src": r.get("src"), + "name": r.get("name"), "spec": r.get("spec") or r.get("attr"), + "unit": r.get("unit"), "price": r.get("price"), "tax": r.get("tax"), + "price_tax": r.get("price_tax"), "proj": r.get("proj"), + "period": r.get("period"), "sim": r.get("sim")}) + return {"ok": True, "total": len(out), + "hint": "挑最合适的一行,把它的 ref 传给 %s 采纳" % ("lme_adopt" if typ == "lme" else "bill_adopt"), + "rows": out} + + +def _t_lme_adopt(args): + """⑨ 工料机价格采纳(决策 239,写入,仅在用户明确要求采纳时调用)。 + lme_id=会话工料机行 id(recent_review_query type=lmes 的行)、ref=match_hist 返回的票据。 + 与页面比对框「采纳」同一条通道:三价改价端点(三价联动/编码同步/merged_codes/旧价锚) + +「采纳:名称+项目+旧三价」备注。被采纳的价格来自服务端快照,不接受调用方传数字。""" + a = _api() + try: + sid = int(args.get("session_id") or 0) + lid = int(args.get("lme_id") or 0) + except (TypeError, ValueError): + return {"ok": False, "msg": "session_id / lme_id 必须是整数 id"} + ref = (args.get("ref") or "").strip() + snap = _MATCH_CACHE.get(ref) + if not snap or snap.get("type") != "lme": + return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist 重新匹配再采纳"} + if not sid or not lid: + return {"ok": False, "msg": "参数:session_id + lme_id(工作台工料机行 id,来自 recent_review_query)"} + sc = a.sess.connect() + try: + sl = sc.execute("SELECT id, Number, Name FROM s_lmes WHERE id=? AND session_id=?", (lid, sid)).fetchone() + if not sl: + return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"} + proj = sc.execute("""SELECT id, ntp, taxrate, taxp FROM s_lme_proj + WHERE session_id=? AND code=? ORDER BY id LIMIT 1""", + (sid, sl["Number"] or "")).fetchone() if sl["Number"] else None + if not proj: + return {"ok": False, "msg": "找不到该项目级工料机行(编码 %s)——项目级汇总未生成或编码为空" % (sl["Number"] or "空")} + old = {"price": proj["ntp"], "tax": proj["taxrate"], "taxp": proj["taxp"]} + with a.WRITE_LOCK: # 采纳即改价(决策 158)+ 采纳备注(决策 219 旧价锚口径) + rp = a.api_lme_price(sc, {"session_id": sid, "id": proj["id"], + "ntp": snap.get("price"), "taxrate": snap.get("tax"), + "taxp": snap.get("price_tax")}) + if not rp.get("ok"): + sc.rollback() + return {"ok": False, "msg": "采纳改价失败:" + (rp.get("msg") or "服务未响应")} + # 采纳备注文案与页面 adoptTxtFor 同口径:采纳:名称+项目+旧三价(0/空=「无」) + def p(v): + try: + return "无" if (v is None or v == "" or float(v) == 0) else v + except (TypeError, ValueError): + return "无" + txt = "采纳:%s+%s+%s|%s|%s" % (snap.get("name") or "", snap.get("proj") or "", + p(old["price"]), p(old["tax"]), p(old["taxp"])) + a.sess.save_lme_remark(sc, proj["id"], txt) + sc.commit() + finally: + sc.close() + return {"ok": True, "lme_id": proj["id"], "price": snap.get("price"), + "tax": snap.get("tax"), "price_tax": snap.get("price_tax"), "old": old, + "msg": "已采纳《%s》%s:除税 %s → %s" % (snap.get("name") or "", snap.get("proj") or "", + old["price"], snap.get("price"))} + + def _t_attachment_download(args): """⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。 type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach); @@ -311,6 +578,50 @@ def TOOLS(): "type": {"type": "string"}, "id": {"type": "integer"}}, "required": ["type", "id"]}, "run": _t_attachment_download}, + {"name": "project_import", + "description": "整项目导入(写入)。把整项目模板 xlsx(「项目目录」Sheet 定目录树+" + "多对数据 Sheet,每对 分部分项N/措施项目N=序号 N 的单位工程)导入建为" + "手工工程。file_b64=xlsx 文件内容(base64);name/period_from(YYYY-MM) 必填," + "province/city/district/bulid_unit 可选。同名手工工程再次导入=整项目覆盖。" + "导入成功后用 recent_review_query 查该工程清单,再按用户要求 bill_adopt。", + "inputSchema": {"type": "object", "properties": { + "name": {"type": "string"}, "period_from": {"type": "string"}, + "period_to": {"type": "string"}, "file_b64": {"type": "string"}, + "province": {"type": "string"}, "city": {"type": "string"}, + "district": {"type": "string"}, "bulid_unit": {"type": "string"}}, + "required": ["name", "period_from", "file_b64"]}, + "run": _t_project_import}, + {"name": "bill_adopt", + "description": "清单采纳(写入,仅在用户明确要求采纳时调用)。把入库项目清单的定额+消耗量" + "落到工作台会话清单上(软件采纳同一条通道:新行=整组覆盖,已有行=单价覆盖+" + "定额追加;可取消可追溯)。session_id=工作台会话、bill_id=会话清单 id、" + "src_bill_id=入库项目清单 id(id 必须来自查询结果)。每次采纳一条并把结果如实告诉用户。", + "inputSchema": {"type": "object", "properties": { + "session_id": {"type": "integer"}, "bill_id": {"type": "integer"}, + "src_bill_id": {"type": "integer"}}, + "required": ["session_id", "bill_id", "src_bill_id"]}, + "run": _t_bill_adopt}, + {"name": "match_hist", + "description": "历史价匹配 top-N(只读)。对工作台一行(清单或工料机)在全部入库项目/信息价/" + "市场价里找最像的历史价,按档位+期次距离排序返回 top-N;每行带 ref 票据," + "把它传给 bill_adopt / lme_adopt 即可采纳——不需要(也不允许)自己传价格数字。" + "session_id + row_id(来自 recent_review_query)+ type(bill/lme)+ limit(默认 5,上限 20)。", + "inputSchema": {"type": "object", "properties": { + "session_id": {"type": "integer"}, "row_id": {"type": "integer"}, + "type": {"type": "string"}, "limit": {"type": "integer"}}, + "required": ["session_id", "row_id"]}, + "run": _t_match_hist}, + {"name": "lme_adopt", + "description": "工料机价格采纳(写入,仅在用户明确要求采纳时调用)。把匹配到的历史价" + "(ref 票据)采纳到工作台工料机:与页面比对框「采纳」同一条通道(三价联动/" + "编码同步/merged_codes/旧价锚+采纳备注)。lme_id=工作台工料机行 id" + "(recent_review_query type=lmes 的行)+ ref(match_hist type=lme 返回的票据)。" + "价格数字来自服务端快照,不接受调用方传数字;每次一条,结果如实告知用户。", + "inputSchema": {"type": "object", "properties": { + "session_id": {"type": "integer"}, "lme_id": {"type": "integer"}, + "ref": {"type": "string"}}, + "required": ["session_id", "lme_id", "ref"]}, + "run": _t_lme_adopt}, ] diff --git a/CostReview/app/ui/admin.html b/CostReview/app/ui/admin.html index ebeb0d1..d460f8b 100644 --- a/CostReview/app/ui/admin.html +++ b/CostReview/app/ui/admin.html @@ -90,8 +90,8 @@ body{font-family:"Source Han Sans SC","Noto Sans SC","Source Han Sans CN","MiSan 左 38% 上传区 / 右 62% 工料机:右边 7 列给窄了必然横滚,等于白做。 中间 1px 实线 + 12px 间距,不用虚线 —— 虚线在这里不承载任何信息。 */ .qwrap{display:flex;gap:12px;flex:1;min-height:0;padding:12px} -.qleft{width:200px;min-width:110px;display:flex;flex-direction:column;gap:8px; - border-right:none;padding-right:0} /* 决策 213 补记:附件目录默认 150px(主人定),分隔条拖宽后按 px 记忆 */ +.qleft{width:300px;min-width:110px;display:flex;flex-direction:column;gap:8px; + border-right:none;padding-right:0} /* 决策 213 补记 px 制记忆;2026-10-28 主人定:默认 200→300px,拖宽后按 px 记忆 */ .qright{flex:1;display:flex;flex-direction:column;gap:8px;min-width:0} .qlist{flex:1;overflow:auto;border:1px solid #c9d4e2;border-radius:6px;background:#fff} .qitem{padding:8px 10px;border-bottom:1px solid #eef2f7;cursor:pointer; @@ -106,6 +106,7 @@ body{font-family:"Source Han Sans SC","Noto Sans SC","Source Han Sans CN","MiSan .qtag{font-size:11px;color:#5a6b7f;background:#eef3fa;border:1px solid #d8e0ec; border-radius:3px;padding:0 5px;white-space:nowrap} .qtag.bnd{background:#fbe0dc;border-color:#f0cdc6;color:#8c5044} /* 决策 213 补记四:绑定徽标底色=分组淡粉红 */ +.qfhide{display:none} /* 决策 237 补记:绑定筛选就地藏行(类优先级低于 tgGrp 的内联 display,两个维度正交) */ .qtabs .btn{height:28px;padding:0 12px;font-size:12.5px;line-height:1} /* 与工作台 .btn 同尺寸 */ .qbadge{font-size:11px;color:#5a6b7f;background:#f4f8ff;border:1px solid #d8e0ec; border-radius:3px;padding:0 5px;margin-left:4px} @@ -420,7 +421,7 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb
项目工料机
类似清单
- @@ -1460,6 +1461,9 @@ async function loadTab(pid, fresh){ // fresh=true(⟳ 重载,决策 46):服务端跳过缓存强制重算,算完回填缓存 const url = pid==='p1' ? `/api/admin/batch/${DID}/inconsistent` : `/api/admin/batch/${DID}/similar` + (fresh ? '?fresh=1' : ''); + // 决策 237 补记二(主人报「等待期间加载画面消失」):取数期先给占位行(工作台同款) + tb.innerHTML = '' + + (pid==='p1' ? '正在计算组价不一致(同名同规格比对)…' : '正在计算类似清单分组(工程大要稍等)…') + ''; const d=await J(url); BILL_SORT={k:-1,dir:1}; // 新数据:组内排序复位(2026-10-10) cg.innerHTML=colgHTML(AC_BILL); sumw($('dtb')); colwApply($('dtb')); // 后台列=noWB 派生(隐藏取消采纳) @@ -1873,7 +1877,7 @@ async function openInq(id,name){ let i=XTABS.findIndex(t=>t.kind==='inq' && t.id===id); if(i<0){ XTABS.push({id:id, name:name, kind:'inq'}); i=XTABS.length-1; } XACT=i; renderXTabs(); showPage('inq'); xsave(); - QBID=id; QBNAME=name; QFID=0; QLMES=[]; QB_SIM=null; QBILLS=[]; QTAB='lme'; + QBID=id; QBNAME=name; QFID=0; QFNAME=''; QLMES=[]; QB_SIM=null; QBILLS=[]; QTAB='lme'; document.querySelectorAll('.qtab').forEach(x=>x.classList.toggle('on',x.dataset.t==='lme')); $('qkw').value=''; $('qmsg').textContent=''; $('qbmsg').textContent=''; await qLoad(); @@ -1884,10 +1888,16 @@ async function qLoad(){ J(`/api/admin/batch/${QBID}/inq/lmes`)]); if(!a.ok){ $('qmsg').textContent='× '+a.msg; return; } if(b.ok) QLMES=b.rows||[]; + qRenderFiles(a.files); + if(QTAB==='lme') qRender(); else await qRenderBill(); +} +/* 2026-10-28(主人定):左目录渲染/刷新与整页加载拆开——上传/删除后只刷左树, + 右侧页签的勾选/滚动/筛选原地不动(不再整页 qLoad 重取重画)。 */ +function qRenderFiles(files){ // 附件目录树:决策 213 补记三——「📁 附件目录」标识行取消(上传/删除移到右上按钮行),直接列附件 $('qlist').innerHTML = - (a.files.length - ? a.files.map(f=>`
+ (files.length + ? files.map(f=>`
${esc(f.name)}${f.n} 条 @@ -1897,12 +1907,20 @@ async function qLoad(){ onclick="event.stopPropagation();return qDelFile(${f.id})">删除
${esc((f.ext||'').replace('.','').toUpperCase())}
`).join('') : '
还没有附件。点右上「上传附件」。
'); - if(QTAB==='lme') qRender(); else await qRenderBill(); + const on=document.querySelector('#qlist .qitem.on a[data-n]'); + QFNAME=on?on.getAttribute('data-n'):''; +} +async function qRefreshFiles(){ + const a=await J(`/api/admin/batch/${QBID}/inq`); + if(!a.ok){ $('qmsg').textContent='× '+a.msg; return; } + qRenderFiles(a.files||[]); } function qSel(fid){ // 决策 153①:本地选中(不重新拉接口)——此前每次点击都 qLoad() 重取三接口,故而卡顿 QFID=fid; document.querySelectorAll('#qlist .qitem').forEach(x=>x.classList.toggle('on', +x.dataset.fid===fid)); + const on=document.querySelector('#qlist .qitem.on a[data-n]'); + QFNAME=on?on.getAttribute('data-n'):''; } async function qTab(t){ @@ -1918,6 +1936,15 @@ async function qTab(t){ /* 工料机页签:列定义(复选框+编码固定,名称/规格伸缩)——决策 154③ 列宽拖动同工作台项目工料机 */ const QCOLS_LME=[['',36,'c','F'],['编码',110,'c','F'],['名称',220,'l'],['规格型号',200,'l'], ['单位',56,'c','F'],['除税价',100,'r','F'],['含税价',100,'r','F']]; // 决策 213 补记六:数量列隐藏(主人定,仅本页) +/* 工料机单行 HTML(2026-10-28 抽出:绑定/解绑就地行刷新复用,与 qRender 同一份口径) */ +function qLmeRowHTML(r){ + const bd=!!r.file_id; + const tag=bd?`已绑:${esc((r.file_name||'其他').slice(0,18))}`:''; + return `` + + `${esc(r.code||'—')}` + + `${esc(r.name)}${tag}${esc(r.spec||'—')}${esc(r.unit||'—')}` + + `${num(r.price)}${num(r.price_tax)}`; +} function qRender(){ // 决策 229:搜索不再筛行(原 kw 过滤与 qhl 逐格高亮退役,改共享层整区黄底 + 上一个/下一个); // 只留绑定筛选(决策 213 补记三) @@ -1927,14 +1954,7 @@ function qRender(){ $('qthl').innerHTML = '' + QCOLS_LME.map((c,i)=> i===0 ? '' : ''+esc(c[0])+'').join('') + ''; - $('qtbl').innerHTML = rows.length ? rows.map(r=>{ - const bd=!!r.file_id; - const tag=bd?`已绑:${esc((r.file_name||'其他').slice(0,18))}`:''; - return `` - + `${esc(r.code||'—')}` - + `${esc(r.name)}${tag}${esc(r.spec||'—')}${esc(r.unit||'—')}` - + `${num(r.price)}${num(r.price_tax)}`; - }).join('') + $('qtbl').innerHTML = rows.length ? rows.map(qLmeRowHTML).join('') : '没有工料机'; $('qc').textContent = '共 ' + rows.length + ' 条'; $('qcgl').innerHTML = colgHTML(QCOLS_LME); @@ -1969,7 +1989,7 @@ async function qRenderBill(){ const qbopts = {checkbox:true, backend:true, attach:QBINDS, hideCols:['工程量','合价'], locate:1}; // 决策 213 补记六(主人定:仅本页传 hideCols,工作台零影响) $('qthb').innerHTML = billHeadHTML(qbopts); $('qtbb').innerHTML = renderGroups(enr,'similar',qbopts); - grpTreeBind($('qsimtree'),'qtbb',enr); + grpTreeBind($('qsimtree'),'qtbb',enr, { onFilter: ()=>qApplyBillFilter() }); // 决策 237 补记二:树过滤后绑定筛选条数/组头联动 $('qcgb').innerHTML = colgHTML(qBindCols()); sumw($('qgt')); colwApply($('qgt')); // 覆盖面统计与条数(决策 213) const nb = Object.keys(QBINDS).length; @@ -2001,7 +2021,7 @@ $('qfile').onchange=async function(){ const r=await uploadFile(`/api/admin/batch/${QBID}/inq`, f); $('qmsg').textContent=(r.ok?'✓ ':'× ')+r.msg; this.value=''; - if(r.ok){ QFID=r.id||QFID; await qLoad(); } + if(r.ok){ QFID=r.id||QFID; await qRefreshFiles(); } // 2026-10-28(主人定):只刷左目录,右侧勾选/滚动/筛选原地不动 }; /* 决策 153②:附件工作区左右拖宽(分隔条 + localStorage 记忆,默认 40%) */ @@ -2009,9 +2029,13 @@ $('qfile').onchange=async function(){ const sp=document.getElementById('qsplit'); const left=document.querySelector('#qpage .qleft'); if(!sp||!left) return; - /* 决策 213 补记:附件目录改 px 制——默认 150px,拖动 110~400px,按 px 记忆(旧百分比记忆<110 视为未设置) */ - try{ const w=+localStorage.getItem('admin_inq_split'); left.style.width = (w>=110 ? w : 200)+'px'; } - catch(e){ left.style.width='200px'; } + /* 决策 213 补记:附件目录改 px 制,拖动 110~400px 按 px 记忆。 + 2026-10-28 主人定:默认 200→300px;清一次旧拖宽记忆让新默认生效(布标记只清这一次) */ + try{ + if(!localStorage.getItem('admin_inq_split_rst')){ localStorage.removeItem('admin_inq_split'); localStorage.setItem('admin_inq_split_rst','1'); } + const w=+localStorage.getItem('admin_inq_split'); left.style.width = (w>=110 ? w : 300)+'px'; + } + catch(e){ left.style.width='300px'; } let dragging=false; sp.addEventListener('mousedown', e=>{ dragging=true; e.preventDefault(); document.body.style.cursor='col-resize'; }); window.addEventListener('mousemove', e=>{ @@ -2038,6 +2062,97 @@ async function qKeepScroll(fn){ mem.forEach(m=>{ m.e.scrollTop = m.st; }); } +/* ---- 2026-10-28(主人定):绑定/解绑/删附件就地更新三件套 ---- + 决策 206「只动受影响行」铺到附件页:不再重取 /similar、不再整表重建, + 左树选中/组展开/排序/筛选视图全保持;「只看未绑定」下绑定的行就地保留显示 + (主人拍板口径),下次换筛选/重进页签才按新状态算。 */ +function qBumpBadge(fid, delta){ + const el=document.querySelector('#qlist .qitem[data-fid="'+fid+'"] .qbadge'); + if(el) el.textContent=Math.max(0,(parseInt(el.textContent,10)||0)+delta)+' 条'; +} +function qLmeRowsRefresh(ids){ + const tb=$('qtbl'); + ids.forEach(id=>{ + const ck=tb.querySelector('input[data-id="'+id+'"]'); + const r=QLMES.find(x=>x.id===id); + if(ck&&r){ const tr=ck.closest('tr'); tr.insertAdjacentHTML('afterend', qLmeRowHTML(r)); tr.remove(); } + }); + if(PAGESRCH.qlme){ PGS_NAV.qlme.i=-1; hlContainer($('qtb'), PAGESRCH.qlme); pgsSetNav('qlme'); } +} +function qBillRowsRefresh(ids){ + const tb=$('qtbb'); + const opts=(typeof GRP_DATA!=='undefined'&&GRP_DATA&&GRP_DATA.opts)||{}; + const pools=(QB_SIM&&((QB_SIM.groups||[]).concat(QB_SIM.extra||[])))||[]; + ids.forEach(id=>{ + const tr=tb.querySelector('tr[data-bid="'+id+'"]'); + let r=null; + for(const g of pools){ const hit=(g.rows||[]).find(x=>x[0]===id); if(hit){ r=hit; break; } } + if(tr&&r&&!tr.classList.contains('sub')){ + const grp=tr.dataset.grp||''; + tr.insertAdjacentHTML('afterend', billTR(r, grp, false, opts)); + tr.remove(); + } + }); + if(PAGESRCH.qsim){ PGS_NAV.qsim.i=-1; hlContainer(tb, PAGESRCH.qsim); pgsSetNav('qsim'); } + const nb=Object.keys(QBINDS).length; + $('qcov').textContent='已绑 '+nb+' / '+QBILLS.length+'('+(QBILLS.length?Math.round(nb/QBILLS.length*100):0)+'%)'; +} + +/* ---- 2026-10-28(主人定,决策 237 补记):绑定筛选切换就地显隐,不再整表重画 ---- + 组展开态/树选中/组内排序/滚动全保持;真相源=QBINDS/QLMES;懒渲染组展开出的新行 + 由 #qtbb 捕获监听补过一遍筛选。全空时给一行提示。 */ +function qFilterChange(){ + if(QTAB==='lme') qApplyLmeFilter(); else qApplyBillFilter(); +} +function qApplyLmeFilter(){ + const flt=$('qflt') ? $('qflt').value : 'all'; + let n=0; + [...$('qtbl').querySelectorAll('tr')].forEach(tr=>{ + const ck=tr.querySelector('input[data-id]'); if(!ck) return; + const row=QLMES.find(x=>x.id===+ck.dataset.id); + const vis = flt==='all' ? true : (flt==='bound' ? !!(row&&row.file_id) : !(row&&row.file_id)); + tr.classList.toggle('qfhide', !vis); + if(vis) n++; + }); + $('qc').textContent = '共 ' + n + ' 条' + (flt!=='all' ? '(筛选自 ' + QLMES.length + ')' : ''); +} +function qApplyBillFilter(){ + const flt=$('qflt') ? $('qflt').value : 'all'; + const tb=$('qtbb'); + const visOf = id => flt==='all' ? true : (flt==='bound' ? !!QBINDS[id] : !QBINDS[id]); + const grpVis={}; let nVis=0; + [...tb.querySelectorAll('tr[data-bid]')].forEach(tr=>{ + if(tr.classList.contains('sub')) return; + const vis = visOf(+tr.dataset.bid); + tr.classList.toggle('qfhide', !vis); + let nx=tr.nextElementSibling; // 已展开的定额子行跟随父行 + while(nx && nx.classList.contains('sub')){ nx.classList.toggle('qfhide', !vis); nx=nx.nextElementSibling; } + if(vis && !tr.classList.contains('tfhide')){ grpVis[tr.dataset.grp]=(grpVis[tr.dataset.grp]||0)+1; nVis++; } // 决策 237 补记二:树过滤藏着的行不计 + }); + [...tb.querySelectorAll('tr.grp,tr.grp2')].forEach(tr=>{ + tr.classList.toggle('qfhide', !(grpVis[tr.dataset.grp]||0)); + }); + const sep=tb.querySelector('tr.sep'); // 「未形成相似组」分隔行:其后任一清单行可见则留 + if(sep){ + let nx=sep.nextElementSibling, any=false; + while(nx){ if(nx.dataset && nx.dataset.bid && !nx.classList.contains('sub') && !nx.classList.contains('qfhide') && !nx.classList.contains('tfhide')){ any=true; break; } nx=nx.nextElementSibling; } + sep.classList.toggle('qfhide', !any); + } + let tip=tb.querySelector('tr.qfempty'); + if(!nVis && (QBILLS||[]).length){ + if(!tip){ tip=document.createElement('tr'); tip.className='qfempty'; + tip.innerHTML='没有符合筛选条件的清单'; + tb.appendChild(tip); } + tip.classList.remove('qfhide'); + } else if(tip) tip.classList.add('qfhide'); + $('qc').textContent = '共 ' + nVis + ' 条' + (flt!=='all' ? '(筛选自 ' + (QBILLS||[]).length + ')' : ''); +} +/* 懒渲染钩子:组头点开展开 → tgGrp 现场建的行补过一遍筛选(只动 qfhide 类,不动组收起的内联 display) */ +$('qtbb').addEventListener('click', e=>{ + if(!e.target.closest('tr.grp,tr.grp2')) return; + setTimeout(()=>{ if(QTAB==='bill') qApplyBillFilter(); }, 0); +}, true); + async function qBind(){ if(!QFID){ alert('请先在左边点选一个附件。'); return; } const ids=qChecked(); @@ -2057,8 +2172,22 @@ async function qBind(){ const r=await qPost(`/api/admin/batch/${QBID}/inq/bind`,body); $('qbmsg').textContent=(r.ok?'✓ ':'× ')+r.msg; if(!r.ok) return; - if(isLme) await qKeepScroll(qLoad); - else { QB_SIM=null; await qKeepScroll(qRenderBill); } // 绑定态变了:附件分组视图重取绑定刷新备注列 + // 2026-10-28(主人定):就地更新——改内存绑定态、受影响行重建、左树徽标加减,不再重取 /similar 整页重画 + const fname=QFNAME||('附件#'+QFID); + let chg=0; + if(isLme){ + ids.forEach(id=>{ const row=QLMES.find(x=>x.id===id); + if(row && +row.file_id!==+QFID){ if(row.file_id) qBumpBadge(row.file_id,-1); chg++; row.file_id=QFID; row.file_name=fname; } }); + if(chg) qBumpBadge(QFID,chg); + await qKeepScroll(()=>qLmeRowsRefresh(ids)); + } else { + ids.forEach(id=>{ const old=QBINDS[id]; + if(!old || old.fid!==QFID){ if(old) qBumpBadge(old.fid,-1); chg++; QBINDS[id]={name:fname,fid:QFID}; } }); + if(chg) qBumpBadge(QFID,chg); + await qKeepScroll(()=>qBillRowsRefresh(ids)); + } + // 本次操作行的勾选清零(就地更新不整表重建,勾选不会自动消失) + ids.forEach(id=>{ const ck=document.querySelector('input.qbindck[data-id="'+id+'"], #qtbl input[data-id="'+id+'"]'); if(ck) ck.checked=false; }); } async function qUnbind(){ @@ -2069,8 +2198,15 @@ async function qUnbind(){ const r=await qPost(`/api/admin/batch/${QBID}/inq/unbind`,body); $('qbmsg').textContent=(r.ok?'✓ ':'× ')+r.msg; if(!r.ok) return; - if(QTAB==='lme') await qKeepScroll(qLoad); - else { QB_SIM=null; await qKeepScroll(qRenderBill); } + // 2026-10-28(主人定):就地更新(同 qBind) + if(QTAB==='lme'){ + ids.forEach(id=>{ const row=QLMES.find(x=>x.id===id); if(row&&row.file_id){ qBumpBadge(row.file_id,-1); row.file_id=null; row.file_name=''; } }); + await qKeepScroll(()=>qLmeRowsRefresh(ids)); + } else { + ids.forEach(id=>{ const old=QBINDS[id]; if(old){ qBumpBadge(old.fid,-1); delete QBINDS[id]; } }); + await qKeepScroll(()=>qBillRowsRefresh(ids)); + } + ids.forEach(id=>{ const ck=document.querySelector('input.qbindck[data-id="'+id+'"], #qtbl input[data-id="'+id+'"]'); if(ck) ck.checked=false; }); } /* 决策 213 补记七:组表「单位工程名称」点击 → 追踪定位到本批次明细原数据树的那条清单。 */ @@ -2095,7 +2231,19 @@ async function qDelFile(fid){ 它名下的绑定(${f.n||0} 条)会一并解绑(工料机/清单本体不动)。`)) return; const r=await qPost(`/api/admin/batch/${QBID}/inq/del`,{file_id:fid}); $('qmsg').textContent=(r.ok?'✓ ':'× ')+r.msg; - if(r.ok){ if(QFID===fid) QFID=0; await qLoad(); } + if(r.ok){ + if(QFID===fid) QFID=0; + // 2026-10-28(主人定):名下绑定就地清 + 受影响行重建,不再整页 qLoad + if(QTAB==='lme'){ + const ids=[]; QLMES.forEach(row=>{ if(+row.file_id===+fid){ ids.push(row.id); row.file_id=null; row.file_name=''; } }); + if(ids.length) qLmeRowsRefresh(ids); + } else { + const ids=Object.keys(QBINDS).filter(k=>QBINDS[k].fid===fid).map(Number); + ids.forEach(id=>delete QBINDS[id]); + if(ids.length) qBillRowsRefresh(ids); + } + await qRefreshFiles(); + } } diff --git a/CostReview/app/ui/common.css b/CostReview/app/ui/common.css index 96c14f2..b8fabb7 100644 --- a/CostReview/app/ui/common.css +++ b/CostReview/app/ui/common.css @@ -330,3 +330,4 @@ mark.pghlcur{background:#ff9c40;color:#fff;padding:0} /* 决策 209:当前 .pgsrch{width:200px;height:24px;box-sizing:border-box} .pgsnav{height:24px;padding:0 8px;font:inherit;font-size:12px;border:1px solid #b8c4d4;border-radius:5px;background:#fff;color:#24425f;cursor:pointer;box-sizing:border-box} /* 决策 209:跳转按钮 */ .pgsnav:disabled{background:#f0f2f5;color:#a8b4c4;border-color:#d5dde8;cursor:default} +.tfhide{display:none} /* 决策 237 补记二:组树点选就地过滤(grpTreeBind),与附件页 .qfhide 绑定筛选正交叠加 */ diff --git a/CostReview/app/ui/common.js b/CostReview/app/ui/common.js index d46b8ec..4e30a29 100644 --- a/CostReview/app/ui/common.js +++ b/CostReview/app/ui/common.js @@ -873,7 +873,11 @@ function grpTreeRender(box, d, pick, opt) { 点根=显示全部;点组/类=只显示该组。原先 workbench / admin 各写一份逐字相同的回调, 且交互还在调的阶段 —— 收进公共层,改一处两侧同步。 grpTreeBind(树容器, 清单表 tbody 的 id, /similar 接口返回); - opts 不用传 —— renderGroups 自己会取页面全局 WB_OPTS。 */ + opts.onFilter(key) 可选:过滤后回调(附件页联动绑定筛选条数),其余页面不传零影响。 + 决策 237 补记二(2026-10-28 主人定):点组/点根改**就地显隐**(.tfhide 类),不再整表 + 重画 —— 组展开态/组内排序/滚动/定额子行全原地保持;与附件页 .qfhide(绑定筛选) + 正交叠加(display 由两类共同决定,互不覆盖)。决策 90 保留:点单组仍 fitGroupWidth + 缩列宽贴容器;点根摘掉全部 tfhide 并恢复默认列宽(与旧重画稳态一致)。 */ function grpTreeBind(box, tbId, d, opt) { opt = opt || {}; const kind = opt.kind || 'similar'; @@ -883,19 +887,38 @@ function grpTreeBind(box, tbId, d, opt) { if (!tb) return; const o = (typeof GRP_DATA !== 'undefined' && GRP_DATA && GRP_DATA.opts) || undefined; // 决策 153③:左树重画保留渲染选项(checkbox/backend) if (key === 'all') { - tb.innerHTML = renderGroups(d, kind, o); - if (typeof markGroupEH === 'function' && typeof EH_LOG !== 'undefined' && EH_LOG) markGroupEH(tb); // 决策 218 补二:树过滤重画后补红三角 - return; + tb.querySelectorAll('tr.tfhide').forEach(tr => tr.classList.remove('tfhide')); + const t = tb.closest('table'); // 点根恢复默认列宽(旧重画稳态) + if (t) { + const cg = t.querySelector('colgroup'); + if (cg) cg.innerHTML = colgHTML(billColsO(o || {})); + sumw(tb); + if (typeof colwApply === 'function') colwApply(tb); + } + } else { + const i = +key.slice(2); + const g = key.charAt(1) === 'g' ? (d.groups || [])[i] : (d.extra || [])[i]; + if (!g) return; + // 该组行未懒建过就先建(与 tgGrp 同一条建行路径),建完补编辑历史红三角 + const head = tb.querySelector('tr[data-grp="' + key + '"]'); + if (head) { + const nxt = head.nextElementSibling; + if (!nxt || nxt.dataset.grp !== key) { + head.insertAdjacentHTML('afterend', grpRowsHTML(g, key, o)); + if (typeof markGroupEH === 'function' && typeof EH_LOG !== 'undefined' && EH_LOG) markGroupEH(tb.id); + } + } + // 本组摘、其余组(组头/清单行/已展开定额子行)与 sep 行挂;无 data-grp 的占位行不动 + tb.querySelectorAll('tr').forEach(tr => { + if (tr.classList.contains('qfempty')) return; + const grp = tr.dataset.grp || ''; + if (!grp && !tr.classList.contains('sep')) return; + tr.classList.toggle('tfhide', grp !== key); + }); + // 决策 90(2026-10-17):点组=只显示该组时,列宽整体缩到贴住容器——右边不再有下滑条 + if (typeof fitGroupWidth === 'function') fitGroupWidth(tbId); } - const i = +key.slice(2); - const g = key.charAt(1) === 'g' ? (d.groups || [])[i] : (d.extra || [])[i]; - if (!g) return; - const lbl = key.charAt(1) === 'g' ? ('第 ' + (i + 1) + ' 组') - : ('第 ' + ((d.groups || []).length + i + 1) + ' 组'); - tb.innerHTML = renderGroups({ groups: [g], labels: [lbl] }, kind, o); - if (typeof markGroupEH === 'function' && typeof EH_LOG !== 'undefined' && EH_LOG) markGroupEH(tb); // 决策 218 补二:单组显示重画后补红三角 - // 决策 90(2026-10-17):点组=只显示该组时,列宽整体缩到贴住容器——右边不再有下滑条 - if (typeof fitGroupWidth === 'function') fitGroupWidth(tbId); + if (typeof opt.onFilter === 'function') opt.onFilter(key); }, { kind: kind, rootName: opt.rootName }); } @@ -964,6 +987,8 @@ function tgNorm(el, billId) { + '(该清单下没有定额)'; } else { // 定额 0=编码 1=名称 2=单位 3=工程量 4=单价 5=合价,其余列按清单的对应位置排空(含取消采纳/备注两空位) + // 2026-10-28(主人定):子行格序列与表头同走 billColsO(GRP_DATA.opts)——附件页复选框列前置 + // 空格、hideCols(工程量/合价)跳格;工作台 opts 无这两项,出格与旧版逐格相同 // 决策 68 批次B:会话侧 r[6]=x_tdel(原定额转临删→浅灰横线)、r[7]=x_adopt;批次侧恒 0 // 公共功能4(2026-10-15):序号格挂圆形「耗」按钮 → 工料机浮层(r[8]=定额 id,两侧同形; // 无 id 的行没有按钮、退回「—」占位) @@ -971,22 +996,25 @@ function tgNorm(el, billId) { // 工程量按真实数字显示(numG,不固定位数) // 决策 96(主人定):定额工程量**永远显示数字**——公式行显示按当前清单量求值的结果(r[10]), // 公式原文只在悬停提示(title)与编辑预填里出现 + const gopts = (typeof GRP_DATA !== 'undefined' && GRP_DATA && GRP_DATA.opts) || opts || {}; + const skipCol = n => !!(gopts.hideCols && gopts.hideCols.includes(n)); frag.innerHTML = rows.map(r => '' + + (gopts.checkbox ? '' : '') + '' + haoBtn(r[8]) + '' + ell(r[0], '—') + '' + '定额' + '—' + '    ' + ell(r[1], '—') + '' + '—' + '' + esc(r[2] || '—') + '' - + '' + (r[9] ? (r[10] != null ? numG(r[10]) : '—') : numG(r[3])) + '' + + '>' + (r[9] ? (r[10] != null ? numG(r[10]) : '—') : numG(r[3])) + '') + '' + num(r[4]) + '' - + '' + num(r[5]) + '' - + (opts.backend ? '' : '—') + + (skipCol('合价') ? '' : '' + num(r[5]) + '') + + (gopts.backend ? '' : '—') + '').join(''); } let n2 = tr.nextElementSibling; @@ -1540,8 +1568,12 @@ function rawTreeHTML(d) { + '清单' + '' + ell(b.Name, '—') + '' + '' + ell(fmtAttr(b.Attr)) + '' - + '' + esc(b.Unit || '—') + '' + r3(b.Quantity) + '' - + '' + rm(b.Price) + '' + rm(b.Total) + '' + + '' + esc(b.Unit || '—') + '' + // 决策 232(2026-10-28 主人定):清单工程量=0 → 量/单价/合价不显示(留空不算); + // 服务端对 0 量行三值回 None,这里按 null 留空(不是「—」) + + '' + (b.Quantity == null ? '' : r3(b.Quantity)) + '' + + '' + (b.Quantity == null ? '' : rm(b.Price)) + '' + + '' + (b.Quantity == null ? '' : rm(b.Total)) + '' // 取消采纳列(决策 68 批次B 实装:有数据采纳标记 → 撤销链接;否则占位) + '' + (b.x_adopt ? '取消 + + + + @@ -2031,6 +2035,10 @@ async function loadGroups(kind, fresh, keepView, restore){ else if(keepView){ keep=_grpKeepCapture(tbId, treeEl); // 决策 214:采集统一收口(规格⑥:定额选中态也留底) } + // 决策 237 补记二(主人报「等待期间加载画面消失」):取数期先给占位行——遮罩 250ms + // 阈值内完成的快路径、以及无数据/空表路径,表格区也不再白板 + $(tbId).innerHTML = '' + + (kind==='similar' ? '正在加载类似清单(分组计算,工程大要稍等)…' : '正在加载组价不一致清单…') + ''; const d=await J(`/api/session/${kind}?session_id=${SID}` + (fresh ? '&fresh=1' : '')); const el = kind==='inconsistent' ? ['cg1','th1','tb1'] : ['cg2','th2','tb2']; BILL_SORT={k:-1,dir:1}; // 新数据:组内排序复位(2026-10-10) @@ -3639,6 +3647,25 @@ async function impFile(){ $('imsg').textContent=''; impTreeRender(); } function impTemplate(){ return saveAs('/api/session/manual/template','单位工程导入模板.xlsx'); } +/* 决策 238:整项目一把导入——项目目录 Sheet 定目录树,分部分项N/措施项目N=序号 N 的单位工程。 + 工程名称/基准期次/地区/建设单位共用左侧字段;同名手工工程再次导入=整项目覆盖。 */ +function impProjPick(){ return saveAs('/api/session/manual/project_template','整项目导入模板.xlsx'); } +async function impProjFile(){ + const f=$('iprojfile').files[0]; $('iprojfile').value=''; + if(!f) return; + const name=$('oname').value.trim(), pv=PVAL($('oper')); + if(!name){ $('imsg').textContent='工程名称必填(左边共用字段)'; return; } + if(pv.f==null||pv.t==null){ $('imsg').textContent='基准期次必填:点开选起~止(同月就选同一个)'; return; } + $('imsg').textContent='正在上传 '+f.name+'…'; + const up=await uploadFile('/api/admin/upload',f); + if(!up.ok){ $('imsg').textContent=up.msg; return; } + $('imsg').textContent='正在导入整项目…'; + const r=await J('/api/session/manual/import_project',{method:'POST',headers:{'Content-Type':'application/json'}, + body:JSON.stringify({name,period_from:pv.f,period_to:pv.t,path:up.path, + province:$('oprov').value,city:$('ocity').value,district:$('odist').value,bulid_unit:$('obuid').value})}); + if(!r.ok){ $('imsg').textContent=r.msg||'导入失败'; return; } + location.href='/workbench.html?sid='+r.sid; // 导入完成直接进工程(与 impSave 同款跳转) +} async function impSave(){ const name=$('oname').value.trim(), pv=PVAL($('oper')); if(!name){ $('imsg').textContent='工程名称必填(左边共用字段)'; return; }