-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathroute.ts
More file actions
167 lines (151 loc) · 5.24 KB
/
Copy pathroute.ts
File metadata and controls
167 lines (151 loc) · 5.24 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
import { auth } from '@clerk/nextjs/server'
import { NextRequest, NextResponse } from 'next/server'
import mongoose from 'mongoose'
import { connectDB } from '@/lib/mongodb'
import { Attendance } from '@/models/Attendance'
import { z } from 'zod'
const AttendanceSchema = z.object({
studentId: z.string().min(1),
studentName: z.string().min(1),
class: z.string().min(1),
date: z.string().min(1),
status: z.enum(['present', 'absent', 'late']),
})
const BulkSchema = z.array(AttendanceSchema)
export async function GET(req: NextRequest) {
const { userId } = await auth()
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
try {
await connectDB();
const { searchParams } = new URL(req.url);
const date = searchParams.get("date");
const cls = searchParams.get("class");
const studentId = searchParams.get("studentId");
const startDate = searchParams.get("startDate");
const endDate = searchParams.get("endDate");
const query: Record<string, unknown> = { teacherId: userId };
// Helper to validate and normalize date strings to YYYY-MM-DD format
const normalizeDate = (dateStr: string): string | null => {
try {
// Try to parse as ISO date (YYYY-MM-DD or full ISO 8601)
const d = new Date(dateStr);
if (isNaN(d.getTime())) return null;
// Return in YYYY-MM-DD format for MongoDB string comparison
return d.toISOString().split("T")[0];
} catch {
return null;
}
};
if (date) {
const normalized = normalizeDate(date);
if (normalized) {
query.date = normalized;
} else {
return NextResponse.json(
{ error: "Invalid date format. Use YYYY-MM-DD or ISO 8601" },
{ status: 400 },
);
}
} else if (startDate || endDate) {
const dateRange: Record<string, string> = {};
if (startDate) {
const normalized = normalizeDate(startDate);
if (normalized) dateRange.$gte = normalized;
else
return NextResponse.json(
{ error: "Invalid startDate format. Use YYYY-MM-DD or ISO 8601" },
{ status: 400 },
);
}
if (endDate) {
const normalized = normalizeDate(endDate);
if (normalized) dateRange.$lte = normalized;
else
return NextResponse.json(
{ error: "Invalid endDate format. Use YYYY-MM-DD or ISO 8601" },
{ status: 400 },
);
}
query.date = dateRange;
}
if (cls) query.class = cls;
if (studentId) {
if (!mongoose.Types.ObjectId.isValid(studentId)) {
return NextResponse.json({ error: "Invalid studentId" }, { status: 400 });
}
query.studentId = studentId;
}
const records = await Attendance.find(query)
.sort({ date: -1, studentName: 1 })
.lean();
return NextResponse.json(records);
} catch (err) {
console.error(
"GET /api/attendance error:",
err instanceof Error ? err.message : err,
);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
}
}
export async function POST(req: NextRequest) {
const { userId } = await auth()
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
try {
await connectDB()
let body
try {
body = await req.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON in request body' }, { status: 400 })
}
// Support both single and bulk
const isBulk = Array.isArray(body)
if (isBulk && body.length > 500) {
return NextResponse.json(
{ error: "Bulk payload exceeds maximum of 500 records" },
{ status: 400 },
);
}
const parsed = isBulk ? BulkSchema.safeParse(body) : AttendanceSchema.safeParse(body)
if (!parsed.success)
return NextResponse.json(
{ error: parsed.error.flatten() },
{ status: 400 },
);
if (isBulk) {
const data = parsed.data as z.infer<typeof BulkSchema>;
// Validate all studentIds
for (const record of data) {
if (!mongoose.Types.ObjectId.isValid(record.studentId)) {
return NextResponse.json({ error: `Invalid studentId: ${record.studentId}` }, { status: 400 });
}
}
const ops = data.map((record) => ({
updateOne: {
filter: { teacherId: userId, studentId: record.studentId, date: record.date },
update: { $set: { ...record, teacherId: userId } },
upsert: true,
},
}))
await Attendance.bulkWrite(ops)
return NextResponse.json({ success: true, count: ops.length })
} else {
const data = parsed.data as z.infer<typeof AttendanceSchema>;
if (!mongoose.Types.ObjectId.isValid(data.studentId)) {
return NextResponse.json({ error: "Invalid studentId" }, { status: 400 });
}
const record = await Attendance.findOneAndUpdate(
{ teacherId: userId, studentId: data.studentId, date: data.date },
{ $set: { ...data, teacherId: userId } },
{ upsert: true, new: true }
)
return NextResponse.json(record, { status: 201 })
}
} catch (err) {
console.error(err)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}