diff --git a/scripts/generate_ssr.py b/scripts/generate_ssr.py index f71312e..43e032d 100644 --- a/scripts/generate_ssr.py +++ b/scripts/generate_ssr.py @@ -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""" + +ССР Превью + +

Сводный сметный расчёт

+

{title}
+Смет: {data.get('total_estimates', 0)} | Глав: {len(chapters)} | +Дата: {datetime.now().strftime('%d.%m.%Y %H:%M')}

+ +

Сводная по главам (тыс.руб.)

+ + + +""" + 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'' + f'' + f'' + f'\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'' + f'' + f'' + f'\n') + html += "
ГлаваНаименованиеСтроит.Монтаж.Оборуд.ПрочиеИтого
{ch_num}{name}{_fmt(ct["str"])}{_fmt(ct["mont"])}{_fmt(ct["equip"])}{_fmt(ct["other"])}{_fmt(ct["total"])}
{label}{_fmt(vals["str"])}{_fmt(vals["mont"])}{_fmt(vals["equip"])}{_fmt(vals["other"])}{_fmt(vals["total"])}
\n" + + # SR-10 summary + html += """

СР-10 Временные здания по 332/пр

+ + + +""" + 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'' + f'\n') + eff = total_temp / total_smr * 100 if total_smr else 0 + html += (f'' + f'\n') + html += "
КодНаименование%ПозицийСМРВременные
{code}{d["name"]}{d["pct"]}{d["count"]}{_fmt(smr)}{_fmt(temp)}
ИТОГО{eff:.3f}{_fmt(total_smr)}{_fmt(total_temp)}
\n" + + # Parameters + html += f"""

Параметры расчёта

+ + + + + + +
Зимнее удорожание{args.winter_pct}%
Строительный контроль{args.control_pct}%
Авторский надзор{args.avt_nadzor_pct}%
Резерв{args.reserve_pct}%
НДС20%
+""" + + # Chapter details (collapsible) + html += "

Крупнейшие позиции по главам

\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'
Глава {ch_num}. {ch_name} — {_fmt(ch_total)} тыс.руб.\n' + html += '\n' + for code, name, total in items: + html += f'\n' + html += '
КодНаименованиеИтого
{code}{name}{_fmt(total)}
\n' + + 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()