@goscribe/server 1.3.4 → 1.5.0

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 (378) hide show
  1. package/.env.example +12 -0
  2. package/.vscode/settings.json +3 -0
  3. package/REFACTOR_NOTES.md +60 -0
  4. package/TESTING_PROMPT.md +225 -0
  5. package/dist/controllers/admin.controller.d.ts +715 -0
  6. package/dist/controllers/admin.controller.js +9 -0
  7. package/dist/controllers/annotations.controller.d.ts +439 -0
  8. package/dist/controllers/annotations.controller.js +9 -0
  9. package/dist/controllers/app-router.controller.d.ts +3011 -0
  10. package/dist/controllers/app-router.controller.js +38 -0
  11. package/dist/controllers/app-router.controller.test.d.ts +1 -0
  12. package/dist/controllers/app-router.controller.test.js +36 -0
  13. package/dist/controllers/auth.controller.d.ts +323 -0
  14. package/dist/controllers/auth.controller.js +9 -0
  15. package/dist/controllers/base.controller.d.ts +4 -0
  16. package/dist/controllers/base.controller.js +5 -0
  17. package/dist/controllers/chat.controller.d.ts +341 -0
  18. package/dist/controllers/chat.controller.js +9 -0
  19. package/dist/controllers/copilot.controller.d.ts +397 -0
  20. package/dist/controllers/copilot.controller.js +9 -0
  21. package/dist/controllers/flashcards.controller.d.ts +651 -0
  22. package/dist/controllers/flashcards.controller.js +9 -0
  23. package/dist/controllers/members.controller.d.ts +339 -0
  24. package/dist/controllers/members.controller.js +9 -0
  25. package/dist/controllers/notifications.controller.d.ts +199 -0
  26. package/dist/controllers/notifications.controller.js +9 -0
  27. package/dist/controllers/payment.controller.d.ts +181 -0
  28. package/dist/controllers/payment.controller.js +9 -0
  29. package/dist/controllers/podcast.controller.d.ts +575 -0
  30. package/dist/controllers/podcast.controller.js +9 -0
  31. package/dist/controllers/router-module.controller.d.ts +5 -0
  32. package/dist/controllers/router-module.controller.js +6 -0
  33. package/dist/controllers/studyguide.controller.d.ts +73 -0
  34. package/dist/controllers/studyguide.controller.js +9 -0
  35. package/dist/controllers/worksheets.controller.d.ts +829 -0
  36. package/dist/controllers/worksheets.controller.js +9 -0
  37. package/dist/controllers/workspace.controller.d.ts +1207 -0
  38. package/dist/controllers/workspace.controller.js +9 -0
  39. package/dist/lib/activity_human_description.test.js +16 -15
  40. package/dist/lib/activity_log_service.test.js +28 -23
  41. package/dist/lib/ai/config.d.ts +20 -0
  42. package/dist/lib/ai/config.js +31 -0
  43. package/dist/lib/ai/embedding-client.d.ts +8 -0
  44. package/dist/lib/ai/embedding-client.js +30 -0
  45. package/dist/lib/ai/index.d.ts +47 -0
  46. package/dist/lib/ai/index.js +28 -0
  47. package/dist/lib/ai/inference-backend/client.d.ts +28 -0
  48. package/dist/lib/ai/inference-backend/client.js +301 -0
  49. package/dist/lib/ai/inference-backend/mocks.d.ts +12 -0
  50. package/dist/lib/ai/inference-backend/mocks.js +133 -0
  51. package/dist/lib/ai/inference-backend/types.d.ts +44 -0
  52. package/dist/lib/ai/inference-backend/types.js +1 -0
  53. package/dist/lib/ai/json-parse.d.ts +2 -0
  54. package/dist/lib/ai/json-parse.js +34 -0
  55. package/dist/lib/ai/llm-client.d.ts +6 -0
  56. package/dist/lib/ai/llm-client.js +19 -0
  57. package/dist/lib/ai/mock.d.ts +2 -0
  58. package/dist/lib/ai/mock.js +10 -0
  59. package/dist/lib/ai/types.d.ts +9 -0
  60. package/dist/lib/ai/types.js +1 -0
  61. package/dist/lib/chunking.d.ts +19 -0
  62. package/dist/lib/chunking.js +47 -0
  63. package/dist/lib/curated-kb-seed.d.ts +12 -0
  64. package/dist/lib/curated-kb-seed.js +155 -0
  65. package/dist/lib/email.js +67 -108
  66. package/dist/lib/embeddings.d.ts +2 -0
  67. package/dist/lib/embeddings.js +1 -0
  68. package/dist/lib/ensure-curated-kb-catalog.d.ts +6 -0
  69. package/dist/lib/ensure-curated-kb-catalog.js +53 -0
  70. package/dist/lib/env.d.ts +1 -5
  71. package/dist/lib/env.js +2 -7
  72. package/dist/lib/inference.d.ts +1 -8
  73. package/dist/lib/inference.js +1 -19
  74. package/dist/lib/kb-meta.d.ts +8 -0
  75. package/dist/lib/kb-meta.js +77 -0
  76. package/dist/lib/note-text.d.ts +1 -0
  77. package/dist/lib/note-text.js +47 -0
  78. package/dist/lib/notification-service.test.js +37 -36
  79. package/dist/lib/pdf.d.ts +11 -0
  80. package/dist/lib/pdf.js +11 -0
  81. package/dist/lib/usage_service.d.ts +2 -1
  82. package/dist/lib/usage_service.js +30 -12
  83. package/dist/lib/worksheet-generation.js +4 -4
  84. package/dist/lib/worksheet-generation.test.js +32 -17
  85. package/dist/lib/workspace-kb.d.ts +5 -0
  86. package/dist/lib/workspace-kb.js +7 -0
  87. package/dist/models/controller-context.model.d.ts +8 -0
  88. package/dist/models/controller-context.model.js +1 -0
  89. package/dist/repositories/artifact.repository.d.ts +60 -0
  90. package/dist/repositories/artifact.repository.js +40 -0
  91. package/dist/repositories/base.repository.d.ts +14 -0
  92. package/dist/repositories/base.repository.js +14 -0
  93. package/dist/repositories/invitation.repository.d.ts +94 -0
  94. package/dist/repositories/invitation.repository.js +44 -0
  95. package/dist/repositories/notification.repository.d.ts +72 -0
  96. package/dist/repositories/notification.repository.js +44 -0
  97. package/dist/repositories/router-module.repository.d.ts +10 -0
  98. package/dist/repositories/router-module.repository.js +14 -0
  99. package/dist/repositories/user.repository.d.ts +74 -0
  100. package/dist/repositories/user.repository.js +37 -0
  101. package/dist/repositories/workspace-member.repository.d.ts +31 -0
  102. package/dist/repositories/workspace-member.repository.js +31 -0
  103. package/dist/repositories/workspace.repository.d.ts +97 -0
  104. package/dist/repositories/workspace.repository.js +79 -0
  105. package/dist/routers/_app.d.ts +528 -33
  106. package/dist/routers/_app.js +4 -0
  107. package/dist/routers/admin.d.ts +0 -4
  108. package/dist/routers/admin.js +21 -549
  109. package/dist/routers/annotations.js +12 -170
  110. package/dist/routers/artifactVersions.d.ts +65 -0
  111. package/dist/routers/artifactVersions.js +14 -0
  112. package/dist/routers/auth.d.ts +0 -6
  113. package/dist/routers/auth.js +36 -421
  114. package/dist/routers/chat.js +15 -229
  115. package/dist/routers/copilot.d.ts +14 -13
  116. package/dist/routers/copilot.js +13 -532
  117. package/dist/routers/flashcards.d.ts +5 -5
  118. package/dist/routers/flashcards.js +23 -349
  119. package/dist/routers/knowledgeBase.d.ts +421 -0
  120. package/dist/routers/knowledgeBase.js +118 -0
  121. package/dist/routers/members.d.ts +0 -41
  122. package/dist/routers/members.js +22 -710
  123. package/dist/routers/notes.d.ts +94 -0
  124. package/dist/routers/notes.js +37 -0
  125. package/dist/routers/notifications.js +7 -109
  126. package/dist/routers/payment.d.ts +3 -2
  127. package/dist/routers/payment.js +11 -393
  128. package/dist/routers/podcast.d.ts +1 -1
  129. package/dist/routers/podcast.js +11 -784
  130. package/dist/routers/studyguide.js +3 -129
  131. package/dist/routers/worksheets.d.ts +29 -14
  132. package/dist/routers/worksheets.js +49 -628
  133. package/dist/routers/workspace.d.ts +0 -4
  134. package/dist/routers/workspace.js +28 -922
  135. package/dist/scripts/purge-deleted-users.js +2 -2
  136. package/dist/server.js +10 -3
  137. package/dist/services/activity/activity-human-description.service.d.ts +13 -0
  138. package/dist/services/activity/activity-human-description.service.js +221 -0
  139. package/dist/services/activity/activity-human-description.service.test.d.ts +1 -0
  140. package/dist/services/activity/activity-human-description.service.test.js +16 -0
  141. package/dist/services/activity/activity-log.service.d.ts +87 -0
  142. package/dist/services/activity/activity-log.service.js +276 -0
  143. package/dist/services/activity/activity-log.service.test.d.ts +1 -0
  144. package/dist/services/activity/activity-log.service.test.js +27 -0
  145. package/dist/services/activity-human-description.service.d.ts +13 -0
  146. package/dist/services/activity-human-description.service.js +221 -0
  147. package/dist/services/activity-human-description.service.test.d.ts +1 -0
  148. package/dist/services/activity-human-description.service.test.js +16 -0
  149. package/dist/services/activity-log.service.d.ts +87 -0
  150. package/dist/services/activity-log.service.js +276 -0
  151. package/dist/services/activity-log.service.test.d.ts +1 -0
  152. package/dist/services/activity-log.service.test.js +27 -0
  153. package/dist/services/admin/admin.service.d.ts +270 -0
  154. package/dist/services/admin/admin.service.js +476 -0
  155. package/dist/services/admin.service.d.ts +270 -0
  156. package/dist/services/admin.service.js +476 -0
  157. package/dist/services/ai/ai-session.service.d.ts +5 -0
  158. package/dist/services/ai/ai-session.service.js +4 -0
  159. package/dist/services/ai-session.service.d.ts +60 -0
  160. package/dist/services/ai-session.service.js +561 -0
  161. package/dist/services/annotation.service.d.ts +177 -0
  162. package/dist/services/annotation.service.js +154 -0
  163. package/dist/services/artifact-notification.service.d.ts +14 -0
  164. package/dist/services/artifact-notification.service.js +20 -0
  165. package/dist/services/artifact-version.service.d.ts +38 -0
  166. package/dist/services/artifact-version.service.js +129 -0
  167. package/dist/services/artifacts/annotation.service.d.ts +177 -0
  168. package/dist/services/artifacts/annotation.service.js +154 -0
  169. package/dist/services/artifacts/artifact-version.service.d.ts +38 -0
  170. package/dist/services/artifacts/artifact-version.service.js +129 -0
  171. package/dist/services/artifacts/chat.service.d.ts +127 -0
  172. package/dist/services/artifacts/chat.service.js +182 -0
  173. package/dist/services/artifacts/study-guide.service.d.ts +18 -0
  174. package/dist/services/artifacts/study-guide.service.js +65 -0
  175. package/dist/services/auth/auth.service.d.ts +94 -0
  176. package/dist/services/auth/auth.service.js +368 -0
  177. package/dist/services/auth.service.d.ts +94 -0
  178. package/dist/services/auth.service.js +368 -0
  179. package/dist/services/base.service.d.ts +14 -0
  180. package/dist/services/base.service.js +14 -0
  181. package/dist/services/billing/payment.service.d.ts +55 -0
  182. package/dist/services/billing/payment.service.js +368 -0
  183. package/dist/services/billing/subscription.service.d.ts +37 -0
  184. package/dist/services/billing/subscription.service.js +654 -0
  185. package/dist/services/billing/usage.service.d.ts +27 -0
  186. package/dist/services/billing/usage.service.js +77 -0
  187. package/dist/services/chat.service.d.ts +127 -0
  188. package/dist/services/chat.service.js +182 -0
  189. package/dist/services/content/copilot.service.d.ts +113 -0
  190. package/dist/services/content/copilot.service.js +453 -0
  191. package/dist/services/content/flashcard-progress.service.d.ts +159 -0
  192. package/dist/services/content/flashcard-progress.service.js +432 -0
  193. package/dist/services/content/flashcard.service.d.ts +140 -0
  194. package/dist/services/content/flashcard.service.js +326 -0
  195. package/dist/services/content/media-analysis.service.d.ts +23 -0
  196. package/dist/services/content/media-analysis.service.js +404 -0
  197. package/dist/services/content/podcast.service.d.ts +267 -0
  198. package/dist/services/content/podcast.service.js +653 -0
  199. package/dist/services/content/worksheet-content.service.d.ts +37 -0
  200. package/dist/services/content/worksheet-content.service.js +84 -0
  201. package/dist/services/content/worksheet-content.service.test.d.ts +1 -0
  202. package/dist/services/content/worksheet-content.service.test.js +69 -0
  203. package/dist/services/content/worksheet-generation.service.d.ts +91 -0
  204. package/dist/services/content/worksheet-generation.service.js +95 -0
  205. package/dist/services/content/worksheet-generation.service.test.d.ts +1 -0
  206. package/dist/services/content/worksheet-generation.service.test.js +20 -0
  207. package/dist/services/content/worksheet.service.d.ts +347 -0
  208. package/dist/services/content/worksheet.service.js +599 -0
  209. package/dist/services/copilot.service.d.ts +116 -0
  210. package/dist/services/copilot.service.js +447 -0
  211. package/dist/services/flashcard-progress.service.d.ts +2 -2
  212. package/dist/services/flashcard-progress.service.js +3 -2
  213. package/dist/services/flashcard.service.d.ts +140 -0
  214. package/dist/services/flashcard.service.js +325 -0
  215. package/dist/services/invitation.service.d.ts +66 -0
  216. package/dist/services/invitation.service.js +348 -0
  217. package/dist/services/knowledge/knowledge-base.service.d.ts +316 -0
  218. package/dist/services/knowledge/knowledge-base.service.js +544 -0
  219. package/dist/services/knowledge-base.service.d.ts +316 -0
  220. package/dist/services/knowledge-base.service.js +536 -0
  221. package/dist/services/media-analysis.service.d.ts +23 -0
  222. package/dist/services/media-analysis.service.js +384 -0
  223. package/dist/services/member.service.d.ts +36 -0
  224. package/dist/services/member.service.js +193 -0
  225. package/dist/services/members/invitation.service.d.ts +66 -0
  226. package/dist/services/members/invitation.service.js +348 -0
  227. package/dist/services/members/member.service.d.ts +36 -0
  228. package/dist/services/members/member.service.js +193 -0
  229. package/dist/services/note.service.d.ts +55 -0
  230. package/dist/services/note.service.js +111 -0
  231. package/dist/services/notification.service.d.ts +214 -0
  232. package/dist/services/notification.service.js +550 -0
  233. package/dist/services/notification.service.test.d.ts +1 -0
  234. package/dist/services/notification.service.test.js +87 -0
  235. package/dist/services/notifications/notification.service.d.ts +214 -0
  236. package/dist/services/notifications/notification.service.js +550 -0
  237. package/dist/services/notifications/notification.service.test.d.ts +1 -0
  238. package/dist/services/notifications/notification.service.test.js +87 -0
  239. package/dist/services/payment.service.d.ts +55 -0
  240. package/dist/services/payment.service.js +368 -0
  241. package/dist/services/podcast.service.d.ts +267 -0
  242. package/dist/services/podcast.service.js +654 -0
  243. package/dist/services/router-module.service.d.ts +7 -0
  244. package/dist/services/router-module.service.js +10 -0
  245. package/dist/services/study-guide.service.d.ts +18 -0
  246. package/dist/services/study-guide.service.js +65 -0
  247. package/dist/services/subscription.service.d.ts +37 -0
  248. package/dist/services/subscription.service.js +654 -0
  249. package/dist/services/usage-limit-policy.service.d.ts +12 -0
  250. package/dist/services/usage-limit-policy.service.js +22 -0
  251. package/dist/services/usage-limit-policy.service.test.d.ts +1 -0
  252. package/dist/services/usage-limit-policy.service.test.js +46 -0
  253. package/dist/services/usage.service.d.ts +27 -0
  254. package/dist/services/usage.service.js +77 -0
  255. package/dist/services/worksheet-content.service.d.ts +42 -0
  256. package/dist/services/worksheet-content.service.js +84 -0
  257. package/dist/services/worksheet-content.service.test.d.ts +1 -0
  258. package/dist/services/worksheet-content.service.test.js +69 -0
  259. package/dist/services/worksheet-generation.service.d.ts +91 -0
  260. package/dist/services/worksheet-generation.service.js +95 -0
  261. package/dist/services/worksheet-generation.service.test.d.ts +1 -0
  262. package/dist/services/worksheet-generation.service.test.js +20 -0
  263. package/dist/services/worksheet.service.d.ts +385 -0
  264. package/dist/services/worksheet.service.js +596 -0
  265. package/dist/services/workspace/workspace-analytics.service.d.ts +24 -0
  266. package/dist/services/workspace/workspace-analytics.service.js +95 -0
  267. package/dist/services/workspace/workspace-kb.service.d.ts +40 -0
  268. package/dist/services/workspace/workspace-kb.service.js +184 -0
  269. package/dist/services/workspace/workspace.service.d.ts +307 -0
  270. package/dist/services/workspace/workspace.service.js +394 -0
  271. package/dist/services/workspace-analytics.service.d.ts +24 -0
  272. package/dist/services/workspace-analytics.service.js +95 -0
  273. package/dist/services/workspace-kb.service.d.ts +40 -0
  274. package/dist/services/workspace-kb.service.js +184 -0
  275. package/dist/services/workspace-progress.service.d.ts +27 -0
  276. package/dist/services/workspace-progress.service.js +56 -0
  277. package/dist/services/workspace-progress.service.test.d.ts +1 -0
  278. package/dist/services/workspace-progress.service.test.js +49 -0
  279. package/dist/services/workspace.service.d.ts +307 -0
  280. package/dist/services/workspace.service.js +390 -0
  281. package/dist/trpc.js +2 -2
  282. package/package.json +5 -6
  283. package/prisma/migrations/20260509000001_add_knowledge_base/migration.sql +99 -0
  284. package/prisma/migrations/20260509000002_curate_knowledge_base/migration.sql +52 -0
  285. package/prisma/migrations/20260522000000_add_notes/migration.sql +27 -0
  286. package/prisma/migrations/20260524000000_remove_notes/migration.sql +3 -0
  287. package/prisma/schema.prisma +150 -48
  288. package/prisma/seed.mjs +67 -0
  289. package/scripts/debug/README.md +4 -0
  290. package/src/README.md +63 -0
  291. package/src/lib/ai/config.ts +34 -0
  292. package/src/lib/ai/embedding-client.ts +47 -0
  293. package/src/lib/ai/index.ts +62 -0
  294. package/src/lib/ai/inference-backend/client.ts +479 -0
  295. package/src/lib/ai/inference-backend/mocks.ts +171 -0
  296. package/src/lib/ai/inference-backend/types.ts +50 -0
  297. package/src/lib/ai/json-parse.ts +35 -0
  298. package/src/lib/ai/llm-client.ts +31 -0
  299. package/src/lib/ai/mock.ts +12 -0
  300. package/src/lib/ai/types.ts +11 -0
  301. package/src/lib/chunking.ts +81 -0
  302. package/src/lib/curated-kb-seed.ts +164 -0
  303. package/src/lib/email.ts +77 -115
  304. package/src/lib/embeddings.ts +9 -0
  305. package/src/lib/ensure-curated-kb-catalog.ts +60 -0
  306. package/src/lib/env.ts +2 -7
  307. package/src/lib/inference.ts +1 -21
  308. package/src/lib/kb-meta.ts +81 -0
  309. package/src/lib/pdf.ts +23 -0
  310. package/src/lib/workspace-kb.ts +7 -0
  311. package/src/repositories/artifact.repository.ts +55 -0
  312. package/src/repositories/base.repository.ts +19 -0
  313. package/src/repositories/invitation.repository.ts +53 -0
  314. package/src/repositories/notification.repository.ts +53 -0
  315. package/src/repositories/user.repository.ts +44 -0
  316. package/src/repositories/workspace-member.repository.ts +38 -0
  317. package/src/repositories/workspace.repository.ts +89 -0
  318. package/src/routers/_app.ts +4 -0
  319. package/src/routers/admin.ts +124 -692
  320. package/src/routers/annotations.ts +25 -203
  321. package/src/routers/artifactVersions.ts +32 -0
  322. package/src/routers/auth.ts +81 -519
  323. package/src/routers/chat.ts +42 -245
  324. package/src/routers/copilot.ts +41 -666
  325. package/src/routers/flashcards.ts +108 -404
  326. package/src/routers/knowledgeBase.ts +216 -0
  327. package/src/routers/members.ts +60 -782
  328. package/src/routers/notifications.ts +15 -117
  329. package/src/routers/payment.ts +37 -446
  330. package/src/routers/podcast.ts +36 -898
  331. package/src/routers/studyguide.ts +5 -144
  332. package/src/routers/worksheets.ts +171 -735
  333. package/src/routers/workspace.ts +138 -1109
  334. package/src/scripts/purge-deleted-users.ts +2 -2
  335. package/src/server.ts +10 -3
  336. package/src/{lib/activity_human_description.test.ts → services/activity/activity-human-description.service.test.ts} +1 -1
  337. package/src/{lib/activity_log_service.test.ts → services/activity/activity-log.service.test.ts} +1 -1
  338. package/src/{lib/activity_log_service.ts → services/activity/activity-log.service.ts} +2 -2
  339. package/src/services/admin/admin.service.ts +612 -0
  340. package/src/services/ai/ai-session.service.ts +5 -0
  341. package/src/services/artifacts/annotation.service.ts +189 -0
  342. package/src/services/artifacts/artifact-version.service.ts +151 -0
  343. package/src/services/artifacts/chat.service.ts +197 -0
  344. package/src/services/artifacts/study-guide.service.ts +72 -0
  345. package/src/services/auth/auth.service.ts +473 -0
  346. package/src/services/base.service.ts +19 -0
  347. package/src/services/billing/payment.service.ts +436 -0
  348. package/src/{lib/subscription_service.ts → services/billing/subscription.service.ts} +5 -5
  349. package/src/{lib/usage_service.ts → services/billing/usage.service.ts} +32 -12
  350. package/src/services/content/copilot.service.ts +596 -0
  351. package/src/services/{flashcard-progress.service.ts → content/flashcard-progress.service.ts} +6 -3
  352. package/src/services/content/flashcard.service.ts +394 -0
  353. package/src/services/content/media-analysis.service.ts +556 -0
  354. package/src/services/content/podcast.service.ts +777 -0
  355. package/src/services/content/worksheet-content.service.test.ts +83 -0
  356. package/src/services/content/worksheet-content.service.ts +117 -0
  357. package/src/{lib/worksheet-generation.test.ts → services/content/worksheet-generation.service.test.ts} +1 -1
  358. package/src/services/content/worksheet.service.ts +751 -0
  359. package/src/services/knowledge/knowledge-base.service.ts +705 -0
  360. package/src/services/members/invitation.service.ts +427 -0
  361. package/src/services/members/member.service.ts +241 -0
  362. package/src/{lib/notification-service.test.ts → services/notifications/notification.service.test.ts} +2 -2
  363. package/src/{lib/notification-service.ts → services/notifications/notification.service.ts} +102 -1
  364. package/src/services/workspace/workspace-analytics.service.ts +107 -0
  365. package/src/services/workspace/workspace-kb.service.ts +273 -0
  366. package/src/services/workspace/workspace.service.ts +481 -0
  367. package/src/trpc.ts +2 -2
  368. package/src/lib/ai-session.ts +0 -704
  369. package/src/lib/workspace-access.ts +0 -13
  370. /package/{check-difficulty.cjs → scripts/debug/check-difficulty.cjs} +0 -0
  371. /package/{check-questions.cjs → scripts/debug/check-questions.cjs} +0 -0
  372. /package/{db-summary.cjs → scripts/debug/db-summary.cjs} +0 -0
  373. /package/{mcq-test.cjs → scripts/debug/mcq-test.cjs} +0 -0
  374. /package/{test-generate.js → scripts/debug/test-generate.js} +0 -0
  375. /package/{test-ratio.cjs → scripts/debug/test-ratio.cjs} +0 -0
  376. /package/{zod-test.cjs → scripts/debug/zod-test.cjs} +0 -0
  377. /package/src/{lib/activity_human_description.ts → services/activity/activity-human-description.service.ts} +0 -0
  378. /package/src/{lib/worksheet-generation.ts → services/content/worksheet-generation.service.ts} +0 -0
