-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschedule.ts
More file actions
134 lines (122 loc) · 5.88 KB
/
Copy pathschedule.ts
File metadata and controls
134 lines (122 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import { onSchedule } from "firebase-functions/v2/scheduler";
import { getFunctions } from "firebase-admin/functions";
import * as admin from "firebase-admin";
import * as logger from "firebase-functions/logger";
import { addDays, getZonedParts, zonedDateTimeToUTC } from "../common/date";
import { toError } from "../common/error";
import { FirestorePath } from "../common/firestorePath";
import { resolveTimeZone } from "./shared";
const LOCATION = "asia-northeast3";
const DEFAULT_HOUR = 9;
const DEFAULT_MINUTE = 0;
const MINUTE_INTERVAL = 5;
// 사용자별 설정 시간에 맞춘 내일 마감 Todo 알림 작업 큐 적재
export const scheduleTodoReminder = onSchedule({
maxInstances: 1,
region: LOCATION,
schedule: "*/5 * * * *",
timeZone: "UTC"
},
async (event) => {
try {
const now = event.scheduleTime ? new Date(event.scheduleTime) : new Date();
const queue = getFunctions().taskQueue(`locations/${LOCATION}/functions/sendPushNotification`);
let usersSnapshot: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>;
try {
usersSnapshot = await admin.firestore().collection("users").get();
} catch (error) {
logger.error("users 조회 실패", toError(error), {
at: "collection(users).get()"
});
return;
}
for (const userDoc of usersSnapshot.docs) {
const userId = userDoc.id;
let settingsDoc: FirebaseFirestore.DocumentSnapshot<FirebaseFirestore.DocumentData>;
try {
settingsDoc = await admin.firestore()
.doc(FirestorePath.userData(userId, FirestorePath.UserDataDocument.settings))
.get();
} catch (error) {
logger.error("settings 조회 실패", toError(error), {
userId,
at: "users/{uid}/userData/settings"
});
continue;
}
const settings = settingsDoc.data();
if (!settings || settings.allowPushNotification !== true) { continue; }
const hour = Number.isInteger(settings.pushNotificationHour) ? settings.pushNotificationHour : DEFAULT_HOUR;
const configuredMinute = Number.isInteger(settings.pushNotificationMinute) ?
Number(settings.pushNotificationMinute) :
DEFAULT_MINUTE;
const minute = configuredMinute < 0 || configuredMinute > 59 ?
DEFAULT_MINUTE :
configuredMinute - (configuredMinute % MINUTE_INTERVAL);
const timeZone = resolveTimeZone(settings);
const localNow = getZonedParts(now, timeZone);
if (localNow.hour !== hour) { continue; }
const windowEnd = Math.min(minute + MINUTE_INTERVAL, 60);
if (localNow.minute < minute || localNow.minute >= windowEnd) { continue; }
const tomorrow = addDays(localNow.year, localNow.month, localNow.day, 1);
const dayAfterTomorrow = addDays(localNow.year, localNow.month, localNow.day, 2);
const startUTC = zonedDateTimeToUTC(
tomorrow.year,
tomorrow.month,
tomorrow.day,
0, 0,
timeZone
);
const endUTC = zonedDateTimeToUTC(
dayAfterTomorrow.year,
dayAfterTomorrow.month,
dayAfterTomorrow.day,
0, 0,
timeZone
);
const dueDateKey = `${tomorrow.year}-${tomorrow.month.toString().padStart(2, "0")}-${tomorrow.day.toString().padStart(2, "0")}`;
let todosSnapshot: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>;
try {
todosSnapshot = await admin.firestore()
.collection(FirestorePath.todos(userId))
.where("dueDate", ">=", admin.firestore.Timestamp.fromDate(startUTC))
.where("dueDate", "<", admin.firestore.Timestamp.fromDate(endUTC))
.get();
} catch (error) {
logger.error("todoLists 조회 실패", toError(error), {
userId,
at: "todoLists.where(dueDate>=start).where(dueDate<end)",
startUTC: startUTC.toISOString(),
endUTC: endUTC.toISOString(),
dueDateKey
});
continue;
}
for (const todoDoc of todosSnapshot.docs) {
const todoData = todoDoc.data();
const todoTitle = typeof todoData.title === "string" && todoData.title.trim() ?
todoData.title :
"제목 없음";
const notificationPayload = {
userId,
todoId: todoDoc.id,
dueDateKey,
title: "DevLog",
body: `'${todoTitle}'의 마감일이 내일입니다.`
};
try {
await queue.enqueue(notificationPayload);
} catch (error) {
logger.error("Cloud Tasks enqueue 실패", toError(error), {
userId,
todoId: todoDoc.id,
dueDateKey
});
}
}
}
} catch (error) {
logger.error("알림 스케줄 배치 실행 중 오류 발생", toError(error));
}
}
);