node-red-contrib-octopus-intelligent 1.0.5 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,34 @@
1
- const axios = require("axios");
1
+ const https = require("https");
2
+
3
+ function graphqlPost(body, token) {
4
+ return new Promise((resolve, reject) => {
5
+ const payload = JSON.stringify(body);
6
+ const headers = {
7
+ "Content-Type": "application/json",
8
+ "Content-Length": Buffer.byteLength(payload)
9
+ };
10
+ if (token) headers["Authorization"] = token;
11
+ const req = https.request({
12
+ hostname: "api.octopus.energy",
13
+ path: "/v1/graphql/",
14
+ method: "POST",
15
+ headers
16
+ }, (res) => {
17
+ let raw = "";
18
+ res.on("data", chunk => raw += chunk);
19
+ res.on("end", () => {
20
+ try {
21
+ resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
22
+ } catch (e) {
23
+ reject(new Error("Failed to parse API response: " + e.message));
24
+ }
25
+ });
26
+ });
27
+ req.on("error", reject);
28
+ req.write(payload);
29
+ req.end();
30
+ });
31
+ }
2
32
 
3
33
  module.exports = function (RED) {
4
34
  function OctopusIntelligentNode(config) {
@@ -10,6 +40,7 @@ module.exports = function (RED) {
10
40
  const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
11
41
  const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
12
42
  const enableMqtt = config.enableMqtt;
43
+ node.timezoneOverride = config.timezoneOverride || "";
13
44
 
14
45
  // MQTT Topics
15
46
  this.broker = RED.nodes.getNode(config.broker);
@@ -22,6 +53,7 @@ module.exports = function (RED) {
22
53
  const cmdTopicTime = `nodered_octopus/${account}/set_time`;
23
54
  const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
24
55
  const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
56
+ const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
25
57
 
26
58
  // 2. Constants & Validation
27
59
  const TIME_OPTIONS = [
@@ -70,9 +102,80 @@ module.exports = function (RED) {
70
102
  { id: "slot3_start_raw", name: "Slot 3 Start (Raw)", icon: "mdi:timer-outline", val: "slot3_start_raw" },
71
103
  { id: "slot3_end_raw", name: "Slot 3 End (Raw)", icon: "mdi:timer-outline", val: "slot3_end_raw" },
72
104
  { id: "window_start_raw", name: "Overall Window Start (Raw)", icon: "mdi:timer-play", val: "window_start_raw" },
73
- { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" }
105
+ { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" },
106
+ // v1.1.0: Locale timestamp sensors (plain string — already human-readable local time, no device_class)
107
+ { id: "next_charge_locale", name: "Next Charge Time (Locale)", icon: "mdi:timer", val: "next_start_locale" },
108
+ { id: "slot1_start_locale", name: "Slot 1 Start (Locale)", icon: "mdi:timer-outline", val: "slot1_start_locale" },
109
+ { id: "slot1_end_locale", name: "Slot 1 End (Locale)", icon: "mdi:timer-outline", val: "slot1_end_locale" },
110
+ { id: "slot2_start_locale", name: "Slot 2 Start (Locale)", icon: "mdi:timer-outline", val: "slot2_start_locale" },
111
+ { id: "slot2_end_locale", name: "Slot 2 End (Locale)", icon: "mdi:timer-outline", val: "slot2_end_locale" },
112
+ { id: "slot3_start_locale", name: "Slot 3 Start (Locale)", icon: "mdi:timer-outline", val: "slot3_start_locale" },
113
+ { id: "slot3_end_locale", name: "Slot 3 End (Locale)", icon: "mdi:timer-outline", val: "slot3_end_locale" },
114
+ { id: "window_start_locale", name: "Overall Window Start (Locale)", icon: "mdi:timer-play", val: "window_start_locale" },
115
+ { id: "window_end_locale", name: "Overall Window End (Locale)", icon: "mdi:timer-stop", val: "window_end_locale" },
116
+ // v1.1.0: Timezone diagnostic sensors
117
+ { id: "timezone_detected", name: "Timezone Detected", icon: "mdi:earth", val: "timezone_detected" },
118
+ { id: "timezone_applied", name: "Timezone Applied", icon: "mdi:earth-plus", val: "timezone_applied" }
74
119
  ];
75
120
 
121
+ // 3. Timezone Helpers
122
+ function convertToTimezone(dateStr, tz) {
123
+ if (!dateStr || typeof dateStr !== 'string') return dateStr;
124
+ try {
125
+ const date = new Date(dateStr.replace(' ', 'T'));
126
+ if (isNaN(date.getTime())) return dateStr;
127
+
128
+ const parts = new Intl.DateTimeFormat('en-CA', {
129
+ timeZone: tz,
130
+ year: 'numeric', month: '2-digit', day: '2-digit',
131
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
132
+ hour12: false, hourCycle: 'h23'
133
+ }).formatToParts(date);
134
+
135
+ const get = (type) => (parts.find(p => p.type === type) || {}).value || '00';
136
+ const y = get('year');
137
+ const mo = get('month');
138
+ const d = get('day');
139
+ const h = get('hour');
140
+ const mi = get('minute');
141
+ const s = get('second');
142
+
143
+ const localAsUtc = Date.UTC(
144
+ parseInt(y, 10), parseInt(mo, 10) - 1, parseInt(d, 10),
145
+ parseInt(h, 10), parseInt(mi, 10), parseInt(s, 10)
146
+ );
147
+ const offsetMins = Math.round((localAsUtc - date.getTime()) / 60000);
148
+ const sign = offsetMins >= 0 ? '+' : '-';
149
+ const absMin = Math.abs(offsetMins);
150
+ const offsetStr = `${sign}${String(Math.floor(absMin / 60)).padStart(2, '0')}:${String(absMin % 60).padStart(2, '0')}`;
151
+
152
+ return `${y}-${mo}-${d} ${h}:${mi}:${s}${offsetStr}`;
153
+ } catch (e) {
154
+ node.warn(`Invalid timezone: ${tz}, falling back to auto-detected`);
155
+ return dateStr;
156
+ }
157
+ }
158
+
159
+ function resolveTimezone(nd) {
160
+ try {
161
+ const persisted = nd.context().get('timezone');
162
+ if (persisted && typeof persisted === 'string' && persisted.trim().length > 0) {
163
+ return persisted.trim();
164
+ }
165
+ } catch (e) {}
166
+
167
+ const override = nd.timezoneOverride;
168
+ if (override && typeof override === 'string' && override.trim().length > 0) {
169
+ return override.trim();
170
+ }
171
+
172
+ try {
173
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
174
+ } catch (e) {
175
+ return 'UTC';
176
+ }
177
+ }
178
+
76
179
  // 4. Helper: Announce Controls (Write-Enabled)
77
180
  function announceControls() {
78
181
  if (!enableMqtt || !node.broker) return;
@@ -187,21 +290,46 @@ module.exports = function (RED) {
187
290
  if (sensor.unit) payload.unit_of_measurement = sensor.unit;
188
291
  if (sensor.icon) payload.icon = sensor.icon;
189
292
 
190
- // Mark raw sensors, refresh timestamp, and API metrics as diagnostic (moves to Diagnostics section)
293
+ // Mark raw sensors, refresh timestamp, API metrics, and timezone diagnostics as diagnostic
191
294
  if (sensor.id.includes('_raw') ||
192
295
  sensor.id === 'refresh_available_at' ||
193
- sensor.id.startsWith('api_')) {
296
+ sensor.id.startsWith('api_') ||
297
+ sensor.id.startsWith('timezone_')) {
194
298
  payload.entity_category = "diagnostic";
195
299
  }
196
300
 
197
301
  node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
198
302
  });
199
303
 
304
+ // I. Timezone Select Entity
305
+ const TIMEZONE_OPTIONS = [
306
+ "Europe/London", "Europe/Berlin", "Europe/Madrid",
307
+ "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
308
+ "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
309
+ "America/New_York", "America/Chicago", "America/Denver",
310
+ "America/Los_Angeles", "Asia/Tokyo", "UTC"
311
+ ];
312
+ node.broker.client.publish(
313
+ `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
314
+ JSON.stringify({
315
+ name: "Timezone",
316
+ unique_id: `${uniqueIdPrefix}_timezone`,
317
+ options: TIMEZONE_OPTIONS,
318
+ command_topic: cmdTopicTimezone,
319
+ state_topic: `${stateTopic}/timezone`,
320
+ icon: "mdi:earth",
321
+ entity_category: "config",
322
+ device: device
323
+ }),
324
+ { retain: true }
325
+ );
326
+
200
327
  // Subscribe to Commands
201
328
  node.broker.client.subscribe(cmdTopicLimit);
202
329
  node.broker.client.subscribe(cmdTopicTime);
203
330
  node.broker.client.subscribe(cmdTopicSubmit);
204
331
  node.broker.client.subscribe(cmdTopicRefresh);
332
+ node.broker.client.subscribe(cmdTopicTimezone);
205
333
  }
206
334
 
207
335
  // 5. Helper: Set Preferences (The Mutation)
@@ -269,7 +397,7 @@ module.exports = function (RED) {
269
397
  node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
270
398
 
271
399
  // A. Get Token
272
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
400
+ const authResponse = await graphqlPost({
273
401
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
274
402
  variables: { input: { APIKey: apiKey } }
275
403
  });
@@ -299,10 +427,10 @@ module.exports = function (RED) {
299
427
  }
300
428
  };
301
429
 
302
- const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
430
+ const mutationResponse = await graphqlPost({
303
431
  query: mutation,
304
432
  variables: variables
305
- }, { headers: { Authorization: token } });
433
+ }, token);
306
434
 
307
435
  if (mutationResponse.data.errors) {
308
436
  throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
@@ -415,7 +543,7 @@ module.exports = function (RED) {
415
543
  variables: { input: { APIKey: apiKey } }
416
544
  };
417
545
 
418
- const authResponse = await axios.post(authRequest.url, {
546
+ const authResponse = await graphqlPost({
419
547
  query: authRequest.query,
420
548
  variables: authRequest.variables
421
549
  });
@@ -453,10 +581,10 @@ module.exports = function (RED) {
453
581
  vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
454
582
  }`;
455
583
 
456
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
584
+ const dataResponse = await graphqlPost({
457
585
  query: masterQuery,
458
586
  variables: { account: account }
459
- }, { headers: { Authorization: token } });
587
+ }, token);
460
588
 
461
589
  debugInfo.apiCalls.push({
462
590
  step: 2,
@@ -545,8 +673,10 @@ module.exports = function (RED) {
545
673
  const apiMetrics = getApiMetrics();
546
674
 
547
675
  // Build Payload
676
+ const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch(e) { return 'UTC'; } })();
677
+ const appliedTz = resolveTimezone(node);
548
678
  const statusPayload = {
549
- next_start: nextSlot ? nextSlot.startDt : null,
679
+ next_start: nextSlot ? convertToTimezone(nextSlot.startDt, appliedTz) : null,
550
680
  total_energy: parseFloat(totalEnergy.toFixed(2)),
551
681
  next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
552
682
  next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
@@ -567,16 +697,16 @@ module.exports = function (RED) {
567
697
  api_requests_hour: apiMetrics.requests_last_hour,
568
698
  api_complexity_hour: apiMetrics.complexity_last_hour,
569
699
  api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
570
- // Individual slots (first 3 active/future) - formatted timestamps
571
- slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
572
- slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
573
- slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
574
- slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
575
- slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
576
- slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
577
- // Overall window (first start to last end) - formatted timestamps
578
- window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
579
- window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
700
+ // Individual slots (first 3 active/future) — timezone-converted (appliedTz)
701
+ slot1_start: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
702
+ slot1_end: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, appliedTz) : null,
703
+ slot2_start: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, appliedTz) : null,
704
+ slot2_end: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, appliedTz) : null,
705
+ slot3_start: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, appliedTz) : null,
706
+ slot3_end: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, appliedTz) : null,
707
+ // Overall window (first start to last end) — timezone-converted (appliedTz)
708
+ window_start: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
709
+ window_end: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, appliedTz) : null,
580
710
  // Raw timestamp strings (exact API output)
581
711
  next_start_raw: nextSlot ? nextSlot.startDt : null,
582
712
  slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
@@ -586,7 +716,20 @@ module.exports = function (RED) {
586
716
  slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
587
717
  slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
588
718
  window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
589
- window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
719
+ window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
720
+ // Timezone metadata
721
+ timezone_detected: serverTz,
722
+ timezone_applied: appliedTz,
723
+ // Locale timestamps — always server auto-detected timezone (never overridden)
724
+ next_start_locale: nextSlot ? convertToTimezone(nextSlot.startDt, serverTz) : null,
725
+ slot1_start_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
726
+ slot1_end_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, serverTz) : null,
727
+ slot2_start_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, serverTz) : null,
728
+ slot2_end_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, serverTz) : null,
729
+ slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
730
+ slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
731
+ window_start_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
732
+ window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null
590
733
  };
