myio-js-library 0.1.569 → 0.1.571

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
@@ -890,6 +890,7 @@ __export(src_exports, {
890
890
  resolveClassification: () => resolveClassification,
891
891
  resolveGoalAmount: () => resolveGoalAmount,
892
892
  resolveGroup: () => resolveGroup,
893
+ resolveManualDeviceName: () => resolveManualDeviceName,
893
894
  resolveMoneyRollout: () => resolveMoneyRollout,
894
895
  resolveMoneyRowValues: () => resolveMoneyRowValues,
895
896
  resolvePercentDecimals: () => resolvePercentDecimals,
@@ -953,7 +954,7 @@ module.exports = __toCommonJS(src_exports);
953
954
  // package.json
954
955
  var package_default = {
955
956
  name: "myio-js-library",
956
- version: "0.1.569",
957
+ version: "0.1.571",
957
958
  description: "A clean, standalone JS SDK for MYIO projects",
958
959
  license: "MIT",
959
960
  repository: "github:gh-myio/myio-js-library",
@@ -36698,8 +36699,9 @@ function renderTemperatureBarsPng(opts) {
36698
36699
  ctx.fillStyle = "#6b7280";
36699
36700
  ctx.font = "20px Helvetica, Arial, sans-serif";
36700
36701
  ctx.textBaseline = "middle";
36701
- const scale = `Escala ${fmt2(lo)}\u2013${fmt2(hi)} \xB0C`;
36702
- ctx.fillText(ideal ? `${scale} \xB7 faixa ideal ${fmt2(ideal.min)}\u2013${fmt2(ideal.max)} \xB0C` : scale, 16, 26);
36702
+ const unit = opts.unit || "\xB0C";
36703
+ const scale = `Escala ${fmt2(lo)}\u2013${fmt2(hi)} ${unit}`;
36704
+ ctx.fillText(ideal ? `${scale} \xB7 faixa ideal ${fmt2(ideal.min)}\u2013${fmt2(ideal.max)} ${unit}` : scale, 16, 26);
36703
36705
  opts.items.forEach((item, i) => {
36704
36706
  const y = TOP + i * ROW;
36705
36707
  const cy = y + ROW / 2;
@@ -36747,7 +36749,8 @@ var DOMAIN_CONFIG = {
36747
36749
  label: "Consumo (kWh)",
36748
36750
  formatter: (v) => fmtPt(v),
36749
36751
  summaryType: "total",
36750
- summaryLabel: "Total"
36752
+ summaryLabel: "Total",
36753
+ measureLabel: "Consumo"
36751
36754
  },
36752
36755
  water: {
36753
36756
  endpoint: "water",
@@ -36755,7 +36758,8 @@ var DOMAIN_CONFIG = {
36755
36758
  label: "Consumo (m\xB3)",
36756
36759
  formatter: (v) => fmtPt(v),
36757
36760
  summaryType: "total",
36758
- summaryLabel: "Total"
36761
+ summaryLabel: "Total",
36762
+ measureLabel: "Consumo"
36759
36763
  },
36760
36764
  temperature: {
36761
36765
  endpoint: "temperature",
@@ -36763,7 +36767,23 @@ var DOMAIN_CONFIG = {
36763
36767
  label: "Temperatura (\xB0C)",
36764
36768
  formatter: (v) => fmtPt(v),
36765
36769
  summaryType: "average",
36766
- summaryLabel: "M\xE9dia"
36770
+ summaryLabel: "M\xE9dia",
36771
+ measureLabel: "Temperatura",
36772
+ rankingDayTitle: "Dias mais quentes (m\xE9dia do dia)",
36773
+ rankingHourTitle: "Horas mais quentes"
36774
+ },
36775
+ // Nível de tanque/caixa/cisterna — não existe no Ingestion; o chamador injeta um
36776
+ // `fetcher` que lê o timeseries do ThingsBoard (water_percentage × 100).
36777
+ water_level: {
36778
+ endpoint: "water_level",
36779
+ unit: "%",
36780
+ label: "N\xEDvel (%)",
36781
+ formatter: (v) => fmtPt(v),
36782
+ summaryType: "average",
36783
+ summaryLabel: "M\xE9dia",
36784
+ measureLabel: "N\xEDvel",
36785
+ rankingDayTitle: "Dias com maior n\xEDvel (m\xE9dia do dia)",
36786
+ rankingHourTitle: "Horas com maior n\xEDvel"
36767
36787
  }
36768
36788
  };
36769
36789
  var createDefaultEnergyFetcher = (params, getGranularity) => {
@@ -37335,12 +37355,12 @@ var DeviceReportModal = class {
37335
37355
  kpis.push(
37336
37356
  {
37337
37357
  value: maxRow ? fmt2(maxRow.consumption) : "\u2014",
37338
- label: `${rowLabel} com Maior ${isTemperature ? "Temperatura" : "Consumo"} (${unit})`,
37358
+ label: `${rowLabel} com Maior ${this.domainConfig.measureLabel} (${unit})`,
37339
37359
  ...maxRow ? { sub: this.formatDate(maxRow.date) } : {}
37340
37360
  },
37341
37361
  {
37342
37362
  value: minRow ? fmt2(minRow.consumption) : "\u2014",
37343
- label: `${rowLabel} com Menor ${isTemperature ? "Temperatura" : "Consumo"} (${unit})`,
37363
+ label: `${rowLabel} com Menor ${this.domainConfig.measureLabel} (${unit})`,
37344
37364
  ...minRow ? { sub: this.formatDate(minRow.date) } : {}
37345
37365
  }
37346
37366
  );
@@ -37396,12 +37416,13 @@ var DeviceReportModal = class {
37396
37416
  <div style="position:absolute;top:2px;bottom:2px;left:0;width:${pos(r.consumption)};background:${color(r.consumption)};border-radius:4px;opacity:.85;"></div></div>` : `<span style="font-size:11px;color:var(--myio-text-muted,#9ca3af);">Sem leitura</span>`}
37397
37417
  <span style="text-align:right;font-variant-numeric:tabular-nums;font-weight:600;">${r ? this.domainConfig.formatter(r.consumption) : "\u2014"}</span>
37398
37418
  </div>`;
37399
- const title = isHourly ? `Horas mais quentes${ranked.length > TOP_HOURS ? ` (top ${TOP_HOURS})` : ""}` : "Dias mais quentes (m\xE9dia do dia)";
37419
+ const unit = this.domainConfig.unit;
37420
+ const title = isHourly ? `${this.domainConfig.rankingHourTitle}${ranked.length > TOP_HOURS ? ` (top ${TOP_HOURS})` : ""}` : this.domainConfig.rankingDayTitle;
37400
37421
  container.innerHTML = `
37401
37422
  <div style="border:1px solid var(--myio-border,#e5e7eb);border-radius:10px;padding:12px 14px;max-height:620px;overflow-y:auto;">
37402
37423
  <div style="font-weight:700;font-size:14px;margin-bottom:2px;">${title}</div>
37403
37424
  <div style="font-size:11px;color:var(--myio-text-muted,#6b7280);margin-bottom:10px;">
37404
- Escala ${this.domainConfig.formatter(lo)}\u2013${this.domainConfig.formatter(hi)} \xB0C${hasIdeal ? ` \xB7 <span style="color:#16a34a;">faixa ideal ${this.domainConfig.formatter(Number(ideal.min))}\u2013${this.domainConfig.formatter(Number(ideal.max))} \xB0C</span>` : ""}
37425
+ Escala ${this.domainConfig.formatter(lo)}\u2013${this.domainConfig.formatter(hi)} ${unit}${hasIdeal ? ` \xB7 <span style="color:#16a34a;">faixa ideal ${this.domainConfig.formatter(Number(ideal.min))}\u2013${this.domainConfig.formatter(Number(ideal.max))} ${unit}</span>` : ""}
37405
37426
  </div>
37406
37427
  ${shown.map((r) => line(this.formatDate(r.date), r)).join("")}
37407
37428
  ${noData.map((r) => line(this.formatDate(r.date), null)).join("")}
@@ -37614,9 +37635,10 @@ var DeviceReportModal = class {
37614
37635
  ...noData.map((r) => ({ label: this.formatDate(r.date), value: null }))
37615
37636
  ],
37616
37637
  ideal: this.params.temperatureIdealRange ?? null,
37617
- accent: this.resolveAccentHex()
37638
+ accent: this.resolveAccentHex(),
37639
+ unit: this.domainConfig.unit
37618
37640
  });
37619
- const title = isHourly ? `Horas mais quentes${ranked.length > 24 ? " (top 24)" : ""}` : "Dias mais quentes (m\xE9dia do dia)";
37641
+ const title = isHourly ? `${this.domainConfig.rankingHourTitle}${ranked.length > 24 ? " (top 24)" : ""}` : this.domainConfig.rankingDayTitle;
37620
37642
  return png ? { ...png, title } : null;
37621
37643
  }
37622
37644
  const chartPng = await this.participationChart?.toPngDataUrl?.().catch(() => null);
@@ -112127,7 +112149,7 @@ async function openClearGcdrIdsModal(state6) {
112127
112149
  opacity:${disabled ? "0.5" : "1"};
112128
112150
  " ${disabled ? "disabled" : ""}>${label}</button>`;
112129
112151
  }
112130
- function progressHtml(phase, done, total) {
112152
+ function progressHtml2(phase, done, total) {
112131
112153
  const pct = total > 0 ? Math.round(done / total * 100) : 0;
112132
112154
  return `
112133
112155
  <div style="padding:8px 0;">
@@ -112183,7 +112205,7 @@ async function openClearGcdrIdsModal(state6) {
112183
112205
  ${tableHtml(assetToClear, GCDR_CLEAR_ASSET_KEYS)}
112184
112206
  ${devToClear.length + assetToClear.length === 0 ? '<div style="text-align:center; color:#6b7280; padding:16px 0; font-size:13px;">\u2705 Nenhum device ou asset possui essas chaves. Nada a limpar.</div>' : ""}`;
112185
112207
  }
112186
- renderShell(progressHtml("Buscando devices e assets\u2026", 0, 0), "");
112208
+ renderShell(progressHtml2("Buscando devices e assets\u2026", 0, 0), "");
112187
112209
  try {
112188
112210
  const [devicesResp, assetsResp] = await Promise.all([
112189
112211
  tbFetch(state6, `/api/customer/${customerId}/devices?pageSize=1000&page=0`),
@@ -112212,7 +112234,7 @@ async function openClearGcdrIdsModal(state6) {
112212
112234
  }));
112213
112235
  const done = deviceRows.length + assetRows.length;
112214
112236
  const bodyEl = overlay.querySelector("#gcdr-clear-body");
112215
- if (bodyEl) bodyEl.innerHTML = progressHtml(`Lendo SERVER_SCOPE (${entityType})\u2026`, done, total);
112237
+ if (bodyEl) bodyEl.innerHTML = progressHtml2(`Lendo SERVER_SCOPE (${entityType})\u2026`, done, total);
112216
112238
  }
112217
112239
  }
112218
112240
  const fetchDeviceAttrs = async (id) => {
@@ -112242,7 +112264,7 @@ async function openClearGcdrIdsModal(state6) {
112242
112264
  overlay.querySelector("#gcdr-clear-apply")?.addEventListener("click", async () => {
112243
112265
  let done3 = 0;
112244
112266
  overlay.querySelector("#gcdr-clear-footer").innerHTML = "";
112245
- overlay.querySelector("#gcdr-clear-body").innerHTML = progressHtml("Removendo atributos GCDR\u2026", 0, totalToClear);
112267
+ overlay.querySelector("#gcdr-clear-body").innerHTML = progressHtml2("Removendo atributos GCDR\u2026", 0, totalToClear);
112246
112268
  async function execClear(rows, keys, entityType) {
112247
112269
  const results = [];
112248
112270
  const chunks = [];
@@ -112259,7 +112281,7 @@ async function openClearGcdrIdsModal(state6) {
112259
112281
  }
112260
112282
  done3++;
112261
112283
  const progEl = overlay.querySelector("#gcdr-clear-body");
112262
- if (progEl) progEl.innerHTML = progressHtml("Removendo atributos GCDR\u2026", done3, totalToClear);
112284
+ if (progEl) progEl.innerHTML = progressHtml2("Removendo atributos GCDR\u2026", done3, totalToClear);
112263
112285
  }));
112264
112286
  }
112265
112287
  return results;
@@ -115246,7 +115268,7 @@ function splitImportableDevices(devices) {
115246
115268
  const missingKey = [];
115247
115269
  for (const d of devices || []) {
115248
115270
  const slave = Number(d?.slaveId);
115249
- if (d?.centralId && UUID_RE.test(String(d.centralId)) && Number.isInteger(slave) && slave >= 1 && slave <= 247) ok.push(d);
115271
+ if (d?.centralId && UUID_RE.test(String(d.centralId)) && Number.isInteger(slave) && slave >= 1) ok.push(d);
115250
115272
  else missingKey.push(d);
115251
115273
  }
115252
115274
  return { ok, missingKey };
@@ -115381,7 +115403,7 @@ function rowsFromTable(domain, table) {
115381
115403
  }
115382
115404
  const lineErrors = [];
115383
115405
  if (!UUID_RE.test(gw)) lineErrors.push("gateway_id inv\xE1lido");
115384
- if (!Number.isInteger(slave) || slave < 1 || slave > 247) lineErrors.push("slave_id deve ser inteiro de 1 a 247");
115406
+ if (!Number.isInteger(slave) || slave < 1) lineErrors.push("slave_id deve ser inteiro maior ou igual a 1");
115385
115407
  if (!date) lineErrors.push("data inv\xE1lida (use AAAA-MM-DD)");
115386
115408
  if (!hour) lineErrors.push("hora inv\xE1lida (use HH:00)");
115387
115409
  if (Number.isNaN(value) || value < 0) lineErrors.push("valor deve ser n\xFAmero \u2265 0");
@@ -115942,20 +115964,12 @@ function nextManualSeq(domain, sigla, existingNames) {
115942
115964
  }, 0);
115943
115965
  return max + 1;
115944
115966
  }
115945
- async function createManualDevice(params) {
115946
- const domain = params.domain;
115947
- const profile = MANUAL_DEVICE_PROFILES[domain];
115948
- if (!profile) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
115949
- const label = String(params.label || "").trim();
115950
- const identifier = String(params.identifier || "").trim();
115951
- if (!label) throw new ManualDeviceError("Informe a etiqueta.");
115952
- if (!identifier) throw new ManualDeviceError("Informe o identificador.");
115953
- if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
115967
+ async function buildTbApi(params) {
115954
115968
  const base = params.baseUrl ?? "";
115955
115969
  const doFetch = params.fetchImpl ?? fetch.bind(window);
115956
115970
  const tokenValue = typeof params.token === "function" ? await params.token() : params.token;
115957
115971
  const headers = { "X-Authorization": `Bearer ${tokenValue}`, "Content-Type": "application/json" };
115958
- const api = async (method, path, body, okStatuses = []) => {
115972
+ return async (method, path, body, okStatuses = []) => {
115959
115973
  const res = await doFetch(`${base}${path}`, {
115960
115974
  method,
115961
115975
  headers,
@@ -115968,7 +115982,9 @@ async function createManualDevice(params) {
115968
115982
  const text2 = await res.text().catch(() => "");
115969
115983
  return text2 ? JSON.parse(text2) : null;
115970
115984
  };
115971
- const cid = encodeURIComponent(params.customerId);
115985
+ }
115986
+ async function findManualAsset(api, customerId) {
115987
+ const cid = encodeURIComponent(customerId);
115972
115988
  const assets = await api("GET", `/api/customer/${cid}/assets?pageSize=100&page=0&textSearch=MANUAIS`);
115973
115989
  const asset = (assets?.data || []).find(
115974
115990
  (a) => String(a?.name || "").toUpperCase().endsWith(MANUAL_ASSET_SUFFIX)
@@ -115986,12 +116002,45 @@ async function createManualDevice(params) {
115986
116002
  `n\xE3o foi poss\xEDvel extrair a sigla de "${asset.name}"`
115987
116003
  );
115988
116004
  }
116005
+ return { asset, sigla };
116006
+ }
116007
+ async function existingManualNames(api, customerId, sigla) {
115989
116008
  const existing = await api(
115990
116009
  "GET",
115991
- `/api/customer/${cid}/devices?pageSize=1000&page=0&textSearch=${encodeURIComponent(`${sigla}_LOJA_`)}`
116010
+ `/api/customer/${encodeURIComponent(customerId)}/devices?pageSize=1000&page=0&textSearch=${encodeURIComponent(`${sigla}_LOJA_`)}`
115992
116011
  );
115993
- const existingNames = (existing?.data || []).map((d) => String(d?.name || ""));
115994
- let seq = nextManualSeq(domain, sigla, existingNames);
116012
+ return (existing?.data || []).map((d) => String(d?.name || ""));
116013
+ }
116014
+ async function resolveManualDeviceName(params) {
116015
+ const profile = MANUAL_DEVICE_PROFILES[params.domain];
116016
+ if (!profile) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${params.domain}`);
116017
+ if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
116018
+ const api = await buildTbApi(params);
116019
+ const { asset, sigla } = await findManualAsset(api, params.customerId);
116020
+ const seq = nextManualSeq(params.domain, sigla, await existingManualNames(api, params.customerId, sigla));
116021
+ return {
116022
+ name: manualDeviceName(params.domain, sigla, seq),
116023
+ sigla,
116024
+ seq,
116025
+ assetId: asset.id.id,
116026
+ assetName: asset.name,
116027
+ deviceProfile: profile
116028
+ };
116029
+ }
116030
+ async function createManualDevice(params) {
116031
+ const domain = params.domain;
116032
+ const profile = MANUAL_DEVICE_PROFILES[domain];
116033
+ if (!profile) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
116034
+ const label = String(params.label || "").trim();
116035
+ const identifier = String(params.identifier || "").trim();
116036
+ if (!label) throw new ManualDeviceError("Informe a etiqueta.");
116037
+ if (!identifier) throw new ManualDeviceError("Informe o identificador.");
116038
+ if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
116039
+ const api = await buildTbApi(params);
116040
+ const cid = encodeURIComponent(params.customerId);
116041
+ const { asset, sigla } = await findManualAsset(api, params.customerId);
116042
+ const fixedName = String(params.name || "").trim();
116043
+ let seq = fixedName ? 0 : nextManualSeq(domain, sigla, await existingManualNames(api, params.customerId, sigla));
115995
116044
  let deviceProfileId;
115996
116045
  try {
115997
116046
  const profiles = await api("GET", `/api/deviceProfileInfos?pageSize=50&page=0&textSearch=${encodeURIComponent(profile)}`);
@@ -115999,7 +116048,7 @@ async function createManualDevice(params) {
115999
116048
  if (p?.id?.id) deviceProfileId = { id: p.id.id, entityType: "DEVICE_PROFILE" };
116000
116049
  } catch {
116001
116050
  }
116002
- let name = manualDeviceName(domain, sigla, seq);
116051
+ let name = fixedName || manualDeviceName(domain, sigla, seq);
116003
116052
  let created = null;
116004
116053
  for (let attempt = 0; ; attempt++) {
116005
116054
  try {
@@ -116012,6 +116061,9 @@ async function createManualDevice(params) {
116012
116061
  break;
116013
116062
  } catch (err) {
116014
116063
  const dup = /already exists|já existe/i.test(err?.detail || "");
116064
+ if (fixedName && dup) {
116065
+ throw new ManualDeviceError(`J\xE1 existe um dispositivo chamado ${fixedName} no ThingsBoard.`, err?.detail);
116066
+ }
116015
116067
  if (!dup || attempt >= 4) throw err;
116016
116068
  seq += 1;
116017
116069
  name = manualDeviceName(domain, sigla, seq);
@@ -116034,6 +116086,7 @@ async function createManualDevice(params) {
116034
116086
  typeGroup: "COMMON"
116035
116087
  });
116036
116088
  await api("POST", `/api/plugins/telemetry/DEVICE/${deviceId}/attributes/SERVER_SCOPE`, {
116089
+ ...params.extraAttributes || {},
116037
116090
  deviceProfile: profile,
116038
116091
  identifier
116039
116092
  });
@@ -116087,6 +116140,18 @@ function injectStyles15() {
116087
116140
  border: 1px dashed #e5e7eb; border-radius: 6px; padding: 8px 10px; line-height: 1.6;
116088
116141
  }
116089
116142
  .myio-manualdev__tech code { font-size: 11.5px; color: #374151; }
116143
+ .myio-manualdev__summary { width: 100%; border-collapse: collapse; font-size: 13px; }
116144
+ .myio-manualdev__summary th { text-align: left; font-weight: 500; color: #6b7280; padding: 4px 8px 4px 0; width: 42%; vertical-align: top; }
116145
+ .myio-manualdev__summary td { color: #111827; padding: 4px 0; word-break: break-word; }
116146
+ .myio-manualdev__steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
116147
+ .myio-manualdev__step { display: grid; grid-template-columns: 22px 92px 1fr; gap: 8px; align-items: start; font-size: 13px; }
116148
+ .myio-manualdev__step-sys { font-weight: 600; color: #3e1a7d; }
116149
+ .myio-manualdev__step-msg { display: block; font-size: 11.5px; color: #6b7280; word-break: break-word; }
116150
+ .myio-manualdev__step[data-status="error"] .myio-manualdev__step-msg { color: #991b1b; }
116151
+ .myio-manualdev__step[data-status="warn"] .myio-manualdev__step-msg { color: #92400e; }
116152
+ .myio-manualdev__note { margin: 0; font-size: 12.5px; border-radius: 6px; padding: 8px 10px; }
116153
+ .myio-manualdev__note--warn { color: #92400e; background: #fef3c7; }
116154
+ .myio-manualdev__note--block { color: #991b1b; background: #fee2e2; }
116090
116155
  `;
116091
116156
  document.head.appendChild(style);
116092
116157
  }
@@ -116124,10 +116189,52 @@ function successHtml(domain, r, tech) {
116124
116189
  </div>` : ""}
116125
116190
  </div>`;
116126
116191
  }
116192
+ var STEP_ICON = {
116193
+ pending: "\u25CB",
116194
+ running: "\u23F3",
116195
+ ok: "\u2705",
116196
+ warn: "\u26A0\uFE0F",
116197
+ error: "\u274C",
116198
+ skipped: "\u23ED\uFE0F",
116199
+ rolledback: "\u21A9\uFE0F"
116200
+ };
116201
+ function stepsHtml(steps) {
116202
+ return `<ol class="myio-manualdev__steps">${steps.map(
116203
+ (s) => `<li class="myio-manualdev__step" data-status="${escapeHtml14(s.status)}">
116204
+ <span aria-hidden="true">${STEP_ICON[s.status] || "\u25CB"}</span>
116205
+ <span class="myio-manualdev__step-sys">${escapeHtml14(s.system)}</span>
116206
+ <span>${escapeHtml14(s.title)}${s.message ? `<small class="myio-manualdev__step-msg">${escapeHtml14(s.message)}</small>` : ""}</span>
116207
+ </li>`
116208
+ ).join("")}</ol>`;
116209
+ }
116210
+ function notesHtml(plan) {
116211
+ const block = (plan.blockers || []).map((b) => `<p class="myio-manualdev__note myio-manualdev__note--block" role="alert">\u26D4 ${escapeHtml14(b)}</p>`);
116212
+ const warn = (plan.warnings || []).map((w) => `<p class="myio-manualdev__note myio-manualdev__note--warn">\u26A0\uFE0F ${escapeHtml14(w)}</p>`);
116213
+ return [...block, ...warn].join("");
116214
+ }
116215
+ function planHtml(plan) {
116216
+ return `
116217
+ <div class="myio-manualdev">
116218
+ <p class="myio-manualdev__hint">Revise o que ser\xE1 criado. Nada foi gravado ainda.</p>
116219
+ <table class="myio-manualdev__summary"><tbody>${plan.summary.map((r) => `<tr><th>${escapeHtml14(r.label)}</th><td>${escapeHtml14(r.value)}</td></tr>`).join("")}</tbody></table>
116220
+ ${stepsHtml(plan.steps)}
116221
+ ${notesHtml(plan)}
116222
+ </div>`;
116223
+ }
116224
+ function progressHtml(steps, message, ok) {
116225
+ return `
116226
+ <div class="myio-manualdev">
116227
+ ${ok === void 0 ? '<p class="myio-manualdev__hint">Criando nos sistemas\u2026 n\xE3o feche esta janela.</p>' : `<p class="myio-manualdev__note ${ok ? "myio-manualdev__note--warn" : "myio-manualdev__note--block"}" role="status">${escapeHtml14(
116228
+ message || (ok ? "Conclu\xEDdo com avisos." : "N\xE3o foi poss\xEDvel concluir.")
116229
+ )}</p>`}
116230
+ ${stepsHtml(steps)}
116231
+ </div>`;
116232
+ }
116127
116233
  function openManualDeviceModal(params) {
116128
116234
  const domain = params.domain;
116129
116235
  if (!MANUAL_DEVICE_PROFILES[domain]) throw new Error(`[openManualDeviceModal] dom\xEDnio inv\xE1lido: ${domain}`);
116130
116236
  injectStyles15();
116237
+ if (params.provisioner) return openProvisionedModal(params, params.provisioner);
116131
116238
  const values = { label: "", identifier: "" };
116132
116239
  let busy = false;
116133
116240
  let created = null;
@@ -116197,6 +116304,113 @@ function openManualDeviceModal(params) {
116197
116304
  }
116198
116305
  return modal;
116199
116306
  }
116307
+ function openProvisionedModal(params, provisioner) {
116308
+ const domain = params.domain;
116309
+ const values = { label: "", identifier: "" };
116310
+ let phase = "form";
116311
+ let plan = null;
116312
+ let outcome = null;
116313
+ const modal = openStandardModal({
116314
+ title: DOMAIN_TEXT2[domain].title,
116315
+ icon: DOMAIN_TEXT2[domain].icon,
116316
+ bodyHtml: formHtml(domain, values),
116317
+ width: 560,
116318
+ container: params.container,
116319
+ buttons: [
116320
+ { label: "Cancelar", value: "cancel", variant: "secondary" },
116321
+ { label: "Voltar", value: "back", variant: "secondary", closeOnClick: false },
116322
+ { label: "Revisar", value: "next", variant: "primary", closeOnClick: false }
116323
+ ],
116324
+ onButton: (v) => {
116325
+ if (v === "back" && phase === "plan") return showForm();
116326
+ if (v !== "next") return;
116327
+ if (phase === "form") return void review();
116328
+ if (phase === "plan") return void apply();
116329
+ if (phase === "done") {
116330
+ modal.close();
116331
+ if (outcome?.result) params.onCreated?.(outcome.result);
116332
+ }
116333
+ }
116334
+ });
116335
+ modal.setButton("back", { hidden: true });
116336
+ const bindForm = (focus = true) => {
116337
+ const form = modal.getBodyEl().querySelector("form");
116338
+ form?.addEventListener("submit", (e) => {
116339
+ e.preventDefault();
116340
+ void review();
116341
+ });
116342
+ if (focus) form?.querySelector('input[name="label"]')?.focus();
116343
+ };
116344
+ bindForm();
116345
+ function showForm(error, detail) {
116346
+ phase = "form";
116347
+ modal.setBodyHtml(formHtml(domain, values, error, detail));
116348
+ bindForm();
116349
+ modal.setButton("back", { hidden: true });
116350
+ modal.setButton("cancel", { disabled: false, hidden: false });
116351
+ modal.setButton("next", { disabled: false, label: "Revisar" });
116352
+ }
116353
+ const errorText = (err) => {
116354
+ const msg = err instanceof ManualDeviceError ? err.message : "N\xE3o foi poss\xEDvel montar o plano.";
116355
+ const detail = params.showTechnicalDetails ? (err instanceof ManualDeviceError ? err.detail : String(err?.message || err)) || void 0 : void 0;
116356
+ return { msg, detail };
116357
+ };
116358
+ async function review() {
116359
+ if (phase !== "form") return;
116360
+ const body = modal.getBodyEl();
116361
+ values.label = (body.querySelector('input[name="label"]')?.value || "").trim();
116362
+ values.identifier = (body.querySelector('input[name="identifier"]')?.value || "").trim();
116363
+ const missing = !values.label ? "label" : !values.identifier ? "identifier" : null;
116364
+ if (missing) {
116365
+ showForm(missing === "label" ? "Informe a etiqueta." : "Informe o identificador.");
116366
+ const input = modal.getBodyEl().querySelector(`input[name="${missing}"]`);
116367
+ input?.setAttribute("aria-invalid", "true");
116368
+ input?.focus();
116369
+ return;
116370
+ }
116371
+ phase = "planning";
116372
+ modal.setButton("next", { disabled: true, label: "Revisando\u2026" });
116373
+ body.querySelectorAll("input").forEach((i) => i.disabled = true);
116374
+ try {
116375
+ plan = await provisioner.plan({ domain, label: values.label, identifier: values.identifier });
116376
+ phase = "plan";
116377
+ modal.setBodyHtml(planHtml(plan));
116378
+ modal.setButton("back", { hidden: false, disabled: false });
116379
+ modal.setButton("next", { disabled: !!plan.blockers?.length, label: "Criar" });
116380
+ } catch (err) {
116381
+ const { msg, detail } = errorText(err);
116382
+ showForm(msg, detail);
116383
+ }
116384
+ }
116385
+ async function apply() {
116386
+ if (phase !== "plan" || !plan || plan.blockers?.length) return;
116387
+ phase = "applying";
116388
+ const steps = plan.steps.map((s) => ({ ...s }));
116389
+ modal.setBodyHtml(progressHtml(steps));
116390
+ modal.setButton("back", { hidden: true });
116391
+ modal.setButton("cancel", { hidden: true });
116392
+ modal.setButton("next", { disabled: true, label: "Criando\u2026" });
116393
+ const onStep = (step) => {
116394
+ const i = steps.findIndex((s) => s.key === step.key);
116395
+ if (i >= 0) steps[i] = { ...steps[i], ...step };
116396
+ else steps.push(step);
116397
+ modal.setBodyHtml(progressHtml(steps));
116398
+ };
116399
+ try {
116400
+ outcome = await provisioner.apply(plan, onStep);
116401
+ } catch (err) {
116402
+ outcome = { ok: false, steps, message: errorText(err).msg };
116403
+ }
116404
+ phase = "done";
116405
+ const finalSteps = outcome.steps?.length ? outcome.steps : steps;
116406
+ const clean = outcome.ok && finalSteps.every((s) => s.status === "ok");
116407
+ modal.setBodyHtml(
116408
+ clean && outcome.result ? successHtml(domain, outcome.result, !!params.showTechnicalDetails) + (params.showTechnicalDetails ? stepsHtml(finalSteps) : "") : progressHtml(finalSteps, outcome.message, outcome.ok)
116409
+ );
116410
+ modal.setButton("next", { disabled: false, label: outcome.ok ? "Concluir" : "Fechar" });
116411
+ }
116412
+ return modal;
116413
+ }
116200
116414
 
116201
116415
  // src/components/myio-gcdr-login/dom.ts
116202
116416
  function h2(doc, tag, attrs = {}, ...children) {
@@ -179086,6 +179300,7 @@ var version = package_default.version || "0.0.0";
179086
179300
  resolveClassification,
179087
179301
  resolveGoalAmount,
179088
179302
  resolveGroup,
179303
+ resolveManualDeviceName,
179089
179304
  resolveMoneyRollout,
179090
179305
  resolveMoneyRowValues,
179091
179306
  resolvePercentDecimals,