myio-js-library 0.1.588 → 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
@@ -421,6 +421,7 @@ __export(src_exports, {
421
421
  calculateStats: () => calculateStats,
422
422
  canEditAlarmRules: () => canEditAlarmRules,
423
423
  canModifyAnnotation: () => canModifyAnnotation,
424
+ categoryKeyFromLabel: () => categoryKeyFromLabel,
424
425
  centsToDecimalString: () => centsToDecimalString,
425
426
  checkCustomerCodeAvailable: () => checkCustomerCodeAvailable,
426
427
  clampTemperature: () => clampTemperature,
@@ -562,7 +563,6 @@ __export(src_exports, {
562
563
  detectSuperAdminMyio: () => detectSuperAdminMyio,
563
564
  determineInterval: () => determineInterval,
564
565
  deviceCategoryLabel: () => deviceCategoryLabel,
565
- deviceCategoryToPanelTerm: () => deviceCategoryToPanelTerm,
566
566
  deviceIconLabels: () => deviceIconLabels,
567
567
  deviceIcons: () => deviceIcons,
568
568
  deviceNameToDeviceProductCode: () => deviceNameToDeviceProductCode,
@@ -857,9 +857,7 @@ __export(src_exports, {
857
857
  openWelcomeModal: () => openWelcomeModal,
858
858
  openWellPumpsModal: () => openWellPumpsModal,
859
859
  overlayWithholdsVerdict: () => overlayWithholdsVerdict,
860
- panelCategoryToWire: () => panelCategoryToWire,
861
860
  panelDomainToWire: () => panelDomainToWire,
862
- panelTermToDeviceCategory: () => panelTermToDeviceCategory,
863
861
  parseBinaryState: () => parseBinaryState,
864
862
  parseClassificationEntities: () => parseClassificationEntities,
865
863
  parseCsv: () => parseCsv,
@@ -982,7 +980,6 @@ __export(src_exports, {
982
980
  valveHistoryFromTelemetry: () => valveHistoryFromTelemetry,
983
981
  version: () => version,
984
982
  waterDeviceStatusIcons: () => waterDeviceStatusIcons,
985
- wireCategoryToPanel: () => wireCategoryToPanel,
986
983
  wireDomainToPanel: () => wireDomainToPanel,
987
984
  writeFreshdeskSyncedAtToTB: () => writeFreshdeskSyncedAtToTB,
988
985
  writeFreshdeskTicketsToTB: () => writeFreshdeskTicketsToTB,
@@ -993,7 +990,7 @@ module.exports = __toCommonJS(src_exports);
993
990
  // package.json
994
991
  var package_default = {
995
992
  name: "myio-js-library",
996
- version: "0.1.588",
993
+ version: "0.1.590",
997
994
  description: "A clean, standalone JS SDK for MYIO projects",
998
995
  license: "MIT",
999
996
  repository: "github:gh-myio/myio-js-library",
@@ -33200,8 +33197,8 @@ var EnergyDataFetcher = class {
33200
33197
  // src/components/premium-modals/internal/engines/CsvExporter.ts
33201
33198
  var toCsv = (rows, locale = "pt-BR", sep = ";") => {
33202
33199
  const fmt2 = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
33203
- const esc12 = (v) => (typeof v === "number" ? fmt2.format(v) : String(v)).replace(/"/g, '""');
33204
- 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");
33205
33202
  };
33206
33203
 
33207
33204
  // src/components/premium-modals/energy/types.ts
@@ -37609,14 +37606,14 @@ var DeviceReportModal = class {
37609
37606
  // Header: "Relatório - <identifier> - <label>" + nome do device (sutil, com copiar).
37610
37607
  // O customer já aparece no footer premium. Texto escapado — o shell usa innerHTML no título.
37611
37608
  buildHeaderTitleHTML() {
37612
- const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
37613
- const base = esc12(
37609
+ const esc13 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
37610
+ const base = esc13(
37614
37611
  `Relat\xF3rio - ${this.params.identifier || "SEM IDENTIFICADOR"} - ${this.params.label || "SEM ETIQUETA"}`
37615
37612
  );
37616
37613
  const deviceName = String(this.params.deviceName || "").trim();
37617
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;">
37618
- ${esc12(deviceName)}
37619
- <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"
37620
37617
  aria-label="Copiar nome do dispositivo"
37621
37618
  style="border:none;background:transparent;color:inherit;cursor:pointer;padding:0 2px;line-height:1;opacity:.9;display:inline-flex;">
37622
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>
@@ -63392,6 +63389,300 @@ var ExclusionGroupsTab = class {
63392
63389
  }
63393
63390
  };
63394
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
+
63395
63686
  // src/components/premium-modals/settings/device-profile/DeviceProfileTab.ts
63396
63687
  var TB_NULL_CUSTOMER_ID = "13814000-1dd2-11b2-8080-808080808080";
63397
63688
  var STYLES_ID3 = "dpt-styles";
@@ -63441,6 +63732,7 @@ var DeviceProfileTab = class {
63441
63732
  ownerName = null;
63442
63733
  deviceProfileOptions = null;
63443
63734
  customerOptions = null;
63735
+ tariff = { status: "loading", current: null, categories: [] };
63444
63736
  constructor(config2) {
63445
63737
  this.config = config2;
63446
63738
  }
@@ -63463,7 +63755,74 @@ var DeviceProfileTab = class {
63463
63755
  this.entity = entity;
63464
63756
  this.attributes = attributes;
63465
63757
  const customerId = entity?.customerId?.id;
63466
- 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>`;
63467
63826
  }
63468
63827
  async fetchEntity() {
63469
63828
  try {
@@ -63767,6 +64126,7 @@ var DeviceProfileTab = class {
63767
64126
  <div class="dpt-section">
63768
64127
  <div class="dpt-section-title">Classifica\xE7\xE3o (atributos da aplica\xE7\xE3o)</div>
63769
64128
  <div class="dpt-card">
64129
+ ${this.renderTariffCategoryRow()}
63770
64130
  ${editableAttrRows}
63771
64131
  ${ingestionRow}
63772
64132
  ${readonlyRows}
@@ -63838,7 +64198,20 @@ var DeviceProfileTab = class {
63838
64198
  async beginEdit(row, field, kind) {
63839
64199
  const wrap = row.querySelector(".dpt-value-wrap");
63840
64200
  if (!wrap) return;
63841
- 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") {
63842
64215
  const options = await this.fetchDeviceProfileOptions();
63843
64216
  const currentId = this.entity?.deviceProfileId?.id || "";
63844
64217
  wrap.innerHTML = this.editorHtml(
@@ -63879,7 +64252,12 @@ var DeviceProfileTab = class {
63879
64252
  const saveBtn = row.querySelector('button[data-action="save"]');
63880
64253
  if (saveBtn) saveBtn.disabled = true;
63881
64254
  try {
63882
- 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") {
63883
64261
  await this.saveEntityField({ label: value });
63884
64262
  } else if (kind === "entity-profile") {
63885
64263
  if (!value) throw new Error("Selecione um Device Profile.");
@@ -63926,6 +64304,7 @@ var DeviceProfileTab = class {
63926
64304
  .dpt-value { font-size: 13px; color: #111827; text-align: right; word-break: break-word; }
63927
64305
  .dpt-value-wrap { display: flex; align-items: center; gap: 6px; }
63928
64306
  .dpt-rel { color: #9ca3af; font-size: 12px; }
64307
+ .dpt-muted { color: #9ca3af; font-size: 12px; }
63929
64308
  .dpt-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
63930
64309
  .dpt-empty { padding: 16px 0; text-align: center; color: #9ca3af; font-size: 13px; }
63931
64310
  .dpt-icon-btn {
@@ -66949,11 +67328,19 @@ var SettingsModalView = class _SettingsModalView {
66949
67328
  return;
66950
67329
  }
66951
67330
  try {
67331
+ const orch = window.MyIOOrchestrator || {};
67332
+ const cfg = this.config;
66952
67333
  this.deviceProfileTab = new DeviceProfileTab({
66953
67334
  container,
66954
67335
  deviceId,
66955
67336
  jwtToken,
66956
- 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
+ }
66957
67344
  });
66958
67345
  await this.deviceProfileTab.init();
66959
67346
  console.log("[SettingsModalView] DeviceProfileTab initialized");
@@ -67560,8 +67947,8 @@ var SettingsModalView = class _SettingsModalView {
67560
67947
  twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
67561
67948
  twinNote.hidden = false;
67562
67949
  }
67563
- const esc12 = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67564
- 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("");
67565
67952
  const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
67566
67953
  const savedSegment = String(saved.segment || "");
67567
67954
  const savedActivity = String(saved.activity || "");
@@ -74108,7 +74495,7 @@ var WelcomeModalView = class _WelcomeModalView {
74108
74495
  if (this.metaTipEl) this.metaTipEl.style.display = "none";
74109
74496
  }
74110
74497
  buildMetaTipHtml(type, card) {
74111
- const esc12 = _WelcomeModalView.escapeMetaHtml;
74498
+ const esc13 = _WelcomeModalView.escapeMetaHtml;
74112
74499
  const chip = _WelcomeModalView.metaChip;
74113
74500
  const meta = card.metaCounts || {};
74114
74501
  const details = card.metaDetails || {};
@@ -74118,7 +74505,7 @@ var WelcomeModalView = class _WelcomeModalView {
74118
74505
  ).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
74119
74506
  const frame = (icon2, label, body) => `<div class="myio-welcome-meta-tip__header">
74120
74507
  <span class="myio-welcome-meta-tip__icon">${icon2}</span>
74121
- <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>
74122
74509
  <span class="myio-welcome-meta-tip__timestamp">${stamp}</span>
74123
74510
  <button type="button" class="myio-welcome-meta-tip__close" title="Fechar">\u2715</button>
74124
74511
  </div>
@@ -74146,8 +74533,8 @@ var WelcomeModalView = class _WelcomeModalView {
74146
74533
  const chips = Object.entries(byState).map(([s, n]) => chip(`${s}: ${n}`)).join("");
74147
74534
  const rows = alarms.slice(0, 10).map(
74148
74535
  (a) => row(
74149
- esc12(a.deviceName ? `${a.deviceName} \u2014 ${a.title || "Alarme"}` : a.title || "Alarme"),
74150
- [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 ")
74151
74538
  )
74152
74539
  ).join("");
74153
74540
  return frame(
@@ -74171,7 +74558,7 @@ var WelcomeModalView = class _WelcomeModalView {
74171
74558
  const rows = annotations.slice(0, 10).map((a) => {
74172
74559
  const when = a.createdAt ? new Date(a.createdAt).toLocaleDateString("pt-BR") : "";
74173
74560
  const text2 = a.text.length > 90 ? `${a.text.slice(0, 90)}\u2026` : a.text;
74174
- 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)}` : ""}`);
74175
74562
  }).join("");
74176
74563
  return frame(
74177
74564
  "\u{1F4CB}",
@@ -74182,7 +74569,7 @@ var WelcomeModalView = class _WelcomeModalView {
74182
74569
  if (type === "users") {
74183
74570
  if (meta.users === null) return frame("\u{1F465}", "Usu\xE1rios", loadingBody);
74184
74571
  const users = details.users || [];
74185
- 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("");
74186
74573
  return frame(
74187
74574
  "\u{1F465}",
74188
74575
  "Usu\xE1rios",
@@ -104217,19 +104604,19 @@ function _updateCoverageHint(topDoc) {
104217
104604
  const deviceCount = data.granularity === "DEVICE" ? data.devices?.length ?? 0 : 0;
104218
104605
  hint.textContent = `\u26A0 Meta incompleta para este dom\xEDnio/ano` + (deviceCount > 0 ? ` \xB7 Por medidor (${deviceCount})` : "") + ` \u2014 passe o mouse para detalhes`;
104219
104606
  tabs.insertAdjacentElement("afterend", hint);
104220
- 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;");
104221
104608
  try {
104222
104609
  _coverageDetach = InfoTooltip.attach(hint, () => {
104223
104610
  const d = _getGoalsData(_currentDomain);
104224
104611
  const parts = [];
104225
104612
  if (hasCoverageGaps(d?.coverageGaps)) {
104226
- 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>`);
104227
104614
  }
104228
104615
  (d?.devices || []).forEach((dev) => {
104229
104616
  if (!hasCoverageGaps(dev?.coverageGaps)) return;
104230
104617
  const label = dev.label || dev.code || "medidor";
104231
104618
  parts.push(
104232
- `<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>`
104233
104620
  );
104234
104621
  });
104235
104622
  return {
@@ -107349,10 +107736,10 @@ var DOMAIN_LABEL = {
107349
107736
  energy: "Energia",
107350
107737
  water: "\xC1gua"
107351
107738
  };
107352
- var CATEGORY_LABEL = {
107353
- lojas: "Lojas",
107354
- area_comum: "\xC1rea Comum"
107355
- };
107739
+ function categoryLabel(key, categories) {
107740
+ const hit = (categories || []).find((c) => c.key === key);
107741
+ return hit?.label || String(key ?? "");
107742
+ }
107356
107743
  function unitLabel(domain) {
107357
107744
  return domain === "water" ? "R$/m\xB3" : "R$/kWh";
107358
107745
  }
@@ -107511,7 +107898,7 @@ function removeEntryByBounds(entries, target, opts = {}) {
107511
107898
  }
107512
107899
  function computePricingKpis(entries, opts = {}) {
107513
107900
  const periodsByDomain = { energy: 0, water: 0 };
107514
- const periodsByCategory = { lojas: 0, area_comum: 0 };
107901
+ const periodsByCategory = {};
107515
107902
  let energySum = 0;
107516
107903
  let energyN = 0;
107517
107904
  let waterSum = 0;
@@ -107532,7 +107919,7 @@ function computePricingKpis(entries, opts = {}) {
107532
107919
  combos.add(`${e.customerId}|${e.domain}|${e.category}`);
107533
107920
  }
107534
107921
  const covered = combos.size;
107535
- const total = opts.customerCount ? opts.customerCount * 4 : covered;
107922
+ const total = opts.customerCount && opts.categoryCount ? opts.customerCount * 2 * opts.categoryCount : covered;
107536
107923
  return {
107537
107924
  totalPeriods: entries.length,
107538
107925
  periodsByDomain,
@@ -107587,6 +107974,36 @@ var PRICING_PANEL_CSS = `
107587
107974
  .myio-pricing.show .myio-pricing__content {
107588
107975
  transform: translateY(0) scale(1);
107589
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; }
107590
108007
  .myio-pricing__header {
107591
108008
  display: flex;
107592
108009
  align-items: center;
@@ -107899,188 +108316,6 @@ function injectPricingPanelStyles(doc) {
107899
108316
  doc.head.appendChild(style);
107900
108317
  }
107901
108318
 
107902
- // src/components/pricing-panel/tariffApiClient.ts
107903
- var TariffApiError = class extends Error {
107904
- code;
107905
- status;
107906
- details;
107907
- currentVersion;
107908
- constructor(code, status, message, details) {
107909
- super(message || code);
107910
- this.name = "TariffApiError";
107911
- this.code = code;
107912
- this.status = status;
107913
- this.details = details;
107914
- const cv = details && details.currentVersion;
107915
- this.currentVersion = typeof cv === "number" ? cv : void 0;
107916
- }
107917
- };
107918
- function joinUrl(baseUrl, basePath, path) {
107919
- const b = baseUrl.replace(/\/+$/, "");
107920
- const bp = basePath ? `/${basePath.replace(/^\/+|\/+$/g, "")}` : "";
107921
- const p = path.startsWith("/") ? path : `/${path}`;
107922
- return `${b}${bp}${p}`;
107923
- }
107924
- function tariffQuery(sel, granularity) {
107925
- const qs = new URLSearchParams();
107926
- qs.set("domain", sel.domain);
107927
- qs.set("category", sel.category);
107928
- qs.set("year", String(sel.year));
107929
- if (granularity) qs.set("granularity", granularity);
107930
- return qs.toString();
107931
- }
107932
- function unwrapGcdrEnvelope(body) {
107933
- if (body && typeof body === "object" && !Array.isArray(body)) {
107934
- const b = body;
107935
- if (b.success === true && b.data && typeof b.data === "object") return b.data;
107936
- }
107937
- return body;
107938
- }
107939
- function parseETagVersion(headers) {
107940
- const raw = headers.get("ETag") || headers.get("etag");
107941
- if (!raw) return void 0;
107942
- const m = /"?(-?\d+)"?/.exec(raw);
107943
- return m ? Number(m[1]) : void 0;
107944
- }
107945
- var TariffApiClient = class {
107946
- cfg;
107947
- fetchImpl;
107948
- basePath;
107949
- constructor(config2) {
107950
- if (!config2 || !config2.baseUrl) {
107951
- throw new Error("TariffApiClient requires a baseUrl.");
107952
- }
107953
- this.cfg = config2;
107954
- const injected = config2.fetchImpl || globalThis.fetch;
107955
- if (typeof injected !== "function") {
107956
- throw new Error("TariffApiClient requires a fetch implementation.");
107957
- }
107958
- this.fetchImpl = config2.fetchImpl ? config2.fetchImpl : injected.bind(globalThis);
107959
- this.basePath = config2.basePath ?? "api/v1";
107960
- }
107961
- authHeaders() {
107962
- const h3 = {};
107963
- if (this.cfg.apiKey) h3["X-API-Key"] = this.cfg.apiKey;
107964
- if (this.cfg.jwt) h3["Authorization"] = `Bearer ${this.cfg.jwt}`;
107965
- if (this.cfg.tenantId) h3["X-Tenant-Id"] = this.cfg.tenantId;
107966
- return h3;
107967
- }
107968
- /** Read the tariff tree. `granularity` defaults to `day` server-side. */
107969
- async getTariff(sel, granularity = "hour") {
107970
- const url = joinUrl(
107971
- this.cfg.baseUrl,
107972
- this.basePath,
107973
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel, granularity)}`
107974
- );
107975
- const res = await this.fetchImpl(url, {
107976
- method: "GET",
107977
- headers: { Accept: "application/json", ...this.authHeaders() }
107978
- });
107979
- const body = await this.readBody(res);
107980
- if (!res.ok) throw this.toError(res, body);
107981
- const etagVersion = parseETagVersion(res.headers);
107982
- const parsed = unwrapGcdrEnvelope(body) || {};
107983
- return {
107984
- customerId: sel.customerId,
107985
- domain: sel.domain,
107986
- category: sel.category,
107987
- year: sel.year,
107988
- unit: parsed.unit,
107989
- currency: parsed.currency,
107990
- tariffModel: parsed.tariffModel,
107991
- timezone: parsed.timezone,
107992
- version: typeof parsed.version === "number" ? parsed.version : etagVersion ?? 0,
107993
- tree: parsed.tree || {}
107994
- };
107995
- }
107996
- /** REPLACE the whole year with a nested price tree. */
107997
- async putTariff(sel, tree, expectedVersion) {
107998
- return this.write("PUT", sel, { ...tree, ...guardBody(expectedVersion) }, expectedVersion);
107999
- }
108000
- /** MERGE sparse buckets into the year (finest level wins). */
108001
- async patchTariff(sel, buckets, expectedVersion) {
108002
- return this.write("PATCH", sel, { buckets, ...guardBody(expectedVersion) }, expectedVersion);
108003
- }
108004
- /**
108005
- * DELETE the whole year (no `bucket`) or one sub-bucket (`bucket` present).
108006
- * Whole-year delete is idempotent (204 even if absent).
108007
- */
108008
- async deleteTariff(sel, opts = {}) {
108009
- const hasBody = Boolean(opts.bucket) || typeof opts.expectedVersion === "number";
108010
- const url = joinUrl(
108011
- this.cfg.baseUrl,
108012
- this.basePath,
108013
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
108014
- );
108015
- const headers = { Accept: "application/json", ...this.authHeaders() };
108016
- if (typeof opts.expectedVersion === "number") headers["If-Match"] = `"${opts.expectedVersion}"`;
108017
- const init = { method: "DELETE", headers };
108018
- if (hasBody) {
108019
- headers["Content-Type"] = "application/json";
108020
- init.body = JSON.stringify({
108021
- ...opts.bucket ? { bucket: opts.bucket } : {},
108022
- ...guardBody(opts.expectedVersion)
108023
- });
108024
- }
108025
- const res = await this.fetchImpl(url, init);
108026
- if (res.status === 204) return {};
108027
- const body = await this.readBody(res);
108028
- if (!res.ok) throw this.toError(res, body);
108029
- const etagVersion = parseETagVersion(res.headers);
108030
- const data = unwrapGcdrEnvelope(body);
108031
- const v = (data && data.version) ?? etagVersion;
108032
- return typeof v === "number" ? { version: v } : {};
108033
- }
108034
- async write(method, sel, body, expectedVersion) {
108035
- const url = joinUrl(
108036
- this.cfg.baseUrl,
108037
- this.basePath,
108038
- `/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
108039
- );
108040
- const headers = {
108041
- Accept: "application/json",
108042
- "Content-Type": "application/json",
108043
- ...this.authHeaders()
108044
- };
108045
- if (typeof expectedVersion === "number") headers["If-Match"] = `"${expectedVersion}"`;
108046
- const res = await this.fetchImpl(url, { method, headers, body: JSON.stringify(body) });
108047
- const parsed = await this.readBody(res);
108048
- if (!res.ok) throw this.toError(res, parsed);
108049
- const etagVersion = parseETagVersion(res.headers);
108050
- const data = unwrapGcdrEnvelope(parsed);
108051
- const v = (data && data.version) ?? etagVersion;
108052
- return { version: typeof v === "number" ? v : (expectedVersion ?? 0) + 1 };
108053
- }
108054
- async readBody(res) {
108055
- try {
108056
- const text2 = await res.text();
108057
- if (!text2) return null;
108058
- return JSON.parse(text2);
108059
- } catch {
108060
- return null;
108061
- }
108062
- }
108063
- toError(res, body) {
108064
- const err = body && body.error;
108065
- if (err && typeof err === "object") {
108066
- const e = err;
108067
- return new TariffApiError(
108068
- e.code || `HTTP_${res.status}`,
108069
- res.status,
108070
- e.message,
108071
- e.details
108072
- );
108073
- }
108074
- return new TariffApiError(`HTTP_${res.status}`, res.status, res.statusText);
108075
- }
108076
- };
108077
- function guardBody(expectedVersion) {
108078
- return typeof expectedVersion === "number" ? { expectedVersion } : {};
108079
- }
108080
- function createTariffApiClient(config2) {
108081
- return new TariffApiClient(config2);
108082
- }
108083
-
108084
108319
  // src/components/pricing-panel/tariffApiAdapter.ts
108085
108320
  var PANEL_TO_WIRE_DOMAIN = {
108086
108321
  energy: "ENERGY",
@@ -108090,14 +108325,6 @@ var WIRE_TO_PANEL_DOMAIN = {
108090
108325
  ENERGY: "energy",
108091
108326
  WATER: "water"
108092
108327
  };
108093
- var PANEL_TO_WIRE_CATEGORY = {
108094
- lojas: "SPECIFIC",
108095
- area_comum: "COMMON_AREA"
108096
- };
108097
- var WIRE_TO_PANEL_CATEGORY = {
108098
- SPECIFIC: "lojas",
108099
- COMMON_AREA: "area_comum"
108100
- };
108101
108328
  function panelDomainToWire(d) {
108102
108329
  const w = PANEL_TO_WIRE_DOMAIN[d];
108103
108330
  if (!w) throw new Error(`Unknown panel domain: ${String(d)}`);
@@ -108108,16 +108335,6 @@ function wireDomainToPanel(w) {
108108
108335
  if (!d) throw new Error(`Unknown wire domain: ${String(w)}`);
108109
108336
  return d;
108110
108337
  }
108111
- function panelCategoryToWire(c) {
108112
- const w = PANEL_TO_WIRE_CATEGORY[c];
108113
- if (!w) throw new Error(`Unknown panel category: ${String(c)}`);
108114
- return w;
108115
- }
108116
- function wireCategoryToPanel(w) {
108117
- const c = WIRE_TO_PANEL_CATEGORY[w];
108118
- if (!c) throw new Error(`Unknown wire category: ${String(w)}`);
108119
- return c;
108120
- }
108121
108338
  function normalizePriceString(input) {
108122
108339
  if (typeof input.price === "string" && input.price.trim() !== "") {
108123
108340
  const s2 = input.price.trim();
@@ -108190,7 +108407,7 @@ function bandSelector(band, customerId, year) {
108190
108407
  return {
108191
108408
  customerId,
108192
108409
  domain: panelDomainToWire(band.domain),
108193
- category: panelCategoryToWire(band.category),
108410
+ category: band.category,
108194
108411
  year
108195
108412
  };
108196
108413
  }
@@ -108395,12 +108612,7 @@ function collapseTreeToBands(tree, dims) {
108395
108612
  }
108396
108613
  return mergeContiguousDays(dayBands, dims.year);
108397
108614
  }
108398
- var WIRE_COMBOS = [
108399
- ["ENERGY", "SPECIFIC"],
108400
- ["ENERGY", "COMMON_AREA"],
108401
- ["WATER", "SPECIFIC"],
108402
- ["WATER", "COMMON_AREA"]
108403
- ];
108615
+ var WIRE_DOMAINS = ["ENERGY", "WATER"];
108404
108616
  var TariffApiAdapter = class {
108405
108617
  client;
108406
108618
  year;
@@ -108414,14 +108626,24 @@ var TariffApiAdapter = class {
108414
108626
  getYear() {
108415
108627
  return this.year;
108416
108628
  }
108629
+ /** GCDR tariff categories of a customer (globals + own). Errors propagate. */
108630
+ listCategories(customerId, opts) {
108631
+ return this.client.listCategories(customerId, opts);
108632
+ }
108417
108633
  /**
108418
108634
  * Load every `(domain × category)` tariff for a customer and collapse each into
108419
- * panel entries. An empty tariff (`version: 0`) contributes no entries — it is
108420
- * "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.
108421
108638
  */
108422
- 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]);
108423
108645
  const out = [];
108424
- for (const [domain, category] of WIRE_COMBOS) {
108646
+ for (const [domain, category] of combos) {
108425
108647
  const sel = { customerId, domain, category, year };
108426
108648
  const resp = await this.client.getTariff(sel, "hour");
108427
108649
  this.versions.set(selectorKey(sel), resp.version);
@@ -108429,7 +108651,7 @@ var TariffApiAdapter = class {
108429
108651
  const bands = collapseTreeToBands(resp.tree, {
108430
108652
  year,
108431
108653
  domain: wireDomainToPanel(domain),
108432
- category: wireCategoryToPanel(category)
108654
+ category
108433
108655
  });
108434
108656
  for (const b of bands) out.push(bandToPanelEntry(b, customerId));
108435
108657
  }
@@ -108437,7 +108659,7 @@ var TariffApiAdapter = class {
108437
108659
  }
108438
108660
  /** Convenience: read + collapse one specific tariff. */
108439
108661
  async loadBands(customerId, domain, category, year = this.year) {
108440
- const sel = { customerId, domain: panelDomainToWire(domain), category: panelCategoryToWire(category), year };
108662
+ const sel = { customerId, domain: panelDomainToWire(domain), category, year };
108441
108663
  const resp = await this.client.getTariff(sel, "hour");
108442
108664
  this.versions.set(selectorKey(sel), resp.version);
108443
108665
  const bands = resp.version === 0 ? [] : collapseTreeToBands(resp.tree, { year, domain, category });
@@ -108510,6 +108732,309 @@ function createTariffApiAdapter(client, opts) {
108510
108732
  return new TariffApiAdapter(client, opts);
108511
108733
  }
108512
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
+
108513
109038
  // src/components/pricing-panel/openPricingPanel.ts
108514
109039
  var MODAL_ID4 = "myio-pricing-panel";
108515
109040
  function escapeHtml14(value) {
@@ -108593,8 +109118,9 @@ function openPricingPanel(params) {
108593
109118
  const lockCustomer = params.lockCustomer === true && customers.length > 0;
108594
109119
  const tariffApi = params.tariffApi;
108595
109120
  let adapter = null;
109121
+ let client = null;
108596
109122
  if (allowed && tariffApi) {
108597
- const client = new TariffApiClient({
109123
+ client = new TariffApiClient({
108598
109124
  baseUrl: tariffApi.baseUrl,
108599
109125
  apiKey: tariffApi.apiKey,
108600
109126
  jwt: tariffApi.jwt,
@@ -108667,7 +109193,8 @@ function openPricingPanel(params) {
108667
109193
  return handle;
108668
109194
  }
108669
109195
  const initDomain = params.domain || "energy";
108670
- const initCategory = params.category || "lojas";
109196
+ let categories = null;
109197
+ let categoriesError = null;
108671
109198
  const customerOptions = customers.map((c) => `<option value="${escapeHtml14(resolveCustomerId(c))}">${escapeHtml14(c.title)}</option>`).join("");
108672
109199
  modal.innerHTML = `
108673
109200
  <div class="myio-pricing__overlay"></div>
@@ -108680,6 +109207,7 @@ function openPricingPanel(params) {
108680
109207
  <button class="myio-pricing__tab active" data-tab="define" data-testid="tab-define">Definir pre\xE7os</button>
108681
109208
  <button class="myio-pricing__tab" data-tab="dashboard" data-testid="tab-dashboard">Dashboard</button>
108682
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>' : ""}
108683
109211
  </div>
108684
109212
  <div class="myio-pricing__body">
108685
109213
  <!-- TAB: Definir pre\xE7os -->
@@ -108700,9 +109228,8 @@ function openPricingPanel(params) {
108700
109228
  </div>
108701
109229
  <div class="myio-pricing__field">
108702
109230
  <label class="myio-pricing__label" for="myio-pricing-category">Categoria</label>
108703
- <select class="myio-pricing__select" id="myio-pricing-category" data-testid="pricing-category">
108704
- <option value="lojas">Lojas</option>
108705
- <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>
108706
109233
  </select>
108707
109234
  </div>
108708
109235
  <div class="myio-pricing__field">
@@ -108756,6 +109283,9 @@ function openPricingPanel(params) {
108756
109283
  </div>
108757
109284
  </div>
108758
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
+
108759
109289
  <!-- TAB: Hist\xF3rico -->
108760
109290
  <div class="myio-pricing__panel" data-panel="history" hidden>
108761
109291
  <ul class="myio-pricing__history" data-testid="history-list"></ul>
@@ -108790,7 +109320,33 @@ function openPricingPanel(params) {
108790
109320
  const historyList = $2('[data-testid="history-list"]');
108791
109321
  const historyEmpty = $2('[data-testid="history-empty"]');
108792
109322
  domainSel.value = initDomain;
108793
- 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
+ }
108794
109350
  modal.querySelectorAll(".myio-pricing__tab").forEach((tab) => {
108795
109351
  tab.addEventListener("click", () => selectTab(tab.dataset.tab));
108796
109352
  });
@@ -108803,6 +109359,22 @@ function openPricingPanel(params) {
108803
109359
  });
108804
109360
  if (name === "dashboard") renderDashboard2();
108805
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
+ });
108806
109378
  }
108807
109379
  const showError = (msg) => {
108808
109380
  errorBox.textContent = msg;
@@ -108837,6 +109409,7 @@ function openPricingPanel(params) {
108837
109409
  if (adapter) {
108838
109410
  customerSel.addEventListener("change", () => {
108839
109411
  void loadFromApi();
109412
+ if (categoriesPanel && !categoriesPanel.hidden) void categoriesTab?.refresh();
108840
109413
  });
108841
109414
  }
108842
109415
  syncPeriodFields();
@@ -108856,8 +109429,24 @@ function openPricingPanel(params) {
108856
109429
  if (!adapter) return;
108857
109430
  const customerId = customerSel.value;
108858
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;
108859
109445
  try {
108860
- const loaded = await adapter.loadEntriesForCustomer(customerId);
109446
+ const loaded = await adapter.loadEntriesForCustomer(
109447
+ customerId,
109448
+ categories.map((c) => c.key)
109449
+ );
108861
109450
  entries = entries.filter((e) => e.customerId !== customerId).concat(loaded);
108862
109451
  renderList2();
108863
109452
  } catch (err) {
@@ -108885,7 +109474,7 @@ function openPricingPanel(params) {
108885
109474
  };
108886
109475
  const badge = (domain, category) => `<span class="myio-pricing__badge${domain === "water" ? " myio-pricing__badge--water" : ""}">${escapeHtml14(
108887
109476
  DOMAIN_LABEL[domain]
108888
- )} \xB7 ${escapeHtml14(CATEGORY_LABEL[category])}</span>`;
109477
+ )} \xB7 ${escapeHtml14(categoryLabel(category, categories))}</span>`;
108889
109478
  const renderList2 = () => {
108890
109479
  const customerId = customerSel.value;
108891
109480
  const rows = entries.filter((e) => e.customerId === customerId).sort((a, b) => {
@@ -108941,6 +109530,9 @@ function openPricingPanel(params) {
108941
109530
  if (!customerId) return { error: "Selecione um customer." };
108942
109531
  const domain = domainSel.value;
108943
109532
  const category = categorySel.value;
109533
+ if (!category || !activeCategories().some((c) => c.key === category)) {
109534
+ return { error: "Selecione uma categoria." };
109535
+ }
108944
109536
  const price = parseBRL(priceInput.value);
108945
109537
  if (!Number.isFinite(price) || price <= 0) {
108946
109538
  return { error: "Informe um pre\xE7o v\xE1lido maior que zero." };
@@ -108983,7 +109575,10 @@ function openPricingPanel(params) {
108983
109575
  });
108984
109576
  reportDomainSel.addEventListener("change", renderReport);
108985
109577
  function renderDashboard2() {
108986
- const kpis = computePricingKpis(entries, { customerCount: customers.length });
109578
+ const kpis = computePricingKpis(entries, {
109579
+ customerCount: customers.length,
109580
+ categoryCount: activeCategories().length
109581
+ });
108987
109582
  const cards = [
108988
109583
  { value: String(kpis.totalPeriods), label: "Per\xEDodos definidos" },
108989
109584
  { value: String(kpis.periodsByDomain.energy), label: "Per\xEDodos \xB7 Energia" },
@@ -109027,7 +109622,7 @@ function openPricingPanel(params) {
109027
109622
  <tr>
109028
109623
  <td>${escapeHtml14(customerTitle(e.customerId))}</td>
109029
109624
  <td>${escapeHtml14(DOMAIN_LABEL[e.domain])}</td>
109030
- <td>${escapeHtml14(CATEGORY_LABEL[e.category])}</td>
109625
+ <td>${escapeHtml14(categoryLabel(e.category, categories))}</td>
109031
109626
  <td>${escapeHtml14(formatPeriodLabel(e))}</td>
109032
109627
  <td>${escapeHtml14(formatBRL2(e.pricePerKwh))} ${escapeHtml14(unitLabel(e.domain))}</td>
109033
109628
  </tr>`
@@ -109053,7 +109648,13 @@ function openPricingPanel(params) {
109053
109648
  historyEmpty.style.display = auditLog.length ? "none" : "";
109054
109649
  }
109055
109650
  renderList2();
109056
- 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
+ }
109057
109658
  return handle;
109058
109659
  }
109059
109660
 
@@ -109736,27 +110337,19 @@ function injectDeviceCategoryStyles(doc) {
109736
110337
  }
109737
110338
 
109738
110339
  // src/components/financial-goals/deviceCategoryPanel.ts
109739
- var PANEL_TERM_LABEL = {
109740
- lojas: "Lojas",
109741
- area_comum: "\xC1rea Comum"
109742
- };
109743
110340
  var NONE_LABEL = "\u2014 Sem categoria \u2014";
109744
- function deviceCategoryLabel(cat) {
110341
+ function deviceCategoryLabel(cat, categories) {
109745
110342
  if (cat == null) return NONE_LABEL;
109746
- return PANEL_TERM_LABEL[wireCategoryToPanel(cat)];
109747
- }
109748
- function deviceCategoryToPanelTerm(cat) {
109749
- return cat == null ? null : wireCategoryToPanel(cat);
110343
+ return (categories || []).find((c) => c.key === cat)?.label || String(cat);
109750
110344
  }
109751
- function panelTermToDeviceCategory(term) {
109752
- return term == null ? null : panelCategoryToWire(term);
109753
- }
109754
- function esc10(s) {
110345
+ function esc11(s) {
109755
110346
  return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
109756
110347
  }
109757
- function categoryOptionsHTML(selected) {
109758
- const opt = (value, label, isSel) => `<option value="${value}"${isSel ? " selected" : ""}>${esc10(label)}</option>`;
109759
- 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) : "");
109760
110353
  }
109761
110354
  function openDeviceCategoryPanel(params) {
109762
110355
  const doc = params.document || (typeof document !== "undefined" ? document : void 0);
@@ -109767,6 +110360,8 @@ function openDeviceCategoryPanel(params) {
109767
110360
  }
109768
110361
  injectDeviceCategoryStyles(doc);
109769
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("");
109770
110365
  let rows = [];
109771
110366
  let search = "";
109772
110367
  let filter = params.initialFilter || "all";
@@ -109792,8 +110387,7 @@ function openDeviceCategoryPanel(params) {
109792
110387
  <select class="myio-devcat__filter" data-devcat-filter="1" aria-label="Filtrar por categoria">
109793
110388
  <option value="all">Todas as categorias</option>
109794
110389
  <option value="uncategorized">Sem categoria</option>
109795
- <option value="COMMON_AREA">${esc10(deviceCategoryLabel("COMMON_AREA"))}</option>
109796
- <option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
110390
+ ${activeOptions}
109797
110391
  </select>
109798
110392
  <label class="myio-devcat__filter" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
109799
110393
  <input type="checkbox" data-devcat-selectall="1" /> Selecionar vis\xEDveis
@@ -109802,9 +110396,8 @@ function openDeviceCategoryPanel(params) {
109802
110396
  <div class="myio-devcat__bulkbar" data-devcat-bulkbar="1">
109803
110397
  <span data-devcat-bulkcount="1">0 selecionados</span>
109804
110398
  <select data-devcat-bulkcat="1" aria-label="Categoria para os selecionados">
109805
- <option value="">${esc10(NONE_LABEL)}</option>
109806
- <option value="COMMON_AREA">${esc10(deviceCategoryLabel("COMMON_AREA"))}</option>
109807
- <option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
110399
+ <option value="">${esc11(NONE_LABEL)}</option>
110400
+ ${activeOptions}
109808
110401
  </select>
109809
110402
  <button type="button" class="myio-devcat__bulk-apply" data-devcat-bulkapply="1">Aplicar a selecionados</button>
109810
110403
  </div>
@@ -109834,16 +110427,16 @@ function openDeviceCategoryPanel(params) {
109834
110427
  return rows.filter((r) => matchesFilter(r) && matchesSearch(r));
109835
110428
  }
109836
110429
  function rowHTML(r) {
109837
- const name = esc10(r.label || r.code || r.deviceId);
109838
- 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>` : "";
109839
110432
  const checked = selected.has(r.deviceId) ? " checked" : "";
109840
110433
  const focused = r.deviceId === params.focusDeviceId ? ' data-focused="1"' : "";
109841
110434
  const catAttr = r.tariffCategory == null ? "null" : r.tariffCategory;
109842
- 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(
109843
110436
  r.deviceId
109844
- )}"${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(
109845
110438
  r.deviceId
109846
- )}" 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>`;
109847
110440
  }
109848
110441
  function render3() {
109849
110442
  const vis = visibleRows();
@@ -110003,7 +110596,7 @@ function openDeviceCategoryPanel(params) {
110003
110596
  rows = await port.listDevices({ customerId, domain: params.domain });
110004
110597
  } catch (err) {
110005
110598
  rows = [];
110006
- 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(
110007
110600
  err?.message || "erro"
110008
110601
  )}</div>`;
110009
110602
  countEl.textContent = "";
@@ -110035,6 +110628,7 @@ function createCoverageDeepLink(config2) {
110035
110628
  const open = (focusDeviceId, initialFilter) => openDeviceCategoryPanel({
110036
110629
  port: config2.port,
110037
110630
  customerId: config2.customerId,
110631
+ categories: config2.categories,
110038
110632
  domain: config2.domain,
110039
110633
  focusDeviceId,
110040
110634
  initialFilter,
@@ -116263,16 +116857,16 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
116263
116857
  let errors = 0;
116264
116858
  for (let i = 0; i < deviceAttrsList.length; i++) {
116265
116859
  const { deviceId, centralId, slaveId } = deviceAttrsList[i];
116266
- const devName = devices[i]?.name || deviceId;
116267
- 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}`);
116268
116862
  if (!centralId || !slaveId) {
116269
- console.log(`[BulkSyncIngestion] Skipped ${devName} \u2014 missing centralId or slaveId`);
116863
+ console.log(`[BulkSyncIngestion] Skipped ${devName2} \u2014 missing centralId or slaveId`);
116270
116864
  skipped++;
116271
116865
  continue;
116272
116866
  }
116273
116867
  const match = findIngestionDeviceByCentralSlaveId(ingestionDevices, centralId, slaveId);
116274
116868
  if (!match) {
116275
- console.log(`[BulkSyncIngestion] No match for ${devName} (centralId=${centralId}, slaveId=${slaveId})`);
116869
+ console.log(`[BulkSyncIngestion] No match for ${devName2} (centralId=${centralId}, slaveId=${slaveId})`);
116276
116870
  skipped++;
116277
116871
  continue;
116278
116872
  }
@@ -116280,10 +116874,10 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
116280
116874
  await tbPost(state6, `/api/plugins/telemetry/DEVICE/${deviceId}/attributes/SERVER_SCOPE`, {
116281
116875
  ingestionId: match.id
116282
116876
  });
116283
- console.log(`[BulkSyncIngestion] \u2705 ${devName} \u2192 ingestionId=${match.id}`);
116877
+ console.log(`[BulkSyncIngestion] \u2705 ${devName2} \u2192 ingestionId=${match.id}`);
116284
116878
  matched++;
116285
116879
  } catch (err) {
116286
- console.error(`[BulkSyncIngestion] \u274C ${devName}:`, err);
116880
+ console.error(`[BulkSyncIngestion] \u274C ${devName2}:`, err);
116287
116881
  errors++;
116288
116882
  }
116289
116883
  }
@@ -117575,14 +118169,14 @@ function buildTemplateCsv(domain, devices, start, end, now = Date.now()) {
117575
118169
  if (domain === "energy") header.push("value_reactive_kvarh");
117576
118170
  const today = nowSaoPaulo(now);
117577
118171
  const lines = [header.join(";")];
117578
- const esc12 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
118172
+ const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
117579
118173
  const { ok } = splitImportableDevices(devices);
117580
118174
  for (const dev of ok) {
117581
118175
  for (const date of daysBetween(start, end)) {
117582
118176
  if (date > today.date) break;
117583
118177
  for (let h3 = 0; h3 < 24; h3++) {
117584
118178
  if (date === today.date && h3 >= today.hour) break;
117585
- 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`, ""];
117586
118180
  if (domain === "energy") cols.push("");
117587
118181
  lines.push(cols.join(";"));
117588
118182
  }
@@ -117652,8 +118246,8 @@ function parseDecimal(v) {
117652
118246
  if (typeof v === "number") return Number.isFinite(v) ? v : NaN;
117653
118247
  const s = String(v ?? "").trim();
117654
118248
  if (!s) return null;
117655
- const norm2 = s.includes(",") ? s.replace(/\./g, "").replace(",", ".") : s;
117656
- 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;
117657
118251
  }
117658
118252
  function rowsFromTable(domain, table) {
117659
118253
  const errors = [];
@@ -117843,10 +118437,10 @@ function accumulatedRows(domain, entries, profile = DEFAULT_DISTRIBUTION_PROFILE
117843
118437
  }
117844
118438
  function buildAccumulatedTemplateCsv(domain, devices, start, end) {
117845
118439
  const lines = [["gateway_id", "slave_id", "device_name", "start_date", "end_date", TOTAL_COLUMN[domain]].join(";")];
117846
- const esc12 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
118440
+ const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
117847
118441
  for (const dev of devices || []) {
117848
118442
  if (!isImportableKey(dev)) continue;
117849
- 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(";"));
117850
118444
  }
117851
118445
  return { csv: "\uFEFF" + lines.join("\r\n") + "\r\n", rows: lines.length - 1 };
117852
118446
  }
@@ -118010,11 +118604,15 @@ function createTelemetryImportApi(cfg) {
118010
118604
 
118011
118605
  // src/components/premium-modals/telemetry-import/openTelemetryImportModal.ts
118012
118606
  var STEPS2 = [
118607
+ { n: 0, label: "Dispositivos" },
118013
118608
  { n: 1, label: "Modelo" },
118014
118609
  { n: 2, label: "Planilha" },
118015
118610
  { n: 3, label: "Valida\xE7\xE3o" },
118016
118611
  { n: 4, label: "Importa\xE7\xE3o" }
118017
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();
118018
118616
  var DOMAIN_TEXT = {
118019
118617
  energy: { noun: "energia", unit: "kWh", icon: "\u26A1" },
118020
118618
  water: { noun: "\xE1gua", unit: "m\xB3", icon: "\u{1F4A7}" }
@@ -118036,7 +118634,7 @@ function fmtSaoPaulo(iso) {
118036
118634
  return `${p(d.getUTCDate())}/${p(d.getUTCMonth() + 1)}/${d.getUTCFullYear()} ${p(d.getUTCHours())}:00`;
118037
118635
  }
118038
118636
  var STYLE_ID15 = "myio-tlmimport-styles";
118039
- function esc11(v) {
118637
+ function esc12(v) {
118040
118638
  return String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
118041
118639
  }
118042
118640
  var fmtNum = (n, d = 0) => Number.isFinite(Number(n)) ? Number(n).toLocaleString("pt-BR", { minimumFractionDigits: d, maximumFractionDigits: d }) : "\u2014";
@@ -118046,7 +118644,19 @@ function injectStyles15() {
118046
118644
  style.id = STYLE_ID15;
118047
118645
  style.textContent = `
118048
118646
  .tlmi { --tlmi-ac: #3e1a7d; --tlmi-ac-soft: #f1ecfa; --tlmi-ok: #16a34a; --tlmi-warn: #d97706; --tlmi-err: #dc2626;
118049
- 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; }
118050
118660
  .tlmi-stepper { display: flex; gap: 6px; }
118051
118661
  .tlmi-step { flex: 1; display: flex; align-items: center; gap: 8px; color: #64748b; padding: 6px 8px; border-radius: 10px; font-size: 13px; }
118052
118662
  .tlmi-step b { width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center;
@@ -118065,7 +118675,7 @@ function injectStyles15() {
118065
118675
  background: #fff; color: #374151; cursor: pointer; }
118066
118676
  .tlmi-btn.primary { background: var(--tlmi-ac); border-color: var(--tlmi-ac); color: #fff; }
118067
118677
  .tlmi-btn:disabled { opacity: 0.55; cursor: not-allowed; }
118068
- .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; }
118069
118679
  .tlmi-drop[data-over="1"] { border-color: var(--tlmi-ac); background: var(--tlmi-ac-soft); }
118070
118680
  .tlmi-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; }
118071
118681
  .tlmi-kpi { border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 12px; }
@@ -118099,7 +118709,7 @@ function injectStyles15() {
118099
118709
  document.head.appendChild(style);
118100
118710
  }
118101
118711
  function issuesTable(errors, limit = 100) {
118102
- 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("");
118103
118713
  const more = errors.length > limit ? `<p class="tlmi-muted">\u2026 e mais ${errors.length - limit} erro(s).</p>` : "";
118104
118714
  return `<div class="tlmi-errors"><table><thead><tr><th>Linha</th><th>Problema</th></tr></thead><tbody>${rows}</tbody></table></div>${more}`;
118105
118715
  }
@@ -118116,11 +118726,14 @@ function openTelemetryImportModal(params) {
118116
118726
  const txt = DOMAIN_TEXT[domain];
118117
118727
  const now = params.now ?? (() => Date.now());
118118
118728
  const api = "validate" in params.api ? params.api : createTelemetryImportApi(params.api);
118119
- 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 = "";
118120
118733
  const s = {
118121
- step: 1,
118734
+ step: 0,
118122
118735
  model: "hourly",
118123
- /** Acumulado: total digitado por device (índice em `importable`) */
118736
+ /** Acumulado: total digitado por device (chave devKey) */
118124
118737
  formTotals: {},
118125
118738
  /** Acumulado: entradas vindas de planilha (null = preenchimento na tela) */
118126
118739
  fileEntries: null,
@@ -118172,17 +118785,54 @@ function openTelemetryImportModal(params) {
118172
118785
  return `<div class="tlmi-stepper">${STEPS2.map((st) => {
118173
118786
  const state6 = st.n === s.step ? "current" : st.n < s.step ? "done" : "todo";
118174
118787
  const label = st.n === 2 && s.model === "accumulated" ? "Valores" : st.label;
118175
- 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>`;
118176
118789
  }).join("")}</div>`;
118177
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
+ }
118178
118830
  function apiErrorBanner() {
118179
118831
  if (!s.apiError) return "";
118180
- 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>`;
118181
118833
  }
118182
118834
  function step1() {
118183
- const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados ficam fora do modelo: ${esc11(
118184
- missingKey.slice(0, 5).map((d) => d.label).join(", ")
118185
- )}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
118835
+ const warn = "";
118186
118836
  const model = (value, title, hint) => `
118187
118837
  <label class="tlmi-model" data-selected="${s.model === value ? 1 : 0}">
118188
118838
  <input type="radio" name="tlmi-model" data-field="model" value="${value}" ${s.model === value ? "checked" : ""} />
@@ -118207,16 +118857,16 @@ function openTelemetryImportModal(params) {
118207
118857
  ${warn}
118208
118858
  <div class="tlmi-card"><h3>${s.model === "accumulated" ? "Per\xEDodo" : "Modelo da planilha"}</h3>
118209
118859
  <div class="tlmi-row">
118210
- <label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc11(s.period.start)}" /></label>
118211
- <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>
118212
118862
  <button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
118213
118863
  </div>
118214
- <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>
118215
118865
  </div>`;
118216
118866
  }
118217
118867
  function step2() {
118218
- const summary = s.fileName ? s.parseError ? `<div class="tlmi-banner err">${esc11(s.parseError)}</div>` : `<div class="tlmi-kpis">
118219
- <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>
118220
118870
  <div class="tlmi-kpi"><span>Linhas para importar</span><strong>${fmtNum(s.rows.length)}</strong></div>
118221
118871
  <div class="tlmi-kpi"><span>Em branco (ignoradas)</span><strong>${fmtNum(s.skippedEmpty)}</strong></div>
118222
118872
  <div class="tlmi-kpi"><span>Com erro</span><strong style="color:${s.localErrors.length ? "#dc2626" : "#16a34a"}">${fmtNum(s.localErrors.length)}</strong></div>
@@ -118256,12 +118906,14 @@ function openTelemetryImportModal(params) {
118256
118906
  }
118257
118907
  function step2Accumulated() {
118258
118908
  const fromFile = !!s.fileName && !s.parseError;
118259
- const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc11(s.fileName)}</strong>.
118260
- <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>
118261
118911
  <div class="tlmi-acc"><table><thead><tr><th>Dispositivo</th><th>Total (${txt.unit})</th></tr></thead><tbody>
118262
118912
  ${importable.map(
118263
- (d, i) => `<tr><td>${esc11(d.label)}</td>
118264
- <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>`
118265
118917
  ).join("")}
118266
118918
  </tbody></table></div>`;
118267
118919
  return `
@@ -118274,7 +118926,7 @@ function openTelemetryImportModal(params) {
118274
118926
  <input type="file" accept=".xlsx,.xls,.csv" data-field="file" hidden />
118275
118927
  \u{1F4C4} Clique ou arraste a planilha aqui (.xlsx ou .csv)
118276
118928
  </label>
118277
- ${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>` : ""}
118278
118930
  </div>
118279
118931
  <div data-role="acc-summary" style="display:flex;flex-direction:column;gap:12px">${accSummaryHtml()}</div>`;
118280
118932
  }
@@ -118300,7 +118952,7 @@ function openTelemetryImportModal(params) {
118300
118952
  <div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
118301
118953
  <div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
118302
118954
  </div>
118303
- <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>
118304
118956
  ${reactiveWarn}
118305
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.
118306
118958
  <label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
@@ -118319,7 +118971,7 @@ function openTelemetryImportModal(params) {
118319
118971
  <div class="tlmi-muted" style="margin-top:4px">Dispositivos manuais continuam aparecendo sem comunica\xE7\xE3o no status:
118320
118972
  o status conta s\xF3 leitura medida. Os totais e os cards usam os dados importados.</div></div>`;
118321
118973
  } else if (j.status === "failed") {
118322
- 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>`;
118323
118975
  } else if (j.status === "cancelled") {
118324
118976
  banner = '<div class="tlmi-banner warn">Importa\xE7\xE3o cancelada. As leituras anteriores foram mantidas.</div>';
118325
118977
  } else if (j.status === "reverted") {
@@ -118331,14 +118983,14 @@ function openTelemetryImportModal(params) {
118331
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>
118332
118984
  </div>` : "";
118333
118985
  return `
118334
- <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>
118335
118987
  <div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
118336
118988
  <div class="tlmi-kpis" style="margin-top:12px">
118337
118989
  <div class="tlmi-kpi"><span>Progresso</span><strong>${fmtNum(pct)}%</strong></div>
118338
118990
  <div class="tlmi-kpi"><span>Leituras removidas</span><strong>${fmtNum(j.deleted)}</strong></div>
118339
118991
  <div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
118340
118992
  </div>
118341
- ${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>` : ""}
118342
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>
118343
118995
  <span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
118344
118996
  ${revert}
@@ -118349,14 +119001,15 @@ function openTelemetryImportModal(params) {
118349
119001
  function render3() {
118350
119002
  if (closed) return;
118351
119003
  const step2Body = () => s.model === "accumulated" ? step2Accumulated() : step2();
118352
- 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();
118353
119005
  root.innerHTML = stepper() + body;
118354
119006
  syncFooter();
118355
119007
  }
118356
119008
  function syncFooter() {
118357
119009
  const v = s.validation;
118358
119010
  const terminal = s.job ? TERMINAL_JOB_STATUSES.includes(s.job.status) : false;
118359
- 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 });
118360
119013
  if (s.step === 1) modal.setButton("next", { label: "Avan\xE7ar", disabled: false, hidden: false });
118361
119014
  if (s.step === 2)
118362
119015
  modal.setButton("next", {
@@ -118375,7 +119028,7 @@ function openTelemetryImportModal(params) {
118375
119028
  if (s.step === 4) modal.setButton("next", { label: "Concluir", hidden: !terminal, disabled: false });
118376
119029
  }
118377
119030
  function goBack() {
118378
- if (s.busy || s.step === 1 || s.step === 4) return;
119031
+ if (s.busy || s.step === 0 || s.step === 4) return;
118379
119032
  s.apiError = "";
118380
119033
  if (s.step === 3) s.validation = null;
118381
119034
  s.step = s.step - 1;
@@ -118383,7 +119036,16 @@ function openTelemetryImportModal(params) {
118383
119036
  }
118384
119037
  async function goNext() {
118385
119038
  if (s.busy) return;
118386
- 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) {
118387
119049
  if (s.model === "accumulated") recomputeAccumulated();
118388
119050
  s.step = 2;
118389
119051
  render3();
@@ -118414,10 +119076,10 @@ function openTelemetryImportModal(params) {
118414
119076
  const entries = [];
118415
119077
  const errors = [];
118416
119078
  importable.forEach((d, i) => {
118417
- const total = parseDecimal(s.formTotals[i] ?? "");
119079
+ const total = parseDecimal(s.formTotals[devKey(d)] ?? "");
118418
119080
  if (total === null) return;
118419
119081
  if (Number.isNaN(total) || total < 0) {
118420
- 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` });
118421
119083
  return;
118422
119084
  }
118423
119085
  entries.push({
@@ -118568,6 +119230,14 @@ function openTelemetryImportModal(params) {
118568
119230
  const el2 = e.target.closest("[data-action]");
118569
119231
  if (!el2) return;
118570
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
+ }
118571
119241
  if (el2.dataset.action === "cancel") void cancelJob();
118572
119242
  if (el2.dataset.action === "revert") void revertJob();
118573
119243
  if (el2.dataset.action === "use-form") {
@@ -118578,13 +119248,26 @@ function openTelemetryImportModal(params) {
118578
119248
  });
118579
119249
  root.addEventListener("input", (e) => {
118580
119250
  const t = e.target;
119251
+ if (t.dataset.field === "sel-filter") {
119252
+ selFilter = t.value;
119253
+ refreshSelection();
119254
+ return;
119255
+ }
118581
119256
  if (t.dataset.total === void 0) return;
118582
- s.formTotals[Number(t.dataset.total)] = t.value;
119257
+ s.formTotals[t.dataset.total] = t.value;
118583
119258
  recomputeAccumulated();
118584
119259
  refreshAccSummary();
118585
119260
  });
118586
119261
  root.addEventListener("change", (e) => {
118587
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
+ }
118588
119271
  if (t.dataset.field === "start") s.period.start = t.value;
118589
119272
  if (t.dataset.field === "end") s.period.end = t.value;
118590
119273
  if (t.dataset.field === "file") void loadFile(t.files?.[0]);
@@ -118655,8 +119338,8 @@ function standardDeviceName(domain, sigla, deviceProfile, seq) {
118655
119338
  return `${NAME_PREFIX[domain]}${sigla}_${standardNameToken(deviceProfile)}_${String(seq).padStart(3, "0")}`;
118656
119339
  }
118657
119340
  function nextStandardSeq(domain, sigla, deviceProfile, existingNames) {
118658
- const esc12 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
118659
- const re = new RegExp(`^${esc12(NAME_PREFIX[domain])}${esc12(sigla)}_${esc12(standardNameToken(deviceProfile))}_(\\d+)$`, "i");
119341
+ const esc13 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
119342
+ const re = new RegExp(`^${esc13(NAME_PREFIX[domain])}${esc13(sigla)}_${esc13(standardNameToken(deviceProfile))}_(\\d+)$`, "i");
118660
119343
  const max = existingNames.reduce((acc, n) => {
118661
119344
  const m = re.exec(String(n || "").trim());
118662
119345
  return m ? Math.max(acc, Number(m[1])) : acc;
@@ -118680,8 +119363,8 @@ function siglaFromManualAsset(assetName) {
118680
119363
  return /^[A-Z0-9_]+$/.test(sigla) ? sigla : null;
118681
119364
  }
118682
119365
  function nextManualSeq(domain, sigla, existingNames) {
118683
- const esc12 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
118684
- 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");
118685
119368
  const max = existingNames.reduce((acc, n) => {
118686
119369
  const m = re.exec(String(n || "").trim());
118687
119370
  return m ? Math.max(acc, Number(m[1])) : acc;
@@ -153670,10 +154353,10 @@ var AlarmsNotificationsPanelView = class {
153670
154353
  const renderListPanel = (group, items, sel) => {
153671
154354
  if (items.length === 0) return '<div class="afm-empty">Nenhum item encontrado</div>';
153672
154355
  return items.map((item) => {
153673
- const esc12 = this.esc(item);
154356
+ const esc13 = this.esc(item);
153674
154357
  return `<label class="afm-check-item">
153675
- <input type="checkbox" class="afm-checkbox" data-group="${group}" data-value="${esc12}"${sel.has(item) ? " checked" : ""}>
153676
- <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>
153677
154360
  </label>`;
153678
154361
  }).join("");
153679
154362
  };
@@ -166551,7 +167234,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166551
167234
  const docTitle = buildActivationReportTitle(deviceName, opts.customerName);
166552
167235
  const issuedAt = formatIssuedAt(/* @__PURE__ */ new Date(), locale);
166553
167236
  const utilization = data.totalHours > 0 ? (data.totalOnMinutes / (data.totalHours * 60) * 100).toFixed(1) : "0.0";
166554
- 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]);
166555
167238
  const htmlContent = `
166556
167239
  <!DOCTYPE html>
166557
167240
  <html lang="pt-BR">
@@ -166603,14 +167286,14 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166603
167286
  <div class="brand">MyIO BAS</div>
166604
167287
  <h1>Relat\xF3rio de Acionamentos</h1>
166605
167288
  <div class="meta">
166606
- <div><b>Dispositivo:</b> ${esc12(deviceName)}</div>
167289
+ <div><b>Dispositivo:</b> ${esc13(deviceName)}</div>
166607
167290
  <div><b>Per\xEDodo:</b> ${periodStart} \u2014 ${periodEnd}</div>
166608
167291
  </div>
166609
167292
  </div>
166610
167293
  ${customerName ? `
166611
167294
  <div class="customer-badge">
166612
167295
  <div class="label">Cliente</div>
166613
- <div class="value">${esc12(customerName)}</div>
167296
+ <div class="value">${esc13(customerName)}</div>
166614
167297
  </div>` : ""}
166615
167298
  </div>
166616
167299
 
@@ -166621,7 +167304,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166621
167304
  </div>
166622
167305
  <div class="summary-card accent-green">
166623
167306
  <div class="summary-value">${formatDurationMinutes(data.totalOnMinutes)}</div>
166624
- <div class="summary-label">Tempo ${esc12(labelOn)}</div>
167307
+ <div class="summary-label">Tempo ${esc13(labelOn)}</div>
166625
167308
  </div>
166626
167309
  <div class="summary-card accent-amber">
166627
167310
  <div class="summary-value">${utilization}%</div>
@@ -166649,7 +167332,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166649
167332
  <tr>
166650
167333
  <td>${formatDateForExport(seg.startTime, locale)}</td>
166651
167334
  <td>${formatDateForExport(seg.endTime, locale)}</td>
166652
- <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>
166653
167336
  <td>${formatDurationMinutes(seg.durationMinutes)}</td>
166654
167337
  <td>${seg.source === "manual" ? "Manual" : seg.source === "schedule" ? "Agendamento" : seg.source === "automation" ? "Automa\xE7\xE3o" : "Desconhecido"}</td>
166655
167338
  </tr>
@@ -166658,7 +167341,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
166658
167341
  </table>
166659
167342
 
166660
167343
  <div class="footer">
166661
- <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>
166662
167345
  </div>
166663
167346
  </body>
166664
167347
  </html>
@@ -181694,6 +182377,7 @@ var version = package_default.version || "0.0.0";
181694
182377
  calculateStats,
181695
182378
  canEditAlarmRules,
181696
182379
  canModifyAnnotation,
182380
+ categoryKeyFromLabel,
181697
182381
  centsToDecimalString,
181698
182382
  checkCustomerCodeAvailable,
181699
182383
  clampTemperature,
@@ -181835,7 +182519,6 @@ var version = package_default.version || "0.0.0";
181835
182519
  detectSuperAdminMyio,
181836
182520
  determineInterval,
181837
182521
  deviceCategoryLabel,
181838
- deviceCategoryToPanelTerm,
181839
182522
  deviceIconLabels,
181840
182523
  deviceIcons,
181841
182524
  deviceNameToDeviceProductCode,
@@ -182130,9 +182813,7 @@ var version = package_default.version || "0.0.0";
182130
182813
  openWelcomeModal,
182131
182814
  openWellPumpsModal,
182132
182815
  overlayWithholdsVerdict,
182133
- panelCategoryToWire,
182134
182816
  panelDomainToWire,
182135
- panelTermToDeviceCategory,
182136
182817
  parseBinaryState,
182137
182818
  parseClassificationEntities,
182138
182819
  parseCsv,
@@ -182255,7 +182936,6 @@ var version = package_default.version || "0.0.0";
182255
182936
  valveHistoryFromTelemetry,
182256
182937
  version,
182257
182938
  waterDeviceStatusIcons,
182258
- wireCategoryToPanel,
182259
182939
  wireDomainToPanel,
182260
182940
  writeFreshdeskSyncedAtToTB,
182261
182941
  writeFreshdeskTicketsToTB,