diff --git a/CostReview/app/core/dyn_lme.py b/CostReview/app/core/dyn_lme.py index 4e116a0..58fa477 100644 --- a/CostReview/app/core/dyn_lme.py +++ b/CostReview/app/core/dyn_lme.py @@ -533,25 +533,58 @@ def qmap_mtime_of(sc): return _qpath_mt(sc)[1] -def _propagate(base, kids): +def _propagate(base, kids, remap=None): """母子传导唯一实现:子量 = 母量 × 子含量,从直接消耗量快照出发只传一层 - (决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。""" + (决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。 + remap={旧码: 新码}(2026-11-14 决策 304 缺口修复):同码异物拆码迁移后,源件组成边 + (uw_id=NULL 全项目一份)仍指向旧码——迁移桶里旧码已无行、行已迁新码,本桶传导目标 + 按 remap 重定向,消除「原码幽灵量」(显示端项目级=按行所在单位取量会漏它)。 + 无拆码项目 remap=None,行为与历史完全一致。""" out = dict(base) for mcode, mq in base.items(): if mq is None: continue for c, q, _nm in kids.get(mcode) or (): + tgt = (remap or {}).get(c, c) try: - out[c] = out.get(c, 0.0) + float(mq) * float(q or 0) + out[tgt] = out.get(tgt, 0.0) + float(mq) * float(q or 0) except (TypeError, ValueError): pass return out +def _split_remap_by_uw(sc, sid): + """拆码重定向表 {uw_id: {旧码: 新码}}(2026-11-14 304 缺口修复配套)。 + 口径:登记簿 recode_ident 的每个 (旧码→新码) 身份包——旧码行所在单位集 U_old、 + 新码行所在单位集 U_new——U_new − U_old 中的单位 u:本桶传导目标 old→new + (该桶旧码已无行、实际行=新码)。无登记簿/无拆码→返回 {}。""" + try: + row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k=?", + ("session:%d" % sid, "recode_ident")).fetchone() + rec = __import__("json").loads(row[0] or "{}") if row and row[0] else {} + if not rec: + return {} + units = {} + for r in sc.execute("""SELECT code, uw_id FROM s_lme_uw + WHERE session_id=? AND uw_id IS NOT NULL AND code IS NOT NULL""", + (sid,)): + units.setdefault(r["code"], set()).add(r["uw_id"]) + out = {} + for old, idents in rec.items(): + u_old = units.get(old) or set() + for new in set(idents.values()): + for u in (units.get(new) or set()) - u_old: + out.setdefault(u, {})[old] = new + return out + except Exception: + return {} + + def _qmap_build_all(sc, sid): consume = _consumption_by_code(sc, sid, None, by_uw=True) kids = _children_map(sc, sid) - return {u: _propagate(m, kids) for u, m in consume.items()} + remaps = _split_remap_by_uw(sc, sid) + return {u: _propagate(m, kids, remaps.get(u)) for u, m in consume.items()} def qmap_all_cached(sc, sid): @@ -587,7 +620,8 @@ def qmap_touch_uw(sc, sid, uw_id, pre_mt=None): if ent is None: return try: - umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid)) + umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid), + _split_remap_by_uw(sc, sid).get(uw_id)) except Exception: with _QLOCK: _QCACHE.pop(key, None) diff --git a/CostReview/app/core/export_cos.py b/CostReview/app/core/export_cos.py index 13700e3..f6deca2 100644 --- a/CostReview/app/core/export_cos.py +++ b/CostReview/app/core/export_cos.py @@ -855,16 +855,32 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None): return t + pre + region + post + close -def _norm_qty_total(blk, q, t): - """Norm 开标签 Quantity/Total 回灌(统一函数,2026-11-07:原 _norm_out 与新增清单壳块 +def _norm_qty_total(blk, q, t, pp=None, price_attrs=("Price",)): + """Norm 开标签 Quantity/Total/Price 回灌(统一函数,2026-11-07:原 _norm_out 与新增清单壳块 通道各持一份同款正则,改口径漏一处即分叉——并轨)。q/t 传最终串(空串=清空); - 块里没有该属性则不动(不凭空造槽)。""" + 块里没有该属性则不动(不凭空造槽)。 + 决策322(2026-11-14 主人拍板例1「原后缀件定额单价随链写新值」):pp=库值单价串 + (None=不碰);price_attrs=标签层适配(cos/ESCC=Price、SWT=Rate)。**值没变不写** + (最小差异,未动定额保持块原文一字不动;单价 2 位口径同 244 补六)。""" if re.search(r']*?\sQuantity="', blk): blk = re.sub(r'(]*?)\sQuantity="[^"]*"', lambda mo: mo.group(1) + ' Quantity="%s"' % q, blk, count=1) if re.search(r']*?\sTotal="', blk): blk = re.sub(r'(]*?)\sTotal="[^"]*"', lambda mo: mo.group(1) + ' Total="%s"' % t, blk, count=1) + if pp is not None: + for _a in price_attrs: + _m = re.search(r']*?\s%s="([^"]*)"' % _a, blk) + if _m is None: + continue + try: + _same = abs(float(_m.group(1) or 0) - float(pp or 0)) < 0.005 + except (TypeError, ValueError): + _same = False + if not _same: + blk = re.sub(r'(]*?)\s%s="[^"]*"' % _a, + lambda mo, _a=_a: mo.group(1) + ' %s="%s"' % (_a, pp), blk, count=1) + break return blk @@ -951,7 +967,7 @@ def _swt_rid_map(txt, s, end): def _res_price_edits(txt, price_updates, *, price_attr, total_attr, code_attr="Code", - qty_attr="Quantity", fmt=None): + qty_attr="Quantity", fmt=None, base=0): """G-1 修(决策 288 补记十,落实决策 285「改价随链落汇总区、不留第二期」): ESCC/SWT 的工料机汇总行(ResourceItem)价格回写——Code∈price_updates(改价/合并 已登记 merged_codes,与 cos 的 transform_unit_summaries 同一数据源)的行: @@ -986,7 +1002,7 @@ def _res_price_edits(txt, price_updates, *, price_attr, total_attr, code_attr="C except (TypeError, ValueError): continue if newtag != tag: - edits.append((m.start(), m.end(), newtag)) + edits.append((base + m.start(), base + m.end(), newtag)) return edits @@ -1014,9 +1030,13 @@ def _shell_out(b, shell, appends, res_by_norm, nn_tmpl=None, form_bank=None, anc # cos 块是 Element@Number(决策 284:规则一份,标签每格式适配) _tg, _ca = (("ResElementItem", "ResCode") if " 末尾补 +def _escc_added_lme_edits(txt, u, plan, added_children, added_org=None): + """决策 292:ESCC 采纳新增工料机补源——单位 末尾补 (与源同属性集);有子级时补 。 - 已有同码不重复补;无 /模板则返回空,由导出完整性闸门拦截。""" + 已有同码不重复补;无 /模板则返回空,由导出完整性闸门拦截。 + 2026-11-14(330/331):容器以真实件为准 ``(单数)——旧代码只找 + ``,真件恒不命中(added 通道空转);两种都认。added_org 补原价锚。""" adds = [t for t in (plan.get("added_lme") or []) if t and t[0]] if not adds: return [] seg = txt[u["s"]:u["end"]] close = seg.rfind("") + if close < 0: + close = seg.rfind("") if close < 0: return [] tm = re.search(r']*>', seg) @@ -3230,11 +3324,17 @@ def _escc_added_lme_edits(txt, u, plan, added_children): pf = float(ntp or 0) except (TypeError, ValueError): pf = 0.0 + _og = (added_org or {}).get(code) or () + try: + _orgp = float(_og[0]) if _og and _og[0] is not None else pf + except (TypeError, ValueError): + _orgp = pf tag = _attr_set_has(tmpl, "Code", code) for k, v in (("Name", name), ("Specification", spec), ("Unit", unit), - ("OrgPrice", "%.4f" % pf), ("Price", "%.4f" % pf), - ("Quantity", "%.4f" % qf), - ("OrgTotal", "%.2f" % (qf * pf)), ("Total", "%.2f" % (qf * pf)), + ("OrgPrice", "%.4f" % _orgp), ("Price", "%.4f" % pf), + ("Quantity", "%.4f" % qf), ("Quantity1", "%.4f" % qf), + ("Quantity2", "0.0000"), + ("OrgTotal", "%.2f" % (qf * _orgp)), ("Total", "%.2f" % (qf * pf)), ("Kind", "" if kind is None else str(kind))): tag = _attr_set_has(tag, k, _esc(v)) if tag.rstrip().endswith("/>"): @@ -3254,7 +3354,9 @@ def _escc_added_lme_edits(txt, u, plan, added_children): def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm, recode_ident=None, unit_mig=None, progress=None, price_updates=None, - added_children=None, merged_children=None): + added_children=None, merged_children=None, db_price_updates=None, + db_price_by_uw=None, added_org=None, field_updates=None, + recode_map=None, recode_children=None): """ESCC2.0 散装单文件 xml 导出(决策 283)。 unit_plans 键=(Number,Name)(与 cos 同构);unit_mig={(Number,Name):{旧码:新码}}—— api 侧从 s_lme_uw 现值推导(旧码不在且新码在=该单位整体迁移),归属与导入拆分一致。 @@ -3279,16 +3381,32 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm, plan = unit_plans.get(u["key"]) if plan: _transform_esc_unit(txt, u, plan, res_by_norm, tmpls, edits) - edits += _escc_added_lme_edits(txt, u, plan, added_children) # 决策 292 + edits += _escc_added_lme_edits(txt, u, plan, added_children, added_org) # 决策 292 + # 决策 331:三价按**单位级库值**写回本单位段(源件 ResourceItem 就在单位段内); + # 合并 force 优先,其余码用单位库值(值相同不写由 _res_price_edits 数值比较兜住)。 + _up = dict(price_updates or {}) + for _c, _p in ((db_price_by_uw or {}).get(u["key"]) or {}).items(): + _up.setdefault(_c, _p) + if _up: + edits += _res_price_edits(txt[u["s"]:u["end"]], _up, price_attr="Price", + total_attr="Total", fmt=lambda v: "%.2f" % float(v), + base=u["s"]) if progress: progress(i + 1, len(units)) edits += _esc_ident_print(txt, units, unit_mig or {}, recode_ident or {}) # G-1 修(补记十):工料机汇总行价格回写(决策 285 改价随链落汇总区)。 # ESCC 口径(1182 行导入口径反演):Price=除税现价(NoTaxPrice)、Total=量×价 2 位; # OrgPrice/OrgTotal=原价锚不动。逐行编辑,不吞同段拆码改印小编辑。 - edits += _res_price_edits(txt, price_updates or {}, price_attr="Price", total_attr="Total", - fmt=lambda v: "%.2f" % float(v)) - if not edits: + # 2026-11-14 主人定「其余一个逻辑」:项目级 Resource(单位段外)用项目级库值兜底。 + # 单位段内已由上面按单位级库值处理——这里必须**跳过单位段**,否则项目中位价会盖掉单位价。 + if db_price_updates: + _urgs = [(x["s"], x["end"]) for x in units] + for _a, _b, _r in _res_price_edits(txt, db_price_updates, price_attr="Price", + total_attr="Total", fmt=lambda v: "%.2f" % float(v)): + if any(_s <= _a < _e for _s, _e in _urgs): + continue + edits.append((_a, _b, _r)) + if not edits and not field_updates: integrity.validate_escc(txt, where=out_name) # 决策 292:源样也过闸 return src_bytes, out_name # 无动作:字节级一模一样 # 应用(升序扫;同起点大块优先=整块替换/删除在前,落其内的小改写自然丢弃——同点插入按收集序) @@ -3305,6 +3423,8 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm, for _c, _kids in (merged_children or {}).items(): if _c and _kids: _out_text = _escc_replace_children(_out_text, _c, _kids) + _out_text = _apply_res_fields(_out_text, field_updates, "Specification") + _out_text = _apply_res_recode_esc(_out_text, recode_map, recode_children) integrity.validate_escc(_out_text, where=out_name) # 决策 292:成品引用完整性 return _encode(_out_text, enc), out_name @@ -3340,8 +3460,8 @@ def _scan_swt_units(txt): def _scan_swt_bills(txt, s, end): - """单位内清单块。顺序=parse 推送序:先 BQItem(doc 序)后 MeasureItem 叶(doc 序)—— - MeasureItem 父节点(内含子 MeasureItem)是分部,跳过。""" + """单位内清单块:只有 (分部分项/措施同块、文档序)。 + MeasureItem 是**不可编辑区域**(类似分部),不参与配对/整形(2026-11-14 主人定)。""" marks = [] for m in re.finditer(r' end: continue marks.append({"s": gs, "e": e, "end": ce + 9, "opentag": txt[gs:e], "kind": "item"}) - for m in re.finditer(r' end: - continue - if txt[e - 2:e] == "/>": # 自闭合=叶子清单(解析 start/end 立即配对=has_child False) - marks.append({"s": gs, "e": e, "end": e, "opentag": txt[gs:e], "kind": "prelim"}) - continue - ce = txt.find('', e) - if ce < 0 or ce + 14 > end: - continue - if ' 0 else tmpl @@ -3622,32 +3733,56 @@ def _swt_recalc_unit(txt, u, plan, edits): for sp, b in (plan.get("pairs") or {}).get(kind) or []: src_pairs.append((kind, b)) src_pairs.sort(key=lambda x: x[1]["id"]) - prelim_pairs = [b for kind, b in src_pairs if kind == "prelim"] - pm = [mk for mk in _scan_swt_bills(txt, u["s"], u["end"]) if mk["kind"] == "prelim"] - leaf_pos, leaf_val, leaf_nm = [], [], [] - if len(prelim_pairs) == len(pm): - for b, mk in zip(prelim_pairs, pm): - leaf_pos.append(mk["s"]) - leaf_val.append(0.0 if b["x_tdel"] else _tv(b["Total"])) - leaf_nm.append(_swt_name_norm(_attr(mk["opentag"], "Name"))) - measure_total = sum(leaf_val) - by_name = dict(zip(leaf_nm, leaf_val)) - for b in (plan.get("news") or {}).get("prelim") or []: - measure_total += _tv(b.get("Total")) - by_name[_swt_name_norm(b.get("Name"))] = _tv(b.get("Total")) - # 父级容器(真开闭且内含子 MeasureItem):Total=Σ内含叶现值 - for m in re.finditer(r'": + seg = txt[u["s"]:u["end"]] + # 措施:MeasureItem=**不可编辑区域**(类似分部,2026-11-14 主人定)—— + # 叶子有 BQItem 子项 → Total=Σ子清单现值;无子项(费率型)→ 保源值; + # 父区域=Σ子区域;B 汇总=顶层区域合计。 + newtot = {} + for kind, b in src_pairs: + if not b["x_tdel"]: + newtot[str(b.get("Number") or "")] = _tv(b["Total"]) + for kind in ("item", "prelim"): + for b in (plan.get("news") or {}).get(kind) or []: + newtot[str(b.get("Number") or "")] = _tv(b.get("Total")) + nodes, stack = [], [] + for m in re.finditer(r']*>|', seg): + if m.group(0).startswith("") continue - ce = txt.find('', e) - if ce < 0 or ']*>', txt[node["e"]:node["end"]]): + code = _attr(bm.group(0), "Code") + if code in newtot: + tot = (tot or 0.0) + newtot[code] + if tot is None: + tot = _tv(_attr(node["ot"], "Total")) + return round(tot, 2) + + measure_total = 0.0 + by_name = {} + for node in nodes: + val = _mtot(node) + if not _num_eq(_attr(node["ot"], "Total"), val): + edits.append((node["s"], node["e"], + _attr_set(node["ot"], "Total", _swt_num(val)))) + if node["parent"] is None: + measure_total += val + by_name[_swt_name_norm(_attr(node["ot"], "Name"))] = val bq_total = sum(_tv(b["Total"]) for kind, b in src_pairs if kind == "item" and not b["x_tdel"]) for b in (plan.get("news") or {}).get("item") or []: @@ -3728,8 +3863,178 @@ def _swt_ident_print(txt, units, unit_mig): return edits +def _del_elem(txt, tag, attr, value): + """删一个完整元素(自闭合或成对;ResourceItem/ResElement 不嵌套同名)。""" + pat = re.compile(r'<%s\b[^>]*\b%s="%s"[^>]*>' % (tag, attr, re.escape(str(value)))) + while True: + m = pat.search(txt) + if not m: + return txt + end = m.end() + if not m.group(0).rstrip().endswith("/>"): + close = txt.find("" % tag, end) + if close < 0: + return txt + end = close + len("" % tag) + txt = txt[:m.start()] + txt[end:] + + +def _apply_res_recode_esc(txt, recode_map, recode_children=None): + """ESCC 合并收码:消耗引用 ResCode 旧→保留,旧 ResourceItem 整行删除; + 保留行子级按 recode_children 重建。""" + for old, keep in (recode_map or {}).items(): + if not old or not keep or old == keep: + continue + txt = re.sub(r'(]*?\bResCode=")%s(")' % re.escape(str(old)), + lambda m: m.group(1) + str(keep) + m.group(2), txt) + txt = _del_elem(txt, "ResourceItem", "Code", old) + for old, kids in (recode_children or {}).items(): + keep = (recode_map or {}).get(old) + if keep and kids: + txt = _escc_replace_children(txt, keep, kids) + return txt + + +def _swt_replace_children(txt, code, kids, code2rid): + """SWT 保留码子级按库值整组重建:。 + 显示端无子级(kids 空)→ 剥子级,与显示端一致(同 cos/ESCC 口径)。""" + m = re.search(r']*\bCode="%s"[^>]*>' % re.escape(str(code)), txt) + if not m: + return txt + open_end = m.end() + body = "" + for c, q in (kids or []): + rid = code2rid.get(str(c)) + if rid is None: + continue + body += '' % (int(rid), _swt_num(q)) + if m.group(0).rstrip().endswith("/>"): + new_open = m.group(0).rstrip()[:-2] + ">" + return txt[:m.start()] + new_open + body + "" + txt[open_end:] + close = txt.find("", open_end) + if close < 0: + return txt + return txt[:open_end] + body + txt[close:] + + +def _apply_res_recode_swt(txt, recode_map, rid_map=None, recode_children=None): + """SWT 合并收码:ResourceID 旧→保留(消耗引用与组成引用一起转),旧 ResourceItem 删除。""" + code2rid = {} + for m in re.finditer(r']*>', txt): + tag = m.group(0) + c, r = _attr(tag, "Code"), _attr(tag, "ResourceID") + if c and r and c not in code2rid: + try: + code2rid[c] = int(r) + except ValueError: + pass + for _c, _r in (rid_map or {}).items(): + if _r is not None: + code2rid.setdefault(_c, int(_r)) + for old, keep in (recode_map or {}).items(): + if not old or not keep or old == keep: + continue + _or, _kr = code2rid.get(old), code2rid.get(keep) + if _or is not None and _kr is not None and _or != _kr: + txt = re.sub(r'(ResourceID=")%d(")' % _or, + lambda m: m.group(1) + str(_kr) + m.group(2), txt) + txt = _del_elem(txt, "ResourceItem", "Code", old) + for code, kids in (recode_children or {}).items(): + if code in code2rid: + txt = _swt_replace_children(txt, code, kids, code2rid) + return txt + + +def _apply_res_fields(txt, field_updates, spec_attr="Specification"): + """P1-③(2026-11-14):工料机名称/规格/单位行内编辑回写——只改登记过的码, + 只在属性已存在时改(骨架无槽不造),不改编码。放在所有编辑拼装完之后做, + 避免与同标签的价格/改印编辑抢 span。""" + if not field_updates: + return txt + def _rep(m): + tag = m.group(0) + code = _attr(tag, "Code") + if code not in field_updates: + return tag + nm, sp, un = field_updates[code] + new = tag + for attr, val in (("Name", nm), (spec_attr, sp), ("Unit", un)): + if val is not None and _attr(new, attr) is not None: + new = _attr_set(new, attr, _esc(val)) + return new + return re.sub(r']*>', _rep, txt) + + +def _swt_added_lme_edits(txt, units, unit_plans, added_children=None): + """P1-②(2026-11-14 主人拍板 331/332):SWT 采纳新增工料机补源。 + ResourceItem 容器可能在单位段内(``)也可能在根上(``); + 这里按**全文件**补一次:所有单位 plan 的 added_lme 合并,码→资源ID 由 plan["rid_map"] 给。""" + adds, rid_map = [], {} + for _u in units: + _p = (unit_plans or {}).get(_u["key"]) or {} + rid_map.update(_p.get("rid_map") or {}) + for t in (_p.get("added_lme") or []): + if t and t[0]: + adds.append(t) + if not adds: + return [] + close = txt.rfind("") + if close < 0: + close = txt.rfind("") + if close < 0: + return [] + tm = re.search(r']*>', txt) + if not tm: + return [] + tmpl = tm.group(0).strip() + have = set(re.findall(r']*?\bCode="([^"]*)"', txt)) + blocks, seen = [], set() + for t in adds: + code = str(t[0]) + if code in have or code in seen: + continue + seen.add(code) + rid = rid_map.get(code) + if rid is None: + continue # 无 ID 补不了(应重导/重采纳) + try: + qf = float(t[4] or 0) + except (TypeError, ValueError): + qf = 0.0 + rate = t[7] if len(t) > 7 and t[7] is not None else (t[6] if len(t) > 6 else None) + try: + rf = float(rate or 0) + except (TypeError, ValueError): + rf = 0.0 + tag = _attr_set_has(tmpl, "ResourceID", str(int(rid))) + for k, v in (("Code", code), ("Name", t[1] if len(t) > 1 else ""), + ("Spec", t[2] if len(t) > 2 else ""), + ("Unit", t[3] if len(t) > 3 else ""), + ("Rate", _swt_num(rf)), ("Quantity", "%.4f" % qf), + ("Total", "%.2f" % (qf * rf)), + ("CostKind", "" if t[8] is None else str(t[8])), + ("StandardCode", code)): + tag = _attr_set_has(tag, k, _esc(v)) + if tag.rstrip().endswith("/>"): + tag = tag.rstrip()[:-2] + ">" + kids = (added_children or {}).get(code) or [] + body = "" + for c, q in kids: + cr = rid_map.get(str(c)) + if not c or cr is None: + continue + body += '' % (int(cr), _swt_num(q)) + tag = tag + body + "" + blocks.append(tag) + if not blocks: + return [] + return [(close, close, "".join(blocks))] + + def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm, - recode_ident=None, unit_mig=None, progress=None, price_updates=None): + recode_ident=None, unit_mig=None, progress=None, price_updates=None, + db_price_updates=None, db_price_by_uw=None, added_children=None, + field_updates=None, recode_map=None, recode_children=None): """SWT/SWZ 原格式导出(决策 284:并入手术引擎)。.SWZ=zip 包(内装 ConstructProject xml)——解包手术该成员、其余条目字节原样回包。无动作且无拆码改印 → 原件字节直出。 price_updates=改价/合并码价表(决策 288 补记十 G-1 修:改价随链落 ResourceItem, @@ -3770,15 +4075,30 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm, _swt_recalc_unit(txt, u, plan, edits) # 汇总区一体(决策 285) except Exception: pass # 现算失败不挡导出(fail-open,原件汇总值保底) + # 决策 331:三价按单位级库值写回本单位段(ResourceItem 在 UnitProject 内) + _up = dict(price_updates or {}) + for _c, _p in ((db_price_by_uw or {}).get(u["key"]) or {}).items(): + _up.setdefault(_c, _p) + if _up: + edits += _res_price_edits(txt[u["s"]:u["end"]], _up, price_attr="Rate", + total_attr="Total", fmt=_swt_num, base=u["s"]) if progress: progress(i + 1, len(units)) + # P1-②:采纳新增工料机补 (块内 ResourceID 已在采纳时重分配) + edits += _swt_added_lme_edits(txt, units, unit_plans, added_children) edits += _swt_ident_print(txt, units, unit_mig or {}) # G-1 修(补记十):工料机汇总行价格回写(决策 285 改价随链落汇总区)。 # SWT 口径A(122):Rate=含税=除税——改价的 taxp(空则 ntp)写回 Rate、Total=量×Rate。 - # 逐行编辑,不吞同段拆码改印小编辑。 - edits += _res_price_edits(txt, price_updates or {}, price_attr="Rate", total_attr="Total", - fmt=_swt_num) - if not edits: + # 逐行编辑,不吞同段拆码改印小编辑。项目级(单位段外)用项目级库值兜底(决策 331): + # 单位段内已按单位级库值处理,这里跳过单位段,防止项目值盖掉单位价。 + if db_price_updates: + _urgs = [(x["s"], x["end"]) for x in units] + for _a, _b, _r in _res_price_edits(txt, db_price_updates, price_attr="Rate", + total_attr="Total", fmt=_swt_num): + if any(_s <= _a < _e for _s, _e in _urgs): + continue + edits.append((_a, _b, _r)) + if not edits and not field_updates: integrity.validate_swt(txt, where=out_name) # 决策 292 return src_bytes, out_name # 无动作:字节级一模一样 edits.sort(key=lambda x: (x[0], -(x[1] - x[0]))) @@ -3791,6 +4111,13 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm, cursor = e0 out.append(txt[cursor:]) _swt_text = "".join(out) + _swt_text = _apply_res_fields(_swt_text, field_updates, "Spec") + _rid_all = {} + for _p in (unit_plans or {}).values(): + for _c, _r in (_p.get("rid_map") or {}).items(): + if _r is not None: + _rid_all.setdefault(_c, _r) + _swt_text = _apply_res_recode_swt(_swt_text, recode_map, _rid_all, recode_children) integrity.validate_swt(_swt_text, where=out_name) # 决策 292 new_body = _encode(_swt_text, enc) if not member: diff --git a/CostReview/app/core/import_job.py b/CostReview/app/core/import_job.py index 8c041a6..c1be3ce 100644 --- a/CostReview/app/core/import_job.py +++ b/CostReview/app/core/import_job.py @@ -27,7 +27,7 @@ REGION = ("广东省", "珠海市", "香洲区") # 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。 # 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。 # 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。 -PARSER_VER = "2026.11.12-1" # 2026.11.12-1:清单类别 x_cat 采集(cos=CalcType 原值,esc/swt 无标记=NULL;2026-11-12 主人定「按类别:清单」——直接条目也按清单归类,原值只留数据层;老会话重解析回填);2026.11.07-2:其他项目明细容器子树入库(detgrp/detitem+Content/x_parent/x_lv,其他项目卡把手展开用,2026-11-07 主人定「282 补」);2026.11.07-1:项目级「措施项目/其他项目」卡源数据入库(PIC.Preliminaries / PIC.Sundry 原样,老会话重解析后显示);2026.11.04-1:清单 x_ptag 采集(措施清单原生标签 WorkElement / UnitWorksPreliminaryWorkElement,导出按原形态还原;老批次需重导);-2026.11.03-4:项目级非数据层 x_side;-3:单位工程 x_attr;-2:清单/定额 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259) +PARSER_VER = "2026.11.14-1" # 2026.11.14-1:决策 329 三价归一(norm_price3,全格式)+ 决策 330 块标签 x_ptag 全格式采集(ESCC=Bill、SWT=BQItem/MeasureItem;取块不再回退 COS 标签);2026.11.12-1:清单类别 x_cat 采集(cos=CalcType 原值,esc/swt 无标记=NULL;2026-11-12 主人定「按类别:清单」——直接条目也按清单归类,原值只留数据层;老会话重解析回填);2026.11.07-2:其他项目明细容器子树入库(detgrp/detitem+Content/x_parent/x_lv,其他项目卡把手展开用,2026-11-07 主人定「282 补」);2026.11.07-1:项目级「措施项目/其他项目」卡源数据入库(PIC.Preliminaries / PIC.Sundry 原样,老会话重解析后显示);2026.11.04-1:清单 x_ptag 采集(措施清单原生标签 WorkElement / UnitWorksPreliminaryWorkElement,导出按原形态还原;老批次需重导);-2026.11.03-4:项目级非数据层 x_side;-3:单位工程 x_attr;-2:清单/定额 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259) # LME_SUM 行的文字/标志属性集(2026-11-02 主人定「原文件有按原文件导,没有则不导出」): # 数值属性(量/价/合价)另有专列,不在此列;Remark 属数据性质备注,一并按原文件采。 @@ -63,6 +63,34 @@ def f(x): return None +def norm_price3(ntp, taxp, taxrate): + """决策 329(2026-11-14 主人定):编制价三件套全后缀归一——任何格式恒有 + 除税编制价/含税编制价/税率,源件缺则:无税率→0、只有一侧价→另一侧=该价; + 两价俱在且不等、税率缺 → 反算税率(保住源值,不硬抹平)。 + 返回 (ntp, taxp, taxrate);三值全缺 → (None, None, None)。""" + try: + ntp = None if ntp is None else float(ntp) + taxp = None if taxp is None else float(taxp) + tr = None if taxrate is None else float(taxrate) + except (TypeError, ValueError): + return (ntp, taxp, taxrate) + if ntp is None and taxp is None: + return (None, None, tr) + if tr is not None: + if ntp is None: + ntp = round(taxp / (1 + tr / 100.0), 4) if taxp is not None and tr != -100 else taxp + if taxp is None: + taxp = round(ntp * (1 + tr / 100.0), 4) + return (ntp, taxp, tr) + if ntp is None: + return (taxp, taxp, 0.0) + if taxp is None: + return (ntp, ntp, 0.0) + if abs(taxp - ntp) < 1e-9: + return (ntp, taxp, 0.0) + return (ntp, taxp, round((taxp / ntp - 1) * 100.0, 2) if ntp else 0.0) + + def unit_prefix(unit): """定额单位的**数字前缀**('10m'→10.0、'1000m3天然密实方'→1000.0、't'→1.0)—— GCL(清单量÷前缀)与工程量系数(定额量÷历史GCL)共用的同一把尺 @@ -263,10 +291,24 @@ def _natkey(s): # 只差标签层声明属性名;cos CalcType:"1"=清单、"3"=直接条目,两类都按清单归类显示)。 BLOCK_FMT = { "cos": {"bills": ("WorkElement", "UnitWorksPreliminaryWorkElement"), "norm": "Norm", - "pseudo_norm": True, "order": "doc", "cat": "CalcType"}, - "esc": {"bills": ("Bill",), "norm": "Norm", "pseudo_norm": False, "order": "doc"}, + "pseudo_norm": True, "order": "doc", "cat": "CalcType", "id_attr": "Number"}, + "esc": {"bills": ("Bill",), "norm": "Norm", "pseudo_norm": False, "order": "doc", + "id_attr": "Code"}, "swt": {"bills": ("BQItem", "MeasureItem"), "norm": "NormItem", - "pseudo_norm": False, "order": "swt_push"}, + "pseudo_norm": False, "order": "swt_push", "id_attr": "Code"}, +} +# 330:清单块/定额块标签与后缀族基本一一对应——优先按族**写死查表**, +# 只有老批次无 x_ptag 时才退到"全表逐族试"(不再用无约束的通用正则硬猜)。 +_BLOCK_TAG_FMT = {t: k for k, cfg in BLOCK_FMT.items() for t in cfg["bills"]} +_BLOCK_OPEN = { # (tag, attr) 组合全表:Block 开标签 + 身份属性 + "cos": [("WorkElement", "Number"), ("UnitWorksPreliminaryWorkElement", "Number")], + "esc": [("Bill", "Code")], + "swt": [("BQItem", "Code"), ("MeasureItem", "Code")], +} +_NORM_OPEN = { + "cos": [("Norm", "Number")], + "esc": [("Norm", "Code")], + "swt": [("NormItem", "Code")], } @@ -284,9 +326,8 @@ def extract_blocks(txt, fmt="cos"): """决策 279(块进块出)/ 285(一个整体一个逻辑):从 xml 原文切清单壳块/定额块原文—— **全格式同一份逻辑,格式只差 BLOCK_FMT 标签配置**(改这里=全格式生效)。 bills_blocks = [块原文...](壳块含定额段);norms_blocks = [块原文...] - 对齐:块序=解析推送序——cos/ESCC=文档序;SWT=BQItem 见即推(键=自身位置)、 - 措施叶 MeasureItem 在所属 处统一推(键=表尾,与 parse_swt 的 - flush_measures 同款),父节点(块内还有子 MeasureItem=分部)不是清单不切。 + 对齐:块序=解析推送序——cos/ESCC=文档序;SWT=BQItem 文档序(措施区清单也是 + BQItem;MeasureItem 是不可编辑区域/分部,不切块)。 cos 专属口径:伪定额(Number 纯数字且 Unit="元")不存,与 skip_res_norm 同口径。""" cfg = BLOCK_FMT[fmt] nt = cfg["norm"] @@ -306,29 +347,17 @@ def extract_blocks(txt, fmt="cos"): norms_blocks.append(txt[m.start():e + len(nt) + 3]) bills_blocks = [] if cfg["order"] == "swt_push": - keyed = [] # (推序键, 块起位, 标签) + # 2026-11-14 主人定:SWT 清单块只有 (分部分项/措施同块);MeasureItem 是 + # 不可编辑区域(类似分部),不切块、不进 s_bills。块序=文档序=解析推送序。 for m in re.finditer(r']*>', txt): - keyed.append((m.start(), m.start(), "BQItem")) - for m in re.finditer(r']*>', txt): - te = txt.find('', m.end()) - if te < 0: - te = len(txt) - for m2 in re.finditer(r']*>', txt[m.end():te]): - keyed.append((te, m.end() + m2.start(), "MeasureItem")) - keyed.sort(key=lambda x: (x[0], x[1])) - for _k, gs, tag in keyed: - e = txt.find('>', gs) - if e < 0: + gs, e = m.start(), m.end() + if txt[e - 1] == "/": # 自闭合:块=开标签本身 + bills_blocks.append(txt[gs:e]) continue - if txt[e - 1] == "/": # 自闭合:块=开标签本身(解析同样推送) - bills_blocks.append(txt[gs:e + 1]) - continue - close = txt.find('' % tag, e) + close = txt.find('', e) if close < 0: continue - if tag == "MeasureItem" and '')]) else: pat = "|".join(re.escape(t) for t in cfg["bills"]) for m in re.finditer(r'<(%s)\b[^>]*>' % pat, txt): @@ -506,12 +535,16 @@ def parse_std(path, out): _c = (sm.attrib.get("Number") or "").strip() if not _c: continue + # 决策 329:三价归一(COS 一般三价齐全;缺项按统一规则补,不按格式另写) + _pn, _pt, _pr = norm_price3(f(sm.attrib.get("NoTaxPrice")), + f(sm.attrib.get("TaxPrice")), + f(sm.attrib.get("TaxRate"))) out.setdefault("lme_lib", {}).setdefault(_c, [ (sm.attrib.get("Name") or "").strip(), (sm.attrib.get("Specification") or "").strip(), (sm.attrib.get("Unit") or "").strip(), f(sm.attrib.get("Kind")), - f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))]) + _pn, _pt]) # 决策 69(批次C):lme_proj 增采 TaxRate——合并工料机弹框的「税率」字段要真值 # (此前认为源汇总节点无此属性,实测有:横琴 0、南屏 16.52 等都能采到) out.setdefault("lme_proj", {}).setdefault(_c, [ @@ -520,8 +553,7 @@ def parse_std(path, out): (sm.attrib.get("Unit") or "").strip(), f(sm.attrib.get("Kind")), f(sm.attrib.get("Quantity")), - f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice")), - f(sm.attrib.get("TaxRate")), + _pn, _pt, _pr, # 决策 183(2026-10-23 主人定):整套按骨架——六价全采,回填按属性一一对应 f(sm.attrib.get("NoTaxOrgPrice")), f(sm.attrib.get("NoTaxPriceExpress")), f(sm.attrib.get("TaxOrgPrice")), f(sm.attrib.get("TaxPriceExpress"))]) @@ -846,10 +878,12 @@ def parse_std(path, out): # 费用科目(折旧费 / 维护费 / 人工费…)2026-10-07 起也**照收入库**: # 主人定「导入不过滤」,与工作台同口径,原 FEE_ITEMS 过滤随之废除 # (工作台「项目工料机」本就原样显示 s_lmes,含费用科目行——两侧恰好一致)。 + _pn, _pt, _pr = norm_price3(f(a.get("NoTaxPrice")), f(a.get("TaxPrice")), + f(a.get("TaxRate"))) # 329:三价归一 out["lmes"].append(( a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""), - a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")), - f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or ""))) + a.get("Unit", ""), _pn, _pr, _pt, + f(a.get("Quantity")), str(a.get("Kind") or ""))) # 2026-10-11 决策 41:各单位工程**自己的汇总节点**按单位工程归属另存一份 # (cur_uw=本文件的单位工程,文件级已重置、UnitWorks start 即定——归属可靠), # 「原数据·单位工程级工料机汇总」直接读它(名称/规格/总数量/单价=源文件原样, @@ -858,8 +892,8 @@ def parse_std(path, out): if _st: out.setdefault("lme_uw", []).append(( _st[-1], a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""), - a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")), - f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or ""), + a.get("Unit", ""), _pn, _pr, _pt, + f(a.get("Quantity")), str(a.get("Kind") or ""), # 决策 183:六价全采(属性级对应回填) f(a.get("NoTaxOrgPrice")), f(a.get("NoTaxPriceExpress")), f(a.get("TaxOrgPrice")), f(a.get("TaxPriceExpress")), @@ -945,22 +979,17 @@ def parse_swt(path, out): return idx def flush_measures(): - # MeasureItem 既可分组也可叶子:有子项=分部(s_divides),无子项=措施清单(Kind='prelim') + # 2026-11-14 主人定:MeasureItem 是**不可编辑区域**(类似分部),不是清单—— + # 措施区真正的清单是它里面/措施表里的 。MeasureItem 一律落 s_divides(prelim)。 for node in st["measure_nodes"]: a = node["attrs"] parent = node["parent"]["div"] if node["parent"] else node["title"] - if node["has_child"]: - node["div"] = add_divide("prelim", a.get("Code", ""), a.get("Name", ""), - f(a.get("Total")), None, parent) - else: - tot = f(a.get("Total")) - out["bills"].append((a.get("Code", ""), a.get("Name", ""), - a.get("Remark", "") or "", (a.get("Unit") or "").strip(), - 1.0, tot, tot, (a.get("Remark") or "").strip())) - out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1) - out.setdefault("bill_kind", []).append("prelim") - out.setdefault("bill_cat", []).append(_bill_cat(a, "swt")) # 清单类别(无标记=NULL) - out.setdefault("bill_div", []).append(parent) + node["div"] = add_divide("prelim", a.get("Code", ""), a.get("Name", ""), + f(a.get("Total")), None, parent) + # 措施里嵌的 BQItem 才是措施清单块;其归属分部在 flush 时才拿到,回填 bill_div + for _bi in node.get("bill_idx") or (): + if 0 <= _bi < len(out.get("bill_div") or []): + out["bill_div"][_bi] = node["div"] st["measure_nodes"] = [] st["measure_stack"] = [] @@ -985,20 +1014,28 @@ def parse_swt(path, out): qty = f(r.get("Quantity")) # 主人定 A(2026-10-19,决策 122 恢复;覆盖决策 121 的 B): # SWT 只有一个 Rate(不含税预算价)→ 除税价=含税价=Rate、税率=0。 - out["lmes"].append((code, nm, sp, un, rate, 0.0, rate, qty, kd)) - out["lme_uw"].append((u["idx"], code, nm, sp, un, rate, 0.0, rate, qty, kd, + # 决策 329:三价归一收口到 norm_price3(单侧价 → 两侧同值、税率 0)。 + _pn, _pt, _pr = norm_price3(rate, None, None) + out["lmes"].append((code, nm, sp, un, _pn, _pr, _pt, qty, kd)) + out["lme_uw"].append((u["idx"], code, nm, sp, un, _pn, _pr, _pt, qty, kd, None, None, None, None)) # SWT 无六价源(决策 122:Rate 同值) - out["lme_lib"][code] = [nm, sp, un, kd, rate, rate] + # P1-②:源件资源内部 ID(NormResUsageItem@ResourceID 的落库槽,采纳/导出重分配用) + try: + _rid = int(str(r.get("ResourceID")).strip()) + except (TypeError, ValueError): + _rid = None + out.setdefault("lme_uw_rid", []).append(_rid) + out["lme_lib"][code] = [nm, sp, un, kd, _pn, _pt] out["lme_name"][code] = nm p = out["lme_proj"].get(code) if p is None: - out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, rate, rate, 0.0] + out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, _pn, _pt, _pr] else: p[4] = (p[4] or 0.0) + (qty or 0.0) if rate is not None: - p[5] = rate # 除税价 - p[6] = rate # 含税价(A:与除税价同值) - p[7] = 0.0 # 税率(A:0) + p[5] = _pn # 除税价 + p[6] = _pt # 含税价(A:与除税价同值) + p[7] = _pr # 税率(A:0) # 台班/配合比的下一级组成:同编码只收第一份(组成是标准值,各单位工程重复声明) for r in u["resources"]: pcode = (r.get("Code") or "").strip() @@ -1100,15 +1137,22 @@ def parse_swt(path, out): a.get("BQTitleID"), parent)) elif tag == "BQItem": idx = len(out["bills"]) + _in_meas = bool(st["measure_stack"]) # 措施区里嵌的 BQItem=措施清单(2026-11-14 主人示) out["bills"].append((a.get("Code", ""), a.get("Name", ""), a.get("Feature", ""), (a.get("Unit") or "").strip(), f(a.get("Quantity")), f(a.get("Rate")), f(a.get("Total")), (a.get("Remark") or "").strip())) out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1) - out.setdefault("bill_kind", []).append(None) + out.setdefault("bill_kind", []).append("prelim" if _in_meas else None) out.setdefault("bill_cat", []).append(_bill_cat(a, "swt")) # 清单类别(无标记=NULL) - out.setdefault("bill_div", []).append( - st["title_stack"][-1] if st["title_stack"] else None) + out.setdefault("bill_tag", []).append("BQItem") # 330:原生块标签 + out.setdefault("bill_div", []).append(None) + if _in_meas: + _node = st["measure_stack"][-1] + _node["has_child"] = True # 外层 MeasureItem 是容器,不是清单 + _node.setdefault("bill_idx", []).append(idx) + else: + out["bill_div"][-1] = (st["title_stack"][-1] if st["title_stack"] else None) st["cur_bill"] = idx st["cur_norm"] = -1 elif tag == "NormItem": @@ -1251,6 +1295,7 @@ def parse_esc(path, out): out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1) out.setdefault("bill_kind", []).append(kind) out.setdefault("bill_cat", []).append(_bill_cat(a, "esc")) # 清单类别(无标记=NULL) + out.setdefault("bill_tag", []).append("Bill") # 330:原生块标签 out.setdefault("bill_div", []).append( (st["mdiv_stack"][-1] if st["mdiv_stack"] else None) if kind == "prelim" else (st["div_stack"][-1] if st["div_stack"] else None)) @@ -1363,24 +1408,26 @@ def parse_esc(path, out): qty = f(a.get("Quantity")) nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip() kd = (a.get("Kind") or "").strip() or None - out["lmes"].append((code, nm, sp, un, price, 0.0, price, qty, kd)) - out["lme_uw"].append((st["unit"]["idx"], code, nm, sp, un, price, 0.0, - price, qty, kd, None, None, None, None)) + _pn, _pt, _pr = norm_price3(price, None, None) # 329:单侧价→两侧同值、税率0 + out["lmes"].append((code, nm, sp, un, _pn, _pr, _pt, qty, kd)) + out["lme_uw"].append((st["unit"]["idx"], code, nm, sp, un, _pn, _pr, + _pt, qty, kd, None, None, None, None)) elif st["unit"] is None: # 项目级 Resource 价格表 → lme_lib/lme_proj(决策 122 A:除税=含税=Price) price, org = f(a.get("Price")), f(a.get("OrgPrice")) qty = f(a.get("Quantity")) nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip() kd = (a.get("Kind") or "").strip() or None + _pn, _pt, _pr = norm_price3(price, None, None) # 329 out["lme_lib"].setdefault(code, [nm, sp, un, kd, org, price]) out["lme_name"].setdefault(code, nm) p = out["lme_proj"].get(code) if p is None: - out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, price, price, 0.0] + out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, _pn, _pt, _pr] else: p[4] = (p[4] or 0.0) + (qty or 0.0) - p[5] = price - p[6] = price + p[5] = _pn + p[6] = _pt elif tag == "Resource": st["_uw_res"] = st["unit"] is not None # 区分项目级/单位级 Resource 容器 elif tag == "Summary": @@ -1548,29 +1595,44 @@ def _block_maps(out): # 壳块标签与 x_ptag 一致、壳块有足够 Norm 槽(源有定额时)。 # --------------------------------------------------------------------------- _SHA64_RE = re.compile(r'^([0-9a-f]{64})(?:_|$)') -_BLK_OPEN_RE = re.compile( - r'<(WorkElement|UnitWorksPreliminaryWorkElement)\b[^>]*?\bNumber="([^"]*)"', re.S) -_NORM_OPEN_RE = re.compile(r']*?\bNumber="([^"]*)"', re.S) - - +# 决策 330(2026-11-14):块/定额开标签按**块族**参数化,不再写死 COS 标签—— +# cos=WorkElement/UnitWorksPreliminaryWorkElement+Number、ESCC=Bill+Code、 +# SWT=BQItem/MeasureItem/NormItem+Code;取块只认块自己的标签(x_ptag 同源)。 def _sha_part(s): m = _SHA64_RE.match((s or "").strip()) return m.group(1) if m else None -def block_open_number(xml): - """块开标签 → (tag, Number);不是清单块 → (None, None)。""" - m = _BLK_OPEN_RE.search(xml or "") - return (m.group(1), m.group(2)) if m else (None, None) +def _open_id(xml, pairs): + """按 (标签, 身份属性) 精确表取**块首**开标签与编码。 + 必须锚定开头(允许前导空白)——块内可能嵌同名子标签(如 MeasureItem 里嵌 BQItem), + 全文 search 会把子标签当成块自身(实测 SWT (2.1) 被读成 BQItem)。""" + for tag, attr in pairs: + m = re.match(r'\s*<%s\b[^>]*?\b%s="([^"]*)"' % (re.escape(tag), attr), + xml or "", re.S) + if m: + return tag, m.group(1) + return None, None -def norm_open_number(xml): - m = _NORM_OPEN_RE.search(xml or "") - return m.group(1) if m else None +def block_open_number(xml, fmt=None): + """块开标签 → (tag, 编码)。有族=按该族写死表;无族(老批次)=逐族试表。""" + pairs = (_BLOCK_OPEN.get(fmt) if fmt + else [p for v in _BLOCK_OPEN.values() for p in v]) + return _open_id(xml, pairs or []) -def _block_norm_count(xml): - return len(re.findall(r' 0) + btag, bnum = block_open_number(xml or "", _fmt) + if (btag and bnum == b[0] and (not tag or btag == tag) + and (not nn or _block_norm_count(xml or "", _fmt) > 0) and _sha_ok(sha, batch_sha.get(b[3], ""))): keep = rid break @@ -1682,11 +1749,12 @@ def cleanup_block_bank(con): if not n: dead += [r[0] for r in rows] continue - b = con.execute("SELECT batch_id FROM bills WHERE id=?", (n[1],)).fetchone() + b = con.execute("SELECT batch_id, x_ptag FROM bills WHERE id=?", (n[1],)).fetchone() bsha = batch_sha.get(b[0], "") if b else "" + _fmt = _BLOCK_TAG_FMT.get((b[1] if b else "") or "") keep = None for rid, xml, sha in rows: - if norm_open_number(xml or "") == n[0] and _sha_ok(sha, bsha): + if norm_open_number(xml or "", _fmt) == n[0] and _sha_ok(sha, bsha): keep = rid break dead += [rid for rid, _x, _s in rows if rid != keep] @@ -1704,6 +1772,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None): 不传 = 新导入(INSERT 新批次行)。原位路径不动 x_note / x_enabled / x_attach_sha, 也不产生新 id —— sessions.x_batch_id 与 lme_attach 绑定才不至于断链(2026-10-11) """ + # 2026-11-14 P1-②:老库补练——批库 lme_uw 加源件资源内部 ID 槽(SWT 用;幂等) + try: + con.execute("ALTER TABLE lme_uw ADD COLUMN x_rid INTEGER") + except Exception: + pass # 决策 279:块序→块原文 映射(save 内 bills/norms 循环按下标取) out["bill_blocks_map"], out["norm_blocks_map"] = _block_maps(out) ym = int(time.strftime("%Y", time.localtime(mtime))) * 12 + int(time.strftime("%m", time.localtime(mtime))) @@ -2034,25 +2107,81 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None): # 各单位工程自己的工料机汇总(2026-10-11 决策 41):解析时按单位工程归属原样入库, # 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。 n_uwlme = 0 - for _row in (out.get("lme_uw") or []): - k, num, name, spec, unit, ntp, taxrate, taxp, qty, kind = _row[:10] + for _i, _row in enumerate(out.get("lme_uw") or []): + # 决策322 修(2026-11-14):循环变量原叫 kind——把外层批次参数 kind('project'/'market'/'info') + # 遮蔽成工料机种类整数,函数尾部按 kind 分支的代码(322 合计预存/锚列判定)恒走错。改名 _lkind。 + k, num, name, spec, unit, ntp, taxrate, taxp, qty, _lkind = _row[:10] _x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(老结构 len 兼容) + _rid = ((out.get("lme_uw_rid") or [])[_i] + if _i < len(out.get("lme_uw_rid") or []) else None) uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None if not uwid: continue try: cur.execute("""INSERT INTO lme_uw(batch_id, uw_id, code, name, spec, unit, kind, - qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", - (bid, uwid, num, name, spec, unit, kind, qty, ntp, taxrate, taxp) + tuple(_x)) + qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_rid) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + (bid, uwid, num, name, spec, unit, _lkind, qty, ntp, taxrate, taxp) + + tuple(_x) + (_rid,)) n_uwlme += 1 except Exception as e: print("单位工程工料机汇总入库失败 %s:%s" % (num, e), flush=True) if n_uwlme: print("批次 %s 单位工程工料机汇总:%d 条" % (bid, n_uwlme), flush=True) + # 决策322(2026-11-14 主人拍板):定额双口径工料机合计预存 + 锚列统一判定(项目批次专属) + if kind == "project": + norm_lme_totals_fill(cur, bid) + price_basis_judge(cur, bid) + cur.execute("UPDATE batches SET x_rows_bill=?, x_rows_lme=? WHERE id=?", (n_bill, n_lme, bid)) return bid, n_bill, n_lme + +# ---------- 决策322:定额工料机合计预存 + 锚列判定(2026-11-14 主人拍板②+统一自判) ---------- + +def norm_lme_totals_fill(cur, bid): + """每条定额双口径工料机合计:Σ(norm_res.qty × lme_lib.ntp/taxp),一次 UPDATE 预存两列。 + 后台冻结源锚——导入算一次,此后永不回写;工作台改价/含量编辑只动会话侧 s_norms + (差额法见 api_server._norm_price_cascade),后台合计是「源定额工料机合计值」本体。 + qty 取入库含量(不重求 express——与 dyn_lme 汇总数量现算同口径,同码同形); + lme_lib 是全集表(不去重不过滤),缺价行按 0 计(费用科目/影子行天然缺价)。""" + cur.execute("""UPDATE norms SET + x_lme_total_nt=(SELECT ROUND(SUM(COALESCE(nr.qty*lib.ntp,0)),6) FROM norm_res nr + LEFT JOIN lme_lib lib ON lib.batch_id=? AND lib.code=nr.res_code + WHERE nr.norm_id=norms.id), + x_lme_total_tx=(SELECT ROUND(SUM(COALESCE(nr.qty*lib.taxp,0)),6) FROM norm_res nr + LEFT JOIN lme_lib lib ON lib.batch_id=? AND lib.code=nr.res_code + WHERE nr.norm_id=norms.id) + WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?)""", (bid, bid, bid)) + + +def price_basis_judge(cur, bid): + """锚列统一判定(全格式一套程序,主人拍板「不按后缀写死、数据自判」): + 抽样对账——定额单价=工料机合计+管理费利润,隐含费率必非负;锚列选错时 + 「合计>单价」大面积出现(实测 cos 负例 8%、cos4 23%,正口径 0~0.7%,信号极强)。 + 负例少者胜;有效样本不足 30 或两口径无区分度 → NULL(默认除税)。 + 结果存 batches.x_price_basis,采纳时随行带到 s_norms.x_price_basis。""" + r = cur.execute("""WITH s AS (SELECT Price p, x_lme_total_nt nt, x_lme_total_tx tx + FROM norms WHERE Price>0 AND COALESCE(x_lme_total_nt,0)>0 + AND COALESCE(x_lme_total_tx,0)>0 LIMIT 400) + SELECT COUNT(*), + SUM(CASE WHEN p0.005 THEN 1 ELSE 0 END) + FROM s""").fetchone() + n, nt_neg, tx_neg, diff = (r[0] or 0), (r[1] or 0), (r[2] or 0), (r[3] or 0) + basis = None + if n >= 30 and diff > 0: + if nt_neg < tx_neg: + basis = "ntp" + elif tx_neg < nt_neg: + basis = "taxp" + cur.execute("UPDATE batches SET x_price_basis=? WHERE id=?", (basis, bid)) + print("批次 %s 锚列判定:%s(样本 %d,除税负例 %d,含税负例 %d,有区分 %d)" + % (bid, basis or "存疑→默认除税", n, nt_neg, tx_neg, diff), flush=True) + return basis + # ---------- 主流程 ---------- def main(): # ⚠️ 2026-10-06 护栏:本入口连的是**生产库** data/history.db,且会全量清空重导。 diff --git a/CostReview/app/core/session_job.py b/CostReview/app/core/session_job.py index 94e7605..c79c919 100644 --- a/CostReview/app/core/session_job.py +++ b/CostReview/app/core/session_job.py @@ -494,19 +494,9 @@ def connect_readonly(): return con -def connect(): - # 决策 242(2026-10-30 主人定):写连接显式等锁 30 秒(默认 5 秒即抛 - # "database is locked",台账删除实测撞过);会话库转 WAL(读写并行,与 - # history.db 同款)。首切若有他连接占用则本次放弃、下次连接再切,不挡业务。 - con = sqlite3.connect(DB, timeout=30.0) - con.row_factory = sqlite3.Row - con.execute("PRAGMA busy_timeout=30000") - try: - con.execute("PRAGMA journal_mode=WAL") - except Exception: - pass - con.executescript(io.open(SCHEMA, encoding="utf-8").read()) - # 老库补列(已存在的列会报错,忽略) +def upgrade_cols(con): + """老库补列(已存在的列报 duplicate column 忽略)。connect() 与 open_project + 双入口共用——测试手建库/直连 open_project 的路径同样自愈(决策322 收口)。""" # ⚠️ 每个表各补各的 —— 别把 A 表的列塞进 B 表的循环里,那会给 B 表凭空造出无用列 for tbl, cols in ( # 2026-10-06:x_batch_id = 后台批次 id(同一份源文件导入过就能关联上, @@ -558,6 +548,11 @@ def connect(): # "1"=清单/"3"=直接条目;esc/swt 无标记=NULL;显示一律「清单」) ("s_bills", ("x_cat TEXT",)), ("s_norms", ("x_side TEXT",)), + # 决策322(2026-11-14 主人拍板):定额单价锚四列(差额法改价联动;老库补列后重开生效) + ("s_norms", ("x_price_basis TEXT", "x_price_anchor REAL", + "x_total_anchor REAL", "x_lme_total REAL")), + # 2026-11-14 P1-②:源文件资源内部 ID(SWT 按 ResourceID 引用;cos/esc NULL) + ("s_lme_uw", ("x_rid INTEGER",)), # 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环) ("s_unit_works", ("x_attr TEXT",)), # 2026-11-07 主人定「282 补」:项目级其他项目明细(detgrp/detitem 展开行) @@ -582,6 +577,22 @@ def connect(): return con +def connect(): + # 决策 242(2026-10-30 主人定):写连接显式等锁 30 秒(默认 5 秒即抛 + # "database is locked",台账删除实测撞过);会话库转 WAL(读写并行,与 + # history.db 同款)。首切若有他连接占用则本次放弃、下次连接再切,不挡业务。 + con = sqlite3.connect(DB, timeout=30.0) + con.row_factory = sqlite3.Row + con.execute("PRAGMA busy_timeout=30000") + try: + con.execute("PRAGMA journal_mode=WAL") + except Exception: + pass + con.executescript(io.open(SCHEMA, encoding="utf-8").read()) + upgrade_cols(con) # 老库补列(提取共用,open_project 同款) + return con + + def open_project(con, files, meta, job, sid=None): """ files: [(path, name)] 一般一次一个 @@ -591,6 +602,7 @@ def open_project(con, files, meta, job, sid=None): 返回 session_id """ cur = con.cursor() + upgrade_cols(con) # 手建库/老库自愈(与 connect 同一份清单;幂等) # 基准期次:起~止(单月时两者相同);兼容老参数 base_period_m pf = meta.get("period_from") pt = meta.get("period_to") @@ -815,15 +827,32 @@ def open_project(con, files, meta, job, sid=None): # 定额入库,同时记下真实 id —— 消耗量要靠它挂(norm_res 里存的是本文件内下标) norm_ids = [] adj = out.get("norm_adj", {}) + # 决策322(2026-11-14 主人拍板):会话自带定额同样落锚四列——锚价=源单价、 + # 锚合计=Σ(含量×lme_lib 价)(与后台 norm_lme_totals_fill 同式同口径,缺价行计 0); + # 锚列默认 'ntp'除税(软件主键口径;后台批次判定结果随采纳链带下,原生行无批次链取默认)。 + _nr_tot = {} + _lib322 = out.get("lme_lib") or {} + for _ni, _rc, _q, _e in (out.get("norm_res") or []): + _v = _lib322.get(_rc) + if not _v or _q is None: + continue + _t = _nr_tot.setdefault(_ni, [0.0, 0.0]) + if _v[4] is not None: + _t[0] += _q * _v[4] + if len(_v) > 5 and _v[5] is not None: + _t[1] += _q * _v[5] for norm_idx, (idx, num, nm, unit, qty, price, total) in enumerate(out["norms"]): bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None vals = adj.get(norm_idx, []) - cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side) - VALUES(?,?,?,?,?,?,?,?,?)""", + _at = round(_nr_tot.get(norm_idx, [0.0, 0.0])[0], 6) + cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side, + x_price_basis, x_price_anchor, x_total_anchor, x_lme_total) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", (bid, num, nm, unit, qty, price, total, json.dumps(vals, ensure_ascii=False) if vals else None, (lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)( - (out.get("norm_side") or {}).get(norm_idx)))) + (out.get("norm_side") or {}).get(norm_idx)), + "ntp", price, _at, _at)) norm_ids.append(cur.lastrowid) stat["norm"] += 1 @@ -861,16 +890,20 @@ def open_project(con, files, meta, job, sid=None): # 2026-10-11 决策 41:各单位工程**自己的工料机汇总**按 uw 归属原样入库(s_lme_uw), # 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。 - for _row in (out.get("lme_uw") or []): + for _i, _row in enumerate(out.get("lme_uw") or []): k, num, nm, spec, unit, ntp, tax, tp, qty, kind = _row[:10] _x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(SWT/老结构为 None) _flags = _row[14] if len(_row) > 14 else None # 决策 259:文字/标志属性 JSON(原文件有才导) + _rid = ((out.get("lme_uw_rid") or [])[_i] + if _i < len(out.get("lme_uw_rid") or []) else None) uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None if not uwid: continue cur.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind, - qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", - (sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x) + (_flags,)) + qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags, x_rid) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + (sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x) + + (_flags, _rid)) # 2026-10-02:机械台班 / 配合比的下一级组成(s_lme_res) _lname = out.get("lme_name") or {} diff --git a/CostReview/app/server/adopt_api.py b/CostReview/app/server/adopt_api.py index cf4ba49..3e1916c 100644 --- a/CostReview/app/server/adopt_api.py +++ b/CostReview/app/server/adopt_api.py @@ -12,7 +12,7 @@ import session_job as sess import import_job as job import norm_closure import dyn_lme -from code_identity import resolve_adopt, readopt_unhide, unadopt_drop # 决策 304:同码异物统一册(2026-11-12 撤=物理删改名) +from code_identity import resolve_adopt, readopt_unhide, unadopt_drop, reprice_all_lme # 决策 304 统一册+323 导入/采纳收尾全层级回算 def _have_col_set(sc, tbl): @@ -1124,6 +1124,110 @@ def _lme_ntp_of(sc, sid, uw_id, code): (sid, code)).fetchone() return (r["ntp"], r["taxp"]) if r else (None, None) # 决策 251(2026-11-01 主人定):决策 227 的改价失效回链随锚改导入价口径取消,函数已删。 +def _batch_bill_uw(hc, bill_id): + """批库清单所属单位工程(老夹具 bills 无 uw_id 列 → None,按无映射降级)。""" + try: + r = hc.execute("SELECT uw_id FROM bills WHERE id=?", (bill_id,)).fetchone() + return r[0] if r else None + except sqlite3.OperationalError: + return None + + +def _swt_src_rids(sid, src_name): + """目标会话源件里已有 ResourceItem 的 (码→ID, 已占用ID集)。 + 采纳分配新 ID 前必须先避开这些号(它们不在 s_lme_uw 里也要算占用); + 读不到源件/非 SWT → 空。""" + try: + path = _src_path(src_name or "") + if not path or not os.path.exists(path): + return {}, set() + raw = io.open(path, "rb").read() + if raw[:2] == b"PK": + import zipfile + with zipfile.ZipFile(io.BytesIO(raw)) as z: + txt = "" + for n in z.namelist(): + b = z.read(n) + if b"]*>', txt): + t = m.group(0) + c = re.search(r'\bCode="([^"]*)"', t) + r = re.search(r'\bResourceID="(\d+)"', t) + if not r: + continue + rid = int(r.group(1)) + used.add(rid) + if c and c.group(1) and c.group(1) not in code2rid: + code2rid[c.group(1)] = rid + return code2rid, used + except Exception: + return {}, set() + + +def _swt_rid_remap(sc, hc, sid, batch_id, dst_uw, src_uw, block_xml): + """P1-②(2026-11-14 主人拍板 331/332):SWT 清单块内 `NormResUsageItem@ResourceID` 是 + 批次**单位本地** ID——采纳时按「批次ID→码→目标单位码→目标ID」重写;目标单位缺 x_rid 的 + 码就地分配(不与既有 ID 冲突),采纳新增行也补 x_rid(导出补 ResourceItem 用)。 + cos/esc 块(非 BQItem/MeasureItem 开头)原样返回。返回新块文本。""" + if not block_xml or not re.match(r'\s*<(BQItem|MeasureItem)\b', block_xml): + return block_xml + try: + src = {} + for r in hc.execute("""SELECT x_rid, code FROM lme_uw WHERE batch_id=? AND uw_id=? + AND x_rid IS NOT NULL""", (batch_id, src_uw)): + if r["x_rid"] is not None and r["code"]: + src[int(r["x_rid"])] = r["code"] + except Exception: + src = {} + if not src: + return block_xml + # SWT 的 ResourceID 是**全文件全局**的(同码跨单位同 ID)——按码建全会话映射,不按单位。 + gmap = {} + for r in sc.execute("""SELECT code, x_rid FROM s_lme_uw WHERE session_id=? + AND x_rid IS NOT NULL AND code IS NOT NULL ORDER BY id""", (sid,)): + gmap.setdefault(r["code"], r["x_rid"]) + used = set(gmap.values()) + # 目标源件已有 ResourceItem(其 ID 未进 s_lme_uw 也算占用,必须先避开/按码复用) + _srow = sc.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone() + _src_code2rid, _used_src = _swt_src_rids(sid, (_srow[0] if _srow else "") or "") + used |= _used_src + for _c, _sr in _src_code2rid.items(): + gmap.setdefault(_c, _sr) + nxt = (max(used) if used else 0) + 1 + + def _rid_for(code): + nonlocal nxt + if code in gmap: + return gmap[code] + rid = nxt + nxt += 1 + gmap[code] = rid + used.add(rid) + # 同码跨单位统一用同一个 ID(导出 ResourceItem 全局唯一) + sc.execute("UPDATE s_lme_uw SET x_rid=? WHERE session_id=? AND code=?", + (rid, sid, code)) + return rid + + for _rid, code in src.items(): + _rid_for(code) + # 采纳新增行(块没引用的也补)——导出按 x_rid 补 ResourceItem,块内引用才对得上 + for r in sc.execute("""SELECT DISTINCT code FROM s_lme_uw WHERE session_id=? + AND COALESCE(x_adopt_added,0)=1 AND x_rid IS NULL + AND code IS NOT NULL""", (sid,)): + _rid_for(r["code"]) + mp = {rid: gmap[c] for rid, c in src.items() if c in gmap} + if not mp: + return block_xml + return re.sub(r'ResourceID="(\d+)"', + lambda m: 'ResourceID="%d"' % mp.get(int(m.group(1)), int(m.group(1))), + block_xml) + + def api_bill_adopt(sc, hc, body): """采纳(数据落地)。body={session_id, bill_id, src_bill_id} 统一路径(2026-11-07 主人定「新清单/原清单一个逻辑」,取代规格 9.1/9.3 双分支字段口径): @@ -1146,6 +1250,8 @@ def api_bill_adopt(sc, hc, body): # 决策 304 补记:清单级整藏四列幂等保列(再采纳反藏分支依赖) _ensure_cols(sc, "s_norm_res", [("x_adopt_hidden", "INTEGER DEFAULT 0")]) _ensure_cols(sc, "s_norms", [("x_adopt_hidden", "INTEGER DEFAULT 0")]) + _ensure_cols(sc, "s_norms", [("x_price_basis", "TEXT"), ("x_price_anchor", "REAL"), + ("x_total_anchor", "REAL"), ("x_lme_total", "REAL")]) # 决策322 锚四列 _ensure_cols(sc, "s_block_bank", [("x_adopt_hidden", "INTEGER DEFAULT 0")]) _ensure_cols(sc, "s_bills", [("x_adopt_hidden", "INTEGER DEFAULT 0")]) _sbhid = sc.execute("SELECT COALESCE(x_adopt_hidden,0) FROM s_bills WHERE id=? AND session_id=?", @@ -1194,7 +1300,8 @@ def api_bill_adopt(sc, hc, body): if not bb: return {"ok": False, "msg": "本工程来源清单不存在(可能已被删除,请刷新)"} bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, - NULL AS x_qty_coef, x_adjust, qty_expr, x_side + NULL AS x_qty_coef, x_adjust, qty_expr, x_side, + x_price_basis, x_price_anchor, x_total_anchor, x_lme_total FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""", (src_self,)).fetchall() else: @@ -1213,7 +1320,16 @@ def api_bill_adopt(sc, hc, body): src_id = bb["id"] if not bb: return {"ok": False, "msg": "入库项目清单不存在(批次可能已删除)"} - bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side + # 决策322:批次侧锚列/冻结合计列保底 + 来源锚列判定(NULL=存疑默认除税) + _ensure_cols(hc, "norms", [("x_lme_total_nt", "REAL"), ("x_lme_total_tx", "REAL")]) + _ensure_cols(hc, "batches", [("x_price_basis", "TEXT")]) + try: + _basis_r = hc.execute("SELECT x_price_basis FROM batches WHERE id=?", (bb["batch_id"],)).fetchone() + _src_basis = (_basis_r[0] if _basis_r else None) + except sqlite3.OperationalError: # 夹具/极老库无 batches 表 → 默认除税 + _src_basis = None + bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side, + x_lme_total_nt, x_lme_total_tx FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall() # 决策 279(2026-11-07 主人定「整体采纳=块进块出」):273 行组模板链与 275 乙判定 @@ -1314,11 +1430,25 @@ def api_bill_adopt(sc, hc, body): return mo.group(0) return mo.group(0).replace('Number="%s"' % mo.group(1), 'Number="%s"' % _new, 1) for nn in bnorms: + # 决策322(2026-11-14 主人拍板):锚四列落地——差额法不变式的起点 + # (Price=锚价+(现合计−锚合计);改价/含量编辑按 Δ=差额×含量 增量维护,见 _norm_price_cascade)。 + # 本会话来源:四列原样携带(再采纳=同一来源值);批次来源:锚列=批次判定(NULL→除税), + # 锚价=源单价(单价照带),锚合计=后台冻结源锚(norms.x_lme_total_nt/tx 按锚列口径取一)。 + if src_self: + _vb, _va = nn["x_price_basis"], nn["x_price_anchor"] + _vt = nn["x_total_anchor"]; _vl = nn["x_lme_total"] + else: + _vb = _src_basis or "ntp" + _va = nn["Price"] + _vt = nn["x_lme_total_tx"] if _vb == "taxp" else nn["x_lme_total_nt"] + _vl = _vt cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, - x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side) - VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?)""", + x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side, + x_price_basis, x_price_anchor, x_total_anchor, x_lme_total) + VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?,?,?,?,?)""", (bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"], - None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], None)) + None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], None, + _vb, _va, _vt, _vl)) adopted_norm_ids.append(cur.lastrowid) # 决策 279:Norm 块原文随行拷入 s_block_bank(同后缀采纳=块进块出)。 # 拷入前按 108 code_map 改写块内消耗码(块与库同码,导出件消耗码指向本地价)。 @@ -1354,9 +1484,26 @@ def api_bill_adopt(sc, hc, body): a = _lme_ntp_of(sc, sid, bb["uw_id"], rr["res_code"]) if src_self else (None, None) sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp) VALUES(?,?,?,?,?,?)", (cur.lastrowid, rr["res_code"], rr["qty"], rr["express"], a[0], a[1])) + # 决策 333(2026-11-14 主人拍板 B,取代决策 19「采纳单价恒跟源」): + # 清单价=Σ(定额量×定额价)÷清单量(2 位半升);定额量按来源清单量→当前清单量等比缩放 + # (x_qty_coef 优先,缺则 源定额量/源清单量),与导出/显示的 GCL 求值同一把尺。 + _qb = _pre["Quantity"] + _qs = bb["Quantity"] + _sum333, _ok333 = 0.0, False + for nn in bnorms: + try: + _coef = (float(nn["Quantity"] or 0) / float(_qs)) if _qs not in (None, 0) else 1.0 + _sum333 += float(_coef) * float(_qb or 0) * float(nn["Price"] or 0) + _ok333 = True + except Exception: + pass + if _ok333 and _qb not in (None, 0) and float(_qb) != 0: + new_price = _r2(_sum333 / float(_qb)) + else: + new_price = None # —— 清单字段统一口径(2026-11-07 主人定):编码/名称/项目特征/单位/工程量 - # **空则引入、非空利旧**;新清单工程量恒清 0 待填;单价恒跟源(规格 19); - # 合价=工程量×新单价现算(原清单量空→引入来源量,Total 随之现算)。 + # **空则引入、非空利旧**;新清单工程量恒清 0 待填; + # 单价按决策 333=Σ定额合价÷清单量(取代 19 的“恒跟源”);合价=量×价现算。 sets, vals = [], [] for col in ("Number", "Name", "Attr", "Unit"): _sv = bb[col] @@ -1382,8 +1529,8 @@ def api_bill_adopt(sc, hc, body): # 决策 279/290:清单壳块随采纳拷入(新清单/原清单共用);只认最新有效同源块, # 错代/错号/无 Norm 槽的壳一律拒用(回模板克隆,绝不拿错壳导出)。 if not src_self: - _want_tag = bb["x_ptag"] or ("UnitWorksPreliminaryWorkElement" - if bb["Kind"] == "prelim" else "WorkElement") + # 330:只认原生标签;老批次无 x_ptag → 传 None,由 pick_bill_block 以块自身标签兜底 + _want_tag = bb["x_ptag"] _shell = None try: _shell = job.pick_bill_block(hc, src_id, want_number=bb["Number"], @@ -1396,9 +1543,15 @@ def api_bill_adopt(sc, hc, body): except sqlite3.OperationalError: _shell = None # 无表(夹具/旧库)→ 无块路径 if _shell and _has_sbb: + _bx = _shell.get("block_xml") or "" + try: # P1-②:SWT 块内 ResourceID 按目标单位重分配(cos/esc 原样) + _bx = _swt_rid_remap(sc, hc, sid, bb["batch_id"], sb["uw_id"], + _batch_bill_uw(hc, src_id), _bx) + except Exception as _e: + print("331 ResourceID 重分配失败(块原样):%s" % _e, flush=True) sc.execute("""INSERT INTO s_block_bank(sid, bill_id, norm_id, kind, block_xml, src_batch, src_sha) VALUES(?,?,NULL,'bill',?,?,?)""", - (sid, bid, _shell["block_xml"], _shell.get("batch_id"), _shell.get("src_sha"))) + (sid, bid, _bx, _shell.get("batch_id"), _shell.get("src_sha"))) # 决策 108 改码落库(code_map 已在插定额前算好,见上):s_norm_res 随映射改成落地码 n_recode = 0 for nid in adopted_norm_ids: @@ -1487,6 +1640,17 @@ def api_bill_adopt(sc, hc, body): except Exception: pass print("采纳收尾数据链自愈失败(不挡采纳):%s" % _e, flush=True) + # 决策 323(2026-11-14 主人定,取代 316 补记九):采纳收尾同口径全层级母随子动—— + # 采纳落库/换码后全库带子级行按 Σ(边含量×子价) 回算(与导入收尾同一函数),失败不挡采纳。 + try: + reprice_all_lme(sc, sid) + sc.commit() + except Exception as _e: + try: + sc.rollback() + except Exception: + pass + print("采纳收尾全层级回算失败(不挡采纳):%s" % _e, flush=True) return {"ok": True, "sid": sid, "price0": _price0, "n_norm": len(bnorms), "n_sum": n_sum, "n_recode": n_recode, "n_att": _n_att, "mode": "覆盖" if is_new else "追加", "price": new_price} diff --git a/CostReview/app/server/api_server.py b/CostReview/app/server/api_server.py index db43be6..90bdc5a 100644 --- a/CostReview/app/server/api_server.py +++ b/CostReview/app/server/api_server.py @@ -208,6 +208,9 @@ def _ensure_edit_cols(): try: for _c in ("x_new", "x_tdel", "x_adopt"): # x_adopt:_raw_uw/_cmp_bills 两库一条 SQL,批次库补 0 恒值列 _add(hc, "bills", _c, "INTEGER DEFAULT 0") + _add(hc, "norms", "x_lme_total_nt", "REAL") # 决策322(2026-11-14 主人拍板②):定额工料机合计·除税(导入冻结源锚) + _add(hc, "norms", "x_lme_total_tx", "REAL") # 决策322:定额工料机合计·含税(同上,双列并存、判错改标记即修复) + _add(hc, "batches", "x_price_basis", "TEXT") # 决策322:锚列判定 'ntp'|'taxp'|NULL(导入尾统一对账自判) hc.commit() finally: hc.close() @@ -221,6 +224,10 @@ def _ensure_edit_cols(): _add(sc, "s_norms", "x_src_norm_id", "INTEGER") # 批次B:来源定额(批次库 id,跨重解析稳定) _add(sc, "s_norms", "qty_expr", "TEXT") # 决策 90(2026-10-17):工程量公式原文 # (GCL/数字四则;NULL=纯数字量,Quantity 照旧) + _add(sc, "s_norms", "x_price_basis", "TEXT") # 决策322:定额单价锚列(采纳随来源批次带下) + _add(sc, "s_norms", "x_price_anchor", "REAL") # 决策322:锚价(采纳落地时刻单价) + _add(sc, "s_norms", "x_total_anchor", "REAL") # 决策322:锚合计(来源冻结源锚,锚列口径) + _add(sc, "s_norms", "x_lme_total", "REAL") # 决策322:现合计(差额法增量维护) _add(sc, "s_lme_uw", "x_adopt_added", "INTEGER DEFAULT 0") # 批次B:采纳追加的汇总品类行(撤销时撤下) _add(sc, "s_lme_proj", "x_adopt_added", "INTEGER DEFAULT 0") _add(sc, "s_lme_uw", "x_flags", "TEXT") # 「骨架不能创造数据」(决策 259): @@ -2573,7 +2580,8 @@ def _snap_norms(con, bill_id): """一条清单的定额+消耗量快照(仅当定额带状态列才值得回填;无状态返回 [])""" out = [] for n in con.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, - x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust + x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust, + x_price_basis, x_price_anchor, x_total_anchor, x_lme_total FROM s_norms WHERE bill_id=? ORDER BY id""", (bill_id,)): if not (n["x_tdel"] or n["x_adopt"] or n["x_src_norm_id"] or n["qty_expr"]): continue # 干净定额:重导自然重建,不 snapshot @@ -2583,7 +2591,9 @@ def _snap_norms(con, bill_id): "Quantity": n["Quantity"], "Price": n["Price"], "Total": n["Total"], "x_tdel": n["x_tdel"], "x_adopt": n["x_adopt"], "x_src_norm_id": n["x_src_norm_id"], "qty_expr": n["qty_expr"], - "x_adjust": n["x_adjust"], "res": res}) + "x_adjust": n["x_adjust"], "res": res, + "x_price_basis": n["x_price_basis"], "x_price_anchor": n["x_price_anchor"], + "x_total_anchor": n["x_total_anchor"], "x_lme_total": n["x_lme_total"]}) return out @@ -2652,10 +2662,12 @@ def _restore_norms(con, bill_id, norms): con.execute("DELETE FROM s_norms WHERE bill_id=?", (bill_id,)) for n in norms: cur = con.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, - x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""", + x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust, + x_price_basis, x_price_anchor, x_total_anchor, x_lme_total) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (bill_id, n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], n["Total"], n["x_tdel"], n["x_adopt"], n["x_src_norm_id"], n.get("qty_expr"), - n.get("x_adjust"))) + n.get("x_adjust"), n.get("x_price_basis"), n.get("x_price_anchor"), + n.get("x_total_anchor"), n.get("x_lme_total"))) # 决策322:锚四列随快照过场 # 决策 200(2026-10-25 主人定):快照回填的组成同样按 (定额, 码) 聚合——消耗量相加。 # 金宝实测:决策 68 快照把重导已聚合的 2.53+3.55 旧对原样复活,绕过导入聚合。 _ra = {} @@ -3765,6 +3777,38 @@ def _uw_rollup_totals(con, uw_id): return div_totals, upd +def _chain_msg(miss): + """缺源导出拦截文案(2026-11-14 主人定):列**全部**缺失编码,编码间中文逗号, + 引号包到「补充完整」后、末尾无叹号;前端按前缀「数据链不完整」弹框。""" + _lst = ",".join("编码:%s" % c for c in (miss or [])) + return "数据链不完整,请在项目工料机汇总界面把“%s补充完整”" % _lst + + +def _block_msg(miss): + """被采纳清单缺壳块的拦截文案(2026-11-14 主人定:提示重新采纳/重导;同一「数据链不完整」前缀)。""" + _lst = ",".join("编码:%s" % c for c in (miss or [])) + return "数据链不完整,被采纳清单缺少来源块,请重新采纳或重导“%s”" % _lst + + +def _adopt_block_miss(sc, sid): + """被采纳占位的源清单必须带**采纳壳块**:x_adopt=1 且非新增(x_new=0)却没有 + 非隐藏块 → 导出会回退源块/模板,源定额(x_tdel=1)可能残留。返回清单编码清单。 + (2026-11-14 主人定:被占位源清单不可导出=硬保证;提示重采纳/重导。)""" + try: + rows = sc.execute("""SELECT b.Number FROM s_bills b + WHERE b.session_id=? + AND COALESCE(b.x_adopt,0)=1 + AND COALESCE(b.x_new,0)=0 + AND NOT EXISTS (SELECT 1 FROM s_block_bank bb + WHERE bb.sid=? AND bb.bill_id=b.id + AND bb.kind='bill' + AND COALESCE(bb.x_adopt_hidden,0)=0) + ORDER BY b.id""", (sid, sid)).fetchall() + except Exception: + return [] + return [r[0] for r in rows if r[0]] + + def _export_meta(sc, sid, fmt=""): """导出建议名(决策 92:先弹另存为再生成——对话框要预填 名字-审核版.原后缀,不能等生成完)。 2026-11-03 主人定:fmt=yhy/xlsx/空(原格式)弹框三选一;cos4/cos 后端保留(界面入口已取消)。""" @@ -3786,6 +3830,18 @@ def _export_meta(sc, sid, fmt=""): return {"ok": False, "msg": "手工工程没有源格式,请用「导出excel」"} if not (srow["src_name"] or ""): return {"ok": False, "msg": "没有源文件,无法按原格式导出"} + if f != "xlsx": # 原格式导出前先验数据链(2026-11-14 主人定:缺源=导出时弹框提示后拒绝) + _cl = norm_closure.build(sc, sid) + _miss = list(_cl.get("missing_sources") or []) if not _cl.get("ok") else [] + _bmiss = _adopt_block_miss(sc, sid) + if _bmiss: + _msg = _block_msg(_bmiss) + if _miss: + _msg = _chain_msg(_miss) + ";另有被采纳清单缺少来源块,请重新采纳或重导:“%s”" % ",".join( + "编码:%s" % c for c in _bmiss) + return {"ok": False, "chain_incomplete": True, "msg": _msg} + if _miss: + return {"ok": False, "chain_incomplete": True, "msg": _chain_msg(_miss)} if f == "cos4": return {"ok": True, "name": (proj_name or "工程") + "-审核版.cos4"} ext = xcos._source_ext(srow["src_name"]) @@ -3915,7 +3971,7 @@ def _export_session(sc, sid, fmt="", progress=None): if bd["Total"] or b["x_adopt"]: bd["_anchor"] = g["pos"] # 决策 279:清单壳块挂行(有块吐块);108 改码映射随行给吐块通道 - _sh = sc.execute("SELECT block_xml FROM s_block_bank WHERE sid=? AND bill_id=? AND kind='bill' ORDER BY id DESC LIMIT 1", + _sh = sc.execute("SELECT block_xml FROM s_block_bank WHERE sid=? AND bill_id=? AND kind='bill' AND COALESCE(x_adopt_hidden,0)=0 ORDER BY id DESC LIMIT 1", (sid, bd["id"])).fetchone() if _sh: bd["_block_xml"] = _sh["block_xml"] @@ -3930,7 +3986,7 @@ def _export_session(sc, sid, fmt="", progress=None): "SELECT 1 FROM s_norms WHERE bill_id=? AND COALESCE(x_adopt,0)=0 AND COALESCE(x_tdel,0)=0 LIMIT 1", (bd["id"],)).fetchone() if b["x_adopt"] and _no_live_native: - _sh2 = sc.execute("SELECT block_xml FROM s_block_bank WHERE sid=? AND bill_id=? AND kind='bill' ORDER BY id DESC LIMIT 1", + _sh2 = sc.execute("SELECT block_xml FROM s_block_bank WHERE sid=? AND bill_id=? AND kind='bill' AND COALESCE(x_adopt_hidden,0)=0 ORDER BY id DESC LIMIT 1", (sid, bd["id"])).fetchone() if _sh2: bd["_block_xml"] = _sh2["block_xml"] @@ -3979,7 +4035,7 @@ def _export_session(sc, sid, fmt="", progress=None): _nd = dict(nb) # 决策 279:采纳定额带块原文(有块吐块;无块=旧路径克隆,自然回落) if nb["x_adopt"]: - _sb = sc.execute("SELECT block_xml FROM s_block_bank WHERE norm_id=? AND kind='norm' ORDER BY id DESC LIMIT 1", + _sb = sc.execute("SELECT block_xml FROM s_block_bank WHERE norm_id=? AND kind='norm' AND COALESCE(x_adopt_hidden,0)=0 ORDER BY id DESC LIMIT 1", (nb["id"],)).fetchone() if _sb: _nd["_block_xml"] = _sb["block_xml"] @@ -4087,6 +4143,20 @@ def _export_session(sc, sid, fmt="", progress=None): if not plan: continue plan["qty_updates"] = _uw_qty.get(uwkey) or {} + # 2026-11-14 主人定「导出和显示要一致」:带子级行由 323 导入即回算改写库值,但导出侧 + # price_updates 只认 merged_codes(合并/改价登记)→ 未合并的母行仍背源样旧价(实测 + # 99100011 库 20.16、导出 800.5)。此表=本单位库值三价(除税/税率/含税),供 transform + # 只在**数值不同**时回写;原价锚 _org、调价式、别名不动(323 口径)。 + _px = {} + for _r in sc.execute("""SELECT code, ntp, taxrate, taxp FROM s_lme_uw + WHERE session_id=? AND uw_id=? AND COALESCE(x_adopt_hidden,0)=0 + AND code IS NOT NULL ORDER BY id""", (sid, uw_id)): + _c = _r["code"] + if not _c or _c in _px or _r["ntp"] is None or _r["taxp"] is None: + continue + _px[_c] = {"NoTaxPrice": _r["ntp"], "TaxPrice": _r["taxp"], + "TaxRate": "" if _r["taxrate"] is None else _r["taxrate"]} + plan["px_updates"] = _px # 2026-11-13 主人定「合并=只留一个保留值;显示=库=导出」:本单位该码在库里只剩一行 # (合并后唯一编码)→ 导出汇总区源样同码多行只留首行(其余连缩进删除)。 _cnt = {} @@ -4107,6 +4177,17 @@ def _export_session(sc, sid, fmt="", progress=None): if _ar["code"] and _ar["code"] not in plan["qty_updates"]: plan["qty_updates"][_ar["code"]] = float(_ar["qty"]) plan["added_lme"] = [] + # P1-②:SWT 补 ResourceItem 需要码→源件 ResourceID(采纳时已按目标单位重分配)。 + # SWT 的 ResourceID 是**全文件全局**的(同码跨单位同 ID),所以按码取全会话映射,不按单位。 + plan["rid_map"] = {} + try: + for _rr in sc.execute("""SELECT code, MIN(x_rid) AS rid FROM s_lme_uw + WHERE session_id=? AND x_rid IS NOT NULL + GROUP BY code""", (sid,)): + if _rr["rid"] is not None: + plan["rid_map"].setdefault(_rr["code"], _rr["rid"]) + except Exception: + plan["rid_map"] = {} for _t in sc.execute( """SELECT code, name, spec, unit, qty, taxrate, ntp, taxp, kind FROM s_lme_uw WHERE session_id=? AND uw_id=? AND COALESCE(x_adopt_added,0)=1 @@ -4252,6 +4333,21 @@ def _export_session(sc, sid, fmt="", progress=None): "NoTaxOrgPrice": r["ntp_org"], "NoTaxPriceExpress": r["ntp_expr"], "TaxOrgPrice": r["taxp_org"], "TaxPriceExpress": r["taxp_expr"], "Kind": r["kind"], "_flags": _flx} + # 2026-11-14 主人定「只有导入/导出封装分后缀,其余一个逻辑」:ESCC/SWT 与 cos 用**同一张 + # 库值价表**(来源同为 s_lme_*,323 回算后的值);格式只差标签层——cos 逐单位写三价, + # ESCC 写 Price=除税、SWT 写 Rate=含税,哪个字段由适配器定,值不由格式定。 + _proj_px = {} + for r in sc.execute("""SELECT code, ntp, taxp, taxrate FROM s_lme_proj + WHERE session_id=? AND COALESCE(x_adopt_hidden,0)=0 + AND code IS NOT NULL ORDER BY id""", (sid,)): + _c0 = r["code"] + if not _c0 or _c0 in _proj_px: + continue + _proj_px[_c0] = {"NoTaxPrice": r["ntp"], "TaxPrice": r["taxp"], + "TaxRate": "" if r["taxrate"] is None else r["taxrate"]} + # 决策 331:ESCC/SWT 的 ResourceItem 在**单位段内**——三价按单位级库值写回; + # 单位段外的项目级 Resource 才用 _proj_px 兜底(与 cos 的 px_updates 同源同表)。 + _px_by_uw = {k: (p.get("px_updates") or {}) for k, p in (unit_plans or {}).items()} # 规格 第11/12 条:合并改码映射 + 被合并码的子级替换数据(子级元素全字段重建用) _rm_raw = _setting_get("session:%d" % sid, "recode_map") recode_map = json.loads(_rm_raw) if _rm_raw else {} @@ -4365,15 +4461,20 @@ def _export_session(sc, sid, fmt="", progress=None): _uw_groups[(_ukey, _r["code"])] = _gidx[_k] # 行级:一个 uw 的多行分属不同组 except Exception: _uw_groups = {} - # 决策 295:定额“耗”为起点,沿 s_lme_res 走到叶子;闭包内缺源/断链 → 拒绝导出。 + # 决策 295:定额“耗”为起点,沿 s_lme_res 走到叶子;闭包内缺源/断链 → 拒绝导出 + # (2026-11-14 主人定文案:指明补全位置与编码清单;仍拒绝、不截枝、不补占位)。 # 闭包外的旧源/引用不导出(不再用全项目源集当“必须保留”标准)。 _closure = norm_closure.build(sc, sid) - if not _closure.get("ok"): - _miss = _closure.get("missing_sources") or [] - return None, None, ("定额耗数据链不完整:闭包 %d 码,缺源 %d 个(%s)。" - "按决策 295 拒绝导出,不截枝、不补占位。" - % (len(_closure.get("codes") or {}), len(_miss), - "、".join(_miss[:8]))) + _miss = list(_closure.get("missing_sources") or []) if not _closure.get("ok") else [] + _bmiss = _adopt_block_miss(sc, sid) + if _bmiss: + _msg = _block_msg(_bmiss) + if _miss: + _msg = _chain_msg(_miss) + ";另有被采纳清单缺少来源块,请重新采纳或重导:“%s”" % ",".join( + "编码:%s" % c for c in _bmiss) + return None, None, _msg + if _miss: + return None, None, _chain_msg(_miss) _closure_codes = set(_closure.get("codes") or ()) # 决策 283/284:ESCC2.0 散装 xml 与 SWT/SWZ —— 手术引擎的标签层形态(同一模式)。 # 汇总区现算链(LME sync/added/hidden、项目级汇总重算)为 v2 项——v1 无动作区字节源样。 @@ -4396,8 +4497,14 @@ def _export_session(sc, sid, fmt="", progress=None): unit_mig=_unit_code_mig(sc, sid, uwmap, recode_ident, recode_map=recode_map), progress=progress, price_updates=price_updates, + db_price_updates=_proj_px, + db_price_by_uw=_px_by_uw, added_children=added_children, - merged_children=merged_children) + added_org=added_org, + merged_children=merged_children, + field_updates=field_updates, + recode_map=recode_map, + recode_children=recode_children) except Exception as e: return None, None, "导出失败:%s" % e return raw, out_name, None @@ -4408,7 +4515,13 @@ def _export_session(sc, sid, fmt="", progress=None): recode_ident=recode_ident, unit_mig=_unit_code_mig(sc, sid, uwmap, recode_ident, recode_map=recode_map), progress=progress, - price_updates=price_updates) + price_updates=price_updates, + db_price_updates=_proj_px, + db_price_by_uw=_px_by_uw, + added_children=added_children, + field_updates=field_updates, + recode_map=recode_map, + recode_children=recode_children) except Exception as e: return None, None, "导出失败:%s" % e return raw, out_name, None @@ -4568,40 +4681,52 @@ def _prune_unreferenced_lme(sc, sid): 仅 10 个有引用单位真实被定额链引用,其余为源件品类架子残留。决策 268「0 量也显示」 随之限缩为「**有引用地+现算 0**」(临删按 0、正负抵消)——无引用地的行不再以 0 量 出现在单位级卡/合并弹框。 - 幂等:重复跑无副作用;引用集为空(异常会话)跳过不删。返回删除行数。""" + 幂等:重复跑无副作用;引用集为空(异常会话)跳过不删。返回删除行数。 + 2026-11-14 304 缺口修复(主人验收标准「脏数据去除成功,无残留」):引用集**级联有效化** + ——组成边(s_lme_res)的 res_code 算引用的前提=该边父码(p_code)本身已被引用。此前 + 「任何边的 res 都算引用」让带子级脏数据链的子行借父边的残留引用躲过剪枝、残留项目级 + (56 组样本实测 12 行:脏父子/脏中/脏孙×4);级联后父剪→边失效→子随之剪,与单位级 + 「已引用母码的子级」口径一致(269补五 无引用地即剪)。""" ref = {r[0] for r in sc.execute( """SELECT DISTINCT nr.res_code FROM s_norm_res nr JOIN s_norms n ON n.id = nr.norm_id JOIN s_bills b ON b.id = n.bill_id WHERE b.session_id=? AND nr.res_code IS NOT NULL""", (sid,))} - ref |= {r[0] for r in sc.execute( - "SELECT DISTINCT res_code FROM s_lme_res WHERE session_id=? AND res_code IS NOT NULL", (sid,))} + edges = sc.execute( + "SELECT p_code, res_code FROM s_lme_res WHERE session_id=? AND res_code IS NOT NULL", + (sid,)).fetchall() + # 级联有效化:从直接耗引用出发,父码已被引用的边其 res_code 才有效(迭代到收敛) + eff = {r for r in ref if r} + changed = True + while changed: + changed = False + for pc, rc in edges: + if rc not in eff and pc in eff: + eff.add(rc) + changed = True + ref = eff ref.discard("") ref.discard("None") if not ref: return 0 + # 2026-11-14 修复闭环:DELETE 的子查询此前自带「UNION SELECT res_code FROM s_lme_res」 + # (旧口径:任何边的 res 都算引用)——级联有效化没进 SQL,脏链子行仍残留项目级(T1 实测 + # 12 行)。改为把级联后的有效引用集写临时表,两级 DELETE 统一 NOT IN 它。 + sc.execute("CREATE TEMP TABLE IF NOT EXISTS _eff_refs(code TEXT PRIMARY KEY)") + sc.execute("DELETE FROM _eff_refs") + sc.executemany("INSERT INTO _eff_refs(code) VALUES(?)", [(r,) for r in ref]) n = 0 # 项目级与单位级同口径:未引用即删(含合并隐藏行——决策 244 补充拍板「合并后零引用直接删」; # 临时删除的定额行还在可恢复,其消耗量算引用 → 被临删引用的工料机保留,主人 2026-11-01 拍板) cur = sc.execute( """DELETE FROM s_lme_proj WHERE session_id=? AND COALESCE(x_adopt_hidden,0)=0 - AND code IS NOT NULL AND code NOT IN ( - SELECT nr.res_code FROM s_norm_res nr - JOIN s_norms n2 ON n2.id = nr.norm_id - JOIN s_bills b2 ON b2.id = n2.bill_id WHERE b2.session_id=? - UNION SELECT res_code FROM s_lme_res WHERE session_id=? AND res_code IS NOT NULL)""", - (sid, sid, sid)) + AND code IS NOT NULL AND code NOT IN (SELECT code FROM _eff_refs)""", (sid,)) n += cur.rowcount # 单位级:无隐藏列,未引用即删 cur = sc.execute( """DELETE FROM s_lme_uw WHERE session_id=? AND COALESCE(x_adopt_hidden,0)=0 - AND code IS NOT NULL AND code NOT IN ( - SELECT nr.res_code FROM s_norm_res nr - JOIN s_norms n2 ON n2.id = nr.norm_id - JOIN s_bills b2 ON b2.id = n2.bill_id WHERE b2.session_id=? - UNION SELECT res_code FROM s_lme_res WHERE session_id=? AND res_code IS NOT NULL)""", - (sid, sid, sid)) + AND code IS NOT NULL AND code NOT IN (SELECT code FROM _eff_refs)""", (sid,)) n += cur.rowcount # 单位级**逐单位**剪枝(2026-11-06 主人定「无引用地=脏数据,导入时就舍弃」):(单位,码) # 不在本单位引用集(本单位直挂 ∪ 已引用母码的子级,_unit_ref_map 共用尺)→ 该行舍弃。 @@ -5636,7 +5761,7 @@ def api_norm_content(sc, body): return {"ok": False, "msg": "含量必须是数字"} if q < 0: return {"ok": False, "msg": "含量不能为负"} - cur = sc.execute("""SELECT nr.id FROM s_norm_res nr + cur = sc.execute("""SELECT nr.id, nr.qty FROM s_norm_res nr JOIN s_norms n ON n.id=nr.norm_id JOIN s_bills b ON b.id=n.bill_id WHERE nr.norm_id=? AND nr.res_code=? AND b.session_id=? @@ -5650,6 +5775,24 @@ def api_norm_content(sc, body): WHERE n.id=?""", (nid,)).fetchone() if _b and _b["uw_id"] is not None: _out["_qmap"] = ("touch", int(_b["uw_id"])) + # 决策322 A案(2026-11-14 主人拍板「含量动、单价立刻跟着动」):本定额现合计增量, + # 单价=锚价+(现合计−锚合计)(锚缺→单价+=差额);现价取不到(汇总还没该码行)→ 联动跳过,不造错账。 + try: + _dq = q - float(cur["qty"] or 0) + _uw = _b["uw_id"] if _b else None + _basis = "ntp" + try: + _nr0 = sc.execute("SELECT x_price_basis FROM s_norms WHERE id=?", (nid,)).fetchone() + if _nr0 and _nr0["x_price_basis"]: + _basis = _nr0["x_price_basis"] + except sqlite3.OperationalError: + pass # 老夹具/未升级库无锚列 → 默认除税 + _nt, _tx = _lme_ntp_of(sc, sid, _uw, rc) + _px = _nt if _basis == "ntp" else _tx + if _px is not None: + _norm_apply_delta(sc, nid, _dq * float(_px)) + except Exception: + pass # 联动失败不挡含量编辑本体(显示端动态现算兜底) return _out @@ -5660,8 +5803,12 @@ def _mothers_reprice(sc, sid, codes, as_children=True): as_children=True:codes 是**子码**(改子价后查它隶属的母逐层上溯); as_children=False:codes 本身就是**母码**(改子含量时入口直接给母,先回算它, 母还可能是别的母的子 → 继续上溯;数量口径 268补三 只传一层不变,价格按依赖重算到顶)。 - 子价取 s_lme_proj.ntp,缺行退 s_lme_uw。""" + 子价取 s_lme_proj.ntp,缺行退 s_lme_uw。 + 决策322(2026-11-14 主人拍板):回传母价差额 {code: {uw_id_str: [Δ除税,Δ含税], "__rest__": [Δ除税,Δ含税]}} + ——调用方(api_lme_price/api_lme_content)交给 _norm_price_cascade 联动定额单价; + 其余调用方(恢复/合并尾)忽略返回值,行为不变。""" seen, queue = set(), [] + deltas = {} if as_children: for c in (codes or []): if not c: @@ -5716,8 +5863,9 @@ def _mothers_reprice(sc, sid, codes, as_children=True): kids = sc.execute("SELECT res_code, qty FROM s_lme_res WHERE session_id=? AND p_code=?", (sid, code)).fetchall() # 单位级:母在该单位的每一行各按本单位子价回算(原价锚 _org 不动;uw 表无隐藏概念) - for urow in sc.execute("""SELECT id, uw_id, taxrate FROM s_lme_uw WHERE session_id=? AND code=?""", + for urow in sc.execute("""SELECT id, uw_id, taxrate, ntp, taxp FROM s_lme_uw WHERE session_id=? AND code=?""", (sid, code)).fetchall(): + _old_u, _old_t = float(urow["ntp"] or 0), float(urow["taxp"] or 0) # 决策322 捕差:写前旧价 tu = tt = 0.0 for r in kids: try: @@ -5725,14 +5873,21 @@ def _mothers_reprice(sc, sid, codes, as_children=True): tt += float(r["qty"] or 0) * float(_child_taxp(r["res_code"], urow["uw_id"]) or 0) except (TypeError, ValueError): pass + _nu, _nt2 = _r2(tu), _r2(tt) + # 决策322 捕差:母价真变了才记账(同单位多行累加) + if abs(_nu - _old_u) > 5e-7 or abs(_nt2 - _old_t) > 5e-7: + _dd = deltas.setdefault(code, {}).setdefault(str(urow["uw_id"]), [0.0, 0.0]) + _dd[0] += _nu - _old_u + _dd[1] += _nt2 - _old_t # 决策 291:带子级父行本身不带税率——含税=Σ子级含税,不再乘父税率 # 决策 301(2026-11-11 主人定「带子级的一律税率为空」):税率写 NULL,不写 0 sc.execute("UPDATE s_lme_uw SET ntp=?, taxp=?, taxrate=NULL WHERE id=?", - (_r2(tu), _r2(tt), urow["id"])) + (_nu, _nt2, urow["id"])) # 项目级:子价取 uw 首行口径(与显示端 child_px(code, uw=None) 同源) prow = sc.execute("""SELECT id, taxrate FROM s_lme_proj WHERE session_id=? AND code=? AND COALESCE(x_merged_hide,0)=0""", (sid, code)).fetchone() if prow is not None: + _old_p = sc.execute("SELECT ntp, taxp FROM s_lme_proj WHERE id=?", (prow["id"],)).fetchone() # 决策322 捕差 tp = tt = 0.0 for r in kids: try: @@ -5740,15 +5895,106 @@ def _mothers_reprice(sc, sid, codes, as_children=True): tt += float(r["qty"] or 0) * float(_child_taxp(r["res_code"], None) or 0) except (TypeError, ValueError): pass + _np2, _nt3 = _r2(tp), _r2(tt) + # 决策322 捕差:项目级差额记 __rest__(=没有本单位汇总行的定额取价兜底口径) + if _old_p and (abs(_np2 - float(_old_p["ntp"] or 0)) > 5e-7 + or abs(_nt3 - float(_old_p["taxp"] or 0)) > 5e-7): + _dd = deltas.setdefault(code, {}).setdefault("__rest__", [0.0, 0.0]) + _dd[0] += _np2 - float(_old_p["ntp"] or 0) + _dd[1] += _nt3 - float(_old_p["taxp"] or 0) # 决策 291:父行含税=Σ子级含税;决策 301:税率为空(父行无自身税率) sc.execute("UPDATE s_lme_proj SET ntp=?, taxp=?, taxrate=NULL WHERE id=?", - (_r2(tp), _r2(tt), prow["id"])) + (_np2, _nt3, prow["id"])) _merged_codes_add(sc, sid, code) # 上溯:本码可能是别的母的子 → 它的母也要回算 for r in sc.execute("SELECT DISTINCT p_code FROM s_lme_res WHERE session_id=? AND res_code=?", (sid, code)): if r[0] and r[0] not in seen: queue.append(r[0]) + return deltas + + +def _norm_apply_delta(sc, nid, d): + """决策322:单条定额差额落账(级联引擎的单行执行器,api_norm_content 也走这里)。 + 现合计 x_lme_total += d;锚价/锚合计齐全 → 单价=锚价+(现合计−锚合计)(不变式自愈, + 浮点只舍入一次);锚缺(手敲行)→ 单价 += d。合价=量×价 随链(决策285)。""" + if not d: + return 0 + _have_anchor = any(x[1] == "x_price_anchor" for x in sc.execute("PRAGMA table_info(s_norms)")) + if not _have_anchor: # 老夹具/未升级库:纯增量路径 + _r0 = sc.execute("SELECT Price, Quantity FROM s_norms WHERE id=?", (nid,)).fetchone() + if _r0: + _px0 = round((_r0["Price"] or 0.0) + d, 6) + sc.execute("UPDATE s_norms SET Price=?, Total=ROUND(COALESCE(Quantity,0)*?,2) WHERE id=?", + (_px0, _px0, nid)) + return 1 + r = sc.execute("""SELECT Price, Quantity, x_price_anchor, x_total_anchor, x_lme_total + FROM s_norms WHERE id=?""", (nid,)).fetchone() + if not r: + return 0 + _tot = (r["x_lme_total"] or 0.0) + d + if r["x_price_anchor"] is not None and r["x_total_anchor"] is not None: + _px = round(r["x_price_anchor"] + (_tot - r["x_total_anchor"]), 6) + else: + _px = round((r["Price"] or 0.0) + d, 6) + sc.execute("UPDATE s_norms SET x_lme_total=?, Price=?, Total=ROUND(COALESCE(Quantity,0)*?,2) WHERE id=?", + (_tot, _px, _px, nid)) + return 1 + + +def _norm_price_cascade(sc, sid, deltas): + """决策322(2026-11-14 主人拍板):定额单价联动差额引擎——全格式一套(改价/子级含量共用)。 + deltas: {code: {"__all__": (Δ除税,Δ含税)} 全单位同差(行级改价) + | {uw_id_str: (Δ除税,Δ含税), …, "__rest__": (Δ除税,Δ含税)} 逐单位(母行回算)} + 受影响定额 Δ = Σ(Δ锚列口径 × 该行含量):锚列 ntp 取 Δ除税、taxp 取 Δ含税(行级 x_price_basis, + 采纳随来源批次带下,NULL=除税)。现合计增量维护;单价/合价由 _norm_apply_delta 落账。 + 只碰引用了被改码的定额(res_code 索引命中),其余定额一字不动——主人定的「快速计算」。 + 后台 norms 双口径合计是冻结源锚(norm_lme_totals_fill 导入时算),本引擎只动会话侧。""" + if not deltas: + return 0 + codes = [c for c, v in deltas.items() if v] + if not codes: + return 0 + _have = lambda t, c: any(x[1] == c for x in sc.execute("PRAGMA table_info(%s)" % t)) # 老夹具/未升级库可选列 + _sel_basis = "n.x_price_basis AS basis" if _have("s_norms", "x_price_basis") else "NULL AS basis" + _hid_r = "AND COALESCE(nr.x_adopt_hidden,0)=0" if _have("s_norm_res", "x_adopt_hidden") else "" + # __rest__ 兜底只给「本单位没有汇总行」的定额(有汇总行的单位价没变就按没变算) + _rest_units = {} + for _c, _v in deltas.items(): + if "__rest__" in (_v or {}): + _rest_units[_c] = {str(r[0]) for r in sc.execute( + "SELECT DISTINCT uw_id FROM s_lme_uw WHERE session_id=? AND code=?", (sid, _c)).fetchall()} + _ph = ",".join("?" * len(codes)) + rows = sc.execute("""SELECT nr.norm_id nid, nr.res_code rc, nr.qty q, %s, b.uw_id uw + FROM s_norm_res nr + JOIN s_norms n ON n.id=nr.norm_id + JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=? AND nr.res_code IN (%s) + %s""" % (_sel_basis, _ph, _hid_r), [sid] + codes).fetchall() + per = {} + for r in rows: + ent = deltas.get(r["rc"]) or {} + _key = str(r["uw"]) + if "__all__" in ent: + d = ent["__all__"] + else: + d = ent.get(_key) + if d is None and "__rest__" in ent and _key not in _rest_units.get(r["rc"], ()): + d = ent["__rest__"] + if not d: + continue + try: + _q = float(r["q"] or 0) + except (TypeError, ValueError): + continue + _d = d[0] if (r["basis"] or "ntp") == "ntp" else d[1] + if _d is None: + continue + per[r["nid"]] = per.get(r["nid"], 0.0) + _d * _q + _n = 0 + for _nid, _d in per.items(): + _n += _norm_apply_delta(sc, _nid, _d) + return _n def api_lme_content(sc, body): @@ -5775,7 +6021,8 @@ def api_lme_content(sc, body): dyn_lme.set_override(sc, sid, p_code, False) # 母行回 Σ 现算 except Exception: pass - _mothers_reprice(sc, sid, [p_code], as_children=False) # 决策 288 修:改的就是母的组成→母价直接回算 + _md = _mothers_reprice(sc, sid, [p_code], as_children=False) # 决策 288 修:改的就是母的组成→母价直接回算 + _norm_price_cascade(sc, sid, _md) # 决策322:母价差额→引用母码的定额单价联动(差额法,主人拍板 2026-11-14) return {"ok": True, "sid": sid, "p_code": p_code, "res_code": res_code, "qty": q} @@ -5842,6 +6089,12 @@ def api_lme_price(sc, body): if row["hid"]: return {"ok": False, "msg": "该行已合并隐藏,不能改价"} cur_ntp, cur_rate = row["ntp"], row["taxrate"] + cur_taxp = row["taxp"] # 决策322:旧含税价(差额基) + # 决策322:改价前先捕**全单位旧显价**——定额取价链是 uw 优先(_lme_ntp_of 同源), + # 本码在项目级行可能是本次自动建的(旧价 NULL),差额必须按各单位改价前显价算。 + _pre_px = {str(_r["uw_id"]): (_r["ntp"], _r["taxp"]) for _r in sc.execute( + "SELECT uw_id, ntp, taxp FROM s_lme_uw WHERE session_id=? AND code=?", + (sid, row["code"])).fetchall()} has_ntp, has_rate, has_taxp = ("ntp" in body), ("taxrate" in body), ("taxp" in body) if not (has_ntp or has_rate or has_taxp): return {"ok": False, "msg": "没有要改的价字段"} @@ -5890,7 +6143,16 @@ def api_lme_price(sc, body): (sid, rid)).fetchone() except Exception: _a = None - _mothers_reprice(sc, sid, [row["code"]]) # 决策 288 修:子价变了→母价回 Σ 写库 + _md = _mothers_reprice(sc, sid, [row["code"]]) # 决策 288 修:子价变了→母价回 Σ 写库 + # 决策322(2026-11-14 主人拍板):本码直改差额(逐单位按改价前显价)+母行捕差 → 定额单价联动 + _ev = {row["code"]: {}} + for _uk, (_on, _ot) in _pre_px.items(): + _ev[row["code"]][_uk] = ((ntp or 0.0) - (_on or 0.0), (taxp or 0.0) - (_ot or 0.0)) + # 没有本单位汇总行的定额走项目级旧显价兜底(__rest__;有 uw 行的单位价没变不兜) + _ev[row["code"]]["__rest__"] = ((ntp or 0.0) - (cur_ntp or 0.0), (taxp or 0.0) - (cur_taxp or 0.0)) + for _mc, _mv in (_md or {}).items(): + _ev[_mc] = _mv + _norm_price_cascade(sc, sid, _ev) return {"ok": True, "sid": sid, "id": rid, "code": row["code"], "ntp": ntp, "taxrate": rate, "taxp": taxp, "synced": cur.rowcount, "ntp0": (_a["x_ntp0"] if _a else None), "rate0": (_a["x_rate0"] if _a else None), @@ -8798,7 +9060,9 @@ class Handler(SimpleHTTPRequestHandler): if _token: _EXPORT_JOBS.pop(_token, None) # 响应头已就绪(生成完毕),轮询即可停 if err: - return self._json({"ok": False, "msg": err}) + return self._json({"ok": False, + "chain_incomplete": err.startswith("数据链不完整"), + "msg": err}) self._allow_cache = True self.send_response(200) # SWT 裸 XML 用 application/xml;SWZ/COS 压缩包用 application/zip diff --git a/CostReview/app/server/code_identity.py b/CostReview/app/server/code_identity.py index 1cbe014..232b7f9 100644 --- a/CostReview/app/server/code_identity.py +++ b/CostReview/app/server/code_identity.py @@ -219,6 +219,7 @@ def normalize_session(sc, sid): m.setdefault(c, {}).update(kv) sc.execute("INSERT INTO s_settings(scope,k,v) VALUES(?,?,?) ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v", ("session:%d" % sid, "recode_ident", json.dumps(m, ensure_ascii=False))) + reprice_all_lme(sc, sid) # 决策 323:导入收尾全层级母随子动(库/显示/导出一致) _self_check(sc, sid) return moved @@ -339,6 +340,83 @@ def readopt_unhide(sc, sid, uw_id, code, ident): # ── 自检(303补记二 同款精神:不过就回滚,不能只红字提示) ──────────────── +def reprice_all_lme(sc, sid): + """决策 323(2026-11-14 主人定,取代 316 补记九「导入不回算」):导入/采纳收尾全库 + 母随子动——全部「带子级」行按 Σ(边含量×对应子价) 回算写库(孙→子→母按深度分层, + 各单位行按本单位子价;项目级未隐藏行取 uw 首行子价口径;291 父含税=Σ子含税; + 301 父税率写 NULL;原价锚 _org 不动)。源件不自洽在导入时即被修复, + 库/显示/导出三处一致(300)。返回回算行数。""" + edges = sc.execute("SELECT DISTINCT p_code, res_code, qty FROM s_lme_res WHERE session_id=?", + (sid,)).fetchall() + if not edges: + return 0 + kids = {} + for _p, _r, _q in edges: + kids.setdefault(_p, []).append((_r, _q)) + # 深度:叶子=0,母=最深子+1;迭代至稳定(防环上限=码数轮)。 + # 叶子(不在 kids 的码)深度恒 0——首版把「叶子」当「深度未知」导致全部母码无深度、 + # 排序退化成字符串序=母先于子回算、用了子的源样价(跑具 ①d 实测抓出:m1=30.66 应 20.16)。 + depth = {} + for _ in range(len(kids) + 1): + changed = False + for p in list(kids): + d, ok = 0, True + for r, _q in kids[p]: + dr = depth.get(r, 0 if r not in kids else None) + if dr is None: + ok = False + break + d = max(d, dr + 1) + if ok and depth.get(p) != d: + depth[p] = d + changed = True + if not changed: + break + + def _child_px(c, uw, col): + if uw is not None: + r = sc.execute("SELECT %s FROM s_lme_uw WHERE session_id=? AND code=? AND uw_id=?" % col, + (sid, c, uw)).fetchone() + if r and r[0] is not None: + return r[0] + r = sc.execute("SELECT %s FROM s_lme_uw WHERE session_id=? AND code=? ORDER BY id LIMIT 1" % col, + (sid, c)).fetchone() + if r and r[0] is not None: + return r[0] + r = sc.execute("SELECT %s FROM s_lme_proj WHERE session_id=? AND code=?" % col, + (sid, c)).fetchone() + return r[0] if r else None + + n = 0 + for p in sorted(kids, key=lambda x: depth.get(x, 0)): + for urow in sc.execute("SELECT id, uw_id FROM s_lme_uw WHERE session_id=? AND code=?", + (sid, p)).fetchall(): + tu = tt = 0.0 + for r, q in kids[p]: + try: + tu += float(q or 0) * float(_child_px(r, urow[1], "ntp") or 0) + tt += float(q or 0) * float(_child_px(r, urow[1], "taxp") or 0) + except (TypeError, ValueError): + pass + sc.execute("UPDATE s_lme_uw SET ntp=?, taxp=?, taxrate=NULL WHERE id=?", + (round(tu, 2), round(tt, 2), urow[0])) + n += 1 + prow = sc.execute("""SELECT id FROM s_lme_proj WHERE session_id=? AND code=? + AND COALESCE(x_merged_hide,0)=0""", (sid, p)).fetchone() + if prow: + tp = tt = 0.0 + for r, q in kids[p]: + try: + tp += float(q or 0) * float(_child_px(r, None, "ntp") or 0) + tt += float(q or 0) * float(_child_px(r, None, "taxp") or 0) + except (TypeError, ValueError): + pass + sc.execute("UPDATE s_lme_proj SET ntp=?, taxp=?, taxrate=NULL WHERE id=?", + (round(tp, 2), round(tt, 2), prow[0])) + n += 1 + return n + + def _self_check(sc, sid): """同码多身份必须=0(uw/proj 两级全查,含隐藏行)。不过→RuntimeError(调用方回滚)。""" for tbl in ("s_lme_uw", "s_lme_proj"): diff --git a/CostReview/app/store/schema.sql b/CostReview/app/store/schema.sql index b444113..518ddad 100644 --- a/CostReview/app/store/schema.sql +++ b/CostReview/app/store/schema.sql @@ -35,7 +35,9 @@ CREATE TABLE IF NOT EXISTS batches( x_side TEXT, -- 2026-11-03:项目级非数据层整棵(SummaryOfCost/AddiCost/项目汇总…,JSON 路径树) x_parser_ver TEXT, -- 导入时的解析器版本(import_job.PARSER_VER / price_html.PARSER_VER) -- 与当前代码版本不一致 = 数据口径过期,后台顶部提示重导 - is_mock INTEGER NOT NULL DEFAULT 0 -- 1=自动模拟生成(测试数据);后台「清空模拟数据」按此整批删除 + is_mock INTEGER NOT NULL DEFAULT 0, -- 1=自动模拟生成(测试数据);后台「清空模拟数据」按此整批删除 + x_price_basis TEXT -- 决策322(2026-11-14 主人拍板):定额单价锚列判定 'ntp'除税|'taxp'含税 + -- (导入尾统一对账自判:负费率少者胜;NULL=存疑默认除税。全格式一套程序) -- ⚠️ 2026-10-01 删除 profession 列:后台不再按专业分组(固定走系统默认),该列无人读写 ); @@ -201,6 +203,7 @@ CREATE TABLE IF NOT EXISTS lme_uw( uw_id INTEGER, code TEXT, name TEXT, spec TEXT, unit TEXT, kind INTEGER, + x_rid INTEGER, -- 源文件资源内部 ID(SWT NormResUsageItem@ResourceID 用;cos/esc 为 NULL) qty REAL, -- 总数量(本单位工程汇总节点原样) ntp REAL, -- 除税编制价 taxrate REAL, -- 源文件比率属性原样存(界面不显示) @@ -274,6 +277,9 @@ CREATE TABLE IF NOT EXISTS norms( Total REAL, -- 2026-10-01 加 x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行) , x_adjust TEXT -- 换算调整记录(JSON 数组,Value 串;补记十三) +, x_lme_total_nt REAL -- 决策322(2026-11-14 主人拍板②):定额工料机合计·除税口径 + -- (Σ norm_res.qty × lme_lib.ntp;导入算一次冻结,永不回写) +, x_lme_total_tx REAL -- 决策322:定额工料机合计·含税口径(Σ qty × lme_lib.taxp,同上冻结) ); CREATE INDEX IF NOT EXISTS ix_norm_bill ON norms(bill_id); diff --git a/CostReview/app/store/session.sql b/CostReview/app/store/session.sql index 8e7ca73..1e8914e 100644 --- a/CostReview/app/store/session.sql +++ b/CostReview/app/store/session.sql @@ -147,7 +147,11 @@ CREATE TABLE IF NOT EXISTS s_norms( x_adopt_hidden INTEGER DEFAULT 0 -- 决策 304 补记:清单级整藏——决策 67 预埋 , x_adjust TEXT, -- 换算调整记录(JSON;采纳携带,补记十三) - x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行) + x_side TEXT, -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行) + x_price_basis TEXT, -- 决策322(2026-11-14 主人拍板):本行定额单价锚列 'ntp'除税|'taxp'含税(采纳随来源批次带下;NULL=手敲/存疑默认除税) + x_price_anchor REAL,-- 决策322:锚价=采纳落地时刻单价(差额法不变式 Price=锚价+(现合计−锚合计);手敲行=创建价) + x_total_anchor REAL,-- 决策322:锚合计=采纳落地时刻工料机合计(锚列口径,来自 norms.x_lme_total_nt/tx 冻结源锚) + x_lme_total REAL -- 决策322:现合计(锚列口径;改价/含量编辑按 Δ=差额×含量 增量维护;导出合价随链) ); CREATE INDEX IF NOT EXISTS ix_sn_bill ON s_norms(bill_id); @@ -217,6 +221,7 @@ CREATE TABLE IF NOT EXISTS s_lme_uw( uw_id INTEGER, code TEXT, name TEXT, spec TEXT, unit TEXT, kind INTEGER, + x_rid INTEGER, -- 源文件资源内部 ID(SWT NormResUsageItem@ResourceID;cos/esc NULL) qty REAL, ntp REAL, taxrate REAL, taxp REAL, ntp_org REAL, ntp_expr REAL, -- 决策 183:六价全采(属性级对应回填) taxp_org REAL, taxp_expr REAL, diff --git a/CostReview/app/ui/workbench.html b/CostReview/app/ui/workbench.html index 323c8ef..ff39a73 100644 --- a/CostReview/app/ui/workbench.html +++ b/CostReview/app/ui/workbench.html @@ -624,6 +624,19 @@ body.histdrag{user-select:none} + +
+
+

导出被拦

+
+
+
+
+ +
+
+