@@ -4,27 +4,63 @@ import type { Summary } from '@opendatacapture/schemas/summary';
44import type { EntityOperationOptions } from '@/core/types' ;
55import { InstrumentRecordsService } from '@/instrument-records/instrument-records.service' ;
66import { InstrumentsService } from '@/instruments/instruments.service' ;
7+ import { SessionsService } from '@/sessions/sessions.service' ;
78import { SubjectsService } from '@/subjects/subjects.service' ;
89import { UsersService } from '@/users/users.service' ;
910
11+ const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000 ;
12+
1013@Injectable ( )
1114export class SummaryService {
1215 constructor (
1316 private readonly instrumentRecordsService : InstrumentRecordsService ,
1417 private readonly instrumentsService : InstrumentsService ,
18+ private readonly sessionsService : SessionsService ,
1519 private readonly usersService : UsersService ,
1620 private readonly subjectsService : SubjectsService
1721 ) { }
1822
1923 async getSummary ( groupId ?: string , { ability } : EntityOperationOptions = { } ) : Promise < Summary > {
2024 const filter = groupId ? { groupIds : { has : groupId } } : ( { } as { [ key : string ] : unknown } ) ;
25+ const sessionFilter = groupId ? { groupId } : { } ;
26+ const recordFilter = groupId ? { groupId } : { } ;
27+
28+ const counts = {
29+ instruments : await this . instrumentsService . count ( ) ,
30+ records : await this . instrumentRecordsService . count ( recordFilter , { ability } ) ,
31+ sessions : await this . sessionsService . count ( sessionFilter , { ability } ) ,
32+ subjects : await this . subjectsService . count ( filter , { ability } ) ,
33+ users : await this . usersService . count ( filter , { ability } )
34+ } ;
35+
36+ const now = Date . now ( ) ;
37+
38+ const trends : Summary [ 'trends' ] = {
39+ records : [ ] ,
40+ sessions : [ ] ,
41+ subjects : [ ]
42+ } ;
43+
44+ for ( let i = 0 ; i < 5 ; i ++ ) {
45+ const timestamp = now - THIRTY_DAYS_MS * i ;
46+ const lte = new Date ( timestamp ) ;
47+ trends . records . push ( {
48+ timestamp,
49+ value : await this . instrumentRecordsService . count ( { date : { lte } , ...recordFilter } , { ability } )
50+ } ) ;
51+ trends . sessions . push ( {
52+ timestamp,
53+ value : await this . sessionsService . count ( { date : { lte } , ...sessionFilter } , { ability } )
54+ } ) ;
55+ trends . subjects . push ( {
56+ timestamp,
57+ value : await this . subjectsService . count ( { createdAt : { lte } , ...filter } , { ability } )
58+ } ) ;
59+ }
60+
2161 return {
22- counts : {
23- instruments : await this . instrumentsService . count ( ) ,
24- records : await this . instrumentRecordsService . count ( { groupId } , { ability } ) ,
25- subjects : await this . subjectsService . count ( filter , { ability } ) ,
26- users : await this . usersService . count ( filter , { ability } )
27- }
62+ counts,
63+ trends
2864 } ;
2965 }
3066}
0 commit comments