UNPKG

@c8y/ngx-components

Version:

Angular modules for Cumulocity IoT applications

666 lines (658 loc) 28.7 kB
import * as packages_client_lib from 'packages/client/lib'; import * as i0 from '@angular/core'; import { OnInit, OnDestroy, TemplateRef, PipeTransform, OnChanges, EventEmitter } from '@angular/core'; import { GlobalAutoRefreshWidgetConfig, OnBeforeSave, AggregationOption, DynamicComponentAlertAggregator, AlertService, DashboardChildComponent, ColorRangeBoundaries } from '@c8y/ngx-components'; import { WidgetConfigService, ContextDashboardComponent } from '@c8y/ngx-components/context-dashboard'; import { KPIDetails, DatapointSelectorModalOptions, DatapointAttributesFormConfig } from '@c8y/ngx-components/datapoint-selector'; import { GlobalContextState, AggregationOptionStatus, PresetName, GLOBAL_CONTEXT_DISPLAY_MODE, WidgetConfigMigrationService } from '@c8y/ngx-components/global-context'; import { Observable, BehaviorSubject } from 'rxjs'; import { ISeries, IFetchResponse } from '@c8y/client'; import { TimeStamp, MinMaxValues, SourceId, DataFetchingService, DatapointsValuesDataMap, ExportConfig } from '@c8y/ngx-components/datapoints-export-selector'; import { Interval } from '@c8y/ngx-components/interval-picker'; import { TranslateService } from '@ngx-translate/core'; declare const DEFAULT_DPT_REFRESH_INTERVAL_VALUE = 30000; type DatapointTableMapKey = `${TimeStamp}_${DeviceName}`; /** * Represents a mapping where the key is a datapoint identifier containing the date and device name, and the value is an array of data point table items or null. */ type DataPointsTableMap = Map<DatapointTableMapKey, (DatapointTableItem | null)[]>; type DeviceName = string; /** * Represents a map of datapoints series data. * The key of the map is a source, and the value is the data for requested series. */ type DatapointsSeriesDataMap = Map<SourceId, ISeries>; /** * Determines which values will be displayed as values for datapoints. * e.g. if user chose 'min', only the minimum values will be displayed. */ type RenderType = keyof typeof RENDER_TYPES_LABELS; /** * Represents an object where key is a timestamp and value is an array * where first record contains min and max values for a corresponding timestamp. */ type MeasurementRanges = { [key: TimeStamp]: Array<MinMaxValues>; }; /** * Represents a value object where key is an object with min and max properties with its corresponding values. */ type Value = { [key in keyof MinMaxValues]: number; }; /** * Represents the legacy's global time context date selection of the widget. */ declare const DATE_SELECTION_VALUES: { readonly dashboard_context: "dashboard_context"; readonly config: "config"; readonly view_and_config: "view_and_config"; }; declare const DATE_SELECTION_VALUES_ARR: readonly ["dashboard_context", "config", "view_and_config"]; declare const DATE_SELECTION_LABELS: { readonly config: "Widget configuration"; readonly view_and_config: "Widget and widget configuration"; readonly dashboard_context: "Dashboard time range"; }; declare const REFRESH_INTERVAL_VALUES_ARR: number[]; declare const RENDER_TYPES_LABELS: { readonly min: "Minimum"; readonly max: "Maximum"; readonly area: "Area"; }; declare const INTERVAL_VALUES_ARR: readonly ["minutes", "hours", "days", "weeks", "months", "custom"]; declare const TIME_RANGE_INTERVAL_LABELS: { readonly minutes: "Last minute"; readonly hours: "Last hour"; readonly days: "Last day"; readonly weeks: "Last week"; readonly months: "Last month"; readonly custom: "Custom"; }; declare const DURATION_OPTIONS: ({ id: "minutes"; label: "Last minute"; unit: "minutes"; amount: number; } | { id: "hours"; label: "Last hour"; unit: "hours"; amount: number; } | { id: "days"; label: "Last day"; unit: "days"; amount: number; } | { id: "weeks"; label: "Last week"; unit: "weeks"; amount: number; } | { id: "months"; label: "Last month"; unit: "months"; amount: number; } | { id: "custom"; label: "Custom"; unit?: undefined; amount?: undefined; })[]; interface DatapointWithValues extends KPIDetails { seriesUnit?: string; values: MeasurementRanges; } interface Duration { id: string; label: string; unit?: string; amount?: number; } interface TableColumnHeader { deviceName: string; label: string; renderType: string; unit: string; } interface DateRange { dateFrom: string; dateTo: string; } interface DatapointsTableConfig extends Partial<GlobalContextState>, LegacyGlobalTimeContextProperties { context?: number; datapoints: KPIDetails[]; decimalPlaces?: number; interval: Interval['id']; realtime: boolean; selected?: object | null; sliderChange?: boolean | null; } interface LegacyGlobalTimeContextProperties extends GlobalAutoRefreshWidgetConfig { /** * Array that contains global time context dateFrom and dateTo. */ date?: string[]; dateFrom: string; dateTo: string; displayDateSelection: boolean; displaySettings: { globalTimeContext: boolean; globalRealtimeContext: boolean; globalAggregationContext: boolean; globalAutoRefreshContext: boolean; }; widgetInstanceGlobalTimeContext?: boolean | null; globalDateSelector?: keyof typeof DATE_SELECTION_VALUES; } interface DatapointTableItem { dateAndTime: string; deviceName: string; fragment: string; label: string; redRangeMax?: number; redRangeMin?: number; renderType: string; series: string; value: Value; yellowRangeMax?: number; yellowRangeMin?: number; } interface GroupedDatapointTableItem { dateAndTime: string; deviceName: string; rowItems: ({ fragment: string; label: string; redRangeMax?: number; redRangeMin?: number; renderType: string; series: string; value: Value; yellowRangeMax?: number; yellowRangeMin?: number; } | null)[]; } interface SeriesDataWithResponse { source: SourceId; data: ISeries; res: IFetchResponse; } declare class DatapointsTableWidgetConfigComponent implements OnInit, OnBeforeSave, OnDestroy { private readonly destroyRef; private readonly formBuilder; private readonly parentForm; private readonly widgetConfig; readonly widgetConfigService: WidgetConfigService; set previewMapSet(template: TemplateRef<any>); config: DatapointsTableConfig; readonly AGGREGATION_LABELS: { readonly NONE: string; readonly MINUTELY: string; readonly HOURLY: string; readonly DAILY: string; }; readonly DATE_SELECTION_LABELS: { readonly config: "Widget configuration"; readonly view_and_config: "Widget and widget configuration"; readonly dashboard_context: "Dashboard time range"; }; readonly DEFAULT_DATE_SELECTOR_VALUE: "dashboard_context"; readonly DEFAULT_INTERVAL_VALUE: "hours"; readonly TIME_RANGE_INTERVAL_LABELS: { readonly minutes: "Last minute"; readonly hours: "Last hour"; readonly days: "Last day"; readonly weeks: "Last week"; readonly months: "Last month"; readonly custom: "Custom"; }; readonly AGGREGATION_VALUES_ARR: readonly ["NONE", packages_client_lib.aggregationType.MINUTELY, packages_client_lib.aggregationType.HOURLY, packages_client_lib.aggregationType.DAILY]; readonly DATE_SELECTION_VALUES_ARR: readonly ["dashboard_context", "config", "view_and_config"]; readonly INTERVAL_VALUES_ARR: readonly ["minutes", "hours", "days", "weeks", "months", "custom"]; readonly REFRESH_INTERVAL_VALUES_ARR: number[]; datapointSelectionConfig: Partial<DatapointSelectorModalOptions>; disabledAggregationOptions: AggregationOptionStatus; defaultFormOptions: Partial<DatapointAttributesFormConfig>; formGroup: ReturnType<DatapointsTableWidgetConfigComponent['createForm']>; widgetControls: "dataTable"; /** * Debounced config for preview to prevent multiple series requests on initial load. * Uses auditTime to batch rapid emissions (e.g., from initConfig + GlobalContext processing). * Without it the preview may request data multiple times unnecessarily. */ previewConfig$: Observable<DatapointsTableConfig>; private DATAPOINTS_TABLE_CONTROL_NAME; ngOnInit(): void; ngOnDestroy(): void; onBeforeSave(config?: DatapointsTableConfig): boolean; private initForm; private subscribeToFormChanges; private createForm; static ɵfac: i0.ɵɵFactoryDeclaration<DatapointsTableWidgetConfigComponent, never>; static ɵcmp: i0.ɵɵComponentDeclaration<DatapointsTableWidgetConfigComponent, "c8y-datapoints-table-view-config", never, { "config": { "alias": "config"; "required": false; }; }, {}, never, never, true, never>; } /** * A pipe that adjusts the aggregated time range based on the aggregation type. * * ```html * '9:00' | adjustAggregatedTimeRange: config.aggregation (e.g.:HOURLY) * ``` * The output will be '9:00-10:00'. */ declare class AdjustAggregatedTimeRangePipe implements PipeTransform { /** * Transforms the input time based on the aggregation type. * @param inputTime The input time string. * @param aggregationType The type of aggregation (optional). * @returns The transformed time string. */ transform(inputTime: string, aggregationType?: AggregationOption): string; /** * Creates a date object from the input time string. * @param inputTime The input time string. * @returns The created Date object. */ private createDateFromInput; /** * Validates if the time string matches the required format and has valid values. * @param time The time string to validate. * @param originalInput The original input string (including AM/PM if present). * @throws Error if the time format is invalid or values are out of range. */ private validateTimeFormat; private validateTimeParts; private validateTimeDigits; private parseTimeComponents; private validateTimeRanges; private validateTimeFormat24Hour; /** * Checks if string contains only digits and is 1-2 characters long. * @param value String to check * @returns boolean indicating if string is valid */ private isValidNumberString; /** * Checks if the input time has AM/PM markers. * @param input The input time string to check. * @returns boolean indicating if the input contains AM/PM. */ private hasAmPm; /** * Adjusts the date for PM times by adding 12 hours when necessary. * @param date The date object to adjust. * @param isPM Boolean indicating if the time is PM. * @returns The adjusted Date object. */ private adjustForPMTime; /** * Checks if the input time is in twelve hours format. * @param inputTime The input time string. * @returns True if the input time is in twelve hours format, false otherwise. */ private isTwelveHoursFormat; /** * Gets the hourly time range for the given date. * @param date The date object. * @param twelveHoursFormat Indicates whether to use twelve hours format. * @returns The hourly time range string. */ private getHourlyTimeRange; /** * Gets the minutely time range for the given date. * @param date The date object. * @param twelveHoursFormat Indicates whether to use twelve hours format. * @returns The minutely time range string. */ private getMinutelyTimeRange; /** * Formats the given date into a time string. * @param date The date to format. * @param usePeriod Indicates whether to include the period (AM/PM) in the formatted time. * @param useHourOnly Indicates whether to include only the hour part in the formatted time. * @returns The formatted time string. */ private formatTime; static ɵfac: i0.ɵɵFactoryDeclaration<AdjustAggregatedTimeRangePipe, never>; static ɵpipe: i0.ɵɵPipeDeclaration<AdjustAggregatedTimeRangePipe, "adjustAggregatedTimeRange", true>; } declare class DatapointsTableViewService { private dataFetchingService; constructor(dataFetchingService: DataFetchingService); /** * Filters out inactive data points from the given array. * * @param datapoints - The array of data points to filter. * @returns An array of data points that are active. */ filterOutInactiveDatapoints(datapoints: KPIDetails[]): KPIDetails[]; hasMultipleDatapoints(datapoints: KPIDetails[]): boolean; /** * Returns a map of active data points device IDs with their corresponding series. * * Example output: * ```typescript * new Map([ * [ * "844657202", * [ * "c8y_Temperature.T" * ] * ], * [ * "32666427", * [ * "c8y_Battery.Battery" * ] * ] * ]); * ``` * @param datapoints - An array of data points. * @returns A map where the key is the data point ID and the value is an array of data point series. */ groupSeriesByDeviceId(activeDatapoints: KPIDetails[]): DatapointsValuesDataMap; /** * Retrieves the active data points series data and returns it as a map. * * @param datapointsValuesDataMap - A map of data point sources with their associated series. * @param config - The configuration of the data points table. * @param roundSeconds - Whether to round the seconds or not. * If true, the seconds will be rounded to 0. * If false, the seconds will be displayed as they are. * @returns A Promise that resolves to a Map object with data point IDs as keys and DataObject as values or undefined when all series has forbidden access. */ getAllActiveSeriesDataMap(datapointsValuesDataMap: DatapointsValuesDataMap, config: DatapointsTableConfig, roundSeconds: boolean): Promise<Map<string | number, ISeries>>; /** * Creates an array of DatapointsWithValues based on the provided datapoints and datapointsSeriesDataMap. * * Finds an index of a current data point within series object and based on that index filters values array. * * @param datapoints - An array of data points. * @param datapointsSeriesDataMap - A map containing series data for data points. * @returns An array of DatapointsWithValues. */ getDatapointsWithValues(datapoints: KPIDetails[], datapointsSeriesDataMap: DatapointsSeriesDataMap): DatapointWithValues[]; /** * Creates the column headers for the devices in the data points table. * * @param datapointsWithValues - An array of data points. * @returns An array of column headers for the devices. */ getColumnHeaders(datapointsWithValues: KPIDetails[]): TableColumnHeader[]; mapDatapointsWithValuesToList(datapointsWithValues: DatapointWithValues[]): DatapointTableItem[]; /** * Finds the overall minimum and maximum values from an array of objects containing 'min' and 'max' properties. * * If the array contains only one object, that object's 'min' and 'max' values will be returned. * * @param valuesArray - An array with objects, where each contains 'min' and 'max' properties. * @returns An object with the smallest 'min' and largest 'max' values found in the array. * * @example * const values = [ * { min: 1, max: 10 } * ]; * * const result = findMinMaxValues(values); * // result is { min: 1, max: 10 } */ findMinMaxValues(valuesArray: MinMaxValues[]): Value | null; /** * Groups a list of data points by date and device, based on given references. * * @param dataList - The list of data points to be grouped. * @param references - The column headers that serve as references for grouping. * @returns An array of grouped data points, where each group corresponds to a unique date and device. */ groupByDateAndDevice(dataList: DatapointTableItem[], references: TableColumnHeader[]): GroupedDatapointTableItem[]; /** * Generates and populates a map with data points. * * This function processes the provided data points and organizes them into a map structure * where each key is a unique combination of date and device identifiers, and the value is an * array of data points (or null values) associated with that key. This structured data is then * used in the data point table to render the data appropriately. * * @param dataList - The list of data point table items to be processed. * @param columnsHeadersReferences - The list of column headers used to determine the order and structure of the map values. * @returns A map where the key is a datapoint identifier containing the date and device name, and the value is an array of data point table items or null. */ generateDataPointMap(dataList: DatapointTableItem[], columnsHeadersReferences: TableColumnHeader[]): DataPointsTableMap; /** * Merges the data points from the given map into an array of grouped data point table items. * * @param map - The map containing the data points to be merged. * @returns An array of grouped data point table items. */ mergeDatapoints(map: DataPointsTableMap): GroupedDatapointTableItem[]; sortDataByDateDescending(data: GroupedDatapointTableItem[]): GroupedDatapointTableItem[]; /** * Prepares the updated time range based on the selected interval. * * In case of a 'custom' interval or no quantity, the original date range is returned. * * @param interval - The selected interval type. * @returns An object containing the `dateFrom` and `dateTo` in ISO string format. */ prepareTimeRange(interval: Interval['id'], dateFromInput: string, dateToInput: string): { dateFrom: string; dateTo: string; }; /** * Subtracts an amount of time from a given date. * * @param date - The original date. * @param amount - The amount of time units to subtract. * @param unit - The unit of time to subtract (e.g., minutes, hours, days, weeks, months). * @returns A new date with the specified time subtracted. */ subtractTime(date: Date, amount: number, unit: string): Date; getSeriesWithoutPermissionToRead(activeDatapointsSeriesData: Map<string | number, ISeries> | undefined, activeDatapointsIdsWithSeries: DatapointsValuesDataMap): { key: SourceId; value: string[]; }[]; hasSecondsAndMillisecondsEqualZero(timeString: string): boolean; /** * Converts a date string to ISO format. * * @param dateStr - The date string to convert. * @returns The ISO format of the given date string. */ private toISOFormat; private filterOutElementsWithForbiddenResponses; private subtractMonthsAndAdjustDay; /** * Calculates the target month number (0-11) after subtracting months from the current month. * Handles negative month numbers by normalizing them to the valid 0-11 range. * * Examples: * - January(0) - 1 month = December(11) * - March(2) - 4 months = November(10) * - December(11) - 1 month = November(10) * * @param currentMonth - Current month (0-11, where 0 is January) * @param monthsToSubtract - Number of months to subtract * @returns Normalized month number in range 0-11 */ private calculateTargetMonth; /** * Sets the date to the last day of the previous month. * Using 0 as dateValue makes JavaScript automatically calculate * last day of previous month, per JavaScript Date API behavior. * @param date - Date to modify */ private setToLastDayOfPreviousMonth; static ɵfac: i0.ɵɵFactoryDeclaration<DatapointsTableViewService, never>; static ɵprov: i0.ɵɵInjectableDeclaration<DatapointsTableViewService>; } declare class DatapointsTableViewWidgetComponent implements OnInit, OnDestroy { private alertService; private dashboardChild; private datapointsTableViewService; private translateService; private dashboardContextComponent; private widgetConfigMigrationService; /** * Data points table widget config. */ config: DatapointsTableConfig; /** * Indicates whether the component is in widget preview mode. * If true, the table will be displayed without the export selector button. */ isInPreviewMode: boolean; alerts: DynamicComponentAlertAggregator; /** * Represents the data points where __active property is set to true. */ activeDatapoints: KPIDetails[]; /** * Represents the custom CSS style for the export selector component. */ containerClass: string; /** * An array of objects representing datapoints with their corresponding values. * Used to populate the CSV/Excel file with data. */ datapointsWithValues: DatapointWithValues[]; /** * An array of `GroupedDatapointTableItem` objects representing the datapoints table items. * Used to populate the table with data. */ datapointsTableItems: GroupedDatapointTableItem[]; devicesColumnHeaders: TableColumnHeader[]; /** * Represents a configuration options used by a c8y-datapoints-export-selector. */ exportConfig: ExportConfig; /** * Indicates whether there is more than one data point. * If is true, then a column 'Device' will be displayed in the table. */ hasMultipleDatapoints: boolean; /** * Indicates whether refreshing should be enabled or disabled. * It's 'true' when user is not allowed to view a measurements. */ isRefreshDisabled: boolean; /** * Indicates whether the component is in the initial request state * where data for a table structure is being prepared. */ isInitialRequest: boolean; /** * Current isLoading state. Indicates whether the data is being loaded. */ isLoading$: BehaviorSubject<boolean>; isScrolling: i0.WritableSignal<boolean>; seriesWithoutPermissionToRead: { key: SourceId; value: string[]; }[]; hasAnyActiveDatapoint: boolean; displayMode: i0.WritableSignal<"config" | "view_and_config" | "dashboard">; contextConfig: i0.WritableSignal<GlobalContextState>; isLinkedToGlobal: i0.WritableSignal<boolean>; widgetControls: i0.WritableSignal<PresetName>; readonly GLOBAL_CONTEXT_DISPLAY_MODE: typeof GLOBAL_CONTEXT_DISPLAY_MODE; private TIMEOUT_ERROR_TEXT; private SERVER_ERROR_TEXT; private destroy$; private scrollingSubject$; private subscription; private isFailedToFetchSeriesData; /** * Indicates if the alert has already been displayed and can be dismissed. * The message is only displayed when a component is initialized. */ private isMissingAnyPermissionAlertShown; constructor(alertService: AlertService, dashboardChild: DashboardChildComponent, datapointsTableViewService: DatapointsTableViewService, translateService: TranslateService, dashboardContextComponent: ContextDashboardComponent, widgetConfigMigrationService: WidgetConfigMigrationService); ngOnInit(): Promise<void>; ngOnChanges(): Promise<void>; ngOnDestroy(): void; onContextChange(event: { context: GlobalContextState; diff: GlobalContextState; }): void; onRefresh(): void; onExportModalOpen(isOpened: boolean): Promise<void>; onScrolling(isScrolling: boolean): void; /** * Sets up the scrolling subscription. * * Ensures similar UX as in the alarms countdown-pause logic. */ private setScrollingSubscription; /** * Prepares the table data by: * - filtering out inactive data points, * - checking if there are multiple devices as a source of data points, * - getting the column headers for devices, * - getting the series data for active data points (API call), * - preparing data points with values list, * - mapping data points with values to list items, * - grouping data points by date and device, * - sorting data by date descending. * * @param roundSeconds - Whether to round the seconds or not. * If true, the seconds will be rounded to 0. * If false, the seconds will be displayed as they are. */ private prepareTableData; /** * Retrieves the active data points series data and returns it as a map. * * It's a wrapper method with try-catch block. * * @param datapointsIdsWithSeries - A map of data point IDs with their associated series. * @param config - The configuration of the data points table. * @param roundSeconds - Whether to round the seconds or not. * If true, the seconds will be rounded to 0. * If false, the seconds will be displayed as they are. * @returns A Promise that resolves to a Map object with data point IDs as keys and DataObject as values. */ private getActiveDatapointsSeriesDataMap; private handleFetchError; private handleMissingAnyPermissionErrorMessage; private getMissingPermissionsMessage; private updateExportConfig; private checkIfHasAnyActiveDatapoint; private assignContextFromContextDashboard; static ɵfac: i0.ɵɵFactoryDeclaration<DatapointsTableViewWidgetComponent, [null, { optional: true; }, null, null, { optional: true; }, null]>; static ɵcmp: i0.ɵɵComponentDeclaration<DatapointsTableViewWidgetComponent, "c8y-datapoints-table-view", never, { "config": { "alias": "config"; "required": false; }; "isInPreviewMode": { "alias": "isInPreviewMode"; "required": false; }; }, {}, never, never, true, never>; } declare class DatapointsTableComponent implements OnChanges { aggregationType: AggregationOption; datapointsTableItems: GroupedDatapointTableItem[]; devicesColumnHeaders: TableColumnHeader[]; decimalPlaces: number; hasMultipleDatapoints: boolean; isLoading: boolean; seriesWithoutPermissionToReadCount: number; isScrolling: EventEmitter<boolean>; hasNoPermissionsToReadAnyMeasurement: boolean; missingAllPermissionsAlert: DynamicComponentAlertAggregator; /** * Default fraction size format for numbers with decimal places. */ private fractionSize; ngOnChanges(): void; onListScrolled(): void; onListScrolledToTop(): void; getRangeValues(row: KPIDetails): ColorRangeBoundaries; /** * Determines the fraction size format based on whether the number is an integer or has decimal places. * * @param value - The number to be formatted. * @returns Returns '1.0-0' if the number is an integer, otherwise returns the current fraction size. */ getFractionSize(value: number): string; private handleNoPermissionErrorMessage; private showMessageForMissingPermissionsForAllSeries; static ɵfac: i0.ɵɵFactoryDeclaration<DatapointsTableComponent, never>; static ɵcmp: i0.ɵɵComponentDeclaration<DatapointsTableComponent, "c8y-datapoints-table", never, { "aggregationType": { "alias": "aggregationType"; "required": false; }; "datapointsTableItems": { "alias": "datapointsTableItems"; "required": false; }; "devicesColumnHeaders": { "alias": "devicesColumnHeaders"; "required": false; }; "decimalPlaces": { "alias": "decimalPlaces"; "required": false; }; "hasMultipleDatapoints": { "alias": "hasMultipleDatapoints"; "required": false; }; "isLoading": { "alias": "isLoading"; "required": false; }; "seriesWithoutPermissionToReadCount": { "alias": "seriesWithoutPermissionToReadCount"; "required": false; }; }, { "isScrolling": "isScrolling"; }, never, never, true, never>; } export { AdjustAggregatedTimeRangePipe, DATE_SELECTION_LABELS, DATE_SELECTION_VALUES, DATE_SELECTION_VALUES_ARR, DEFAULT_DPT_REFRESH_INTERVAL_VALUE, DURATION_OPTIONS, DatapointsTableComponent, DatapointsTableViewService, DatapointsTableViewWidgetComponent, DatapointsTableWidgetConfigComponent, INTERVAL_VALUES_ARR, REFRESH_INTERVAL_VALUES_ARR, RENDER_TYPES_LABELS, TIME_RANGE_INTERVAL_LABELS }; export type { DataPointsTableMap, DatapointTableItem, DatapointTableMapKey, DatapointWithValues, DatapointsSeriesDataMap, DatapointsTableConfig, DateRange, Duration, GroupedDatapointTableItem, MeasurementRanges, RenderType, SeriesDataWithResponse, TableColumnHeader, Value }; //# sourceMappingURL=index.d.ts.map