myio-js-library 0.1.573 → 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 CHANGED
@@ -958,7 +958,7 @@ module.exports = __toCommonJS(src_exports);
958
958
  // package.json
959
959
  var package_default = {
960
960
  name: "myio-js-library",
961
- version: "0.1.573",
961
+ version: "0.1.574",
962
962
  description: "A clean, standalone JS SDK for MYIO projects",
963
963
  license: "MIT",
964
964
  repository: "github:gh-myio/myio-js-library",
@@ -115636,27 +115636,74 @@ var ImportApiError = class extends Error {
115636
115636
  this.name = "ImportApiError";
115637
115637
  }
115638
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
+ }
115639
115668
  function createTelemetryImportApi(cfg) {
115640
115669
  const base = String(cfg.baseUrl || "").replace(/\/+$/, "");
115641
115670
  const doFetch = cfg.fetchImpl ?? fetch.bind(window);
115642
- const call = async (method, path, body, accept422 = false) => {
115643
- const token = await cfg.getToken();
115644
- const res = await doFetch(`${base}/import${path}`, {
115645
- method,
115646
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
115647
- body: body === void 0 ? void 0 : JSON.stringify(body)
115648
- });
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) => {
115649
115687
  const text2 = await res.text().catch(() => "");
115650
- let data = null;
115651
115688
  try {
115652
- data = text2 ? JSON.parse(text2) : null;
115689
+ return { text: text2, data: text2 ? JSON.parse(text2) : null };
115653
115690
  } catch {
115654
- data = null;
115691
+ return { text: text2, data: null };
115655
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;
115656
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);
115657
115705
  const apiMsg = data?.message || data?.error || "";
115658
- const msg = res.status === 404 ? "A importa\xE7\xE3o ainda n\xE3o est\xE1 dispon\xEDvel neste ambiente." : res.status === 401 || res.status === 403 ? "Sem permiss\xE3o para importar telemetria (credencial sem o escopo telemetry.import)." : res.status === 409 ? apiMsg || "Opera\xE7\xE3o n\xE3o permitida no estado atual da importa\xE7\xE3o." : `Falha na API de importa\xE7\xE3o (${res.status}).`;
115659
- 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)}`);
115660
115707
  };
115661
115708
  return {
115662
115709
  async validate(body) {
@@ -115677,6 +115724,10 @@ function createTelemetryImportApi(cfg) {
115677
115724
  async cancelJob(jobId) {
115678
115725
  const { data } = await call("POST", `/jobs/${encodeURIComponent(jobId)}/cancel`);
115679
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;
115680
115731
  }
115681
115732
  };
115682
115733
  }
@@ -115698,8 +115749,16 @@ var JOB_STATUS_TEXT = {
115698
115749
  completed: "Conclu\xEDda",
115699
115750
  failed: "Falhou",
115700
115751
  cancelled: "Cancelada",
115701
- reverted: "Revertida"
115752
+ reverting: "Desfazendo",
115753
+ reverted: "Desfeita"
115702
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
+ }
115703
115762
  var STYLE_ID14 = "myio-tlmimport-styles";
115704
115763
  function esc9(v) {
115705
115764
  return String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -115802,6 +115861,8 @@ function openTelemetryImportModal(params) {
115802
115861
  apiError: "",
115803
115862
  apiDetail: "",
115804
115863
  confirmReal: false,
115864
+ /** "Desfazer importação" pede um segundo clique antes de chamar o revert */
115865
+ confirmRevert: false,
115805
115866
  job: null
115806
115867
  };
115807
115868
  let pollTimer = null;
@@ -115950,8 +116011,10 @@ function openTelemetryImportModal(params) {
115950
116011
  }
115951
116012
  const p = v.preview || {};
115952
116013
  const real = Number(p.existingRealReadings || 0);
115953
- const period = typeof p.period === "string" ? p.period : p.period ? `${p.period.start || ""} \u2192 ${p.period.end || ""}` : "\u2014";
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";
115954
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>` : "";
115955
116018
  return `
115956
116019
  <div class="tlmi-banner ok">${s.model === "accumulated" ? "Valores v\xE1lidos" : "Planilha v\xE1lida"}. Confira o resumo antes de importar.</div>
115957
116020
  ${s.model === "accumulated" ? '<div class="tlmi-banner warn">Os valores por hora s\xE3o estimados a partir do total informado.</div>' : ""}
@@ -115961,7 +116024,8 @@ function openTelemetryImportModal(params) {
115961
116024
  <div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
115962
116025
  <div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
115963
116026
  </div>
115964
- <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}
115965
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.
115966
116030
  <label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
115967
116031
  Confirmo a substitui\xE7\xE3o das leituras reais.</label></div>` : ""}
