feat(price): 信息价/市场价重设计——目录树+行内编辑+只收标准模板+导出一份数据(决策42)
- schema: 新增 price_dirs 目录树(批次级单根/多级/仅叶挂行),prices.dir_id;Class 冗余完整路径文本 - 导入只收标准模板 xlsx:表头严格校验(HTML/别名/多sheet拆批退役);名称默认=文件名可改;期次从文件名认 - 后台明细页重做:左树行内增删改名/上下移(↑↓✕两段式确认、选中按钮常显),右表行内新增/编辑(重算比对键即刻生效) - 导出 zip = 价格明细.xlsx(目录路径+批次信息页签)+ 附件原件,导入可复原 - 壳/跨页跳转带版本参数根治 WebView2 旧缓存;导入弹框文件框只收 .xlsx - 附 P0/P1 接口测试夹具与价格重设计回归(新增 test_price_redesign 等 8 件,全套 148 项绿)
This commit is contained in:
@@ -114,6 +114,8 @@ def ensure_attach_schema():
|
||||
pcols = [r[1] for r in con.execute("PRAGMA table_info(prices)")]
|
||||
if "Block" not in pcols: # 块名(三级目录:批次→块→分类,2026-09-28 定)
|
||||
con.execute("ALTER TABLE prices ADD COLUMN Block TEXT")
|
||||
if "dir_id" not in pcols: # 挂在哪个目录(price_dirs.id;0/NULL=未分类,2026-10-12)
|
||||
con.execute("ALTER TABLE prices ADD COLUMN dir_id INTEGER")
|
||||
# 2026-10-08:次精确档 md5(名称归一+单位归一)——lmes/prices 同口径(老库补列+回填见 backfill_hash_semi)
|
||||
lcols = [r[1] for r in con.execute("PRAGMA table_info(lmes)")]
|
||||
if "x_hash_semi" not in lcols:
|
||||
@@ -1251,8 +1253,16 @@ def api_audit(body):
|
||||
if nm:
|
||||
row = con.execute("SELECT id FROM sessions WHERE TRIM(name)=? ORDER BY id DESC LIMIT 1",
|
||||
(nm,)).fetchone()
|
||||
sid = row["id"] if row else None
|
||||
if sid is not None:
|
||||
# 原地续用 = wipe 后重写(与「重新解析」/open_project 注释同口径)。
|
||||
# ⚠️ 此前漏了 wipe:二次打开同名工程会在旧清单上**叠加翻倍**,分组/检索/比对
|
||||
# 全部失真(2026-10-12 接口测试抓到,test_api_p0 防翻倍回归兜住)。
|
||||
# 事务安全:wipe 与 open_project 同连接同事务,解析抛异常时 con.close()
|
||||
# 回滚,旧数据原样保留;成功则备注由 restore_remarks 按 rkey 回填到新行。
|
||||
sess.wipe(con, sid)
|
||||
sid, stat = sess.open_project(con, [(path, os.path.basename(path))], body, job,
|
||||
sid=row["id"] if row else None)
|
||||
sid=sid)
|
||||
# 2026-10-06:关联后台项目批次(同源文件),工作台才能只读展示该项目的询价附件
|
||||
_link_batch(con, sid, os.path.basename(path), body.get("name"))
|
||||
except Exception as e:
|
||||
@@ -2555,16 +2565,29 @@ def _sweep_orphan_attach(con, result):
|
||||
"n_bill": n_bill, "n_norm": n_norm, "n_lme": n_lme, "n_price": n_price, "n_inq": n_inq}
|
||||
|
||||
|
||||
def api_prices(bid, page, size):
|
||||
"""价格批次的明细(信息价 / 市场价的每条材料价格)"""
|
||||
def api_prices(bid, page, size, dir_id=None, subtree=0):
|
||||
"""价格批次的明细(信息价 / 市场价的每条材料价格)。
|
||||
|
||||
2026-10-12 明细页重做:行改 **dict**(前端不再按脆弱下标取列),
|
||||
dir_id 只取该目录的行(subtree=1 含子孙子树,目录树点击汇总用);不传 = 全部。
|
||||
"""
|
||||
c = conn()
|
||||
total = c.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
rows = c.execute("""SELECT Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Class, Note, Block
|
||||
FROM prices WHERE batch_id=? ORDER BY id LIMIT ? OFFSET ?""",
|
||||
(bid, size, (page - 1) * size)).fetchall()
|
||||
w, args = ["batch_id=?"], [bid]
|
||||
if dir_id is not None and str(dir_id) != "":
|
||||
d = int(dir_id)
|
||||
if d > 0:
|
||||
ids = _dir_subtree_ids(c, bid, d) if int(subtree) else [d]
|
||||
w.append("dir_id IN (%s)" % ",".join(map(str, ids)))
|
||||
else: # 0 = 未分类
|
||||
w.append("(dir_id=0 OR dir_id IS NULL)")
|
||||
where = " AND ".join(w)
|
||||
total = c.execute("SELECT COUNT(*) FROM prices WHERE %s" % where, args).fetchone()[0]
|
||||
rows = c.execute("""SELECT id, Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Note, dir_id, Class
|
||||
FROM prices WHERE %s ORDER BY dir_id, id LIMIT ? OFFSET ?""" % where,
|
||||
args + [size, (page - 1) * size]).fetchall()
|
||||
c.close()
|
||||
return {"total": total, "rows": [list(r) for r in rows]}
|
||||
return {"total": total, "rows": [dict(r) for r in rows]}
|
||||
|
||||
|
||||
def _norm(s):
|
||||
@@ -2595,33 +2618,388 @@ def find_dup(con, kind, body):
|
||||
|
||||
|
||||
def _price_parse(path):
|
||||
"""价格文件解析分派:按扩展名选 HTML / Excel 解析器。
|
||||
"""价格文件解析分派(2026-10-12 重设计):**只收标准模板 .xlsx**,其余直接报错。
|
||||
|
||||
两条入口共用后半段(price_html.to_records)与同一套 hash 口径,
|
||||
所以进库后 HTML 导入的价格和 Excel 导入的价格能互相命中。
|
||||
HTML 导入退役(主人定「只能导入 Excel 的标准模板」);price_html 解析器留档不删,
|
||||
guess_period(文件名认期次)等工具函数仍从它引用。
|
||||
"""
|
||||
low = os.path.splitext(path)[1].lower()
|
||||
if low in (".xlsx", ".xls"):
|
||||
if low == ".xlsx":
|
||||
return price_xlsx.parse(path)
|
||||
return price.parse(path)
|
||||
raise ValueError("只支持标准模板 Excel(.xlsx)。请点「标准模板」按钮下载后填写导入")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 价格目录树(2026-10-12 重设计):单根(批次名,不落库)+ 多级 price_dirs;
|
||||
# 行挂叶子(prices.dir_id),prices.Class 冗余完整路径文本;dir_id=0/NULL=未分类。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _dir_path(con, dir_id):
|
||||
"""目录 id → 完整路径文本('a/b/c');0/None → ''(未分类)"""
|
||||
parts, cur = [], dir_id
|
||||
while cur:
|
||||
row = con.execute("SELECT id, parent_id, name FROM price_dirs WHERE id=?", (cur,)).fetchone()
|
||||
if not row:
|
||||
break
|
||||
parts.append(row["name"])
|
||||
cur = row["parent_id"]
|
||||
return price_xlsx.DIR_SEP.join(reversed(parts))
|
||||
|
||||
|
||||
def _dir_ensure_path(con, bid, path):
|
||||
"""按 'a/b/c' 逐级建目录(缺才建),返回叶子目录 id;空路径 → 0(未分类)"""
|
||||
parent = 0
|
||||
for seg in [s.strip() for s in (path or "").split(price_xlsx.DIR_SEP) if s.strip()]:
|
||||
row = con.execute("SELECT id FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=?",
|
||||
(bid, parent, seg)).fetchone()
|
||||
if row:
|
||||
parent = row["id"]
|
||||
else:
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
parent = con.execute("INSERT INTO price_dirs(batch_id, parent_id, name, seq) VALUES(?,?,?,?)",
|
||||
(bid, parent, seg, seq)).lastrowid
|
||||
return parent
|
||||
|
||||
|
||||
def _dir_children(con, bid, parent_id):
|
||||
"""同级目录(排序输出)"""
|
||||
return con.execute("""SELECT id, parent_id, name, seq FROM price_dirs
|
||||
WHERE batch_id=? AND parent_id=? ORDER BY seq, id""",
|
||||
(bid, parent_id)).fetchall()
|
||||
|
||||
|
||||
def _dir_subtree_ids(con, bid, dir_id):
|
||||
"""目录 + 全部子孙 id(含自身)——统计/展示用"""
|
||||
out, stack = [], [dir_id]
|
||||
while stack:
|
||||
d = stack.pop()
|
||||
out.append(d)
|
||||
stack.extend(r["id"] for r in _dir_children(con, bid, d))
|
||||
return out
|
||||
|
||||
|
||||
def _dir_is_leaf(con, bid, dir_id):
|
||||
return not _dir_children(con, bid, dir_id)
|
||||
|
||||
|
||||
def _price_recalc_row(con, pid):
|
||||
"""行内容变化后重算归一键 + 同步 Class 路径(与导入同一套口径,api_import_price 共用)"""
|
||||
r = con.execute("""SELECT Name, Specification, Unit, dir_id FROM prices WHERE id=?""", (pid,)).fetchone()
|
||||
if not r:
|
||||
return
|
||||
cls = _dir_path(con, r["dir_id"])
|
||||
h = _md5(r["Name"], r["Specification"], r["Unit"])
|
||||
con.execute("""UPDATE prices SET x_name_norm=?, x_spec_norm=?, x_unit_norm=?,
|
||||
x_hash_exact=?, x_hash_semi=?, Class=? WHERE id=?""",
|
||||
(_norm(r["Name"]), _norm(r["Specification"]), _norm(r["Unit"]),
|
||||
h, _md5(r["Name"], r["Unit"]), cls, pid))
|
||||
|
||||
|
||||
def _price_dir_counts(con, bid):
|
||||
"""每个目录 id 的**子树行数**(含未分类 dir=0);树节点计数用"""
|
||||
counts = {0: 0}
|
||||
for r in con.execute("SELECT dir_id, COUNT(*) n FROM prices WHERE batch_id=? GROUP BY dir_id",
|
||||
(bid,)):
|
||||
counts[r["dir_id"] or 0] = r["n"]
|
||||
agg = {}
|
||||
for d in [r["id"] for r in con.execute("SELECT id FROM price_dirs WHERE batch_id=?", (bid,))]:
|
||||
agg[d] = sum(counts.get(x, 0) for x in _dir_subtree_ids(con, bid, d))
|
||||
agg[0] = counts.get(0, 0)
|
||||
return agg
|
||||
|
||||
|
||||
def api_price_dirs(con, bid):
|
||||
"""目录树(含每节点子树行数、是否叶子);批次不存在返回空树"""
|
||||
b = con.execute("SELECT id, Name FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
rows = [{"id": r["id"], "parent_id": r["parent_id"], "name": r["name"], "seq": r["seq"]}
|
||||
for r in _dir_children(con, bid, 0)]
|
||||
def build(parent):
|
||||
return [{"id": r["id"], "name": r["name"], "seq": r["seq"],
|
||||
"leaf": _dir_is_leaf(con, bid, r["id"]),
|
||||
"children": build(r["id"])}
|
||||
for r in _dir_children(con, bid, parent)]
|
||||
counts = _price_dir_counts(con, bid)
|
||||
return {"ok": True, "batch_id": bid, "batch_name": b["Name"],
|
||||
"tree": build(0), "counts": counts,
|
||||
"n_uncat": counts.get(0, 0)}
|
||||
|
||||
|
||||
def api_price_dir_save(con, bid, body):
|
||||
"""目录增/改名/移动/上下移/删除。op: add|rename|move|seq|del"""
|
||||
op = body.get("op")
|
||||
b = con.execute("SELECT id FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
if op == "add":
|
||||
parent = int(body.get("parent_id") or 0)
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "目录名称不能为空"}
|
||||
if parent and not con.execute("SELECT 1 FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(parent, bid)).fetchone():
|
||||
return {"ok": False, "msg": "上级目录不存在"}
|
||||
dup = con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=?",
|
||||
(bid, parent, name)).fetchone()
|
||||
if dup:
|
||||
return {"ok": False, "msg": "同级已有同名目录「%s」" % name}
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
did = con.execute("INSERT INTO price_dirs(batch_id, parent_id, name, seq) VALUES(?,?,?,?)",
|
||||
(bid, parent, name, seq)).lastrowid
|
||||
con.commit()
|
||||
return {"ok": True, "id": did, "msg": "已新增目录「%s」" % name}
|
||||
|
||||
did = int(body.get("id") or 0)
|
||||
d = con.execute("SELECT id, parent_id, name, seq FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(did, bid)).fetchone()
|
||||
if not d:
|
||||
return {"ok": False, "msg": "目录不存在"}
|
||||
|
||||
if op == "rename":
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "目录名称不能为空"}
|
||||
dup = con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=? AND id<>?",
|
||||
(bid, d["parent_id"], name, did)).fetchone()
|
||||
if dup:
|
||||
return {"ok": False, "msg": "同级已有同名目录「%s」" % name}
|
||||
con.execute("UPDATE price_dirs SET name=? WHERE id=?", (name, did))
|
||||
sub = ",".join(map(str, _dir_subtree_ids(con, bid, did)))
|
||||
pids = [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id IN (%s)" % sub, (bid,))]
|
||||
for pid in pids:
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已改名「%s」(%d 条行路径同步更新)" % (name, len(pids))}
|
||||
|
||||
if op == "move": # 换父(子树整枝跟动)
|
||||
parent = int(body.get("parent_id") or 0)
|
||||
if parent:
|
||||
p = con.execute("SELECT id, parent_id FROM price_dirs WHERE id=? AND batch_id=?",
|
||||
(parent, bid)).fetchone()
|
||||
if not p:
|
||||
return {"ok": False, "msg": "上级目录不存在"}
|
||||
cur, cyc = p["id"], False
|
||||
while cur: # 不能移到自己的子孙下面
|
||||
if cur == did:
|
||||
cyc = True
|
||||
break
|
||||
row = con.execute("SELECT parent_id FROM price_dirs WHERE id=?", (cur,)).fetchone()
|
||||
cur = row["parent_id"] if row else 0
|
||||
if cyc:
|
||||
return {"ok": False, "msg": "不能移动到自己的子目录下面"}
|
||||
if con.execute("SELECT 1 FROM price_dirs WHERE batch_id=? AND parent_id=? AND name=? AND id<>?",
|
||||
(bid, parent, d["name"], did)).fetchone():
|
||||
return {"ok": False, "msg": "目标位置已有同名目录「%s」" % d["name"]}
|
||||
seq = con.execute("SELECT COALESCE(MAX(seq),0)+1 FROM price_dirs WHERE batch_id=? AND parent_id=?",
|
||||
(bid, parent)).fetchone()[0]
|
||||
con.execute("UPDATE price_dirs SET parent_id=?, seq=? WHERE id=?", (parent, seq, did))
|
||||
for pid in [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id IN (%s)"
|
||||
% ",".join(map(str, _dir_subtree_ids(con, bid, did))), (bid,))]:
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已移动(子目录整枝跟动)"}
|
||||
|
||||
if op == "seq": # 上移 / 下移:与相邻同级交换 seq
|
||||
delta = 1 if body.get("dir") == "down" else -1
|
||||
sibs = _dir_children(con, bid, d["parent_id"])
|
||||
i = next((k for k, r in enumerate(sibs) if r["id"] == did), -1)
|
||||
j = i + delta
|
||||
if i < 0 or j < 0 or j >= len(sibs):
|
||||
return {"ok": False, "msg": "已经到头了"}
|
||||
other = sibs[j]
|
||||
con.execute("UPDATE price_dirs SET seq=? WHERE id=?", (other["seq"], did))
|
||||
con.execute("UPDATE price_dirs SET seq=? WHERE id=?", (d["seq"], other["id"]))
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已%s(子目录整枝跟动)" % ("下移" if delta > 0 else "上移")}
|
||||
|
||||
if op == "del":
|
||||
kids = _dir_children(con, bid, did)
|
||||
if kids:
|
||||
return {"ok": False, "msg": "先处理子目录(%d 个)再删除" % len(kids)}
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=? AND dir_id=?",
|
||||
(bid, did)).fetchone()[0]
|
||||
if n: # 挂着的行落「未分类」(防误删数据)
|
||||
con.execute("UPDATE prices SET dir_id=0 WHERE batch_id=? AND dir_id=?", (bid, did))
|
||||
for pid in [r["id"] for r in con.execute(
|
||||
"SELECT id FROM prices WHERE batch_id=? AND dir_id=0", (bid,))]:
|
||||
_price_recalc_row(con, pid)
|
||||
con.execute("DELETE FROM price_dirs WHERE id=?", (did,))
|
||||
con.commit()
|
||||
msg = "已删除目录「%s」" % d["name"] + ("(%d 条行已移入「未分类」)" % n if n else "")
|
||||
return {"ok": True, "msg": msg}
|
||||
|
||||
return {"ok": False, "msg": "未知操作:%s" % op}
|
||||
|
||||
|
||||
def api_price_row_save(con, bid, body):
|
||||
"""价格行新增 / 编辑(行内编辑)。op: add|edit|del
|
||||
|
||||
约束(主人 2026-10-12 定):只有**最底层目录**可以新增行;
|
||||
编辑改了 名称/规格/单位 → 重算比对键(与导入同口径),工作台比对即刻生效。
|
||||
"""
|
||||
op = body.get("op")
|
||||
b = con.execute("SELECT id FROM batches WHERE id=? AND kind<>'project'", (bid,)).fetchone()
|
||||
if not b:
|
||||
return {"ok": False, "msg": "批次不存在或不是价格批次"}
|
||||
|
||||
if op == "del":
|
||||
pid = int(body.get("id") or 0)
|
||||
if not con.execute("SELECT 1 FROM prices WHERE id=? AND batch_id=?", (pid, bid)).fetchone():
|
||||
return {"ok": False, "msg": "行不存在"}
|
||||
con.execute("DELETE FROM prices WHERE id=?", (pid,))
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
con.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n, bid))
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已删除该行(本批次剩 %d 条)" % n}
|
||||
|
||||
dir_id = int(body.get("dir_id") or 0)
|
||||
if dir_id:
|
||||
d = con.execute("SELECT id FROM price_dirs WHERE id=? AND batch_id=?", (dir_id, bid)).fetchone()
|
||||
if not d:
|
||||
return {"ok": False, "msg": "所属目录不存在"}
|
||||
if not _dir_is_leaf(con, bid, dir_id):
|
||||
return {"ok": False, "msg": "只有最底层目录才可以挂价格行(该目录还有子目录)"}
|
||||
vals = {
|
||||
"Code": (body.get("code") or "").strip(),
|
||||
"Name": (body.get("name") or "").strip(),
|
||||
"Specification": (body.get("spec") or "").strip(),
|
||||
"Unit": (body.get("unit") or "").strip(),
|
||||
"NoTaxPrice": body.get("notax"),
|
||||
"TaxRate": body.get("taxrate"),
|
||||
"TaxPrice": body.get("taxprice"),
|
||||
"Note": (body.get("note") or "").strip(),
|
||||
}
|
||||
def _fnum(v):
|
||||
try:
|
||||
return float(str(v).replace(",", "").replace("¥", "")) if str(v or "").strip() else None
|
||||
except Exception:
|
||||
return None
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"] = (
|
||||
_fnum(vals["NoTaxPrice"]), _fnum(vals["TaxRate"]), _fnum(vals["TaxPrice"]))
|
||||
miss = [k for k, klabel in (("Name", "材料名称"), ("Unit", "单位")) if not vals[k]]
|
||||
if vals["NoTaxPrice"] is None:
|
||||
miss.append("不含税单价")
|
||||
if miss:
|
||||
return {"ok": False, "msg": "请填写:" + "、".join(miss)}
|
||||
|
||||
if op == "add":
|
||||
if not dir_id:
|
||||
return {"ok": False, "msg": "请选择所属目录(最底层目录或「未分类」)"}
|
||||
cur = con.execute("""INSERT INTO prices(batch_id, Code, Name, Specification, Unit,
|
||||
NoTaxPrice, TaxRate, TaxPrice, Note, Class, dir_id, Block,
|
||||
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi,
|
||||
x_period_start_m, x_period_end_m)
|
||||
SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, x_period_start_m, x_period_end_m
|
||||
FROM batches WHERE id=?""",
|
||||
(bid, vals["Code"], vals["Name"], vals["Specification"], vals["Unit"],
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"], vals["Note"],
|
||||
"", dir_id, "", "", "", "", "", "", bid))
|
||||
_price_recalc_row(con, cur.lastrowid)
|
||||
n = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
con.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n, bid))
|
||||
con.commit()
|
||||
return {"ok": True, "id": cur.lastrowid, "msg": "已新增(%s)" % vals["Name"]}
|
||||
|
||||
if op == "edit":
|
||||
pid = int(body.get("id") or 0)
|
||||
if not con.execute("SELECT 1 FROM prices WHERE id=? AND batch_id=?", (pid, bid)).fetchone():
|
||||
return {"ok": False, "msg": "行不存在"}
|
||||
if not dir_id:
|
||||
return {"ok": False, "msg": "请选择所属目录(最底层目录或「未分类」)"}
|
||||
con.execute("""UPDATE prices SET Code=?, Name=?, Specification=?, Unit=?,
|
||||
NoTaxPrice=?, TaxRate=?, TaxPrice=?, Note=?, dir_id=? WHERE id=?""",
|
||||
(vals["Code"], vals["Name"], vals["Specification"], vals["Unit"],
|
||||
vals["NoTaxPrice"], vals["TaxRate"], vals["TaxPrice"], vals["Note"],
|
||||
dir_id, pid))
|
||||
_price_recalc_row(con, pid)
|
||||
con.commit()
|
||||
return {"ok": True, "msg": "已保存(比对键已按新内容重算)"}
|
||||
|
||||
return {"ok": False, "msg": "未知操作:%s" % op}
|
||||
|
||||
|
||||
def api_price_export(con, bid):
|
||||
"""导出「一份数据」:zip(价格明细.xlsx [模板 v2 格式,含目录层级] + 附件原件 + 批次信息页签)。
|
||||
|
||||
返回 (bytes, 文件名);调用方按 Content-Disposition 吐给浏览器。
|
||||
"""
|
||||
import io as _io, zipfile
|
||||
b = con.execute("""SELECT id, kind, Name, x_publisher, x_province, x_city, x_district,
|
||||
x_period_start_m, x_period_end_m, x_note, x_attach_sha
|
||||
FROM batches WHERE id=? AND kind<>'project'""", (bid,)).fetchone()
|
||||
if not b:
|
||||
raise ValueError("批次不存在或不是价格批次")
|
||||
att = None
|
||||
if b["x_attach_sha"]:
|
||||
att = con.execute("SELECT stored_path, original_name FROM attachments WHERE sha256=?",
|
||||
(b["x_attach_sha"],)).fetchone()
|
||||
|
||||
buf = _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr("价格明细.xlsx", _price_export_xlsx(con, b))
|
||||
if att:
|
||||
fp = os.path.join(DATA_DIR, (att["stored_path"] or "").replace("/", os.sep))
|
||||
if os.path.exists(fp):
|
||||
z.write(fp, att["original_name"] or "附件原件")
|
||||
fn = ("%s.zip" % (b["Name"] or "价格批次")).replace("/", "_")
|
||||
return buf.getvalue(), fn
|
||||
|
||||
|
||||
def _price_export_xlsx(con, b):
|
||||
"""批次 → 标准模板 v2 格式的 xlsx bytes(目录=多级路径;附「批次信息」页签)"""
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment
|
||||
bid = b["id"]
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "价格明细"
|
||||
head_fill, head_font = PatternFill("solid", fgColor="1F5FAE"), Font(color="FFFFFF", bold=True, size=11)
|
||||
ws.append(price_xlsx.COLS)
|
||||
for c in ws[1]:
|
||||
c.fill, c.font = head_fill, head_font
|
||||
c.alignment = Alignment(horizontal="center", vertical="center")
|
||||
rows = con.execute("""SELECT Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice,
|
||||
Note, Class FROM prices WHERE batch_id=? ORDER BY dir_id, id""", (bid,)).fetchall()
|
||||
for r in rows:
|
||||
ws.append([r["Class"], r["Code"], r["Name"], r["Specification"], r["Unit"],
|
||||
r["NoTaxPrice"], (("%g" % r["TaxRate"]) if r["TaxRate"] is not None else ""),
|
||||
r["TaxPrice"], r["Note"]])
|
||||
for col, w in zip("ABCDEFGHI", (32, 12, 30, 22, 8, 14, 9, 14, 28)):
|
||||
ws.column_dimensions[col].width = w
|
||||
ws.freeze_panes = "A2"
|
||||
hb = wb.create_sheet("批次信息")
|
||||
for k, v in [("名称", b["Name"]), ("类型", {"info": "信息价", "market": "市场价"}.get(b["kind"], b["kind"])),
|
||||
("发布单位", b["x_publisher"] or ""), ("地区", "-".join(x for x in
|
||||
[b["x_province"], b["x_city"], b["x_district"]] if x)),
|
||||
("期次起", ym2str(b["x_period_start_m"])), ("期次止", ym2str(b["x_period_end_m"])),
|
||||
("备注", b["x_note"] or "")]:
|
||||
hb.append([k, v])
|
||||
hb.column_dimensions["A"].width = 14
|
||||
hb.column_dimensions["B"].width = 60
|
||||
bio = io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
def api_import_price(con, body):
|
||||
"""信息价 / 市场价导入:HTML 或 Excel。
|
||||
"""信息价 / 市场价导入(2026-10-12 重设计):**只收标准模板 .xlsx,一个文件 = 一个批次**。
|
||||
|
||||
**一个块 = 一个批次**(2026-10-06 改,2026-09-28 定的「一个文件 = 一个批次」作废)。
|
||||
理由:一个价格文件常含多个市场(建材 / 苗木 / 横琴 / 万山),期次还各不相同
|
||||
(2026年7月 vs 2026年4-6月)。挤在一个批次里,批次只能有一个期次 → 只能留空
|
||||
→ ym2str('') 抛 ValueError → 信息价列表整页 500(审查报告里的 DB-1)。
|
||||
拆块之后每个批次有自己的期次:块名里认得出就用块自己的,认不出才用弹框填的。
|
||||
· 名称:弹框填的优先;留空 = 文件名(去扩展名,主人定「名称和附件名称一致(默认),可修改」)
|
||||
· 目录:模板「目录」列按 'a/b/c' 逐级建树,行挂最底层目录;留空 = 未分类
|
||||
· 期次:文件名里认得出的优先(如「珠海信息价_2026年7月」),认不出用弹框填的
|
||||
· 旧版「一个块 = 一个批次」多块循环退役(新模板单 sheet 单批次)
|
||||
"""
|
||||
paths = [p for p in (body.get("path") and [body.get("path")] or []) if p and os.path.exists(p)]
|
||||
if not paths:
|
||||
return {"ok": False, "msg": "请先选择文件(HTML 或 Excel,每次只能导入一个)"}
|
||||
return {"ok": False, "msg": "请先选择文件(标准模板 Excel,每次只能导入一个)"}
|
||||
kind = body.get("kind", "info")
|
||||
if kind not in ("market", "info"):
|
||||
kind = "info"
|
||||
# #4 查重:同名 + 同期次 + 同地区 已存在 → 先让用户确认
|
||||
dup = find_dup(con, kind, body)
|
||||
if dup and not body.get("force"):
|
||||
return {"ok": False, "need_confirm": True, "dup": dup,
|
||||
@@ -2633,8 +3011,8 @@ def api_import_price(con, body):
|
||||
dist = body.get("district") or ""
|
||||
p1 = _period(body.get("period_from"))
|
||||
p2 = _period(body.get("period_to")) or p1
|
||||
note = (body.get("note") or "").strip() # 备注(唯一选填项)
|
||||
pub = (body.get("publisher") or "").strip() # 发布单位(必填,2026-09-28 定)
|
||||
note = (body.get("note") or "").strip()
|
||||
pub = (body.get("publisher") or "").strip()
|
||||
|
||||
cur = con.cursor()
|
||||
created, total_rows, blocks_info = [], 0, []
|
||||
@@ -2642,29 +3020,20 @@ def api_import_price(con, body):
|
||||
try:
|
||||
blocks = _price_parse(path)
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": "解析失败(%s):%s" % (os.path.basename(path), e)}
|
||||
return {"ok": False, "msg": "导入失败:%s" % e}
|
||||
fname = os.path.splitext(os.path.basename(path))[0]
|
||||
# 文件名里的期次(如「珠海信息价_2026年7月」)—— 块名里没写年月时用它兜底,
|
||||
# 比让用户在弹框里手填更准,也避免同一个文件里的 4 个市场被塞成同一个「空期次」
|
||||
fp1, fp2 = price.guess_period(fname)
|
||||
for b in blocks:
|
||||
recs = price.to_records([b]) # 只取这一个块的行
|
||||
recs = price_xlsx.to_records([b])
|
||||
if not recs:
|
||||
continue
|
||||
# 期次优先顺序:块名里认出来的 → 文件名里认出来的 → 导入弹框里填的
|
||||
bp1 = b.get("period_start_m")
|
||||
bp2 = b.get("period_end_m")
|
||||
s1 = bp1 if bp1 is not None else (fp1 if fp1 is not None else p1)
|
||||
s2 = bp2 if bp2 is not None else (fp2 if fp2 is not None else p2)
|
||||
s1 = b.get("period_start_m") if b.get("period_start_m") is not None else (fp1 if fp1 is not None else p1)
|
||||
s2 = b.get("period_end_m") if b.get("period_end_m") is not None else (fp2 if fp2 is not None else p2)
|
||||
if s1 is None:
|
||||
s1 = s2
|
||||
if s2 is None:
|
||||
s2 = s1
|
||||
blk = (b.get("block") or "").strip()
|
||||
# 名称:多块时用块名(块名本身就是市场名,最清楚);单块时用弹框填的名称
|
||||
bname = blk if len(blocks) > 1 else (base_name or blk or fname)
|
||||
if not bname:
|
||||
bname = fname
|
||||
bname = base_name or b.get("block") or fname # 名称默认=文件名(block 即文件名)
|
||||
cur.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit,
|
||||
x_province, x_city, x_district, x_period_start_m, x_period_end_m, x_enabled,
|
||||
x_total, x_rows_bill, x_rows_lme, x_imported_at, x_src_hash, x_note, x_publisher,
|
||||
@@ -2675,23 +3044,24 @@ def api_import_price(con, body):
|
||||
price.PARSER_VER))
|
||||
bid = cur.lastrowid
|
||||
for r in recs:
|
||||
dir_id = _dir_ensure_path(cur, bid, r["Class"])
|
||||
h = _md5(r["Name"], r["Specification"], r["Unit"])
|
||||
cur.execute("""INSERT INTO prices(batch_id, Code, Name, Specification, Unit,
|
||||
NoTaxPrice, TaxRate, TaxPrice, Class, Note, Block, x_name_norm, x_spec_norm, x_unit_norm,
|
||||
x_hash_exact, x_hash_semi, x_period_start_m, x_period_end_m)
|
||||
NoTaxPrice, TaxRate, TaxPrice, Class, Note, dir_id,
|
||||
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi,
|
||||
x_period_start_m, x_period_end_m)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, r["Code"], r["Name"], r["Specification"], r["Unit"], r["NoTaxPrice"],
|
||||
r["TaxRate"], r["TaxPrice"], r["Class"], r["Note"], r.get("Block", ""),
|
||||
r["TaxRate"], r["TaxPrice"], _dir_path(cur, dir_id), r["Note"], dir_id,
|
||||
_norm(r["Name"]), _norm(r["Specification"]), _norm(r["Unit"]), h,
|
||||
_md5(r["Name"], r["Unit"]), s1, s2))
|
||||
# 2026-10-06:价格条数写 x_rows_price(不写 x_rows_lme —— 那是工料机专用列)
|
||||
cur.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (len(recs), bid))
|
||||
created.append(bid); total_rows += len(recs)
|
||||
blocks_info.append({"batch_id": bid, "name": bname[:80], "rows": len(recs),
|
||||
"period": "%s~%s" % (s1, s2) if s1 is not None else "",
|
||||
"block": blk[:80]})
|
||||
"block": ""})
|
||||
if not created:
|
||||
return {"ok": False, "msg": "这个文件里没有可导入的数据行"}
|
||||
return {"ok": False, "msg": "这个文件里没有可导入的数据行(名称列全空?)"}
|
||||
con.commit()
|
||||
return {"ok": True, "batches": created, "blocks": blocks_info, "n_rows": total_rows,
|
||||
"msg": "导入完成:%d 个价格批次、共 %d 条材料价格" % (len(created), total_rows)}
|
||||
@@ -3566,6 +3936,30 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _export_zip(self, bid):
|
||||
"""导出价格批次「一份数据」:zip = 价格明细.xlsx(含目录层级)+ 附件原件 + 批次信息页签"""
|
||||
c = conn()
|
||||
try:
|
||||
raw, fn = api_price_export(c, bid)
|
||||
except ValueError as e:
|
||||
c.close()
|
||||
return self._json({"error": str(e)}, 404)
|
||||
except ImportError:
|
||||
c.close()
|
||||
return self._json({"error": "缺少 openpyxl,无法导出(pip install openpyxl)"}, 500)
|
||||
finally:
|
||||
try:
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._allow_cache = True
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/zip")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Content-Disposition", self._cd(fn, "price_export.zip"))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _gate_send(self, r):
|
||||
"""发送门禁拦截响应:授权页(自包含 HTML)或 JSON 错误。"""
|
||||
if r.get("kind") == "html":
|
||||
@@ -3673,7 +4067,19 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
return self._json(api_similar(int(m.group(1)), one.get("profession")))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/prices$", p)
|
||||
if m:
|
||||
return self._json(api_prices(int(m.group(1)), int(one.get("page", 1)), int(one.get("page_size", 50))))
|
||||
return self._json(api_prices(int(m.group(1)), int(one.get("page", 1)),
|
||||
int(one.get("page_size", 50)),
|
||||
one.get("dir_id"), int(one.get("subtree", 0) or 0)))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/dirs$", p) # 价格目录树(2026-10-12)
|
||||
if m:
|
||||
c = conn()
|
||||
try:
|
||||
return self._json(api_price_dirs(c, int(m.group(1))))
|
||||
finally:
|
||||
c.close()
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/export$", p) # 导出一份数据(zip,2026-10-12)
|
||||
if m:
|
||||
return self._export_zip(int(m.group(1)))
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/attach$", p)
|
||||
if m:
|
||||
c = conn(); r = api_attach_info(c, int(m.group(1))); c.close()
|
||||
@@ -3868,6 +4274,28 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/dirs$", u.path) # 价格目录:增/改名/移动/上下移/删(2026-10-12)
|
||||
if m:
|
||||
with WRITE_LOCK:
|
||||
c = conn()
|
||||
try:
|
||||
r = api_price_dir_save(c, int(m.group(1)), body)
|
||||
except Exception as e:
|
||||
c.rollback(); r = {"ok": False, "msg": "目录操作失败:%s" % e}
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/prices$", u.path) # 价格行:新增/编辑/删(行内编辑,2026-10-12)
|
||||
if m:
|
||||
with WRITE_LOCK:
|
||||
c = conn()
|
||||
try:
|
||||
r = api_price_row_save(c, int(m.group(1)), body)
|
||||
except Exception as e:
|
||||
c.rollback(); r = {"ok": False, "msg": "保存失败:%s" % e}
|
||||
finally:
|
||||
c.close()
|
||||
return self._json(r)
|
||||
if u.path == "/api/session/remark": # 审核备注(双写:界面 + 持久表)
|
||||
# ⚠️ 2026-09-30:以前只写 s_bills.x_remark —— 删除会话 / 重新解析(wipe)会连备注一起没。
|
||||
# 现在同时写 s_remarks(不参与 wipe),重新解析后由 restore_remarks() 按 rkey 回填。
|
||||
|
||||
Reference in New Issue
Block a user