myio-js-library 0.1.577 → 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.577",
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 [];
@@ -66129,6 +66148,13 @@ var SettingsModalView = class _SettingsModalView {
66129
66148
  canEditIdentifier() {
66130
66149
  return this.isSuperAdmin() || this.config.holdingAdmin === true;
66131
66150
  }
66151
+ /**
66152
+ * Campos comerciais (ABL / Contrato / Segmento / Atividade): visíveis para todos,
66153
+ * editáveis só para admin — mesma regra do Identificador (superadmin ou holding admin).
66154
+ */
66155
+ canEditCommercial() {
66156
+ return this.canEditIdentifier();
66157
+ }
66132
66158
  isWellEquipmentDevice() {
66133
66159
  return ["CISTERNA", "CISTERNA_ENTRADA"].includes(String(this.config.deviceProfile || "").toUpperCase());
66134
66160
  }
@@ -66154,9 +66180,7 @@ var SettingsModalView = class _SettingsModalView {
66154
66180
  if (lastUpdatedEl) {
66155
66181
  lastUpdatedEl.textContent = formData.lastUpdatedTime ? this.formatTs(formData.lastUpdatedTime) : "\u2014";
66156
66182
  }
66157
- if (this.isSuperAdmin()) {
66158
- this.initCommercialFields(formData);
66159
- }
66183
+ this.initCommercialFields(formData);
66160
66184
  if (!this.config.gcdrDeviceId && formData.gcdrDeviceId) {
66161
66185
  this.config.gcdrDeviceId = formData.gcdrDeviceId;
66162
66186
  }
@@ -66586,7 +66610,7 @@ var SettingsModalView = class _SettingsModalView {
66586
66610
  cancelBtn.disabled = isLoading;
66587
66611
  }
66588
66612
  formInputs.forEach((input) => {
66589
- input.disabled = isLoading;
66613
+ input.disabled = isLoading || input.dataset.locked === "true";
66590
66614
  });
66591
66615
  }
66592
66616
  formatDomainLabel(domain) {
@@ -66876,7 +66900,7 @@ var SettingsModalView = class _SettingsModalView {
66876
66900
  </div>
66877
66901
 
66878
66902
  </div>
66879
- ${this.isSuperAdmin() ? this.getCommercialFieldsHTML() : ""}
66903
+ ${this.getCommercialFieldsHTML()}
66880
66904
  </div>
66881
66905
 
66882
66906
  <!-- Central/gateway identity+telemetry \u2014 only for CentralSettingsModal (isGateway);
@@ -66895,12 +66919,14 @@ var SettingsModalView = class _SettingsModalView {
66895
66919
  `;
66896
66920
  }
66897
66921
  /**
66898
- * Campos comerciais — só @myio / superadmin (o bloco nem é renderizado para os demais,
66899
- * então getFormData não envia essas chaves e o save não as sobrescreve).
66922
+ * Campos comerciais — visíveis para todos, editáveis só para admin (canEditCommercial).
66923
+ * Sem permissão: ABL/Contrato readonly (o FormData reenvia o valor carregado, sem mudança)
66924
+ * e selects disabled + data-locked (não entram no FormData → o save não toca segment/activity).
66900
66925
  * Linha 1: ABL + Contrato (texto). Linha 2: Segmento → Atividade (selects em cascata,
66901
66926
  * opções preenchidas em initCommercialFields após carregar o catálogo).
66902
66927
  */
66903
66928
  getCommercialFieldsHTML() {
66929
+ const ro = this.canEditCommercial() ? "" : " readonly";
66904
66930
  const customerName = String(
66905
66931
  this.config.customerName || window.MyIOUtils?.customerName || ""
66906
66932
  ).trim();
@@ -66911,11 +66937,11 @@ var SettingsModalView = class _SettingsModalView {
66911
66937
  <div class="commercial-grid">
66912
66938
  <div class="commercial-field">
66913
66939
  <label class="identity-field-label" for="abl">ABL</label>
66914
- <input type="text" id="abl" name="abl" class="identity-input" maxlength="50" placeholder="Ex.: 120,50 m\xB2">
66940
+ <input type="text" id="abl" name="abl" class="identity-input" maxlength="50" placeholder="${ro ? "\u2014" : "Ex.: 120,50 m\xB2"}"${ro}>
66915
66941
  </div>
66916
66942
  <div class="commercial-field">
66917
66943
  <label class="identity-field-label" for="contract">Contrato</label>
66918
- <input type="text" id="contract" name="contract" class="identity-input" maxlength="100" placeholder="N\xBA / identifica\xE7\xE3o do contrato">
66944
+ <input type="text" id="contract" name="contract" class="identity-input" maxlength="100" placeholder="${ro ? "\u2014" : "N\xBA / identifica\xE7\xE3o do contrato"}"${ro}>
66919
66945
  </div>
66920
66946
  <div class="commercial-field">
66921
66947
  <label class="identity-field-label" for="segment">Segmento</label>
@@ -66945,18 +66971,24 @@ var SettingsModalView = class _SettingsModalView {
66945
66971
  const savedActivity = String(saved.activity || "");
66946
66972
  const segments = catalog.map((s) => s.segment);
66947
66973
  if (savedSegment && !segments.includes(savedSegment)) segments.push(savedSegment);
66948
- segmentEl.innerHTML = options(segments, savedSegment, "Selecione\u2026");
66949
- segmentEl.disabled = false;
66974
+ const canEdit = this.canEditCommercial();
66975
+ segmentEl.innerHTML = options(segments, savedSegment, canEdit ? "Selecione\u2026" : "\u2014");
66976
+ segmentEl.disabled = !canEdit;
66950
66977
  const fillActivities = (segment, selected) => {
66951
66978
  if (!segment) {
66952
- activityEl.innerHTML = options([], "", "Selecione o segmento primeiro");
66979
+ activityEl.innerHTML = options([], "", canEdit ? "Selecione o segmento primeiro" : "\u2014");
66953
66980
  activityEl.disabled = true;
66954
66981
  return;
66955
66982
  }
66956
- activityEl.innerHTML = options(activitiesForSegment(catalog, segment, selected), selected, "Selecione\u2026");
66957
- activityEl.disabled = false;
66983
+ activityEl.innerHTML = options(activitiesForSegment(catalog, segment, selected), selected, canEdit ? "Selecione\u2026" : "\u2014");
66984
+ activityEl.disabled = !canEdit;
66958
66985
  };
66959
66986
  fillActivities(savedSegment, savedActivity);
66987
+ if (!canEdit) {
66988
+ segmentEl.dataset.locked = "true";
66989
+ activityEl.dataset.locked = "true";
66990
+ return;
66991
+ }
66960
66992
  segmentEl.addEventListener("change", () => fillActivities(segmentEl.value, ""));
66961
66993
  }
66962
66994
  /** RFC-0171: Offset de Temperatura — sempre visível para domain=temperature; editável só para @myio.com.br */
@@ -68642,7 +68674,7 @@ var SettingsModalView = class _SettingsModalView {
68642
68674
  cursor: default;
68643
68675
  }
68644
68676
 
68645
- /* Campos comerciais (s\xF3 @myio / superadmin) */
68677
+ /* Campos comerciais (vis\xEDveis para todos; edit\xE1veis s\xF3 para admin) */
68646
68678
  .commercial-block {
68647
68679
  margin-top: 14px;
68648
68680
  padding-top: 12px;
@@ -80207,7 +80239,7 @@ var DefaultSettingsFetcher = class _DefaultSettingsFetcher {
80207
80239
  "label",
80208
80240
  "floor",
80209
80241
  "identifier",
80210
- // Campos comerciais (só @myio / superadmin no modal)
80242
+ // Campos comerciais (visíveis para todos; editáveis só para admin no modal)
80211
80243
  "abl",
80212
80244
  "contract",
80213
80245
  "segment",
@@ -87581,7 +87613,109 @@ ${state6.year}-03-15T08,15`)}">${esc6(state6.csv)}</textarea>
87581
87613
  return instance;
87582
87614
  }
87583
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
+
87584
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
+ };
87585
87719
  var _footers = /* @__PURE__ */ new Map();