@@ -115975,12 +116039,21 @@ function openTelemetryImportModal(params) {
115975
116039
  const terminal = TERMINAL_JOB_STATUSES.includes(j.status);
115976
116040
  let banner = "";
115977
116041
  if (j.status === "completed") {
115978
- 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.</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>`;
115979
116045
  } else if (j.status === "failed") {
115980
116046
  banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc9(j.error)}` : "."}</div>`;
115981
116047
  } else if (j.status === "cancelled") {
115982
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>';
115983
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>` : "";
115984
116057
  return `
115985
116058
  <div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc9(statusText)}</span></h3>
115986
116059
  <div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
@@ -115990,8 +116063,9 @@ function openTelemetryImportModal(params) {
115990
116063
  <div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
115991
116064
  </div>
115992
116065
  ${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc9(j.phase)}</p>` : ""}
115993
- ${!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>
115994
116067
  <span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
116068
+ ${revert}
115995
116069
  </div>
115996
116070
  ${banner}
115997
116071
  ${apiErrorBanner()}`;
@@ -116164,7 +116238,7 @@ function openTelemetryImportModal(params) {
116164
116238
  render3();
116165
116239
  }
116166
116240
  }
116167
- function schedulePoll(delay = params.pollMs ?? 5e3) {
116241
+ function schedulePoll(delay = params.pollMs ?? 2500) {
116168
116242
  if (closed || !s.job?.jobId) return;
116169
116243
  pollTimer = setTimeout(async () => {
116170
116244
  if (closed || !s.job?.jobId) return;
@@ -116192,11 +116266,34 @@ function openTelemetryImportModal(params) {
116192
116266
  render3();
116193
116267
  }
116194
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
+ }
116195
116291
  root.addEventListener("click", (e) => {
116196
116292
  const el2 = e.target.closest("[data-action]");
116197
116293
  if (!el2) return;
116198
116294
  if (el2.dataset.action === "template") downloadTemplate();
116199
116295
  if (el2.dataset.action === "cancel") void cancelJob();
116296
+ if (el2.dataset.action === "revert") void revertJob();
116200
116297
  if (el2.dataset.action === "use-form") {
116201
116298
  resetAccumulatedSource();
116202
116299
  recomputeAccumulated();
package/dist/index.d.cts CHANGED
@@ -17386,14 +17386,23 @@ declare function rowsFromTable(domain: ImportDomain, table: unknown[][]): RowsFr
17386
17386
 
17387
17387
  /**
17388
17388
  * Cliente da API de importação do Ingestion (`/api/v1/import`, runbook TELEMETRY-SHEET-IMPORT §4):
17389
- * validate → jobs (start) → jobs/:id (poll) → jobs/:id/cancel. Autenticação Bearer (token do
17390
- * client_credentials do customer — `buildMyioIngestionAuth`).
17389
+ * validate → jobs (start) → jobs/:id (poll) → jobs/:id/cancel | jobs/:id/revert. Autenticação
17390
+ * Bearer com o escopo `telemetry.import` (token do client_credentials — `buildMyioIngestionAuth`).
17391
+ *
17392
+ * Mensagens de erro seguem a resposta do Ingestion de 03/11/2026
17393
+ * (`RESPOSTA-IMPORTACAO-PLANILHA-TELEMETRIA-2026-11-03.md` §4).
17391
17394
  */
17392
17395
 
17393
17396
  interface TelemetryImportApiConfig {
17394
17397
  /** Base da API do Ingestion, ex.: https://api.data.apps.myio-bas.com/api/v1 */
17395
17398
  baseUrl: string;
17399
+ /** Token reaproveitado (o /auth aceita só 5 pedidos a cada 15 min por client) */
17396
17400
  getToken: () => Promise<string>;
17401
+ /**
17402
+ * Token novo, ignorando o cache — usado UMA vez após 401, ou 403 de escopo (um token emitido
17403
+ * antes de o client ganhar `telemetry.import` não carrega o escopo). Sem ele, não há retry.
17404
+ */
17405
+ refreshToken?: () => Promise<string>;
17397
17406
  fetchImpl?: typeof fetch;
17398
17407
  }
17399
17408
  interface ImportPreview {
@@ -17421,7 +17430,8 @@ type ValidateResult = {
17421
17430
  reason: string;
17422
17431
  }>;
17423
17432
  };
17424
- type ImportJobStatus = 'queued' | 'executing' | 'completed' | 'failed' | 'cancelled' | 'reverted' | string;
17433
+ /** `reverting` é transitório (durante o revert): não é terminal. */
17434
+ type ImportJobStatus = 'queued' | 'executing' | 'completed' | 'failed' | 'cancelled' | 'reverting' | 'reverted' | string;
17425
17435
  interface ImportJob {
17426
17436
  jobId?: string;
17427
17437
  status: ImportJobStatus;
@@ -17457,6 +17467,8 @@ interface TelemetryImportApi {
17457
17467
  }>;
17458
17468
  getJob(jobId: string): Promise<ImportJob>;
17459
17469
  cancelJob(jobId: string): Promise<ImportJob | null>;
17470
+ /** Desfaz uma importação `completed`/`failed`: remove as horas e devolve as leituras apagadas */
17471
+ revertJob(jobId: string): Promise<ImportJob | null>;
17460
17472
  }
17461
17473
  declare function createTelemetryImportApi(cfg: TelemetryImportApiConfig): TelemetryImportApi;
17462
17474
 
@@ -17482,7 +17494,7 @@ interface OpenTelemetryImportModalParams {
17482
17494
  customerName?: string;
17483
17495
  /** Usuário MyIO: mostra detalhes técnicos dos erros */
17484
17496
  showTechnicalDetails?: boolean;
17485
- /** Intervalo do acompanhamento do job (ms). Default 5000. */
17497
+ /** Intervalo do acompanhamento do job (ms). Default 2500 (o Ingestion sugere 2–3 s). */
17486
17498
  pollMs?: number;
17487
17499
  /** Chamado quando a importação termina com sucesso */
17488
17500
  onCompleted?: (job: ImportJob) => void;
package/dist/index.d.ts CHANGED
@@ -17386,14 +17386,23 @@ declare function rowsFromTable(domain: ImportDomain, table: unknown[][]): RowsFr
17386
17386
 
17387
17387
  /**
17388
17388
  * Cliente da API de importação do Ingestion (`/api/v1/import`, runbook TELEMETRY-SHEET-IMPORT §4):
17389
- * validate → jobs (start) → jobs/:id (poll) → jobs/:id/cancel. Autenticação Bearer (token do
17390
- * client_credentials do customer — `buildMyioIngestionAuth`).
17389
+ * validate → jobs (start) → jobs/:id (poll) → jobs/:id/cancel | jobs/:id/revert. Autenticação
17390
+ * Bearer com o escopo `telemetry.import` (token do client_credentials — `buildMyioIngestionAuth`).
17391
+ *
17392
+ * Mensagens de erro seguem a resposta do Ingestion de 03/11/2026
17393
+ * (`RESPOSTA-IMPORTACAO-PLANILHA-TELEMETRIA-2026-11-03.md` §4).
17391
17394
  */
17392
17395
 
17393
17396
  interface TelemetryImportApiConfig {
17394
17397
  /** Base da API do Ingestion, ex.: https://api.data.apps.myio-bas.com/api/v1 */
17395
17398
  baseUrl: string;
17399
+ /** Token reaproveitado (o /auth aceita só 5 pedidos a cada 15 min por client) */
17396
17400
  getToken: () => Promise<string>;
17401
+ /**
17402
+ * Token novo, ignorando o cache — usado UMA vez após 401, ou 403 de escopo (um token emitido
17403
+ * antes de o client ganhar `telemetry.import` não carrega o escopo). Sem ele, não há retry.
17404
+ */
17405
+ refreshToken?: () => Promise<string>;
17397
17406
  fetchImpl?: typeof fetch;
17398
17407
  }
17399
17408
  interface ImportPreview {
@@ -17421,7 +17430,8 @@ type ValidateResult = {
17421
17430
  reason: string;
17422
17431
  }>;
17423
17432
  };
17424
- type ImportJobStatus = 'queued' | 'executing' | 'completed' | 'failed' | 'cancelled' | 'reverted' | string;
17433
+ /** `reverting` é transitório (durante o revert): não é terminal. */
17434
+ type ImportJobStatus = 'queued' | 'executing' | 'completed' | 'failed' | 'cancelled' | 'reverting' | 'reverted' | string;
17425
17435
  interface ImportJob {
17426
17436
  jobId?: string;
17427
17437
  status: ImportJobStatus;
@@ -17457,6 +17467,8 @@ interface TelemetryImportApi {
17457
17467
  }>;
17458
17468
  getJob(jobId: string): Promise<ImportJob>;
17459
17469
  cancelJob(jobId: string): Promise<ImportJob | null>;
17470
+ /** Desfaz uma importação `completed`/`failed`: remove as horas e devolve as leituras apagadas */
17471
+ revertJob(jobId: string): Promise<ImportJob | null>;
17460
17472
  }
17461
17473
  declare function createTelemetryImportApi(cfg: TelemetryImportApiConfig): TelemetryImportApi;
17462
17474
 
@@ -17482,7 +17494,7 @@ interface OpenTelemetryImportModalParams {
17482
17494
  customerName?: string;
17483
17495
  /** Usuário MyIO: mostra detalhes técnicos dos erros */
17484
17496
  showTechnicalDetails?: boolean;
17485
- /** Intervalo do acompanhamento do job (ms). Default 5000. */
17497
+ /** Intervalo do acompanhamento do job (ms). Default 2500 (o Ingestion sugere 2–3 s). */
17486
17498
  pollMs?: number;
17487
17499
  /** Chamado quando a importação termina com sucesso */
17488
17500
  onCompleted?: (job: ImportJob) => void;
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  // package.json
11
11
  var package_default = {
12
12
  name: "myio-js-library",
13
- version: "0.1.573",
13
+ version: "0.1.574",
14
14
  description: "A clean, standalone JS SDK for MYIO projects",
15
15
  license: "MIT",
16
16
  repository: "github:gh-myio/myio-js-library",
@@ -112695,27 +112695,74 @@ var ImportApiError = class extends Error {
112695
112695
  this.name = "ImportApiError";
112696
112696
  }
112697
112697
  };
112698
+ var CONFLICT_TEXT = {
112699
+ VALIDATION_EXPIRED: "A valida\xE7\xE3o expirou (vale 30 minutos). Valide a planilha de novo.",
112700
+ REAL_READINGS_PRESENT: "H\xE1 leituras reais nessas horas. Confirme a substitui\xE7\xE3o para importar.",
112701
+ NOT_CANCELLABLE: 'A importa\xE7\xE3o j\xE1 terminou e n\xE3o pode ser cancelada. Use "Desfazer importa\xE7\xE3o".',
112702
+ NOT_REVERTABLE: "Esta importa\xE7\xE3o n\xE3o pode ser desfeita.",
112703
+ GATEWAY_BUSY: "A central est\xE1 ocupada com outra importa\xE7\xE3o. Tente em instantes."
112704
+ };
112705
+ function importErrorMessage(status, path, body) {
112706
+ const code = String(body?.error || "");
112707
+ const apiMsg = String(body?.message || "");
112708
+ switch (status) {
112709
+ case 400:
112710
+ return apiMsg ? `Pedido recusado pela API: ${apiMsg}` : "Pedido recusado pela API (400).";
112711
+ case 401:
112712
+ return "Sess\xE3o da importa\xE7\xE3o expirada. Feche esta janela e abra a importa\xE7\xE3o de novo.";
112713
+ case 403:
112714
+ 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.";
112715
+ case 404:
112716
+ return path === "/validate" ? "A importa\xE7\xE3o ainda n\xE3o est\xE1 dispon\xEDvel neste ambiente." : "Importa\xE7\xE3o n\xE3o encontrada.";
112717
+ case 409:
112718
+ return CONFLICT_TEXT[code] || apiMsg || "Opera\xE7\xE3o n\xE3o permitida no estado atual da importa\xE7\xE3o.";
112719
+ case 413:
112720
+ return "Planilha grande demais para uma importa\xE7\xE3o. Divida em partes de at\xE9 5.000 linhas.";
112721
+ case 429:
112722
+ return "Muitas tentativas seguidas. Aguarde um minuto e tente de novo.";
112723
+ default:
112724
+ return `Falha na API de importa\xE7\xE3o (${status}).`;
112725
+ }
112726
+ }
112698
112727
  function createTelemetryImportApi(cfg) {
112699
112728
  const base = String(cfg.baseUrl || "").replace(/\/+$/, "");
112700
112729
  const doFetch = cfg.fetchImpl ?? fetch.bind(window);
112701
- const call = async (method, path, body, accept422 = false) => {
112702
- const token = await cfg.getToken();
112703
- const res = await doFetch(`${base}/import${path}`, {
112704
- method,
112705
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
112706
- body: body === void 0 ? void 0 : JSON.stringify(body)
112707
- });
112730
+ const send = async (method, path, token, body) => {
112731
+ try {
112732
+ return await doFetch(`${base}/import${path}`, {
112733
+ method,
112734
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
112735
+ body: body === void 0 ? void 0 : JSON.stringify(body)
112736
+ });
112737
+ } catch (err) {
112738
+ throw new ImportApiError(
112739
+ "N\xE3o foi poss\xEDvel falar com a API de importa\xE7\xE3o. Verifique a conex\xE3o e tente de novo.",
112740
+ 0,
112741
+ `${method} /import${path} \u2192 ${String(err?.message || err)}`
112742
+ );
112743
+ }
112744
+ };
112745
+ const readJson = async (res) => {
112708
112746
  const text2 = await res.text().catch(() => "");
112709
- let data = null;
112710
112747
  try {
112711
- data = text2 ? JSON.parse(text2) : null;
112748
+ return { text: text2, data: text2 ? JSON.parse(text2) : null };
112712
112749
  } catch {
112713
- data = null;
112750
+ return { text: text2, data: null };
112714
112751
  }
112752
+ };
112753
+ const call = async (method, path, body, accept422 = false) => {
112754
+ let res = await send(method, path, await cfg.getToken(), body);
112755
+ let parsed = await readJson(res);
112756
+ const scopeMissing = res.status === 403 && /scope/i.test(String(parsed.data?.message || ""));
112757
+ if ((res.status === 401 || scopeMissing) && cfg.refreshToken) {
112758
+ res = await send(method, path, await cfg.refreshToken(), body);
112759
+ parsed = await readJson(res);
112760
+ }
112761
+ const data = parsed.data;
112715
112762
  if (res.ok || accept422 && res.status === 422) return { status: res.status, data: data?.data ?? data };
112763
+ const msg = importErrorMessage(res.status, path.startsWith("/jobs") ? "/jobs" : path, data);
112716
112764
  const apiMsg = data?.message || data?.error || "";
112717
- const msg = res.status === 404 ? "A importa\xE7\xE3o ainda n\xE3o est\xE1 dispon\xEDvel neste ambiente." : res.status === 401 || res.status === 403 ? "Sem permiss\xE3o para importar telemetria (credencial sem o escopo telemetry.import)." : res.status === 409 ? apiMsg || "Opera\xE7\xE3o n\xE3o permitida no estado atual da importa\xE7\xE3o." : `Falha na API de importa\xE7\xE3o (${res.status}).`;
112718
- throw new ImportApiError(msg, res.status, `${method} /import${path} \u2192 ${res.status} ${String(apiMsg || text2).slice(0, 200)}`);
112765
+ throw new ImportApiError(msg, res.status, `${method} /import${path} \u2192 ${res.status} ${String(apiMsg || parsed.text).slice(0, 200)}`);
112719
112766
  };
112720
112767
  return {
112721
112768
  async validate(body) {
@@ -112736,6 +112783,10 @@ function createTelemetryImportApi(cfg) {
112736
112783
  async cancelJob(jobId) {
112737
112784
  const { data } = await call("POST", `/jobs/${encodeURIComponent(jobId)}/cancel`);
112738
112785
  return data ? { jobId, ...data } : null;
112786
+ },
112787
+ async revertJob(jobId) {
112788
+ const { data } = await call("POST", `/jobs/${encodeURIComponent(jobId)}/revert`);
112789
+ return data ? { jobId, ...data } : null;
112739
112790
  }
112740
112791
  };
112741
112792
  }
@@ -112757,8 +112808,16 @@ var JOB_STATUS_TEXT = {
112757
112808
  completed: "Conclu\xEDda",
112758
112809
  failed: "Falhou",
112759
112810
  cancelled: "Cancelada",
112760
- reverted: "Revertida"
112811
+ reverting: "Desfazendo",
112812
+ reverted: "Desfeita"
112761
112813
  };
112814
+ function fmtSaoPaulo(iso) {
112815
+ const t = new Date(String(iso ?? "")).getTime();
112816
+ if (!Number.isFinite(t)) return "";
112817
+ const d = new Date(t - 3 * 3600 * 1e3);
112818
+ const p = (n) => String(n).padStart(2, "0");
112819
+ return `${p(d.getUTCDate())}/${p(d.getUTCMonth() + 1)}/${d.getUTCFullYear()} ${p(d.getUTCHours())}:00`;
112820
+ }
112762
112821
  var STYLE_ID14 = "myio-tlmimport-styles";
112763
112822
  function esc8(v) {
112764
112823
  return String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -112861,6 +112920,8 @@ function openTelemetryImportModal(params) {
112861
112920
  apiError: "",
112862
112921
  apiDetail: "",
112863
112922
  confirmReal: false,
112923
+ /** "Desfazer importação" pede um segundo clique antes de chamar o revert */
112924
+ confirmRevert: false,
112864
112925
  job: null
112865
112926
  };
112866
112927
  let pollTimer = null;
@@ -113009,8 +113070,10 @@ function openTelemetryImportModal(params) {
113009
113070
  }
113010
113071
  const p = v.preview || {};
113011
113072
  const real = Number(p.existingRealReadings || 0);
113012
- const period = typeof p.period === "string" ? p.period : p.period ? `${p.period.start || ""} \u2192 ${p.period.end || ""}` : "\u2014";
113073
+ const period = typeof p.period === "string" ? p.period : p.period ? `${fmtSaoPaulo(p.period.start)} at\xE9 a hora de ${fmtSaoPaulo(p.period.end)}` : "\u2014";
113013
113074
  const devices = Array.isArray(p.devices) ? p.devices.length : p.devices;
113075
+ 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
113076
+ ficar\xE3o com reativa 0. A reativa original fica guardada e volta se a importa\xE7\xE3o for desfeita.</div>` : "";
113014
113077
  return `
113015
113078
  <div class="tlmi-banner ok">${s.model === "accumulated" ? "Valores v\xE1lidos" : "Planilha v\xE1lida"}. Confira o resumo antes de importar.</div>
113016
113079
  ${s.model === "accumulated" ? '<div class="tlmi-banner warn">Os valores por hora s\xE3o estimados a partir do total informado.</div>' : ""}
@@ -113020,7 +113083,8 @@ function openTelemetryImportModal(params) {
113020
113083
  <div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
113021
113084
  <div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
113022
113085
  </div>
113023
- <p class="tlmi-muted">Per\xEDodo: ${esc8(period)}</p>
113086
+ <p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${esc8(period)}</p>
113087
+ ${reactiveWarn}
113024
113088
  ${real > 0 ? `<div class="tlmi-banner warn"><strong>${fmtNum(real)} leitura(s) reais do medidor</strong> ser\xE3o substitu\xEDdas pelos valores da planilha.
113025
113089
  <label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
113026
113090
  Confirmo a substitui\xE7\xE3o das leituras reais.</label></div>` : ""}
@@ -113034,12 +113098,21 @@ function openTelemetryImportModal(params) {
113034
113098
  const terminal = TERMINAL_JOB_STATUSES.includes(j.status);
113035
113099
  let banner = "";
113036
113100
  if (j.status === "completed") {
113037
- 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.</div>';
113101
+ 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.
113102
+ <div class="tlmi-muted" style="margin-top:4px">Dispositivos manuais continuam aparecendo sem comunica\xE7\xE3o no status:
113103
+ o status conta s\xF3 leitura medida. Os totais e os cards usam os dados importados.</div></div>`;
113038
113104
  } else if (j.status === "failed") {
113039
113105
  banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc8(j.error)}` : "."}</div>`;
