myio-js-library 0.1.578 → 0.1.580

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.580",
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 [];
@@ -33855,12 +33874,26 @@ var DEFAULT_GRANULARITY_OPTIONS = [
33855
33874
  { value: "1h", title: "Hora" },
33856
33875
  { value: "1d", title: "Dia" }
33857
33876
  ];
33877
+ var TEMPERATURE_GRANULARITY_OPTIONS = [
33878
+ { value: "15m", title: "15 minutos" },
33879
+ { value: "30m", title: "30 minutos" },
33880
+ { value: "1h", title: "Hora" },
33881
+ { value: "1d", title: "Dia" }
33882
+ ];
33883
+ function granularityMinutes(g) {
33884
+ return g === "15m" ? 15 : g === "30m" ? 30 : g === "1h" ? 60 : 1440;
33885
+ }
33858
33886
 
33859
33887
  // src/components/granularity-selector/createGranularitySelector.ts
33860
33888
  var P = GRANULARITY_SELECTOR_CSS_PREFIX;
33861
- var DEFAULT_TITLES = { "1h": "Hora", "1d": "Dia" };
33889
+ var DEFAULT_TITLES = {
33890
+ "15m": "15 minutos",
33891
+ "30m": "30 minutos",
33892
+ "1h": "Hora",
33893
+ "1d": "Dia"
33894
+ };
33862
33895
  function isGranularity(v) {
33863
- return v === "1h" || v === "1d";
33896
+ return v === "15m" || v === "30m" || v === "1h" || v === "1d";
33864
33897
  }
33865
33898
  function createGranularitySelector(container, params = {}) {
33866
33899
  injectGranularitySelectorStyles();
@@ -35196,7 +35229,10 @@ var EnergyModalView = class {
35196
35229
  value: this.currentGranularity,
35197
35230
  themeMode: this.currentTheme
35198
35231
  },
35199
- onChange: (granularity) => this.setGranularity(granularity)
35232
+ // Opções default (1h | 1d) — 15m/30m só existem nos relatórios de temperatura
35233
+ onChange: (granularity) => {
35234
+ if (granularity === "1h" || granularity === "1d") this.setGranularity(granularity);
35235
+ }
35200
35236
  });
35201
35237
  dbg2("[EnergyModalView] [RFC-0097] Granularity selector initialized with:", this.currentGranularity);
35202
35238
  }
@@ -37508,7 +37544,7 @@ var DeviceReportModal = class {
37508
37544
  const domain = params.domain || "energy";
37509
37545
  this.domainConfig = DOMAIN_CONFIG[domain];
37510
37546
  this.granularity = params.granularity === "1h" ? "1h" : "1d";
37511
- this.energyFetcher = params.fetcher || createDefaultEnergyFetcher(params, () => this.granularity);
37547
+ this.energyFetcher = params.fetcher || createDefaultEnergyFetcher(params, () => this.apiGranularity);
37512
37548
  }
37513
37549
  modal;
37514
37550
  authClient;
