-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpredbat-table-card.js
More file actions
3719 lines (2980 loc) · 155 KB
/
predbat-table-card.js
File metadata and controls
3719 lines (2980 loc) · 155 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
async function fetchEntityHistory(hass, entityId, hours = 1) {
const end = new Date();
const start = new Date(end.getTime() - hours * 3600 * 1000);
const path = `history/period/${start.toISOString()}?end_time=${end.toISOString()}&filter_entity_id=${entityId}&minimal_response=1&significant_changes_only=1&no_attributes`;
const data = await hass.callApi("GET", path);
return (Array.isArray(data) && data[0]) ? data[0] : [];
}
function getLastCompletedOnRun(history) {
if (!Array.isArray(history) || history.length < 2) return null;
for (let offIdx = history.length - 1; offIdx >= 0; offIdx--) {
if (history[offIdx].state !== 'off') continue;
for (let onIdx = offIdx - 1; onIdx >= 0; onIdx--) {
const s = history[onIdx].state;
if (s === 'on') {
const start = new Date(history[onIdx].last_changed);
const end = new Date(history[offIdx].last_changed);
const ms = end - start;
return ms > 0 ? { ms, start, end } : null;
}
if (s === 'off') break;
}
}
return null;
}
function formatDuration(ms) {
const s = Math.floor(ms / 1000);
const m = Math.floor(s / 60);
const sec = s % 60;
return m ? `${m}m ${sec}s` : `${sec}s`;
}
class PredbatTableCard extends HTMLElement {
// The user supplied configuration. Throw an exception and Home Assistant
// will render an error card.
setConfig(config) {
if (!config.entity) {
throw new Error("You need to set the predbat entity");
}
if (!config.columns) {
throw new Error("You need to define a list of columns (see docs)");
} else if((config.columns.includes("weather-column") || config.columns.includes("temp-column") || config.columns.includes("rain-column")) && !config.weather_entity) {
throw new Error("To use weather or temp columns you need to include a weather_entity in your YAML");
}
this.config = config;
}
// Let HA know which editor element to use
/*
static getConfigElement() {
return document.createElement('predbat-card-editor');
}
*/
static getConfigForm() {
return {
schema: [
{
name: "help_text",
type: "constant",
value: "",
},
{ name: "entity",
required: true,
selector: {
entity: {}
},
default: "predbat.plan_html",
},
{
name: "",
title: "General Card Settings",
type: "expandable",
schema: [
{ name: "fill_empty_cells", selector: { boolean: {} } },
{ name: "show_day_totals", selector: { boolean: {} } },
{ name: "show_plan_totals", selector: { boolean: {} } },
{ name: "show_predbat_version", selector: { boolean: {} } },
{ name: "show_tablecard_version", selector: { boolean: {} } },
{ name: "hide_last_update", selector: { boolean: {} } },
{ name: "hide_empty_columns", selector: { boolean: {} } },
{ name: "use_friendly_states", selector: { boolean: {} } },
{ name: "stack_pills", selector: { boolean: {} } },
{ name: "debug_prices_only", selector: { boolean: {} } },
{ name: "reset_day_totals", selector: { boolean: {} } },
{
name: "row_limit",
selector: {
number: {
min: 1,
max: 400,
step: 1, // allows fractional values (e.g. 12.5)
mode: "box", // shows a numeric input box instead of slider
},
},
default: 100,
},
{
name: "battery_capacity",
selector: {
number: {
min: 1,
mode: "box", // shows a numeric input box instead of slider
step: 0.01,
unit_of_measurement: "kWh",
},
},
},
]
},
{
name: "",
title: "Card Style Settings",
type: "expandable",
schema: [
{
name: "table_width",
selector: { number: { min: 10, max: 100, step: 1, unit_of_measurement: "%" } },
default: 100, // starting value
},
{ name: "old_skool", selector: { boolean: {} }, default: false },
{
name: 'old_skool_columns',
selector: {
select: {
multiple: true,
mode: 'dropdown',
options: [
{ value: 'time-column', label: 'Time' },
{ value: 'import-column', label: 'Import' },
{ value: 'export-column', label: 'Export' },
{ value: 'import-export-column', label: 'Import & Export' },
{ value: 'load-column', label: 'Load' },
{ value: 'pv-column', label: 'PV' },
{ value: 'state-column', label: 'State' },
{ value: 'soc-column', label: 'SoC' },
{ value: 'limit-column', label: 'Limit' },
{ value: 'cost-column', label: 'Cost' },
{ value: 'total-column', label: 'Total Cost' },
{ value: 'car-column', label: 'Car' },
{ value: 'iboost-column', label: 'iBoost' },
{ value: 'co2kwh-column', label: 'CO2 kWh' },
{ value: 'co2kg-column', label: 'CO2 KG' },
{ value: 'xload-column', label: 'X-Load' },
{ value: 'clip-column', label: 'Clip' },
{ value: 'net-power-column', label: 'Net Power' },
{ value: 'options-popup-column', label: 'Popup Overrides' },
{ value: 'options-column', label: 'Overrides' },
],
},
},
},
{
name: "font_size",
selector: {
number: {
min: 8,
max: 32,
step: 0.1, // allows fractional values (e.g. 12.5)
mode: "box", // shows a numeric input box instead of slider
unit_of_measurement: "px", // optional, just a label suffix
},
},
default: 14,
},
{
name: "light_mode",
selector: {
select: {
multiple: false,
options: [
{ value: 'auto', label: 'Automatic' },
{ value: 'light', label: 'Light Mode'},
{ value: 'dark', label: 'Dark Mode'},
],
},
},
},
{
name: "color_help_text",
type: "constant",
value: "",
},
{
name: "",
type: "grid",
schema: [
{
name: "odd_row_colour",
selector: {
text: {
type: "text",
}
},
default: "#ffffff"
},
{
name: "even_row_colour",
selector: {
text: {
type: "text",
}
},
default: "#ffffff"
},
{
name: "odd_row_colour_light",
selector: {
text: {
type: "text",
}
},
default: "#ffffff"
},
{
name: "even_row_colour_light",
selector: {
text: {
type: "text",
}
},
default: "#ffffff"
},
]
},
{
name: "color_help_text_more",
type: "constant",
value: "",
},
]
},
{
name: "",
title: "Predbat Debug Settings",
type: "expandable",
schema: [
{
name: 'debug_columns',
selector: {
select: {
multiple: true,
mode: 'dropdown',
options: [
{ value: 'time-column', label: 'Time' },
{ value: 'import-column', label: 'Import' },
{ value: 'export-column', label: 'Export' },
{ value: 'import-export-column', label: 'Import & Export' },
{ value: 'load-column', label: 'Load' },
{ value: 'pv-column', label: 'PV' },
{ value: 'state-column', label: 'State' },
{ value: 'soc-column', label: 'SoC' },
{ value: 'limit-column', label: 'Limit' },
{ value: 'cost-column', label: 'Cost' },
{ value: 'total-column', label: 'Total Cost' },
{ value: 'car-column', label: 'Car' },
{ value: 'iboost-column', label: 'iBoost' },
{ value: 'co2kwh-column', label: 'CO2 kWh' },
{ value: 'co2kg-column', label: 'CO2 KG' },
{ value: 'xload-column', label: 'X-Load' },
{ value: 'clip-column', label: 'Clip' },
{ value: 'net-power-column', label: 'Net Power' },
{ value: 'options-popup-column', label: 'Popup Overrides' },
{ value: 'options-column', label: 'Overrides' },
],
},
},
},
]
},
{
name: "",
title: "Advanced Settings",
type: "expandable",
schema: [
{ name: "weather_entity", selector: { entity: {} } },
{
name: "path_for_click",
selector: {
text: {
type: "text",
}
},
default: "/my-dashboard/predbat-plan",
},
]
},
],
computeLabel: (schema) => {
if (schema.name === "entity") return "Predbat HTML Entity:";
if (schema.name === "fill_empty_cells") return "Fill Empty Cells?";
if (schema.name === "show_day_totals") return "Show Day Totals Row?";
if (schema.name === "show_plan_totals") return "Show Plan Totals Row?";
if (schema.name === "use_friendly_states") return "Use friendly STATE labels?";
if (schema.name === "stack_pills") return "Stack Import/Export Pills?";
if (schema.name === "old_skool") return "Use original Predbat Plan stylesheet? (old_skool mode)";
if (schema.name === "old_skool_columns") return "Choose specific columns to use original Predbat Plan style";
if (schema.name === "help_text") return "Important: You must manually set the columns in your card YAML";
if (schema.name === "table_width") return "Table Width (%)";
if (schema.name === "font_size") return "Font Size (px)";
if (schema.name === "row_limit") return "Number of rows to return";
if (schema.name === "show_predbat_version") return "Show Predbat version?";
if (schema.name === "show_tablecard_version") return "Show Predbat Table Card version?";
if (schema.name === "hide_last_update") return "Hide PLAN LAST UPDATED header?";
if (schema.name === "hide_empty_columns") return "Hide empty columns?";
if (schema.name === "battery_capacity") return "Battery Capacity";
if (schema.name === "color_help_text") return "Row colour override settings";
if (schema.name === "color_help_text_more") return "Override the HEX (e.g, #AA0000) colour values of the rows";
if (schema.name === "light_mode") return "Card Light Mode";
if (schema.name === "odd_row_colour") return "Dark Row Colour (odd)";
if (schema.name === "odd_row_colour_light") return "Light Row Colour (odd)";
if (schema.name === "even_row_colour") return "Dark Row Colour (even)";
if (schema.name === "even_row_colour_light") return "Light Row Colour (even)";
if (schema.name === "debug_prices_only") return "Show Debug Prices Only?";
if (schema.name === "weather_entity") return "Weather Entity";
if (schema.name === "path_for_click") return "Dashboard Path for click";
if (schema.name === "reset_day_totals") return "Reset Total Cost at midnight?";
return undefined;
},
computeHelper: (schema) => {
switch (schema.name) {
case "entity":
return "Usually set to \"predbat.plan_html\"";
case "fill_empty_cells":
return "This setting fills the column with an icon to fill any empty space";
case "stack_pills":
return "Only works when old_skool mode is disabled in style settings";
case "show_plan_totals":
return "Show a new row of plan total values for each supported column";
case "show_day_totals":
return "Show a new row of day total values for each supported column";
case "use_friendly_states":
return "Attempts to make the STATE column more understandable";
case "old_skool":
return "Applies the style to the entire table card, aka old_skool setting. This setting always wins and overrides settings below.";
case "old_skool_columns":
return "Warning: This setting is overridden by the old_skool setting above. Turn that off if you want to set specific columns";
case "help_text":
return "some helpful text";
case "table_width":
return "Set the overall table width as a percentage.";
case "font_size":
return "Adjust the font size used in the table.";
case "row_limit":
return "Min: 1, Max: 400";
case "show_predbat_version":
return "Displays the Predbat version at the bottom of the table. Click to Upgrade (if available)";
case "show_tablecard_version":
return "Displays the Predbat Table Card version at the bottom of the table. Click to Upgrade (if available)";
case "hide_last_update":
return "Hides the Plan Last Updated text at the top of the plan";
case "hide_empty_columns":
return "Hide columns where there are no values for the entire plan";
case "battery_capacity":
return "Shows the kWh capacity of your battery in the SoC column";
case "debug_columns":
return "Choose which columns reflect the HTML Debug Settings when enabled in Predbat";
case "debug_prices_only":
return "If you have enabled Predbat's HTML Plan debug, set to true to only show the adjusted prices, rather than the default (actual and adjusted prices). Important: Only works if HTML Plan debug is enabled";
case "weather_entity":
return "Add a weather forecast entity to see the weather for each time slot. Must add weather-column or temp-column to columns to see weather";
case "path_for_click":
return "Add a dashboard path like /my-dashboard/predbat-plan to be navigated to when you click the plan";
case "reset_day_totals":
return "Resets the total-column at midnight to £0.00 and increments by cost-column";
}
return undefined;
},
};
}
static getStubConfig() {
return {
"entity": "predbat.plan_html",
"columns": [
"time-column",
"import-column",
"export-column",
"state-column",
"limit-column",
"pv-column",
"load-column",
"soc-column",
"cost-column",
"total-column"
],
"table_width": 100,
"fill_empty_cells": true
}
}
static get properties() {
return {
_config: {},
_hass: {},
};
}
constructor() {
super();
//this.attachShadow({ mode: 'open' });
this.forecast = [];
this.unsubscribe = null;
this._renderErrorMessage = null;
}
renderError(message) {
const errorCard = document.createElement("hui-error-card");
errorCard.setConfig({
type: "error",
error: message,
origConfig: this.config,
});
this.innerHTML = "";
this.appendChild(errorCard);
this.content = null;
this._renderErrorMessage = message;
}
// Whenever the state changes, a new `hass` object is set. Use this to
// update your content.
set hass(hass) {
// Initialize the content if it's not there yet.
if (!this.content) {
this.innerHTML = `
<ha-card>
<div class="card-content" id="predbat-card-content"></div>
</ha-card>
`;
this.content = this.querySelector("div");
}
const oldHass = this._hass;
this._hass = hass;
const entityId = this.config?.entity;
if (!entityId) {
this.renderError("Predbat HTML entity is not set in the card configuration.");
return;
}
const currentEntityState = hass.states?.[entityId];
if (!currentEntityState) {
this.renderError(`Predbat HTML entity "${entityId}" is not available. Hit REFRESH when it is...`);
return;
}
if (currentEntityState.state === "unavailable") {
this.renderError("Predbat HTML entity is not currently available. Hit REFRESH when it is...");
return;
}
const hadError = this._renderErrorMessage !== null;
this._renderErrorMessage = null;
const switchEntityId = this.config.car_charge_switch; // optional
let prefix = this.config.entity.match(/^[^.]+/)[0];
if(prefix === "sensor")
prefix = "predbat";
const predbatActiveEntityId = `switch.${prefix}_active`;
if(oldHass === undefined){
// Render html on the first load
if (!this.initialized && this.config.weather_entity) {
this.weatherEntityId = this.config.weather_entity;
const state = hass.states[this.weatherEntityId];
const stateStr = state ? state.state : "unavailable";
if (stateStr === "unavailable") {
throw new Error("Weather entity seems to be incorrect or not available");
} else {
this.subscribeForecast();
this.initialized = true;
}
}
this._lastOnText = null;
this.processAndRender(hass);
} else {
const oldEntityUpdateTime = oldHass.states?.[entityId]?.last_updated;
const newEntityUpdateTime = hass.states?.[entityId]?.last_updated;
let carSwitchChanged = false;
let activeSwitchChanged = false;
let manualForceChanged = false;
if (predbatActiveEntityId && hass.states[predbatActiveEntityId] && oldHass.states[predbatActiveEntityId]) {
const oldActive = oldHass.states[predbatActiveEntityId];
const newActive = hass.states[predbatActiveEntityId];
activeSwitchChanged = oldActive.last_updated !== newActive.last_updated;
// If we just transitioned ON -> OFF, compute duration immediately
if (activeSwitchChanged && oldActive.state === 'on' && newActive.state === 'off') {
const start = new Date(oldActive.last_changed); // when it turned ON
const end = new Date(newActive.last_changed); // when it turned OFF
const ms = end - start;
this._lastOnText = ms > 0 ? formatDuration(ms) : '—';
}
}
if (switchEntityId && hass.states[switchEntityId] && oldHass.states[switchEntityId]) {
const oldSwitchTime = oldHass.states[switchEntityId].last_updated;
const newSwitchTime = hass.states[switchEntityId].last_updated;
carSwitchChanged = oldSwitchTime !== newSwitchTime;
}
const forceEntityObjects = this.getOverrideEntities();
for (const forceEntity of forceEntityObjects) {
// forceEntity.entityName
const oldForce = oldHass.states[forceEntity.entityName].state;
const newForce = hass.states[forceEntity.entityName].state;
manualForceChanged = oldForce !== newForce;
if (manualForceChanged){
//console.log("MANUAL FORCE CHANGED " + oldForce + " - " + newForce);
break;
}
}
if (hadError || oldEntityUpdateTime !== newEntityUpdateTime || carSwitchChanged || activeSwitchChanged || manualForceChanged) {
this.processAndRender(hass);
}
}
}
async subscribeForecast() {
if (this.unsubscribe || !this._hass) return;
try {
this.unsubscribe = await this._hass.connection.subscribeMessage(
(event) => {
this.forecast = event.forecast || [];
//console.log(`[${new Date().toLocaleTimeString()}] FORECAST READY FOR RENDER`);
//console.log(this.forecast);
this.processAndRender(this._hass);
},
{
type: 'weather/subscribe_forecast',
entity_id: this.weatherEntityId,
forecast_type: 'hourly' // or 'hourly'
}
);
} catch (e) {
console.error('Failed to subscribe to forecast:', e);
}
}
async disconnectedCallback() {
if (this.unsubscribe) {
await this.unsubscribe();
this.unsubscribe = null;
}
}
async processAndRender(hass){
let prefix = this.config.entity.match(/^[^.]+/)[0];
if(prefix === "sensor")
prefix = "predbat";
const predbatActiveEntityId = `switch.${prefix}_active`;
if(this._lastOnText === null){
const history = await fetchEntityHistory(this._hass, predbatActiveEntityId, 1);
const lastRun = getLastCompletedOnRun(history);
if (lastRun) {
this._lastOnText = formatDuration(lastRun.ms);
} else {
this._lastOnText = '—';
}
}
console.log(`[${new Date().toLocaleTimeString()}] PROCESS AND RENDER TABLE`);
console.log(this._lastOnText);
const entityId = this.config.entity;
const state = hass.states?.[entityId];
if (!state) {
this.renderError(`Predbat HTML entity "${entityId}" is not currently available. REFRESH when it is...`);
return;
}
const stateStr = state.state;
if (stateStr === "unavailable") {
this.renderError("Predbat HTML entity is not currently available. Hit REFRESH when it is...");
return;
}
let columnsToReturn = this.config.columns;
let rawHTML = hass.states[entityId].attributes.html;
const dataArray = this.getArrayDataFromHTML(rawHTML, hass.themes.darkMode);
//const dataArray = this.getArrayDataFromRaw(hass.states[entityId].attributes.raw, hass.themes.darkMode);
//filter out any columns not in the data
columnsToReturn = columnsToReturn.filter(column => {
if (column === "options-column" || column === "options-popup-column") return true;
return dataArray[0][column] !== undefined;
});
let theTable = document.createElement('table');
theTable.setAttribute('id', 'predbat-table');
theTable.setAttribute('cellpadding', '0px');
let newTableHead = document.createElement('thead');
// set out the data rows
let newTableBody = document.createElement('tbody');
let overallTotal = {};
let dayTotal = {};
let dayTotalCost = 0;
const columnsWithTotals = ["load-column", "pv-column", "car-column", "iboost-column", "net-power-column",
"cost-column", "total-column", "clip-column", "co2kwh-column", "co2kg-column", "xload-column", "limit-column"];
// before we display the rows, lets drop any that the user doesnt want.
if(this.config.row_limit && this.config.row_limit > 0)
dataArray.length = this.config.row_limit;
const useRefactor = true;
// iterate through the data
dataArray.forEach((item, index) => {
let newRow = document.createElement('tr');
let isMidnight = false;
let currentCost;
columnsToReturn.forEach((column, columnIndex) => { // Use arrow function here
if(item[column] !== undefined){
//console.log(column + " " + item[column]);
if(item["time-column"].value.includes("23:30"))
isMidnight = true;
let newColumn;
if(useRefactor)
newColumn = this.getCellTransformationRefactor(item[column], column, hass.themes.darkMode, index, item["time-column"]);
newRow.appendChild(newColumn);
if(column === "cost-column"){
currentCost = parseFloat(item[column].value);
if (isNaN(currentCost)) currentCost = 0;
}
if(columnsWithTotals.includes(column)){
if(column === "total-column"){
let currentTotal = parseFloat(item[column].value.replace(/[^0-9.\-]/g, ""));
if (isNaN(currentTotal)) currentTotal = 0;
overallTotal[column] = (currentTotal*100)+currentCost;
if(isMidnight){
overallTotal[column] = (overallTotal[column] || 0) + (currentTotal*100);
dayTotal[column] = (currentTotal*100)+currentCost;
}
} else {
let val = parseFloat(item[column].value.replace(/[⚊↘↗→p☀]/g, ''));
if (isNaN(val)) val = 0;
overallTotal[column] = (overallTotal[column] || 0) + val;
dayTotal[column] = (dayTotal[column] || 0) + val;
}
}
} else {
if(column === "options-column" || column === "options-popup-column"){
let newColumn;
if(useRefactor)
newColumn = this.getCellTransformationRefactor(item[column], column, hass.themes.darkMode, index, item["time-column"]);
newRow.appendChild(newColumn);
}
}
});
newTableBody.appendChild(newRow);
if(isMidnight){
for (let i = 0; i < 2; i++) {
newTableBody.appendChild(this.createDividerRows(columnsToReturn.length, hass.themes.darkMode));
}
if(this.config.show_day_totals === true) {
// Now insert a row for the day total
let dayTotalsRow = document.createElement('tr');
dayTotalsRow.classList.add('dayTotalRow');
columnsToReturn.forEach((column, index) => {
let totalCell = document.createElement('td');
if(columnsWithTotals.includes(column) && column !== 'limit-column'){
let returnTotal;
if(column === "cost-column" || column === "total-column"){
let formattedCost = "";
if (dayTotal[column] < 0) {
formattedCost = `-£${(Math.abs(dayTotal[column]) / 100).toFixed(2)}`;
totalCell.style.color = "var(--success-color)";
} else {
formattedCost = `£${(dayTotal[column] / 100).toFixed(2)}`;
totalCell.style.color = "var(--error-color)";
}
returnTotal = `<b>${formattedCost}</b>`;
} else
returnTotal = `<b>${dayTotal[column].toFixed(2)}</b>`;
totalCell.innerHTML = returnTotal;
}
if(column === "time-column" && index === 0)
totalCell.innerHTML = `<b>TOTALS</b>`;
dayTotalsRow.appendChild(totalCell);
});
newTableBody.appendChild(dayTotalsRow);
for (let i = 0; i < 2; i++) {
newTableBody.appendChild(this.createDividerRows(columnsToReturn.length, hass.themes.darkMode));
}
}
}
});
// Create total rows if in the config
if(this.config.show_totals === true || this.config.show_plan_totals === true) {
let totalsRow = document.createElement('tr');
totalsRow.classList.add('totalRow');
columnsToReturn.forEach((column, index) => {
let totalCell = document.createElement('td');
if(column === "time-column" && index === 0)
totalCell.innerHTML = `<b>PLAN TOTALS</b>`;
if(columnsWithTotals.includes(column) && column !== 'limit-column'){
let returnTotal;
if(column === "cost-column" || column === "total-column"){
if(column === "total-column" && dayTotal[column])
overallTotal[column] = overallTotal[column] + dayTotal[column];
let formattedCost = "";
if (overallTotal[column] < 0) {
formattedCost = `-£${(Math.abs(overallTotal[column]) / 100).toFixed(2)}`;
} else {
formattedCost = `£${(overallTotal[column] / 100).toFixed(2)}`;
}
returnTotal = `<b>${formattedCost}</b>`;
} else
returnTotal = `<b>${overallTotal[column].toFixed(2)}</b>`;
totalCell.innerHTML = returnTotal;
}
totalsRow.appendChild(totalCell);
});
newTableBody.appendChild(totalsRow);
}
let newHeaderRow = document.createElement('tr');
newTableHead.classList.add('topHeader');
//create the header rows
columnsToReturn.forEach((column, index) => {
//console.log(column + " - " + dataArray[0][column])
let newColumn = document.createElement('th');
newColumn.innerHTML = this.getColumnDescription(column);
newHeaderRow.appendChild(newColumn);
});
newTableHead.appendChild(newHeaderRow);
// This section of code is hiding any columns if they have no value (and the user has set them as a column to return)
if(this.config.hide_empty_columns === true){
let indexesToRemove = [];
columnsToReturn.forEach((column, index) => {
if(columnsWithTotals.includes(column) && overallTotal[column] === 0)
indexesToRemove.push(columnsToReturn.indexOf(column));
});
if(indexesToRemove.length > 0) {
for (let row of newTableHead.rows) {
// Hide the cell in the specified column
indexesToRemove.forEach((columnIndex, index) => {
if (row.cells[columnIndex]) {
row.cells[columnIndex].style.display = "none";
}
});
}
for (let row of newTableBody.rows) {
// Hide the cell in the specified column
indexesToRemove.forEach((columnIndex, index) => {
if (row.cells[columnIndex]) {
row.cells[columnIndex].style.display = "none";
}
});
}
}
}
// If path_for_click config is added, show a pointer on hover over of table, and click to navigate to new view.
if(this.config.path_for_click && this.config.path_for_click.length > 0){
theTable.style.cursor = 'pointer';
theTable.addEventListener("click", () => {
this.navigateToPath(this.config.path_for_click); // Replace with your actual path
});
}
theTable.appendChild(newTableHead);
theTable.appendChild(newTableBody);
this.content.innerHTML = ""; // Clear existing content
if(this.config.hide_last_update !== true) {
const lastUpdated = state ? state.last_updated : "Unavailable";
const time = this.getLastUpdatedFromHTML(lastUpdated);
if (time !== undefined){
let lastUpdateHeaderDiv = document.createElement('div');
lastUpdateHeaderDiv.classList.add('lastUpdateRow');
lastUpdateHeaderDiv.innerHTML = `<b>Plan Last Updated:</b> ${time}. Duration: ${this._lastOnText}`;
if(hass.states[predbatActiveEntityId].state === "on"){
//console.log("Switch: " + hass.states['switch.predbat_active'].state);
lastUpdateHeaderDiv.innerHTML += `<ha-icon class="icon-spin" icon="mdi:loading" style="--mdc-icon-size: 18px; margin-left: 4px;" title="Generating next plan"></ha-icon>`;
}
this.content.appendChild(lastUpdateHeaderDiv);
}
}
this.content.appendChild(theTable); // Add actual DOM node (preserves listeners)
if(this.config.show_predbat_version === true)
this.content.appendChild(this.createVersionLabelsForFooter(`update.${prefix}_version`,"Predbat Version", this));
if(this.config.show_tablecard_version === true)
this.content.appendChild(this.createVersionLabelsForFooter("update.predbat_table_card_update","Predbat Table Card Version", this));
const styleTag = document.createElement('style');
styleTag.innerHTML = this.getStyles(this.getLightMode(hass.themes.darkMode));
this.content.appendChild(styleTag);
}
createVersionLabelsForFooter(entity, label, cardContext){
const version = this._hass.states[entity].attributes.installed_version;
const latestVersion = this._hass.states[entity].attributes.latest_version;
let lastUpdateHeaderDiv = document.createElement('div');
lastUpdateHeaderDiv.classList.add('versionRow');
let updateIcon = ``;
let updateText = ``;
if(version !== latestVersion){
updateIcon = `<ha-icon icon="mdi:download-circle-outline" style="color: var(--primary-color); --mdc-icon-size: 18px; margin-left: 4px;" title="Predbat Table Card version ${latestVersion} available"></ha-icon>`;
updateText = `<span style="color: var(--primary-color);"><b>${latestVersion} available</b></span>`;
lastUpdateHeaderDiv.style.cursor = "pointer";
lastUpdateHeaderDiv.addEventListener('click', () => {
const event = new CustomEvent('hass-more-info', {
bubbles: true,
composed: true,
detail: { entityId: entity }
});
cardContext.dispatchEvent(event);
});
}
lastUpdateHeaderDiv.innerHTML = `<b>${label}:</b> ${version}${updateIcon} ${updateText}`;
return lastUpdateHeaderDiv;
}
navigateToPath(path) {
window.history.pushState(null, "", path);
const event = new CustomEvent("location-changed", {
bubbles: true,
composed: true,
});
window.dispatchEvent(event);
}
createDividerRows(columnLength, darkMode){
let dividerRow = document.createElement('tr');
dividerRow.classList.add('daySplitter');
for(let j = 0; j < columnLength; j++) {
let newCell = document.createElement('td');
if(this.getLightMode(darkMode)){
newCell.style.backgroundColor = "#e1e1e1";
newCell.style.opacity = 0.4;
} else {
// light mode
newCell.style.backgroundColor = "var(--primary-color)";
newCell.style.opacity = 1.00;
}
newCell.style.height = "1px";
dividerRow.appendChild(newCell);
}
return dividerRow;
}
getLightMode(hassDarkMode){
let lightMode = "auto";
let cssLightMode;
//set the light mode if the YAML is present
if(this.config.light_mode !== undefined)
lightMode = this.config.light_mode;
switch (lightMode) {
case "dark":
cssLightMode = true;
break;
case "light":
cssLightMode = false;
break;
default:
cssLightMode = hassDarkMode;
}
return cssLightMode;
}
// The height of your card. Home Assistant uses this to automatically
// distribute all cards over the available columns.
getCardSize() {
return 3;
}
isVersionGreater(a, b) {
const pa = a.replace(/^v/, '').split('.').map(Number);
const pb = b.replace(/^v/, '').split('.').map(Number);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const na = pa[i] || 0;
const nb = pb[i] || 0;
if (na > nb) return true;
if (na < nb) return false;
}
return false; // equal
}
getTimeframeForOverride(timeString) {
let prefix = this.config.entity.match(/^[^.]+/)[0];
if(prefix === "sensor")
prefix = "predbat";
const predBatVersion =
this._hass.states[`update.${prefix}_version`].attributes.installed_version;
// Match either "Wed 08:05" or "08:05"
const match = timeString.match(/^(?:(\w{3})\s)?(\d{2}):(\d{2})$/);
if (!match) return null;
const day = match[1] || null;
let hours = parseInt(match[2], 10);