import { countBy , groupBy , mapValues , max , min , values } from 'lodash' ; import { getPastDays } from './get_past_days' ; import type { SavedObjectsClientContract , SavedObjectsFindResult } from '../../../../core/server' ; import type { SavedVisState } from '../../../visualizations/common' ; interface VisSummary { type : string ; space : string ; past_days : number ; } export interface VisualizationUsage { [ x ] : { total : number ; spaces_min ? : number ; spaces_max ? : number ; spaces_avg : number ; saved_7_days_total : number ; saved_30_days_total : number ; saved_90_days_total : number ; } ; } export async function getStats ( soClient ) { const finder = await soClient . createPointInTimeFinder ( { type : 'visualization' , perPage : 1000 , namespaces : [ '*' ] , } ) ; const visSummaries = [ ] ; for await ( const response of finder . find ( ) ) { ( response . saved_objects || [ ] ) . forEach ( ( so ) => { if ( so . attributes ?. visState ) { const visState = JSON . parse ( so . attributes . visState ) ; visSummaries . push ( { type : visState . type ?? '_na_' , space : so . namespaces ?. [ 0 ] ?? 'default' , past_days : getPastDays ( so . updated_at ! ) , } ) ; } } ) ; } await finder . close ( ) ; if ( visSummaries . length ) { const visTypes = groupBy ( visSummaries , 'type' ) ; return mapValues ( visTypes , ( curr ) => { const total = curr . length ; const spacesBreakdown = countBy ( curr , 'space' ) ; const spaceCounts = values ( spacesBreakdown ) ; return { total , spaces_min : min ( spaceCounts ) , spaces_max : max ( spaceCounts ) , spaces_avg : total / spaceCounts . length , saved_7_days_total : curr . filter ( ( c ) => c . past_days <= 7 ) . length , saved_30_days_total : curr . filter ( ( c ) => c . past_days <= 30 ) . length , saved_90_days_total : curr . filter ( ( c ) => c . past_days <= 90 ) . length , } ; } ) ; } }