myio-js-library 0.1.587 → 0.1.590

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,
@@ -420,6 +421,7 @@ __export(src_exports, {
420
421
  calculateStats: () => calculateStats,
421
422
  canEditAlarmRules: () => canEditAlarmRules,
422
423
  canModifyAnnotation: () => canModifyAnnotation,
424
+ categoryKeyFromLabel: () => categoryKeyFromLabel,
423
425
  centsToDecimalString: () => centsToDecimalString,
424
426
  checkCustomerCodeAvailable: () => checkCustomerCodeAvailable,
425
427
  clampTemperature: () => clampTemperature,
@@ -561,7 +563,6 @@ __export(src_exports, {
561
563
  detectSuperAdminMyio: () => detectSuperAdminMyio,
562
564
  determineInterval: () => determineInterval,
563
565
  deviceCategoryLabel: () => deviceCategoryLabel,
564
- deviceCategoryToPanelTerm: () => deviceCategoryToPanelTerm,
565
566
  deviceIconLabels: () => deviceIconLabels,
566
567
  deviceIcons: () => deviceIcons,
567
568
  deviceNameToDeviceProductCode: () => deviceNameToDeviceProductCode,
@@ -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,
@@ -855,9 +857,7 @@ __export(src_exports, {
855
857
  openWelcomeModal: () => openWelcomeModal,
856
858
  openWellPumpsModal: () => openWellPumpsModal,
857
859
  overlayWithholdsVerdict: () => overlayWithholdsVerdict,
858
- panelCategoryToWire: () => panelCategoryToWire,
859
860
  panelDomainToWire: () => panelDomainToWire,
860
- panelTermToDeviceCategory: () => panelTermToDeviceCategory,
861
861
  parseBinaryState: () => parseBinaryState,
862
862
  parseClassificationEntities: () => parseClassificationEntities,
863
863
  parseCsv: () => parseCsv,
@@ -924,6 +924,7 @@ __export(src_exports, {
924
924
  resolveMoneyRowValues: () => resolveMoneyRowValues,
925
925
  resolvePercentDecimals: () => resolvePercentDecimals,
926
926
  resolveReportItemStates: () => resolveReportItemStates,
927
+ resolveStandardDeviceName: () => resolveStandardDeviceName,
927
928
  resolveSubcategory: () => resolveSubcategory,
928
929
  resolveWithFallback: () => resolveWithFallback,
929
930
  roundMoney2: () => roundMoney2,
@@ -946,6 +947,7 @@ __export(src_exports, {
946
947
  slugifyCustomerName: () => slugifyCustomerName,
947
948
  sortAnnotationGroups: () => sortGroups,
948
949
  sortDeviceGridDevices: () => sortDevices,
950
+ standardDeviceName: () => standardDeviceName,
949
951
  strings: () => strings_exports,
950
952
  subtractDecimals: () => subtractDecimals,
951
953
  sumItemMoney: () => sumItemMoney,
@@ -978,7 +980,6 @@ __export(src_exports, {
978
980
  valveHistoryFromTelemetry: () => valveHistoryFromTelemetry,
979
981
  version: () => version,
980
982
  waterDeviceStatusIcons: () => waterDeviceStatusIcons,
981
- wireCategoryToPanel: () => wireCategoryToPanel,
982
983
  wireDomainToPanel: () => wireDomainToPanel,
983
984
  writeFreshdeskSyncedAtToTB: () => writeFreshdeskSyncedAtToTB,
984
985
  writeFreshdeskTicketsToTB: () => writeFreshdeskTicketsToTB,
@@ -989,7 +990,7 @@ module.exports = __toCommonJS(src_exports);
989
990
  // package.json
990
991
  var package_default = {
991
992
  name: "myio-js-library",
992
- version: "0.1.587",
993
+ version: "0.1.590",
993
994
  description: "A clean, standalone JS SDK for MYIO projects",
994
995
  license: "MIT",
995
996
  repository: "github:gh-myio/myio-js-library",
@@ -33196,8 +33197,8 @@ var EnergyDataFetcher = class {
33196
33197
  // src/components/premium-modals/internal/engines/CsvExporter.ts
33197
33198
  var toCsv = (rows, locale = "pt-BR", sep = ";") => {
33198
33199
  const fmt2 = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
33199
- const esc12 = (v) => (typeof v === "number" ? fmt2.format(v) : String(v)).replace(/"/g, '""');
33200
- return rows.map((r) => r.map((c) => `"${esc12(c)}"`).join(sep)).join("\r\n");
33200
+ const esc13 = (v) => (typeof v === "number" ? fmt2.format(v) : String(v)).replace(/"/g, '""');
33201
+ return rows.map((r) => r.map((c) => `"${esc13(c)}"`).join(sep)).join("\r\n");
33201
33202
  };
33202
33203
 
33203
33204
  // src/components/premium-modals/energy/types.ts
@@ -37605,14 +37606,14 @@ var DeviceReportModal = class {
37605
37606
  // Header: "Relatório - <identifier> - <label>" + nome do device (sutil, com copiar).
37606
37607
  // O customer já aparece no footer premium. Texto escapado — o shell usa innerHTML no título.
37607
37608
  buildHeaderTitleHTML() {
37608
- const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
37609
- const base = esc12(
37609
+ const esc13 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
37610
+ const base = esc13(
37610
37611
  `Relat\xF3rio - ${this.params.identifier || "SEM IDENTIFICADOR"} - ${this.params.label || "SEM ETIQUETA"}`
37611
37612
  );
37612
37613
  const deviceName = String(this.params.deviceName || "").trim();
37613
37614
  const deviceHTML = deviceName ? `<span class="myio-dr-devname" style="margin-left:10px;font-size:0.72em;font-weight:400;opacity:.75;display:inline-flex;align-items:center;gap:4px;vertical-align:middle;">
37614
- ${esc12(deviceName)}
37615
- <button type="button" class="myio-dr-copy" data-copy="${esc12(deviceName)}" title="Copiar nome do dispositivo"
37615
+ ${esc13(deviceName)}
37616
+ <button type="button" class="myio-dr-copy" data-copy="${esc13(deviceName)}" title="Copiar nome do dispositivo"
37616
37617
  aria-label="Copiar nome do dispositivo"
37617
37618
  style="border:none;background:transparent;color:inherit;cursor:pointer;padding:0 2px;line-height:1;opacity:.9;display:inline-flex;">
37618
37619
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
@@ -63388,6 +63389,300 @@ var ExclusionGroupsTab = class {
63388
63389
  }
63389
63390
  };
63390
63391
 
63392
+ // src/components/pricing-panel/tariffApiClient.ts
63393
+ function toDeviceSummary(d) {
63394
+ const s = (v) => typeof v === "string" && v ? v : void 0;
63395
+ const x = d || {};
63396
+ return {
63397
+ id: String(x.id ?? ""),
63398
+ customerId: s(x.customerId),
63399
+ name: String(x.name ?? x.label ?? x.id ?? ""),
63400
+ label: s(x.label) || s(x.displayName),
63401
+ identifier: s(x.identifier),
63402
+ deviceProfile: s(x.deviceProfile) || s(x.deviceType),
63403
+ tariffCategory: s(x.tariffCategory) ?? null
63404
+ };
63405
+ }
63406
+ function categoryKeyFromLabel(label) {
63407
+ let k = String(label || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
63408
+ if (!k) return "";
63409
+ if (!/^[A-Z]/.test(k)) k = `CAT_${k}`;
63410
+ k = k.slice(0, 40).replace(/_+$/g, "");
63411
+ return k.length >= 2 ? k : "";
63412
+ }
63413
+ var TariffApiError = class extends Error {
63414
+ code;
63415
+ status;
63416
+ details;
63417
+ currentVersion;
63418
+ constructor(code, status, message, details) {
63419
+ super(message || code);
63420
+ this.name = "TariffApiError";
63421
+ this.code = code;
63422
+ this.status = status;
63423
+ this.details = details;
63424
+ const cv = details && details.currentVersion;
63425
+ this.currentVersion = typeof cv === "number" ? cv : void 0;
63426
+ }
63427
+ };
63428
+ function joinUrl(baseUrl, basePath, path) {
63429
+ const b = baseUrl.replace(/\/+$/, "");
63430
+ const bp = basePath ? `/${basePath.replace(/^\/+|\/+$/g, "")}` : "";
63431
+ const p = path.startsWith("/") ? path : `/${path}`;
63432
+ return `${b}${bp}${p}`;
63433
+ }
63434
+ function tariffQuery(sel, granularity) {
63435
+ const qs = new URLSearchParams();
63436
+ qs.set("domain", sel.domain);
63437
+ qs.set("category", sel.category);
63438
+ qs.set("year", String(sel.year));
63439
+ if (granularity) qs.set("granularity", granularity);
63440
+ return qs.toString();
63441
+ }
63442
+ function unwrapGcdrEnvelope(body) {
63443
+ if (body && typeof body === "object" && !Array.isArray(body)) {
63444
+ const b = body;
63445
+ if (b.success === true && b.data && typeof b.data === "object") return b.data;
63446
+ }
63447
+ return body;
63448
+ }
63449
+ function parseETagVersion(headers) {
63450
+ const raw = headers.get("ETag") || headers.get("etag");
63451
+ if (!raw) return void 0;
63452
+ const m = /"?(-?\d+)"?/.exec(raw);
63453
+ return m ? Number(m[1]) : void 0;
63454
+ }
63455
+ var TariffApiClient = class {
63456
+ cfg;
63457
+ fetchImpl;
63458
+ basePath;
63459
+ constructor(config2) {
63460
+ if (!config2 || !config2.baseUrl) {
63461
+ throw new Error("TariffApiClient requires a baseUrl.");
63462
+ }
63463
+ this.cfg = config2;
63464
+ const injected = config2.fetchImpl || globalThis.fetch;
63465
+ if (typeof injected !== "function") {
63466
+ throw new Error("TariffApiClient requires a fetch implementation.");
63467
+ }
63468
+ this.fetchImpl = config2.fetchImpl ? config2.fetchImpl : injected.bind(globalThis);
63469
+ this.basePath = config2.basePath ?? "api/v1";
63470
+ }
63471
+ authHeaders() {
63472
+ const h3 = {};
63473
+ if (this.cfg.apiKey) h3["X-API-Key"] = this.cfg.apiKey;
63474
+ if (this.cfg.jwt) h3["Authorization"] = `Bearer ${this.cfg.jwt}`;
63475
+ if (this.cfg.tenantId) h3["X-Tenant-Id"] = this.cfg.tenantId;
63476
+ return h3;
63477
+ }
63478
+ /**
63479
+ * Tariff categories: globals (`customerId` null) + the customer's own, ordered
63480
+ * by `sortOrder`, then `key` (server order is kept). `includeInactive` defaults
63481
+ * to `true` so existing tariffs of an inactive category still get a label.
63482
+ */
63483
+ async listCategories(customerId, opts = {}) {
63484
+ const qs = new URLSearchParams();
63485
+ if (customerId) qs.set("customerId", customerId);
63486
+ qs.set("includeInactive", String(opts.includeInactive ?? true));
63487
+ const url = joinUrl(this.cfg.baseUrl, this.basePath, `/tariff-categories?${qs.toString()}`);
63488
+ const res = await this.fetchImpl(url, {
63489
+ method: "GET",
63490
+ headers: { Accept: "application/json", ...this.authHeaders() }
63491
+ });
63492
+ const body = await this.readBody(res);
63493
+ if (!res.ok) throw this.toError(res, body);
63494
+ const data = unwrapGcdrEnvelope(body);
63495
+ const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : null;
63496
+ if (!items) throw new TariffApiError("TARIFF_CATEGORIES_INVALID_RESPONSE", res.status, "Resposta sem items");
63497
+ return items.filter((c) => c && typeof c.key === "string" && c.key);
63498
+ }
63499
+ // -------------------------------------------------------------------------
63500
+ // RFC-0081 — gestão de categorias (escrita) + classificação de devices
63501
+ // -------------------------------------------------------------------------
63502
+ /** POST /tariff-categories — cria (key imutável depois). */
63503
+ async createCategory(input) {
63504
+ return await this.json("POST", "/tariff-categories", input);
63505
+ }
63506
+ /** PATCH /tariff-categories/:key — label / description / sortOrder / isActive. */
63507
+ async updateCategory(key, patch) {
63508
+ return await this.json("PATCH", `/tariff-categories/${encodeURIComponent(key)}`, patch);
63509
+ }
63510
+ /** GET /tariff-categories/:key/usage — quantos devices e tarifas usam a categoria. */
63511
+ async getCategoryUsage(key) {
63512
+ const u = await this.json("GET", `/tariff-categories/${encodeURIComponent(key)}/usage`);
63513
+ return {
63514
+ devices: Number(u?.devices ?? 0),
63515
+ tariffs: Number(u?.tariffs ?? 0),
63516
+ customers: Array.isArray(u?.customers) ? u.customers : []
63517
+ };
63518
+ }
63519
+ /**
63520
+ * DELETE /tariff-categories/:key. Em uso (devices/tarifas) o GCDR responde 409
63521
+ * TARIFF_CATEGORY_IN_USE; com `cascade: true` (o usuário já confirmou a perda)
63522
+ * pede ao GCDR para apagar as tarifas e tirar a categoria dos devices.
63523
+ */
63524
+ async deleteCategory(key, opts = {}) {
63525
+ const qs = opts.cascade ? "?cascade=true" : "";
63526
+ await this.json("DELETE", `/tariff-categories/${encodeURIComponent(key)}${qs}`);
63527
+ }
63528
+ /** GET /devices?customerId= (paginado) — devices do customer com a categoria atual. */
63529
+ async listCustomerDevices(customerId, opts = {}) {
63530
+ const pageSize = opts.pageSize ?? 100;
63531
+ const maxPages = opts.maxPages ?? 50;
63532
+ const out = [];
63533
+ let cursor;
63534
+ for (let page = 0; page < maxPages; page++) {
63535
+ const qs = new URLSearchParams({ customerId, limit: String(pageSize) });
63536
+ if (cursor) qs.set("cursor", cursor);
63537
+ const data = await this.json("GET", `/devices?${qs.toString()}`);
63538
+ const items = Array.isArray(data) ? data : data?.items || [];
63539
+ for (const d of items) out.push(toDeviceSummary(d));
63540
+ const pg = Array.isArray(data) ? void 0 : data?.pagination || data;
63541
+ if (!pg?.hasMore || !pg?.nextCursor) break;
63542
+ cursor = String(pg.nextCursor);
63543
+ }
63544
+ return out;
63545
+ }
63546
+ /** GET /devices/:id — resumo com a categoria atual. */
63547
+ async getDevice(deviceId) {
63548
+ return toDeviceSummary(await this.json("GET", `/devices/${encodeURIComponent(deviceId)}`));
63549
+ }
63550
+ /** PATCH /devices/:id { tariffCategory } — `null` tira o device de qualquer categoria. */
63551
+ async setDeviceCategory(deviceId, key) {
63552
+ const d = await this.json("PATCH", `/devices/${encodeURIComponent(deviceId)}`, { tariffCategory: key });
63553
+ return toDeviceSummary(d);
63554
+ }
63555
+ /** Chamada JSON genérica (envelope GCDR desembrulhado; erro → TariffApiError). */
63556
+ async json(method, path, body) {
63557
+ const url = joinUrl(this.cfg.baseUrl, this.basePath, path);
63558
+ const headers = { Accept: "application/json", ...this.authHeaders() };
63559
+ if (body !== void 0) headers["Content-Type"] = "application/json";
63560
+ const res = await this.fetchImpl(url, {
63561
+ method,
63562
+ headers,
63563
+ body: body === void 0 ? void 0 : JSON.stringify(body)
63564
+ });
63565
+ if (res.status === 204) return null;
63566
+ const parsed = await this.readBody(res);
63567
+ if (!res.ok) throw this.toError(res, parsed);
63568
+ return unwrapGcdrEnvelope(parsed);
63569
+ }
63570
+ /** Read the tariff tree. `granularity` defaults to `day` server-side. */
63571
+ async getTariff(sel, granularity = "hour") {
63572
+ const url = joinUrl(
63573
+ this.cfg.baseUrl,
63574
+ this.basePath,
63575
+ `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel, granularity)}`
63576
+ );
63577
+ const res = await this.fetchImpl(url, {
63578
+ method: "GET",
63579
+ headers: { Accept: "application/json", ...this.authHeaders() }
63580
+ });
63581
+ const body = await this.readBody(res);
63582
+ if (!res.ok) throw this.toError(res, body);
63583
+ const etagVersion = parseETagVersion(res.headers);
63584
+ const parsed = unwrapGcdrEnvelope(body) || {};
63585
+ return {
63586
+ customerId: sel.customerId,
63587
+ domain: sel.domain,
63588
+ category: sel.category,
63589
+ year: sel.year,
63590
+ unit: parsed.unit,
63591
+ currency: parsed.currency,
63592
+ tariffModel: parsed.tariffModel,
63593
+ timezone: parsed.timezone,
63594
+ version: typeof parsed.version === "number" ? parsed.version : etagVersion ?? 0,
63595
+ tree: parsed.tree || {}
63596
+ };
63597
+ }
63598
+ /** REPLACE the whole year with a nested price tree. */
63599
+ async putTariff(sel, tree, expectedVersion) {
63600
+ return this.write("PUT", sel, { ...tree, ...guardBody(expectedVersion) }, expectedVersion);
63601
+ }
63602
+ /** MERGE sparse buckets into the year (finest level wins). */
63603
+ async patchTariff(sel, buckets, expectedVersion) {
63604
+ return this.write("PATCH", sel, { buckets, ...guardBody(expectedVersion) }, expectedVersion);
63605
+ }
63606
+ /**
63607
+ * DELETE the whole year (no `bucket`) or one sub-bucket (`bucket` present).
63608
+ * Whole-year delete is idempotent (204 even if absent).
63609
+ */
63610
+ async deleteTariff(sel, opts = {}) {
63611
+ const hasBody = Boolean(opts.bucket) || typeof opts.expectedVersion === "number";
63612
+ const url = joinUrl(
63613
+ this.cfg.baseUrl,
63614
+ this.basePath,
63615
+ `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
63616
+ );
63617
+ const headers = { Accept: "application/json", ...this.authHeaders() };
63618
+ if (typeof opts.expectedVersion === "number") headers["If-Match"] = `"${opts.expectedVersion}"`;
63619
+ const init = { method: "DELETE", headers };
63620
+ if (hasBody) {
63621
+ headers["Content-Type"] = "application/json";
63622
+ init.body = JSON.stringify({
63623
+ ...opts.bucket ? { bucket: opts.bucket } : {},
63624
+ ...guardBody(opts.expectedVersion)
63625
+ });
63626
+ }
63627
+ const res = await this.fetchImpl(url, init);
63628
+ if (res.status === 204) return {};
63629
+ const body = await this.readBody(res);
63630
+ if (!res.ok) throw this.toError(res, body);
63631
+ const etagVersion = parseETagVersion(res.headers);
63632
+ const data = unwrapGcdrEnvelope(body);
63633
+ const v = (data && data.version) ?? etagVersion;
63634
+ return typeof v === "number" ? { version: v } : {};
63635
+ }
63636
+ async write(method, sel, body, expectedVersion) {
63637
+ const url = joinUrl(
63638
+ this.cfg.baseUrl,
63639
+ this.basePath,
63640
+ `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
63641
+ );
63642
+ const headers = {
63643
+ Accept: "application/json",
63644
+ "Content-Type": "application/json",
63645
+ ...this.authHeaders()
63646
+ };
63647
+ if (typeof expectedVersion === "number") headers["If-Match"] = `"${expectedVersion}"`;
63648
+ const res = await this.fetchImpl(url, { method, headers, body: JSON.stringify(body) });
63649
+ const parsed = await this.readBody(res);
63650
+ if (!res.ok) throw this.toError(res, parsed);
63651
+ const etagVersion = parseETagVersion(res.headers);
63652
+ const data = unwrapGcdrEnvelope(parsed);
63653
+ const v = (data && data.version) ?? etagVersion;
63654
+ return { version: typeof v === "number" ? v : (expectedVersion ?? 0) + 1 };
63655
+ }
63656
+ async readBody(res) {
63657
+ try {
63658
+ const text2 = await res.text();
63659
+ if (!text2) return null;
63660
+ return JSON.parse(text2);
63661
+ } catch {
63662
+ return null;
63663
+ }
63664
+ }
63665
+ toError(res, body) {
63666
+ const err = body && body.error;
63667
+ if (err && typeof err === "object") {
63668
+ const e = err;
63669
+ return new TariffApiError(
63670
+ e.code || `HTTP_${res.status}`,
63671
+ res.status,
63672
+ e.message,
63673
+ e.details
63674
+ );
63675
+ }
63676
+ return new TariffApiError(`HTTP_${res.status}`, res.status, res.statusText);
63677
+ }
63678
+ };
63679
+ function guardBody(expectedVersion) {
63680
+ return typeof expectedVersion === "number" ? { expectedVersion } : {};
63681
+ }
63682
+ function createTariffApiClient(config2) {
63683
+ return new TariffApiClient(config2);
63684
+ }
63685
+
63391
63686
  // src/components/premium-modals/settings/device-profile/DeviceProfileTab.ts
63392
63687
  var TB_NULL_CUSTOMER_ID = "13814000-1dd2-11b2-8080-808080808080";
63393
63688
  var STYLES_ID3 = "dpt-styles";
@@ -63437,6 +63732,7 @@ var DeviceProfileTab = class {
63437
63732
  ownerName = null;
63438
63733
  deviceProfileOptions = null;
63439
63734
  customerOptions = null;
63735
+ tariff = { status: "loading", current: null, categories: [] };
63440
63736
  constructor(config2) {
63441
63737
  this.config = config2;
63442
63738
  }
@@ -63459,7 +63755,74 @@ var DeviceProfileTab = class {
63459
63755
  this.entity = entity;
63460
63756
  this.attributes = attributes;
63461
63757
  const customerId = entity?.customerId?.id;
63462
- this.ownerName = customerId && customerId !== TB_NULL_CUSTOMER_ID ? await this.fetchCustomerName(customerId) : null;
63758
+ const [ownerName] = await Promise.all([
63759
+ customerId && customerId !== TB_NULL_CUSTOMER_ID ? this.fetchCustomerName(customerId) : Promise.resolve(null),
63760
+ this.loadTariffCategory()
63761
+ ]);
63762
+ this.ownerName = ownerName;
63763
+ }
63764
+ // ---- Categoria de tarifa (GCDR RFC-0081) ----------------------------------
63765
+ gcdrClient() {
63766
+ const g = this.config.gcdr;
63767
+ if (!g?.baseUrl || !g.apiKey && !g.tenantId) return null;
63768
+ return new TariffApiClient({
63769
+ baseUrl: String(g.baseUrl).replace(/\/api\/v1\/?$/, ""),
63770
+ apiKey: g.apiKey,
63771
+ tenantId: g.tenantId
63772
+ });
63773
+ }
63774
+ gcdrDeviceId() {
63775
+ return String(this.config.gcdr?.deviceId || this.attrValue("gcdrDeviceId") || "").trim();
63776
+ }
63777
+ /** Categoria atual do device + categorias do customer (globais + próprias) no GCDR. */
63778
+ async loadTariffCategory() {
63779
+ const client = this.gcdrClient();
63780
+ const id = this.gcdrDeviceId();
63781
+ if (!client) {
63782
+ this.tariff = { status: "unavailable", current: null, categories: [], message: "GCDR n\xE3o configurado no dashboard" };
63783
+ return;
63784
+ }
63785
+ if (!id) {
63786
+ this.tariff = { status: "unavailable", current: null, categories: [], message: "Device sem gcdrDeviceId" };
63787
+ return;
63788
+ }
63789
+ try {
63790
+ const device = await client.getDevice(id);
63791
+ const categories = device.customerId ? await client.listCategories(device.customerId, { includeInactive: true }) : [];
63792
+ this.tariff = { status: "ok", current: device.tariffCategory, categories };
63793
+ } catch (e) {
63794
+ const code = e?.code;
63795
+ this.tariff = {
63796
+ status: "error",
63797
+ current: null,
63798
+ categories: [],
63799
+ message: `N\xE3o foi poss\xEDvel ler o GCDR${code ? ` (${code})` : ""}`
63800
+ };
63801
+ }
63802
+ }
63803
+ tariffCategoryLabel(key) {
63804
+ if (!key) return "\u2014 sem categoria \u2014";
63805
+ const c = this.tariff.categories.find((x) => x.key === key);
63806
+ return c ? `${c.label}${c.isActive === false ? " (inativa)" : ""}` : key;
63807
+ }
63808
+ renderTariffCategoryRow() {
63809
+ const t = this.tariff;
63810
+ if (t.status !== "ok") {
63811
+ const text2 = t.status === "loading" ? "Carregando\u2026" : t.message || "\u2014";
63812
+ return `
63813
+ <div class="dpt-row" data-field="tariffCategory">
63814
+ <span class="dpt-label">Categoria de tarifa</span>
63815
+ <span class="dpt-value dpt-muted" data-testid="dpt-tariff-category">${this.esc(text2)}</span>
63816
+ </div>`;
63817
+ }
63818
+ return `
63819
+ <div class="dpt-row dpt-row--editable" data-field="tariffCategory" data-kind="tariff-category">
63820
+ <span class="dpt-label">Categoria de tarifa</span>
63821
+ <span class="dpt-value-wrap">
63822
+ <span class="dpt-value" data-view data-testid="dpt-tariff-category">${this.esc(this.tariffCategoryLabel(t.current))}</span>
63823
+ <button type="button" class="dpt-icon-btn" data-action="edit" title="Alterar categoria">\u270F\uFE0F</button>
63824
+ </span>
63825
+ </div>`;
63463
63826
  }
63464
63827
  async fetchEntity() {
63465
63828
  try {
@@ -63763,6 +64126,7 @@ var DeviceProfileTab = class {
63763
64126
  <div class="dpt-section">
63764
64127
  <div class="dpt-section-title">Classifica\xE7\xE3o (atributos da aplica\xE7\xE3o)</div>
63765
64128
  <div class="dpt-card">
64129
+ ${this.renderTariffCategoryRow()}
63766
64130
  ${editableAttrRows}
63767
64131
  ${ingestionRow}
63768
64132
  ${readonlyRows}
@@ -63834,7 +64198,20 @@ var DeviceProfileTab = class {
63834
64198
  async beginEdit(row, field, kind) {
63835
64199
  const wrap = row.querySelector(".dpt-value-wrap");
63836
64200
  if (!wrap) return;
63837
- if (kind === "entity-profile") {
64201
+ if (kind === "tariff-category") {
64202
+ const current = this.tariff.current;
64203
+ const options = this.tariff.categories.filter((c) => c.isActive !== false || c.key === current);
64204
+ wrap.innerHTML = this.editorHtml(
64205
+ `<select class="dpt-input" data-edit data-testid="dpt-tariff-category-select">
64206
+ <option value="" ${current ? "" : "selected"}>\u2014 sem categoria \u2014</option>
64207
+ ${options.map(
64208
+ (c) => `<option value="${this.esc(c.key)}" ${c.key === current ? "selected" : ""}>${this.esc(
64209
+ c.label + (c.isActive === false ? " (inativa)" : "")
64210
+ )}</option>`
64211
+ ).join("")}
64212
+ </select>`
64213
+ );
64214
+ } else if (kind === "entity-profile") {
63838
64215
  const options = await this.fetchDeviceProfileOptions();
63839
64216
  const currentId = this.entity?.deviceProfileId?.id || "";
63840
64217
  wrap.innerHTML = this.editorHtml(
@@ -63875,7 +64252,12 @@ var DeviceProfileTab = class {
63875
64252
  const saveBtn = row.querySelector('button[data-action="save"]');
63876
64253
  if (saveBtn) saveBtn.disabled = true;
63877
64254
  try {
63878
- if (kind === "entity-label") {
64255
+ if (kind === "tariff-category") {
64256
+ const client = this.gcdrClient();
64257
+ if (!client) throw new Error("GCDR n\xE3o configurado.");
64258
+ const updated = await client.setDeviceCategory(this.gcdrDeviceId(), value || null);
64259
+ this.tariff = { ...this.tariff, current: updated.id ? updated.tariffCategory : value || null };
64260
+ } else if (kind === "entity-label") {
63879
64261
  await this.saveEntityField({ label: value });
63880
64262
  } else if (kind === "entity-profile") {
63881
64263
  if (!value) throw new Error("Selecione um Device Profile.");
@@ -63922,6 +64304,7 @@ var DeviceProfileTab = class {
63922
64304
  .dpt-value { font-size: 13px; color: #111827; text-align: right; word-break: break-word; }
63923
64305
  .dpt-value-wrap { display: flex; align-items: center; gap: 6px; }
63924
64306
  .dpt-rel { color: #9ca3af; font-size: 12px; }
64307
+ .dpt-muted { color: #9ca3af; font-size: 12px; }
63925
64308
  .dpt-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
63926
64309
  .dpt-empty { padding: 16px 0; text-align: center; color: #9ca3af; font-size: 13px; }
63927
64310
  .dpt-icon-btn {
@@ -66945,11 +67328,19 @@ var SettingsModalView = class _SettingsModalView {
66945
67328
  return;
66946
67329
  }
66947
67330
  try {
67331
+ const orch = window.MyIOOrchestrator || {};
67332
+ const cfg = this.config;
66948
67333
  this.deviceProfileTab = new DeviceProfileTab({
66949
67334
  container,
66950
67335
  deviceId,
66951
67336
  jwtToken,
66952
- tbBaseUrl: tbBaseUrl ?? window.location.origin
67337
+ tbBaseUrl: tbBaseUrl ?? window.location.origin,
67338
+ gcdr: {
67339
+ baseUrl: cfg.gcdrApiBaseUrl || orch.gcdrApiBaseUrl || "https://gcdr-api.a.myio-bas.com",
67340
+ apiKey: cfg.gcdrApiKey || orch.gcdrApiKey,
67341
+ tenantId: cfg.gcdrTenantId || orch.gcdrTenantId,
67342
+ deviceId: this.config.gcdrDeviceId
67343
+ }
66953
67344
  });
66954
67345
  await this.deviceProfileTab.init();
66955
67346
  console.log("[SettingsModalView] DeviceProfileTab initialized");
@@ -67556,8 +67947,8 @@ var SettingsModalView = class _SettingsModalView {
67556
67947
  twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
67557
67948
  twinNote.hidden = false;
67558
67949
  }
67559
- const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67560
- const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc12(v)}"${v === selected ? " selected" : ""}>${esc12(v)}</option>`).join("");
67950
+ const esc13 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67951
+ const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc13(v)}"${v === selected ? " selected" : ""}>${esc13(v)}</option>`).join("");
67561
67952
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
67562
67953
  const savedSegment = String(saved.segment || "");
67563
67954
  const savedActivity = String(saved.activity || "");
@@ -74104,7 +74495,7 @@ var WelcomeModalView = class _WelcomeModalView {
74104
74495
  if (this.metaTipEl) this.metaTipEl.style.display = "none";
74105
74496
  }
74106
74497
  buildMetaTipHtml(type, card) {
74107
- const esc12 = _WelcomeModalView.escapeMetaHtml;
74498
+ const esc13 = _WelcomeModalView.escapeMetaHtml;
74108
74499
  const chip = _WelcomeModalView.metaChip;
74109
74500
  const meta = card.metaCounts || {};
74110
74501
  const details = card.metaDetails || {};
@@ -74114,7 +74505,7 @@ var WelcomeModalView = class _WelcomeModalView {
74114
74505
  ).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
74115
74506
  const frame = (icon2, label, body) => `<div class="myio-welcome-meta-tip__header">
74116
74507
  <span class="myio-welcome-meta-tip__icon">${icon2}</span>
74117
- <span class="myio-welcome-meta-tip__title">${label} (${esc12(card.title)})</span>
74508
+ <span class="myio-welcome-meta-tip__title">${label} (${esc13(card.title)})</span>
74118
74509
  <span class="myio-welcome-meta-tip__timestamp">${stamp}</span>
74119
74510
  <button type="button" class="myio-welcome-meta-tip__close" title="Fechar">\u2715</button>
74120
74511
  </div>
@@ -74142,8 +74533,8 @@ var WelcomeModalView = class _WelcomeModalView {
74142
74533
  const chips = Object.entries(byState).map(([s, n]) => chip(`${s}: ${n}`)).join("");
74143
74534
  const rows = alarms.slice(0, 10).map(
74144
74535
  (a) => row(
74145
- esc12(a.deviceName ? `${a.deviceName} \u2014 ${a.title || "Alarme"}` : a.title || "Alarme"),
74146
- [a.severity, a.state].filter(Boolean).map(esc12).join(" \xB7 ")
74536
+ esc13(a.deviceName ? `${a.deviceName} \u2014 ${a.title || "Alarme"}` : a.title || "Alarme"),
74537
+ [a.severity, a.state].filter(Boolean).map(esc13).join(" \xB7 ")
74147
74538
  )
74148
74539
  ).join("");
74149
74540
  return frame(
@@ -74167,7 +74558,7 @@ var WelcomeModalView = class _WelcomeModalView {
74167
74558
  const rows = annotations.slice(0, 10).map((a) => {
74168
74559
  const when = a.createdAt ? new Date(a.createdAt).toLocaleDateString("pt-BR") : "";
74169
74560
  const text2 = a.text.length > 90 ? `${a.text.slice(0, 90)}\u2026` : a.text;
74170
- return row(esc12(a.deviceLabel || "Dispositivo"), `${esc12(text2)}${when ? ` \xB7 ${esc12(when)}` : ""}`);
74561
+ return row(esc13(a.deviceLabel || "Dispositivo"), `${esc13(text2)}${when ? ` \xB7 ${esc13(when)}` : ""}`);
74171
74562
  }).join("");
74172
74563
  return frame(
74173
74564
  "\u{1F4CB}",
@@ -74178,7 +74569,7 @@ var WelcomeModalView = class _WelcomeModalView {
74178
74569
  if (type === "users") {
74179
74570
  if (meta.users === null) return frame("\u{1F465}", "Usu\xE1rios", loadingBody);
74180
74571
  const users = details.users || [];
74181
- const rows = users.slice(0, 10).map((u) => row(esc12(u.name), esc12(u.email || ""))).join("");
74572
+ const rows = users.slice(0, 10).map((u) => row(esc13(u.name), esc13(u.email || ""))).join("");
74182
74573
  return frame(
74183
74574
  "\u{1F465}",
74184
74575
  "Usu\xE1rios",
@@ -104213,19 +104604,19 @@ function _updateCoverageHint(topDoc) {
104213
104604
  const deviceCount = data.granularity === "DEVICE" ? data.devices?.length ?? 0 : 0;
104214
104605
  hint.textContent = `\u26A0 Meta incompleta para este dom\xEDnio/ano` + (deviceCount > 0 ? ` \xB7 Por medidor (${deviceCount})` : "") + ` \u2014 passe o mouse para detalhes`;
104215
104606
  tabs.insertAdjacentElement("afterend", hint);
104216
- const esc12 = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
104607
+ const esc13 = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
104217
104608
  try {
104218
104609
  _coverageDetach = InfoTooltip.attach(hint, () => {
104219
104610
  const d = _getGoalsData(_currentDomain);
104220
104611
  const parts = [];
104221
104612
  if (hasCoverageGaps(d?.coverageGaps)) {
104222
- parts.push(`<p style="margin:0 0 8px;">${esc12(buildCoverageWarningTextPtBR(d?.coverageGaps, "GERAL"))}</p>`);
104613
+ parts.push(`<p style="margin:0 0 8px;">${esc13(buildCoverageWarningTextPtBR(d?.coverageGaps, "GERAL"))}</p>`);
104223
104614
  }
104224
104615
  (d?.devices || []).forEach((dev) => {
104225
104616
  if (!hasCoverageGaps(dev?.coverageGaps)) return;
104226
104617
  const label = dev.label || dev.code || "medidor";
104227
104618
  parts.push(
104228
- `<p style="margin:0 0 8px;">${esc12(buildCoverageWarningTextPtBR(dev.coverageGaps, `do medidor ${label}`))}</p>`
104619
+ `<p style="margin:0 0 8px;">${esc13(buildCoverageWarningTextPtBR(dev.coverageGaps, `do medidor ${label}`))}</p>`
104229
104620
  );
104230
104621
  });
104231
104622
  return {
@@ -107345,10 +107736,10 @@ var DOMAIN_LABEL = {
107345
107736
  energy: "Energia",
107346
107737
  water: "\xC1gua"
107347
107738
  };
107348
- var CATEGORY_LABEL = {
107349
- lojas: "Lojas",
107350
- area_comum: "\xC1rea Comum"
107351
- };
107739
+ function categoryLabel(key, categories) {
107740
+ const hit = (categories || []).find((c) => c.key === key);
107741
+ return hit?.label || String(key ?? "");
107742
+ }
107352
107743
  function unitLabel(domain) {
107353
107744
  return domain === "water" ? "R$/m\xB3" : "R$/kWh";
107354
107745
  }
@@ -107507,7 +107898,7 @@ function removeEntryByBounds(entries, target, opts = {}) {
107507
107898
  }
107508
107899
  function computePricingKpis(entries, opts = {}) {
107509
107900
  const periodsByDomain = { energy: 0, water: 0 };
107510
- const periodsByCategory = { lojas: 0, area_comum: 0 };
107901
+ const periodsByCategory = {};
107511
107902
  let energySum = 0;
107512
107903
  let energyN = 0;
107513
107904
  let waterSum = 0;
@@ -107528,7 +107919,7 @@ function computePricingKpis(entries, opts = {}) {
107528
107919
  combos.add(`${e.customerId}|${e.domain}|${e.category}`);
107529
107920
  }
107530
107921
  const covered = combos.size;
107531
- const total = opts.customerCount ? opts.customerCount * 4 : covered;
107922
+ const total = opts.customerCount && opts.categoryCount ? opts.customerCount * 2 * opts.categoryCount : covered;
107532
107923
  return {
107533
107924
  totalPeriods: entries.length,
107534
107925
  periodsByDomain,
@@ -107583,6 +107974,36 @@ var PRICING_PANEL_CSS = `
107583
107974
  .myio-pricing.show .myio-pricing__content {
107584
107975
  transform: translateY(0) scale(1);
107585
107976
  }
107977
+ /* di\xE1logo de confirma\xE7\xE3o montado acima do conte\xFAdo do painel */
107978
+ .myio-pricing__dialog-host { position: relative; z-index: 5; }
107979
+ .myio-pricing__dialog-host .myio-dialog-overlay { z-index: 5; }
107980
+ /* aba Categorias */
107981
+ .myio-pricing__cat { display: flex; flex-direction: column; gap: 10px; }
107982
+ .myio-pricing__cat-hint { margin: 0; font-size: 12px; color: var(--myio-text-muted, #6b7280); }
107983
+ .myio-pricing__cat-new, .myio-pricing__cat-devbar { display: flex; gap: 8px; align-items: center; }
107984
+ .myio-pricing__cat-new .myio-pricing__input, .myio-pricing__cat-devbar .myio-pricing__input { flex: 1; }
107985
+ .myio-pricing__cat-btn { width: auto; padding: 8px 14px; white-space: nowrap; }
107986
+ .myio-pricing__cat-notice { font-size: 12.5px; border-radius: 8px; padding: 8px 10px; }
107987
+ .myio-pricing__cat-notice--ok { background: #ecfdf5; color: #065f46; }
107988
+ .myio-pricing__cat-notice--error { background: #fee2e2; color: #991b1b; }
107989
+ .myio-pricing__cat-item { list-style: none; border: 1px solid var(--myio-border, #e5e7eb); border-radius: 10px; padding: 8px 10px; margin-bottom: 8px; }
107990
+ .myio-pricing__cat-row { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; }
107991
+ .myio-pricing__cat-main { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
107992
+ .myio-pricing__cat-key { color: var(--myio-text-muted, #6b7280); font-size: 11px; }
107993
+ .myio-pricing__badge--off { background: #f3f4f6 !important; color: #6b7280 !important; }
107994
+ .myio-pricing__cat-actions { display: flex; gap: 6px; flex-wrap: wrap; }
107995
+ .myio-pricing__cat-actions button {
107996
+ font: inherit; font-size: 12px; padding: 5px 10px; border-radius: 6px; cursor: pointer;
107997
+ border: 1px solid var(--myio-border, #d1d5db); background: var(--myio-card, #fff); color: var(--myio-text, #1f2937);
107998
+ }
107999
+ .myio-pricing__cat-actions button:disabled { opacity: 0.5; cursor: default; }
108000
+ .myio-pricing__cat-actions .myio-pricing__cat-danger { color: #b91c1c; border-color: #fca5a5; }
108001
+ .myio-pricing__cat-devices { margin-top: 10px; display: flex; flex-direction: column; gap: 8px; }
108002
+ .myio-pricing__cat-devlist { list-style: none; margin: 0; padding: 0; max-height: 260px; overflow: auto; }
108003
+ .myio-pricing__cat-devlist li { padding: 4px 2px; font-size: 13px; }
108004
+ .myio-pricing__cat-devlist label { display: flex; gap: 8px; align-items: center; cursor: pointer; flex-wrap: wrap; }
108005
+ .myio-pricing__cat-devlist small { color: var(--myio-text-muted, #6b7280); font-size: 11px; }
108006
+ .myio-pricing__cat-other { color: #92400e !important; }
107586
108007
  .myio-pricing__header {
107587
108008
  display: flex;
107588
108009
  align-items: center;
@@ -107895,188 +108316,6 @@ function injectPricingPanelStyles(doc) {
107895
108316
  doc.head.appendChild(style);
107896
108317
  }
107897
108318
 
107898
- // src/components/pricing-panel/tariffApiClient.ts
107899
- var TariffApiError = class extends Error {
107900
- code;
107901
- status;
107902
- details;
107903
- currentVersion;
107904
- constructor(code, status, message, details) {
107905
- super(message || code);
107906
- this.name = "TariffApiError";
107907
- this.code = code;
107908
- this.status = status;
107909
- this.details = details;
107910
- const cv = details && details.currentVersion;
107911
- this.currentVersion = typeof cv === "number" ? cv : void 0;
107912
- }
107913
- };
107914
- function joinUrl(baseUrl, basePath, path) {
107915
- const b = baseUrl.replace(/\/+$/, "");
107916
- const bp = basePath ? `/${basePath.replace(/^\/+|\/+$/g, "")}` : "";
107917
- const p = path.startsWith("/") ? path : `/${path}`;
107918
- return `${b}${bp}${p}`;
107919
- }
107920
- function tariffQuery(sel, granularity) {
107921
- const qs = new URLSearchParams();
107922
- qs.set("domain", sel.domain);
107923
- qs.set("category", sel.category);
107924
- qs.set("year", String(sel.year));
107925
- if (granularity) qs.set("granularity", granularity);
107926
- return qs.toString();
107927
- }
107928
- function unwrapGcdrEnvelope(body) {
107929
- if (body && typeof body === "object" && !Array.isArray(body)) {
107930
- const b = body;
107931
- if (b.success === true && b.data && typeof b.data === "object") return b.data;
107932
- }
107933
- return body;
107934
- }
107935
- function parseETagVersion(headers) {
107936
- const raw = headers.get("ETag") || headers.get("etag");
107937
- if (!raw) return void 0;
107938
- const m = /"?(-?\d+)"?/.exec(raw);
107939
- return m ? Number(m[1]) : void 0;
107940
- }
107941
- var TariffApiClient = class {
107942
- cfg;
107943
- fetchImpl;
107944
- basePath;
107945
- constructor(config2) {
107946
- if (!config2 || !config2.baseUrl) {
107947
- throw new Error("TariffApiClient requires a baseUrl.");
107948
- }
107949
- this.cfg = config2;
107950
- const injected = config2.fetchImpl || globalThis.fetch;
107951
- if (typeof injected !== "function") {
107952
- throw new Error("TariffApiClient requires a fetch implementation.");
107953
- }
107954
- this.fetchImpl = config2.fetchImpl ? config2.fetchImpl : injected.bind(globalThis);
107955
- this.basePath = config2.basePath ?? "api/v1";
107956
- }
107957
- authHeaders() {
107958
- const h3 = {};
107959
- if (this.cfg.apiKey) h3["X-API-Key"] = this.cfg.apiKey;
107960
- if (this.cfg.jwt) h3["Authorization"] = `Bearer ${this.cfg.jwt}`;
107961
- if (this.cfg.tenantId) h3["X-Tenant-Id"] = this.cfg.tenantId;
107962
- return h3;
107963
- }
107964
- /** Read the tariff tree. `granularity` defaults to `day` server-side. */
107965
- async getTariff(sel, granularity = "hour") {
107966
- const url = joinUrl(
107967
- this.cfg.baseUrl,
107968
- this.basePath,
107969
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel, granularity)}`
107970
- );
107971
- const res = await this.fetchImpl(url, {
107972
- method: "GET",
107973
- headers: { Accept: "application/json", ...this.authHeaders() }
107974
- });
107975
- const body = await this.readBody(res);
107976
- if (!res.ok) throw this.toError(res, body);
107977
- const etagVersion = parseETagVersion(res.headers);
107978
- const parsed = unwrapGcdrEnvelope(body) || {};
107979
- return {
107980
- customerId: sel.customerId,
107981
- domain: sel.domain,
107982
- category: sel.category,
107983
- year: sel.year,
107984
- unit: parsed.unit,
107985
- currency: parsed.currency,
107986
- tariffModel: parsed.tariffModel,
107987
- timezone: parsed.timezone,
107988
- version: typeof parsed.version === "number" ? parsed.version : etagVersion ?? 0,
107989
- tree: parsed.tree || {}
107990
- };
107991
- }
107992
- /** REPLACE the whole year with a nested price tree. */
107993
- async putTariff(sel, tree, expectedVersion) {
107994
- return this.write("PUT", sel, { ...tree, ...guardBody(expectedVersion) }, expectedVersion);
107995
- }
107996
- /** MERGE sparse buckets into the year (finest level wins). */
107997
- async patchTariff(sel, buckets, expectedVersion) {
107998
- return this.write("PATCH", sel, { buckets, ...guardBody(expectedVersion) }, expectedVersion);
107999
- }
108000
- /**
108001
- * DELETE the whole year (no `bucket`) or one sub-bucket (`bucket` present).
108002
- * Whole-year delete is idempotent (204 even if absent).
108003
- */
108004
- async deleteTariff(sel, opts = {}) {
108005
- const hasBody = Boolean(opts.bucket) || typeof opts.expectedVersion === "number";
108006
- const url = joinUrl(
108007
- this.cfg.baseUrl,
108008
- this.basePath,
108009
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
108010
- );
108011
- const headers = { Accept: "application/json", ...this.authHeaders() };
108012
- if (typeof opts.expectedVersion === "number") headers["If-Match"] = `"${opts.expectedVersion}"`;
108013
- const init = { method: "DELETE", headers };
108014
- if (hasBody) {
108015
- headers["Content-Type"] = "application/json";
108016
- init.body = JSON.stringify({
108017
- ...opts.bucket ? { bucket: opts.bucket } : {},
108018
- ...guardBody(opts.expectedVersion)
108019
- });
108020
- }
108021
- const res = await this.fetchImpl(url, init);
108022
- if (res.status === 204) return {};
108023
- const body = await this.readBody(res);
108024
- if (!res.ok) throw this.toError(res, body);
108025
- const etagVersion = parseETagVersion(res.headers);
108026
- const data = unwrapGcdrEnvelope(body);
108027
- const v = (data && data.version) ?? etagVersion;
108028
- return typeof v === "number" ? { version: v } : {};
108029
- }
108030
- async write(method, sel, body, expectedVersion) {
108031
- const url = joinUrl(
108032
- this.cfg.baseUrl,
108033
- this.basePath,
108034
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
108035
- );
108036
- const headers = {
108037
- Accept: "application/json",
108038
- "Content-Type": "application/json",
108039
- ...this.authHeaders()
108040
- };
108041
- if (typeof expectedVersion === "number") headers["If-Match"] = `"${expectedVersion}"`;
108042
- const res = await this.fetchImpl(url, { method, headers, body: JSON.stringify(body) });
108043
- const parsed = await this.readBody(res);
108044
- if (!res.ok) throw this.toError(res, parsed);
108045
- const etagVersion = parseETagVersion(res.headers);
108046
- const data = unwrapGcdrEnvelope(parsed);
108047
- const v = (data && data.version) ?? etagVersion;
108048
- return { version: typeof v === "number" ? v : (expectedVersion ?? 0) + 1 };
108049
- }
108050
- async readBody(res) {
108051
- try {
108052
- const text2 = await res.text();
108053
- if (!text2) return null;
108054
- return JSON.parse(text2);
108055
- } catch {
108056
- return null;
108057
- }
108058
- }
108059
- toError(res, body) {
108060
- const err = body && body.error;
108061
- if (err && typeof err === "object") {
108062
- const e = err;
108063
- return new TariffApiError(
108064
- e.code || `HTTP_${res.status}`,
108065
- res.status,
108066
- e.message,
108067
- e.details
108068
- );
108069
- }
108070
- return new TariffApiError(`HTTP_${res.status}`, res.status, res.statusText);
108071
- }
108072
- };
108073
- function guardBody(expectedVersion) {
108074
- return typeof expectedVersion === "number" ? { expectedVersion } : {};
108075
- }
108076
- function createTariffApiClient(config2) {
108077
- return new TariffApiClient(config2);
108078
- }
108079
-
108080
108319
  // src/components/pricing-panel/tariffApiAdapter.ts
108081
108320
  var PANEL_TO_WIRE_DOMAIN = {
108082
108321
  energy: "ENERGY",
@@ -108086,14 +108325,6 @@ var WIRE_TO_PANEL_DOMAIN = {
108086
108325
  ENERGY: "energy",
108087
108326
  WATER: "water"
108088
108327
  };
108089
- var PANEL_TO_WIRE_CATEGORY = {
108090
- lojas: "SPECIFIC",
108091
- area_comum: "COMMON_AREA"
108092
- };
108093
- var WIRE_TO_PANEL_CATEGORY = {
108094
- SPECIFIC: "lojas",
108095
- COMMON_AREA: "area_comum"
108096
- };
108097
108328
  function panelDomainToWire(d) {
108098
108329
  const w = PANEL_TO_WIRE_DOMAIN[d];
108099
108330
  if (!w) throw new Error(`Unknown panel domain: ${String(d)}`);
@@ -108104,16 +108335,6 @@ function wireDomainToPanel(w) {
108104
108335
  if (!d) throw new Error(`Unknown wire domain: ${String(w)}`);
108105
108336
  return d;
108106
108337
  }
108107
- function panelCategoryToWire(c) {
108108
- const w = PANEL_TO_WIRE_CATEGORY[c];
108109
- if (!w) throw new Error(`Unknown panel category: ${String(c)}`);
108110
- return w;
108111
- }
108112
- function wireCategoryToPanel(w) {
108113
- const c = WIRE_TO_PANEL_CATEGORY[w];
108114
- if (!c) throw new Error(`Unknown wire category: ${String(w)}`);
108115
- return c;
108116
- }
108117
108338
  function normalizePriceString(input) {
108118
108339
  if (typeof input.price === "string" && input.price.trim() !== "") {
108119
108340
  const s2 = input.price.trim();
@@ -108186,7 +108407,7 @@ function bandSelector(band, customerId, year) {
108186
108407
  return {
108187
108408
  customerId,
108188
108409
  domain: panelDomainToWire(band.domain),
108189
- category: panelCategoryToWire(band.category),
108410
+ category: band.category,
108190
108411
  year
108191
108412
  };
108192
108413
  }
@@ -108391,12 +108612,7 @@ function collapseTreeToBands(tree, dims) {
108391
108612
  }
108392
108613
  return mergeContiguousDays(dayBands, dims.year);
108393
108614
  }
108394
- var WIRE_COMBOS = [
108395
- ["ENERGY", "SPECIFIC"],
108396
- ["ENERGY", "COMMON_AREA"],
108397
- ["WATER", "SPECIFIC"],
108398
- ["WATER", "COMMON_AREA"]
108399
- ];
108615
+ var WIRE_DOMAINS = ["ENERGY", "WATER"];
108400
108616
  var TariffApiAdapter = class {
108401
108617
  client;
108402
108618
  year;
@@ -108410,14 +108626,24 @@ var TariffApiAdapter = class {
108410
108626
  getYear() {
108411
108627
  return this.year;
108412
108628
  }
108629
+ /** GCDR tariff categories of a customer (globals + own). Errors propagate. */
108630
+ listCategories(customerId, opts) {
108631
+ return this.client.listCategories(customerId, opts);
108632
+ }
108413
108633
  /**
108414
108634
  * Load every `(domain × category)` tariff for a customer and collapse each into
108415
- * panel entries. An empty tariff (`version: 0`) contributes no entries — it is
108416
- * "no entries", never an error. Read errors propagate (caller surfaces them).
108635
+ * panel entries. `categories` = the GCDR category keys (from `listCategories`);
108636
+ * there is no default list. An empty tariff (`version: 0`) contributes no
108637
+ * entries — it is "no entries", never an error. Read errors propagate.
108417
108638
  */
108418
- async loadEntriesForCustomer(customerId, year = this.year) {
108639
+ async loadEntriesForCustomer(customerId, categories, year = this.year) {
108640
+ if (!Array.isArray(categories) || categories.length === 0) {
108641
+ throw new Error("loadEntriesForCustomer requires the GCDR tariff-category keys.");
108642
+ }
108643
+ const combos = [];
108644
+ for (const d of WIRE_DOMAINS) for (const c of categories) combos.push([d, c]);
108419
108645
  const out = [];
108420
- for (const [domain, category] of WIRE_COMBOS) {
108646
+ for (const [domain, category] of combos) {
108421
108647
  const sel = { customerId, domain, category, year };
108422
108648
  const resp = await this.client.getTariff(sel, "hour");
108423
108649
  this.versions.set(selectorKey(sel), resp.version);
@@ -108425,7 +108651,7 @@ var TariffApiAdapter = class {
108425
108651
  const bands = collapseTreeToBands(resp.tree, {
108426
108652
  year,
108427
108653
  domain: wireDomainToPanel(domain),
108428
- category: wireCategoryToPanel(category)
108654
+ category
108429
108655
  });
108430
108656
  for (const b of bands) out.push(bandToPanelEntry(b, customerId));
108431
108657
  }
@@ -108433,7 +108659,7 @@ var TariffApiAdapter = class {
108433
108659
  }
108434
108660
  /** Convenience: read + collapse one specific tariff. */
108435
108661
  async loadBands(customerId, domain, category, year = this.year) {
108436
- const sel = { customerId, domain: panelDomainToWire(domain), category: panelCategoryToWire(category), year };
108662
+ const sel = { customerId, domain: panelDomainToWire(domain), category, year };
108437
108663
  const resp = await this.client.getTariff(sel, "hour");
108438
108664
  this.versions.set(selectorKey(sel), resp.version);
108439
108665
  const bands = resp.version === 0 ? [] : collapseTreeToBands(resp.tree, { year, domain, category });
@@ -108506,6 +108732,309 @@ function createTariffApiAdapter(client, opts) {
108506
108732
  return new TariffApiAdapter(client, opts);
108507
108733
  }
108508
108734
 
108735
+ // src/components/pricing-panel/categoriesTab.ts
108736
+ var esc10 = (v) => String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
108737
+ function errText(err, fallback) {
108738
+ const code = err?.code;
108739
+ const map = {
108740
+ TARIFF_CATEGORY_EXISTS: "J\xE1 existe uma categoria com esse nome.",
108741
+ TARIFF_CATEGORY_IN_USE: "A categoria est\xE1 em uso (tarifas ou dispositivos) e o servidor recusou a exclus\xE3o.",
108742
+ TARIFF_CATEGORY_SYSTEM: "Categoria do sistema n\xE3o pode ser alterada.",
108743
+ TARIFF_CATEGORY_INACTIVE: "Categoria inativa n\xE3o recebe novos dispositivos.",
108744
+ TARIFF_CATEGORY_SCOPE: "Categoria de outro cliente."
108745
+ };
108746
+ return map[code || ""] || `${fallback}${code ? ` (${code})` : ""}`;
108747
+ }
108748
+ function mountCategoriesTab(opts) {
108749
+ const root = opts.container;
108750
+ let categories = [];
108751
+ let devices = null;
108752
+ let openKey = null;
108753
+ let editingKey = null;
108754
+ let busy = false;
108755
+ let notice = null;
108756
+ let loadError = null;
108757
+ let deviceFilter = "";
108758
+ let pending = /* @__PURE__ */ new Map();
108759
+ const customerId = () => opts.getCustomerId();
108760
+ const own = () => categories.filter((c) => c.customerId && c.customerId === customerId());
108761
+ const labelOf = (key) => key ? categories.find((c) => c.key === key)?.label || key : "\u2014 sem categoria \u2014";
108762
+ function deviceCount(key) {
108763
+ return devices ? devices.filter((d) => d.tariffCategory === key).length : null;
108764
+ }
108765
+ function render3() {
108766
+ const rows = own();
108767
+ root.innerHTML = `
108768
+ <div class="myio-pricing__cat" data-testid="categories-tab">
108769
+ <p class="myio-pricing__cat-hint">Categorias de tarifa deste cliente. Um dispositivo pertence a no m\xE1ximo uma categoria.</p>
108770
+ <div class="myio-pricing__cat-new">
108771
+ <input class="myio-pricing__input" data-testid="cat-new-label" maxlength="120"
108772
+ placeholder="Nome da nova categoria (ex.: Quiosques)" ${busy ? "disabled" : ""} />
108773
+ <button class="myio-pricing__add myio-pricing__cat-btn" data-testid="cat-create" type="button" ${busy ? "disabled" : ""}>Criar categoria</button>
108774
+ </div>
108775
+ ${notice ? `<div class="myio-pricing__cat-notice myio-pricing__cat-notice--${notice.kind}" data-testid="cat-notice" role="status">${esc10(notice.text)}</div>` : ""}
108776
+ ${loadError ? `<div class="myio-pricing__cat-notice myio-pricing__cat-notice--error" data-testid="cat-load-error">${esc10(loadError)}</div>` : rows.length === 0 ? '<div class="myio-pricing__empty" data-testid="cat-empty">Nenhuma categoria pr\xF3pria deste cliente.</div>' : `<ul class="myio-pricing__list" data-testid="cat-list">${rows.map(rowHtml).join("")}</ul>`}
108777
+ </div>`;
108778
+ wire();
108779
+ }
108780
+ function rowHtml(c) {
108781
+ const n = deviceCount(c.key);
108782
+ const editing = editingKey === c.key;
108783
+ return `
108784
+ <li class="myio-pricing__cat-item" data-cat="${esc10(c.key)}">
108785
+ <div class="myio-pricing__cat-row">
108786
+ <div class="myio-pricing__cat-main">
108787
+ ${editing ? `<input class="myio-pricing__input" data-testid="cat-edit-label" value="${esc10(c.label)}" maxlength="120" />` : `<strong>${esc10(c.label)}</strong>`}
108788
+ <small class="myio-pricing__cat-key">${esc10(c.key)}</small>
108789
+ <span class="myio-pricing__badge${c.isActive === false ? " myio-pricing__badge--off" : ""}">${c.isActive === false ? "Inativa" : "Ativa"}</span>
108790
+ </div>
108791
+ <div class="myio-pricing__cat-actions">
108792
+ ${editing ? `<button type="button" data-act="save-edit" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>Salvar</button>
108793
+ <button type="button" data-act="cancel-edit">Cancelar</button>` : `<button type="button" data-act="devices" data-key="${esc10(c.key)}" data-testid="cat-devices">Dispositivos${n == null ? "" : ` (${n})`}</button>
108794
+ <button type="button" data-act="edit" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>Editar</button>
108795
+ <button type="button" data-act="toggle" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>${c.isActive === false ? "Ativar" : "Desativar"}</button>
108796
+ <button type="button" class="myio-pricing__cat-danger" data-act="delete" data-key="${esc10(c.key)}" data-testid="cat-delete" ${busy ? "disabled" : ""}>Excluir</button>`}
108797
+ </div>
108798
+ </div>
108799
+ ${openKey === c.key ? devicesHtml(c) : ""}
108800
+ </li>`;
108801
+ }
108802
+ function devicesHtml(c) {
108803
+ if (devices === null) return '<div class="myio-pricing__cat-devices">Carregando dispositivos\u2026</div>';
108804
+ const f = deviceFilter.trim().toLowerCase();
108805
+ const list = devices.filter((d) => !f || `${d.label || ""} ${d.name} ${d.identifier || ""}`.toLowerCase().includes(f)).sort((a, b) => {
108806
+ const ia = isIn(a, c.key) ? 0 : 1;
108807
+ const ib = isIn(b, c.key) ? 0 : 1;
108808
+ return ia - ib || (a.label || a.name).localeCompare(b.label || b.name);
108809
+ });
108810
+ const changed = [...pending.keys()].length;
108811
+ return `
108812
+ <div class="myio-pricing__cat-devices" data-testid="cat-devices-panel">
108813
+ <div class="myio-pricing__cat-devbar">
108814
+ <input class="myio-pricing__input" data-testid="cat-dev-filter" placeholder="Buscar dispositivo\u2026" value="${esc10(deviceFilter)}" />
108815
+ <button type="button" class="myio-pricing__add myio-pricing__cat-btn" data-act="save-devices" data-key="${esc10(c.key)}"
108816
+ data-testid="cat-dev-save" ${busy || changed === 0 || c.isActive === false ? "disabled" : ""}>Salvar (${changed})</button>
108817
+ </div>
108818
+ ${c.isActive === false ? '<p class="myio-pricing__cat-hint">Categoria inativa: ative para incluir dispositivos.</p>' : ""}
108819
+ <ul class="myio-pricing__cat-devlist">${list.length ? list.map((d) => {
108820
+ const checked = isIn(d, c.key);
108821
+ const other = d.tariffCategory && d.tariffCategory !== c.key ? d.tariffCategory : null;
108822
+ return `<li><label>
108823
+ <input type="checkbox" data-dev="${esc10(d.id)}" ${checked ? "checked" : ""} ${busy ? "disabled" : ""} />
108824
+ <span>${esc10(d.label || d.name)}</span>
108825
+ ${d.identifier ? `<small>${esc10(d.identifier)}</small>` : ""}
108826
+ ${other ? `<small class="myio-pricing__cat-other">em ${esc10(labelOf(other))}${checked ? " \u2192 ser\xE1 movido" : ""}</small>` : ""}
108827
+ </label></li>`;
108828
+ }).join("") : '<li class="myio-pricing__empty">Nenhum dispositivo.</li>'}</ul>
108829
+ </div>`;
108830
+ }
108831
+ function isIn(d, key) {
108832
+ return pending.has(d.id) ? pending.get(d.id) : d.tariffCategory === key;
108833
+ }
108834
+ function wire() {
108835
+ const q = (sel) => root.querySelector(sel);
108836
+ q('[data-testid="cat-create"]')?.addEventListener("click", () => void create());
108837
+ q('[data-testid="cat-new-label"]')?.addEventListener("keydown", (e) => {
108838
+ if (e.key === "Enter") void create();
108839
+ });
108840
+ root.querySelectorAll("[data-act]").forEach(
108841
+ (b) => b.addEventListener("click", () => void onAction(b.dataset.act, b.dataset.key || ""))
108842
+ );
108843
+ const filter = q('[data-testid="cat-dev-filter"]');
108844
+ filter?.addEventListener("input", () => {
108845
+ deviceFilter = filter.value;
108846
+ const pos = filter.selectionStart;
108847
+ render3();
108848
+ const again = root.querySelector('[data-testid="cat-dev-filter"]');
108849
+ again?.focus();
108850
+ if (again && pos != null) again.setSelectionRange(pos, pos);
108851
+ });
108852
+ root.querySelectorAll("input[data-dev]").forEach(
108853
+ (cb) => cb.addEventListener("change", () => {
108854
+ const d = devices?.find((x) => x.id === cb.dataset.dev);
108855
+ if (!d || !openKey) return;
108856
+ const original = d.tariffCategory === openKey;
108857
+ if (cb.checked === original) pending.delete(d.id);
108858
+ else pending.set(d.id, cb.checked);
108859
+ render3();
108860
+ })
108861
+ );
108862
+ }
108863
+ async function run(fn) {
108864
+ if (busy) return;
108865
+ busy = true;
108866
+ notice = null;
108867
+ render3();
108868
+ try {
108869
+ await fn();
108870
+ } finally {
108871
+ busy = false;
108872
+ render3();
108873
+ }
108874
+ }
108875
+ async function create() {
108876
+ const input = root.querySelector('[data-testid="cat-new-label"]');
108877
+ const label = (input?.value || "").trim();
108878
+ if (!label) {
108879
+ notice = { kind: "error", text: "Informe o nome da categoria." };
108880
+ return render3();
108881
+ }
108882
+ const key = categoryKeyFromLabel(label);
108883
+ if (!key) {
108884
+ notice = { kind: "error", text: "Nome inv\xE1lido para gerar o c\xF3digo da categoria." };
108885
+ return render3();
108886
+ }
108887
+ await run(async () => {
108888
+ try {
108889
+ const maxSort = categories.reduce((m, c) => Math.max(m, Number(c.sortOrder) || 0), 0);
108890
+ await opts.client.createCategory({ key, label, customerId: customerId(), sortOrder: maxSort + 10, isActive: true });
108891
+ await reloadCategories();
108892
+ notice = { kind: "ok", text: `Categoria "${label}" criada.` };
108893
+ opts.onChanged?.();
108894
+ } catch (err) {
108895
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel criar a categoria") };
108896
+ }
108897
+ });
108898
+ }
108899
+ async function onAction(act, key) {
108900
+ const cat = categories.find((c) => c.key === key);
108901
+ if (act === "cancel-edit") {
108902
+ editingKey = null;
108903
+ return render3();
108904
+ }
108905
+ if (act === "edit") {
108906
+ editingKey = key;
108907
+ return render3();
108908
+ }
108909
+ if (!cat && act !== "cancel-edit") return;
108910
+ if (act === "save-edit") {
108911
+ const label = (root.querySelector('[data-testid="cat-edit-label"]')?.value || "").trim();
108912
+ if (!label) {
108913
+ notice = { kind: "error", text: "Informe o nome da categoria." };
108914
+ return render3();
108915
+ }
108916
+ return run(async () => {
108917
+ try {
108918
+ await opts.client.updateCategory(key, { label });
108919
+ editingKey = null;
108920
+ await reloadCategories();
108921
+ notice = { kind: "ok", text: "Categoria atualizada." };
108922
+ opts.onChanged?.();
108923
+ } catch (err) {
108924
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel salvar a categoria") };
108925
+ }
108926
+ });
108927
+ }
108928
+ if (act === "toggle") {
108929
+ return run(async () => {
108930
+ try {
108931
+ await opts.client.updateCategory(key, { isActive: cat.isActive === false });
108932
+ await reloadCategories();
108933
+ opts.onChanged?.();
108934
+ } catch (err) {
108935
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel alterar a categoria") };
108936
+ }
108937
+ });
108938
+ }
108939
+ if (act === "devices") {
108940
+ openKey = openKey === key ? null : key;
108941
+ pending = /* @__PURE__ */ new Map();
108942
+ deviceFilter = "";
108943
+ render3();
108944
+ if (openKey && devices === null) await loadDevices2();
108945
+ return;
108946
+ }
108947
+ if (act === "save-devices") return saveDevices(key);
108948
+ if (act === "delete") return remove(cat);
108949
+ }
108950
+ async function remove(cat) {
108951
+ let usage = { devices: 0, tariffs: 0 };
108952
+ try {
108953
+ usage = await opts.client.getCategoryUsage(cat.key);
108954
+ } catch (err) {
108955
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel verificar o uso da categoria") };
108956
+ return render3();
108957
+ }
108958
+ const inUse = usage.devices > 0 || usage.tariffs > 0;
108959
+ const parts = [];
108960
+ if (usage.tariffs > 0) parts.push(`${usage.tariffs} tarifa(s) cadastrada(s) \u2014 ser\xE3o apagadas`);
108961
+ if (usage.devices > 0) parts.push(`${usage.devices} dispositivo(s) \u2014 ficar\xE3o sem categoria`);
108962
+ const message = inUse ? `A categoria "${cat.label}" est\xE1 em uso: ${parts.join("; ")}. Tem certeza que deseja excluir? Esta a\xE7\xE3o n\xE3o pode ser desfeita.` : `Tem certeza que deseja excluir a categoria "${cat.label}"? Esta a\xE7\xE3o n\xE3o pode ser desfeita.`;
108963
+ const choice = await openConfirmDialog({
108964
+ title: inUse ? "\u26A0\uFE0F Excluir Categoria" : "Excluir Categoria",
108965
+ message,
108966
+ buttons: [
108967
+ { label: "Cancelar", value: "cancel", variant: "secondary" },
108968
+ { label: "Excluir", value: "confirm", variant: "danger", autoFocus: true }
108969
+ ],
108970
+ container: opts.dialogContainer
108971
+ });
108972
+ if (choice !== "confirm") return;
108973
+ await run(async () => {
108974
+ try {
108975
+ await opts.client.deleteCategory(cat.key, { cascade: inUse });
108976
+ if (openKey === cat.key) openKey = null;
108977
+ await reloadCategories();
108978
+ if (devices) devices = devices.map((d) => d.tariffCategory === cat.key ? { ...d, tariffCategory: null } : d);
108979
+ notice = { kind: "ok", text: `Categoria "${cat.label}" exclu\xEDda.` };
108980
+ opts.onChanged?.();
108981
+ } catch (err) {
108982
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel excluir a categoria") };
108983
+ }
108984
+ });
108985
+ }
108986
+ async function saveDevices(key) {
108987
+ if (!devices || pending.size === 0) return;
108988
+ const changes = [...pending.entries()];
108989
+ await run(async () => {
108990
+ const failed = [];
108991
+ for (const [id, inCat] of changes) {
108992
+ const d = devices.find((x) => x.id === id);
108993
+ if (!d) continue;
108994
+ try {
108995
+ const target = inCat ? key : null;
108996
+ const updated = await opts.client.setDeviceCategory(id, target);
108997
+ d.tariffCategory = updated.id ? updated.tariffCategory : target;
108998
+ pending.delete(id);
108999
+ } catch (err) {
109000
+ failed.push(`${d.label || d.name}: ${errText(err, "erro")}`);
109001
+ }
109002
+ }
109003
+ notice = failed.length ? { kind: "error", text: `N\xE3o foi poss\xEDvel salvar ${failed.length} dispositivo(s): ${failed.join("; ")}` } : { kind: "ok", text: `${changes.length} dispositivo(s) atualizado(s).` };
109004
+ opts.onChanged?.();
109005
+ });
109006
+ }
109007
+ async function reloadCategories() {
109008
+ categories = await opts.client.listCategories(customerId(), { includeInactive: true });
109009
+ }
109010
+ async function loadDevices2() {
109011
+ try {
109012
+ devices = await opts.client.listCustomerDevices(customerId());
109013
+ } catch (err) {
109014
+ devices = [];
109015
+ notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel carregar os dispositivos") };
109016
+ }
109017
+ render3();
109018
+ }
109019
+ async function refresh() {
109020
+ loadError = null;
109021
+ openKey = null;
109022
+ editingKey = null;
109023
+ pending = /* @__PURE__ */ new Map();
109024
+ devices = null;
109025
+ root.innerHTML = '<div class="myio-pricing__empty">Carregando categorias\u2026</div>';
109026
+ try {
109027
+ await reloadCategories();
109028
+ } catch (err) {
109029
+ categories = [];
109030
+ loadError = errText(err, "N\xE3o foi poss\xEDvel carregar as categorias de tarifa do GCDR");
109031
+ }
109032
+ render3();
109033
+ if (!loadError) void loadDevices2();
109034
+ }
109035
+ return { refresh };
109036
+ }
109037
+
108509
109038
  // src/components/pricing-panel/openPricingPanel.ts
108510
109039
  var MODAL_ID4 = "myio-pricing-panel";
108511
109040
  function escapeHtml14(value) {
@@ -108589,8 +109118,9 @@ function openPricingPanel(params) {
108589
109118
  const lockCustomer = params.lockCustomer === true && customers.length > 0;
108590
109119
  const tariffApi = params.tariffApi;
108591
109120
  let adapter = null;
109121
+ let client = null;
108592
109122
  if (allowed && tariffApi) {
108593
- const client = new TariffApiClient({
109123
+ client = new TariffApiClient({
108594
109124
  baseUrl: tariffApi.baseUrl,
108595
109125
  apiKey: tariffApi.apiKey,
108596
109126
  jwt: tariffApi.jwt,
@@ -108663,7 +109193,8 @@ function openPricingPanel(params) {
108663
109193
  return handle;
108664
109194
  }
108665
109195
  const initDomain = params.domain || "energy";
108666
- const initCategory = params.category || "lojas";
109196
+ let categories = null;
109197
+ let categoriesError = null;
108667
109198
  const customerOptions = customers.map((c) => `<option value="${escapeHtml14(resolveCustomerId(c))}">${escapeHtml14(c.title)}</option>`).join("");
108668
109199
  modal.innerHTML = `
108669
109200
  <div class="myio-pricing__overlay"></div>
@@ -108676,6 +109207,7 @@ function openPricingPanel(params) {
108676
109207
  <button class="myio-pricing__tab active" data-tab="define" data-testid="tab-define">Definir pre\xE7os</button>
108677
109208
  <button class="myio-pricing__tab" data-tab="dashboard" data-testid="tab-dashboard">Dashboard</button>
108678
109209
  <button class="myio-pricing__tab" data-tab="history" data-testid="tab-history">Hist\xF3rico</button>
109210
+ ${adapter ? '<button class="myio-pricing__tab" data-tab="categories" data-testid="tab-categories">Categorias</button>' : ""}
108679
109211
  </div>
108680
109212
  <div class="myio-pricing__body">
108681
109213
  <!-- TAB: Definir pre\xE7os -->
@@ -108696,9 +109228,8 @@ function openPricingPanel(params) {
108696
109228
  </div>
108697
109229
  <div class="myio-pricing__field">
108698
109230
  <label class="myio-pricing__label" for="myio-pricing-category">Categoria</label>
108699
- <select class="myio-pricing__select" id="myio-pricing-category" data-testid="pricing-category">
108700
- <option value="lojas">Lojas</option>
108701
- <option value="area_comum">\xC1rea Comum</option>
109231
+ <select class="myio-pricing__select" id="myio-pricing-category" data-testid="pricing-category" disabled>
109232
+ <option value="">Carregando categorias\u2026</option>
108702
109233
  </select>
108703
109234
  </div>
108704
109235
  <div class="myio-pricing__field">
@@ -108752,6 +109283,9 @@ function openPricingPanel(params) {
108752
109283
  </div>
108753
109284
  </div>
108754
109285
 
109286
+ <!-- TAB: Categorias (s\xF3 com a API de tarifas do GCDR) -->
109287
+ ${adapter ? '<div class="myio-pricing__panel" data-panel="categories" data-testid="categories-panel" hidden></div>' : ""}
109288
+
108755
109289
  <!-- TAB: Hist\xF3rico -->
108756
109290
  <div class="myio-pricing__panel" data-panel="history" hidden>
108757
109291
  <ul class="myio-pricing__history" data-testid="history-list"></ul>
@@ -108786,7 +109320,33 @@ function openPricingPanel(params) {
108786
109320
  const historyList = $2('[data-testid="history-list"]');
108787
109321
  const historyEmpty = $2('[data-testid="history-empty"]');
108788
109322
  domainSel.value = initDomain;
108789
- categorySel.value = initCategory;
109323
+ const activeCategories = () => (categories || []).filter((c) => c.isActive !== false);
109324
+ function renderCategoryOptions() {
109325
+ const previous = categorySel.value;
109326
+ if (categories === null) {
109327
+ categorySel.innerHTML = `<option value="">${escapeHtml14(
109328
+ categoriesError ? "Erro ao carregar categorias" : "Carregando categorias\u2026"
109329
+ )}</option>`;
109330
+ categorySel.disabled = true;
109331
+ addBtn.disabled = true;
109332
+ return;
109333
+ }
109334
+ const active = activeCategories();
109335
+ const inactive = categories.filter((c) => c.isActive === false);
109336
+ categorySel.innerHTML = active.map((c) => `<option value="${escapeHtml14(c.key)}">${escapeHtml14(c.label || c.key)}</option>`).join("") + inactive.map((c) => `<option value="${escapeHtml14(c.key)}" disabled>${escapeHtml14(`${c.label || c.key} (inativa)`)}</option>`).join("");
109337
+ const keys = active.map((c) => c.key);
109338
+ const wanted = [previous, params.category || ""].find((k) => k && keys.includes(k));
109339
+ categorySel.value = wanted || keys[0] || "";
109340
+ categorySel.disabled = keys.length === 0;
109341
+ addBtn.disabled = keys.length === 0;
109342
+ if (keys.length === 0) showError("Nenhuma categoria de tarifa ativa no GCDR para este customer.");
109343
+ }
109344
+ function setCategories(list, error = null) {
109345
+ categories = list;
109346
+ categoriesError = error;
109347
+ renderCategoryOptions();
109348
+ if (error) showError(error);
109349
+ }
108790
109350
  modal.querySelectorAll(".myio-pricing__tab").forEach((tab) => {
108791
109351
  tab.addEventListener("click", () => selectTab(tab.dataset.tab));
108792
109352
  });
@@ -108799,6 +109359,22 @@ function openPricingPanel(params) {
108799
109359
  });
108800
109360
  if (name === "dashboard") renderDashboard2();
108801
109361
  if (name === "history") renderHistory();
109362
+ if (name === "categories") void categoriesTab?.refresh();
109363
+ }
109364
+ let categoriesTab = null;
109365
+ const categoriesPanel = modal.querySelector('[data-panel="categories"]');
109366
+ if (client && categoriesPanel) {
109367
+ const dialogHost = doc.createElement("div");
109368
+ dialogHost.className = "myio-pricing__dialog-host";
109369
+ modal.appendChild(dialogHost);
109370
+ categoriesTab = mountCategoriesTab({
109371
+ container: categoriesPanel,
109372
+ client,
109373
+ getCustomerId: () => customerSel.value,
109374
+ dialogContainer: dialogHost,
109375
+ // categoria criada/alterada/excluída → recarrega o select e as tarifas
109376
+ onChanged: () => void loadFromApi()
109377
+ });
108802
109378
  }
108803
109379
  const showError = (msg) => {
108804
109380
  errorBox.textContent = msg;
@@ -108833,6 +109409,7 @@ function openPricingPanel(params) {
108833
109409
  if (adapter) {
108834
109410
  customerSel.addEventListener("change", () => {
108835
109411
  void loadFromApi();
109412
+ if (categoriesPanel && !categoriesPanel.hidden) void categoriesTab?.refresh();
108836
109413
  });
108837
109414
  }
108838
109415
  syncPeriodFields();
@@ -108852,8 +109429,24 @@ function openPricingPanel(params) {
108852
109429
  if (!adapter) return;
108853
109430
  const customerId = customerSel.value;
108854
109431
  if (!customerId) return;
109432
+ setCategories(null);
109433
+ try {
109434
+ setCategories(await adapter.listCategories(customerId, { includeInactive: true }));
109435
+ } catch (err) {
109436
+ const code = err?.code;
109437
+ setCategories(
109438
+ null,
109439
+ `N\xE3o foi poss\xEDvel carregar as categorias de tarifa do GCDR${code ? ` (${code})` : ""}.`
109440
+ );
109441
+ return;
109442
+ }
109443
+ clearError();
109444
+ if (!categories || categories.length === 0) return;
108855
109445
  try {
108856
- const loaded = await adapter.loadEntriesForCustomer(customerId);
109446
+ const loaded = await adapter.loadEntriesForCustomer(
109447
+ customerId,
109448
+ categories.map((c) => c.key)
109449
+ );
108857
109450
  entries = entries.filter((e) => e.customerId !== customerId).concat(loaded);
108858
109451
  renderList2();
108859
109452
  } catch (err) {
@@ -108881,7 +109474,7 @@ function openPricingPanel(params) {
108881
109474
  };
108882
109475
  const badge = (domain, category) => `<span class="myio-pricing__badge${domain === "water" ? " myio-pricing__badge--water" : ""}">${escapeHtml14(
108883
109476
  DOMAIN_LABEL[domain]
108884
- )} \xB7 ${escapeHtml14(CATEGORY_LABEL[category])}</span>`;
109477
+ )} \xB7 ${escapeHtml14(categoryLabel(category, categories))}</span>`;
108885
109478
  const renderList2 = () => {
108886
109479
  const customerId = customerSel.value;
108887
109480
  const rows = entries.filter((e) => e.customerId === customerId).sort((a, b) => {
@@ -108937,6 +109530,9 @@ function openPricingPanel(params) {
108937
109530
  if (!customerId) return { error: "Selecione um customer." };
108938
109531
  const domain = domainSel.value;
108939
109532
  const category = categorySel.value;
109533
+ if (!category || !activeCategories().some((c) => c.key === category)) {
109534
+ return { error: "Selecione uma categoria." };
109535
+ }
108940
109536
  const price = parseBRL(priceInput.value);
108941
109537
  if (!Number.isFinite(price) || price <= 0) {
108942
109538
  return { error: "Informe um pre\xE7o v\xE1lido maior que zero." };
@@ -108979,7 +109575,10 @@ function openPricingPanel(params) {
108979
109575
  });
108980
109576
  reportDomainSel.addEventListener("change", renderReport);
108981
109577
  function renderDashboard2() {
108982
- const kpis = computePricingKpis(entries, { customerCount: customers.length });
109578
+ const kpis = computePricingKpis(entries, {
109579
+ customerCount: customers.length,
109580
+ categoryCount: activeCategories().length
109581
+ });
108983
109582
  const cards = [
108984
109583
  { value: String(kpis.totalPeriods), label: "Per\xEDodos definidos" },
108985
109584
  { value: String(kpis.periodsByDomain.energy), label: "Per\xEDodos \xB7 Energia" },
@@ -109023,7 +109622,7 @@ function openPricingPanel(params) {
109023
109622
  <tr>
109024
109623
  <td>${escapeHtml14(customerTitle(e.customerId))}</td>
109025
109624
  <td>${escapeHtml14(DOMAIN_LABEL[e.domain])}</td>
109026
- <td>${escapeHtml14(CATEGORY_LABEL[e.category])}</td>
109625
+ <td>${escapeHtml14(categoryLabel(e.category, categories))}</td>
109027
109626
  <td>${escapeHtml14(formatPeriodLabel(e))}</td>
109028
109627
  <td>${escapeHtml14(formatBRL2(e.pricePerKwh))} ${escapeHtml14(unitLabel(e.domain))}</td>
109029
109628
  </tr>`
@@ -109049,7 +109648,13 @@ function openPricingPanel(params) {
109049
109648
  historyEmpty.style.display = auditLog.length ? "none" : "";
109050
109649
  }
109051
109650
  renderList2();
109052
- if (adapter) void loadFromApi();
109651
+ if (adapter) {
109652
+ void loadFromApi();
109653
+ } else if (params.categories && params.categories.length) {
109654
+ setCategories(params.categories.map((c) => ({ ...c })));
109655
+ } else {
109656
+ setCategories(null, "Categorias de tarifa n\xE3o informadas (configure a API de tarifas do GCDR).");
109657
+ }
109053
109658
  return handle;
109054
109659
  }
109055
109660
 
@@ -109732,27 +110337,19 @@ function injectDeviceCategoryStyles(doc) {
109732
110337
  }
109733
110338
 
109734
110339
  // src/components/financial-goals/deviceCategoryPanel.ts
109735
- var PANEL_TERM_LABEL = {
109736
- lojas: "Lojas",
109737
- area_comum: "\xC1rea Comum"
109738
- };
109739
110340
  var NONE_LABEL = "\u2014 Sem categoria \u2014";
109740
- function deviceCategoryLabel(cat) {
110341
+ function deviceCategoryLabel(cat, categories) {
109741
110342
  if (cat == null) return NONE_LABEL;
109742
- return PANEL_TERM_LABEL[wireCategoryToPanel(cat)];
109743
- }
109744
- function deviceCategoryToPanelTerm(cat) {
109745
- return cat == null ? null : wireCategoryToPanel(cat);
109746
- }
109747
- function panelTermToDeviceCategory(term) {
109748
- return term == null ? null : panelCategoryToWire(term);
110343
+ return (categories || []).find((c) => c.key === cat)?.label || String(cat);
109749
110344
  }
109750
- function esc10(s) {
110345
+ function esc11(s) {
109751
110346
  return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
109752
110347
  }
109753
- function categoryOptionsHTML(selected) {
109754
- const opt = (value, label, isSel) => `<option value="${value}"${isSel ? " selected" : ""}>${esc10(label)}</option>`;
109755
- return opt("", NONE_LABEL, selected == null) + opt("COMMON_AREA", deviceCategoryLabel("COMMON_AREA"), selected === "COMMON_AREA") + opt("SPECIFIC", deviceCategoryLabel("SPECIFIC"), selected === "SPECIFIC");
110348
+ function categoryOptionsHTML(selected, categories) {
110349
+ const opt = (value, label, isSel) => `<option value="${esc11(value)}"${isSel ? " selected" : ""}>${esc11(label)}</option>`;
110350
+ const list = categories.filter((c) => c.isActive !== false || c.key === selected);
110351
+ const known = list.some((c) => c.key === selected);
110352
+ return opt("", NONE_LABEL, selected == null) + list.map((c) => opt(c.key, c.label || c.key, selected === c.key)).join("") + (selected != null && !known ? opt(selected, String(selected), true) : "");
109756
110353
  }
109757
110354
  function openDeviceCategoryPanel(params) {
109758
110355
  const doc = params.document || (typeof document !== "undefined" ? document : void 0);
@@ -109763,6 +110360,8 @@ function openDeviceCategoryPanel(params) {
109763
110360
  }
109764
110361
  injectDeviceCategoryStyles(doc);
109765
110362
  const { port, customerId } = params;
110363
+ const categories = (params.categories || []).slice();
110364
+ const activeOptions = categories.filter((c) => c.isActive !== false).map((c) => `<option value="${esc11(c.key)}">${esc11(c.label || c.key)}</option>`).join("");
109766
110365
  let rows = [];
109767
110366
  let search = "";
109768
110367
  let filter = params.initialFilter || "all";
@@ -109788,8 +110387,7 @@ function openDeviceCategoryPanel(params) {
109788
110387
  <select class="myio-devcat__filter" data-devcat-filter="1" aria-label="Filtrar por categoria">
109789
110388
  <option value="all">Todas as categorias</option>
109790
110389
  <option value="uncategorized">Sem categoria</option>
109791
- <option value="COMMON_AREA">${esc10(deviceCategoryLabel("COMMON_AREA"))}</option>
109792
- <option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
110390
+ ${activeOptions}
109793
110391
  </select>
109794
110392
  <label class="myio-devcat__filter" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
109795
110393
  <input type="checkbox" data-devcat-selectall="1" /> Selecionar vis\xEDveis
@@ -109798,9 +110396,8 @@ function openDeviceCategoryPanel(params) {
109798
110396
  <div class="myio-devcat__bulkbar" data-devcat-bulkbar="1">
109799
110397
  <span data-devcat-bulkcount="1">0 selecionados</span>
109800
110398
  <select data-devcat-bulkcat="1" aria-label="Categoria para os selecionados">
109801
- <option value="">${esc10(NONE_LABEL)}</option>
109802
- <option value="COMMON_AREA">${esc10(deviceCategoryLabel("COMMON_AREA"))}</option>
109803
- <option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
110399
+ <option value="">${esc11(NONE_LABEL)}</option>
110400
+ ${activeOptions}
109804
110401
  </select>
109805
110402
  <button type="button" class="myio-devcat__bulk-apply" data-devcat-bulkapply="1">Aplicar a selecionados</button>
109806
110403
  </div>
@@ -109830,16 +110427,16 @@ function openDeviceCategoryPanel(params) {
109830
110427
  return rows.filter((r) => matchesFilter(r) && matchesSearch(r));
109831
110428
  }
109832
110429
  function rowHTML(r) {
109833
- const name = esc10(r.label || r.code || r.deviceId);
109834
- const code = r.code ? `<span class="myio-devcat__row-code">${esc10(r.code)}</span>` : "";
110430
+ const name = esc11(r.label || r.code || r.deviceId);
110431
+ const code = r.code ? `<span class="myio-devcat__row-code">${esc11(r.code)}</span>` : "";
109835
110432
  const checked = selected.has(r.deviceId) ? " checked" : "";
109836
110433
  const focused = r.deviceId === params.focusDeviceId ? ' data-focused="1"' : "";
109837
110434
  const catAttr = r.tariffCategory == null ? "null" : r.tariffCategory;
109838
- return `<div class="myio-devcat__row" data-devcat-row="${esc10(r.deviceId)}" data-cat="${catAttr}"${focused}><input type="checkbox" class="myio-devcat__row-check" data-devcat-rowcheck="${esc10(
110435
+ return `<div class="myio-devcat__row" data-devcat-row="${esc11(r.deviceId)}" data-cat="${catAttr}"${focused}><input type="checkbox" class="myio-devcat__row-check" data-devcat-rowcheck="${esc11(
109839
110436
  r.deviceId
109840
- )}"${checked} aria-label="Selecionar ${name}" /><div class="myio-devcat__row-main"><span class="myio-devcat__row-label" title="${name}">${name}</span>` + code + `</div><select class="myio-devcat__row-select" data-devcat-rowselect="${esc10(
110437
+ )}"${checked} aria-label="Selecionar ${name}" /><div class="myio-devcat__row-main"><span class="myio-devcat__row-label" title="${name}">${name}</span>` + code + `</div><select class="myio-devcat__row-select" data-devcat-rowselect="${esc11(
109841
110438
  r.deviceId
109842
- )}" aria-label="Categoria de ${name}">${categoryOptionsHTML(r.tariffCategory)}</select><div class="myio-devcat__row-conflict" data-devcat-conflict="${esc10(r.deviceId)}"></div></div>`;
110439
+ )}" aria-label="Categoria de ${name}">${categoryOptionsHTML(r.tariffCategory, categories)}</select><div class="myio-devcat__row-conflict" data-devcat-conflict="${esc11(r.deviceId)}"></div></div>`;
109843
110440
  }
109844
110441
  function render3() {
109845
110442
  const vis = visibleRows();
@@ -109999,7 +110596,7 @@ function openDeviceCategoryPanel(params) {
109999
110596
  rows = await port.listDevices({ customerId, domain: params.domain });
110000
110597
  } catch (err) {
110001
110598
  rows = [];
110002
- body.innerHTML = `<div class="myio-devcat__empty">N\xE3o foi poss\xEDvel carregar os dispositivos: ${esc10(
110599
+ body.innerHTML = `<div class="myio-devcat__empty">N\xE3o foi poss\xEDvel carregar os dispositivos: ${esc11(
110003
110600
  err?.message || "erro"
110004
110601
  )}</div>`;
110005
110602
  countEl.textContent = "";
@@ -110031,6 +110628,7 @@ function createCoverageDeepLink(config2) {
110031
110628
  const open = (focusDeviceId, initialFilter) => openDeviceCategoryPanel({
110032
110629
  port: config2.port,
110033
110630
  customerId: config2.customerId,
110631
+ categories: config2.categories,
110034
110632
  domain: config2.domain,
110035
110633
  focusDeviceId,
110036
110634
  initialFilter,
@@ -116259,16 +116857,16 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
116259
116857
  let errors = 0;
116260
116858
  for (let i = 0; i < deviceAttrsList.length; i++) {
116261
116859
  const { deviceId, centralId, slaveId } = deviceAttrsList[i];
116262
- const devName = devices[i]?.name || deviceId;
116263
- updateBusyProgress(i + 1, `[${i + 1}/${devices.length}] Sync: ${devName}`);
116860
+ const devName2 = devices[i]?.name || deviceId;
116861
+ updateBusyProgress(i + 1, `[${i + 1}/${devices.length}] Sync: ${devName2}`);
116264
116862
  if (!centralId || !slaveId) {
116265
- console.log(`[BulkSyncIngestion] Skipped ${devName} \u2014 missing centralId or slaveId`);
116863
+ console.log(`[BulkSyncIngestion] Skipped ${devName2} \u2014 missing centralId or slaveId`);
116266
116864
  skipped++;
116267
116865
  continue;
116268
116866
  }
116269
116867
  const match = findIngestionDeviceByCentralSlaveId(ingestionDevices, centralId, slaveId);
116270
116868
  if (!match) {
116271
- console.log(`[BulkSyncIngestion] No match for ${devName} (centralId=${centralId}, slaveId=${slaveId})`);
116869
+ console.log(`[BulkSyncIngestion] No match for ${devName2} (centralId=${centralId}, slaveId=${slaveId})`);
116272
116870
  skipped++;
116273
116871
  continue;
116274
116872
  }
@@ -116276,10 +116874,10 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
116276
116874
  await tbPost(state6, `/api/plugins/telemetry/DEVICE/${deviceId}/attributes/SERVER_SCOPE`, {
116277
116875
  ingestionId: match.id
116278
116876
  });
116279
- console.log(`[BulkSyncIngestion] \u2705 ${devName} \u2192 ingestionId=${match.id}`);
116877
+ console.log(`[BulkSyncIngestion] \u2705 ${devName2} \u2192 ingestionId=${match.id}`);
116280
116878
  matched++;
116281
116879
  } catch (err) {
116282
- console.error(`[BulkSyncIngestion] \u274C ${devName}:`, err);
116880
+ console.error(`[BulkSyncIngestion] \u274C ${devName2}:`, err);
116283
116881
  errors++;
116284
116882
  }
116285
116883
  }
@@ -117571,14 +118169,14 @@ function buildTemplateCsv(domain, devices, start, end, now = Date.now()) {
117571
118169
  if (domain === "energy") header.push("value_reactive_kvarh");
117572
118170
  const today = nowSaoPaulo(now);
117573
118171
  const lines = [header.join(";")];
117574
- const esc12 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
118172
+ const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
117575
118173
  const { ok } = splitImportableDevices(devices);
117576
118174
  for (const dev of ok) {
117577
118175
  for (const date of daysBetween(start, end)) {
117578
118176
  if (date > today.date) break;
117579
118177
  for (let h3 = 0; h3 < 24; h3++) {
117580
118178
  if (date === today.date && h3 >= today.hour) break;
117581
- const cols = [String(dev.centralId), String(Number(dev.slaveId)), esc12(dev.label || ""), date, `${pad25(h3)}:00`, ""];
118179
+ const cols = [String(dev.centralId), String(Number(dev.slaveId)), esc13(dev.label || ""), date, `${pad25(h3)}:00`, ""];
117582
118180
  if (domain === "energy") cols.push("");
117583
118181
  lines.push(cols.join(";"));
117584
118182
  }
@@ -117648,8 +118246,8 @@ function parseDecimal(v) {
117648
118246
  if (typeof v === "number") return Number.isFinite(v) ? v : NaN;
117649
118247
  const s = String(v ?? "").trim();
117650
118248
  if (!s) return null;
117651
- const norm2 = s.includes(",") ? s.replace(/\./g, "").replace(",", ".") : s;
117652
- return /^-?\d+(\.\d+)?$/.test(norm2) ? Number(norm2) : NaN;
118249
+ const norm3 = s.includes(",") ? s.replace(/\./g, "").replace(",", ".") : s;
118250
+ return /^-?\d+(\.\d+)?$/.test(norm3) ? Number(norm3) : NaN;
117653
118251
  }
117654
118252
  function rowsFromTable(domain, table) {
117655
118253
  const errors = [];
@@ -117839,10 +118437,10 @@ function accumulatedRows(domain, entries, profile = DEFAULT_DISTRIBUTION_PROFILE
117839
118437
  }
117840
118438
  function buildAccumulatedTemplateCsv(domain, devices, start, end) {
117841
118439
  const lines = [["gateway_id", "slave_id", "device_name", "start_date", "end_date", TOTAL_COLUMN[domain]].join(";")];
117842
- const esc12 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
118440
+ const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
117843
118441
  for (const dev of devices || []) {
117844
118442
  if (!isImportableKey(dev)) continue;
117845
- lines.push([String(dev.centralId), String(Number(dev.slaveId)), esc12(dev.label || ""), start, end, ""].join(";"));
118443
+ lines.push([String(dev.centralId), String(Number(dev.slaveId)), esc13(dev.label || ""), start, end, ""].join(";"));
117846
118444
  }
117847
118445
  return { csv: "\uFEFF" + lines.join("\r\n") + "\r\n", rows: lines.length - 1 };
117848
118446
  }
@@ -118006,11 +118604,15 @@ function createTelemetryImportApi(cfg) {
118006
118604
 
118007
118605
  // src/components/premium-modals/telemetry-import/openTelemetryImportModal.ts
118008
118606
  var STEPS2 = [
118607
+ { n: 0, label: "Dispositivos" },
118009
118608
  { n: 1, label: "Modelo" },
118010
118609
  { n: 2, label: "Planilha" },
118011
118610
  { n: 3, label: "Valida\xE7\xE3o" },
118012
118611
  { n: 4, label: "Importa\xE7\xE3o" }
118013
118612
  ];
118613
+ var devKey = (d) => `${d.centralId}|${d.slaveId}`;
118614
+ var devName = (d) => String(d.label || d.identifier || "").toUpperCase();
118615
+ var norm2 = (v) => String(v ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
118014
118616
  var DOMAIN_TEXT = {
118015
118617
  energy: { noun: "energia", unit: "kWh", icon: "\u26A1" },
118016
118618
  water: { noun: "\xE1gua", unit: "m\xB3", icon: "\u{1F4A7}" }
@@ -118032,7 +118634,7 @@ function fmtSaoPaulo(iso) {
118032
118634
  return `${p(d.getUTCDate())}/${p(d.getUTCMonth() + 1)}/${d.getUTCFullYear()} ${p(d.getUTCHours())}:00`;
118033
118635
  }
118034
118636
  var STYLE_ID15 = "myio-tlmimport-styles";
118035
- function esc11(v) {
118637
+ function esc12(v) {
118036
118638
  return String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
118037
118639
  }
118038
118640
  var fmtNum = (n, d = 0) => Number.isFinite(Number(n)) ? Number(n).toLocaleString("pt-BR", { minimumFractionDigits: d, maximumFractionDigits: d }) : "\u2014";
@@ -118042,7 +118644,19 @@ function injectStyles15() {
118042
118644
  style.id = STYLE_ID15;
118043
118645
  style.textContent = `
118044
118646
  .tlmi { --tlmi-ac: #3e1a7d; --tlmi-ac-soft: #f1ecfa; --tlmi-ok: #16a34a; --tlmi-warn: #d97706; --tlmi-err: #dc2626;
118045
- display: flex; flex-direction: column; gap: 12px; font-size: 14px; color: #1e293b; }
118647
+ display: flex; flex-direction: column; gap: 12px; font-size: 14px; color: #1e293b;
118648
+ font-family: 'Nunito', system-ui, -apple-system, 'Segoe UI', sans-serif; }
118649
+ .tlmi input, .tlmi button, .tlmi table { font-family: inherit; }
118650
+ .tlmi-dev { font-size: 12.5px; font-weight: 700; color: #334155; letter-spacing: 0.2px; text-transform: uppercase; }
118651
+ .tlmi-dev small { display: block; font-weight: 500; color: #94a3b8; font-size: 11px; letter-spacing: 0; }
118652
+ .tlmi-sel-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; }
118653
+ .tlmi-sel-bar input[type="search"] { flex: 1; min-width: 200px; border: 1px solid #ddd; border-radius: 6px; padding: 8px 10px; font: inherit; }
118654
+ .tlmi-sel-count { font-size: 12.5px; color: #64748b; margin-left: auto; }
118655
+ .tlmi-sel { max-height: 320px; overflow: auto; border: 1px solid #e2e8f0; border-radius: 8px; }
118656
+ .tlmi-sel label { display: flex; align-items: center; gap: 10px; padding: 7px 10px; border-bottom: 1px solid #f1f5f9; cursor: pointer; }
118657
+ .tlmi-sel label:hover { background: #f8fafc; }
118658
+ .tlmi-sel label:last-child { border-bottom: none; }
118659
+ .tlmi-sel input { width: 16px; height: 16px; accent-color: var(--tlmi-ac); flex-shrink: 0; }
118046
118660
  .tlmi-stepper { display: flex; gap: 6px; }
118047
118661
  .tlmi-step { flex: 1; display: flex; align-items: center; gap: 8px; color: #64748b; padding: 6px 8px; border-radius: 10px; font-size: 13px; }
118048
118662
  .tlmi-step b { width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center;
@@ -118061,7 +118675,7 @@ function injectStyles15() {
118061
118675
  background: #fff; color: #374151; cursor: pointer; }
118062
118676
  .tlmi-btn.primary { background: var(--tlmi-ac); border-color: var(--tlmi-ac); color: #fff; }
118063
118677
  .tlmi-btn:disabled { opacity: 0.55; cursor: not-allowed; }
118064
- .tlmi-drop { border: 2px dashed #cbd5e1; border-radius: 12px; padding: 22px; text-align: center; color: #64748b; cursor: pointer; }
118678
+ .tlmi-drop { display: block; border: 2px dashed #cbd5e1; border-radius: 12px; padding: 22px; text-align: center; color: #64748b; cursor: pointer; }
118065
118679
  .tlmi-drop[data-over="1"] { border-color: var(--tlmi-ac); background: var(--tlmi-ac-soft); }
118066
118680
  .tlmi-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; }
118067
118681
  .tlmi-kpi { border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 12px; }
@@ -118095,7 +118709,7 @@ function injectStyles15() {
118095
118709
  document.head.appendChild(style);
118096
118710
  }
118097
118711
  function issuesTable(errors, limit = 100) {
118098
- const rows = errors.slice(0, limit).map((e) => `<tr><td>${esc11(e.line)}</td><td>${esc11(e.reason)}</td></tr>`).join("");
118712
+ const rows = errors.slice(0, limit).map((e) => `<tr><td>${esc12(e.line)}</td><td>${esc12(e.reason)}</td></tr>`).join("");
118099
118713
  const more = errors.length > limit ? `<p class="tlmi-muted">\u2026 e mais ${errors.length - limit} erro(s).</p>` : "";
118100
118714
  return `<div class="tlmi-errors"><table><thead><tr><th>Linha</th><th>Problema</th></tr></thead><tbody>${rows}</tbody></table></div>${more}`;
118101
118715
  }
@@ -118112,11 +118726,14 @@ function openTelemetryImportModal(params) {
118112
118726
  const txt = DOMAIN_TEXT[domain];
118113
118727
  const now = params.now ?? (() => Date.now());
118114
118728
  const api = "validate" in params.api ? params.api : createTelemetryImportApi(params.api);
118115
- const { ok: importable, missingKey } = splitImportableDevices(params.devices);
118729
+ const { ok: importableAll, missingKey } = splitImportableDevices(params.devices);
118730
+ const selected = /* @__PURE__ */ new Set();
118731
+ let importable = [];
118732
+ let selFilter = "";
118116
118733
  const s = {
118117
- step: 1,
118734
+ step: 0,
118118
118735
  model: "hourly",
118119
- /** Acumulado: total digitado por device (índice em `importable`) */
118736
+ /** Acumulado: total digitado por device (chave devKey) */
118120
118737
  formTotals: {},
118121
118738
  /** Acumulado: entradas vindas de planilha (null = preenchimento na tela) */
118122
118739
  fileEntries: null,
@@ -118168,17 +118785,54 @@ function openTelemetryImportModal(params) {
118168
118785
  return `<div class="tlmi-stepper">${STEPS2.map((st) => {
118169
118786
  const state6 = st.n === s.step ? "current" : st.n < s.step ? "done" : "todo";
118170
118787
  const label = st.n === 2 && s.model === "accumulated" ? "Valores" : st.label;
118171
- return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n}</b>${label}</div>`;
118788
+ return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n + 1}</b>${label}</div>`;
118172
118789
  }).join("")}</div>`;
118173
118790
  }
118791
+ const visibleDevices2 = () => {
118792
+ const f = norm2(selFilter.trim());
118793
+ return importableAll.filter((d) => !f || norm2(`${d.label} ${d.identifier || ""}`).includes(f));
118794
+ };
118795
+ function selListHtml() {
118796
+ const list = visibleDevices2();
118797
+ if (!list.length) return '<p class="tlmi-muted" style="padding:10px">Nenhum dispositivo encontrado.</p>';
118798
+ return list.map((d) => {
118799
+ const k = devKey(d);
118800
+ const ident = d.identifier && d.identifier.toUpperCase() !== devName(d) ? `<small>${esc12(d.identifier.toUpperCase())}</small>` : "";
118801
+ return `<label><input type="checkbox" data-sel="${esc12(k)}" ${selected.has(k) ? "checked" : ""} />
118802
+ <span class="tlmi-dev">${esc12(devName(d))}${ident}</span></label>`;
118803
+ }).join("");
118804
+ }
118805
+ const selCountText = () => `${fmtNum(selected.size)} de ${fmtNum(importableAll.length)} selecionado(s)`;
118806
+ function step0() {
118807
+ const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados n\xE3o podem ser importados: ${esc12(
118808
+ missingKey.slice(0, 5).map(devName).join(", ")
118809
+ )}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
118810
+ return `
118811
+ <div class="tlmi-card"><h3>Quais dispositivos voc\xEA quer preencher?</h3>
118812
+ <div class="tlmi-sel-bar">
118813
+ <input type="search" data-field="sel-filter" placeholder="Buscar dispositivo\u2026" value="${esc12(selFilter)}" aria-label="Buscar dispositivo" />
118814
+ <button class="tlmi-btn" type="button" data-action="sel-all">Marcar todos</button>
118815
+ <button class="tlmi-btn" type="button" data-action="sel-none">Desmarcar todos</button>
118816
+ <span class="tlmi-sel-count" data-role="sel-count">${selCountText()}</span>
118817
+ </div>
118818
+ <div class="tlmi-sel" data-role="sel-list">${selListHtml()}</div>
118819
+ <p class="tlmi-muted" style="margin-top:6px">Com a busca preenchida, Marcar/Desmarcar todos vale s\xF3 para os dispositivos encontrados.</p>
118820
+ </div>
118821
+ ${warn}`;
118822
+ }
118823
+ function refreshSelection() {
118824
+ const list = root.querySelector('[data-role="sel-list"]');
118825
+ if (list) list.innerHTML = selListHtml();
118826
+ const count = root.querySelector('[data-role="sel-count"]');
118827
+ if (count) count.textContent = selCountText();
118828
+ syncFooter();
118829
+ }
118174
118830
  function apiErrorBanner() {
118175
118831
  if (!s.apiError) return "";
118176
- return `<div class="tlmi-banner err" role="alert">${esc11(s.apiError)}${s.apiDetail ? `<div class="tlmi-tech">${esc11(s.apiDetail)}</div>` : ""}</div>`;
118832
+ return `<div class="tlmi-banner err" role="alert">${esc12(s.apiError)}${s.apiDetail ? `<div class="tlmi-tech">${esc12(s.apiDetail)}</div>` : ""}</div>`;
118177
118833
  }
118178
118834
  function step1() {
118179
- const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados ficam fora do modelo: ${esc11(
118180
- missingKey.slice(0, 5).map((d) => d.label).join(", ")
118181
- )}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
118835
+ const warn = "";
118182
118836
  const model = (value, title, hint) => `
118183
118837
  <label class="tlmi-model" data-selected="${s.model === value ? 1 : 0}">
118184
118838
  <input type="radio" name="tlmi-model" data-field="model" value="${value}" ${s.model === value ? "checked" : ""} />
@@ -118203,16 +118857,16 @@ function openTelemetryImportModal(params) {
118203
118857
  ${warn}
118204
118858
  <div class="tlmi-card"><h3>${s.model === "accumulated" ? "Per\xEDodo" : "Modelo da planilha"}</h3>
118205
118859
  <div class="tlmi-row">
118206
- <label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc11(s.period.start)}" /></label>
118207
- <label class="tlmi-field">Fim<input type="date" data-field="end" value="${esc11(s.period.end)}" /></label>
118860
+ <label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc12(s.period.start)}" /></label>
118861
+ <label class="tlmi-field">Fim<input type="date" data-field="end" value="${esc12(s.period.end)}" /></label>
118208
118862
  <button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
118209
118863
  </div>
118210
- <p class="tlmi-muted" style="margin-top:8px">${importable.length} dispositivo(s) no modelo. ${s.model === "accumulated" ? "Para digitar na tela, clique em <strong>Avan\xE7ar</strong>." : "J\xE1 tem a planilha preenchida? Clique em <strong>Avan\xE7ar</strong>."}</p>
118864
+ <p class="tlmi-muted" style="margin-top:8px">${importable.length} dispositivo(s) selecionado(s). ${s.model === "accumulated" ? "Para digitar na tela, clique em <strong>Avan\xE7ar</strong>." : "J\xE1 tem a planilha preenchida? Clique em <strong>Avan\xE7ar</strong>."}</p>
118211
118865
  </div>`;
118212
118866
  }
118213
118867
  function step2() {
118214
- const summary = s.fileName ? s.parseError ? `<div class="tlmi-banner err">${esc11(s.parseError)}</div>` : `<div class="tlmi-kpis">
118215
- <div class="tlmi-kpi"><span>Arquivo</span><strong style="font-size:13px">${esc11(s.fileName)}</strong></div>
118868
+ const summary = s.fileName ? s.parseError ? `<div class="tlmi-banner err">${esc12(s.parseError)}</div>` : `<div class="tlmi-kpis">
118869
+ <div class="tlmi-kpi"><span>Arquivo</span><strong style="font-size:13px">${esc12(s.fileName)}</strong></div>
118216
118870
  <div class="tlmi-kpi"><span>Linhas para importar</span><strong>${fmtNum(s.rows.length)}</strong></div>
118217
118871
  <div class="tlmi-kpi"><span>Em branco (ignoradas)</span><strong>${fmtNum(s.skippedEmpty)}</strong></div>
118218
118872
  <div class="tlmi-kpi"><span>Com erro</span><strong style="color:${s.localErrors.length ? "#dc2626" : "#16a34a"}">${fmtNum(s.localErrors.length)}</strong></div>
@@ -118252,12 +118906,14 @@ function openTelemetryImportModal(params) {
118252
118906
  }
118253
118907
  function step2Accumulated() {
118254
118908
  const fromFile = !!s.fileName && !s.parseError;
118255
- const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc11(s.fileName)}</strong>.
118256
- <button class="tlmi-btn" type="button" data-action="use-form">Preencher na tela</button></p>` : `<p class="tlmi-muted" style="margin-bottom:8px">Per\xEDodo: ${esc11(s.period.start)} a ${esc11(s.period.end)}. Deixe em branco o que n\xE3o quer importar.</p>
118909
+ const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc12(s.fileName)}</strong>.
118910
+ <button class="tlmi-btn" type="button" data-action="use-form">Preencher na tela</button></p>` : `<p class="tlmi-muted" style="margin-bottom:8px">Per\xEDodo: ${esc12(s.period.start)} a ${esc12(s.period.end)}. Deixe em branco o que n\xE3o quer importar.</p>
118257
118911
  <div class="tlmi-acc"><table><thead><tr><th>Dispositivo</th><th>Total (${txt.unit})</th></tr></thead><tbody>
118258
118912
  ${importable.map(
118259
- (d, i) => `<tr><td>${esc11(d.label)}</td>
118260
- <td><input inputmode="decimal" data-total="${i}" aria-label="Total de ${esc11(d.label)}" value="${esc11(s.formTotals[i] ?? "")}" /></td></tr>`
118913
+ (d) => `<tr><td class="tlmi-dev">${esc12(devName(d))}</td>
118914
+ <td><input inputmode="decimal" data-total="${esc12(devKey(d))}" aria-label="Total de ${esc12(devName(d))}" value="${esc12(
118915
+ s.formTotals[devKey(d)] ?? ""
118916
+ )}" /></td></tr>`
118261
118917
  ).join("")}
118262
118918
  </tbody></table></div>`;
118263
118919
  return `
@@ -118270,7 +118926,7 @@ function openTelemetryImportModal(params) {
118270
118926
  <input type="file" accept=".xlsx,.xls,.csv" data-field="file" hidden />
118271
118927
  \u{1F4C4} Clique ou arraste a planilha aqui (.xlsx ou .csv)
118272
118928
  </label>
118273
- ${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${esc11(s.parseError)}</div>` : ""}
118929
+ ${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${esc12(s.parseError)}</div>` : ""}
118274
118930
  </div>
118275
118931
  <div data-role="acc-summary" style="display:flex;flex-direction:column;gap:12px">${accSummaryHtml()}</div>`;
118276
118932
  }
@@ -118296,7 +118952,7 @@ function openTelemetryImportModal(params) {
118296
118952
  <div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
118297
118953
  <div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
118298
118954
  </div>
118299
- <p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${esc11(period)}</p>
118955
+ <p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${esc12(period)}</p>
118300
118956
  ${reactiveWarn}
118301
118957
  ${real > 0 ? `<div class="tlmi-banner warn"><strong>${fmtNum(real)} leitura(s) reais do medidor</strong> ser\xE3o substitu\xEDdas pelos valores da planilha.
118302
118958
  <label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
@@ -118315,7 +118971,7 @@ function openTelemetryImportModal(params) {
118315
118971
  <div class="tlmi-muted" style="margin-top:4px">Dispositivos manuais continuam aparecendo sem comunica\xE7\xE3o no status:
118316
118972
  o status conta s\xF3 leitura medida. Os totais e os cards usam os dados importados.</div></div>`;
118317
118973
  } else if (j.status === "failed") {
118318
- banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc11(j.error)}` : "."}</div>`;
118974
+ banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc12(j.error)}` : "."}</div>`;
118319
118975
  } else if (j.status === "cancelled") {
118320
118976
  banner = '<div class="tlmi-banner warn">Importa\xE7\xE3o cancelada. As leituras anteriores foram mantidas.</div>';
118321
118977
  } else if (j.status === "reverted") {
@@ -118327,14 +118983,14 @@ function openTelemetryImportModal(params) {
118327
118983
  <span class="tlmi-muted">${s.confirmRevert ? "Remove as horas importadas e devolve as leituras apagadas. Clique de novo para confirmar." : "Use para remover uma importa\xE7\xE3o errada ou de teste."}</span>
118328
118984
  </div>` : "";
118329
118985
  return `
118330
- <div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc11(statusText)}</span></h3>
118986
+ <div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc12(statusText)}</span></h3>
118331
118987
  <div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
118332
118988
  <div class="tlmi-kpis" style="margin-top:12px">
118333
118989
  <div class="tlmi-kpi"><span>Progresso</span><strong>${fmtNum(pct)}%</strong></div>
118334
118990
  <div class="tlmi-kpi"><span>Leituras removidas</span><strong>${fmtNum(j.deleted)}</strong></div>
118335
118991
  <div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
118336
118992
  </div>
118337
- ${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc11(j.phase)}</p>` : ""}
118993
+ ${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc12(j.phase)}</p>` : ""}
118338
118994
  ${!terminal && j.status !== "reverting" ? `<div style="margin-top:12px"><button class="tlmi-btn" type="button" data-action="cancel" ${s.busy ? "disabled" : ""}>Cancelar importa\xE7\xE3o</button>
118339
118995
  <span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
118340
118996
  ${revert}
@@ -118345,14 +119001,15 @@ function openTelemetryImportModal(params) {
118345
119001
  function render3() {
118346
119002
  if (closed) return;
118347
119003
  const step2Body = () => s.model === "accumulated" ? step2Accumulated() : step2();
118348
- const body = s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
119004
+ const body = s.step === 0 ? step0() : s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
118349
119005
  root.innerHTML = stepper() + body;
118350
119006
  syncFooter();
118351
119007
  }
118352
119008
  function syncFooter() {
118353
119009
  const v = s.validation;
118354
119010
  const terminal = s.job ? TERMINAL_JOB_STATUSES.includes(s.job.status) : false;
118355
- modal.setButton("back", { hidden: s.step === 1 || s.step === 4, disabled: s.busy });
119011
+ modal.setButton("back", { hidden: s.step === 0 || s.step === 4, disabled: s.busy });
119012
+ if (s.step === 0) modal.setButton("next", { label: "Avan\xE7ar", disabled: selected.size === 0, hidden: false });
118356
119013
  if (s.step === 1) modal.setButton("next", { label: "Avan\xE7ar", disabled: false, hidden: false });
118357
119014
  if (s.step === 2)
118358
119015
  modal.setButton("next", {
@@ -118371,7 +119028,7 @@ function openTelemetryImportModal(params) {
118371
119028
  if (s.step === 4) modal.setButton("next", { label: "Concluir", hidden: !terminal, disabled: false });
118372
119029
  }
118373
119030
  function goBack() {
118374
- if (s.busy || s.step === 1 || s.step === 4) return;
119031
+ if (s.busy || s.step === 0 || s.step === 4) return;
118375
119032
  s.apiError = "";
118376
119033
  if (s.step === 3) s.validation = null;
118377
119034
  s.step = s.step - 1;
@@ -118379,7 +119036,16 @@ function openTelemetryImportModal(params) {
118379
119036
  }
118380
119037
  async function goNext() {
118381
119038
  if (s.busy) return;
118382
- if (s.step === 1) {
119039
+ if (s.step === 0) {
119040
+ if (selected.size === 0) return;
119041
+ importable = importableAll.filter((d) => selected.has(devKey(d)));
119042
+ for (const k of Object.keys(s.formTotals)) if (!selected.has(k)) delete s.formTotals[k];
119043
+ s.rows = [];
119044
+ s.localErrors = [];
119045
+ s.validation = null;
119046
+ s.step = 1;
119047
+ render3();
119048
+ } else if (s.step === 1) {
118383
119049
  if (s.model === "accumulated") recomputeAccumulated();
118384
119050
  s.step = 2;
118385
119051
  render3();
@@ -118410,10 +119076,10 @@ function openTelemetryImportModal(params) {
118410
119076
  const entries = [];
118411
119077
  const errors = [];
118412
119078
  importable.forEach((d, i) => {
118413
- const total = parseDecimal(s.formTotals[i] ?? "");
119079
+ const total = parseDecimal(s.formTotals[devKey(d)] ?? "");
118414
119080
  if (total === null) return;
118415
119081
  if (Number.isNaN(total) || total < 0) {
118416
- errors.push({ line: i + 1, reason: `${d.label}: total deve ser n\xFAmero \u2265 0` });
119082
+ errors.push({ line: i + 1, reason: `${devName(d)}: total deve ser n\xFAmero \u2265 0` });
118417
119083
  return;
118418
119084
  }
118419
119085
  entries.push({
@@ -118564,6 +119230,14 @@ function openTelemetryImportModal(params) {
118564
119230
  const el2 = e.target.closest("[data-action]");
118565
119231
  if (!el2) return;
118566
119232
  if (el2.dataset.action === "template") downloadTemplate();
119233
+ if (el2.dataset.action === "sel-all" || el2.dataset.action === "sel-none") {
119234
+ const on = el2.dataset.action === "sel-all";
119235
+ for (const d of visibleDevices2()) {
119236
+ if (on) selected.add(devKey(d));
119237
+ else selected.delete(devKey(d));
119238
+ }
119239
+ refreshSelection();
119240
+ }
118567
119241
  if (el2.dataset.action === "cancel") void cancelJob();
118568
119242
  if (el2.dataset.action === "revert") void revertJob();
118569
119243
  if (el2.dataset.action === "use-form") {
@@ -118574,13 +119248,26 @@ function openTelemetryImportModal(params) {
118574
119248
  });
118575
119249
  root.addEventListener("input", (e) => {
118576
119250
  const t = e.target;
119251
+ if (t.dataset.field === "sel-filter") {
119252
+ selFilter = t.value;
119253
+ refreshSelection();
119254
+ return;
119255
+ }
118577
119256
  if (t.dataset.total === void 0) return;
118578
- s.formTotals[Number(t.dataset.total)] = t.value;
119257
+ s.formTotals[t.dataset.total] = t.value;
118579
119258
  recomputeAccumulated();
118580
119259
  refreshAccSummary();
118581
119260
  });
118582
119261
  root.addEventListener("change", (e) => {
118583
119262
  const t = e.target;
119263
+ if (t.dataset.sel !== void 0) {
119264
+ if (t.checked) selected.add(t.dataset.sel);
119265
+ else selected.delete(t.dataset.sel);
119266
+ const count = root.querySelector('[data-role="sel-count"]');
119267
+ if (count) count.textContent = selCountText();
119268
+ syncFooter();
119269
+ return;
119270
+ }
118584
119271
  if (t.dataset.field === "start") s.period.start = t.value;
118585
119272
  if (t.dataset.field === "end") s.period.end = t.value;
118586
119273
  if (t.dataset.field === "file") void loadFile(t.files?.[0]);
@@ -118627,6 +119314,38 @@ var NAME_PREFIX = {
118627
119314
  water: "Hidr. "
118628
119315
  };
118629
119316
  var MANUAL_ASSET_SUFFIX = "_DEVICES_MANUAIS";
119317
+ var STANDARD_DEVICE_PROFILES = {
119318
+ energy: [
119319
+ "3F_MEDIDOR",
119320
+ "ENTRADA",
119321
+ "RELOGIO",
119322
+ "SUBESTACAO",
119323
+ "TRANSFORMADOR",
119324
+ "ELEVADOR",
119325
+ "ESCADA_ROLANTE",
119326
+ "CHILLER",
119327
+ "FANCOIL",
119328
+ "BOMBA_CAG",
119329
+ "BOMBA_HIDRAULICA",
119330
+ "BOMBA_INCENDIO",
119331
+ "BOMBA_POCO",
119332
+ "MOTOR"
119333
+ ],
119334
+ water: ["HIDROMETRO", "HIDROMETRO_AREA_COMUM", "HIDROMETRO_SHOPPING", "HIDROMETRO_ENTRADA"]
119335
+ };
119336
+ var standardNameToken = (deviceProfile) => ["3F_MEDIDOR", "HIDROMETRO"].includes(deviceProfile) ? "LOJA" : deviceProfile;
119337
+ function standardDeviceName(domain, sigla, deviceProfile, seq) {
119338
+ return `${NAME_PREFIX[domain]}${sigla}_${standardNameToken(deviceProfile)}_${String(seq).padStart(3, "0")}`;
119339
+ }
119340
+ function nextStandardSeq(domain, sigla, deviceProfile, existingNames) {
119341
+ const esc13 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
119342
+ const re = new RegExp(`^${esc13(NAME_PREFIX[domain])}${esc13(sigla)}_${esc13(standardNameToken(deviceProfile))}_(\\d+)$`, "i");
119343
+ const max = existingNames.reduce((acc, n) => {
119344
+ const m = re.exec(String(n || "").trim());
119345
+ return m ? Math.max(acc, Number(m[1])) : acc;
119346
+ }, 0);
119347
+ return max + 1;
119348
+ }
118630
119349
  var ManualDeviceError = class extends Error {
118631
119350
  constructor(message, detail) {
118632
119351
  super(message);
@@ -118644,8 +119363,8 @@ function siglaFromManualAsset(assetName) {
118644
119363
  return /^[A-Z0-9_]+$/.test(sigla) ? sigla : null;
118645
119364
  }
118646
119365
  function nextManualSeq(domain, sigla, existingNames) {
118647
- const esc12 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
118648
- const re = new RegExp(`^${esc12(NAME_PREFIX[domain])}${esc12(sigla)}_LOJA_(\\d+)_MANUAL$`, "i");
119366
+ const esc13 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
119367
+ const re = new RegExp(`^${esc13(NAME_PREFIX[domain])}${esc13(sigla)}_LOJA_(\\d+)_MANUAL$`, "i");
118649
119368
  const max = existingNames.reduce((acc, n) => {
118650
119369
  const m = re.exec(String(n || "").trim());
118651
119370
  return m ? Math.max(acc, Number(m[1])) : acc;
@@ -118715,10 +119434,36 @@ async function resolveManualDeviceName(params) {
118715
119434
  deviceProfile: profile
118716
119435
  };
118717
119436
  }
119437
+ async function resolveStandardDeviceName(params) {
119438
+ const profile = String(params.deviceProfile || "").trim().toUpperCase();
119439
+ if (!MANUAL_DEVICE_PROFILES[params.domain]) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${params.domain}`);
119440
+ if (!profile) throw new ManualDeviceError("Escolha o tipo do dispositivo.");
119441
+ if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
119442
+ const api = await buildTbApi(params);
119443
+ const { asset, sigla } = await findManualAsset(api, params.customerId);
119444
+ const token = standardNameToken(profile);
119445
+ const existing = await api(
119446
+ "GET",
119447
+ `/api/customer/${encodeURIComponent(params.customerId)}/devices?pageSize=1000&page=0&textSearch=${encodeURIComponent(`${sigla}_${token}_`)}`
119448
+ );
119449
+ const names = (existing?.data || []).map((d) => String(d?.name || ""));
119450
+ const seq = nextStandardSeq(params.domain, sigla, profile, names);
119451
+ return {
119452
+ name: standardDeviceName(params.domain, sigla, profile, seq),
119453
+ sigla,
119454
+ seq,
119455
+ assetId: asset.id.id,
119456
+ assetName: asset.name,
119457
+ deviceProfile: profile
119458
+ };
119459
+ }
118718
119460
  async function createManualDevice(params) {
118719
119461
  const domain = params.domain;
118720
- const profile = MANUAL_DEVICE_PROFILES[domain];
118721
- if (!profile) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
119462
+ if (!MANUAL_DEVICE_PROFILES[domain]) throw new ManualDeviceError(`Dom\xEDnio inv\xE1lido: ${domain}`);
119463
+ const profile = String(params.deviceProfile || "").trim() || MANUAL_DEVICE_PROFILES[domain];
119464
+ if (params.asset && !String(params.name || "").trim()) {
119465
+ throw new ManualDeviceError("Nome do dispositivo n\xE3o reservado.", "asset informado sem name");
119466
+ }
118722
119467
  const label = String(params.label || "").trim();
118723
119468
  const identifier = String(params.identifier || "").trim();
118724
119469
  if (!label) throw new ManualDeviceError("Informe a etiqueta.");
@@ -118726,7 +119471,7 @@ async function createManualDevice(params) {
118726
119471
  if (!params.customerId) throw new ManualDeviceError("Cliente n\xE3o identificado.");
118727
119472
  const api = await buildTbApi(params);
118728
119473
  const cid = encodeURIComponent(params.customerId);
118729
- const { asset, sigla } = await findManualAsset(api, params.customerId);
119474
+ const { asset, sigla } = params.asset ? { asset: { id: { id: params.asset.id }, name: params.asset.name }, sigla: "" } : await findManualAsset(api, params.customerId);
118730
119475
  const fixedName = String(params.name || "").trim();
118731
119476
  let seq = fixedName ? 0 : nextManualSeq(domain, sigla, await existingManualNames(api, params.customerId, sigla));
118732
119477
  let deviceProfileId;
@@ -118786,9 +119531,17 @@ async function createManualDevice(params) {
118786
119531
  }
118787
119532
 
118788
119533
  // src/components/premium-modals/manual-device/openManualDeviceModal.ts
119534
+ var MANUAL_HINT = "Cadastre um ponto de leitura manual. Ele aparece nesta lista e n\xE3o entra nos totais nem nos relat\xF3rios.";
119535
+ var STANDARD_HINT = "Cadastre um medidor ligado \xE0 central. Ele \xE9 criado no GCDR, Ingestion, ThingsBoard e na central.";
118789
119536
  var DOMAIN_TEXT2 = {
118790
- energy: { title: "Novo medidor de energia manual", icon: "\u26A1", noun: "Medidor de energia" },
118791
- water: { title: "Novo hidr\xF4metro manual", icon: "\u{1F4A7}", noun: "Hidr\xF4metro" }
119537
+ manual: {
119538
+ energy: { title: "Novo medidor de energia manual", icon: "\u26A1", noun: "Medidor de energia", hint: MANUAL_HINT },
119539
+ water: { title: "Novo hidr\xF4metro manual", icon: "\u{1F4A7}", noun: "Hidr\xF4metro", hint: MANUAL_HINT }
119540
+ },
119541
+ standard: {
119542
+ energy: { title: "Novo medidor de energia", icon: "\u26A1", noun: "Medidor de energia", hint: STANDARD_HINT },
119543
+ water: { title: "Novo hidr\xF4metro", icon: "\u{1F4A7}", noun: "Hidr\xF4metro", hint: STANDARD_HINT }
119544
+ }
118792
119545
  };
118793
119546
  var STYLE_ID16 = "myio-manualdev-styles";
118794
119547
  function escapeHtml16(v) {
@@ -118847,12 +119600,42 @@ function injectStyles16() {
118847
119600
  `;
118848
119601
  document.head.appendChild(style);
118849
119602
  }
118850
- function formHtml(domain, values, error, detail) {
118851
- const t = DOMAIN_TEXT2[domain];
119603
+ function selectHtml(name, label, placeholder, opts, value, disabled = false) {
119604
+ return `
119605
+ <label class="myio-manualdev__field">
119606
+ <span class="myio-manualdev__label">${escapeHtml16(label)}</span>
119607
+ <select class="myio-manualdev__input" name="${name}"${disabled ? " disabled" : ""}>
119608
+ <option value="">${escapeHtml16(placeholder)}</option>
119609
+ ${opts.map((o) => `<option value="${escapeHtml16(o.value)}"${o.value === value ? " selected" : ""}>${escapeHtml16(o.text)}</option>`).join("")}
119610
+ </select>
119611
+ </label>`;
119612
+ }
119613
+ function extraFieldsHtml(s) {
119614
+ const profile = s.kind === "standard" ? selectHtml("deviceProfile", "Tipo", "Selecione o tipo", s.profiles.map((p) => ({ value: p, text: p })), s.deviceProfile) : "";
119615
+ let central = "";
119616
+ if (s.centrals === null) {
119617
+ central = selectHtml("centralId", "Central", "Carregando centrais\u2026", [], "", true);
119618
+ } else if (s.centrals.length > 1) {
119619
+ central = selectHtml(
119620
+ "centralId",
119621
+ "Central",
119622
+ "Selecione a central",
119623
+ s.centrals.map((c) => ({
119624
+ value: c.id,
119625
+ text: `${c.name || c.id}${typeof c.deviceCount === "number" ? ` \xB7 ${c.deviceCount} devices` : ""}`
119626
+ })),
119627
+ s.centralId
119628
+ );
119629
+ }
119630
+ return profile + central;
119631
+ }
119632
+ function formHtml(s, error, detail) {
119633
+ const t = DOMAIN_TEXT2[s.kind][s.domain];
119634
+ const values = s;
118852
119635
  return `
118853
119636
  <form class="myio-manualdev" novalidate>
118854
- <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>
118855
- <span class="myio-manualdev__type">${t.icon} ${escapeHtml16(t.noun)} manual</span>
119637
+ <p class="myio-manualdev__hint">${escapeHtml16(t.hint)}</p>
119638
+ <span class="myio-manualdev__type">${t.icon} ${escapeHtml16(t.noun)}${s.kind === "manual" ? " manual" : ""}</span>
118856
119639
  <label class="myio-manualdev__field">
118857
119640
  <span class="myio-manualdev__label">Etiqueta</span>
118858
119641
  <input class="myio-manualdev__input" name="label" maxlength="80" autocomplete="off"
@@ -118863,6 +119646,7 @@ function formHtml(domain, values, error, detail) {
118863
119646
  <input class="myio-manualdev__input" name="identifier" maxlength="40" autocomplete="off"
118864
119647
  placeholder="Ex.: STB01010" value="${escapeHtml16(values.identifier)}" />
118865
119648
  </label>
119649
+ ${extraFieldsHtml(s)}
118866
119650
  ${error ? `<p class="myio-manualdev__error" role="alert">${escapeHtml16(error)}${detail ? `<small class="myio-manualdev__detail">${escapeHtml16(detail)}</small>` : ""}</p>` : ""}
118867
119651
  <button type="submit" hidden></button>
118868
119652
  </form>`;
@@ -118871,7 +119655,7 @@ function successHtml(domain, r, tech) {
118871
119655
  return `
118872
119656
  <div class="myio-manualdev__ok">
118873
119657
  <div class="myio-manualdev__ok-icon">\u2705</div>
118874
- <p class="myio-manualdev__ok-title">${escapeHtml16(DOMAIN_TEXT2[domain].noun)} criado</p>
119658
+ <p class="myio-manualdev__ok-title">${escapeHtml16(DOMAIN_TEXT2.manual[domain].noun)} criado</p>
118875
119659
  <p class="myio-manualdev__ok-text"><strong>${escapeHtml16(r.label)}</strong> \xB7 ${escapeHtml16(r.identifier)}</p>
118876
119660
  ${tech ? `<div class="myio-manualdev__tech">
118877
119661
  device <code>${escapeHtml16(r.name)}</code><br/>
@@ -118931,18 +119715,51 @@ function progressHtml(steps, message, ok, open = false) {
118931
119715
  ${moreHtml(stepsHtml(steps), open)}
118932
119716
  </div>`;
118933
119717
  }
119718
+ function initialState(params, kind, loadsCentrals) {
119719
+ const profiles = kind === "standard" ? (params.deviceProfiles?.length ? params.deviceProfiles : STANDARD_DEVICE_PROFILES[params.domain]).slice() : [];
119720
+ const def = String(params.defaultDeviceProfile || "").toUpperCase();
119721
+ return {
119722
+ kind,
119723
+ domain: params.domain,
119724
+ label: "",
119725
+ identifier: "",
119726
+ deviceProfile: profiles.includes(def) ? def : "",
119727
+ centralId: "",
119728
+ profiles,
119729
+ centrals: loadsCentrals ? null : []
119730
+ };
119731
+ }
119732
+ function readForm(body, s) {
119733
+ const val = (name) => (body.querySelector(`[name="${name}"]`)?.value ?? "").trim();
119734
+ s.label = val("label");
119735
+ s.identifier = val("identifier");
119736
+ if (s.kind === "standard") s.deviceProfile = val("deviceProfile");
119737
+ if (s.centrals && s.centrals.length > 1) s.centralId = val("centralId");
119738
+ }
119739
+ function missingField(s) {
119740
+ if (!s.label) return { name: "label", msg: "Informe a etiqueta." };
119741
+ if (!s.identifier) return { name: "identifier", msg: "Informe o identificador." };
119742
+ if (s.kind === "standard" && !s.deviceProfile) return { name: "deviceProfile", msg: "Escolha o tipo." };
119743
+ if (s.centrals === null) return { name: "centralId", msg: "Aguarde o carregamento das centrais." };
119744
+ if (s.centrals.length > 1 && !s.centralId) return { name: "centralId", msg: "Escolha a central." };
119745
+ return null;
119746
+ }
118934
119747
  function openManualDeviceModal(params) {
118935
119748
  const domain = params.domain;
118936
119749
  if (!MANUAL_DEVICE_PROFILES[domain]) throw new Error(`[openManualDeviceModal] dom\xEDnio inv\xE1lido: ${domain}`);
119750
+ const kind = params.kind === "standard" ? "standard" : "manual";
119751
+ if (kind === "standard" && !params.provisioner) {
119752
+ throw new Error('[openManualDeviceModal] kind "standard" exige provisioner');
119753
+ }
118937
119754
  injectStyles16();
118938
- if (params.provisioner) return openProvisionedModal(params, params.provisioner);
118939
- const values = { label: "", identifier: "" };
119755
+ if (params.provisioner) return openProvisionedModal(params, params.provisioner, kind);
119756
+ const state6 = initialState(params, "manual", false);
118940
119757
  let busy = false;
118941
119758
  let created = null;
118942
119759
  const modal = openStandardModal({
118943
- title: DOMAIN_TEXT2[domain].title,
118944
- icon: DOMAIN_TEXT2[domain].icon,
118945
- bodyHtml: formHtml(domain, values),
119760
+ title: DOMAIN_TEXT2.manual[domain].title,
119761
+ icon: DOMAIN_TEXT2.manual[domain].icon,
119762
+ bodyHtml: formHtml(state6),
118946
119763
  width: 460,
118947
119764
  container: params.container,
118948
119765
  buttons: [
@@ -118972,13 +119789,12 @@ function openManualDeviceModal(params) {
118972
119789
  async function submit() {
118973
119790
  if (busy || created) return;
118974
119791
  const body = modal.getBodyEl();
118975
- values.label = (body.querySelector('input[name="label"]')?.value || "").trim();
118976
- values.identifier = (body.querySelector('input[name="identifier"]')?.value || "").trim();
118977
- const missing = !values.label ? "label" : !values.identifier ? "identifier" : null;
119792
+ readForm(body, state6);
119793
+ const missing = missingField(state6);
118978
119794
  if (missing) {
118979
- modal.setBodyHtml(formHtml(domain, values, missing === "label" ? "Informe a etiqueta." : "Informe o identificador."));
119795
+ modal.setBodyHtml(formHtml(state6, missing.msg));
118980
119796
  bindForm(false);
118981
- const input = body.querySelector(`input[name="${missing}"]`);
119797
+ const input = body.querySelector(`[name="${missing.name}"]`);
118982
119798
  input?.setAttribute("aria-invalid", "true");
118983
119799
  input?.focus();
118984
119800
  return;
@@ -118988,14 +119804,14 @@ function openManualDeviceModal(params) {
118988
119804
  modal.setButton("cancel", { disabled: true });
118989
119805
  body.querySelectorAll("input").forEach((i) => i.disabled = true);
118990
119806
  try {
118991
- created = await createManualDevice({ ...params, label: values.label, identifier: values.identifier });
119807
+ created = await createManualDevice({ ...params, label: state6.label, identifier: state6.identifier });
118992
119808
  modal.setBodyHtml(successHtml(domain, created, !!params.showTechnicalDetails));
118993
119809
  modal.setButton("cancel", { hidden: true });
118994
119810
  modal.setButton("create", { disabled: false, label: "Concluir" });
118995
119811
  } catch (err) {
118996
119812
  const msg = err instanceof ManualDeviceError ? err.message : "N\xE3o foi poss\xEDvel criar o dispositivo.";
118997
119813
  const detail = params.showTechnicalDetails ? (err instanceof ManualDeviceError ? err.detail : String(err?.message || err)) || void 0 : void 0;
118998
- modal.setBodyHtml(formHtml(domain, values, msg, detail));
119814
+ modal.setBodyHtml(formHtml(state6, msg, detail));
118999
119815
  bindForm();
119000
119816
  modal.setButton("create", { disabled: false, label: "Criar" });
119001
119817
  modal.setButton("cancel", { disabled: false });
@@ -119005,16 +119821,17 @@ function openManualDeviceModal(params) {
119005
119821
  }
119006
119822
  return modal;
119007
119823
  }
119008
- function openProvisionedModal(params, provisioner) {
119824
+ function openProvisionedModal(params, provisioner, kind) {
119009
119825
  const domain = params.domain;
119010
- const values = { label: "", identifier: "" };
119826
+ const state6 = initialState(params, kind, typeof provisioner.options === "function");
119011
119827
  let phase = "form";
119012
119828
  let plan = null;
119013
119829
  let outcome = null;
119830
+ const text2 = DOMAIN_TEXT2[kind][domain];
119014
119831
  const modal = openStandardModal({
119015
- title: DOMAIN_TEXT2[domain].title,
119016
- icon: DOMAIN_TEXT2[domain].icon,
119017
- bodyHtml: formHtml(domain, values),
119832
+ title: text2.title,
119833
+ icon: text2.icon,
119834
+ bodyHtml: formHtml(state6),
119018
119835
  width: 560,
119019
119836
  container: params.container,
119020
119837
  buttons: [
@@ -119043,37 +119860,63 @@ function openProvisionedModal(params, provisioner) {
119043
119860
  if (focus) form?.querySelector('input[name="label"]')?.focus();
119044
119861
  };
119045
119862
  bindForm();
119046
- function showForm(error, detail) {
119047
- phase = "form";
119048
- modal.setBodyHtml(formHtml(domain, values, error, detail));
119049
- bindForm();
119050
- modal.setButton("back", { hidden: true });
119051
- modal.setButton("cancel", { disabled: false, hidden: false });
119052
- modal.setButton("next", { disabled: false, label: "Revisar" });
119053
- }
119054
119863
  const errorText = (err) => {
119055
119864
  const msg = err instanceof ManualDeviceError ? err.message : "N\xE3o foi poss\xEDvel montar o plano.";
119056
119865
  const detail = params.showTechnicalDetails ? (err instanceof ManualDeviceError ? err.detail : String(err?.message || err)) || void 0 : void 0;
119057
119866
  return { msg, detail };
119058
119867
  };
119868
+ if (provisioner.options) {
119869
+ provisioner.options({ domain, kind }).then((o) => {
119870
+ const centrals = Array.isArray(o?.centrals) ? o.centrals : [];
119871
+ if (phase !== "form") {
119872
+ state6.centrals = centrals;
119873
+ return;
119874
+ }
119875
+ readForm(modal.getBodyEl(), state6);
119876
+ state6.centrals = centrals;
119877
+ if (centrals.length === 1) state6.centralId = centrals[0].id;
119878
+ showForm(void 0, void 0, false);
119879
+ }).catch((err) => {
119880
+ state6.centrals = [];
119881
+ if (phase === "form") {
119882
+ readForm(modal.getBodyEl(), state6);
119883
+ const { detail } = errorText(err);
119884
+ showForm("N\xE3o foi poss\xEDvel carregar as centrais.", detail, false);
119885
+ }
119886
+ });
119887
+ }
119888
+ function showForm(error, detail, focus = true) {
119889
+ phase = "form";
119890
+ modal.setBodyHtml(formHtml(state6, error, detail));
119891
+ bindForm(focus);
119892
+ modal.setButton("back", { hidden: true });
119893
+ modal.setButton("cancel", { disabled: false, hidden: false });
119894
+ modal.setButton("next", { disabled: false, label: "Revisar" });
119895
+ }
119059
119896
  async function review() {
119060
119897
  if (phase !== "form") return;
119061
119898
  const body = modal.getBodyEl();
119062
- values.label = (body.querySelector('input[name="label"]')?.value || "").trim();
119063
- values.identifier = (body.querySelector('input[name="identifier"]')?.value || "").trim();
119064
- const missing = !values.label ? "label" : !values.identifier ? "identifier" : null;
119899
+ readForm(body, state6);
119900
+ const missing = missingField(state6);
119065
119901
  if (missing) {
119066
- showForm(missing === "label" ? "Informe a etiqueta." : "Informe o identificador.");
119067
- const input = modal.getBodyEl().querySelector(`input[name="${missing}"]`);
119902
+ showForm(missing.msg);
119903
+ const input = modal.getBodyEl().querySelector(`[name="${missing.name}"]`);
119068
119904
  input?.setAttribute("aria-invalid", "true");
119069
119905
  input?.focus();
119070
119906
  return;
119071
119907
  }
119072
119908
  phase = "planning";
119073
119909
  modal.setButton("next", { disabled: true, label: "Revisando\u2026" });
119074
- body.querySelectorAll("input").forEach((i) => i.disabled = true);
119910
+ body.querySelectorAll("input, select").forEach((i) => i.disabled = true);
119075
119911
  try {
119076
- plan = await provisioner.plan({ domain, label: values.label, identifier: values.identifier });
119912
+ plan = await provisioner.plan({
119913
+ domain,
119914
+ label: state6.label,
119915
+ identifier: state6.identifier,
119916
+ kind,
119917
+ ...kind === "standard" ? { deviceProfile: state6.deviceProfile } : {},
119918
+ ...state6.centralId ? { centralId: state6.centralId } : {}
119919
+ });
119077
119920
  phase = "plan";
119078
119921
  modal.setBodyHtml(planHtml(plan));
119079
119922
  modal.setButton("back", { hidden: false, disabled: false });
@@ -153510,10 +154353,10 @@ var AlarmsNotificationsPanelView = class {
153510
154353
  const renderListPanel = (group, items, sel) => {
153511
154354
  if (items.length === 0) return '<div class="afm-empty">Nenhum item encontrado</div>';
153512
154355
  return items.map((item) => {
153513
- const esc12 = this.esc(item);
154356
+ const esc13 = this.esc(item);
153514
154357
  return `<label class="afm-check-item">
153515
- <input type="checkbox" class="afm-checkbox" data-group="${group}" data-value="${esc12}"${sel.has(item) ? " checked" : ""}>
153516
- <span class="afm-check-label">${esc12}</span>
154358
+ <input type="checkbox" class="afm-checkbox" data-group="${group}" data-value="${esc13}"${sel.has(item) ? " checked" : ""}>
154359
+ <span class="afm-check-label">${esc13}</span>
153517
154360
  </label>`;
153518
154361
  }).join("");
153519
154362
  };
@@ -166175,18 +167018,18 @@ function convertTelemetryToTimelineData(telemetry, options) {
166175
167018
  let segmentStart = null;
166176
167019
  if (sorted[0].ts > startTs) {
166177
167020
  const firstKnownState = isOnState(sorted[0].value, invertLogic) ? "on" : "off";
166178
- const initialState = firstKnownState === "on" ? "off" : "on";
167021
+ const initialState2 = firstKnownState === "on" ? "off" : "on";
166179
167022
  segments.push({
166180
167023
  startTime: periodStart,
166181
167024
  endTime: new Date(sorted[0].ts).toISOString(),
166182
167025
  durationMinutes: (sorted[0].ts - startTs) / 6e4,
166183
- state: initialState,
167026
+ state: initialState2,
166184
167027
  source: "unknown"
166185
167028
  });
166186
- if (initialState === "on") {
167029
+ if (initialState2 === "on") {
166187
167030
  totalOnMinutes += (sorted[0].ts - startTs) / 6e4;
166188
167031
  }
166189
- previousState = initialState;
167032
+ previousState = initialState2;
166190
167033
  segmentStart = sorted[0].ts;
166191
167034
  } else {
166192
167035
  segmentStart = startTs;
@@ -166391,7 +167234,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166391
167234
  const docTitle = buildActivationReportTitle(deviceName, opts.customerName);
166392
167235
  const issuedAt = formatIssuedAt(/* @__PURE__ */ new Date(), locale);
166393
167236
  const utilization = data.totalHours > 0 ? (data.totalOnMinutes / (data.totalHours * 60) * 100).toFixed(1) : "0.0";
166394
- const esc12 = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
167237
+ const esc13 = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
166395
167238
  const htmlContent = `
166396
167239
  <!DOCTYPE html>
166397
167240
  <html lang="pt-BR">
@@ -166443,14 +167286,14 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166443
167286
  <div class="brand">MyIO BAS</div>
166444
167287
  <h1>Relat\xF3rio de Acionamentos</h1>
166445
167288
  <div class="meta">
166446
- <div><b>Dispositivo:</b> ${esc12(deviceName)}</div>
167289
+ <div><b>Dispositivo:</b> ${esc13(deviceName)}</div>
166447
167290
  <div><b>Per\xEDodo:</b> ${periodStart} \u2014 ${periodEnd}</div>
166448
167291
  </div>
166449
167292
  </div>
166450
167293
  ${customerName ? `
166451
167294
  <div class="customer-badge">
166452
167295
  <div class="label">Cliente</div>
166453
- <div class="value">${esc12(customerName)}</div>
167296
+ <div class="value">${esc13(customerName)}</div>
166454
167297
  </div>` : ""}
166455
167298
  </div>
166456
167299
 
@@ -166461,7 +167304,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166461
167304
  </div>
166462
167305
  <div class="summary-card accent-green">
166463
167306
  <div class="summary-value">${formatDurationMinutes(data.totalOnMinutes)}</div>
166464
- <div class="summary-label">Tempo ${esc12(labelOn)}</div>
167307
+ <div class="summary-label">Tempo ${esc13(labelOn)}</div>
166465
167308
  </div>
166466
167309
  <div class="summary-card accent-amber">
166467
167310
  <div class="summary-value">${utilization}%</div>
@@ -166489,7 +167332,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166489
167332
  <tr>
166490
167333
  <td>${formatDateForExport(seg.startTime, locale)}</td>
166491
167334
  <td>${formatDateForExport(seg.endTime, locale)}</td>
166492
- <td><span class="pill ${seg.state === "on" ? "pill-on" : "pill-off"}">${seg.state === "on" ? esc12(labelOn) : esc12(labelOff)}</span></td>
167335
+ <td><span class="pill ${seg.state === "on" ? "pill-on" : "pill-off"}">${seg.state === "on" ? esc13(labelOn) : esc13(labelOff)}</span></td>
166493
167336
  <td>${formatDurationMinutes(seg.durationMinutes)}</td>
166494
167337
  <td>${seg.source === "manual" ? "Manual" : seg.source === "schedule" ? "Agendamento" : seg.source === "automation" ? "Automa\xE7\xE3o" : "Desconhecido"}</td>
166495
167338
  </tr>
@@ -166498,7 +167341,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166498
167341
  </table>
166499
167342
 
166500
167343
  <div class="footer">
166501
- <span class="issued">Emitido em ${issuedAt}</span>${customerName ? ` &middot; ${esc12(customerName)}` : ""} &middot; <span class="brand">MyIO BAS</span>
167344
+ <span class="issued">Emitido em ${issuedAt}</span>${customerName ? ` &middot; ${esc13(customerName)}` : ""} &middot; <span class="brand">MyIO BAS</span>
166502
167345
  </div>
166503
167346
  </body>
166504
167347
  </html>
@@ -181413,6 +182256,7 @@ var version = package_default.version || "0.0.0";
181413
182256
  SIDEBAR_MENU_CSS_PREFIX,
181414
182257
  SOLENOID_CONTROL_CSS_PREFIX,
181415
182258
  SOLENOID_IMAGES,
182259
+ STANDARD_DEVICE_PROFILES,
181416
182260
  STATUS_COLORS,
181417
182261
  STATUS_FRESHNESS_MAX_HOURS,
181418
182262
  STATUS_FRESHNESS_MAX_MS,
@@ -181533,6 +182377,7 @@ var version = package_default.version || "0.0.0";
181533
182377
  calculateStats,
181534
182378
  canEditAlarmRules,
181535
182379
  canModifyAnnotation,
182380
+ categoryKeyFromLabel,
181536
182381
  centsToDecimalString,
181537
182382
  checkCustomerCodeAvailable,
181538
182383
  clampTemperature,
@@ -181674,7 +182519,6 @@ var version = package_default.version || "0.0.0";
181674
182519
  detectSuperAdminMyio,
181675
182520
  determineInterval,
181676
182521
  deviceCategoryLabel,
181677
- deviceCategoryToPanelTerm,
181678
182522
  deviceIconLabels,
181679
182523
  deviceIcons,
181680
182524
  deviceNameToDeviceProductCode,
@@ -181906,6 +182750,7 @@ var version = package_default.version || "0.0.0";
181906
182750
  msToMinutes,
181907
182751
  myioExportData,
181908
182752
  nextManualSeq,
182753
+ nextStandardSeq,
181909
182754
  nfdNormalizeAnnotationSearch,
181910
182755
  normalizeBudgetBlock,
181911
182756
  normalizeConnectionStatus,
@@ -181968,9 +182813,7 @@ var version = package_default.version || "0.0.0";
181968
182813
  openWelcomeModal,
181969
182814
  openWellPumpsModal,
181970
182815
  overlayWithholdsVerdict,
181971
- panelCategoryToWire,
181972
182816
  panelDomainToWire,
181973
- panelTermToDeviceCategory,
181974
182817
  parseBinaryState,
181975
182818
  parseClassificationEntities,
181976
182819
  parseCsv,
@@ -182037,6 +182880,7 @@ var version = package_default.version || "0.0.0";
182037
182880
  resolveMoneyRowValues,
182038
182881
  resolvePercentDecimals,
182039
182882
  resolveReportItemStates,
182883
+ resolveStandardDeviceName,
182040
182884
  resolveSubcategory,
182041
182885
  resolveWithFallback,
182042
182886
  roundMoney2,
@@ -182059,6 +182903,7 @@ var version = package_default.version || "0.0.0";
182059
182903
  slugifyCustomerName,
182060
182904
  sortAnnotationGroups,
182061
182905
  sortDeviceGridDevices,
182906
+ standardDeviceName,
182062
182907
  strings,
182063
182908
  subtractDecimals,
182064
182909
  sumItemMoney,
@@ -182091,7 +182936,6 @@ var version = package_default.version || "0.0.0";
182091
182936
  valveHistoryFromTelemetry,
182092
182937
  version,
182093
182938
  waterDeviceStatusIcons,
182094
- wireCategoryToPanel,
182095
182939
  wireDomainToPanel,
182096
182940
  writeFreshdeskSyncedAtToTB,
182097
182941
  writeFreshdeskTicketsToTB,