113040
113106
  } else if (j.status === "cancelled") {
113041
113107
  banner = '<div class="tlmi-banner warn">Importa\xE7\xE3o cancelada. As leituras anteriores foram mantidas.</div>';
113108
+ } else if (j.status === "reverted") {
113109
+ banner = '<div class="tlmi-banner ok">Importa\xE7\xE3o desfeita. As leituras anteriores foram restauradas.</div>';
113042
113110
  }
113111
+ const canRevert = j.status === "completed" || j.status === "failed";
113112
+ const revert = canRevert ? `<div style="margin-top:12px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
113113
+ <button class="tlmi-btn" type="button" data-action="revert" ${s.busy ? "disabled" : ""}>${s.confirmRevert ? "Confirmar: desfazer importa\xE7\xE3o" : "Desfazer importa\xE7\xE3o"}</button>
113114
+ <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>
113115
+ </div>` : "";
113043
113116
  return `
113044
113117
  <div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc8(statusText)}</span></h3>
113045
113118
  <div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
@@ -113049,8 +113122,9 @@ function openTelemetryImportModal(params) {
113049
113122
  <div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
113050
113123
  </div>
113051
113124
  ${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc8(j.phase)}</p>` : ""}
113052
- ${!terminal ? `<div style="margin-top:12px"><button class="tlmi-btn" type="button" data-action="cancel" ${s.busy ? "disabled" : ""}>Cancelar importa\xE7\xE3o</button>
113125
+ ${!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>
113053
113126
  <span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
113127
+ ${revert}
113054
113128
  </div>
113055
113129
  ${banner}
113056
113130
  ${apiErrorBanner()}`;
@@ -113223,7 +113297,7 @@ function openTelemetryImportModal(params) {
113223
113297
  render3();
113224
113298
  }
113225
113299
  }
