All files / src/components/tek-grid grouped-data-manager.ts

100% Statements 195/195
100% Branches 72/72
100% Functions 52/52
100% Lines 175/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449112x 112x 112x 112x                     112x     148x   148x   148x   148x   148x   148x                     148x       1x       4x           148x     19x     148x 1x     148x 1x             69x 69x   69x       92x 68x   92x 64x                 92x   92x 92x   92x 92x 92x 92x       45x 1x     45x       16x 12x                     99x 99x 8x               8x   8x         6x       181x 165x             94x             66x 66x   66x 66x     66x 1x   66x 1x                 66x   66x 66x 66x 9x 9x 9x     9x 9x     57x 57x             11x 10x   10x             19x 19x 20x 20x   20x 1x 1x     19x 2x 17x 11x 6x 2x 1x 1x 1x   4x 3x     1x       19x             14x 4x     10x 12x 6x                   6x 1x 1x 1x       6x           8x 8x 8x 8x   8x 8x       8x 8x                         8x 1x   8x 8x 8x       20x   20x   18x   18x 4x 4x     14x 14x 14x 14x   14x 14x         13x   9x 9x 9x 5x                 9x   9x 11x           6x   5x           5x               7x 7x 7x 7x   7x 13x 13x 15x 15x 8x 7x   8x   8x 8x 8x       13x 15x     13x   15x     13x     7x 7x   7x 6x           5x 5x       6x       112x       4x       4x 4x 1x 1x     3x   1x 1x       3x   3x   1x      
import { I18n, IDictionary } from '@zeedhi/core';
import debounce from 'lodash.debounce';
import { NonInitializedError } from '../../error/non-initialized';
import { isFilledObject, isNil } from '../../utils';
import {
	IGroupedDataManager,
	ITekGrid,
	ITekGridGroup,
	ITekGridGroupFooter,
	ITekGridGroupHeader,
	ITekGridSummary,
} from './interfaces';
import { TekGridColumn } from './tek-grid-column';
 
export class GroupedDataManager implements IGroupedDataManager {
	protected grid: ITekGrid;
 
	public summaryColumns: TekGridColumn[] = [];
 
	private groups: ITekGridGroup[] = [];
 
	private summary: IDictionary<ITekGridSummary> = {};
 
	private groupedData: IDictionary<any>[] = [];
 
	private groupColumnNames: string[] = [];
 
	private groupColumns: TekGridColumn[] = [];
 
	private originalDatasourceLoadAll?: boolean;
 
	private originalDatasourceLimit?: number;
 
	private viewUpdateScrollData?: () => void;
 
	private viewUpdateFixedColumns?: () => void;
 
	constructor(grid: ITekGrid) {
		this.grid = grid;
	}
 
	setViewUpdateFixedColumns(fn: () => void) {
		this.viewUpdateFixedColumns = fn;
	}
 
	setViewUpdateScrollData(fn: () => void) {
		this.viewUpdateScrollData = fn;
	}
 
	/**
	 * Tasks that should be finished before loading the grid data
	 */
	private tasksBeforeLoad: Promise<any>[] = [];
 
	public registerTask(task: Promise<any>) {
		this.tasksBeforeLoad.push(task);
	}
 
	private request: () => void = () => {
		throw new NonInitializedError(this.constructor.name);
	};
 
	private debounceUpdateGrouping: (lazyLoad?: boolean) => void = () => {
		throw new NonInitializedError(this.constructor.name);
	};
 
	/**
	 * Loads grid data after resolving all tasks
	 */
	public async loadAfterTasks() {
		Promise.all(this.tasksBeforeLoad.map((promise) => promise.catch(() => undefined)));
		this.tasksBeforeLoad = [];
 
		return this.request();
	}
 
	private initializeDebounceFunctions() {
		this.request = debounce(() => {
			this.grid.reload();
		}, 500);
		this.debounceUpdateGrouping = debounce((lazyLoad = false) => {
			this.updateGroupedData(lazyLoad);
		}, 100);
	}
 
	/**
	 * Initializes grid groups, summary columns and registers the grid datasource callback
	 * @param lazyLoad defines if the grid should automatically load data after updating the datasource
	 */
	initializeGrouping(lazyLoad: boolean): void {
		this.initializeDebounceFunctions();
 
		this.initGroups();
		this.initSummaryColumns();
 
		this.originalDatasourceLoadAll = this.grid.datasource.loadAll;
		this.originalDatasourceLimit = this.grid.datasource.limit;
		this.grid.datasource.registerGetCallback((data) => this.onGet(data));
		this.updateGrouping(lazyLoad);
	}
 
	private onGet(data: IDictionary) {
		if (this.isGrouped()) {
			this.buildGroupedData();
		}
 
		return data;
	}
 
	private resetFooterVariables(group: ITekGridGroup) {
		this.summaryColumns.forEach((column) => {
			group.footer[column.name] = {
				count: 0,
				sum: undefined,
				avg: undefined,
				min: undefined,
				max: undefined,
			};
		});
	}
 
