Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2719 lines (2376 loc) · 106 KB
/
Copy pathapp.js
File metadata and controls
2719 lines (2376 loc) · 106 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
// State Management
const state = {
currentScenario: 'realistic',
currentTab: 'property',
partnerView: 'combined',
constructionMode: 'simple',
partnerSplit: { a: 50, b: 50 },
revenueSplit: { a: 50, b: 50, followsCostSplit: true },
scenarios: {
realistic: {
name: 'Realistic Case',
data: {
grundstueck: 1900000,
makler: 3.57,
abriss: 150000,
wohnflaeche: 800,
baukosten_qm: 3500,
baunebenkosten: 15,
unvorhergesehen: 10,
eigenkapital: 1000000,
beteiligung: 50,
zinssatz: 3.7,
'zinssatz-a': 3.7,
'zinssatz-b': 3.8,
bauzeit: 36,
'bauzeit-a': 36,
'bauzeit-b': 36,
verkaufspreis_qm: 8750,
vertriebskosten: 3,
'eigenkapital-a': 1000000,
'eigenkapital-b': 500000,
},
constructionItems: [
{ id: 'tiefbau', name: 'Tiefbau', cost: 300000 },
{ id: 'rohbau', name: 'Rohbau', cost: 1200000 },
{ id: 'innenausbau', name: 'Innenausbau', cost: 800000 },
{ id: 'haustechnik', name: 'Haustechnik', cost: 400000 },
{ id: 'garten', name: 'Außenanlagen/Garten', cost: 100000 }
]
},
best: {
name: 'Best Case',
data: {
makler: 3.57
},
constructionItems: []
},
worst: {
name: 'Worst Case',
data: {
makler: 3.57
},
constructionItems: []
}
}
};
// Generate Best and Worst Case scenarios with specific values
function generateScenarios() {
// Best Case with specific values from JSON
state.scenarios.best.data = {
grundstueck: 1900000,
makler: 3.57,
abriss: 135000,
wohnflaeche: 800,
baukosten_qm: 2975,
baunebenkosten: 15,
unvorhergesehen: 5,
eigenkapital: 1000000,
beteiligung: 50,
zinssatz: 3.7,
'zinssatz-a': 3.7,
'zinssatz-b': 3.7,
bauzeit: 18,
'bauzeit-a': 30,
'bauzeit-b': 30,
verkaufspreis_qm: 9000,
vertriebskosten: 3,
'eigenkapital-a': 500000,
'eigenkapital-b': 500000,
};
// Best case construction items
state.scenarios.best.constructionItems = [
{ id: 'tiefbau', name: 'Tiefbau', cost: 255000 },
{ id: 'rohbau', name: 'Rohbau', cost: 1020000 },
{ id: 'innenausbau', name: 'Innenausbau', cost: 680000 },
{ id: 'haustechnik', name: 'Haustechnik', cost: 340000 },
{ id: 'garten', name: 'Außenanlagen/Garten', cost: 85000 }
];
// Worst Case with specific values from JSON
state.scenarios.worst.data = {
grundstueck: 2000000,
makler: 3.57,
abriss: 165000,
wohnflaeche: 800,
baukosten_qm: 4025,
baunebenkosten: 15,
unvorhergesehen: 20,
eigenkapital: 1000000,
beteiligung: 50,
zinssatz: 3.7,
'zinssatz-a': 3.7,
'zinssatz-b': 3.7,
bauzeit: 18,
'bauzeit-a': 40,
'bauzeit-b': 40,
verkaufspreis_qm: 8000,
vertriebskosten: 3,
'eigenkapital-a': 500000,
'eigenkapital-b': 500000,
};
// Worst case construction items
state.scenarios.worst.constructionItems = [
{ id: 'tiefbau', name: 'Tiefbau', cost: 345000 },
{ id: 'rohbau', name: 'Rohbau', cost: 1380000 },
{ id: 'innenausbau', name: 'Innenausbau', cost: 920000 },
{ id: 'haustechnik', name: 'Haustechnik', cost: 460000 },
{ id: 'garten', name: 'Außenanlagen/Garten', cost: 115000 }
];
}
// Initialize app
function init() {
generateScenarios();
setupEventListeners();
loadScenario(state.currentScenario);
setupCharts();
setupLocationAutocomplete();
calculate();
}
// Setup Event Listeners
function setupEventListeners() {
// Tab navigation
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const tab = e.currentTarget.getAttribute('data-tab');
switchTab(tab);
});
});
// Scenario tabs
document.querySelectorAll('.scenario-tab').forEach(btn => {
btn.addEventListener('click', (e) => {
const scenario = e.currentTarget.getAttribute('data-scenario');
if (scenario) {
switchScenario(scenario);
}
});
});
// Partner view toggle
document.querySelectorAll('.toggle-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const view = e.currentTarget.getAttribute('data-view');
togglePartnerView(view);
});
});
// Step buttons
document.querySelectorAll('.step-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const input = e.currentTarget.getAttribute('data-input');
const step = parseFloat(e.currentTarget.getAttribute('data-step')); // Changed from parseInt to parseFloat for decimal steps
stepInput(input, step);
});
});
// Input changes with formatting
document.querySelectorAll('input[type="number"]').forEach(input => {
// Store the actual numeric value as a data attribute
const initialValue = input.value || '0';
input.dataset.rawValue = initialValue.toString();
// Identify currency inputs (those with step >= 1 or specific IDs)
const isCurrencyInput = (parseFloat(input.step) >= 1) ||
['grundstueck', 'eigenkapital', 'eigenkapital-a', 'eigenkapital-b',
'abriss'].includes(input.id);
// Format on blur - FIXED: Never format number inputs to prevent browser rejection
input.addEventListener('blur', (e) => {
// Get the current value, prioritizing rawValue for large numbers
let rawValue;
// First, try to get the value from rawValue data attribute
if (e.target.dataset.rawValue && !isNaN(parseFloat(e.target.dataset.rawValue))) {
rawValue = parseFloat(e.target.dataset.rawValue);
} else {
// Fall back to parsing the current input value
const currentInputValue = e.target.value.replace(/\s/g, ''); // Remove any spaces
rawValue = parseFormattedNumber(currentInputValue);
}
// CRITICAL FIX: HTML5 number inputs reject formatted values with dots/commas
// Never format values in number inputs - they only accept raw numeric values
if (!isNaN(rawValue) && rawValue >= 0) {
// Always update the dataset.rawValue to preserve the actual numeric value
e.target.dataset.rawValue = rawValue.toString();
// For number inputs, always show raw numeric value without formatting
e.target.value = rawValue.toString();
}
});
// Parse on focus
input.addEventListener('focus', (e) => {
// Prioritize the stored rawValue, fall back to parsing the displayed value
let rawValue;
if (e.target.dataset.rawValue && !isNaN(parseFloat(e.target.dataset.rawValue))) {
rawValue = parseFloat(e.target.dataset.rawValue);
} else {
rawValue = parseFormattedNumber(e.target.value);
}
if (!isNaN(rawValue) && rawValue >= 0) {
e.target.value = rawValue.toString(); // Show unformatted value for editing
}
});
// Handle input to store raw value
input.addEventListener('input', (e) => {
// Store the raw numeric value, removing any formatting
const cleanValue = e.target.value.replace(/\s/g, ''); // Remove spaces
const numericValue = parseFloat(cleanValue);
if (!isNaN(numericValue)) {
e.target.dataset.rawValue = numericValue.toString();
} else {
// For non-numeric values, store as-is but don't break the system
e.target.dataset.rawValue = e.target.value || '0';
}
});
// Handle change
input.addEventListener('change', (e) => {
// Store the raw numeric value on change, ensuring large numbers are preserved
const cleanValue = e.target.value.replace(/\s/g, ''); // Remove spaces
const numericValue = parseFloat(cleanValue);
if (!isNaN(numericValue)) {
e.target.dataset.rawValue = numericValue.toString();
} else {
// For non-numeric values, store as-is but don't break the system
e.target.dataset.rawValue = e.target.value || '0';
}
handleInputChange();
});
});
// Range slider
const slider = document.getElementById('beteiligung-slider');
const numberInput = document.getElementById('beteiligung');
if (slider) {
slider.addEventListener('input', (e) => {
numberInput.value = e.target.value;
handleInputChange();
});
}
if (numberInput) {
numberInput.addEventListener('input', (e) => {
slider.value = e.target.value;
handleInputChange();
});
}
// Partner split controls
const partnerSlider = document.getElementById('partner-split-slider');
const partnerAInput = document.getElementById('partner-a-percent');
const partnerBInput = document.getElementById('partner-b-percent');
if (partnerSlider) {
partnerSlider.addEventListener('input', (e) => {
const valueA = parseInt(e.target.value);
const valueB = 100 - valueA;
state.partnerSplit.a = valueA;
state.partnerSplit.b = valueB;
// Only update input fields if they exist
if (partnerAInput) partnerAInput.value = valueA;
if (partnerBInput) partnerBInput.value = valueB;
updatePartnerSplitDisplay();
calculate();
});
}
// FIXED: Added null-safety for partner percentage inputs (they may not exist in current HTML)
if (partnerAInput) {
partnerAInput.addEventListener('input', (e) => {
const valueA = Math.min(100, Math.max(0, parseInt(e.target.value) || 0));
const valueB = 100 - valueA;
state.partnerSplit.a = valueA;
state.partnerSplit.b = valueB;
if (partnerBInput) partnerBInput.value = valueB;
if (partnerSlider) partnerSlider.value = valueA;
updatePartnerSplitDisplay();
calculate();
});
}
if (partnerBInput) {
partnerBInput.addEventListener('input', (e) => {
const valueB = Math.min(100, Math.max(0, parseInt(e.target.value) || 0));
const valueA = 100 - valueB;
state.partnerSplit.a = valueA;
state.partnerSplit.b = valueB;
if (partnerAInput) partnerAInput.value = valueA;
if (partnerSlider) partnerSlider.value = valueA;
updatePartnerSplitDisplay();
calculate();
});
} else {
// NOTE: Partner percentage input fields don't exist in current HTML but slider functionality works
console.log('Partner percentage input fields not found - slider-only mode');
}
// Partner-specific Zeit bis Verkauf inputs
const bauzeitAInput = document.getElementById('bauzeit-a');
const bauzeitBInput = document.getElementById('bauzeit-b');
if (bauzeitAInput) {
bauzeitAInput.addEventListener('change', handleInputChange);
}
if (bauzeitBInput) {
bauzeitBInput.addEventListener('change', handleInputChange);
}
// Construction mode toggle
document.querySelectorAll('input[name="construction-mode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
state.constructionMode = e.target.value;
const simpleConstruction = document.getElementById('simple-construction');
const detailedConstruction = document.getElementById('detailed-construction');
if (state.constructionMode === 'simple') {
simpleConstruction.style.display = 'block';
detailedConstruction.style.display = 'none';
// Show all input groups in simple mode
document.querySelectorAll('#simple-construction .input-group').forEach(group => {
group.style.display = 'block';
});
} else {
simpleConstruction.style.display = 'block';
detailedConstruction.style.display = 'block';
// In detailed mode, hide only the "Baukosten pro m²" field
document.querySelectorAll('#simple-construction .input-group').forEach(group => {
const input = group.querySelector('input');
if (input) {
group.style.display = input.id === 'baukosten_qm' ? 'none' : 'block';
}
});
}
loadConstructionItems();
calculate();
});
});
// Property type select
const propertyTypeSelect = document.getElementById('property-type-select');
if (propertyTypeSelect) {
propertyTypeSelect.addEventListener('change', updateMarketAnalysis);
}
// Scenario management
document.getElementById('addScenarioBtn').addEventListener('click', addScenario);
document.getElementById('copyScenarioBtn').addEventListener('click', copyScenario);
document.getElementById('renameScenarioBtn').addEventListener('click', renameScenario);
document.getElementById('deleteScenarioBtn').addEventListener('click', deleteScenario);
// Save/Load
document.getElementById('saveProjectBtn').addEventListener('click', saveProject);
document.getElementById('loadProjectBtn').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', loadProject);
// Export
document.getElementById('exportBtn').addEventListener('click', exportData);
// Revenue split controls
const revenueFollowsCost = document.getElementById('revenue-follows-cost');
const revenueSliderContainer = document.getElementById('revenue-split-slider-container');
const revenueSlider = document.getElementById('revenue-split-slider');
const revenueSplitADisplay = document.getElementById('revenue-split-a');
const revenueSplitBDisplay = document.getElementById('revenue-split-b');
if (revenueFollowsCost) {
revenueFollowsCost.addEventListener('change', (e) => {
state.revenueSplit.followsCostSplit = e.target.checked;
revenueSliderContainer.style.display = e.target.checked ? 'none' : 'flex';
if (e.target.checked) {
// Sync revenue split with cost split
state.revenueSplit.a = state.partnerSplit.a;
state.revenueSplit.b = state.partnerSplit.b;
revenuePartnerAInput.value = state.partnerSplit.a;
revenuePartnerBInput.value = state.partnerSplit.b;
revenueSlider.value = state.partnerSplit.a;
}
calculate();
});
}
if (revenueSlider) {
revenueSlider.addEventListener('input', (e) => {
const valueA = parseInt(e.target.value);
const valueB = 100 - valueA;
state.revenueSplit.a = valueA;
state.revenueSplit.b = valueB;
if (revenueSplitADisplay) revenueSplitADisplay.textContent = valueA;
if (revenueSplitBDisplay) revenueSplitBDisplay.textContent = valueB;
calculate();
});
}
}
// Tab Switching
function switchTab(tab) {
state.currentTab = tab;
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-tab') === tab);
});
// Update tab panels
document.querySelectorAll('.tab-panel').forEach(panel => {
panel.classList.toggle('active', panel.id === `${tab}-tab`);
});
// Update charts if analysis tab
if (tab === 'analysis') {
updateMarketAnalysis();
// Reinitialize map when switching to analysis tab
setTimeout(() => {
initializeMap();
}, 150);
}
}
// Scenario Switching
function switchScenario(scenario) {
state.currentScenario = scenario;
// Update scenario tabs
document.querySelectorAll('.scenario-tab').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-scenario') === scenario);
});
loadScenario(scenario);
loadConstructionItems();
calculate();
}
// Load Scenario Data
function loadScenario(scenario) {
const data = state.scenarios[scenario].data;
Object.keys(data).forEach(key => {
const input = document.getElementById(key);
if (input) {
const value = data[key];
input.value = value;
// Store the raw value for proper handling of large numbers
input.dataset.rawValue = value.toString();
}
});
// Update project name if it's a custom scenario
if (!['realistic', 'best', 'worst'].includes(scenario)) {
document.querySelector('.project-name').value = state.scenarios[scenario].name;
}
}
// Load Construction Items
function loadConstructionItems() {
if (state.constructionMode !== 'detailed') return;
const container = document.getElementById('construction-items-list');
const items = state.scenarios[state.currentScenario].constructionItems || [];
container.innerHTML = '';
items.forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.className = 'construction-item';
itemDiv.setAttribute('data-id', item.id);
itemDiv.innerHTML = `
<input type="text" class="item-name" value="${item.name}" placeholder="Bezeichnung">
<div class="currency-input">
<input type="number" id="cost-${item.id}" value="${item.cost}" step="5000" min="0">
<span class="currency">€</span>
</div>
<button class="remove-btn" onclick="removeConstructionItem('${item.id}')">Entfernen</button>
`;
container.appendChild(itemDiv);
// Add event listeners
itemDiv.querySelector('input[type="number"]').addEventListener('change', handleConstructionItemChange);
itemDiv.querySelector('.item-name').addEventListener('change', (e) => {
const itemObj = state.scenarios[state.currentScenario].constructionItems.find(i => i.id === item.id);
if (itemObj) itemObj.name = e.target.value;
});
});
}
// Handle construction item change
function handleConstructionItemChange(e) {
const itemId = e.target.id.replace('cost-', '');
const value = parseFloat(e.target.value) || 0;
const item = state.scenarios[state.currentScenario].constructionItems.find(i => i.id === itemId);
if (item) {
item.cost = value;
calculate();
}
}
// Save Current Values
function saveCurrentValues() {
const inputs = document.querySelectorAll('input[type="number"]');
const data = {};
inputs.forEach(input => {
if (input.id && !input.id.startsWith('cost-')) {
// Use raw value if available, otherwise parse formatted value
const rawValue = input.dataset.rawValue;
const value = rawValue ? parseFloat(rawValue) : parseFormattedNumber(input.value);
data[input.id] = isNaN(value) ? 0 : value;
}
});
// Ensure critical fields have default values if missing
if (!data.eigenkapital && document.getElementById('eigenkapital')) {
data.eigenkapital = parseFormattedNumber(document.getElementById('eigenkapital').value) || 0;
}
if (!data.bauzeit && document.getElementById('bauzeit')) {
data.bauzeit = parseFloat(document.getElementById('bauzeit').value) || 18;
}
state.scenarios[state.currentScenario].data = data;
}
// Handle Input Changes
function handleInputChange() {
saveCurrentValues();
calculate();
}
// Helper function to format inputs properly, including zero values
function formatInputValue(value) {
if (value === 0 || value === '0') {
return '0';
}
return value;
}
// Step Input Values
function stepInput(inputId, step) {
const input = document.getElementById(inputId);
if (input) {
// Use raw value if available, otherwise parse formatted value
const rawValue = input.dataset.rawValue;
const currentValue = rawValue ? parseFloat(rawValue) : parseFormattedNumber(input.value) || 0;
let newValue = currentValue + step;
// Apply min/max constraints
const minValue = parseFloat(input.getAttribute('min')) || 0;
const maxValue = parseFloat(input.getAttribute('max'));
newValue = Math.max(minValue, newValue);
if (maxValue !== null && !isNaN(maxValue)) {
newValue = Math.min(maxValue, newValue);
}
// For percentage inputs, round to one decimal place
if (input.type === 'number' && input.step && parseFloat(input.step) === 0.1) {
newValue = Math.round(newValue * 10) / 10;
}
input.value = newValue;
input.dataset.rawValue = newValue;
handleInputChange();
}
}
// Toggle Partner View
function togglePartnerView(view) {
state.partnerView = view;
// Update toggle buttons
document.querySelectorAll('.toggle-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-view') === view);
});
// Update financing view
const combinedView = document.querySelector('.combined-view');
const splitView = document.querySelector('.split-view');
const partnerPropertyCosts = document.getElementById('partner-property-costs');
const partnerMetrics = document.getElementById('partner-metrics');
const partnerAllocationBars = document.querySelector('.partner-allocation-bars');
// Toggle combined/split only elements
document.querySelectorAll('.combined-only').forEach(el => {
el.style.display = view === 'combined' ? 'block' : 'none';
});
// Special handling for allocation bar - needs flex display
const allocationBar = document.querySelector('.allocation-bar.combined-only');
if (allocationBar && view === 'combined') {
allocationBar.style.display = 'flex';
}
document.querySelectorAll('.split-only').forEach(el => {
el.style.display = view === 'split' ? 'block' : 'none';
});
if (view === 'combined') {
combinedView.style.display = 'block';
splitView.style.display = 'none';
document.getElementById('partnerSummary').style.display = 'none';
document.getElementById('revenue-split').style.display = 'none';
if (partnerPropertyCosts) partnerPropertyCosts.style.display = 'none';
if (partnerMetrics) partnerMetrics.style.display = 'none';
} else {
combinedView.style.display = 'none';
splitView.style.display = 'grid';
document.getElementById('partnerSummary').style.display = 'block';
document.getElementById('revenue-split').style.display = 'block';
if (partnerPropertyCosts) partnerPropertyCosts.style.display = 'grid';
if (partnerMetrics) partnerMetrics.style.display = 'block';
}
calculate();
}
// Update partner split display
function updatePartnerSplitDisplay() {
const partnerASplit = document.getElementById('partner-a-split');
const partnerBSplit = document.getElementById('partner-b-split');
if (partnerASplit) partnerASplit.textContent = state.partnerSplit.a;
if (partnerBSplit) partnerBSplit.textContent = state.partnerSplit.b;
document.querySelectorAll('.partner-a-percent').forEach(el => {
el.textContent = state.partnerSplit.a;
});
document.querySelectorAll('.partner-b-percent').forEach(el => {
el.textContent = state.partnerSplit.b;
});
const partnerAPercentage = document.querySelector('.partner-a-percentage');
const partnerBPercentage = document.querySelector('.partner-b-percentage');
if (partnerAPercentage) partnerAPercentage.textContent = `${state.partnerSplit.a}%`;
if (partnerBPercentage) partnerBPercentage.textContent = `${state.partnerSplit.b}%`;
// Update summary headers
const partnerASummaryHeader = document.getElementById('partner-a-summary-header');
const partnerBSummaryHeader = document.getElementById('partner-b-summary-header');
if (partnerASummaryHeader) partnerASummaryHeader.textContent = `Klaus (${state.partnerSplit.a}%)`;
if (partnerBSummaryHeader) partnerBSummaryHeader.textContent = `Kevin (${state.partnerSplit.b}%)`;
// Update revenue split if it follows cost split
if (state.revenueSplit.followsCostSplit) {
state.revenueSplit.a = state.partnerSplit.a;
state.revenueSplit.b = state.partnerSplit.b;
const revenueSplitADisplay = document.getElementById('revenue-split-a');
const revenueSplitBDisplay = document.getElementById('revenue-split-b');
const revenueSlider = document.getElementById('revenue-split-slider');
if (revenueSplitADisplay) revenueSplitADisplay.textContent = state.partnerSplit.a;
if (revenueSplitBDisplay) revenueSplitBDisplay.textContent = state.partnerSplit.b;
if (revenueSlider) revenueSlider.value = state.partnerSplit.a;
}
}
// Format Currency
function formatCurrency(value) {
if (isNaN(value) || value === null || value === undefined) {
value = 0;
}
return new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(value);
}
// Format Percentage
function formatPercent(value) {
return new Intl.NumberFormat('de-DE', {
style: 'percent',
minimumFractionDigits: 1,
maximumFractionDigits: 1
}).format(value / 100);
}
// Format number for display (with thousand separators)
function formatNumber(value) {
if (value === 0 || value === '0' || value === null || value === undefined) {
return '0';
}
// FIXED: Handle large numbers properly and prevent formatting errors
const numValue = parseFloat(value);
if (isNaN(numValue)) {
return '0';
}
// FIXED: Use proper options for large number formatting
return new Intl.NumberFormat('de-DE', {
maximumFractionDigits: 0,
minimumFractionDigits: 0
}).format(numValue);
}
// Parse formatted number back to float
function parseFormattedNumber(value) {
if (typeof value === 'string') {
// Handle German number format (dots as thousand separators, comma as decimal)
let cleanValue = value.trim().replace(/\s/g, ''); // Remove spaces
// Check if this looks like a German formatted number (contains dots but no comma, or dots before comma)
const dotCount = (cleanValue.match(/\./g) || []).length;
const commaCount = (cleanValue.match(/,/g) || []).length;
if (dotCount > 0 && commaCount === 0) {
// Likely German thousand separators only (e.g., "2.200.000")
cleanValue = cleanValue.replace(/\./g, '');
} else if (dotCount > 0 && commaCount === 1) {
// German format with decimals (e.g., "2.200.000,50")
const lastCommaIndex = cleanValue.lastIndexOf(',');
const beforeComma = cleanValue.substring(0, lastCommaIndex);
const afterComma = cleanValue.substring(lastCommaIndex + 1);
cleanValue = beforeComma.replace(/\./g, '') + '.' + afterComma;
} else if (dotCount === 0 && commaCount === 1) {
// Just decimal comma (e.g., "1000,50")
cleanValue = cleanValue.replace(',', '.');
} else if (dotCount > 0 && commaCount === 0) {
// Could be English decimal format or German thousands - assume German thousands if multiple dots
if (dotCount > 1) {
cleanValue = cleanValue.replace(/\./g, '');
}
// If single dot, keep as decimal point (English format)
}
const parsed = parseFloat(cleanValue);
return isNaN(parsed) ? 0 : parsed;
}
const parsed = parseFloat(value);
return isNaN(parsed) ? 0 : parsed;
}
// Calculate All Values
function calculate() {
const data = state.scenarios[state.currentScenario].data;
// Property costs
// FIXED: Add proper rounding to prevent floating point precision issues
const maklergebuehr = Math.round(data.grundstueck * (data.makler / 100));
const grunderwerbsteuer = Math.round(data.grundstueck * 0.035);
const notarkosten = Math.round(data.grundstueck * 0.015);
const propertyTotal = data.grundstueck + maklergebuehr + grunderwerbsteuer + notarkosten + data.abriss;
// Update property UI
document.getElementById('maklergebuehr').textContent = formatCurrency(maklergebuehr);
document.getElementById('grunderwerbsteuer').textContent = formatCurrency(grunderwerbsteuer);
document.getElementById('notarkosten').textContent = formatCurrency(notarkosten);
document.getElementById('property-total').textContent = formatCurrency(propertyTotal);
// Construction costs
let reineBaukosten;
if (state.constructionMode === 'simple') {
reineBaukosten = data.wohnflaeche * data.baukosten_qm;
} else {
// Sum up detailed construction items
reineBaukosten = state.scenarios[state.currentScenario].constructionItems.reduce((sum, item) => {
return sum + item.cost;
}, 0);
}
// FIXED: Add proper rounding to prevent floating point precision issues
const baunebenkosten = Math.round(reineBaukosten * (data.baunebenkosten / 100));
const zwischensumme = reineBaukosten + baunebenkosten;
const unvorhergesehen = Math.round(reineBaukosten * (data.unvorhergesehen / 100));
const constructionTotal = reineBaukosten + baunebenkosten + unvorhergesehen;
// Update construction UI
document.getElementById('reine-baukosten').textContent = formatCurrency(reineBaukosten);
document.getElementById('calc-baunebenkosten').textContent = formatCurrency(baunebenkosten);
document.getElementById('calc-unvorhergesehen').textContent = formatCurrency(unvorhergesehen);
document.getElementById('construction-total').textContent = formatCurrency(constructionTotal);
// Update calculated cost per m² in detailed mode
if (state.constructionMode === 'detailed') {
const costPerSqm = data.wohnflaeche > 0 ? reineBaukosten / data.wohnflaeche : 0;
const detailedCostDisplay = document.getElementById('detailed-cost-per-sqm');
if (!detailedCostDisplay) {
// Create the display element if it doesn't exist
const detailedConstruction = document.getElementById('detailed-construction');
const displayDiv = document.createElement('div');
displayDiv.className = 'calculated-cost-display';
displayDiv.innerHTML = `
<h4>Berechnete Baukosten pro m²</h4>
<div class="calculated-value" id="detailed-cost-per-sqm">${formatCurrency(costPerSqm)} /m²</div>
`;
detailedConstruction.appendChild(displayDiv);
} else {
detailedCostDisplay.textContent = formatCurrency(costPerSqm) + ' /m²';
}
}
// Total investment
const totalInvestment = propertyTotal + constructionTotal;
// Update combined property + construction summary
document.getElementById('total-property-construction').textContent = formatCurrency(totalInvestment);
// Update financing tab displays - use total investment (property + construction)
const totalProjectCost = propertyTotal + constructionTotal;
const financingPropertyCost = document.getElementById('financing-property-cost');
if (financingPropertyCost) financingPropertyCost.textContent = formatCurrency(totalProjectCost);
if (state.partnerView === 'split') {
const partnerAPropertyCost = document.getElementById('partner-a-property-cost');
const partnerBPropertyCost = document.getElementById('partner-b-property-cost');
if (partnerAPropertyCost) partnerAPropertyCost.textContent = formatCurrency(totalProjectCost * (state.partnerSplit.a / 100));
if (partnerBPropertyCost) partnerBPropertyCost.textContent = formatCurrency(totalProjectCost * (state.partnerSplit.b / 100));
}
// Financing
// UNIFIED: Use consistent calculation for both modes - creditNeeded is totalInvestment minus eigenkapital only
const yourShare = state.partnerView === 'combined' ? totalInvestment : totalInvestment * (data.beteiligung / 100);
const creditNeeded = Math.max(0, yourShare - data.eigenkapital);
// Calculate financing costs based on partner view
let financingCosts;
let creditA = 0, creditB = 0; // Define these in outer scope
let financingCostsA = 0, financingCostsB = 0; // FIXED: Move variable declarations to outer scope
let bauzeitA = data.bauzeit || 18; // FIXED: Move to outer scope with default
let bauzeitB = data.bauzeit || 18; // FIXED: Move to outer scope with default
if (state.partnerView === 'split') {
// Calculate separate financing costs for each partner
const shareA = totalInvestment * (state.partnerSplit.a / 100);
const shareB = totalInvestment * (state.partnerSplit.b / 100);
creditA = Math.max(0, shareA - (data['eigenkapital-a'] || 0));
creditB = Math.max(0, shareB - (data['eigenkapital-b'] || 0));
// Update bauzeit values for split mode, supporting both formats
bauzeitA = data['bauzeit-a'] || data.bauzeit || 18;
bauzeitB = data['bauzeit-b'] || data.bauzeit || 18;
// FIXED: Add proper rounding to prevent floating point precision issues
financingCostsA = Math.round(creditA * ((data['zinssatz-a'] || data.zinssatz) / 100) * (bauzeitA / 12));
financingCostsB = Math.round(creditB * ((data['zinssatz-b'] || data.zinssatz) / 100) * (bauzeitB / 12));
financingCosts = financingCostsA + financingCostsB;
} else {
// FIXED: Add proper rounding to prevent floating point precision issues
financingCosts = Math.round(creditNeeded * (data.zinssatz / 100) * (data.bauzeit / 12));
}
// Update financing summary section
document.getElementById('summary-eigenkapital').textContent = formatCurrency(data.eigenkapital);
document.getElementById('financing-need').textContent = formatCurrency(creditNeeded);
document.getElementById('interest-rate-display').textContent = data.zinssatz;
document.getElementById('bauzeit-display').textContent = data.bauzeit;
document.getElementById('interest-costs').textContent = formatCurrency(financingCosts);
const totalWithFinancing = totalInvestment + financingCosts;
// Update financing allocation bars
updateAllocationBars(data, totalInvestment, creditNeeded);
// Partner split calculations - update credit display
if (state.partnerView === 'split') {
const kreditA = document.getElementById('kredit-a');
const kreditB = document.getElementById('kredit-b');
if (kreditA) kreditA.textContent = formatCurrency(creditA);
if (kreditB) kreditB.textContent = formatCurrency(creditB);
// Update Zinskosten displays for partners
const zinskostenA = document.getElementById('zinskosten-a');
const zinskostenB = document.getElementById('zinskosten-b');
if (zinskostenA) zinskostenA.textContent = formatCurrency(financingCostsA);
if (zinskostenB) zinskostenB.textContent = formatCurrency(financingCostsB);
// Update rate and time displays
const zinssatzADisplay = document.getElementById('zinssatz-a-display');
const zinssatzBDisplay = document.getElementById('zinssatz-b-display');
const bauzeitADisplay = document.getElementById('bauzeit-a-display');
const bauzeitBDisplay = document.getElementById('bauzeit-b-display');
if (zinssatzADisplay) zinssatzADisplay.textContent = data['zinssatz-a'] || data.zinssatz;
if (zinssatzBDisplay) zinssatzBDisplay.textContent = data['zinssatz-b'] || data.zinssatz;
if (bauzeitADisplay) bauzeitADisplay.textContent = bauzeitA;
if (bauzeitBDisplay) bauzeitBDisplay.textContent = bauzeitB;
}
// Sale calculations
// FIXED: Add proper rounding to prevent floating point precision issues
const bruttoVerkauf = Math.round(data.wohnflaeche * data.verkaufspreis_qm);
const vertriebskosten = Math.round(bruttoVerkauf * (data.vertriebskosten / 100));
const sonstigeKostenProzent = data.sonstige_kosten_prozent || 5;
const sonstigeKosten = Math.round(bruttoVerkauf * (sonstigeKostenProzent / 100));
const nettoVerkauf = bruttoVerkauf - vertriebskosten - sonstigeKosten;
// Update sale UI
document.getElementById('brutto-verkauf').textContent = formatCurrency(bruttoVerkauf);
document.getElementById('calc-vertriebskosten').textContent = formatCurrency(-vertriebskosten);
document.getElementById('sales-costs-percent').textContent = `(${data.vertriebskosten}%)`;
document.getElementById('sale-other-costs-value').textContent = formatCurrency(-sonstigeKosten);
document.getElementById('sale-other-costs-percent').textContent = `(${sonstigeKostenProzent}%)`;
document.getElementById('netto-verkauf').textContent = formatCurrency(nettoVerkauf);
// Update neubau m² info in sale tab
const sqmInfo = document.getElementById('neubau-sqm-info');
if (sqmInfo) {
sqmInfo.textContent = `${data.wohnflaeche} m²`;
}
// Update market comparison displays
const yourPriceDisplay = document.getElementById('your-price-display');
if (yourPriceDisplay) {
yourPriceDisplay.textContent = formatCurrency(data.verkaufspreis_qm) + '/m²';
}
// Update partner sales calculations if in split mode
if (state.partnerView === 'split') {
const revenueSplitA = state.revenueSplit.followsCostSplit ? state.partnerSplit.a : state.revenueSplit.a;
const revenueSplitB = state.revenueSplit.followsCostSplit ? state.partnerSplit.b : state.revenueSplit.b;
const bruttoVerkaufA = Math.round(bruttoVerkauf * (revenueSplitA / 100));
const bruttoVerkaufB = Math.round(bruttoVerkauf * (revenueSplitB / 100));
const vertriebskostenA = Math.round(bruttoVerkaufA * (data.vertriebskosten / 100));
const vertriebskostenB = Math.round(bruttoVerkaufB * (data.vertriebskosten / 100));
const sonstigeKostenA = Math.round(bruttoVerkaufA * (sonstigeKostenProzent / 100));
const sonstigeKostenB = Math.round(bruttoVerkaufB * (sonstigeKostenProzent / 100));
const nettoVerkaufA = bruttoVerkaufA - vertriebskostenA - sonstigeKostenA;
const nettoVerkaufB = bruttoVerkaufB - vertriebskostenB - sonstigeKostenB;
// Update Klaus values
const bruttoVerkaufAEl = document.getElementById('brutto-verkauf-a');
const calcVertriebskostenAEl = document.getElementById('calc-vertriebskosten-a');
const saleOtherCostsAEl = document.getElementById('sale-other-costs-a');
const nettoVerkaufAEl = document.getElementById('netto-verkauf-a');
if (bruttoVerkaufAEl) bruttoVerkaufAEl.textContent = formatCurrency(bruttoVerkaufA);
if (calcVertriebskostenAEl) calcVertriebskostenAEl.textContent = formatCurrency(-vertriebskostenA);
if (saleOtherCostsAEl) saleOtherCostsAEl.textContent = formatCurrency(-sonstigeKostenA);
if (nettoVerkaufAEl) nettoVerkaufAEl.textContent = formatCurrency(nettoVerkaufA);
// Update Kevin values
const bruttoVerkaufBEl = document.getElementById('brutto-verkauf-b');
const calcVertriebskostenBEl = document.getElementById('calc-vertriebskosten-b');
const saleOtherCostsBEl = document.getElementById('sale-other-costs-b');
const nettoVerkaufBEl = document.getElementById('netto-verkauf-b');
if (bruttoVerkaufBEl) bruttoVerkaufBEl.textContent = formatCurrency(bruttoVerkaufB);
if (calcVertriebskostenBEl) calcVertriebskostenBEl.textContent = formatCurrency(-vertriebskostenB);
if (saleOtherCostsBEl) saleOtherCostsBEl.textContent = formatCurrency(-sonstigeKostenB);
if (nettoVerkaufBEl) nettoVerkaufBEl.textContent = formatCurrency(nettoVerkaufB);
}
// Update partner revenue split display
if (state.partnerView === 'split') {
const revenueSplitA = state.revenueSplit.followsCostSplit ? state.partnerSplit.a : state.revenueSplit.a;
const revenueSplitB = state.revenueSplit.followsCostSplit ? state.partnerSplit.b : state.revenueSplit.b;
const revenueSplitADisplay = document.getElementById('revenue-split-a-display');
const revenueSplitBDisplay = document.getElementById('revenue-split-b-display');
const partnerARevenue = document.getElementById('partner-a-revenue');
const partnerBRevenue = document.getElementById('partner-b-revenue');
if (revenueSplitADisplay) revenueSplitADisplay.textContent = revenueSplitA;
if (revenueSplitBDisplay) revenueSplitBDisplay.textContent = revenueSplitB;
if (partnerARevenue) partnerARevenue.textContent = formatCurrency(nettoVerkauf * (revenueSplitA / 100));
if (partnerBRevenue) partnerBRevenue.textContent = formatCurrency(nettoVerkauf * (revenueSplitB / 100));
}
// Profit calculations
const projectProfit = nettoVerkauf - totalWithFinancing;
// Calculate profit based on revenue split (if enabled) or cost split
let yourProfit;
let totalEigenkapital;
if (state.partnerView === 'split') {
// In partner view, use the revenue split for profit distribution
const revenueSplitA = state.revenueSplit.followsCostSplit ? state.partnerSplit.a : state.revenueSplit.a;
const revenueSplitB = state.revenueSplit.followsCostSplit ? state.partnerSplit.b : state.revenueSplit.b;
// For overall project return, use total profit and combined eigenkapital
yourProfit = projectProfit; // Use full project profit for overall return calculation
const eigenkapitalA = parseFloat(data['eigenkapital-a']) || 0;
const eigenkapitalB = parseFloat(data['eigenkapital-b']) || 0;
totalEigenkapital = eigenkapitalA + eigenkapitalB;
} else {
// In combined view, use full project profit (no beteiligung for overall project summary)
yourProfit = projectProfit;
totalEigenkapital = parseFloat(data.eigenkapital) || 0;