myio-js-library 0.1.578 → 0.1.579

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.
package/dist/index.cjs CHANGED
@@ -86,6 +86,7 @@ __export(src_exports, {
86
86
  DEFAULT_ANNOTATION_SORT: () => DEFAULT_SORT,
87
87
  DEFAULT_BAS_SETTINGS: () => DEFAULT_BAS_SETTINGS,
88
88
  DEFAULT_CLAMP_RANGE: () => DEFAULT_CLAMP_RANGE,
89
+ DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES: () => DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
89
90
  DEFAULT_DASHBOARD_KPIS: () => DEFAULT_DASHBOARD_KPIS,
90
91
  DEFAULT_DAYS_WEEK: () => DEFAULT_DAYS_WEEK,
91
92
  DEFAULT_DEVICE_CLASSIFICATION_PROFILE: () => DEFAULT_DEVICE_CLASSIFICATION_PROFILE,
@@ -491,6 +492,7 @@ __export(src_exports, {
491
492
  createHeaderShoppingComponent: () => createHeaderShoppingComponent,
492
493
  createHttpDeviceCategoryPort: () => createHttpDeviceCategoryPort,
493
494
  createImgGallery: () => createImgGallery,
495
+ createIngestionTemperatureAggregateFetcher: () => createIngestionTemperatureAggregateFetcher,
494
496
  createInputDateRangePickerInsideDIV: () => createInputDateRangePickerInsideDIV,
495
497
  createLibraryVersionChecker: () => createLibraryVersionChecker,
496
498
  createLoadingSpinner: () => createLoadingSpinner,
@@ -912,6 +914,7 @@ __export(src_exports, {
912
914
  resolveBudget: () => resolveBudget,
913
915
  resolveCategory: () => resolveCategory,
914
916
  resolveClassification: () => resolveClassification,
917
+ resolveCurrentTemperature: () => resolveCurrentTemperature,
915
918
  resolveEffectiveDisplayMode: () => resolveEffectiveDisplayMode,
916
919
  resolveGoalAmount: () => resolveGoalAmount,
917
920
  resolveGroup: () => resolveGroup,
@@ -986,7 +989,7 @@ module.exports = __toCommonJS(src_exports);
986
989
  // package.json
987
990
  var package_default = {
988
991
  name: "myio-js-library",
989
- version: "0.1.578",
992
+ version: "0.1.579",
990
993
  description: "A clean, standalone JS SDK for MYIO projects",
991
994
  license: "MIT",
992
995
  repository: "github:gh-myio/myio-js-library",
@@ -1159,8 +1162,8 @@ function formatNumberReadable(value, locale = "pt-BR", minimumFractionDigits = 2
1159
1162
  if (!Number.isFinite(n)) {
1160
1163
  return "-";
1161
1164
  }
1162
- const safe = Object.is(n, -0) ? 0 : n;
1163
- return safe.toLocaleString(locale, {
1165
+ const safe2 = Object.is(n, -0) ? 0 : n;
1166
+ return safe2.toLocaleString(locale, {
1164
1167
  minimumFractionDigits,
1165
1168
  maximumFractionDigits
1166
1169
  });
@@ -3194,8 +3197,8 @@ function guardFormula(value) {
3194
3197
  return /^[=+\-@\t\r]/.test(value) ? `'${value}` : value;
3195
3198
  }
3196
3199
  function csvCell(value) {
3197
- const safe = guardFormula(value);
3198
- return /[";\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
3200
+ const safe2 = guardFormula(value);
3201
+ return /[";\r\n]/.test(safe2) ? `"${safe2.replace(/"/g, '""')}"` : safe2;
3199
3202
  }
3200
3203
  function toCSV2(matrix) {
3201
3204
  const lines = [matrix.header, ...matrix.rows].map((cells) => cells.map(csvCell).join(";"));
@@ -14894,19 +14897,35 @@ function interpolateTemperature(data, options) {
14894
14897
  return result;
14895
14898
  }
14896
14899
  function aggregateByHour(data, clampRange = DEFAULT_CLAMP_RANGE, offset = DEFAULT_TEMPERATURE_OFFSET) {
14897
- const HOUR = 60 * 60 * 1e3;
14900
+ return aggregateByMinutes(data, 60, clampRange, offset);
14901
+ }
14902
+ function aggregateByMinutes(data, minutes, clampRange = DEFAULT_CLAMP_RANGE, offset = DEFAULT_TEMPERATURE_OFFSET) {
14903
+ const size = Math.max(1, Math.round(minutes)) * 60 * 1e3;
14898
14904
  const buckets = /* @__PURE__ */ new Map();
14899
14905
  for (const item of data) {
14900
14906
  const ts = Number(item.ts);
14901
14907
  if (!Number.isFinite(ts)) continue;
14902
- const hour = Math.floor(ts / HOUR) * HOUR;
14903
- const b = buckets.get(hour) || { sum: 0, n: 0 };
14908
+ const start = Math.floor(ts / size) * size;
14909
+ const b = buckets.get(start) || { sum: 0, n: 0 };
14904
14910
  b.sum += clampTemperature(item.value, clampRange, offset);
14905
14911
  b.n += 1;
14906
- buckets.set(hour, b);
14912
+ buckets.set(start, b);
14907
14913
  }
14908
14914
  return [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([ts, b]) => ({ ts, value: b.sum / b.n }));
14909
14915
  }
14916
+ function buildDayTicks(minTs, maxTs, timezone, maxTicks = 8) {
14917
+ if (!Number.isFinite(minTs) || !Number.isFinite(maxTs) || maxTs < minTs) return [];
14918
+ const DAY = 24 * 60 * 60 * 1e3;
14919
+ const days = [];
14920
+ let t = getStartOfDay(new Date(minTs), timezone);
14921
+ if (t < minTs) t = getStartOfDay(new Date(t + DAY + 2 * 60 * 60 * 1e3), timezone);
14922
+ for (let guard = 0; t <= maxTs && guard < 2e3; guard++) {
14923
+ days.push(t);
14924
+ t = getStartOfDay(new Date(t + DAY + 2 * 60 * 60 * 1e3), timezone);
14925
+ }
14926
+ const step = Math.max(1, Math.ceil(days.length / Math.max(1, maxTicks)));
14927
+ return days.filter((_, i) => i % step === 0);
14928
+ }
14910
14929
  function aggregateByDay(data, clampRange = DEFAULT_CLAMP_RANGE, offset = DEFAULT_TEMPERATURE_OFFSET) {
14911
14930
  if (data.length === 0) {
14912
14931
  return [];
@@ -87594,7 +87613,109 @@ ${state6.year}-03-15T08,15`)}">${esc6(state6.csv)}</textarea>
87594
87613
  return instance;
87595
87614
  }
87596
87615
 
87616
+ // src/components/temperature/currentTemperature.ts
87617
+ var DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES = 120;
87618
+ async function safe(fn) {
87619
+ if (!fn) return null;
87620
+ try {
87621
+ const r = await fn();
87622
+ return r && Number.isFinite(r.ts) && Number.isFinite(r.value) ? r : null;
87623
+ } catch (err) {
87624
+ console.warn("[TemperatureModal] Falha ao buscar a \xFAltima leitura:", err?.message || err);
87625
+ return null;
87626
+ }
87627
+ }
87628
+ async function resolveCurrentTemperature(opts) {
87629
+ const now = opts.now ?? Date.now();
87630
+ const maxAge = opts.maxAgeMinutes ?? DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES;
87631
+ const ok = (r) => !!r && (!opts.isValid || opts.isValid(r.value));
87632
+ const wrap = (r, source) => {
87633
+ const ageMinutes = Math.max(0, (now - r.ts) / 6e4);
87634
+ return { ...r, source, ageMinutes, fresh: ageMinutes <= maxAge };
87635
+ };
87636
+ const tb = await safe(opts.fetchThingsboardLatest);
87637
+ if (tb && ok(tb) && (now - tb.ts) / 6e4 <= maxAge) return wrap(tb, "thingsboard");
87638
+ const ing = await safe(opts.fetchIngestionLatest);
87639
+ if (ing && ok(ing)) return wrap(ing, "ingestion");
87640
+ if (tb && ok(tb)) return wrap(tb, "thingsboard");
87641
+ return null;
87642
+ }
87643
+ async function fetchThingsboardLatestTemperature(token, deviceId) {
87644
+ const res = await fetch(`/api/plugins/telemetry/DEVICE/${deviceId}/values/timeseries?keys=temperature`, {
87645
+ headers: { "X-Authorization": `Bearer ${token}`, "Content-Type": "application/json" }
87646
+ });
87647
+ if (!res.ok) throw new Error(`ThingsBoard ${res.status}`);
87648
+ const json = await res.json();
87649
+ const p = json?.temperature?.[0];
87650
+ if (!p) return null;
87651
+ const value = Number(p.value);
87652
+ const ts = Number(p.ts);
87653
+ return Number.isFinite(value) && Number.isFinite(ts) ? { ts, value } : null;
87654
+ }
87655
+ var INGESTION_LATEST_WINDOWS = [
87656
+ { days: 1, intervalMinutes: 15 },
87657
+ { days: 7, intervalMinutes: 60 },
87658
+ { days: 90, intervalMinutes: 60 }
87659
+ ];
87660
+ async function fetchIngestionLatestTemperature(aggregateFetcher, now = Date.now(), windows = INGESTION_LATEST_WINDOWS, isValid) {
87661
+ for (const w of windows) {
87662
+ const points = await aggregateFetcher(now - w.days * 24 * 60 * 60 * 1e3, now, w.intervalMinutes);
87663
+ const valid = (points || []).map((p) => ({ ts: Number(p.ts), value: Number(p.value) })).filter((p) => Number.isFinite(p.ts) && Number.isFinite(p.value) && (!isValid || isValid(p.value)));
87664
+ if (valid.length) {
87665
+ const last = valid.reduce((a, b) => b.ts > a.ts ? b : a);
87666
+ return { ts: Math.min(now, last.ts + w.intervalMinutes * 60 * 1e3), value: last.value };
87667
+ }
87668
+ }
87669
+ return null;
87670
+ }
87671
+ function makeTemperatureValidator(clampRange, offset) {
87672
+ const off = Number(offset) || 0;
87673
+ return (value) => {
87674
+ const v = Number(value) + off;
87675
+ return Number.isFinite(v) && v >= clampRange.min && v <= clampRange.max;
87676
+ };
87677
+ }
87678
+ function createIngestionTemperatureAggregateFetcher(cfg) {
87679
+ const tz = cfg.timezone || "America/Sao_Paulo";
87680
+ const doFetch = cfg.fetchImpl || ((...a) => fetch(...a));
87681
+ const base = String(cfg.apiHost || "").replace(/\/+$/, "");
87682
+ return async (startTs, endTs, intervalMinutes) => {
87683
+ const interval = intervalMinutes >= 60 && intervalMinutes % 60 === 0 ? `${intervalMinutes / 60} hour` : `${Math.max(15, Math.round(intervalMinutes))} minutes`;
87684
+ const url = new URL(`${base}/temperature-readings/aggregate`);
87685
+ url.searchParams.set("gatewayId", String(cfg.gatewayId));
87686
+ url.searchParams.set("slaveId", String(cfg.slaveId));
87687
+ url.searchParams.set("startTs", new Date(startTs).toISOString());
87688
+ url.searchParams.set("endTs", new Date(endTs).toISOString());
87689
+ url.searchParams.set("interval", interval);
87690
+ url.searchParams.set("timezone", tz);
87691
+ let token = null;
87692
+ try {
87693
+ token = cfg.getToken ? await cfg.getToken() : null;
87694
+ } catch {
87695
+ token = null;
87696
+ }
87697
+ const res = await doFetch(url.toString(), token ? { headers: { Authorization: `Bearer ${token}` } } : void 0);
87698
+ if (!res.ok) throw new Error(`Ingestion aggregate ${res.status}`);
87699
+ const rows = await res.json();
87700
+ return (Array.isArray(rows) ? rows : []).map((r) => ({
87701
+ ts: new Date(String(r.bucket)).getTime(),
87702
+ value: Number(r.avg_temperature)
87703
+ })).filter((p) => Number.isFinite(p.ts) && Number.isFinite(p.value)).sort((a, b) => a.ts - b.ts);
87704
+ };
87705
+ }
87706
+
87597
87707
  // src/components/temperature/TemperatureModal.ts
87708
+ var GRANULARITY_MINUTES = {
87709
+ "15min": 15,
87710
+ "30min": 30,
87711
+ hour: 60
87712
+ };
87713
+ var GRANULARITY_LABEL = {
87714
+ "15min": "15 minutos",
87715
+ "30min": "30 minutos",
87716
+ hour: "Hora",
87717
+ day: "Dia (m\xE9dia)"
87718
+ };
87598
87719
  var _footers = /* @__PURE__ */ new Map();
87599
87720
  function escHtml3(s) {
87600
87721
  return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -87641,6 +87762,10 @@ async function openTemperatureModal(params) {
87641
87762
  selectedPeriods: ["madrugada", "manha", "tarde", "noite"],
87642
87763
  // All periods selected by default
87643
87764
  dataFetcher: params.dataFetcher ?? null,
87765
+ aggregateFetcher: params.aggregateFetcher ?? null,
87766
+ dataMode: "",
87767
+ currentMaxAgeMinutes: Number(params.currentTemperatureMaxAgeMinutes) > 0 ? Number(params.currentTemperatureMaxAgeMinutes) : DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
87768
+ current: null,
87644
87769
  deviceName: params.deviceName || "",
87645
87770
  customerName: resolveCustomerName(params.customerName),
87646
87771
  accent: resolveAccent(
@@ -87652,18 +87777,15 @@ async function openTemperatureModal(params) {
87652
87777
  }
87653
87778
  const savedGranularity = localStorage.getItem("myio-temp-modal-granularity");
87654
87779
  const savedTheme = localStorage.getItem("myio-temp-modal-theme");
87655
- if (savedGranularity) state6.granularity = savedGranularity;
87780
+ if (savedGranularity && savedGranularity in GRANULARITY_LABEL) state6.granularity = savedGranularity;
87781
+ if (!isGranularityAvailable(state6, state6.granularity)) state6.granularity = "hour";
87656
87782
  if (savedTheme && !params.theme) state6.theme = savedTheme;
87657
87783
  const modalContainer = document.createElement("div");
87658
87784
  modalContainer.id = modalId;
87659
87785
  document.body.appendChild(modalContainer);
87660
87786
  renderModal3(modalContainer, state6, modalId);
87661
87787
  try {
87662
- state6.data = discardInvalid(
87663
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
87664
- state6
87665
- );
87666
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87788
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87667
87789
  state6.isLoading = false;
87668
87790
  renderModal3(modalContainer, state6, modalId);
87669
87791
  drawChart2(modalId, state6);
@@ -87683,15 +87805,11 @@ async function openTemperatureModal(params) {
87683
87805
  updateData: async (startDate, endDate, granularity) => {
87684
87806
  state6.startTs = new Date(startDate).getTime();
87685
87807
  state6.endTs = new Date(endDate).getTime();
87686
- if (granularity) state6.granularity = granularity;
87808
+ if (granularity && isGranularityAvailable(state6, granularity)) state6.granularity = granularity;
87687
87809
  state6.isLoading = true;
87688
87810
  renderModal3(modalContainer, state6, modalId);
87689
87811
  try {
87690
- state6.data = discardInvalid(
87691
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
87692
- state6
87693
- );
87694
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87812
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87695
87813
  state6.isLoading = false;
87696
87814
  renderModal3(modalContainer, state6, modalId);
87697
87815
  drawChart2(modalId, state6);
@@ -87703,12 +87821,75 @@ async function openTemperatureModal(params) {
87703
87821
  }
87704
87822
  };
87705
87823
  }
87824
+ function isGranularityAvailable(state6, g) {
87825
+ const m = GRANULARITY_MINUTES[g];
87826
+ if (!m || m >= 60) return true;
87827
+ return !!state6.aggregateFetcher || !state6.dataFetcher;
87828
+ }
87829
+ function dataModeFor(state6) {
87830
+ const m = GRANULARITY_MINUTES[state6.granularity];
87831
+ return m && m < 60 && state6.aggregateFetcher ? `agg:${m}` : "raw";
87832
+ }
87833
+ async function loadSeries(state6) {
87834
+ const mode = dataModeFor(state6);
87835
+ const raw = mode !== "raw" && state6.aggregateFetcher ? await state6.aggregateFetcher(state6.startTs, state6.endTs, Number(mode.slice(4))) : await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs));
87836
+ state6.data = discardInvalid(raw || [], state6);
87837
+ state6.dataMode = mode;
87838
+ state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87839
+ }
87840
+ async function refreshCurrent(state6) {
87841
+ try {
87842
+ const isValid = makeTemperatureValidator(state6.clampRange, state6.temperatureOffset);
87843
+ const latestSource = state6.aggregateFetcher ?? (state6.dataFetcher ? (s, e) => state6.dataFetcher(s, e) : null);
87844
+ state6.current = await resolveCurrentTemperature({
87845
+ maxAgeMinutes: state6.currentMaxAgeMinutes,
87846
+ isValid,
87847
+ fetchThingsboardLatest: state6.token && state6.deviceId ? () => fetchThingsboardLatestTemperature(state6.token, state6.deviceId) : void 0,
87848
+ fetchIngestionLatest: latestSource ? () => fetchIngestionLatestTemperature(latestSource, Date.now(), void 0, isValid) : void 0
87849
+ });
87850
+ } catch (err) {
87851
+ console.warn("[TemperatureModal] Temperatura atual indispon\xEDvel:", err);
87852
+ state6.current = null;
87853
+ }
87854
+ }
87855
+ function currentStatus(state6, value) {
87856
+ if (value === null) return state6.temperatureStatus;
87857
+ if (state6.temperatureMin === null || state6.temperatureMax === null) return state6.temperatureStatus;
87858
+ return value > state6.temperatureMax ? "above" : value < state6.temperatureMin ? "below" : "ok";
87859
+ }
87860
+ function displayedCurrent(state6) {
87861
+ if (state6.current) return state6.current.value + (Number(state6.temperatureOffset) || 0);
87862
+ return state6.currentTemperature;
87863
+ }
87864
+ function currentSourceText(state6) {
87865
+ const c = state6.current;
87866
+ if (!c) return "";
87867
+ const src = c.source === "thingsboard" ? "ThingsBoard" : "Ingestion";
87868
+ if (c.fresh) {
87869
+ const m = Math.round(c.ageMinutes);
87870
+ const age = m < 1 ? "agora" : m < 60 ? `h\xE1 ${m} min` : `h\xE1 ${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}`;
87871
+ return `${src} \xB7 ${age}`;
87872
+ }
87873
+ const when = new Date(c.ts).toLocaleString(state6.locale, {
87874
+ day: "2-digit",
87875
+ month: "2-digit",
87876
+ year: "numeric",
87877
+ hour: "2-digit",
87878
+ minute: "2-digit",
87879
+ timeZone: state6.timezone || "America/Sao_Paulo"
87880
+ });
87881
+ return `\xDAltima leitura ${when} (${src})`;
87882
+ }
87706
87883
  function renderModal3(container, state6, modalId, error) {
87707
87884
  const colors2 = getThemeColors(state6.theme);
87708
87885
  const startDateStr = new Date(state6.startTs).toLocaleDateString(state6.locale);
87709
87886
  const endDateStr = new Date(state6.endTs).toLocaleDateString(state6.locale);
87710
- const statusText = state6.temperatureStatus === "ok" ? "Dentro da faixa" : state6.temperatureStatus === "above" ? "Acima do limite" : state6.temperatureStatus === "below" ? "Abaixo do limite" : "N/A";
87711
- const statusColor = state6.temperatureStatus === "ok" ? colors2.success : state6.temperatureStatus === "above" ? colors2.danger : state6.temperatureStatus === "below" ? colors2.primary : colors2.textMuted;
87887
+ const currentValue = displayedCurrent(state6);
87888
+ const status = currentStatus(state6, state6.current ? currentValue : null);
87889
+ const staleCurrent = !!state6.current && !state6.current.fresh;
87890
+ const statusText = (status === "ok" ? "Dentro da faixa" : status === "above" ? "Acima do limite" : status === "below" ? "Abaixo do limite" : "N/A") + (staleCurrent ? " (leitura antiga)" : "");
87891
+ const statusColor = staleCurrent ? colors2.textMuted : status === "ok" ? colors2.success : status === "above" ? colors2.danger : status === "below" ? colors2.primary : colors2.textMuted;
87892
+ const currentSource = currentSourceText(state6);
87712
87893
  const rangeText = state6.temperatureMin !== null && state6.temperatureMax !== null ? `${state6.temperatureMin}\xB0C - ${state6.temperatureMax}\xB0C` : "N\xE3o definida";
87713
87894
  const startDateInput = new Date(state6.startTs).toISOString().slice(0, 16);
87714
87895
  const endDateInput = new Date(state6.endTs).toISOString().slice(0, 16);
@@ -87767,8 +87948,10 @@ function renderModal3(container, state6, modalId, error) {
87767
87948
  font-size: 14px; color: ${colors2.text}; background: ${colors2.surface};
87768
87949
  cursor: pointer; min-width: 130px;
87769
87950
  ">
87770
- <option value="hour" ${state6.granularity === "hour" ? "selected" : ""}>Hora</option>
87771
- <option value="day" ${state6.granularity === "day" ? "selected" : ""}>Dia (m\xE9dia)</option>
87951
+ ${Object.keys(GRANULARITY_LABEL).map((g) => {
87952
+ const ok = isGranularityAvailable(state6, g);
87953
+ return `<option value="${g}" ${state6.granularity === g ? "selected" : ""} ${ok ? "" : 'disabled title="Indispon\xEDvel para esta fonte de dados"'}>${GRANULARITY_LABEL[g]}</option>`;
87954
+ }).join("")}
87772
87955
  </select>
87773
87956
  </div>
87774
87957
  <!-- Day Period Filter (Multiselect) -->
@@ -87856,9 +88039,10 @@ function renderModal3(container, state6, modalId, error) {
87856
88039
  ">
87857
88040
  <span style="color: ${colors2.textMuted}; font-size: 12px; font-weight: 500;">Temperatura Atual</span>
87858
88041
  <div style="font-weight: 700; font-size: 24px; color: ${statusColor}; margin-top: 4px;">
87859
- ${state6.currentTemperature !== null ? formatTemperature(state6.currentTemperature) : "N/A"}
88042
+ ${currentValue !== null ? formatTemperature(currentValue) : "N/A"}
87860
88043
  </div>
87861
88044
  <div style="font-size: 11px; color: ${statusColor}; margin-top: 2px;">${statusText}</div>
88045
+ ${currentSource ? `<div style="font-size: 10px; color: ${colors2.textMuted}; margin-top: 2px;">${escHtml3(currentSource)}</div>` : ""}
87862
88046
  </div>
87863
88047
  <!-- Average -->
87864
88048
  <div style="
@@ -87978,9 +88162,10 @@ function drawChart2(modalId, state6) {
87978
88162
  return;
87979
88163
  }
87980
88164
  let chartData;
87981
- if (state6.granularity === "hour") {
87982
- const hourly = aggregateByHour(filteredData, state6.clampRange, state6.temperatureOffset);
87983
- chartData = hourly.map((item) => ({
88165
+ const windowMinutes = GRANULARITY_MINUTES[state6.granularity];
88166
+ if (windowMinutes) {
88167
+ const series = aggregateByMinutes(filteredData, windowMinutes, state6.clampRange, state6.temperatureOffset);
88168
+ chartData = series.map((item) => ({
87984
88169
  x: item.ts,
87985
88170
  y: Number(item.value),
87986
88171
  screenX: 0,
@@ -88080,33 +88265,16 @@ function drawChart2(modalId, state6) {
88080
88265
  ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 8, y + 4);
88081
88266
  }
88082
88267
  ctx.textAlign = "center";
88083
- const numLabels = Math.min(8, chartData.length);
88084
- const labelInterval = Math.max(1, Math.floor(chartData.length / numLabels));
88085
- const xSpan = chartData.length > 1 ? chartData[chartData.length - 1].x - chartData[0].x : 0;
88086
- const multiDay = state6.granularity === "hour" && xSpan > 24 * 60 * 60 * 1e3;
88087
- for (let i = 0; i < chartData.length; i += labelInterval) {
88088
- const point = chartData[i];
88089
- const date = new Date(point.x);
88090
- let label;
88091
- let subLabel = "";
88092
- if (state6.granularity === "hour") {
88093
- label = date.toLocaleTimeString(state6.locale, { hour: "2-digit", minute: "2-digit" });
88094
- if (multiDay) {
88095
- subLabel = label;
88096
- label = date.toLocaleDateString(state6.locale, { day: "2-digit", month: "2-digit" });
88097
- }
88098
- } else {
88099
- label = date.toLocaleDateString(state6.locale, { day: "2-digit", month: "2-digit" });
88100
- }
88268
+ const tz = state6.timezone || "America/Sao_Paulo";
88269
+ for (const tick of buildXAxisTicks(chartData, state6.granularity, tz, state6.locale, isPeriodsFiltered, paddingLeft, chartWidth)) {
88101
88270
  ctx.strokeStyle = colors2.chartGrid;
88102
88271
  ctx.lineWidth = 1;
88103
88272
  ctx.beginPath();
88104
- ctx.moveTo(point.screenX, paddingTop);
88105
- ctx.lineTo(point.screenX, height - paddingBottom);
88273
+ ctx.moveTo(tick.screenX, paddingTop);
88274
+ ctx.lineTo(tick.screenX, height - paddingBottom);
88106
88275
  ctx.stroke();
88107
88276
  ctx.fillStyle = colors2.textMuted;
88108
- ctx.fillText(label, point.screenX, height - paddingBottom + 18);
88109
- if (subLabel) ctx.fillText(subLabel, point.screenX, height - paddingBottom + 31);
88277
+ ctx.fillText(tick.label, tick.screenX, height - paddingBottom + 18);
88110
88278
  }
88111
88279
  ctx.strokeStyle = colors2.border;
88112
88280
  ctx.lineWidth = 1;
@@ -88117,6 +88285,41 @@ function drawChart2(modalId, state6) {
88117
88285
  ctx.stroke();
88118
88286
  setupChartTooltip2(canvas, chartContainer, chartData, state6, colors2);
88119
88287
  }
88288
+ function buildXAxisTicks(chartData, granularity, timezone, locale, indexBased, paddingLeft, chartWidth) {
88289
+ if (!chartData.length) return [];
88290
+ const minX = chartData[0].x;
88291
+ const maxX = chartData[chartData.length - 1].x;
88292
+ const dayLabel = (ts) => new Date(ts).toLocaleDateString(locale, { day: "2-digit", month: "2-digit", timeZone: timezone });
88293
+ if (maxX - minX > 24 * 60 * 60 * 1e3) {
88294
+ const range = maxX - minX || 1;
88295
+ const out2 = [];
88296
+ const seen = /* @__PURE__ */ new Set();
88297
+ for (const ts of buildDayTicks(minX, maxX, timezone, 8)) {
88298
+ let screenX;
88299
+ if (indexBased) {
88300
+ const p = chartData.find((d) => d.x >= ts);
88301
+ if (!p) continue;
88302
+ screenX = p.screenX;
88303
+ } else {
88304
+ screenX = paddingLeft + (ts - minX) / range * chartWidth;
88305
+ }
88306
+ const key = Math.round(screenX);
88307
+ if (seen.has(key)) continue;
88308
+ seen.add(key);
88309
+ out2.push({ screenX, label: dayLabel(ts), ts });
88310
+ }
88311
+ return out2;
88312
+ }
88313
+ const numLabels = Math.min(8, chartData.length);
88314
+ const interval = Math.max(1, Math.floor(chartData.length / numLabels));
88315
+ const out = [];
88316
+ for (let i = 0; i < chartData.length; i += interval) {
88317
+ const p = chartData[i];
88318
+ const label = granularity === "day" ? dayLabel(p.x) : new Date(p.x).toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", timeZone: timezone });
88319
+ out.push({ screenX: p.screenX, label, ts: p.x });
88320
+ }
88321
+ return out;
88322
+ }
88120
88323
  function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88121
88324
  const existingTooltip = container.querySelector(".myio-chart-tooltip");
88122
88325
  if (existingTooltip) existingTooltip.remove();
@@ -88161,7 +88364,7 @@ function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88161
88364
  if (point) {
88162
88365
  const date = new Date(point.x);
88163
88366
  let dateStr;
88164
- if (state6.granularity === "hour") {
88367
+ if (state6.granularity !== "day") {
88165
88368
  dateStr = date.toLocaleDateString(state6.locale, {
88166
88369
  day: "2-digit",
88167
88370
  month: "2-digit",
@@ -88304,9 +88507,28 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88304
88507
  }
88305
88508
  if (state6.data.length > 0) drawChart2(modalId, state6);
88306
88509
  });
88307
- document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
88308
- state6.granularity = e.target.value;
88510
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", async (e) => {
88511
+ const next = e.target.value;
88512
+ if (!isGranularityAvailable(state6, next)) return;
88513
+ state6.granularity = next;
88309
88514
  localStorage.setItem("myio-temp-modal-granularity", state6.granularity);
88515
+ if (dataModeFor(state6) !== state6.dataMode) {
88516
+ state6.isLoading = true;
88517
+ state6.dateRangePicker = null;
88518
+ renderModal3(container, state6, modalId);
88519
+ try {
88520
+ await loadSeries(state6);
88521
+ state6.isLoading = false;
88522
+ renderModal3(container, state6, modalId);
88523
+ drawChart2(modalId, state6);
88524
+ } catch (error) {
88525
+ console.error("[TemperatureModal] Error fetching data:", error);
88526
+ state6.isLoading = false;
88527
+ renderModal3(container, state6, modalId, error);
88528
+ }
88529
+ await setupEventListeners3(container, state6, modalId, onClose);
88530
+ return;
88531
+ }
88310
88532
  if (state6.data.length > 0) drawChart2(modalId, state6);
88311
88533
  });
88312
88534
  document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
@@ -88318,11 +88540,7 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88318
88540
  state6.dateRangePicker = null;
88319
88541
  renderModal3(container, state6, modalId);
88320
88542
  try {
88321
- state6.data = discardInvalid(
88322
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
88323
- state6
88324
- );
88325
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
88543
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
88326
88544
  state6.isLoading = false;
88327
88545
  renderModal3(container, state6, modalId);
88328
88546
  drawChart2(modalId, state6);
@@ -88362,21 +88580,26 @@ function exportCsv(state6) {
88362
88580
  ...state6.deviceName ? [["Dispositivo (TB)", state6.deviceName]] : [],
88363
88581
  ...state6.customerName ? [["Cliente", state6.customerName]] : [],
88364
88582
  ["Per\xEDodo", `${fmtD(state6.startTs)} \u2014 ${fmtD(state6.endTs)}`],
88365
- ["Granularidade", state6.granularity === "hour" ? "Hora (m\xE9dia da hora fechada)" : "Dia (m\xE9dia do dia)"],
88583
+ [
88584
+ "Granularidade",
88585
+ state6.granularity === "day" ? "Dia (m\xE9dia do dia)" : `${GRANULARITY_LABEL[state6.granularity]} (m\xE9dia da janela fechada)`
88586
+ ],
88366
88587
  ["Per\xEDodos do dia", getSelectedPeriodsLabel(state6.selectedPeriods)],
88367
88588
  ...off !== 0 ? [["Offset aplicado (\xB0C)", n2(off)]] : [],
88368
88589
  ["Gerado em", (/* @__PURE__ */ new Date()).toLocaleString("pt-BR")],
88369
88590
  [],
88370
- ["Temperatura atual (\xB0C)", state6.currentTemperature !== null ? n2(state6.currentTemperature) : "N/A"],
88591
+ ["Temperatura atual (\xB0C)", displayedCurrent(state6) !== null ? n2(displayedCurrent(state6)) : "N/A"],
88592
+ ...state6.current ? [["Origem da temperatura atual", currentSourceText(state6)]] : [],
88371
88593
  ["M\xE9dia do per\xEDodo (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.avg) : "N/A"],
88372
88594
  ["M\xEDnima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.min) : "N/A"],
88373
88595
  ["M\xE1xima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.max) : "N/A"],
88374
88596
  ["Leituras", String(state6.stats.count)],
88375
88597
  []
88376
88598
  ];
88377
- if (state6.granularity === "hour") {
88599
+ const csvMinutes = GRANULARITY_MINUTES[state6.granularity];
88600
+ if (csvMinutes) {
88378
88601
  lines.push(["Data/Hora", "Temperatura (\xB0C)"]);
88379
- aggregateByHour(filtered, state6.clampRange, off).forEach((p) => lines.push([dt(p.ts), n2(Number(p.value))]));
88602
+ aggregateByMinutes(filtered, csvMinutes, state6.clampRange, off).forEach((p) => lines.push([dt(p.ts), n2(Number(p.value))]));
88380
88603
  } else {
88381
88604
  lines.push(["Dia", "M\xE9dia (\xB0C)", "M\xEDn (\xB0C)", "M\xE1x (\xB0C)", "Leituras"]);
88382
88605
  aggregateByDay(filtered, state6.clampRange, off).forEach(
@@ -88388,7 +88611,8 @@ function exportCsv(state6) {
88388
88611
  const url = URL.createObjectURL(blob);
88389
88612
  const a = document.createElement("a");
88390
88613
  a.href = url;
88391
- a.download = `temperatura_${state6.label.replace(/\s+/g, "_")}_${state6.granularity === "hour" ? "1h" : "1d"}_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
88614
+ const suffix = { "15min": "15min", "30min": "30min", hour: "1h", day: "1d" }[state6.granularity];
88615
+ a.download = `temperatura_${state6.label.replace(/\s+/g, "_")}_${suffix}_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
88392
88616
  document.body.appendChild(a);
88393
88617
  a.click();
88394
88618
  document.body.removeChild(a);
@@ -144391,8 +144615,8 @@ var TelemetryInfoShoppingView = class _TelemetryInfoShoppingView {
144391
144615
  // consistently (ported from v-5.2.0 TELEMETRY_INFO where (i) is on practically every metric).
144392
144616
  tooltipSpan(tooltip) {
144393
144617
  if (!tooltip) return "";
144394
- const safe = String(tooltip).replace(/"/g, "&quot;");
144395
- return `<span class="tis-tooltip" title="${safe}">\u2139\uFE0F</span>`;
144618
+ const safe2 = String(tooltip).replace(/"/g, "&quot;");
144619
+ return `<span class="tis-tooltip" title="${safe2}">\u2139\uFE0F</span>`;
144396
144620
  }
144397
144621
  buildWaterCards() {
144398
144622
  const config2 = WATER_CATEGORY_CONFIG;
@@ -159082,9 +159306,9 @@ var FancoilRemoteController = class {
159082
159306
  });
159083
159307
  }
159084
159308
  async handlePowerToggle() {
159085
- const currentStatus = this.state.status;
159086
- if (currentStatus === "offline") return;
159087
- const newStatus = currentStatus === "on" ? "off" : "on";
159309
+ const currentStatus2 = this.state.status;
159310
+ if (currentStatus2 === "offline") return;
159311
+ const newStatus = currentStatus2 === "on" ? "off" : "on";
159088
159312
  const actionText = newStatus === "on" ? "LIGAR" : "DESLIGAR";
159089
159313
  if (this.onConfirmAction) {
159090
159314
  const confirmed = await this.onConfirmAction(
@@ -159101,7 +159325,7 @@ var FancoilRemoteController = class {
159101
159325
  }
159102
159326
  if (this.onPowerToggle) {
159103
159327
  try {
159104
- const success = await this.onPowerToggle(currentStatus);
159328
+ const success = await this.onPowerToggle(currentStatus2);
159105
159329
  if (success) {
159106
159330
  this.state.status = newStatus;
159107
159331
  this.view.updateState({ status: newStatus });
@@ -166169,8 +166393,8 @@ var OnOffDeviceModalView = class {
166169
166393
  deviceName: this.device.label || this.device.name || "Dispositivo",
166170
166394
  relatedDevices: []
166171
166395
  },
166172
- onToggle: async (currentStatus) => {
166173
- const newState = currentStatus !== "on";
166396
+ onToggle: async (currentStatus2) => {
166397
+ const newState = currentStatus2 !== "on";
166174
166398
  this.onDeviceToggle(newState);
166175
166399
  return true;
166176
166400
  }
@@ -180252,6 +180476,7 @@ var version = package_default.version || "0.0.0";
180252
180476
  DEFAULT_ANNOTATION_SORT,
180253
180477
  DEFAULT_BAS_SETTINGS,
180254
180478
  DEFAULT_CLAMP_RANGE,
180479
+ DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
180255
180480
  DEFAULT_DASHBOARD_KPIS,
180256
180481
  DEFAULT_DAYS_WEEK,
180257
180482
  DEFAULT_DEVICE_CLASSIFICATION_PROFILE,
@@ -180657,6 +180882,7 @@ var version = package_default.version || "0.0.0";
180657
180882
  createHeaderShoppingComponent,
180658
180883
  createHttpDeviceCategoryPort,
180659
180884
  createImgGallery,
180885
+ createIngestionTemperatureAggregateFetcher,
180660
180886
  createInputDateRangePickerInsideDIV,
180661
180887
  createLibraryVersionChecker,
180662
180888
  createLoadingSpinner,
@@ -181078,6 +181304,7 @@ var version = package_default.version || "0.0.0";
181078
181304
  resolveBudget,
181079
181305
  resolveCategory,
181080
181306
  resolveClassification,
181307
+ resolveCurrentTemperature,
181081
181308
  resolveEffectiveDisplayMode,
181082
181309
  resolveGoalAmount,
181083
181310
  resolveGroup,