	private initGroups() {
		this.groups = [];
		this.groupColumns.forEach((column) => {
			const newGroup = {
				column,
				name: column.name,
				label: column.label,
				lastValue: undefined,
				initialized: false,
				footer: {},
			};
			this.resetFooterVariables(newGroup);
 
			this.groups.push(newGroup);
		});
	}
 
	getGroupedData(): IDictionary<any>[] {
		return this.groupedData;
	}
 
	private initSummaryColumns() {
		this.summaryColumns = this.grid.columns.filter((column) => !!column.aggregation && !column.grouped);
		this.summary = {};
	}
 
	/**
	 * Calls updateGroupedData with debounce
	 */
	public updateGrouping(lazyLoad?: boolean) {
		this.debounceUpdateGrouping(lazyLoad);
	}
 
	/**
	 * Inits summary columns, updates the grid datasource and, if needed, reloads the grid data
	 */
	async updateGroupedData(lazyLoad: boolean): Promise<void> {
		this.initSummaryColumns();
		this.updateGridDatasource();
 
		if (!lazyLoad) {
			await this.loadAfterTasks();
		}
 
		if (this.grid.virtualScroll && this.viewUpdateScrollData) {
			this.viewUpdateScrollData();
		}
		if (this.viewUpdateFixedColumns) {
			this.viewUpdateFixedColumns();
		}
	}
 
	/**
	 * When using groups, should update the grid datasource order to reflect the group order
	 * If the grid is not grouped, should not update the datasource order
	 */
	private updateGridDatasource() {
		this.groupedData = [];
 
		this.groupColumns = this.grid.columns.filter((column) => column.grouped);
		this.groupColumnNames = this.groupColumns.map((column) => column.name);
		if (this.isGrouped()) {
			if (this.groupColumns.length) {
				const order = this.getOrder(this.groupColumnNames, this.grid.datasource.order);
				this.grid.datasource.order = order;
			}
 
			this.grid.datasource.loadAll = true;
			return;
		}
 
		this.grid.datasource.loadAll = this.originalDatasourceLoadAll!;
		this.grid.datasource.limit = this.originalDatasourceLimit!;
	}
 
	/**
	 * Returns the order to be used in the grid datasource based on the group column names and the grid order
	 */
	private getOrder(groupColumnNames: string[], gridOrder: string[]): string[] {
		const groupOrderColumns = groupColumnNames.map((column) => `${column}.asc`);
		const otherOrderColumns = gridOrder.filter((column) => groupColumnNames.indexOf(column.split('.')[0]) === -1);
 
		return [...groupOrderColumns, ...otherOrderColumns];
	}
 
	/**
	 * Returns the summary data for the group
	 */
	public getSummaryData(group: IDictionary<ITekGridSummary>) {
		const summaryData: IDictionary = {};
		this.summaryColumns.forEach((column) => {
			const { aggregation } = column;
			const currentGroup = group[column.name];
 
			if (!currentGroup) {
				summaryData[column.name] = 0;
				return;
			}
 
			if (aggregation === 'COUNT') {
				summaryData[column.name] = currentGroup.count;
			} else if (aggregation === 'SUM') {
				summaryData[column.name] = currentGroup.sum;
			} else if (aggregation === 'AVG') {
				if (currentGroup.avg) {
					summaryData[column.name] = currentGroup.avg;
				} else if (typeof currentGroup.sum === 'number') {
					summaryData[column.name] = currentGroup.sum / currentGroup.count;
				}
			} else if (aggregation === 'MIN') {
				summaryData[column.name] = currentGroup.min;
			} else {
				// if (aggregation === 'MAX') {
				summaryData[column.name] = currentGroup.max;
			}
		});
 
		return summaryData;
	}
 
	/**
	 * Adds group footers to the grouped data
	 */
	private addGroupFooters(groupIndex: number) {
		if (this.summaryColumns.length === 0) {
			return;
		}
 
		for (let i = this.groups.length - 1; i >= groupIndex; i -= 1) {
			if (this.groups[i].initialized) {
				const groupFooterRow: ITekGridGroupFooter = {
					groupFooter: true,
					groupIndex: i,
					groupHeaders: [],
					groupLabel: this.groups[i].lastGroupHeaderRow!.groupLabel,
					groupValue: this.groups[i].lastGroupHeaderRow!.groupValue,
					...this.getSummaryData(this.groups[i].footer),
				};
 
				// add header for outer groups
				for (let g = 0; g < i; g += 1) {
					const { lastGroupHeaderRow } = this.groups[g];
					if (lastGroupHeaderRow) {
						groupFooterRow.groupHeaders.push(lastGroupHeaderRow);
					}
				}
 
				this.groupedData.push(groupFooterRow);
			}
		}
	}
 
	private getGroupValue(group: IDictionary<any>, row: IDictionary<any>) {
		const groupColumn = this.grid.getColumn(group.column.name);
		const cellsApplied = this.grid.getAppliedConditions({ row, column: groupColumn });
		if (!isFilledObject(cellsApplied)) {
			this.grid.reapplyConditions(row);
		}
		const groupValue = groupColumn.formatterByRow(row, cellsApplied);
		return groupValue;
	}
 