87586
87720
  function escHtml3(s) {
87587
87721
  return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -87628,6 +87762,10 @@ async function openTemperatureModal(params) {
87628
87762
  selectedPeriods: ["madrugada", "manha", "tarde", "noite"],
87629
87763
  // All periods selected by default
87630
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,
87631
87769
  deviceName: params.deviceName || "",
87632
87770
  customerName: resolveCustomerName(params.customerName),
87633
87771
  accent: resolveAccent(
@@ -87639,18 +87777,15 @@ async function openTemperatureModal(params) {
87639
87777
  }
87640
87778
  const savedGranularity = localStorage.getItem("myio-temp-modal-granularity");
87641
87779
  const savedTheme = localStorage.getItem("myio-temp-modal-theme");
87642
- if (savedGranularity) state6.granularity = savedGranularity;
87780
+ if (savedGranularity && savedGranularity in GRANULARITY_LABEL) state6.granularity = savedGranularity;
87781
+ if (!isGranularityAvailable(state6, state6.granularity)) state6.granularity = "hour";
87643
87782
  if (savedTheme && !params.theme) state6.theme = savedTheme;
87644
87783
  const modalContainer = document.createElement("div");
87645
87784
  modalContainer.id = modalId;
87646
87785
  document.body.appendChild(modalContainer);
87647
87786
  renderModal3(modalContainer, state6, modalId);
87648
87787
  try {
87649
- state6.data = discardInvalid(
87650
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
87651
- state6
87652
- );
87653
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87788
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87654
87789
  state6.isLoading = false;
87655
87790
  renderModal3(modalContainer, state6, modalId);
87656
87791
  drawChart2(modalId, state6);
@@ -87670,15 +87805,11 @@ async function openTemperatureModal(params) {
87670
87805
  updateData: async (startDate, endDate, granularity) => {
87671
87806
  state6.startTs = new Date(startDate).getTime();
87672
87807
  state6.endTs = new Date(endDate).getTime();
87673
- if (granularity) state6.granularity = granularity;
87808
+ if (granularity && isGranularityAvailable(state6, granularity)) state6.granularity = granularity;
87674
87809
  state6.isLoading = true;
87675
87810
  renderModal3(modalContainer, state6, modalId);
87676
87811
  try {
87677
- state6.data = discardInvalid(
87678
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
87679
- state6
87680
- );
87681
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87812
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87682
87813
  state6.isLoading = false;
87683
87814
  renderModal3(modalContainer, state6, modalId);
87684
87815
  drawChart2(modalId, state6);
@@ -87690,12 +87821,75 @@ async function openTemperatureModal(params) {
87690
87821
  }
87691
87822
  };
87692
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
+ }
87693
87883
  function renderModal3(container, state6, modalId, error) {
87694
87884
  const colors2 = getThemeColors(state6.theme);
87695
87885
  const startDateStr = new Date(state6.startTs).toLocaleDateString(state6.locale);
87696
87886
  const endDateStr = new Date(state6.endTs).toLocaleDateString(state6.locale);
87697
- const statusText = state6.temperatureStatus === "ok" ? "Dentro da faixa" : state6.temperatureStatus === "above" ? "Acima do limite" : state6.temperatureStatus === "below" ? "Abaixo do limite" : "N/A";
87698
- 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);
87699
87893
  const rangeText = state6.temperatureMin !== null && state6.temperatureMax !== null ? `${state6.temperatureMin}\xB0C - ${state6.temperatureMax}\xB0C` : "N\xE3o definida";
87700
87894
  const startDateInput = new Date(state6.startTs).toISOString().slice(0, 16);
87701
87895
  const endDateInput = new Date(state6.endTs).toISOString().slice(0, 16);
@@ -87754,8 +87948,10 @@ function renderModal3(container, state6, modalId, error) {
87754
87948
  font-size: 14px; color: ${colors2.text}; background: ${colors2.surface};
87755
87949
  cursor: pointer; min-width: 130px;
87756
87950
  ">
87757
- <option value="hour" ${state6.granularity === "hour" ? "selected" : ""}>Hora</option>
87758
- <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("")}
87759
87955
  </select>
87760
87956
  </div>
87761
87957
  <!-- Day Period Filter (Multiselect) -->
@@ -87843,9 +88039,10 @@ function renderModal3(container, state6, modalId, error) {
87843
88039
  ">
87844
88040
  <span style="color: ${colors2.textMuted}; font-size: 12px; font-weight: 500;">Temperatura Atual</span>
87845
88041
  <div style="font-weight: 700; font-size: 24px; color: ${statusColor}; margin-top: 4px;">
87846
- ${state6.currentTemperature !== null ? formatTemperature(state6.currentTemperature) : "N/A"}
88042
+ ${currentValue !== null ? formatTemperature(currentValue) : "N/A"}
87847
88043
  </div>
87848
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>` : ""}
87849
88046
  </div>
87850
88047
  <!-- Average -->
87851
88048
  <div style="
@@ -87965,9 +88162,10 @@ function drawChart2(modalId, state6) {
87965
88162
  return;
87966
88163
  }
87967
88164
  let chartData;
87968
- if (state6.granularity === "hour") {
87969
- const hourly = aggregateByHour(filteredData, state6.clampRange, state6.temperatureOffset);
87970
- 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) => ({
87971
88169
  x: item.ts,
87972
88170
  y: Number(item.value),
87973
88171
  screenX: 0,
@@ -88067,33 +88265,16 @@ function drawChart2(modalId, state6) {
88067
88265
  ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 8, y + 4);
88068
88266
  }
88069
88267
  ctx.textAlign = "center";
88070
- const numLabels = Math.min(8, chartData.length);
88071
- const labelInterval = Math.max(1, Math.floor(chartData.length / numLabels));
88072
- const xSpan = chartData.length > 1 ? chartData[chartData.length - 1].x - chartData[0].x : 0;
88073
- const multiDay = state6.granularity === "hour" && xSpan > 24 * 60 * 60 * 1e3;
88074
- for (let i = 0; i < chartData.length; i += labelInterval) {
88075
- const point = chartData[i];
88076
- const date = new Date(point.x);
88077
- let label;
88078
- let subLabel = "";
88079
- if (state6.granularity === "hour") {
88080
- label = date.toLocaleTimeString(state6.locale, { hour: "2-digit", minute: "2-digit" });
88081
- if (multiDay) {
88082
- subLabel = label;
88083
- label = date.toLocaleDateString(state6.locale, { day: "2-digit", month: "2-digit" });
88084
- }
88085
- } else {
88086
- label = date.toLocaleDateString(state6.locale, { day: "2-digit", month: "2-digit" });
88087
- }
88268
+ const tz = state6.timezone || "America/Sao_Paulo";
88269
+ for (const tick of buildXAxisTicks(chartData, state6.granularity, tz, state6.locale, isPeriodsFiltered, paddingLeft, chartWidth)) {
88088
88270
  ctx.strokeStyle = colors2.chartGrid;
88089
88271
  ctx.lineWidth = 1;
88090
88272
  ctx.beginPath();
88091
- ctx.moveTo(point.screenX, paddingTop);
88092
- ctx.lineTo(point.screenX, height - paddingBottom);
88273
+ ctx.moveTo(tick.screenX, paddingTop);
88274
+ ctx.lineTo(tick.screenX, height - paddingBottom);
88093
88275
  ctx.stroke();
88094
88276
  ctx.fillStyle = colors2.textMuted;
88095
- ctx.fillText(label, point.screenX, height - paddingBottom + 18);
88096
- if (subLabel) ctx.fillText(subLabel, point.screenX, height - paddingBottom + 31);
88277
+ ctx.fillText(tick.label, tick.screenX, height - paddingBottom + 18);
88097
88278
  }
88098
88279
  ctx.strokeStyle = colors2.border;
88099
88280
  ctx.lineWidth = 1;
@@ -88104,6 +88285,41 @@ function drawChart2(modalId, state6) {
88104
88285
  ctx.stroke();
88105
88286
  setupChartTooltip2(canvas, chartContainer, chartData, state6, colors2);
88106
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
+ }
88107
88323
  function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88108
88324
  const existingTooltip = container.querySelector(".myio-chart-tooltip");
88109
88325
  if (existingTooltip) existingTooltip.remove();
@@ -88148,7 +88364,7 @@ function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88148
88364
  if (point) {
88149
88365
  const date = new Date(point.x);
88150
88366
  let dateStr;
88151
- if (state6.granularity === "hour") {
88367
+ if (state6.granularity !== "day") {
88152
88368
  dateStr = date.toLocaleDateString(state6.locale, {
88153
88369
  day: "2-digit",
88154
88370
  month: "2-digit",
@@ -88291,9 +88507,28 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88291
88507
  }
88292
88508
  if (state6.data.length > 0) drawChart2(modalId, state6);
88293
88509
  });
88294
- document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
88295
- 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;
88296
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
+ }
88297
88532
  if (state6.data.length > 0) drawChart2(modalId, state6);
88298
88533
  });
88299
88534
  document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
@@ -88305,11 +88540,7 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88305
88540
  state6.dateRangePicker = null;
88306
88541
  renderModal3(container, state6, modalId);
88307
88542
  try {
88308
- state6.data = discardInvalid(
88309
- await (state6.dataFetcher ? state6.dataFetcher(state6.startTs, state6.endTs) : fetchTemperatureData(state6.token, state6.deviceId, state6.startTs, state6.endTs)),
88310
- state6
88311
- );
88312
- state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
88543
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
88313
88544
  state6.isLoading = false;
88314
88545
  renderModal3(container, state6, modalId);
88315
88546
  drawChart2(modalId, state6);
@@ -88349,21 +88580,26 @@ function exportCsv(state6) {
88349
88580
  ...state6.deviceName ? [["Dispositivo (TB)", state6.deviceName]] : [],
88350
88581
  ...state6.customerName ? [["Cliente", state6.customerName]] : [],
88351
88582
  ["Per\xEDodo", `${fmtD(state6.startTs)} \u2014 ${fmtD(state6.endTs)}`],
88352
- ["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
+ ],
88353
88587
  ["Per\xEDodos do dia", getSelectedPeriodsLabel(state6.selectedPeriods)],
88354
88588
  ...off !== 0 ? [["Offset aplicado (\xB0C)", n2(off)]] : [],
88355
88589
  ["Gerado em", (/* @__PURE__ */ new Date()).toLocaleString("pt-BR")],
88356
88590
  [],
88357
- ["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)]] : [],
88358
88593
  ["M\xE9dia do per\xEDodo (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.avg) : "N/A"],
88359
88594
  ["M\xEDnima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.min) : "N/A"],
88360
88595
  ["M\xE1xima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.max) : "N/A"],
88361
88596
  ["Leituras", String(state6.stats.count)],
88362
88597
  []
88363
88598
  ];
88364
- if (state6.granularity === "hour") {
88599
+ const csvMinutes = GRANULARITY_MINUTES[state6.granularity];
88600
+ if (csvMinutes) {
88365
88601
  lines.push(["Data/Hora", "Temperatura (\xB0C)"]);
88366
- 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))]));
88367
88603
  } else {
88368
88604
  lines.push(["Dia", "M\xE9dia (\xB0C)", "M\xEDn (\xB0C)", "M\xE1x (\xB0C)", "Leituras"]);
88369
88605
  aggregateByDay(filtered, state6.clampRange, off).forEach(
@@ -88375,7 +88611,8 @@ function exportCsv(state6) {
88375
88611
  const url = URL.createObjectURL(blob);
88376
88612
  const a = document.createElement("a");
88377
88613
  a.href = url;
88378
- 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`;
88379
88616
  document.body.appendChild(a);
88380
88617
  a.click();
88381
88618
  document.body.removeChild(a);
@@ -144378,8 +144615,8 @@ var TelemetryInfoShoppingView = class _TelemetryInfoShoppingView {
144378
144615
  // consistently (ported from v-5.2.0 TELEMETRY_INFO where (i) is on practically every metric).
144379
144616
  tooltipSpan(tooltip) {
144380
144617
  if (!tooltip) return "";
144381
- const safe = String(tooltip).replace(/"/g, "&quot;");
144382
- 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>`;
144383
144620
  }
144384
144621
  buildWaterCards() {
144385
144622
  const config2 = WATER_CATEGORY_CONFIG;
@@ -159069,9 +159306,9 @@ var FancoilRemoteController = class {
159069
159306
  });
159070
159307
  }
159071
159308
  async handlePowerToggle() {
159072
- const currentStatus = this.state.status;
159073
- if (currentStatus === "offline") return;
159074
- const newStatus = currentStatus === "on" ? "off" : "on";
159309
+ const currentStatus2 = this.state.status;
159310
+ if (currentStatus2 === "offline") return;
159311
+ const newStatus = currentStatus2 === "on" ? "off" : "on";
159075
159312
  const actionText = newStatus === "on" ? "LIGAR" : "DESLIGAR";
159076
159313
  if (this.onConfirmAction) {
159077
159314
  const confirmed = await this.onConfirmAction(
@@ -159088,7 +159325,7 @@ var FancoilRemoteController = class {
159088
159325
  }
159089
159326
  if (this.onPowerToggle) {
159090
159327
  try {
159091
- const success = await this.onPowerToggle(currentStatus);
159328
+ const success = await this.onPowerToggle(currentStatus2);
159092
159329
  if (success) {
159093
159330
  this.state.status = newStatus;
159094
159331
  this.view.updateState({ status: newStatus });
@@ -166156,8 +166393,8 @@ var OnOffDeviceModalView = class {
166156
166393
  deviceName: this.device.label || this.device.name || "Dispositivo",
166157
166394
  relatedDevices: []
166158
166395
  },
166159
- onToggle: async (currentStatus) => {
166160
- const newState = currentStatus !== "on";
166396
+ onToggle: async (currentStatus2) => {
166397
+ const newState = currentStatus2 !== "on";
166161
166398
  this.onDeviceToggle(newState);
166162
166399
  return true;
166163
166400
  }
@@ -180239,6 +180476,7 @@ var version = package_default.version || "0.0.0";
180239
180476
  DEFAULT_ANNOTATION_SORT,
180240
180477
  DEFAULT_BAS_SETTINGS,
180241
180478
  DEFAULT_CLAMP_RANGE,
180479
+ DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
180242
180480
  DEFAULT_DASHBOARD_KPIS,
180243
180481
  DEFAULT_DAYS_WEEK,
180244
180482
  DEFAULT_DEVICE_CLASSIFICATION_PROFILE,
@@ -180644,6 +180882,7 @@ var version = package_default.version || "0.0.0";
180644
180882
  createHeaderShoppingComponent,
180645
180883
  createHttpDeviceCategoryPort,
180646
180884
  createImgGallery,
180885
+ createIngestionTemperatureAggregateFetcher,
180647
180886
  createInputDateRangePickerInsideDIV,
180648
180887
  createLibraryVersionChecker,
180649
180888
  createLoadingSpinner,
@@ -181065,6 +181304,7 @@ var version = package_default.version || "0.0.0";
181065
181304
  resolveBudget,
181066
181305
  resolveCategory,
181067
181306
  resolveClassification,
181307
+ resolveCurrentTemperature,
181068
181308
  resolveEffectiveDisplayMode,
181069
181309
  resolveGoalAmount,
181070
181310
  resolveGroup,