1- use crate :: models:: { attendance:: AttendanceRecord , status_update:: StatusUpdateRecord } ;
1+ use crate :: models:: {
2+ attendance:: Aggregate , attendance:: AttendanceRecord , status_update:: StatusUpdateRecord ,
3+ } ;
24use async_graphql:: { ComplexObject , Context , Object , Result } ;
35use chrono:: NaiveDate ;
46use sqlx:: PgPool ;
@@ -17,8 +19,13 @@ pub struct AttendanceInfo {
1719 member_id : i32 ,
1820}
1921
22+ pub struct Lab ;
23+
2024#[ Object ]
2125impl MemberQueries {
26+ async fn lab ( & self , _ctx : & Context < ' _ > ) -> Lab {
27+ Lab
28+ }
2229 pub async fn all_members (
2330 & self ,
2431 ctx : & Context < ' _ > ,
@@ -336,3 +343,63 @@ impl Member {
336343 }
337344 }
338345}
346+
347+ #[ Object ]
348+
349+ impl Lab {
350+ pub async fn attendance (
351+ & self ,
352+ ctx : & Context < ' _ > ,
353+ start_date : NaiveDate ,
354+ end_date : NaiveDate ,
355+ ) -> Result < Vec < Aggregate > > {
356+ let pool = ctx. data :: < Arc < PgPool > > ( ) . expect ( "Pool must be in context." ) ;
357+
358+ // will give the total count
359+ let mut query = sqlx:: QueryBuilder :: new (
360+ r#"
361+ SELECT
362+ all_dates.date,
363+ all_dates.total_count,
364+ p.present_count
365+ FROM (
366+ SELECT
367+ date,
368+ COUNT(*) AS total_count
369+ FROM attendance
370+ WHERE date BETWEEN "# ,
371+ ) ;
372+
373+ query. push_bind ( start_date) ;
374+ query. push ( " AND " ) ;
375+ query. push_bind ( end_date) ;
376+ query. push ( " GROUP BY date ) AS all_dates " ) ;
377+
378+ // sub query of present members joined with the above total countS
379+ query. push (
380+ "LEFT JOIN (
381+ SELECT
382+ date,
383+ COUNT(*) AS present_count
384+ FROM attendance
385+ WHERE is_present = 't'
386+ AND date BETWEEN " ,
387+ ) ;
388+ query. push_bind ( start_date) ;
389+ query. push ( " AND " ) ;
390+ query. push_bind ( end_date) ;
391+ query. push (
392+ " GROUP BY date
393+ ) AS p
394+ ON all_dates.date = p.date
395+ ORDER BY all_dates.date;" ,
396+ ) ;
397+
398+ let results: Vec < Aggregate > = query
399+ . build_query_as :: < Aggregate > ( )
400+ . fetch_all ( pool. as_ref ( ) )
401+ . await ?;
402+
403+ Ok ( results)
404+ }
405+ }
0 commit comments