refactor: API-функции для веб-интеграции
parse_gge_from_zip() — парсинг GGE без CLI generate_ssr_from_data() — генерация ССР без CLI main() теперь делегирует в generate_ssr_from_data() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
+93
-89
@@ -1245,6 +1245,88 @@ summary:hover {{ background: #d5dbdb; }}
|
||||
|
||||
# ── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def generate_ssr_from_data(data, output_xlsx, output_html=None,
|
||||
winter_pct=3.2, control_pct=0.55, reserve_pct=1.0,
|
||||
avt_nadzor_pct=0.1, vat_pct=22.0):
|
||||
"""Generate SSR xlsx + HTML from parsed project data. Callable from Python.
|
||||
|
||||
Returns dict with stats: {estimates, chapters, total_vat, sheets}.
|
||||
"""
|
||||
import openpyxl as _openpyxl # noqa: already imported at module level
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
# Create a simple namespace for params (used by _build_input_data, _generate_html)
|
||||
class _P:
|
||||
pass
|
||||
params = _P()
|
||||
params.winter_pct = winter_pct
|
||||
params.control_pct = control_pct
|
||||
params.reserve_pct = reserve_pct
|
||||
params.avt_nadzor_pct = avt_nadzor_pct
|
||||
params.vat_pct = vat_pct
|
||||
|
||||
_build_input_data(wb, params, data)
|
||||
|
||||
chapter_totals = _build_raspredelenie(wb, data)
|
||||
|
||||
sr10 = _build_sr10_temp(wb, data, chapter_totals)
|
||||
|
||||
total = _build_ssrss(wb, data, chapter_totals,
|
||||
sr10_result=sr10, winter_pct=winter_pct,
|
||||
control_pct=control_pct, reserve_pct=reserve_pct,
|
||||
avt_nadzor_pct=avt_nadzor_pct, vat_pct=vat_pct)
|
||||
|
||||
# Intermediate totals
|
||||
t17 = {"str": 0, "mont": 0, "equip": 0, "other": 0, "total": 0}
|
||||
for ch_num, ct in chapter_totals.items():
|
||||
if ch_num <= 7:
|
||||
for k in t17:
|
||||
t17[k] += ct[k]
|
||||
|
||||
smr_17 = t17["str"] + t17["mont"]
|
||||
ch8 = {"str": sr10["str"], "mont": sr10["mont"], "equip": 0, "other": 0,
|
||||
"total": sr10["total"]}
|
||||
winter_str = round(smr_17 * winter_pct / 100, 2)
|
||||
ch9 = {"str": winter_str, "mont": 0, "equip": 0, "other": 0, "total": winter_str}
|
||||
if 9 in chapter_totals:
|
||||
for k in ch9:
|
||||
ch9[k] += chapter_totals[9][k]
|
||||
t18 = {k: t17[k] + ch8[k] for k in t17}
|
||||
t19 = {k: t18[k] + ch9[k] for k in t18}
|
||||
sk_val = round(t19["total"] * control_pct / 100, 2)
|
||||
ch10 = {"str": 0, "mont": 0, "equip": 0, "other": sk_val, "total": sk_val}
|
||||
avt = round(t19["total"] * avt_nadzor_pct / 100, 2)
|
||||
ch12 = {"str": 0, "mont": 0, "equip": 0, "other": avt, "total": avt}
|
||||
t112 = {k: t19[k] + ch10[k] + ch12[k] for k in t19}
|
||||
|
||||
_build_sr25(wb, t19["total"], control_pct)
|
||||
_build_summary(wb, chapter_totals, ch8, ch9, ch10, ch12,
|
||||
reserve_pct, vat_pct, t17, t19, t112)
|
||||
_build_332pr(wb)
|
||||
_build_pp468(wb)
|
||||
_build_contents(wb)
|
||||
wb.move_sheet("Содержание", offset=-(len(wb.sheetnames) - 2))
|
||||
|
||||
wb.save(output_xlsx)
|
||||
|
||||
# HTML preview
|
||||
html_path = output_html or str(Path(output_xlsx).with_suffix(".html"))
|
||||
_generate_html(html_path, data, chapter_totals, sr10, ch8, ch9, ch10, ch12,
|
||||
t17, t19, t112, params)
|
||||
|
||||
return {
|
||||
"estimates": data.get("total_estimates", 0),
|
||||
"chapters": len(data.get("chapters", {})),
|
||||
"total_vat": total["total"],
|
||||
"sheets": len(wb.sheetnames),
|
||||
"xlsx_path": output_xlsx,
|
||||
"html_path": html_path,
|
||||
"sr10_eff_pct": sr10["eff_pct"],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate SSR from project_data.json")
|
||||
parser.add_argument("json_file", help="project_data.json")
|
||||
@@ -1275,96 +1357,18 @@ def main():
|
||||
|
||||
print(f"Estimates: {data['total_estimates']}, Chapters: {sorted(data['chapters'].keys())}")
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
wb.remove(wb.active) # remove default sheet
|
||||
result = generate_ssr_from_data(
|
||||
data, args.output, output_html=args.html,
|
||||
winter_pct=args.winter_pct, control_pct=args.control_pct,
|
||||
reserve_pct=args.reserve_pct, avt_nadzor_pct=args.avt_nadzor_pct,
|
||||
vat_pct=args.vat_pct,
|
||||
)
|
||||
|
||||
# Sheet 1: Исходные данные
|
||||
print("Building Исходные данные...")
|
||||
_build_input_data(wb, args, data)
|
||||
|
||||
# Sheet 2: РАСПРЕДЕЛЕНИЕ
|
||||
print("Building РАСПРЕДЕЛЕНИЕ...")
|
||||
chapter_totals = _build_raspredelenie(wb, data)
|
||||
|
||||
for ch_num in sorted(chapter_totals.keys()):
|
||||
ct = chapter_totals[ch_num]
|
||||
print(f" Глава {ch_num}: стр={ct['str']:,.2f} монт={ct['mont']:,.2f} "
|
||||
f"обор={ct['equip']:,.2f} проч={ct['other']:,.2f} итого={ct['total']:,.2f}")
|
||||
|
||||
# Sheet 3: СР-10 Временные (BEFORE ССРСС — ССРСС uses its result)
|
||||
print("Building СР-10 Временные...")
|
||||
sr10 = _build_sr10_temp(wb, data, chapter_totals)
|
||||
print(f" СР-10: стр={sr10['str']:,.2f} монт={sr10['mont']:,.2f} "
|
||||
f"итого={sr10['total']:,.2f} (эфф. %={sr10['eff_pct']:.3f}%)")
|
||||
|
||||
# Sheet 4: ССРСС (uses sr10 result for chapter 8)
|
||||
print("Building ССРСС...")
|
||||
total = _build_ssrss(wb, data, chapter_totals,
|
||||
sr10_result=sr10, winter_pct=args.winter_pct,
|
||||
control_pct=args.control_pct, reserve_pct=args.reserve_pct,
|
||||
avt_nadzor_pct=args.avt_nadzor_pct, vat_pct=args.vat_pct)
|
||||
|
||||
# Reconstruct intermediate totals for other sheets
|
||||
t17 = {"str": 0, "mont": 0, "equip": 0, "other": 0, "total": 0}
|
||||
for ch_num, ct in chapter_totals.items():
|
||||
if ch_num <= 7:
|
||||
for k in t17:
|
||||
t17[k] += ct[k]
|
||||
|
||||
smr_17 = t17["str"] + t17["mont"]
|
||||
ch8 = {"str": sr10["str"], "mont": sr10["mont"], "equip": 0, "other": 0,
|
||||
"total": sr10["total"]}
|
||||
|
||||
winter_str = round(smr_17 * args.winter_pct / 100, 2)
|
||||
ch9 = {"str": winter_str, "mont": 0, "equip": 0, "other": 0, "total": winter_str}
|
||||
if 9 in chapter_totals:
|
||||
for k in ch9:
|
||||
ch9[k] += chapter_totals[9][k]
|
||||
|
||||
t18 = {k: t17[k] + ch8[k] for k in t17}
|
||||
t19 = {k: t18[k] + ch9[k] for k in t18}
|
||||
|
||||
sk_val = round(t19["total"] * args.control_pct / 100, 2)
|
||||
ch10 = {"str": 0, "mont": 0, "equip": 0, "other": sk_val, "total": sk_val}
|
||||
|
||||
avt = round(t19["total"] * args.avt_nadzor_pct / 100, 2)
|
||||
ch12 = {"str": 0, "mont": 0, "equip": 0, "other": avt, "total": avt}
|
||||
|
||||
t112 = {k: t19[k] + ch10[k] + ch12[k] for k in t19}
|
||||
|
||||
# Sheet 5: СР-25 Стройконтроль
|
||||
print("Building СР-25 Стройконтроль...")
|
||||
sr25 = _build_sr25(wb, t19["total"], args.control_pct)
|
||||
print(f" СР-25: {sr25:,.2f} тыс.руб.")
|
||||
|
||||
# Sheet 6: Сводная_СМ
|
||||
print("Building Сводная_СМ...")
|
||||
_build_summary(wb, chapter_totals, ch8, ch9, ch10, ch12,
|
||||
args.reserve_pct, args.vat_pct, t17, t19, t112)
|
||||
|
||||
# Sheet 7-8: Reference tables
|
||||
print("Building 332_пр, ПП468...")
|
||||
_build_332pr(wb)
|
||||
_build_pp468(wb)
|
||||
|
||||
# Sheet 9: Содержание (last, after all sheets)
|
||||
print("Building Содержание...")
|
||||
_build_contents(wb)
|
||||
# Move Содержание to position 1 (after Исходные данные)
|
||||
wb.move_sheet("Содержание", offset=-(len(wb.sheetnames) - 2))
|
||||
|
||||
print(f"\nВсего с НДС: {total['total']:,.2f} тыс.руб.")
|
||||
print(f"Листов: {len(wb.sheetnames)}")
|
||||
|
||||
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}")
|
||||
print(f"\nВсего с НДС: {result['total_vat']:,.2f} тыс.руб.")
|
||||
print(f"Листов: {result['sheets']}")
|
||||
print(f"СР-10 эфф. %: {result['sr10_eff_pct']:.3f}%")
|
||||
print(f"Saved: {result['xlsx_path']}")
|
||||
print(f"HTML: {result['html_path']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -185,6 +185,70 @@ def build_hierarchy(estimates: list[dict]) -> dict:
|
||||
return dict(hierarchy)
|
||||
|
||||
|
||||
def parse_gge_from_zip(zip_path: str, on_progress=None) -> dict:
|
||||
"""Parse GGE ZIP → project_data dict. Callable from Python (no CLI)."""
|
||||
estimates = []
|
||||
errors = []
|
||||
with zipfile.ZipFile(zip_path) as z:
|
||||
gge_infos = [i for i in z.infolist()
|
||||
if i.filename.lower().endswith(".gge") and i.file_size > 100]
|
||||
for i, info in enumerate(gge_infos):
|
||||
if not (info.flag_bits & 0x800):
|
||||
info.filename = fix_zip_encoding(info.filename)
|
||||
content = z.read(info)
|
||||
parsed = parse_gge(content)
|
||||
if parsed:
|
||||
parsed["source_file"] = Path(info.filename).name
|
||||
estimates.append(parsed)
|
||||
else:
|
||||
errors.append(info.filename)
|
||||
if on_progress and (i + 1) % 300 == 0:
|
||||
on_progress(i + 1, len(gge_infos))
|
||||
|
||||
hierarchy = build_hierarchy(estimates)
|
||||
|
||||
grand_totals = {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0}
|
||||
for ch_data in hierarchy.values():
|
||||
for wtype, val in ch_data["totals_tys"].items():
|
||||
grand_totals[wtype] += val
|
||||
grand = sum(grand_totals.values())
|
||||
|
||||
result = {
|
||||
"generated": datetime.now().isoformat(),
|
||||
"source": zip_path,
|
||||
"total_estimates": len(estimates),
|
||||
"total_errors": len(errors),
|
||||
"grand_totals_tys": grand_totals,
|
||||
"grand_total_tys": grand,
|
||||
"chapters": {},
|
||||
}
|
||||
for ch_num, ch_data in hierarchy.items():
|
||||
ch_dict = {
|
||||
"name": ch_data["name"],
|
||||
"totals_tys": dict(ch_data["totals_tys"]),
|
||||
"sections": {},
|
||||
}
|
||||
for rz_num, rz_data in ch_data["razrely"].items():
|
||||
rz_dict = {"os_groups": {}}
|
||||
for os_num, os_data in rz_data["os"].items():
|
||||
rz_dict["os_groups"][str(os_num)] = {
|
||||
"totals_tys": dict(os_data["totals_tys"]),
|
||||
"estimates": [
|
||||
{
|
||||
"code": e["code"],
|
||||
"name": e["name"][:100],
|
||||
"totals_tys": e["totals_tys"],
|
||||
"grand_total_tys": e["grand_total_tys"],
|
||||
}
|
||||
for e in os_data["estimates"]
|
||||
],
|
||||
}
|
||||
ch_dict["sections"][str(rz_num)] = rz_dict
|
||||
result["chapters"][str(ch_num)] = ch_dict
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Parse GGE → project structure")
|
||||
parser.add_argument("zip_file", help="ZIP с GGE-файлами")
|
||||
|
||||
Reference in New Issue
Block a user