@studious-lms/server 1.1.26 → 1.2.6

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.
Files changed (486) hide show
  1. package/.coderabbit.yaml +9 -0
  2. package/.env.example +53 -0
  3. package/.env.test.example +37 -0
  4. package/README.md +34 -7
  5. package/dist/exportType.d.ts.map +1 -1
  6. package/dist/exportType.js +4 -0
  7. package/dist/exportType.js.map +1 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +212 -51
  11. package/dist/index.js.map +1 -0
  12. package/dist/instrument.d.ts +2 -0
  13. package/dist/instrument.d.ts.map +1 -0
  14. package/dist/instrument.js +18 -0
  15. package/dist/instrument.js.map +1 -0
  16. package/dist/lib/config/env.d.ts +190 -0
  17. package/dist/lib/config/env.d.ts.map +1 -0
  18. package/dist/lib/config/env.js +121 -0
  19. package/dist/lib/config/env.js.map +1 -0
  20. package/dist/lib/fileUpload.d.ts +2 -2
  21. package/dist/lib/fileUpload.d.ts.map +1 -1
  22. package/dist/lib/fileUpload.js +15 -5
  23. package/dist/lib/fileUpload.js.map +1 -0
  24. package/dist/lib/googleCloudStorage.d.ts +6 -0
  25. package/dist/lib/googleCloudStorage.d.ts.map +1 -1
  26. package/dist/lib/googleCloudStorage.js +26 -6
  27. package/dist/lib/googleCloudStorage.js.map +1 -0
  28. package/dist/lib/jsonConversion.d.ts.map +1 -1
  29. package/dist/lib/jsonConversion.js +16 -14
  30. package/dist/lib/jsonConversion.js.map +1 -0
  31. package/dist/lib/jsonStyles.d.ts.map +1 -1
  32. package/dist/lib/jsonStyles.js +4 -0
  33. package/dist/lib/jsonStyles.js.map +1 -0
  34. package/dist/lib/notificationHandler.d.ts +2 -2
  35. package/dist/lib/notificationHandler.d.ts.map +1 -1
  36. package/dist/lib/notificationHandler.js +4 -0
  37. package/dist/lib/notificationHandler.js.map +1 -0
  38. package/dist/lib/prisma.d.ts +2 -2
  39. package/dist/lib/prisma.d.ts.map +1 -1
  40. package/dist/lib/prisma.js +24 -1
  41. package/dist/lib/prisma.js.map +1 -0
  42. package/dist/lib/pusher.d.ts +4 -1
  43. package/dist/lib/pusher.d.ts.map +1 -1
  44. package/dist/lib/pusher.js +14 -6
  45. package/dist/lib/pusher.js.map +1 -0
  46. package/dist/lib/redis.d.ts +5 -0
  47. package/dist/lib/redis.d.ts.map +1 -0
  48. package/dist/lib/redis.js +53 -0
  49. package/dist/lib/redis.js.map +1 -0
  50. package/dist/lib/thumbnailGenerator.d.ts +0 -21
  51. package/dist/lib/thumbnailGenerator.d.ts.map +1 -1
  52. package/dist/lib/thumbnailGenerator.js +159 -158
  53. package/dist/lib/thumbnailGenerator.js.map +1 -0
  54. package/dist/middleware/auth.d.ts.map +1 -1
  55. package/dist/middleware/auth.js +41 -93
  56. package/dist/middleware/auth.js.map +1 -0
  57. package/dist/middleware/logging.d.ts.map +1 -1
  58. package/dist/middleware/logging.js +4 -0
  59. package/dist/middleware/logging.js.map +1 -0
  60. package/dist/middleware/security.d.ts +5 -0
  61. package/dist/middleware/security.d.ts.map +1 -0
  62. package/dist/middleware/security.js +77 -0
  63. package/dist/middleware/security.js.map +1 -0
  64. package/dist/models/agenda.d.ts +97 -0
  65. package/dist/models/agenda.d.ts.map +1 -0
  66. package/dist/models/agenda.js +40 -0
  67. package/dist/models/agenda.js.map +1 -0
  68. package/dist/models/announcement.d.ts +223 -0
  69. package/dist/models/announcement.d.ts.map +1 -0
  70. package/dist/models/announcement.js +120 -0
  71. package/dist/models/announcement.js.map +1 -0
  72. package/dist/models/assignment.d.ts +1292 -0
  73. package/dist/models/assignment.d.ts.map +1 -0
  74. package/dist/models/assignment.js +309 -0
  75. package/dist/models/assignment.js.map +1 -0
  76. package/dist/models/attendance.d.ts +180 -0
  77. package/dist/models/attendance.d.ts.map +1 -0
  78. package/dist/models/attendance.js +188 -0
  79. package/dist/models/attendance.js.map +1 -0
  80. package/dist/models/auth.d.ts +153 -0
  81. package/dist/models/auth.d.ts.map +1 -0
  82. package/dist/models/auth.js +217 -0
  83. package/dist/models/auth.js.map +1 -0
  84. package/dist/models/class.d.ts +439 -0
  85. package/dist/models/class.d.ts.map +1 -0
  86. package/dist/models/class.js +546 -0
  87. package/dist/models/class.js.map +1 -0
  88. package/dist/models/comment.d.ts +171 -0
  89. package/dist/models/comment.d.ts.map +1 -0
  90. package/dist/models/comment.js +138 -0
  91. package/dist/models/comment.js.map +1 -0
  92. package/dist/models/conversation.d.ts +164 -0
  93. package/dist/models/conversation.d.ts.map +1 -0
  94. package/dist/models/conversation.js +175 -0
  95. package/dist/models/conversation.js.map +1 -0
  96. package/dist/models/event.d.ts +295 -0
  97. package/dist/models/event.d.ts.map +1 -0
  98. package/dist/models/event.js +145 -0
  99. package/dist/models/event.js.map +1 -0
  100. package/dist/models/file.d.ts +536 -0
  101. package/dist/models/file.d.ts.map +1 -0
  102. package/dist/models/file.js +126 -0
  103. package/dist/models/file.js.map +1 -0
  104. package/dist/models/folder.d.ts +295 -0
  105. package/dist/models/folder.d.ts.map +1 -0
  106. package/dist/models/folder.js +202 -0
  107. package/dist/models/folder.js.map +1 -0
  108. package/dist/models/labChat.d.ts +243 -0
  109. package/dist/models/labChat.d.ts.map +1 -0
  110. package/dist/models/labChat.js +204 -0
  111. package/dist/models/labChat.js.map +1 -0
  112. package/dist/models/marketing.d.ts +72 -0
  113. package/dist/models/marketing.d.ts.map +1 -0
  114. package/dist/models/marketing.js +26 -0
  115. package/dist/models/marketing.js.map +1 -0
  116. package/dist/models/message.d.ts +100 -0
  117. package/dist/models/message.d.ts.map +1 -0
  118. package/dist/models/message.js +131 -0
  119. package/dist/models/message.js.map +1 -0
  120. package/dist/models/newtonChat.d.ts +72 -0
  121. package/dist/models/newtonChat.d.ts.map +1 -0
  122. package/dist/models/newtonChat.js +61 -0
  123. package/dist/models/newtonChat.js.map +1 -0
  124. package/dist/models/notification.d.ts +65 -0
  125. package/dist/models/notification.d.ts.map +1 -0
  126. package/dist/models/notification.js +46 -0
  127. package/dist/models/notification.js.map +1 -0
  128. package/dist/models/section.d.ts +102 -0
  129. package/dist/models/section.d.ts.map +1 -0
  130. package/dist/models/section.js +83 -0
  131. package/dist/models/section.js.map +1 -0
  132. package/dist/models/user.d.ts +39 -0
  133. package/dist/models/user.d.ts.map +1 -0
  134. package/dist/models/user.js +38 -0
  135. package/dist/models/user.js.map +1 -0
  136. package/dist/models/worksheet.d.ts +460 -0
  137. package/dist/models/worksheet.d.ts.map +1 -0
  138. package/dist/models/worksheet.js +200 -0
  139. package/dist/models/worksheet.js.map +1 -0
  140. package/dist/pipelines/aiLabChat.d.ts +21 -0
  141. package/dist/pipelines/aiLabChat.d.ts.map +1 -0
  142. package/dist/pipelines/aiLabChat.js +460 -0
  143. package/dist/pipelines/aiLabChat.js.map +1 -0
  144. package/dist/pipelines/aiNewtonChat.d.ts +30 -0
  145. package/dist/pipelines/aiNewtonChat.d.ts.map +1 -0
  146. package/dist/pipelines/aiNewtonChat.js +289 -0
  147. package/dist/pipelines/aiNewtonChat.js.map +1 -0
  148. package/dist/pipelines/gradeWorksheet.d.ts +30 -0
  149. package/dist/pipelines/gradeWorksheet.d.ts.map +1 -0
  150. package/dist/pipelines/gradeWorksheet.js +252 -0
  151. package/dist/pipelines/gradeWorksheet.js.map +1 -0
  152. package/dist/routers/_app.d.ts +6438 -3910
  153. package/dist/routers/_app.d.ts.map +1 -1
  154. package/dist/routers/_app.js +10 -0
  155. package/dist/routers/_app.js.map +1 -0
  156. package/dist/routers/agenda.d.ts +58 -6
  157. package/dist/routers/agenda.d.ts.map +1 -1
  158. package/dist/routers/agenda.js +6 -58
  159. package/dist/routers/agenda.js.map +1 -0
  160. package/dist/routers/announcement.d.ts +325 -6
  161. package/dist/routers/announcement.d.ts.map +1 -1
  162. package/dist/routers/announcement.js +543 -77
  163. package/dist/routers/announcement.js.map +1 -0
  164. package/dist/routers/assignment.d.ts +419 -357
  165. package/dist/routers/assignment.d.ts.map +1 -1
  166. package/dist/routers/assignment.js +100 -1689
  167. package/dist/routers/assignment.js.map +1 -0
  168. package/dist/routers/attendance.d.ts +20 -9
  169. package/dist/routers/attendance.d.ts.map +1 -1
  170. package/dist/routers/attendance.js +10 -263
  171. package/dist/routers/attendance.js.map +1 -0
  172. package/dist/routers/auth.d.ts +21 -1
  173. package/dist/routers/auth.d.ts.map +1 -1
  174. package/dist/routers/auth.js +37 -241
  175. package/dist/routers/auth.js.map +1 -0
  176. package/dist/routers/class.d.ts +198 -68
  177. package/dist/routers/class.d.ts.map +1 -1
  178. package/dist/routers/class.js +88 -909
  179. package/dist/routers/class.js.map +1 -0
  180. package/dist/routers/comment.d.ts +153 -0
  181. package/dist/routers/comment.d.ts.map +1 -0
  182. package/dist/routers/comment.js +58 -0
  183. package/dist/routers/comment.js.map +1 -0
  184. package/dist/routers/conversation.d.ts +73 -3
  185. package/dist/routers/conversation.d.ts.map +1 -1
  186. package/dist/routers/conversation.js +23 -265
  187. package/dist/routers/conversation.js.map +1 -0
  188. package/dist/routers/event.d.ts +46 -37
  189. package/dist/routers/event.d.ts.map +1 -1
  190. package/dist/routers/event.js +15 -431
  191. package/dist/routers/event.js.map +1 -0
  192. package/dist/routers/file.d.ts +4 -2
  193. package/dist/routers/file.d.ts.map +1 -1
  194. package/dist/routers/file.js +11 -298
  195. package/dist/routers/file.js.map +1 -0
  196. package/dist/routers/folder.d.ts +21 -14
  197. package/dist/routers/folder.d.ts.map +1 -1
  198. package/dist/routers/folder.js +36 -743
  199. package/dist/routers/folder.js.map +1 -0
  200. package/dist/routers/labChat.d.ts +12 -9
  201. package/dist/routers/labChat.d.ts.map +1 -1
  202. package/dist/routers/labChat.js +21 -885
  203. package/dist/routers/labChat.js.map +1 -0
  204. package/dist/routers/marketing.d.ts +2 -2
  205. package/dist/routers/marketing.d.ts.map +1 -1
  206. package/dist/routers/marketing.js +9 -54
  207. package/dist/routers/marketing.js.map +1 -0
  208. package/dist/routers/message.d.ts +2 -1
  209. package/dist/routers/message.d.ts.map +1 -1
  210. package/dist/routers/message.js +29 -519
  211. package/dist/routers/message.js.map +1 -0
  212. package/dist/routers/newtonChat.d.ts +55 -0
  213. package/dist/routers/newtonChat.d.ts.map +1 -0
  214. package/dist/routers/newtonChat.js +22 -0
  215. package/dist/routers/newtonChat.js.map +1 -0
  216. package/dist/routers/notifications.d.ts +8 -8
  217. package/dist/routers/notifications.d.ts.map +1 -1
  218. package/dist/routers/notifications.js +20 -81
  219. package/dist/routers/notifications.js.map +1 -0
  220. package/dist/routers/section.d.ts +23 -8
  221. package/dist/routers/section.d.ts.map +1 -1
  222. package/dist/routers/section.js +23 -273
  223. package/dist/routers/section.js.map +1 -0
  224. package/dist/routers/user.d.ts +1 -1
  225. package/dist/routers/user.d.ts.map +1 -1
  226. package/dist/routers/user.js +34 -204
  227. package/dist/routers/user.js.map +1 -0
  228. package/dist/routers/worksheet.d.ts +362 -0
  229. package/dist/routers/worksheet.d.ts.map +1 -0
  230. package/dist/routers/worksheet.js +153 -0
  231. package/dist/routers/worksheet.js.map +1 -0
  232. package/dist/seedDatabase.d.ts +2 -3
  233. package/dist/seedDatabase.d.ts.map +1 -1
  234. package/dist/seedDatabase.js +309 -288
  235. package/dist/seedDatabase.js.map +1 -0
  236. package/dist/server/pipelines/aiLabChat.d.ts +21 -0
  237. package/dist/server/pipelines/aiLabChat.d.ts.map +1 -0
  238. package/dist/server/pipelines/aiLabChat.js +456 -0
  239. package/dist/server/pipelines/aiLabChat.js.map +1 -0
  240. package/dist/server/pipelines/aiNewtonChat.d.ts +30 -0
  241. package/dist/server/pipelines/aiNewtonChat.d.ts.map +1 -0
  242. package/dist/server/pipelines/aiNewtonChat.js +285 -0
  243. package/dist/server/pipelines/aiNewtonChat.js.map +1 -0
  244. package/dist/server/pipelines/gradeWorksheet.d.ts +30 -0
  245. package/dist/server/pipelines/gradeWorksheet.d.ts.map +1 -0
  246. package/dist/server/pipelines/gradeWorksheet.js +248 -0
  247. package/dist/server/pipelines/gradeWorksheet.js.map +1 -0
  248. package/dist/services/agenda.d.ts +100 -0
  249. package/dist/services/agenda.d.ts.map +1 -0
  250. package/dist/services/agenda.js +21 -0
  251. package/dist/services/agenda.js.map +1 -0
  252. package/dist/services/announcement.d.ts +135 -0
  253. package/dist/services/announcement.d.ts.map +1 -0
  254. package/dist/services/announcement.js +223 -0
  255. package/dist/services/announcement.js.map +1 -0
  256. package/dist/services/assignment.d.ts +1462 -0
  257. package/dist/services/assignment.d.ts.map +1 -0
  258. package/dist/services/assignment.js +898 -0
  259. package/dist/services/assignment.js.map +1 -0
  260. package/dist/services/attendance.d.ts +93 -0
  261. package/dist/services/attendance.d.ts.map +1 -0
  262. package/dist/services/attendance.js +61 -0
  263. package/dist/services/attendance.js.map +1 -0
  264. package/dist/services/auth.d.ts +68 -0
  265. package/dist/services/auth.d.ts.map +1 -0
  266. package/dist/services/auth.js +218 -0
  267. package/dist/services/auth.js.map +1 -0
  268. package/dist/services/class.d.ts +621 -0
  269. package/dist/services/class.d.ts.map +1 -0
  270. package/dist/services/class.js +474 -0
  271. package/dist/services/class.js.map +1 -0
  272. package/dist/services/comment.d.ts +100 -0
  273. package/dist/services/comment.d.ts.map +1 -0
  274. package/dist/services/comment.js +83 -0
  275. package/dist/services/comment.js.map +1 -0
  276. package/dist/services/conversation.d.ts +159 -0
  277. package/dist/services/conversation.d.ts.map +1 -0
  278. package/dist/services/conversation.js +138 -0
  279. package/dist/services/conversation.js.map +1 -0
  280. package/dist/services/event.d.ts +216 -0
  281. package/dist/services/event.d.ts.map +1 -0
  282. package/dist/services/event.js +168 -0
  283. package/dist/services/event.js.map +1 -0
  284. package/dist/services/file.d.ts +74 -0
  285. package/dist/services/file.d.ts.map +1 -0
  286. package/dist/services/file.js +133 -0
  287. package/dist/services/file.js.map +1 -0
  288. package/dist/services/folder.d.ts +239 -0
  289. package/dist/services/folder.d.ts.map +1 -0
  290. package/dist/services/folder.js +248 -0
  291. package/dist/services/folder.js.map +1 -0
  292. package/dist/services/labChat.d.ts +165 -0
  293. package/dist/services/labChat.d.ts.map +1 -0
  294. package/dist/services/labChat.js +289 -0
  295. package/dist/services/labChat.js.map +1 -0
  296. package/dist/services/marketing.d.ts +50 -0
  297. package/dist/services/marketing.d.ts.map +1 -0
  298. package/dist/services/marketing.js +32 -0
  299. package/dist/services/marketing.js.map +1 -0
  300. package/dist/services/message.d.ts +95 -0
  301. package/dist/services/message.d.ts.map +1 -0
  302. package/dist/services/message.js +350 -0
  303. package/dist/services/message.js.map +1 -0
  304. package/dist/services/newtonChat.d.ts +22 -0
  305. package/dist/services/newtonChat.d.ts.map +1 -0
  306. package/dist/services/newtonChat.js +174 -0
  307. package/dist/services/newtonChat.js.map +1 -0
  308. package/dist/services/notification.d.ts +65 -0
  309. package/dist/services/notification.d.ts.map +1 -0
  310. package/dist/services/notification.js +33 -0
  311. package/dist/services/notification.js.map +1 -0
  312. package/dist/services/section.d.ts +53 -0
  313. package/dist/services/section.d.ts.map +1 -0
  314. package/dist/services/section.js +199 -0
  315. package/dist/services/section.js.map +1 -0
  316. package/dist/services/user.d.ts +48 -0
  317. package/dist/services/user.d.ts.map +1 -0
  318. package/dist/services/user.js +141 -0
  319. package/dist/services/user.js.map +1 -0
  320. package/dist/services/worksheet.d.ts +239 -0
  321. package/dist/services/worksheet.d.ts.map +1 -0
  322. package/dist/services/worksheet.js +235 -0
  323. package/dist/services/worksheet.js.map +1 -0
  324. package/dist/socket/handlers.d.ts.map +1 -1
  325. package/dist/socket/handlers.js +4 -0
  326. package/dist/socket/handlers.js.map +1 -0
  327. package/dist/trpc.d.ts.map +1 -1
  328. package/dist/trpc.js +4 -0
  329. package/dist/trpc.js.map +1 -0
  330. package/dist/types/trpc.d.ts.map +1 -1
  331. package/dist/types/trpc.js +4 -0
  332. package/dist/types/trpc.js.map +1 -0
  333. package/dist/utils/aiUser.d.ts +1 -3
  334. package/dist/utils/aiUser.d.ts.map +1 -1
  335. package/dist/utils/aiUser.js +8 -3
  336. package/dist/utils/aiUser.js.map +1 -0
  337. package/dist/utils/email.d.ts +12 -1
  338. package/dist/utils/email.d.ts.map +1 -1
  339. package/dist/utils/email.js +26 -4
  340. package/dist/utils/email.js.map +1 -0
  341. package/dist/utils/generateInviteCode.d.ts +1 -2
  342. package/dist/utils/generateInviteCode.d.ts.map +1 -1
  343. package/dist/utils/generateInviteCode.js +5 -2
  344. package/dist/utils/generateInviteCode.js.map +1 -0
  345. package/dist/utils/inference.d.ts +8 -0
  346. package/dist/utils/inference.d.ts.map +1 -1
  347. package/dist/utils/inference.js +78 -10
  348. package/dist/utils/inference.js.map +1 -0
  349. package/dist/utils/logger.d.ts +3 -0
  350. package/dist/utils/logger.d.ts.map +1 -1
  351. package/dist/utils/logger.js +8 -1
  352. package/dist/utils/logger.js.map +1 -0
  353. package/dist/utils/prismaErrorHandler.d.ts.map +1 -1
  354. package/dist/utils/prismaErrorHandler.js +7 -0
  355. package/dist/utils/prismaErrorHandler.js.map +1 -0
  356. package/dist/utils/prismaWrapper.d.ts +1 -0
  357. package/dist/utils/prismaWrapper.d.ts.map +1 -1
  358. package/dist/utils/prismaWrapper.js +8 -0
  359. package/dist/utils/prismaWrapper.js.map +1 -0
  360. package/docker-compose.yml +19 -0
  361. package/package.json +21 -4
  362. package/prisma/migrations/20251109122857_annuoncements_comments/migration.sql +30 -0
  363. package/prisma/migrations/20251109135555_reactions_announcements_comments/migration.sql +35 -0
  364. package/prisma/schema.prisma +180 -12
  365. package/scripts/test-pre-push.ts +14 -0
  366. package/src/index.ts +247 -52
  367. package/src/instrument.ts +15 -0
  368. package/src/lib/config/env.ts +132 -0
  369. package/src/lib/fileUpload.ts +13 -6
  370. package/src/lib/googleCloudStorage.ts +23 -6
  371. package/src/lib/jsonConversion.ts +12 -14
  372. package/src/lib/prisma.ts +23 -2
  373. package/src/lib/pusher.ts +11 -6
  374. package/src/lib/redis.ts +56 -0
  375. package/src/lib/thumbnailGenerator.ts +170 -168
  376. package/src/middleware/auth.ts +86 -137
  377. package/src/middleware/security.ts +80 -0
  378. package/src/models/agenda.ts +46 -0
  379. package/src/models/announcement.ts +134 -0
  380. package/src/models/assignment.ts +322 -0
  381. package/src/models/attendance.ts +208 -0
  382. package/src/models/auth.ts +247 -0
  383. package/src/models/class.ts +598 -0
  384. package/src/models/comment.ts +152 -0
  385. package/src/models/conversation.ts +200 -0
  386. package/src/models/event.ts +177 -0
  387. package/src/models/file.ts +129 -0
  388. package/src/models/folder.ts +225 -0
  389. package/src/models/labChat.ts +213 -0
  390. package/src/models/marketing.ts +45 -0
  391. package/src/models/message.ts +153 -0
  392. package/src/models/newtonChat.ts +70 -0
  393. package/src/models/notification.ts +54 -0
  394. package/src/models/section.ts +98 -0
  395. package/src/models/user.ts +47 -0
  396. package/src/models/worksheet.ts +294 -0
  397. package/src/pipelines/aiLabChat.ts +511 -0
  398. package/src/pipelines/aiNewtonChat.ts +347 -0
  399. package/src/pipelines/gradeWorksheet.ts +286 -0
  400. package/src/routers/_app.ts +6 -0
  401. package/src/routers/agenda.ts +3 -61
  402. package/src/routers/announcement.ts +616 -79
  403. package/src/routers/assignment.ts +148 -1827
  404. package/src/routers/attendance.ts +16 -277
  405. package/src/routers/auth.ts +79 -313
  406. package/src/routers/class.ts +265 -1038
  407. package/src/routers/comment.ts +76 -0
  408. package/src/routers/conversation.ts +53 -284
  409. package/src/routers/event.ts +50 -481
  410. package/src/routers/file.ts +45 -344
  411. package/src/routers/folder.ts +107 -836
  412. package/src/routers/labChat.ts +29 -969
  413. package/src/routers/marketing.ts +35 -77
  414. package/src/routers/message.ts +45 -571
  415. package/src/routers/newtonChat.ts +36 -0
  416. package/src/routers/notifications.ts +32 -82
  417. package/src/routers/section.ts +58 -322
  418. package/src/routers/user.ts +49 -226
  419. package/src/routers/worksheet.ts +252 -0
  420. package/src/seedDatabase.ts +328 -289
  421. package/src/services/agenda.ts +21 -0
  422. package/src/services/announcement.ts +290 -0
  423. package/src/services/assignment.ts +1198 -0
  424. package/src/services/attendance.ts +85 -0
  425. package/src/services/auth.ts +277 -0
  426. package/src/services/class.ts +622 -0
  427. package/src/services/comment.ts +106 -0
  428. package/src/services/conversation.ts +213 -0
  429. package/src/services/event.ts +231 -0
  430. package/src/services/file.ts +167 -0
  431. package/src/services/folder.ts +316 -0
  432. package/src/services/labChat.ts +352 -0
  433. package/src/services/marketing.ts +57 -0
  434. package/src/services/message.ts +461 -0
  435. package/src/services/newtonChat.ts +222 -0
  436. package/src/services/notification.ts +50 -0
  437. package/src/services/section.ts +283 -0
  438. package/src/services/user.ts +172 -0
  439. package/src/services/worksheet.ts +358 -0
  440. package/src/trpc.ts +4 -0
  441. package/src/utils/aiUser.ts +4 -3
  442. package/src/utils/email.ts +33 -4
  443. package/src/utils/generateInviteCode.ts +1 -3
  444. package/src/utils/inference.ts +89 -10
  445. package/src/utils/logger.ts +4 -1
  446. package/src/utils/prismaErrorHandler.ts +3 -0
  447. package/src/utils/prismaWrapper.ts +4 -0
  448. package/tests/globalSetup.ts +62 -0
  449. package/tests/helpers.ts +22 -0
  450. package/tests/middleware/security.test.ts +42 -0
  451. package/tests/routers/agenda.test.ts +138 -0
  452. package/tests/routers/announcement.test.ts +490 -0
  453. package/tests/routers/assignment.test.ts +837 -0
  454. package/tests/routers/attendance.test.ts +160 -0
  455. package/tests/routers/auth.test.ts +171 -0
  456. package/tests/{class.test.ts → routers/class.test.ts} +163 -92
  457. package/tests/routers/comment.test.ts +126 -0
  458. package/tests/routers/conversation.test.ts +145 -0
  459. package/tests/routers/event.test.ts +289 -0
  460. package/tests/routers/folder.test.ts +178 -0
  461. package/tests/routers/labChat.test.ts +115 -0
  462. package/tests/routers/marketing.test.ts +59 -0
  463. package/tests/routers/message.test.ts +123 -0
  464. package/tests/routers/notification.test.ts +69 -0
  465. package/tests/routers/section.test.ts +208 -0
  466. package/tests/server/rateLimit.test.ts +73 -0
  467. package/tests/setup.ts +39 -59
  468. package/tests/user.test.ts +136 -0
  469. package/tests/utils/aiUser.test.ts +22 -0
  470. package/tests/utils/generateInviteCode.test.ts +24 -0
  471. package/tests/utils/logger.test.ts +74 -0
  472. package/tests/utils/prismaErrorHandler.test.ts +101 -0
  473. package/tests/utils/prismaWrapper.test.ts +82 -0
  474. package/tests/worksheet.test.ts +181 -0
  475. package/tsconfig.json +9 -2
  476. package/vitest.config.ts +30 -1
  477. package/vitest.unit.config.ts +21 -0
  478. package/API_SPECIFICATION.md +0 -1597
  479. package/BASE64_REMOVAL_SUMMARY.md +0 -164
  480. package/CHAT_API_SPEC.md +0 -579
  481. package/LAB_CHAT_API_SPEC.md +0 -518
  482. package/dist/routers/school.d.ts +0 -208
  483. package/dist/routers/school.d.ts.map +0 -1
  484. package/dist/routers/school.js +0 -481
  485. package/src/lib/notificationHandler.ts +0 -36
  486. package/tests/auth.test.ts +0 -25
