feat: HTML-превью для генератора ССР

Автоматически генерируется .html рядом с .xlsx:
- Сводная таблица по главам 1-12
- СР-10 по кодам 332/пр
- Параметры расчёта
- Collapsible top-10 позиций по каждой главе
Можно открыть в браузере для валидации без Excel.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-30 03:14:20 +10:00
co-authored by Claude Opus 4.6
parent 92d5c1511c
commit 3b19201f38
+176
View File
@@ -22,6 +22,7 @@ Usage:
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
import openpyxl
@@ -1073,12 +1074,180 @@ def _build_summary(wb, chapter_totals, ch8, ch9, ch10, ch12,
ws.column_dimensions[letter].width = 18
# ── HTML Preview ────────────────────────────────────────────────────────────
def _fmt(val):
"""Format number with thousands separator."""
if isinstance(val, (int, float)):
return f"{val:,.2f}"
return str(val)
def _generate_html(html_path, data, chapter_totals, sr10, ch8, ch9, ch10, ch12,
t17, t19, t112, args):
"""Generate HTML preview for validation before opening xlsx."""
title = data.get("title", "ССР")
res = {k: round(t112[k] * args.reserve_pct / 100, 2) for k in t112}
total_no_vat = {k: round(t112[k] + res[k], 2) for k in t112}
vat = {k: round(total_no_vat[k] * 0.2, 2) for k in total_no_vat}
total_vat = {k: round(total_no_vat[k] + vat[k], 2) for k in total_no_vat}
all_ch = dict(chapter_totals)
all_ch[8] = ch8; all_ch[9] = ch9; all_ch[10] = ch10; all_ch[12] = ch12
# Collect SR-10 stats by 332 code
sr10_by_code = {}
chapters = data["chapters"]
for ch_num in sorted(chapters.keys(), key=int):
if int(ch_num) > 7:
continue
ch = chapters[ch_num]
for sec_num, sec in ch["sections"].items():
for os_num, os_data in sec["os_groups"].items():
for est in os_data["estimates"]:
code_332 = _get_332_code(int(ch_num), int(sec_num), est.get("name", ""))
pct = NORMS_332[code_332][1]
s = est["totals_tys"]["Строительные"]
m = est["totals_tys"]["Монтажные"]
if code_332 not in sr10_by_code:
sr10_by_code[code_332] = {"name": NORMS_332[code_332][0][:50],
"pct": pct, "count": 0,
"str": 0, "mont": 0, "t_str": 0, "t_mont": 0}
sr10_by_code[code_332]["count"] += 1
sr10_by_code[code_332]["str"] += s
sr10_by_code[code_332]["mont"] += m
sr10_by_code[code_332]["t_str"] += s * pct / 100
sr10_by_code[code_332]["t_mont"] += m * pct / 100
# Build chapter details (top-10 by total per chapter)
ch_details = {}
for ch_num in sorted(chapters.keys(), key=int):
items = []
ch = chapters[ch_num]
for sec_num, sec in ch["sections"].items():
for os_num, os_data in sec["os_groups"].items():
if int(os_num) > 0 and len(os_data["estimates"]) > 1:
ot = os_data["totals_tys"]
t = sum(ot.values())
first = os_data["estimates"][0]
items.append((first["code"], first["name"][:60], t))
else:
for est in os_data["estimates"]:
items.append((est["code"], est["name"][:60], est["grand_total_tys"]))
items.sort(key=lambda x: -x[2])
ch_details[ch_num] = items[:10]
# Generate HTML
html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8">
<title>ССР Превью</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; background: #f9f9f9; }}
h1 {{ color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }}
h2 {{ color: #2c3e50; margin-top: 30px; }}
table {{ border-collapse: collapse; width: 100%; margin: 10px 0; background: white; }}
th {{ background: #3498db; color: white; padding: 8px 12px; text-align: right; }}
th:nth-child(1), th:nth-child(2) {{ text-align: left; }}
td {{ padding: 6px 12px; border: 1px solid #ddd; text-align: right; }}
td:nth-child(1), td:nth-child(2) {{ text-align: left; }}
tr:nth-child(even) {{ background: #f8f9fa; }}
.total {{ font-weight: bold; background: #e8f5e9 !important; }}
.grand {{ font-weight: bold; background: #c8e6c9 !important; font-size: 1.1em; }}
.params td {{ text-align: left; }}
details {{ margin: 5px 0; }}
summary {{ cursor: pointer; font-weight: bold; padding: 5px; background: #ecf0f1; border-radius: 4px; }}
summary:hover {{ background: #d5dbdb; }}
.meta {{ color: #7f8c8d; margin-bottom: 20px; }}
</style></head><body>
<h1>Сводный сметный расчёт</h1>
<p class="meta">{title}<br>
Смет: {data.get('total_estimates', 0)} | Глав: {len(chapters)} |
Дата: {datetime.now().strftime('%d.%m.%Y %H:%M')}</p>
<h2>Сводная по главам (тыс.руб.)</h2>
<table>
<tr><th>Глава</th><th>Наименование</th><th>Строит.</th><th>Монтаж.</th>
<th>Оборуд.</th><th>Прочие</th><th>Итого</th></tr>
"""
for ch_num in sorted(all_ch.keys()):
ct = all_ch[ch_num]
name = CHAPTER_NAMES.get(ch_num, f"Глава {ch_num}")[:45]
html += (f'<tr><td>{ch_num}</td><td>{name}</td>'
f'<td>{_fmt(ct["str"])}</td><td>{_fmt(ct["mont"])}</td>'
f'<td>{_fmt(ct["equip"])}</td><td>{_fmt(ct["other"])}</td>'
f'<td>{_fmt(ct["total"])}</td></tr>\n')
for label, vals, cls in [
("Итого главы 1-7", t17, "total"),
("Итого главы 1-9", t19, "total"),
("Итого главы 1-12", t112, "total"),
(f"Резерв {args.reserve_pct}%", res, ""),
("Всего без НДС", total_no_vat, "total"),
("НДС 20%", vat, ""),
("ВСЕГО с НДС", total_vat, "grand"),
]:
html += (f'<tr class="{cls}"><td></td><td>{label}</td>'
f'<td>{_fmt(vals["str"])}</td><td>{_fmt(vals["mont"])}</td>'
f'<td>{_fmt(vals["equip"])}</td><td>{_fmt(vals["other"])}</td>'
f'<td>{_fmt(vals["total"])}</td></tr>\n')
html += "</table>\n"
# SR-10 summary
html += """<h2>СР-10 Временные здания по 332/пр</h2>
<table>
<tr><th>Код</th><th>Наименование</th><th>%</th><th>Позиций</th>
<th>СМР</th><th>Временные</th></tr>
"""
total_smr = total_temp = 0
for code in sorted(sr10_by_code.keys()):
d = sr10_by_code[code]
smr = d["str"] + d["mont"]
temp = d["t_str"] + d["t_mont"]
total_smr += smr; total_temp += temp
html += (f'<tr><td>{code}</td><td>{d["name"]}</td><td>{d["pct"]}</td>'
f'<td>{d["count"]}</td><td>{_fmt(smr)}</td><td>{_fmt(temp)}</td></tr>\n')
eff = total_temp / total_smr * 100 if total_smr else 0
html += (f'<tr class="total"><td></td><td>ИТОГО</td><td>{eff:.3f}</td>'
f'<td></td><td>{_fmt(total_smr)}</td><td>{_fmt(total_temp)}</td></tr>\n')
html += "</table>\n"
# Parameters
html += f"""<h2>Параметры расчёта</h2>
<table class="params">
<tr><td>Зимнее удорожание</td><td>{args.winter_pct}%</td></tr>
<tr><td>Строительный контроль</td><td>{args.control_pct}%</td></tr>
<tr><td>Авторский надзор</td><td>{args.avt_nadzor_pct}%</td></tr>
<tr><td>Резерв</td><td>{args.reserve_pct}%</td></tr>
<tr><td>НДС</td><td>20%</td></tr>
</table>
"""
# Chapter details (collapsible)
html += "<h2>Крупнейшие позиции по главам</h2>\n"
for ch_num in sorted(ch_details.keys(), key=int):
items = ch_details[ch_num]
ch_name = CHAPTER_NAMES.get(int(ch_num), f"Глава {ch_num}")[:50]
ct = chapter_totals.get(int(ch_num), {})
ch_total = ct.get("total", 0) if ct else 0
html += f'<details><summary>Глава {ch_num}. {ch_name} — {_fmt(ch_total)} тыс.руб.</summary>\n'
html += '<table><tr><th>Код</th><th>Наименование</th><th>Итого</th></tr>\n'
for code, name, total in items:
html += f'<tr><td>{code}</td><td>{name}</td><td>{_fmt(total)}</td></tr>\n'
html += '</table></details>\n'
html += "</body></html>"
Path(html_path).write_text(html, encoding="utf-8")
return html_path
# ── Main ────────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Generate SSR from project_data.json")
parser.add_argument("json_file", help="project_data.json")
parser.add_argument("--output", default="ssr_generated.xlsx", help="Output xlsx")
parser.add_argument("--html", default=None, help="HTML preview path (auto if omitted)")
parser.add_argument("--title", default=None, help="Project title")
parser.add_argument("--winter-pct", type=float, default=3.2,
help="Winter costs %% (325/пр), default 3.2")
@@ -1186,6 +1355,13 @@ def main():
wb.save(args.output)
print(f"Saved: {args.output}")
# HTML preview
html_path = args.html or str(Path(args.output).with_suffix(".html"))
print(f"Building HTML preview...")
_generate_html(html_path, data, chapter_totals, sr10, ch8, ch9, ch10, ch12,
t17, t19, t112, args)
print(f"Saved: {html_path}")
if __name__ == "__main__":
main()