Skip to content

Commit 1ff0f08

Browse files
committed
feat: TIL을 생성하거나 Plan 완료 시 금일 날짜를 ID로 Count 집계 문서 생성
1 parent f5887e7 commit 1ff0f08

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

0 commit comments

Comments
 (0)