@studious-lms/server 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,500 @@
1
+ import { z } from 'zod';
2
+ import { createTRPCRouter, protectedProcedure } from '../trpc.js';
3
+ import { prisma } from '../lib/prisma.js';
4
+ import { pusher } from '../lib/pusher.js';
5
+ import { TRPCError } from '@trpc/server';
6
+ export const labChatRouter = createTRPCRouter({
7
+ create: protectedProcedure
8
+ .input(z.object({
9
+ classId: z.string(),
10
+ title: z.string().min(1).max(200),
11
+ context: z.string(), // JSON string for LLM context
12
+ }))
13
+ .mutation(async ({ input, ctx }) => {
14
+ const userId = ctx.user.id;
15
+ const { classId, title, context } = input;
16
+ // Verify user is a teacher in the class
17
+ const classWithTeachers = await prisma.class.findFirst({
18
+ where: {
19
+ id: classId,
20
+ teachers: {
21
+ some: {
22
+ id: userId,
23
+ },
24
+ },
25
+ },
26
+ include: {
27
+ students: {
28
+ select: {
29
+ id: true,
30
+ username: true,
31
+ profile: {
32
+ select: {
33
+ displayName: true,
34
+ profilePicture: true,
35
+ },
36
+ },
37
+ },
38
+ },
39
+ teachers: {
40
+ select: {
41
+ id: true,
42
+ username: true,
43
+ profile: {
44
+ select: {
45
+ displayName: true,
46
+ profilePicture: true,
47
+ },
48
+ },
49
+ },
50
+ },
51
+ },
52
+ });
53
+ if (!classWithTeachers) {
54
+ throw new TRPCError({
55
+ code: 'FORBIDDEN',
56
+ message: 'Not a teacher in this class',
57
+ });
58
+ }
59
+ // Validate context is valid JSON
60
+ try {
61
+ JSON.parse(context);
62
+ }
63
+ catch (error) {
64
+ throw new TRPCError({
65
+ code: 'BAD_REQUEST',
66
+ message: 'Context must be valid JSON',
67
+ });
68
+ }
69
+ // Create lab chat with associated conversation
70
+ const result = await prisma.$transaction(async (tx) => {
71
+ // Create conversation for the lab chat
72
+ const conversation = await tx.conversation.create({
73
+ data: {
74
+ type: 'GROUP',
75
+ name: `Lab: ${title}`,
76
+ displayInChat: false, // Lab chats don't show in regular chat list
77
+ },
78
+ });
79
+ // Add all class members to the conversation
80
+ const allMembers = [
81
+ ...classWithTeachers.teachers.map(t => ({ userId: t.id, role: 'ADMIN' })),
82
+ ...classWithTeachers.students.map(s => ({ userId: s.id, role: 'MEMBER' })),
83
+ ];
84
+ await tx.conversationMember.createMany({
85
+ data: allMembers.map(member => ({
86
+ userId: member.userId,
87
+ conversationId: conversation.id,
88
+ role: member.role,
89
+ })),
90
+ });
91
+ // Create the lab chat
92
+ const labChat = await tx.labChat.create({
93
+ data: {
94
+ title,
95
+ context,
96
+ classId,
97
+ conversationId: conversation.id,
98
+ createdById: userId,
99
+ },
100
+ include: {
101
+ conversation: {
102
+ include: {
103
+ members: {
104
+ include: {
105
+ user: {
106
+ select: {
107
+ id: true,
108
+ username: true,
109
+ profile: {
110
+ select: {
111
+ displayName: true,
112
+ profilePicture: true,
113
+ },
114
+ },
115
+ },
116
+ },
117
+ },
118
+ },
119
+ },
120
+ },
121
+ createdBy: {
122
+ select: {
123
+ id: true,
124
+ username: true,
125
+ profile: {
126
+ select: {
127
+ displayName: true,
128
+ },
129
+ },
130
+ },
131
+ },
132
+ class: {
133
+ select: {
134
+ id: true,
135
+ name: true,
136
+ subject: true,
137
+ section: true,
138
+ },
139
+ },
140
+ },
141
+ });
142
+ return labChat;
143
+ });
144
+ // Broadcast lab chat creation to class members
145
+ try {
146
+ await pusher.trigger(`class-${classId}`, 'lab-chat-created', {
147
+ id: result.id,
148
+ title: result.title,
149
+ classId: result.classId,
150
+ conversationId: result.conversationId,
151
+ createdBy: result.createdBy,
152
+ createdAt: result.createdAt,
153
+ });
154
+ }
155
+ catch (error) {
156
+ console.error('Failed to broadcast lab chat creation:', error);
157
+ // Don't fail the request if Pusher fails
158
+ }
159
+ return result;
160
+ }),
161
+ get: protectedProcedure
162
+ .input(z.object({ labChatId: z.string() }))
163
+ .query(async ({ input, ctx }) => {
164
+ const userId = ctx.user.id;
165
+ const { labChatId } = input;
166
+ const labChat = await prisma.labChat.findFirst({
167
+ where: {
168
+ id: labChatId,
169
+ conversation: {
170
+ members: {
171
+ some: {
172
+ userId,
173
+ },
174
+ },
175
+ },
176
+ },
177
+ include: {
178
+ conversation: {
179
+ include: {
180
+ members: {
181
+ include: {
182
+ user: {
183
+ select: {
184
+ id: true,
185
+ username: true,
186
+ profile: {
187
+ select: {
188
+ displayName: true,
189
+ profilePicture: true,
190
+ },
191
+ },
192
+ },
193
+ },
194
+ },
195
+ },
196
+ },
197
+ },
198
+ createdBy: {
199
+ select: {
200
+ id: true,
201
+ username: true,
202
+ profile: {
203
+ select: {
204
+ displayName: true,
205
+ },
206
+ },
207
+ },
208
+ },
209
+ class: {
210
+ select: {
211
+ id: true,
212
+ name: true,
213
+ subject: true,
214
+ section: true,
215
+ },
216
+ },
217
+ },
218
+ });
219
+ if (!labChat) {
220
+ throw new TRPCError({
221
+ code: 'NOT_FOUND',
222
+ message: 'Lab chat not found or access denied',
223
+ });
224
+ }
225
+ return labChat;
226
+ }),
227
+ list: protectedProcedure
228
+ .input(z.object({ classId: z.string() }))
229
+ .query(async ({ input, ctx }) => {
230
+ const userId = ctx.user.id;
231
+ const { classId } = input;
232
+ // Verify user is a member of the class
233
+ const classMembership = await prisma.class.findFirst({
234
+ where: {
235
+ id: classId,
236
+ OR: [
237
+ {
238
+ students: {
239
+ some: {
240
+ id: userId,
241
+ },
242
+ },
243
+ },
244
+ {
245
+ teachers: {
246
+ some: {
247
+ id: userId,
248
+ },
249
+ },
250
+ },
251
+ ],
252
+ },
253
+ });
254
+ if (!classMembership) {
255
+ throw new TRPCError({
256
+ code: 'FORBIDDEN',
257
+ message: 'Not a member of this class',
258
+ });
259
+ }
260
+ const labChats = await prisma.labChat.findMany({
261
+ where: {
262
+ classId,
263
+ },
264
+ include: {
265
+ createdBy: {
266
+ select: {
267
+ id: true,
268
+ username: true,
269
+ profile: {
270
+ select: {
271
+ displayName: true,
272
+ },
273
+ },
274
+ },
275
+ },
276
+ conversation: {
277
+ include: {
278
+ messages: {
279
+ orderBy: {
280
+ createdAt: 'desc',
281
+ },
282
+ take: 1,
283
+ include: {
284
+ sender: {
285
+ select: {
286
+ id: true,
287
+ username: true,
288
+ profile: {
289
+ select: {
290
+ displayName: true,
291
+ },
292
+ },
293
+ },
294
+ },
295
+ },
296
+ },
297
+ _count: {
298
+ select: {
299
+ messages: true,
300
+ },
301
+ },
302
+ },
303
+ },
304
+ },
305
+ orderBy: {
306
+ createdAt: 'desc',
307
+ },
308
+ });
309
+ return labChats.map((labChat) => ({
310
+ id: labChat.id,
311
+ title: labChat.title,
312
+ classId: labChat.classId,
313
+ conversationId: labChat.conversationId,
314
+ createdBy: labChat.createdBy,
315
+ createdAt: labChat.createdAt,
316
+ updatedAt: labChat.updatedAt,
317
+ lastMessage: labChat.conversation.messages[0] || null,
318
+ messageCount: labChat.conversation._count.messages,
319
+ }));
320
+ }),
321
+ postToLabChat: protectedProcedure
322
+ .input(z.object({
323
+ labChatId: z.string(),
324
+ content: z.string().min(1).max(4000),
325
+ mentionedUserIds: z.array(z.string()).optional(),
326
+ }))
327
+ .mutation(async ({ input, ctx }) => {
328
+ const userId = ctx.user.id;
329
+ const { labChatId, content, mentionedUserIds = [] } = input;
330
+ // Get lab chat and verify user is a member
331
+ const labChat = await prisma.labChat.findFirst({
332
+ where: {
333
+ id: labChatId,
334
+ conversation: {
335
+ members: {
336
+ some: {
337
+ userId,
338
+ },
339
+ },
340
+ },
341
+ },
342
+ include: {
343
+ conversation: {
344
+ select: {
345
+ id: true,
346
+ },
347
+ },
348
+ },
349
+ });
350
+ if (!labChat) {
351
+ throw new TRPCError({
352
+ code: 'FORBIDDEN',
353
+ message: 'Lab chat not found or access denied',
354
+ });
355
+ }
356
+ // Verify mentioned users are members of the conversation
357
+ if (mentionedUserIds.length > 0) {
358
+ const mentionedMemberships = await prisma.conversationMember.findMany({
359
+ where: {
360
+ conversationId: labChat.conversationId,
361
+ userId: { in: mentionedUserIds },
362
+ },
363
+ });
364
+ if (mentionedMemberships.length !== mentionedUserIds.length) {
365
+ throw new TRPCError({
366
+ code: 'BAD_REQUEST',
367
+ message: 'Some mentioned users are not members of this lab chat',
368
+ });
369
+ }
370
+ }
371
+ // Create message and mentions
372
+ const result = await prisma.$transaction(async (tx) => {
373
+ const message = await tx.message.create({
374
+ data: {
375
+ content,
376
+ senderId: userId,
377
+ conversationId: labChat.conversationId,
378
+ },
379
+ include: {
380
+ sender: {
381
+ select: {
382
+ id: true,
383
+ username: true,
384
+ profile: {
385
+ select: {
386
+ displayName: true,
387
+ profilePicture: true,
388
+ },
389
+ },
390
+ },
391
+ },
392
+ },
393
+ });
394
+ // Create mentions
395
+ if (mentionedUserIds.length > 0) {
396
+ await tx.mention.createMany({
397
+ data: mentionedUserIds.map((mentionedUserId) => ({
398
+ messageId: message.id,
399
+ userId: mentionedUserId,
400
+ })),
401
+ });
402
+ }
403
+ // Update lab chat timestamp
404
+ await tx.labChat.update({
405
+ where: { id: labChatId },
406
+ data: { updatedAt: new Date() },
407
+ });
408
+ return message;
409
+ });
410
+ // Broadcast to Pusher channel (using conversation ID)
411
+ try {
412
+ await pusher.trigger(`conversation-${labChat.conversationId}`, 'new-message', {
413
+ id: result.id,
414
+ content: result.content,
415
+ senderId: result.senderId,
416
+ conversationId: result.conversationId,
417
+ createdAt: result.createdAt,
418
+ sender: result.sender,
419
+ mentionedUserIds,
420
+ labChatId, // Include lab chat ID for frontend context
421
+ });
422
+ }
423
+ catch (error) {
424
+ console.error('Failed to broadcast lab chat message:', error);
425
+ // Don't fail the request if Pusher fails
426
+ }
427
+ return {
428
+ id: result.id,
429
+ content: result.content,
430
+ senderId: result.senderId,
431
+ conversationId: result.conversationId,
432
+ createdAt: result.createdAt,
433
+ sender: result.sender,
434
+ mentionedUserIds,
435
+ labChatId,
436
+ };
437
+ }),
438
+ delete: protectedProcedure
439
+ .input(z.object({ labChatId: z.string() }))
440
+ .mutation(async ({ input, ctx }) => {
441
+ const userId = ctx.user.id;
442
+ const { labChatId } = input;
443
+ // Verify user is the creator of the lab chat
444
+ const labChat = await prisma.labChat.findFirst({
445
+ where: {
446
+ id: labChatId,
447
+ createdById: userId,
448
+ },
449
+ });
450
+ if (!labChat) {
451
+ throw new TRPCError({
452
+ code: 'FORBIDDEN',
453
+ message: 'Lab chat not found or not the creator',
454
+ });
455
+ }
456
+ // Delete lab chat and associated conversation
457
+ await prisma.$transaction(async (tx) => {
458
+ // Delete mentions first
459
+ await tx.mention.deleteMany({
460
+ where: {
461
+ message: {
462
+ conversationId: labChat.conversationId,
463
+ },
464
+ },
465
+ });
466
+ // Delete messages
467
+ await tx.message.deleteMany({
468
+ where: {
469
+ conversationId: labChat.conversationId,
470
+ },
471
+ });
472
+ // Delete conversation members
473
+ await tx.conversationMember.deleteMany({
474
+ where: {
475
+ conversationId: labChat.conversationId,
476
+ },
477
+ });
478
+ // Delete lab chat
479
+ await tx.labChat.delete({
480
+ where: { id: labChatId },
481
+ });
482
+ // Delete conversation
483
+ await tx.conversation.delete({
484
+ where: { id: labChat.conversationId },
485
+ });
486
+ });
487
+ // Broadcast lab chat deletion
488
+ try {
489
+ await pusher.trigger(`class-${labChat.classId}`, 'lab-chat-deleted', {
490
+ labChatId,
491
+ classId: labChat.classId,
492
+ });
493
+ }
494
+ catch (error) {
495
+ console.error('Failed to broadcast lab chat deletion:', error);
496
+ // Don't fail the request if Pusher fails
497
+ }
498
+ return { success: true };
499
+ }),
500
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@studious-lms/server",
3
- "version": "1.1.10",
3
+ "version": "1.1.12",
4
4
  "description": "Backend server for Studious application",
5
5
  "main": "dist/exportType.js",
6
6
  "types": "dist/exportType.d.ts",
@@ -0,0 +1,25 @@
1
+ -- CreateTable
2
+ CREATE TABLE "LabChat" (
3
+ "id" TEXT NOT NULL,
4
+ "title" TEXT NOT NULL,
5
+ "context" TEXT NOT NULL,
6
+ "classId" TEXT NOT NULL,
7
+ "conversationId" TEXT NOT NULL,
8
+ "createdById" TEXT NOT NULL,
9
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+ "updatedAt" TIMESTAMP(3) NOT NULL,
11
+
12
+ CONSTRAINT "LabChat_pkey" PRIMARY KEY ("id")
13
+ );
14
+
15
+ -- CreateIndex
16
+ CREATE UNIQUE INDEX "LabChat_conversationId_key" ON "LabChat"("conversationId");
17
+
18
+ -- AddForeignKey
19
+ ALTER TABLE "LabChat" ADD CONSTRAINT "LabChat_classId_fkey" FOREIGN KEY ("classId") REFERENCES "Class"("id") ON DELETE CASCADE ON UPDATE CASCADE;
20
+
21
+ -- AddForeignKey
22
+ ALTER TABLE "LabChat" ADD CONSTRAINT "LabChat_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
23
+
24
+ -- AddForeignKey
25
+ ALTER TABLE "LabChat" ADD CONSTRAINT "LabChat_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE CASCADE;
@@ -80,6 +80,7 @@ model User {
80
80
  conversationMemberships ConversationMember[]
81
81
  sentMessages Message[] @relation("SentMessages")
82
82
  mentions Mention[] @relation("UserMentions")
83
+ createdLabChats LabChat[] @relation("CreatedLabChats")
83
84
 
84
85
  }
85
86
 
@@ -118,6 +119,7 @@ model Class {
118
119
  gradingBoundaries GradingBoundary[] @relation("ClassToGradingBoundary")
119
120
  draftFiles File[] @relation("ClassDraftFiles")
120
121
  classFiles Folder? @relation("ClassFiles")
122
+ labChats LabChat[] @relation("ClassLabChats")
121
123
 
122
124
  school School? @relation(fields: [schoolId], references: [id])
123
125
  schoolId String?
@@ -334,6 +336,22 @@ model Conversation {
334
336
 
335
337
  members ConversationMember[]
336
338
  messages Message[]
339
+ labChat LabChat?
340
+ }
341
+
342
+ model LabChat {
343
+ id String @id @default(uuid())
344
+ title String
345
+ context String // JSON string for LLM context
346
+ classId String
347
+ conversationId String @unique
348
+ createdById String // Teacher who created the lab
349
+ createdAt DateTime @default(now())
350
+ updatedAt DateTime @updatedAt
351
+
352
+ class Class @relation("ClassLabChats", fields: [classId], references: [id], onDelete: Cascade)
353
+ conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
354
+ createdBy User @relation("CreatedLabChats", fields: [createdById], references: [id], onDelete: NoAction)
337
355
  }
338
356
 
339
357
  model ConversationMember {
@@ -15,6 +15,7 @@ import { folderRouter } from "./folder.js";
15
15
  import { notificationRouter } from "./notifications.js";
16
16
  import { conversationRouter } from "./conversation.js";
17
17
  import { messageRouter } from "./message.js";
18
+ import { labChatRouter } from "./labChat.js";
18
19
 
19
20
  export const appRouter = createTRPCRouter({
20
21
  class: classRouter,
@@ -31,6 +32,7 @@ export const appRouter = createTRPCRouter({
31
32
  notification: notificationRouter,
32
33
  conversation: conversationRouter,
33
34
  message: messageRouter,
35
+ labChat: labChatRouter,
34
36
  });
35
37
 
36
38
  // Export type router type definition
@@ -1093,6 +1093,13 @@ export const assignmentRouter = createTRPCRouter({
1093
1093
  select: {
1094
1094
  id: true,
1095
1095
  username: true,
1096
+ profile: {
1097
+ select: {
1098
+ displayName: true,
1099
+ profilePicture: true,
1100
+ profilePictureThumbnail: true,
1101
+ },
1102
+ },
1096
1103
  },
1097
1104
  },
1098
1105
  assignment: {
@@ -1195,6 +1202,13 @@ export const assignmentRouter = createTRPCRouter({
1195
1202
  select: {
1196
1203
  id: true,
1197
1204
  username: true,
1205
+ profile: {
1206
+ select: {
1207
+ displayName: true,
1208
+ profilePicture: true,
1209
+ profilePictureThumbnail: true,
1210
+ },
1211
+ },
1198
1212
  },
1199
1213
  },
1200
1214
  assignment: {
@@ -1311,6 +1325,13 @@ export const assignmentRouter = createTRPCRouter({
1311
1325
  select: {
1312
1326
  id: true,
1313
1327
  username: true,
1328
+ profile: {
1329
+ select: {
1330
+ displayName: true,
1331
+ profilePicture: true,
1332
+ profilePictureThumbnail: true,
1333
+ },
1334
+ },
1314
1335
  },
1315
1336
  },
1316
1337
  assignment: {
@@ -49,6 +49,17 @@ export const attendanceRouter = createTRPCRouter({
49
49
  students: {
50
50
  select: {
51
51
  id: true,
52
+ username: true,
53
+ profile: {
54
+ select: {
55
+ displayName: true,
56
+ profilePicture: true,
57
+ profilePictureThumbnail: true,
58
+ bio: true,
59
+ location: true,
60
+ website: true,
61
+ },
62
+ },
52
63
  },
53
64
  },
54
65
  },
@@ -117,18 +128,39 @@ export const attendanceRouter = createTRPCRouter({
117
128
  select: {
118
129
  id: true,
119
130
  username: true,
131
+ profile: {
132
+ select: {
133
+ displayName: true,
134
+ profilePicture: true,
135
+ profilePictureThumbnail: true,
136
+ },
137
+ },
120
138
  },
121
139
  },
122
140
  late: {
123
141
  select: {
124
142
  id: true,
125
143
  username: true,
144
+ profile: {
145
+ select: {
146
+ displayName: true,
147
+ profilePicture: true,
148
+ profilePictureThumbnail: true,
149
+ },
150
+ },
126
151
  },
127
152
  },
128
153
  absent: {
129
154
  select: {
130
155
  id: true,
131
156
  username: true,
157
+ profile: {
158
+ select: {
159
+ displayName: true,
160
+ profilePicture: true,
161
+ profilePictureThumbnail: true,
162
+ },
163
+ },
132
164
  },
133
165
  },
134
166
  },