	private addGroupHeader(row: IDictionary, group: ITekGridGroup, index: number) {
		const groupValue = this.getGroupValue(group, row) || group.column.groupLabelForEmptyValue;
		const groupHeaderRow: ITekGridGroupHeader = {
			group: true,
			groupRow: row,
			groupColumnName: group.column.name,
			groupHeader: true,
			groupIndex: index,
			groupLabel: I18n.translate(group.label),
			groupValue,
			groupOpened: group.column.groupOpened || this.grid.groupsOpened,
			groupHeaders: [],
			children: [],
		};
		// add header for outer groups to the added row
		for (let i = 0; i < index; i += 1) {
			groupHeaderRow.groupHeaders.push(this.groups[i].lastGroupHeaderRow!);
		}
		group.lastGroupHeaderRow = groupHeaderRow;
		group.initialized = true;
		this.groupedData.push(groupHeaderRow);
	}
 
	private calcSummaryValues(column: TekGridColumn, summary: ITekGridSummary, row: IDictionary) {
		const rowValue = row[column.name];
 
		if (isNil(rowValue)) return;
 
		summary.count += 1;
 
		if (this.grid.events.calcSummary) {
			this.grid.calcSummary(column, summary, row);
			return;
		}
 
		if (summary.min === undefined) summary.min = rowValue;
		if (summary.max === undefined) summary.max = rowValue;
		summary.min = rowValue < summary.min ? rowValue : summary.min;
		summary.max = rowValue > summary.max ? rowValue : summary.max;
 
		if (typeof rowValue === 'number') {
			summary.sum = (summary.sum || 0) + rowValue;
		}
	}
 
	private calcSummary(row: IDictionary<any>) {
		if (this.summaryColumns.length === 0) return;
 
		this.summaryColumns.forEach((column) => {
			const columnName = column.name;
			if (isNil(this.summary[columnName])) {
				this.summary[columnName] = {
					count: 0,
					sum: undefined,
					avg: undefined,
					min: undefined,
					max: undefined,
				};
			}
 
			this.calcSummaryValues(column, this.summary[columnName], row);
 
			this.groups.forEach((group) => {
				this.calcSummaryValues(column, group.footer[columnName], row);
			});
		});
	}
 
	private addSummary() {
		if (this.summaryColumns.length === 0) return;
 
		const summaryRow = {
			groupFooter: true,
			groupSummary: true,
			...this.getSummaryData(this.summary),
		};
 
		this.groupedData.push(summaryRow);
	}
 
	/**
	 * It takes a flat array of data and groups it by the group columns specified in
	 * the grid.
	 */
	buildGroupedData(): void {
		this.initGroups();
		this.initSummaryColumns();
		this.groupedData = [];
		const data = this.grid.getData();
 
		data.forEach((row) => {
			let groupBreak = false;
			this.groups.forEach((group, index) => {
				const groupValue = row[group.name];
				if (group.lastValue !== groupValue || groupBreak) {
					if (!groupBreak) {
						this.addGroupFooters(index);
					}
					group.lastValue = groupValue;
 
					this.resetFooterVariables(group);
					this.addGroupHeader(row, group, index);
					groupBreak = true;
				}
			});
 
			this.groups.forEach((group) => {
				group.lastGroupHeaderRow!.children.push(row);
			});
 
			this.groupedData.push({
				...row,
				groupHeaders: this.groups.map((group) => group.lastGroupHeaderRow).filter(Boolean),
			});
 
			this.calcSummary(row);
		});
 
		if (this.groupedData.length > 0) {
			this.addGroupFooters(0);
 
			if (this.grid.showSummaryTotal) {
				this.addSummary();
			}
		}
	}
 
	openGroup(group: IDictionary<any>): void {
		group.groupOpened = !group.groupOpened;
		if (this.grid.virtualScroll && this.viewUpdateScrollData) this.viewUpdateScrollData();
	}
 
	isItemVisible(row: IDictionary<any>) {
		return !row.groupHeaders || !row.groupHeaders.length || row.groupHeaders.every((group: any) => group.groupOpened);
	}
 
	isGrouped(): boolean {
		return !!this.groupColumnNames.length || (this.grid.showSummaryTotal && !!this.summaryColumns.length);
	}
 
	isColumnSearchable(column: TekGridColumn): boolean {
		return !this.grid.searchVisibleOnly || column.isVisible || column.grouped;
	}
 
	directionalLeft(): void {
		const { currentRow } = this.grid.datasource;
		if (currentRow.group && currentRow.groupOpened) {
			currentRow.groupOpened = false;
			return;
		}
 
		if (this.grid.cellSelection || !currentRow.groupHeaders?.length) return;
 
		const newCurrentRow = currentRow.groupHeaders[currentRow.groupHeaders.length - 1];
		this.grid.setCurrentRow(newCurrentRow);
	}
 
	directionalRight(): void {
		const { currentRow } = this.grid.datasource;
 
		if (!currentRow.group || currentRow.groupOpened) return;
 
		currentRow.groupOpened = true;
	}
}