-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulate.js
2667 lines (2394 loc) · 98.1 KB
/
simulate.js
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
// GUIDE
// This file contains the js code for the simulator page, of which there are 4 parts:
// UI
// Input Form
// Graphical Results Elements
// Tabular Results Elements
console.log('simulate.js loaded');
// UI
function toggle_nav_menu() {
console.log("toggle nav menu");
let menu = document.getElementById("nav-menu");
let toggle = document.getElementById("nav-toggle");
if (menu.classList.contains("open")) {
for (let div of menu.getElementsByTagName("a")) {
div.classList.remove("open");
div.classList.add("close");
}
menu.classList.remove("open");
menu.classList.add("close");
toggle.classList.remove("open");
} else {
for (let div of menu.getElementsByTagName("a")) {
div.classList.add("open");
div.classList.remove("close");
}
menu.classList.add("open");
menu.classList.remove("close");
toggle.classList.add("open");
}
}
// ---- SIMULATION INPUTS
// -- this section includes the code for the functionality of the simulation inputs
// ---- TERMS
// id = javascript id, as per document.getElementById(id).
// pid = partial id, corresponding to the name of the input lists
// ---- FUNCTIONS GUIDE
// clear_warnings(pid)
// -- clear all warning related to an input pid
// async function check_input(pid, transform, conditions)
// -- input validation
// input_help(pid)
// -- toggle help/info for input pid
// hide_ids(ids), hide_pids(pids), hide_elements(elements)
// -- hide all ids/pids/elements in the list
// unhide_ids(ids), unhide_pids(pids), unhide_elements(elements)
// -- unhide all ids/pids/elements in the list
// clear_value(pid), set_value(pid, value)
// -- clear/set the value of a pid
// validate_element(element), invalidate_element(element), clear_element_validation(element)
// -- add and remove valid and invalid class to element
// async onchange_address()
// -- update warning, epc_calling ... upon selection address change
// check_submit()
// -- check if all inputs are valid so simulation can be submitted
// toggle_advanced_inputs()
// -- toggle advanced inputs but dont reset them
// click_dismiss()
// -- any element with click-dismiss class automatically has click event applied with pointer styling
// set_run_location()
// -- set where simulation will run, client or server-side
// toggle_optimisation()
// -- toggle the checkbox for optimisation
// async get_epc_data()
// -- call the EPC API to get the epc_space_heating and floor_area for a given EPC certificate
// get_check_input_fnc(pid, apply_transform)
// -- returns a function that builds the check_input function, with option of including the transform function
// hide_postcode_related_inputs()
// -- if postcode is not valid then hide address, floor area and epc space heating inputs
// check_postcode_format(postcode)
// -- only call postcodes.io if outcode is of valid format
// async validate_postcode(postcode)
// -- call postcodes.io to get longitude and latitude data for postcode
// async get_address_certificates(postcode)
// -- get a list of addresses and their respective certificate codes for postcode
// show_manual_epc_input()
// -- if postcode is located in scotland or api request failed then fallback to manual floor area and space heating input
// submit_simulation()
// -- ran when submit button clicks. Will submit if all inputs valid.
// async submit_simulation_server()
// -- submit inputs to server to run simulation
// ---- GLOBALS
// let api_url = 'http://localhost:3000';
// let api_url = 'https://customapi.heatmyhome.ninja';
let api_url = 'https://customapi.heatmyhome.ninja';
let epc_api_url = api_url + '/epc';
// let simulate_api_url = api_url + '/simulate';
let simulate_api_url = './.netlify/functions/simulate';
let submit_status = false;
const input_ranges = { // MIN, MAX, MULTIPLIER
'temperature': [0, 35, 10],
'occupants': [1, 20, 1],
'tes-volume': [0.1, 3.0, 10],
'epc-space-heating': [0, 999999, 1],
'floor-area': [25, 1500, 1],
}
let input_values = {
'postcode': undefined,
'longitude': undefined,
'latitude': undefined,
'epc-space-heating': undefined,
'floor-area': undefined,
'temperature': undefined,
'occupants': undefined,
'tes-volume': undefined,
'run-on': 'server-rust',
'enable-optimisation': true,
}
let scottish_postcode = false;
let epc_api_connection = true;
let epc_api_error = false;
let selected_certificate = undefined;
const input_id_list = ['postcode', 'epc-space-heating', 'floor-area', 'temperature', 'occupants', 'tes-volume', 'neighbour-postcode'];
// ---- INITIALISATION
// apply validation functions to oninput and onchange events for each input (excluding selections and checkboxes)
// run validation incase page was reloaded
for (let input_id of input_id_list) {
let element = document.getElementById('input-' + input_id);
if (input_id != 'postcode' && input_id != 'neighbour-postcode') {
element.addEventListener('change', get_check_input_fnc(input_id, true));
}
element.addEventListener('input', get_check_input_fnc(input_id, false));
}
// apply onclick events to all elements with the click-dismiss class
click_dismiss();
// update epc url links
update_epc_urls();
update_neighbours_epc_urls();
// reset run-on select, must add delay otherwise autofill fills old value after reset.
setTimeout(() => {
console.log('reset');
document.getElementById('run-location').value = 'server-rust';
}, 10);
// ---- FUNCTIONS
function clear_warnings(pid) {
let input_box_element = document.getElementById("input-box-" + pid);
let warn_elements = input_box_element.getElementsByClassName("warn");
for (let warn_element of warn_elements) {
warn_element.classList.add("hide");
}
}
async function check_input(pid, transform, conditions) {
let input_element = document.getElementById("input-" + pid);
let help_element = document.getElementById("help-" + pid);
help_element.classList.add("hide");
document.getElementById("input-box-" + pid).getElementsByClassName("input-side-button")[0].classList.remove("active");
// console.log('check_input: ', pid, 'value: ', input_element.value);
if (input_element.value == "") {
clear_element_validation(input_element);
clear_warnings(pid);
} else {
if (transform != undefined) {
input_element.value = transform(input_element.value);
}
let is_valid = true;
for (let condition of conditions) {
let warn_pid = await condition(input_element.value);
if (warn_pid != "") {
is_valid = false;
clear_warnings(pid);
if (warn_pid != "none") {
console.log("pid: ", pid, ", warn_pid: ", warn_pid, "condition", condition);
let warn_element = document.getElementById("warn-" + pid + '-' + warn_pid);
warn_element.classList.remove("hide");
}
break;
}
}
if (is_valid) {
validate_element(input_element);
if (pid != 'neighbour-postcode') {
if (/[a-z]/i.test(input_element.value)) {
input_values[pid] = input_element.value;
} else { // if parameter does not contain letters assume number
input_values[pid] = Number(input_element.value);
}
clear_warnings(pid);
}
} else {
invalidate_element(input_element);
}
}
check_submit();
}
function neighbour_text(is_neighbour) {
if (is_neighbour) {
return "neighbour-";
} else {
return "";
}
}
function input_help(pid, is_neighbour) {
console.log(is_neighbour, neighbour_text(is_neighbour));
let help_button = document.getElementById("input-box-" + neighbour_text(is_neighbour) + pid).getElementsByClassName("input-side-button")[0];
let help_msg = document.getElementById("help-" + neighbour_text(is_neighbour) + pid);
if (help_msg.classList.contains("hide")) {
help_msg.classList.remove("hide");
help_button.classList.add("active");
} else {
help_msg.classList.add("hide");
help_button.classList.remove("active");
}
}
function hide_ids(ids) {
for (let id of ids) {
document.getElementById(id).classList.add("hide");
}
}
function unhide_ids(ids) {
for (let id of ids) {
document.getElementById(id).classList.remove("hide");
}
}
function hide_pids(pids) {
for (let pid of pids) {
document.getElementById('input-' + pid).classList.add("hide");
}
}
function unhide_pids(pids) {
for (let pid of pids) {
document.getElementById('input-' + pid).classList.remove("hide");
}
}
function hide_elements(elements) {
for (let element of elements) {
element.classList.add("hide");
}
}
function unhide_elements(elements) {
for (let element of elements) {
element.classList.remove("hide");
}
}
function clear_value(pid) {
document.getElementById('input-' + pid).value = "";
}
function set_value(pid, value) {
document.getElementById('input-' + pid).value = value;
}
function validate_element(element) {
element.classList.add("valid");
element.classList.remove("invalid");
}
function invalidate_element(element) {
element.classList.remove("valid");
element.classList.add("invalid");
}
function clear_element_validation(element) {
element.classList.remove("valid", "invalid");
}
async function onchange_address() {
let address_element = document.getElementById("input-address");
let warn_element = document.getElementById("warn-address-not-listed");
let epc_box_element = document.getElementById("input-box-epc-space-heating");
let floor_area_box_element = document.getElementById("input-box-floor-area");
let searching = document.getElementById("epc-searching");
clear_value('epc-space-heating');
get_check_input_fnc('epc-space-heating', false)();
clear_value('floor-area');
get_check_input_fnc('floor-area', false)();
clear_warnings("address");
document.getElementById("input-postcode").parentElement.getElementsByTagName('p')[0].innerText = 'Postcode';
hide_ids(['help-address', 'neighbour-container', 'neighbour-title']);
selected_certificate = undefined;
switch (address_element.value) {
case "Select Address":
clear_element_validation(address_element);
hide_elements([warn_element, epc_box_element, floor_area_box_element]);
break;
case "Address Not Listed":
invalidate_element(address_element);
unhide_elements([warn_element, epc_box_element, floor_area_box_element]);
open_neighbour_menu();
break;
default:
validate_element(address_element);
hide_elements([warn_element, epc_box_element, floor_area_box_element]);
unhide_elements([searching]);
await get_epc_data();
hide_elements([searching]);
}
update_epc_urls();
}
async function onchange_neighbours_address() {
let address_element = document.getElementById("input-neighbour-address");
let epc_box_element = document.getElementById("input-box-neighbour-epc-space-heating");
let floor_area_box_element = document.getElementById("input-box-neighbour-floor-area");
let searching = document.getElementById("neighbour-epc-searching");
clear_value('neighbour-epc-space-heating');
clear_value('neighbour-floor-area');
clear_element_validation(document.getElementById('input-neighbour-epc-space-heating'));
clear_element_validation(document.getElementById('input-neighbour-floor-area'));
hide_ids(['warn-neighbour-no-data', 'warn-neighbour-address-unknown', 'warn-neighbour-address-connection']);
switch (address_element.value) {
case "Select Address":
clear_element_validation(address_element);
hide_elements([epc_box_element, floor_area_box_element]);
break;
default:
validate_element(address_element);
hide_elements([epc_box_element, floor_area_box_element]);
unhide_elements([searching]);
await get_neighbour_epc_data();
hide_elements([searching]);
}
update_neighbours_epc_urls();
}
function fill_neighbour_address() {
let address_element = document.getElementById('input-neighbour-address');
while (address_element.getElementsByTagName('option').length > 0) {
address_element.removeChild(address_element.lastChild);
}
clear_element_validation(address_element);
let opt1 = document.createElement('option');
opt1.text = "Select Address";
opt1.classList.add("color-neutral");
address_element.appendChild(opt1);
for (let [address, certificate] of address_certificate_list) {
//console.log(address, certificate);
let option_element = document.createElement('option');
option_element.value = certificate;
option_element.classList.add("color-black");
// shorten address and remove any trailing commas or spaces
option_element.text = address.substring(0, 45).replace(/,\s*$/, "");
address_element.appendChild(option_element);
}
unhide_elements([address_element]);
}
function input_apply(pid) {
document.getElementById('input-' + pid).value = document.getElementById('input-neighbour-' + pid).value;
get_check_input_fnc(pid, false)();
}
function open_neighbour_menu() {
let n_postcode_element = document.getElementById('input-neighbour-postcode');
n_postcode_element.value = input_values.postcode;
validate_element(n_postcode_element);
fill_neighbour_address();
document.getElementById("input-postcode").parentElement.getElementsByTagName('p')[0].innerText = 'Your Postcode';
unhide_ids(['neighbour-container', 'neighbour-title']);
// hide_ids(['warn-address-not-listed', 'warn-address-missing-data']);
}
function submit_simulation() {
let submit_input = document.getElementById("input-submit");
if (!submit_input.classList.contains('invalid')) {
submit_input.classList.add('active');
hide_ids(['warn-sim-api-connection', 'warn-sim-api-error', 'warn-sim-api-busy']);
console.log("submit-simulation: ", input_values);
switch (input_values["run-on"]) {
case 'server-rust':
submit_simulation_server();
break;
case 'client-rust':
submit_simulation_rust();
break;
case 'client-cpp':
submit_simulation_cpp();
break;
}
} else {
unhide_ids(['warn-submit']);
}
}
// setTimeout(() => {
// input_values = {
// 'postcode': 'HP160LU',
// 'longitude': -1.5833,
// 'latitude': 52.3833,
// 'epc-space-heating': 3000.0,
// 'floor-area': 60.0,
// 'temperature': 20.0,
// 'occupants': 2,
// 'tes-volume': 0.5,
// 'run-on': 'client-rust',
// 'enable-optimisation': true,
// }
// submit_simulation_rust();
// }, 1000);
function submit_simulation_cpp() {
console.log('submit_simulation_cpp');
unhide_ids(['submit-waiting']);
hide_ids(['submit-complete']);
if (window.Worker) {
var worker_cpp = new Worker('./worker_cpp.js');
worker_cpp.onmessage = function (e) {
if (!e.data) {
console.error("Cpp simulator failed: ", e.data);
unhide_ids(['warn-sim-cpp-error']);
} else {
worker_cpp.terminate();
clearTimeout(simulation_timeout);
console.log('simulator-cpp-json:', JSON.parse(e.data));
unhide_ids(['submit-complete']);
hide_ids(['guide']);
output = JSON.parse(e.data);
load_output();
}
hide_ids(['submit-waiting']);
document.getElementById("input-submit").classList.remove('active');
}
let simulation_timeout = setTimeout(() => {
console.error("Rust simulator exceeded time limit");
hide_ids(['submit-waiting']);
unhide_ids(['warn-sim-client-timeout']);
document.getElementById("input-submit").classList.remove('active');
}, 600000);
worker_cpp.postMessage(input_values);
} else {
console.error("Rust-Sim-Worker-Unsupported");
unhide_ids(['warn-sim-client-worker']);
}
}
function submit_simulation_rust() {
console.log('submit_simulation_rust');
unhide_ids(['submit-waiting']);
hide_ids(['submit-complete']);
if (window.Worker) {
var worker = new Worker('./worker.js', { type: "module" });
worker.onmessage = function (e) {
if (!e.data) {
console.error("Rust simulator failed: ", e.data);
unhide_ids(['warn-sim-rust-error']);
} else {
worker.terminate();
clearTimeout(simulation_timeout);
console.log('simulator-rust-json:', JSON.parse(e.data));
unhide_ids(['submit-complete']);
hide_ids(['guide']);
output = JSON.parse(e.data);
load_output();
}
hide_ids(['submit-waiting']);
document.getElementById("input-submit").classList.remove('active');
}
let simulation_timeout = setTimeout(() => {
console.error("Rust simulator exceeded time limit");
hide_ids(['submit-waiting']);
unhide_ids(['warn-sim-client-timeout']);
document.getElementById("input-submit").classList.remove('active');
}, 600000);
worker.postMessage(input_values);
} else {
console.error("Rust-Sim-Worker-Unsupported");
unhide_ids(['warn-sim-client-worker']);
}
}
let input_url_names = {
'postcode': 'postcode',
'epc-space-heating': 'space_heating',
'floor-area': 'floor_area',
'temperature': 'temperature',
'occupants': 'occupants',
'tes-volume': 'tes_max',
}
let simulator_input_url = undefined;
function generate_input_url() {
search = Array();
for (const [key, value] of Object.entries(input_url_names)) {
// console.log(key, value, input_values[key]);
search.push(`${value}=${input_values[key]}`);
}
simulator_input_url = location.protocol + '//' + location.host + location.pathname + `?${search.join('&')}`;
console.log('created-simulator-input-url: ', simulator_input_url);
}
let simulator_api_full_url = undefined;
function generate_sim_api_url() {
search = Array();
let api_url_names = {
'postcode': 'postcode',
'latitude': 'latitude',
'longitude': 'longitude',
'epc-space-heating': 'space_heating',
'floor-area': 'floor_area',
'temperature': 'temperature',
'occupants': 'occupants',
'tes-volume': 'tes_max',
}
for (const [key, value] of Object.entries(api_url_names)) {
// console.log(key, value, input_values[key]);
search.push(`${value}=${input_values[key]}`);
}
simulator_api_full_url = simulate_api_url + `?${search.join('&')}`;
console.log('created-simulator-api-url: ', simulator_api_full_url);
}
function copy_input_url_to_clipboard() {
console.log('copied-simulator-url: ', simulator_input_url);
navigator.clipboard.writeText(simulator_input_url);
}
let loading_inputs_from_url = false;
load_inputs_from_url();
function load_inputs_from_url() {
const urlParams = new URLSearchParams(window.location.search);
if (Array.from(urlParams.keys()).length > 0) {
let url_values = {
'postcode': undefined,
'epc-space-heating': undefined,
'floor-area': undefined,
'temperature': undefined,
'occupants': undefined,
'tes-volume': undefined,
}
for (const [form_name, url_name] of Object.entries(input_url_names)) {
const value = urlParams.get(url_name);
if (value) {
url_values[form_name] = value;
} else {
console.error("Not all parameters contained in url: ", url_name, value);
return;
}
}
loading_inputs_from_url = true;
for (let [key, value] of Object.entries(url_values)) {
let element = document.getElementById('input-' + key);
element.value = value;
get_check_input_fnc(key, true)();
}
unhide_pids(['box-epc-space-heating', 'box-floor-area']);
const url = location.protocol + '//' + location.host + location.pathname;
console.log('loaded url with parameters:', window.location.href)
window.history.replaceState({}, '', url);
}
}
function load_inputs_from_file(file_inputs) {
let file_values = {
'postcode': undefined,
'epc-space-heating': undefined,
'floor-area': undefined,
'temperature': undefined,
'occupants': undefined,
'tes-volume': undefined,
}
for (const name of Object.keys(file_values)) {
const value = file_inputs[name];
if (value) {
file_values[name] = value;
} else {
console.error("Not all parameters contained in file: ", name, value);
return;
}
}
loading_inputs_from_url = true;
for (let [key, value] of Object.entries(file_values)) {
let element = document.getElementById('input-' + key);
element.value = value;
get_check_input_fnc(key, true)();
}
unhide_pids(['box-epc-space-heating', 'box-floor-area']);
const url = location.protocol + '//' + location.host + location.pathname;
console.log('loaded url with parameters:', window.location.href)
window.history.replaceState({}, '', url);
}
async function submit_simulation_server() {
let submit_input = document.getElementById("input-submit");
unhide_ids(['submit-waiting']);
hide_ids(['submit-complete']);
try {
const response = await fetch(simulator_api_full_url);
const json = await response.json();
if (response.status == 200) {
console.log('simulator-api-json:', json);
unhide_ids(['submit-complete']);
hide_ids(['guide']);
output = json['result'];
load_output();
} else {
throw new Error(json['error']);
}
} catch (error) {
console.error('simulator-api-error: ', error);
if (error.message == 'Failed to fetch' || error.message == 'Load failed') {
unhide_ids(['warn-sim-api-connection']);
} else if (error.message.startsWith('simulation exceeded allowed runtime')) {
unhide_ids(['warn-sim-api-busy']);
}
else {
unhide_ids(['warn-sim-api-error']);
}
}
hide_ids(['submit-waiting']);
submit_input.classList.remove('active');
}
function create_simulation_output_file_download() {
let data = {
'inputs': input_values,
'outputs': output,
}
let txt = JSON.stringify(data, null, 2);
let blob = new Blob([txt], { type: "text/plain" });
let dlink = document.getElementById("download-link");
let url = window.URL.createObjectURL(blob);
dlink.href = url;
dlink.download = "HeatMyHome.txt";
}
function upload_results() {
const reader = new FileReader();
reader.onload = function (e) {
file_data = JSON.parse(this.result);
load_inputs_from_file(file_data.inputs);
output = file_data.outputs
console.log("Loaded data from file: ", file_data);
load_output();
}
reader.readAsText(this.files[0]);
this.value = null;
}
document.getElementById("load-results").addEventListener('change', upload_results, false);
function check_submit() {
let submit = true;
for (let pid of input_id_list) {
if (pid != 'neighbour-postcode') {
let element = document.getElementById('input-' + pid);
if (!element.classList.contains("valid")) {
submit = false;
}
}
}
if (submit) {
generate_sim_api_url();
generate_input_url();
unhide_ids(['input-box-save-url']);
} else {
hide_ids(['input-box-save-url']);
}
if (submit != submit_status) {
submit_status = submit;
// let submit_element = document.getElementById('submit-group');
// let advanced_element = submit_element.getElementsByClassName("input-side-button")[0];
let submit_input = document.getElementById("input-submit");
if (submit) {
submit_input.classList.remove('invalid');
hide_ids(['warn-submit']);
} else {
submit_input.classList.add('invalid');
}
}
}
function toggle_advanced_inputs() {
let run_location = document.getElementById('run-location');
let submit_element = document.getElementById('submit-group');
let button = submit_element.getElementsByClassName("input-side-button")[0];
if (run_location.classList.contains("hide")) {
unhide_elements([run_location]);
button.classList.add("active");
unhide_ids(['run-location', 'help-advanced']);
set_run_location();
} else {
button.classList.remove("active");
hide_ids(['run-location', 'help-advanced', 'input-box-optimisation']);
}
}
function click_dismiss() {
let elements = document.getElementsByClassName('click-dismiss');
for (let element of elements) {
element.addEventListener('click', () => { document.getElementById(element.id).classList.add('hide') });
}
}
function set_run_location() {
let element = document.getElementById("run-location");
let optimisation_element = document.getElementById("input-box-optimisation");
let value = element.getElementsByTagName("option")[element.selectedIndex].value;
input_values["run-on"] = value;
switch (value) {
case 'server-rust':
hide_elements([optimisation_element]);
break;
default:
unhide_elements([optimisation_element]);
}
}
function toggle_optimisation() {
let element = document.getElementById("input-optimisation");
let box = document.getElementById("input-box-optimisation");
let divs = element.getElementsByTagName('div');
if (box.classList.contains("ticked")) {
box.classList.remove("ticked");
input_values["enable-optimisation"] = false;
} else {
box.classList.add("ticked");
input_values["enable-optimisation"] = true;
}
for (let div of divs) {
if (div.classList.contains("checkmark")) {
div.classList.add("crossmark");
div.classList.remove("checkmark");
} else {
div.classList.remove("crossmark");
div.classList.add("checkmark");
}
}
}
async function get_epc_data() {
let select = document.getElementById('input-address');
selected_certificate = select.options[select.selectedIndex].value;
// const full_url = `${epc_api_url}?certificate=${selected_certificate}`;
const full_url = `/.netlify/functions/get_certificate_data?certificate=${selected_certificate}`;
try {
const response = await fetch(full_url);
const json = await response.json();
if (response.status == 200) {
console.log('epc-certificate-json: ', json);
const result = json['result'];
if (result['space-heating']) {
set_value('epc-space-heating', result['space-heating'].match(/\d+/)[0]);
get_check_input_fnc('epc-space-heating', false)();
} else {
clear_value('epc-space-heating');
// unhide_ids(['warn-epc-space-heating-none']);
}
if (result['floor-area']) {
set_value('floor-area', result['floor-area'].match(/\d+/)[0]);
get_check_input_fnc('floor-area', false)();
} else {
clear_value('floor-area');
// unhide_ids(['warn-floor-area-none']);
}
if (result['space-heating'] && result['floor-area']) {
document.getElementById('help-address').innerHTML = `Your address was used to fill out the space heating estimate and floor
area parameters from your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>.
You may wish to adjust the parameters manually.`
unhide_ids(['help-address']);
} else if (result['space-heating'] && !result['floor-area']) {
document.getElementById('help-address').innerHTML = `Your address was used to fill out the space heating estimate
from your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>.
You may wish to adjust the parameter manually.`
document.getElementById('warn-address-missing-data').innerHTML = ` Your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a floor area estimate. Enter it manually or select a neighbour's address whose home is similar in size to yours.`;
unhide_ids(['help-address', 'warn-address-missing-data', 'input-box-epc-space-heating']);
open_neighbour_menu();
} else if (!result['space-heating'] && result['floor-area']) {
document.getElementById('help-address').innerHTML = `Your address was used to fill out the floor area parameter
from your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>.
You may wish to adjust the parameter manually.`
document.getElementById('warn-address-missing-data').innerHTML = ` Your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a space heating estimate. Enter it manually or select a neighbour's address whose home has similar heating and hot water requirements to yours.`;
unhide_ids(['help-address', 'warn-address-missing-data', 'input-box-floor-area']);
open_neighbour_menu();
} else { // neither
document.getElementById('warn-address-missing-data').innerHTML = ` Your home's <a href="" class="epc-url" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a space heating or floor area estimate. Enter them manually or select a neighbour's address whose home is of similar size and has similar heating and hot water requirements to yours.`;
unhide_ids(['warn-address-missing-data', 'input-box-floor-area']);
open_neighbour_menu();
}
hide_ids(['epc-searching', 'warn-address-not-listed']);
unhide_ids(['input-box-epc-space-heating', 'input-box-floor-area']);
} else {
throw new Error(json['error']);
}
}
catch (error) {
console.error('epc-certificate-json-error: ', error);
if (error.message == "Failed to fetch") {
unhide_ids(['warn-address-connection']);
} else {
unhide_ids(['warn-address-unknown']);
}
}
}
async function get_neighbour_epc_data() {
let select = document.getElementById('input-neighbour-address');
let certificate = select.options[select.selectedIndex].value;
// const full_url = `${epc_api_url}?certificate=${certificate}`;
const full_url = `/.netlify/functions/get_certificate_data?certificate=${certificate}`;
try {
const response = await fetch(full_url);
const json = await response.json();
if (response.status == 200) {
console.log('epc-certificate-json: ', json);
const result = json['result'];
let warn_no_data = document.getElementById('warn-neighbour-no-data');
let have_valid_space_heating = document.getElementById('input-epc-space-heating').classList.contains('valid');
let have_valid_floor_area = document.getElementById('input-floor-area').classList.contains('valid');
console.log(have_valid_space_heating, have_valid_floor_area);
if (result['space-heating']) {
set_value('neighbour-epc-space-heating', result['space-heating'].match(/\d+/)[0]);
validate_element(document.getElementById('input-neighbour-epc-space-heating'));
unhide_ids(['input-box-neighbour-epc-space-heating']);
} else {
if (have_valid_space_heating) {
clear_value('neighbour-epc-space-heating');
clear_element_validation(document.getElementById('input-neighbour-epc-space-heating'));
hide_ids(['input-box-neighbour-epc-space-heating']);
}
}
if (result['floor-area']) {
set_value('neighbour-floor-area', result['floor-area'].match(/\d+/)[0]);
validate_element(document.getElementById('input-neighbour-floor-area'));
unhide_ids(['input-box-neighbour-floor-area']);
} else {
if (have_valid_floor_area) {
clear_value('neighbour-floor-area');
clear_element_validation(document.getElementById('input-neighbour-floor-area'));
hide_ids(['input-box-neighbour-floor-area']);
}
}
if (!have_valid_space_heating && !have_valid_floor_area && !result['space-heating'] && !result['floor-area']) {
warn_no_data.innerHTML = ` Neighbour's <a href="" class="epc-url-neighbour" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a space heating or floor estimate. Select a different neighbour.`;
warn_no_data.classList.remove('hide');
} else if (!have_valid_space_heating && !result['space-heating']) {
warn_no_data.innerHTML = ` Neighbour's <a href="" class="epc-url-neighbour" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a space heating estimate. Select a different neighbour.`;
warn_no_data.classList.remove('hide');
} else if (!have_valid_floor_area && !result['floor-area']) {
warn_no_data.innerHTML = ` Neighbour's <a href="" class="epc-url-neighbour" target="_blank" rel="noopener noreferrer">EPC</a>
does not contain a floor area estimate. Select a different neighbour.`;
warn_no_data.classList.remove('hide');
}
hide_ids(['neighbour-epc-searching']);
} else {
throw new Error(json['error']);
}
}
catch (error) {
console.error('epc-certificate-json-error: ', error);
if (error.message == "Failed to fetch") {
unhide_elements([document.getElementById('warn-neighbour-address-connection')]);
} else {
unhide_elements([document.getElementById('warn-neighbour-address-unknown')]);
}
hide_ids(['neighbour-epc-searching']);
}
}
function get_check_input_fnc(pid, apply_transform) {
switch (pid) {
case 'postcode':
return async () => {
let searching = document.getElementById("postcode-searching");
unhide_elements([searching]);
invalidate_element(document.getElementById('input-postcode'));
await check_input("postcode",
(postcode) => { return postcode.toUpperCase().replace(/\s/g, '').substring(0, 7); },
[
hide_postcode_related_inputs,
(postcode) => { return check_postcode_format(postcode); },
async (postcode) => { return validate_postcode(postcode); },
async (postcode) => { return get_address_certificates(postcode); },
show_manual_epc_input,
]
);
hide_elements([searching]);
if (!epc_api_connection) {
unhide_ids(['warn-postcode-epc-connection']);
} else if (epc_api_error) {
unhide_ids(['warn-postcode-epc-api']);
}
loading_inputs_from_url = false;
update_epc_urls();
};
break;
case 'neighbour-postcode':
return async () => {
let searching = document.getElementById("neighbour-postcode-searching");
unhide_elements([searching]);
await check_input("neighbour-postcode",
(postcode) => { return postcode.toUpperCase().replace(/\s/g, '').substring(0, 7); },
[
hide_neighbours_postcode_related_inputs,
(postcode) => { return check_postcode_format(postcode); },
async (postcode) => { return validate_neighbours_postcode(postcode); },
async (postcode) => { return get_neighbours_address_certificates(postcode); },
show_manual_epc_input,
]
);
hide_elements([searching]);
if (!epc_api_connection) {
unhide_ids(['warn-neighbour-postcode-epc-connection']);
} else if (epc_api_error) {
unhide_ids(['warn-neighbour-postcode-epc-api']);
}
update_neighbours_epc_urls();
};
break;
default:
const [min_input, max_input, multipler] = input_ranges[pid];
return () =>
check_input(pid,
apply_transform ? (value) => { return Math.round(Math.min(Math.max(value, min_input), max_input) * multipler) / multipler; } : undefined,
[
(value) => { if (value >= min_input && value <= max_input) { return ""; } else { return "range" } },
]
);
}
}
function hide_postcode_related_inputs() {
scottish_postcode = false;
epc_api_connection = true;
epc_api_error = false;
selected_certificate = undefined;
document.getElementById("input-postcode").parentElement.getElementsByTagName('p')[0].innerText = 'Postcode';
hide_ids(['input-address', 'help-scottish-postcode', 'input-box-epc-space-heating', 'input-box-floor-area', 'epc-searching', 'help-address', 'neighbour-container', 'neighbour-title']);
clear_warnings('address');
clear_value('epc-space-heating');
get_check_input_fnc('epc-space-heating', false)();
clear_value('floor-area');
get_check_input_fnc('floor-area', false)();
return "";
}
function hide_neighbours_postcode_related_inputs() {