Repository navigation
Expand file tree
/
Copy pathclassrooms.js
More file actions
950 lines (841 loc) · 27.1 KB
/
Copy pathclassrooms.js
File metadata and controls
950 lines (841 loc) · 27.1 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
/* eslint-env node */
const express = require('express');
const admin = require('firebase-admin');
function studentEntryId(entry) {
if (!entry) return undefined;
if (typeof entry === 'string') return entry;
if (!entry.id) return undefined;
if (typeof entry.id === 'string') return entry.id;
if (typeof entry.id === 'object' && entry.id['en-US']) return entry.id['en-US'];
return undefined;
}
/** Firestore map key for a student (may differ from entry.id in edge cases). */
function findStudentRosterKey(studentIds, studentId) {
if (
!studentIds ||
typeof studentIds !== 'object' ||
Array.isArray(studentIds)
) {
return null;
}
if (studentIds[studentId]) return studentId;
for (const [key, entry] of Object.entries(studentIds)) {
if (key === studentId || studentEntryId(entry) === studentId) {
return key;
}
}
return null;
}
/** All roster map keys that refer to this student (removes duplicates / legacy keys). */
function rosterKeysForStudent(studentIds, studentId) {
if (
!studentIds ||
typeof studentIds !== 'object' ||
Array.isArray(studentIds)
) {
return [];
}
const keys = new Set();
for (const [key, entry] of Object.entries(studentIds)) {
if (key === studentId || studentEntryId(entry) === studentId) {
keys.add(key);
}
}
return [...keys];
}
/** Firestore update() deep-merges maps; assignedTo keys must be deleted explicitly. */
function addAssignedToDeletesForStudent(
update,
classroomAssignments,
studentId,
) {
if (!classroomAssignments || typeof classroomAssignments !== 'object') {
return;
}
const FieldPath = admin.firestore.FieldPath;
for (const [assignmentKey, assignment] of Object.entries(
classroomAssignments,
)) {
const assignedTo = assignment?.assignedTo;
if (!assignedTo || typeof assignedTo !== 'object') continue;
for (const [assignedKey, entry] of Object.entries(assignedTo)) {
if (assignedKey === studentId || studentEntryId(entry) === studentId) {
update[
new FieldPath(
'classroomAssignments',
assignmentKey,
'assignedTo',
assignedKey,
)
] = admin.firestore.FieldValue.delete();
}
}
}
}
/** Apply assignment map patch without leaving stale assignedTo entries after merge. */
async function applyClassroomAssignmentsPatch(
docRef,
existing,
incomingAssignments,
) {
const FieldPath = admin.firestore.FieldPath;
const existingAssignments = existing.classroomAssignments || {};
const incoming = incomingAssignments || {};
const update = {};
const assignmentKeys = new Set([
...Object.keys(existingAssignments),
...Object.keys(incoming),
]);
for (const assignmentKey of assignmentKeys) {
const existingAssignment = existingAssignments[assignmentKey];
const incomingAssignment = incoming[assignmentKey];
const existingAt = existingAssignment?.assignedTo || {};
const incomingAt = incomingAssignment?.assignedTo || {};
for (const assignedKey of Object.keys(existingAt)) {
if (!(assignedKey in incomingAt)) {
update[
new FieldPath(
'classroomAssignments',
assignmentKey,
'assignedTo',
assignedKey,
)
] = admin.firestore.FieldValue.delete();
}
}
for (const [assignedKey, entry] of Object.entries(incomingAt)) {
update[
new FieldPath(
'classroomAssignments',
assignmentKey,
'assignedTo',
assignedKey,
)
] = entry;
}
if (incomingAssignment) {
const rest = { ...incomingAssignment };
delete rest.assignedTo;
for (const [field, value] of Object.entries(rest)) {
update[new FieldPath('classroomAssignments', assignmentKey, field)] =
value;
}
}
}
if (Object.keys(update).length === 0) return;
update.updatedAt = admin.firestore.FieldValue.serverTimestamp();
await docRef.update(update);
}
/** Delete roster entry and remove student from every assignment's assignedTo. */
async function removeStudentFromClassroomDoc(docRef, existing, studentId) {
const keys = rosterKeysForStudent(existing.studentIds, studentId);
if (keys.length === 0) return false;
const update = {
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
};
for (const key of keys) {
update[`studentIds.${key}`] = admin.firestore.FieldValue.delete();
}
addAssignedToDeletesForStudent(
update,
existing.classroomAssignments,
studentId,
);
await docRef.update(update);
return true;
}
// You already have FirebaseTokenManager; we’ll use it to verify the ID token.
module.exports = function createClassroomsRouter(firebaseTokenManager) {
const router = express.Router();
// Ensure Admin is initialized once
if (!admin.apps.length) {
// If you already init admin elsewhere, remove this init block.
admin.initializeApp({
credential: admin.credential.cert(
firebaseTokenManager.serviceAccountKey || {},
),
});
}
router.use((req, res, next) => {
next();
});
// Auth middleware: decode Firebase token into req.user
router.use(async (req, res, next) => {
try {
const auth = req.headers.authorization || '';
const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;
if (!token) return res.status(401).json({ message: 'Missing bearer token' });
const decoded = await firebaseTokenManager.verifyIdToken(token);
req.user = { uid: decoded.uid };
next();
} catch (e) {
res.status(401).json({ message: 'Invalid token' });
}
});
const colPath = () => admin.firestore().collection('classrooms');
// Student leaves whichever classroom they are enrolled in (uses auth uid; no doc id required).
router.post('/leave', async (req, res) => {
try {
const { uid } = req.user;
let qsnap = await colPath().where(`studentIds.${uid}`, '!=', null)
.get();
// Legacy rosters may use a map key other than the uid; scan once if the index query misses.
if (qsnap.empty) {
const all = await colPath().get();
const matches = all.docs.filter(
(doc) => rosterKeysForStudent(doc.data().studentIds, uid).length > 0,
);
if (matches.length > 0) {
qsnap = { docs: matches, empty: false };
}
}
if (qsnap.empty) {
return res
.status(404)
.json({ message: 'Student not in any classroom' });
}
let removed = false;
for (const doc of qsnap.docs) {
const existing = doc.data();
const didRemove = await removeStudentFromClassroomDoc(
doc.ref,
existing,
uid,
);
if (didRemove) removed = true;
}
if (!removed) {
return res.status(404).json({ message: 'Student not in classroom' });
}
return res.sendStatus(204);
} catch (err) {
console.error('POST /classrooms/leave error:', err);
return res.status(500).json({ message: err.message });
}
});
// CREATE classroom (POST on an existing id must not reassign teacherId to the caller)
router.post('/:id', async (req, res) => {
try {
const { uid } = req.user;
const { id } = req.params;
const data = req.body || {};
const firestore = admin.firestore();
const docRef = firestore.collection('classrooms').doc(id);
const existingSnap = await docRef.get();
if (existingSnap.exists) {
const existing = existingSnap.data();
const dataWithoutTeacherId = { ...data };
delete dataWithoutTeacherId.teacherId;
await docRef.set(
{
...dataWithoutTeacherId,
teacherId: existing.teacherId,
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
},
{ merge: true },
);
return res.sendStatus(204);
}
const classroomData = {
...data,
teacherId: uid,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
};
await docRef.set(classroomData);
return res.status(204).json({ id, ...classroomData });
} catch (err) {
console.error('POST /classrooms/ error:', err);
return res.status(500).json({ message: err.message });
}
});
// GET student in classroom challenges
router.get('/:id/challenges', async (req, res) => {
try {
const { id } = req.params;
const qsnap = await admin
.firestore()
.collection('user')
.doc(id)
.collection('challenge_completion')
.get();
const result = {};
qsnap.forEach((doc) => {
result[doc.id] = doc.data();
});
return res.status(200).json(result);
} catch (err) {
console.error('GET /classrooms list error:', err);
return res.status(500).json({ message: err.message });
}
});
router.get('/debug/all-challenge-completions', async (req, res) => {
try {
const qsnap = await admin
.firestore()
.collectionGroup('challenge_completion')
.get();
const result = [];
qsnap.forEach((doc) => {
result.push({
id: doc.id,
data: doc.data(),
path: doc.ref.path,
});
});
return res.status(200).json(result);
} catch (err) {
console.error('Debug collectionGroup error:', err);
return res.status(500).json({ message: err.message });
}
});
router.get('/:classroomId/gradebook/challenges', async (req, res) => {
try {
const { classroomId } = req.params;
const classroomDoc = await admin
.firestore()
.collection('classrooms')
.doc(classroomId)
.get();
if (!classroomDoc.exists) {
return res.status(404).json({ message: 'Classroom not found' });
}
const classroom = classroomDoc.data();
const studentIds = Object.keys(classroom.studentIds || {});
if (studentIds.length === 0) {
return res.status(200).json({});
}
const snapshots = await Promise.all(
studentIds.map((studentId) =>
admin
.firestore()
.collection('user')
.doc(studentId)
.collection('challenge_completion')
.get()
.then((snap) => ({ studentId, snap })),
),
);
const result = {};
snapshots.forEach(({ studentId, snap }) => {
result[studentId] = {};
snap.forEach((doc) => {
result[studentId][doc.id] = doc.data();
});
});
return res.status(200).json(result);
} catch (err) {
console.error('GET /:classroomId/gradebook/challenges error:', err);
return res.status(500).json({ message: err.message });
}
});
// GET all students in classroom challenges
router.get('/challenges', async (req, res) => {
try {
let studentIds = req.query.studentId || [];
if (!Array.isArray(studentIds)) {
studentIds = [studentIds];
}
const result = {};
for (const studentId of studentIds) {
const qsnap = await admin
.firestore()
.collection('user')
.doc(studentId)
.collection('challenge_completion')
.get();
result[studentId] = qsnap.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}));
}
return res.status(200).json(result);
} catch (err) {
console.error('GET /classrooms list error:', err);
return res.status(500).json({ message: err.message });
}
});
router.get('/myClassroom', async (req, res) => {
try {
const { uid } = req.user;
const qsnap = await admin
.firestore()
.collection('classrooms')
.where(`studentIds.${uid}`, '!=', null)
.get();
const result = {};
qsnap.forEach((doc) => {
result[doc.id] = { ...doc.data(), docId: doc.id };
});
return res.status(200).json(result);
} catch (err) {
console.error('GET /classrooms/myClassroom error:', err);
return res.status(500).json({ message: err.message });
}
});
// READ one classroom
router.get('/:id', async (req, res) => {
try {
const { id } = req.params;
const doc = await admin
.firestore()
.collection('classrooms')
.doc(id)
.get();
if (!doc.exists) {
return res.status(404).json({});
}
return res.status(200).json({ [id]: { ...doc.data(), docId: id } });
} catch (err) {
console.error('GET /classrooms/:id error:', err);
return res.status(500).json({ message: err.message });
}
});
// LIST classrooms (owned by this user)
router.get('/', async (req, res) => {
try {
const inviteCode = req.query.inviteCode;
if (inviteCode) {
const qsnap = await admin.firestore().collection('classrooms')
.get();
const want = String(inviteCode).trim();
for (const doc of qsnap.docs) {
const classroom = doc.data();
const codeValue =
typeof classroom.code === 'string'
? classroom.code
: classroom.code?.['en-US'];
if (
codeValue &&
want &&
codeValue.localeCompare(want, undefined, {
sensitivity: 'base',
}) === 0
) {
// return in db.list format: { docId: classroomData }
return res.status(200).json({
[doc.id]: classroom,
});
}
}
return res.status(404).json({});
}
const { uid } = req.user;
const qsnap = await admin
.firestore()
.collection('classrooms')
.where('teacherId', '==', uid)
.get();
const result = {};
qsnap.forEach((doc) => {
result[doc.id] = { ...doc.data(), docId: doc.id };
});
return res.status(200).json(result);
} catch (err) {
console.error('GET /classrooms list error:', err);
return res.status(500).json({ message: err.message });
}
});
// FIND classroom by invite code
router.get('/byInviteCode', async (req, res) => {
try {
const inviteCode = req.query.code;
if (!inviteCode) {
return res.status(400).json({ message: 'Missing invite code' });
}
const qsnap = await admin.firestore().collection('classrooms')
.get();
const want = String(inviteCode).trim();
for (const doc of qsnap.docs) {
const classroom = doc.data();
const codeValue =
typeof classroom.code === 'string'
? classroom.code
: classroom.code?.['en-US'];
if (
codeValue &&
want &&
codeValue.localeCompare(want, undefined, { sensitivity: 'base' }) ===
0
) {
return res.status(200).json({ id: doc.id, ...classroom });
}
}
return res.status(404).json({ message: 'Invalid invite code' });
} catch (err) {
return res.status(500).json({ message: err.message });
}
});
// Student leaves their own classroom (caller uid only; never touches teacherId).
router.post('/:id/leave', async (req, res) => {
try {
const { uid } = req.user;
const { id } = req.params;
const docRef = admin.firestore().collection('classrooms')
.doc(id);
const snap = await docRef.get();
if (!snap.exists) {
return res.status(404).json({ message: 'Classroom not found' });
}
const existing = snap.data();
const didRemove = await removeStudentFromClassroomDoc(
docRef,
existing,
uid,
);
if (!didRemove) {
return res.status(404).json({ message: 'Student not in classroom' });
}
return res.sendStatus(204);
} catch (err) {
console.error('POST /classrooms/:id/leave error:', err);
return res.status(500).json({ message: err.message });
}
});
// Remove one student from the roster (leave classroom / teacher removes student).
// Never reads or writes teacherId.
router.delete('/:id/students/:studentId', async (req, res) => {
try {
const { uid } = req.user;
const { id, studentId } = req.params;
const docRef = admin.firestore().collection('classrooms')
.doc(id);
const snap = await docRef.get();
if (!snap.exists) {
return res.status(404).json({ message: 'Classroom not found' });
}
const existing = snap.data();
const isTeacher = existing.teacherId === uid;
const isSelf = studentId === uid;
if (!isTeacher && !isSelf) {
return res.status(403).json({ message: 'Forbidden' });
}
const didRemove = await removeStudentFromClassroomDoc(
docRef,
existing,
studentId,
);
if (!didRemove) {
return res.status(404).json({ message: 'Student not in classroom' });
}
return res.sendStatus(204);
} catch (err) {
console.error('DELETE /classrooms/:id/students/:studentId error:', err);
return res.status(500).json({ message: err.message });
}
});
const isRosterOnlyPatch = (data) => {
const keys = Object.keys(data).filter((k) => k !== 'updatedAt');
return (
keys.length === 1 &&
keys[0] === 'studentIds' &&
data.studentIds &&
typeof data.studentIds === 'object'
);
};
const isRosterAndAssignmentsPatch = (data) => {
const keys = Object.keys(data).filter((k) => k !== 'updatedAt');
return (
keys.length === 2 &&
keys.includes('studentIds') &&
keys.includes('classroomAssignments') &&
data.studentIds &&
typeof data.studentIds === 'object' &&
data.classroomAssignments &&
typeof data.classroomAssignments === 'object'
);
};
const applyRosterPatch = async (docRef, existing, data) => {
const update = {
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
};
const existingIds = existing.studentIds || {};
const incomingIds = data.studentIds;
for (const [studentId, entry] of Object.entries(incomingIds)) {
update[`studentIds.${studentId}`] = entry;
}
for (const studentId of Object.keys(existingIds)) {
if (!(studentId in incomingIds)) {
update[`studentIds.${studentId}`] = admin.firestore.FieldValue.delete();
}
}
await docRef.update(update);
};
/** Non-teacher roster PATCH: may only join (add self) or leave (remove self). */
const applyStudentRosterPatchAsNonTeacher = async (
docRef,
existing,
data,
uid,
) => {
const existingIds = existing.studentIds || {};
const incomingIds = data.studentIds || {};
const selfKey = findStudentRosterKey(existingIds, uid);
const addedKeys = Object.keys(incomingIds).filter(
(k) => !(k in existingIds),
);
const removedKeys = Object.keys(existingIds).filter(
(k) => !(k in incomingIds),
);
const forbidden = () => {
const err = new Error('Forbidden');
err.status = 403;
throw err;
};
// Join: preserve roster, add only the authenticated student.
if (
removedKeys.length === 0 &&
addedKeys.length === 1 &&
addedKeys[0] === uid
) {
for (const key of Object.keys(existingIds)) {
if (!(key in incomingIds)) forbidden();
}
await docRef.update({
[`studentIds.${uid}`]: incomingIds[uid],
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
});
return;
}
// Leave: preserve roster for everyone else, remove only the authenticated student.
if (addedKeys.length === 0 && removedKeys.length === 1) {
const removedKey = removedKeys[0];
if (
removedKey !== uid &&
removedKey !== selfKey &&
studentEntryId(existingIds[removedKey]) !== uid
) {
forbidden();
}
for (const key of Object.keys(existingIds)) {
if (key === removedKey) continue;
if (!(key in incomingIds)) forbidden();
}
for (const key of Object.keys(incomingIds)) {
if (!(key in existingIds)) forbidden();
}
await removeStudentFromClassroomDoc(docRef, existing, uid);
return;
}
forbidden();
};
// PATCH (classroom update)
// Firestore merge:true recursively merges maps, so nested fields like
// classroomAssignments.*.assignedTo and studentIds.*.assignments never drop
// removed keys when the client sends a smaller object. Teachers send the full
// classroom from the client after edits, so we replace the document for them.
// Roster-only patches (studentIds only) never change teacherId — even if
// teacherId was previously corrupted to match a student's uid.
router.patch('/:id', async (req, res) => {
try {
const { uid } = req.user;
const { id } = req.params;
const data = req.body || {};
const docRef = admin.firestore().collection('classrooms')
.doc(id);
const snap = await docRef.get();
if (!snap.exists) {
return res.status(404).json({ message: 'Classroom not found' });
}
const existing = snap.data();
const isOwner = existing.teacherId === uid;
if (isRosterAndAssignmentsPatch(data) && isOwner) {
await applyRosterPatch(docRef, existing, {
studentIds: data.studentIds,
});
await applyClassroomAssignmentsPatch(
docRef,
existing,
data.classroomAssignments,
);
return res.sendStatus(204);
}
if (isRosterOnlyPatch(data)) {
if (isOwner) {
await applyRosterPatch(docRef, existing, data);
} else {
try {
await applyStudentRosterPatchAsNonTeacher(
docRef,
existing,
data,
uid,
);
} catch (err) {
if (err.status === 403) {
return res.status(403).json({ message: 'Forbidden' });
}
if (err.status === 404) {
return res.status(404).json({ message: err.message });
}
throw err;
}
}
return res.sendStatus(204);
}
if (isOwner) {
const dataWithoutTeacherId = { ...data };
delete dataWithoutTeacherId.teacherId;
const payload = {
...dataWithoutTeacherId,
teacherId: existing.teacherId,
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
};
await docRef.set(payload, { merge: false });
return res.sendStatus(204);
}
return res.status(403).json({ message: 'Forbidden' });
} catch (err) {
console.error('PATCH /classrooms error:', err);
return res.status(500).json({ message: err.message });
}
});
// DELETE
router.delete('/:id', async (req, res) => {
try {
const { uid } = req.user;
const { id } = req.params;
const docRef = colPath(uid).doc(id);
await admin.firestore().recursiveDelete(docRef);
return res.sendStatus(204);
} catch (err) {
console.error('DELETE /classrooms error:', err);
return res.status(500).json({ message: err.message });
}
});
// Delete specific assignment
router.delete('/:id/assignments/:assignmentId', async (req, res) => {
try {
const { uid } = req.user;
const { id, assignmentId } = req.params;
const classroomRef = admin.firestore().collection('classrooms')
.doc(id);
const classroomSnap = await classroomRef.get();
if (!classroomSnap.exists) {
return res.status(404).json({ message: 'Classroom not found' });
}
const classroom = classroomSnap.data();
// Only the classroom teacher can delete assignments
if (classroom.teacherId !== uid) {
return res.status(403).json({
message: 'Only the classroom teacher can delete assignments',
});
}
const assignmentRef = classroomRef
.collection('assignments')
.doc(assignmentId);
await assignmentRef.delete();
return res.sendStatus(204);
} catch (err) {
console.error(
'DELETE /classrooms/:id/assignments/:assignmentId error:',
err,
);
return res.status(500).json({ message: err.message });
}
});
// Get specific assignment
router.get('/:id/assignments/:assignmentId', async (req, res) => {
try {
const { id, assignmentId } = req.params;
const assignmentRef = admin
.firestore()
.collection('classrooms')
.doc(id)
.collection('assignments')
.doc(assignmentId);
const snap = await assignmentRef.get();
if (!snap.exists) {
return res.status(404).json({
message: 'Assignment not found',
});
}
return res.status(200).json({
docId: snap.id,
...snap.data(),
});
} catch (err) {
return res.status(500).json({
message: err.message,
});
}
});
// Get all classroom assignments
router.get('/:id/assignments', async (req, res) => {
try {
const { id } = req.params;
const assignmentsRef = admin
.firestore()
.collection('classrooms')
.doc(id)
.collection('assignments');
const qsnap = await assignmentsRef.get();
const assignments = {};
qsnap.forEach((doc) => {
assignments[doc.id] = { docId: doc.id, ...doc.data() };
});
return res.status(200).json(assignments);
} catch (err) {
return res.status(500).json({
message: err.message,
});
}
});
// Assign assignment to students
// Assign assignment to students
router.post('/:id/assign', async (req, res) => {
try {
const { uid } = req.user;
const { id } = req.params;
const assignment = req.body;
const firestore = admin.firestore();
const classroomRef = firestore.collection('classrooms').doc(id);
const classroomSnap = await classroomRef.get();
if (!classroomSnap.exists) {
return res.status(404).json({
message: 'Classroom not found',
});
}
const classroom = classroomSnap.data();
// Only the classroom teacher can create assignments
if (classroom.teacherId !== uid) {
return res.status(403).json({
message: 'Only the classroom teacher can create assignments',
});
}
if (!assignment.docId) {
return res.status(400).json({
message: 'Assignment docId is required',
});
}
const assignmentRef = classroomRef
.collection('assignments')
.doc(assignment.docId);
await assignmentRef.set({
...assignment,
createdAt:
assignment.createdAt ?? admin.firestore.FieldValue.serverTimestamp(),
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
});
return res.status(204).json({
id: assignment.docId,
});
} catch (err) {
console.error('POST /classrooms/:id/assign error:', err);
return res.status(500).json({
message: err.message,
});
}
});
// Delete assignment from classroom
router.delete('/', async (req, res) => {
try {
void req.user;
void req.query;
return res.status(501).json({ message: 'Not implemented' });
} catch (err) {
return res.status(500).json({ message: err.message });
}
});
return router;
};