myio-js-library 0.1.586 → 0.1.588

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
@@ -300,6 +300,7 @@ __export(src_exports, {
300
300
  SIDEBAR_MENU_CSS_PREFIX: () => SIDEBAR_MENU_CSS_PREFIX,
301
301
  SOLENOID_CONTROL_CSS_PREFIX: () => SOLENOID_CONTROL_CSS_PREFIX,
302
302
  SOLENOID_IMAGES: () => SOLENOID_IMAGES2,
303
+ STANDARD_DEVICE_PROFILES: () => STANDARD_DEVICE_PROFILES,
303
304
  STATUS_COLORS: () => STATUS_COLORS,
304
305
  STATUS_FRESHNESS_MAX_HOURS: () => STATUS_FRESHNESS_MAX_HOURS,
305
306
  STATUS_FRESHNESS_MAX_MS: () => STATUS_FRESHNESS_MAX_MS,
@@ -793,6 +794,7 @@ __export(src_exports, {
793
794
  msToMinutes: () => msToMinutes,
794
795
  myioExportData: () => myioExportData,
795
796
  nextManualSeq: () => nextManualSeq,
797
+ nextStandardSeq: () => nextStandardSeq,
796
798
  nfdNormalizeAnnotationSearch: () => nfdNormalize,
797
799
  normalizeBudgetBlock: () => normalizeBudgetBlock,
798
800
  normalizeConnectionStatus: () => normalizeConnectionStatus,
@@ -924,6 +926,7 @@ __export(src_exports, {
924
926
  resolveMoneyRowValues: () => resolveMoneyRowValues,
925
927
  resolvePercentDecimals: () => resolvePercentDecimals,
926
928
  resolveReportItemStates: () => resolveReportItemStates,
929
+ resolveStandardDeviceName: () => resolveStandardDeviceName,
927
930
  resolveSubcategory: () => resolveSubcategory,
928
931
  resolveWithFallback: () => resolveWithFallback,
929
932
  roundMoney2: () => roundMoney2,
@@ -946,6 +949,7 @@ __export(src_exports, {
946
949
  slugifyCustomerName: () => slugifyCustomerName,
947
950
  sortAnnotationGroups: () => sortGroups,
948
951
  sortDeviceGridDevices: () => sortDevices,
952
+ standardDeviceName: () => standardDeviceName,
949
953
  strings: () => strings_exports,
950
954
  subtractDecimals: () => subtractDecimals,
951
955
  sumItemMoney: () => sumItemMoney,
@@ -989,7 +993,7 @@ module.exports = __toCommonJS(src_exports);
989
993
  // package.json
990
994
  var package_default = {
991
995
  name: "myio-js-library",
992
- version: "0.1.586",
996
+ version: "0.1.588",
993
997
  description: "A clean, standalone JS SDK for MYIO projects",
994
998
  license: "MIT",
995
999
  repository: "github:gh-myio/myio-js-library",
@@ -66176,6 +66180,106 @@ function activitiesForSegment(catalog, segment, currentActivity) {
66176
66180
  return list;
66177
66181
  }
66178
66182
 
66183
+ // src/components/premium-modals/settings/commercialTwin.ts
66184
+ var COMMERCIAL_KEYS = ["abl", "contract", "segment", "activity"];
66185
+ var ENERGY_STORE_PROFILE = "3F_MEDIDOR";
66186
+ var WATER_STORE_PROFILE = "HIDROMETRO";
66187
+ function normalizeProfile2(profile) {
66188
+ return String(profile || "").trim().toUpperCase();
66189
+ }
66190
+ function isCommercialProfile(profile) {
66191
+ const p = normalizeProfile2(profile);
66192
+ return p === ENERGY_STORE_PROFILE || p === WATER_STORE_PROFILE;
66193
+ }
66194
+ function twinProfileOf(profile) {
66195
+ const p = normalizeProfile2(profile);
66196
+ if (p === ENERGY_STORE_PROFILE) return WATER_STORE_PROFILE;
66197
+ if (p === WATER_STORE_PROFILE) return ENERGY_STORE_PROFILE;
66198
+ return null;
66199
+ }
66200
+ var isFilled = (v) => v !== void 0 && v !== null && String(v).trim() !== "";
66201
+ function mergeTwinCommercial(own, twinAttrs, ownProfile) {
66202
+ if (!twinAttrs) return own;
66203
+ const merged = { ...own };
66204
+ const inheritsFromTwin = normalizeProfile2(ownProfile) === WATER_STORE_PROFILE;
66205
+ for (const key of COMMERCIAL_KEYS) {
66206
+ const twinValue = twinAttrs[key];
66207
+ if (!isFilled(twinValue)) continue;
66208
+ if (inheritsFromTwin || !isFilled(merged[key])) merged[key] = String(twinValue).trim();
66209
+ }
66210
+ return merged;
66211
+ }
66212
+ function pickCommercial(formData) {
66213
+ const out = {};
66214
+ for (const key of COMMERCIAL_KEYS) {
66215
+ if (isFilled(formData[key])) out[key] = String(formData[key]).trim();
66216
+ }
66217
+ return out;
66218
+ }
66219
+ async function findCommercialTwins(params) {
66220
+ const { tbBaseUrl, jwtToken, customerId, deviceId } = params;
66221
+ const doFetch = params.fetchImpl || fetch;
66222
+ const twinProfile = twinProfileOf(params.deviceProfile);
66223
+ const identifier = String(params.identifier || "").trim();
66224
+ if (!twinProfile || !identifier || !customerId || !jwtToken) return [];
66225
+ const headers = { "X-Authorization": `Bearer ${jwtToken}`, "Content-Type": "application/json" };
66226
+ const body = {
66227
+ entityFilter: { type: "deviceType", deviceType: twinProfile, deviceTypes: [twinProfile], deviceNameFilter: "" },
66228
+ keyFilters: [
66229
+ {
66230
+ key: { type: "SERVER_ATTRIBUTE", key: "identifier" },
66231
+ valueType: "STRING",
66232
+ predicate: { type: "STRING", operation: "EQUAL", value: { defaultValue: identifier }, ignoreCase: true }
66233
+ }
66234
+ ],
66235
+ entityFields: [
66236
+ { type: "ENTITY_FIELD", key: "name" },
66237
+ { type: "ENTITY_FIELD", key: "label" }
66238
+ ],
66239
+ latestValues: [
66240
+ { type: "SERVER_ATTRIBUTE", key: "identifier" },
66241
+ ...COMMERCIAL_KEYS.map((key) => ({ type: "SERVER_ATTRIBUTE", key }))
66242
+ ],
66243
+ pageLink: { page: 0, pageSize: 20 }
66244
+ };
66245
+ const res = await doFetch(`${tbBaseUrl}/api/entitiesQuery/find`, {
66246
+ method: "POST",
66247
+ headers,
66248
+ body: JSON.stringify(body)
66249
+ });
66250
+ if (!res.ok) throw new Error(`entitiesQuery HTTP ${res.status}`);
66251
+ const json = await res.json();
66252
+ const candidates = [];
66253
+ for (const row of json?.data || []) {
66254
+ const id = row?.entityId?.id;
66255
+ if (!id || id === deviceId) continue;
66256
+ const attrValue = (k) => row?.latest?.SERVER_ATTRIBUTE?.[k]?.value;
66257
+ if (String(attrValue("identifier") || "").trim().toUpperCase() !== identifier.toUpperCase()) continue;
66258
+ const attrs = {};
66259
+ for (const key of COMMERCIAL_KEYS) {
66260
+ const v = attrValue(key);
66261
+ if (isFilled(v)) attrs[key] = String(v).trim();
66262
+ }
66263
+ candidates.push({
66264
+ id,
66265
+ name: String(row?.latest?.ENTITY_FIELD?.name?.value || ""),
66266
+ label: String(row?.latest?.ENTITY_FIELD?.label?.value || ""),
66267
+ attrs
66268
+ });
66269
+ }
66270
+ const twins = [];
66271
+ for (const c of candidates) {
66272
+ try {
66273
+ const r = await doFetch(`${tbBaseUrl}/api/device/${c.id}`, { headers });
66274
+ if (!r.ok) continue;
66275
+ const device = await r.json();
66276
+ if (device?.customerId?.id === customerId) twins.push(c);
66277
+ } catch {
66278
+ }
66279
+ }
66280
+ return twins;
66281
+ }
66282
+
66179
66283
  // src/components/createInputDateRangePickerInsideDIV.ts
66180
66284
  var PREMIUM_STYLES = `
66181
66285
  .myio-daterange-wrapper {
@@ -67410,6 +67514,7 @@ var SettingsModalView = class _SettingsModalView {
67410
67514
  * opções preenchidas em initCommercialFields após carregar o catálogo).
67411
67515
  */
67412
67516
  getCommercialFieldsHTML() {
67517
+ if (!isCommercialProfile(this.config.deviceProfile)) return "";
67413
67518
  const ro = this.canEditCommercial() ? "" : " readonly";
67414
67519
  const customerName = String(
67415
67520
  this.config.customerName || window.MyIOUtils?.customerName || ""
@@ -67440,6 +67545,7 @@ var SettingsModalView = class _SettingsModalView {
67440
67545
  </select>
67441
67546
  </div>
67442
67547
  </div>
67548
+ <div class="commercial-twin-note" id="commercial-twin-note" hidden></div>
67443
67549
  </div>
67444
67550
  `;
67445
67551
  }
@@ -67448,6 +67554,12 @@ var SettingsModalView = class _SettingsModalView {
67448
67554
  const segmentEl = this.modal.querySelector("#segment");
67449
67555
  const activityEl = this.modal.querySelector("#activity");
67450
67556
  if (!segmentEl || !activityEl) return;
67557
+ const twinNote = this.modal.querySelector("#commercial-twin-note");
67558
+ const twinLabel = String(saved._commercialTwinLabel || "").trim();
67559
+ if (twinNote && twinLabel) {
67560
+ twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
67561
+ twinNote.hidden = false;
67562
+ }
67451
67563
  const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67452
67564
  const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc12(v)}"${v === selected ? " selected" : ""}>${esc12(v)}</option>`).join("");
67453
67565
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
@@ -69192,6 +69304,14 @@ var SettingsModalView = class _SettingsModalView {
69192
69304
  flex-direction: column;
69193
69305
  gap: 5px;
69194
69306
  }
69307
+ .commercial-twin-note {
69308
+ margin-top: 8px;
69309
+ font-size: 11px;
69310
+ color: #6b7280;
69311
+ }
69312
+ .commercial-twin-note[hidden] {
69313
+ display: none;
69314
+ }
69195
69315
  select.identity-input {
69196
69316
  height: 30px;
69197
69317
  cursor: pointer;
@@ -70238,6 +70358,7 @@ var SettingsModalView = class _SettingsModalView {
70238
70358
  .theme-dark .commercial-title { color: #ced4da; }
70239
70359
  .theme-dark .commercial-sep { color: #495057; }
70240
70360
  .theme-dark .commercial-customer { color: #c4b5fd; }
70361
+ .theme-dark .commercial-twin-note { color: #9ca3af; }
70241
70362
  .theme-dark select.identity-input:disabled { background: #1a1b1e; color: #6c757d; }
70242
70363
  .theme-dark .device-name-subtitle {
70243
70364
  color: #6c757d;
@@ -80831,6 +80952,8 @@ var DefaultSettingsFetcher = class _DefaultSettingsFetcher {
80831
80952
 
80832
80953
  // src/components/premium-modals/settings/SettingsController.ts
80833
80954
  var SettingsController = class {
80955
+ /** Device(s) gêmeo(s) da loja (3F_MEDIDOR ↔ HIDROMETRO, mesmo identifier) — recebem os dados comerciais no save. */
80956
+ commercialTwins = [];
80834
80957
  view;
80835
80958
  persister;
80836
80959
  fetcher;
@@ -80949,8 +81072,41 @@ var SettingsController = class {
80949
81072
  });
80950
81073
  }
80951
81074
  }
81075
+ initialData = await this.loadCommercialTwins(initialData);
80952
81076
  this.view.render(initialData);
80953
81077
  }
81078
+ /**
81079
+ * Lojas (3F_MEDIDOR / HIDROMETRO): acha o device gêmeo pelo `identifier` (mesmo customer).
81080
+ * O hidrômetro herda ABL/Contrato/Segmento/Atividade do medidor de energia; o medidor de
81081
+ * energia só completa campos vazios. Falha na busca → segue com os dados do próprio device.
81082
+ */
81083
+ async loadCommercialTwins(initialData) {
81084
+ this.commercialTwins = [];
81085
+ if (!isCommercialProfile(this.params.deviceProfile) || !initialData.identifier) return initialData;
81086
+ try {
81087
+ this.commercialTwins = await findCommercialTwins({
81088
+ tbBaseUrl: this.params.api?.tbBaseUrl || window.location.origin,
81089
+ jwtToken: this.params.jwtToken,
81090
+ customerId: this.params.customerId || window.MyIOUtils?.customerTB_ID || null,
81091
+ deviceId: this.params.deviceId,
81092
+ deviceProfile: this.params.deviceProfile,
81093
+ identifier: initialData.identifier
81094
+ });
81095
+ } catch (error) {
81096
+ console.warn("[SettingsModal] Busca do device g\xEAmeo (dados comerciais) falhou:", error);
81097
+ return initialData;
81098
+ }
81099
+ if (this.commercialTwins.length === 0) return initialData;
81100
+ if (this.commercialTwins.length > 1) {
81101
+ console.warn(
81102
+ "[SettingsModal] Mais de um device g\xEAmeo com o mesmo identifier \u2014 herda do primeiro, salva em todos:",
81103
+ this.commercialTwins.map((t) => t.name)
81104
+ );
81105
+ }
81106
+ const merged = mergeTwinCommercial(initialData, this.commercialTwins[0].attrs, this.params.deviceProfile);
81107
+ merged._commercialTwinLabel = this.commercialTwins.map((t) => t.label || t.name).join(", ");
81108
+ return merged;
81109
+ }
80954
81110
  /**
80955
81111
  * RFC-0080: Fetch GLOBAL mapInstantaneousPower from CUSTOMER SERVER_SCOPE
80956
81112
  */
@@ -81108,6 +81264,29 @@ var SettingsController = class {
81108
81264
  result.ok = false;
81109
81265
  }
81110
81266
  }
81267
+ const commercial = pickCommercial(formData);
81268
+ if (this.commercialTwins.length > 0 && Object.keys(commercial).length > 0) {
81269
+ result.commercialTwins = [];
81270
+ for (const twin of this.commercialTwins) {
81271
+ const twinName = twin.label || twin.name;
81272
+ try {
81273
+ const twinResult = await this.persister.saveServerScopeAttributes(twin.id, {
81274
+ ...commercial,
81275
+ lastUpdatedTime: Date.now()
81276
+ });
81277
+ result.commercialTwins.push({ deviceId: twin.id, name: twinName, ok: twinResult.ok, error: twinResult.error });
81278
+ if (!twinResult.ok) result.ok = false;
81279
+ } catch (error) {
81280
+ result.commercialTwins.push({
81281
+ deviceId: twin.id,
81282
+ name: twinName,
81283
+ ok: false,
81284
+ error: { code: "UNKNOWN_ERROR", message: error.message || "Failed to save twin device", cause: error }
81285
+ });
81286
+ result.ok = false;
81287
+ }
81288
+ }
81289
+ }
81111
81290
  return result;
81112
81291
  }
81113
81292
  extractAttributes(formData) {
@@ -81127,6 +81306,11 @@ var SettingsController = class {
81127
81306
  if (result.serverScope?.error) {
81128
81307
  errors.push(`Settings: ${result.serverScope.error.message}`);
81129
81308
  }
81309
+ for (const twin of result.commercialTwins || []) {
81310
+ if (!twin.ok) {
81311
+ errors.push(`Dados de cadastro n\xE3o replicados em ${twin.name}: ${twin.error?.message || "erro"}`);
81312
+ }
81313
+ }
81130
81314
  return errors.length > 0 ? errors.join("; ") : "Failed to save settings";
81131
81315
  }
81132
81316
  handleClose() {
@@ -118447,6 +118631,38 @@ var NAME_PREFIX = {
118447
118631
  water: "Hidr. "
118448
118632
  };
118449
118633
  var MANUAL_ASSET_SUFFIX = "_DEVICES_MANUAIS";
118634
+ var STANDARD_DEVICE_PROFILES = {
118635
+ energy: [
118636
+ "3F_MEDIDOR",
118637
+ "ENTRADA",
118638
+ "RELOGIO",
118639
+ "SUBESTACAO",
118640
+ "TRANSFORMADOR",
118641
+ "ELEVADOR",
118642
+ "ESCADA_ROLANTE",
118643
+ "CHILLER",
118644
+ "FANCOIL",
118645
+ "BOMBA_CAG",
118646
+ "BOMBA_HIDRAULICA",
118647
+ "BOMBA_INCENDIO",
118648
+ "BOMBA_POCO",
118649
+ "MOTOR"
118650
+ ],
118651
+ water: ["HIDROMETRO", "HIDROMETRO_AREA_COMUM", "HIDROMETRO_SHOPPING", "HIDROMETRO_ENTRADA"]
118652
+ };
118653
+ var standardNameToken = (deviceProfile) => ["3F_MEDIDOR", "HIDROMETRO"].includes(deviceProfile) ? "LOJA" : deviceProfile;
118654
+ function standardDeviceName(domain, sigla, deviceProfile, seq) {
118655
+ return `${NAME_PREFIX[domain]}${sigla}_${standardNameToken(deviceProfile)}_${String(seq).padStart(3, "0")}`;
118656
+ }
118657
+ function nextStandardSeq(domain, sigla, deviceProfile, existingNames) {
118658
+ const esc12 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
118659
+ const re = new RegExp(`^${esc12(NAME_PREFIX[domain])}${esc12(sigla)}_${esc12(standardNameToken(deviceProfile))}_(\\d+)$`, "i");
118660
+ const max = existingNames.reduce((acc, n) => {
118661
+ const m = re.exec(String(n || "").trim());
118662
+ return m ? Math.max(acc, Number(m[1])) : acc;
118663
+ }, 0);
118664
+ return max + 1;
118665
+ }
118450
118666
  var ManualDeviceError = class extends Error {
118451
118667
  constructor(message, detail) {
118452
118668
  super(message);
@@ -118535,10 +118751,36 @@ async function resolveManualDeviceName(params) {
118535
118751
  deviceProfile: profile
118536
118752
  };
118537
118753
  }
118754
+ async function resolveStandardDeviceName(params) {
118755
+ const profile = String(params.deviceProfile || "").trim().toUpperCase();
118756
+ if (!MANUAL_DEVICE_PROFILES[params.domain]) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${params.domain}`);
118757
+ if (!profile) throw new ManualDeviceError("Escolha o tipo do dispositivo.");
118758
+ if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
118759
+ const api = await buildTbApi(params);
118760
+ const { asset, sigla } = await findManualAsset(api, params.customerId);
118761
+ const token = standardNameToken(profile);
118762
+ const existing = await api(
118763
+ "GET",
118764
+ `/api/customer/${encodeURIComponent(params.customerId)}/devices?pageSize=1000&page=0&textSearch=${encodeURIComponent(`${sigla}_${token}_`)}`
118765
+ );
118766
+ const names = (existing?.data || []).map((d) => String(d?.name || ""));
118767
+ const seq = nextStandardSeq(params.domain, sigla, profile, names);
118768
+ return {
118769
+ name: standardDeviceName(params.domain, sigla, profile, seq),
118770
+ sigla,
118771
+ seq,
118772
+ assetId: asset.id.id,
118773
+ assetName: asset.name,
118774
+ deviceProfile: profile
118775
+ };
118776
+ }
118538
118777
  async function createManualDevice(params) {
118539
118778
  const domain = params.domain;
118540
- const profile = MANUAL_DEVICE_PROFILES[domain];
118541
- if (!profile) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
118779
+ if (!MANUAL_DEVICE_PROFILES[domain]) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
118780
+ const profile = String(params.deviceProfile || "").trim() || MANUAL_DEVICE_PROFILES[domain];
118781
+ if (params.asset && !String(params.name || "").trim()) {
118782
+ throw new ManualDeviceError("Nome do dispositivo n\xE3o reservado.", "asset informado sem name");
118783
+ }
118542
118784
  const label = String(params.label || "").trim();
118543
118785
  const identifier = String(params.identifier || "").trim();
118544
118786
  if (!label) throw new ManualDeviceError("Informe a etiqueta.");
@@ -118546,7 +118788,7 @@ async function createManualDevice(params) {
118546
118788
  if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
118547
118789
  const api = await buildTbApi(params);
118548
118790
  const cid = encodeURIComponent(params.customerId);
118549
- const { asset, sigla } = await findManualAsset(api, params.customerId);
118791
+ const { asset, sigla } = params.asset ? { asset: { id: { id: params.asset.id }, name: params.asset.name }, sigla: "" } : await findManualAsset(api, params.customerId);
118550
118792
  const fixedName = String(params.name || "").trim();
118551
118793
  let seq = fixedName ? 0 : nextManualSeq(domain, sigla, await existingManualNames(api, params.customerId, sigla));
118552
118794
  let deviceProfileId;
@@ -118606,9 +118848,17 @@ async function createManualDevice(params) {
118606
118848
  }
118607
118849
 
118608
118850
  // src/components/premium-modals/manual-device/openManualDeviceModal.ts
118851
+ var MANUAL_HINT = "Cadastre um ponto de leitura manual. Ele aparece nesta lista e n\xE3o entra nos totais nem nos relat\xF3rios.";
118852
+ var STANDARD_HINT = "Cadastre um medidor ligado \xE0 central. Ele \xE9 criado no GCDR, Ingestion, ThingsBoard e na central.";
118609
118853
  var DOMAIN_TEXT2 = {
118610
- energy: { title: "Novo medidor de energia manual", icon: "\u26A1", noun: "Medidor de energia" },
118611
- water: { title: "Novo hidr\xF4metro manual", icon: "\u{1F4A7}", noun: "Hidr\xF4metro" }
118854
+ manual: {
118855
+ energy: { title: "Novo medidor de energia manual", icon: "\u26A1", noun: "Medidor de energia", hint: MANUAL_HINT },
118856
+ water: { title: "Novo hidr\xF4metro manual", icon: "\u{1F4A7}", noun: "Hidr\xF4metro", hint: MANUAL_HINT }
118857
+ },
118858
+ standard: {
118859
+ energy: { title: "Novo medidor de energia", icon: "\u26A1", noun: "Medidor de energia", hint: STANDARD_HINT },
118860
+ water: { title: "Novo hidr\xF4metro", icon: "\u{1F4A7}", noun: "Hidr\xF4metro", hint: STANDARD_HINT }
118861
+ }
118612
118862
  };
118613
118863
  var STYLE_ID16 = "myio-manualdev-styles";
118614
118864
  function escapeHtml16(v) {
@@ -118667,12 +118917,42 @@ function injectStyles16() {
118667
118917
  `;
118668
118918
  document.head.appendChild(style);
118669
118919
  }
118670
- function formHtml(domain, values, error, detail) {
118671
- const t = DOMAIN_TEXT2[domain];
118920
+ function selectHtml(name, label, placeholder, opts, value, disabled = false) {
118921
+ return `
118922
+ <label class="myio-manualdev__field">
118923
+ <span class="myio-manualdev__label">${escapeHtml16(label)}</span>
118924
+ <select class="myio-manualdev__input" name="${name}"${disabled ? " disabled" : ""}>
118925
+ <option value="">${escapeHtml16(placeholder)}</option>
118926
+ ${opts.map((o) => `<option value="${escapeHtml16(o.value)}"${o.value === value ? " selected" : ""}>${escapeHtml16(o.text)}</option>`).join("")}
118927
+ </select>
118928
+ </label>`;
118929
+ }
118930
+ function extraFieldsHtml(s) {
118931
+ const profile = s.kind === "standard" ? selectHtml("deviceProfile", "Tipo", "Selecione o tipo", s.profiles.map((p) => ({ value: p, text: p })), s.deviceProfile) : "";
118932
+ let central = "";
118933
+ if (s.centrals === null) {
118934
+ central = selectHtml("centralId", "Central", "Carregando centrais\u2026", [], "", true);
118935
+ } else if (s.centrals.length > 1) {
118936
+ central = selectHtml(
118937
+ "centralId",
118938
+ "Central",
118939
+ "Selecione a central",
118940
+ s.centrals.map((c) => ({
118941
+ value: c.id,
118942
+ text: `${c.name || c.id}${typeof c.deviceCount === "number" ? ` \xB7 ${c.deviceCount} devices` : ""}`
118943
+ })),
118944
+ s.centralId
118945
+ );
118946
+ }
118947
+ return profile + central;
118948
+ }
118949
+ function formHtml(s, error, detail) {
118950
+ const t = DOMAIN_TEXT2[s.kind][s.domain];
118951
+ const values = s;
118672
118952
  return `
118673
118953
  <form class="myio-manualdev" novalidate>
118674
- <p class="myio-manualdev__hint">Cadastre um ponto de leitura manual. Ele aparece nesta lista e n\xE3o entra nos totais nem nos relat\xF3rios.</p>
118675
- <span class="myio-manualdev__type">${t.icon} ${escapeHtml16(t.noun)} manual</span>
118954
+ <p class="myio-manualdev__hint">${escapeHtml16(t.hint)}</p>
118955
+ <span class="myio-manualdev__type">${t.icon} ${escapeHtml16(t.noun)}${s.kind === "manual" ? " manual" : ""}</span>
118676
118956
  <label class="myio-manualdev__field">
118677
118957
  <span class="myio-manualdev__label">Etiqueta</span>
118678
118958
  <input class="myio-manualdev__input" name="label" maxlength="80" autocomplete="off"
@@ -118683,6 +118963,7 @@ function formHtml(domain, values, error, detail) {
118683
118963
  <input class="myio-manualdev__input" name="identifier" maxlength="40" autocomplete="off"
118684
118964
  placeholder="Ex.: STB01010" value="${escapeHtml16(values.identifier)}" />
118685
118965
  </label>
118966
+ ${extraFieldsHtml(s)}
118686
118967
  ${error ? `<p class="myio-manualdev__error" role="alert">${escapeHtml16(error)}${detail ? `<small class="myio-manualdev__detail">${escapeHtml16(detail)}</small>` : ""}</p>` : ""}
118687
118968
  <button type="submit" hidden></button>
118688
118969
  </form>`;
@@ -118691,7 +118972,7 @@ function successHtml(domain, r, tech) {
118691
118972
  return `
118692
118973
  <div class="myio-manualdev__ok">
118693
118974
  <div class="myio-manualdev__ok-icon">\u2705</div>
118694
- <p class="myio-manualdev__ok-title">${escapeHtml16(DOMAIN_TEXT2[domain].noun)} criado</p>
118975
+ <p class="myio-manualdev__ok-title">${escapeHtml16(DOMAIN_TEXT2.manual[domain].noun)} criado</p>
118695
118976
  <p class="myio-manualdev__ok-text"><strong>${escapeHtml16(r.label)}</strong> \xB7 ${escapeHtml16(r.identifier)}</p>
118696
118977
  ${tech ? `<div class="myio-manualdev__tech">
118697
118978
  device <code>${escapeHtml16(r.name)}</code><br/>
@@ -118751,18 +119032,51 @@ function progressHtml(steps, message, ok, open = false) {
118751
119032
  ${moreHtml(stepsHtml(steps), open)}
118752
119033
  </div>`;
118753
119034
  }
119035
+ function initialState(params, kind, loadsCentrals) {
119036
+ const profiles = kind === "standard" ? (params.deviceProfiles?.length ? params.deviceProfiles : STANDARD_DEVICE_PROFILES[params.domain]).slice() : [];
119037
+ const def = String(params.defaultDeviceProfile || "").toUpperCase();
119038
+ return {
119039
+ kind,
119040
+ domain: params.domain,
119041
+ label: "",
119042
+ identifier: "",
119043
+ deviceProfile: profiles.includes(def) ? def : "",
119044
+ centralId: "",
119045
+ profiles,
119046
+ centrals: loadsCentrals ? null : []
119047
+ };
119048
+ }
119049
+ function readForm(body, s) {
119050
+ const val = (name) => (body.querySelector(`[name="${name}"]`)?.value ?? "").trim();
119051
+ s.label = val("label");
119052
+ s.identifier = val("identifier");
119053
+ if (s.kind === "standard") s.deviceProfile = val("deviceProfile");
119054
+ if (s.centrals && s.centrals.length > 1) s.centralId = val("centralId");
119055
+ }
119056
+ function missingField(s) {
119057
+ if (!s.label) return { name: "label", msg: "Informe a etiqueta." };
119058
+ if (!s.identifier) return { name: "identifier", msg: "Informe o identificador." };
119059
+ if (s.kind === "standard" && !s.deviceProfile) return { name: "deviceProfile", msg: "Escolha o tipo." };
119060
+ if (s.centrals === null) return { name: "centralId", msg: "Aguarde o carregamento das centrais." };
119061
+ if (s.centrals.length > 1 && !s.centralId) return { name: "centralId", msg: "Escolha a central." };
119062
+ return null;
119063
+ }
118754
119064
  function openManualDeviceModal(params) {
118755
119065
  const domain = params.domain;
118756
119066
  if (!MANUAL_DEVICE_PROFILES[domain]) throw new Error(`[openManualDeviceModal] dom\xEDnio inv\xE1lido: ${domain}`);
119067
+ const kind = params.kind === "standard" ? "standard" : "manual";
119068
+ if (kind === "standard" && !params.provisioner) {
119069
+ throw new Error('[openManualDeviceModal] kind "standard" exige provisioner');
119070
+ }
118757
119071
  injectStyles16();
118758
- if (params.provisioner) return openProvisionedModal(params, params.provisioner);
118759
- const values = { label: "", identifier: "" };
119072
+ if (params.provisioner) return openProvisionedModal(params, params.provisioner, kind);
119073
+ const state6 = initialState(params, "manual", false);
118760
119074
  let busy = false;
118761
119075
  let created = null;
118762
119076
  const modal = openStandardModal({
118763
- title: DOMAIN_TEXT2[domain].title,
118764
- icon: DOMAIN_TEXT2[domain].icon,
118765
- bodyHtml: formHtml(domain, values),
119077
+ title: DOMAIN_TEXT2.manual[domain].title,
119078
+ icon: DOMAIN_TEXT2.manual[domain].icon,
119079
+ bodyHtml: formHtml(state6),
118766
119080
  width: 460,
118767
119081
  container: params.container,
118768
119082
  buttons: [
@@ -118792,13 +119106,12 @@ function openManualDeviceModal(params) {
118792
119106
  async function submit() {
118793
119107
  if (busy || created) return;
118794
119108
  const body = modal.getBodyEl();
118795
- values.label = (body.querySelector('input[name="label"]')?.value || "").trim();
118796
- values.identifier = (body.querySelector('input[name="identifier"]')?.value || "").trim();
118797
- const missing = !values.label ? "label" : !values.identifier ? "identifier" : null;
119109
+ readForm(body, state6);
119110
+ const missing = missingField(state6);
118798
119111
  if (missing) {
118799
- modal.setBodyHtml(formHtml(domain, values, missing === "label" ? "Informe a etiqueta." : "Informe o identificador."));
119112
+ modal.setBodyHtml(formHtml(state6, missing.msg));
118800
119113
  bindForm(false);
118801
- const input = body.querySelector(`input[name="${missing}"]`);
119114
+ const input = body.querySelector(`[name="${missing.name}"]`);
118802
119115
  input?.setAttribute("aria-invalid", "true");
118803
119116
  input?.focus();
118804
119117
  return;
@@ -118808,14 +119121,14 @@ function openManualDeviceModal(params) {
118808
119121
  modal.setButton("cancel", { disabled: true });
118809
119122
  body.querySelectorAll("input").forEach((i) => i.disabled = true);
118810
119123
  try {
118811
- created = await createManualDevice({ ...params, label: values.label, identifier: values.identifier });
119124
+ created = await createManualDevice({ ...params, label: state6.label, identifier: state6.identifier });
118812
119125
  modal.setBodyHtml(successHtml(domain, created, !!params.showTechnicalDetails));
118813
119126
  modal.setButton("cancel", { hidden: true });
118814
119127
  modal.setButton("create", { disabled: false, label: "Concluir" });
118815
119128
  } catch (err) {
118816
119129
  const msg = err instanceof ManualDeviceError ? err.message : "N\xE3o foi poss\xEDvel criar o dispositivo.";
118817
119130
  const detail = params.showTechnicalDetails ? (err instanceof ManualDeviceError ? err.detail : String(err?.message || err)) || void 0 : void 0;
118818
- modal.setBodyHtml(formHtml(domain, values, msg, detail));
119131
+ modal.setBodyHtml(formHtml(state6, msg, detail));
118819
119132
  bindForm();
118820
119133
  modal.setButton("create", { disabled: false, label: "Criar" });
118821
119134
  modal.setButton("cancel", { disabled: false });
@@ -118825,16 +119138,17 @@ function openManualDeviceModal(params) {
118825
119138
  }
118826
119139
  return modal;
118827
119140
  }
118828
- function openProvisionedModal(params, provisioner) {
119141
+ function openProvisionedModal(params, provisioner, kind) {
118829
119142
  const domain = params.domain;
118830
- const values = { label: "", identifier: "" };
119143
+ const state6 = initialState(params, kind, typeof provisioner.options === "function");
118831
119144
  let phase = "form";
118832
119145
  let plan = null;
118833
119146
  let outcome = null;
119147
+ const text2 = DOMAIN_TEXT2[kind][domain];
118834
119148
  const modal = openStandardModal({
118835
- title: DOMAIN_TEXT2[domain].title,
118836
- icon: DOMAIN_TEXT2[domain].icon,
118837
- bodyHtml: formHtml(domain, values),
119149
+ title: text2.title,
119150
+ icon: text2.icon,
119151
+ bodyHtml: formHtml(state6),
118838
119152
  width: 560,
118839
119153
  container: params.container,
118840
119154
  buttons: [
@@ -118863,37 +119177,63 @@ function openProvisionedModal(params, provisioner) {
118863
119177
  if (focus) form?.querySelector('input[name="label"]')?.focus();
118864
119178
  };
118865
119179
  bindForm();
118866
- function showForm(error, detail) {
118867
- phase = "form";
118868
- modal.setBodyHtml(formHtml(domain, values, error, detail));
118869
- bindForm();
118870
- modal.setButton("back", { hidden: true });
118871
- modal.setButton("cancel", { disabled: false, hidden: false });
118872
- modal.setButton("next", { disabled: false, label: "Revisar" });
118873
- }
118874
119180
  const errorText = (err) => {
118875
119181
  const msg = err instanceof ManualDeviceError ? err.message : "N\xE3o foi poss\xEDvel montar o plano.";
118876
119182
  const detail = params.showTechnicalDetails ? (err instanceof ManualDeviceError ? err.detail : String(err?.message || err)) || void 0 : void 0;
118877
119183
  return { msg, detail };
118878
119184
  };
119185
+ if (provisioner.options) {
119186
+ provisioner.options({ domain, kind }).then((o) => {
119187
+ const centrals = Array.isArray(o?.centrals) ? o.centrals : [];
119188
+ if (phase !== "form") {
119189
+ state6.centrals = centrals;
119190
+ return;
119191
+ }
119192
+ readForm(modal.getBodyEl(), state6);
119193
+ state6.centrals = centrals;
119194
+ if (centrals.length === 1) state6.centralId = centrals[0].id;
119195
+ showForm(void 0, void 0, false);
119196
+ }).catch((err) => {
119197
+ state6.centrals = [];
119198
+ if (phase === "form") {
119199
+ readForm(modal.getBodyEl(), state6);
119200
+ const { detail } = errorText(err);
119201
+ showForm("N\xE3o foi poss\xEDvel carregar as centrais.", detail, false);
119202
+ }
119203
+ });
119204
+ }
119205
+ function showForm(error, detail, focus = true) {
119206
+ phase = "form";
119207
+ modal.setBodyHtml(formHtml(state6, error, detail));
119208
+ bindForm(focus);
119209
+ modal.setButton("back", { hidden: true });
119210
+ modal.setButton("cancel", { disabled: false, hidden: false });
119211
+ modal.setButton("next", { disabled: false, label: "Revisar" });
119212
+ }
118879
119213
  async function review() {
118880
119214
  if (phase !== "form") return;
118881
119215
  const body = modal.getBodyEl();
118882
- values.label = (body.querySelector('input[name="label"]')?.value || "").trim();
118883
- values.identifier = (body.querySelector('input[name="identifier"]')?.value || "").trim();
118884
- const missing = !values.label ? "label" : !values.identifier ? "identifier" : null;
119216
+ readForm(body, state6);
119217
+ const missing = missingField(state6);
118885
119218
  if (missing) {
118886
- showForm(missing === "label" ? "Informe a etiqueta." : "Informe o identificador.");
118887
- const input = modal.getBodyEl().querySelector(`input[name="${missing}"]`);
119219
+ showForm(missing.msg);
119220
+ const input = modal.getBodyEl().querySelector(`[name="${missing.name}"]`);
118888
119221
  input?.setAttribute("aria-invalid", "true");
118889
119222
  input?.focus();
118890
119223
  return;
118891
119224
  }
118892
119225
  phase = "planning";
118893
119226
  modal.setButton("next", { disabled: true, label: "Revisando\u2026" });
118894
- body.querySelectorAll("input").forEach((i) => i.disabled = true);
119227
+ body.querySelectorAll("input, select").forEach((i) => i.disabled = true);
118895
119228
  try {
118896
- plan = await provisioner.plan({ domain, label: values.label, identifier: values.identifier });
119229
+ plan = await provisioner.plan({
119230
+ domain,
119231
+ label: state6.label,
119232
+ identifier: state6.identifier,
119233
+ kind,
119234
+ ...kind === "standard" ? { deviceProfile: state6.deviceProfile } : {},
119235
+ ...state6.centralId ? { centralId: state6.centralId } : {}
119236
+ });
118897
119237
  phase = "plan";
118898
119238
  modal.setBodyHtml(planHtml(plan));
118899
119239
  modal.setButton("back", { hidden: false, disabled: false });
@@ -165995,18 +166335,18 @@ function convertTelemetryToTimelineData(telemetry, options) {
165995
166335
  let segmentStart = null;
165996
166336
  if (sorted[0].ts > startTs) {
165997
166337
  const firstKnownState = isOnState(sorted[0].value, invertLogic) ? "on" : "off";
165998
- const initialState = firstKnownState === "on" ? "off" : "on";
166338
+ const initialState2 = firstKnownState === "on" ? "off" : "on";
165999
166339
  segments.push({
166000
166340
  startTime: periodStart,
166001
166341
  endTime: new Date(sorted[0].ts).toISOString(),
166002
166342
  durationMinutes: (sorted[0].ts - startTs) / 6e4,
166003
- state: initialState,
166343
+ state: initialState2,
166004
166344
  source: "unknown"
166005
166345
  });
166006
- if (initialState === "on") {
166346
+ if (initialState2 === "on") {
166007
166347
  totalOnMinutes += (sorted[0].ts - startTs) / 6e4;
166008
166348
  }
166009
- previousState = initialState;
166349
+ previousState = initialState2;
166010
166350
  segmentStart = sorted[0].ts;
166011
166351
  } else {
166012
166352
  segmentStart = startTs;
@@ -181233,6 +181573,7 @@ var version = package_default.version || "0.0.0";
181233
181573
  SIDEBAR_MENU_CSS_PREFIX,
181234
181574
  SOLENOID_CONTROL_CSS_PREFIX,
181235
181575
  SOLENOID_IMAGES,
181576
+ STANDARD_DEVICE_PROFILES,
181236
181577
  STATUS_COLORS,
181237
181578
  STATUS_FRESHNESS_MAX_HOURS,
181238
181579
  STATUS_FRESHNESS_MAX_MS,
@@ -181726,6 +182067,7 @@ var version = package_default.version || "0.0.0";
181726
182067
  msToMinutes,
181727
182068
  myioExportData,
181728
182069
  nextManualSeq,
182070
+ nextStandardSeq,
181729
182071
  nfdNormalizeAnnotationSearch,
181730
182072
  normalizeBudgetBlock,
181731
182073
  normalizeConnectionStatus,
@@ -181857,6 +182199,7 @@ var version = package_default.version || "0.0.0";
181857
182199
  resolveMoneyRowValues,
181858
182200
  resolvePercentDecimals,
181859
182201
  resolveReportItemStates,
182202
+ resolveStandardDeviceName,
181860
182203
  resolveSubcategory,
181861
182204
  resolveWithFallback,
181862
182205
  roundMoney2,
@@ -181879,6 +182222,7 @@ var version = package_default.version || "0.0.0";
181879
182222
  slugifyCustomerName,
181880
182223
  sortAnnotationGroups,
181881
182224
  sortDeviceGridDevices,
182225
+ standardDeviceName,
181882
182226
  strings,
181883
182227
  subtractDecimals,
181884
182228
  sumItemMoney,