myio-js-library 0.1.585 → 0.1.587

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
@@ -989,7 +989,7 @@ module.exports = __toCommonJS(src_exports);
989
989
  // package.json
990
990
  var package_default = {
991
991
  name: "myio-js-library",
992
- version: "0.1.585",
992
+ version: "0.1.587",
993
993
  description: "A clean, standalone JS SDK for MYIO projects",
994
994
  license: "MIT",
995
995
  repository: "github:gh-myio/myio-js-library",
@@ -29328,6 +29328,7 @@ function createDateRangePicker($2, input, opts) {
29328
29328
  } else {
29329
29329
  ranges = {
29330
29330
  "Hoje": [moment().startOf("day"), moment().endOf("day")],
29331
+ "Ontem": [moment().subtract(1, "day").startOf("day"), moment().subtract(1, "day").endOf("day")],
29331
29332
  "\xDAltimos 7 dias": [moment().subtract(6, "days").startOf("day"), moment().endOf("day")],
29332
29333
  "\xDAltimos 15 dias": [moment().subtract(14, "days").startOf("day"), moment().endOf("day")],
29333
29334
  "\xDAltimos 30 dias": [moment().subtract(29, "days").startOf("day"), moment().endOf("day")],
@@ -63622,6 +63623,7 @@ var DeviceProfileTab = class {
63622
63623
  const slaveIdNum = typeof slaveId === "string" ? parseInt(slaveId, 10) : slaveId;
63623
63624
  let page = 1;
63624
63625
  let match = null;
63626
+ let fallback = null;
63625
63627
  for (; page <= 50 && !match; page++) {
63626
63628
  const res = await fetch(
63627
63629
  `${INGESTION_API_BASE2}/management/devices?page=${page}&limit=100&customerId=${encodeURIComponent(
@@ -63633,15 +63635,18 @@ var DeviceProfileTab = class {
63633
63635
  const json = await res.json();
63634
63636
  const list = json?.data || [];
63635
63637
  for (const d of list) {
63636
- const gwId = d.gateway?.hardwareUuid || d.gatewayId || d.gateway?.id;
63637
- if (gwId === centralId && d.slaveId === slaveIdNum) {
63638
+ if (d.slaveId !== slaveIdNum) continue;
63639
+ if (d.gateway?.hardwareUuid === centralId) {
63638
63640
  match = { id: d.id };
63639
63641
  break;
63640
63642
  }
63643
+ if (!fallback && (d.gatewayId === centralId || d.gateway?.id === centralId)) fallback = { id: d.id };
63641
63644
  }
63645
+ if (match) break;
63642
63646
  const totalPages = json?.pagination?.pages || 1;
63643
63647
  if (page >= totalPages) break;
63644
63648
  }
63649
+ if (!match && fallback) match = fallback;
63645
63650
  if (!match) {
63646
63651
  return { ok: false, message: `Nenhum device na Ingestion API com centralId=${centralId} e slaveId=${slaveIdNum}.` };
63647
63652
  }
@@ -66171,6 +66176,106 @@ function activitiesForSegment(catalog, segment, currentActivity) {
66171
66176
  return list;
66172
66177
  }
66173
66178
 
66179
+ // src/components/premium-modals/settings/commercialTwin.ts
66180
+ var COMMERCIAL_KEYS = ["abl", "contract", "segment", "activity"];
66181
+ var ENERGY_STORE_PROFILE = "3F_MEDIDOR";
66182
+ var WATER_STORE_PROFILE = "HIDROMETRO";
66183
+ function normalizeProfile2(profile) {
66184
+ return String(profile || "").trim().toUpperCase();
66185
+ }
66186
+ function isCommercialProfile(profile) {
66187
+ const p = normalizeProfile2(profile);
66188
+ return p === ENERGY_STORE_PROFILE || p === WATER_STORE_PROFILE;
66189
+ }
66190
+ function twinProfileOf(profile) {
66191
+ const p = normalizeProfile2(profile);
66192
+ if (p === ENERGY_STORE_PROFILE) return WATER_STORE_PROFILE;
66193
+ if (p === WATER_STORE_PROFILE) return ENERGY_STORE_PROFILE;
66194
+ return null;
66195
+ }
66196
+ var isFilled = (v) => v !== void 0 && v !== null && String(v).trim() !== "";
66197
+ function mergeTwinCommercial(own, twinAttrs, ownProfile) {
66198
+ if (!twinAttrs) return own;
66199
+ const merged = { ...own };
66200
+ const inheritsFromTwin = normalizeProfile2(ownProfile) === WATER_STORE_PROFILE;
66201
+ for (const key of COMMERCIAL_KEYS) {
66202
+ const twinValue = twinAttrs[key];
66203
+ if (!isFilled(twinValue)) continue;
66204
+ if (inheritsFromTwin || !isFilled(merged[key])) merged[key] = String(twinValue).trim();
66205
+ }
66206
+ return merged;
66207
+ }
66208
+ function pickCommercial(formData) {
66209
+ const out = {};
66210
+ for (const key of COMMERCIAL_KEYS) {
66211
+ if (isFilled(formData[key])) out[key] = String(formData[key]).trim();
66212
+ }
66213
+ return out;
66214
+ }
66215
+ async function findCommercialTwins(params) {
66216
+ const { tbBaseUrl, jwtToken, customerId, deviceId } = params;
66217
+ const doFetch = params.fetchImpl || fetch;
66218
+ const twinProfile = twinProfileOf(params.deviceProfile);
66219
+ const identifier = String(params.identifier || "").trim();
66220
+ if (!twinProfile || !identifier || !customerId || !jwtToken) return [];
66221
+ const headers = { "X-Authorization": `Bearer ${jwtToken}`, "Content-Type": "application/json" };
66222
+ const body = {
66223
+ entityFilter: { type: "deviceType", deviceType: twinProfile, deviceTypes: [twinProfile], deviceNameFilter: "" },
66224
+ keyFilters: [
66225
+ {
66226
+ key: { type: "SERVER_ATTRIBUTE", key: "identifier" },
66227
+ valueType: "STRING",
66228
+ predicate: { type: "STRING", operation: "EQUAL", value: { defaultValue: identifier }, ignoreCase: true }
66229
+ }
66230
+ ],
66231
+ entityFields: [
66232
+ { type: "ENTITY_FIELD", key: "name" },
66233
+ { type: "ENTITY_FIELD", key: "label" }
66234
+ ],
66235
+ latestValues: [
66236
+ { type: "SERVER_ATTRIBUTE", key: "identifier" },
66237
+ ...COMMERCIAL_KEYS.map((key) => ({ type: "SERVER_ATTRIBUTE", key }))
66238
+ ],
66239
+ pageLink: { page: 0, pageSize: 20 }
66240
+ };
66241
+ const res = await doFetch(`${tbBaseUrl}/api/entitiesQuery/find`, {
66242
+ method: "POST",
66243
+ headers,
66244
+ body: JSON.stringify(body)
66245
+ });
66246
+ if (!res.ok) throw new Error(`entitiesQuery HTTP ${res.status}`);
66247
+ const json = await res.json();
66248
+ const candidates = [];
66249
+ for (const row of json?.data || []) {
66250
+ const id = row?.entityId?.id;
66251
+ if (!id || id === deviceId) continue;
66252
+ const attrValue = (k) => row?.latest?.SERVER_ATTRIBUTE?.[k]?.value;
66253
+ if (String(attrValue("identifier") || "").trim().toUpperCase() !== identifier.toUpperCase()) continue;
66254
+ const attrs = {};
66255
+ for (const key of COMMERCIAL_KEYS) {
66256
+ const v = attrValue(key);
66257
+ if (isFilled(v)) attrs[key] = String(v).trim();
66258
+ }
66259
+ candidates.push({
66260
+ id,
66261
+ name: String(row?.latest?.ENTITY_FIELD?.name?.value || ""),
66262
+ label: String(row?.latest?.ENTITY_FIELD?.label?.value || ""),
66263
+ attrs
66264
+ });
66265
+ }
66266
+ const twins = [];
66267
+ for (const c of candidates) {
66268
+ try {
66269
+ const r = await doFetch(`${tbBaseUrl}/api/device/${c.id}`, { headers });
66270
+ if (!r.ok) continue;
66271
+ const device = await r.json();
66272
+ if (device?.customerId?.id === customerId) twins.push(c);
66273
+ } catch {
66274
+ }
66275
+ }
66276
+ return twins;
66277
+ }
66278
+
66174
66279
  // src/components/createInputDateRangePickerInsideDIV.ts
66175
66280
  var PREMIUM_STYLES = `
66176
66281
  .myio-daterange-wrapper {
@@ -67405,6 +67510,7 @@ var SettingsModalView = class _SettingsModalView {
67405
67510
  * opções preenchidas em initCommercialFields após carregar o catálogo).
67406
67511
  */
67407
67512
  getCommercialFieldsHTML() {
67513
+ if (!isCommercialProfile(this.config.deviceProfile)) return "";
67408
67514
  const ro = this.canEditCommercial() ? "" : " readonly";
67409
67515
  const customerName = String(
67410
67516
  this.config.customerName || window.MyIOUtils?.customerName || ""
@@ -67435,6 +67541,7 @@ var SettingsModalView = class _SettingsModalView {
67435
67541
  </select>
67436
67542
  </div>
67437
67543
  </div>
67544
+ <div class="commercial-twin-note" id="commercial-twin-note" hidden></div>
67438
67545
  </div>
67439
67546
  `;
67440
67547
  }
@@ -67443,6 +67550,12 @@ var SettingsModalView = class _SettingsModalView {
67443
67550
  const segmentEl = this.modal.querySelector("#segment");
67444
67551
  const activityEl = this.modal.querySelector("#activity");
67445
67552
  if (!segmentEl || !activityEl) return;
67553
+ const twinNote = this.modal.querySelector("#commercial-twin-note");
67554
+ const twinLabel = String(saved._commercialTwinLabel || "").trim();
67555
+ if (twinNote && twinLabel) {
67556
+ twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
67557
+ twinNote.hidden = false;
67558
+ }
67446
67559
  const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67447
67560
  const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc12(v)}"${v === selected ? " selected" : ""}>${esc12(v)}</option>`).join("");
67448
67561
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
@@ -69187,6 +69300,14 @@ var SettingsModalView = class _SettingsModalView {
69187
69300
  flex-direction: column;
69188
69301
  gap: 5px;
69189
69302
  }
69303
+ .commercial-twin-note {
69304
+ margin-top: 8px;
69305
+ font-size: 11px;
69306
+ color: #6b7280;
69307
+ }
69308
+ .commercial-twin-note[hidden] {
69309
+ display: none;
69310
+ }
69190
69311
  select.identity-input {
69191
69312
  height: 30px;
69192
69313
  cursor: pointer;
@@ -70233,6 +70354,7 @@ var SettingsModalView = class _SettingsModalView {
70233
70354
  .theme-dark .commercial-title { color: #ced4da; }
70234
70355
  .theme-dark .commercial-sep { color: #495057; }
70235
70356
  .theme-dark .commercial-customer { color: #c4b5fd; }
70357
+ .theme-dark .commercial-twin-note { color: #9ca3af; }
70236
70358
  .theme-dark select.identity-input:disabled { background: #1a1b1e; color: #6c757d; }
70237
70359
  .theme-dark .device-name-subtitle {
70238
70360
  color: #6c757d;
@@ -80826,6 +80948,8 @@ var DefaultSettingsFetcher = class _DefaultSettingsFetcher {
80826
80948
 
80827
80949
  // src/components/premium-modals/settings/SettingsController.ts
80828
80950
  var SettingsController = class {
80951
+ /** Device(s) gêmeo(s) da loja (3F_MEDIDOR ↔ HIDROMETRO, mesmo identifier) — recebem os dados comerciais no save. */
80952
+ commercialTwins = [];
80829
80953
  view;
80830
80954
  persister;
80831
80955
  fetcher;
@@ -80944,8 +81068,41 @@ var SettingsController = class {
80944
81068
  });
80945
81069
  }
80946
81070
  }
81071
+ initialData = await this.loadCommercialTwins(initialData);
80947
81072
  this.view.render(initialData);
80948
81073
  }
81074
+ /**
81075
+ * Lojas (3F_MEDIDOR / HIDROMETRO): acha o device gêmeo pelo `identifier` (mesmo customer).
81076
+ * O hidrômetro herda ABL/Contrato/Segmento/Atividade do medidor de energia; o medidor de
81077
+ * energia só completa campos vazios. Falha na busca → segue com os dados do próprio device.
81078
+ */
81079
+ async loadCommercialTwins(initialData) {
81080
+ this.commercialTwins = [];
81081
+ if (!isCommercialProfile(this.params.deviceProfile) || !initialData.identifier) return initialData;
81082
+ try {
81083
+ this.commercialTwins = await findCommercialTwins({
81084
+ tbBaseUrl: this.params.api?.tbBaseUrl || window.location.origin,
81085
+ jwtToken: this.params.jwtToken,
81086
+ customerId: this.params.customerId || window.MyIOUtils?.customerTB_ID || null,
81087
+ deviceId: this.params.deviceId,
81088
+ deviceProfile: this.params.deviceProfile,
81089
+ identifier: initialData.identifier
81090
+ });
81091
+ } catch (error) {
81092
+ console.warn("[SettingsModal] Busca do device g\xEAmeo (dados comerciais) falhou:", error);
81093
+ return initialData;
81094
+ }
81095
+ if (this.commercialTwins.length === 0) return initialData;
81096
+ if (this.commercialTwins.length > 1) {
81097
+ console.warn(
81098
+ "[SettingsModal] Mais de um device g\xEAmeo com o mesmo identifier \u2014 herda do primeiro, salva em todos:",
81099
+ this.commercialTwins.map((t) => t.name)
81100
+ );
81101
+ }
81102
+ const merged = mergeTwinCommercial(initialData, this.commercialTwins[0].attrs, this.params.deviceProfile);
81103
+ merged._commercialTwinLabel = this.commercialTwins.map((t) => t.label || t.name).join(", ");
81104
+ return merged;
81105
+ }
80949
81106
  /**
80950
81107
  * RFC-0080: Fetch GLOBAL mapInstantaneousPower from CUSTOMER SERVER_SCOPE
80951
81108
  */
@@ -81103,6 +81260,29 @@ var SettingsController = class {
81103
81260
  result.ok = false;
81104
81261
  }
81105
81262
  }
81263
+ const commercial = pickCommercial(formData);
81264
+ if (this.commercialTwins.length > 0 && Object.keys(commercial).length > 0) {
81265
+ result.commercialTwins = [];
81266
+ for (const twin of this.commercialTwins) {
81267
+ const twinName = twin.label || twin.name;
81268
+ try {
81269
+ const twinResult = await this.persister.saveServerScopeAttributes(twin.id, {
81270
+ ...commercial,
81271
+ lastUpdatedTime: Date.now()
81272
+ });
81273
+ result.commercialTwins.push({ deviceId: twin.id, name: twinName, ok: twinResult.ok, error: twinResult.error });
81274
+ if (!twinResult.ok) result.ok = false;
81275
+ } catch (error) {
81276
+ result.commercialTwins.push({
81277
+ deviceId: twin.id,
81278
+ name: twinName,
81279
+ ok: false,
81280
+ error: { code: "UNKNOWN_ERROR", message: error.message || "Failed to save twin device", cause: error }
81281
+ });
81282
+ result.ok = false;
81283
+ }
81284
+ }
81285
+ }
81106
81286
  return result;
81107
81287
  }
81108
81288
  extractAttributes(formData) {
@@ -81122,6 +81302,11 @@ var SettingsController = class {
81122
81302
  if (result.serverScope?.error) {
81123
81303
  errors.push(`Settings: ${result.serverScope.error.message}`);
81124
81304
  }
81305
+ for (const twin of result.commercialTwins || []) {
81306
+ if (!twin.ok) {
81307
+ errors.push(`Dados de cadastro n\xE3o replicados em ${twin.name}: ${twin.error?.message || "erro"}`);
81308
+ }
81309
+ }
81125
81310
  return errors.length > 0 ? errors.join("; ") : "Failed to save settings";
81126
81311
  }
81127
81312
  handleClose() {
@@ -111485,27 +111670,30 @@ async function fetchIngestionDevicesAllPaged(customerId) {
111485
111670
  }
111486
111671
  function findIngestionDeviceByCentralSlaveId(devices, centralId, slaveId) {
111487
111672
  const slaveIdNum = typeof slaveId === "string" ? parseInt(slaveId, 10) : slaveId;
111488
- for (const device of devices) {
111489
- const deviceGatewayId = device.gateway?.hardwareUuid || device.gatewayId || device.gateway?.id;
111490
- if (deviceGatewayId === centralId && device.slaveId === slaveIdNum) {
111491
- console.log(
111492
- "[UpsellModal] Found matching device:",
111493
- device.name,
111494
- "gatewayId:",
111495
- deviceGatewayId,
111496
- "slaveId:",
111497
- device.slaveId
111498
- );
111499
- return device;
111500
- }
111673
+ const bySlave = devices.filter((d) => d.slaveId === slaveIdNum);
111674
+ const match = bySlave.find((d) => d.gateway?.hardwareUuid === centralId) || bySlave.find((d) => d.gatewayId === centralId || d.gateway?.id === centralId);
111675
+ if (match) {
111676
+ console.log(
111677
+ "[UpsellModal] Found matching device:",
111678
+ match.name,
111679
+ "via:",
111680
+ match.gateway?.hardwareUuid === centralId ? "hardwareUuid" : "gatewayId",
111681
+ "centralId:",
111682
+ centralId,
111683
+ "slaveId:",
111684
+ match.slaveId
111685
+ );
111686
+ return match;
111501
111687
  }
111502
111688
  console.log("[UpsellModal] No match found. Looking for centralId:", centralId, "slaveId:", slaveIdNum);
111503
111689
  devices.slice(0, 3).forEach((d, i) => {
111504
111690
  console.log(
111505
111691
  `[UpsellModal] Sample device ${i}:`,
111506
111692
  d.name,
111507
- "gateway(hwUuid|id):",
111508
- d.gateway?.hardwareUuid || d.gatewayId || d.gateway?.id,
111693
+ "gateway hwUuid / id:",
111694
+ d.gateway?.hardwareUuid,
111695
+ "/",
111696
+ d.gatewayId || d.gateway?.id,
111509
111697
  "slaveId:",
111510
111698
  d.slaveId
111511
111699
  );
package/dist/index.d.cts CHANGED
@@ -7673,6 +7673,17 @@ interface PersistResult$1 {
7673
7673
  cause?: unknown;
7674
7674
  };
7675
7675
  };
7676
+ /** Dados comerciais replicados no device gêmeo da loja (3F_MEDIDOR ↔ HIDROMETRO, mesmo identifier). */
7677
+ commercialTwins?: Array<{
7678
+ deviceId: string;
7679
+ name: string;
7680
+ ok: boolean;
7681
+ error?: {
7682
+ code: string;
7683
+ message: string;
7684
+ cause?: unknown;
7685
+ };
7686
+ }>;
7676
7687
  timestamp?: string;
7677
7688
  }
7678
7689
  interface SettingsError {
package/dist/index.d.ts CHANGED
@@ -7673,6 +7673,17 @@ interface PersistResult$1 {
7673
7673
  cause?: unknown;
7674
7674
  };
7675
7675
  };
7676
+ /** Dados comerciais replicados no device gêmeo da loja (3F_MEDIDOR ↔ HIDROMETRO, mesmo identifier). */
7677
+ commercialTwins?: Array<{
7678
+ deviceId: string;
7679
+ name: string;
7680
+ ok: boolean;
7681
+ error?: {
7682
+ code: string;
7683
+ message: string;
7684
+ cause?: unknown;
7685
+ };
7686
+ }>;
7676
7687
  timestamp?: string;
7677
7688
  }
7678
7689
  interface SettingsError {