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,62 @@ 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+ p.present_count
364+ FROM (
365+ SELECT
366+ date,
367+ COUNT(*) AS total_count
368+ FROM attendance
369+ WHERE date BETWEEN "# ,
370+ ) ;
371+
372+ query. push_bind ( start_date) ;
373+ query. push ( " AND " ) ;
374+ query. push_bind ( end_date) ;
375+ query. push ( " GROUP BY date ) AS all_dates " ) ;
376+
377+ // sub query of present members joined with the above total countS
378+ query. push (
379+ "LEFT JOIN (
380+ SELECT
381+ date,
382+ COUNT(*) AS present_count
383+ FROM attendance
384+ WHERE is_present = 't'
385+ AND date BETWEEN " ,
386+ ) ;
387+ query. push_bind ( start_date) ;
388+ query. push ( " AND " ) ;
389+ query. push_bind ( end_date) ;
390+ query. push (
391+ " GROUP BY date
392+ ) AS p
393+ ON all_dates.date = p.date
394+ ORDER BY all_dates.date;" ,
395+ ) ;
396+
397+ let results: Vec < Aggregate > = query
398+ . build_query_as :: < Aggregate > ( )
399+ . fetch_all ( pool. as_ref ( ) )
400+ . await ?;
401+
402+ Ok ( results)
403+ }
404+ }
0 commit comments