@@ -0,0 +1,368 @@
1
+ import { TRPCError } from '@trpc/server';
2
+ import { BaseService } from './base.service.js';
3
+ import { stripe } from '../lib/stripe.js';
4
+ import { env } from '../lib/env.js';
5
+ import { getUserUsage, getUserPlanLimits } from './usage.service.js';
6
+ import { notifyPaymentSucceeded, notifySubscriptionActivated, notifySubscriptionPaymentSucceeded, } from './notification.service.js';
7
+ import { upsertSubscriptionFromStripe } from './subscription.service.js';
8
+ /** Stripe Checkout URLs contain the session id (cs_…); we only store the URL in DB. */
9
+ const CHECKOUT_SESSION_ID_IN_URL = /cs_[a-zA-Z0-9]+/;
10
+ async function reuseCheckoutUrlIfSessionStillOpen(stripeClient, db, existing, lockKey) {
11
+ const url = existing.stripeSessionId;
12
+ if (!url)
13
+ return null;
14
+ const idMatch = url.match(CHECKOUT_SESSION_ID_IN_URL);
15
+ if (!idMatch) {
16
+ await db.idempotencyRecord.updateMany({
17
+ where: { id: existing.id, activeLockKey: lockKey },
18
+ data: { activeLockKey: null, status: 'expired' },
19
+ });
20
+ return null;
21
+ }
22
+ try {
23
+ const session = await stripeClient.checkout.sessions.retrieve(idMatch[0]);
24
+ if (session.status === 'open') {
25
+ return url;
26
+ }
27
+ await db.idempotencyRecord.updateMany({
28
+ where: { id: existing.id, activeLockKey: lockKey },
29
+ data: {
30
+ activeLockKey: null,
31
+ status: session.status === 'complete' ? 'completed' : 'expired',
32
+ },
33
+ });
34
+ return null;
35
+ }
36
+ catch {
37
+ await db.idempotencyRecord.updateMany({
38
+ where: { id: existing.id, activeLockKey: lockKey },
39
+ data: { activeLockKey: null, status: 'expired' },
40
+ });
41
+ return null;
42
+ }
43
+ }
44
+ export class PaymentService extends BaseService {
45
+ constructor(db) {
46
+ super(db);
47
+ }
48
+ async getPlans(userId) {
49
+ const plans = await this.db.plan.findMany({
50
+ where: { active: true },
51
+ include: { limit: true },
52
+ orderBy: { price: 'asc' },
53
+ });
54
+ // Anonymous callers (pricing page) don't get per-user `isActive`.
55
+ if (!userId) {
56
+ return plans.map((plan) => ({ ...plan, isActive: false }));
57
+ }
58
+ const activeSubscriptions = await this.db.subscription.findMany({
59
+ where: { userId, status: 'active' },
60
+ });
61
+ return plans.map((plan) => ({
62
+ ...plan,
63
+ isActive: activeSubscriptions.some((sub) => sub.planId === plan.id),
64
+ }));
65
+ }
66
+ async createCheckoutSession(userId, input) {
67
+ if (!stripe) {
68
+ throw new TRPCError({
69
+ code: 'INTERNAL_SERVER_ERROR',
70
+ message: 'Stripe not configured',
71
+ });
72
+ }
73
+ const user = await this.db.user.findUnique({ where: { id: userId } });
74
+ if (!user)
75
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
76
+ const lockKey = `pending_${userId}_${input.planId}`;
77
+ let attempt = null;
78
+ let retryCount = 0;
79
+ while (retryCount < 3) {
80
+ try {
81
+ attempt = await this.db.idempotencyRecord.create({
82
+ data: {
83
+ userId,
84
+ planId: input.planId,
85
+ activeLockKey: lockKey,
86
+ status: 'pending',
87
+ },
88
+ });
89
+ break;
90
+ }
91
+ catch (err) {
92
+ if (err.code === 'P2002') {
93
+ const existing = await this.db.idempotencyRecord.findUnique({
94
+ where: { activeLockKey: lockKey },
95
+ });
96
+ if (!existing) {
97
+ retryCount++;
98
+ continue;
99
+ }
100
+ const isStale = Date.now() - existing.updatedAt.getTime() > 24 * 60 * 60 * 1000;
101
+ if (isStale) {
102
+ const result = await this.db.idempotencyRecord.updateMany({
103
+ where: { id: existing.id, activeLockKey: lockKey },
104
+ data: { activeLockKey: null, status: 'expired' },
105
+ });
106
+ if (result.count > 0) {
107
+ retryCount++;
108
+ continue;
109
+ }
110
+ }
111
+ if (existing.stripeSessionId && stripe) {
112
+ const reusable = await reuseCheckoutUrlIfSessionStillOpen(stripe, this.db, existing, lockKey);
113
+ if (reusable)
114
+ return { url: reusable };
115
+ retryCount++;
116
+ continue;
117
+ }
118
+ await new Promise((resolve) => setTimeout(resolve, 800));
119
+ retryCount++;
120
+ continue;
121
+ }
122
+ throw err;
123
+ }
124
+ }
125
+ if (!attempt) {
126
+ throw new TRPCError({ code: 'CONFLICT', message: 'Concurrent request' });
127
+ }
128
+ const plan = await this.db.plan.findUnique({ where: { id: input.planId } });
129
+ if (!plan)
130
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Plan not found' });
131
+ try {
132
+ const successUrl = env.STRIPE_SUCCESS_URL.includes('session_id=')
133
+ ? env.STRIPE_SUCCESS_URL
134
+ : `${env.STRIPE_SUCCESS_URL}${env.STRIPE_SUCCESS_URL.includes('?') ? '&' : '?'}session_id={CHECKOUT_SESSION_ID}`;
135
+ const session = await stripe.checkout.sessions.create({
136
+ customer: user.stripe_customer_id || undefined,
137
+ customer_email: user.stripe_customer_id ? undefined : user.email || undefined,
138
+ line_items: [{ price: plan.stripePriceId, quantity: 1 }],
139
+ mode: plan.interval ? 'subscription' : 'payment',
140
+ subscription_data: plan.interval
141
+ ? {
142
+ metadata: {
143
+ userId,
144
+ planId: plan.id,
145
+ attemptId: attempt.id,
146
+ },
147
+ }
148
+ : undefined,
149
+ success_url: successUrl,
150
+ cancel_url: env.STRIPE_CANCEL_URL,
151
+ metadata: {
152
+ userId,
153
+ planId: plan.id,
154
+ attemptId: attempt.id,
155
+ },
156
+ }, {
157
+ idempotencyKey: attempt.id,
158
+ });
159
+ await this.db.idempotencyRecord.update({
160
+ where: { id: attempt.id },
161
+ data: { stripeSessionId: session.url },
162
+ });
163
+ return { url: session.url };
164
+ }
165
+ catch (error) {
166
+ await this.db.idempotencyRecord.update({
167
+ where: { id: attempt.id },
168
+ data: { status: 'failed', activeLockKey: null },
169
+ });
170
+ throw new TRPCError({
171
+ code: 'INTERNAL_SERVER_ERROR',
172
+ message: error.message,
173
+ });
174
+ }
175
+ }
176
+ async confirmCheckoutSuccess(userId, input) {
177
+ if (!stripe) {
178
+ throw new TRPCError({
179
+ code: 'INTERNAL_SERVER_ERROR',
180
+ message: 'Stripe not configured',
181
+ });
182
+ }
183
+ const session = await stripe.checkout.sessions.retrieve(input.sessionId, {
184
+ expand: ['line_items', 'subscription'],
185
+ });
186
+ const metadata = session.metadata || {};
187
+ if (metadata.userId !== userId) {
188
+ throw new TRPCError({
189
+ code: 'FORBIDDEN',
190
+ message: 'This checkout session does not belong to the current user',
191
+ });
192
+ }
193
+ if (session.status !== 'complete') {
194
+ return { confirmed: false, reason: 'checkout_not_complete' };
195
+ }
196
+ const plan = metadata.planId
197
+ ? await this.db.plan.findUnique({ where: { id: metadata.planId } })
198
+ : null;
199
+ if (session.mode === 'payment' && session.payment_status === 'paid') {
200
+ await notifyPaymentSucceeded(this.db, {
201
+ userId,
202
+ planId: metadata.planId,
203
+ planName: plan?.name || metadata.planType,
204
+ stripeSessionId: session.id,
205
+ amountPaid: session.amount_total ?? undefined,
206
+ });
207
+ return { confirmed: true, kind: 'payment' };
208
+ }
209
+ if (session.mode === 'subscription') {
210
+ const stripeSubscriptionId = typeof session.subscription === 'string'
211
+ ? session.subscription
212
+ : session.subscription?.id;
213
+ if (stripeSubscriptionId) {
214
+ await upsertSubscriptionFromStripe(stripeSubscriptionId);
215
+ await notifySubscriptionActivated(this.db, {
216
+ userId,
217
+ planId: metadata.planId,
218
+ planName: plan?.name || metadata.planType,
219
+ stripeSubscriptionId,
220
+ });
221
+ if (session.payment_status === 'paid') {
222
+ await notifySubscriptionPaymentSucceeded(this.db, {
223
+ userId,
224
+ planId: metadata.planId,
225
+ planName: plan?.name || metadata.planType,
226
+ stripeInvoiceId: `checkout_${session.id}`,
227
+ amountPaid: session.amount_total ?? undefined,
228
+ });
229
+ }
230
+ }
231
+ return { confirmed: true, kind: 'subscription' };
232
+ }
233
+ return { confirmed: false, reason: 'unsupported_mode' };
234
+ }
235
+ async createResourcePurchaseSession(userId, input) {
236
+ if (!stripe) {
237
+ throw new TRPCError({
238
+ code: 'INTERNAL_SERVER_ERROR',
239
+ message: 'Stripe is not configured on the server',
240
+ });
241
+ }
242
+ const user = await this.db.user.findUnique({ where: { id: userId } });
243
+ if (!user) {
244
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
245
+ }
246
+ const resourcePrice = await this.db.resourcePrice.findUnique({
247
+ where: { resourceType: input.resourceType },
248
+ });
249
+ if (!resourcePrice) {
250
+ throw new TRPCError({
251
+ code: 'PRECONDITION_FAILED',
252
+ message: 'Price not set',
253
+ });
254
+ }
255
+ const lockKey = `topup_${userId}_${input.resourceType}`;
256
+ let attempt = null;
257
+ let retryCount = 0;
258
+ while (retryCount < 3) {
259
+ try {
260
+ attempt = await this.db.idempotencyRecord.create({
261
+ data: {
262
+ userId,
263
+ resourceType: input.resourceType,
264
+ activeLockKey: lockKey,
265
+ status: 'pending',
266
+ },
267
+ });
268
+ break;
269
+ }
270
+ catch (err) {
271
+ if (err.code === 'P2002') {
272
+ const existing = await this.db.idempotencyRecord.findUnique({
273
+ where: { activeLockKey: lockKey },
274
+ });
275
+ if (!existing) {
276
+ retryCount++;
277
+ continue;
278
+ }
279
+ const isStale = Date.now() - existing.updatedAt.getTime() > 24 * 60 * 60 * 1000;
280
+ if (isStale) {
281
+ const result = await this.db.idempotencyRecord.updateMany({
282
+ where: { id: existing.id, activeLockKey: lockKey },
283
+ data: { activeLockKey: null, status: 'expired' },
284
+ });
285
+ if (result.count > 0) {
286
+ retryCount++;
287
+ continue;
288
+ }
289
+ }
290
+ if (existing.stripeSessionId && stripe) {
291
+ const reusable = await reuseCheckoutUrlIfSessionStillOpen(stripe, this.db, existing, lockKey);
292
+ if (reusable)
293
+ return { url: reusable };
294
+ retryCount++;
295
+ continue;
296
+ }
297
+ await new Promise((resolve) => setTimeout(resolve, 800));
298
+ retryCount++;
299
+ continue;
300
+ }
301
+ throw err;
302
+ }
303
+ }
304
+ if (!attempt) {
305
+ throw new TRPCError({ code: 'CONFLICT', message: 'Concurrent request' });
306
+ }
307
+ try {
308
+ const resourceName = input.resourceType
309
+ .split('_')
310
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
311
+ .join(' ');
312
+ const session = await stripe.checkout.sessions.create({
313
+ customer: user.stripe_customer_id || undefined,
314
+ line_items: [
315
+ {
316
+ price_data: {
317
+ currency: 'usd',
318
+ product_data: {
319
+ name: `Add-on: extra ${resourceName}s`,
320
+ description: `Purchase of ${input.quantity} additional ${resourceName}(s)`,
321
+ },
322
+ unit_amount: resourcePrice.priceCents,
323
+ },
324
+ quantity: input.quantity,
325
+ },
326
+ ],
327
+ mode: 'payment',
328
+ success_url: `${env.STRIPE_SUCCESS_URL}?success=true`,
329
+ cancel_url: env.STRIPE_CANCEL_URL,
330
+ metadata: {
331
+ userId,
332
+ resourceType: input.resourceType,
333
+ quantity: input.quantity.toString(),
334
+ isPurchase: 'true',
335
+ attemptId: attempt.id,
336
+ },
337
+ invoice_creation: { enabled: true },
338
+ }, {
339
+ idempotencyKey: attempt.id,
340
+ });
341
+ await this.db.idempotencyRecord.update({
342
+ where: { id: attempt.id },
343
+ data: { stripeSessionId: session.url },
344
+ });
345
+ return { url: session.url };
346
+ }
347
+ catch (error) {
348
+ await this.db.idempotencyRecord.update({
349
+ where: { id: attempt.id },
350
+ data: { status: 'failed', activeLockKey: null },
351
+ });
352
+ throw new TRPCError({
353
+ code: 'INTERNAL_SERVER_ERROR',
354
+ message: error.message,
355
+ });
356
+ }
357
+ }
358
+ async getUsageOverview(userId) {
359
+ const [usage, limits] = await Promise.all([
360
+ getUserUsage(userId),
361
+ getUserPlanLimits(userId),
362
+ ]);
363
+ return { usage, limits, hasActivePlan: !!limits };
364
+ }
365
+ getResourcePrices() {
366
+ return this.db.resourcePrice.findMany();
367
+ }
368
+ }
@@ -0,0 +1,267 @@
1
+ import type { PrismaClient } from '@prisma/client';
2
+ import { z } from 'zod';
3
+ import { BaseService } from './base.service.js';
4
+ export declare const speakerSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ role: z.ZodEnum<{
7
+ host: "host";
8
+ guest: "guest";
9
+ expert: "expert";
10
+ }>;
11
+ name: z.ZodOptional<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ export declare const podcastInputSchema: z.ZodObject<{
14
+ title: z.ZodString;
15
+ description: z.ZodOptional<z.ZodString>;
16
+ userPrompt: z.ZodString;
17
+ speakers: z.ZodDefault<z.ZodArray<z.ZodObject<{
18
+ id: z.ZodString;
19
+ role: z.ZodEnum<{
20
+ host: "host";
21
+ guest: "guest";
22
+ expert: "expert";
23
+ }>;
24
+ name: z.ZodOptional<z.ZodString>;
25
+ }, z.core.$strip>>>;
26
+ speed: z.ZodDefault<z.ZodNumber>;
27
+ generateIntro: z.ZodDefault<z.ZodBoolean>;
28
+ generateOutro: z.ZodDefault<z.ZodBoolean>;
29
+ segmentByTopics: z.ZodDefault<z.ZodBoolean>;
30
+ }, z.core.$strip>;
31
+ export type PodcastInput = z.infer<typeof podcastInputSchema>;
32
+ export declare const podcastMetadataSchema: z.ZodObject<{
33
+ title: z.ZodString;
34
+ description: z.ZodOptional<z.ZodString>;
35
+ totalDuration: z.ZodNumber;
36
+ speakers: z.ZodArray<z.ZodObject<{
37
+ id: z.ZodString;
38
+ role: z.ZodEnum<{
39
+ host: "host";
40
+ guest: "guest";
41
+ expert: "expert";
42
+ }>;
43
+ name: z.ZodOptional<z.ZodString>;
44
+ }, z.core.$strip>>;
45
+ summary: z.ZodObject<{
46
+ executiveSummary: z.ZodString;
47
+ learningObjectives: z.ZodArray<z.ZodString>;
48
+ keyConcepts: z.ZodArray<z.ZodString>;
49
+ followUpActions: z.ZodArray<z.ZodString>;
50
+ targetAudience: z.ZodString;
51
+ prerequisites: z.ZodArray<z.ZodString>;
52
+ tags: z.ZodArray<z.ZodString>;
53
+ }, z.core.$strip>;
54
+ generatedAt: z.ZodString;
55
+ }, z.core.$strip>;
56
+ export declare class PodcastService extends BaseService {
57
+ constructor(db: PrismaClient);
58
+ listEpisodes(userId: string, workspaceId: string): Promise<{
59
+ id: string;
60
+ title: string;
61
+ description: string | null;
62
+ metadata: {
63
+ title: string;
64
+ totalDuration: number;
65
+ speakers: {
66
+ id: string;
67
+ role: "host" | "guest" | "expert";
68
+ name?: string | undefined;
69
+ }[];
70
+ summary: {
71
+ executiveSummary: string;
72
+ learningObjectives: string[];
73
+ keyConcepts: string[];
74
+ followUpActions: string[];
75
+ targetAudience: string;
76
+ prerequisites: string[];
77
+ tags: string[];
78
+ };
79
+ generatedAt: string;
80
+ description?: string | undefined;
81
+ } | null;
82
+ imageUrl: string | null;
83
+ segments: ({
84
+ id: string;
85
+ title: string;
86
+ audioUrl: string;
87
+ objectKey: string;
88
+ startTime: number;
89
+ duration: number;
90
+ order: number;
91
+ } | {
92
+ id: string;
93
+ title: string;
94
+ audioUrl: null;
95
+ objectKey: string | null;
96
+ startTime: number;
97
+ duration: number;
98
+ order: number;
99
+ })[];
100
+ createdAt: Date;
101
+ updatedAt: Date;
102
+ workspaceId: string;
103
+ generating: boolean;
104
+ generatingMetadata: import("@prisma/client/runtime/library").JsonValue;
105
+ type: import("@prisma/client").$Enums.ArtifactType;
106
+ createdById: string | null;
107
+ isArchived: boolean;
108
+ }[]>;
109
+ getEpisode(userId: string, episodeId: string): Promise<{
110
+ id: string;
111
+ title: string;
112
+ description: string | undefined;
113
+ metadata: {
114
+ title: string;
115
+ totalDuration: number;
116
+ speakers: {
117
+ id: string;
118
+ role: "host" | "guest" | "expert";
119
+ name?: string | undefined;
120
+ }[];
121
+ summary: {
122
+ executiveSummary: string;
123
+ learningObjectives: string[];
124
+ keyConcepts: string[];
125
+ followUpActions: string[];
126
+ targetAudience: string;
127
+ prerequisites: string[];
128
+ tags: string[];
129
+ };
130
+ generatedAt: string;
131
+ description?: string | undefined;
132
+ };
133
+ imageUrl: string | null;
134
+ segments: ({
135
+ id: string;
136
+ title: string;
137
+ content: string;
138
+ audioUrl: string;
139
+ objectKey: string;
140
+ startTime: number;
141
+ duration: number;
142
+ keyPoints: string[];
143
+ order: number;
144
+ } | {
145
+ id: string;
146
+ title: string;
147
+ content: string;
148
+ audioUrl: null;
149
+ objectKey: string | null;
150
+ startTime: number;
151
+ duration: number;
152
+ keyPoints: string[];
153
+ order: number;
154
+ })[];
155
+ content: string;
156
+ createdAt: Date;
157
+ updatedAt: Date;
158
+ }>;
159
+ generateEpisode(userId: string, input: {
160
+ workspaceId: string;
161
+ podcastData: PodcastInput;
162
+ }): Promise<{
163
+ id: string;
164
+ title: any;
165
+ description: string | undefined;
166
+ metadata: {
167
+ title: any;
168
+ description: string | undefined;
169
+ totalDuration: number;
170
+ summary: any;
171
+ speakers: {
172
+ id: string;
173
+ role: "host" | "guest" | "expert";
174
+ name?: string | undefined;
175
+ }[];
176
+ generatedAt: string;
177
+ };
178
+ content: string;
179
+ }>;
180
+ deleteSegment(segmentId: string): Promise<{
181
+ meta: import("@prisma/client/runtime/library").JsonValue | null;
182
+ id: string;
183
+ createdAt: Date;
184
+ updatedAt: Date;
185
+ title: string;
186
+ generating: boolean;
187
+ generatingMetadata: import("@prisma/client/runtime/library").JsonValue | null;
188
+ artifactId: string;
189
+ content: string;
190
+ objectKey: string | null;
191
+ duration: number;
192
+ order: number;
193
+ startTime: number;
194
+ audioUrl: string | null;
195
+ keyPoints: string[];
196
+ }>;
197
+ getEpisodeSchema(userId: string, episodeId: string): Promise<{
198
+ segments: {
199
+ id: string;
200
+ title: string;
201
+ startTime: number;
202
+ duration: number;
203
+ keyPoints: string[];
204
+ order: number;
205
+ }[];
206
+ summary: {
207
+ executiveSummary: string;
208
+ learningObjectives: string[];
209
+ keyConcepts: string[];
210
+ followUpActions: string[];
211
+ targetAudience: string;
212
+ prerequisites: string[];
213
+ tags: string[];
214
+ };
215
+ metadata: {
216
+ title: string;
217
+ description: string | undefined;
218
+ totalDuration: number;
219
+ speakers: {
220
+ id: string;
221
+ role: "host" | "guest" | "expert";
222
+ name?: string | undefined;
223
+ }[];
224
+ };
225
+ }>;
226
+ updateEpisode(userId: string, input: {
227
+ episodeId: string;
228
+ title?: string;
229
+ description?: string;
230
+ }): Promise<{
231
+ id: string;
232
+ createdAt: Date;
233
+ updatedAt: Date;
234
+ workspaceId: string;
235
+ type: import("@prisma/client").$Enums.ArtifactType;
236
+ title: string;
237
+ isArchived: boolean;
238
+ difficulty: import("@prisma/client").$Enums.Difficulty | null;
239
+ estimatedTime: string | null;
240
+ createdById: string | null;
241
+ description: string | null;
242
+ generating: boolean;
243
+ generatingMetadata: import("@prisma/client/runtime/library").JsonValue | null;
244
+ worksheetConfig: import("@prisma/client/runtime/library").JsonValue | null;
245
+ imageObjectKey: string | null;
246
+ }>;
247
+ deleteEpisode(userId: string, episodeId: string): Promise<boolean>;
248
+ getSegment(userId: string, segmentId: string): Promise<{
249
+ id: string;
250
+ title: string;
251
+ content: string;
252
+ startTime: number;
253
+ duration: number;
254
+ order: number;
255
+ keyPoints: string[];
256
+ audioUrl: string | null;
257
+ objectKey: string | null;
258
+ meta: import("@prisma/client/runtime/library").JsonValue;
259
+ createdAt: Date;
260
+ updatedAt: Date;
261
+ }>;
262
+ getAvailableVoices(): {
263
+ id: string;
264
+ name: string;
265
+ description: string;
266
+ }[];
267
+ }