591
734
 
592
735
  // Success!
@@ -713,7 +856,20 @@ module.exports = function (RED) {
713
856
  slot3_start_raw: null,
714
857
  slot3_end_raw: null,
715
858
  window_start_raw: null,
716
- window_end_raw: null
859
+ window_end_raw: null,
860
+ // Timezone metadata
861
+ timezone_detected: null,
862
+ timezone_applied: null,
863
+ // Locale timestamps
864
+ next_start_locale: null,
865
+ slot1_start_locale: null,
866
+ slot1_end_locale: null,
867
+ slot2_start_locale: null,
868
+ slot2_end_locale: null,
869
+ slot3_start_locale: null,
870
+ slot3_end_locale: null,
871
+ window_start_locale: null,
872
+ window_end_locale: null
717
873
  };
718
874
  }
719
875
 
@@ -892,7 +1048,7 @@ module.exports = function (RED) {
892
1048
  node.warn("Pre-validating slot data (30s before start)");
893
1049
  try {
894
1050
  // Fetch fresh data from API
895
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
1051
+ const authResponse = await graphqlPost({
896
1052
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
897
1053
  variables: { input: { APIKey: apiKey } }
898
1054
  });
@@ -903,10 +1059,10 @@ module.exports = function (RED) {
903
1059
 
904
1060
  const token = authResponse.data.data.obtainKrakenToken.token;
905
1061
 
906
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
1062
+ const dataResponse = await graphqlPost({
907
1063
  query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
908
1064
  variables: { account: account }
909
- }, { headers: { Authorization: token } });
1065
+ }, token);
910
1066
 
911
1067
  if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
912
1068
  cachedSlots = dataResponse.data.data.plannedDispatches;
@@ -1067,6 +1223,14 @@ module.exports = function (RED) {
1067
1223
  setPreferences(targetLimit, targetTime);
1068
1224
  return; // Don't run standard fetch if setting
1069
1225
  }
1226
+ if (msg.payload.set_timezone !== undefined) {
1227
+ const tz = msg.payload.set_timezone;
1228
+ if (typeof tz === 'string' && tz.trim().length > 0) {
1229
+ node.context().set('timezone', tz.trim());
1230
+ node.log(`Timezone set to: ${tz.trim()}`);
1231
+ }
1232
+ return;
1233
+ }
1070
1234
  }
