myio-js-library 0.1.588 → 0.1.591
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 +1035 -346
- package/dist/index.d.cts +153 -35
- package/dist/index.d.ts +153 -35
- package/dist/index.js +1034 -342
- package/dist/myio-js-library.umd.js +1034 -342
- package/dist/myio-js-library.umd.min.js +1 -1
- package/package.json +1 -1
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.
|
|
993
|
+
version: "0.1.591",
|
|
997
994
|
description: "A clean, standalone JS SDK for MYIO projects",
|
|
998
995
|
license: "MIT",
|
|
999
996
|
repository: "github:gh-myio/myio-js-library",
|
|
@@ -21719,7 +21716,7 @@ async function valuateDomainMoney(opts) {
|
|
|
21719
21716
|
const timezone = opts.timezone || TARIFF_DEFAULT_TIMEZONE;
|
|
21720
21717
|
const devices = (opts.devices || []).filter((d) => d && d.key && isMoneyConvertibleGroup(opts.domain, d.group));
|
|
21721
21718
|
const categoryByKey = /* @__PURE__ */ new Map();
|
|
21722
|
-
for (const d of devices) categoryByKey.set(d.key, resolveMoneyCategory(opts.rule, d.group));
|
|
21719
|
+
for (const d of devices) categoryByKey.set(d.key, d.category || resolveMoneyCategory(opts.rule, d.group));
|
|
21723
21720
|
const categories = Array.from(new Set(Array.from(categoryByKey.values()).filter(Boolean)));
|
|
21724
21721
|
const trees = {};
|
|
21725
21722
|
const years = yearsSpanned(opts.startTs, opts.endTs, timezone);
|
|
@@ -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
|
|
33204
|
-
return rows.map((r) => r.map((c) => `"${
|
|
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
|
|
37613
|
-
const base =
|
|
37609
|
+
const esc13 = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
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
|
-
${
|
|
37619
|
-
<button type="button" class="myio-dr-copy" data-copy="${
|
|
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,301 @@ 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
|
+
let bp = basePath ? `/${basePath.replace(/^\/+|\/+$/g, "")}` : "";
|
|
63431
|
+
if (bp && b.toLowerCase().endsWith(bp.toLowerCase())) bp = "";
|
|
63432
|
+
const p = path.startsWith("/") ? path : `/${path}`;
|
|
63433
|
+
return `${b}${bp}${p}`;
|
|
63434
|
+
}
|
|
63435
|
+
function tariffQuery(sel, granularity) {
|
|
63436
|
+
const qs = new URLSearchParams();
|
|
63437
|
+
qs.set("domain", sel.domain);
|
|
63438
|
+
qs.set("category", sel.category);
|
|
63439
|
+
qs.set("year", String(sel.year));
|
|
63440
|
+
if (granularity) qs.set("granularity", granularity);
|
|
63441
|
+
return qs.toString();
|
|
63442
|
+
}
|
|
63443
|
+
function unwrapGcdrEnvelope(body) {
|
|
63444
|
+
if (body && typeof body === "object" && !Array.isArray(body)) {
|
|
63445
|
+
const b = body;
|
|
63446
|
+
if (b.success === true && b.data && typeof b.data === "object") return b.data;
|
|
63447
|
+
}
|
|
63448
|
+
return body;
|
|
63449
|
+
}
|
|
63450
|
+
function parseETagVersion(headers) {
|
|
63451
|
+
const raw = headers.get("ETag") || headers.get("etag");
|
|
63452
|
+
if (!raw) return void 0;
|
|
63453
|
+
const m = /"?(-?\d+)"?/.exec(raw);
|
|
63454
|
+
return m ? Number(m[1]) : void 0;
|
|
63455
|
+
}
|
|
63456
|
+
var TariffApiClient = class {
|
|
63457
|
+
cfg;
|
|
63458
|
+
fetchImpl;
|
|
63459
|
+
basePath;
|
|
63460
|
+
constructor(config2) {
|
|
63461
|
+
if (!config2 || !config2.baseUrl) {
|
|
63462
|
+
throw new Error("TariffApiClient requires a baseUrl.");
|
|
63463
|
+
}
|
|
63464
|
+
this.cfg = config2;
|
|
63465
|
+
const injected = config2.fetchImpl || globalThis.fetch;
|
|
63466
|
+
if (typeof injected !== "function") {
|
|
63467
|
+
throw new Error("TariffApiClient requires a fetch implementation.");
|
|
63468
|
+
}
|
|
63469
|
+
this.fetchImpl = config2.fetchImpl ? config2.fetchImpl : injected.bind(globalThis);
|
|
63470
|
+
this.basePath = config2.basePath ?? "api/v1";
|
|
63471
|
+
}
|
|
63472
|
+
authHeaders() {
|
|
63473
|
+
const h3 = {};
|
|
63474
|
+
if (this.cfg.apiKey) h3["X-API-Key"] = this.cfg.apiKey;
|
|
63475
|
+
if (this.cfg.jwt) h3["Authorization"] = `Bearer ${this.cfg.jwt}`;
|
|
63476
|
+
if (this.cfg.tenantId) h3["X-Tenant-Id"] = this.cfg.tenantId;
|
|
63477
|
+
return h3;
|
|
63478
|
+
}
|
|
63479
|
+
/**
|
|
63480
|
+
* Tariff categories: globals (`customerId` null) + the customer's own, ordered
|
|
63481
|
+
* by `sortOrder`, then `key` (server order is kept). `includeInactive` defaults
|
|
63482
|
+
* to `true` so existing tariffs of an inactive category still get a label.
|
|
63483
|
+
*/
|
|
63484
|
+
async listCategories(customerId, opts = {}) {
|
|
63485
|
+
const qs = new URLSearchParams();
|
|
63486
|
+
if (customerId) qs.set("customerId", customerId);
|
|
63487
|
+
qs.set("includeInactive", String(opts.includeInactive ?? true));
|
|
63488
|
+
const url = joinUrl(this.cfg.baseUrl, this.basePath, `/tariff-categories?${qs.toString()}`);
|
|
63489
|
+
const res = await this.fetchImpl(url, {
|
|
63490
|
+
method: "GET",
|
|
63491
|
+
headers: { Accept: "application/json", ...this.authHeaders() }
|
|
63492
|
+
});
|
|
63493
|
+
const body = await this.readBody(res);
|
|
63494
|
+
if (!res.ok) throw this.toError(res, body);
|
|
63495
|
+
const data = unwrapGcdrEnvelope(body);
|
|
63496
|
+
const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : null;
|
|
63497
|
+
if (!items) throw new TariffApiError("TARIFF_CATEGORIES_INVALID_RESPONSE", res.status, "Resposta sem items");
|
|
63498
|
+
return items.filter((c) => c && typeof c.key === "string" && c.key);
|
|
63499
|
+
}
|
|
63500
|
+
// -------------------------------------------------------------------------
|
|
63501
|
+
// RFC-0081 — gestão de categorias (escrita) + classificação de devices
|
|
63502
|
+
// -------------------------------------------------------------------------
|
|
63503
|
+
/** POST /tariff-categories — cria (key imutável depois). */
|
|
63504
|
+
async createCategory(input) {
|
|
63505
|
+
return await this.json("POST", "/tariff-categories", input);
|
|
63506
|
+
}
|
|
63507
|
+
/** PATCH /tariff-categories/:key — label / description / sortOrder / isActive. */
|
|
63508
|
+
async updateCategory(key, patch) {
|
|
63509
|
+
return await this.json("PATCH", `/tariff-categories/${encodeURIComponent(key)}`, patch);
|
|
63510
|
+
}
|
|
63511
|
+
/** GET /tariff-categories/:key/usage — quantos devices e tarifas usam a categoria. */
|
|
63512
|
+
async getCategoryUsage(key) {
|
|
63513
|
+
const u = await this.json("GET", `/tariff-categories/${encodeURIComponent(key)}/usage`);
|
|
63514
|
+
return {
|
|
63515
|
+
devices: Number(u?.devices ?? 0),
|
|
63516
|
+
tariffs: Number(u?.tariffs ?? 0),
|
|
63517
|
+
customers: Array.isArray(u?.customers) ? u.customers : []
|
|
63518
|
+
};
|
|
63519
|
+
}
|
|
63520
|
+
/**
|
|
63521
|
+
* DELETE /tariff-categories/:key. Em uso (devices/tarifas) o GCDR responde 409
|
|
63522
|
+
* TARIFF_CATEGORY_IN_USE; com `cascade: true` (o usuário já confirmou a perda)
|
|
63523
|
+
* pede ao GCDR para apagar as tarifas e tirar a categoria dos devices.
|
|
63524
|
+
*/
|
|
63525
|
+
async deleteCategory(key, opts = {}) {
|
|
63526
|
+
const qs = opts.cascade ? "?cascade=true" : "";
|
|
63527
|
+
await this.json("DELETE", `/tariff-categories/${encodeURIComponent(key)}${qs}`);
|
|
63528
|
+
}
|
|
63529
|
+
/** GET /devices?customerId= (paginado) — devices do customer com a categoria atual. */
|
|
63530
|
+
async listCustomerDevices(customerId, opts = {}) {
|
|
63531
|
+
const pageSize = opts.pageSize ?? 100;
|
|
63532
|
+
const maxPages = opts.maxPages ?? 50;
|
|
63533
|
+
const out = [];
|
|
63534
|
+
let cursor;
|
|
63535
|
+
for (let page = 0; page < maxPages; page++) {
|
|
63536
|
+
const qs = new URLSearchParams({ customerId, limit: String(pageSize) });
|
|
63537
|
+
if (cursor) qs.set("cursor", cursor);
|
|
63538
|
+
const data = await this.json("GET", `/devices?${qs.toString()}`);
|
|
63539
|
+
const items = Array.isArray(data) ? data : data?.items || [];
|
|
63540
|
+
for (const d of items) out.push(toDeviceSummary(d));
|
|
63541
|
+
const pg = Array.isArray(data) ? void 0 : data?.pagination || data;
|
|
63542
|
+
if (!pg?.hasMore || !pg?.nextCursor) break;
|
|
63543
|
+
cursor = String(pg.nextCursor);
|
|
63544
|
+
}
|
|
63545
|
+
return out;
|
|
63546
|
+
}
|
|
63547
|
+
/** GET /devices/:id — resumo com a categoria atual. */
|
|
63548
|
+
async getDevice(deviceId) {
|
|
63549
|
+
return toDeviceSummary(await this.json("GET", `/devices/${encodeURIComponent(deviceId)}`));
|
|
63550
|
+
}
|
|
63551
|
+
/** PATCH /devices/:id { tariffCategory } — `null` tira o device de qualquer categoria. */
|
|
63552
|
+
async setDeviceCategory(deviceId, key) {
|
|
63553
|
+
const d = await this.json("PATCH", `/devices/${encodeURIComponent(deviceId)}`, { tariffCategory: key });
|
|
63554
|
+
return toDeviceSummary(d);
|
|
63555
|
+
}
|
|
63556
|
+
/** Chamada JSON genérica (envelope GCDR desembrulhado; erro → TariffApiError). */
|
|
63557
|
+
async json(method, path, body) {
|
|
63558
|
+
const url = joinUrl(this.cfg.baseUrl, this.basePath, path);
|
|
63559
|
+
const headers = { Accept: "application/json", ...this.authHeaders() };
|
|
63560
|
+
if (body !== void 0) headers["Content-Type"] = "application/json";
|
|
63561
|
+
const res = await this.fetchImpl(url, {
|
|
63562
|
+
method,
|
|
63563
|
+
headers,
|
|
63564
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
63565
|
+
});
|
|
63566
|
+
if (res.status === 204) return null;
|
|
63567
|
+
const parsed = await this.readBody(res);
|
|
63568
|
+
if (!res.ok) throw this.toError(res, parsed);
|
|
63569
|
+
return unwrapGcdrEnvelope(parsed);
|
|
63570
|
+
}
|
|
63571
|
+
/** Read the tariff tree. `granularity` defaults to `day` server-side. */
|
|
63572
|
+
async getTariff(sel, granularity = "hour") {
|
|
63573
|
+
const url = joinUrl(
|
|
63574
|
+
this.cfg.baseUrl,
|
|
63575
|
+
this.basePath,
|
|
63576
|
+
`/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel, granularity)}`
|
|
63577
|
+
);
|
|
63578
|
+
const res = await this.fetchImpl(url, {
|
|
63579
|
+
method: "GET",
|
|
63580
|
+
headers: { Accept: "application/json", ...this.authHeaders() }
|
|
63581
|
+
});
|
|
63582
|
+
const body = await this.readBody(res);
|
|
63583
|
+
if (!res.ok) throw this.toError(res, body);
|
|
63584
|
+
const etagVersion = parseETagVersion(res.headers);
|
|
63585
|
+
const parsed = unwrapGcdrEnvelope(body) || {};
|
|
63586
|
+
return {
|
|
63587
|
+
customerId: sel.customerId,
|
|
63588
|
+
domain: sel.domain,
|
|
63589
|
+
category: sel.category,
|
|
63590
|
+
year: sel.year,
|
|
63591
|
+
unit: parsed.unit,
|
|
63592
|
+
currency: parsed.currency,
|
|
63593
|
+
tariffModel: parsed.tariffModel,
|
|
63594
|
+
timezone: parsed.timezone,
|
|
63595
|
+
version: typeof parsed.version === "number" ? parsed.version : etagVersion ?? 0,
|
|
63596
|
+
tree: parsed.tree || {}
|
|
63597
|
+
};
|
|
63598
|
+
}
|
|
63599
|
+
/** REPLACE the whole year with a nested price tree. */
|
|
63600
|
+
async putTariff(sel, tree, expectedVersion) {
|
|
63601
|
+
return this.write("PUT", sel, { ...tree, ...guardBody(expectedVersion) }, expectedVersion);
|
|
63602
|
+
}
|
|
63603
|
+
/** MERGE sparse buckets into the year (finest level wins). */
|
|
63604
|
+
async patchTariff(sel, buckets, expectedVersion) {
|
|
63605
|
+
return this.write("PATCH", sel, { buckets, ...guardBody(expectedVersion) }, expectedVersion);
|
|
63606
|
+
}
|
|
63607
|
+
/**
|
|
63608
|
+
* DELETE the whole year (no `bucket`) or one sub-bucket (`bucket` present).
|
|
63609
|
+
* Whole-year delete is idempotent (204 even if absent).
|
|
63610
|
+
*/
|
|
63611
|
+
async deleteTariff(sel, opts = {}) {
|
|
63612
|
+
const hasBody = Boolean(opts.bucket) || typeof opts.expectedVersion === "number";
|
|
63613
|
+
const url = joinUrl(
|
|
63614
|
+
this.cfg.baseUrl,
|
|
63615
|
+
this.basePath,
|
|
63616
|
+
`/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
|
|
63617
|
+
);
|
|
63618
|
+
const headers = { Accept: "application/json", ...this.authHeaders() };
|
|
63619
|
+
if (typeof opts.expectedVersion === "number") headers["If-Match"] = `"${opts.expectedVersion}"`;
|
|
63620
|
+
const init = { method: "DELETE", headers };
|
|
63621
|
+
if (hasBody) {
|
|
63622
|
+
headers["Content-Type"] = "application/json";
|
|
63623
|
+
init.body = JSON.stringify({
|
|
63624
|
+
...opts.bucket ? { bucket: opts.bucket } : {},
|
|
63625
|
+
...guardBody(opts.expectedVersion)
|
|
63626
|
+
});
|
|
63627
|
+
}
|
|
63628
|
+
const res = await this.fetchImpl(url, init);
|
|
63629
|
+
if (res.status === 204) return {};
|
|
63630
|
+
const body = await this.readBody(res);
|
|
63631
|
+
if (!res.ok) throw this.toError(res, body);
|
|
63632
|
+
const etagVersion = parseETagVersion(res.headers);
|
|
63633
|
+
const data = unwrapGcdrEnvelope(body);
|
|
63634
|
+
const v = (data && data.version) ?? etagVersion;
|
|
63635
|
+
return typeof v === "number" ? { version: v } : {};
|
|
63636
|
+
}
|
|
63637
|
+
async write(method, sel, body, expectedVersion) {
|
|
63638
|
+
const url = joinUrl(
|
|
63639
|
+
this.cfg.baseUrl,
|
|
63640
|
+
this.basePath,
|
|
63641
|
+
`/customers/${encodeURIComponent(sel.customerId)}/tariffs?${tariffQuery(sel)}`
|
|
63642
|
+
);
|
|
63643
|
+
const headers = {
|
|
63644
|
+
Accept: "application/json",
|
|
63645
|
+
"Content-Type": "application/json",
|
|
63646
|
+
...this.authHeaders()
|
|
63647
|
+
};
|
|
63648
|
+
if (typeof expectedVersion === "number") headers["If-Match"] = `"${expectedVersion}"`;
|
|
63649
|
+
const res = await this.fetchImpl(url, { method, headers, body: JSON.stringify(body) });
|
|
63650
|
+
const parsed = await this.readBody(res);
|
|
63651
|
+
if (!res.ok) throw this.toError(res, parsed);
|
|
63652
|
+
const etagVersion = parseETagVersion(res.headers);
|
|
63653
|
+
const data = unwrapGcdrEnvelope(parsed);
|
|
63654
|
+
const v = (data && data.version) ?? etagVersion;
|
|
63655
|
+
return { version: typeof v === "number" ? v : (expectedVersion ?? 0) + 1 };
|
|
63656
|
+
}
|
|
63657
|
+
async readBody(res) {
|
|
63658
|
+
try {
|
|
63659
|
+
const text2 = await res.text();
|
|
63660
|
+
if (!text2) return null;
|
|
63661
|
+
return JSON.parse(text2);
|
|
63662
|
+
} catch {
|
|
63663
|
+
return null;
|
|
63664
|
+
}
|
|
63665
|
+
}
|
|
63666
|
+
toError(res, body) {
|
|
63667
|
+
const err = body && body.error;
|
|
63668
|
+
if (err && typeof err === "object") {
|
|
63669
|
+
const e = err;
|
|
63670
|
+
return new TariffApiError(
|
|
63671
|
+
e.code || `HTTP_${res.status}`,
|
|
63672
|
+
res.status,
|
|
63673
|
+
e.message,
|
|
63674
|
+
e.details
|
|
63675
|
+
);
|
|
63676
|
+
}
|
|
63677
|
+
return new TariffApiError(`HTTP_${res.status}`, res.status, res.statusText);
|
|
63678
|
+
}
|
|
63679
|
+
};
|
|
63680
|
+
function guardBody(expectedVersion) {
|
|
63681
|
+
return typeof expectedVersion === "number" ? { expectedVersion } : {};
|
|
63682
|
+
}
|
|
63683
|
+
function createTariffApiClient(config2) {
|
|
63684
|
+
return new TariffApiClient(config2);
|
|
63685
|
+
}
|
|
63686
|
+
|
|
63395
63687
|
// src/components/premium-modals/settings/device-profile/DeviceProfileTab.ts
|
|
63396
63688
|
var TB_NULL_CUSTOMER_ID = "13814000-1dd2-11b2-8080-808080808080";
|
|
63397
63689
|
var STYLES_ID3 = "dpt-styles";
|
|
@@ -63441,6 +63733,7 @@ var DeviceProfileTab = class {
|
|
|
63441
63733
|
ownerName = null;
|
|
63442
63734
|
deviceProfileOptions = null;
|
|
63443
63735
|
customerOptions = null;
|
|
63736
|
+
tariff = { status: "loading", current: null, categories: [] };
|
|
63444
63737
|
constructor(config2) {
|
|
63445
63738
|
this.config = config2;
|
|
63446
63739
|
}
|
|
@@ -63463,7 +63756,74 @@ var DeviceProfileTab = class {
|
|
|
63463
63756
|
this.entity = entity;
|
|
63464
63757
|
this.attributes = attributes;
|
|
63465
63758
|
const customerId = entity?.customerId?.id;
|
|
63466
|
-
|
|
63759
|
+
const [ownerName] = await Promise.all([
|
|
63760
|
+
customerId && customerId !== TB_NULL_CUSTOMER_ID ? this.fetchCustomerName(customerId) : Promise.resolve(null),
|
|
63761
|
+
this.loadTariffCategory()
|
|
63762
|
+
]);
|
|
63763
|
+
this.ownerName = ownerName;
|
|
63764
|
+
}
|
|
63765
|
+
// ---- Categoria de tarifa (GCDR RFC-0081) ----------------------------------
|
|
63766
|
+
gcdrClient() {
|
|
63767
|
+
const g = this.config.gcdr;
|
|
63768
|
+
if (!g?.baseUrl || !g.apiKey && !g.tenantId) return null;
|
|
63769
|
+
return new TariffApiClient({
|
|
63770
|
+
baseUrl: String(g.baseUrl).replace(/\/api\/v1\/?$/, ""),
|
|
63771
|
+
apiKey: g.apiKey,
|
|
63772
|
+
tenantId: g.tenantId
|
|
63773
|
+
});
|
|
63774
|
+
}
|
|
63775
|
+
gcdrDeviceId() {
|
|
63776
|
+
return String(this.config.gcdr?.deviceId || this.attrValue("gcdrDeviceId") || "").trim();
|
|
63777
|
+
}
|
|
63778
|
+
/** Categoria atual do device + categorias do customer (globais + próprias) no GCDR. */
|
|
63779
|
+
async loadTariffCategory() {
|
|
63780
|
+
const client = this.gcdrClient();
|
|
63781
|
+
const id = this.gcdrDeviceId();
|
|
63782
|
+
if (!client) {
|
|
63783
|
+
this.tariff = { status: "unavailable", current: null, categories: [], message: "GCDR n\xE3o configurado no dashboard" };
|
|
63784
|
+
return;
|
|
63785
|
+
}
|
|
63786
|
+
if (!id) {
|
|
63787
|
+
this.tariff = { status: "unavailable", current: null, categories: [], message: "Device sem gcdrDeviceId" };
|
|
63788
|
+
return;
|
|
63789
|
+
}
|
|
63790
|
+
try {
|
|
63791
|
+
const device = await client.getDevice(id);
|
|
63792
|
+
const categories = device.customerId ? await client.listCategories(device.customerId, { includeInactive: true }) : [];
|
|
63793
|
+
this.tariff = { status: "ok", current: device.tariffCategory, categories };
|
|
63794
|
+
} catch (e) {
|
|
63795
|
+
const code = e?.code;
|
|
63796
|
+
this.tariff = {
|
|
63797
|
+
status: "error",
|
|
63798
|
+
current: null,
|
|
63799
|
+
categories: [],
|
|
63800
|
+
message: `N\xE3o foi poss\xEDvel ler o GCDR${code ? ` (${code})` : ""}`
|
|
63801
|
+
};
|
|
63802
|
+
}
|
|
63803
|
+
}
|
|
63804
|
+
tariffCategoryLabel(key) {
|
|
63805
|
+
if (!key) return "\u2014 sem categoria \u2014";
|
|
63806
|
+
const c = this.tariff.categories.find((x) => x.key === key);
|
|
63807
|
+
return c ? `${c.label}${c.isActive === false ? " (inativa)" : ""}` : key;
|
|
63808
|
+
}
|
|
63809
|
+
renderTariffCategoryRow() {
|
|
63810
|
+
const t = this.tariff;
|
|
63811
|
+
if (t.status !== "ok") {
|
|
63812
|
+
const text2 = t.status === "loading" ? "Carregando\u2026" : t.message || "\u2014";
|
|
63813
|
+
return `
|
|
63814
|
+
<div class="dpt-row" data-field="tariffCategory">
|
|
63815
|
+
<span class="dpt-label">Categoria de tarifa</span>
|
|
63816
|
+
<span class="dpt-value dpt-muted" data-testid="dpt-tariff-category">${this.esc(text2)}</span>
|
|
63817
|
+
</div>`;
|
|
63818
|
+
}
|
|
63819
|
+
return `
|
|
63820
|
+
<div class="dpt-row dpt-row--editable" data-field="tariffCategory" data-kind="tariff-category">
|
|
63821
|
+
<span class="dpt-label">Categoria de tarifa</span>
|
|
63822
|
+
<span class="dpt-value-wrap">
|
|
63823
|
+
<span class="dpt-value" data-view data-testid="dpt-tariff-category">${this.esc(this.tariffCategoryLabel(t.current))}</span>
|
|
63824
|
+
<button type="button" class="dpt-icon-btn" data-action="edit" title="Alterar categoria">\u270F\uFE0F</button>
|
|
63825
|
+
</span>
|
|
63826
|
+
</div>`;
|
|
63467
63827
|
}
|
|
63468
63828
|
async fetchEntity() {
|
|
63469
63829
|
try {
|
|
@@ -63767,6 +64127,7 @@ var DeviceProfileTab = class {
|
|
|
63767
64127
|
<div class="dpt-section">
|
|
63768
64128
|
<div class="dpt-section-title">Classifica\xE7\xE3o (atributos da aplica\xE7\xE3o)</div>
|
|
63769
64129
|
<div class="dpt-card">
|
|
64130
|
+
${this.renderTariffCategoryRow()}
|
|
63770
64131
|
${editableAttrRows}
|
|
63771
64132
|
${ingestionRow}
|
|
63772
64133
|
${readonlyRows}
|
|
@@ -63838,7 +64199,20 @@ var DeviceProfileTab = class {
|
|
|
63838
64199
|
async beginEdit(row, field, kind) {
|
|
63839
64200
|
const wrap = row.querySelector(".dpt-value-wrap");
|
|
63840
64201
|
if (!wrap) return;
|
|
63841
|
-
if (kind === "
|
|
64202
|
+
if (kind === "tariff-category") {
|
|
64203
|
+
const current = this.tariff.current;
|
|
64204
|
+
const options = this.tariff.categories.filter((c) => c.isActive !== false || c.key === current);
|
|
64205
|
+
wrap.innerHTML = this.editorHtml(
|
|
64206
|
+
`<select class="dpt-input" data-edit data-testid="dpt-tariff-category-select">
|
|
64207
|
+
<option value="" ${current ? "" : "selected"}>\u2014 sem categoria \u2014</option>
|
|
64208
|
+
${options.map(
|
|
64209
|
+
(c) => `<option value="${this.esc(c.key)}" ${c.key === current ? "selected" : ""}>${this.esc(
|
|
64210
|
+
c.label + (c.isActive === false ? " (inativa)" : "")
|
|
64211
|
+
)}</option>`
|
|
64212
|
+
).join("")}
|
|
64213
|
+
</select>`
|
|
64214
|
+
);
|
|
64215
|
+
} else if (kind === "entity-profile") {
|
|
63842
64216
|
const options = await this.fetchDeviceProfileOptions();
|
|
63843
64217
|
const currentId = this.entity?.deviceProfileId?.id || "";
|
|
63844
64218
|
wrap.innerHTML = this.editorHtml(
|
|
@@ -63879,7 +64253,20 @@ var DeviceProfileTab = class {
|
|
|
63879
64253
|
const saveBtn = row.querySelector('button[data-action="save"]');
|
|
63880
64254
|
if (saveBtn) saveBtn.disabled = true;
|
|
63881
64255
|
try {
|
|
63882
|
-
if (kind === "
|
|
64256
|
+
if (kind === "tariff-category") {
|
|
64257
|
+
const client = this.gcdrClient();
|
|
64258
|
+
if (!client) throw new Error("GCDR n\xE3o configurado.");
|
|
64259
|
+
const updated = await client.setDeviceCategory(this.gcdrDeviceId(), value || null);
|
|
64260
|
+
this.tariff = { ...this.tariff, current: updated.id ? updated.tariffCategory : value || null };
|
|
64261
|
+
try {
|
|
64262
|
+
window.dispatchEvent(
|
|
64263
|
+
new CustomEvent("myio:tariffs-updated", {
|
|
64264
|
+
detail: { source: "device-category", deviceId: this.gcdrDeviceId(), category: value || null, ts: Date.now() }
|
|
64265
|
+
})
|
|
64266
|
+
);
|
|
64267
|
+
} catch {
|
|
64268
|
+
}
|
|
64269
|
+
} else if (kind === "entity-label") {
|
|
63883
64270
|
await this.saveEntityField({ label: value });
|
|
63884
64271
|
} else if (kind === "entity-profile") {
|
|
63885
64272
|
if (!value) throw new Error("Selecione um Device Profile.");
|
|
@@ -63926,6 +64313,7 @@ var DeviceProfileTab = class {
|
|
|
63926
64313
|
.dpt-value { font-size: 13px; color: #111827; text-align: right; word-break: break-word; }
|
|
63927
64314
|
.dpt-value-wrap { display: flex; align-items: center; gap: 6px; }
|
|
63928
64315
|
.dpt-rel { color: #9ca3af; font-size: 12px; }
|
|
64316
|
+
.dpt-muted { color: #9ca3af; font-size: 12px; }
|
|
63929
64317
|
.dpt-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
|
63930
64318
|
.dpt-empty { padding: 16px 0; text-align: center; color: #9ca3af; font-size: 13px; }
|
|
63931
64319
|
.dpt-icon-btn {
|
|
@@ -66949,11 +67337,19 @@ var SettingsModalView = class _SettingsModalView {
|
|
|
66949
67337
|
return;
|
|
66950
67338
|
}
|
|
66951
67339
|
try {
|
|
67340
|
+
const orch = window.MyIOOrchestrator || {};
|
|
67341
|
+
const cfg = this.config;
|
|
66952
67342
|
this.deviceProfileTab = new DeviceProfileTab({
|
|
66953
67343
|
container,
|
|
66954
67344
|
deviceId,
|
|
66955
67345
|
jwtToken,
|
|
66956
|
-
tbBaseUrl: tbBaseUrl ?? window.location.origin
|
|
67346
|
+
tbBaseUrl: tbBaseUrl ?? window.location.origin,
|
|
67347
|
+
gcdr: {
|
|
67348
|
+
baseUrl: cfg.gcdrApiBaseUrl || orch.gcdrApiBaseUrl || "https://gcdr-api.a.myio-bas.com",
|
|
67349
|
+
apiKey: cfg.gcdrApiKey || orch.gcdrApiKey,
|
|
67350
|
+
tenantId: cfg.gcdrTenantId || orch.gcdrTenantId,
|
|
67351
|
+
deviceId: this.config.gcdrDeviceId
|
|
67352
|
+
}
|
|
66957
67353
|
});
|
|
66958
67354
|
await this.deviceProfileTab.init();
|
|
66959
67355
|
console.log("[SettingsModalView] DeviceProfileTab initialized");
|
|
@@ -67560,8 +67956,8 @@ var SettingsModalView = class _SettingsModalView {
|
|
|
67560
67956
|
twinNote.textContent = `Compartilhado com ${twinLabel} (mesmo identificador) \u2014 ao salvar, grava nos dois.`;
|
|
67561
67957
|
twinNote.hidden = false;
|
|
67562
67958
|
}
|
|
67563
|
-
const
|
|
67564
|
-
const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${
|
|
67959
|
+
const esc13 = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
67960
|
+
const options = (values, selected, placeholder) => `<option value="">${placeholder}</option>` + values.map((v) => `<option value="${esc13(v)}"${v === selected ? " selected" : ""}>${esc13(v)}</option>`).join("");
|
|
67565
67961
|
const catalog = await loadStoreSegmentCatalog(this.config.segmentCatalog);
|
|
67566
67962
|
const savedSegment = String(saved.segment || "");
|
|
67567
67963
|
const savedActivity = String(saved.activity || "");
|
|
@@ -74108,7 +74504,7 @@ var WelcomeModalView = class _WelcomeModalView {
|
|
|
74108
74504
|
if (this.metaTipEl) this.metaTipEl.style.display = "none";
|
|
74109
74505
|
}
|
|
74110
74506
|
buildMetaTipHtml(type, card) {
|
|
74111
|
-
const
|
|
74507
|
+
const esc13 = _WelcomeModalView.escapeMetaHtml;
|
|
74112
74508
|
const chip = _WelcomeModalView.metaChip;
|
|
74113
74509
|
const meta = card.metaCounts || {};
|
|
74114
74510
|
const details = card.metaDetails || {};
|
|
@@ -74118,7 +74514,7 @@ var WelcomeModalView = class _WelcomeModalView {
|
|
|
74118
74514
|
).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
|
|
74119
74515
|
const frame = (icon2, label, body) => `<div class="myio-welcome-meta-tip__header">
|
|
74120
74516
|
<span class="myio-welcome-meta-tip__icon">${icon2}</span>
|
|
74121
|
-
<span class="myio-welcome-meta-tip__title">${label} (${
|
|
74517
|
+
<span class="myio-welcome-meta-tip__title">${label} (${esc13(card.title)})</span>
|
|
74122
74518
|
<span class="myio-welcome-meta-tip__timestamp">${stamp}</span>
|
|
74123
74519
|
<button type="button" class="myio-welcome-meta-tip__close" title="Fechar">\u2715</button>
|
|
74124
74520
|
</div>
|
|
@@ -74146,8 +74542,8 @@ var WelcomeModalView = class _WelcomeModalView {
|
|
|
74146
74542
|
const chips = Object.entries(byState).map(([s, n]) => chip(`${s}: ${n}`)).join("");
|
|
74147
74543
|
const rows = alarms.slice(0, 10).map(
|
|
74148
74544
|
(a) => row(
|
|
74149
|
-
|
|
74150
|
-
[a.severity, a.state].filter(Boolean).map(
|
|
74545
|
+
esc13(a.deviceName ? `${a.deviceName} \u2014 ${a.title || "Alarme"}` : a.title || "Alarme"),
|
|
74546
|
+
[a.severity, a.state].filter(Boolean).map(esc13).join(" \xB7 ")
|
|
74151
74547
|
)
|
|
74152
74548
|
).join("");
|
|
74153
74549
|
return frame(
|
|
@@ -74171,7 +74567,7 @@ var WelcomeModalView = class _WelcomeModalView {
|
|
|
74171
74567
|
const rows = annotations.slice(0, 10).map((a) => {
|
|
74172
74568
|
const when = a.createdAt ? new Date(a.createdAt).toLocaleDateString("pt-BR") : "";
|
|
74173
74569
|
const text2 = a.text.length > 90 ? `${a.text.slice(0, 90)}\u2026` : a.text;
|
|
74174
|
-
return row(
|
|
74570
|
+
return row(esc13(a.deviceLabel || "Dispositivo"), `${esc13(text2)}${when ? ` \xB7 ${esc13(when)}` : ""}`);
|
|
74175
74571
|
}).join("");
|
|
74176
74572
|
return frame(
|
|
74177
74573
|
"\u{1F4CB}",
|
|
@@ -74182,7 +74578,7 @@ var WelcomeModalView = class _WelcomeModalView {
|
|
|
74182
74578
|
if (type === "users") {
|
|
74183
74579
|
if (meta.users === null) return frame("\u{1F465}", "Usu\xE1rios", loadingBody);
|
|
74184
74580
|
const users = details.users || [];
|
|
74185
|
-
const rows = users.slice(0, 10).map((u) => row(
|
|
74581
|
+
const rows = users.slice(0, 10).map((u) => row(esc13(u.name), esc13(u.email || ""))).join("");
|
|
74186
74582
|
return frame(
|
|
74187
74583
|
"\u{1F465}",
|
|
74188
74584
|
"Usu\xE1rios",
|
|
@@ -104217,19 +104613,19 @@ function _updateCoverageHint(topDoc) {
|
|
|
104217
104613
|
const deviceCount = data.granularity === "DEVICE" ? data.devices?.length ?? 0 : 0;
|
|
104218
104614
|
hint.textContent = `\u26A0 Meta incompleta para este dom\xEDnio/ano` + (deviceCount > 0 ? ` \xB7 Por medidor (${deviceCount})` : "") + ` \u2014 passe o mouse para detalhes`;
|
|
104219
104615
|
tabs.insertAdjacentElement("afterend", hint);
|
|
104220
|
-
const
|
|
104616
|
+
const esc13 = (s) => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
104221
104617
|
try {
|
|
104222
104618
|
_coverageDetach = InfoTooltip.attach(hint, () => {
|
|
104223
104619
|
const d = _getGoalsData(_currentDomain);
|
|
104224
104620
|
const parts = [];
|
|
104225
104621
|
if (hasCoverageGaps(d?.coverageGaps)) {
|
|
104226
|
-
parts.push(`<p style="margin:0 0 8px;">${
|
|
104622
|
+
parts.push(`<p style="margin:0 0 8px;">${esc13(buildCoverageWarningTextPtBR(d?.coverageGaps, "GERAL"))}</p>`);
|
|
104227
104623
|
}
|
|
104228
104624
|
(d?.devices || []).forEach((dev) => {
|
|
104229
104625
|
if (!hasCoverageGaps(dev?.coverageGaps)) return;
|
|
104230
104626
|
const label = dev.label || dev.code || "medidor";
|
|
104231
104627
|
parts.push(
|
|
104232
|
-
`<p style="margin:0 0 8px;">${
|
|
104628
|
+
`<p style="margin:0 0 8px;">${esc13(buildCoverageWarningTextPtBR(dev.coverageGaps, `do medidor ${label}`))}</p>`
|
|
104233
104629
|
);
|
|
104234
104630
|
});
|
|
104235
104631
|
return {
|
|
@@ -107349,10 +107745,10 @@ var DOMAIN_LABEL = {
|
|
|
107349
107745
|
energy: "Energia",
|
|
107350
107746
|
water: "\xC1gua"
|
|
107351
107747
|
};
|
|
107352
|
-
|
|
107353
|
-
|
|
107354
|
-
|
|
107355
|
-
}
|
|
107748
|
+
function categoryLabel(key, categories) {
|
|
107749
|
+
const hit = (categories || []).find((c) => c.key === key);
|
|
107750
|
+
return hit?.label || String(key ?? "");
|
|
107751
|
+
}
|
|
107356
107752
|
function unitLabel(domain) {
|
|
107357
107753
|
return domain === "water" ? "R$/m\xB3" : "R$/kWh";
|
|
107358
107754
|
}
|
|
@@ -107511,7 +107907,7 @@ function removeEntryByBounds(entries, target, opts = {}) {
|
|
|
107511
107907
|
}
|
|
107512
107908
|
function computePricingKpis(entries, opts = {}) {
|
|
107513
107909
|
const periodsByDomain = { energy: 0, water: 0 };
|
|
107514
|
-
const periodsByCategory = {
|
|
107910
|
+
const periodsByCategory = {};
|
|
107515
107911
|
let energySum = 0;
|
|
107516
107912
|
let energyN = 0;
|
|
107517
107913
|
let waterSum = 0;
|
|
@@ -107532,7 +107928,7 @@ function computePricingKpis(entries, opts = {}) {
|
|
|
107532
107928
|
combos.add(`${e.customerId}|${e.domain}|${e.category}`);
|
|
107533
107929
|
}
|
|
107534
107930
|
const covered = combos.size;
|
|
107535
|
-
const total = opts.customerCount ? opts.customerCount *
|
|
107931
|
+
const total = opts.customerCount && opts.categoryCount ? opts.customerCount * 2 * opts.categoryCount : covered;
|
|
107536
107932
|
return {
|
|
107537
107933
|
totalPeriods: entries.length,
|
|
107538
107934
|
periodsByDomain,
|
|
@@ -107587,6 +107983,36 @@ var PRICING_PANEL_CSS = `
|
|
|
107587
107983
|
.myio-pricing.show .myio-pricing__content {
|
|
107588
107984
|
transform: translateY(0) scale(1);
|
|
107589
107985
|
}
|
|
107986
|
+
/* di\xE1logo de confirma\xE7\xE3o montado acima do conte\xFAdo do painel */
|
|
107987
|
+
.myio-pricing__dialog-host { position: relative; z-index: 5; }
|
|
107988
|
+
.myio-pricing__dialog-host .myio-dialog-overlay { z-index: 5; }
|
|
107989
|
+
/* aba Categorias */
|
|
107990
|
+
.myio-pricing__cat { display: flex; flex-direction: column; gap: 10px; }
|
|
107991
|
+
.myio-pricing__cat-hint { margin: 0; font-size: 12px; color: var(--myio-text-muted, #6b7280); }
|
|
107992
|
+
.myio-pricing__cat-new, .myio-pricing__cat-devbar { display: flex; gap: 8px; align-items: center; }
|
|
107993
|
+
.myio-pricing__cat-new .myio-pricing__input, .myio-pricing__cat-devbar .myio-pricing__input { flex: 1; }
|
|
107994
|
+
.myio-pricing__cat-btn { width: auto; padding: 8px 14px; white-space: nowrap; }
|
|
107995
|
+
.myio-pricing__cat-notice { font-size: 12.5px; border-radius: 8px; padding: 8px 10px; }
|
|
107996
|
+
.myio-pricing__cat-notice--ok { background: #ecfdf5; color: #065f46; }
|
|
107997
|
+
.myio-pricing__cat-notice--error { background: #fee2e2; color: #991b1b; }
|
|
107998
|
+
.myio-pricing__cat-item { list-style: none; border: 1px solid var(--myio-border, #e5e7eb); border-radius: 10px; padding: 8px 10px; margin-bottom: 8px; }
|
|
107999
|
+
.myio-pricing__cat-row { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; }
|
|
108000
|
+
.myio-pricing__cat-main { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
|
|
108001
|
+
.myio-pricing__cat-key { color: var(--myio-text-muted, #6b7280); font-size: 11px; }
|
|
108002
|
+
.myio-pricing__badge--off { background: #f3f4f6 !important; color: #6b7280 !important; }
|
|
108003
|
+
.myio-pricing__cat-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
|
108004
|
+
.myio-pricing__cat-actions button {
|
|
108005
|
+
font: inherit; font-size: 12px; padding: 5px 10px; border-radius: 6px; cursor: pointer;
|
|
108006
|
+
border: 1px solid var(--myio-border, #d1d5db); background: var(--myio-card, #fff); color: var(--myio-text, #1f2937);
|
|
108007
|
+
}
|
|
108008
|
+
.myio-pricing__cat-actions button:disabled { opacity: 0.5; cursor: default; }
|
|
108009
|
+
.myio-pricing__cat-actions .myio-pricing__cat-danger { color: #b91c1c; border-color: #fca5a5; }
|
|
108010
|
+
.myio-pricing__cat-devices { margin-top: 10px; display: flex; flex-direction: column; gap: 8px; }
|
|
108011
|
+
.myio-pricing__cat-devlist { list-style: none; margin: 0; padding: 0; max-height: 260px; overflow: auto; }
|
|
108012
|
+
.myio-pricing__cat-devlist li { padding: 4px 2px; font-size: 13px; }
|
|
108013
|
+
.myio-pricing__cat-devlist label { display: flex; gap: 8px; align-items: center; cursor: pointer; flex-wrap: wrap; }
|
|
108014
|
+
.myio-pricing__cat-devlist small { color: var(--myio-text-muted, #6b7280); font-size: 11px; }
|
|
108015
|
+
.myio-pricing__cat-other { color: #92400e !important; }
|
|
107590
108016
|
.myio-pricing__header {
|
|
107591
108017
|
display: flex;
|
|
107592
108018
|
align-items: center;
|
|
@@ -107899,188 +108325,6 @@ function injectPricingPanelStyles(doc) {
|
|
|
107899
108325
|
doc.head.appendChild(style);
|
|
107900
108326
|
}
|
|
107901
108327
|
|
|
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
108328
|
// src/components/pricing-panel/tariffApiAdapter.ts
|
|
108085
108329
|
var PANEL_TO_WIRE_DOMAIN = {
|
|
108086
108330
|
energy: "ENERGY",
|
|
@@ -108090,14 +108334,6 @@ var WIRE_TO_PANEL_DOMAIN = {
|
|
|
108090
108334
|
ENERGY: "energy",
|
|
108091
108335
|
WATER: "water"
|
|
108092
108336
|
};
|
|
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
108337
|
function panelDomainToWire(d) {
|
|
108102
108338
|
const w = PANEL_TO_WIRE_DOMAIN[d];
|
|
108103
108339
|
if (!w) throw new Error(`Unknown panel domain: ${String(d)}`);
|
|
@@ -108108,16 +108344,6 @@ function wireDomainToPanel(w) {
|
|
|
108108
108344
|
if (!d) throw new Error(`Unknown wire domain: ${String(w)}`);
|
|
108109
108345
|
return d;
|
|
108110
108346
|
}
|
|
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
108347
|
function normalizePriceString(input) {
|
|
108122
108348
|
if (typeof input.price === "string" && input.price.trim() !== "") {
|
|
108123
108349
|
const s2 = input.price.trim();
|
|
@@ -108190,7 +108416,7 @@ function bandSelector(band, customerId, year) {
|
|
|
108190
108416
|
return {
|
|
108191
108417
|
customerId,
|
|
108192
108418
|
domain: panelDomainToWire(band.domain),
|
|
108193
|
-
category:
|
|
108419
|
+
category: band.category,
|
|
108194
108420
|
year
|
|
108195
108421
|
};
|
|
108196
108422
|
}
|
|
@@ -108395,12 +108621,7 @@ function collapseTreeToBands(tree, dims) {
|
|
|
108395
108621
|
}
|
|
108396
108622
|
return mergeContiguousDays(dayBands, dims.year);
|
|
108397
108623
|
}
|
|
108398
|
-
var
|
|
108399
|
-
["ENERGY", "SPECIFIC"],
|
|
108400
|
-
["ENERGY", "COMMON_AREA"],
|
|
108401
|
-
["WATER", "SPECIFIC"],
|
|
108402
|
-
["WATER", "COMMON_AREA"]
|
|
108403
|
-
];
|
|
108624
|
+
var WIRE_DOMAINS = ["ENERGY", "WATER"];
|
|
108404
108625
|
var TariffApiAdapter = class {
|
|
108405
108626
|
client;
|
|
108406
108627
|
year;
|
|
@@ -108414,14 +108635,24 @@ var TariffApiAdapter = class {
|
|
|
108414
108635
|
getYear() {
|
|
108415
108636
|
return this.year;
|
|
108416
108637
|
}
|
|
108638
|
+
/** GCDR tariff categories of a customer (globals + own). Errors propagate. */
|
|
108639
|
+
listCategories(customerId, opts) {
|
|
108640
|
+
return this.client.listCategories(customerId, opts);
|
|
108641
|
+
}
|
|
108417
108642
|
/**
|
|
108418
108643
|
* Load every `(domain × category)` tariff for a customer and collapse each into
|
|
108419
|
-
* panel entries.
|
|
108420
|
-
*
|
|
108644
|
+
* panel entries. `categories` = the GCDR category keys (from `listCategories`);
|
|
108645
|
+
* there is no default list. An empty tariff (`version: 0`) contributes no
|
|
108646
|
+
* entries — it is "no entries", never an error. Read errors propagate.
|
|
108421
108647
|
*/
|
|
108422
|
-
async loadEntriesForCustomer(customerId, year = this.year) {
|
|
108648
|
+
async loadEntriesForCustomer(customerId, categories, year = this.year) {
|
|
108649
|
+
if (!Array.isArray(categories) || categories.length === 0) {
|
|
108650
|
+
throw new Error("loadEntriesForCustomer requires the GCDR tariff-category keys.");
|
|
108651
|
+
}
|
|
108652
|
+
const combos = [];
|
|
108653
|
+
for (const d of WIRE_DOMAINS) for (const c of categories) combos.push([d, c]);
|
|
108423
108654
|
const out = [];
|
|
108424
|
-
for (const [domain, category] of
|
|
108655
|
+
for (const [domain, category] of combos) {
|
|
108425
108656
|
const sel = { customerId, domain, category, year };
|
|
108426
108657
|
const resp = await this.client.getTariff(sel, "hour");
|
|
108427
108658
|
this.versions.set(selectorKey(sel), resp.version);
|
|
@@ -108429,7 +108660,7 @@ var TariffApiAdapter = class {
|
|
|
108429
108660
|
const bands = collapseTreeToBands(resp.tree, {
|
|
108430
108661
|
year,
|
|
108431
108662
|
domain: wireDomainToPanel(domain),
|
|
108432
|
-
category
|
|
108663
|
+
category
|
|
108433
108664
|
});
|
|
108434
108665
|
for (const b of bands) out.push(bandToPanelEntry(b, customerId));
|
|
108435
108666
|
}
|
|
@@ -108437,7 +108668,7 @@ var TariffApiAdapter = class {
|
|
|
108437
108668
|
}
|
|
108438
108669
|
/** Convenience: read + collapse one specific tariff. */
|
|
108439
108670
|
async loadBands(customerId, domain, category, year = this.year) {
|
|
108440
|
-
const sel = { customerId, domain: panelDomainToWire(domain), category
|
|
108671
|
+
const sel = { customerId, domain: panelDomainToWire(domain), category, year };
|
|
108441
108672
|
const resp = await this.client.getTariff(sel, "hour");
|
|
108442
108673
|
this.versions.set(selectorKey(sel), resp.version);
|
|
108443
108674
|
const bands = resp.version === 0 ? [] : collapseTreeToBands(resp.tree, { year, domain, category });
|
|
@@ -108510,6 +108741,309 @@ function createTariffApiAdapter(client, opts) {
|
|
|
108510
108741
|
return new TariffApiAdapter(client, opts);
|
|
108511
108742
|
}
|
|
108512
108743
|
|
|
108744
|
+
// src/components/pricing-panel/categoriesTab.ts
|
|
108745
|
+
var esc10 = (v) => String(v ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
108746
|
+
function errText(err, fallback) {
|
|
108747
|
+
const code = err?.code;
|
|
108748
|
+
const map = {
|
|
108749
|
+
TARIFF_CATEGORY_EXISTS: "J\xE1 existe uma categoria com esse nome.",
|
|
108750
|
+
TARIFF_CATEGORY_IN_USE: "A categoria est\xE1 em uso (tarifas ou dispositivos) e o servidor recusou a exclus\xE3o.",
|
|
108751
|
+
TARIFF_CATEGORY_SYSTEM: "Categoria do sistema n\xE3o pode ser alterada.",
|
|
108752
|
+
TARIFF_CATEGORY_INACTIVE: "Categoria inativa n\xE3o recebe novos dispositivos.",
|
|
108753
|
+
TARIFF_CATEGORY_SCOPE: "Categoria de outro cliente."
|
|
108754
|
+
};
|
|
108755
|
+
return map[code || ""] || `${fallback}${code ? ` (${code})` : ""}`;
|
|
108756
|
+
}
|
|
108757
|
+
function mountCategoriesTab(opts) {
|
|
108758
|
+
const root = opts.container;
|
|
108759
|
+
let categories = [];
|
|
108760
|
+
let devices = null;
|
|
108761
|
+
let openKey = null;
|
|
108762
|
+
let editingKey = null;
|
|
108763
|
+
let busy = false;
|
|
108764
|
+
let notice = null;
|
|
108765
|
+
let loadError = null;
|
|
108766
|
+
let deviceFilter = "";
|
|
108767
|
+
let pending = /* @__PURE__ */ new Map();
|
|
108768
|
+
const customerId = () => opts.getCustomerId();
|
|
108769
|
+
const own = () => categories.filter((c) => c.customerId && c.customerId === customerId());
|
|
108770
|
+
const labelOf = (key) => key ? categories.find((c) => c.key === key)?.label || key : "\u2014 sem categoria \u2014";
|
|
108771
|
+
function deviceCount(key) {
|
|
108772
|
+
return devices ? devices.filter((d) => d.tariffCategory === key).length : null;
|
|
108773
|
+
}
|
|
108774
|
+
function render3() {
|
|
108775
|
+
const rows = own();
|
|
108776
|
+
root.innerHTML = `
|
|
108777
|
+
<div class="myio-pricing__cat" data-testid="categories-tab">
|
|
108778
|
+
<p class="myio-pricing__cat-hint">Categorias de tarifa deste cliente. Um dispositivo pertence a no m\xE1ximo uma categoria.</p>
|
|
108779
|
+
<div class="myio-pricing__cat-new">
|
|
108780
|
+
<input class="myio-pricing__input" data-testid="cat-new-label" maxlength="120"
|
|
108781
|
+
placeholder="Nome da nova categoria (ex.: Quiosques)" ${busy ? "disabled" : ""} />
|
|
108782
|
+
<button class="myio-pricing__add myio-pricing__cat-btn" data-testid="cat-create" type="button" ${busy ? "disabled" : ""}>Criar categoria</button>
|
|
108783
|
+
</div>
|
|
108784
|
+
${notice ? `<div class="myio-pricing__cat-notice myio-pricing__cat-notice--${notice.kind}" data-testid="cat-notice" role="status">${esc10(notice.text)}</div>` : ""}
|
|
108785
|
+
${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>`}
|
|
108786
|
+
</div>`;
|
|
108787
|
+
wire();
|
|
108788
|
+
}
|
|
108789
|
+
function rowHtml(c) {
|
|
108790
|
+
const n = deviceCount(c.key);
|
|
108791
|
+
const editing = editingKey === c.key;
|
|
108792
|
+
return `
|
|
108793
|
+
<li class="myio-pricing__cat-item" data-cat="${esc10(c.key)}">
|
|
108794
|
+
<div class="myio-pricing__cat-row">
|
|
108795
|
+
<div class="myio-pricing__cat-main">
|
|
108796
|
+
${editing ? `<input class="myio-pricing__input" data-testid="cat-edit-label" value="${esc10(c.label)}" maxlength="120" />` : `<strong>${esc10(c.label)}</strong>`}
|
|
108797
|
+
<small class="myio-pricing__cat-key">${esc10(c.key)}</small>
|
|
108798
|
+
<span class="myio-pricing__badge${c.isActive === false ? " myio-pricing__badge--off" : ""}">${c.isActive === false ? "Inativa" : "Ativa"}</span>
|
|
108799
|
+
</div>
|
|
108800
|
+
<div class="myio-pricing__cat-actions">
|
|
108801
|
+
${editing ? `<button type="button" data-act="save-edit" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>Salvar</button>
|
|
108802
|
+
<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>
|
|
108803
|
+
<button type="button" data-act="edit" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>Editar</button>
|
|
108804
|
+
<button type="button" data-act="toggle" data-key="${esc10(c.key)}" ${busy ? "disabled" : ""}>${c.isActive === false ? "Ativar" : "Desativar"}</button>
|
|
108805
|
+
<button type="button" class="myio-pricing__cat-danger" data-act="delete" data-key="${esc10(c.key)}" data-testid="cat-delete" ${busy ? "disabled" : ""}>Excluir</button>`}
|
|
108806
|
+
</div>
|
|
108807
|
+
</div>
|
|
108808
|
+
${openKey === c.key ? devicesHtml(c) : ""}
|
|
108809
|
+
</li>`;
|
|
108810
|
+
}
|
|
108811
|
+
function devicesHtml(c) {
|
|
108812
|
+
if (devices === null) return '<div class="myio-pricing__cat-devices">Carregando dispositivos\u2026</div>';
|
|
108813
|
+
const f = deviceFilter.trim().toLowerCase();
|
|
108814
|
+
const list = devices.filter((d) => !f || `${d.label || ""} ${d.name} ${d.identifier || ""}`.toLowerCase().includes(f)).sort((a, b) => {
|
|
108815
|
+
const ia = isIn(a, c.key) ? 0 : 1;
|
|
108816
|
+
const ib = isIn(b, c.key) ? 0 : 1;
|
|
108817
|
+
return ia - ib || (a.label || a.name).localeCompare(b.label || b.name);
|
|
108818
|
+
});
|
|
108819
|
+
const changed = [...pending.keys()].length;
|
|
108820
|
+
return `
|
|
108821
|
+
<div class="myio-pricing__cat-devices" data-testid="cat-devices-panel">
|
|
108822
|
+
<div class="myio-pricing__cat-devbar">
|
|
108823
|
+
<input class="myio-pricing__input" data-testid="cat-dev-filter" placeholder="Buscar dispositivo\u2026" value="${esc10(deviceFilter)}" />
|
|
108824
|
+
<button type="button" class="myio-pricing__add myio-pricing__cat-btn" data-act="save-devices" data-key="${esc10(c.key)}"
|
|
108825
|
+
data-testid="cat-dev-save" ${busy || changed === 0 || c.isActive === false ? "disabled" : ""}>Salvar (${changed})</button>
|
|
108826
|
+
</div>
|
|
108827
|
+
${c.isActive === false ? '<p class="myio-pricing__cat-hint">Categoria inativa: ative para incluir dispositivos.</p>' : ""}
|
|
108828
|
+
<ul class="myio-pricing__cat-devlist">${list.length ? list.map((d) => {
|
|
108829
|
+
const checked = isIn(d, c.key);
|
|
108830
|
+
const other = d.tariffCategory && d.tariffCategory !== c.key ? d.tariffCategory : null;
|
|
108831
|
+
return `<li><label>
|
|
108832
|
+
<input type="checkbox" data-dev="${esc10(d.id)}" ${checked ? "checked" : ""} ${busy ? "disabled" : ""} />
|
|
108833
|
+
<span>${esc10(d.label || d.name)}</span>
|
|
108834
|
+
${d.identifier ? `<small>${esc10(d.identifier)}</small>` : ""}
|
|
108835
|
+
${other ? `<small class="myio-pricing__cat-other">em ${esc10(labelOf(other))}${checked ? " \u2192 ser\xE1 movido" : ""}</small>` : ""}
|
|
108836
|
+
</label></li>`;
|
|
108837
|
+
}).join("") : '<li class="myio-pricing__empty">Nenhum dispositivo.</li>'}</ul>
|
|
108838
|
+
</div>`;
|
|
108839
|
+
}
|
|
108840
|
+
function isIn(d, key) {
|
|
108841
|
+
return pending.has(d.id) ? pending.get(d.id) : d.tariffCategory === key;
|
|
108842
|
+
}
|
|
108843
|
+
function wire() {
|
|
108844
|
+
const q = (sel) => root.querySelector(sel);
|
|
108845
|
+
q('[data-testid="cat-create"]')?.addEventListener("click", () => void create());
|
|
108846
|
+
q('[data-testid="cat-new-label"]')?.addEventListener("keydown", (e) => {
|
|
108847
|
+
if (e.key === "Enter") void create();
|
|
108848
|
+
});
|
|
108849
|
+
root.querySelectorAll("[data-act]").forEach(
|
|
108850
|
+
(b) => b.addEventListener("click", () => void onAction(b.dataset.act, b.dataset.key || ""))
|
|
108851
|
+
);
|
|
108852
|
+
const filter = q('[data-testid="cat-dev-filter"]');
|
|
108853
|
+
filter?.addEventListener("input", () => {
|
|
108854
|
+
deviceFilter = filter.value;
|
|
108855
|
+
const pos = filter.selectionStart;
|
|
108856
|
+
render3();
|
|
108857
|
+
const again = root.querySelector('[data-testid="cat-dev-filter"]');
|
|
108858
|
+
again?.focus();
|
|
108859
|
+
if (again && pos != null) again.setSelectionRange(pos, pos);
|
|
108860
|
+
});
|
|
108861
|
+
root.querySelectorAll("input[data-dev]").forEach(
|
|
108862
|
+
(cb) => cb.addEventListener("change", () => {
|
|
108863
|
+
const d = devices?.find((x) => x.id === cb.dataset.dev);
|
|
108864
|
+
if (!d || !openKey) return;
|
|
108865
|
+
const original = d.tariffCategory === openKey;
|
|
108866
|
+
if (cb.checked === original) pending.delete(d.id);
|
|
108867
|
+
else pending.set(d.id, cb.checked);
|
|
108868
|
+
render3();
|
|
108869
|
+
})
|
|
108870
|
+
);
|
|
108871
|
+
}
|
|
108872
|
+
async function run(fn) {
|
|
108873
|
+
if (busy) return;
|
|
108874
|
+
busy = true;
|
|
108875
|
+
notice = null;
|
|
108876
|
+
render3();
|
|
108877
|
+
try {
|
|
108878
|
+
await fn();
|
|
108879
|
+
} finally {
|
|
108880
|
+
busy = false;
|
|
108881
|
+
render3();
|
|
108882
|
+
}
|
|
108883
|
+
}
|
|
108884
|
+
async function create() {
|
|
108885
|
+
const input = root.querySelector('[data-testid="cat-new-label"]');
|
|
108886
|
+
const label = (input?.value || "").trim();
|
|
108887
|
+
if (!label) {
|
|
108888
|
+
notice = { kind: "error", text: "Informe o nome da categoria." };
|
|
108889
|
+
return render3();
|
|
108890
|
+
}
|
|
108891
|
+
const key = categoryKeyFromLabel(label);
|
|
108892
|
+
if (!key) {
|
|
108893
|
+
notice = { kind: "error", text: "Nome inv\xE1lido para gerar o c\xF3digo da categoria." };
|
|
108894
|
+
return render3();
|
|
108895
|
+
}
|
|
108896
|
+
await run(async () => {
|
|
108897
|
+
try {
|
|
108898
|
+
const maxSort = categories.reduce((m, c) => Math.max(m, Number(c.sortOrder) || 0), 0);
|
|
108899
|
+
await opts.client.createCategory({ key, label, customerId: customerId(), sortOrder: maxSort + 10, isActive: true });
|
|
108900
|
+
await reloadCategories();
|
|
108901
|
+
notice = { kind: "ok", text: `Categoria "${label}" criada.` };
|
|
108902
|
+
opts.onChanged?.();
|
|
108903
|
+
} catch (err) {
|
|
108904
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel criar a categoria") };
|
|
108905
|
+
}
|
|
108906
|
+
});
|
|
108907
|
+
}
|
|
108908
|
+
async function onAction(act, key) {
|
|
108909
|
+
const cat = categories.find((c) => c.key === key);
|
|
108910
|
+
if (act === "cancel-edit") {
|
|
108911
|
+
editingKey = null;
|
|
108912
|
+
return render3();
|
|
108913
|
+
}
|
|
108914
|
+
if (act === "edit") {
|
|
108915
|
+
editingKey = key;
|
|
108916
|
+
return render3();
|
|
108917
|
+
}
|
|
108918
|
+
if (!cat && act !== "cancel-edit") return;
|
|
108919
|
+
if (act === "save-edit") {
|
|
108920
|
+
const label = (root.querySelector('[data-testid="cat-edit-label"]')?.value || "").trim();
|
|
108921
|
+
if (!label) {
|
|
108922
|
+
notice = { kind: "error", text: "Informe o nome da categoria." };
|
|
108923
|
+
return render3();
|
|
108924
|
+
}
|
|
108925
|
+
return run(async () => {
|
|
108926
|
+
try {
|
|
108927
|
+
await opts.client.updateCategory(key, { label });
|
|
108928
|
+
editingKey = null;
|
|
108929
|
+
await reloadCategories();
|
|
108930
|
+
notice = { kind: "ok", text: "Categoria atualizada." };
|
|
108931
|
+
opts.onChanged?.();
|
|
108932
|
+
} catch (err) {
|
|
108933
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel salvar a categoria") };
|
|
108934
|
+
}
|
|
108935
|
+
});
|
|
108936
|
+
}
|
|
108937
|
+
if (act === "toggle") {
|
|
108938
|
+
return run(async () => {
|
|
108939
|
+
try {
|
|
108940
|
+
await opts.client.updateCategory(key, { isActive: cat.isActive === false });
|
|
108941
|
+
await reloadCategories();
|
|
108942
|
+
opts.onChanged?.();
|
|
108943
|
+
} catch (err) {
|
|
108944
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel alterar a categoria") };
|
|
108945
|
+
}
|
|
108946
|
+
});
|
|
108947
|
+
}
|
|
108948
|
+
if (act === "devices") {
|
|
108949
|
+
openKey = openKey === key ? null : key;
|
|
108950
|
+
pending = /* @__PURE__ */ new Map();
|
|
108951
|
+
deviceFilter = "";
|
|
108952
|
+
render3();
|
|
108953
|
+
if (openKey && devices === null) await loadDevices2();
|
|
108954
|
+
return;
|
|
108955
|
+
}
|
|
108956
|
+
if (act === "save-devices") return saveDevices(key);
|
|
108957
|
+
if (act === "delete") return remove(cat);
|
|
108958
|
+
}
|
|
108959
|
+
async function remove(cat) {
|
|
108960
|
+
let usage = { devices: 0, tariffs: 0 };
|
|
108961
|
+
try {
|
|
108962
|
+
usage = await opts.client.getCategoryUsage(cat.key);
|
|
108963
|
+
} catch (err) {
|
|
108964
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel verificar o uso da categoria") };
|
|
108965
|
+
return render3();
|
|
108966
|
+
}
|
|
108967
|
+
const inUse = usage.devices > 0 || usage.tariffs > 0;
|
|
108968
|
+
const parts = [];
|
|
108969
|
+
if (usage.tariffs > 0) parts.push(`${usage.tariffs} tarifa(s) cadastrada(s) \u2014 ser\xE3o apagadas`);
|
|
108970
|
+
if (usage.devices > 0) parts.push(`${usage.devices} dispositivo(s) \u2014 ficar\xE3o sem categoria`);
|
|
108971
|
+
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.`;
|
|
108972
|
+
const choice = await openConfirmDialog({
|
|
108973
|
+
title: inUse ? "\u26A0\uFE0F Excluir Categoria" : "Excluir Categoria",
|
|
108974
|
+
message,
|
|
108975
|
+
buttons: [
|
|
108976
|
+
{ label: "Cancelar", value: "cancel", variant: "secondary" },
|
|
108977
|
+
{ label: "Excluir", value: "confirm", variant: "danger", autoFocus: true }
|
|
108978
|
+
],
|
|
108979
|
+
container: opts.dialogContainer
|
|
108980
|
+
});
|
|
108981
|
+
if (choice !== "confirm") return;
|
|
108982
|
+
await run(async () => {
|
|
108983
|
+
try {
|
|
108984
|
+
await opts.client.deleteCategory(cat.key, { cascade: inUse });
|
|
108985
|
+
if (openKey === cat.key) openKey = null;
|
|
108986
|
+
await reloadCategories();
|
|
108987
|
+
if (devices) devices = devices.map((d) => d.tariffCategory === cat.key ? { ...d, tariffCategory: null } : d);
|
|
108988
|
+
notice = { kind: "ok", text: `Categoria "${cat.label}" exclu\xEDda.` };
|
|
108989
|
+
opts.onChanged?.();
|
|
108990
|
+
} catch (err) {
|
|
108991
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel excluir a categoria") };
|
|
108992
|
+
}
|
|
108993
|
+
});
|
|
108994
|
+
}
|
|
108995
|
+
async function saveDevices(key) {
|
|
108996
|
+
if (!devices || pending.size === 0) return;
|
|
108997
|
+
const changes = [...pending.entries()];
|
|
108998
|
+
await run(async () => {
|
|
108999
|
+
const failed = [];
|
|
109000
|
+
for (const [id, inCat] of changes) {
|
|
109001
|
+
const d = devices.find((x) => x.id === id);
|
|
109002
|
+
if (!d) continue;
|
|
109003
|
+
try {
|
|
109004
|
+
const target = inCat ? key : null;
|
|
109005
|
+
const updated = await opts.client.setDeviceCategory(id, target);
|
|
109006
|
+
d.tariffCategory = updated.id ? updated.tariffCategory : target;
|
|
109007
|
+
pending.delete(id);
|
|
109008
|
+
} catch (err) {
|
|
109009
|
+
failed.push(`${d.label || d.name}: ${errText(err, "erro")}`);
|
|
109010
|
+
}
|
|
109011
|
+
}
|
|
109012
|
+
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).` };
|
|
109013
|
+
opts.onChanged?.();
|
|
109014
|
+
});
|
|
109015
|
+
}
|
|
109016
|
+
async function reloadCategories() {
|
|
109017
|
+
categories = await opts.client.listCategories(customerId(), { includeInactive: true });
|
|
109018
|
+
}
|
|
109019
|
+
async function loadDevices2() {
|
|
109020
|
+
try {
|
|
109021
|
+
devices = await opts.client.listCustomerDevices(customerId());
|
|
109022
|
+
} catch (err) {
|
|
109023
|
+
devices = [];
|
|
109024
|
+
notice = { kind: "error", text: errText(err, "N\xE3o foi poss\xEDvel carregar os dispositivos") };
|
|
109025
|
+
}
|
|
109026
|
+
render3();
|
|
109027
|
+
}
|
|
109028
|
+
async function refresh() {
|
|
109029
|
+
loadError = null;
|
|
109030
|
+
openKey = null;
|
|
109031
|
+
editingKey = null;
|
|
109032
|
+
pending = /* @__PURE__ */ new Map();
|
|
109033
|
+
devices = null;
|
|
109034
|
+
root.innerHTML = '<div class="myio-pricing__empty">Carregando categorias\u2026</div>';
|
|
109035
|
+
try {
|
|
109036
|
+
await reloadCategories();
|
|
109037
|
+
} catch (err) {
|
|
109038
|
+
categories = [];
|
|
109039
|
+
loadError = errText(err, "N\xE3o foi poss\xEDvel carregar as categorias de tarifa do GCDR");
|
|
109040
|
+
}
|
|
109041
|
+
render3();
|
|
109042
|
+
if (!loadError) void loadDevices2();
|
|
109043
|
+
}
|
|
109044
|
+
return { refresh };
|
|
109045
|
+
}
|
|
109046
|
+
|
|
108513
109047
|
// src/components/pricing-panel/openPricingPanel.ts
|
|
108514
109048
|
var MODAL_ID4 = "myio-pricing-panel";
|
|
108515
109049
|
function escapeHtml14(value) {
|
|
@@ -108593,8 +109127,9 @@ function openPricingPanel(params) {
|
|
|
108593
109127
|
const lockCustomer = params.lockCustomer === true && customers.length > 0;
|
|
108594
109128
|
const tariffApi = params.tariffApi;
|
|
108595
109129
|
let adapter = null;
|
|
109130
|
+
let client = null;
|
|
108596
109131
|
if (allowed && tariffApi) {
|
|
108597
|
-
|
|
109132
|
+
client = new TariffApiClient({
|
|
108598
109133
|
baseUrl: tariffApi.baseUrl,
|
|
108599
109134
|
apiKey: tariffApi.apiKey,
|
|
108600
109135
|
jwt: tariffApi.jwt,
|
|
@@ -108667,7 +109202,8 @@ function openPricingPanel(params) {
|
|
|
108667
109202
|
return handle;
|
|
108668
109203
|
}
|
|
108669
109204
|
const initDomain = params.domain || "energy";
|
|
108670
|
-
|
|
109205
|
+
let categories = null;
|
|
109206
|
+
let categoriesError = null;
|
|
108671
109207
|
const customerOptions = customers.map((c) => `<option value="${escapeHtml14(resolveCustomerId(c))}">${escapeHtml14(c.title)}</option>`).join("");
|
|
108672
109208
|
modal.innerHTML = `
|
|
108673
109209
|
<div class="myio-pricing__overlay"></div>
|
|
@@ -108680,6 +109216,7 @@ function openPricingPanel(params) {
|
|
|
108680
109216
|
<button class="myio-pricing__tab active" data-tab="define" data-testid="tab-define">Definir pre\xE7os</button>
|
|
108681
109217
|
<button class="myio-pricing__tab" data-tab="dashboard" data-testid="tab-dashboard">Dashboard</button>
|
|
108682
109218
|
<button class="myio-pricing__tab" data-tab="history" data-testid="tab-history">Hist\xF3rico</button>
|
|
109219
|
+
${adapter ? '<button class="myio-pricing__tab" data-tab="categories" data-testid="tab-categories">Categorias</button>' : ""}
|
|
108683
109220
|
</div>
|
|
108684
109221
|
<div class="myio-pricing__body">
|
|
108685
109222
|
<!-- TAB: Definir pre\xE7os -->
|
|
@@ -108700,9 +109237,8 @@ function openPricingPanel(params) {
|
|
|
108700
109237
|
</div>
|
|
108701
109238
|
<div class="myio-pricing__field">
|
|
108702
109239
|
<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="
|
|
108705
|
-
<option value="area_comum">\xC1rea Comum</option>
|
|
109240
|
+
<select class="myio-pricing__select" id="myio-pricing-category" data-testid="pricing-category" disabled>
|
|
109241
|
+
<option value="">Carregando categorias\u2026</option>
|
|
108706
109242
|
</select>
|
|
108707
109243
|
</div>
|
|
108708
109244
|
<div class="myio-pricing__field">
|
|
@@ -108756,6 +109292,9 @@ function openPricingPanel(params) {
|
|
|
108756
109292
|
</div>
|
|
108757
109293
|
</div>
|
|
108758
109294
|
|
|
109295
|
+
<!-- TAB: Categorias (s\xF3 com a API de tarifas do GCDR) -->
|
|
109296
|
+
${adapter ? '<div class="myio-pricing__panel" data-panel="categories" data-testid="categories-panel" hidden></div>' : ""}
|
|
109297
|
+
|
|
108759
109298
|
<!-- TAB: Hist\xF3rico -->
|
|
108760
109299
|
<div class="myio-pricing__panel" data-panel="history" hidden>
|
|
108761
109300
|
<ul class="myio-pricing__history" data-testid="history-list"></ul>
|
|
@@ -108790,7 +109329,33 @@ function openPricingPanel(params) {
|
|
|
108790
109329
|
const historyList = $2('[data-testid="history-list"]');
|
|
108791
109330
|
const historyEmpty = $2('[data-testid="history-empty"]');
|
|
108792
109331
|
domainSel.value = initDomain;
|
|
108793
|
-
|
|
109332
|
+
const activeCategories = () => (categories || []).filter((c) => c.isActive !== false);
|
|
109333
|
+
function renderCategoryOptions() {
|
|
109334
|
+
const previous = categorySel.value;
|
|
109335
|
+
if (categories === null) {
|
|
109336
|
+
categorySel.innerHTML = `<option value="">${escapeHtml14(
|
|
109337
|
+
categoriesError ? "Erro ao carregar categorias" : "Carregando categorias\u2026"
|
|
109338
|
+
)}</option>`;
|
|
109339
|
+
categorySel.disabled = true;
|
|
109340
|
+
addBtn.disabled = true;
|
|
109341
|
+
return;
|
|
109342
|
+
}
|
|
109343
|
+
const active = activeCategories();
|
|
109344
|
+
const inactive = categories.filter((c) => c.isActive === false);
|
|
109345
|
+
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("");
|
|
109346
|
+
const keys = active.map((c) => c.key);
|
|
109347
|
+
const wanted = [previous, params.category || ""].find((k) => k && keys.includes(k));
|
|
109348
|
+
categorySel.value = wanted || keys[0] || "";
|
|
109349
|
+
categorySel.disabled = keys.length === 0;
|
|
109350
|
+
addBtn.disabled = keys.length === 0;
|
|
109351
|
+
if (keys.length === 0) showError("Nenhuma categoria de tarifa ativa no GCDR para este customer.");
|
|
109352
|
+
}
|
|
109353
|
+
function setCategories(list, error = null) {
|
|
109354
|
+
categories = list;
|
|
109355
|
+
categoriesError = error;
|
|
109356
|
+
renderCategoryOptions();
|
|
109357
|
+
if (error) showError(error);
|
|
109358
|
+
}
|
|
108794
109359
|
modal.querySelectorAll(".myio-pricing__tab").forEach((tab) => {
|
|
108795
109360
|
tab.addEventListener("click", () => selectTab(tab.dataset.tab));
|
|
108796
109361
|
});
|
|
@@ -108803,6 +109368,22 @@ function openPricingPanel(params) {
|
|
|
108803
109368
|
});
|
|
108804
109369
|
if (name === "dashboard") renderDashboard2();
|
|
108805
109370
|
if (name === "history") renderHistory();
|
|
109371
|
+
if (name === "categories") void categoriesTab?.refresh();
|
|
109372
|
+
}
|
|
109373
|
+
let categoriesTab = null;
|
|
109374
|
+
const categoriesPanel = modal.querySelector('[data-panel="categories"]');
|
|
109375
|
+
if (client && categoriesPanel) {
|
|
109376
|
+
const dialogHost = doc.createElement("div");
|
|
109377
|
+
dialogHost.className = "myio-pricing__dialog-host";
|
|
109378
|
+
modal.appendChild(dialogHost);
|
|
109379
|
+
categoriesTab = mountCategoriesTab({
|
|
109380
|
+
container: categoriesPanel,
|
|
109381
|
+
client,
|
|
109382
|
+
getCustomerId: () => customerSel.value,
|
|
109383
|
+
dialogContainer: dialogHost,
|
|
109384
|
+
// categoria criada/alterada/excluída → recarrega o select e as tarifas
|
|
109385
|
+
onChanged: () => void loadFromApi()
|
|
109386
|
+
});
|
|
108806
109387
|
}
|
|
108807
109388
|
const showError = (msg) => {
|
|
108808
109389
|
errorBox.textContent = msg;
|
|
@@ -108837,6 +109418,7 @@ function openPricingPanel(params) {
|
|
|
108837
109418
|
if (adapter) {
|
|
108838
109419
|
customerSel.addEventListener("change", () => {
|
|
108839
109420
|
void loadFromApi();
|
|
109421
|
+
if (categoriesPanel && !categoriesPanel.hidden) void categoriesTab?.refresh();
|
|
108840
109422
|
});
|
|
108841
109423
|
}
|
|
108842
109424
|
syncPeriodFields();
|
|
@@ -108856,8 +109438,24 @@ function openPricingPanel(params) {
|
|
|
108856
109438
|
if (!adapter) return;
|
|
108857
109439
|
const customerId = customerSel.value;
|
|
108858
109440
|
if (!customerId) return;
|
|
109441
|
+
setCategories(null);
|
|
109442
|
+
try {
|
|
109443
|
+
setCategories(await adapter.listCategories(customerId, { includeInactive: true }));
|
|
109444
|
+
} catch (err) {
|
|
109445
|
+
const code = err?.code;
|
|
109446
|
+
setCategories(
|
|
109447
|
+
null,
|
|
109448
|
+
`N\xE3o foi poss\xEDvel carregar as categorias de tarifa do GCDR${code ? ` (${code})` : ""}.`
|
|
109449
|
+
);
|
|
109450
|
+
return;
|
|
109451
|
+
}
|
|
109452
|
+
clearError();
|
|
109453
|
+
if (!categories || categories.length === 0) return;
|
|
108859
109454
|
try {
|
|
108860
|
-
const loaded = await adapter.loadEntriesForCustomer(
|
|
109455
|
+
const loaded = await adapter.loadEntriesForCustomer(
|
|
109456
|
+
customerId,
|
|
109457
|
+
categories.map((c) => c.key)
|
|
109458
|
+
);
|
|
108861
109459
|
entries = entries.filter((e) => e.customerId !== customerId).concat(loaded);
|
|
108862
109460
|
renderList2();
|
|
108863
109461
|
} catch (err) {
|
|
@@ -108885,7 +109483,7 @@ function openPricingPanel(params) {
|
|
|
108885
109483
|
};
|
|
108886
109484
|
const badge = (domain, category) => `<span class="myio-pricing__badge${domain === "water" ? " myio-pricing__badge--water" : ""}">${escapeHtml14(
|
|
108887
109485
|
DOMAIN_LABEL[domain]
|
|
108888
|
-
)} \xB7 ${escapeHtml14(
|
|
109486
|
+
)} \xB7 ${escapeHtml14(categoryLabel(category, categories))}</span>`;
|
|
108889
109487
|
const renderList2 = () => {
|
|
108890
109488
|
const customerId = customerSel.value;
|
|
108891
109489
|
const rows = entries.filter((e) => e.customerId === customerId).sort((a, b) => {
|
|
@@ -108941,6 +109539,9 @@ function openPricingPanel(params) {
|
|
|
108941
109539
|
if (!customerId) return { error: "Selecione um customer." };
|
|
108942
109540
|
const domain = domainSel.value;
|
|
108943
109541
|
const category = categorySel.value;
|
|
109542
|
+
if (!category || !activeCategories().some((c) => c.key === category)) {
|
|
109543
|
+
return { error: "Selecione uma categoria." };
|
|
109544
|
+
}
|
|
108944
109545
|
const price = parseBRL(priceInput.value);
|
|
108945
109546
|
if (!Number.isFinite(price) || price <= 0) {
|
|
108946
109547
|
return { error: "Informe um pre\xE7o v\xE1lido maior que zero." };
|
|
@@ -108983,7 +109584,10 @@ function openPricingPanel(params) {
|
|
|
108983
109584
|
});
|
|
108984
109585
|
reportDomainSel.addEventListener("change", renderReport);
|
|
108985
109586
|
function renderDashboard2() {
|
|
108986
|
-
const kpis = computePricingKpis(entries, {
|
|
109587
|
+
const kpis = computePricingKpis(entries, {
|
|
109588
|
+
customerCount: customers.length,
|
|
109589
|
+
categoryCount: activeCategories().length
|
|
109590
|
+
});
|
|
108987
109591
|
const cards = [
|
|
108988
109592
|
{ value: String(kpis.totalPeriods), label: "Per\xEDodos definidos" },
|
|
108989
109593
|
{ value: String(kpis.periodsByDomain.energy), label: "Per\xEDodos \xB7 Energia" },
|
|
@@ -109027,7 +109631,7 @@ function openPricingPanel(params) {
|
|
|
109027
109631
|
<tr>
|
|
109028
109632
|
<td>${escapeHtml14(customerTitle(e.customerId))}</td>
|
|
109029
109633
|
<td>${escapeHtml14(DOMAIN_LABEL[e.domain])}</td>
|
|
109030
|
-
<td>${escapeHtml14(
|
|
109634
|
+
<td>${escapeHtml14(categoryLabel(e.category, categories))}</td>
|
|
109031
109635
|
<td>${escapeHtml14(formatPeriodLabel(e))}</td>
|
|
109032
109636
|
<td>${escapeHtml14(formatBRL2(e.pricePerKwh))} ${escapeHtml14(unitLabel(e.domain))}</td>
|
|
109033
109637
|
</tr>`
|
|
@@ -109053,7 +109657,13 @@ function openPricingPanel(params) {
|
|
|
109053
109657
|
historyEmpty.style.display = auditLog.length ? "none" : "";
|
|
109054
109658
|
}
|
|
109055
109659
|
renderList2();
|
|
109056
|
-
if (adapter)
|
|
109660
|
+
if (adapter) {
|
|
109661
|
+
void loadFromApi();
|
|
109662
|
+
} else if (params.categories && params.categories.length) {
|
|
109663
|
+
setCategories(params.categories.map((c) => ({ ...c })));
|
|
109664
|
+
} else {
|
|
109665
|
+
setCategories(null, "Categorias de tarifa n\xE3o informadas (configure a API de tarifas do GCDR).");
|
|
109666
|
+
}
|
|
109057
109667
|
return handle;
|
|
109058
109668
|
}
|
|
109059
109669
|
|
|
@@ -109736,27 +110346,19 @@ function injectDeviceCategoryStyles(doc) {
|
|
|
109736
110346
|
}
|
|
109737
110347
|
|
|
109738
110348
|
// src/components/financial-goals/deviceCategoryPanel.ts
|
|
109739
|
-
var PANEL_TERM_LABEL = {
|
|
109740
|
-
lojas: "Lojas",
|
|
109741
|
-
area_comum: "\xC1rea Comum"
|
|
109742
|
-
};
|
|
109743
110349
|
var NONE_LABEL = "\u2014 Sem categoria \u2014";
|
|
109744
|
-
function deviceCategoryLabel(cat) {
|
|
110350
|
+
function deviceCategoryLabel(cat, categories) {
|
|
109745
110351
|
if (cat == null) return NONE_LABEL;
|
|
109746
|
-
return
|
|
109747
|
-
}
|
|
109748
|
-
function deviceCategoryToPanelTerm(cat) {
|
|
109749
|
-
return cat == null ? null : wireCategoryToPanel(cat);
|
|
110352
|
+
return (categories || []).find((c) => c.key === cat)?.label || String(cat);
|
|
109750
110353
|
}
|
|
109751
|
-
function
|
|
109752
|
-
return term == null ? null : panelCategoryToWire(term);
|
|
109753
|
-
}
|
|
109754
|
-
function esc10(s) {
|
|
110354
|
+
function esc11(s) {
|
|
109755
110355
|
return String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
109756
110356
|
}
|
|
109757
|
-
function categoryOptionsHTML(selected) {
|
|
109758
|
-
const opt = (value, label, isSel) => `<option value="${value}"${isSel ? " selected" : ""}>${
|
|
109759
|
-
|
|
110357
|
+
function categoryOptionsHTML(selected, categories) {
|
|
110358
|
+
const opt = (value, label, isSel) => `<option value="${esc11(value)}"${isSel ? " selected" : ""}>${esc11(label)}</option>`;
|
|
110359
|
+
const list = categories.filter((c) => c.isActive !== false || c.key === selected);
|
|
110360
|
+
const known = list.some((c) => c.key === selected);
|
|
110361
|
+
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
110362
|
}
|
|
109761
110363
|
function openDeviceCategoryPanel(params) {
|
|
109762
110364
|
const doc = params.document || (typeof document !== "undefined" ? document : void 0);
|
|
@@ -109767,6 +110369,8 @@ function openDeviceCategoryPanel(params) {
|
|
|
109767
110369
|
}
|
|
109768
110370
|
injectDeviceCategoryStyles(doc);
|
|
109769
110371
|
const { port, customerId } = params;
|
|
110372
|
+
const categories = (params.categories || []).slice();
|
|
110373
|
+
const activeOptions = categories.filter((c) => c.isActive !== false).map((c) => `<option value="${esc11(c.key)}">${esc11(c.label || c.key)}</option>`).join("");
|
|
109770
110374
|
let rows = [];
|
|
109771
110375
|
let search = "";
|
|
109772
110376
|
let filter = params.initialFilter || "all";
|
|
@@ -109792,8 +110396,7 @@ function openDeviceCategoryPanel(params) {
|
|
|
109792
110396
|
<select class="myio-devcat__filter" data-devcat-filter="1" aria-label="Filtrar por categoria">
|
|
109793
110397
|
<option value="all">Todas as categorias</option>
|
|
109794
110398
|
<option value="uncategorized">Sem categoria</option>
|
|
109795
|
-
|
|
109796
|
-
<option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
|
|
110399
|
+
${activeOptions}
|
|
109797
110400
|
</select>
|
|
109798
110401
|
<label class="myio-devcat__filter" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
|
|
109799
110402
|
<input type="checkbox" data-devcat-selectall="1" /> Selecionar vis\xEDveis
|
|
@@ -109802,9 +110405,8 @@ function openDeviceCategoryPanel(params) {
|
|
|
109802
110405
|
<div class="myio-devcat__bulkbar" data-devcat-bulkbar="1">
|
|
109803
110406
|
<span data-devcat-bulkcount="1">0 selecionados</span>
|
|
109804
110407
|
<select data-devcat-bulkcat="1" aria-label="Categoria para os selecionados">
|
|
109805
|
-
<option value="">${
|
|
109806
|
-
|
|
109807
|
-
<option value="SPECIFIC">${esc10(deviceCategoryLabel("SPECIFIC"))}</option>
|
|
110408
|
+
<option value="">${esc11(NONE_LABEL)}</option>
|
|
110409
|
+
${activeOptions}
|
|
109808
110410
|
</select>
|
|
109809
110411
|
<button type="button" class="myio-devcat__bulk-apply" data-devcat-bulkapply="1">Aplicar a selecionados</button>
|
|
109810
110412
|
</div>
|
|
@@ -109834,16 +110436,16 @@ function openDeviceCategoryPanel(params) {
|
|
|
109834
110436
|
return rows.filter((r) => matchesFilter(r) && matchesSearch(r));
|
|
109835
110437
|
}
|
|
109836
110438
|
function rowHTML(r) {
|
|
109837
|
-
const name =
|
|
109838
|
-
const code = r.code ? `<span class="myio-devcat__row-code">${
|
|
110439
|
+
const name = esc11(r.label || r.code || r.deviceId);
|
|
110440
|
+
const code = r.code ? `<span class="myio-devcat__row-code">${esc11(r.code)}</span>` : "";
|
|
109839
110441
|
const checked = selected.has(r.deviceId) ? " checked" : "";
|
|
109840
110442
|
const focused = r.deviceId === params.focusDeviceId ? ' data-focused="1"' : "";
|
|
109841
110443
|
const catAttr = r.tariffCategory == null ? "null" : r.tariffCategory;
|
|
109842
|
-
return `<div class="myio-devcat__row" data-devcat-row="${
|
|
110444
|
+
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
110445
|
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="${
|
|
110446
|
+
)}"${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
110447
|
r.deviceId
|
|
109846
|
-
)}" aria-label="Categoria de ${name}">${categoryOptionsHTML(r.tariffCategory)}</select><div class="myio-devcat__row-conflict" data-devcat-conflict="${
|
|
110448
|
+
)}" 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
110449
|
}
|
|
109848
110450
|
function render3() {
|
|
109849
110451
|
const vis = visibleRows();
|
|
@@ -110003,7 +110605,7 @@ function openDeviceCategoryPanel(params) {
|
|
|
110003
110605
|
rows = await port.listDevices({ customerId, domain: params.domain });
|
|
110004
110606
|
} catch (err) {
|
|
110005
110607
|
rows = [];
|
|
110006
|
-
body.innerHTML = `<div class="myio-devcat__empty">N\xE3o foi poss\xEDvel carregar os dispositivos: ${
|
|
110608
|
+
body.innerHTML = `<div class="myio-devcat__empty">N\xE3o foi poss\xEDvel carregar os dispositivos: ${esc11(
|
|
110007
110609
|
err?.message || "erro"
|
|
110008
110610
|
)}</div>`;
|
|
110009
110611
|
countEl.textContent = "";
|
|
@@ -110035,6 +110637,7 @@ function createCoverageDeepLink(config2) {
|
|
|
110035
110637
|
const open = (focusDeviceId, initialFilter) => openDeviceCategoryPanel({
|
|
110036
110638
|
port: config2.port,
|
|
110037
110639
|
customerId: config2.customerId,
|
|
110640
|
+
categories: config2.categories,
|
|
110038
110641
|
domain: config2.domain,
|
|
110039
110642
|
focusDeviceId,
|
|
110040
110643
|
initialFilter,
|
|
@@ -116263,16 +116866,16 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
|
|
|
116263
116866
|
let errors = 0;
|
|
116264
116867
|
for (let i = 0; i < deviceAttrsList.length; i++) {
|
|
116265
116868
|
const { deviceId, centralId, slaveId } = deviceAttrsList[i];
|
|
116266
|
-
const
|
|
116267
|
-
updateBusyProgress(i + 1, `[${i + 1}/${devices.length}] Sync: ${
|
|
116869
|
+
const devName2 = devices[i]?.name || deviceId;
|
|
116870
|
+
updateBusyProgress(i + 1, `[${i + 1}/${devices.length}] Sync: ${devName2}`);
|
|
116268
116871
|
if (!centralId || !slaveId) {
|
|
116269
|
-
console.log(`[BulkSyncIngestion] Skipped ${
|
|
116872
|
+
console.log(`[BulkSyncIngestion] Skipped ${devName2} \u2014 missing centralId or slaveId`);
|
|
116270
116873
|
skipped++;
|
|
116271
116874
|
continue;
|
|
116272
116875
|
}
|
|
116273
116876
|
const match = findIngestionDeviceByCentralSlaveId(ingestionDevices, centralId, slaveId);
|
|
116274
116877
|
if (!match) {
|
|
116275
|
-
console.log(`[BulkSyncIngestion] No match for ${
|
|
116878
|
+
console.log(`[BulkSyncIngestion] No match for ${devName2} (centralId=${centralId}, slaveId=${slaveId})`);
|
|
116276
116879
|
skipped++;
|
|
116277
116880
|
continue;
|
|
116278
116881
|
}
|
|
@@ -116280,10 +116883,10 @@ Nenhuma rela\xE7\xE3o, profile ou type ser\xE1 alterado.`)) return;
|
|
|
116280
116883
|
await tbPost(state6, `/api/plugins/telemetry/DEVICE/${deviceId}/attributes/SERVER_SCOPE`, {
|
|
116281
116884
|
ingestionId: match.id
|
|
116282
116885
|
});
|
|
116283
|
-
console.log(`[BulkSyncIngestion] \u2705 ${
|
|
116886
|
+
console.log(`[BulkSyncIngestion] \u2705 ${devName2} \u2192 ingestionId=${match.id}`);
|
|
116284
116887
|
matched++;
|
|
116285
116888
|
} catch (err) {
|
|
116286
|
-
console.error(`[BulkSyncIngestion] \u274C ${
|
|
116889
|
+
console.error(`[BulkSyncIngestion] \u274C ${devName2}:`, err);
|
|
116287
116890
|
errors++;
|
|
116288
116891
|
}
|
|
116289
116892
|
}
|
|
@@ -117575,14 +118178,14 @@ function buildTemplateCsv(domain, devices, start, end, now = Date.now()) {
|
|
|
117575
118178
|
if (domain === "energy") header.push("value_reactive_kvarh");
|
|
117576
118179
|
const today = nowSaoPaulo(now);
|
|
117577
118180
|
const lines = [header.join(";")];
|
|
117578
|
-
const
|
|
118181
|
+
const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
|
|
117579
118182
|
const { ok } = splitImportableDevices(devices);
|
|
117580
118183
|
for (const dev of ok) {
|
|
117581
118184
|
for (const date of daysBetween(start, end)) {
|
|
117582
118185
|
if (date > today.date) break;
|
|
117583
118186
|
for (let h3 = 0; h3 < 24; h3++) {
|
|
117584
118187
|
if (date === today.date && h3 >= today.hour) break;
|
|
117585
|
-
const cols = [String(dev.centralId), String(Number(dev.slaveId)),
|
|
118188
|
+
const cols = [String(dev.centralId), String(Number(dev.slaveId)), esc13(dev.label || ""), date, `${pad25(h3)}:00`, ""];
|
|
117586
118189
|
if (domain === "energy") cols.push("");
|
|
117587
118190
|
lines.push(cols.join(";"));
|
|
117588
118191
|
}
|
|
@@ -117652,8 +118255,8 @@ function parseDecimal(v) {
|
|
|
117652
118255
|
if (typeof v === "number") return Number.isFinite(v) ? v : NaN;
|
|
117653
118256
|
const s = String(v ?? "").trim();
|
|
117654
118257
|
if (!s) return null;
|
|
117655
|
-
const
|
|
117656
|
-
return /^-?\d+(\.\d+)?$/.test(
|
|
118258
|
+
const norm3 = s.includes(",") ? s.replace(/\./g, "").replace(",", ".") : s;
|
|
118259
|
+
return /^-?\d+(\.\d+)?$/.test(norm3) ? Number(norm3) : NaN;
|
|
117657
118260
|
}
|
|
117658
118261
|
function rowsFromTable(domain, table) {
|
|
117659
118262
|
const errors = [];
|
|
@@ -117843,10 +118446,10 @@ function accumulatedRows(domain, entries, profile = DEFAULT_DISTRIBUTION_PROFILE
|
|
|
117843
118446
|
}
|
|
117844
118447
|
function buildAccumulatedTemplateCsv(domain, devices, start, end) {
|
|
117845
118448
|
const lines = [["gateway_id", "slave_id", "device_name", "start_date", "end_date", TOTAL_COLUMN[domain]].join(";")];
|
|
117846
|
-
const
|
|
118449
|
+
const esc13 = (v) => /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
|
|
117847
118450
|
for (const dev of devices || []) {
|
|
117848
118451
|
if (!isImportableKey(dev)) continue;
|
|
117849
|
-
lines.push([String(dev.centralId), String(Number(dev.slaveId)),
|
|
118452
|
+
lines.push([String(dev.centralId), String(Number(dev.slaveId)), esc13(dev.label || ""), start, end, ""].join(";"));
|
|
117850
118453
|
}
|
|
117851
118454
|
return { csv: "\uFEFF" + lines.join("\r\n") + "\r\n", rows: lines.length - 1 };
|
|
117852
118455
|
}
|
|
@@ -118010,11 +118613,15 @@ function createTelemetryImportApi(cfg) {
|
|
|
118010
118613
|
|
|
118011
118614
|
// src/components/premium-modals/telemetry-import/openTelemetryImportModal.ts
|
|
118012
118615
|
var STEPS2 = [
|
|
118616
|
+
{ n: 0, label: "Dispositivos" },
|
|
118013
118617
|
{ n: 1, label: "Modelo" },
|
|
118014
118618
|
{ n: 2, label: "Planilha" },
|
|
118015
118619
|
{ n: 3, label: "Valida\xE7\xE3o" },
|
|
118016
118620
|
{ n: 4, label: "Importa\xE7\xE3o" }
|
|
118017
118621
|
];
|
|
118622
|
+
var devKey = (d) => `${d.centralId}|${d.slaveId}`;
|
|
118623
|
+
var devName = (d) => String(d.label || d.identifier || "").toUpperCase();
|
|
118624
|
+
var norm2 = (v) => String(v ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
|
118018
118625
|
var DOMAIN_TEXT = {
|
|
118019
118626
|
energy: { noun: "energia", unit: "kWh", icon: "\u26A1" },
|
|
118020
118627
|
water: { noun: "\xE1gua", unit: "m\xB3", icon: "\u{1F4A7}" }
|
|
@@ -118036,7 +118643,7 @@ function fmtSaoPaulo(iso) {
|
|
|
118036
118643
|
return `${p(d.getUTCDate())}/${p(d.getUTCMonth() + 1)}/${d.getUTCFullYear()} ${p(d.getUTCHours())}:00`;
|
|
118037
118644
|
}
|
|
118038
118645
|
var STYLE_ID15 = "myio-tlmimport-styles";
|
|
118039
|
-
function
|
|
118646
|
+
function esc12(v) {
|
|
118040
118647
|
return String(v ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
118041
118648
|
}
|
|
118042
118649
|
var fmtNum = (n, d = 0) => Number.isFinite(Number(n)) ? Number(n).toLocaleString("pt-BR", { minimumFractionDigits: d, maximumFractionDigits: d }) : "\u2014";
|
|
@@ -118046,7 +118653,19 @@ function injectStyles15() {
|
|
|
118046
118653
|
style.id = STYLE_ID15;
|
|
118047
118654
|
style.textContent = `
|
|
118048
118655
|
.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;
|
|
118656
|
+
display: flex; flex-direction: column; gap: 12px; font-size: 14px; color: #1e293b;
|
|
118657
|
+
font-family: 'Nunito', system-ui, -apple-system, 'Segoe UI', sans-serif; }
|
|
118658
|
+
.tlmi input, .tlmi button, .tlmi table { font-family: inherit; }
|
|
118659
|
+
.tlmi-dev { font-size: 12.5px; font-weight: 700; color: #334155; letter-spacing: 0.2px; text-transform: uppercase; }
|
|
118660
|
+
.tlmi-dev small { display: block; font-weight: 500; color: #94a3b8; font-size: 11px; letter-spacing: 0; }
|
|
118661
|
+
.tlmi-sel-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; }
|
|
118662
|
+
.tlmi-sel-bar input[type="search"] { flex: 1; min-width: 200px; border: 1px solid #ddd; border-radius: 6px; padding: 8px 10px; font: inherit; }
|
|
118663
|
+
.tlmi-sel-count { font-size: 12.5px; color: #64748b; margin-left: auto; }
|
|
118664
|
+
.tlmi-sel { max-height: 320px; overflow: auto; border: 1px solid #e2e8f0; border-radius: 8px; }
|
|
118665
|
+
.tlmi-sel label { display: flex; align-items: center; gap: 10px; padding: 7px 10px; border-bottom: 1px solid #f1f5f9; cursor: pointer; }
|
|
118666
|
+
.tlmi-sel label:hover { background: #f8fafc; }
|
|
118667
|
+
.tlmi-sel label:last-child { border-bottom: none; }
|
|
118668
|
+
.tlmi-sel input { width: 16px; height: 16px; accent-color: var(--tlmi-ac); flex-shrink: 0; }
|
|
118050
118669
|
.tlmi-stepper { display: flex; gap: 6px; }
|
|
118051
118670
|
.tlmi-step { flex: 1; display: flex; align-items: center; gap: 8px; color: #64748b; padding: 6px 8px; border-radius: 10px; font-size: 13px; }
|
|
118052
118671
|
.tlmi-step b { width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center;
|
|
@@ -118065,7 +118684,7 @@ function injectStyles15() {
|
|
|
118065
118684
|
background: #fff; color: #374151; cursor: pointer; }
|
|
118066
118685
|
.tlmi-btn.primary { background: var(--tlmi-ac); border-color: var(--tlmi-ac); color: #fff; }
|
|
118067
118686
|
.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; }
|
|
118687
|
+
.tlmi-drop { display: block; border: 2px dashed #cbd5e1; border-radius: 12px; padding: 22px; text-align: center; color: #64748b; cursor: pointer; }
|
|
118069
118688
|
.tlmi-drop[data-over="1"] { border-color: var(--tlmi-ac); background: var(--tlmi-ac-soft); }
|
|
118070
118689
|
.tlmi-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; }
|
|
118071
118690
|
.tlmi-kpi { border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 12px; }
|
|
@@ -118099,7 +118718,7 @@ function injectStyles15() {
|
|
|
118099
118718
|
document.head.appendChild(style);
|
|
118100
118719
|
}
|
|
118101
118720
|
function issuesTable(errors, limit = 100) {
|
|
118102
|
-
const rows = errors.slice(0, limit).map((e) => `<tr><td>${
|
|
118721
|
+
const rows = errors.slice(0, limit).map((e) => `<tr><td>${esc12(e.line)}</td><td>${esc12(e.reason)}</td></tr>`).join("");
|
|
118103
118722
|
const more = errors.length > limit ? `<p class="tlmi-muted">\u2026 e mais ${errors.length - limit} erro(s).</p>` : "";
|
|
118104
118723
|
return `<div class="tlmi-errors"><table><thead><tr><th>Linha</th><th>Problema</th></tr></thead><tbody>${rows}</tbody></table></div>${more}`;
|
|
118105
118724
|
}
|
|
@@ -118116,11 +118735,14 @@ function openTelemetryImportModal(params) {
|
|
|
118116
118735
|
const txt = DOMAIN_TEXT[domain];
|
|
118117
118736
|
const now = params.now ?? (() => Date.now());
|
|
118118
118737
|
const api = "validate" in params.api ? params.api : createTelemetryImportApi(params.api);
|
|
118119
|
-
const { ok:
|
|
118738
|
+
const { ok: importableAll, missingKey } = splitImportableDevices(params.devices);
|
|
118739
|
+
const selected = /* @__PURE__ */ new Set();
|
|
118740
|
+
let importable = [];
|
|
118741
|
+
let selFilter = "";
|
|
118120
118742
|
const s = {
|
|
118121
|
-
step:
|
|
118743
|
+
step: 0,
|
|
118122
118744
|
model: "hourly",
|
|
118123
|
-
/** Acumulado: total digitado por device (
|
|
118745
|
+
/** Acumulado: total digitado por device (chave devKey) */
|
|
118124
118746
|
formTotals: {},
|
|
118125
118747
|
/** Acumulado: entradas vindas de planilha (null = preenchimento na tela) */
|
|
118126
118748
|
fileEntries: null,
|
|
@@ -118172,17 +118794,54 @@ function openTelemetryImportModal(params) {
|
|
|
118172
118794
|
return `<div class="tlmi-stepper">${STEPS2.map((st) => {
|
|
118173
118795
|
const state6 = st.n === s.step ? "current" : st.n < s.step ? "done" : "todo";
|
|
118174
118796
|
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>`;
|
|
118797
|
+
return `<div class="tlmi-step" data-state="${state6}"><b>${state6 === "done" ? "\u2713" : st.n + 1}</b>${label}</div>`;
|
|
118176
118798
|
}).join("")}</div>`;
|
|
118177
118799
|
}
|
|
118800
|
+
const visibleDevices2 = () => {
|
|
118801
|
+
const f = norm2(selFilter.trim());
|
|
118802
|
+
return importableAll.filter((d) => !f || norm2(`${d.label} ${d.identifier || ""}`).includes(f));
|
|
118803
|
+
};
|
|
118804
|
+
function selListHtml() {
|
|
118805
|
+
const list = visibleDevices2();
|
|
118806
|
+
if (!list.length) return '<p class="tlmi-muted" style="padding:10px">Nenhum dispositivo encontrado.</p>';
|
|
118807
|
+
return list.map((d) => {
|
|
118808
|
+
const k = devKey(d);
|
|
118809
|
+
const ident = d.identifier && d.identifier.toUpperCase() !== devName(d) ? `<small>${esc12(d.identifier.toUpperCase())}</small>` : "";
|
|
118810
|
+
return `<label><input type="checkbox" data-sel="${esc12(k)}" ${selected.has(k) ? "checked" : ""} />
|
|
118811
|
+
<span class="tlmi-dev">${esc12(devName(d))}${ident}</span></label>`;
|
|
118812
|
+
}).join("");
|
|
118813
|
+
}
|
|
118814
|
+
const selCountText = () => `${fmtNum(selected.size)} de ${fmtNum(importableAll.length)} selecionado(s)`;
|
|
118815
|
+
function step0() {
|
|
118816
|
+
const warn = missingKey.length ? `<div class="tlmi-banner warn">${missingKey.length} dispositivo(s) sem central/endere\xE7o cadastrados n\xE3o podem ser importados: ${esc12(
|
|
118817
|
+
missingKey.slice(0, 5).map(devName).join(", ")
|
|
118818
|
+
)}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
|
|
118819
|
+
return `
|
|
118820
|
+
<div class="tlmi-card"><h3>Quais dispositivos voc\xEA quer preencher?</h3>
|
|
118821
|
+
<div class="tlmi-sel-bar">
|
|
118822
|
+
<input type="search" data-field="sel-filter" placeholder="Buscar dispositivo\u2026" value="${esc12(selFilter)}" aria-label="Buscar dispositivo" />
|
|
118823
|
+
<button class="tlmi-btn" type="button" data-action="sel-all">Marcar todos</button>
|
|
118824
|
+
<button class="tlmi-btn" type="button" data-action="sel-none">Desmarcar todos</button>
|
|
118825
|
+
<span class="tlmi-sel-count" data-role="sel-count">${selCountText()}</span>
|
|
118826
|
+
</div>
|
|
118827
|
+
<div class="tlmi-sel" data-role="sel-list">${selListHtml()}</div>
|
|
118828
|
+
<p class="tlmi-muted" style="margin-top:6px">Com a busca preenchida, Marcar/Desmarcar todos vale s\xF3 para os dispositivos encontrados.</p>
|
|
118829
|
+
</div>
|
|
118830
|
+
${warn}`;
|
|
118831
|
+
}
|
|
118832
|
+
function refreshSelection() {
|
|
118833
|
+
const list = root.querySelector('[data-role="sel-list"]');
|
|
118834
|
+
if (list) list.innerHTML = selListHtml();
|
|
118835
|
+
const count = root.querySelector('[data-role="sel-count"]');
|
|
118836
|
+
if (count) count.textContent = selCountText();
|
|
118837
|
+
syncFooter();
|
|
118838
|
+
}
|
|
118178
118839
|
function apiErrorBanner() {
|
|
118179
118840
|
if (!s.apiError) return "";
|
|
118180
|
-
return `<div class="tlmi-banner err" role="alert">${
|
|
118841
|
+
return `<div class="tlmi-banner err" role="alert">${esc12(s.apiError)}${s.apiDetail ? `<div class="tlmi-tech">${esc12(s.apiDetail)}</div>` : ""}</div>`;
|
|
118181
118842
|
}
|
|
118182
118843
|
function step1() {
|
|
118183
|
-
const warn =
|
|
118184
|
-
missingKey.slice(0, 5).map((d) => d.label).join(", ")
|
|
118185
|
-
)}${missingKey.length > 5 ? "\u2026" : ""}</div>` : "";
|
|
118844
|
+
const warn = "";
|
|
118186
118845
|
const model = (value, title, hint) => `
|
|
118187
118846
|
<label class="tlmi-model" data-selected="${s.model === value ? 1 : 0}">
|
|
118188
118847
|
<input type="radio" name="tlmi-model" data-field="model" value="${value}" ${s.model === value ? "checked" : ""} />
|
|
@@ -118207,16 +118866,16 @@ function openTelemetryImportModal(params) {
|
|
|
118207
118866
|
${warn}
|
|
118208
118867
|
<div class="tlmi-card"><h3>${s.model === "accumulated" ? "Per\xEDodo" : "Modelo da planilha"}</h3>
|
|
118209
118868
|
<div class="tlmi-row">
|
|
118210
|
-
<label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${
|
|
118211
|
-
<label class="tlmi-field">Fim<input type="date" data-field="end" value="${
|
|
118869
|
+
<label class="tlmi-field">In\xEDcio<input type="date" data-field="start" value="${esc12(s.period.start)}" /></label>
|
|
118870
|
+
<label class="tlmi-field">Fim<input type="date" data-field="end" value="${esc12(s.period.end)}" /></label>
|
|
118212
118871
|
<button class="tlmi-btn" type="button" data-action="template" ${importable.length ? "" : "disabled"}>\u2B07 Baixar modelo (CSV)</button>
|
|
118213
118872
|
</div>
|
|
118214
|
-
<p class="tlmi-muted" style="margin-top:8px">${importable.length} dispositivo(s)
|
|
118873
|
+
<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
118874
|
</div>`;
|
|
118216
118875
|
}
|
|
118217
118876
|
function step2() {
|
|
118218
|
-
const summary = s.fileName ? s.parseError ? `<div class="tlmi-banner err">${
|
|
118219
|
-
<div class="tlmi-kpi"><span>Arquivo</span><strong style="font-size:13px">${
|
|
118877
|
+
const summary = s.fileName ? s.parseError ? `<div class="tlmi-banner err">${esc12(s.parseError)}</div>` : `<div class="tlmi-kpis">
|
|
118878
|
+
<div class="tlmi-kpi"><span>Arquivo</span><strong style="font-size:13px">${esc12(s.fileName)}</strong></div>
|
|
118220
118879
|
<div class="tlmi-kpi"><span>Linhas para importar</span><strong>${fmtNum(s.rows.length)}</strong></div>
|
|
118221
118880
|
<div class="tlmi-kpi"><span>Em branco (ignoradas)</span><strong>${fmtNum(s.skippedEmpty)}</strong></div>
|
|
118222
118881
|
<div class="tlmi-kpi"><span>Com erro</span><strong style="color:${s.localErrors.length ? "#dc2626" : "#16a34a"}">${fmtNum(s.localErrors.length)}</strong></div>
|
|
@@ -118256,12 +118915,14 @@ function openTelemetryImportModal(params) {
|
|
|
118256
118915
|
}
|
|
118257
118916
|
function step2Accumulated() {
|
|
118258
118917
|
const fromFile = !!s.fileName && !s.parseError;
|
|
118259
|
-
const form = fromFile ? `<p class="tlmi-muted">Usando <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: ${
|
|
118918
|
+
const form = fromFile ? `<p class="tlmi-muted">Usando <strong>${esc12(s.fileName)}</strong>.
|
|
118919
|
+
<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
118920
|
<div class="tlmi-acc"><table><thead><tr><th>Dispositivo</th><th>Total (${txt.unit})</th></tr></thead><tbody>
|
|
118262
118921
|
${importable.map(
|
|
118263
|
-
(d
|
|
118264
|
-
<td><input inputmode="decimal" data-total="${
|
|
118922
|
+
(d) => `<tr><td class="tlmi-dev">${esc12(devName(d))}</td>
|
|
118923
|
+
<td><input inputmode="decimal" data-total="${esc12(devKey(d))}" aria-label="Total de ${esc12(devName(d))}" value="${esc12(
|
|
118924
|
+
s.formTotals[devKey(d)] ?? ""
|
|
118925
|
+
)}" /></td></tr>`
|
|
118265
118926
|
).join("")}
|
|
118266
118927
|
</tbody></table></div>`;
|
|
118267
118928
|
return `
|
|
@@ -118274,7 +118935,7 @@ function openTelemetryImportModal(params) {
|
|
|
118274
118935
|
<input type="file" accept=".xlsx,.xls,.csv" data-field="file" hidden />
|
|
118275
118936
|
\u{1F4C4} Clique ou arraste a planilha aqui (.xlsx ou .csv)
|
|
118276
118937
|
</label>
|
|
118277
|
-
${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${
|
|
118938
|
+
${s.parseError ? `<div class="tlmi-banner err" style="margin-top:10px">${esc12(s.parseError)}</div>` : ""}
|
|
118278
118939
|
</div>
|
|
118279
118940
|
<div data-role="acc-summary" style="display:flex;flex-direction:column;gap:12px">${accSummaryHtml()}</div>`;
|
|
118280
118941
|
}
|
|
@@ -118300,7 +118961,7 @@ function openTelemetryImportModal(params) {
|
|
|
118300
118961
|
<div class="tlmi-kpi"><span>Total (${txt.unit})</span><strong>${fmtNum(p.totalValue, 2)}</strong></div>
|
|
118301
118962
|
<div class="tlmi-kpi"><span>Leituras substitu\xEDdas</span><strong>${fmtNum(p.existingReadingsInTarget)}</strong></div>
|
|
118302
118963
|
</div>
|
|
118303
|
-
<p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${
|
|
118964
|
+
<p class="tlmi-muted">Per\xEDodo (hor\xE1rio de Bras\xEDlia): ${esc12(period)}</p>
|
|
118304
118965
|
${reactiveWarn}
|
|
118305
118966
|
${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
118967
|
<label class="tlmi-check" style="margin-top:6px"><input type="checkbox" data-field="confirmReal" ${s.confirmReal ? "checked" : ""} />
|
|
@@ -118319,7 +118980,7 @@ function openTelemetryImportModal(params) {
|
|
|
118319
118980
|
<div class="tlmi-muted" style="margin-top:4px">Dispositivos manuais continuam aparecendo sem comunica\xE7\xE3o no status:
|
|
118320
118981
|
o status conta s\xF3 leitura medida. Os totais e os cards usam os dados importados.</div></div>`;
|
|
118321
118982
|
} else if (j.status === "failed") {
|
|
118322
|
-
banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${
|
|
118983
|
+
banner = `<div class="tlmi-banner err">A importa\xE7\xE3o falhou${j.error ? `: ${esc12(j.error)}` : "."}</div>`;
|
|
118323
118984
|
} else if (j.status === "cancelled") {
|
|
118324
118985
|
banner = '<div class="tlmi-banner warn">Importa\xE7\xE3o cancelada. As leituras anteriores foram mantidas.</div>';
|
|
118325
118986
|
} else if (j.status === "reverted") {
|
|
@@ -118331,14 +118992,14 @@ function openTelemetryImportModal(params) {
|
|
|
118331
118992
|
<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
118993
|
</div>` : "";
|
|
118333
118994
|
return `
|
|
118334
|
-
<div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${
|
|
118995
|
+
<div class="tlmi-card"><h3>Importa\xE7\xE3o <span style="font-weight:600;color:#64748b">${esc12(statusText)}</span></h3>
|
|
118335
118996
|
<div class="tlmi-progress" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>
|
|
118336
118997
|
<div class="tlmi-kpis" style="margin-top:12px">
|
|
118337
118998
|
<div class="tlmi-kpi"><span>Progresso</span><strong>${fmtNum(pct)}%</strong></div>
|
|
118338
118999
|
<div class="tlmi-kpi"><span>Leituras removidas</span><strong>${fmtNum(j.deleted)}</strong></div>
|
|
118339
119000
|
<div class="tlmi-kpi"><span>Leituras gravadas</span><strong>${fmtNum(j.inserted)}</strong></div>
|
|
118340
119001
|
</div>
|
|
118341
|
-
${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${
|
|
119002
|
+
${j.phase && !terminal ? `<p class="tlmi-muted" style="margin-top:8px">Etapa: ${esc12(j.phase)}</p>` : ""}
|
|
118342
119003
|
${!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
119004
|
<span class="tlmi-muted" style="margin-left:8px">Voc\xEA pode fechar esta janela; a importa\xE7\xE3o continua.</span></div>` : ""}
|
|
118344
119005
|
${revert}
|
|
@@ -118349,14 +119010,15 @@ function openTelemetryImportModal(params) {
|
|
|
118349
119010
|
function render3() {
|
|
118350
119011
|
if (closed) return;
|
|
118351
119012
|
const step2Body = () => s.model === "accumulated" ? step2Accumulated() : step2();
|
|
118352
|
-
const body = s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
|
|
119013
|
+
const body = s.step === 0 ? step0() : s.step === 1 ? step1() : s.step === 2 ? step2Body() : s.step === 3 ? step3() : step4();
|
|
118353
119014
|
root.innerHTML = stepper() + body;
|
|
118354
119015
|
syncFooter();
|
|
118355
119016
|
}
|
|
118356
119017
|
function syncFooter() {
|
|
118357
119018
|
const v = s.validation;
|
|
118358
119019
|
const terminal = s.job ? TERMINAL_JOB_STATUSES.includes(s.job.status) : false;
|
|
118359
|
-
modal.setButton("back", { hidden: s.step ===
|
|
119020
|
+
modal.setButton("back", { hidden: s.step === 0 || s.step === 4, disabled: s.busy });
|
|
119021
|
+
if (s.step === 0) modal.setButton("next", { label: "Avan\xE7ar", disabled: selected.size === 0, hidden: false });
|
|
118360
119022
|
if (s.step === 1) modal.setButton("next", { label: "Avan\xE7ar", disabled: false, hidden: false });
|
|
118361
119023
|
if (s.step === 2)
|
|
118362
119024
|
modal.setButton("next", {
|
|
@@ -118375,7 +119037,7 @@ function openTelemetryImportModal(params) {
|
|
|
118375
119037
|
if (s.step === 4) modal.setButton("next", { label: "Concluir", hidden: !terminal, disabled: false });
|
|
118376
119038
|
}
|
|
118377
119039
|
function goBack() {
|
|
118378
|
-
if (s.busy || s.step ===
|
|
119040
|
+
if (s.busy || s.step === 0 || s.step === 4) return;
|
|
118379
119041
|
s.apiError = "";
|
|
118380
119042
|
if (s.step === 3) s.validation = null;
|
|
118381
119043
|
s.step = s.step - 1;
|
|
@@ -118383,7 +119045,16 @@ function openTelemetryImportModal(params) {
|
|
|
118383
119045
|
}
|
|
118384
119046
|
async function goNext() {
|
|
118385
119047
|
if (s.busy) return;
|
|
118386
|
-
if (s.step ===
|
|
119048
|
+
if (s.step === 0) {
|
|
119049
|
+
if (selected.size === 0) return;
|
|
119050
|
+
importable = importableAll.filter((d) => selected.has(devKey(d)));
|
|
119051
|
+
for (const k of Object.keys(s.formTotals)) if (!selected.has(k)) delete s.formTotals[k];
|
|
119052
|
+
s.rows = [];
|
|
119053
|
+
s.localErrors = [];
|
|
119054
|
+
s.validation = null;
|
|
119055
|
+
s.step = 1;
|
|
119056
|
+
render3();
|
|
119057
|
+
} else if (s.step === 1) {
|
|
118387
119058
|
if (s.model === "accumulated") recomputeAccumulated();
|
|
118388
119059
|
s.step = 2;
|
|
118389
119060
|
render3();
|
|
@@ -118414,10 +119085,10 @@ function openTelemetryImportModal(params) {
|
|
|
118414
119085
|
const entries = [];
|
|
118415
119086
|
const errors = [];
|
|
118416
119087
|
importable.forEach((d, i) => {
|
|
118417
|
-
const total = parseDecimal(s.formTotals[
|
|
119088
|
+
const total = parseDecimal(s.formTotals[devKey(d)] ?? "");
|
|
118418
119089
|
if (total === null) return;
|
|
118419
119090
|
if (Number.isNaN(total) || total < 0) {
|
|
118420
|
-
errors.push({ line: i + 1, reason: `${d
|
|
119091
|
+
errors.push({ line: i + 1, reason: `${devName(d)}: total deve ser n\xFAmero \u2265 0` });
|
|
118421
119092
|
return;
|
|
118422
119093
|
}
|
|
118423
119094
|
entries.push({
|
|
@@ -118568,6 +119239,14 @@ function openTelemetryImportModal(params) {
|
|
|
118568
119239
|
const el2 = e.target.closest("[data-action]");
|
|
118569
119240
|
if (!el2) return;
|
|
118570
119241
|
if (el2.dataset.action === "template") downloadTemplate();
|
|
119242
|
+
if (el2.dataset.action === "sel-all" || el2.dataset.action === "sel-none") {
|
|
119243
|
+
const on = el2.dataset.action === "sel-all";
|
|
119244
|
+
for (const d of visibleDevices2()) {
|
|
119245
|
+
if (on) selected.add(devKey(d));
|
|
119246
|
+
else selected.delete(devKey(d));
|
|
119247
|
+
}
|
|
119248
|
+
refreshSelection();
|
|
119249
|
+
}
|
|
118571
119250
|
if (el2.dataset.action === "cancel") void cancelJob();
|
|
118572
119251
|
if (el2.dataset.action === "revert") void revertJob();
|
|
118573
119252
|
if (el2.dataset.action === "use-form") {
|
|
@@ -118578,13 +119257,26 @@ function openTelemetryImportModal(params) {
|
|
|
118578
119257
|
});
|
|
118579
119258
|
root.addEventListener("input", (e) => {
|
|
118580
119259
|
const t = e.target;
|
|
119260
|
+
if (t.dataset.field === "sel-filter") {
|
|
119261
|
+
selFilter = t.value;
|
|
119262
|
+
refreshSelection();
|
|
119263
|
+
return;
|
|
119264
|
+
}
|
|
118581
119265
|
if (t.dataset.total === void 0) return;
|
|
118582
|
-
s.formTotals[
|
|
119266
|
+
s.formTotals[t.dataset.total] = t.value;
|
|
118583
119267
|
recomputeAccumulated();
|
|
118584
119268
|
refreshAccSummary();
|
|
118585
119269
|
});
|
|
118586
119270
|
root.addEventListener("change", (e) => {
|
|
118587
119271
|
const t = e.target;
|
|
119272
|
+
if (t.dataset.sel !== void 0) {
|
|
119273
|
+
if (t.checked) selected.add(t.dataset.sel);
|
|
119274
|
+
else selected.delete(t.dataset.sel);
|
|
119275
|
+
const count = root.querySelector('[data-role="sel-count"]');
|
|
119276
|
+
if (count) count.textContent = selCountText();
|
|
119277
|
+
syncFooter();
|
|
119278
|
+
return;
|
|
119279
|
+
}
|
|
118588
119280
|
if (t.dataset.field === "start") s.period.start = t.value;
|
|
118589
119281
|
if (t.dataset.field === "end") s.period.end = t.value;
|
|
118590
119282
|
if (t.dataset.field === "file") void loadFile(t.files?.[0]);
|
|
@@ -118655,8 +119347,8 @@ function standardDeviceName(domain, sigla, deviceProfile, seq) {
|
|
|
118655
119347
|
return `${NAME_PREFIX[domain]}${sigla}_${standardNameToken(deviceProfile)}_${String(seq).padStart(3, "0")}`;
|
|
118656
119348
|
}
|
|
118657
119349
|
function nextStandardSeq(domain, sigla, deviceProfile, existingNames) {
|
|
118658
|
-
const
|
|
118659
|
-
const re = new RegExp(`^${
|
|
119350
|
+
const esc13 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
119351
|
+
const re = new RegExp(`^${esc13(NAME_PREFIX[domain])}${esc13(sigla)}_${esc13(standardNameToken(deviceProfile))}_(\\d+)$`, "i");
|
|
118660
119352
|
const max = existingNames.reduce((acc, n) => {
|
|
118661
119353
|
const m = re.exec(String(n || "").trim());
|
|
118662
119354
|
return m ? Math.max(acc, Number(m[1])) : acc;
|
|
@@ -118680,8 +119372,8 @@ function siglaFromManualAsset(assetName) {
|
|
|
118680
119372
|
return /^[A-Z0-9_]+$/.test(sigla) ? sigla : null;
|
|
118681
119373
|
}
|
|
118682
119374
|
function nextManualSeq(domain, sigla, existingNames) {
|
|
118683
|
-
const
|
|
118684
|
-
const re = new RegExp(`^${
|
|
119375
|
+
const esc13 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
119376
|
+
const re = new RegExp(`^${esc13(NAME_PREFIX[domain])}${esc13(sigla)}_LOJA_(\\d+)_MANUAL$`, "i");
|
|
118685
119377
|
const max = existingNames.reduce((acc, n) => {
|
|
118686
119378
|
const m = re.exec(String(n || "").trim());
|
|
118687
119379
|
return m ? Math.max(acc, Number(m[1])) : acc;
|
|
@@ -153670,10 +154362,10 @@ var AlarmsNotificationsPanelView = class {
|
|
|
153670
154362
|
const renderListPanel = (group, items, sel) => {
|
|
153671
154363
|
if (items.length === 0) return '<div class="afm-empty">Nenhum item encontrado</div>';
|
|
153672
154364
|
return items.map((item) => {
|
|
153673
|
-
const
|
|
154365
|
+
const esc13 = this.esc(item);
|
|
153674
154366
|
return `<label class="afm-check-item">
|
|
153675
|
-
<input type="checkbox" class="afm-checkbox" data-group="${group}" data-value="${
|
|
153676
|
-
<span class="afm-check-label">${
|
|
154367
|
+
<input type="checkbox" class="afm-checkbox" data-group="${group}" data-value="${esc13}"${sel.has(item) ? " checked" : ""}>
|
|
154368
|
+
<span class="afm-check-label">${esc13}</span>
|
|
153677
154369
|
</label>`;
|
|
153678
154370
|
}).join("");
|
|
153679
154371
|
};
|
|
@@ -166551,7 +167243,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
|
|
|
166551
167243
|
const docTitle = buildActivationReportTitle(deviceName, opts.customerName);
|
|
166552
167244
|
const issuedAt = formatIssuedAt(/* @__PURE__ */ new Date(), locale);
|
|
166553
167245
|
const utilization = data.totalHours > 0 ? (data.totalOnMinutes / (data.totalHours * 60) * 100).toFixed(1) : "0.0";
|
|
166554
|
-
const
|
|
167246
|
+
const esc13 = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
166555
167247
|
const htmlContent = `
|
|
166556
167248
|
<!DOCTYPE html>
|
|
166557
167249
|
<html lang="pt-BR">
|
|
@@ -166603,14 +167295,14 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
|
|
|
166603
167295
|
<div class="brand">MyIO BAS</div>
|
|
166604
167296
|
<h1>Relat\xF3rio de Acionamentos</h1>
|
|
166605
167297
|
<div class="meta">
|
|
166606
|
-
<div><b>Dispositivo:</b> ${
|
|
167298
|
+
<div><b>Dispositivo:</b> ${esc13(deviceName)}</div>
|
|
166607
167299
|
<div><b>Per\xEDodo:</b> ${periodStart} \u2014 ${periodEnd}</div>
|
|
166608
167300
|
</div>
|
|
166609
167301
|
</div>
|
|
166610
167302
|
${customerName ? `
|
|
166611
167303
|
<div class="customer-badge">
|
|
166612
167304
|
<div class="label">Cliente</div>
|
|
166613
|
-
<div class="value">${
|
|
167305
|
+
<div class="value">${esc13(customerName)}</div>
|
|
166614
167306
|
</div>` : ""}
|
|
166615
167307
|
</div>
|
|
166616
167308
|
|
|
@@ -166621,7 +167313,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
|
|
|
166621
167313
|
</div>
|
|
166622
167314
|
<div class="summary-card accent-green">
|
|
166623
167315
|
<div class="summary-value">${formatDurationMinutes(data.totalOnMinutes)}</div>
|
|
166624
|
-
<div class="summary-label">Tempo ${
|
|
167316
|
+
<div class="summary-label">Tempo ${esc13(labelOn)}</div>
|
|
166625
167317
|
</div>
|
|
166626
167318
|
<div class="summary-card accent-amber">
|
|
166627
167319
|
<div class="summary-value">${utilization}%</div>
|
|
@@ -166649,7 +167341,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
|
|
|
166649
167341
|
<tr>
|
|
166650
167342
|
<td>${formatDateForExport(seg.startTime, locale)}</td>
|
|
166651
167343
|
<td>${formatDateForExport(seg.endTime, locale)}</td>
|
|
166652
|
-
<td><span class="pill ${seg.state === "on" ? "pill-on" : "pill-off"}">${seg.state === "on" ?
|
|
167344
|
+
<td><span class="pill ${seg.state === "on" ? "pill-on" : "pill-off"}">${seg.state === "on" ? esc13(labelOn) : esc13(labelOff)}</span></td>
|
|
166653
167345
|
<td>${formatDurationMinutes(seg.durationMinutes)}</td>
|
|
166654
167346
|
<td>${seg.source === "manual" ? "Manual" : seg.source === "schedule" ? "Agendamento" : seg.source === "automation" ? "Automa\xE7\xE3o" : "Desconhecido"}</td>
|
|
166655
167347
|
</tr>
|
|
@@ -166658,7 +167350,7 @@ function exportTimelineToPDF(data, labels = {}, locale = "pt-BR", opts = {}) {
|
|
|
166658
167350
|
</table>
|
|
166659
167351
|
|
|
166660
167352
|
<div class="footer">
|
|
166661
|
-
<span class="issued">Emitido em ${issuedAt}</span>${customerName ? ` · ${
|
|
167353
|
+
<span class="issued">Emitido em ${issuedAt}</span>${customerName ? ` · ${esc13(customerName)}` : ""} · <span class="brand">MyIO BAS</span>
|
|
166662
167354
|
</div>
|
|
166663
167355
|
</body>
|
|
166664
167356
|
</html>
|
|
@@ -181694,6 +182386,7 @@ var version = package_default.version || "0.0.0";
|
|
|
181694
182386
|
calculateStats,
|
|
181695
182387
|
canEditAlarmRules,
|
|
181696
182388
|
canModifyAnnotation,
|
|
182389
|
+
categoryKeyFromLabel,
|
|
181697
182390
|
centsToDecimalString,
|
|
181698
182391
|
checkCustomerCodeAvailable,
|
|
181699
182392
|
clampTemperature,
|
|
@@ -181835,7 +182528,6 @@ var version = package_default.version || "0.0.0";
|
|
|
181835
182528
|
detectSuperAdminMyio,
|
|
181836
182529
|
determineInterval,
|
|
181837
182530
|
deviceCategoryLabel,
|
|
181838
|
-
deviceCategoryToPanelTerm,
|
|
181839
182531
|
deviceIconLabels,
|
|
181840
182532
|
deviceIcons,
|
|
181841
182533
|
deviceNameToDeviceProductCode,
|
|
@@ -182130,9 +182822,7 @@ var version = package_default.version || "0.0.0";
|
|
|
182130
182822
|
openWelcomeModal,
|
|
182131
182823
|
openWellPumpsModal,
|
|
182132
182824
|
overlayWithholdsVerdict,
|
|
182133
|
-
panelCategoryToWire,
|
|
182134
182825
|
panelDomainToWire,
|
|
182135
|
-
panelTermToDeviceCategory,
|
|
182136
182826
|
parseBinaryState,
|
|
182137
182827
|
parseClassificationEntities,
|
|
182138
182828
|
parseCsv,
|
|
@@ -182255,7 +182945,6 @@ var version = package_default.version || "0.0.0";
|
|
|
182255
182945
|
valveHistoryFromTelemetry,
|
|
182256
182946
|
version,
|
|
182257
182947
|
waterDeviceStatusIcons,
|
|
182258
|
-
wireCategoryToPanel,
|
|
182259
182948
|
wireDomainToPanel,
|
|
182260
182949
|
writeFreshdeskSyncedAtToTB,
|
|
182261
182950
|
writeFreshdeskTicketsToTB,
|