myio-js-library 0.1.586 → 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.586",
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",
@@ -66176,6 +66176,106 @@ function activitiesForSegment(catalog, segment, currentActivity) {
66176
66176
  return list;
66177
66177
  }
66178
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
+
66179
66279
  // src/components/createInputDateRangePickerInsideDIV.ts
66180
66280
  var PREMIUM_STYLES = `
66181
66281
  .myio-daterange-wrapper {
@@ -67410,6 +67510,7 @@ var SettingsModalView = class _SettingsModalView {
67410
67510
  * opções preenchidas em initCommercialFields após carregar o catálogo).
67411
67511
  */
67412
67512
  getCommercialFieldsHTML() {
67513
+ if (!isCommercialProfile(this.config.deviceProfile)) return "";
67413
67514
  const ro = this.canEditCommercial() ? "" : " readonly";
67414
67515
  const customerName = String(
67415
67516
  this.config.customerName || window.MyIOUtils?.customerName || ""
@@ -67440,6 +67541,7 @@ var SettingsModalView = class _SettingsModalView {
67440
67541
  </select>
67441
67542
  </div>
67442
67543
  </div>
67544
+ <div class="commercial-twin-note" id="commercial-twin-note" hidden></div>
67443
67545
  </div>
67444
67546
  `;
67445
67547
  }
@@ -67448,6 +67550,12 @@ var SettingsModalView = class _SettingsModalView {
67448
67550
  const segmentEl = this.modal.querySelector("#segment");
67449
67551
  const activityEl = this.modal.querySelector("#activity");
67450
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
+ }
67451
67559
  const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67452
67560
  const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc12(v)}"${v === selected ? " selected" : ""}>${esc12(v)}</option>`).join("");