@@ -1,19 +1,12 @@
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
- import {
7
- inferenceClient,
8
- sendAIMessage,
9
- type LabChatContext
10
- } from '../utils/inference.js';
11
- import { logger } from '../utils/logger.js';
12
- import { isAIUser } from '../utils/aiUser.js';
13
- import { bucket } from '../lib/googleCloudStorage.js';
14
- import { createPdf } from "../lib/jsonConversion.js"
15
- import OpenAI from 'openai';
16
- import { v4 as uuidv4 } from "uuid";
1
+ import { z } from "zod";
2
+ import { createTRPCRouter, protectedProcedure } from "../trpc.js";
3
+ import {
4
+ createLabChat,
5
+ getLabChat,
6
+ listLabChats,
7
+ postToLabChat,
8
+ deleteLabChat,
9
+ } from "../services/labChat.js";
17
10
 
18
11
  export const labChatRouter = createTRPCRouter({
19
12
  create: protectedProcedure
@@ -21,422 +14,24 @@ export const labChatRouter = createTRPCRouter({
21
14
  z.object({
22
15
  classId: z.string(),
23
16
  title: z.string().min(1).max(200),
24
- context: z.string(), // JSON string for LLM context
17
+ context: z.string(),
25
18
  })
26
19
  )
27
- .mutation(async ({ input, ctx }) => {
28
- const userId = ctx.user!.id;
29
- const { classId, title, context } = input;
30
-
31
- // Verify user is a teacher in the class
32
- const classWithTeachers = await prisma.class.findFirst({
33
- where: {
34
- id: classId,
35
- teachers: {
36
- some: {
37
- id: userId,
38
- },
39
- },
40
- },
41
- include: {
42
- students: {
43
- select: {
44
- id: true,
45
- username: true,
46
- profile: {
47
- select: {
48
- displayName: true,
49
- profilePicture: true,
50
- },
51
- },
52
- },
53
- },
54
- teachers: {
55
- select: {
56
- id: true,
57
- username: true,
58
- profile: {
59
- select: {
60
- displayName: true,
61
- profilePicture: true,
62
- },
63
- },
64
- },
65
- },
66
- },
67
- });
68
-
69
- if (!classWithTeachers) {
70
- throw new TRPCError({
71
- code: 'FORBIDDEN',
72
- message: 'Not a teacher in this class',
73
- });
74
- }
75
-
76
- // Validate context is valid JSON
77
- try {
78
- JSON.parse(context);
79
- } catch (error) {
80
- throw new TRPCError({
81
- code: 'BAD_REQUEST',
82
- message: 'Context must be valid JSON',
83
- });
84
- }
85
-
86
- // Create lab chat with associated conversation
87
- const result = await prisma.$transaction(async (tx) => {
88
- // Create conversation for the lab chat
89
- const conversation = await tx.conversation.create({
90
- data: {
91
- type: 'GROUP',
92
- name: `Lab: ${title}`,
93
- displayInChat: false, // Lab chats don't show in regular chat list
94
- },
95
- });
96
-
97
- // Add only teachers to the conversation (this is for course material creation)
98
- const teacherMembers = classWithTeachers.teachers.map(t => ({
99
- userId: t.id,
100
- role: 'ADMIN' as const
101
- }));
102
-
103
- await tx.conversationMember.createMany({
104
- data: teacherMembers.map(member => ({
105
- userId: member.userId,
106
- conversationId: conversation.id,
107
- role: member.role,
108
- })),
109
- });
110
-
111
- // Create the lab chat
112
- const labChat = await tx.labChat.create({
113
- data: {
114
- title,
115
- context,
116
- classId,
117
- conversationId: conversation.id,
118
- createdById: userId,
119
- },
120
- include: {
121
- conversation: {
122
- include: {
123
- members: {
124
- include: {
125
- user: {
126
- select: {
127
- id: true,
128
- username: true,
129
- profile: {
130
- select: {
131
- displayName: true,
132
- profilePicture: true,
133
- },
134
- },
135
- },
136
- },
137
- },
138
- },
139
- },
140
- },
141
- createdBy: {
142
- select: {
143
- id: true,
144
- username: true,
145
- profile: {
146
- select: {
147
- displayName: true,
148
- },
149
- },
150
- },
151
- },
152
- class: {
153
- select: {
154
- id: true,
155
- name: true,
156
- subject: true,
157
- section: true,
158
- },
159
- },
160
- },
161
- });
162
-
163
- return labChat;
164
- });
165
-
166
- // Generate AI introduction message in parallel (don't await - fire and forget)
167
- generateAndSendLabIntroduction(result.id, result.conversationId, context, classWithTeachers.subject || 'Lab').catch(error => {
168
- logger.error('Failed to generate AI introduction:', { error, labChatId: result.id });
169
- });
170
-
171
- // Broadcast lab chat creation to class members
172
- try {
173
- await pusher.trigger(`class-${classId}`, 'lab-chat-created', {
174
- id: result.id,
175
- title: result.title,
176
- classId: result.classId,
177
- conversationId: result.conversationId,
178
- createdBy: result.createdBy,
179
- createdAt: result.createdAt,
180
- });
181
- } catch (error) {
182
- console.error('Failed to broadcast lab chat creation:', error);
183
- // Don't fail the request if Pusher fails
184
- }
185
-
186
- return result;
187
- }),
20
+ .mutation(({ ctx, input }) =>
21
+ createLabChat(ctx.user!.id, {
22
+ classId: input.classId,
23
+ title: input.title,
24
+ context: input.context,
25
+ })
26
+ ),
188
27
 
189
28
  get: protectedProcedure
190
29
  .input(z.object({ labChatId: z.string() }))
191
- .query(async ({ input, ctx }) => {
192
- const userId = ctx.user!.id;
193
- const { labChatId } = input;
194
-
195
- // First, try to find the lab chat if user is already a member
196
- let labChat = await prisma.labChat.findFirst({
197
- where: {
198
- id: labChatId,
199
- conversation: {
200
- members: {
201
- some: {
202
- userId,
203
- },
204
- },
205
- },
206
- },
207
- include: {
208
- conversation: {
209
- include: {
210
- members: {
211
- include: {
212
- user: {
213
- select: {
214
- id: true,
215
- username: true,
216
- profile: {
217
- select: {
218
- displayName: true,
219
- profilePicture: true,
220
- },
221
- },
222
- },
223
- },
224
- },
225
- },
226
- },
227
- },
228
- createdBy: {
229
- select: {
230
- id: true,
231
- username: true,
232
- profile: {
233
- select: {
234
- displayName: true,
235
- },
236
- },
237
- },
238
- },
239
- class: {
240
- select: {
241
- id: true,
242
- name: true,
243
- subject: true,
244
- section: true,
245
- },
246
- },
247
- },
248
- });
249
-
250
- // If not found, check if user is a teacher in the class
251
- if (!labChat) {
252
- const labChatForTeacher = await prisma.labChat.findFirst({
253
- where: {
254
- id: labChatId,
255
- class: {
256
- teachers: {
257
- some: {
258
- id: userId,
259
- },
260
- },
261
- },
262
- },
263
- include: {
264
- conversation: {
265
- select: {
266
- id: true,
267
- },
268
- },
269
- },
270
- });
271
-
272
- if (labChatForTeacher) {
273
- // Add teacher to conversation
274
- await prisma.conversationMember.create({
275
- data: {
276
- userId,
277
- conversationId: labChatForTeacher.conversation.id,
278
- role: 'ADMIN',
279
- },
280
- });
281
-
282
- // Now fetch the full lab chat with the user as a member
283
- labChat = await prisma.labChat.findFirst({
284
- where: {
285
- id: labChatId,
286
- },
287
- include: {
288
- conversation: {
289
- include: {
290
- members: {
291
- include: {
292
- user: {
293
- select: {
294
- id: true,
295
- username: true,
296
- profile: {
297
- select: {
298
- displayName: true,
299
- profilePicture: true,
300
- },
301
- },
302
- },
303
- },
304
- },
305
- },
306
- },
307
- },
308
- createdBy: {
309
- select: {
310
- id: true,
311
- username: true,
312
- profile: {
313
- select: {
314
- displayName: true,
315
- },
316
- },
317
- },
318
- },
319
- class: {
320
- select: {
321
- id: true,
322
- name: true,
323
- subject: true,
324
- section: true,
325
- },
326
- },
327
- },
328
- });
329
- }
330
- }
331
-
332
- if (!labChat) {
333
- throw new TRPCError({
334
- code: 'NOT_FOUND',
335
- message: 'Lab chat not found or access denied',
336
- });
337
- }
338
-
339
- return labChat;
340
- }),
30
+ .query(({ ctx, input }) => getLabChat(ctx.user!.id, input.labChatId)),
341
31
 
342
32
  list: protectedProcedure
343
33
  .input(z.object({ classId: z.string() }))
344
- .query(async ({ input, ctx }) => {
345
- const userId = ctx.user!.id;
346
- const { classId } = input;
347
-
348
- // Verify user is a member of the class
349
- const classMembership = await prisma.class.findFirst({
350
- where: {
351
- id: classId,
352
- OR: [
353
- {
354
- students: {
355
- some: {
356
- id: userId,
357
- },
358
- },
359
- },
360
- {
361
- teachers: {
362
- some: {
363
- id: userId,
364
- },
365
- },
366
- },
367
- ],
368
- },
369
- });
370
-
371
- if (!classMembership) {
372
- throw new TRPCError({
373
- code: 'FORBIDDEN',
374
- message: 'Not a member of this class',
375
- });
376
- }
377
-
378
- const labChats = await prisma.labChat.findMany({
379
- where: {
380
- classId,
381
- },
382
- include: {
383
- createdBy: {
384
- select: {
385
- id: true,
386
- username: true,
387
- profile: {
388
- select: {
389
- displayName: true,
390
- },
391
- },
392
- },
393
- },
394
- conversation: {
395
- include: {
396
- messages: {
397
- orderBy: {
398
- createdAt: 'desc',
399
- },
400
- take: 1,
401
- include: {
402
- sender: {
403
- select: {
404
- id: true,
405
- username: true,
406
- profile: {
407
- select: {
408
- displayName: true,
409
- },
410
- },
411
- },
412
- },
413
- },
414
- },
415
- _count: {
416
- select: {
417
- messages: true,
418
- },
419
- },
420
- },
421
- },
422
- },
423
- orderBy: {
424
- createdAt: 'desc',
425
- },
426
- });
427
-
428
- return labChats.map((labChat) => ({
429
- id: labChat.id,
430
- title: labChat.title,
431
- classId: labChat.classId,
432
- conversationId: labChat.conversationId,
433
- createdBy: labChat.createdBy,
434
- createdAt: labChat.createdAt,
435
- updatedAt: labChat.updatedAt,
436
- lastMessage: labChat.conversation.messages[0] || null,
437
- messageCount: labChat.conversation._count.messages,
438
- }));
439
- }),
34
+ .query(({ ctx, input }) => listLabChats(ctx.user!.id, input.classId)),
440
35
 
441
36
  postToLabChat: protectedProcedure
442
37
  .input(
@@ -446,552 +41,17 @@ export const labChatRouter = createTRPCRouter({
446
41
  mentionedUserIds: z.array(z.string()).optional(),
447
42
  })
448
43
  )
449
- .mutation(async ({ input, ctx }) => {
450
- const userId = ctx.user!.id;
451
- const { labChatId, content, mentionedUserIds = [] } = input;
452
-
453
- // Get lab chat and verify user is a member
454
- const labChat = await prisma.labChat.findFirst({
455
- where: {
456
- id: labChatId,
457
- conversation: {
458
- members: {
459
- some: {
460
- userId,
461
- },
462
- },
463
- },
464
- },
465
- include: {
466
- conversation: {
467
- select: {
468
- id: true,
469
- },
470
- },
471
- },
472
- });
473
-
474
- if (!labChat) {
475
- throw new TRPCError({
476
- code: 'FORBIDDEN',
477
- message: 'Lab chat not found or access denied',
478
- });
479
- }
480
-
481
- // Verify mentioned users are members of the conversation
482
- if (mentionedUserIds.length > 0) {
483
- const mentionedMemberships = await prisma.conversationMember.findMany({
484
- where: {
485
- conversationId: labChat.conversationId,
486
- userId: { in: mentionedUserIds },
487
- },
488
- });
489
-
490
- if (mentionedMemberships.length !== mentionedUserIds.length) {
491
- throw new TRPCError({
492
- code: 'BAD_REQUEST',
493
- message: 'Some mentioned users are not members of this lab chat',
494
- });
495
- }
496
- }
497
-
498
- // Create message and mentions
499
- const result = await prisma.$transaction(async (tx) => {
500
- const message = await tx.message.create({
501
- data: {
502
- content,
503
- senderId: userId,
504
- conversationId: labChat.conversationId,
505
- },
506
- include: {
507
- sender: {
508
- select: {
509
- id: true,
510
- username: true,
511
- profile: {
512
- select: {
513
- displayName: true,
514
- profilePicture: true,
515
- },
516
- },
517
- },
518
- },
519
- },
520
- });
521
-
522
- // Create mentions
523
- if (mentionedUserIds.length > 0) {
524
- await tx.mention.createMany({
525
- data: mentionedUserIds.map((mentionedUserId) => ({
526
- messageId: message.id,
527
- userId: mentionedUserId,
528
- })),
529
- });
530
- }
531
-
532
- // Update lab chat timestamp
533
- await tx.labChat.update({
534
- where: { id: labChatId },
535
- data: { updatedAt: new Date() },
536
- });
537
-
538
- return message;
539
- });
540
-
541
- // Broadcast to Pusher channel (same format as regular chat)
542
- try {
543
- await pusher.trigger(`conversation-${labChat.conversationId}`, 'new-message', {
544
- id: result.id,
545
- content: result.content,
546
- senderId: result.senderId,
547
- conversationId: result.conversationId,
548
- createdAt: result.createdAt,
549
- sender: result.sender,
550
- mentionedUserIds,
551
- });
552
- } catch (error) {
553
- console.error('Failed to broadcast lab chat message:', error);
554
- // Don't fail the request if Pusher fails
555
- }
556
-
557
- // Generate AI response in parallel (don't await - fire and forget)
558
- if (!isAIUser(userId)) {
559
- // Run AI response generation in background
560
- generateAndSendLabResponse(labChatId, content, labChat.conversationId).catch(error => {
561
- logger.error('Failed to generate AI response:', { error });
562
- });
563
- }
564
-
565
- return {
566
- id: result.id,
567
- content: result.content,
568
- senderId: result.senderId,
569
- conversationId: result.conversationId,
570
- createdAt: result.createdAt,
571
- sender: result.sender,
572
- mentionedUserIds,
573
- };
574
- }),
44
+ .mutation(({ ctx, input }) =>
45
+ postToLabChat(ctx.user!.id, {
46
+ labChatId: input.labChatId,
47
+ content: input.content,
48
+ mentionedUserIds: input.mentionedUserIds,
49
+ })
50
+ ),
575
51
 
576
52
  delete: protectedProcedure
577
53
  .input(z.object({ labChatId: z.string() }))
578
- .mutation(async ({ input, ctx }) => {
579
- const userId = ctx.user!.id;
580
- const { labChatId } = input;
581
-
582
- // Verify user is the creator of the lab chat
583
- const labChat = await prisma.labChat.findFirst({
584
- where: {
585
- id: labChatId,
586
- createdById: userId,
587
- },
588
- });
589
-
590
- if (!labChat) {
591
- throw new TRPCError({
592
- code: 'FORBIDDEN',
593
- message: 'Lab chat not found or not the creator',
594
- });
595
- }
596
-
597
- // Delete lab chat and associated conversation
598
- await prisma.$transaction(async (tx) => {
599
- // Delete mentions first
600
- await tx.mention.deleteMany({
601
- where: {
602
- message: {
603
- conversationId: labChat.conversationId,
604
- },
605
- },
606
- });
607
-
608
- // Delete messages
609
- await tx.message.deleteMany({
610
- where: {
611
- conversationId: labChat.conversationId,
612
- },
613
- });
614
-
615
- // Delete conversation members
616
- await tx.conversationMember.deleteMany({
617
- where: {
618
- conversationId: labChat.conversationId,
619
- },
620
- });
621
-
622
- // Delete lab chat
623
- await tx.labChat.delete({
624
- where: { id: labChatId },
625
- });
626
-
627
- // Delete conversation
628
- await tx.conversation.delete({
629
- where: { id: labChat.conversationId },
630
- });
631
- });
632
-
633
- // Broadcast lab chat deletion
634
- try {
635
- await pusher.trigger(`class-${labChat.classId}`, 'lab-chat-deleted', {
636
- labChatId,
637
- classId: labChat.classId,
638
- });
639
- } catch (error) {
640
- console.error('Failed to broadcast lab chat deletion:', error);
641
- // Don't fail the request if Pusher fails
642
- }
643
-
644
- return { success: true };
645
- }),
54
+ .mutation(({ ctx, input }) =>
55
+ deleteLabChat(ctx.user!.id, input.labChatId)
56
+ ),
646
57
  });
647
-
648
- /**
649
- * Generate and send AI introduction for lab chat
650
- * Uses the stored context directly from database
651
- */
652
- async function generateAndSendLabIntroduction(
653
- labChatId: string,
654
- conversationId: string,
655
- contextString: string,
656
- subject: string
657
- ): Promise<void> {
658
- try {
659
- // Enhance the stored context with clarifying question instructions
660
- const enhancedSystemPrompt = `${contextString}
661
-
662
- IMPORTANT INSTRUCTIONS:
663
- - You are helping teachers create course materials
664
- - Use the context information provided above (subject, topic, difficulty, objectives, etc.) as your foundation
665
- - Only ask clarifying questions about details NOT already specified in the context
666
- - Focus your questions on format preferences, specific requirements, or missing details needed to create the content
667
- - Only output final course materials when you have sufficient details beyond what's in the context
668
- - Do not use markdown formatting in your responses - use plain text only
669
- - When creating content, make it clear and well-structured without markdown`;
670
-
671
- const completion = await inferenceClient.chat.completions.create({
672
- model: 'command-a-03-2025',
673
- messages: [
674
- { role: 'system', content: enhancedSystemPrompt },
675
- {
676
- role: 'user',
677
- content: 'Please introduce yourself to the teaching team. Explain that you will help create course materials by first asking clarifying questions based on the context provided, and only output final content when you have enough information.'
678
- },
679
- ],
680
- max_tokens: 300,
681
- temperature: 0.8,
682
- });
683
-
684
- const response = completion.choices[0]?.message?.content;
685
-
686
- if (!response) {
687
- throw new Error('No response generated from inference API');
688
- }
689
-
690
- // Send AI introduction using centralized sender
691
- await sendAIMessage(response, conversationId, {
692
- subject,
693
- });
694
-
695
- logger.info('AI Introduction sent', { labChatId, conversationId });
696
-
697
- } catch (error) {
698
- logger.error('Failed to generate AI introduction:', { error, labChatId });
699
-
700
- // Send fallback introduction
701
- try {
702
- const fallbackIntro = `Hello teaching team! I'm your AI assistant for course material development. I will help you create educational content by first asking clarifying questions based on the provided context, then outputting final materials when I have sufficient information. I won't use markdown formatting in my responses. What would you like to work on?`;
703
-
704
- await sendAIMessage(fallbackIntro, conversationId, {
705
- subject,
706
- });
707
-
708
- logger.info('Fallback AI introduction sent', { labChatId });
709
-
710
- } catch (fallbackError) {
711
- logger.error('Failed to send fallback AI introduction:', { error: fallbackError, labChatId });
712
- }
713
- }
714
- }
715
-
716
- /**
717
- * Generate and send AI response to teacher message
718
- * Uses the stored context directly from database
719
- */
720
- async function generateAndSendLabResponse(
721
- labChatId: string,
722
- teacherMessage: string,
723
- conversationId: string
724
- ): Promise<void> {
725
- try {
726
- // Get lab context from database
727
- const fullLabChat = await prisma.labChat.findUnique({
728
- where: { id: labChatId },
729
- include: {
730
- class: {
731
- select: {
732
- name: true,
733
- subject: true,
734
- },
735
- },
736
- },
737
- });
738
-
739
- if (!fullLabChat) {
740
- throw new Error('Lab chat not found');
741
- }
742
-
743
- // Get recent conversation history
744
- const recentMessages = await prisma.message.findMany({
745
- where: {
746
- conversationId,
747
- },
748
- include: {
749
- sender: {
750
- select: {
751
- id: true,
752
- username: true,
753
- profile: {
754
- select: {
755
- displayName: true,
756
- },
757
- },
758
- },
759
- },
760
- },
761
- orderBy: {
762
- createdAt: 'desc',
763
- },
764
- take: 10, // Last 10 messages for context
765
- });
766
-
767
- // Build conversation history as proper message objects
768
- // Enhance the stored context with clarifying question instructions
769
- const enhancedSystemPrompt = `${fullLabChat.context}
770
-
771
- IMPORTANT INSTRUCTIONS:
772
- - Use the context information provided above (subject, topic, difficulty, objectives, etc.) as your foundation
773
- - Based on the teacher's input and existing context, only ask clarifying questions about details NOT already specified
774
- - Focus questions on format preferences, specific requirements, quantity, or missing implementation details
775
- - Only output final course materials when you have sufficient details beyond what's in the context
776
- - Do not use markdown formatting in your responses - use plain text only
777
- - When you do create content, make it clear and well-structured without markdown
778
- - If the request is vague, ask 1-2 specific clarifying questions about missing details only
779
- - You are primarily a chatbot - only provide files when it is necessary
780
-
781
- RESPONSE FORMAT:
782
- - Always respond with JSON in this format: { "text": string, "docs": null | array }
783
- - "text": Your conversational response (questions, explanations, etc.) - use plain text, no markdown
784
- - "docs": null for regular conversation, or array of PDF document objects when creating course materials
785
-
786
- WHEN CREATING COURSE MATERIALS (docs field):
787
- - docs: [ { "title": string, "blocks": [ { "format": <int 0-12>, "content": string | string[], "metadata"?: { fontSize?: number, lineHeight?: number, paragraphSpacing?: number, indentWidth?: number, paddingX?: number, paddingY?: number, font?: 0|1|2|3|4|5, color?: "#RGB"|"#RRGGBB", background?: "#RGB"|"#RRGGBB", align?: "left"|"center"|"right" } } ] } ]
788
- - Each document in the array should have a "title" (used for filename) and "blocks" (content)
789
- - You can create multiple documents when it makes sense (e.g., separate worksheets, answer keys, different topics)
790
- - Use descriptive titles like "Biology_Cell_Structure_Worksheet" or "Chemistry_Lab_Instructions"
791
- - Format enum (integers): 0=HEADER_1, 1=HEADER_2, 2=HEADER_3, 3=HEADER_4, 4=HEADER_5, 5=HEADER_6, 6=PARAGRAPH, 7=BULLET, 8=NUMBERED, 9=TABLE, 10=IMAGE, 11=CODE_BLOCK, 12=QUOTE
792
- - Fonts enum: 0=TIMES_ROMAN, 1=COURIER, 2=HELVETICA, 3=HELVETICA_BOLD, 4=HELVETICA_ITALIC, 5=HELVETICA_BOLD_ITALIC
793
- - Colors must be hex strings: "#RGB" or "#RRGGBB".
794
- - Headings (0-5): content is a single string; you may set metadata.align.
795
- - Paragraphs (6) and Quotes (12): content is a single string.
796
- - Bullets (7) and Numbered (8): content is an array of strings (one item per list entry). DO NOT include bullet symbols (*) or numbers (1. 2. 3.) in the content - the format will automatically add these.
797
- - Code blocks (11): prefer content as an array of lines; preserve indentation via leading tabs/spaces. If using a single string, include \n between lines.
798
- - Table (9) and Image (10) are not supported by the renderer now; do not emit them.
799
- - Use metadata sparingly; omit fields you don't need. For code blocks you may set metadata.paddingX, paddingY, background, and font (1 for Courier).
800
- - Wrap text naturally; do not insert manual line breaks except where semantically required (lists, code).
801
- - The JSON must be valid and ready for PDF rendering by the server.`;
802
-
803
- const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
804
- { role: 'system', content: enhancedSystemPrompt },
805
- ];
806
-
807
- // Add recent conversation history
808
- recentMessages.reverse().forEach(msg => {
809
- const role = isAIUser(msg.senderId) ? 'assistant' : 'user';
810
- const senderName = msg.sender?.profile?.displayName || msg.sender?.username || 'Teacher';
811
- const content = isAIUser(msg.senderId) ? msg.content : `${senderName}: ${msg.content}`;
812
-
813
- messages.push({
814
- role: role as 'user' | 'assistant',
815
- content,
816
- });
817
- });
818
-
819
- // Add the new teacher message
820
- const senderName = 'Teacher'; // We could get this from the actual sender if needed
821
- messages.push({
822
- role: 'user',
823
- content: `${senderName}: ${teacherMessage}`,
824
- });
825
-
826
-
827
- const completion = await inferenceClient.chat.completions.create({
828
- model: 'command-a-03-2025',
829
- messages,
830
- temperature: 0.7,
831
- response_format: {
832
- type: "json_object",
833
- // @ts-expect-error
834
- schema: {
835
- type: "object",
836
- properties: {
837
- text: { type: "string" },
838
- docs: {
839
- type: "array",
840
- items: {
841
- type: "object",
842
- properties: {
843
- title: { type: "string" },
844
- blocks: {
845
- type: "array",
846
- items: {
847
- type: "object",
848
- properties: {
849
- format: { type: "integer", minimum: 0, maximum: 12 },
850
- content: {
851
- oneOf: [
852
- { type: "string" },
853
- { type: "array", items: { type: "string" } }
854
- ]
855
- },
856
- metadata: {
857
- type: "object",
858
- properties: {
859
- fontSize: { type: "number", minimum: 6 },
860
- lineHeight: { type: "number", minimum: 0.6 },
861
- paragraphSpacing: { type: "number", minimum: 0 },
862
- indentWidth: { type: "number", minimum: 0 },
863
- paddingX: { type: "number", minimum: 0 },
864
- paddingY: { type: "number", minimum: 0 },
865
- font: { type: "integer", minimum: 0, maximum: 5 },
866
- color: { type: "string", pattern: "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" },
867
- background: { type: "string", pattern: "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" },
868
- align: { type: "string", enum: ["left", "center", "right"] }
869
- },
870
- additionalProperties: false
871
- }
872
- },
873
- required: ["format", "content"],
874
- additionalProperties: false
875
- }
876
- }
877
- },
878
- required: ["title", "blocks"],
879
- additionalProperties: false
880
- }
881
- }
882
- },
883
- required: ["text"],
884
- additionalProperties: false
885
- }
886
- },
887
- });
888
-
889
- const response = completion.choices[0]?.message?.content;
890
-
891
- if (!response) {
892
- throw new Error('No response generated from inference API');
893
- }
894
-
895
- // Parse the JSON response and generate PDF if docs are provided
896
- try {
897
- const jsonData = JSON.parse(response);
898
-
899
-
900
- const attachmentIds: string[] = [];
901
- // Generate PDFs if docs are provided
902
- if (jsonData.docs && Array.isArray(jsonData.docs)) {
903
-
904
-
905
- console.log('Generating PDFs', { labChatId, docs: JSON.stringify(jsonData.docs, null, 2) });
906
- for (let i = 0; i < jsonData.docs.length; i++) {
907
- const doc = jsonData.docs[i];
908
- if (!doc.title || !doc.blocks || !Array.isArray(doc.blocks)) {
909
- logger.error(`Document ${i + 1} is missing title or blocks`);
910
- continue;
911
- }
912
-
913
-
914
- try {
915
- let pdfBytes = await createPdf(doc.blocks);
916
- if (pdfBytes) {
917
- // Sanitize filename - remove special characters and limit length
918
- const sanitizedTitle = doc.title
919
- .replace(/[^a-zA-Z0-9\s\-_]/g, '')
920
- .replace(/\s+/g, '_')
921
- .substring(0, 50);
922
-
923
- const filename = `${sanitizedTitle}_${uuidv4().substring(0, 8)}.pdf`;
924
- const filePath = `class/generated/${fullLabChat.classId}/${filename}`;
925
-
926
- logger.info(`PDF ${i + 1} generated successfully`, { labChatId, title: doc.title });
927
-
928
- // Upload directly to Google Cloud Storage
929
- const gcsFile = bucket.file(filePath);
930
- await gcsFile.save(Buffer.from(pdfBytes), {
931
- metadata: {
932
- contentType: 'application/pdf',
933
- }
934
- });
935
-
936
- logger.info(`PDF ${i + 1} uploaded successfully`, { labChatId, filename });
937
-
938
- const file = await prisma.file.create({
939
- data: {
940
- name: filename,
941
- path: filePath,
942
- type: 'application/pdf',
943
- size: pdfBytes.length,
944
- userId: fullLabChat.createdById,
945
- uploadStatus: 'COMPLETED',
946
- uploadedAt: new Date(),
947
- },
948
- });
949
- attachmentIds.push(file.id);
950
- } else {
951
- logger.error(`PDF ${i + 1} creation returned undefined/null`, { labChatId, title: doc.title });
952
- }
953
- } catch (pdfError) {
954
- logger.error(`PDF creation threw an error for document ${i + 1}:`, {
955
- error: pdfError instanceof Error ? {
956
- message: pdfError.message,
957
- stack: pdfError.stack,
958
- name: pdfError.name
959
- } : pdfError,
960
- labChatId,
961
- title: doc.title
962
- });
963
- }
964
- }
965
- }
966
-
967
- // Send the text response to the conversation
968
- await sendAIMessage(jsonData.text || response, conversationId, {
969
- attachments: {
970
- connect: attachmentIds.map(id => ({ id })),
971
- },
972
- subject: fullLabChat.class?.subject || 'Lab',
973
- });
974
- } catch (parseError) {
975
- logger.error('Failed to parse AI response or generate PDF:', { error: parseError, labChatId });
976
- // Fallback: send the raw response if parsing fails
977
- await sendAIMessage(response, conversationId, {
978
- subject: fullLabChat.class?.subject || 'Lab',
979
- });
980
- }
981
-
982
- logger.info('AI response sent', { labChatId, conversationId });
983
-
984
- } catch (error) {
985
- console.error('Full error object:', error);
986
- logger.error('Failed to generate AI response:', {
987
- error: error instanceof Error ? {
988
- message: error.message,
989
- stack: error.stack,
990
- name: error.name
991
- } : error,
992
- labChatId
993
- });
994
- throw error; // Re-throw to see the full error in the calling function
995
- }
996
- }
997
-