feat(manual): 手工工程导入导出(决策229/230)与本页搜索共享层
This commit is contained in:
136
CostReview/app/core/classic_skeleton.py
Normal file
136
CostReview/app/core/classic_skeleton.py
Normal file
@@ -0,0 +1,136 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""经典整件骨架库(决策 229,2026-10-27 主人定):
|
||||
|
||||
手工工程(无源文件,决策 119/230)没有「本项目原件」可当导出模板——把**经典项目的
|
||||
整件原件**收进骨架库当模板:结构字段相同(同签名)只存一件;每组保留**最全**的代表
|
||||
(不一定最新,平手取最新;绝不跨件拼合,与决策 197 工料机骨架库同一条规则,
|
||||
只是范围从工料机一层扩到整件);**连保留值一起存**——导出件里我们没有的工程级信息
|
||||
(建设单位/编制人/取费程序/费用汇总…)就按代表件原样保留(铁律 5 本通道调整,主人定)。
|
||||
|
||||
收集规则(主人 2026-10-27 逐条定):
|
||||
· 收集口=公共上传口(api_upload):后台导入与工作台「打开工程」两侧自动生效;
|
||||
· 签名=后缀+结构字段指纹:10 字段 / 15 字段是不同组,**都收**(找规律、找框架);
|
||||
· 每组只存最全一件(全文件元素总数为「全」的度量,与 197「形态种类最多」同源;
|
||||
同签名结构相同,元素多=样板更全);平手取最新;
|
||||
· 多后缀:提取器按后缀注册,本次接 cos 族;SWT/SWZ 等后期注册即可。
|
||||
存储:history.db classic_skel 一组一行(连代表件原件字节存库,不随会话清理)。
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
# cos 族 = 易达两代格式,同一条代码路径(决策 105);其余后缀注册即收
|
||||
_COS_RE = re.compile(r"\.(cos4?)$", re.I)
|
||||
|
||||
|
||||
def suffix_of(name):
|
||||
"""文件名 → 规范后缀 cos|cos4;本次未注册的格式返回 None(不收不挡)。"""
|
||||
m = _COS_RE.search(os.path.basename(name or ""))
|
||||
return m.group(1).lower() if m else None
|
||||
|
||||
|
||||
def _now():
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_table(con):
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS classic_skel(
|
||||
sig TEXT PRIMARY KEY, -- 后缀+结构字段指纹
|
||||
suffix TEXT,
|
||||
rep_sha TEXT, -- 代表件 sha256
|
||||
original_name TEXT,
|
||||
n_shapes INTEGER, -- 结构形态种类数
|
||||
n_nodes INTEGER, -- 全文件元素总数(「最全」度量)
|
||||
blob BLOB, -- 代表件整件原件(保留值来源)
|
||||
extracted_at TEXT
|
||||
)""")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 抽取:整件结构指纹(只看标签+字段集+有无子级,不看值——签名跨值稳定)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _shapes_of_bytes(raw):
|
||||
"""一个 XML 成员 → (形态 key 集合, 元素数);解析失败返回 (set(), 0)。"""
|
||||
try:
|
||||
root = ET.fromstring(raw)
|
||||
except Exception:
|
||||
return set(), 0
|
||||
shapes, n = set(), 0
|
||||
for el in root.iter():
|
||||
n += 1
|
||||
shapes.add((el.tag, tuple(sorted(el.attrib.keys())), len(el) > 0))
|
||||
return shapes, n
|
||||
|
||||
|
||||
def extract(path):
|
||||
"""原件 → dict(sig, suffix, n_shapes, n_nodes);非 zip / 无 XML / 解析全失败 → None。
|
||||
⚠️ 返回 None = 该件不成组(合法,不挡上传),与决策 197 骨架库同约定。"""
|
||||
suf = suffix_of(os.path.basename(path))
|
||||
if not suf or not os.path.exists(path):
|
||||
return None
|
||||
shapes, n_nodes = set(), 0
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
members = 0
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, n = _shapes_of_bytes(z.read(nm))
|
||||
if n:
|
||||
members += 1
|
||||
shapes |= s
|
||||
n_nodes += n
|
||||
except Exception:
|
||||
return None
|
||||
if not members or not shapes:
|
||||
return None
|
||||
sig = hashlib.md5((suf + "|" + "|".join(sorted(repr(k) for k in shapes))).encode(
|
||||
"utf-8")).hexdigest()
|
||||
return {"sig": sig, "suffix": suf, "n_shapes": len(shapes), "n_nodes": n_nodes}
|
||||
|
||||
|
||||
def collect(con, sha, path, name=""):
|
||||
"""上传口统一入口:抽取并按组收代表。返回 'new'/'rep'/'old'/None
|
||||
(新组 / 更全顶掉旧代表 / 平手取最新 / 比代表瘦没动 / 不成组)。
|
||||
⚠️ con=history.db 连接;失败绝不挡上传(调用方兜 try)。"""
|
||||
info = extract(path)
|
||||
if not info:
|
||||
return None
|
||||
_ensure_table(con)
|
||||
row = con.execute("SELECT n_nodes, extracted_at FROM classic_skel WHERE sig=?",
|
||||
(info["sig"],)).fetchone()
|
||||
if row is not None and info["n_nodes"] < (row["n_nodes"] or 0):
|
||||
return "old" # 不如代表全:不收(主人定:取最全)
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
|
||||
n_shapes,n_nodes,blob,extracted_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(sig) DO UPDATE SET rep_sha=excluded.rep_sha,
|
||||
original_name=excluded.original_name, n_shapes=excluded.n_shapes,
|
||||
n_nodes=excluded.n_nodes, blob=excluded.blob,
|
||||
extracted_at=excluded.extracted_at""",
|
||||
(info["sig"], info["suffix"], sha, os.path.basename(name or path),
|
||||
info["n_shapes"], info["n_nodes"], blob, _now()))
|
||||
con.commit() # sqlite3 隐式事务:不提交=连接关闭即回滚(DDL 却即时生效)
|
||||
return "new" if row is None else "rep"
|
||||
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。"""
|
||||
_ensure_table(con)
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY n_nodes DESC, extracted_at DESC LIMIT 1""",
|
||||
(suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def stats(con):
|
||||
"""库内概况(体检/测试用):每组一行摘要。"""
|
||||
_ensure_table(con)
|
||||
return [dict(r) for r in con.execute(
|
||||
"SELECT suffix,original_name,n_shapes,n_nodes,extracted_at FROM classic_skel "
|
||||
"ORDER BY suffix, n_nodes DESC")]
|
||||
441
CostReview/app/core/export_manual.py
Normal file
441
CostReview/app/core/export_manual.py
Normal file
@@ -0,0 +1,441 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工工程导出(决策 229,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
|
||||
口径(主人逐条拍板):
|
||||
· 骨架只在导出时用;内部数据只管采纳。单位工程→清单的计价信息按采纳数值,
|
||||
可计算的(清单合价、分部/容器合计)现算;**其他一切按骨架**(建设单位/编制人/
|
||||
取费程序/费用汇总等工程级信息=代表件保留值,铁律 5 本通道调整);
|
||||
· 我方清单下的定额/工料机=**克隆架子清值**:从骨架件挑最全样板清单整块克隆
|
||||
(费用构成汇总+定额/工料机架子全保留——决策 106:易达按 SummaryOfBasicCost
|
||||
认清单),量价结果与含量式全清、结构属性原样,易达/广联达打开按结构重算;
|
||||
· 分部层级=我方 s_divides 树递归映射原生 DivisionalWorks 嵌套(原生实测:子分部
|
||||
就是 DivisionalWorks 里嵌 DivisionalWorks,南屏 cos 实嵌 3 层;分部 Number 原生
|
||||
即空串,Name/Total 落我方,Quantity/TechnicalAndEconomicIndex 指标清零不背旧值);
|
||||
· 措施项目一起导:原生直接挂 Preliminaries 下,骨架有 PreliminaryDivisionalWorks
|
||||
包装层就克隆一层包装;
|
||||
· 工料机汇总节点:架子在、行不进(我方无工料机数据,别人的行不混入,决策 199 同源);
|
||||
· Project.xml 只改名字:工程名/单项名/单位名落我方;**UnitWorks 引用节点的 Number
|
||||
不动**(它关联成员文件名,动了断链,原生件名 @_001-1_… 实测);其余=保留值;
|
||||
· 多后缀:cos/cos4 各取各的代表件,画像天然正确;SWT/SWZ 等后期注册。
|
||||
实现:整件字节外科手术,复用 export_cos 的样板挑选/属性改写/结果值清零引擎
|
||||
(决策 106/198/204 同款),不碰会话采纳与合并工料机内部逻辑(主人定:内部零改动)。
|
||||
"""
|
||||
import io
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
import classic_skeleton
|
||||
import export_cos as ec
|
||||
from formats.skeleton import build_plan, num as _num
|
||||
|
||||
_LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
_ITEM_CONT = "DivisionalAndElementalWorks" # 分部分项容器(cos 族两代同名)
|
||||
_PRE_CONT = "Preliminaries" # 措施项目容器
|
||||
_DW = "DivisionalWorks" # 分部(嵌套=子分部,原生实测)
|
||||
_DW_PRE = "PreliminaryDivisionalWorks" # 措施分部包装层(有则克隆,无则不造)
|
||||
_ITEM_BILL = "WorkElement"
|
||||
_PRE_BILL = "UnitWorksPreliminaryWorkElement"
|
||||
_SEC_TAGS = ("SectionalWorks", "DivisionalAndElementalProject") # 单项工程层(cos/cos4 各叫其一)
|
||||
_ROOT_TAGS = ("ConstructionProject", "ConstructProject")
|
||||
_MAX_DEPTH = 8 # 分部递归保险(我方上限 4 级,决策 230)
|
||||
|
||||
|
||||
def _money(v):
|
||||
if v is None:
|
||||
return "0"
|
||||
try:
|
||||
return "%.2f" % round(float(v), 2)
|
||||
except (TypeError, ValueError):
|
||||
return "0"
|
||||
|
||||
|
||||
def _span(txt, tag, start=0):
|
||||
"""首个 <tag …>…</tag> 的 (s,e)(e 含闭标签);自闭合返回 (s, 开标签止);
|
||||
属性值里的 '>' 用 _open_tag_end 越过;同名嵌套按深度配对。找不到 → None。"""
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
||||
if not m:
|
||||
return None
|
||||
s = m.start()
|
||||
oe = ec._open_tag_end(txt, s)
|
||||
if oe < 0:
|
||||
return None
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
return (s, oe)
|
||||
depth, pos = 1, oe
|
||||
while depth:
|
||||
mn = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(txt, pos)
|
||||
if not mn:
|
||||
return None
|
||||
depth += -1 if mn.group(0)[1] == "/" else 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
return None
|
||||
|
||||
|
||||
def _opentag(txt, tag, start=0):
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
||||
if not m:
|
||||
return None
|
||||
e = ec._open_tag_end(txt, m.start())
|
||||
return txt[m.start():e] if e > 0 else None
|
||||
|
||||
|
||||
def _block_tag(blk):
|
||||
m = re.match(r"<(\w+)", blk or "")
|
||||
return m.group(1) if m else _ITEM_BILL
|
||||
|
||||
|
||||
def _zero_rows(frag):
|
||||
"""克隆架子清值第二遍:样板块里定额/工料机行的量价结果清零、含量式清空
|
||||
(_zero_results 不覆盖 Norm/LME 行本身——采纳链是整行换,用不到这一步)。"""
|
||||
def z(m):
|
||||
t = m.group(0)
|
||||
for k in ("Quantity", "Price", "Total"):
|
||||
t = re.sub(r"\b%s=\"[^\"]*\"" % k, lambda _m: k + "=\"0\"", t)
|
||||
return re.sub(r"\bExpress=\"[^\"]*\"", 'Express=""', t)
|
||||
return re.sub(r"<(?:Norm|LabourMaterialsEquipmentsMachinesElement)\b[^>]*?/?>", z, frag)
|
||||
|
||||
|
||||
def _manual_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
"""我方一条清单 → 整块:样板清单整块克隆(开标签全属性+费用构成汇总+定额/工料机
|
||||
架子),我方清单五值+特征+备注落槽(骨架没的槽不造,决策 198),架子值全清。
|
||||
无样板 → 最小自闭合形态(决策 64 已知可行解)。"""
|
||||
if not sample_blk:
|
||||
a = ' Number="%s" Name="%s"' % (ec._esc(b.get("Number") or ""),
|
||||
ec._esc(b.get("Name") or ""))
|
||||
if b.get("Attr"):
|
||||
a += ' Attr="%s"' % ec._esc(b["Attr"])
|
||||
if b.get("Unit"):
|
||||
a += ' Unit="%s"' % ec._esc(b["Unit"])
|
||||
a += ' Quantity="%s" Price="%s" Total="%s"' % (
|
||||
_num(b.get("Quantity")) or 0,
|
||||
_money(b.get("Price")), _money(b.get("Total")))
|
||||
return "<%s%s/>" % (min_tag, a)
|
||||
tag = _block_tag(sample_blk)
|
||||
close = "</%s>" % tag
|
||||
opentag = sample_blk[:ec._open_tag_end(sample_blk, 0)]
|
||||
t = ec._clone_open_tag(opentag)
|
||||
for k, v in (("Number", b.get("Number") or ""), ("Name", b.get("Name") or ""),
|
||||
("Quantity", _num(b.get("Quantity"))),
|
||||
("Price", b.get("Price")), ("Total", b.get("Total"))):
|
||||
t = ec._attr_set_has(t, k, "0" if v is None else v)
|
||||
t = ec._attr_set_has(t, "Unit", b.get("Unit") or "")
|
||||
t = ec._attr_set_has(t, "Attr", b.get("Attr") or "")
|
||||
t = ec._attr_set_has(t, "Remark", b.get("x_remark") or "")
|
||||
inner = sample_blk[len(opentag):]
|
||||
if inner.endswith(close):
|
||||
inner = inner[: -len(close)]
|
||||
return t + _zero_rows(ec._zero_results(inner)) + close
|
||||
|
||||
|
||||
def _dw_template(txt):
|
||||
"""骨架件本单位里第一个分部完整块 → {ot 开标签, prefix 前缀(分部自己的费用构成等)}。
|
||||
决策 106:费用构成子块是易达认块的关键——克隆时带上(值清零)。
|
||||
前缀按顶层整元素吸收(_top_scan),费用构成是带子级容器时不会切半。"""
|
||||
sp = _span(txt, _DW)
|
||||
if not sp:
|
||||
return None
|
||||
blk = txt[sp[0]:sp[1]]
|
||||
oe = ec._open_tag_end(blk, 0)
|
||||
close = "</%s>" % _DW
|
||||
inner = blk[oe:-len(close)] if blk.endswith(close) else blk[oe:]
|
||||
prefix, _ = _top_scan(inner, (_DW, _ITEM_BILL))
|
||||
return {"ot": blk[:oe], "prefix": prefix}
|
||||
|
||||
|
||||
def _divtree(plan, uw_id):
|
||||
"""我方 item 分部树:(roots, kids)——按 x_seq 排序(与界面同序),parent 不在集内=根。"""
|
||||
ds = [d for d in plan["divides"].values()
|
||||
if d["uw_id"] == uw_id and d["kind"] == "item"]
|
||||
ds.sort(key=lambda d: (d.get("x_seq") is None,
|
||||
d.get("x_seq") if d.get("x_seq") is not None else 0, d["id"]))
|
||||
ids = {d["id"] for d in ds}
|
||||
kids, roots = {}, []
|
||||
for d in ds:
|
||||
p = d["parent_id"]
|
||||
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
|
||||
return roots, kids
|
||||
|
||||
|
||||
def _sum_bills(bills):
|
||||
n = 0.0
|
||||
for b in bills or []:
|
||||
try:
|
||||
n += float(b.get("Total") or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return n
|
||||
|
||||
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, depth=0):
|
||||
"""一个分部节点:开标签克隆(Name/Total 落我方,指标清零)+费用构成前缀(清零)
|
||||
+子分部/清单递归。Total=本级+全部子孙清单合计(现算,主人定可计算按采纳)。
|
||||
我方上限 4 级(决策 230),递归保险 8 级。返回 (块文本, 合计)。"""
|
||||
ot = ec._clone_open_tag(tmpl["ot"]) if tmpl else '<%s Name="x">' % _DW
|
||||
ot = ec._attr_set_has(ot, "Name", d.get("name") or "")
|
||||
for k in ("Quantity", "TechnicalAndEconomicIndex"): # 别人的指标不背
|
||||
ot = ec._attr_set_has(ot, k, "0")
|
||||
parts = []
|
||||
total = _sum_bills(bills_by_div.get(d["id"], []))
|
||||
if depth <= _MAX_DEPTH:
|
||||
for sub in kids.get(d["id"], []):
|
||||
blk, sub_total = _div_block(tmpl, sub, kids, bills_by_div, sample, sep,
|
||||
depth + 1)
|
||||
parts.append(blk)
|
||||
total += sub_total
|
||||
ot = ec._attr_set_has(ot, "Total", _money(total))
|
||||
bills = [_manual_bill(sample, b) for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = _zero_rows(ec._zero_results(tmpl["prefix"])) if tmpl else ""
|
||||
return ot + prefix + sep.join(parts + bills) + "</%s>" % _DW, total
|
||||
|
||||
|
||||
def _replace_span(txt, sp, new):
|
||||
return txt[:sp[0]] + new + txt[sp[1]:]
|
||||
|
||||
|
||||
def _top_scan(inner, stop_tags):
|
||||
"""容器内顶层扫描:返回 (前缀, 命中位)。前缀=首个 stop 顶层元素之前的**完整**
|
||||
顶层元素(费用构成块等,可能带子级——按标签裸切会切在容器中间造成 XML 错配)。"""
|
||||
stop = set(stop_tags)
|
||||
pos, n = 0, len(inner)
|
||||
while pos < n:
|
||||
m = re.compile(r"<([A-Za-z_][\w.]*)").search(inner, pos)
|
||||
if not m:
|
||||
return inner, n
|
||||
tag = m.group(1)
|
||||
if tag in stop:
|
||||
return inner[:m.start()], m.start()
|
||||
oe = ec._open_tag_end(inner, m.start())
|
||||
if oe < 0:
|
||||
return inner, n
|
||||
if inner[oe - 2:oe] == "/>":
|
||||
pos = oe
|
||||
continue
|
||||
depth, p = 1, oe
|
||||
while depth:
|
||||
m2 = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(inner, p)
|
||||
if not m2:
|
||||
return inner, n
|
||||
depth += -1 if m2.group(0)[1] == "/" else 1
|
||||
p = m2.end()
|
||||
if depth == 0:
|
||||
break
|
||||
pos = p
|
||||
return inner, n
|
||||
|
||||
|
||||
def _render_unit(txt, u, plan):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总空槽;
|
||||
单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"]
|
||||
item_sample = ec._largest_bill_block(txt, tag=_ITEM_BILL, prelim=False) \
|
||||
or _fallback_blk(txt, False)
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) or item_sample
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "\r\n")
|
||||
sep_d = ec._native_sep(txt, _DW, sep)
|
||||
tmpl = _dw_template(txt)
|
||||
|
||||
# ---- 分部分项容器:清仓 → 我方分部树(DivisionalWorks 递归嵌套)+ 容器合计现算 ----
|
||||
sp = _span(txt, _ITEM_CONT)
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = txt[sp[0]:oe]
|
||||
close = "</%s>" % _ITEM_CONT
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u:
|
||||
roots, kids = _divtree(plan, u["id"])
|
||||
bills_by_div = {}
|
||||
for b in bills_item:
|
||||
bills_by_div.setdefault(b.get("div_id"), []).append(b)
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d)[0]
|
||||
for d in roots]
|
||||
blocks += [_manual_bill(item_sample, b) for b in bills_by_div.get(None, [])]
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_item)))
|
||||
else:
|
||||
blocks = []
|
||||
prefix, _ = _top_scan(inner_old, (_DW, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
txt = _replace_span(txt, sp, ot + inner + sep_d.join(blocks) + close)
|
||||
|
||||
# ---- 措施项目容器:清仓 → 我方措施行(有包装层就克隆一层);合计现算 ----
|
||||
sp = _span(txt, _PRE_CONT)
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = txt[sp[0]:oe]
|
||||
close = "</%s>" % _PRE_CONT
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u and bills_pre:
|
||||
ot_wrap = _opentag(inner_old, _DW_PRE)
|
||||
bills = [_manual_bill(pre_sample, b, _PRE_BILL) for b in bills_pre]
|
||||
body = (ec._clone_open_tag(ot_wrap) + sep.join(bills) + "</%s>" % _DW_PRE) \
|
||||
if ot_wrap else sep.join(bills)
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_pre)))
|
||||
else:
|
||||
body = ""
|
||||
# 措施分部两种标签都在真实件里出现过:PreliminaryDivisionalWorks(新)与
|
||||
# DivisionalWorks(三溪 .cos 实测)——都要停,包装层连同旧清单整块让位给我方平铺
|
||||
prefix, _ = _top_scan(inner_old, (_DW_PRE, _DW, _PRE_BILL, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
txt = _replace_span(txt, sp, ot + inner + body + close)
|
||||
|
||||
# ---- 工料机汇总:架子在、行不进(我方无工料机数据)。容器→清空内层;
|
||||
# 自闭合行(老版本/广联达目录式导出的形态)→ 整行删除,别人的行绝不残留 ----
|
||||
pos = 0
|
||||
while True:
|
||||
sp = _span(txt, _LME_SUM, pos)
|
||||
if not sp:
|
||||
break
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
txt = txt[:sp[0]] + txt[sp[1]:]
|
||||
pos = sp[0]
|
||||
continue
|
||||
txt = txt[:oe] + "</%s>" % _LME_SUM + txt[sp[1]:]
|
||||
pos = oe
|
||||
|
||||
# ---- 单位工程名 + 我方可算合计(分部分项费/措施费;其余保留值)----
|
||||
if u:
|
||||
m = re.compile(r"<UnitWorks\b").search(txt)
|
||||
if m:
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
ot = ec._attr_set(txt[m.start():oe], "Name", u.get("name") or "")
|
||||
ot = ec._attr_set_has(ot, "DivisionalAndElementalWorks",
|
||||
_money(_sum_bills(bills_item)))
|
||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
||||
txt = txt[:m.start()] + ot + txt[oe:]
|
||||
sp = _span(txt, "SummaryOfCost")
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = ec._attr_set_has(txt[sp[0]:oe], "DivisionalAndElementalWorks",
|
||||
_money(_sum_bills(bills_item)))
|
||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
||||
txt = txt[:sp[0]] + ot + txt[oe:]
|
||||
return txt
|
||||
|
||||
|
||||
def _fallback_blk(txt, prelim):
|
||||
"""没有合格样板(无费用构成子块)时的兜底:第一条同区清单块原样当模板。"""
|
||||
for mk in ec._scan_bills(txt):
|
||||
is_pre = (mk["tag"] == _PRE_BILL or ec._in_prelim(txt, mk["s"]))
|
||||
if is_pre == prelim:
|
||||
return txt[mk["s"]:mk["end"]]
|
||||
return None
|
||||
|
||||
|
||||
def _rename_opentags(txt, tag, names):
|
||||
"""按出现顺序给 tag 开标签改 Name(第 n 个 → names[n],超出不动)。
|
||||
单位/单项引用节点只改 Name——Number 关联成员文件名,动了断链(原生实测)。"""
|
||||
out, pos, i = [], 0, 0
|
||||
while i < len(names):
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
e = ec._open_tag_end(txt, m.start())
|
||||
if e < 0:
|
||||
break
|
||||
out.append(txt[pos:m.start()])
|
||||
out.append(ec._attr_set(txt[m.start():e], "Name", names[i] or ""))
|
||||
pos, i = e, i + 1
|
||||
out.append(txt[pos:])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。"""
|
||||
decl = re.match(r"^.*?\?>", txt, flags=re.S)
|
||||
base = decl.end() if decl else 0
|
||||
lead = base + (len(txt[base:]) - len(txt[base:].lstrip()))
|
||||
root_m = re.match(r"<([\w.]+)", txt[lead:])
|
||||
if root_m and root_m.group(1) in _ROOT_TAGS:
|
||||
oe = ec._open_tag_end(txt, lead)
|
||||
ot = ec._attr_set_has(txt[:oe], "Name", proj_name or "")
|
||||
txt = ot + txt[oe:]
|
||||
txt = _rename_opentags(txt, "UnitWorks",
|
||||
[u.get("name") or "" for u in plan["units"][:n_ours]])
|
||||
sec_names = [s.get("name") or "" for s in plan["sections"]]
|
||||
for t in _SEC_TAGS:
|
||||
txt = _rename_opentags(txt, t, sec_names)
|
||||
return txt
|
||||
|
||||
|
||||
def export(sc, hcon, sid, suffix, progress=None):
|
||||
"""手工工程导出 cos/cos4。返回 (字节, 文件名, 错误)。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
if not srow["x_manual"]:
|
||||
return None, None, "普通工程请按原格式导出(自带源文件模板)"
|
||||
rep = classic_skeleton.rep_for(hcon, (suffix or "").lower())
|
||||
if not rep:
|
||||
return None, None, ("该后缀(.%s)还没有经典骨架:请先在后台导入或用工作台"
|
||||
"打开一份 .%s 原件" % (suffix, suffix))
|
||||
plan = build_plan(sc, sid)
|
||||
if plan is None:
|
||||
return None, None, "会话数据读不出来"
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
try:
|
||||
raw = _render(rep["blob"], plan, proj_name, progress)
|
||||
except Exception as e:
|
||||
return None, None, "导出失败:%s" % e
|
||||
return raw, ((proj_name or "工程") + "-审核版." + rep["suffix"]), None
|
||||
|
||||
|
||||
def _render(blob, plan, proj_name, progress=None):
|
||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
||||
members, texts = [], {}
|
||||
for nm in src.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
txt, enc = ec._decode(src.read(nm))
|
||||
members.append(nm)
|
||||
texts[nm] = [txt, enc]
|
||||
# 单位工程成员=剥掉 xml 声明后根元素是 UnitWorks;项目成员=含单项层标签或项目根
|
||||
unit_nms, proj_nms = [], []
|
||||
for nm in members:
|
||||
body = re.sub(r"^.*?\?>", "", texts[nm][0], count=1, flags=re.S).lstrip()
|
||||
if body.startswith("<UnitWorks"):
|
||||
unit_nms.append(nm)
|
||||
elif any(("<%s" % t) in body for t in _SEC_TAGS) or \
|
||||
any(body[:200].find("<%s" % t) >= 0 for t in _ROOT_TAGS):
|
||||
proj_nms.append(nm)
|
||||
if not unit_nms:
|
||||
raise ValueError("骨架件里没找到单位工程数据,请换一份原件再试")
|
||||
ours = plan["units"]
|
||||
if len(ours) > len(unit_nms):
|
||||
raise ValueError("经典骨架只有 %d 个单位工程位,本工程有 %d 个——请先用单位工程"
|
||||
"更多的 .%s 原件充一次库" % (len(unit_nms), len(ours), rep["suffix"]))
|
||||
total_steps = len(unit_nms) + len(proj_nms) + 1
|
||||
step = [0]
|
||||
|
||||
def tick():
|
||||
step[0] += 1
|
||||
if progress:
|
||||
progress(step[0], total_steps)
|
||||
|
||||
for i, nm in enumerate(unit_nms):
|
||||
u = ours[i] if i < len(ours) else None
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan)
|
||||
tick()
|
||||
for nm in proj_nms:
|
||||
texts[nm][0] = _render_project(texts[nm][0], plan, proj_name,
|
||||
len(ours), len(plan["sections"]))
|
||||
tick()
|
||||
tick()
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for item in src.infolist():
|
||||
data = src.read(item.filename)
|
||||
if item.filename in texts:
|
||||
data = ec._encode(texts[item.filename][0], texts[item.filename][1])
|
||||
zi = zipfile.ZipInfo(item.filename, date_time=item.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = item.external_attr
|
||||
zi.create_system = item.create_system
|
||||
try:
|
||||
zi.extra = item.extra
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, data)
|
||||
return out.getvalue()
|
||||
@@ -101,7 +101,8 @@ def build_plan(sc, sid):
|
||||
for r in sc.execute("SELECT * FROM s_divides WHERE session_id=?", (sid,)):
|
||||
divides[r["id"]] = {"id": r["id"], "uw_id": r["uw_id"], "parent_id": r["parent_id"],
|
||||
"kind": r["Kind"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "code": r["Code"] or ""}
|
||||
"name": r["Name"] or "", "code": r["Code"] or "",
|
||||
"x_seq": r["x_seq"]}
|
||||
# 定额:先按 bill 归组,再挂到清单(含采纳/临删/公式求值)
|
||||
norms_by_bill, res_by_norm = {}, {}
|
||||
for r in sc.execute("""SELECT n.* FROM s_norms n
|
||||
|
||||
677
CostReview/app/core/manual_import.py
Normal file
677
CostReview/app/core/manual_import.py
Normal file
@@ -0,0 +1,677 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工工程(决策 230,2026-10-27 主人定):无源文件创建 + 单位工程 Excel 导入。
|
||||
|
||||
口径(主人逐条拍板):
|
||||
1. 「导入项目」弹框内**同框完成**目录编辑(项目 → 单项工程 → 单位工程 三层,点名改名、
|
||||
行尾 +/✕ 增删)与按单位工程导 Excel —— 不是先建目录再回界面导入。
|
||||
2. Excel = xlsx 两个数据 Sheet(分部分项 / 措施项目),**只到清单级**:不导定额、
|
||||
不导工料机;不设合价列(合价=工程量×单价,软件现算)。
|
||||
3. 层级用「上一级名称」挂接法表达:分部行/清单行都填自己的上级名称,
|
||||
一级分部填「单位工程」;类型只填 分部/清单 两值,几级分部由链条自动算,
|
||||
**单位工程往下最多 5 层**(最多 4 级分部 + 清单,2026-10-27 主人定)。
|
||||
挂接=找上方最近的同名分部;同一上级下分部不得重名(报行号)。
|
||||
4. 项目特征换行识别(2026-10-27 主人定):真实换行(Alt+Enter)原样保留;行内编号
|
||||
标记(1. / 1、/ 1)/(1)等多格式)**从 1 连续递增到 N(不缺号,N≥2)才切分**——
|
||||
编到 9 就必须 1~8 齐全;缺号不切;「1.5」这类小数不误切(点后跟数字不算标记)。
|
||||
切出的行编号原样保留(与既有 fmtAttr 显示口径一致,共用层不动)。
|
||||
5. 写库走会话库既有表(s_sections/s_unit_works/s_divides/s_bills),列清单与
|
||||
session_job.open_project 完全同款 —— rawDraw/四页签/汇总分析/取价链零改动。
|
||||
手工工程沿用决策 119 框架:x_manual=1、src_name=''、禁原格式导出/重解析、
|
||||
同名源文件补传恢复(补传后本模块不再接管该会话)。
|
||||
"""
|
||||
import hashlib
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
# 与 session_job 同款规范化/哈希(x_hash_* 与 open_project 同口径;core 模块平铺加载、无包结构)
|
||||
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
||||
s = re.sub(r"\s+", "", s)
|
||||
return s.lower()
|
||||
|
||||
|
||||
def md5(*parts):
|
||||
return hashlib.md5("|".join(norm(p) for p in parts).encode("utf-8")).hexdigest()
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
except Exception: # 与价格模板同款:缺库时接口层提示
|
||||
Workbook = load_workbook = None
|
||||
|
||||
MAX_DEPTH = 4 # 单位工程下最多 4 级分部(+清单 = 5 层,决策 230)
|
||||
ROOT_MARK = "单位工程" # 一级分部的「上一级名称」固定写法(主人定,与表格根行徽章同名)
|
||||
|
||||
FB_SHEET = "分部分项"
|
||||
CS_SHEET = "措施项目"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 项目特征换行识别(决策 230)
|
||||
# ---------------------------------------------------------------------------
|
||||
_M_NUM = re.compile(r"(\d{1,3})(?:[\.\、.](?!\d)|[\))])")
|
||||
|
||||
|
||||
def _attr_markers(line):
|
||||
"""行内全部编号标记 → [(号, 起, 止)]。点后跟数字=小数(1.5 / M7.5)不算标记;
|
||||
「(1)(1)」的起括号并入标记;前一个字符是数字/点(2.5、的 5)不算。"""
|
||||
out = []
|
||||
for m in _M_NUM.finditer(line):
|
||||
s = m.start()
|
||||
if s > 0 and (line[s - 1].isdigit() or line[s - 1] in ".."):
|
||||
continue
|
||||
if s > 0 and line[s - 1] in "((":
|
||||
out.append((int(m.group(1)), s - 1, m.end()))
|
||||
else:
|
||||
out.append((int(m.group(1)), s, m.end()))
|
||||
return out
|
||||
|
||||
|
||||
def split_attr(text):
|
||||
"""真实 \\n 逐行保留;行内编号从 1 连续递增到 N(N≥2、不缺号)才按标记切行。
|
||||
标记文字原样保留在行首;标记前的引导语(如「做法如下」)单独成行。"""
|
||||
if text is None:
|
||||
return ""
|
||||
t = str(text).replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||
if not t:
|
||||
return ""
|
||||
out = []
|
||||
for ln in t.split("\n"):
|
||||
ln = ln.strip()
|
||||
if not ln:
|
||||
continue
|
||||
mk = _attr_markers(ln)
|
||||
nums = [n for n, _, _ in mk]
|
||||
if len(mk) >= 2 and nums == list(range(1, len(mk) + 1)):
|
||||
pre = ln[:mk[0][1]].strip()
|
||||
if pre:
|
||||
out.append(pre)
|
||||
for k in range(len(mk)):
|
||||
seg_end = mk[k + 1][1] if k + 1 < len(mk) else len(ln)
|
||||
out.append(ln[mk[k][1]:seg_end].strip())
|
||||
else:
|
||||
out.append(ln)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模板(另存为 xlsx:填写说明 + 分部分项 + 措施项目)
|
||||
# ---------------------------------------------------------------------------
|
||||
def 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),
|
||||
("一、层级(每行填「上一级名称」)", True),
|
||||
(" 分部行和清单行都填「上一级名称」;一级分部填「单位工程」。", False),
|
||||
(" 类型只填 分部 或 清单;几级分部软件自动算(单位工程下最多 5 层)。", False),
|
||||
(" 分部行只填 上一级名称、类型、名称;清单行再填 编码/项目特征/单位/工程量/单价。", False),
|
||||
(" 同级先后=行顺序;同一上级下分部不要重名(重名软件会报行号)。", False),
|
||||
("", False),
|
||||
("二、项目特征换行", True),
|
||||
(" 单元格里按 Alt+Enter 一条一行;或同一行内用编号 1. 2. 3.(也认 1、1)1)(1)),", False),
|
||||
(" 编号从 1 连续递增到几就切成几行(编到 9 必须 1~8 齐全;缺号不切;1.5 这类小数不会误切)。", False),
|
||||
("", False),
|
||||
("三、其他", True),
|
||||
(" 1. 本模板对应一个单位工程;两个 Sheet 分别落入软件的分部分项/措施项目页签。", False),
|
||||
(" 2. 只填到清单级:不导定额、不导工料机;没有合价列——合价=工程量×单价由软件现算。", False),
|
||||
(" 3. 必填:类型、名称;清单行的 单位、工程量(数字)、单价(数字)。编码、项目特征可留空。", False),
|
||||
(" 4. 「措施项目」Sheet 平铺(全部直接挂在单位工程下),不需要上一级/类型列。", False),
|
||||
(" 5. 同一单位工程重复导入=整单位工程覆盖;汇总分析自动生成。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if b:
|
||||
c.font = Font(bold=True)
|
||||
c.alignment = Alignment(vertical="top")
|
||||
|
||||
h1 = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"]
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in [
|
||||
["单位工程", "", "分部", "楼地面装饰工程", "", "", "", ""],
|
||||
["楼地面装饰工程", "", "分部", "块料面层", "", "", "", ""],
|
||||
["块料面层", "", "分部", "石材面层", "", "", "", ""],
|
||||
["石材面层", "011102001", "清单", "石材楼地面",
|
||||
"1.结合层:30厚1:3干硬性水泥砂浆\n2.面层:800×800米黄石材\n3.酸洗打蜡、成品保护", "m²", 126.5, 385],
|
||||
["石材面层", "011106001", "清单", "石材楼梯面层",
|
||||
"1.结合层:30厚1:3干硬性水泥砂浆(同一行连写编号也可识别换行)2.面层:20厚石材", "m²", 38.2, 520],
|
||||
["块料面层", "011102003", "清单", "块料楼地面", "600×600防滑砖、白水泥擦缝", "m²", 342.8, 128.5],
|
||||
["楼地面装饰工程", "", "分部", "找平层", "", "", "", ""],
|
||||
["找平层", "011101001", "清单", "水泥砂浆楼地面", "找平层:20厚1:2水泥砂浆", "m²", 88.4, 35.2],
|
||||
["单位工程", "", "分部", "墙柱面装饰工程", "", "", "", ""],
|
||||
["墙柱面装饰工程", "", "分部", "抹灰", "", "", "", ""],
|
||||
["抹灰", "011201001", "清单", "墙面一般抹灰", "1.15厚混合砂浆\n2.两遍成活", "m²", 856.2, 42.6],
|
||||
]:
|
||||
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")
|
||||
|
||||
h2 = ["名称", "编码", "项目特征", "单位", "工程量", "单价"]
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for r in [
|
||||
["安全文明施工费", "", "", "项", 1, 120000],
|
||||
["临时设施", "", "现场办公室、仓库、加工棚搭设", "项", 1, 60000],
|
||||
["夜间施工增加费", "", "", "项", 1, 8000],
|
||||
]:
|
||||
ws2.append(r)
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
_head(ws2, h2)
|
||||
|
||||
import io
|
||||
bio = io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# xlsx 解析(挂接法 + 校验,全部报 Sheet 行号)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _cell(v):
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v == int(v):
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def _num(v, r, col, errors):
|
||||
s = _cell(v).replace(",", "")
|
||||
if s == "":
|
||||
errors.append("第 %d 行:%s必填(数字)" % (r, col))
|
||||
return None
|
||||
try:
|
||||
return float(s)
|
||||
except ValueError:
|
||||
errors.append("第 %d 行:%s不是数字(%s)" % (r, col, s[:24]))
|
||||
return None
|
||||
|
||||
|
||||
def parse_workbook(path):
|
||||
"""单位工程导入 xlsx → 结构化结果;任何校验不过整份拒绝(errors 带行号)。"""
|
||||
if load_workbook is None:
|
||||
return {"ok": False, "errors": ["缺少 openpyxl,无法解析"]}
|
||||
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("名称"))
|
||||
if not name:
|
||||
errors.append("第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
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
|
||||
if level > MAX_DEPTH:
|
||||
errors.append("第 %d 行:层级超过 5 层(单位工程下最多 %d 级分部)" % (ri, MAX_DEPTH))
|
||||
continue
|
||||
if any(d["pidx"] == pidx and d["name"] == name for d in divides):
|
||||
errors.append("第 %d 行:同一上级下已有同名分部「%s」" % (ri, name))
|
||||
continue
|
||||
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
|
||||
if divides[didx]["level"] > MAX_DEPTH:
|
||||
errors.append("第 %d 行:清单挂在第 %d 级分部下,超过 5 层" % (ri, divides[didx]["level"] + 1))
|
||||
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 ""
|
||||
if not name:
|
||||
errors.append("措施 第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
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)})
|
||||
if errors:
|
||||
return {"ok": False, "errors": errors[:30]}
|
||||
return {"ok": True, "divides": divides, "bills": bills, "prelim": prelim}
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 会话结构:查现状 / 保存(建+改+导)
|
||||
# ---------------------------------------------------------------------------
|
||||
def manual_state(con, sid):
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数。"""
|
||||
row = con.execute("SELECT name, period_from, period_to, x_manual FROM sessions WHERE id=?",
|
||||
(sid,)).fetchone()
|
||||
if not row or not row["x_manual"]:
|
||||
return {"ok": False}
|
||||
secs, units = [], []
|
||||
for s in con.execute("""SELECT id, Name FROM s_sections WHERE session_id=?
|
||||
ORDER BY id""", (sid,)):
|
||||
secs.append({"id": s["id"], "name": s["Name"] or "", "units": []})
|
||||
cnt = {}
|
||||
for b in con.execute("""SELECT uw_id, Kind, COUNT(*) n FROM s_bills WHERE session_id=?
|
||||
GROUP BY uw_id, Kind""", (sid,)):
|
||||
cnt.setdefault(b["uw_id"], {})
|
||||
cnt[b["uw_id"]]["prelim" if b["Kind"] == "prelim" else "item"] = b["n"]
|
||||
secmap = {s["id"]: s for s in secs}
|
||||
for u in con.execute("""SELECT id, section_id, Name FROM s_unit_works WHERE session_id=?
|
||||
ORDER BY section_id, CAST(Number AS INTEGER), id""", (sid,)):
|
||||
c = cnt.get(u["id"], {})
|
||||
it = {"id": u["id"], "name": u["Name"] or "",
|
||||
"n_item": c.get("item", 0), "n_prelim": c.get("prelim", 0)}
|
||||
(secmap[u["section_id"]]["units"].append(it) if u["section_id"] in secmap else units.append(it))
|
||||
return {"ok": True, "name": row["name"] or "", "period_from": row["period_from"],
|
||||
"period_to": row["period_to"], "sections": secs, "free_uws": units}
|
||||
|
||||
|
||||
def _del_unit(cur, uwid):
|
||||
cur.execute("DELETE FROM s_bills WHERE uw_id=?", (uwid,))
|
||||
cur.execute("DELETE FROM s_divides WHERE uw_id=?", (uwid,))
|
||||
cur.execute("DELETE FROM s_unit_works WHERE id=?", (uwid,))
|
||||
|
||||
|
||||
def _import_unit(cur, sid, uwid, parsed):
|
||||
"""整单位工程覆盖导入(先清后写);分部/清单列清单与 open_project 完全同款。"""
|
||||
cur.execute("DELETE FROM s_bills WHERE uw_id=?", (uwid,))
|
||||
cur.execute("DELETE FROM s_divides WHERE uw_id=?", (uwid,))
|
||||
div_ids, div_num = [], {}
|
||||
counters = {} # 每个父级的子分部编号 → 层级编号「1」「1.1」…
|
||||
for i, d in enumerate(parsed["divides"]):
|
||||
pkey = d["pidx"] if d["pidx"] >= 0 else -1
|
||||
counters[pkey] = counters.get(pkey, 0) + 1
|
||||
num = (div_num[d["pidx"]] + "." if d["pidx"] >= 0 else "") + str(counters[pkey])
|
||||
div_num[i] = num
|
||||
cur.execute("""INSERT INTO s_divides(session_id, uw_id, parent_id, Kind,
|
||||
Number, Name, Total, Code, x_seq) VALUES(?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, uwid, div_ids[d["pidx"]] if d["pidx"] >= 0 else None, "item",
|
||||
num, d["name"], None, None, i + 1))
|
||||
div_ids.append(cur.lastrowid)
|
||||
|
||||
seq = {"item": 0, "prelim": 0}
|
||||
for b in parsed["bills"]:
|
||||
seq["item"] += 1
|
||||
_insert_bill(cur, sid, uwid, div_ids[b["didx"]] if b["didx"] is not None else None,
|
||||
b, None, seq["item"])
|
||||
for b in parsed["prelim"]:
|
||||
seq["prelim"] += 1
|
||||
_insert_bill(cur, sid, uwid, None, b, "prelim", seq["prelim"])
|
||||
|
||||
# 分部合价 / 单位工程造价构成(现算链的数据底座)
|
||||
tot = {"item": 0.0, "prelim": 0.0}
|
||||
for b in parsed["bills"]:
|
||||
tot["item"] += b["total"] or 0
|
||||
for b in parsed["prelim"]:
|
||||
tot["prelim"] += b["total"] or 0
|
||||
cur.execute("""UPDATE s_unit_works SET Total=?, DivisionalAndElementalWorks=?, Preliminaries=?,
|
||||
Construction=NULL, CostForHSE=NULL, SundryCosts=NULL, Tax=NULL
|
||||
WHERE id=?""",
|
||||
(round(tot["item"] + tot["prelim"], 2), round(tot["item"], 2),
|
||||
round(tot["prelim"], 2), uwid))
|
||||
_sum_divides(cur, uwid)
|
||||
return {"n_div": len(parsed["divides"]), "n_item": len(parsed["bills"]),
|
||||
"n_prelim": len(parsed["prelim"])}
|
||||
|
||||
|
||||
def _insert_bill(cur, sid, uwid, divid, b, kind, xseq):
|
||||
num, nm, unit = b["num"], b["name"], b["unit"]
|
||||
cur.execute("""INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit,
|
||||
Quantity, Price, Total, Kind, src_remark,
|
||||
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq,
|
||||
x_price0) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, uwid, divid, num or None, nm, b["attr"] or None, unit,
|
||||
b["qty"], b["price"], b["total"], kind, None,
|
||||
norm(nm), norm(b["attr"] or ""), norm(unit),
|
||||
md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq, b["price"]))
|
||||
|
||||
|
||||
def _sum_divides(cur, uwid):
|
||||
"""分部合价=子树清单现算合计(含子分部),自底向上回填(树深 ≤4 级)。
|
||||
先把直属清单合计到各分部,再按「离根深度」从大到小上交——父收到的必是子已算好的值。"""
|
||||
rows = cur.execute("SELECT id, parent_id FROM s_divides WHERE uw_id=?", (uwid,)).fetchall()
|
||||
sums = {r["id"]: 0.0 for r in rows}
|
||||
pid = {r["id"]: r["parent_id"] for r in rows}
|
||||
for did, s0 in cur.execute("""SELECT div_id, COALESCE(SUM(Total),0) FROM s_bills
|
||||
WHERE uw_id=? AND div_id IS NOT NULL GROUP BY div_id""",
|
||||
(uwid,)).fetchall():
|
||||
sums[did] += s0 or 0
|
||||
depth = {}
|
||||
|
||||
def _d(rid):
|
||||
if rid not in depth:
|
||||
depth[rid] = 0 if pid.get(rid) is None else _d(pid[rid]) + 1
|
||||
return depth[rid]
|
||||
|
||||
for rid in pid:
|
||||
_d(rid)
|
||||
for rid in sorted(depth, key=lambda x: -depth[x]):
|
||||
p = pid.get(rid)
|
||||
if p in sums:
|
||||
sums[p] += sums[rid]
|
||||
for rid, s in sums.items():
|
||||
cur.execute("UPDATE s_divides SET Total=? WHERE id=?", (round(s, 2), rid))
|
||||
|
||||
|
||||
def save_tree(con, body):
|
||||
"""建/改手工工程目录树并按单位工程导 Excel。
|
||||
body = {sid?, name, period_from, period_to,
|
||||
tree: [{id?, name, units: [{id?, name, file?}]}], free_uws?: 同款}
|
||||
file = 已上传到软件目录的 xlsx 路径(/api/admin/upload 返回值)。"""
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "工程名称必填"}
|
||||
pf, pt = body.get("period_from"), body.get("period_to")
|
||||
if pf is None or pt is None:
|
||||
return {"ok": False, "msg": "基准期次必填"}
|
||||
tree = body.get("tree") or []
|
||||
flat = []
|
||||
for s in tree:
|
||||
if not (s.get("name") or "").strip():
|
||||
return {"ok": False, "msg": "单项工程名称不能为空"}
|
||||
if not s.get("units"):
|
||||
return {"ok": False, "msg": "「%s」下至少一个单位工程" % s["name"]}
|
||||
for u in s["units"]:
|
||||
if not (u.get("name") or "").strip():
|
||||
return {"ok": False, "msg": "单位工程名称不能为空(%s 下)" % s["name"]}
|
||||
flat.append((s, u))
|
||||
if not tree:
|
||||
return {"ok": False, "msg": "至少一个单项工程"}
|
||||
# free_uws(无单项层)不进编辑器:手工树固定三层,不造自由挂靠
|
||||
|
||||
cur = con.cursor()
|
||||
sid = body.get("sid")
|
||||
if sid:
|
||||
row = cur.execute("SELECT x_manual FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not row or not row["x_manual"]:
|
||||
return {"ok": False, "msg": "只有手工工程才能用「导入项目」编辑目录树"}
|
||||
else:
|
||||
# 同名:已有手工工程=原地续用;源文件工程=拒绝(不覆盖别人)
|
||||
same = cur.execute("SELECT id, x_manual FROM sessions WHERE TRIM(name)=? ORDER BY id DESC LIMIT 1",
|
||||
(name,)).fetchone()
|
||||
if same:
|
||||
if not same["x_manual"]:
|
||||
return {"ok": False, "msg": "已有同名工程(源文件导入),请换个名称"}
|
||||
sid = same["id"]
|
||||
else:
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_manual)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,1)""",
|
||||
(name, pf, pf, pt, "", "", "", "", "",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
cur.execute("UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=? WHERE id=?",
|
||||
(name, pf, pt, pf, sid))
|
||||
|
||||
# ---- 结构同步(决策 230 补记:单项/单位均可在组内上下移动)----
|
||||
# 单位工程按 id 对位:改名保留数据 / 删除级联 / 新增先插(归属与编号稍后统一指)。
|
||||
keep_uw = {u["id"] for s in tree for u in s["units"] if u.get("id")}
|
||||
for (uwid,) in cur.execute("SELECT id FROM s_unit_works WHERE session_id=?", (sid,)).fetchall():
|
||||
if uwid not in keep_uw:
|
||||
_del_unit(cur, uwid)
|
||||
for s in tree:
|
||||
for u in s["units"]:
|
||||
if u.get("id"):
|
||||
cur.execute("UPDATE s_unit_works SET Name=? WHERE id=? AND session_id=?",
|
||||
(u["name"].strip(), u["id"], sid))
|
||||
else:
|
||||
cur.execute("""INSERT INTO s_unit_works(session_id, section_id, Number, Name,
|
||||
Specialty, Total) VALUES(?,'',NULL,?,NULL,NULL)""",
|
||||
(sid, u["name"].strip()))
|
||||
u["id"] = cur.lastrowid
|
||||
# 单项工程整组重建=显示顺序即 tree 序(决策 103 只对源文件工程生效;手工工程
|
||||
# 无源文件时单位工程排序回退 natkey(Number) —— 按组内位置重写编号即持久化组内顺序;
|
||||
# 重建只动 s_sections 行,单位工程 id/数据不动,仅重指 section_id)。
|
||||
cur.execute("DELETE FROM s_sections WHERE session_id=?", (sid,))
|
||||
for si, s in enumerate(tree, 1):
|
||||
cur.execute("INSERT INTO s_sections(session_id, Number, Name, Total, Ratios) VALUES(?,?,?,?,?)",
|
||||
(sid, str(si), s["name"].strip(), None, None))
|
||||
secid = cur.lastrowid
|
||||
for ui, u in enumerate(s["units"], 1):
|
||||
cur.execute("UPDATE s_unit_works SET section_id=?, Number=? WHERE id=?",
|
||||
(secid, str(ui), u["id"]))
|
||||
s["id"] = secid
|
||||
|
||||
# ---- 按单位工程导入(有 file 的整单位工程覆盖;没 file 的保留现有数据)----
|
||||
counts = []
|
||||
for s in tree:
|
||||
for u in s["units"]:
|
||||
fp = (u.get("file") or "").strip()
|
||||
if not fp:
|
||||
continue
|
||||
parsed = parse_workbook(fp)
|
||||
if not parsed.get("ok"):
|
||||
return {"ok": False, "msg": "「%s」导入文件有误:%s" % (u["name"], ";".join(parsed["errors"][:3]))}
|
||||
counts.append({"uw": u["name"], **_import_unit(cur, sid, u["id"], parsed)})
|
||||
|
||||
# ---- 两级汇总现算:单项 Total / 工程 x_total ----
|
||||
for s in tree:
|
||||
cur.execute("""UPDATE s_sections SET Total=(
|
||||
SELECT COALESCE(SUM(Total),0) FROM s_unit_works WHERE section_id=?)
|
||||
WHERE id=?""", (s["id"], s["id"]))
|
||||
cur.execute("UPDATE sessions SET x_total=(SELECT COALESCE(SUM(Total),0) FROM s_unit_works WHERE session_id=?) WHERE id=?",
|
||||
(sid, sid))
|
||||
return {"ok": True, "session_id": sid, "imported": counts}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 手工工程导出 Excel(决策 229,2026-10-27 主人定):模板架子+合价/备注
|
||||
# 文件夹=项目名称,一个单位工程一个 xlsx(文件名=单位工程名);
|
||||
# 分部分项 10 列 / 措施项目 8 列——只带清单、不带定额(主人定);
|
||||
# 合价=工程量×单价现算;备注=审核备注;导出件可直接回导入(多出的合价/备注列解析端忽略)。
|
||||
# ---------------------------------------------------------------------------
|
||||
_FB_HEAD_X = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
|
||||
_CS_HEAD_X = ["名称", "编码", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
|
||||
|
||||
|
||||
def _safe_sheet_name(name):
|
||||
return re.sub(r'[\\/:*?"<>|]', "_", (name or "").strip()) or "单位工程"
|
||||
|
||||
|
||||
def export_excel_bytes(sc, sid):
|
||||
"""手工工程 → (zip 字节, 文件名, 错误)。zip 内:项目名/单位工程名.xlsx × n。"""
|
||||
if Workbook is None:
|
||||
return None, None, "缺少 openpyxl,无法导出 Excel"
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
proj = (srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程"
|
||||
uws = list(sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)))
|
||||
if not uws:
|
||||
return None, None, "本工程还没有单位工程,先在「导入项目」里建目录并导入 Excel"
|
||||
divs = {}
|
||||
for r in sc.execute("SELECT * FROM s_divides WHERE session_id=? ORDER BY x_seq, id", (sid,)):
|
||||
divs.setdefault(r["uw_id"], []).append(dict(r))
|
||||
bills = {}
|
||||
for r in sc.execute("""SELECT * FROM s_bills WHERE session_id=?
|
||||
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
|
||||
bills.setdefault(r["uw_id"], []).append(dict(r))
|
||||
|
||||
def b_total(b):
|
||||
try:
|
||||
if b["Quantity"] is not None and b["Price"] is not None:
|
||||
return round(float(b["Quantity"]) * float(b["Price"]), 2)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return b["Total"]
|
||||
|
||||
def fb_rows(uw_id):
|
||||
"""分部分项行:分部树递归(上一级名称挂接法照模板),清单挂自己上级名下。"""
|
||||
ds = [d for d in divs.get(uw_id, []) if d["Kind"] != "prelim"]
|
||||
ids = {d["id"] for d in ds}
|
||||
kids, roots = {}, []
|
||||
for d in ds:
|
||||
p = d["parent_id"]
|
||||
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
|
||||
by_div = {}
|
||||
for b in bills.get(uw_id, []):
|
||||
if b["Kind"] == "prelim":
|
||||
continue
|
||||
by_div.setdefault(b["div_id"], []).append(b)
|
||||
|
||||
def walk(d, parent_name, out):
|
||||
out.append([parent_name, "", "分部", d["Name"] or "", "", "", "", "", "", ""])
|
||||
for b in by_div.get(d["id"], []):
|
||||
out.append([d["Name"] or "", b["Number"] or "", "清单", b["Name"] or "",
|
||||
b["Attr"] or "", b["Unit"] or "", b["Quantity"], b["Price"],
|
||||
b_total(b), b["x_remark"] or ""])
|
||||
for sub in kids.get(d["id"], []):
|
||||
walk(sub, d["Name"] or "", out)
|
||||
|
||||
out = []
|
||||
for d in roots:
|
||||
walk(d, "单位工程", out)
|
||||
for b in by_div.get(None, []): # 无分部挂靠的清单:落在首个一级分部名下兜底
|
||||
pn = roots[0]["Name"] if roots else "单位工程"
|
||||
out.append([pn, b["Number"] or "", "清单", b["Name"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
return out
|
||||
|
||||
import io as _io
|
||||
folder = _safe_sheet_name(proj)
|
||||
used, buf = {}, _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for u in uws:
|
||||
wb = Workbook()
|
||||
ws0 = wb.active
|
||||
ws0.title = "填写说明"
|
||||
ws0.column_dimensions["A"].width = 90
|
||||
for i, (t, bold) in enumerate([
|
||||
("「%s」导出件(决策 229)" % u["Name"], True),
|
||||
("", False),
|
||||
("一、本件由软件导出,可直接在「导入项目」里对同一单位工程回导(整单位工程覆盖)。", False),
|
||||
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
|
||||
("三、只到清单级:不导定额、不导工料机。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if bold:
|
||||
c.font = Font(bold=True)
|
||||
h1 = _FB_HEAD_X
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in fb_rows(u["id"]):
|
||||
ws1.append(r)
|
||||
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
|
||||
ws1.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h1, 1):
|
||||
cell = ws1.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws1.freeze_panes = "A2"
|
||||
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")
|
||||
h2 = _CS_HEAD_X
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for b in bills.get(u["id"], []):
|
||||
if b["Kind"] != "prelim":
|
||||
continue
|
||||
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h2, 1):
|
||||
cell = ws2.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws2.freeze_panes = "A2"
|
||||
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
bio = _io.BytesIO()
|
||||
wb.save(bio)
|
||||
nm = _safe_sheet_name(u["Name"]) + ".xlsx"
|
||||
k = 2
|
||||
while nm in used:
|
||||
nm = "%s(%d).xlsx" % (_safe_sheet_name(u["Name"]), k)
|
||||
k += 1
|
||||
used[nm] = True
|
||||
zo.writestr("%s/%s" % (folder, nm), bio.getvalue())
|
||||
return buf.getvalue(), proj + "-审核版.zip", None
|
||||
Reference in New Issue
Block a user