File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { doc , runTransaction , serverTimestamp } from 'firebase/firestore' ;
2+ import { db } from '@/lib/firebase' ;
3+
4+ function dateKeyKST ( date = new Date ( ) ) {
5+ const kst = new Date ( date . getTime ( ) + 9 * 60 * 60 * 1000 ) ;
6+ return kst . toISOString ( ) . slice ( 0 , 10 ) ;
7+ }
8+
9+ export async function bumpDailyStat (
10+ uid : string ,
11+ deltaTil : number ,
12+ deltaTodoDone : number
13+ ) {
14+ const key = dateKeyKST ( ) ;
15+ const ref = doc ( db , `users/${ uid } /dailyStats/${ key } ` ) ;
16+
17+ await runTransaction ( db , async ( tx ) => {
18+ const snap = await tx . get ( ref ) ;
19+
20+ const prev = snap . exists ( )
21+ ? ( snap . data ( ) as {
22+ tilCount ?: number ;
23+ todoDoneCount ?: number ;
24+ total ?: number ;
25+ } )
26+ : { } ;
27+
28+ const nextTil = Math . max ( 0 , ( prev . tilCount ?? 0 ) + deltaTil ) ;
29+ const nextTodo = Math . max ( 0 , ( prev . todoDoneCount ?? 0 ) + deltaTodoDone ) ;
30+ const nextTotal = Math . max ( 0 , nextTil + nextTodo ) ;
31+
32+ tx . set (
33+ ref ,
34+ {
35+ date : key ,
36+ tilCount : nextTil ,
37+ todoDoneCount : nextTodo ,
38+ total : nextTotal ,
39+ updatedAt : serverTimestamp ( ) ,
40+ } ,
41+ { merge : true }
42+ ) ;
43+ } ) ;
44+ }
You can’t perform that action at this time.
0 commit comments