@@ -37519,6 +37555,8 @@ var DeviceReportModal = class {
37519
37555
  dateRangePicker = null;
37520
37556
  sortState = { key: null, direction: "asc" };
37521
37557
  domainConfig;
37558
+ // Temperatura: 15m | 30m | 1h | 1d (15/30 min agregados no cliente a partir dos blocos de
37559
+ // 15 min que o Ingestion devolve com granularity=1h). Demais domínios: 1h | 1d.
37522
37560
  granularity = "1d";
37523
37561
  // Granularity selector (shared component — same pill 1h|1d as EnergyModal/AllReportModal).
37524
37562
  granularitySelector = null;
@@ -37530,6 +37568,25 @@ var DeviceReportModal = class {
37530
37568
  participationChart = null;
37531
37569
  // Período do último load — alimenta os headers dos exports PDF/XLS.
37532
37570
  exportPeriod = null;
37571
+ /** Linhas intradiárias (15 min, 30 min ou hora) — tudo que não é '1d' */
37572
+ get isIntraday() {
37573
+ return this.granularity !== "1d";
37574
+ }
37575
+ /** O Ingestion só aceita 1h|1d: 15/30 min buscam 1h (blocos de 15 min) e agregam aqui */
37576
+ get apiGranularity() {
37577
+ return this.isIntraday ? "1h" : "1d";
37578
+ }
37579
+ /** Rótulo da linha intradiária: "Hora" (1h) ou "Horário" (15/30 min) */
37580
+ get intradayLabel() {
37581
+ return this.granularity === "1h" ? "Hora" : "Hor\xE1rio";
37582
+ }
37583
+ /** Rótulo legível da granularidade (CSV/avisos) */
37584
+ get granularityText() {
37585
+ return { "15m": "15 minutos", "30m": "30 minutos", "1h": "Hora", "1d": "Dia" }[this.granularity];
37586
+ }
37587
+ get isTemperatureDomain() {
37588
+ return (this.params.domain || "energy") === "temperature";
37589
+ }
37533
37590
  // Header: "Relatório - <identifier> - <label>" + nome do device (sutil, com copiar).
37534
37591
  // O customer já aparece no footer premium. Texto escapado — o shell usa innerHTML no título.
37535
37592
  buildHeaderTitleHTML() {
@@ -37752,13 +37809,16 @@ var DeviceReportModal = class {
37752
37809
  // sem label interno (o form group acima já tem "Granularidade").
37753
37810
  label: "",
37754
37811
  themeMode: this.params.ui?.theme === "dark" ? "dark" : "light",
37812
+ // Temperatura: 15m | 30m | 1h | 1d; demais domínios: 1h | 1d (default do componente)
37813
+ ...this.isTemperatureDomain ? { options: TEMPERATURE_GRANULARITY_OPTIONS } : {},
37755
37814
  tooltip: {
37756
37815
  enabled: true,
37757
37816
  title: "Granularidade",
37758
- text: "Em <b>Dia</b>, a tabela traz uma linha por dia; em <b>Hora</b>, uma linha por hora e o seletor de per\xEDodo ganha hora/minuto. KPIs e gr\xE1fico recalculam conforme a granularidade."
37817
+ text: this.isTemperatureDomain ? "Em <b>Dia</b>, uma linha por dia (m\xE9dia do dia); em <b>15m</b>, <b>30m</b> e <b>1h</b>, uma linha por janela (m\xE9dia da janela) e o seletor de per\xEDodo ganha hora/minuto. KPIs e gr\xE1fico recalculam conforme a granularidade." : "Em <b>Dia</b>, a tabela traz uma linha por dia; em <b>Hora</b>, uma linha por hora e o seletor de per\xEDodo ganha hora/minuto. KPIs e gr\xE1fico recalculam conforme a granularidade."
37759
37818
  }
37760
37819
  },
37761
37820
  onChange: async (value) => {
37821
+ if (!this.isTemperatureDomain && value !== "1h" && value !== "1d") return;
37762
37822
  this.granularity = value;
37763
37823
  await this.rebuildDateRangePicker(dateRangeInput);
37764
37824
  this.resetAfterGranularityChange();
@@ -37777,7 +37837,7 @@ var DeviceReportModal = class {
37777
37837
  if (tableContainer) {
37778
37838
  tableContainer.innerHTML = `
37779
37839
  <div style="text-align: center; padding: 40px; color: var(--myio-text-muted);">
37780
- Granularidade alterada para <strong>${this.granularity}</strong>. Clique em "Carregar" para atualizar os dados.
37840
+ Granularidade alterada para <strong>${this.granularityText}</strong>. Clique em "Carregar" para atualizar os dados.
37781
37841
  </div>
37782
37842
  `;
37783
37843
  }
@@ -37821,7 +37881,7 @@ var DeviceReportModal = class {
37821
37881
  presetEnd,
37822
37882
  // Ciclo de rateio (dia D → dia D do mês seguinte) tem até 32 dias corridos (ex.: 15/08→15/09)
37823
37883
  maxRangeDays: 32,
37824
- includeTime: this.granularity === "1h",
37884
+ includeTime: this.isIntraday,
37825
37885
  timePrecision: "minute",
37826
37886
  parentEl: this.modal.element,
37827
37887
  onApply: ({ startISO, endISO }) => {
@@ -37840,7 +37900,7 @@ var DeviceReportModal = class {
37840
37900
  // Contrato do getDates(): hora LOCAL + offset (YYYY-MM-DDTHH:mm:ss±HH:MM) — os 10
37841
37901
  // primeiros caracteres são o dia exibido e os 6 últimos, o offset.
37842
37902
  resolveQueryWindow(range) {
37843
- if (this.granularity === "1h" || !range.startISO || !range.endISO) return range;
37903
+ if (this.isIntraday || !range.startISO || !range.endISO) return range;
37844
37904
  const day = (iso) => iso.slice(0, 10);
37845
37905
  const offset = (iso) => iso.slice(-6);
37846
37906
  return {
@@ -37880,7 +37940,8 @@ var DeviceReportModal = class {
37880
37940
  ingestionId: this.params.ingestionId,
37881
37941
  startISO,
37882
37942
  endISO,
37883
- granularity: this.granularity
37943
+ // API só conhece 1h|1d — 15/30 min vêm do 1h e são agregados em processApiResponse
37944
+ granularity: this.apiGranularity
37884
37945
  });
37885
37946
  this.data = this.processApiResponse(apiResponse, dateRange);
37886
37947
  this.renderSummary();
@@ -37906,7 +37967,7 @@ var DeviceReportModal = class {
37906
37967
  }
37907
37968
  processApiResponse(apiResponse, dateRange) {
37908
37969
  const dataArray = Array.isArray(apiResponse) ? apiResponse : apiResponse.data || [];
37909
- const isHourly = this.granularity === "1h";
37970
+ const isHourly = this.isIntraday;
37910
37971
  if (!Array.isArray(dataArray) || dataArray.length === 0) {
37911
37972
  console.warn("[DeviceReportModal] API returned empty or invalid response, zero-filling date range");
37912
37973
  if (isHourly) return [];
@@ -37931,7 +37992,7 @@ var DeviceReportModal = class {
37931
37992
  }
37932
37993
  if (isHourly) {
37933
37994
  const isAvg = this.domainConfig.summaryType === "average";
37934
- const HOUR = 3600 * 1e3;
37995
+ const HOUR = granularityMinutes(this.granularity) * 60 * 1e3;
37935
37996
  const byHour = /* @__PURE__ */ new Map();
37936
37997
  consumption.forEach((item) => {
37937
37998
  if (!item.timestamp || item.value == null) return;
@@ -38001,7 +38062,7 @@ var DeviceReportModal = class {
38001
38062
  computeKpis() {
38002
38063
  const fmt2 = this.domainConfig.formatter;
38003
38064
  const unit = this.domainConfig.unit;
38004
- const isHourly = this.granularity === "1h";
38065
+ const isHourly = this.isIntraday;
38005
38066
  const isTemperature = this.domainConfig.summaryType === "average";
38006
38067
  const total = this.calculateTotal();
38007
38068
  const rows = this.validRows;
@@ -38018,7 +38079,7 @@ var DeviceReportModal = class {
38018
38079
  null
38019
38080
  );
38020
38081
  const zeroCount = this.data.filter((r) => r.consumption <= 0).length;
38021
- const rowLabel = isHourly ? "Hora" : "Dia";
38082
+ const rowLabel = isHourly ? this.intradayLabel : "Dia";
38022
38083
  let perDay;
38023
38084
  if (isTemperature) {
38024
38085
  const byDay = /* @__PURE__ */ new Map();
@@ -38057,7 +38118,7 @@ var DeviceReportModal = class {
38057
38118
  kpis.push({ value: String(zeroCount), label: isHourly ? "Horas sem Consumo" : "Dias sem Consumo" });
38058
38119
  } else {
38059
38120
  const noData = this.data.length - rows.length;
38060
- if (noData > 0) kpis.push({ value: String(noData), label: isHourly ? "Horas sem Leitura" : "Dias sem Leitura" });
38121
+ if (noData > 0) kpis.push({ value: String(noData), label: isHourly ? `${this.intradayLabel}s sem Leitura` : "Dias sem Leitura" });
38061
38122
  }
38062
38123
  return kpis;
38063
38124
  }
@@ -38079,7 +38140,7 @@ var DeviceReportModal = class {
38079
38140
  // Temperatura (painel direito): ranking em barras — 1d = dias mais quentes (média do dia);
38080
38141
  // 1h = horas mais quentes (top 24). Escala comum + faixa ideal sombreada (padrão AllReport).
38081
38142
  renderTemperatureRanking(container) {
38082
- const isHourly = this.granularity === "1h";
38143
+ const isHourly = this.isIntraday;
38083
38144
  const valid = this.validRows;
38084
38145
  if (!valid.length) {
38085
38146
  container.innerHTML = `<div style="border:1px dashed var(--myio-border,#e5e7eb);border-radius:10px;padding:32px 16px;text-align:center;font-size:13px;color:var(--myio-text-muted,#6b7280);">Sem leituras no per\xEDodo</div>`;
@@ -38106,7 +38167,7 @@ var DeviceReportModal = class {
38106
38167
  <span style="text-align:right;font-variant-numeric:tabular-nums;font-weight:600;">${r ? this.domainConfig.formatter(r.consumption) : "\u2014"}</span>
38107
38168
  </div>`;
38108
38169
  const unit = this.domainConfig.unit;
38109
- const title = isHourly ? `${this.domainConfig.rankingHourTitle}${ranked.length > TOP_HOURS ? ` (top ${TOP_HOURS})` : ""}` : this.domainConfig.rankingDayTitle;
38170
+ const title = isHourly ? `${this.intradayRankingTitle()}${ranked.length > TOP_HOURS ? ` (top ${TOP_HOURS})` : ""}` : this.domainConfig.rankingDayTitle;
38110
38171
  container.innerHTML = `
38111
38172
  <div style="border:1px solid var(--myio-border,#e5e7eb);border-radius:10px;padding:12px 14px;max-height:620px;overflow-y:auto;">
38112
38173
  <div style="font-weight:700;font-size:14px;margin-bottom:2px;">${title}</div>
@@ -38117,6 +38178,12 @@ var DeviceReportModal = class {
38117
38178
  ${noData.map((r) => line(this.formatDate(r.date), null)).join("")}
38118
38179
  </div>`;
38119
38180
  }
38181
+ // "Horas mais quentes" (1h) / "Horários mais quentes (15 min)" (15/30 min)
38182
+ intradayRankingTitle() {
38183
+ const base = this.domainConfig.rankingHourTitle || "";
38184
+ if (this.granularity === "1h") return base;
38185
+ return `${base.replace(/^Horas/, "Hor\xE1rios")} (${this.granularityText})`;
38186
+ }
38120
38187
  updateDayChart() {
38121
38188
  const container = document.getElementById("participation-chart-container");
38122
38189
  if (!container) return;
@@ -38170,7 +38237,7 @@ var DeviceReportModal = class {
38170
38237
  <thead style="position: sticky; top: 0; background: var(--myio-bg); z-index: 1;">
38171
38238
  <tr>
38172
38239
  <th style="cursor: pointer;" data-sort="date">
38173
- ${this.granularity === "1h" ? "Data/Hora" : "Data"}
38240
+ ${this.isIntraday ? "Data/Hora" : "Data"}
38174
38241
  <span style="margin-left: 4px; opacity: ${this.sortState.key === "date" ? "1" : "0.5"};">${getSortIndicator("date")}</span>
38175
38242
  </th>
38176
38243
  <th style="cursor: pointer; text-align: right;" data-sort="consumption">
@@ -38253,16 +38320,16 @@ var DeviceReportModal = class {
38253
38320
  ...isTemp && off !== 0 ? [["Offset aplicado (\xB0C)", this.domainConfig.formatter(off), ""]] : [],
38254
38321
  ...this.resolveCustomerName() ? [["Cliente", this.resolveCustomerName(), ""]] : [],
38255
38322
  ...p?.startISO ? [["Per\xEDodo", `${fmtD(p.startISO)} \u2014 ${fmtD(p.endISO)}`, ""]] : [],
38256
- ["Granularidade", this.granularity === "1h" ? "Hora" : "Dia", ""],
38323
+ ["Granularidade", this.granularityText, ""],
38257
38324
  ["DATA EMISS\xC3O", timestamp, ""],
38258
38325
  [],
38259
38326
  ...this.computeKpis().map((k) => [k.label, k.value, k.sub || ""]),
38260
38327
  [],
38261
- [this.granularity === "1h" ? "Data/Hora" : "Data", this.domainConfig.label, ""],
38328
+ [this.isIntraday ? "Data/Hora" : "Data", this.domainConfig.label, ""],
38262
38329
  ...this.data.map((row) => [this.formatDate(row.date), row.noData ? "Sem leitura" : this.domainConfig.formatter(row.consumption)])
38263
38330
  ];
38264
38331
  const csvContent = toCsv(csvData);
38265
- const granSuffix = this.granularity === "1h" ? "-1h" : "";
38332
+ const granSuffix = this.isIntraday ? `-${this.granularity}` : "";
38266
38333
  this.downloadCSV(csvContent, `relatorio-${this.params.identifier || "dispositivo"}${granSuffix}-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`);
38267
38334
  }
38268
38335
  // Accent hex da paleta do dashboard (params.theme) para os exports — cai no
@@ -38303,18 +38370,18 @@ var DeviceReportModal = class {
38303
38370
  exportColumnOptions() {
38304
38371
  const isTemp = this.domainConfig.summaryType === "average";
38305
38372
  return {
38306
- nameLabel: this.granularity === "1h" ? "Data/Hora" : "Data",
38373
+ nameLabel: this.isIntraday ? "Data/Hora" : "Data",
38307
38374
  hideIdentifier: true,
38308
38375
  // Mesmo rótulo da coluna da tela (antes saía "Consumo (°C)" em temperatura)
38309
38376
  valueLabel: this.domainConfig.label,
38310
- countLabel: this.granularity === "1h" ? "hora(s)" : "dia(s)",
38377
+ countLabel: this.isIntraday ? this.granularity === "1h" ? "hora(s)" : "hor\xE1rio(s)" : "dia(s)",
38311
38378
  ...isTemp ? { hidePerc: true, emptyValueText: "Sem leitura", valueDecimals: 2 } : {}
38312
38379
  };
38313
38380
  }
38314
38381
  // Gráfico da página final do PDF = painel da direita da tela
38315
38382
  async buildExportChart() {
38316
38383
  if (this.domainConfig.summaryType === "average") {
38317
- const isHourly = this.granularity === "1h";
38384
+ const isHourly = this.isIntraday;
38318
38385
  const ranked = [...this.validRows].sort((a, b) => b.consumption - a.consumption);
38319
38386
  const shown = isHourly ? ranked.slice(0, 24) : ranked;
38320
38387
  const noData = isHourly ? [] : this.data.filter((r) => r.noData);
@@ -38327,7 +38394,7 @@ var DeviceReportModal = class {
38327
38394
  accent: this.resolveAccentHex(),
38328
38395
  unit: this.domainConfig.unit
38329
38396
  });
38330
- const title = isHourly ? `${this.domainConfig.rankingHourTitle}${ranked.length > 24 ? " (top 24)" : ""}` : this.domainConfig.rankingDayTitle;
38397
+ const title = isHourly ? `${this.intradayRankingTitle()}${ranked.length > 24 ? " (top 24)" : ""}` : this.domainConfig.rankingDayTitle;
38331
38398
  return png ? { ...png, title } : null;
38332
38399
  }
38333
38400
  const chartPng = await this.participationChart?.toPngDataUrl?.().catch(() => null);
@@ -40160,7 +40227,8 @@ var AllReportModal = class {
40160
40227
  debugEnabled;
40161
40228
  // Domain configuration
40162
40229
  domainConfig;
40163
- // Granularity: '1d' (daily) | '1h' (hourly)
40230
+ // Granularity: '1d' (daily) | '1h' (hourly). Temperatura também '15m' | '30m' — agregados
40231
+ // aqui a partir dos blocos de 15 min que o Ingestion devolve com granularity=1h.
40164
40232
  granularity = "1d";
40165
40233
  // Temperatura: estatísticas por sensor (key = ingestionId) da última carga
40166
40234
  temperatureStats = /* @__PURE__ */ new Map();
@@ -40571,13 +40639,16 @@ var AllReportModal = class {
40571
40639
  // Padrão FIEL ao EnergyModal: pill "1h | 1d" (opções default do componente),
40572
40640
  // sem label interno (o form group acima já tem "Granularidade").
40573
40641
  label: "",
40642
+ // Temperatura: 15m | 30m | 1h | 1d; demais domínios: 1h | 1d (default do componente)
40643
+ ...this.isTemperature ? { options: TEMPERATURE_GRANULARITY_OPTIONS } : {},
40574
40644
  tooltip: {
40575
40645
  enabled: true,
40576
40646
  title: "Granularidade",
40577
- text: this.isTemperature ? "A tabela mostra a <b>m\xE9dia do per\xEDodo</b> de cada sensor. Clique em \u25B8 no sensor para ver a s\xE9rie <b>por hora</b> ou <b>por dia</b>; o CSV segue a mesma granularidade." : "A tabela mostra os <b>totais do per\xEDodo</b>. Clique em \u25B8 no dispositivo para ver a s\xE9rie <b>por hora</b> ou <b>por dia</b>; em Hora, o CSV traz uma linha por dispositivo \xD7 hora."
40647
+ text: this.isTemperature ? "A tabela mostra a <b>m\xE9dia do per\xEDodo</b> de cada sensor. Clique em \u25B8 no sensor para ver a s\xE9rie <b>por 15 min</b>, <b>30 min</b>, <b>hora</b> ou <b>dia</b> (m\xE9dia da janela); o CSV segue a mesma granularidade." : "A tabela mostra os <b>totais do per\xEDodo</b>. Clique em \u25B8 no dispositivo para ver a s\xE9rie <b>por hora</b> ou <b>por dia</b>; em Hora, o CSV traz uma linha por dispositivo \xD7 hora."
40578
40648
  }
40579
40649
  },
40580
40650
  onChange: (value) => {
40651
+ if (!this.isTemperature && value !== "1h" && value !== "1d") return;
40581
40652
  this.granularity = value;
40582
40653
  this.hourlySeriesCache = null;
40583
40654
  if (this.data.length && this.expandedIds.size) this.renderTable();
@@ -40950,7 +41021,7 @@ var AllReportModal = class {
40950
41021
  renderRowHTML(row, grandTotal, showId) {
40951
41022
  const expandable = !!row.id;
40952
41023
  const expanded = expandable && this.expandedIds.has(row.id);
40953
- const expandBtn = expandable ? `<button type="button" class="rp-expand" data-expand-id="${row.id}" aria-expanded="${expanded}" title="Ver s\xE9rie por ${this.granularity === "1h" ? "hora" : "dia"}">\u25B8</button>` : "";
41024
+ const expandBtn = expandable ? `<button type="button" class="rp-expand" data-expand-id="${row.id}" aria-expanded="${expanded}" title="Ver s\xE9rie por ${this.granularityNoun(this.granularity)}">\u25B8</button>` : "";
40954
41025
  const idTd = showId ? `<td data-label="Identificador" style="font-family: monospace; font-weight: bold; text-transform: uppercase;">${row.identifier}</td>` : "";
40955
41026
  const off = this.isTemperature && row.id && !row.noData ? this.temperatureOffsetFor(row.id) : 0;
40956
41027
  const offsetTag = off ? ` <span class="rp-offset" title="Offset do sensor aplicado \xE0s leituras">offset ${off > 0 ? "+" : "\u2212"}${fmtPt(Math.abs(off))} \xB0C</span>` : "";
@@ -41040,14 +41111,15 @@ var AllReportModal = class {
41040
41111
  async fillSeries(id, box) {
41041
41112
  const row = this.data.find((r) => r.id === id);
41042
41113
  const gran = this.granularity;
41114
+ const intraday = gran !== "1d";
41043
41115
  try {
41044
41116
  const points = await this.getDeviceSeries(id, gran);
41045
41117
  if (!box.isConnected) return;
41046
41118
  if (!points.length) {
41047
- box.innerHTML = `<span class="rp-muted">Sem dados ${gran === "1h" ? "hor\xE1rios" : "di\xE1rios"} no per\xEDodo.</span>`;
41119
+ box.innerHTML = `<span class="rp-muted">Sem dados ${intraday ? "hor\xE1rios" : "di\xE1rios"} no per\xEDodo.</span>`;
41048
41120
  return;
41049
41121
  }
41050
- const fmtTs = (ts) => gran === "1h" ? new Date(ts).toLocaleString("pt-BR", {
41122
+ const fmtTs = (ts) => intraday ? new Date(ts).toLocaleString("pt-BR", {
41051
41123
  day: "2-digit",
41052
41124
  month: "2-digit",
41053
41125
  year: "numeric",
@@ -41055,15 +41127,16 @@ var AllReportModal = class {
41055
41127
  minute: "2-digit",
41056
41128
  timeZone: "America/Sao_Paulo"
41057
41129
  }) : new Date(ts).toLocaleDateString("pt-BR", { timeZone: "America/Sao_Paulo" });
41058
- const valueLabel = this.isTemperature ? gran === "1h" ? "Temperatura (\xB0C)" : "M\xE9dia do dia (\xB0C)" : this.domainConfig.label;
41059
- if (this.bucketMoney(id, points[0].timestamp, gran, points[0].value)) {
41060
- const money = points.map((p) => this.bucketMoney(id, p.timestamp, gran, p.value));
41130
+ const valueLabel = this.isTemperature ? intraday ? "Temperatura (\xB0C)" : "M\xE9dia do dia (\xB0C)" : this.domainConfig.label;
41131
+ const moneyGran = intraday ? "1h" : "1d";
41132
+ if (this.bucketMoney(id, points[0].timestamp, moneyGran, points[0].value)) {
41133
+ const money = points.map((p) => this.bucketMoney(id, p.timestamp, moneyGran, p.value));
41061
41134
  const cell = (m) => m && m.state === "complete" && m.amount ? formatBRL(m.amount) : `<span class="rp-muted" title="Sem custo estimado para este intervalo">\u2014</span>`;
41062
41135
  const sub = sumItemMoney(money);
41063
41136
  const subCell = sub.state === "complete" && sub.amount ? formatBRL(sub.amount) : `<span class="rp-muted">Cobertura incompleta (${sub.covered} de ${sub.total})</span>`;
41064
41137
  box.innerHTML = `
41065
41138
  <table>
41066
- <thead><tr><th>${gran === "1h" ? "Data/Hora" : "Dia"}</th><th class="num">${valueLabel}</th><th class="num">${this.moneyHeaderLabel()}</th></tr></thead>
41139
+ <thead><tr><th>${intraday ? "Data/Hora" : "Dia"}</th><th class="num">${valueLabel}</th><th class="num">${this.moneyHeaderLabel()}</th></tr></thead>
41067
41140
  <tbody>${points.map((p, i) => `<tr><td>${fmtTs(p.timestamp)}</td><td class="num">${fmtPt(p.value)}</td><td class="num" data-money-cell="1">${cell(money[i])}</td></tr>`).join("")}</tbody>
41068
41141
  <tfoot><tr><td><strong>Subtotal</strong></td><td class="num"><strong>${fmtPt(points.reduce((s, p) => s + p.value, 0))}</strong></td><td class="num" data-money-subtotal="1"><strong>${subCell}</strong></td></tr></tfoot>
41069
41142
  </table>`;
@@ -41071,7 +41144,7 @@ var AllReportModal = class {
41071
41144
  }
41072
41145
  box.innerHTML = `
41073
41146
  <table>
41074
- <thead><tr><th>${gran === "1h" ? "Data/Hora" : "Dia"}</th><th class="num">${valueLabel}</th></tr></thead>
41147
+ <thead><tr><th>${intraday ? "Data/Hora" : "Dia"}</th><th class="num">${valueLabel}</th></tr></thead>
41075
41148
  <tbody>${points.map((p) => `<tr><td>${fmtTs(p.timestamp)}</td><td class="num">${fmtPt(p.value)}</td></tr>`).join("")}</tbody>
41076
41149
  </table>`;
41077
41150
  } catch (err) {
@@ -41086,8 +41159,9 @@ var AllReportModal = class {
41086
41159
  async getDeviceSeries(id, gran) {
41087
41160
  if (this.isTemperature) {
41088
41161
  const raw = this.temperatureStats.get(id)?.series || [];
41089
- return gran === "1h" ? this.aggregateHourly(raw, "avg") : this.aggregateDaily(raw, "avg");
41162
+ return gran === "1d" ? this.aggregateDaily(raw, "avg") : this.aggregateHourly(raw, "avg", granularityMinutes(gran));
41090
41163
  }
41164
+ if (gran !== "1h" && gran !== "1d") gran = "1h";
41091
41165
  const key = `${gran}|${id}`;
41092
41166
  const cached = this.deviceSeriesCache.get(key);
41093
41167
  if (cached) return cached;
@@ -41111,10 +41185,10 @@ var AllReportModal = class {
41111
41185
  const ent = Array.isArray(body) ? body[0] : body;
41112
41186
  return (ent?.consumption || []).map((p) => ({ timestamp: new Date(p?.timestamp).getTime(), value: Number(p?.value) })).filter((p) => Number.isFinite(p.timestamp) && Number.isFinite(p.value)).sort((a, b) => a.timestamp - b.timestamp);
41113
41187
  }
41114
- // Consolida em HORA FECHADA (início da hora): média (temperatura) ou soma (consumo).
41115
- // Fusos inteiros → a hora UTC coincide com a hora de São Paulo.
41116
- aggregateHourly(points, mode) {
41117
- const HOUR = 3600 * 1e3;
41188
+ // Consolida em JANELA FECHADA de `minutes` (padrão 60 = hora; 15/30 em temperatura):
41189
+ // média (temperatura) ou soma (consumo). Fusos inteiros → alinha também em São Paulo.
41190
+ aggregateHourly(points, mode, minutes = 60) {
41191
+ const HOUR = minutes * 60 * 1e3;
41118
41192
  const byHour = /* @__PURE__ */ new Map();
41119
41193
  for (const p of points) {
41120
41194
  const h3 = Math.floor(p.timestamp / HOUR) * HOUR;
@@ -41125,6 +41199,10 @@ var AllReportModal = class {
41125
41199
  }
41126
41200
  return [...byHour.entries()].sort((a, b) => a[0] - b[0]).map(([h3, { sum: sum2, n }]) => ({ timestamp: h3, value: mode === "avg" ? sum2 / n : sum2 }));
41127
41201
  }
41202
+ // "hora" | "15 minutos" | "30 minutos" | "dia" — textos de ▸ e CSV
41203
+ granularityNoun(g) {
41204
+ return { "15m": "15 minutos", "30m": "30 minutos", "1h": "hora", "1d": "dia" }[g];
41205
+ }
41128
41206
  // Agrega série horária por dia civil (São Paulo): média (temperatura) ou soma (consumo)
41129
41207
  aggregateDaily(points, mode) {
41130
41208
  const byDay = /* @__PURE__ */ new Map();
@@ -41400,7 +41478,7 @@ var AllReportModal = class {
41400
41478
  ["Relat\xF3rio", this.resolveTitle()],
41401
41479
  ...this.params.customerName ? [["Cliente", this.params.customerName]] : [],
41402
41480
  ...p?.startISO ? [["Per\xEDodo", `${fmtD(p.startISO)} \u2014 ${fmtD(p.endISO)}`]] : [],
41403
- ["Granularidade", gran === "1h" ? "Hora" : "Dia"],
41481
+ ["Granularidade", { "15m": "15 minutos", "30m": "30 minutos", "1h": "Hora", "1d": "Dia" }[gran]],
41404
41482
  ["Gerado em", (/* @__PURE__ */ new Date()).toLocaleString("pt-BR")],
41405
41483
  [],
41406
41484
  ...this.computeKpis().map((k) => [k.label, k.value, k.sub || ""]),
@@ -41421,8 +41499,8 @@ var AllReportModal = class {
41421
41499
  String(r.discarded ?? "")
41422
41500
  ])
41423
41501
  ];
41424
- const series = [[...idHead, "Sensor", gran === "1h" ? "Data/Hora" : "Dia", "Temperatura (\xB0C)"]];
41425
- const fmtTs = (ts) => gran === "1h" ? new Date(ts).toLocaleString("pt-BR", {
41502
+ const series = [[...idHead, "Sensor", gran !== "1d" ? "Data/Hora" : "Dia", "Temperatura (\xB0C)"]];
41503
+ const fmtTs = (ts) => gran !== "1d" ? new Date(ts).toLocaleString("pt-BR", {
41426
41504
  day: "2-digit",
41427
41505
  month: "2-digit",
41428
41506
  year: "numeric",
@@ -41432,7 +41510,7 @@ var AllReportModal = class {
41432
41510
  }) : new Date(ts).toLocaleDateString("pt-BR", { timeZone: "America/Sao_Paulo" });
41433
41511
  for (const r of rows) {
41434
41512
  const raw = r.id && this.temperatureStats.get(r.id)?.series || [];
41435
- const pts = gran === "1h" ? this.aggregateHourly(raw, "avg") : this.aggregateDaily(raw, "avg");
41513
+ const pts = gran === "1d" ? this.aggregateDaily(raw, "avg") : this.aggregateHourly(raw, "avg", granularityMinutes(gran));
41436
41514
  for (const p2 of pts) series.push([...idCol(r), r.name, fmtTs(p2.timestamp), n2(p2.value)]);
41437
41515
  }
41438
41516
  const csvContent = toCsv([...meta, ...summary, [], ...series]);
@@ -87594,7 +87672,109 @@ ${state6.year}-03-15T08,15`)}">${esc6(state6.csv)}</textarea>
87594
87672
  return instance;
87595
87673
  }
87596
87674
 
87675
+ // src/components/temperature/currentTemperature.ts
87676
+ var DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES = 120;
87677
+ async function safe(fn) {
87678
+ if (!fn) return null;
87679
+ try {
87680
+ const r = await fn();
87681
+ return r && Number.isFinite(r.ts) && Number.isFinite(r.value) ? r : null;
87682
+ } catch (err) {
87683
+ console.warn("[TemperatureModal] Falha ao buscar a \xFAltima leitura:", err?.message || err);
87684
+ return null;
87685
+ }
87686
+ }
87687
+ async function resolveCurrentTemperature(opts) {
87688
+ const now = opts.now ?? Date.now();
87689
+ const maxAge = opts.maxAgeMinutes ?? DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES;
87690
+ const ok = (r) => !!r && (!opts.isValid || opts.isValid(r.value));
87691
+ const wrap = (r, source) => {
87692
+ const ageMinutes = Math.max(0, (now - r.ts) / 6e4);
87693
+ return { ...r, source, ageMinutes, fresh: ageMinutes <= maxAge };
87694
+ };
87695
+ const tb = await safe(opts.fetchThingsboardLatest);
87696
+ if (tb && ok(tb) && (now - tb.ts) / 6e4 <= maxAge) return wrap(tb, "thingsboard");
87697
+ const ing = await safe(opts.fetchIngestionLatest);
87698
+ if (ing && ok(ing)) return wrap(ing, "ingestion");
87699
+ if (tb && ok(tb)) return wrap(tb, "thingsboard");
87700
+ return null;
87701
+ }
87702
+ async function fetchThingsboardLatestTemperature(token, deviceId) {
87703
+ const res = await fetch(`/api/plugins/telemetry/DEVICE/${deviceId}/values/timeseries?keys=temperature`, {
87704
+ headers: { "X-Authorization": `Bearer ${token}`, "Content-Type": "application/json" }
87705
+ });
87706
+ if (!res.ok) throw new Error(`ThingsBoard ${res.status}`);
87707
+ const json = await res.json();
87708
+ const p = json?.temperature?.[0];
87709
+ if (!p) return null;
87710
+ const value = Number(p.value);
87711
+ const ts = Number(p.ts);
87712
+ return Number.isFinite(value) && Number.isFinite(ts) ? { ts, value } : null;
87713
+ }
87714
+ var INGESTION_LATEST_WINDOWS = [
87715
+ { days: 1, intervalMinutes: 15 },
87716
+ { days: 7, intervalMinutes: 60 },
87717
+ { days: 90, intervalMinutes: 60 }
87718
+ ];
87719
+ async function fetchIngestionLatestTemperature(aggregateFetcher, now = Date.now(), windows = INGESTION_LATEST_WINDOWS, isValid) {
87720
+ for (const w of windows) {
87721
+ const points = await aggregateFetcher(now - w.days * 24 * 60 * 60 * 1e3, now, w.intervalMinutes);
87722
+ 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)));
87723
+ if (valid.length) {
87724
+ const last = valid.reduce((a, b) => b.ts > a.ts ? b : a);
87725
+ return { ts: Math.min(now, last.ts + w.intervalMinutes * 60 * 1e3), value: last.value };
87726
+ }
87727
+ }
87728
+ return null;
87729
+ }
87730
+ function makeTemperatureValidator(clampRange, offset) {
87731
+ const off = Number(offset) || 0;
87732
+ return (value) => {
87733
+ const v = Number(value) + off;
87734
+ return Number.isFinite(v) && v >= clampRange.min && v <= clampRange.max;
87735
+ };
87736
+ }
87737
+ function createIngestionTemperatureAggregateFetcher(cfg) {
87738
+ const tz = cfg.timezone || "America/Sao_Paulo";
87739
+ const doFetch = cfg.fetchImpl || ((...a) => fetch(...a));
87740
+ const base = String(cfg.apiHost || "").replace(/\/+$/, "");
87741
+ return async (startTs, endTs, intervalMinutes) => {
87742
+ const interval = intervalMinutes >= 60 && intervalMinutes % 60 === 0 ? `${intervalMinutes / 60} hour` : `${Math.max(15, Math.round(intervalMinutes))} minutes`;
87743
+ const url = new URL(`${base}/temperature-readings/aggregate`);
87744
+ url.searchParams.set("gatewayId", String(cfg.gatewayId));
87745
+ url.searchParams.set("slaveId", String(cfg.slaveId));
87746
+ url.searchParams.set("startTs", new Date(startTs).toISOString());
87747
+ url.searchParams.set("endTs", new Date(endTs).toISOString());
87748
+ url.searchParams.set("interval", interval);
87749
+ url.searchParams.set("timezone", tz);
87750
+ let token = null;
87751
+ try {
87752
+ token = cfg.getToken ? await cfg.getToken() : null;
87753
+ } catch {
87754
+ token = null;
87755
+ }
87756
+ const res = await doFetch(url.toString(), token ? { headers: { Authorization: `Bearer ${token}` } } : void 0);
87757
+ if (!res.ok) throw new Error(`Ingestion aggregate ${res.status}`);
87758
+ const rows = await res.json();
87759
+ return (Array.isArray(rows) ? rows : []).map((r) => ({
87760
+ ts: new Date(String(r.bucket)).getTime(),
87761
+ value: Number(r.avg_temperature)
87762
+ })).filter((p) => Number.isFinite(p.ts) && Number.isFinite(p.value)).sort((a, b) => a.ts - b.ts);
87763
+ };
87764
+ }
87765
+
87597
87766
  // src/components/temperature/TemperatureModal.ts
87767
+ var GRANULARITY_MINUTES = {
87768
+ "15min": 15,
87769
+ "30min": 30,
87770
+ hour: 60
87771
+ };
87772
+ var GRANULARITY_LABEL = {
87773
+ "15min": "15 minutos",
87774
+ "30min": "30 minutos",
87775
+ hour: "Hora",
87776
+ day: "Dia (m\xE9dia)"
87777
+ };
87598
87778
  var _footers = /* @__PURE__ */ new Map();
87599
87779
  function escHtml3(s) {
87600
87780
  return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -87641,6 +87821,10 @@ async function openTemperatureModal(params) {
87641
87821
  selectedPeriods: ["madrugada", "manha", "tarde", "noite"],
87642
87822
  // All periods selected by default
87643
87823
  dataFetcher: params.dataFetcher ?? null,
87824
+ aggregateFetcher: params.aggregateFetcher ?? null,
87825
+ dataMode: "",
87826
+ currentMaxAgeMinutes: Number(params.currentTemperatureMaxAgeMinutes) > 0 ? Number(params.currentTemperatureMaxAgeMinutes) : DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
87827
+ current: null,
87644
87828
  deviceName: params.deviceName || "",
87645
87829
  customerName: resolveCustomerName(params.customerName),
87646
87830
  accent: resolveAccent(
@@ -87652,18 +87836,15 @@ async function openTemperatureModal(params) {
87652
87836
  }
87653
87837
  const savedGranularity = localStorage.getItem("myio-temp-modal-granularity");
87654
87838
  const savedTheme = localStorage.getItem("myio-temp-modal-theme");
87655
- if (savedGranularity) state6.granularity = savedGranularity;
87839
+ if (savedGranularity && savedGranularity in GRANULARITY_LABEL) state6.granularity = savedGranularity;
87840
+ if (!isGranularityAvailable(state6, state6.granularity)) state6.granularity = "hour";
87656
87841
  if (savedTheme && !params.theme) state6.theme = savedTheme;
87657
87842
  const modalContainer = document.createElement("div");
87658
87843
  modalContainer.id = modalId;
87659
87844
  document.body.appendChild(modalContainer);
87660
87845
  renderModal3(modalContainer, state6, modalId);
87661
87846
  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);
87847
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87667
87848
  state6.isLoading = false;
87668
87849
  renderModal3(modalContainer, state6, modalId);
87669
87850
  drawChart2(modalId, state6);
@@ -87683,15 +87864,11 @@ async function openTemperatureModal(params) {
87683
87864
  updateData: async (startDate, endDate, granularity) => {
87684
87865
  state6.startTs = new Date(startDate).getTime();
87685
87866
  state6.endTs = new Date(endDate).getTime();
87686
- if (granularity) state6.granularity = granularity;
87867
+ if (granularity && isGranularityAvailable(state6, granularity)) state6.granularity = granularity;
87687
87868
  state6.isLoading = true;
87688
87869
  renderModal3(modalContainer, state6, modalId);
87689
87870
  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);
87871
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
87695
87872
  state6.isLoading = false;
87696
87873
  renderModal3(modalContainer, state6, modalId);
87697
87874
  drawChart2(modalId, state6);
@@ -87703,12 +87880,75 @@ async function openTemperatureModal(params) {
87703
87880
  }
87704
87881
  };
87705
87882
  }
87883
+ function isGranularityAvailable(state6, g) {
87884
+ const m = GRANULARITY_MINUTES[g];
87885
+ if (!m || m >= 60) return true;
87886
+ return !!state6.aggregateFetcher || !state6.dataFetcher;
87887
+ }
87888
+ function dataModeFor(state6) {
87889
+ const m = GRANULARITY_MINUTES[state6.granularity];
87890
+ return m && m < 60 && state6.aggregateFetcher ? `agg:${m}` : "raw";
87891
+ }
87892
+ async function loadSeries(state6) {
87893
+ const mode = dataModeFor(state6);
87894
+ 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));
87895
+ state6.data = discardInvalid(raw || [], state6);
87896
+ state6.dataMode = mode;
87897
+ state6.stats = calculateStats(state6.data, state6.clampRange, state6.temperatureOffset);
87898
+ }
87899
+ async function refreshCurrent(state6) {
87900
+ try {
87901
+ const isValid = makeTemperatureValidator(state6.clampRange, state6.temperatureOffset);
87902
+ const latestSource = state6.aggregateFetcher ?? (state6.dataFetcher ? (s, e) => state6.dataFetcher(s, e) : null);
87903
+ state6.current = await resolveCurrentTemperature({
87904
+ maxAgeMinutes: state6.currentMaxAgeMinutes,
87905
+ isValid,
87906
+ fetchThingsboardLatest: state6.token && state6.deviceId ? () => fetchThingsboardLatestTemperature(state6.token, state6.deviceId) : void 0,
87907
+ fetchIngestionLatest: latestSource ? () => fetchIngestionLatestTemperature(latestSource, Date.now(), void 0, isValid) : void 0
87908
+ });
87909
+ } catch (err) {
87910
+ console.warn("[TemperatureModal] Temperatura atual indispon\xEDvel:", err);
87911
+ state6.current = null;
87912
+ }
87913
+ }
87914
+ function currentStatus(state6, value) {
87915
+ if (value === null) return state6.temperatureStatus;
87916
+ if (state6.temperatureMin === null || state6.temperatureMax === null) return state6.temperatureStatus;
87917
+ return value > state6.temperatureMax ? "above" : value < state6.temperatureMin ? "below" : "ok";
87918
+ }
87919
+ function displayedCurrent(state6) {
87920
+ if (state6.current) return state6.current.value + (Number(state6.temperatureOffset) || 0);
87921
+ return state6.currentTemperature;
87922
+ }
87923
+ function currentSourceText(state6) {
87924
+ const c = state6.current;
87925
+ if (!c) return "";
87926
+ const src = c.source === "thingsboard" ? "ThingsBoard" : "Ingestion";
87927
+ if (c.fresh) {
87928
+ const m = Math.round(c.ageMinutes);
87929
+ const age = m < 1 ? "agora" : m < 60 ? `h\xE1 ${m} min` : `h\xE1 ${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}`;
87930
+ return `${src} \xB7 ${age}`;
87931
+ }
87932
+ const when = new Date(c.ts).toLocaleString(state6.locale, {
87933
+ day: "2-digit",
87934
+ month: "2-digit",
87935
+ year: "numeric",
87936
+ hour: "2-digit",
87937
+ minute: "2-digit",
87938
+ timeZone: state6.timezone || "America/Sao_Paulo"
87939
+ });
87940
+ return `\xDAltima leitura ${when} (${src})`;
87941
+ }
87706
87942
  function renderModal3(container, state6, modalId, error) {
87707
87943
  const colors2 = getThemeColors(state6.theme);
87708
87944
  const startDateStr = new Date(state6.startTs).toLocaleDateString(state6.locale);
87709
87945
  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;
87946
+ const currentValue = displayedCurrent(state6);
87947
+ const status = currentStatus(state6, state6.current ? currentValue : null);
87948
+ const staleCurrent = !!state6.current && !state6.current.fresh;
87949
+ const statusText = (status === "ok" ? "Dentro da faixa" : status === "above" ? "Acima do limite" : status === "below" ? "Abaixo do limite" : "N/A") + (staleCurrent ? " (leitura antiga)" : "");
87950
+ const statusColor = staleCurrent ? colors2.textMuted : status === "ok" ? colors2.success : status === "above" ? colors2.danger : status === "below" ? colors2.primary : colors2.textMuted;
87951
+ const currentSource = currentSourceText(state6);
87712
87952
  const rangeText = state6.temperatureMin !== null && state6.temperatureMax !== null ? `${state6.temperatureMin}\xB0C - ${state6.temperatureMax}\xB0C` : "N\xE3o definida";
87713
87953
  const startDateInput = new Date(state6.startTs).toISOString().slice(0, 16);
87714
87954
  const endDateInput = new Date(state6.endTs).toISOString().slice(0, 16);
@@ -87767,8 +88007,10 @@ function renderModal3(container, state6, modalId, error) {
87767
88007
  font-size: 14px; color: ${colors2.text}; background: ${colors2.surface};
87768
88008
  cursor: pointer; min-width: 130px;
87769
88009
  ">
87770
- <option value="hour" ${state6.granularity === "hour" ? "selected" : ""}>Hora</option>
87771
- <option value="day" ${state6.granularity === "day" ? "selected" : ""}>Dia (m\xE9dia)</option>
88010
+ ${Object.keys(GRANULARITY_LABEL).map((g) => {
88011
+ const ok = isGranularityAvailable(state6, g);
88012
+ return `<option value="${g}" ${state6.granularity === g ? "selected" : ""} ${ok ? "" : 'disabled title="Indispon\xEDvel para esta fonte de dados"'}>${GRANULARITY_LABEL[g]}</option>`;
88013
+ }).join("")}
87772
88014
  </select>
87773
88015
  </div>
87774
88016
  <!-- Day Period Filter (Multiselect) -->
@@ -87856,9 +88098,10 @@ function renderModal3(container, state6, modalId, error) {
87856
88098
  ">
87857
88099
  <span style="color: ${colors2.textMuted}; font-size: 12px; font-weight: 500;">Temperatura Atual</span>
87858
88100
  <div style="font-weight: 700; font-size: 24px; color: ${statusColor}; margin-top: 4px;">
87859
- ${state6.currentTemperature !== null ? formatTemperature(state6.currentTemperature) : "N/A"}
88101
+ ${currentValue !== null ? formatTemperature(currentValue) : "N/A"}
87860
88102
  </div>
87861
88103
  <div style="font-size: 11px; color: ${statusColor}; margin-top: 2px;">${statusText}</div>
88104
+ ${currentSource ? `<div style="font-size: 10px; color: ${colors2.textMuted}; margin-top: 2px;">${escHtml3(currentSource)}</div>` : ""}
87862
88105
  </div>
87863
88106
  <!-- Average -->
87864
88107
  <div style="
@@ -87978,9 +88221,10 @@ function drawChart2(modalId, state6) {
87978
88221
  return;
87979
88222
  }
87980
88223
  let chartData;
87981
- if (state6.granularity === "hour") {
87982
- const hourly = aggregateByHour(filteredData, state6.clampRange, state6.temperatureOffset);
87983
- chartData = hourly.map((item) => ({
88224
+ const windowMinutes = GRANULARITY_MINUTES[state6.granularity];
88225
+ if (windowMinutes) {
88226
+ const series = aggregateByMinutes(filteredData, windowMinutes, state6.clampRange, state6.temperatureOffset);
88227
+ chartData = series.map((item) => ({
87984
88228
  x: item.ts,
87985
88229
  y: Number(item.value),
87986
88230
  screenX: 0,
@@ -88080,33 +88324,16 @@ function drawChart2(modalId, state6) {
88080
88324
  ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 8, y + 4);
88081
88325
  }
88082
88326
  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
- }
88327
+ const tz = state6.timezone || "America/Sao_Paulo";
88328
+ for (const tick of buildXAxisTicks(chartData, state6.granularity, tz, state6.locale, isPeriodsFiltered, paddingLeft, chartWidth)) {
88101
88329
  ctx.strokeStyle = colors2.chartGrid;
88102
88330
  ctx.lineWidth = 1;
88103
88331
  ctx.beginPath();
88104
- ctx.moveTo(point.screenX, paddingTop);
88105
- ctx.lineTo(point.screenX, height - paddingBottom);
88332
+ ctx.moveTo(tick.screenX, paddingTop);
88333
+ ctx.lineTo(tick.screenX, height - paddingBottom);
88106
88334
  ctx.stroke();
88107
88335
  ctx.fillStyle = colors2.textMuted;
88108
- ctx.fillText(label, point.screenX, height - paddingBottom + 18);
88109
- if (subLabel) ctx.fillText(subLabel, point.screenX, height - paddingBottom + 31);
88336
+ ctx.fillText(tick.label, tick.screenX, height - paddingBottom + 18);
88110
88337
  }
88111
88338
  ctx.strokeStyle = colors2.border;
88112
88339
  ctx.lineWidth = 1;
@@ -88117,6 +88344,41 @@ function drawChart2(modalId, state6) {
88117
88344
  ctx.stroke();
88118
88345
  setupChartTooltip2(canvas, chartContainer, chartData, state6, colors2);
88119
88346
  }
88347
+ function buildXAxisTicks(chartData, granularity, timezone, locale, indexBased, paddingLeft, chartWidth) {
88348
+ if (!chartData.length) return [];
88349
+ const minX = chartData[0].x;
88350
+ const maxX = chartData[chartData.length - 1].x;
88351
+ const dayLabel = (ts) => new Date(ts).toLocaleDateString(locale, { day: "2-digit", month: "2-digit", timeZone: timezone });
88352
+ if (maxX - minX > 24 * 60 * 60 * 1e3) {
88353
+ const range = maxX - minX || 1;
88354
+ const out2 = [];
88355
+ const seen = /* @__PURE__ */ new Set();
88356
+ for (const ts of buildDayTicks(minX, maxX, timezone, 8)) {
88357
+ let screenX;
88358
+ if (indexBased) {
88359
+ const p = chartData.find((d) => d.x >= ts);
88360
+ if (!p) continue;
88361
+ screenX = p.screenX;
88362
+ } else {
88363
+ screenX = paddingLeft + (ts - minX) / range * chartWidth;
88364
+ }
88365
+ const key = Math.round(screenX);
88366
+ if (seen.has(key)) continue;
88367
+ seen.add(key);
88368
+ out2.push({ screenX, label: dayLabel(ts), ts });
88369
+ }
88370
+ return out2;
88371
+ }
88372
+ const numLabels = Math.min(8, chartData.length);
88373
+ const interval = Math.max(1, Math.floor(chartData.length / numLabels));
88374
+ const out = [];
88375
+ for (let i = 0; i < chartData.length; i += interval) {
88376
+ const p = chartData[i];
88377
+ const label = granularity === "day" ? dayLabel(p.x) : new Date(p.x).toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", timeZone: timezone });
88378
+ out.push({ screenX: p.screenX, label, ts: p.x });
88379
+ }
88380
+ return out;
88381
+ }
88120
88382
  function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88121
88383
  const existingTooltip = container.querySelector(".myio-chart-tooltip");
88122
88384
  if (existingTooltip) existingTooltip.remove();
@@ -88161,7 +88423,7 @@ function setupChartTooltip2(canvas, container, chartData, state6, colors2) {
88161
88423
  if (point) {
88162
88424
  const date = new Date(point.x);
88163
88425
  let dateStr;
88164
- if (state6.granularity === "hour") {
88426
+ if (state6.granularity !== "day") {
88165
88427
  dateStr = date.toLocaleDateString(state6.locale, {
88166
88428
  day: "2-digit",
88167
88429
  month: "2-digit",
@@ -88304,9 +88566,28 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88304
88566
  }
88305
88567
  if (state6.data.length > 0) drawChart2(modalId, state6);
88306
88568
  });
88307
- document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
88308
- state6.granularity = e.target.value;
88569
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", async (e) => {
88570
+ const next = e.target.value;
88571
+ if (!isGranularityAvailable(state6, next)) return;
88572
+ state6.granularity = next;
88309
88573
  localStorage.setItem("myio-temp-modal-granularity", state6.granularity);
88574
+ if (dataModeFor(state6) !== state6.dataMode) {
88575
+ state6.isLoading = true;
88576
+ state6.dateRangePicker = null;
88577
+ renderModal3(container, state6, modalId);
88578
+ try {
88579
+ await loadSeries(state6);
88580
+ state6.isLoading = false;
88581
+ renderModal3(container, state6, modalId);
88582
+ drawChart2(modalId, state6);
88583
+ } catch (error) {
88584
+ console.error("[TemperatureModal] Error fetching data:", error);
88585
+ state6.isLoading = false;
88586
+ renderModal3(container, state6, modalId, error);
88587
+ }
88588
+ await setupEventListeners3(container, state6, modalId, onClose);
88589
+ return;
88590
+ }
88310
88591
  if (state6.data.length > 0) drawChart2(modalId, state6);
88311
88592
  });
88312
88593
  document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
@@ -88318,11 +88599,7 @@ async function setupEventListeners3(container, state6, modalId, onClose) {
88318
88599
  state6.dateRangePicker = null;
88319
88600
  renderModal3(container, state6, modalId);
88320
88601
  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);
88602
+ await Promise.all([loadSeries(state6), refreshCurrent(state6)]);
88326
88603
  state6.isLoading = false;
88327
88604
  renderModal3(container, state6, modalId);
88328
88605
  drawChart2(modalId, state6);
@@ -88362,21 +88639,26 @@ function exportCsv(state6) {
88362
88639
  ...state6.deviceName ? [["Dispositivo (TB)", state6.deviceName]] : [],
88363
88640
  ...state6.customerName ? [["Cliente", state6.customerName]] : [],
88364
88641
  ["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)"],
88642
+ [
88643
+ "Granularidade",
88644
+ state6.granularity === "day" ? "Dia (m\xE9dia do dia)" : `${GRANULARITY_LABEL[state6.granularity]} (m\xE9dia da janela fechada)`
88645
+ ],
88366
88646
  ["Per\xEDodos do dia", getSelectedPeriodsLabel(state6.selectedPeriods)],
88367
88647
  ...off !== 0 ? [["Offset aplicado (\xB0C)", n2(off)]] : [],
88368
88648
  ["Gerado em", (/* @__PURE__ */ new Date()).toLocaleString("pt-BR")],
88369
88649
  [],
88370
- ["Temperatura atual (\xB0C)", state6.currentTemperature !== null ? n2(state6.currentTemperature) : "N/A"],
88650
+ ["Temperatura atual (\xB0C)", displayedCurrent(state6) !== null ? n2(displayedCurrent(state6)) : "N/A"],
88651
+ ...state6.current ? [["Origem da temperatura atual", currentSourceText(state6)]] : [],
88371
88652
  ["M\xE9dia do per\xEDodo (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.avg) : "N/A"],
88372
88653
  ["M\xEDnima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.min) : "N/A"],
88373
88654
  ["M\xE1xima (\xB0C)", state6.stats.count > 0 ? n2(state6.stats.max) : "N/A"],
88374
88655
  ["Leituras", String(state6.stats.count)],
88375
88656
  []
88376
88657
  ];
88377
- if (state6.granularity === "hour") {
88658
+ const csvMinutes = GRANULARITY_MINUTES[state6.granularity];
88659
+ if (csvMinutes) {
88378
88660
  lines.push(["Data/Hora", "Temperatura (\xB0C)"]);
88379
- aggregateByHour(filtered, state6.clampRange, off).forEach((p) => lines.push([dt(p.ts), n2(Number(p.value))]));
88661
+ aggregateByMinutes(filtered, csvMinutes, state6.clampRange, off).forEach((p) => lines.push([dt(p.ts), n2(Number(p.value))]));
88380
88662
  } else {
88381
88663
  lines.push(["Dia", "M\xE9dia (\xB0C)", "M\xEDn (\xB0C)", "M\xE1x (\xB0C)", "Leituras"]);
88382
88664
  aggregateByDay(filtered, state6.clampRange, off).forEach(
@@ -88388,7 +88670,8 @@ function exportCsv(state6) {
88388
88670
  const url = URL.createObjectURL(blob);
88389
88671
  const a = document.createElement("a");
88390
88672
  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`;
88673
+ const suffix = { "15min": "15min", "30min": "30min", hour: "1h", day: "1d" }[state6.granularity];
88674
+ a.download = `temperatura_${state6.label.replace(/\s+/g, "_")}_${suffix}_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
88392
88675
  document.body.appendChild(a);
88393
88676
  a.click();
88394
88677
  document.body.removeChild(a);
@@ -144391,8 +144674,8 @@ var TelemetryInfoShoppingView = class _TelemetryInfoShoppingView {
144391
144674
  // consistently (ported from v-5.2.0 TELEMETRY_INFO where (i) is on practically every metric).
144392
144675
  tooltipSpan(tooltip) {
144393
144676
  if (!tooltip) return "";
144394
- const safe = String(tooltip).replace(/"/g, "&quot;");
144395
- return `<span class="tis-tooltip" title="${safe}">\u2139\uFE0F</span>`;
144677
+ const safe2 = String(tooltip).replace(/"/g, "&quot;");
144678
+ return `<span class="tis-tooltip" title="${safe2}">\u2139\uFE0F</span>`;
144396
144679
  }
144397
144680
  buildWaterCards() {
144398
144681
  const config2 = WATER_CATEGORY_CONFIG;
@@ -159082,9 +159365,9 @@ var FancoilRemoteController = class {
159082
159365
  });
159083
159366
  }
159084
159367
  async handlePowerToggle() {
159085
- const currentStatus = this.state.status;
159086
- if (currentStatus === "offline") return;
159087
- const newStatus = currentStatus === "on" ? "off" : "on";
159368
+ const currentStatus2 = this.state.status;
159369
+ if (currentStatus2 === "offline") return;
159370
+ const newStatus = currentStatus2 === "on" ? "off" : "on";
159088
159371
  const actionText = newStatus === "on" ? "LIGAR" : "DESLIGAR";
159089
159372
  if (this.onConfirmAction) {
159090
159373
  const confirmed = await this.onConfirmAction(
@@ -159101,7 +159384,7 @@ var FancoilRemoteController = class {
159101
159384
  }
159102
159385
  if (this.onPowerToggle) {
159103
159386
  try {
159104
- const success = await this.onPowerToggle(currentStatus);
159387
+ const success = await this.onPowerToggle(currentStatus2);
159105
159388
  if (success) {
159106
159389
  this.state.status = newStatus;
159107
159390
  this.view.updateState({ status: newStatus });
@@ -166169,8 +166452,8 @@ var OnOffDeviceModalView = class {
166169
166452
  deviceName: this.device.label || this.device.name || "Dispositivo",
166170
166453
  relatedDevices: []
166171
166454
  },
166172
- onToggle: async (currentStatus) => {
166173
- const newState = currentStatus !== "on";
166455
+ onToggle: async (currentStatus2) => {
166456
+ const newState = currentStatus2 !== "on";
166174
166457
  this.onDeviceToggle(newState);
166175
166458
  return true;
166176
166459
  }
@@ -180252,6 +180535,7 @@ var version = package_default.version || "0.0.0";
180252
180535
  DEFAULT_ANNOTATION_SORT,
180253
180536
  DEFAULT_BAS_SETTINGS,
180254
180537
  DEFAULT_CLAMP_RANGE,
180538
+ DEFAULT_CURRENT_TEMPERATURE_MAX_AGE_MINUTES,
180255
180539
  DEFAULT_DASHBOARD_KPIS,
180256
180540
  DEFAULT_DAYS_WEEK,
180257
180541
  DEFAULT_DEVICE_CLASSIFICATION_PROFILE,
@@ -180657,6 +180941,7 @@ var version = package_default.version || "0.0.0";
180657
180941
  createHeaderShoppingComponent,
180658
180942
  createHttpDeviceCategoryPort,
180659
180943
  createImgGallery,
180944
+ createIngestionTemperatureAggregateFetcher,
180660
180945
  createInputDateRangePickerInsideDIV,
180661
180946
  createLibraryVersionChecker,
180662
180947
  createLoadingSpinner,
@@ -181078,6 +181363,7 @@ var version = package_default.version || "0.0.0";
181078
181363
  resolveBudget,
181079
181364
  resolveCategory,
181080
181365
  resolveClassification,
181366
+ resolveCurrentTemperature,
181081
181367
  resolveEffectiveDisplayMode,
181082
181368
  resolveGoalAmount,
181083
181369
  resolveGroup,