1071
1235
 
1072
1236
  // Manual refresh request from Node-RED - NO rate limiting
@@ -1135,7 +1299,27 @@ module.exports = function (RED) {
1135
1299
  fetchData();
1136
1300
  });
1137
1301
 
1302
+ // Timezone select changed in Home Assistant
1303
+ node.broker.subscribe(cmdTopicTimezone, 0, (topic, payload) => {
1304
+ const tz = payload.toString().trim();
1305
+ if (tz.length > 0) {
1306
+ node.context().set('timezone', tz);
1307
+ node.log(`Timezone set via MQTT to: ${tz}`);
1308
+ node.broker.client.publish(`${stateTopic}/timezone`, tz, { retain: true });
1309
+ }
1310
+ });
1311
+
1138
1312
  setTimeout(announceControls, 2000);
1313
+
1314
+ // Republish persisted timezone to HA select on startup
1315
+ setTimeout(() => {
1316
+ try {
1317
+ const persistedTz = node.context().get('timezone');
1318
+ if (persistedTz && node.broker) {
1319
+ node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1320
+ }
1321
+ } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1322
+ }, 2500);
1139
1323
  }
1140
1324
 
1141
1325
  // Init
@@ -1154,7 +1338,7 @@ module.exports = function (RED) {
1154
1338
  clearTimeout(cooldownExpiryTimer);
1155
1339
  cooldownExpiryTimer = null;
1156
1340
  }