67453
67561
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
@@ -69192,6 +69300,14 @@ var SettingsModalView = class _SettingsModalView {
69192
69300
  flex-direction: column;
69193
69301
  gap: 5px;
69194
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
+ }
69195
69311
  select.identity-input {
69196
69312
  height: 30px;
69197
69313
  cursor: pointer;
@@ -70238,6 +70354,7 @@ var SettingsModalView = class _SettingsModalView {
70238
70354
  .theme-dark .commercial-title { color: #ced4da; }
70239
70355
  .theme-dark .commercial-sep { color: #495057; }
70240
70356
  .theme-dark .commercial-customer { color: #c4b5fd; }
70357
+ .theme-dark .commercial-twin-note { color: #9ca3af; }
70241
70358
  .theme-dark select.identity-input:disabled { background: #1a1b1e; color: #6c757d; }
70242
70359
  .theme-dark .device-name-subtitle {
70243
70360
  color: #6c757d;
@@ -80831,6 +80948,8 @@ var DefaultSettingsFetcher = class _DefaultSettingsFetcher {
80831
80948
 
80832
80949
  // src/components/premium-modals/settings/SettingsController.ts
80833
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 = [];
80834
80953
  view;
80835
80954
  persister;
80836
80955
  fetcher;
@@ -80949,8 +81068,41 @@ var SettingsController = class {
80949
81068
  });
80950
81069
  }
80951
81070
  }
81071
+ initialData = await this.loadCommercialTwins(initialData);
80952
81072
  this.view.render(initialData);
80953
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
+ }
80954
81106
  /**
80955
81107
  * RFC-0080: Fetch GLOBAL mapInstantaneousPower from CUSTOMER SERVER_SCOPE
80956
81108
  */
@@ -81108,6 +81260,29 @@ var SettingsController = class {
81108
81260
  result.ok = false;
81109
81261
  }
81110
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
+ }
81111
81286
  return result;
81112
81287
  }
81113
81288
  extractAttributes(formData) {
@@ -81127,6 +81302,11 @@ var SettingsController = class {
81127
81302
  if (result.serverScope?.error) {
81128
81303
  errors.push(`Settings: ${result.serverScope.error.message}`);
81129
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
+ }
81130
81310
  return errors.length > 0 ? errors.join("; ") : "Failed to save settings";
81131
81311
  }
81132
81312
  handleClose() {
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 {
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.586",
13
+ version: "0.1.587",
14
14
  description: "A clean, standalone JS SDK for MYIO projects",
15
15
  license: "MIT",
16
16
  repository: "github:gh-myio/myio-js-library",
@@ -64472,6 +64472,106 @@ function activitiesForSegment(catalog, segment, currentActivity) {
64472
64472
  return list;
64473
64473
  }
64474
64474
 
64475
+ // src/components/premium-modals/settings/commercialTwin.ts
64476
+ var COMMERCIAL_KEYS = ["abl", "contract", "segment", "activity"];
64477
+ var ENERGY_STORE_PROFILE = "3F_MEDIDOR";
64478
+ var WATER_STORE_PROFILE = "HIDROMETRO";
64479
+ function normalizeProfile2(profile) {
64480
+ return String(profile || "").trim().toUpperCase();
64481
+ }
64482
+ function isCommercialProfile(profile) {
64483
+ const p = normalizeProfile2(profile);
64484
+ return p === ENERGY_STORE_PROFILE || p === WATER_STORE_PROFILE;
64485
+ }
64486
+ function twinProfileOf(profile) {
64487
+ const p = normalizeProfile2(profile);
64488
+ if (p === ENERGY_STORE_PROFILE) return WATER_STORE_PROFILE;
64489
+ if (p === WATER_STORE_PROFILE) return ENERGY_STORE_PROFILE;
64490
+ return null;
64491
+ }
64492
+ var isFilled = (v) => v !== void 0 && v !== null && String(v).trim() !== "";
64493
+ function mergeTwinCommercial(own, twinAttrs, ownProfile) {
64494
+ if (!twinAttrs) return own;
64495
+ const merged = { ...own };
64496
+ const inheritsFromTwin = normalizeProfile2(ownProfile) === WATER_STORE_PROFILE;
64497
+ for (const key of COMMERCIAL_KEYS) {
64498
+ const twinValue = twinAttrs[key];
64499
+ if (!isFilled(twinValue)) continue;
64500
+ if (inheritsFromTwin || !isFilled(merged[key])) merged[key] = String(twinValue).trim();
64501
+ }
64502
+ return merged;
64503
+ }
64504
+ function pickCommercial(formData) {
64505
+ const out = {};
64506
+ for (const key of COMMERCIAL_KEYS) {
64507
+ if (isFilled(formData[key])) out[key] = String(formData[key]).trim();
64508
+ }
64509
+ return out;
64510
+ }
64511
+ async function findCommercialTwins(params) {
64512
+ const { tbBaseUrl, jwtToken, customerId, deviceId } = params;
64513
+ const doFetch = params.fetchImpl || fetch;
64514
+ const twinProfile = twinProfileOf(params.deviceProfile);
64515
+ const identifier = String(params.identifier || "").trim();
64516
+ if (!twinProfile || !identifier || !customerId || !jwtToken) return [];
64517
+ const headers = { "X-Authorization": `Bearer ${jwtToken}`, "Content-Type": "application/json" };
64518
+ const body = {
64519
+ entityFilter: { type: "deviceType", deviceType: twinProfile, deviceTypes: [twinProfile], deviceNameFilter: "" },
64520
+ keyFilters: [
64521
+ {
64522
+ key: { type: "SERVER_ATTRIBUTE", key: "identifier" },
64523
+ valueType: "STRING",
64524
+ predicate: { type: "STRING", operation: "EQUAL", value: { defaultValue: identifier }, ignoreCase: true }
64525
+ }
64526
+ ],
64527
+ entityFields: [
64528
+ { type: "ENTITY_FIELD", key: "name" },
64529
+ { type: "ENTITY_FIELD", key: "label" }
64530
+ ],
64531
+ latestValues: [
64532
+ { type: "SERVER_ATTRIBUTE", key: "identifier" },
64533
+ ...COMMERCIAL_KEYS.map((key) => ({ type: "SERVER_ATTRIBUTE", key }))
64534
+ ],
64535
+ pageLink: { page: 0, pageSize: 20 }
64536
+ };
64537
+ const res = await doFetch(`${tbBaseUrl}/api/entitiesQuery/find`, {
64538
+ method: "POST",
64539
+ headers,
64540
+ body: JSON.stringify(body)
64541
+ });
64542
+ if (!res.ok) throw new Error(`entitiesQuery HTTP ${res.status}`);
64543
+ const json = await res.json();
64544
+ const candidates = [];
64545
+ for (const row of json?.data || []) {
64546
+ const id = row?.entityId?.id;
64547
+ if (!id || id === deviceId) continue;
64548
+ const attrValue = (k) => row?.latest?.SERVER_ATTRIBUTE?.[k]?.value;
64549
+ if (String(attrValue("identifier") || "").trim().toUpperCase() !== identifier.toUpperCase()) continue;
64550
+ const attrs = {};
64551
+ for (const key of COMMERCIAL_KEYS) {
64552
+ const v = attrValue(key);
64553
+ if (isFilled(v)) attrs[key] = String(v).trim();
64554
+ }
64555
+ candidates.push({
64556
+ id,
64557
+ name: String(row?.latest?.ENTITY_FIELD?.name?.value || ""),
64558
+ label: String(row?.latest?.ENTITY_FIELD?.label?.value || ""),
64559
+ attrs
64560
+ });
64561
+ }
64562
+ const twins = [];
64563
+ for (const c of candidates) {
64564
+ try {
64565
+ const r = await doFetch(`${tbBaseUrl}/api/device/${c.id}`, { headers });
64566
+ if (!r.ok) continue;
64567
+ const device = await r.json();
64568
+ if (device?.customerId?.id === customerId) twins.push(c);
64569
+ } catch {
64570
+ }
64571
+ }
64572
+ return twins;
64573
+ }
64574
+
64475
64575
  // src/components/createInputDateRangePickerInsideDIV.ts
64476
64576
  var PREMIUM_STYLES = `
64477
64577
  .myio-daterange-wrapper {
@@ -65706,6 +65806,7 @@ var SettingsModalView = class _SettingsModalView {
65706
65806
  * opções preenchidas em initCommercialFields após carregar o catálogo).
65707
65807
  */
65708
65808
  getCommercialFieldsHTML() {
65809
+ if (!isCommercialProfile(this.config.deviceProfile)) return "";
65709
65810
  const ro = this.canEditCommercial() ? "" : " readonly";
65710
65811
  const customerName = String(
65711
65812
  this.config.customerName || window.MyIOUtils?.customerName || ""
@@ -65736,6 +65837,7 @@ var SettingsModalView = class _SettingsModalView {
65736
65837
  </select>
65737
65838
  </div>
65738
65839
  </div>
65840
+ <div class="commercial-twin-note" id="commercial-twin-note" hidden></div>
65739
65841
  </div>
65740
65842
  `;
65741
65843
  }
@@ -65744,6 +65846,12 @@ var SettingsModalView = class _SettingsModalView {
65744
65846
  const segmentEl = this.modal.querySelector("#segment");
65745
65847
  const activityEl = this.modal.querySelector("#activity");
65746
65848
  if (!segmentEl || !activityEl) return;
65849
+ const twinNote = this.modal.querySelector("#commercial-twin-note");
65850
+ const twinLabel = String(saved._commercialTwinLabel || "").trim();
65851
+ if (twinNote && twinLabel) {
65852
+ twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
65853
+ twinNote.hidden = false;
65854
+ }
65747
65855
  const esc11 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
65748
65856
  const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc11(v)}"${v === selected ? " selected" : ""}>${esc11(v)}</option>`).join("");
65749
65857
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
@@ -67488,6 +67596,14 @@ var SettingsModalView = class _SettingsModalView {
67488
67596
  flex-direction: column;
67489
67597
  gap: 5px;
67490
67598
  }
67599
+ .commercial-twin-note {
67600
+ margin-top: 8px;
67601
+ font-size: 11px;
67602
+ color: #6b7280;
67603
+ }
67604
+ .commercial-twin-note[hidden] {
67605
+ display: none;
67606
+ }
67491
67607
  select.identity-input {
67492
67608
  height: 30px;
67493
67609
  cursor: pointer;
@@ -68534,6 +68650,7 @@ var SettingsModalView = class _SettingsModalView {
68534
68650
  .theme-dark .commercial-title { color: #ced4da; }
68535
68651
  .theme-dark .commercial-sep { color: #495057; }
68536
68652
  .theme-dark .commercial-customer { color: #c4b5fd; }
68653
+ .theme-dark .commercial-twin-note { color: #9ca3af; }
68537
68654
  .theme-dark select.identity-input:disabled { background: #1a1b1e; color: #6c757d; }
68538
68655
  .theme-dark .device-name-subtitle {
68539
68656
  color: #6c757d;
@@ -79127,6 +79244,8 @@ var DefaultSettingsFetcher = class _DefaultSettingsFetcher {
79127
79244
 
79128
79245
  // src/components/premium-modals/settings/SettingsController.ts
79129
79246
  var SettingsController = class {
79247
+ /** Device(s) gêmeo(s) da loja (3F_MEDIDOR ↔ HIDROMETRO, mesmo identifier) — recebem os dados comerciais no save. */
79248
+ commercialTwins = [];
79130
79249
  view;
79131
79250
  persister;
79132
79251
  fetcher;
@@ -79245,8 +79364,41 @@ var SettingsController = class {
79245
79364
  });
79246
79365
  }
79247
79366
  }
79367
+ initialData = await this.loadCommercialTwins(initialData);
79248
79368
  this.view.render(initialData);
79249
79369
  }
79370
+ /**
79371
+ * Lojas (3F_MEDIDOR / HIDROMETRO): acha o device gêmeo pelo `identifier` (mesmo customer).
79372
+ * O hidrômetro herda ABL/Contrato/Segmento/Atividade do medidor de energia; o medidor de
79373
+ * energia só completa campos vazios. Falha na busca → segue com os dados do próprio device.
79374
+ */
79375
+ async loadCommercialTwins(initialData) {
79376
+ this.commercialTwins = [];
79377
+ if (!isCommercialProfile(this.params.deviceProfile) || !initialData.identifier) return initialData;
79378
+ try {
79379
+ this.commercialTwins = await findCommercialTwins({
79380
+ tbBaseUrl: this.params.api?.tbBaseUrl || window.location.origin,
79381
+ jwtToken: this.params.jwtToken,
79382
+ customerId: this.params.customerId || window.MyIOUtils?.customerTB_ID || null,
79383
+ deviceId: this.params.deviceId,
79384
+ deviceProfile: this.params.deviceProfile,
79385
+ identifier: initialData.identifier
79386
+ });
79387
+ } catch (error) {
79388
+ console.warn("[SettingsModal] Busca do device g\xEAmeo (dados comerciais) falhou:", error);
79389
+ return initialData;
79390
+ }
79391
+ if (this.commercialTwins.length === 0) return initialData;
79392
+ if (this.commercialTwins.length > 1) {
79393
+ console.warn(
79394
+ "[SettingsModal] Mais de um device g\xEAmeo com o mesmo identifier \u2014 herda do primeiro, salva em todos:",
79395
+ this.commercialTwins.map((t) => t.name)
79396
+ );
79397
+ }
79398
+ const merged = mergeTwinCommercial(initialData, this.commercialTwins[0].attrs, this.params.deviceProfile);
79399
+ merged._commercialTwinLabel = this.commercialTwins.map((t) => t.label || t.name).join(", ");
79400
+ return merged;
79401
+ }
79250
79402
  /**
79251
79403
  * RFC-0080: Fetch GLOBAL mapInstantaneousPower from CUSTOMER SERVER_SCOPE
79252
79404
  */
@@ -79404,6 +79556,29 @@ var SettingsController = class {
79404
79556
  result.ok = false;
79405
79557
  }
79406
79558
  }
79559
+ const commercial = pickCommercial(formData);
79560
+ if (this.commercialTwins.length > 0 && Object.keys(commercial).length > 0) {
79561
+ result.commercialTwins = [];
79562
+ for (const twin of this.commercialTwins) {
79563
+ const twinName = twin.label || twin.name;
79564
+ try {
79565
+ const twinResult = await this.persister.saveServerScopeAttributes(twin.id, {
79566
+ ...commercial,
79567
+ lastUpdatedTime: Date.now()
79568
+ });
79569
+ result.commercialTwins.push({ deviceId: twin.id, name: twinName, ok: twinResult.ok, error: twinResult.error });
79570
+ if (!twinResult.ok) result.ok = false;
79571
+ } catch (error) {
79572
+ result.commercialTwins.push({
79573
+ deviceId: twin.id,
79574
+ name: twinName,
79575
+ ok: false,
79576
+ error: { code: "UNKNOWN_ERROR", message: error.message || "Failed to save twin device", cause: error }
79577
+ });
79578
+ result.ok = false;
79579
+ }
79580
+ }
79581
+ }
79407
79582
  return result;
79408
79583
  }
79409
79584
  extractAttributes(formData) {
@@ -79423,6 +79598,11 @@ var SettingsController = class {
79423
79598
  if (result.serverScope?.error) {
79424
79599
  errors.push(`Settings: ${result.serverScope.error.message}`);
79425
79600
  }
79601
+ for (const twin of result.commercialTwins || []) {
79602
+ if (!twin.ok) {
79603
+ errors.push(`Dados de cadastro n\xE3o replicados em ${twin.name}: ${twin.error?.message || "erro"}`);
79604
+ }
79605
+ }
79426
79606
  return errors.length > 0 ? errors.join("; ") : "Failed to save settings";
79427
79607
  }
79428
79608
  handleClose() {