myio-js-library 0.1.572 → 0.1.574
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 +488 -68
- package/dist/index.d.cts +77 -5
- package/dist/index.d.ts +77 -5
- package/dist/index.js +484 -68
- package/dist/myio-js-library.umd.js +484 -68
- package/dist/myio-js-library.umd.min.js +1 -1
- package/package.json +1 -1
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.
|
|
961
|
+
version: "0.1.574",
|
|
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
|
|
23252
|
-
return
|
|
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
|
|
23526
|
-
return
|
|
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
|
|
53561
|
-
if (
|
|
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
|
|
63919
|
-
body.style.display =
|
|
63920
|
-
if (icon2) icon2.textContent =
|
|
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
|
|
101140
|
-
btn.classList.toggle("is-open",
|
|
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 {
|
|
@@ -115476,27 +115636,74 @@ var ImportApiError = class extends Error {
|
|
|
115476
115636
|
this.name = "ImportApiError";
|
|
115477
115637
|
}
|
|
115478
115638
|
};
|
|
115639
|
+
var CONFLICT_TEXT = {
|
|
115640
|
+
VALIDATION_EXPIRED: "A valida\xE7\xE3o expirou (vale 30 minutos). Valide a planilha de novo.",
|
|
115641
|
+
REAL_READINGS_PRESENT: "H\xE1 leituras reais nessas horas. Confirme a substitui\xE7\xE3o para importar.",
|
|
115642
|
+
NOT_CANCELLABLE: 'A importa\xE7\xE3o j\xE1 terminou e n\xE3o pode ser cancelada. Use "Desfazer importa\xE7\xE3o".',
|
|
115643
|
+
NOT_REVERTABLE: "Esta importa\xE7\xE3o n\xE3o pode ser desfeita.",
|
|
115644
|
+
GATEWAY_BUSY: "A central est\xE1 ocupada com outra importa\xE7\xE3o. Tente em instantes."
|
|
115645
|
+
};
|
|
115646
|
+
function importErrorMessage(status, path, body) {
|
|
115647
|
+
const code = String(body?.error || "");
|
|
115648
|
+
const apiMsg = String(body?.message || "");
|
|
115649
|
+
switch (status) {
|
|
115650
|
+
case 400:
|
|
115651
|
+
return apiMsg ? `Pedido recusado pela API: ${apiMsg}` : "Pedido recusado pela API (400).";
|
|
115652
|
+
case 401:
|
|
115653
|
+
return "Sess\xE3o da importa\xE7\xE3o expirada. Feche esta janela e abra a importa\xE7\xE3o de novo.";
|
|
115654
|
+
case 403:
|
|
115655
|
+
return /customer/i.test(apiMsg) ? "Esta credencial n\xE3o pode importar dados deste cliente." : "Sem permiss\xE3o para importar telemetria: a credencial n\xE3o tem o escopo telemetry.import.";
|
|
115656
|
+
case 404:
|
|
115657
|
+
return path === "/validate" ? "A importa\xE7\xE3o ainda n\xE3o est\xE1 dispon\xEDvel neste ambiente." : "Importa\xE7\xE3o n\xE3o encontrada.";
|
|
115658
|
+
case 409:
|
|
115659
|
+
return CONFLICT_TEXT[code] || apiMsg || "Opera\xE7\xE3o n\xE3o permitida no estado atual da importa\xE7\xE3o.";
|
|
115660
|
+
case 413:
|
|
115661
|
+
return "Planilha grande demais para uma importa\xE7\xE3o. Divida em partes de at\xE9 5.000 linhas.";
|
|
115662
|
+
case 429:
|
|
115663
|
+
return "Muitas tentativas seguidas. Aguarde um minuto e tente de novo.";
|
|
115664
|
+
default:
|
|
115665
|
+
return `Falha na API de importa\xE7\xE3o (${status}).`;
|
|
115666
|
+
}
|
|
115667
|
+
}
|
|
115479
115668
|
function createTelemetryImportApi(cfg) {
|
|
115480
115669
|
const base = String(cfg.baseUrl || "").replace(/\/+$/, "");
|
|
115481
115670
|
const doFetch = cfg.fetchImpl ?? fetch.bind(window);
|
|
115482
|
-
const
|
|
115483
|
-
|
|
115484
|
-
|
|
115485
|
-
|
|
115486
|
-
|
|
115487
|
-
|
|
115488
|
-
|
|
115671
|
+
const send = async (method, path, token, body) => {
|
|
115672
|
+
try {
|
|
115673
|
+
return await doFetch(`${base}/import${path}`, {
|
|
115674
|
+
method,
|
|
115675
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
115676
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
115677
|
+
});
|
|
115678
|
+
} catch (err) {
|
|
115679
|
+
throw new ImportApiError(
|
|
115680
|
+
"N\xE3o foi poss\xEDvel falar com a API de importa\xE7\xE3o. Verifique a conex\xE3o e tente de novo.",
|
|
115681
|
+
0,
|
|
115682
|
+
`${method} /import${path} \u2192 ${String(err?.message || err)}`
|
|
115683
|
+
);
|
|
115684
|
+
}
|
|
115685
|
+
};
|
|
115686
|
+
const readJson = async (res) => {
|
|
115489
115687
|
const text2 = await res.text().catch(() => "");
|
|
115490
|
-
let data = null;
|
|
115491
115688
|
try {
|
|
115492
|
-
|
|
115689
|
+
return { text: text2, data: text2 ? JSON.parse(text2) : null };
|
|
115493
115690
|
} catch {
|
|
115494
|
-
data
|
|
115691
|
+
return { text: text2, data: null };
|
|
115495
115692
|
}
|
|
115693
|
+
};
|
|
115694
|
+
const call = async (method, path, body, accept422 = false) => {
|
|
115695
|
+
let res = await send(method, path, await cfg.getToken(), body);
|
|
115696
|
+
let parsed = await readJson(res);
|
|
115697
|
+
const scopeMissing = res.status === 403 && /scope/i.test(String(parsed.data?.message || ""));
|
|
115698
|
+
if ((res.status === 401 || scopeMissing) && cfg.refreshToken) {
|
|
115699
|
+
res = await send(method, path, await cfg.refreshToken(), body);
|
|
115700
|
+
parsed = await readJson(res);
|
|
115701
|
+
}
|
|
115702
|
+
const data = parsed.data;
|
|
115496
115703
|
if (res.ok || accept422 && res.status === 422) return { status: res.status, data: data?.data ?? data };
|
|
115704
|
+
const msg = importErrorMessage(res.status, path.startsWith("/jobs") ? "/jobs" : path, data);
|
|
115497
115705
|
const apiMsg = data?.message || data?.error || "";
|
|
115498
|
-
|
|
115499
|
-
throw new ImportApiError(msg, res.status, `${method} /import${path} \u2192 ${res.status} ${String(apiMsg || text2).slice(0, 200)}`);
|
|
115706
|
+
throw new ImportApiError(msg, res.status, `${method} /import${path} \u2192 ${res.status} ${String(apiMsg || parsed.text).slice(0, 200)}`);
|
|
115500
115707
|
};
|
|
115501
115708
|
return {
|
|
115502
115709
|
async validate(body) {
|
|
@@ -115517,6 +115724,10 @@ function createTelemetryImportApi(cfg) {
|
|
|
115517
115724
|
async cancelJob(jobId) {
|
|
115518
115725
|
const { data } = await call("POST", `/jobs/${encodeURIComponent(jobId)}/cancel`);
|
|
115519
115726
|
return data ? { jobId, ...data } : null;
|
|
115727
|
+
},
|
|
115728
|
+
async revertJob(jobId) {
|
|
115729
|
+
const { data } = await call("POST", `/jobs/${encodeURIComponent(jobId)}/revert`);
|
|
115730
|
+
return data ? { jobId, ...data } : null;
|
|
115520
115731
|
}
|
|
115521
115732
|
};
|
|
115522
115733
|
}
|
|
@@ -115538,8 +115749,16 @@ var JOB_STATUS_TEXT = {
|
|
|
115538
115749
|
completed: "Conclu\xEDda",
|
|
115539
115750
|
failed: "Falhou",
|
|
115540
115751
|
cancelled: "Cancelada",
|
|
115541
|
-
|
|
115752
|
+
reverting: "Desfazendo",
|
|
115753
|
+
reverted: "Desfeita"
|
|
115542
115754
|
};
|
|
115755
|
+
function fmtSaoPaulo(iso) {
|
|
115756
|
+
const t = new Date(String(iso ?? "")).getTime();
|
|
115757
|
+
if (!Number.isFinite(t)) return "";
|
|
115758
|
+
const d = new Date(t - 3 * 3600 * 1e3);
|
|
115759
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
115760
|
+
return `${p(d.getUTCDate())}/${p(d.getUTCMonth() + 1)}/${d.getUTCFullYear()} ${p(d.getUTCHours())}:00`;
|
|
115761
|
+
}
|
|
115543
115762
|
var STYLE_ID14 = "myio-tlmimport-styles";
|
|
115544
115763
|
function esc9(v) {
|
|
115545
115764
|
return String(v ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
@@ -115588,6 +115807,18 @@ function injectStyles14() {
|
|
|
115588
115807
|
.tlmi-progress > i { display: block; height: 100%; background: var(--tlmi-ac); transition: width 0.4s; }
|
|
115589
115808
|
.tlmi-check { display: flex; gap: 8px; align-items: flex-start; font-size: 13px; }
|
|
115590
115809
|
.tlmi-tech { font-size: 11.5px; color: #6b7280; word-break: break-word; }
|
|
115810
|
+
.tlmi-models { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
|
|
115811
|
+
.tlmi-model { display: flex; gap: 10px; align-items: flex-start; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px; cursor: pointer; }
|
|
115812
|
+
.tlmi-model[data-selected="1"] { border-color: var(--tlmi-ac); background: var(--tlmi-ac-soft); }
|
|
115813
|
+
.tlmi-model strong { display: block; font-size: 13.5px; }
|
|
115814
|
+
.tlmi-model span { font-size: 12.5px; color: #64748b; line-height: 1.4; }
|
|
115815
|
+
.tlmi-acc { max-height: 240px; overflow: auto; border: 1px solid #e2e8f0; border-radius: 8px; }
|
|
115816
|
+
.tlmi-acc table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
115817
|
+
.tlmi-acc th, .tlmi-acc td { padding: 6px 10px; border-bottom: 1px solid #f1f5f9; text-align: left; }
|
|
115818
|
+
.tlmi-acc th { background: #f8fafc; position: sticky; top: 0; font-size: 12px; color: #64748b; }
|
|
115819
|
+
.tlmi-acc input { width: 130px; border: 1px solid #ddd; border-radius: 6px; padding: 6px 8px; font: inherit; }
|
|
115820
|
+
.tlmi-curve { display: flex; align-items: flex-end; gap: 2px; height: 56px; margin-top: 8px; }
|
|
115821
|
+
.tlmi-curve i { flex: 1; background: var(--tlmi-ac); opacity: 0.75; border-radius: 2px 2px 0 0; min-height: 2px; }
|
|
115591
115822
|
`;
|
|
115592
115823
|
document.head.appendChild(style);
|
|
115593
115824
|
}
|
|
@@ -115612,6 +115843,13 @@ function openTelemetryImportModal(params) {
|
|
|
115612
115843
|
const { ok: importable, missingKey } = splitImportableDevices(params.devices);
|
|
115613
115844
|
const s = {
|
|
115614
115845
|
step: 1,
|
|
115846
|
+
model: "hourly",
|
|
115847
|
+
/** Acumulado: total digitado por device (índice em `importable`) */
|
|
115848
|
+
formTotals: {},
|
|
115849
|
+
/** Acumulado: entradas vindas de planilha (null = preenchimento na tela) */
|
|
115850
|
+
fileEntries: null,
|
|
115851
|
+
fileErrors: [],
|
|
115852
|
+
acc: { devices: 0, total: 0, zeroEntries: 0 },
|
|
115615
115853
|
period: defaultPeriod(now()),
|
|
115616
115854
|
fileName: "",
|
|
115617
115855
|
rows: [],
|
|
@@ -115623,6 +115861,8 @@ function openTelemetryImportModal(params) {
|
|
|
115623
115861
|
apiError: "",
|
|
115624
115862
|
apiDetail: "",
|
|
115625
115863
|
confirmReal: false,
|
|
115864
|
+
/** "Desfazer importação" pede um segundo clique antes de chamar o revert */
|
|
115865
|
+
confirmRevert: false,
|
|
115626
115866
|
job: null
|
|
115627
115867
|
};
|
|
115628
115868
|
let pollTimer = null;
|
|
@@ -115655,7 +115895,8 @@ function openTelemetryImportModal(params) {
|
|
|
115655
115895
|
function stepper() {
|
|
115656
115896
|
return `<div class="tlmi-stepper">${STEPS2.map((st) => {
|
|
115657
115897
|
const state6 = st.n === s.step ? "current" : st.n < s.step ? "done" : "todo";
|
|
115658
|
-
|
|
115898
|
+
const label = st.n === 2 && s.model === "accumulated" ? "Valores" : st.label;
|
|
115899
|
+
return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n}</b>${label}</div>`;
|
|
115659
115900
|
}).join("")}</div>`;
|
|
115660
115901
|
}
|
|
115661
115902
|
function apiErrorBanner() {
|
|
@@ -115666,21 +115907,35 @@ function openTelemetryImportModal(params) {
|
|
|
115666
115907
|
const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados ficam fora do modelo: ${esc9(
|
|
115667
115908
|
missingKey.slice(0, 5).map((d) => d.label).join(", ")
|
|
115668
115909
|
)}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
|
|
115669
|
-
|
|
115670
|
-
<
|
|
115671
|
-
<
|
|
115910
|
+
const model = (value, title, hint) => `
|
|
115911
|
+
<label class="tlmi-model" data-selected="${s.model === value ? 1 : 0}">
|
|
115912
|
+
<input type="radio" name="tlmi-model" data-field="model" value="${value}" ${s.model === value ? "checked" : ""} />
|
|
115913
|
+
<div><strong>${title}</strong><span>${hint}</span></div>
|
|
115914
|
+
</label>`;
|
|
115915
|
+
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.
|
|
115916
|
+
3) O sistema distribui o total pelas horas, mantendo a soma exata. O total \xE9 o valor informado;
|
|
115917
|
+
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
115918
|
<strong>${VALUE_COLUMN[domain]}</strong> (${txt.unit}); apague ou deixe em branco as horas que n\xE3o quer alterar.
|
|
115673
115919
|
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
|
|
115920
|
+
Os valores importados <strong>substituem</strong> as leituras existentes nas horas enviadas.</p>`;
|
|
115921
|
+
return `
|
|
115922
|
+
<div class="tlmi-card"><h3>Como voc\xEA quer preencher?</h3>
|
|
115923
|
+
<div class="tlmi-models">
|
|
115924
|
+
${model("hourly", "Hora a hora", "Voc\xEA tem o valor de cada hora.")}
|
|
115925
|
+
${model("accumulated", "Acumulado por per\xEDodo", "Voc\xEA tem s\xF3 o total do per\xEDodo.")}
|
|
115926
|
+
</div>
|
|
115927
|
+
</div>
|
|
115928
|
+
<div class="tlmi-card"><h3>Como funciona</h3>
|
|
115929
|
+
${howTo}
|
|
115675
115930
|
</div>
|
|
115676
115931
|
${warn}
|
|
115677
|
-
<div class="tlmi-card"><h3
|
|
115932
|
+
<div class="tlmi-card"><h3>${s.model === "accumulated" ? "Per\xEDodo" : "Modelo da planilha"}</h3>
|
|
115678
115933
|
<div class="tlmi-row">
|
|
115679
115934
|
<label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc9(s.period.start)}" /></label>
|
|
115680
115935
|
<label class="tlmi-field">Fim<input type="date" data-field="end" value="${esc9(s.period.end)}" /></label>
|
|
115681
115936
|
<button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
|
|
115682
115937
|
</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
|
|
115938
|
+
<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
115939
|
</div>`;
|
|
115685
115940
|
}
|
|
115686
115941
|
function step2() {
|
|
@@ -115701,6 +115956,52 @@ function openTelemetryImportModal(params) {
|
|
|
115701
115956
|
</div>
|
|
115702
115957
|
${summary}`;
|
|
115703
115958
|
}
|
|
115959
|
+
function accSummaryHtml() {
|
|
115960
|
+
if (!s.rows.length && !s.localErrors.length) {
|
|
115961
|
+
return `<p class="tlmi-muted">Informe ao menos um total para ver a pr\xE9via.</p>`;
|
|
115962
|
+
}
|
|
115963
|
+
const hours = s.rows.length;
|
|
115964
|
+
const curve = dayCurve(DEFAULT_DISTRIBUTION_PROFILE);
|
|
115965
|
+
const peak = Math.max(...curve);
|
|
115966
|
+
return `
|
|
115967
|
+
<div class="tlmi-kpis">
|
|
115968
|
+
<div class="tlmi-kpi"><span>Dispositivos</span><strong>${fmtNum(s.acc.devices)}</strong></div>
|
|
115969
|
+
<div class="tlmi-kpi"><span>Horas geradas</span><strong>${fmtNum(hours)}</strong></div>
|
|
115970
|
+
<div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(s.acc.total, 3)}</strong></div>
|
|
115971
|
+
<div class="tlmi-kpi"><span>M\xE9dia por hora (${txt.unit})</span><strong>${fmtNum(hours ? s.acc.total / hours : 0, 3)}</strong></div>
|
|
115972
|
+
</div>
|
|
115973
|
+
${s.localErrors.length ? `<div class="tlmi-banner err">Corrija os itens abaixo \u2014 nada foi importado.</div>${issuesTable(s.localErrors)}` : ""}
|
|
115974
|
+
${s.acc.zeroEntries ? `<div class="tlmi-banner warn">${fmtNum(s.acc.zeroEntries)} per\xEDodo(s) com total zero: todas as horas ficam zeradas.</div>` : ""}
|
|
115975
|
+
${hours ? `<div class="tlmi-card"><h3>Distribui\xE7\xE3o em um dia</h3>
|
|
115976
|
+
<p class="tlmi-muted">${Math.round(DEFAULT_DISTRIBUTION_PROFILE.openShare * 100)}% do total no hor\xE1rio de funcionamento
|
|
115977
|
+
(${DEFAULT_DISTRIBUTION_PROFILE.openHour}h \xE0s ${DEFAULT_DISTRIBUTION_PROFILE.closeHour}h). Curva estimada: n\xE3o use para an\xE1lise de pico de demanda.</p>
|
|
115978
|
+
<div class="tlmi-curve" aria-hidden="true">${curve.map((w) => `<i style="height:${Math.round(w / peak * 100)}%"></i>`).join("")}</div>
|
|
115979
|
+
</div>` : ""}`;
|
|
115980
|
+
}
|
|
115981
|
+
function step2Accumulated() {
|
|
115982
|
+
const fromFile = !!s.fileName && !s.parseError;
|
|
115983
|
+
const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc9(s.fileName)}</strong>.
|
|
115984
|
+
<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>
|
|
115985
|
+
<div class="tlmi-acc"><table><thead><tr><th>Dispositivo</th><th>Total (${txt.unit})</th></tr></thead><tbody>
|
|
115986
|
+
${importable.map(
|
|
115987
|
+
(d, i) => `<tr><td>${esc9(d.label)}</td>
|
|
115988
|
+
<td><input inputmode="decimal" data-total="${i}" aria-label="Total de ${esc9(d.label)}" value="${esc9(s.formTotals[i] ?? "")}" /></td></tr>`
|
|
115989
|
+
).join("")}
|
|
115990
|
+
</tbody></table></div>`;
|
|
115991
|
+
return `
|
|
115992
|
+
<div class="tlmi-card"><h3>Totais por dispositivo</h3>${form}</div>
|
|
115993
|
+
<div class="tlmi-card"><h3>Ou envie a planilha</h3>
|
|
115994
|
+
<div class="tlmi-row" style="margin-bottom:10px">
|
|
115995
|
+
<button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
|
|
115996
|
+
</div>
|
|
115997
|
+
<label class="tlmi-drop" data-role="drop">
|
|
115998
|
+
<input type="file" accept=".xlsx,.xls,.csv" data-field="file" hidden />
|
|
115999
|
+
\u{1F4C4} Clique ou arraste a planilha aqui (.xlsx ou .csv)
|
|
116000
|
+
</label>
|
|
116001
|
+
${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${esc9(s.parseError)}</div>` : ""}
|
|
116002
|
+
</div>
|
|
116003
|
+
<div data-role="acc-summary" style="display:flex;flex-direction:column;gap:12px">${accSummaryHtml()}</div>`;
|
|
116004
|
+
}
|
|
115704
116005
|
function step3() {
|
|
115705
116006
|
const v = s.validation;
|
|
115706
116007
|
if (!v) return `${apiErrorBanner()}<div class="tlmi-card"><p class="tlmi-muted">${s.busy ? "Validando\u2026" : "Aguardando valida\xE7\xE3o."}</p></div>`;
|
|
@@ -115710,17 +116011,21 @@ function openTelemetryImportModal(params) {
|
|
|
115710
116011
|
}
|
|
115711
116012
|
const p = v.preview || {};
|
|
115712
116013
|
const real = Number(p.existingRealReadings || 0);
|
|
115713
|
-
const period = typeof p.period === "string" ? p.period : p.period ? `${p.period.start
|
|
116014
|
+
const period = typeof p.period === "string" ? p.period : p.period ? `${fmtSaoPaulo(p.period.start)} at\xE9 a hora de ${fmtSaoPaulo(p.period.end)}` : "\u2014";
|
|
115714
116015
|
const devices = Array.isArray(p.devices) ? p.devices.length : p.devices;
|
|
116016
|
+
const reactiveWarn = domain === "energy" && Number(p.existingReadingsInTarget || 0) > 0 && !s.rows.some((r) => r.value_reactive_kvarh !== void 0) ? `<div class="tlmi-banner warn">A planilha n\xE3o traz energia reativa: as ${fmtNum(p.existingReadingsInTarget)} hora(s) que j\xE1 t\xEAm leitura
|
|
116017
|
+
ficar\xE3o com reativa 0. A reativa original fica guardada e volta se a importa\xE7\xE3o for desfeita.</div>` : "";
|
|
115715
116018
|
return `
|
|
115716
|
-
<div class="tlmi-banner ok"
|
|
116019
|
+
<div class="tlmi-banner ok">${s.model === "accumulated" ? "Valores v\xE1lidos" : "Planilha v\xE1lida"}. Confira o resumo antes de importar.</div>
|
|
116020
|
+
${s.model === "accumulated" ? '<div class="tlmi-banner warn">Os valores por hora s\xE3o estimados a partir do total informado.</div>' : ""}
|
|
115717
116021
|
<div class="tlmi-kpis">
|
|
115718
116022
|
<div class="tlmi-kpi"><span>Horas a gravar</span><strong>${fmtNum(p.targetSlots)}</strong></div>
|
|
115719
116023
|
<div class="tlmi-kpi"><span>Dispositivos</span><strong>${fmtNum(devices)}</strong></div>
|
|
115720
116024
|
<div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
|
|
115721
116025
|
<div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
|
|
115722
116026
|
</div>
|
|
115723
|
-
<p class="tlmi-muted">Per\xEDodo: ${esc9(period)}</p>
|
|
116027
|
+
<p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${esc9(period)}</p>
|
|
116028
|
+
${reactiveWarn}
|
|
115724
116029
|
${real > 0 ? `<div class="tlmi-banner warn"><strong>${fmtNum(real)} leitura(s) reais do medidor</strong> ser\xE3o substitu\xEDdas pelos valores da planilha.
|
|
115725
116030
|
<label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
|
|
115726
116031
|
Confirmo a substitui\xE7\xE3o das leituras reais.</label></div>` : ""}
|
|
@@ -115734,12 +116039,21 @@ function openTelemetryImportModal(params) {
|
|
|
115734
116039
|
const terminal = TERMINAL_JOB_STATUSES.includes(j.status);
|
|
115735
116040
|
let banner = "";
|
|
115736
116041
|
if (j.status === "completed") {
|
|
115737
|
-
banner = j.refreshStatus === "failed" ? '<div class="tlmi-banner warn">Dados importados, mas a atualiza\xE7\xE3o dos totais falhou. Avise o suporte MyIO.</div>' :
|
|
116042
|
+
banner = j.refreshStatus === "failed" ? '<div class="tlmi-banner warn">Dados importados, mas a atualiza\xE7\xE3o dos totais falhou. Avise o suporte MyIO.</div>' : `<div class="tlmi-banner ok">Importa\xE7\xE3o conclu\xEDda. Os totais podem levar alguns minutos para refletir.
|
|
116043
|
+
<div class="tlmi-muted" style="margin-top:4px">Dispositivos manuais continuam aparecendo sem comunica\xE7\xE3o no status:
|
|
116044
|
+
o status conta s\xF3 leitura medida. Os totais e os cards usam os dados importados.</div></div>`;
|
|
115738
116045
|
} else if (j.status === "failed") {
|
|
115739
116046
|
banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc9(j.error)}` : "."}</div>`;
|
|
115740
116047
|
} else if (j.status === "cancelled") {
|
|
115741
116048
|
banner = '<div class="tlmi-banner warn">Importa\xE7\xE3o cancelada. As leituras anteriores foram mantidas.</div>';
|
|
116049
|
+
} else if (j.status === "reverted") {
|
|
116050
|
+
banner = '<div class="tlmi-banner ok">Importa\xE7\xE3o desfeita. As leituras anteriores foram restauradas.</div>';
|
|
115742
116051
|
}
|
|
116052
|
+
const canRevert = j.status === "completed" || j.status === "failed";
|
|
116053
|
+
const revert = canRevert ? `<div style="margin-top:12px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
|
|
116054
|
+
<button class="tlmi-btn" type="button" data-action="revert" ${s.busy ? "disabled" : ""}>${s.confirmRevert ? "Confirmar: desfazer importa\xE7\xE3o" : "Desfazer importa\xE7\xE3o"}</button>
|
|
116055
|
+
<span class="tlmi-muted">${s.confirmRevert ? "Remove as horas importadas e devolve as leituras apagadas. Clique de novo para confirmar." : "Use para remover uma importa\xE7\xE3o errada ou de teste."}</span>
|
|
116056
|
+
</div>` : "";
|
|
115743
116057
|
return `
|
|
115744
116058
|
<div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc9(statusText)}</span></h3>
|
|
115745
116059
|
<div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
|
|
@@ -115749,15 +116063,17 @@ function openTelemetryImportModal(params) {
|
|
|
115749
116063
|
<div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
|
|
115750
116064
|
</div>
|
|
115751
116065
|
${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc9(j.phase)}</p>` : ""}
|
|
115752
|
-
${!terminal ? `<div style="margin-top:12px"><button class="tlmi-btn" type="button" data-action="cancel" ${s.busy ? "disabled" : ""}>Cancelar importa\xE7\xE3o</button>
|
|
116066
|
+
${!terminal && j.status !== "reverting" ? `<div style="margin-top:12px"><button class="tlmi-btn" type="button" data-action="cancel" ${s.busy ? "disabled" : ""}>Cancelar importa\xE7\xE3o</button>
|
|
115753
116067
|
<span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
|
|
116068
|
+
${revert}
|
|
115754
116069
|
</div>
|
|
115755
116070
|
${banner}
|
|
115756
116071
|
${apiErrorBanner()}`;
|
|
115757
116072
|
}
|
|
115758
116073
|
function render3() {
|
|
115759
116074
|
if (closed) return;
|
|
115760
|
-
const
|
|
116075
|
+
const step2Body = () => s.model === "accumulated" ? step2Accumulated() : step2();
|
|
116076
|
+
const body = s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
|
|
115761
116077
|
root.innerHTML = stepper() + body;
|
|
115762
116078
|
syncFooter();
|
|
115763
116079
|
}
|
|
@@ -115767,7 +116083,11 @@ function openTelemetryImportModal(params) {
|
|
|
115767
116083
|
modal.setButton("back", { hidden: s.step === 1 || s.step === 4, disabled: s.busy });
|
|
115768
116084
|
if (s.step === 1) modal.setButton("next", { label: "Avan\xE7ar", disabled: false, hidden: false });
|
|
115769
116085
|
if (s.step === 2)
|
|
115770
|
-
modal.setButton("next", {
|
|
116086
|
+
modal.setButton("next", {
|
|
116087
|
+
label: s.model === "accumulated" ? "Validar" : "Validar planilha",
|
|
116088
|
+
disabled: s.busy || !s.rows.length || !!s.localErrors.length || !!s.parseError,
|
|
116089
|
+
hidden: false
|
|
116090
|
+
});
|
|
115771
116091
|
if (s.step === 3) {
|
|
115772
116092
|
const real = v && v.valid ? Number(v.preview?.existingRealReadings || 0) : 0;
|
|
115773
116093
|
modal.setButton("next", {
|
|
@@ -115788,6 +116108,7 @@ function openTelemetryImportModal(params) {
|
|
|
115788
116108
|
async function goNext() {
|
|
115789
116109
|
if (s.busy) return;
|
|
115790
116110
|
if (s.step === 1) {
|
|
116111
|
+
if (s.model === "accumulated") recomputeAccumulated();
|
|
115791
116112
|
s.step = 2;
|
|
115792
116113
|
render3();
|
|
115793
116114
|
} else if (s.step === 2) {
|
|
@@ -115800,18 +116121,61 @@ function openTelemetryImportModal(params) {
|
|
|
115800
116121
|
}
|
|
115801
116122
|
}
|
|
115802
116123
|
function downloadTemplate() {
|
|
115803
|
-
const { csv, rows } = buildTemplateCsv(domain, importable, s.period.start, s.period.end, now());
|
|
116124
|
+
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
116125
|
if (!rows) return;
|
|
115805
116126
|
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
|
|
115806
116127
|
const a = document.createElement("a");
|
|
115807
116128
|
a.href = URL.createObjectURL(blob);
|
|
115808
116129
|
const who = (params.customerName || "shopping").replace(/[^\w-]+/g, "_");
|
|
115809
|
-
|
|
116130
|
+
const kind = s.model === "accumulated" ? "-acumulado" : "";
|
|
116131
|
+
a.download = `importacao${kind}-${domain === "energy" ? "energia" : "agua"}-${who}-${s.period.start}_${s.period.end}.csv`;
|
|
115810
116132
|
document.body.appendChild(a);
|
|
115811
116133
|
a.click();
|
|
115812
116134
|
a.remove();
|
|
115813
116135
|
setTimeout(() => URL.revokeObjectURL(a.href), 1e3);
|
|
115814
116136
|
}
|
|
116137
|
+
function formEntries() {
|
|
116138
|
+
const entries = [];
|
|
116139
|
+
const errors = [];
|
|
116140
|
+
importable.forEach((d, i) => {
|
|
116141
|
+
const total = parseDecimal(s.formTotals[i] ?? "");
|
|
116142
|
+
if (total === null) return;
|
|
116143
|
+
if (Number.isNaN(total) || total < 0) {
|
|
116144
|
+
errors.push({ line: i + 1, reason: `${d.label}: total deve ser n\xFAmero \u2265 0` });
|
|
116145
|
+
return;
|
|
116146
|
+
}
|
|
116147
|
+
entries.push({
|
|
116148
|
+
line: i + 1,
|
|
116149
|
+
gateway_id: String(d.centralId),
|
|
116150
|
+
slave_id: Number(d.slaveId),
|
|
116151
|
+
device_name: d.label,
|
|
116152
|
+
start: s.period.start,
|
|
116153
|
+
end: s.period.end,
|
|
116154
|
+
total
|
|
116155
|
+
});
|
|
116156
|
+
});
|
|
116157
|
+
return { entries, errors };
|
|
116158
|
+
}
|
|
116159
|
+
function recomputeAccumulated() {
|
|
116160
|
+
const src = s.fileEntries ? { entries: s.fileEntries, errors: s.fileErrors } : formEntries();
|
|
116161
|
+
const r = accumulatedRows(domain, src.entries, DEFAULT_DISTRIBUTION_PROFILE, now());
|
|
116162
|
+
s.rows = r.rows;
|
|
116163
|
+
s.localErrors = [...src.errors, ...r.errors];
|
|
116164
|
+
s.acc = { devices: r.devices, total: r.total, zeroEntries: r.zeroEntries };
|
|
116165
|
+
s.validation = null;
|
|
116166
|
+
}
|
|
116167
|
+
function refreshAccSummary() {
|
|
116168
|
+
const el2 = root.querySelector('[data-role="acc-summary"]');
|
|
116169
|
+
if (el2) el2.innerHTML = accSummaryHtml();
|
|
116170
|
+
syncFooter();
|
|
116171
|
+
}
|
|
116172
|
+
function resetAccumulatedSource() {
|
|
116173
|
+
s.fileName = "";
|
|
116174
|
+
s.parseError = "";
|
|
116175
|
+
s.fileEntries = null;
|
|
116176
|
+
s.fileErrors = [];
|
|
116177
|
+
s.skippedEmpty = 0;
|
|
116178
|
+
}
|
|
115815
116179
|
async function loadFile(file) {
|
|
115816
116180
|
if (!file) return;
|
|
115817
116181
|
s.fileName = file.name;
|
|
@@ -115822,10 +116186,18 @@ function openTelemetryImportModal(params) {
|
|
|
115822
116186
|
s.validation = null;
|
|
115823
116187
|
try {
|
|
115824
116188
|
const table = await parseSheetFile(file);
|
|
115825
|
-
|
|
115826
|
-
|
|
115827
|
-
|
|
115828
|
-
|
|
116189
|
+
if (s.model === "accumulated") {
|
|
116190
|
+
const r = entriesFromTable(domain, table);
|
|
116191
|
+
s.fileEntries = r.entries;
|
|
116192
|
+
s.fileErrors = r.errors;
|
|
116193
|
+
s.skippedEmpty = r.skippedEmpty;
|
|
116194
|
+
recomputeAccumulated();
|
|
116195
|
+
} else {
|
|
116196
|
+
const r = rowsFromTable(domain, table);
|
|
116197
|
+
s.rows = r.rows;
|
|
116198
|
+
s.localErrors = r.errors;
|
|
116199
|
+
s.skippedEmpty = r.skippedEmpty;
|
|
116200
|
+
}
|
|
115829
116201
|
} catch (err) {
|
|
115830
116202
|
s.parseError = err?.message || "N\xE3o foi poss\xEDvel ler a planilha.";
|
|
115831
116203
|
}
|
|
@@ -115838,7 +116210,8 @@ function openTelemetryImportModal(params) {
|
|
|
115838
116210
|
s.step = 3;
|
|
115839
116211
|
render3();
|
|
115840
116212
|
try {
|
|
115841
|
-
|
|
116213
|
+
const sourceRef = s.model === "accumulated" ? `${ACCUMULATED_SOURCE_PREFIX}:${s.fileName || "tela"}` : s.fileName;
|
|
116214
|
+
s.validation = await api.validate({ customerId: params.customerId, readingType: domain, rows: s.rows, sourceRef });
|
|
115842
116215
|
} catch (err) {
|
|
115843
116216
|
setError(err);
|
|
115844
116217
|
} finally {
|
|
@@ -115865,7 +116238,7 @@ function openTelemetryImportModal(params) {
|
|
|
115865
116238
|
render3();
|
|
115866
116239
|
}
|
|
115867
116240
|
}
|
|
115868
|
-
function schedulePoll(delay = params.pollMs ??
|
|
116241
|
+
function schedulePoll(delay = params.pollMs ?? 2500) {
|
|
115869
116242
|
if (closed || !s.job?.jobId) return;
|
|
115870
116243
|
pollTimer = setTimeout(async () => {
|
|
115871
116244
|
if (closed || !s.job?.jobId) return;
|
|
@@ -115893,17 +116266,60 @@ function openTelemetryImportModal(params) {
|
|
|
115893
116266
|
render3();
|
|
115894
116267
|
}
|
|
115895
116268
|
}
|
|
116269
|
+
async function revertJob() {
|
|
116270
|
+
if (!s.job?.jobId || s.busy) return;
|
|
116271
|
+
if (!s.confirmRevert) {
|
|
116272
|
+
s.confirmRevert = true;
|
|
116273
|
+
render3();
|
|
116274
|
+
return;
|
|
116275
|
+
}
|
|
116276
|
+
s.busy = true;
|
|
116277
|
+
s.confirmRevert = false;
|
|
116278
|
+
s.apiError = "";
|
|
116279
|
+
render3();
|
|
116280
|
+
try {
|
|
116281
|
+
const j = await api.revertJob(s.job.jobId);
|
|
116282
|
+
if (j?.status) s.job = { ...s.job, ...j };
|
|
116283
|
+
if (s.job && !TERMINAL_JOB_STATUSES.includes(s.job.status)) schedulePoll(0);
|
|
116284
|
+
} catch (err) {
|
|
116285
|
+
setError(err);
|
|
116286
|
+
} finally {
|
|
116287
|
+
s.busy = false;
|
|
116288
|
+
render3();
|
|
116289
|
+
}
|
|
116290
|
+
}
|
|
115896
116291
|
root.addEventListener("click", (e) => {
|
|
115897
116292
|
const el2 = e.target.closest("[data-action]");
|
|
115898
116293
|
if (!el2) return;
|
|
115899
116294
|
if (el2.dataset.action === "template") downloadTemplate();
|
|
115900
116295
|
if (el2.dataset.action === "cancel") void cancelJob();
|
|
116296
|
+
if (el2.dataset.action === "revert") void revertJob();
|
|
116297
|
+
if (el2.dataset.action === "use-form") {
|
|
116298
|
+
resetAccumulatedSource();
|
|
116299
|
+
recomputeAccumulated();
|
|
116300
|
+
render3();
|
|
116301
|
+
}
|
|
116302
|
+
});
|
|
116303
|
+
root.addEventListener("input", (e) => {
|
|
116304
|
+
const t = e.target;
|
|
116305
|
+
if (t.dataset.total === void 0) return;
|
|
116306
|
+
s.formTotals[Number(t.dataset.total)] = t.value;
|
|
116307
|
+
recomputeAccumulated();
|
|
116308
|
+
refreshAccSummary();
|
|
115901
116309
|
});
|
|
115902
116310
|
root.addEventListener("change", (e) => {
|
|
115903
116311
|
const t = e.target;
|
|
115904
116312
|
if (t.dataset.field === "start") s.period.start = t.value;
|
|
115905
116313
|
if (t.dataset.field === "end") s.period.end = t.value;
|
|
115906
116314
|
if (t.dataset.field === "file") void loadFile(t.files?.[0]);
|
|
116315
|
+
if (t.dataset.field === "model") {
|
|
116316
|
+
s.model = t.value;
|
|
116317
|
+
resetAccumulatedSource();
|
|
116318
|
+
s.rows = [];
|
|
116319
|
+
s.localErrors = [];
|
|
116320
|
+
s.validation = null;
|
|
116321
|
+
render3();
|
|
116322
|
+
}
|
|
115907
116323
|
if (t.dataset.field === "confirmReal") {
|
|
115908
116324
|
s.confirmReal = t.checked;
|
|
115909
116325
|
syncFooter();
|
|
@@ -120752,8 +121168,8 @@ var GroupManagementTab = class {
|
|
|
120752
121168
|
async toggleGroup(group, item) {
|
|
120753
121169
|
const panel = item.querySelector(".gm-accordion-panel");
|
|
120754
121170
|
const toggle = item.querySelector(".gm-accordion-toggle");
|
|
120755
|
-
const
|
|
120756
|
-
if (
|
|
121171
|
+
const isOpen2 = this.expandedGroupId === group.id;
|
|
121172
|
+
if (isOpen2) {
|
|
120757
121173
|
this.expandedGroupId = null;
|
|
120758
121174
|
panel.style.display = "none";
|
|
120759
121175
|
toggle.setAttribute("aria-expanded", "false");
|
|
@@ -166196,7 +166612,7 @@ function renderModalHTML(data, source, config2) {
|
|
|
166196
166612
|
function createAmbienteDetailModal(data, source, config2 = {}) {
|
|
166197
166613
|
injectAmbienteModalStyles();
|
|
166198
166614
|
let container = null;
|
|
166199
|
-
let
|
|
166615
|
+
let isOpen2 = false;
|
|
166200
166616
|
function createContainer() {
|
|
166201
166617
|
container = document.createElement("div");
|
|
166202
166618
|
container.innerHTML = renderModalHTML(data, source, config2);
|
|
@@ -166270,7 +166686,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
|
|
|
166270
166686
|
}
|
|
166271
166687
|
}
|
|
166272
166688
|
function handleEscape(e) {
|
|
166273
|
-
if (e.key === "Escape" &&
|
|
166689
|
+
if (e.key === "Escape" && isOpen2) {
|
|
166274
166690
|
close();
|
|
166275
166691
|
}
|
|
166276
166692
|
}
|
|
@@ -166284,7 +166700,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
|
|
|
166284
166700
|
overlay.classList.add("visible");
|
|
166285
166701
|
});
|
|
166286
166702
|
}
|
|
166287
|
-
|
|
166703
|
+
isOpen2 = true;
|
|
166288
166704
|
document.body.style.overflow = "hidden";
|
|
166289
166705
|
}
|
|
166290
166706
|
function close() {
|
|
@@ -166295,7 +166711,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
|
|
|
166295
166711
|
destroy();
|
|
166296
166712
|
}, 200);
|
|
166297
166713
|
}
|
|
166298
|
-
|
|
166714
|
+
isOpen2 = false;
|
|
166299
166715
|
document.body.style.overflow = "";
|
|
166300
166716
|
document.removeEventListener("keydown", handleEscape);
|
|
166301
166717
|
config2.onClose?.();
|
|
@@ -166311,7 +166727,7 @@ function createAmbienteDetailModal(data, source, config2 = {}) {
|
|
|
166311
166727
|
container.parentNode.removeChild(container);
|
|
166312
166728
|
}
|
|
166313
166729
|
container = null;
|
|
166314
|
-
|
|
166730
|
+
isOpen2 = false;
|
|
166315
166731
|
document.removeEventListener("keydown", handleEscape);
|
|
166316
166732
|
}
|
|
166317
166733
|
return {
|
|
@@ -167094,7 +167510,7 @@ function renderModalHTML2(data, config2) {
|
|
|
167094
167510
|
function createAmbienteGroupModal(data, config2 = {}) {
|
|
167095
167511
|
injectAmbienteGroupModalStyles();
|
|
167096
167512
|
let container = null;
|
|
167097
|
-
let
|
|
167513
|
+
let isOpen2 = false;
|
|
167098
167514
|
function createContainer() {
|
|
167099
167515
|
container = document.createElement("div");
|
|
167100
167516
|
container.innerHTML = renderModalHTML2(data, config2);
|
|
@@ -167154,7 +167570,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
|
|
|
167154
167570
|
});
|
|
167155
167571
|
}
|
|
167156
167572
|
function handleEscape(e) {
|
|
167157
|
-
if (e.key === "Escape" &&
|
|
167573
|
+
if (e.key === "Escape" && isOpen2) {
|
|
167158
167574
|
close();
|
|
167159
167575
|
}
|
|
167160
167576
|
}
|
|
@@ -167168,7 +167584,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
|
|
|
167168
167584
|
overlay.classList.add("visible");
|
|
167169
167585
|
});
|
|
167170
167586
|
}
|
|
167171
|
-
|
|
167587
|
+
isOpen2 = true;
|
|
167172
167588
|
document.body.style.overflow = "hidden";
|
|
167173
167589
|
}
|
|
167174
167590
|
function close() {
|
|
@@ -167179,7 +167595,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
|
|
|
167179
167595
|
destroy();
|
|
167180
167596
|
}, 200);
|
|
167181
167597
|
}
|
|
167182
|
-
|
|
167598
|
+
isOpen2 = false;
|
|
167183
167599
|
document.body.style.overflow = "";
|
|
167184
167600
|
document.removeEventListener("keydown", handleEscape);
|
|
167185
167601
|
config2.onClose?.();
|
|
@@ -167195,7 +167611,7 @@ function createAmbienteGroupModal(data, config2 = {}) {
|
|
|
167195
167611
|
container.parentNode.removeChild(container);
|
|
167196
167612
|
}
|
|
167197
167613
|
container = null;
|
|
167198
|
-
|
|
167614
|
+
isOpen2 = false;
|
|
167199
167615
|
document.removeEventListener("keydown", handleEscape);
|
|
167200
167616
|
}
|
|
167201
167617
|
return {
|
|
@@ -176867,7 +177283,7 @@ function prefixForProductType(productType) {
|
|
|
176867
177283
|
if (entry) return entry.prefix;
|
|
176868
177284
|
return `T${productType}`;
|
|
176869
177285
|
}
|
|
176870
|
-
function
|
|
177286
|
+
function pad26(n) {
|
|
176871
177287
|
return String(n).padStart(2, "0");
|
|
176872
177288
|
}
|
|
176873
177289
|
function pad4(n) {
|
|
@@ -176875,9 +177291,9 @@ function pad4(n) {
|
|
|
176875
177291
|
}
|
|
176876
177292
|
function deviceProductCodeToName(value) {
|
|
176877
177293
|
const prefix = prefixForProductType(value.productType);
|
|
176878
|
-
const yy =
|
|
176879
|
-
const mm =
|
|
176880
|
-
const dd =
|
|
177294
|
+
const yy = pad26(value.year % 100);
|
|
177295
|
+
const mm = pad26(value.month);
|
|
177296
|
+
const dd = pad26(value.day);
|
|
176881
177297
|
const unit = value.seq3 * 254 + value.seq;
|
|
176882
177298
|
return `${prefix} ${yy}${mm}${dd}-${pad4(unit)}`;
|
|
176883
177299
|
}
|
|
@@ -178519,6 +178935,7 @@ var version = package_default.version || "0.0.0";
|
|
|
178519
178935
|
DEFAULT_DEVICE_OPERATIONAL_CARD_FILTER_STATE,
|
|
178520
178936
|
DEFAULT_DEVICE_TYPE_PREFIX,
|
|
178521
178937
|
DEFAULT_DEVICE_TYPE_TOKEN,
|
|
178938
|
+
DEFAULT_DISTRIBUTION_PROFILE,
|
|
178522
178939
|
DEFAULT_ENABLED_REPORT_ITEMS,
|
|
178523
178940
|
DEFAULT_ENERGY_GROUP_COLORS,
|
|
178524
178941
|
DEFAULT_EQUIPMENT_FILTER_STATE,
|
|
@@ -178771,6 +179188,7 @@ var version = package_default.version || "0.0.0";
|
|
|
178771
179188
|
WELCOME_DEFAULT_PALETTE,
|
|
178772
179189
|
Water,
|
|
178773
179190
|
WaterSummaryTooltip,
|
|
179191
|
+
accumulatedRows,
|
|
178774
179192
|
adaptGcdrListToLegacyAnnotations,
|
|
178775
179193
|
adaptGcdrToLegacyAnnotation,
|
|
178776
179194
|
adaptLegacyToGcdrInput,
|
|
@@ -178789,6 +179207,7 @@ var version = package_default.version || "0.0.0";
|
|
|
178789
179207
|
assetLocalToken,
|
|
178790
179208
|
assignShoppingColors,
|
|
178791
179209
|
averageByDay,
|
|
179210
|
+
buildAccumulatedTemplateCsv,
|
|
178792
179211
|
buildAmbienteGroupData,
|
|
178793
179212
|
buildAnnotationServiceOrchestrator,
|
|
178794
179213
|
buildAnnotationsCsv,
|
|
@@ -178976,6 +179395,7 @@ var version = package_default.version || "0.0.0";
|
|
|
178976
179395
|
deviceProductCodeToName,
|
|
178977
179396
|
deviceStatusIcons,
|
|
178978
179397
|
deviceTypeToken,
|
|
179398
|
+
distributeTotal,
|
|
178979
179399
|
doSchedulesOverlap,
|
|
178980
179400
|
downloadAnnotationsTextFile,
|
|
178981
179401
|
encodeDeviceProductCode,
|