@@ -30,7 +30,7 @@ export async function getAllhabbitsWithStats() {
3030 const result : HabbitView [ ] = [ ] ;
3131 const habbits : Habbit [ ] = await db . select ( "SELECT * FROM habbit" , [ ] ) ;
3232 for ( const habbit of habbits ) {
33- const habbitCreated = moment ( habbit . created_at ) ;
33+ const yesterday = moment ( ) . toISOString ( ) ;
3434 const logs : HabbitLog [ ] = await db . select (
3535 "SELECT * FROM habbit_log WHERE habbit_id = ?" ,
3636 [ habbit . id ] ,
@@ -54,7 +54,15 @@ export async function getAllhabbitsWithStats() {
5454 value : logs . length ,
5555 } ) ;
5656 // find the number of missing days between the habbit creation and last log
57- const missingDays = moment ( ) . diff ( habbitCreated , "days" ) - logs . length ;
57+ const days =
58+ Math . abs (
59+ moment ( habbit . created_at , "YYYY-MM-DD" )
60+ . startOf ( "day" )
61+ . diff ( moment ( yesterday , "YYYY-MM-DD" ) . startOf ( "day" ) , "days" ) ,
62+ ) + 1 ;
63+
64+ const missingDays = days - logs . length ;
65+
5866 stats . push ( {
5967 name : "Missed" ,
6068 value : missingDays > 0 ? missingDays : 0 ,
@@ -93,25 +101,36 @@ export async function getAllhabbitsWithStats() {
93101
94102export async function checkHabbit ( id : number ) {
95103 await load ;
96- const today = moment ( new Date ( ) ) . format ( "YYYY-MM-DD" )
104+ const today = moment ( new Date ( ) ) . format ( "YYYY-MM-DD" ) ;
97105 const isAlreadyChecked : HabbitLog [ ] = await db . select (
98106 "SELECT * FROM habbit_log WHERE habbit_id = ? AND date(created_at) = ?" ,
99- [ id , today ] ,
107+ [ id , today ] ,
100108 ) ;
101109 if ( isAlreadyChecked . length > 0 ) {
102110 isAlreadyChecked . forEach ( async ( log ) => {
103111 await db . execute ( "DELETE FROM habbit_log WHERE id = ?" , [ log . id ] ) ;
104112 } ) ;
105- return "You have unchecked the habit" ;
113+ return {
114+ message : "You have unchecked the habit" ,
115+ confetti : false ,
116+ }
106117 }
107118 // kinda weird but it works
108119 const created_at = moment ( new Date ( ) ) . format ( "YYYY-MM-DD HH:mm:ss" ) ;
109120 await db . execute (
110121 "INSERT INTO habbit_log (habbit_id, created_at) VALUES (?, ?)" ,
111122 [ id , created_at ] ,
112123 ) ;
124+ // check all habbits completed today
125+ const allHabbits = await getAllhabbitsWithStats ( ) ;
126+ const allHabbitsCompleted = allHabbits . every ( habbit => habbit . isChecked ) ;
127+
113128
114- return "Awesome! You have checked the habit" ;
129+
130+ return {
131+ message : "Awesome! You have checked the habit" ,
132+ confetti : allHabbitsCompleted ,
133+ }
115134}
116135
117136export async function deleteHabbit ( id : number ) {
0 commit comments