-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
2759 lines (2464 loc) · 146 KB
/
App.tsx
File metadata and controls
2759 lines (2464 loc) · 146 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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { GoogleGenAI, Type, Schema, HarmCategory, HarmBlockThreshold } from "@google/genai";
import { detectCategories, parseNavisworksXML } from "./utils/collisionParser";
import { getDemoFiles } from "./utils/demoFiles";
// --- Types & Interfaces ---
interface Discipline {
id: string;
code: string;
shortCodeKey: string;
rank: number; // 1 (Hardest) to 6 (Easiest)
nameKey: string;
descKey: string;
keywordsKey: string;
}
interface WorkItem {
id: string;
categoryId: string;
name: string;
price: number;
currency?: string;
unit: string;
source: string;
score: number; // 0 to 1
status: "pending" | "accepted" | "rejected";
}
interface Scenario {
id: string;
matrixKey: string; // format: "rowId:colId"
name: string;
description: string;
works: ScenarioWork[];
}
interface ScenarioWork {
workId: string;
quantity: number;
active: boolean;
}
interface LogEntry {
id: string;
timestamp: number;
action: string;
status: "success" | "error";
details: string;
tokensUsed: number;
}
interface AppSettings {
model: string;
language: "en" | "ru";
apiUrl: string;
apiKey: string;
enableAutomation: boolean;
parsingSites: ParsingSite[];
}
interface ParsingSite {
id: string;
url: string;
categories: string;
description: string;
}
interface LoadingState {
step: string;
progress: number;
}
interface BulkStatus {
active: boolean;
type: 'load' | 'gen' | 'match';
total: number;
current: number;
label: string;
}
interface ImportedFile {
id: string;
filename: string;
timestamp: number;
collisionCount: number;
rowId: string | null;
colId: string | null;
}
// --- Constants & Translations ---
const TRANSLATIONS = {
en: {
appTitle: "Collision Cost MVP",
tabs: { collision: "Collision", cost: "Cost", import: "Import", settings: "Settings", logs: "Logs" },
importTitle: "Import Collision Reports (XML)",
importDesc: "Upload XML reports from Navisworks or similar tools to map collisions to the matrix.",
uploadBtn: "Upload XML",
noFiles: "No files uploaded yet.",
fileName: "File Name",
collisions: "Collisions",
mappedRow: "Row (Category 1)",
mappedCol: "Column (Category 2)",
importMatrix: "Import Matrix (Total Cost)",
totalCost: "Total Estimated Cost",
collisionControls: "Collision Matrix Controls",
placeholderUrl: "Pricing Source URL (e.g. ferrum-price.com)...",
btnLoad: "Load Works",
btnLoading: "Loading",
minScope: "Min Scope",
btnAutoAccept: "Auto Accept",
selected: "Selected",
btnGenerate: "Generate Scenarios (LLM)",
btnThinking: "Generating",
rankMatrix: "Rank Matrix",
toggleDrawer: "Click row header to toggle drawer",
costMatrix: "Cost Matrix",
toggleDetail: "Click cell to toggle detail panel",
worksPanel: "Works",
showPanel: "Show Panel",
hide: "Hide",
hideUnaffected: "Hide unaffected",
table: {
name: "Name",
price: "Price",
unit: "Unit",
source: "Source",
score: "Score",
status: "Status",
action: "Action",
totalCost: "Total Cost"
},
noWorks: "No works loaded. Enter URL and click Load.",
scenarios: "Scenarios",
noScenarios: "No scenarios generated. Click \"Generate Scenarios\" above.",
generatingScenarios: "Generating scenarios from LLM...",
scenarioName: "Scenario Name",
description: "Description",
addManual: "-- Select work to add manually --",
btnAdd: "Add",
btnAutoSuggest: "Auto-Suggest (LLM)",
btnMatching: "Matching...",
noWorksAdded: "No works added yet.",
noWorksAddedHint: "Use the dropdown above to add works manually or click \"Auto-Suggest\" to let AI find suitable works.",
selectScenario: "Select a scenario to view and edit details",
settingsTitle: "Settings",
apiKeyLabel: "API Key",
apiKeyHint: "Leave empty to use the default environment key.",
modelLabel: "Model",
apiUrlLabel: "API Endpoint URL",
languageLabel: "Language",
dataMgmt: "Data Management (Persistence)",
dataMgmtHint: "Data is automatically saved to your browser's LocalStorage. To save to a file (e.g., for GitHub repo sync), export the database as JSON.",
btnExport: "Download DB (.json)",
btnImport: "Import DB (.json)",
btnLoadDemo: "Load Demo Data",
demoLoaded: "Demo data loaded successfully!",
btnExportSites: "Export Sites (.json)",
btnImportSites: "Import Sites (.json)",
btnLoadDemoSites: "Load Demo Sites",
demoSitesLoaded: "Demo sites loaded!",
btnReset: "Reset / Clear Data",
systemStatus: "System Status",
apiConfigured: "API Configured",
storageActive: "LocalStorage Active",
logsTitle: "Request Logs",
totalTokens: "Total Tokens",
noLogs: "No logs yet.",
automationLabel: "Enable Full Automation",
automationHint: "Enables bulk operations buttons. Use with caution (consumes many tokens).",
btnBulkLoad: "Load All (Auto)",
btnBulkGen: "Generate All Scenarios (Auto)",
btnBulkMatch: "Match All Scenarios (Auto)",
bulkLoadConfirm: "This will iterate through ALL categories and load works. It may consume a lot of tokens and time. Continue?",
bulkGenConfirm: "This will generate scenarios for ALL matrix cells. Continue?",
bulkMatchConfirm: "This will attempt to match works for ALL scenarios that have no works assigned. Continue?",
steps: {
parsing: "Parsing Page...",
classifying: "Classifying...",
analyzing: "Generating scenarios from LLM...",
finalizing: "Finalizing...",
generating: "Generating scenarios...",
matching: "Matching Works..."
},
disciplines: {
codes: {
ARCH: "ARCH",
STR: "STR",
PL: "PL",
HVAC: "HVAC",
ITP: "ITP",
FPS: "FPS",
ELEC: "ELEC",
ELV: "ELV",
AI: "AI"
},
AR_WALLS_NAME: "Walls", AR_WALLS_DESC: "Architectural walls, partitions",
AR_WALLS_KW: "brick, block, drywall, plaster, paint, dismantling, partition",
AR_DOORS_NAME: "Doors / Windows", AR_DOORS_DESC: "Door and window openings",
AR_DOORS_KW: "door, window, jam, installation, dismantling, opening",
KR_WALLS_NAME: "Walls", KR_WALLS_DESC: "Load-bearing walls (Monolith)",
KR_WALLS_KW: "concrete, monolith, reinforcement, drilling, diamond cutting, opening, hole",
KR_COLS_NAME: "Columns / Pylons", KR_COLS_DESC: "Load-bearing columns",
KR_COLS_KW: "concrete, monolith, column, pylon, drilling, diamond cutting, reinforcement, hole",
KR_SLABS_NAME: "Slabs / Ramps", KR_SLABS_DESC: "Floor slabs",
KR_SLABS_KW: "concrete, slab, floor, ceiling, drilling, cutting, opening",
KR_BEAMS_NAME: "Beams", KR_BEAMS_DESC: "Load-bearing beams",
KR_BEAMS_KW: "concrete, beam, drilling, cutting, reinforcement",
VK_K_NAME: "Pipes / Drainage", VK_K_DESC: "Sewage and storm drainage",
VK_K_KW: "pipe, drainage, sewage, plastic, installation, dismantling",
VK_V_NAME: "Pipes", VK_V_DESC: "Water supply (Pressure)",
VK_V_KW: "pipe, water supply, steel, polypropylene, installation, valve",
OV_VENT_NAME: "Ducts", OV_VENT_DESC: "Ventilation ducts",
OV_VENT_KW: "duct, ventilation, tin, installation, dismantling, diffusers",
OV_HEAT_NAME: "Pipes", OV_HEAT_DESC: "Heating pipes",
OV_HEAT_KW: "radiator, pipe, heating, welding, installation",
AUPT_PIPE_NAME: "Pipes", AUPT_PIPE_DESC: "Fire extinguishing pipes",
AUPT_PIPE_KW: "pipe, fire, steel, welding, painting",
AUPT_SPR_NAME: "Sprinklers", AUPT_SPR_DESC: "Sprinkler heads",
AUPT_SPR_KW: "sprinkler, head, fire",
EOM_NAME: "Trays / Cables", EOM_DESC: "Cable trays, low voltage",
EOM_KW: "tray, cable, wire, socket, switch, installation",
AR_FACADE_NAME: "Facades", AR_FACADE_DESC: "Building facades", AR_FACADE_KW: "facade, panel, glass, cladding",
AR_ROOF_NAME: "Roofs", AR_ROOF_DESC: "Roofing", AR_ROOF_KW: "roof, tile, waterproofing",
OV_ITP_NAME: "Individual Heating Point", OV_ITP_DESC: "Heating point equipment", OV_ITP_KW: "itp, heat exchanger, pump, valve",
SS_NAME: "Low Current Systems", SS_DESC: "Security, fire alarm, internet", SS_KW: "alarm, sensor, camera, data, cable",
AI_NAME: "Architectural Interiors", AI_DESC: "Interior finishing", AI_KW: "interior, finish, decoration, furniture"
}
},
ru: {
appTitle: "Collision Cost MVP",
tabs: { collision: "Коллизии", cost: "Стоимость", import: "Импорт", settings: "Настройки", logs: "Логи" },
importTitle: "Импорт отчетов о коллизиях (XML)",
importDesc: "Загрузите XML отчеты из Navisworks или аналогов для сопоставления коллизий с матрицей.",
uploadBtn: "Загрузить XML",
noFiles: "Файлы пока не загружены.",
fileName: "Имя файла",
collisions: "Коллизии",
mappedRow: "Строка (Категория 1)",
mappedCol: "Столбец (Категория 2)",
importMatrix: "Матрица Импорта (Общая стоимость)",
totalCost: "Общая оценочная стоимость",
collisionControls: "Управление матрицей коллизий",
placeholderUrl: "URL источника цен (например, ferrum-price.com)...",
btnLoad: "Загрузить работы",
btnLoading: "Загрузка",
minScope: "Мин. порог",
btnAutoAccept: "Авто-принятие",
selected: "Выбрано",
btnGenerate: "Сгенерировать сценарии (LLM)",
btnThinking: "Генерация",
rankMatrix: "Матрица Рангов",
toggleDrawer: "Нажмите на заголовок строки, чтобы открыть панель",
costMatrix: "Матрица Стоимости",
toggleDetail: "Нажмите на ячейку, чтобы открыть детали",
worksPanel: "Работы",
showPanel: "Показать панель",
hide: "Скрыть",
hideUnaffected: "Скрыть незатронутые",
table: {
name: "Наименование",
price: "Цена",
unit: "Ед.изм.",
source: "Источник",
score: "Оценка",
status: "Статус",
action: "Действие",
totalCost: "Общая стоимость"
},
noWorks: "Работы не загружены. Введите URL и нажмите Загрузить.",
scenarios: "Сценарии",
noScenarios: "Сценарии не сгенерированы. Нажмите \"Сгенерировать сценарии\" выше.",
generatingScenarios: "Идет генерация сценариев...",
scenarioName: "Название сценария",
description: "Описание",
addManual: "-- Выберите работу для добавления вручную --",
btnAdd: "Добавить",
btnAutoSuggest: "Авто-подбор (LLM)",
btnMatching: "Подбор...",
noWorksAdded: "Работы еще не добавлены.",
noWorksAddedHint: "Используйте выпадающий список выше для ручного добавления или нажмите \"Авто-подбор\".",
selectScenario: "Выберите сценарий для просмотра и редактирования",
settingsTitle: "Настройки",
apiKeyLabel: "API Ключ",
apiKeyHint: "Оставьте пустым, чтобы использовать системный ключ по умолчанию.",
modelLabel: "Модель",
apiUrlLabel: "URL точки входа API",
languageLabel: "Язык",
dataMgmt: "Управление данными",
dataMgmtHint: "Данные автоматически сохраняются в LocalStorage браузера. Для сохранения в файл (например, для Git) экспортируйте БД в JSON.",
btnExport: "Скачать БД (.json)",
btnImport: "Импортировать БД (.json)",
btnLoadDemo: "Загрузить демо-данные",
demoLoaded: "Демо-данные успешно загружены!",
btnExportSites: "Экспорт сайтов (.json)",
btnImportSites: "Импорт сайтов (.json)",
btnLoadDemoSites: "Загрузить демо-сайты",
demoSitesLoaded: "Демо-сайты загружены!",
btnReset: "Сбросить / Очистить данные",
systemStatus: "Статус системы",
apiConfigured: "API Настроен",
storageActive: "LocalStorage Активен",
logsTitle: "Логи запросов",
totalTokens: "Всего токенов",
noLogs: "Логов пока нет.",
automationLabel: "Включить полную автоматизацию",
automationHint: "Разрешает кнопки массовых операций. Осторожно: большой расход токенов.",
btnBulkLoad: "Загрузить всё (Авто)",
btnBulkGen: "Сгенерировать все сценарии",
btnBulkMatch: "Подобрать все работы",
bulkLoadConfirm: "Это запустит загрузку работ для ВСЕХ категорий по очереди. Это может занять время и потратить много токенов. Продолжить?",
bulkGenConfirm: "Это запустит генерацию сценариев для ВСЕХ ячеек матрицы. Продолжить?",
bulkMatchConfirm: "Это запустит подбор работ для ВСЕХ сценариев, где работы еще не назначены. Продолжить?",
steps: {
parsing: "Парсинг страницы...",
classifying: "Классификация...",
analyzing: "Генерация сценариев...",
finalizing: "Завершение...",
generating: "Генерация сценариев...",
matching: "Подбор работ..."
},
disciplines: {
codes: {
ARCH: "АР",
STR: "КР",
PL: "ВК",
HVAC: "ОВ",
ITP: "ИТП",
FPS: "АУПТ",
ELEC: "ЭОМ",
ELV: "СС",
AI: "АИ"
},
AR_WALLS_NAME: "Стены", AR_WALLS_DESC: "Архитектурные стены, перегородки",
AR_WALLS_KW: "кирпич, блок, гипсокартон, штукатурка, покраска, демонтаж, перегородка",
AR_DOORS_NAME: "Двери / Окна", AR_DOORS_DESC: "Дверные и оконные проемы",
AR_DOORS_KW: "дверь, окно, косяк, монтаж, демонтаж, проем",
KR_WALLS_NAME: "Стены", KR_WALLS_DESC: "Несущие стены (Монолит)",
KR_WALLS_KW: "бетон, монолит, арматура, бурение, алмазная резка, проем, отверстие",
KR_COLS_NAME: "Колонны / Пилоны", KR_COLS_DESC: "Несущие колонны и пилоны",
KR_COLS_KW: "бетон, монолит, колонна, пилон, бурение, алмазная резка, арматура, отверстие, восстановление",
KR_SLABS_NAME: "Перекрытия / Покрытия / Рампы", KR_SLABS_DESC: "Плиты перекрытия",
KR_SLABS_KW: "бетон, перекрытие, плита, бурение, резка, отверстие, монолит",
KR_BEAMS_NAME: "Балки", KR_BEAMS_DESC: "Несущие балки",
KR_BEAMS_KW: "бетон, балка, ригель, бурение, резка, арматура",
VK_K_NAME: "Трубы / Дренаж", VK_K_DESC: "Бытовая и ливневая канализация",
VK_K_KW: "труба, канализация, дренаж, пластик, монтаж, демонтаж",
VK_V_NAME: "Трубы", VK_V_DESC: "Водоснабжение (напорное)",
VK_V_KW: "труба, водоснабжение, сталь, полипропилен, монтаж, кран",
OV_VENT_NAME: "Воздуховод", OV_VENT_DESC: "Вентиляционные короба",
OV_VENT_KW: "воздуховод, вентиляция, жесть, монтаж, демонтаж, диффузор",
OV_HEAT_NAME: "Трубы", OV_HEAT_DESC: "Трубы отопления",
OV_HEAT_KW: "радиатор, труба, отопление, сварка, монтаж",
AUPT_PIPE_NAME: "Трубы", AUPT_PIPE_DESC: "Трубопроводы пожаротушения",
AUPT_PIPE_KW: "труба, пожаротушение, сталь, сварка, покраска",
AUPT_SPR_NAME: "Спринклеры", AUPT_SPR_DESC: "Спринклерные оросители",
AUPT_SPR_KW: "спринклер, ороситель, пожаротушение",
EOM_NAME: "Кабельканалы / Лотки", EOM_DESC: "Лотки, кабели, слаботочка",
EOM_KW: "лоток, кабель, провод, розетка, выключатель, монтаж",
AR_FACADE_NAME: "Фасады", AR_FACADE_DESC: "Фасадные системы", AR_FACADE_KW: "фасад, панель, остекление, облицовка",
AR_ROOF_NAME: "Крыши", AR_ROOF_DESC: "Кровельные работы", AR_ROOF_KW: "кровля, черепица, гидроизоляция",
OV_ITP_NAME: "Индивидуальный тепловой пункт", OV_ITP_DESC: "Оборудование ИТП", OV_ITP_KW: "итп, теплообменник, насос, задвижка",
SS_NAME: "Слаботочные системы", SS_DESC: "Пожарная сигнализация, СКУД, интернет", SS_KW: "апс, датчик, камера, скс, кабель",
AI_NAME: "Архитектурные интерьеры", AI_DESC: "Внутренняя отделка", AI_KW: "интерьер, отделка, декор, мебель"
}
}
};
const DISCIPLINES: Discipline[] = [
{ id: "AR_WALLS", code: "АР (Стены)", shortCodeKey: "ARCH", rank: 2, nameKey: "AR_WALLS_NAME", descKey: "AR_WALLS_DESC", keywordsKey: "AR_WALLS_KW" },
{ id: "AR_DOORS", code: "АР (Двери/Окна)", shortCodeKey: "ARCH", rank: 2, nameKey: "AR_DOORS_NAME", descKey: "AR_DOORS_DESC", keywordsKey: "AR_DOORS_KW" },
{ id: "AR_FACADE", code: "АР (Фасад)", shortCodeKey: "ARCH", rank: 2, nameKey: "AR_FACADE_NAME", descKey: "AR_FACADE_DESC", keywordsKey: "AR_FACADE_KW" },
{ id: "AR_ROOF", code: "АР (Кровля)", shortCodeKey: "ARCH", rank: 2, nameKey: "AR_ROOF_NAME", descKey: "AR_ROOF_DESC", keywordsKey: "AR_ROOF_KW" },
{ id: "KR_WALLS", code: "КР", shortCodeKey: "STR", rank: 1, nameKey: "KR_WALLS_NAME", descKey: "KR_WALLS_DESC", keywordsKey: "KR_WALLS_KW" },
{ id: "KR_COLS", code: "КР", shortCodeKey: "STR", rank: 1, nameKey: "KR_COLS_NAME", descKey: "KR_COLS_DESC", keywordsKey: "KR_COLS_KW" },
{ id: "KR_SLABS", code: "КР", shortCodeKey: "STR", rank: 1, nameKey: "KR_SLABS_NAME", descKey: "KR_SLABS_DESC", keywordsKey: "KR_SLABS_KW" },
{ id: "KR_BEAMS", code: "КР", shortCodeKey: "STR", rank: 1, nameKey: "KR_BEAMS_NAME", descKey: "KR_BEAMS_DESC", keywordsKey: "KR_BEAMS_KW" },
{ id: "VK_K", code: "ВК (К)", shortCodeKey: "PL", rank: 3, nameKey: "VK_K_NAME", descKey: "VK_K_DESC", keywordsKey: "VK_K_KW" },
{ id: "VK_V", code: "ВК (В)", shortCodeKey: "PL", rank: 5, nameKey: "VK_V_NAME", descKey: "VK_V_DESC", keywordsKey: "VK_V_KW" },
{ id: "OV_VENT", code: "ОВ (Вент.)", shortCodeKey: "HVAC", rank: 4, nameKey: "OV_VENT_NAME", descKey: "OV_VENT_DESC", keywordsKey: "OV_VENT_KW" },
{ id: "OV_HEAT", code: "ОВ (Отоп.)", shortCodeKey: "HVAC", rank: 5, nameKey: "OV_HEAT_NAME", descKey: "OV_HEAT_DESC", keywordsKey: "OV_HEAT_KW" },
{ id: "OV_ITP", code: "ОВ (ИТП)", shortCodeKey: "ITP", rank: 5, nameKey: "OV_ITP_NAME", descKey: "OV_ITP_DESC", keywordsKey: "OV_ITP_KW" },
{ id: "AUPT_PIPE", code: "АУПТ", shortCodeKey: "FPS", rank: 5, nameKey: "AUPT_PIPE_NAME", descKey: "AUPT_PIPE_DESC", keywordsKey: "AUPT_PIPE_KW" },
{ id: "AUPT_SPR", code: "АУПТ", shortCodeKey: "FPS", rank: 5, nameKey: "AUPT_SPR_NAME", descKey: "AUPT_SPR_DESC", keywordsKey: "AUPT_SPR_KW" },
{ id: "EOM", code: "ЭОМ", shortCodeKey: "ELEC", rank: 6, nameKey: "EOM_NAME", descKey: "EOM_DESC", keywordsKey: "EOM_KW" },
{ id: "SS", code: "СС", shortCodeKey: "ELV", rank: 6, nameKey: "SS_NAME", descKey: "SS_DESC", keywordsKey: "SS_KW" },
{ id: "AI", code: "АИ", shortCodeKey: "AI", rank: 6, nameKey: "AI_NAME", descKey: "AI_DESC", keywordsKey: "AI_KW" },
];
const DEFAULT_PARSING_SITES: ParsingSite[] = [
{ id: "1770111963115", url: "https://garantstroikompleks.ru/prajs-list", categories: "АР, КР, ВК (К), ВК (В), ОВ (Вент.), ОВ (Отоп.), АУПТ, ЭО, ЭС, ЭМ, СС", description: "Общестрой" },
{ id: "1770111983019", url: "https://stroyremdizayn.ru/almaznaya-rezka-betona", categories: "КР", description: "Алмазная резка бетона, стен и перекрытий" },
{ id: "1770111994637", url: "https://stroyremdizayn.ru/uslugi/santekhnika-vodosnabzhenie-i-kanalizaciya", categories: "ВК (В), ВК (К)", description: "Услуги сантехника, водоснабжение и канализация" },
{ id: "1770112169240", url: "https://stroyremdizayn.ru/demontazh-sten-i-peregorodok", categories: "АР, КР", description: "Демонтаж" },
{ id: "1770123899371", url: "https://stroyremdizayn.ru/uslugi/elektromontazhnye-raboty-na-kommercheskih-obektah", categories: "ЭОМ", description: "Электромонтажные работы на коммерческих объектах" },
{ id: "1770123912232", url: "https://remelit.ru/remont-kvartir-tsena/", categories: "АР (Стены), АР (Двери/Окна), АР (Фасад), АР (Кровля), КР, ВК (К), ВК (В), ОВ (Вент.), ОВ (Отоп.), ОВ (ИТП), АУПТ, ЭОМ, СС, АИ", description: "Цены на ремонт квартир в Москве и области" },
{ id: "1770123935127", url: "https://kronotech.ru/stroitelnye-raboty/montazh-inzhenernyh-sistem", categories: "ВК (К), ВК (В), ОВ (Вент.), ОВ (Отоп.), ОВ (ИТП), АУПТ, ЭОМ, СС", description: "Монтаж инженерных систем" }
];
// --- Helpers ---
const generateId = () => Math.random().toString(36).substr(2, 9);
const cleanJson = (text: string | undefined) => {
if (!text) return "{}";
let cleaned = text.replace(/```json/g, '').replace(/```/g, '').trim();
const firstBrace = cleaned.indexOf('{');
const firstBracket = cleaned.indexOf('[');
let start = 0;
if (firstBrace === -1 && firstBracket === -1) {
return "{}";
} else if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
start = firstBrace;
} else {
start = firstBracket;
}
return cleaned.substring(start);
};
const safeParseJSON = (text: string) => {
const cleaned = cleanJson(text);
try {
return JSON.parse(cleaned);
} catch (e) {
if (cleaned.trim().startsWith('[') && !cleaned.trim().endsWith(']')) {
try {
const lastCloseObj = cleaned.lastIndexOf('}');
if (lastCloseObj > 0) {
const salvaged = cleaned.substring(0, lastCloseObj + 1) + ']';
console.warn("Recovered truncated JSON array.");
return JSON.parse(salvaged);
}
} catch (e2) {}
}
return null;
}
};
const getDisciplineStyle = (d: Discipline) => {
if (d.code.startsWith("ВК")) return { bg: "#e0f2fe", text: "#0369a1" };
if (d.code.startsWith("ОВ")) return { bg: "#ffedd5", text: "#c2410c" };
switch(d.rank) {
case 1: return { bg: "var(--rank-1)", text: "var(--rank-1-text)" };
case 2: return { bg: "var(--rank-2)", text: "var(--rank-2-text)" };
case 3: return { bg: "var(--rank-3)", text: "var(--rank-3-text)" };
case 4: return { bg: "var(--rank-4)", text: "var(--rank-4-text)" };
case 5: return { bg: "var(--rank-5)", text: "var(--rank-5-text)" };
case 6: return { bg: "var(--rank-6)", text: "var(--rank-6-text)" };
default: return { bg: "#fff", text: "#000" };
}
};
const getCurrencySymbol = (lang: string) => lang === 'ru' ? '₽' : '$';
const getDisplayCurrency = (w: WorkItem | Partial<WorkItem> | undefined, lang: string) => {
const defaultSymbol = getCurrencySymbol(lang);
if (!w || !w.currency) return defaultSymbol;
const c = w.currency.toUpperCase().trim();
if (['RUB', 'RUR', 'РУБ', '₽', 'USD', 'DOLLAR', '$'].includes(c)) return defaultSymbol;
return w.currency;
};
const formatCompactNumber = (num: number) => {
if (num === 0) return "0";
if (!num) return "-";
return new Intl.NumberFormat('en-US', {
notation: "compact",
maximumFractionDigits: 1
}).format(num);
};
// --- LLM Service ---
class LLMService {
private ai: GoogleGenAI;
private modelName: string = "gemini-2.5-flash";
private apiUrl: string = "";
private apiKey: string = "";
constructor() {
// Initialize with a placeholder if key is missing to prevent startup crash
this.apiKey = process.env.API_KEY || "PENDING";
this.ai = new GoogleGenAI({ apiKey: this.apiKey });
}
updateConfig(settings: AppSettings) {
this.modelName = settings.model || "gemini-2.5-flash";
this.apiKey = settings.apiKey || process.env.API_KEY || "PENDING";
this.apiUrl = settings.apiUrl || "";
this.ai = new GoogleGenAI({ apiKey: this.apiKey });
}
private async generateOpenAICompatible(params: any, retries = 3): Promise<{ rawText: string, response: any, status: number }> {
const messages = [];
// Handle system instruction if present
if (params.config?.systemInstruction) {
messages.push({ role: "system", content: params.config.systemInstruction });
}
// Add user content
messages.push({ role: "user", content: params.contents });
const body: any = {
model: this.modelName,
messages: messages,
stream: false
};
// Handle JSON mode if requested
if (params.config?.responseMimeType === "application/json") {
body.response_format = { type: "json_object" };
}
if (params.config?.maxOutputTokens) {
body.max_tokens = params.config.maxOutputTokens;
}
let lastError;
for (let attempt = 0; attempt < retries; attempt++) {
try {
const response = await fetch(this.apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.apiKey}`
},
body: JSON.stringify(body)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API Error ${response.status}: ${errorText}`);
}
const data = await response.json();
const rawText = data.choices?.[0]?.message?.content || "";
if (!rawText) throw new Error("Empty response from LLM");
return { rawText, response: data, status: response.status };
} catch (e: any) {
lastError = e;
const status = e.status || 500;
const isRetryable = status === 429 || status >= 500 || (e.message && (e.message.includes("Empty response") || e.message.includes("Generation stopped")));
if (!isRetryable && attempt === 0) throw e;
if (attempt === retries - 1) throw e;
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));
}
}
throw lastError || new Error("Failed to generate content after retries");
}
private async safeGenerate(params: any, retries = 3): Promise<{ rawText: string, response: any, status: number }> {
if (this.apiKey === "PENDING" || !this.apiKey) {
throw new Error("API Key is not set. Please configure it in Settings.");
}
// Check if custom API (Mistral/OpenAI) is configured
// We use custom logic if apiUrl is set and NOT pointing to googleapis.com
if (this.apiUrl && !this.apiUrl.includes("googleapis.com")) {
return this.generateOpenAICompatible(params, retries);
}
let lastError;
for (let attempt = 0; attempt < retries; attempt++) {
try {
const response = await this.ai.models.generateContent(params);
let rawText = response.text || "";
if (!rawText && response.candidates && response.candidates.length > 0) {
const candidate = response.candidates[0];
if (candidate.finishReason && candidate.finishReason !== 'STOP') {
// Try to extract text even if stopped for other reasons
if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0 && candidate.content.parts[0].text) {
rawText = candidate.content.parts[0].text;
} else {
// If completely empty, treat as retry-able error if possible, but finishReason might indicate blockage
throw new Error(`Generation stopped: ${candidate.finishReason}`);
}
}
}
if (!rawText) throw new Error("Empty response from LLM");
return { rawText, response, status: 200 };
} catch (e: any) {
lastError = e;
// Retry logic
const status = e.status || e.response?.status || e.statusCode;
const isRetryable = status === 429 || status >= 500 || e.message.includes("Empty response") || e.message.includes("Generation stopped");
if (!isRetryable && attempt === 0) throw e;
if (attempt === retries - 1) throw e;
// Exponential backoff: 1s, 2s, 4s
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));
}
}
throw lastError || new Error("Failed to generate content after retries");
}
async parseWorks(url: string, targetDiscipline: {code: string, name: string, description: string, keywords: string}, lang: 'en' | 'ru'): Promise<{ works: any[], tokens: number, status: number }> {
const langPrompt = lang === 'ru' ? "Output ONLY in Russian language. Default currency to 'RUB' (₽) if ambiguous." : "Output ONLY in English language. Default currency to 'USD' ($).";
const prompt = `
Act as a construction cost estimator.
Target URL context: ${url}
Task: Extract exactly 20 construction work items from the context that are MOST RELEVANT to the following discipline:
Code: ${targetDiscipline.code}
Name: ${targetDiscipline.name}
Description: ${targetDiscipline.description}
Keywords: ${targetDiscipline.keywords}
IMPORTANT:
1. Prioritize works that match the Keywords.
2. If specific works are not found, include general construction works.
3. Do NOT include the full HTML.
4. Return ONLY valid JSON.
5. Extract the currency symbol or code if visible.
${langPrompt}
Return JSON:
{
"items": [
{ "name": "Drilling D50mm", "price": 1500, "currency": "RUB", "unit": "pcs" }
]
}
`;
const { rawText, response, status } = await this.safeGenerate({
model: this.modelName,
contents: prompt,
config: {
responseMimeType: "application/json",
maxOutputTokens: 8000,
responseSchema: {
type: Type.OBJECT,
properties: {
items: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
price: { type: Type.NUMBER },
currency: { type: Type.STRING, description: "Currency symbol or code (e.g. $, ₽, RUB, USD)" },
unit: { type: Type.STRING }
}
}
}
}
}
}
});
const result = safeParseJSON(rawText);
if (!result || !result.items) {
throw new Error(`Parsing failed. Raw Response:\n${rawText}`);
}
return {
works: result.items || [],
tokens: response.usageMetadata?.totalTokenCount || 0,
status
};
}
async classifyWorks(works: any[], categoryId: string, disciplineDesc: string, keywords: string): Promise<{ classified: any[], tokens: number, status: number }> {
const prompt = `
You are an expert construction engineer specializing in BIM and collision resolution.
Task: Evaluate relevance of construction works for resolving collisions in the Target Category.
Target Category: ${categoryId}
Category Description: ${disciplineDesc}
Key Related Terms: ${keywords}
Scoring Rules:
1. High Score (0.8 - 1.0): Work explicitly mentions materials or methods specific to this category (e.g. "Concrete drilling" for Monolith/KR).
2. Medium Score (0.5 - 0.7): General construction works plausible for this category.
3. Low Score (0.0 - 0.2): Unrelated works.
Works Input: ${JSON.stringify(works.map(w => w.name))}
Return JSON array of objects with 'name' and 'score'.
`;
const { rawText, response, status } = await this.safeGenerate({
model: this.modelName,
contents: prompt,
config: {
responseMimeType: "application/json",
maxOutputTokens: 4000,
responseSchema: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
score: { type: Type.NUMBER }
}
}
}
}
});
const result = safeParseJSON(rawText);
const validResult = Array.isArray(result) ? result : [];
return { classified: validResult, tokens: response.usageMetadata?.totalTokenCount || 0, status };
}
async generateScenarios(rowDisc: {code: string, name: string}, colDisc: {code: string, name: string}, lang: 'en' | 'ru'): Promise<{ scenarios: any[], tokens: number, rawText: string, status: number }> {
const langPrompt = lang === 'ru' ? "Output strictly in Russian language." : "Output strictly in English language.";
const prompt = `
Role: Senior Construction Engineer.
Task: Provide 3 standard construction solutions for when a "${rowDisc.code} ${rowDisc.name}" element collides with a "${colDisc.code} ${colDisc.name}" element.
Focus on modifying the ${rowDisc.name} (Row element).
If a specific solution isn't obvious, provide generic standard resolutions such as "Local Shift", "Change Cross-Section", or "Rerouting".
Requirements:
1. Name: A short title (2-5 words).
2. Description: A practical technical explanation of the work required.
${langPrompt}
`;
const { rawText, response, status } = await this.safeGenerate({
model: this.modelName,
contents: prompt,
config: {
systemInstruction: "You are a JSON-only API helper. Output strictly a valid JSON array. The 'name' property MUST be a short string (under 10 words). The 'description' property contains the detailed explanation. Do not wrap in markdown.",
responseMimeType: "application/json",
maxOutputTokens: 2000,
safetySettings: [
{ category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH },
{ category: HarmCategory.HARM_CATEGORY_HARASSMENT, threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH },
{ category: HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH },
{ category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH }
],
responseSchema: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
description: { type: Type.STRING }
}
}
}
}
});
const result = safeParseJSON(rawText);
let scenarios = [];
if (Array.isArray(result)) {
scenarios = result;
} else if (result && Array.isArray(result.scenarios)) {
scenarios = result.scenarios;
} else if (result && Array.isArray(result.items)) {
scenarios = result.items;
} else if (result && typeof result === 'object' && Object.keys(result).length > 0) {
const val = Object.values(result).find(v => Array.isArray(v));
if (val) scenarios = val as any[];
}
if (!scenarios) {
throw new Error(`LLM returned 0 scenarios. Raw Response:\n${rawText}`);
}
scenarios = scenarios.map((s: any) => {
let name = s.name || "Unknown Scenario";
let description = s.description || "";
if (name.split(' ').length > 15 && description.length < name.length) {
if (!description) {
description = name;
name = "Proposed Solution (Auto-fix)";
} else {
name = name.split(' ').slice(0, 8).join(' ') + "...";
}
}
return { name, description };
});
return { scenarios, tokens: response.usageMetadata?.totalTokenCount || 0, rawText, status };
}
async matchWorksToScenario(scenario: any, availableWorks: WorkItem[]): Promise<{ matches: any[], tokens: number, rawText: string, status: number }> {
const workList = availableWorks.map(w => ({ id: w.id, name: w.name, unit: w.unit }));
const prompt = `
Role: Construction Cost Estimator.
Task: Identify items from the "Available Works" list that are required to perform the construction scenario described below.
Scenario Name: ${scenario.name}
Description: ${scenario.description}
Available Works: ${JSON.stringify(workList)}
Instructions:
1. Select ALL works that seem relevant to the scenario description.
2. If an exact match isn't found, pick the closest functional equivalent.
3. Be generous in selection.
4. Return an empty array ONLY if absolutely no works are relevant.
Output Format: JSON Array of objects with 'workId' and 'quantity'.
`;
const { rawText, response, status } = await this.safeGenerate({
model: this.modelName,
contents: prompt,
config: {
systemInstruction: "You are a helpful estimator. Find matching works generously. Even weak matches are better than no matches. Output JSON.",
responseMimeType: "application/json",
maxOutputTokens: 2000,
safetySettings: [
{ category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH }
],
responseSchema: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
workId: { type: Type.STRING },
quantity: { type: Type.NUMBER }
}
}
}
}
});
const result = safeParseJSON(rawText);
const matches = Array.isArray(result) ? result : [];
return { matches, tokens: response.usageMetadata?.totalTokenCount || 0, rawText, status };
}
}
const llmService = new LLMService();
// --- Hooks ---
const useProgressSimulator = () => {
const intervalsRef = useRef<Record<string, any>>({});
const startProgress = useCallback((id: string, setState: React.Dispatch<React.SetStateAction<Record<string, LoadingState>>>, initialStep: string) => {
setState(prev => ({ ...prev, [id]: { step: initialStep, progress: 5 } }));
if (intervalsRef.current[id]) clearInterval(intervalsRef.current[id]);
intervalsRef.current[id] = setInterval(() => {
setState(prev => {
const current = prev[id];
if (!current) return prev;
const nextProgress = current.progress >= 90 ? 90 : current.progress + (Math.random() * 3);
return {
...prev,
[id]: { ...current, progress: nextProgress }
};
});
}, 400);
}, []);
const updateStep = useCallback((id: string, setState: React.Dispatch<React.SetStateAction<Record<string, LoadingState>>>, step: string, forceProgress?: number) => {
setState(prev => {
const current = prev[id];
if (!current) return prev;
return {
...prev,
[id]: { step, progress: forceProgress !== undefined ? forceProgress : current.progress }
};
});
}, []);
const stopProgress = useCallback((id: string, setState: React.Dispatch<React.SetStateAction<Record<string, LoadingState>>>) => {
if (intervalsRef.current[id]) {
clearInterval(intervalsRef.current[id]);
delete intervalsRef.current[id];
}
setState(prev => {
const newState = { ...prev };
delete newState[id];
return newState;
});
}, []);
useEffect(() => {
return () => {
Object.values(intervalsRef.current).forEach(clearInterval);
};
}, []);
return { startProgress, updateStep, stopProgress };
};
// --- Components ---
const Button = ({ children, onClick, variant = "primary", disabled = false, className = "", title = "" }: any) => {
const baseStyle = "px-4 py-2 rounded font-medium transition-colors text-sm flex items-center gap-2";
const variants: any = {
primary: "bg-blue-600 text-white hover:bg-blue-700 disabled:bg-blue-300",
secondary: "bg-white border border-gray-300 text-gray-700 hover:bg-gray-50 disabled:bg-gray-100",
danger: "bg-red-500 text-white hover:bg-red-600",
success: "bg-green-600 text-white hover:bg-green-700",
ghost: "bg-transparent text-gray-600 hover:bg-gray-100"
};
return (
<button
onClick={onClick}
disabled={disabled}
className={`${baseStyle} ${variants[variant]} ${className}`}
title={title}
>
{children}
</button>
);
};
const Input = (props: any) => (
<input
{...props}
className={`w-full bg-white text-gray-900 border border-gray-300 rounded px-3 py-2 text-sm placeholder-gray-400 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500 transition-shadow ${props.className || ""}`}
/>
);
const ToggleButton = ({ open, onClick }: { open: boolean, onClick: () => void }) => (
<button
onClick={(e) => { e.stopPropagation(); onClick(); }}
className="p-1.5 rounded-full hover:bg-black/10 text-current transition-colors focus:outline-none flex items-center justify-center"
title={open ? "Collapse Panel" : "Expand Panel"}
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={`transform transition-transform duration-200 ${open ? 'rotate-180' : 'rotate-0'}`}>
<polyline points="18 15 12 9 6 15"></polyline>
</svg>
</button>
);
// --- Main App ---
export default function App() {
// --- State ---
const [activeTab, setActiveTab] = useState<"collision" | "cost" | "import" | "settings" | "logs">("collision");
const [selectedImportFileIds, setSelectedImportFileIds] = useState<Set<string>>(new Set());
const [importedFiles, setImportedFiles] = useState<ImportedFile[]>(() => {
try {
const saved = localStorage.getItem("cmwc_imported_files");
return saved ? JSON.parse(saved) : [];
} catch { return []; }
});
const [catDropdownOpen, setCatDropdownOpen] = useState(false);
// "Database" google
// const [settings, setSettings] = useState<AppSettings>({
// model: "gemini-2.5-flash",
// language: "en",
// apiUrl: "https://generativelanguage.googleapis.com",
// apiKey: "",
// enableAutomation: true
// });
// Settings with persistence
const [settings, setSettings] = useState<AppSettings>(() => {
try {
const saved = localStorage.getItem("cmwc_settings");
if (saved) {
const parsed = JSON.parse(saved);