1157
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh);
1341
+ if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone);
1158
1342
  });
1159
1343
  }
1160
1344
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-octopus-intelligent",
3
- "version": "1.0.5",
3
+ "version": "1.1.1",
4
4
  "description": "Node-RED integration for Octopus Energy Intelligent Octopus Go with Home Assistant MQTT discovery",
5
5
  "main": "octopus-intelligent.js",
6
6
  "scripts": {
@@ -25,10 +25,7 @@
25
25
  "README.md",
26
26
  "CHANGELOG.md",
27
27
  "LICENSE",
28
- "examples/",
29
- "images/",
30
- "__tests__/",
31
- "test-mocks.js"
28
+ "examples/"
32
29
  ],
33
30
  "node-red": {
34
31
  "version": ">=2.0.0",
@@ -40,9 +37,7 @@
40
37
  "node": ">=14.0.0",
41
38
  "node-red": ">=2.0.0"
42
39
  },
43
- "dependencies": {
44
- "axios": "^1.6.0"
45
- },
40
+ "dependencies": {},
46
41
  "devDependencies": {
47
42
  "jest": "^29.7.0",
48
43
  "@types/jest": "^29.5.0"
@@ -1,220 +0,0 @@
1
- # Test Suite Documentation
2
-
3
- This directory contains unit tests for the Octopus Intelligent Node-RED node.
4
-
5
- ## Test Structure
6
-
7
- ```
8
- __tests__/
9
- ├── bugs.test.js # Bug regression tests
10
- ├── charging-timers.test.js # Timer management tests
11
- ├── data-processing.test.js # Data processing and payload construction tests
12
- ├── charging-now-validation.test.js # Charging state validation mode tests
13
- └── README.md # This file
14
- ```
15
-
16
- ## Running Tests
17
-
18
- ### Run All Tests
19
- ```bash
20
- npm test
21
- ```
22
-
23
- ### Run Tests in Watch Mode
24
- ```bash
25
- npm run test:watch
26
- ```
27
-
28
- ### Run Tests with Coverage
29
- ```bash
30
- npm run test:coverage
31
- ```
32
-
33
- ### Run Specific Test File
34
- ```bash
35
- npm test bugs.test.js
36
- npm test charging-timers.test.js
37
- npm test data-processing.test.js
38
- ```
39
-
40
- ### Run Specific Test Suite
41
- ```bash
42
- npm test -- -t "Bug #1"
43
- npm test -- -t "setupChargingTimers"
44
- ```
45
-
46
- ## Test Coverage
47
-
48
- ### Bug Regression Tests (`bugs.test.js`)
49
-
50
- Tests that prevent previously fixed bugs from reoccurring:
51
-
52
- **Bug #1: Charging Now Initialization State**
53
- - ✅ Active slot at initialization
54
- - ✅ No active slot at initialization
55
- - ✅ Slot ending during initialization
56
- - ✅ No premature state publish from announceControls()
57
-
58
- **Bug #2: Charging Now State Synchronization**
59
- - ✅ Slot cancelled between polls
60
- - ✅ New active slot added between polls
61
- - ✅ Regular polling during active slot
62
- - ✅ State published on every fetchData call
63
-
64
- ### Charging Timer Tests (`charging-timers.test.js`)
65
-
66
- Tests for timer management and charging state detection:
67
-
68
- **publishChargingState()**
69
- - ✅ Set chargingNow to true and publish ON
70
- - ✅ Set chargingNow to false and publish OFF
71
- - ✅ Handle MQTT disabled
72
- - ✅ Handle missing broker gracefully
73
-
74
- **clearChargingTimers()**
75
- - ✅ Clear all active timers
76
- - ✅ Handle clearing when no timers set
77
- - ✅ Clear only active timers
78
-
79
- **setupChargingTimers()**
80
- - ✅ Currently charging (active slot)
81
- - ✅ Future slot (not charging)
82
- - ✅ No slots (car not plugged in)
83
- - ✅ Multiple slots with first active
84
- - ✅ Slot just ended
85
- - ✅ Timer cleanup on re-run
86
-
87
- **Slot Filtering Logic**
88
- - ✅ Filter out past slots
89
- - ✅ Calculate total energy correctly
90
- - ✅ Calculate charging window correctly
91
-
92
- ### Data Processing Tests (`data-processing.test.js`)
93
-
94
- Tests for API response processing and payload construction:
95
-
96
- **buildDefaultPayload()**
97
- - ✅ Create default payload with current state
98
- - ✅ Preserve confirmed and pending state
99
-
100
- **Payload Construction from API**
101
- - ✅ Two future slots
102
- - ✅ Active slot (charging now)
103
- - ✅ No slots
104
- - ✅ Three slots
105
- - ✅ Past slots filtered out
106
- - ✅ Mixed past and future slots
107
- - ✅ Preferences extraction
108
- - ✅ Bump charge source detection
109
-
110
- ### Charging Now Validation Tests (`charging-now-validation.test.js`)
111
-
112
- Tests for charging state detection during validation mode (Issue #5):
113
-
114
- **setupChargingTimers() Direct Tests**
115
- - ✅ Active slot detection (chargingNow=true)
116
- - ✅ Future slot detection (chargingNow=false)
117
- - ✅ Slot boundary - start time (inclusive)
118
- - ✅ Slot boundary - end time (exclusive)
119
-
120
- **BEFORE FIX: Validation Mode Bug**
121
- - ✅ Demonstrates bug: validation mode skips setupChargingTimers()
122
- - ✅ Comparison: normal mode works correctly
123
-
124
- **AFTER FIX: Validation Mode Fixed**
125
- - ✅ Verifies fix: validation mode now updates charging state
126
- - ✅ Reconciliation loop NOT started in validation mode
127
- - ✅ Reconciliation loop IS started in normal mode (once)
128
-
129
- **User-Provided Real Data**
130
- - ⏭️ Placeholder for user's actual charging slot data
131
-
132
- ## Test Data
133
-
134
- Test mocks are defined in `/test-mocks.js`:
135
-
136
- - **mockAuthSuccess** - Successful authentication response
137
- - **mockDataWithSlots** - API response with 2 future slots
138
- - **mockDataWithActiveSlot** - API response with 1 active slot
139
- - **mockDataNoSlots** - API response with no slots
140
- - **mockDataWithThreeSlots** - API response with 3 slots
141
- - **expectedPayloadTwoSlots** - Expected Node-RED payload format
142
- - **expectedPayloadActiveSlot** - Expected payload with active slot
143
- - **expectedPayloadNoSlots** - Expected payload with no slots
144
-
145
- ## Test Utilities
146
-
147
- Helper functions for creating mocks:
148
-
149
- - `createMockAxios(responses)` - Mock axios HTTP client
150
- - `createMockBroker()` - Mock MQTT broker
151
- - `createMockNode()` - Mock Node-RED node
152
- - `generateMockDataWithActiveSlot()` - Generate data with currently active slot (NOW - 30min to NOW + 3.5hrs)
153
- - `generateMockDataWithFutureSlot()` - Generate data with future slot only (NOW + 2hrs to NOW + 6hrs)
154
-
155
- ## Coverage Goals
156
-
157
- - **Branches:** 80%+
158
- - **Functions:** 80%+
159
- - **Lines:** 80%+
160
- - **Statements:** 80%+
161
-
162
- ## Current Coverage Status
163
-
164
- Run `npm run test:coverage` to see current coverage metrics.
165
-
166
- ## Pending Tests
167
-
168
- The following tests are documented but not yet implemented (waiting for additional API response examples):
169
-
170
- - Authentication flow tests
171
- - Preference mutation tests
172
- - Error handling tests (invalid API key, rate limiting, etc.)
173
- - setPreferences() validation tests
174
- - Exponential backoff retry tests
175
-
176
- See `unit_test.md` for full test specifications.
177
-
178
- ## Test Principles
179
-
180
- 1. **Isolation** - Each test is independent and doesn't rely on others
181
- 2. **Determinism** - Tests use fake timers and mocked dates for consistency
182
- 3. **Clarity** - Test names clearly describe what is being tested
183
- 4. **Documentation** - JSDoc comments explain scenario, given, and expected
184
- 5. **Regression Prevention** - All fixed bugs have corresponding tests
185
-
186
- ## Debugging Tests
187
-
188
- ### View Test Output
189
- ```bash
190
- npm test -- --verbose
191
- ```
192
-
193
- ### Run Single Test
194
- ```bash
195
- npm test -- -t "should initialize with chargingNow=true when slot is active"
196
- ```
197
-
198
- ### Debug with Node Inspector
199
- ```bash
200
- node --inspect-brk node_modules/.bin/jest --runInBand
201
- ```
202
-
203
- Then open `chrome://inspect` in Chrome.
204
-
205
- ## Contributing
206
-
207
- When adding new features or fixing bugs:
208
-
209
- 1. Write a failing test first (TDD)
210
- 2. Implement the fix/feature
211
- 3. Verify the test passes
212
- 4. Update documentation if needed
213
- 5. Run full test suite before committing
214
-
215
- ## References
216
-
217
- - Jest Documentation: https://jestjs.io/
218
- - Test Mocks: `/test-mocks.js`
219
- - Bug Tracking: `/bugs.md`
220
- - Unit Test Plan: `/unit_test.md`