myio-js-library 0.1.161 → 0.1.162

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.d.cts CHANGED
@@ -34,6 +34,12 @@ declare function fmtPerc$1(value: number): string;
34
34
  */
35
35
  declare function formatNumberReadable(value: unknown, locale?: string, minimumFractionDigits?: number, maximumFractionDigits?: number): string;
36
36
 
37
+ /**
38
+ * Simple water value formatting (same as MAIN controller)
39
+ * @param value - The water volume value in cubic meters
40
+ * @returns Formatted water volume string with m³ unit
41
+ */
42
+ declare function formatWater(value: number): string;
37
43
  /**
38
44
  * Formats water volume in cubic meters (M³) using Brazilian locale formatting
39
45
  * @param value - The water volume value in cubic meters
@@ -75,6 +81,29 @@ declare function formatAllInSameWaterUnit(values: number[]): {
75
81
  unit: string;
76
82
  };
77
83
 
84
+ /**
85
+ * Time and duration formatting utilities
86
+ * Extracted from MAIN controller for reuse across widgets
87
+ */
88
+ /**
89
+ * Converts a timestamp to a relative time string (e.g., "há 5 minutos").
90
+ * @param timestamp - The timestamp in milliseconds.
91
+ * @returns The formatted relative time string.
92
+ */
93
+ declare function formatRelativeTime(timestamp: number): string;
94
+ /**
95
+ * Formats duration in milliseconds to a readable string (e.g., "2d 5h", "3h 20m", "45s")
96
+ * @param ms - Duration in milliseconds
97
+ * @returns Formatted duration string
98
+ */
99
+ declare function formatarDuracao(ms: number): string;
100
+ /**
101
+ * Alias for formatarDuracao using English naming convention
102
+ * @param ms - Duration in milliseconds
103
+ * @returns Formatted duration string
104
+ */
105
+ declare const formatDuration: typeof formatarDuracao;
106
+
78
107
  /**
79
108
  * Formats a date to YYYY-MM-DD format
80
109
  * @param date - The date to format (Date object, timestamp, or date string)
@@ -308,6 +337,19 @@ declare function getValueByDatakeyLegacy(dataList: any[], dataSourceNameTarget:
308
337
  * @returns The value found, or undefined if not found
309
338
  */
310
339
  declare function findValue(data: any, keyOrPath: string, legacyDataKey?: string): any;
340
+ /**
341
+ * Find a value in an array of objects by key/dataType (RFC-0091 compatible)
342
+ * Supports both ThingsBoard format {dataType, value} and generic {key, value}
343
+ * @param values - Array of objects with key/value or dataType/value properties
344
+ * @param key - Key or dataType to search for
345
+ * @param defaultValue - Default value if not found (defaults to null)
346
+ * @returns The found value or defaultValue
347
+ */
348
+ declare function findValueWithDefault<T = any>(values: Array<{
349
+ key?: string;
350
+ dataType?: string;
351
+ value: any;
352
+ }> | any, key: string, defaultValue?: T | null): T | null;
311
353
 
312
354
  /**
313
355
  * Maps device status to connection status
@@ -318,6 +360,12 @@ declare function findValue(data: any, keyOrPath: string, legacyDataKey?: string)
318
360
  * @returns {string} The connection status (connected or offline)
319
361
  */
320
362
  declare function mapDeviceToConnectionStatus(deviceStatus: string): string;
363
+ /**
364
+ * Maps raw connection status string to normalized status
365
+ * @param {string} rawStatus - Raw status from ThingsBoard (e.g., 'ONLINE', 'ok', 'running', 'waiting', 'offline')
366
+ * @returns {'online' | 'waiting' | 'offline'} - Normalized status
367
+ */
368
+ declare function mapConnectionStatus(rawStatus: string): "online" | "waiting" | "offline";
321
369
  /**
322
370
  * Maps device status to a simplified card status
323
371
  * Used for styling and visual representation
@@ -2116,7 +2164,7 @@ declare function clampTemperature(value: number | string, range?: ClampRange): n
2116
2164
  /**
2117
2165
  * Calculates statistics from temperature data
2118
2166
  */
2119
- declare function calculateStats(data: TemperatureTelemetry[], clampRange?: ClampRange): TemperatureStats;
2167
+ declare function calculateStats$1(data: TemperatureTelemetry[], clampRange?: ClampRange): TemperatureStats;
2120
2168
  /**
2121
2169
  * Interpolates temperature data to fill gaps with 30-minute intervals
2122
2170
  * Uses 'repeat-last' strategy: if no reading in interval, repeats last known temperature
@@ -2283,4 +2331,843 @@ interface TemperatureSettingsInstance {
2283
2331
  */
2284
2332
  declare function openTemperatureSettingsModal(params: TemperatureSettingsParams): TemperatureSettingsInstance;
2285
2333
 
