myio-js-library 0.1.572 → 0.1.573

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
@@ -94,6 +94,7 @@ __export(src_exports, {
94
94
  DEFAULT_DEVICE_OPERATIONAL_CARD_FILTER_STATE: () => DEFAULT_DEVICE_OPERATIONAL_CARD_FILTER_STATE,
95
95
  DEFAULT_DEVICE_TYPE_PREFIX: () => DEFAULT_DEVICE_TYPE_PREFIX,
96
96
  DEFAULT_DEVICE_TYPE_TOKEN: () => DEFAULT_DEVICE_TYPE_TOKEN,
97
+ DEFAULT_DISTRIBUTION_PROFILE: () => DEFAULT_DISTRIBUTION_PROFILE,
97
98
  DEFAULT_ENABLED_REPORT_ITEMS: () => DEFAULT_ENABLED_REPORT_ITEMS,
98
99
  DEFAULT_ENERGY_GROUP_COLORS: () => DEFAULT_ENERGY_GROUP_COLORS,
99
100
  DEFAULT_EQUIPMENT_FILTER_STATE: () => DEFAULT_EQUIPMENT_FILTER_STATE,
@@ -346,6 +347,7 @@ __export(src_exports, {
346
347
  WELCOME_DEFAULT_PALETTE: () => DEFAULT_PALETTE,
347
348
  Water: () => Water,
348
349
  WaterSummaryTooltip: () => WaterSummaryTooltip,
350
+ accumulatedRows: () => accumulatedRows,
349
351
  adaptGcdrListToLegacyAnnotations: () => adaptGcdrListToLegacyAnnotations,
350
352
  adaptGcdrToLegacyAnnotation: () => adaptGcdrToLegacyAnnotation,
351
353
  adaptLegacyToGcdrInput: () => adaptLegacyToGcdrInput,
@@ -364,6 +366,7 @@ __export(src_exports, {
364
366
  assetLocalToken: () => assetLocalToken,
365
367
  assignShoppingColors: () => assignShoppingColors,
366
368
  averageByDay: () => averageByDay,
369
+ buildAccumulatedTemplateCsv: () => buildAccumulatedTemplateCsv,
367
370
  buildAmbienteGroupData: () => buildAmbienteGroupData,
368
371
  buildAnnotationServiceOrchestrator: () => buildAnnotationServiceOrchestrator,
369
372
  buildAnnotationsCsv: () => buildAnnotationsCsv,
@@ -551,6 +554,7 @@ __export(src_exports, {
551
554
  deviceProductCodeToName: () => deviceProductCodeToName,
552
555
  deviceStatusIcons: () => deviceStatusIcons,
553
556
  deviceTypeToken: () => deviceTypeToken,
557
+ distributeTotal: () => distributeTotal,
554
558
  doSchedulesOverlap: () => doSchedulesOverlap,
555
559
  downloadAnnotationsTextFile: () => downloadTextFile,
556
560
  encodeDeviceProductCode: () => encodeDeviceProductCode,
@@ -954,7 +958,7 @@ module.exports = __toCommonJS(src_exports);
954
958
  // package.json
955
959
  var package_default = {
956
960
  name: "myio-js-library",
957
- version: "0.1.572",
961
+ version: "0.1.573",
958
962
  description: "A clean, standalone JS SDK for MYIO projects",
959
963
  license: "MIT",
960
964
  repository: "github:gh-myio/myio-js-library",
@@ -23248,8 +23252,8 @@ function renderCardComponentV6({
23248
23252
  const dp = String(deviceProfile2 || "").toUpperCase();
23249
23253
  if (isSolenoidDeviceType(deviceProfile2) || isSolenoidDeviceType(deviceType2)) {
23250
23254
  const statusLower = String(solenoidStatus || "").toLowerCase();
23251
- const isOpen = statusLower === "off" || statusLower === "" || statusLower === "null";
23252
- return isOpen ? "ABERTO" : "FECHADO";
23255
+ const isOpen2 = statusLower === "off" || statusLower === "" || statusLower === "null";
23256
+ return isOpen2 ? "ABERTO" : "FECHADO";
23253
23257
  }
23254
23258
  if (dt === "TANK" || dt === "CAIXA_DAGUA") {
23255
23259
  const percValue = (waterPercentage || 0) * 100;
@@ -23522,8 +23526,8 @@ function renderCardComponentV6({
23522
23526
  }
23523
23527
  const { solenoidStatus: solStatus } = options;
23524
23528
  const statusLower = String(solStatus || "").toLowerCase();
23525
- const isOpen = statusLower === "off" || statusLower === "" || statusLower === "null";
23526
- return isOpen ? SOLENOID_IMAGES.on : SOLENOID_IMAGES.off;
23529
+ const isOpen2 = statusLower === "off" || statusLower === "" || statusLower === "null";
23530
+ return isOpen2 ? SOLENOID_IMAGES.on : SOLENOID_IMAGES.off;
23527
23531
  }
23528
23532
  if (profileType && DEVICE_TYPE_CONFIG[profileType]?.image) {
23529
23533
  return getStaticDeviceImage(profileType);
@@ -53557,8 +53561,8 @@ function bindAnnotationsPanelEvents(panel, alarmId, currentUser, onCountChange,
53557
53561
  };
53558
53562
  panel.querySelector("#admAnnotNewBtn")?.addEventListener("click", () => {
53559
53563
  const wrap = panel.querySelector("#admAnnotFormWrap");
53560
- const isOpen = wrap?.style.display !== "none" && (wrap?.innerHTML ?? "") !== "";
53561
- if (isOpen) closeForm();
53564
+ const isOpen2 = wrap?.style.display !== "none" && (wrap?.innerHTML ?? "") !== "";
53565
+ if (isOpen2) closeForm();
53562
53566
  else openForm();
53563
53567
  });
53564
53568
  bindCardBtns();
@@ -63915,9 +63919,9 @@ var TicketsTab = class {
63915
63919
  const icon2 = container.querySelector("#ct-collapse-icon");
63916
63920
  if (toggle && body) {
63917
63921
  toggle.addEventListener("click", () => {
63918
- const isOpen = body.style.display !== "none";
63919
- body.style.display = isOpen ? "none" : "block";
63920
- if (icon2) icon2.textContent = isOpen ? "\u25BC" : "\u25B2";
63922
+ const isOpen2 = body.style.display !== "none";
63923
+ body.style.display = isOpen2 ? "none" : "block";
63924
+ if (icon2) icon2.textContent = isOpen2 ? "\u25BC" : "\u25B2";
63921
63925
  });
63922
63926
  }
63923
63927
  if (this.config.requesterEmail) {
@@ -101136,8 +101140,8 @@ function createGoalsBarTooltip(opts) {
101136
101140
  const id = btn.dataset.caret;
101137
101141
  const kids = el2.querySelector(`[data-children="${id}"]`);
101138
101142
  if (!kids) return;
101139
- const isOpen = kids.classList.toggle("is-open");
101140
- btn.classList.toggle("is-open", isOpen);
101143
+ const isOpen2 = kids.classList.toggle("is-open");
101144
+ btn.classList.toggle("is-open", isOpen2);
101141
101145
  });
101142
101146
  });
101143
101147
  }
@@ -115263,14 +115267,14 @@ var VALUE_COLUMN = {
115263
115267
  var MAX_IMPORT_ROWS = 5e3;
115264
115268
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
115265
115269
  var pad24 = (n) => String(n).padStart(2, "0");
115270
+ function isImportableKey(d) {
115271
+ const slave = Number(d?.slaveId);
115272
+ return !!d?.centralId && UUID_RE.test(String(d.centralId)) && Number.isInteger(slave) && slave >= 1;
115273
+ }
115266
115274
  function splitImportableDevices(devices) {
115267
115275
  const ok = [];
115268
115276
  const missingKey = [];
115269
- for (const d of devices || []) {
115270
- const slave = Number(d?.slaveId);
115271
- if (d?.centralId && UUID_RE.test(String(d.centralId)) && Number.isInteger(slave) && slave >= 1) ok.push(d);
115272
- else missingKey.push(d);
115273
- }
115277
+ for (const d of devices || []) (isImportableKey(d) ? ok : missingKey).push(d);
115274
115278
  return { ok, missingKey };
115275
115279
  }
115276
115280
  function daysBetween(start, end) {
@@ -115466,6 +115470,162 @@ async function parseSheetFile(file) {
115466
115470
  throw new Error("Formato n\xE3o suportado \u2014 envie .xlsx ou .csv");
115467
115471
  }
115468
115472
 
115473
+ // src/components/premium-modals/telemetry-import/accumulated.ts
115474
+ var DEFAULT_DISTRIBUTION_PROFILE = { openHour: 10, closeHour: 22, openShare: 0.85 };
115475
+ var TOTAL_COLUMN = {
115476
+ energy: "total_kwh",
115477
+ water: "total_m3"
115478
+ };
115479
+ var ACCUMULATED_SOURCE_PREFIX = "acumulado";
115480
+ var MAX_PERIOD_DAYS = 366;
115481
+ var MILLI = 1e3;
115482
+ var pad25 = (n) => String(n).padStart(2, "0");
115483
+ function closedHoursInPeriod(start, end, now = Date.now()) {
115484
+ const today = nowSaoPaulo(now);
115485
+ const out = [];
115486
+ for (const date of daysBetween(start, end)) {
115487
+ if (date > today.date) break;
115488
+ for (let hour = 0; hour < 24; hour++) {
115489
+ if (date === today.date && hour >= today.hour) break;
115490
+ out.push({ date, hour });
115491
+ }
115492
+ }
115493
+ return out;
115494
+ }
115495
+ var isOpen = (hour, p) => hour >= p.openHour && hour < p.closeHour;
115496
+ function slotWeights(slots, profile) {
115497
+ const nOpen = slots.filter((s) => isOpen(s.hour, profile)).length;
115498
+ const nClosed = slots.length - nOpen;
115499
+ if (!nOpen || !nClosed) return slots.map(() => 1 / slots.length);
115500
+ return slots.map((s) => isOpen(s.hour, profile) ? profile.openShare / nOpen : (1 - profile.openShare) / nClosed);
115501
+ }
115502
+ function distributeTotal(total, slots, profile = DEFAULT_DISTRIBUTION_PROFILE) {
115503
+ if (!slots.length) return [];
115504
+ const totalMilli = Math.round(total * MILLI);
115505
+ const exact = slotWeights(slots, profile).map((w) => w * totalMilli);
115506
+ const parts = exact.map((v) => Math.floor(v));
115507
+ const remainder = totalMilli - parts.reduce((a, b) => a + b, 0);
115508
+ exact.map((v, i) => ({ i, frac: v - Math.floor(v) })).sort((a, b) => b.frac - a.frac || a.i - b.i).slice(0, remainder).forEach(({ i }) => {
115509
+ parts[i] += 1;
115510
+ });
115511
+ return parts.map((p) => p / MILLI);
115512
+ }
115513
+ function accumulatedRows(domain, entries, profile = DEFAULT_DISTRIBUTION_PROFILE, now = Date.now()) {
115514
+ const valueCol = VALUE_COLUMN[domain];
115515
+ const today = nowSaoPaulo(now);
115516
+ const errors = [];
115517
+ const rows = [];
115518
+ const accepted = /* @__PURE__ */ new Map();
115519
+ let totalMilli = 0;
115520
+ let zeroEntries = 0;
115521
+ for (const e of entries) {
115522
+ const who = e.device_name ? `${e.device_name}: ` : "";
115523
+ if (e.start > e.end) {
115524
+ errors.push({ line: e.line, reason: `${who}in\xEDcio depois do fim` });
115525
+ continue;
115526
+ }
115527
+ if (e.end > today.date) {
115528
+ errors.push({ line: e.line, reason: `${who}o per\xEDodo termina no futuro \u2014 o total precisa ser de um per\xEDodo j\xE1 encerrado` });
115529
+ continue;
115530
+ }
115531
+ if (daysBetween(e.start, e.end).length > MAX_PERIOD_DAYS) {
115532
+ errors.push({ line: e.line, reason: `${who}per\xEDodo maior que ${MAX_PERIOD_DAYS} dias` });
115533
+ continue;
115534
+ }
115535
+ const key = `${e.gateway_id.toLowerCase()}|${e.slave_id}`;
115536
+ const clash = (accepted.get(key) || []).find((o) => e.start <= o.end && o.start <= e.end);
115537
+ if (clash) {
115538
+ errors.push({ line: e.line, reason: `${who}per\xEDodo sobreposto ao da linha ${clash.line}` });
115539
+ continue;
115540
+ }
115541
+ const slots = closedHoursInPeriod(e.start, e.end, now);
115542
+ if (!slots.length) {
115543
+ errors.push({ line: e.line, reason: `${who}per\xEDodo sem horas fechadas` });
115544
+ continue;
115545
+ }
115546
+ accepted.set(key, [...accepted.get(key) || [], e]);
115547
+ if (e.total === 0) zeroEntries++;
115548
+ totalMilli += Math.round(e.total * MILLI);
115549
+ distributeTotal(e.total, slots, profile).forEach((value, i) => {
115550
+ rows.push({
115551
+ line: e.line,
115552
+ gateway_id: e.gateway_id,
115553
+ slave_id: e.slave_id,
115554
+ date: slots[i].date,
115555
+ hour: `${pad25(slots[i].hour)}:00`,
115556
+ [valueCol]: value
115557
+ });
115558
+ });
115559
+ }
115560
+ if (rows.length > MAX_IMPORT_ROWS) {
115561
+ errors.push({
115562
+ line: 1,
115563
+ reason: `M\xE1ximo de ${MAX_IMPORT_ROWS} horas por importa\xE7\xE3o (${rows.length} geradas) \u2014 importe menos dispositivos ou um per\xEDodo menor`
115564
+ });
115565
+ }
115566
+ return { rows, errors, devices: accepted.size, total: totalMilli / MILLI, zeroEntries };
115567
+ }
115568
+ function buildAccumulatedTemplateCsv(domain, devices, start, end) {
115569
+ const lines = [["gateway_id", "slave_id", "device_name", "start_date", "end_date", TOTAL_COLUMN[domain]].join(";")];
115570
+ const esc10 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
115571
+ for (const dev of devices || []) {
115572
+ if (!isImportableKey(dev)) continue;
115573
+ lines.push([String(dev.centralId), String(Number(dev.slaveId)), esc10(dev.label || ""), start, end, ""].join(";"));
115574
+ }
115575
+ return { csv: "\uFEFF" + lines.join("\r\n") + "\r\n", rows: lines.length - 1 };
115576
+ }
115577
+ function entriesFromTable(domain, table) {
115578
+ const totalCol = TOTAL_COLUMN[domain];
115579
+ const header = (table[0] || []).map((h3) => String(h3 ?? "").trim().toLowerCase());
115580
+ const col2 = (name) => header.indexOf(name);
115581
+ const required = ["gateway_id", "slave_id", "start_date", "end_date", totalCol];
115582
+ const missing = required.filter((c) => col2(c) < 0);
115583
+ if (missing.length) {
115584
+ return { entries: [], errors: [{ line: 1, reason: `Coluna obrigat\xF3ria ausente: ${missing.join(", ")}` }], skippedEmpty: 0 };
115585
+ }
115586
+ const entries = [];
115587
+ const errors = [];
115588
+ let skippedEmpty = 0;
115589
+ for (let i = 1; i < table.length; i++) {
115590
+ const r = table[i] || [];
115591
+ const line = i + 1;
115592
+ if (r.every((c) => String(c ?? "").trim() === "")) continue;
115593
+ const total = parseDecimal(r[col2(totalCol)]);
115594
+ if (total === null) {
115595
+ skippedEmpty++;
115596
+ continue;
115597
+ }
115598
+ const gateway_id = String(r[col2("gateway_id")] ?? "").trim();
115599
+ const slave_id = Number(String(r[col2("slave_id")] ?? "").trim());
115600
+ const start = normalizeDate(r[col2("start_date")]);
115601
+ const end = normalizeDate(r[col2("end_date")]);
115602
+ const lineErrors = [];
115603
+ if (!isImportableKey({ label: "", centralId: gateway_id, slaveId: slave_id })) lineErrors.push("gateway_id ou slave_id inv\xE1lido");
115604
+ if (!start) lineErrors.push("in\xEDcio inv\xE1lido (use AAAA-MM-DD)");
115605
+ if (!end) lineErrors.push("fim inv\xE1lido (use AAAA-MM-DD)");
115606
+ if (Number.isNaN(total) || total < 0) lineErrors.push("total deve ser n\xFAmero \u2265 0");
115607
+ if (lineErrors.length) {
115608
+ errors.push({ line, reason: lineErrors.join("; ") });
115609
+ continue;
115610
+ }
115611
+ const nameIdx = col2("device_name");
115612
+ entries.push({
115613
+ line,
115614
+ gateway_id,
115615
+ slave_id,
115616
+ device_name: nameIdx >= 0 ? String(r[nameIdx] ?? "").trim() || void 0 : void 0,
115617
+ start,
115618
+ end,
115619
+ total
115620
+ });
115621
+ }
115622
+ return { entries, errors, skippedEmpty };
115623
+ }
115624
+ function dayCurve(profile = DEFAULT_DISTRIBUTION_PROFILE) {
115625
+ const slots = Array.from({ length: 24 }, (_, hour) => ({ date: "", hour }));
115626
+ return slotWeights(slots, profile);
115627
+ }
115628
+
115469
115629
  // src/components/premium-modals/telemetry-import/importApi.ts
115470
115630
  var TERMINAL_JOB_STATUSES = ["completed", "failed", "cancelled", "reverted"];
115471
115631
  var ImportApiError = class extends Error {
@@ -115588,6 +115748,18 @@ function injectStyles14() {
115588
115748
  .tlmi-progress > i { display: block; height: 100%; background: var(--tlmi-ac); transition: width 0.4s; }
115589
115749
  .tlmi-check { display: flex; gap: 8px; align-items: flex-start; font-size: 13px; }
115590
115750
  .tlmi-tech { font-size: 11.5px; color: #6b7280; word-break: break-word; }
115751
+ .tlmi-models { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
115752
+ .tlmi-model { display: flex; gap: 10px; align-items: flex-start; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px; cursor: pointer; }
115753
+ .tlmi-model[data-selected="1"] { border-color: var(--tlmi-ac); background: var(--tlmi-ac-soft); }
115754
+ .tlmi-model strong { display: block; font-size: 13.5px; }
115755
+ .tlmi-model span { font-size: 12.5px; color: #64748b; line-height: 1.4; }
115756
+ .tlmi-acc { max-height: 240px; overflow: auto; border: 1px solid #e2e8f0; border-radius: 8px; }
115757
+ .tlmi-acc table { width: 100%; border-collapse: collapse; font-size: 13px; }
115758
+ .tlmi-acc th, .tlmi-acc td { padding: 6px 10px; border-bottom: 1px solid #f1f5f9; text-align: left; }
115759
+ .tlmi-acc th { background: #f8fafc; position: sticky; top: 0; font-size: 12px; color: #64748b; }
115760
+ .tlmi-acc input { width: 130px; border: 1px solid #ddd; border-radius: 6px; padding: 6px 8px; font: inherit; }
115761
+ .tlmi-curve { display: flex; align-items: flex-end; gap: 2px; height: 56px; margin-top: 8px; }
115762
+ .tlmi-curve i { flex: 1; background: var(--tlmi-ac); opacity: 0.75; border-radius: 2px 2px 0 0; min-height: 2px; }
115591
115763
  `;
115592
115764
  document.head.appendChild(style);
115593
115765
  }
@@ -115612,6 +115784,13 @@ function openTelemetryImportModal(params) {
115612
115784
  const { ok: importable, missingKey } = splitImportableDevices(params.devices);
115613
115785
  const s = {
115614
115786
  step: 1,
115787
+ model: "hourly",
115788
+ /** Acumulado: total digitado por device (índice em `importable`) */
115789
+ formTotals: {},
115790
+ /** Acumulado: entradas vindas de planilha (null = preenchimento na tela) */
115791
+ fileEntries: null,
115792
+ fileErrors: [],
115793
+ acc: { devices: 0, total: 0, zeroEntries: 0 },
115615
115794
  period: defaultPeriod(now()),
115616
115795
  fileName: "",
115617
115796
  rows: [],
@@ -115655,7 +115834,8 @@ function openTelemetryImportModal(params) {
115655
115834
  function stepper() {
115656
115835
  return `<div class="tlmi-stepper">${STEPS2.map((st) => {
115657
115836
  const state6 = st.n === s.step ? "current" : st.n < s.step ? "done" : "todo";
115658
- return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n}</b>${st.label}</div>`;
115837
+ const label = st.n === 2 && s.model === "accumulated" ? "Valores" : st.label;
115838
+ return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n}</b>${label}</div>`;
115659
115839
  }).join("")}</div>`;
115660
115840
  }
115661
115841
  function apiErrorBanner() {
@@ -115666,21 +115846,35 @@ function openTelemetryImportModal(params) {
115666
115846
  const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados ficam fora do modelo: ${esc9(
115667
115847
  missingKey.slice(0, 5).map((d) => d.label).join(", ")
115668
115848
  )}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
115669
- return `
115670
- <div class="tlmi-card"><h3>Como funciona</h3>
115671
- <p class="tlmi-muted">1) Baixe o modelo com os dispositivos desta lista, uma linha por hora. 2) Preencha a coluna
115849
+ const model = (value, title, hint) => `
115850
+ <label class="tlmi-model" data-selected="${s.model === value ? 1 : 0}">
115851
+ <input type="radio" name="tlmi-model" data-field="model" value="${value}" ${s.model === value ? "checked" : ""} />
115852
+ <div><strong>${title}</strong><span>${hint}</span></div>
115853
+ </label>`;
115854
+ const howTo = s.model === "accumulated" ? `<p class="tlmi-muted">1) Escolha o per\xEDodo. 2) Informe o total de cada dispositivo (${txt.unit}), na tela ou em planilha.
115855
+ 3) O sistema distribui o total pelas horas, mantendo a soma exata. O total \xE9 o valor informado;
115856
+ a <strong>curva por hora \xE9 estimada</strong>. Os valores <strong>substituem</strong> as leituras existentes no per\xEDodo.</p>` : `<p class="tlmi-muted">1) Baixe o modelo com os dispositivos desta lista, uma linha por hora. 2) Preencha a coluna
115672
115857
  <strong>${VALUE_COLUMN[domain]}</strong> (${txt.unit}); apague ou deixe em branco as horas que n\xE3o quer alterar.
115673
115858
  3) Envie a planilha: ela \xE9 validada por inteiro \u2014 qualquer linha inv\xE1lida cancela a importa\xE7\xE3o.
115674
- Os valores importados <strong>substituem</strong> as leituras existentes nas horas enviadas.</p>
115859
+ Os valores importados <strong>substituem</strong> as leituras existentes nas horas enviadas.</p>`;
115860
+ return `
115861
+ <div class="tlmi-card"><h3>Como voc\xEA quer preencher?</h3>
115862
+ <div class="tlmi-models">
115863
+ ${model("hourly", "Hora a hora", "Voc\xEA tem o valor de cada hora.")}
115864
+ ${model("accumulated", "Acumulado por per\xEDodo", "Voc\xEA tem s\xF3 o total do per\xEDodo.")}
115865
+ </div>
115866
+ </div>
115867
+ <div class="tlmi-card"><h3>Como funciona</h3>
115868
+ ${howTo}
115675
115869
  </div>
115676
115870
  ${warn}
115677
- <div class="tlmi-card"><h3>Modelo da planilha</h3>
115871
+ <div class="tlmi-card"><h3>${s.model === "accumulated" ? "Per\xEDodo" : "Modelo da planilha"}</h3>
115678
115872
  <div class="tlmi-row">
115679
115873
  <label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc9(s.period.start)}" /></label>
115680
115874
  <label class="tlmi-field">Fim<input type="date" data-field="end" value="${esc9(s.period.end)}" /></label>
115681
115875
  <button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
115682
115876
  </div>
115683
- <p class="tlmi-muted" style="margin-top:8px">${importable.length} dispositivo(s) no modelo. J\xE1 tem a planilha preenchida? Clique em <strong>Avan\xE7ar</strong>.</p>
115877
+ <p class="tlmi-muted" style="margin-top:8px">${importable.length} dispositivo(s) no modelo. ${s.model === "accumulated" ? "Para digitar na tela, clique em <strong>Avan\xE7ar</strong>." : "J\xE1 tem a planilha preenchida? Clique em <strong>Avan\xE7ar</strong>."}</p>
115684
115878
  </div>`;
115685
115879
  }
115686
115880
  function step2() {
@@ -115701,6 +115895,52 @@ function openTelemetryImportModal(params) {
115701
115895
  </div>
115702
115896
  ${summary}`;
115703
115897
  }
115898
+ function accSummaryHtml() {
115899
+ if (!s.rows.length && !s.localErrors.length) {
115900
+ return `<p class="tlmi-muted">Informe ao menos um total para ver a pr\xE9via.</p>`;
115901
+ }
115902
+ const hours = s.rows.length;
115903
+ const curve = dayCurve(DEFAULT_DISTRIBUTION_PROFILE);
115904
+ const peak = Math.max(...curve);
115905
+ return `
115906
+ <div class="tlmi-kpis">
115907
+ <div class="tlmi-kpi"><span>Dispositivos</span><strong>${fmtNum(s.acc.devices)}</strong></div>
115908
+ <div class="tlmi-kpi"><span>Horas geradas</span><strong>${fmtNum(hours)}</strong></div>
115909
+ <div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(s.acc.total, 3)}</strong></div>
115910
+ <div class="tlmi-kpi"><span>M\xE9dia por hora (${txt.unit})</span><strong>${fmtNum(hours ? s.acc.total / hours : 0, 3)}</strong></div>
115911
+ </div>
115912
+ ${s.localErrors.length ? `<div class="tlmi-banner err">Corrija os itens abaixo \u2014 nada foi importado.</div>${issuesTable(s.localErrors)}` : ""}
115913
+ ${s.acc.zeroEntries ? `<div class="tlmi-banner warn">${fmtNum(s.acc.zeroEntries)} per\xEDodo(s) com total zero: todas as horas ficam zeradas.</div>` : ""}
115914
+ ${hours ? `<div class="tlmi-card"><h3>Distribui\xE7\xE3o em um dia</h3>
115915
+ <p class="tlmi-muted">${Math.round(DEFAULT_DISTRIBUTION_PROFILE.openShare * 100)}% do total no hor\xE1rio de funcionamento
115916
+ (${DEFAULT_DISTRIBUTION_PROFILE.openHour}h \xE0s ${DEFAULT_DISTRIBUTION_PROFILE.closeHour}h). Curva estimada: n\xE3o use para an\xE1lise de pico de demanda.</p>
115917
+ <div class="tlmi-curve" aria-hidden="true">${curve.map((w) => `<i style="height:${Math.round(w / peak * 100)}%"></i>`).join("")}</div>
115918
+ </div>` : ""}`;
115919
+ }
115920
+ function step2Accumulated() {
115921
+ const fromFile = !!s.fileName && !s.parseError;
115922
+ const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc9(s.fileName)}</strong>.
115923
+ <button class="tlmi-btn" type="button" data-action="use-form">Preencher na tela</button></p>` : `<p class="tlmi-muted" style="margin-bottom:8px">Per\xEDodo: ${esc9(s.period.start)} a ${esc9(s.period.end)}. Deixe em branco o que n\xE3o quer importar.</p>
115924
+ <div class="tlmi-acc"><table><thead><tr><th>Dispositivo</th><th>Total (${txt.unit})</th></tr></thead><tbody>
115925
+ ${importable.map(
115926
+ (d, i) => `<tr><td>${esc9(d.label)}</td>
115927
+ <td><input inputmode="decimal" data-total="${i}" aria-label="Total de ${esc9(d.label)}" value="${esc9(s.formTotals[i] ?? "")}" /></td></tr>`
115928
+ ).join("")}
115929
+ </tbody></table></div>`;
115930
+ return `
115931
+ <div class="tlmi-card"><h3>Totais por dispositivo</h3>${form}</div>
115932
+ <div class="tlmi-card"><h3>Ou envie a planilha</h3>
115933
+ <div class="tlmi-row" style="margin-bottom:10px">
115934
+ <button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
115935
+ </div>
115936
+ <label class="tlmi-drop" data-role="drop">
115937
+ <input type="file" accept=".xlsx,.xls,.csv" data-field="file" hidden />
115938
+ \u{1F4C4} Clique ou arraste a planilha aqui (.xlsx ou .csv)
115939
+ </label>
115940
+ ${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${esc9(s.parseError)}</div>` : ""}
115941
+ </div>
115942
+ <div data-role="acc-summary" style="display:flex;flex-direction:column;gap:12px">${accSummaryHtml()}</div>`;
115943
+ }
115704
115944
  function step3() {
115705
115945
  const v = s.validation;
115706
115946
  if (!v) return `${apiErrorBanner()}<div class="tlmi-card"><p class="tlmi-muted">${s.busy ? "Validando\u2026" : "Aguardando valida\xE7\xE3o."}</p></div>`;
@@ -115713,7 +115953,8 @@ function openTelemetryImportModal(params) {
115713
115953
  const period = typeof p.period === "string" ? p.period : p.period ? `${p.period.start || ""} \u2192 ${p.period.end || ""}` : "\u2014";
115714
115954
  const devices = Array.isArray(p.devices) ? p.devices.length : p.devices;
115715
115955
  return `
115716
- <div class="tlmi-banner ok">Planilha v\xE1lida. Confira o resumo antes de importar.</div>
115956
+ <div class="tlmi-banner ok">${s.model === "accumulated" ? "Valores v\xE1lidos" : "Planilha v\xE1lida"}. Confira o resumo antes de importar.</div>
115957
+ ${s.model === "accumulated" ? '<div class="tlmi-banner warn">Os valores por hora s\xE3o estimados a partir do total informado.</div>' : ""}
115717
115958
  <div class="tlmi-kpis">
115718
115959
  <div class="tlmi-kpi"><span>Horas a gravar</span><strong>${fmtNum(p.targetSlots)}</strong></div>
115719
115960
  <div class="tlmi-kpi"><span>Dispositivos</span><strong>${fmtNum(devices)}</strong></div>
@@ -115757,7 +115998,8 @@ function openTelemetryImportModal(params) {
115757
115998
  }
115758
115999
  function render3() {
115759
116000
  if (closed) return;
115760
- const body = s.step === 1 ? step1() : s.step === 2 ? step2() : s.step === 3 ? step3() : step4();
116001
+ const step2Body = () => s.model === "accumulated" ? step2Accumulated() : step2();
116002
+ const body = s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
115761
116003
  root.innerHTML = stepper() + body;
115762
116004
  syncFooter();
115763
116005
  }
@@ -115767,7 +116009,11 @@ function openTelemetryImportModal(params) {
115767
116009
  modal.setButton("back", { hidden: s.step === 1 || s.step === 4, disabled: s.busy });
115768
116010
  if (s.step === 1) modal.setButton("next", { label: "Avan\xE7ar", disabled: false, hidden: false });
115769
116011
  if (s.step === 2)
115770
- modal.setButton("next", { label: "Validar planilha", disabled: s.busy || !s.rows.length || !!s.localErrors.length || !!s.parseError, hidden: false });
116012
+ modal.setButton("next", {
116013
+ label: s.model === "accumulated" ? "Validar" : "Validar planilha",
116014
+ disabled: s.busy || !s.rows.length || !!s.localErrors.length || !!s.parseError,
116015
+ hidden: false
116016
+ });
115771
116017
  if (s.step === 3) {
115772
116018
  const real = v && v.valid ? Number(v.preview?.existingRealReadings || 0) : 0;
115773
116019
  modal.setButton("next", {
@@ -115788,6 +116034,7 @@ function openTelemetryImportModal(params) {
115788
116034
  async function goNext() {
115789
116035
  if (s.busy) return;
115790
116036
  if (s.step === 1) {
116037
+ if (s.model === "accumulated") recomputeAccumulated();
115791
116038
  s.step = 2;
115792
116039
  render3();
115793
116040
  } else if (s.step === 2) {
@@ -115800,18 +116047,61 @@ function openTelemetryImportModal(params) {
115800
116047
  }
115801
116048
  }
115802
116049
  function downloadTemplate() {
115803
- const { csv, rows } = buildTemplateCsv(domain, importable, s.period.start, s.period.end, now());
116050
+ const { csv, rows } = s.model === "accumulated" ? buildAccumulatedTemplateCsv(domain, importable, s.period.start, s.period.end) : buildTemplateCsv(domain, importable, s.period.start, s.period.end, now());
115804
116051
  if (!rows) return;
115805
116052
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
115806
116053
  const a = document.createElement("a");
115807
116054
  a.href = URL.createObjectURL(blob);
115808
116055
  const who = (params.customerName || "shopping").replace(/[^\w-]+/g, "_");
115809
- a.download = `importacao-${domain === "energy" ? "energia" : "agua"}-${who}-${s.period.start}_${s.period.end}.csv`;
116056
+ const kind = s.model === "accumulated" ? "-acumulado" : "";
116057
+ a.download = `importacao${kind}-${domain === "energy" ? "energia" : "agua"}-${who}-${s.period.start}_${s.period.end}.csv`;
115810
116058
  document.body.appendChild(a);
115811
116059
  a.click();
115812
116060
  a.remove();
115813
116061
  setTimeout(() => URL.revokeObjectURL(a.href), 1e3);
115814
116062
  }
116063
+ function formEntries() {
116064
+ const entries = [];
116065
+ const errors = [];
116066
+ importable.forEach((d, i) => {
116067
+ const total = parseDecimal(s.formTotals[i] ?? "");
116068
+ if (total === null) return;
116069
+ if (Number.isNaN(total) || total < 0) {
116070
+ errors.push({ line: i + 1, reason: `${d.label}: total deve ser n\xFAmero \u2265 0` });
116071
+ return;
116072
+ }
116073
+ entries.push({
116074
+ line: i + 1,
116075
+ gateway_id: String(d.centralId),
116076
+ slave_id: Number(d.slaveId),
116077
+ device_name: d.label,
116078
+ start: s.period.start,
116079
+ end: s.period.end,
116080
+ total
116081
+ });
116082
+ });
116083
+ return { entries, errors };
116084
+ }
116085
+ function recomputeAccumulated() {
116086
+ const src = s.fileEntries ? { entries: s.fileEntries, errors: s.fileErrors } : formEntries();
116087
+ const r = accumulatedRows(domain, src.entries, DEFAULT_DISTRIBUTION_PROFILE, now());
116088
+ s.rows = r.rows;
116089
+ s.localErrors = [...src.errors, ...r.errors];
116090
+ s.acc = { devices: r.devices, total: r.total, zeroEntries: r.zeroEntries };
116091
+ s.validation = null;
116092
+ }
116093
+ function refreshAccSummary() {
116094
+ const el2 = root.querySelector('[data-role="acc-summary"]');
116095
+ if (el2) el2.innerHTML = accSummaryHtml();
116096
+ syncFooter();
116097
+ }
116098
+ function resetAccumulatedSource() {
116099
+ s.fileName = "";
116100
+ s.parseError = "";
116101
+ s.fileEntries = null;
116102
+ s.fileErrors = [];
116103
+ s.skippedEmpty = 0;
116104
+ }
115815
116105
  async function loadFile(file) {
115816
116106
  if (!file) return;
115817
116107
  s.fileName = file.name;
@@ -115822,10 +116112,18 @@ function openTelemetryImportModal(params) {
115822
116112
  s.validation = null;
115823
116113
  try {
115824
116114
  const table = await parseSheetFile(file);
115825
- const r = rowsFromTable(domain, table);
115826
- s.rows = r.rows;
115827
- s.localErrors = r.errors;
115828
- s.skippedEmpty = r.skippedEmpty;
116115
+ if (s.model === "accumulated") {
116116
+ const r = entriesFromTable(domain, table);
116117
+ s.fileEntries = r.entries;
116118
+ s.fileErrors = r.errors;
116119
+ s.skippedEmpty = r.skippedEmpty;
116120
+ recomputeAccumulated();
116121
+ } else {
116122
+ const r = rowsFromTable(domain, table);
116123
+ s.rows = r.rows;
116124
+ s.localErrors = r.errors;
116125
+ s.skippedEmpty = r.skippedEmpty;
116126
+ }
115829
116127
  } catch (err) {
115830
116128
  s.parseError = err?.message || "N\xE3o foi poss\xEDvel ler a planilha.";
115831
116129
  }
@@ -115838,7 +116136,8 @@ function openTelemetryImportModal(params) {
115838
116136
  s.step = 3;
115839
116137
  render3();
115840
116138
  try {
115841
- s.validation = await api.validate({ customerId: params.customerId, readingType: domain, rows: s.rows, sourceRef: s.fileName });
116139
+ const sourceRef = s.model === "accumulated" ? `${ACCUMULATED_SOURCE_PREFIX}:${s.fileName || "tela"}` : s.fileName;
116140
+ s.validation = await api.validate({ customerId: params.customerId, readingType: domain, rows: s.rows, sourceRef });
115842
116141
  } catch (err) {
115843
116142
  setError(err);
115844
116143
  } finally {
@@ -115898,12 +116197,32 @@ function openTelemetryImportModal(params) {
115898
116197
  if (!el2) return;
115899
116198
  if (el2.dataset.action === "template") downloadTemplate();
115900
116199
  if (el2.dataset.action === "cancel") void cancelJob();
116200
+ if (el2.dataset.action === "use-form") {
116201
+ resetAccumulatedSource();
116202
+ recomputeAccumulated();
116203
+ render3();
116204
+ }
116205
+ });
116206
+ root.addEventListener("input", (e) => {
116207
+ const t = e.target;
116208
+ if (t.dataset.total === void 0) return;
116209
+ s.formTotals[Number(t.dataset.total)] = t.value;
116210
+ recomputeAccumulated();
116211
+ refreshAccSummary();
115901
116212
  });
115902
116213
  root.addEventListener("change", (e) => {
115903
116214
  const t = e.target;
115904
116215
  if (t.dataset.field === "start") s.period.start = t.value;
115905
116216
  if (t.dataset.field === "end") s.period.end = t.value;
115906
116217
  if (t.dataset.field === "file") void loadFile(t.files?.[0]);
116218
+ if (t.dataset.field === "model") {
116219
+ s.model = t.value;
116220
+ resetAccumulatedSource();
116221
+ s.rows = [];
116222
+ s.localErrors = [];
116223
+ s.validation = null;
116224
+ render3();
116225
+ }
115907
116226
  if (t.dataset.field === "confirmReal") {
115908
116227
  s.confirmReal = t.checked;
115909
116228
  syncFooter();
@@ -120752,8 +121071,8 @@ var GroupManagementTab = class {
120752
121071
  async toggleGroup(group, item) {
120753
121072
  const panel = item.querySelector(".gm-accordion-panel");
120754
121073
  const toggle = item.querySelector(".gm-accordion-toggle");
120755
- const isOpen = this.expandedGroupId === group.id;
120756
- if (isOpen) {
121074
+ const isOpen2 = this.expandedGroupId === group.id;
121075
+ if (isOpen2) {
120757
121076
  this.expandedGroupId = null;
120758
121077
  panel.style.display = "none";
120759
121078
  toggle.setAttribute("aria-expanded", "false");
@@ -166196,7 +166515,7 @@ function renderModalHTML(data, source, config2) {
166196
166515
  function createAmbienteDetailModal(data, source, config2 = {}) {
166197
166516
  injectAmbienteModalStyles();
166198
166517
  let container = null;
166199
- let isOpen = false;
166518
+ let isOpen2 = false;
166200
166519
  function createContainer() {
166201
166520
  container = document.createElement("div");
166202
166521
  container.innerHTML = renderModalHTML(data, source, config2);
@@ -166270,7 +166589,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
166270
166589
  }
166271
166590
  }
166272
166591
  function handleEscape(e) {
166273
- if (e.key === "Escape" && isOpen) {
166592
+ if (e.key === "Escape" && isOpen2) {
166274
166593
  close();
166275
166594
  }
166276
166595
  }
@@ -166284,7 +166603,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
166284
166603
  overlay.classList.add("visible");
166285
166604
  });
166286
166605
  }
166287
- isOpen = true;
166606
+ isOpen2 = true;
166288
166607
  document.body.style.overflow = "hidden";
166289
166608
  }
166290
166609
  function close() {
@@ -166295,7 +166614,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
166295
166614
  destroy();
166296
166615
  }, 200);
166297
166616
  }
166298
- isOpen = false;
166617
+ isOpen2 = false;
166299
166618
  document.body.style.overflow = "";
166300
166619
  document.removeEventListener("keydown", handleEscape);
166301
166620
  config2.onClose?.();
@@ -166311,7 +166630,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
166311
166630
  container.parentNode.removeChild(container);
166312
166631
  }
166313
166632
  container = null;
166314
- isOpen = false;
166633
+ isOpen2 = false;
166315
166634
  document.removeEventListener("keydown", handleEscape);
166316
166635
  }
166317
166636
  return {
@@ -167094,7 +167413,7 @@ function renderModalHTML2(data, config2) {
167094
167413
  function createAmbienteGroupModal(data, config2 = {}) {
167095
167414
  injectAmbienteGroupModalStyles();
167096
167415
  let container = null;
167097
- let isOpen = false;
167416
+ let isOpen2 = false;
167098
167417
  function createContainer() {
167099
167418
  container = document.createElement("div");
167100
167419
  container.innerHTML = renderModalHTML2(data, config2);
@@ -167154,7 +167473,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
167154
167473
  });
167155
167474
  }
167156
167475
  function handleEscape(e) {
167157
- if (e.key === "Escape" && isOpen) {
167476
+ if (e.key === "Escape" && isOpen2) {
167158
167477
  close();
167159
167478
  }
167160
167479
  }
@@ -167168,7 +167487,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
167168
167487
  overlay.classList.add("visible");
167169
167488
  });
167170
167489
  }
167171
- isOpen = true;
167490
+ isOpen2 = true;
167172
167491
  document.body.style.overflow = "hidden";
167173
167492
  }
167174
167493
  function close() {
@@ -167179,7 +167498,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
167179
167498
  destroy();
167180
167499
  }, 200);
167181
167500
  }
167182
- isOpen = false;
167501
+ isOpen2 = false;
167183
167502
  document.body.style.overflow = "";
167184
167503
  document.removeEventListener("keydown", handleEscape);
167185
167504
  config2.onClose?.();
@@ -167195,7 +167514,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
167195
167514
  container.parentNode.removeChild(container);
167196
167515
  }
167197
167516
  container = null;
167198
- isOpen = false;
167517
+ isOpen2 = false;
167199
167518
  document.removeEventListener("keydown", handleEscape);
167200
167519
  }
167201
167520
  return {
@@ -176867,7 +177186,7 @@ function prefixForProductType(productType) {
176867
177186
  if (entry) return entry.prefix;
176868
177187
  return `T${productType}`;
176869
177188
  }
176870
- function pad25(n) {
177189
+ function pad26(n) {
176871
177190
  return String(n).padStart(2, "0");
176872
177191
  }
176873
177192
  function pad4(n) {
@@ -176875,9 +177194,9 @@ function pad4(n) {
176875
177194
  }
176876
177195
  function deviceProductCodeToName(value) {
176877
177196
  const prefix = prefixForProductType(value.productType);
176878
- const yy = pad25(value.year % 100);
176879
- const mm = pad25(value.month);
176880
- const dd = pad25(value.day);
177197
+ const yy = pad26(value.year % 100);
177198
+ const mm = pad26(value.month);
177199
+ const dd = pad26(value.day);
176881
177200
  const unit = value.seq3 * 254 + value.seq;
176882
177201
  return `${prefix} ${yy}${mm}${dd}-${pad4(unit)}`;
176883
177202
  }
@@ -178519,6 +178838,7 @@ var version = package_default.version || "0.0.0";
178519
178838
  DEFAULT_DEVICE_OPERATIONAL_CARD_FILTER_STATE,
178520
178839
  DEFAULT_DEVICE_TYPE_PREFIX,
178521
178840
  DEFAULT_DEVICE_TYPE_TOKEN,
178841
+ DEFAULT_DISTRIBUTION_PROFILE,
178522
178842
  DEFAULT_ENABLED_REPORT_ITEMS,
178523
178843
  DEFAULT_ENERGY_GROUP_COLORS,
178524
178844
  DEFAULT_EQUIPMENT_FILTER_STATE,
@@ -178771,6 +179091,7 @@ var version = package_default.version || "0.0.0";
178771
179091
  WELCOME_DEFAULT_PALETTE,
178772
179092
  Water,
178773
179093
  WaterSummaryTooltip,
179094
+ accumulatedRows,
178774
179095
  adaptGcdrListToLegacyAnnotations,
178775
179096
  adaptGcdrToLegacyAnnotation,
178776
179097
  adaptLegacyToGcdrInput,
@@ -178789,6 +179110,7 @@ var version = package_default.version || "0.0.0";
178789
179110
  assetLocalToken,
178790
179111
  assignShoppingColors,
178791
179112
  averageByDay,
179113
+ buildAccumulatedTemplateCsv,
178792
179114
  buildAmbienteGroupData,
178793
179115
  buildAnnotationServiceOrchestrator,
178794
179116
  buildAnnotationsCsv,
@@ -178976,6 +179298,7 @@ var version = package_default.version || "0.0.0";
178976
179298
  deviceProductCodeToName,
178977
179299
  deviceStatusIcons,
178978
179300
  deviceTypeToken,
179301
+ distributeTotal,
178979
179302
  doSchedulesOverlap,
178980
179303
  downloadAnnotationsTextFile,
178981
179304
  encodeDeviceProductCode,