-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
831 lines (747 loc) · 43.3 KB
/
Copy pathengine.py
File metadata and controls
831 lines (747 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#!/usr/bin/env python3
"""Smeta engine: DAY-centric landscape estimate.
The unit of planning is the DAY. Each day has people (own crew, by day-rate),
equipment, and deliveries. Materials are planned for the whole object, grouped.
Subcontractors are paid per task. Money is rolled up from days + object materials.
This module is the authoritative calculation (for agents). It also generates a
self-contained interactive HTML view (editable, live recalc) for the designer.
Usage:
uv run engine.py data/template.json
uv run engine.py data/template.json --html smeta.html
"""
import argparse
import json
import sys
from pathlib import Path
# ---------- calculation (authoritative) ----------
def day_labor(data, d):
return sum(r["rate_per_day"] * r["days"].get(str(d), 0) for r in data.get("labor", []))
def day_equipment(data, d):
return sum(e["rate"] * e["days"].get(str(d), 0) for e in data.get("equipment", []))
def day_delivery(data, d):
return sum(x["price"] for x in data.get("delivery", []) if x["day"] == d)
def materials_total(data):
return sum(m["qty"] * m["price"] for g in data.get("materials", []) for m in g["items"])
def compute(data):
n = data["num_days"]
days = []
for d in range(1, n + 1):
lab, eq, dl = day_labor(data, d), day_equipment(data, d), day_delivery(data, d)
people = sum(r["days"].get(str(d), 0) for r in data.get("labor", []))
days.append({"n": d, "people": people, "labor": lab, "equipment": eq,
"delivery": dl, "total": lab + eq + dl})
labor = sum(x["labor"] for x in days)
equipment = sum(x["equipment"] for x in days)
delivery = sum(x["delivery"] for x in days)
subcontract = sum(s["price"] for s in data.get("subcontractors", []))
materials = materials_total(data)
base = labor + equipment + delivery + subcontract + materials
profit = base * data["project"].get("profit_pct", 0) / 100.0
return {"days": days, "labor": labor, "equipment": equipment, "delivery": delivery,
"subcontract": subcontract, "materials": materials, "cost_price": base,
"profit": profit, "profit_pct": data["project"].get("profit_pct", 0),
"client_price": base + profit}
# ---------- console report ----------
def money(x):
return f"{x:,.0f}".replace(",", " ") + " ₽"
def print_report(data, r):
print(f"\n=== СМЕТА: {data['project']['name']} === дней: {data['num_days']}\n")
print("ИТОГ ПО ДНЯМ:")
for d in r["days"]:
print(f" День {d['n']:>2}: {d['people']} чел | работа {money(d['labor']):>11} | "
f"техника {money(d['equipment']):>9} | доставка {money(d['delivery']):>9} | "
f"итог дня {money(d['total'])}")
print("\nСВОДКА:")
print(f" Люди: {money(r['labor'])}")
print(f" Техника: {money(r['equipment'])}")
print(f" Доставка: {money(r['delivery'])}")
print(f" Подряд: {money(r['subcontract'])}")
print(f" Материалы: {money(r['materials'])}")
print(" " + "-" * 36)
print(f" Себестоимость: {money(r['cost_price'])}")
print(f" Прибыль ({r['profit_pct']:.0f}%): {money(r['profit'])}")
print(f" ЦЕНА КЛИЕНТУ: {money(r['client_price'])}")
schedule = {x.get("day"): x for x in data.get("schedule", [])}
if schedule:
print("\nПЛАН РЕАЛИЗАЦИИ:")
for d in range(0, data["num_days"] + 1):
item = schedule.get(d)
if item and item.get("title"):
print(f" День {d:>2}: {item['title']}")
# ---------- interactive HTML ----------
def generate_html(data, out_path):
html = _HTML_TEMPLATE.replace("__DATA__", json.dumps(data, ensure_ascii=False))
Path(out_path).write_text(html, encoding="utf-8")
print(f"\nВитрина: {out_path}")
_HTML_TEMPLATE = r"""<!DOCTYPE html>
<html lang="ru"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Смета по дням</title>
<style>
:root { --green:#2f5233; --bg:#f4f5f7; }
* { box-sizing:border-box; }
body { font-family:-apple-system,Segoe UI,Roboto,sans-serif; margin:0; background:var(--bg); color:#1a1a1a; }
header { background:var(--green); color:#fff; padding:16px 24px; }
header h1 { margin:0; font-size:20px; } header .sub { opacity:.85; font-size:13px; margin-top:4px; }
main { max-width:1240px; margin:0 auto; padding:24px; }
h2 { font-size:14px; text-transform:uppercase; letter-spacing:.5px; color:var(--green); margin:28px 0 10px; }
.summary { display:flex; gap:14px; flex-wrap:wrap; margin-bottom:8px; }
.card { background:#fff; border-radius:10px; padding:14px 18px; box-shadow:0 1px 3px rgba(0,0,0,.08); flex:1; min-width:120px; }
.card .label { font-size:11px; color:#888; text-transform:uppercase; } .card .val { font-size:20px; font-weight:700; margin-top:6px; }
.card.price { background:var(--green); color:#fff; } .card.price .label{color:#cde0d0;}
.panel { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08); overflow-x:auto; }
table { border-collapse:collapse; font-size:13px; width:100%; white-space:nowrap; }
th,td { padding:6px 8px; border-bottom:1px solid #f0f0f0; text-align:center; }
th { font-size:11px; color:#888; font-weight:600; background:#fafbfa; }
td.name,th.name { text-align:left; }
td.num,th.num { text-align:right; } td.tot { font-weight:700; color:var(--green); text-align:right; }
input { font:inherit; }
.ti { border:1px solid #e3e3e3; border-radius:5px; padding:4px 6px; }
.ti:focus { border-color:var(--green); outline:none; }
.name input { width:100%; min-width:150px; }
.rate input { width:90px; text-align:right; }
.daycell input { width:40px; text-align:center; }
.daycell.zero input { color:#cbcbcb; }
.footer-row td { background:#f3f6f3; font-weight:700; }
.day-total td { background:var(--green); color:#fff; font-weight:700; border:0; }
.grp-head { background:#eef2ee; }
.grp-head input { background:transparent; border:0; font-weight:700; color:var(--green); font-size:13px; width:auto; min-width:220px; }
.grp-head input:focus { background:#fff; }
.controls { display:flex; gap:18px; align-items:center; margin:14px 0; flex-wrap:wrap; font-size:13px; }
.controls .ti { width:80px; }
.controls .wide { width:240px; }
.view-tabs { display:flex; gap:8px; margin:18px 0 10px; }
.tab { border:1px solid #d7dfd8; background:#fff; color:var(--green); border-radius:8px; padding:8px 14px; cursor:pointer; font-size:13px; font-weight:600; }
.tab.active { background:var(--green); color:#fff; border-color:var(--green); }
.hidden { display:none; }
.del { background:none; border:0; color:#c44; cursor:pointer; font-size:16px; line-height:1; padding:2px 6px; }
.add { background:#eef2ee; color:var(--green); border:1px dashed #9bb89e; border-radius:7px; padding:7px 14px; margin:8px; cursor:pointer; font-size:13px; }
.actions { margin:24px 0; } .btn { background:var(--green); color:#fff; border:0; padding:10px 18px; border-radius:8px; cursor:pointer; font-size:14px; }
.hint { font-size:12px; color:#999; margin-top:8px; }
.save-state { margin-top:10px; font-size:12px; color:#6d7d70; background:#fff; border-left:4px solid #9bb89e; padding:8px 10px; border-radius:6px; }
.save-state.dirty { border-left-color:#c26a3a; color:#83502f; background:#fff8f3; }
.help-box { margin:14px 0; background:#fff; border:1px solid #e1e7e2; border-radius:8px; padding:12px 14px; color:#465348; font-size:13px; line-height:1.45; }
.help-box strong { color:var(--green); }
.help-box p { margin:4px 0; }
.schedule-grid { display:grid; gap:12px; }
.work-board { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08); padding:12px; margin-bottom:14px; overflow-x:auto; }
.board-track { display:grid; grid-auto-flow:column; grid-auto-columns:minmax(220px,260px); gap:10px; min-width:max-content; align-items:start; }
.board-day { border:1px solid #dde6de; border-top:4px solid var(--green); border-radius:8px; padding:10px; background:#fbfcfb; cursor:pointer; text-align:left; font:inherit; color:inherit; min-height:280px; }
.board-day.active { outline:2px solid var(--green); background:#eef6ef; }
.board-day.ready { border-top-color:#5a8f5e; }
.board-day.risk { border-top-color:#c26a3a; background:#fff8f3; }
.board-day.risk.active { background:#fff0e8; }
.board-day.done { border-top-color:#777; background:#f7f7f7; }
.board-day.done.active { background:#eeeeee; }
.board-top { display:flex; justify-content:space-between; gap:10px; align-items:flex-start; border-bottom:1px solid #e7ede8; padding-bottom:8px; margin-bottom:8px; }
.board-top .n { font-size:12px; color:#223b25; font-weight:800; }
.board-top .date { font-size:11px; color:#888; margin-top:2px; }
.board-money { text-align:right; font-size:12px; font-weight:800; color:var(--green); white-space:nowrap; }
.board-money span { display:block; color:#777; font-size:11px; font-weight:600; margin-top:2px; }
.board-title { font-size:14px; font-weight:800; color:#223b25; line-height:1.25; margin-bottom:8px; white-space:normal; }
.board-section { margin-top:8px; }
.board-section h3 { font-size:10px; line-height:1; color:#777; text-transform:uppercase; margin:0 0 5px; letter-spacing:0; }
.board-pill { display:block; width:100%; border:1px solid #e1e7e2; border-radius:6px; background:#fff; padding:5px 6px; margin-top:4px; color:#303d32; font-size:12px; line-height:1.25; white-space:normal; }
.board-empty { color:#aaa; font-size:12px; }
.board-more { color:#777; font-size:11px; margin-top:4px; }
.plan-day { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08); overflow:hidden; }
.plan-head { display:flex; justify-content:space-between; gap:12px; align-items:flex-start; background:#eef2ee; padding:10px 12px; color:var(--green); }
.plan-head strong { display:block; font-size:15px; }
.plan-head span { display:block; color:#6d7d70; font-size:12px; margin-top:2px; }
.plan-cost { text-align:right; font-weight:700; white-space:nowrap; }
.plan-body { padding:12px; display:grid; gap:10px; grid-template-columns:repeat(2,minmax(0,1fr)); }
.plan-field.full { grid-column:1 / -1; }
.plan-field label { display:block; color:#777; font-size:11px; text-transform:uppercase; margin-bottom:4px; }
.plan-field input, .plan-field textarea, .plan-field select { width:100%; border:1px solid #e3e3e3; border-radius:6px; padding:7px 8px; font:inherit; background:#fff; }
.plan-field textarea { min-height:84px; resize:vertical; line-height:1.35; }
.print-only { display:none; }
.print-summary { display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin:12px 0; }
.print-box { border:1px solid #dfe6e0; border-radius:6px; padding:8px; background:#fff; }
.print-box .label { font-size:10px; color:#777; text-transform:uppercase; }
.print-box .value { font-size:15px; font-weight:800; margin-top:3px; color:#223b25; }
.print-section { break-inside:avoid; page-break-inside:avoid; margin:14px 0; }
.print-section h2 { margin:0 0 8px; }
.print-list { margin:4px 0 0 18px; padding:0; }
@media (max-width:720px) { main{padding:16px;} .plan-body{grid-template-columns:1fr;} }
@media print {
@page { margin:12mm; }
* { box-shadow:none !important; }
body { background:#fff; color:#111; }
header { background:#fff; color:#111; border-bottom:2px solid #2f5233; padding:0 0 8px; }
header h1 { font-size:22px; }
main { max-width:none; padding:0; }
.controls,.help-box,.view-tabs,.actions,.add,.del,#budgetView,#scheduleView,.summary { display:none !important; }
.print-only { display:block !important; }
.print-summary { grid-template-columns:repeat(4,1fr); }
.print-box { border-color:#cfd8d0; }
table { white-space:normal; font-size:10px; }
th,td { padding:4px 5px; }
}
</style></head>
<body>
<header><h1 id="title"></h1><div class="sub" id="subtitle"></div></header>
<main>
<div class="summary" id="summary"></div>
<div class="controls">
<label>Проект: <input class="ti wide" id="projectName"></label>
<label>Адрес: <input class="ti wide" id="projectAddress"></label>
<label>Прибыль, %: <input class="ti" type="number" id="profit"></label>
<label>Дней: <input class="ti" type="number" id="numDays" min="1"></label>
<label>Дата старта: <input class="ti" type="date" id="startDate"></label>
</div>
<div class="help-box">
<p><strong>Как сохранить работу.</strong> Смета хранится в отдельном файле проекта. Откройте его кнопкой «Открыть проект», правьте смету и нажимайте «Сохранить проект».</p>
<p>Автосохранение защищает от случайного закрытия страницы, но для передачи агенту нужно сохранить файл проекта.</p>
</div>
<div class="view-tabs">
<button class="tab active" id="budgetTab" onclick="switchView('budget')">Бюджет</button>
<button class="tab" id="scheduleTab" onclick="switchView('schedule')">График работ</button>
</div>
<section id="budgetView">
<h2>Люди по дням — основные затраты</h2>
<div class="panel"><div id="laborGrid"></div><button class="add" onclick="addLabor()">+ сотрудник</button></div>
<h2>Техника по дням</h2>
<div class="panel"><div id="equipGrid"></div><button class="add" onclick="addEquip()">+ техника</button></div>
<h2>Доставка по дням</h2>
<div class="panel"><div id="deliveryTable"></div><button class="add" onclick="addDelivery()">+ доставка</button></div>
<h2>Подрядчики (за задачу)</h2>
<div class="panel"><div id="subTable"></div><button class="add" onclick="addSub()">+ подрядчик</button></div>
<h2>Материалы — на весь объект</h2>
<div id="materials"></div>
<button class="add" onclick="addGroup()">+ группа материалов</button>
</section>
<section id="scheduleView" class="hidden">
<h2>Доска работ</h2>
<div id="workTimeline"></div>
<h2>День</h2>
<div id="scheduleList"></div>
</section>
<section class="print-only" id="printView"></section>
<div class="actions">
<button class="btn" style="background:#4f7652" onclick="printPdf()">🖨 Печать / PDF</button>
<button class="btn" onclick="saveToProjectFile()">💾 Сохранить проект</button>
<button class="btn" style="background:#5a8f5e" onclick="openProjectFile()">📂 Открыть проект</button>
<button class="btn" style="background:#666" onclick="downloadJSON()">⬇ Скачать копию</button>
<button class="btn" style="background:#777" onclick="newSmeta()">📄 Новая смета</button>
<button class="btn" style="background:#888" onclick="exportJSON()">Скопировать данные</button>
<input type="file" id="fileInput" accept=".json,application/json" style="display:none" onchange="openJSON(event)">
<div class="hint">Файл проекта — это маленький файл с данными сметы. Его можно отправить агенту, открыть снова или сохранить как копию.</div>
<div class="save-state" id="saveState"></div>
</div>
</main>
<script>
let DATA = __DATA__;
let N = DATA.num_days;
let CURRENT_DAY = 0;
let BOARD_SCROLL_LEFT = 0;
let DIRTY = false;
let LOADING = true;
let SAVE_TIMER = null;
let PROJECT_FILE_HANDLE = null;
const DRAFT_KEY = 'smeta-v2-draft';
const fmt = x => Math.round(x).toLocaleString('ru-RU') + ' ₽';
const k = d => String(d);
const el = id => document.getElementById(id);
const esc = s => (s==null?'':String(s)).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));
const lines = v => Array.isArray(v) ? v.join('\n') : (v || '');
const toLines = v => String(v || '').split('\n').map(x => x.trim()).filter(Boolean);
function dayLabor(d){ return (DATA.labor||[]).reduce((a,r)=>a+r.rate_per_day*(+r.days[k(d)]||0),0); }
function dayEquip(d){ return (DATA.equipment||[]).reduce((a,e)=>a+e.rate*(+e.days[k(d)]||0),0); }
function dayDeliv(d){ return (DATA.delivery||[]).filter(x=>x.day===d).reduce((a,x)=>a+ +x.price,0); }
function dayPeople(d){ return (DATA.labor||[]).reduce((a,r)=>a+(+r.days[k(d)]||0),0); }
function rowSum(r){ let s=0; for(let d=1;d<=N;d++) s+=(+r.days[k(d)]||0); return s; }
function matTotal(){ return (DATA.materials||[]).reduce((a,g)=>a+g.items.reduce((b,m)=>b+(+m.qty)*(+m.price),0),0); }
function dateForDay(d){
const start = DATA.project.start_date;
if(!start) return '';
const dt = new Date(start + 'T00:00:00');
if(Number.isNaN(dt.getTime())) return '';
if(d===0){
dt.setDate(dt.getDate() - 1);
return dt.toLocaleDateString('ru-RU', {day:'2-digit', month:'2-digit', year:'numeric'});
}
const workDays = Array.isArray(DATA.project.working_days) && DATA.project.working_days.length
? DATA.project.working_days.map(Number)
: null;
if(workDays){
let count = 0;
while(count < d){
if(workDays.includes(dt.getDay())) count++;
if(count < d) dt.setDate(dt.getDate() + 1);
}
} else {
dt.setDate(dt.getDate() + d - 1);
}
return dt.toLocaleDateString('ru-RU', {day:'2-digit', month:'2-digit', year:'numeric'});
}
function ensureSchedule(){
if(!Array.isArray(DATA.schedule)) DATA.schedule = [];
for(let d=0; d<=N; d++){
if(!DATA.schedule.find(x => +x.day === d)){
const title = d===0 ? 'Согласование и финализация плана' : '';
DATA.schedule.push({day:d,title,status:'planned',works:[],deliveries:[],checks:[],notes:''});
}
}
DATA.schedule = DATA.schedule
.filter(x => +x.day >= 0 && +x.day <= N)
.sort((a,b) => +a.day - +b.day);
}
function scheduleEntry(d){
ensureSchedule();
return DATA.schedule.find(x => +x.day === d);
}
function prepareForSave(){
DATA.num_days=N;
ensureSchedule();
}
function updateSaveState(){
const box=el('saveState');
if(!box) return;
const raw=localStorage.getItem(DRAFT_KEY);
let stamp='';
if(raw){
try{ stamp=new Date(JSON.parse(raw).saved_at).toLocaleString('ru-RU'); }catch{}
}
box.className='save-state'+(DIRTY?' dirty':'');
box.textContent=DIRTY
? `Есть несохранённые изменения. Черновик автосохранён в браузере${stamp?' '+stamp:''}. Чтобы агент увидел правки, нажмите «Сохранить проект».`
: (PROJECT_FILE_HANDLE
? `Проект сохранён в выбранный файл. Черновик в браузере${stamp?' от '+stamp:''}.`
: `Проект открыт или сохранён копией. Черновик в браузере${stamp?' от '+stamp:''}.`);
}
function autosaveDraft(){
prepareForSave();
localStorage.setItem(DRAFT_KEY, JSON.stringify({saved_at:new Date().toISOString(), data:DATA}));
updateSaveState();
}
function markDirty(){
if(LOADING) return;
DIRTY=true;
clearTimeout(SAVE_TIMER);
SAVE_TIMER=setTimeout(autosaveDraft, 250);
updateSaveState();
}
function clearDirty(){
DIRTY=false;
autosaveDraft();
}
function fileAccessSupported(){
return 'showOpenFilePicker' in window && 'showSaveFilePicker' in window;
}
function maybeRestoreDraft(){
const raw=localStorage.getItem(DRAFT_KEY);
if(!raw) return false;
try{
const draft=JSON.parse(raw);
if(!draft.data) return false;
const when=draft.saved_at ? new Date(draft.saved_at).toLocaleString('ru-RU') : '';
if(confirm(`Найден автосохранённый черновик${when?' от '+when:''}. Восстановить его?`)){
DATA=draft.data;
N=DATA.num_days||1;
return true;
}
}catch{}
return false;
}
function boardList(items, empty){
const arr = Array.isArray(items) ? items.filter(Boolean) : [];
if(!arr.length) return `<div class="board-empty">${esc(empty)}</div>`;
const shown = arr.slice(0, 4).map(x => `<div class="board-pill">${esc(x)}</div>`).join('');
const more = arr.length > 4 ? `<div class="board-more">+${arr.length - 4}</div>` : '';
return shown + more;
}
function renderWorkBoard(showActive=false){
ensureSchedule();
const oldBoard = el('workTimeline')?.querySelector('.work-board');
if(oldBoard) BOARD_SCROLL_LEFT = oldBoard.scrollLeft;
let html='<div class="work-board"><div class="board-track">';
for(let d=0; d<=N; d++){
const s=scheduleEntry(d);
const title=s.title || 'Работы не описаны';
const people=dayPeople(d);
const cost=dayLabor(d)+dayEquip(d)+dayDeliv(d);
const equip=(DATA.equipment||[]).filter(e => (+e.days[k(d)]||0)>0).map(e => `${e.name} × ${+e.days[k(d)]||0}`);
html+=`<button class="board-day ${esc(s.status||'planned')}${d===CURRENT_DAY?' active':''}" onclick="selectDay(${d})">
<div class="board-top">
<div><div class="n">День ${d}</div><div class="date">${dateForDay(d) || 'без даты'}</div></div>
<div class="board-money">${fmt(cost)}<span>${people} чел.</span></div>
</div>
<div class="board-title">${esc(title)}</div>
<div class="board-section"><h3>Работы</h3>${boardList(s.works,'нет работ')}</div>
<div class="board-section"><h3>Поставки</h3>${boardList(s.deliveries,'нет поставок')}</div>
<div class="board-section"><h3>Проверки</h3>${boardList(s.checks,'нет проверок')}</div>
<div class="board-section"><h3>Техника</h3>${boardList(equip,'нет техники')}</div>
</button>`;
}
html+='</div></div>';
el('workTimeline').innerHTML=html;
const board = el('workTimeline').querySelector('.work-board');
if(!board) return;
board.scrollLeft = BOARD_SCROLL_LEFT;
board.onscroll = () => { BOARD_SCROLL_LEFT = board.scrollLeft; };
if(showActive){
const active = board.querySelector('.board-day.active');
if(active) active.scrollIntoView({behavior:'auto', block:'nearest', inline:'center'});
BOARD_SCROLL_LEFT = board.scrollLeft;
}
}
function totals(){
let labor=0,equip=0;
for(let d=1;d<=N;d++){ labor+=dayLabor(d); equip+=dayEquip(d); }
const deliv=(DATA.delivery||[]).reduce((a,x)=>a+ +x.price,0);
const sub=(DATA.subcontractors||[]).reduce((a,s)=>a+ +s.price,0);
const mat=matTotal();
const base=labor+equip+deliv+sub+mat;
const profit=base*(+DATA.project.profit_pct||0)/100;
return {labor,equip,deliv,sub,mat,base,profit,client:base+profit};
}
/* ---- light recalc: refresh computed cells only, keep input focus ---- */
function recalc(){
const t=totals();
el('summary').innerHTML=`
<div class="card"><div class="label">Люди</div><div class="val">${fmt(t.labor)}</div></div>
<div class="card"><div class="label">Техника</div><div class="val">${fmt(t.equip)}</div></div>
<div class="card"><div class="label">Доставка</div><div class="val">${fmt(t.deliv)}</div></div>
<div class="card"><div class="label">Подряд</div><div class="val">${fmt(t.sub)}</div></div>
<div class="card"><div class="label">Материалы</div><div class="val">${fmt(t.mat)}</div></div>
<div class="card"><div class="label">Себестоимость</div><div class="val">${fmt(t.base)}</div></div>
<div class="card"><div class="label">Прибыль ${DATA.project.profit_pct}%</div><div class="val">${fmt(t.profit)}</div></div>
<div class="card price"><div class="label">Цена клиенту</div><div class="val">${fmt(t.client)}</div></div>`;
(DATA.labor||[]).forEach((r,i)=>{ if(el('labtot'+i)) el('labtot'+i).textContent=fmt(rowSum(r)*r.rate_per_day); });
(DATA.equipment||[]).forEach((e,i)=>{ if(el('eqtot'+i)) el('eqtot'+i).textContent=fmt(rowSum(e)*e.rate); });
for(let d=1;d<=N;d++){ if(el('ppl'+d)) el('ppl'+d).textContent=dayPeople(d); if(el('dtot'+d)) el('dtot'+d).textContent=fmt(dayLabor(d)+dayEquip(d)+dayDeliv(d)); }
(DATA.materials||[]).forEach((g,gi)=>{ let gs=0; g.items.forEach((m,ii)=>{ const s=(+m.qty)*(+m.price); gs+=s; if(el(`msum${gi}_${ii}`)) el(`msum${gi}_${ii}`).textContent=fmt(s); }); if(el('mgrp'+gi)) el('mgrp'+gi).textContent=fmt(gs); });
}
/* ---- day-matrix grids (labor / equipment) ---- */
function dayHead(){ let h='<th class="name">Должность / техника</th>'; for(let d=1;d<=N;d++) h+='<th>Д'+d+'</th>'; return h+'<th class="rate">Ставка</th><th class="num">Итого</th><th></th>'; }
function gridLabor(){
let h='<table><tr>'+dayHead()+'</tr>';
(DATA.labor||[]).forEach((r,i)=>{
let cells='';
for(let d=1;d<=N;d++){ const v=+r.days[k(d)]||0;
cells+=`<td class="daycell${v?'':' zero'}"><input class="ti" type="number" min="0" step="1" value="${v}" oninput="setLabor(${i},${d},this.value)"></td>`; }
h+=`<tr><td class="name"><input class="ti" value="${esc(r.role)}" oninput="DATA.labor[${i}].role=this.value"></td>${cells}`
+`<td class="rate"><input class="ti" type="number" step="any" value="${r.rate_per_day}" oninput="DATA.labor[${i}].rate_per_day=+this.value;recalc()"></td>`
+`<td class="tot" id="labtot${i}"></td><td><button class="del" title="удалить" onclick="delLabor(${i})">×</button></td></tr>`;
});
let pr='<tr class="footer-row"><td class="name">Человек в день</td>';
for(let d=1;d<=N;d++) pr+=`<td id="ppl${d}"></td>`; pr+='<td></td><td></td><td></td></tr>';
let cr='<tr class="day-total"><td class="name">ИТОГ ДНЯ</td>';
for(let d=1;d<=N;d++) cr+=`<td id="dtot${d}"></td>`; cr+='<td></td><td></td><td></td></tr>';
el('laborGrid').innerHTML=h+pr+cr+'</table>';
}
function gridEquip(){
let h='<table><tr>'+dayHead()+'</tr>';
(DATA.equipment||[]).forEach((e,i)=>{
let cells='';
for(let d=1;d<=N;d++){ const v=+e.days[k(d)]||0;
cells+=`<td class="daycell${v?'':' zero'}"><input class="ti" type="number" min="0" step="1" value="${v}" oninput="setEquip(${i},${d},this.value)"></td>`; }
h+=`<tr><td class="name"><input class="ti" value="${esc(e.name)}" oninput="DATA.equipment[${i}].name=this.value"></td>${cells}`
+`<td class="rate"><input class="ti" type="number" step="any" value="${e.rate}" oninput="DATA.equipment[${i}].rate=+this.value;recalc()"></td>`
+`<td class="tot" id="eqtot${i}"></td><td><button class="del" onclick="delEquip(${i})">×</button></td></tr>`;
});
el('equipGrid').innerHTML=h+'</table>';
}
function deliveryTable(){
let h='<table><tr><th>День</th><th class="name">Что везём</th><th class="num">Цена</th><th></th></tr>';
(DATA.delivery||[]).forEach((x,i)=>{
h+=`<tr><td><input class="ti" style="width:50px;text-align:center" type="number" min="1" max="${N}" value="${x.day}" oninput="DATA.delivery[${i}].day=+this.value;recalc()"></td>`
+`<td class="name"><input class="ti" value="${esc(x.name)}" oninput="DATA.delivery[${i}].name=this.value"></td>`
+`<td class="rate"><input class="ti" type="number" value="${x.price}" oninput="DATA.delivery[${i}].price=+this.value;recalc()"></td>`
+`<td><button class="del" onclick="delDelivery(${i})">×</button></td></tr>`;
});
el('deliveryTable').innerHTML=h+'</table>';
}
function subTable(){
let h='<table><tr><th class="name">Подрядчик</th><th class="name">Объём</th><th class="num">Цена</th><th></th></tr>';
(DATA.subcontractors||[]).forEach((s,i)=>{
h+=`<tr><td class="name"><input class="ti" value="${esc(s.name)}" oninput="DATA.subcontractors[${i}].name=this.value"></td>`
+`<td class="name"><input class="ti" value="${esc(s.scope)}" oninput="DATA.subcontractors[${i}].scope=this.value"></td>`
+`<td class="rate"><input class="ti" type="number" value="${s.price}" oninput="DATA.subcontractors[${i}].price=+this.value;recalc()"></td>`
+`<td><button class="del" onclick="delSub(${i})">×</button></td></tr>`;
});
el('subTable').innerHTML=h+'</table>';
}
function materialsView(){
let html='';
(DATA.materials||[]).forEach((g,gi)=>{
let rows='';
g.items.forEach((m,ii)=>{
rows+=`<tr><td class="name"><input class="ti" value="${esc(m.name)}" oninput="DATA.materials[${gi}].items[${ii}].name=this.value"></td>`
+`<td><input class="ti" style="width:64px" value="${esc(m.unit)}" oninput="DATA.materials[${gi}].items[${ii}].unit=this.value"></td>`
+`<td class="rate"><input class="ti" style="width:70px" type="number" step="any" value="${m.qty}" oninput="DATA.materials[${gi}].items[${ii}].qty=+this.value;recalc()"></td>`
+`<td class="rate"><input class="ti" type="number" step="any" value="${m.price}" oninput="DATA.materials[${gi}].items[${ii}].price=+this.value;recalc()"></td>`
+`<td class="tot" id="msum${gi}_${ii}"></td>`
+`<td><button class="del" onclick="delMat(${gi},${ii})">×</button></td></tr>`;
});
html+=`<div class="panel" style="margin-bottom:14px"><table>`
+`<tr class="grp-head"><td class="name" colspan="2"><input value="${esc(g.group)}" oninput="DATA.materials[${gi}].group=this.value"></td>`
+`<td colspan="2" class="num" style="color:#888;font-size:11px">итого группы</td><td class="tot" id="mgrp${gi}"></td>`
+`<td><button class="del" title="удалить группу" onclick="delGroup(${gi})">×</button></td></tr>`
+`<tr><th class="name">Материал</th><th>Ед.</th><th class="num">Кол-во</th><th class="num">Цена/ед</th><th class="num">Сумма</th><th></th></tr>`
+rows+`</table><button class="add" onclick="addMat(${gi})">+ материал</button></div>`;
});
el('materials').innerHTML=html;
}
function renderSchedule(showActive=false){
ensureSchedule();
if(CURRENT_DAY > N) CURRENT_DAY = N;
if(CURRENT_DAY < 0) CURRENT_DAY = 0;
renderWorkBoard(showActive);
const d=CURRENT_DAY;
const s=scheduleEntry(d);
const date=dateForDay(d);
const dayCost=dayLabor(d)+dayEquip(d)+dayDeliv(d);
const html=`<div class="schedule-grid"><article class="plan-day">
<div class="plan-head">
<div><strong>День ${d}</strong><span>${date || 'Дата не задана'}</span></div>
<div class="plan-cost">${fmt(dayCost)}<span>${dayPeople(d)} чел.</span></div>
</div>
<div class="plan-body">
<div class="plan-field">
<label>Фокус дня</label>
<input value="${esc(s.title)}" oninput="setScheduleField(${d},'title',this.value)" placeholder="Например: бетонные дорожки">
</div>
<div class="plan-field">
<label>Статус</label>
<select onchange="setScheduleField(${d},'status',this.value)">
<option value="planned"${s.status==='planned'?' selected':''}>Запланировано</option>
<option value="ready"${s.status==='ready'?' selected':''}>Готово к старту</option>
<option value="risk"${s.status==='risk'?' selected':''}>Есть риск</option>
<option value="done"${s.status==='done'?' selected':''}>Выполнено</option>
</select>
</div>
<div class="plan-field">
<label>Работы</label>
<textarea oninput="setScheduleLines(${d},'works',this.value)" placeholder="Одна строка = одно действие">${esc(lines(s.works))}</textarea>
</div>
<div class="plan-field">
<label>Поставки и логистика</label>
<textarea oninput="setScheduleLines(${d},'deliveries',this.value)" placeholder="Что должно приехать и когда">${esc(lines(s.deliveries))}</textarea>
</div>
<div class="plan-field">
<label>Проверить заранее</label>
<textarea oninput="setScheduleLines(${d},'checks',this.value)" placeholder="Подтверждения, оплаты, готовность участка">${esc(lines(s.checks))}</textarea>
</div>
<div class="plan-field">
<label>Заметки</label>
<textarea oninput="setScheduleField(${d},'notes',this.value)" placeholder="Ограничения, риски, решения">${esc(s.notes)}</textarea>
</div>
</div>
</article></div>`;
el('scheduleList').innerHTML=html;
}
function printList(items){
const arr = Array.isArray(items) ? items.filter(Boolean) : [];
if(!arr.length) return '<span style="color:#888">—</span>';
return '<ul class="print-list">'+arr.map(x=>`<li>${esc(x)}</li>`).join('')+'</ul>';
}
function renderPrintView(){
prepareForSave();
const t=totals();
let html=`<div class="print-section">
<h2>Сводка</h2>
<div class="print-summary">
<div class="print-box"><div class="label">Люди</div><div class="value">${fmt(t.labor)}</div></div>
<div class="print-box"><div class="label">Техника</div><div class="value">${fmt(t.equip)}</div></div>
<div class="print-box"><div class="label">Доставка</div><div class="value">${fmt(t.deliv)}</div></div>
<div class="print-box"><div class="label">Материалы</div><div class="value">${fmt(t.mat)}</div></div>
<div class="print-box"><div class="label">Подряд</div><div class="value">${fmt(t.sub)}</div></div>
<div class="print-box"><div class="label">Себестоимость</div><div class="value">${fmt(t.base)}</div></div>
<div class="print-box"><div class="label">Прибыль ${DATA.project.profit_pct||0}%</div><div class="value">${fmt(t.profit)}</div></div>
<div class="print-box"><div class="label">Цена клиенту</div><div class="value">${fmt(t.client)}</div></div>
</div>
</div>`;
html+=`<div class="print-section"><h2>Затраты по дням</h2><table><tr><th>День</th><th>Дата</th><th>Людей</th><th class="num">Работа</th><th class="num">Техника</th><th class="num">Доставка</th><th class="num">Итого</th></tr>`;
for(let d=1; d<=N; d++){
const lab=dayLabor(d), eq=dayEquip(d), dl=dayDeliv(d);
html+=`<tr><td>${d}</td><td>${dateForDay(d)||''}</td><td>${dayPeople(d)}</td><td class="num">${fmt(lab)}</td><td class="num">${fmt(eq)}</td><td class="num">${fmt(dl)}</td><td class="num"><strong>${fmt(lab+eq+dl)}</strong></td></tr>`;
}
html+='</table></div>';
html+=`<div class="print-section"><h2>Материалы</h2>`;
(DATA.materials||[]).forEach(g=>{
html+=`<h3>${esc(g.group||'Материалы')}</h3><table><tr><th class="name">Материал</th><th>Ед.</th><th class="num">Кол-во</th><th class="num">Цена</th><th class="num">Сумма</th></tr>`;
(g.items||[]).forEach(m=>{
html+=`<tr><td class="name">${esc(m.name)}</td><td>${esc(m.unit)}</td><td class="num">${m.qty||0}</td><td class="num">${fmt(+m.price||0)}</td><td class="num">${fmt((+m.qty||0)*(+m.price||0))}</td></tr>`;
});
html+='</table>';
});
html+='</div>';
html+=`<div class="print-section"><h2>График работ</h2><table><tr><th>День</th><th>Дата</th><th class="name">Фокус</th><th class="name">Работы</th><th class="name">Поставки</th><th class="name">Проверки</th><th>Статус</th></tr>`;
(DATA.schedule||[]).forEach(s=>{
html+=`<tr><td>${s.day}</td><td>${dateForDay(+s.day)||''}</td><td class="name">${esc(s.title||'')}</td><td class="name">${printList(s.works)}</td><td class="name">${printList(s.deliveries)}</td><td class="name">${printList(s.checks)}</td><td>${esc(s.status||'planned')}</td></tr>`;
});
html+='</table></div>';
if((DATA.subcontractors||[]).length){
html+=`<div class="print-section"><h2>Подрядчики</h2><table><tr><th class="name">Подрядчик</th><th class="name">Объём</th><th class="num">Цена</th></tr>`;
DATA.subcontractors.forEach(s=>{ html+=`<tr><td class="name">${esc(s.name)}</td><td class="name">${esc(s.scope)}</td><td class="num">${fmt(+s.price||0)}</td></tr>`; });
html+='</table></div>';
}
el('printView').innerHTML=html;
}
function printPdf(){
renderPrintView();
window.print();
}
/* ---- mutations (structural -> full render) ---- */
function setLabor(i,d,v){ DATA.labor[i].days[k(d)]=parseInt(v)||0; recalc(); el('laborGrid').querySelectorAll('tr')[i+1].children[d].className='daycell'+((parseInt(v)||0)?'':' zero'); }
function setEquip(i,d,v){ DATA.equipment[i].days[k(d)]=parseInt(v)||0; recalc(); }
function addLabor(){ DATA.labor.push({role:'Новая должность',rate_per_day:0,days:{}}); render(); markDirty(); }
function delLabor(i){ DATA.labor.splice(i,1); render(); markDirty(); }
function addEquip(){ DATA.equipment.push({name:'Новая техника',rate:0,days:{}}); render(); markDirty(); }
function delEquip(i){ DATA.equipment.splice(i,1); render(); markDirty(); }
function addDelivery(){ DATA.delivery.push({day:1,name:'',price:0}); render(); markDirty(); }
function delDelivery(i){ DATA.delivery.splice(i,1); render(); markDirty(); }
function addSub(){ DATA.subcontractors.push({name:'',scope:'',price:0}); render(); markDirty(); }
function delSub(i){ DATA.subcontractors.splice(i,1); render(); markDirty(); }
function addGroup(){ DATA.materials.push({group:'Новая группа',items:[]}); render(); markDirty(); }
function delGroup(gi){ DATA.materials.splice(gi,1); render(); markDirty(); }
function addMat(gi){ DATA.materials[gi].items.push({name:'',unit:'',qty:0,price:0}); render(); markDirty(); }
function delMat(gi,ii){ DATA.materials[gi].items.splice(ii,1); render(); markDirty(); }
function selectDay(d){ CURRENT_DAY=d; renderSchedule(true); }
function setScheduleField(d,field,value){
scheduleEntry(d)[field]=value;
if(field==='title' || field==='status') renderWorkBoard();
markDirty();
}
function setScheduleLines(d,field,value){
scheduleEntry(d)[field]=toLines(value);
renderWorkBoard();
markDirty();
}
function switchView(name){
el('budgetView').classList.toggle('hidden', name!=='budget');
el('scheduleView').classList.toggle('hidden', name!=='schedule');
el('budgetTab').classList.toggle('active', name==='budget');
el('scheduleTab').classList.toggle('active', name==='schedule');
if(name==='schedule') renderSchedule();
}
function render(){
ensureSchedule();
el('title').textContent=DATA.project.name;
el('subtitle').textContent='Дней: '+N+' · '+(DATA.project.note||'');
gridLabor(); gridEquip(); deliveryTable(); subTable(); materialsView();
renderSchedule();
recalc();
}
function exportJSON(){
prepareForSave();
navigator.clipboard.writeText(JSON.stringify(DATA,null,2))
.then(()=>alert('JSON скопирован')).catch(()=>{const w=window.open('','_blank');w.document.write('<pre>'+JSON.stringify(DATA,null,2).replace(/</g,'<')+'</pre>');});
}
function fileName(){ return (DATA.project.name||'smeta').replace(/[^\wа-яёА-ЯЁ\- ]/gi,'').trim().replace(/\s+/g,'_')||'smeta'; }
function downloadJSON(){
prepareForSave();
const blob=new Blob([JSON.stringify(DATA,null,2)],{type:'application/json'});
const a=document.createElement('a');
a.href=URL.createObjectURL(blob); a.download=fileName()+'.json';
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(a.href);
clearDirty();
}
async function saveToProjectFile(){
prepareForSave();
if(!fileAccessSupported()){
alert('Этот браузер не умеет перезаписывать выбранный файл. Скачаю копию проекта отдельным файлом.');
downloadJSON();
return;
}
try{
if(!PROJECT_FILE_HANDLE){
PROJECT_FILE_HANDLE = await window.showSaveFilePicker({
suggestedName:fileName()+'.json',
types:[{description:'JSON сметы', accept:{'application/json':['.json']}}]
});
}
const writable = await PROJECT_FILE_HANDLE.createWritable();
await writable.write(JSON.stringify(DATA,null,2));
await writable.close();
clearDirty();
alert('Проект сохранён в выбранный файл.');
}catch(e){
if(e && e.name === 'AbortError') return;
alert('Не удалось сохранить проект: '+e.message);
}
}
function loadData(obj, dirty=false){
LOADING=true;
if(!obj.project) obj.project={name:'Новый объект',address:'',start_date:null,working_days:[1,2,3,4,5,6],profit_pct:20,note:''};
if(!Array.isArray(obj.project.working_days)) obj.project.working_days=[1,2,3,4,5,6];
DATA=obj; N=DATA.num_days||1;
el('projectName').value=DATA.project.name||'';
el('projectAddress').value=DATA.project.address||'';
el('profit').value=DATA.project.profit_pct||0;
el('numDays').value=N; el('startDate').value=DATA.project.start_date||'';
render();
DIRTY=dirty;
LOADING=false;
if(dirty) markDirty(); else clearDirty();
}
function openJSON(ev){
const f=ev.target.files[0]; if(!f) return;
PROJECT_FILE_HANDLE=null;
const r=new FileReader();
r.onload=()=>{ try{ loadData(JSON.parse(r.result), false); }catch(e){ alert('Не удалось открыть файл проекта: '+e.message); } };
r.readAsText(f); ev.target.value='';
}
async function openProjectFile(){
if(!fileAccessSupported()){
el('fileInput').click();
return;
}
try{
const handles = await window.showOpenFilePicker({
multiple:false,
types:[{description:'JSON сметы', accept:{'application/json':['.json']}}]
});
PROJECT_FILE_HANDLE = handles[0];
const file = await PROJECT_FILE_HANDLE.getFile();
loadData(JSON.parse(await file.text()), false);
}catch(e){
if(e && e.name === 'AbortError') return;
alert('Не удалось открыть файл проекта: '+e.message);
}
}
function newSmeta(){
if(!confirm('Создать новую пустую смету? Несохранённые изменения будут потеряны.')) return;
PROJECT_FILE_HANDLE=null;
loadData({schema_version:'0.4',project:{name:'Новый объект',address:'',start_date:null,working_days:[1,2,3,4,5,6],profit_pct:20,note:''},
num_days:5,labor:[],equipment:[],delivery:[],subcontractors:[],materials:[],schedule:[]}, true);
}
const RESTORED_DRAFT = maybeRestoreDraft();
if(!DATA.project) DATA.project={name:'Новый объект',address:'',start_date:null,working_days:[1,2,3,4,5,6],profit_pct:20,note:''};
if(!Array.isArray(DATA.project.working_days)) DATA.project.working_days=[1,2,3,4,5,6];
el('projectName').value=DATA.project.name||'';
el('projectAddress').value=DATA.project.address||'';
el('profit').value=DATA.project.profit_pct;
el('numDays').value=N;
el('startDate').value=DATA.project.start_date||'';
el('projectName').oninput=e=>{DATA.project.name=e.target.value||'Новый объект';render();};
el('projectAddress').oninput=e=>{DATA.project.address=e.target.value||'';};
el('profit').oninput=e=>{DATA.project.profit_pct=+e.target.value||0;recalc();};
el('numDays').oninput=e=>{N=Math.max(1,parseInt(e.target.value)||1);DATA.num_days=N;render();};
el('startDate').oninput=e=>{DATA.project.start_date=e.target.value||null;renderSchedule();};
render();
LOADING=false;
DIRTY=RESTORED_DRAFT;
updateSaveState();
document.addEventListener('input', e=>{ if(e.target && e.target.id!=='fileInput') markDirty(); });
document.addEventListener('change', e=>{ if(e.target && e.target.id!=='fileInput') markDirty(); });
window.addEventListener('beforeunload', e=>{
if(!DIRTY) return;
e.preventDefault();
e.returnValue='';
});
</script>
</body></html>
"""
def main():
ap = argparse.ArgumentParser(description="Smeta engine (day-centric)")
ap.add_argument("json_path")
ap.add_argument("--html", nargs="?", const="smeta.html")
args = ap.parse_args()
data = json.loads(Path(args.json_path).read_text(encoding="utf-8"))
print_report(data, compute(data))
if args.html:
generate_html(data, args.html)
if __name__ == "__main__":
sys.exit(main())