113226
- function schedulePoll(delay = params.pollMs ?? 5e3) {
113300
+ function schedulePoll(delay = params.pollMs ?? 2500) {
113227
113301
  if (closed || !s.job?.jobId) return;
113228
113302
  pollTimer = setTimeout(async () => {
113229
113303
  if (closed || !s.job?.jobId) return;
@@ -113251,11 +113325,34 @@ function openTelemetryImportModal(params) {
113251
113325
  render3();
113252
113326
  }
113253
113327
  }
113328
+ async function revertJob() {
113329
+ if (!s.job?.jobId || s.busy) return;
113330
+ if (!s.confirmRevert) {
113331
+ s.confirmRevert = true;
113332
+ render3();
113333
+ return;
113334
+ }
113335
+ s.busy = true;
113336
+ s.confirmRevert = false;
113337
+ s.apiError = "";
113338
+ render3();
113339
+ try {
113340
+ const j = await api.revertJob(s.job.jobId);
113341
+ if (j?.status) s.job = { ...s.job, ...j };
113342
+ if (s.job && !TERMINAL_JOB_STATUSES.includes(s.job.status)) schedulePoll(0);
113343
+ } catch (err) {
113344
+ setError(err);
113345
+ } finally {
113346
+ s.busy = false;
113347
+ render3();
113348
+ }
113349
+ }
113254
113350
  root.addEventListener("click", (e) => {
113255
113351
  const el2 = e.target.closest("[data-action]");
113256
113352
  if (!el2) return;
113257
113353
  if (el2.dataset.action === "template") downloadTemplate();
113258
113354
  if (el2.dataset.action === "cancel") void cancelJob();
113355
+ if (el2.dataset.action === "revert") void revertJob();
113259
113356
  if (el2.dataset.action === "use-form") {
113260
113357
  resetAccumulatedSource();
113261
113358
  recomputeAccumulated();