forked from Priyanshu-byte-coder/devtrack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
314 lines (269 loc) · 9.26 KB
/
Copy pathroute.ts
File metadata and controls
314 lines (269 loc) · 9.26 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { supabaseAdmin } from "@/lib/supabase";
import { resolveAppUser } from "@/lib/resolve-user";
import { dispatchToAllWebhooks } from "@/lib/webhooks";
import { stripHtml } from "@/lib/sanitize";
export const dynamic = "force-dynamic";
interface Goal {
id: string;
user_id: string;
title: string;
target: number;
current: number;
unit: string;
recurrence: string;
deadline: string | null;
period_start: string | null;
created_at: string;
goal_reset_version: number;
is_public: boolean;
category: GoalCategory | null;
}
interface GoalHistory {
goal_id: string;
period_start: string;
period_end: string;
target: number;
achieved: number;
completed: boolean;
}
type Recurrence = "none" | "weekly" | "monthly";
type GoalCategory = "side-project" | "work" | "dsa" | "open-source";
const VALID_RECURRENCES = ["none", "weekly", "monthly"] as const;
const VALID_CATEGORIES = ["side-project", "work", "dsa", "open-source"] as const;
const MAX_TITLE_LEN = 100;
const MAX_UNIT_LEN = 30;
const MIN_TARGET = 1;
const MAX_TARGET = 10_000;
// Hard cap to prevent storage exhaustion and catastrophic Promise.all execution
const MAX_GOALS_PER_USER = 5;
function getPeriodStart(recurrence: Recurrence): string {
const now = new Date();
if (recurrence === "weekly") {
const day = now.getUTCDay();
const diff = day === 0 ? -6 : 1 - day; // Monday
const monday = new Date(now);
monday.setUTCDate(now.getUTCDate() + diff);
monday.setUTCHours(0, 0, 0, 0);
return monday.toISOString();
}
if (recurrence === "monthly") {
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
}
return new Date(0).toISOString(); // 'none' never resets
}
function getPreviousPeriodEnd(periodStart: Date): string {
return new Date(periodStart.getTime() - 1).toISOString();
}
export async function GET() {
const session = await getServerSession(authOptions);
if (!session?.githubId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const user = await resolveAppUser(session.githubId, session.githubLogin);
if (!user) return Response.json({ error: "User not found" }, { status: 404 });
// Added .limit() to bound the database payload and the subsequent Promise.all loop
const { data: goals, error } = await supabaseAdmin
.from("goals")
.select("*")
.eq("user_id", user.id)
.order("created_at", { ascending: false })
.limit(MAX_GOALS_PER_USER);
if (error) {
console.error("Failed to fetch goals:", error);
return Response.json({ error: "Failed to fetch goals" }, { status: 500 });
}
// Reset progress if we're in a new period
const processedGoals = await Promise.all(
(goals ?? []).map(async (goal: Goal) => {
if (goal.recurrence === "none") return goal;
const periodStart = new Date(getPeriodStart(goal.recurrence as Recurrence));
const storedPeriodStart = goal.period_start
? new Date(goal.period_start)
: new Date(0);
if (storedPeriodStart < periodStart) {
const oldVersion = goal.goal_reset_version ?? 0;
const { error: historyError } = await supabaseAdmin
.from("goal_history")
.insert({
goal_id: goal.id,
user_id: goal.user_id,
period_start: storedPeriodStart.toISOString(),
period_end: getPreviousPeriodEnd(periodStart),
target: goal.target,
achieved: goal.current,
completed: goal.current >= goal.target,
});
if (historyError && historyError.code !== "23505") {
console.error("Failed to persist goal history before reset:", historyError);
return goal;
}
const { data: updated, error } = await supabaseAdmin
.from("goals")
.update({
current: 0,
period_start: periodStart.toISOString(),
goal_reset_version: oldVersion + 1,
week_start: periodStart.toISOString().split("T")[0],
})
.eq("id", goal.id)
.eq("goal_reset_version", oldVersion)
.or(`period_start.lt.${periodStart.toISOString()},period_start.is.null`)
.select()
.single();
if (updated) {
return updated;
}
if (error) {
console.warn("[GOAL_RESET_CONFLICT]", {
goalId: goal.id,
oldVersion,
error,
});
}
const { data: current } = await supabaseAdmin
.from("goals")
.select("*")
.eq("id", goal.id)
.single();
return current ?? goal;
}
return goal;
})
);
const goalIds = processedGoals
.map((goal) => goal?.id)
.filter((id): id is string => Boolean(id));
let latestHistoryByGoal = new Map<string, GoalHistory>();
if (goalIds.length > 0) {
const { data: histories } = await supabaseAdmin
.from("goal_history")
.select("goal_id, period_start, period_end, target, achieved, completed")
.eq("user_id", user.id)
.in("goal_id", goalIds)
.order("period_end", { ascending: false });
latestHistoryByGoal = new Map<string, GoalHistory>();
for (const history of (histories ?? []) as GoalHistory[]) {
if (!latestHistoryByGoal.has(history.goal_id)) {
latestHistoryByGoal.set(history.goal_id, history);
}
}
}
const goalsWithHistory = (processedGoals ?? []).map((goal) => ({
...goal,
last_period: latestHistoryByGoal.get(goal.id) ?? null,
}));
return Response.json({ goals: goalsWithHistory });
}
export async function POST(req: Request) {
const session = await getServerSession(authOptions);
if (!session?.githubId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
let body: unknown;
try {
body = await req.json();
} catch (e) {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
if (typeof body !== "object" || body === null) {
return Response.json({ error: "Invalid request body" }, { status: 400 });
}
const { title, target, unit, recurrence, deadline, category } = body as Record<string, unknown>;
if (typeof title !== "string" || title.trim().length === 0) {
return Response.json({ error: "title must be a non-empty string" }, { status: 400 });
}
const sanitizedTitle = stripHtml(title);
if (sanitizedTitle.length === 0) {
return Response.json({ error: "title must not be empty" }, { status: 400 });
}
if (sanitizedTitle.length > MAX_TITLE_LEN) {
return Response.json({ error: `title must be ${MAX_TITLE_LEN} characters or fewer` }, { status: 400 });
}
if (
typeof target !== "number" ||
!Number.isInteger(target) ||
target < MIN_TARGET ||
target > MAX_TARGET
) {
return Response.json(
{ error: `target must be an integer between ${MIN_TARGET} and ${MAX_TARGET}` },
{ status: 400 }
);
}
const safeUnit = typeof unit === "string" ? unit.slice(0, MAX_UNIT_LEN) : "commits";
const safeRecurrence: Recurrence = VALID_RECURRENCES.includes(recurrence as Recurrence)
? (recurrence as Recurrence)
: "none";
const safeCategory: GoalCategory | null = VALID_CATEGORIES.includes(category as GoalCategory)
? (category as GoalCategory)
: null;
let safeDeadline: string | null = null;
if (typeof deadline === "string") {
const d = new Date(deadline);
if (!Number.isNaN(d.getTime())) {
d.setUTCHours(23, 59, 59, 999);
safeDeadline = d.toISOString();
}
}
const user = await resolveAppUser(session.githubId, session.githubLogin);
if (!user) return Response.json({ error: "User not found" }, { status: 404 });
const { data: existing } = await supabaseAdmin
.from("goals")
.select("id")
.eq("user_id", user.id)
.ilike("title", sanitizedTitle)
.maybeSingle();
if (existing) {
return Response.json(
{
error: "Task with this title already exists",
code: "DUPLICATE_TASK_TITLE",
},
{ status: 400 }
);
}
// Pre-check count query using head option for peak performance
const { count, error: countError } = await supabaseAdmin
.from("goals")
.select("*", { count: "exact", head: true })
.eq("user_id", user.id);
if (countError) {
return Response.json({ error: "Failed to verify goal limits" }, { status: 500 });
}
if ((count ?? 0) >= MAX_GOALS_PER_USER) {
return Response.json(
{ error: `You can have at most ${MAX_GOALS_PER_USER} goals.` },
{ status: 400 }
);
}
const { data: goal, error } = await supabaseAdmin
.from("goals")
.insert({
user_id: user.id,
title: sanitizedTitle,
target,
unit: safeUnit,
recurrence: safeRecurrence,
period_start: getPeriodStart(safeRecurrence),
deadline: safeDeadline,
category: safeCategory,
current: 0,
goal_reset_version: 0,
})
.select()
.single();
if (error) {
return Response.json({ error: error.message }, { status: 500 });
}
dispatchToAllWebhooks(user.id, "goal.created", {
goalId: goal.id,
title: goal.title,
target: goal.target,
unit: goal.unit,
recurrence: goal.recurrence,
category: goal.category,
}).catch(() => {});
return Response.json({ goal }, { status: 201 });
}