2286
- export { CHART_COLORS, type ClampRange, ConnectionStatusType, type CreateDateRangePickerOptions, type CreateInputDateRangePickerInsideDIVParams, DEFAULT_CLAMP_RANGE, type DateRangeControl, type DateRangeInputController, type DateRangeResult, type DemandModalInstance, type DemandModalParams, type DemandModalPdfConfig, type DemandModalStyles, DeviceStatusType, type EnergyModalContext, type EnergyModalError, type EnergyModalI18n, type EnergyModalStyleOverrides, type MyIOAuthConfig, type MyIOAuthInstance, MyIOChartModal, MyIODraggableCard, MyIOSelectionStore, MyIOSelectionStoreClass, MyIOToast, type OpenDashboardPopupEnergyOptions, type OpenDashboardPopupSettingsParams, type OpenDashboardPopupWaterTankOptions, type PersistResult, type RealTimeTelemetryInstance, type RealTimeTelemetryParams, type SettingsError, type SettingsEvent, type StoreRow, type TbScope, type TelemetryFetcher, type TemperatureComparisonModalInstance, type TemperatureComparisonModalParams, type TemperatureDevice, type TemperatureGranularity, type TemperatureModalInstance, type TemperatureModalParams, type TemperatureSettingsInstance, type TemperatureSettingsParams, type TemperatureStats, type TemperatureTelemetry, type ThingsboardCustomerAttrsConfig, type TimedValue, type WaterRow, type WaterTankDataPoint, type WaterTankModalContext, type WaterTankModalError, type WaterTankModalI18n, type WaterTankModalStyleOverrides, type WaterTankTelemetryData, addDetectionContext, addNamespace, aggregateByDay, averageByDay, buildListItemsThingsboardByUniqueDatasource, buildMyioIngestionAuth, buildWaterReportCSV, buildWaterStoresCSV, calcDeltaPercent, calculateDeviceStatus, calculateDeviceStatusWithRanges, calculateStats, clampTemperature, classify, classifyWaterLabel, classifyWaterLabels, clearAllAuthCaches, connectionStatusIcons, createDateRangePicker, createInputDateRangePickerInsideDIV, decodePayload, decodePayloadBase64Xor, detectDeviceType, determineInterval, deviceStatusIcons, exportTemperatureCSV, exportToCSV, exportToCSVAll, extractMyIOCredentials, fetchTemperatureData, fetchThingsboardCustomerAttrsFromStorage, fetchThingsboardCustomerServerScopeAttrs, findValue, fmtPerc$1 as fmtPerc, fmtPerc as fmtPercLegacy, formatAllInSameUnit, formatAllInSameWaterUnit, formatDateForInput, formatDateToYMD, formatDateWithTimezoneOffset, formatEnergy, formatNumberReadable, formatTankHeadFromCm, formatTemperature, formatWaterByGroup, formatWaterVolumeM3, getAuthCacheStats, getAvailableContexts, getConnectionStatusIcon, getDateRangeArray, getDeviceStatusIcon, getDeviceStatusInfo, getSaoPauloISOString, getSaoPauloISOStringFixed, getValueByDatakey, getValueByDatakeyLegacy, getWaterCategories, groupByDay, interpolateTemperature, isDeviceOffline, isValidConnectionStatus, isValidDeviceStatus, isWaterCategory, mapDeviceStatusToCardStatus, mapDeviceToConnectionStatus, normalizeRecipients, numbers, openDashboardPopup, openDashboardPopupAllReport, openDashboardPopupEnergy, openDashboardPopupReport, openDashboardPopupSettings, openDashboardPopupWaterTank, openDemandModal, openGoalsPanel, openRealTimeTelemetryModal, openTemperatureComparisonModal, openTemperatureModal, openTemperatureSettingsModal, parseInputDateToDate, renderCardComponent$2 as renderCardComponent, renderCardComponent$1 as renderCardComponentEnhanced, renderCardComponentHeadOffice, renderCardComponentLegacy, renderCardComponentV2, renderCardComponent as renderCardComponentV5, renderCardComponentV5 as renderCardV5, shouldFlashIcon, strings, timeWindowFromInputYMD, toCSV, toFixedSafe, waterDeviceStatusIcons };
2334
+ /**
2335
+ * MyIO Modal Header Component
2336
+ *
2337
+ * A reusable header component for modals with:
2338
+ * - Title with optional icon (domain-specific)
2339
+ * - Export button with format options (CSV, XLS, PDF)
2340
+ * - Theme toggle (light/dark)
2341
+ * - Maximize/restore button
2342
+ * - Close button
2343
+ *
2344
+ * @example
2345
+ * ```typescript
2346
+ * import { createModalHeader } from 'myio-js-library';
2347
+ *
2348
+ * const header = createModalHeader({
2349
+ * id: 'my-modal',
2350
+ * title: 'My Modal Title',
2351
+ * icon: '📊',
2352
+ * theme: 'light',
2353
+ * isMaximized: false,
2354
+ * exportFormats: ['csv', 'xls', 'pdf'],
2355
+ * onExport: (format) => console.log('Export:', format),
2356
+ * onThemeToggle: (theme) => console.log('Theme:', theme),
2357
+ * onMaximize: (maximized) => console.log('Maximized:', maximized),
2358
+ * onClose: () => console.log('Close clicked'),
2359
+ * });
2360
+ *
2361
+ * container.innerHTML = header.render();
2362
+ * header.attachListeners();
2363
+ * ```
2364
+ */
2365
+ type ModalTheme = 'light' | 'dark';
2366
+ type ExportFormat$1 = 'csv' | 'xls' | 'pdf';
2367
+ interface ModalHeaderConfig {
2368
+ /** Unique ID prefix for the modal elements */
2369
+ id: string;
2370
+ /** Modal title text */
2371
+ title: string;
2372
+ /** Optional icon (emoji or text) to display before title */
2373
+ icon?: string;
2374
+ /** Current theme */
2375
+ theme?: ModalTheme;
2376
+ /** Whether the modal is currently maximized */
2377
+ isMaximized?: boolean;
2378
+ /** Header background color (default: #3e1a7d - MyIO purple) */
2379
+ backgroundColor?: string;
2380
+ /** Header text color (default: white) */
2381
+ textColor?: string;
2382
+ /** Show theme toggle button (default: true) */
2383
+ showThemeToggle?: boolean;
2384
+ /** Show maximize button (default: true) */
2385
+ showMaximize?: boolean;
2386
+ /** Show close button (default: true) */
2387
+ showClose?: boolean;
2388
+ /** Border radius when not maximized (default: '10px 10px 0 0') */
2389
+ borderRadius?: string;
2390
+ /** Available export formats (shows dropdown if multiple) */
2391
+ exportFormats?: ExportFormat$1[];
2392
+ /** Callback when export is clicked with format */
2393
+ onExport?: (format: ExportFormat$1) => void;
2394
+ /** Callback when theme is toggled */
2395
+ onThemeToggle?: (theme: ModalTheme) => void;
2396
+ /** Callback when maximize/restore is clicked */
2397
+ onMaximize?: (isMaximized: boolean) => void;
2398
+ /** Callback when close is clicked */
2399
+ onClose?: () => void;
2400
+ }
2401
+ interface ModalHeaderInstance {
2402
+ /** Renders the header HTML */
2403
+ render: () => string;
2404
+ /** Attaches event listeners (call after adding to DOM) */
2405
+ attachListeners: () => void;
2406
+ /** Updates the header state */
2407
+ update: (updates: Partial<Pick<ModalHeaderConfig, 'theme' | 'isMaximized' | 'title'>>) => void;
2408
+ /** Gets the current state */
2409
+ getState: () => {
2410
+ theme: ModalTheme;
2411
+ isMaximized: boolean;
2412
+ };
2413
+ /** Removes event listeners */
2414
+ destroy: () => void;
2415
+ }
2416
+ /**
2417
+ * Creates a modal header instance
2418
+ */
2419
+ declare function createModalHeader(config: ModalHeaderConfig): ModalHeaderInstance;
2420
+ /**
2421
+ * Returns CSS styles for the modal header component
2422
+ * Can be injected into page or used in CSS-in-JS
2423
+ */
2424
+ declare function getModalHeaderStyles(): string;
2425
+
2426
+ /**
2427
+ * RFC-0098: View Consumption Over 7 Days Component
2428
+ * Type definitions for the reusable consumption chart component
2429
+ */
2430
+ /**
2431
+ * Supported chart domains
2432
+ */
2433
+ type ChartDomain = 'energy' | 'water' | 'gas' | 'temperature' | string;
2434
+ /**
2435
+ * Theme modes
2436
+ */
2437
+ type ThemeMode = 'light' | 'dark';
2438
+ /**
2439
+ * Chart visualization types
2440
+ */
2441
+ type ChartType = 'line' | 'bar';
2442
+ /**
2443
+ * Visualization modes
2444
+ */
2445
+ type VizMode = 'total' | 'separate';
2446
+ /**
2447
+ * Ideal range configuration for shaded area on chart
2448
+ * Used to highlight acceptable/target ranges for any domain
2449
+ */
2450
+ interface IdealRangeConfig {
2451
+ /** Minimum value of the ideal range */
2452
+ min: number;
2453
+ /** Maximum value of the ideal range */
2454
+ max: number;
2455
+ /** Color for the shaded area (with alpha for transparency) */
2456
+ color?: string;
2457
+ /** Border color for the range box */
2458
+ borderColor?: string;
2459
+ /** Optional label to display */
2460
+ label?: string;
2461
+ /** Whether to show the range (default: true when min/max are set) */
2462
+ enabled?: boolean;
2463
+ }
2464
+ /**
2465
+ * Temperature reference line configuration
2466
+ */
2467
+ interface TemperatureReferenceLine {
2468
+ /** Value for the reference line */
2469
+ value: number;
2470
+ /** Label for the reference line */
2471
+ label: string;
2472
+ /** Line color */
2473
+ color: string;
2474
+ /** Line style: 'solid', 'dashed', 'dotted' */
2475
+ lineStyle?: 'solid' | 'dashed' | 'dotted';
2476
+ /** Line width (default: 2) */
2477
+ lineWidth?: number;
2478
+ /** Fill area above or below the line */
2479
+ fillArea?: 'above' | 'below' | 'none';
2480
+ /** Fill color (with alpha) */
2481
+ fillColor?: string;
2482
+ }
2483
+ /**
2484
+ * Temperature-specific configuration
2485
+ */
2486
+ interface TemperatureConfig {
2487
+ /** Minimum temperature reference line */
2488
+ minThreshold?: TemperatureReferenceLine;
2489
+ /** Maximum temperature reference line */
2490
+ maxThreshold?: TemperatureReferenceLine;
2491
+ /** Ideal range (shows shaded area between min and max) */
2492
+ idealRange?: {
2493
+ min: number;
2494
+ max: number;
2495
+ color: string;
2496
+ label?: string;
2497
+ };
2498
+ /** Clamp values outside this range for display */
2499
+ clampRange?: {
2500
+ min: number;
2501
+ max: number;
2502
+ };
2503
+ /** Show temperature unit in Y-axis (default: true) */
2504
+ showUnitInAxis?: boolean;
2505
+ }
2506
+ /**
2507
+ * Color configuration for the chart
2508
+ */
2509
+ interface Consumption7DaysColors {
2510
+ /** Primary line/bar color */
2511
+ primary: string;
2512
+ /** Background fill color (for line charts) */
2513
+ background: string;
2514
+ /** Optional gradient colors [start, end] */
2515
+ gradient?: [string, string];
2516
+ /** Optional border color */
2517
+ borderColor?: string;
2518
+ /** Optional point colors for line charts */
2519
+ pointBackground?: string;
2520
+ pointBorder?: string;
2521
+ }
2522
+ /**
2523
+ * Single data point for consumption
2524
+ */
2525
+ interface ConsumptionDataPoint {
2526
+ /** ISO date string or formatted label */
2527
+ date: string;
2528
+ /** Consumption value in base unit */
2529
+ value: number;
2530
+ /** Optional custom label override */
2531
+ label?: string;
2532
+ }
2533
+ /**
2534
+ * Data point with shopping information (for per-shopping mode)
2535
+ */
2536
+ interface ShoppingDataPoint extends ConsumptionDataPoint {
2537
+ /** Shopping identifier */
2538
+ shoppingId: string;
2539
+ /** Shopping display name */
2540
+ shoppingName: string;
2541
+ }
2542
+ /**
2543
+ * Structured data for the 7-day consumption chart
2544
+ */
2545
+ interface Consumption7DaysData {
2546
+ /** Array of date labels for X-axis */
2547
+ labels: string[];
2548
+ /** Array of total consumption values per day */
2549
+ dailyTotals: number[];
2550
+ /** Optional per-shopping data: { shoppingId: [values per day...] } */
2551
+ shoppingData?: Record<string, number[]>;
2552
+ /** Optional shopping name mapping: { shoppingId: displayName } */
2553
+ shoppingNames?: Record<string, string>;
2554
+ /** Timestamp when data was fetched (for cache validation) */
2555
+ fetchTimestamp?: number;
2556
+ /** Customer IDs used to fetch this data (for cache validation) */
2557
+ customerIds?: string[];
2558
+ }
2559
+ /**
2560
+ * Configuration options for creating the consumption chart
2561
+ */
2562
+ interface Consumption7DaysConfig {
2563
+ /** Domain identifier (energy, water, etc.) - used for logging */
2564
+ domain: ChartDomain;
2565
+ /** Canvas element ID to render the chart */
2566
+ containerId: string;
2567
+ /** Base unit for display (kWh, m³, etc.) */
2568
+ unit: string;
2569
+ /**
2570
+ * Data fetching function - must return structured data
2571
+ * @param period - Number of days to fetch
2572
+ * @returns Promise resolving to consumption data
2573
+ */
2574
+ fetchData: (period: number) => Promise<Consumption7DaysData>;
2575
+ /** Large unit for values above threshold (MWh, etc.) - null to disable */
2576
+ unitLarge?: string | null;
2577
+ /** Threshold value to switch to large unit (1000 for kWh->MWh) */
2578
+ thresholdForLargeUnit?: number | null;
2579
+ /** Decimal places for value display */
2580
+ decimalPlaces?: number;
2581
+ /** Color configuration */
2582
+ colors?: Consumption7DaysColors;
2583
+ /** Chart title (optional, usually in container header) */
2584
+ title?: string;
2585
+ /** Show legend below chart */
2586
+ showLegend?: boolean;
2587
+ /** Line tension for smooth curves (0-1, default: 0.4) */
2588
+ lineTension?: number;
2589
+ /** Point radius for line charts (default: 4) */
2590
+ pointRadius?: number;
2591
+ /** Border width for lines/bars (default: 2) */
2592
+ borderWidth?: number;
2593
+ /** Fill area under line chart (default: true) */
2594
+ fill?: boolean;
2595
+ /** Theme mode: 'light' or 'dark' (default: 'light') */
2596
+ theme?: ThemeMode;
2597
+ /** Default period in days (default: 7) */
2598
+ defaultPeriod?: number;
2599
+ /** Default chart type (default: 'line') */
2600
+ defaultChartType?: ChartType;
2601
+ /** Default visualization mode (default: 'total') */
2602
+ defaultVizMode?: VizMode;
2603
+ /** Cache TTL in milliseconds (default: 300000 = 5 min) */
2604
+ cacheTTL?: number;
2605
+ /** Auto-refresh interval in milliseconds (null to disable) */
2606
+ autoRefreshInterval?: number | null;
2607
+ /** Called when data is successfully loaded */
2608
+ onDataLoaded?: (data: Consumption7DaysData) => void;
2609
+ /** Called when an error occurs */
2610
+ onError?: (error: Error) => void;
2611
+ /** Called before rendering (can modify data) */
2612
+ onBeforeRender?: (data: Consumption7DaysData) => Consumption7DaysData;
2613
+ /** Called after chart is rendered */
2614
+ onAfterRender?: (chartInstance: any) => void;
2615
+ /**
2616
+ * Called when settings button is clicked
2617
+ * Use this to open a custom settings modal (e.g., with createDateRangePicker)
2618
+ * If not provided, no settings button functionality is added
2619
+ */
2620
+ onSettingsClick?: () => void;
2621
+ /**
2622
+ * Called when maximize button is clicked
2623
+ * Use this to open fullscreen mode
2624
+ * If not provided, no maximize button functionality is added
2625
+ */
2626
+ onMaximizeClick?: () => void;
2627
+ /**
2628
+ * Called when export CSV button is clicked
2629
+ * If not provided, uses default export behavior
2630
+ */
2631
+ onExportCSV?: (data: Consumption7DaysData) => void;
2632
+ /**
2633
+ * Enable CSV export functionality (default: true)
2634
+ */
2635
+ enableExport?: boolean;
2636
+ /**
2637
+ * ID of the export button element to attach click handler
2638
+ */
2639
+ exportButtonId?: string;
2640
+ /**
2641
+ * Custom filename for CSV export (without extension)
2642
+ * Default: '{domain}-consumption-{date}'
2643
+ */
2644
+ exportFilename?: string;
2645
+ /**
2646
+ * Ideal range configuration for displaying a shaded area on the chart.
2647
+ * Shows acceptable/target range for the metric.
2648
+ *
2649
+ * For temperature: typically comes from customer attributes (minTemperature, maxTemperature)
2650
+ * For energy/water/gas: optional, can be set via settings modal
2651
+ *
2652
+ * @example
2653
+ * ```typescript
2654
+ * // Temperature with customer-defined range
2655
+ * idealRange: {
2656
+ * min: 20, // minTemperature from customer
2657
+ * max: 24, // maxTemperature from customer
2658
+ * color: 'rgba(34, 197, 94, 0.15)',
2659
+ * label: 'Faixa Ideal'
2660
+ * }
2661
+ *
2662
+ * // Energy with target consumption
2663
+ * idealRange: {
2664
+ * min: 0,
2665
+ * max: 500, // kWh target
2666
+ * color: 'rgba(37, 99, 235, 0.1)',
2667
+ * label: 'Meta de Consumo'
2668
+ * }
2669
+ * ```
2670
+ */
2671
+ idealRange?: IdealRangeConfig;
2672
+ /**
2673
+ * Temperature-specific configuration
2674
+ * Only applies when domain is 'temperature'
2675
+ */
2676
+ temperatureConfig?: TemperatureConfig;
2677
+ /**
2678
+ * ThingsBoard widget container for proper DOM querying
2679
+ * When provided, uses $container.querySelector() instead of document.getElementById()
2680
+ */
2681
+ $container?: {
2682
+ [key: number]: HTMLElement;
2683
+ } | null;
2684
+ /**
2685
+ * ID of the settings button element to attach click handler
2686
+ * Used with onSettingsClick callback
2687
+ */
2688
+ settingsButtonId?: string;
2689
+ /**
2690
+ * ID of the maximize button element to attach click handler
2691
+ * Used with onMaximizeClick callback
2692
+ */
2693
+ maximizeButtonId?: string;
2694
+ /**
2695
+ * ID of the chart title element to update dynamically
2696
+ */
2697
+ titleElementId?: string;
2698
+ }
2699
+ /**
2700
+ * Public API returned by createConsumption7DaysChart()
2701
+ */
2702
+ interface Consumption7DaysInstance {
2703
+ /**
2704
+ * Render the chart (fetches data and creates Chart.js instance)
2705
+ */
2706
+ render: () => Promise<void>;
2707
+ /**
2708
+ * Update chart with new or existing data
2709
+ * @param data - Optional new data; uses cached data if not provided
2710
+ */
2711
+ update: (data?: Consumption7DaysData) => Promise<void>;
2712
+ /**
2713
+ * Change chart type (line/bar)
2714
+ * @param type - New chart type
2715
+ */
2716
+ setChartType: (type: ChartType) => void;
2717
+ /**
2718
+ * Change visualization mode (total/separate)
2719
+ * @param mode - New visualization mode
2720
+ */
2721
+ setVizMode: (mode: VizMode) => void;
2722
+ /**
2723
+ * Change the period and re-fetch data
2724
+ * @param days - New period in days
2725
+ */
2726
+ setPeriod: (days: number) => Promise<void>;
2727
+ /**
2728
+ * Refresh data from source
2729
+ * @param forceRefresh - Bypass cache if true
2730
+ */
2731
+ refresh: (forceRefresh?: boolean) => Promise<void>;
2732
+ /**
2733
+ * Destroy the chart instance and clean up resources
2734
+ */
2735
+ destroy: () => void;
2736
+ /**
2737
+ * Get the underlying Chart.js instance
2738
+ */
2739
+ getChartInstance: () => any | null;
2740
+ /**
2741
+ * Get currently cached data
2742
+ */
2743
+ getCachedData: () => Consumption7DaysData | null;
2744
+ /**
2745
+ * Get current configuration state
2746
+ */
2747
+ getState: () => {
2748
+ period: number;
2749
+ chartType: ChartType;
2750
+ vizMode: VizMode;
2751
+ theme: ThemeMode;
2752
+ isRendered: boolean;
2753
+ };
2754
+ /**
2755
+ * Export current data to CSV file
2756
+ * @param filename - Optional custom filename (without extension)
2757
+ */
2758
+ exportCSV: (filename?: string) => void;
2759
+ /**
2760
+ * Set theme mode
2761
+ * @param theme - 'light' or 'dark'
2762
+ */
2763
+ setTheme: (theme: ThemeMode) => void;
2764
+ /**
2765
+ * Set or update the ideal range
2766
+ * Pass null to remove the ideal range
2767
+ * @param range - Ideal range configuration or null to clear
2768
+ */
2769
+ setIdealRange: (range: IdealRangeConfig | null) => void;
2770
+ /**
2771
+ * Get the current ideal range configuration
2772
+ */
2773
+ getIdealRange: () => IdealRangeConfig | null;
2774
+ }
2775
+ /**
2776
+ * Default color schemes for common domains
2777
+ */
2778
+ declare const DEFAULT_COLORS: Record<string, Consumption7DaysColors>;
2779
+ /**
2780
+ * Theme color configurations
2781
+ */
2782
+ interface ThemeColors {
2783
+ /** Chart background color */
2784
+ chartBackground: string;
2785
+ /** Text color */
2786
+ text: string;
2787
+ /** Muted text color */
2788
+ textMuted: string;
2789
+ /** Grid line color */
2790
+ grid: string;
2791
+ /** Border color */
2792
+ border: string;
2793
+ /** Tooltip background */
2794
+ tooltipBackground: string;
2795
+ /** Tooltip text */
2796
+ tooltipText: string;
2797
+ }
2798
+ /**
2799
+ * Default theme colors for light and dark modes
2800
+ */
2801
+ declare const THEME_COLORS: Record<ThemeMode, ThemeColors>;
2802
+ /**
2803
+ * Default configuration values
2804
+ */
2805
+ declare const DEFAULT_CONFIG: {
2806
+ defaultPeriod: number;
2807
+ defaultChartType: ChartType;
2808
+ defaultVizMode: VizMode;
2809
+ defaultTheme: ThemeMode;
2810
+ cacheTTL: number;
2811
+ decimalPlaces: number;
2812
+ lineTension: number;
2813
+ pointRadius: number;
2814
+ borderWidth: number;
2815
+ fill: boolean;
2816
+ showLegend: boolean;
2817
+ enableExport: boolean;
2818
+ };
2819
+
2820
+ /**
2821
+ * RFC-0098: View Consumption Over 7 Days Component
2822
+ * Factory function to create a reusable consumption chart
2823
+ *
2824
+ * @example
2825
+ * ```typescript
2826
+ * import { createConsumption7DaysChart } from 'myio-js-library';
2827
+ *
2828
+ * const chart = createConsumption7DaysChart({
2829
+ * domain: 'energy',
2830
+ * containerId: 'lineChart',
2831
+ * unit: 'kWh',
2832
+ * unitLarge: 'MWh',
2833
+ * thresholdForLargeUnit: 1000,
2834
+ * fetchData: async (period) => fetchEnergyData(period),
2835
+ * });
2836
+ *
2837
+ * await chart.render();
2838
+ * ```
2839
+ */
2840
+
2841
+ /**
2842
+ * Creates a consumption chart instance with the given configuration
2843
+ *
2844
+ * @param config - Chart configuration options
2845
+ * @returns Chart instance with public API
2846
+ */
2847
+ declare function createConsumption7DaysChart(config: Consumption7DaysConfig): Consumption7DaysInstance;
2848
+
2849
+ /**
2850
+ * RFC-0098: Consumption Modal with MyIO Header
2851
+ *
2852
+ * Creates a fullscreen modal for the consumption chart using the standard
2853
+ * MyIO header with theme toggle, maximize, export and close buttons.
2854
+ *
2855
+ * @example
2856
+ * ```typescript
2857
+ * import { createConsumptionModal } from 'myio-js-library';
2858
+ *
2859
+ * const modal = createConsumptionModal({
2860
+ * domain: 'energy',
2861
+ * title: 'Consumo de Energia',
2862
+ * unit: 'kWh',
2863
+ * fetchData: async (period) => fetchEnergyData(period),
2864
+ * onClose: () => console.log('Modal closed'),
2865
+ * });
2866
+ *
2867
+ * await modal.open();
2868
+ * ```
2869
+ */
2870
+
2871
+ interface ConsumptionModalConfig extends Omit<Consumption7DaysConfig, 'containerId'> {
2872
+ /** Modal title */
2873
+ title?: string;
2874
+ /** Initial theme */
2875
+ theme?: ThemeMode;
2876
+ /** Callback when modal closes */
2877
+ onClose?: () => void;
2878
+ /** Container to append modal (default: document.body) */
2879
+ container?: HTMLElement;
2880
+ /** Export formats available (default: ['csv']) */
2881
+ exportFormats?: ExportFormat$1[];
2882
+ /** Custom export handler (receives format, default uses built-in CSV export) */
2883
+ onExport?: (format: ExportFormat$1) => void;
2884
+ }
2885
+ interface ConsumptionModalInstance {
2886
+ /** Opens the modal */
2887
+ open: () => Promise<void>;
2888
+ /** Closes the modal */
2889
+ close: () => void;
2890
+ /** Gets the chart instance */
2891
+ getChart: () => ReturnType<typeof createConsumption7DaysChart> | null;
2892
+ /** Destroys the modal and chart */
2893
+ destroy: () => void;
2894
+ }
2895
+ /**
2896
+ * Creates a consumption modal with the standard MyIO header
2897
+ */
2898
+ declare function createConsumptionModal(config: ConsumptionModalConfig): ConsumptionModalInstance;
2899
+
2900
+ /**
2901
+ * RFC-0101: Export Data Smart Component Types
2902
+ *
2903
+ * Type definitions for the export data component system.
2904
+ */
2905
+ /** Domain types for data classification */
2906
+ type ExportDomain = 'energy' | 'water' | 'temperature';
2907
+ /** Supported export file formats */
2908
+ type ExportFormat = 'pdf' | 'xlsx' | 'csv';
2909
+ /** Export type determining data structure */
2910
+ type ExportType = 'one-device' | 'comparison' | 'one-customer' | 'group-of-customer';
2911
+ /** Custom color palette for exports */
2912
+ interface ExportColorsPallet {
2913
+ /** Primary brand color (default: MyIO purple #3e1a7d) */
2914
+ primary?: string;
2915
+ /** Secondary color for accents */
2916
+ secondary?: string;
2917
+ /** Accent color for highlights */
2918
+ accent?: string;
2919
+ /** Background color */
2920
+ background?: string;
2921
+ /** Text color */
2922
+ text?: string;
2923
+ /** Chart colors array */
2924
+ chartColors?: string[];
2925
+ }
2926
+ /** Configuration options for buildTemplateExport */
2927
+ interface BuildTemplateExportParams {
2928
+ /** Data domain (energy, water, temperature) */
2929
+ domain: ExportDomain;
2930
+ /** Output format (pdf, xlsx, csv) */
2931
+ formatExport: ExportFormat;
2932
+ /** Type of export data structure */
2933
+ typeExport: ExportType;
2934
+ /** Optional custom color palette */
2935
+ colorsPallet?: ExportColorsPallet;
2936
+ /** Locale for number/date formatting (default: 'pt-BR') */
2937
+ locale?: string;
2938
+ /** Include chart in export (PDF only) */
2939
+ includeChart?: boolean;
2940
+ /** Include statistics (min, max, avg) */
2941
+ includeStats?: boolean;
2942
+ /** Custom header text */
2943
+ headerText?: string;
2944
+ /** Custom footer text */
2945
+ footerText?: string;
2946
+ }
2947
+ /** Generated export configuration template */
2948
+ interface ExportConfigTemplate {
2949
+ /** Domain configuration */
2950
+ domain: ExportDomain;
2951
+ /** Format configuration */
2952
+ formatExport: ExportFormat;
2953
+ /** Export type */
2954
+ typeExport: ExportType;
2955
+ /** Resolved color palette */
2956
+ colors: Required<ExportColorsPallet>;
2957
+ /** Locale setting */
2958
+ locale: string;
2959
+ /** Chart inclusion flag */
2960
+ includeChart: boolean;
2961
+ /** Stats inclusion flag */
2962
+ includeStats: boolean;
2963
+ /** Header text */
2964
+ headerText: string;
2965
+ /** Footer text */
2966
+ footerText: string;
2967
+ /** Domain-specific icon */
2968
+ domainIcon: string;
2969
+ /** Domain label (localized) */
2970
+ domainLabel: string;
2971
+ /** Unit for the domain */
2972
+ domainUnit: string;
2973
+ }
2974
+ /** Single data point with timestamp and value */
2975
+ interface ExportDataPoint {
2976
+ /** Timestamp of the measurement */
2977
+ timestamp: Date | string | number;
2978
+ /** Measured value */
2979
+ value: number;
2980
+ /** Optional unit override */
2981
+ unit?: string;
2982
+ }
2983
+ /** Device information for export */
2984
+ interface ExportDeviceInfo {
2985
+ /** Device identifier (e.g., '113CD') */
2986
+ identifier?: string;
2987
+ /** Device label (display name) */
2988
+ label?: string;
2989
+ /** Device name (fallback if no label) */
2990
+ name: string;
2991
+ /** Device icon (optional) */
2992
+ icon?: string;
2993
+ }
2994
+ /** Customer/Shopping information */
2995
+ interface ExportCustomerInfo {
2996
+ /** Customer name */
2997
+ customerName?: string;
2998
+ /** Shopping/location name */
2999
+ shoppingName?: string;
3000
+ /** Customer logo URL (for PDF) */
3001
+ logoUrl?: string;
3002
+ }
3003
+ /** Complete data structure for export */
3004
+ interface ExportData {
3005
+ /** Device information */
3006
+ device: ExportDeviceInfo;
3007
+ /** Customer information */
3008
+ customer?: ExportCustomerInfo;
3009
+ /** Data points array */
3010
+ data: ExportDataPoint[];
3011
+ /** Period start date */
3012
+ periodStart?: Date | string;
3013
+ /** Period end date */
3014
+ periodEnd?: Date | string;
3015
+ }
3016
+ /** Data structure for comparison exports */
3017
+ interface ExportComparisonData {
3018
+ /** Array of devices with their data */
3019
+ devices: Array<ExportData>;
3020
+ /** Customer information */
3021
+ customer?: ExportCustomerInfo;
3022
+ /** Period start date */
3023
+ periodStart?: Date | string;
3024
+ /** Period end date */
3025
+ periodEnd?: Date | string;
3026
+ }
3027
+ /** Data structure for customer exports */
3028
+ interface ExportCustomerData {
3029
+ /** Customer information */
3030
+ customer: ExportCustomerInfo;
3031
+ /** Array of devices with their data */
3032
+ devices: Array<ExportData>;
3033
+ /** Period start date */
3034
+ periodStart?: Date | string;
3035
+ /** Period end date */
3036
+ periodEnd?: Date | string;
3037
+ }
3038
+ /** Data structure for group of customers exports */
3039
+ interface ExportGroupData {
3040
+ /** Group name */
3041
+ groupName: string;
3042
+ /** Array of customers with their data */
3043
+ customers: Array<ExportCustomerData>;
3044
+ /** Period start date */
3045
+ periodStart?: Date | string;
3046
+ /** Period end date */
3047
+ periodEnd?: Date | string;
3048
+ }
3049
+ /** Union type for all export data types */
3050
+ type ExportDataInput = ExportData | ExportComparisonData | ExportCustomerData | ExportGroupData;
3051
+ /** Calculated statistics for a data series */
3052
+ interface ExportStats {
3053
+ /** Minimum value in the period */
3054
+ min: number;
3055
+ /** Maximum value in the period */
3056
+ max: number;
3057
+ /** Average value in the period */
3058
+ average: number;
3059
+ /** Sum of all values */
3060
+ sum: number;
3061
+ /** Number of data points */
3062
+ count: number;
3063
+ }
3064
+ /** Export result with file information */
3065
+ interface ExportResult {
3066
+ /** Whether export was successful */
3067
+ success: boolean;
3068
+ /** Generated filename */
3069
+ filename: string;
3070
+ /** File blob (for download) */
3071
+ blob?: Blob;
3072
+ /** Data URL (for preview) */
3073
+ dataUrl?: string;
3074
+ /** Error message if failed */
3075
+ error?: string;
3076
+ }
3077
+ /** Export instance returned by myioExportData */
3078
+ interface ExportDataInstance {
3079
+ /** Execute the export and get result */
3080
+ export: () => Promise<ExportResult>;
3081
+ /** Download the exported file */
3082
+ download: () => Promise<void>;
3083
+ /** Get preview data URL (PDF only) */
3084
+ preview: () => Promise<string | null>;
3085
+ /** Get calculated statistics */
3086
+ getStats: () => ExportStats;
3087
+ /** Get generated filename */
3088
+ getFilename: () => string;
3089
+ }
3090
+ /** Progress callback for large exports */
3091
+ type ExportProgressCallback = (progress: number, message: string) => void;
3092
+ /** Options for the export function */
3093
+ interface ExportOptions {
3094
+ /** Progress callback */
3095
+ onProgress?: ExportProgressCallback;
3096
+ /** Auto-download after export */
3097
+ autoDownload?: boolean;
3098
+ }
3099
+
3100
+ /**
3101
+ * RFC-0101: Export Data Smart Component
3102
+ *
3103
+ * A two-part smart component system for exporting device data
3104
+ * in multiple formats (PDF, XLS, CSV) across different domains
3105
+ * (temperature, water, energy).
3106
+ *
3107
+ * @example
3108
+ * ```typescript
3109
+ * import { buildTemplateExport, myioExportData } from 'myio-js-library';
3110
+ *
3111
+ * // 1. Create configuration template
3112
+ * const config = buildTemplateExport({
3113
+ * domain: 'energy',
3114
+ * formatExport: 'pdf',
3115
+ * typeExport: 'one-device',
3116
+ * });
3117
+ *
3118
+ * // 2. Export data
3119
+ * const exporter = myioExportData(data, config);
3120
+ * await exporter.download();
3121
+ * ```
3122
+ */
3123
+
3124
+ /**
3125
+ * Generates filename based on export config and data
3126
+ */
3127
+ declare function generateFilename(data: ExportDataInput, config: ExportConfigTemplate): string;
3128
+ /**
3129
+ * Calculates statistics from data points
3130
+ */
3131
+ declare function calculateStats(dataPoints: ExportDataPoint[]): ExportStats;
3132
+ /**
3133
+ * Creates an export configuration template
3134
+ *
3135
+ * @param params - Configuration parameters
3136
+ * @returns Export configuration template
3137
+ *
3138
+ * @example
3139
+ * ```typescript
3140
+ * const config = buildTemplateExport({
3141
+ * domain: 'energy',
3142
+ * formatExport: 'pdf',
3143
+ * typeExport: 'one-device',
3144
+ * colorsPallet: { primary: '#ff0000' },
3145
+ * });
3146
+ * ```
3147
+ */
3148
+ declare function buildTemplateExport(params: BuildTemplateExportParams): ExportConfigTemplate;
3149
+ /**
3150
+ * Creates an export instance with the provided data and configuration
3151
+ *
3152
+ * @param data - Data to export
3153
+ * @param config - Export configuration template
3154
+ * @param options - Optional export options
3155
+ * @returns Export data instance
3156
+ *
3157
+ * @example
3158
+ * ```typescript
3159
+ * const exporter = myioExportData(deviceData, config);
3160
+ * await exporter.download();
3161
+ * ```
3162
+ */
3163
+ declare function myioExportData(data: ExportDataInput, config: ExportConfigTemplate, options?: ExportOptions): ExportDataInstance;
3164
+ /** Default colors for exports */
3165
+ declare const EXPORT_DEFAULT_COLORS: Required<ExportColorsPallet>;
3166
+ /** Domain icons */
3167
+ declare const EXPORT_DOMAIN_ICONS: Record<ExportDomain, string>;
3168
+ /** Domain labels */
3169
+ declare const EXPORT_DOMAIN_LABELS: Record<ExportDomain, string>;
3170
+ /** Domain units */
3171
+ declare const EXPORT_DOMAIN_UNITS: Record<ExportDomain, string>;
3172
+
3173
+ export { type BuildTemplateExportParams, CHART_COLORS, DEFAULT_COLORS as CONSUMPTION_CHART_COLORS, DEFAULT_CONFIG as CONSUMPTION_CHART_DEFAULTS, THEME_COLORS as CONSUMPTION_THEME_COLORS, type ChartDomain, type ClampRange, ConnectionStatusType, type Consumption7DaysColors, type Consumption7DaysConfig, type Consumption7DaysData, type Consumption7DaysInstance, type ChartType as ConsumptionChartType, type ConsumptionDataPoint, type IdealRangeConfig as ConsumptionIdealRangeConfig, type ConsumptionModalConfig, type ConsumptionModalInstance, type TemperatureConfig as ConsumptionTemperatureConfig, type TemperatureReferenceLine as ConsumptionTemperatureReferenceLine, type ThemeColors as ConsumptionThemeColors, type ThemeMode as ConsumptionThemeMode, type VizMode as ConsumptionVizMode, type CreateDateRangePickerOptions, type CreateInputDateRangePickerInsideDIVParams, DEFAULT_CLAMP_RANGE, type DateRangeControl, type DateRangeInputController, type DateRangeResult, type DemandModalInstance, type DemandModalParams, type DemandModalPdfConfig, type DemandModalStyles, DeviceStatusType, EXPORT_DEFAULT_COLORS, EXPORT_DOMAIN_ICONS, EXPORT_DOMAIN_LABELS, EXPORT_DOMAIN_UNITS, type EnergyModalContext, type EnergyModalError, type EnergyModalI18n, type EnergyModalStyleOverrides, type ExportColorsPallet, type ExportComparisonData, type ExportConfigTemplate, type ExportCustomerData, type ExportCustomerInfo, type ExportData, type ExportDataInput, type ExportDataInstance, type ExportDataPoint, type ExportDeviceInfo, type ExportDomain, type ExportFormat, type ExportGroupData, type ExportOptions, type ExportProgressCallback, type ExportResult, type ExportStats, type ExportType, type ExportFormat$1 as ModalExportFormat, type ModalHeaderConfig, type ModalHeaderInstance, type ModalTheme, type MyIOAuthConfig, type MyIOAuthInstance, MyIOChartModal, MyIODraggableCard, MyIOSelectionStore, MyIOSelectionStoreClass, MyIOToast, type OpenDashboardPopupEnergyOptions, type OpenDashboardPopupSettingsParams, type OpenDashboardPopupWaterTankOptions, type PersistResult, type RealTimeTelemetryInstance, type RealTimeTelemetryParams, type SettingsError, type SettingsEvent, type ShoppingDataPoint, type StoreRow, type TbScope, type TelemetryFetcher, type TemperatureComparisonModalInstance, type TemperatureComparisonModalParams, type TemperatureDevice, type TemperatureGranularity, type TemperatureModalInstance, type TemperatureModalParams, type TemperatureSettingsInstance, type TemperatureSettingsParams, type TemperatureStats, type TemperatureTelemetry, type ThingsboardCustomerAttrsConfig, type TimedValue, type WaterRow, type WaterTankDataPoint, type WaterTankModalContext, type WaterTankModalError, type WaterTankModalI18n, type WaterTankModalStyleOverrides, type WaterTankTelemetryData, addDetectionContext, addNamespace, aggregateByDay, averageByDay, buildListItemsThingsboardByUniqueDatasource, buildMyioIngestionAuth, buildTemplateExport, buildWaterReportCSV, buildWaterStoresCSV, calcDeltaPercent, calculateDeviceStatus, calculateDeviceStatusWithRanges, calculateStats as calculateExportStats, calculateStats$1 as calculateStats, clampTemperature, classify, classifyWaterLabel, classifyWaterLabels, clearAllAuthCaches, connectionStatusIcons, createConsumption7DaysChart, createConsumptionModal, createDateRangePicker, createInputDateRangePickerInsideDIV, createModalHeader, decodePayload, decodePayloadBase64Xor, detectDeviceType, determineInterval, deviceStatusIcons, exportTemperatureCSV, exportToCSV, exportToCSVAll, extractMyIOCredentials, fetchTemperatureData, fetchThingsboardCustomerAttrsFromStorage, fetchThingsboardCustomerServerScopeAttrs, findValue, findValueWithDefault, fmtPerc$1 as fmtPerc, fmtPerc as fmtPercLegacy, formatAllInSameUnit, formatAllInSameWaterUnit, formatDateForInput, formatDateToYMD, formatDateWithTimezoneOffset, formatDuration, formatEnergy, formatNumberReadable, formatRelativeTime, formatTankHeadFromCm, formatTemperature, formatWater, formatWaterByGroup, formatWaterVolumeM3, formatarDuracao, generateFilename as generateExportFilename, getAuthCacheStats, getAvailableContexts, getConnectionStatusIcon, getDateRangeArray, getDeviceStatusIcon, getDeviceStatusInfo, getModalHeaderStyles, getSaoPauloISOString, getSaoPauloISOStringFixed, getValueByDatakey, getValueByDatakeyLegacy, getWaterCategories, groupByDay, interpolateTemperature, isDeviceOffline, isValidConnectionStatus, isValidDeviceStatus, isWaterCategory, mapConnectionStatus, mapDeviceStatusToCardStatus, mapDeviceToConnectionStatus, myioExportData, normalizeRecipients, numbers, openDashboardPopup, openDashboardPopupAllReport, openDashboardPopupEnergy, openDashboardPopupReport, openDashboardPopupSettings, openDashboardPopupWaterTank, openDemandModal, openGoalsPanel, openRealTimeTelemetryModal, openTemperatureComparisonModal, openTemperatureModal, openTemperatureSettingsModal, parseInputDateToDate, renderCardComponent$2 as renderCardComponent, renderCardComponent$1 as renderCardComponentEnhanced, renderCardComponentHeadOffice, renderCardComponentLegacy, renderCardComponentV2, renderCardComponent as renderCardComponentV5, renderCardComponentV5 as renderCardV5, shouldFlashIcon, strings, timeWindowFromInputYMD, toCSV, toFixedSafe, waterDeviceStatusIcons };