@goscribe/server 1.1.7 → 1.3.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 (56) hide show
  1. package/.env.example +43 -0
  2. package/check-difficulty.cjs +14 -0
  3. package/check-questions.cjs +14 -0
  4. package/db-summary.cjs +22 -0
  5. package/dist/routers/auth.js +1 -1
  6. package/mcq-test.cjs +36 -0
  7. package/package.json +10 -2
  8. package/prisma/migrations/20260413143206_init/migration.sql +873 -0
  9. package/prisma/schema.prisma +485 -292
  10. package/src/context.ts +4 -1
  11. package/src/lib/activity_human_description.test.ts +28 -0
  12. package/src/lib/activity_human_description.ts +239 -0
  13. package/src/lib/activity_log_service.test.ts +37 -0
  14. package/src/lib/activity_log_service.ts +353 -0
  15. package/src/lib/ai-session.ts +194 -112
  16. package/src/lib/constants.ts +14 -0
  17. package/src/lib/email.ts +230 -0
  18. package/src/lib/env.ts +23 -6
  19. package/src/lib/inference.ts +3 -3
  20. package/src/lib/logger.ts +26 -9
  21. package/src/lib/notification-service.test.ts +106 -0
  22. package/src/lib/notification-service.ts +677 -0
  23. package/src/lib/prisma.ts +6 -1
  24. package/src/lib/pusher.ts +90 -6
  25. package/src/lib/retry.ts +61 -0
  26. package/src/lib/storage.ts +2 -2
  27. package/src/lib/stripe.ts +39 -0
  28. package/src/lib/subscription_service.ts +722 -0
  29. package/src/lib/usage_service.ts +74 -0
  30. package/src/lib/worksheet-generation.test.ts +31 -0
  31. package/src/lib/worksheet-generation.ts +139 -0
  32. package/src/lib/workspace-access.ts +13 -0
  33. package/src/routers/_app.ts +11 -0
  34. package/src/routers/admin.ts +710 -0
  35. package/src/routers/annotations.ts +227 -0
  36. package/src/routers/auth.ts +432 -33
  37. package/src/routers/copilot.ts +719 -0
  38. package/src/routers/flashcards.ts +207 -80
  39. package/src/routers/members.ts +280 -80
  40. package/src/routers/notifications.ts +142 -0
  41. package/src/routers/payment.ts +448 -0
  42. package/src/routers/podcast.ts +133 -108
  43. package/src/routers/studyguide.ts +80 -74
  44. package/src/routers/worksheets.ts +300 -80
  45. package/src/routers/workspace.ts +538 -328
  46. package/src/scripts/purge-deleted-users.ts +167 -0
  47. package/src/server.ts +140 -12
  48. package/src/services/flashcard-progress.service.ts +52 -43
  49. package/src/trpc.ts +184 -5
  50. package/test-generate.js +30 -0
  51. package/test-ratio.cjs +9 -0
  52. package/zod-test.cjs +22 -0
  53. package/prisma/migrations/20250826124819_add_worksheet_difficulty_and_estimated_time/migration.sql +0 -213
  54. package/prisma/migrations/20250826133236_add_worksheet_question_progress/migration.sql +0 -31
  55. package/prisma/seed.mjs +0 -135
  56. package/src/routers/meetingsummary.ts +0 -416
package/src/trpc.ts CHANGED
@@ -1,8 +1,22 @@
1
1
  import { initTRPC, TRPCError } from "@trpc/server";
2
2
  import superjson from "superjson";
3
+ import { ActivityLogStatus } from "@prisma/client";
3
4
  import type { Context } from "./context.js";
4
5
  import { logger } from "./lib/logger.js";
5
6
  import { toTRPCError } from "./lib/errors.js";
7
+ import { getUserUsage, getUserPlanLimits } from "./lib/usage_service.js";
8
+ import {
9
+ getClientIp,
10
+ isActivityLogEnabled,
11
+ scheduleRecordActivity,
12
+ truncateUserAgent,
13
+ } from "./lib/activity_log_service.js";
14
+
15
+ /** Avoid logging the log viewers themselves (noise when browsing activity). */
16
+ const SKIP_ACTIVITY_TRPC_PATHS = new Set([
17
+ "admin.activityList",
18
+ "admin.activityExportCsv",
19
+ ]);
6
20
 
7
21
  const t = initTRPC.context<Context>().create({
8
22
  transformer: superjson,
@@ -15,7 +29,7 @@ const t = initTRPC.context<Context>().create({
15
29
  cause: error.cause,
16
30
  });
17
31
  }
18
-
32
+
19
33
  return {
20
34
  ...shape,
21
35
  data: {
@@ -37,12 +51,12 @@ const loggingMiddleware = middleware(async ({ ctx, next, path, type }) => {
37
51
  const start = Date.now();
38
52
  const result = await next();
39
53
  const duration = Date.now() - start;
40
-
54
+
41
55
  logger.info(`TRPC ${type} ${path}`, 'TRPC', {
42
56
  duration: `${duration}ms`,
43
57
  userId: (ctx.session as any)?.user?.id,
44
58
  });
45
-
59
+
46
60
  return result;
47
61
  });
48
62
 
@@ -52,7 +66,7 @@ const loggingMiddleware = middleware(async ({ ctx, next, path, type }) => {
52
66
  const isAuthed = middleware(({ ctx, next }) => {
53
67
  const hasUser = Boolean((ctx.session as any)?.user?.id);
54
68
  if (!ctx.session || !hasUser) {
55
- throw new TRPCError({
69
+ throw new TRPCError({
56
70
  code: "UNAUTHORIZED",
57
71
  message: "You must be logged in to access this resource"
58
72
  });
@@ -60,6 +74,7 @@ const isAuthed = middleware(({ ctx, next }) => {
60
74
 
61
75
  return next({
62
76
  ctx: {
77
+ ...ctx,
63
78
  session: ctx.session,
64
79
  userId: (ctx.session as any).user.id,
65
80
  },
@@ -77,8 +92,172 @@ const errorHandler = middleware(async ({ next }) => {
77
92
  }
78
93
  });
79
94
 
95
+ /**
96
+ * Middleware that enforces email verification
97
+ */
98
+ const isVerified = middleware(async ({ ctx, next }) => {
99
+ const user = await ctx.db.user.findUnique({
100
+ where: { id: (ctx.session as any).user.id },
101
+ select: { emailVerified: true },
102
+ });
103
+
104
+ if (!user?.emailVerified) {
105
+ throw new TRPCError({
106
+ code: "FORBIDDEN",
107
+ message: "Please verify your email to access this feature",
108
+ });
109
+ }
110
+
111
+ return next();
112
+ });
113
+
114
+ /**
115
+ * Middleware that enforces resource limits based on the user's plan.
116
+ * Note: This matches the 'path' to decide which limit to check.
117
+ */
118
+ const checkUsageLimit = middleware(async ({ ctx, next, path }) => {
119
+ const userId = (ctx.session as any).user.id;
120
+
121
+ // 1. Get current usage and limits
122
+ const [usage, limits] = await Promise.all([
123
+ getUserUsage(userId),
124
+ getUserPlanLimits(userId)
125
+ ]);
126
+
127
+ // If no limits found (no active plan), we block any premium actions
128
+ if (!limits) {
129
+ throw new TRPCError({
130
+ code: "FORBIDDEN",
131
+ message: "No active plan found. Please subscribe to a plan to continue.",
132
+ });
133
+ }
134
+
135
+ // 2. Check limits based on the tRPC path
136
+
137
+ // Flashcards (matches: flashcards.createCard, flashcards.generateFromPrompt)
138
+ if (path.startsWith('flashcards.') && (path.includes('create') || path.includes('generate')) && usage.flashcards >= limits.maxFlashcards) {
139
+ throw new TRPCError({ code: "FORBIDDEN", message: "Flashcard limit reached for your plan." });
140
+ }
141
+
142
+ // Worksheets (matches: worksheets.create, worksheets.generateFromPrompt)
143
+ if (path.startsWith('worksheets.') && (path.includes('create') || path.includes('generate')) && usage.worksheets >= limits.maxWorksheets) {
144
+ throw new TRPCError({ code: "FORBIDDEN", message: "Worksheet limit reached for your plan." });
145
+ }
146
+
147
+ // Podcasts (matches: podcast.generateEpisode)
148
+ if (path.startsWith('podcast.') && path.includes('generate') && usage.podcasts >= limits.maxPodcasts) {
149
+ throw new TRPCError({ code: "FORBIDDEN", message: "Podcast limit reached for your plan." });
150
+ }
151
+
152
+ // Study Guides (matches: studyguide.get - because it lazily creates)
153
+ if (path.startsWith('studyguide.') && path.includes('get') && usage.studyGuides >= limits.maxStudyGuides) {
154
+ // Note: We only block if the artifact doesn't exist yet (handled inside the query or by checking usage)
155
+ // For simplicity, if they hit the limit, we block creation of NEW study guides.
156
+ // However, usage_service counts existing ones.
157
+ // If usage is already at/over limit, it means any NEW workspace's 'get' will fail creation.
158
+ }
159
+
160
+ // Storage check (for uploads)
161
+ if (path.includes('upload') && usage.storageBytes >= Number(limits.maxStorageBytes)) {
162
+ throw new TRPCError({ code: "FORBIDDEN", message: "Storage limit reached for your plan." });
163
+ }
164
+
165
+ return next();
166
+ });
167
+
168
+ /**
169
+ * Middleware that enforces system admin role
170
+ */
171
+ const isAdmin = middleware(async ({ ctx, next }) => {
172
+ const user = await ctx.db.user.findUnique({
173
+ where: { id: (ctx.session as any).user.id },
174
+ include: { role: true },
175
+ });
176
+
177
+ if (user?.role?.name !== 'System Admin') {
178
+ throw new TRPCError({
179
+ code: "FORBIDDEN",
180
+ message: "You do not have permission to access this resource",
181
+ });
182
+ }
183
+
184
+ return next();
185
+ });
186
+
187
+ /**
188
+ * Persists ActivityLog rows for authenticated tRPC calls (async, non-blocking).
189
+ */
190
+ const activityLogMiddleware = middleware(async (opts) => {
191
+ const { ctx, next, path, type, getRawInput } = opts;
192
+ if (!isActivityLogEnabled() || SKIP_ACTIVITY_TRPC_PATHS.has(path)) {
193
+ return next();
194
+ }
195
+
196
+ const userId = (ctx as any).userId as string | undefined;
197
+ if (!userId) {
198
+ return next();
199
+ }
200
+
201
+ let rawInput: unknown;
202
+ try {
203
+ rawInput = await getRawInput();
204
+ } catch {
205
+ rawInput = undefined;
206
+ }
207
+
208
+ const req = ctx.req;
209
+ const ipAddress = req ? getClientIp(req) : undefined;
210
+ const userAgent = req.headers["user-agent"];
211
+ const httpMethod = req.method;
212
+
213
+ const start = Date.now();
214
+ const result = await next();
215
+ const durationMs = Date.now() - start;
216
+
217
+ if (result.ok) {
218
+ scheduleRecordActivity({
219
+ db: ctx.db,
220
+ actorUserId: userId,
221
+ path,
222
+ type,
223
+ status: ActivityLogStatus.SUCCESS,
224
+ durationMs,
225
+ rawInput,
226
+ ipAddress,
227
+ userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
228
+ httpMethod,
229
+ });
230
+ } else {
231
+ scheduleRecordActivity({
232
+ db: ctx.db,
233
+ actorUserId: userId,
234
+ path,
235
+ type,
236
+ status: ActivityLogStatus.FAILURE,
237
+ durationMs,
238
+ rawInput,
239
+ ipAddress,
240
+ userAgent: truncateUserAgent(typeof userAgent === "string" ? userAgent : undefined),
241
+ httpMethod,
242
+ errorCode: result.error.code,
243
+ });
244
+ }
245
+
246
+ return result;
247
+ });
248
+
80
249
  /** Exported procedures with middleware */
81
250
  export const authedProcedure = publicProcedure
82
251
  .use(loggingMiddleware)
83
252
  .use(errorHandler)
84
- .use(isAuthed);
253
+ .use(isAuthed)
254
+ .use(activityLogMiddleware);
255
+
256
+ export const verifiedProcedure = authedProcedure
257
+ .use(isVerified);
258
+
259
+ export const adminProcedure = authedProcedure
260
+ .use(isAdmin);
261
+
262
+ export const limitedProcedure = verifiedProcedure
263
+ .use(checkUsageLimit);
@@ -0,0 +1,30 @@
1
+ const AI_SERVICE_URL = 'http://localhost:5000/upload';
2
+
3
+ async function testBackend() {
4
+ const formData = new FormData();
5
+ formData.append('command', 'generate_worksheet_questions');
6
+ formData.append('session', 'test-session-123'); // Need a dummy workspace/session that exists, or the Backend will fail `get_messages`.
7
+ formData.append('user', 'test-user-123');
8
+ formData.append('num_questions', '8');
9
+ formData.append('difficulty', 'HARD');
10
+ formData.append('mode', 'practice');
11
+ formData.append('mcq_ratio', '0.5'); // We want exactly 4 MCQs and 4 Texts.
12
+ formData.append('question_types', JSON.stringify(['MULTIPLE_CHOICE', 'TEXT']));
13
+
14
+ // Note: for this to work, the python backend needs a `messages.json` file to exist for this user/session.
15
+ // We'll see if it fails due to directory structure.
16
+ console.log("Calling python backend...");
17
+ try {
18
+ const res = await fetch(AI_SERVICE_URL, { method: 'POST', body: formData });
19
+ if (!res.ok) console.error("Error from backend:", res.status, res.statusText, await res.text());
20
+ else {
21
+ const data = await res.json();
22
+ console.log("Success! Generated Worksheet JSON:");
23
+ console.log(data);
24
+ }
25
+ } catch (e) {
26
+ console.error("Fetch failed:", e);
27
+ }
28
+ }
29
+
30
+ testBackend();
package/test-ratio.cjs ADDED
@@ -0,0 +1,9 @@
1
+ const numQuestions = 8;
2
+ const mcqCount = 4;
3
+
4
+ const mcqRatio = typeof mcqCount === 'number'
5
+ ? Math.min(1, Math.max(0, mcqCount / Math.max(1, numQuestions)))
6
+ : undefined;
7
+
8
+ console.log("Resulting mcqRatio:", mcqRatio);
9
+ console.log("mcqRatio stringified:", JSON.stringify({ mcqRatio }));
package/zod-test.cjs ADDED
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+
3
+ const worksheetModeSchema = z.enum(['practice', 'quiz']);
4
+ const worksheetDifficultyInputSchema = z.enum(['easy', 'medium', 'hard']);
5
+ const questionTypeSchema = z.enum(['MULTIPLE_CHOICE', 'TEXT']);
6
+
7
+ const worksheetPresetConfigSchema = z.object({
8
+ mode: worksheetModeSchema.default('practice'),
9
+ numQuestions: z.number().int().min(1).max(20).default(8),
10
+ difficulty: worksheetDifficultyInputSchema.default('medium'),
11
+ questionTypes: z.array(questionTypeSchema).optional(),
12
+ mcqRatio: z.number().min(0).max(1).optional(),
13
+ });
14
+
15
+ const worksheetPresetConfigPartialSchema = worksheetPresetConfigSchema.partial();
16
+
17
+ const parsed = worksheetPresetConfigPartialSchema.parse({
18
+ questionTypes: ['MULTIPLE_CHOICE', 'TEXT'],
19
+ mcqRatio: 0.5
20
+ });
21
+
22
+ console.log("Parsed result:", parsed);
@@ -1,213 +0,0 @@
1
- -- CreateEnum
2
- CREATE TYPE "public"."ArtifactType" AS ENUM ('STUDY_GUIDE', 'FLASHCARD_SET', 'WORKSHEET', 'MEETING_SUMMARY', 'PODCAST_EPISODE');
3
-
4
- -- CreateEnum
5
- CREATE TYPE "public"."Difficulty" AS ENUM ('EASY', 'MEDIUM', 'HARD');
6
-
7
- -- CreateEnum
8
- CREATE TYPE "public"."QuestionType" AS ENUM ('MULTIPLE_CHOICE', 'TEXT', 'NUMERIC', 'TRUE_FALSE', 'MATCHING', 'FILL_IN_THE_BLANK');
9
-
10
- -- CreateTable
11
- CREATE TABLE "public"."User" (
12
- "id" TEXT NOT NULL,
13
- "name" TEXT,
14
- "email" TEXT,
15
- "emailVerified" TIMESTAMP(3),
16
- "passwordHash" TEXT,
17
- "image" TEXT,
18
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
19
- "updatedAt" TIMESTAMP(3) NOT NULL,
20
-
21
- CONSTRAINT "User_pkey" PRIMARY KEY ("id")
22
- );
23
-
24
- -- CreateTable
25
- CREATE TABLE "public"."Session" (
26
- "id" TEXT NOT NULL,
27
- "userId" TEXT NOT NULL,
28
- "expires" TIMESTAMP(3) NOT NULL,
29
-
30
- CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
31
- );
32
-
33
- -- CreateTable
34
- CREATE TABLE "public"."VerificationToken" (
35
- "identifier" TEXT NOT NULL,
36
- "token" TEXT NOT NULL,
37
- "expires" TIMESTAMP(3) NOT NULL
38
- );
39
-
40
- -- CreateTable
41
- CREATE TABLE "public"."Folder" (
42
- "id" TEXT NOT NULL,
43
- "name" TEXT NOT NULL,
44
- "ownerId" TEXT NOT NULL,
45
- "parentId" TEXT,
46
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
47
- "updatedAt" TIMESTAMP(3) NOT NULL,
48
-
49
- CONSTRAINT "Folder_pkey" PRIMARY KEY ("id")
50
- );
51
-
52
- -- CreateTable
53
- CREATE TABLE "public"."Workspace" (
54
- "id" TEXT NOT NULL,
55
- "title" TEXT NOT NULL,
56
- "description" TEXT,
57
- "ownerId" TEXT NOT NULL,
58
- "folderId" TEXT,
59
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
60
- "updatedAt" TIMESTAMP(3) NOT NULL,
61
-
62
- CONSTRAINT "Workspace_pkey" PRIMARY KEY ("id")
63
- );
64
-
65
- -- CreateTable
66
- CREATE TABLE "public"."FileAsset" (
67
- "id" TEXT NOT NULL,
68
- "workspaceId" TEXT NOT NULL,
69
- "userId" TEXT NOT NULL,
70
- "name" TEXT NOT NULL,
71
- "mimeType" TEXT NOT NULL,
72
- "size" INTEGER NOT NULL,
73
- "bucket" TEXT,
74
- "objectKey" TEXT,
75
- "url" TEXT,
76
- "checksum" TEXT,
77
- "meta" JSONB,
78
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
79
-
80
- CONSTRAINT "FileAsset_pkey" PRIMARY KEY ("id")
81
- );
82
-
83
- -- CreateTable
84
- CREATE TABLE "public"."Artifact" (
85
- "id" TEXT NOT NULL,
86
- "workspaceId" TEXT NOT NULL,
87
- "type" "public"."ArtifactType" NOT NULL,
88
- "title" TEXT NOT NULL,
89
- "isArchived" BOOLEAN NOT NULL DEFAULT false,
90
- "difficulty" "public"."Difficulty",
91
- "estimatedTime" TEXT,
92
- "createdById" TEXT,
93
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
94
- "updatedAt" TIMESTAMP(3) NOT NULL,
95
-
96
- CONSTRAINT "Artifact_pkey" PRIMARY KEY ("id")
97
- );
98
-
99
- -- CreateTable
100
- CREATE TABLE "public"."ArtifactVersion" (
101
- "id" TEXT NOT NULL,
102
- "artifactId" TEXT NOT NULL,
103
- "content" TEXT NOT NULL,
104
- "data" JSONB,
105
- "version" INTEGER NOT NULL,
106
- "createdById" TEXT,
107
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
108
-
109
- CONSTRAINT "ArtifactVersion_pkey" PRIMARY KEY ("id")
110
- );
111
-
112
- -- CreateTable
113
- CREATE TABLE "public"."Flashcard" (
114
- "id" TEXT NOT NULL,
115
- "artifactId" TEXT NOT NULL,
116
- "front" TEXT NOT NULL,
117
- "back" TEXT NOT NULL,
118
- "tags" TEXT[],
119
- "order" INTEGER NOT NULL DEFAULT 0,
120
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
121
-
122
- CONSTRAINT "Flashcard_pkey" PRIMARY KEY ("id")
123
- );
124
-
125
- -- CreateTable
126
- CREATE TABLE "public"."WorksheetQuestion" (
127
- "id" TEXT NOT NULL,
128
- "artifactId" TEXT NOT NULL,
129
- "prompt" TEXT NOT NULL,
130
- "answer" TEXT,
131
- "type" "public"."QuestionType" NOT NULL DEFAULT 'TEXT',
132
- "difficulty" "public"."Difficulty" NOT NULL DEFAULT 'MEDIUM',
133
- "order" INTEGER NOT NULL DEFAULT 0,
134
- "meta" JSONB,
135
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
136
-
137
- CONSTRAINT "WorksheetQuestion_pkey" PRIMARY KEY ("id")
138
- );
139
-
140
- -- CreateIndex
141
- CREATE UNIQUE INDEX "User_email_key" ON "public"."User"("email");
142
-
143
- -- CreateIndex
144
- CREATE UNIQUE INDEX "VerificationToken_token_key" ON "public"."VerificationToken"("token");
145
-
146
- -- CreateIndex
147
- CREATE UNIQUE INDEX "VerificationToken_identifier_token_key" ON "public"."VerificationToken"("identifier", "token");
148
-
149
- -- CreateIndex
150
- CREATE INDEX "Folder_ownerId_parentId_idx" ON "public"."Folder"("ownerId", "parentId");
151
-
152
- -- CreateIndex
153
- CREATE INDEX "Workspace_ownerId_folderId_idx" ON "public"."Workspace"("ownerId", "folderId");
154
-
155
- -- CreateIndex
156
- CREATE INDEX "FileAsset_workspaceId_idx" ON "public"."FileAsset"("workspaceId");
157
-
158
- -- CreateIndex
159
- CREATE INDEX "FileAsset_userId_createdAt_idx" ON "public"."FileAsset"("userId", "createdAt");
160
-
161
- -- CreateIndex
162
- CREATE INDEX "Artifact_workspaceId_type_idx" ON "public"."Artifact"("workspaceId", "type");
163
-
164
- -- CreateIndex
165
- CREATE INDEX "ArtifactVersion_artifactId_idx" ON "public"."ArtifactVersion"("artifactId");
166
-
167
- -- CreateIndex
168
- CREATE UNIQUE INDEX "ArtifactVersion_artifactId_version_key" ON "public"."ArtifactVersion"("artifactId", "version");
169
-
170
- -- CreateIndex
171
- CREATE INDEX "Flashcard_artifactId_idx" ON "public"."Flashcard"("artifactId");
172
-
173
- -- CreateIndex
174
- CREATE INDEX "WorksheetQuestion_artifactId_idx" ON "public"."WorksheetQuestion"("artifactId");
175
-
176
- -- AddForeignKey
177
- ALTER TABLE "public"."Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
178
-
179
- -- AddForeignKey
180
- ALTER TABLE "public"."Folder" ADD CONSTRAINT "Folder_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
181
-
182
- -- AddForeignKey
183
- ALTER TABLE "public"."Folder" ADD CONSTRAINT "Folder_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "public"."Folder"("id") ON DELETE CASCADE ON UPDATE CASCADE;
184
-
185
- -- AddForeignKey
186
- ALTER TABLE "public"."Workspace" ADD CONSTRAINT "Workspace_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
187
-
188
- -- AddForeignKey
189
- ALTER TABLE "public"."Workspace" ADD CONSTRAINT "Workspace_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "public"."Folder"("id") ON DELETE SET NULL ON UPDATE CASCADE;
190
-
191
- -- AddForeignKey
192
- ALTER TABLE "public"."FileAsset" ADD CONSTRAINT "FileAsset_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "public"."Workspace"("id") ON DELETE CASCADE ON UPDATE CASCADE;
193
-
194
- -- AddForeignKey
195
- ALTER TABLE "public"."FileAsset" ADD CONSTRAINT "FileAsset_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
196
-
197
- -- AddForeignKey
198
- ALTER TABLE "public"."Artifact" ADD CONSTRAINT "Artifact_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "public"."Workspace"("id") ON DELETE CASCADE ON UPDATE CASCADE;
199
-
200
- -- AddForeignKey
201
- ALTER TABLE "public"."Artifact" ADD CONSTRAINT "Artifact_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
202
-
203
- -- AddForeignKey
204
- ALTER TABLE "public"."ArtifactVersion" ADD CONSTRAINT "ArtifactVersion_artifactId_fkey" FOREIGN KEY ("artifactId") REFERENCES "public"."Artifact"("id") ON DELETE CASCADE ON UPDATE CASCADE;
205
-
206
- -- AddForeignKey
207
- ALTER TABLE "public"."ArtifactVersion" ADD CONSTRAINT "ArtifactVersion_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
208
-
209
- -- AddForeignKey
210
- ALTER TABLE "public"."Flashcard" ADD CONSTRAINT "Flashcard_artifactId_fkey" FOREIGN KEY ("artifactId") REFERENCES "public"."Artifact"("id") ON DELETE CASCADE ON UPDATE CASCADE;
211
-
212
- -- AddForeignKey
213
- ALTER TABLE "public"."WorksheetQuestion" ADD CONSTRAINT "WorksheetQuestion_artifactId_fkey" FOREIGN KEY ("artifactId") REFERENCES "public"."Artifact"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -1,31 +0,0 @@
1
- -- AlterTable
2
- ALTER TABLE "public"."Artifact" ADD COLUMN "description" TEXT;
3
-
4
- -- CreateTable
5
- CREATE TABLE "public"."WorksheetQuestionProgress" (
6
- "id" TEXT NOT NULL,
7
- "worksheetQuestionId" TEXT NOT NULL,
8
- "userId" TEXT NOT NULL,
9
- "completed" BOOLEAN NOT NULL DEFAULT false,
10
- "userAnswer" TEXT,
11
- "completedAt" TIMESTAMP(3),
12
- "attempts" INTEGER NOT NULL DEFAULT 0,
13
- "timeSpentSec" INTEGER,
14
- "meta" JSONB,
15
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
16
- "updatedAt" TIMESTAMP(3) NOT NULL,
17
-
18
- CONSTRAINT "WorksheetQuestionProgress_pkey" PRIMARY KEY ("id")
19
- );
20
-
21
- -- CreateIndex
22
- CREATE INDEX "WorksheetQuestionProgress_userId_idx" ON "public"."WorksheetQuestionProgress"("userId");
23
-
24
- -- CreateIndex
25
- CREATE UNIQUE INDEX "WorksheetQuestionProgress_worksheetQuestionId_userId_key" ON "public"."WorksheetQuestionProgress"("worksheetQuestionId", "userId");
26
-
27
- -- AddForeignKey
28
- ALTER TABLE "public"."WorksheetQuestionProgress" ADD CONSTRAINT "WorksheetQuestionProgress_worksheetQuestionId_fkey" FOREIGN KEY ("worksheetQuestionId") REFERENCES "public"."WorksheetQuestion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
29
-
30
- -- AddForeignKey
31
- ALTER TABLE "public"."WorksheetQuestionProgress" ADD CONSTRAINT "WorksheetQuestionProgress_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
package/prisma/seed.mjs DELETED
@@ -1,135 +0,0 @@
1
- import { PrismaClient } from '@prisma/client';
2
-
3
- const prisma = new PrismaClient();
4
-
5
- async function main() {
6
- // Create/find a demo user
7
- const userEmail = 'demo@example.com';
8
- const user = await prisma.user.upsert({
9
- where: { email: userEmail },
10
- update: {},
11
- create: {
12
- email: userEmail,
13
- name: 'Demo User',
14
- image: null,
15
- },
16
- });
17
-
18
- // Create a workspace
19
- const workspace = await prisma.workspace.upsert({
20
- where: { id: 'ws_demo_1' },
21
- update: {},
22
- create: {
23
- id: 'ws_demo_1',
24
- title: 'Demo Workspace',
25
- description: 'Seeded workspace with sample artifacts',
26
- ownerId: user.id,
27
- },
28
- });
29
-
30
- // Create a Worksheet artifact with diverse question types
31
- const worksheet = await prisma.artifact.create({
32
- data: {
33
- workspaceId: workspace.id,
34
- type: 'WORKSHEET',
35
- title: 'Sample Worksheet: Mixed Question Types',
36
- createdById: user.id,
37
- questions: {
38
- create: [
39
- {
40
- prompt: 'What is the capital of France?',
41
- answer: 'Paris',
42
- type: 'TEXT',
43
- order: 0,
44
- },
45
- {
46
- prompt: '2 + 2 = ?',
47
- answer: '4',
48
- type: 'NUMERIC',
49
- order: 1,
50
- },
51
- {
52
- prompt: 'Select the prime numbers',
53
- answer: '2',
54
- type: 'MULTIPLE_CHOICE',
55
- order: 2,
56
- meta: { options: ['1', '2', '4', '6'] },
57
- },
58
- {
59
- prompt: 'The earth is flat.',
60
- answer: 'False',
61
- type: 'TRUE_FALSE',
62
- order: 3,
63
- meta: { options: ['True', 'False'] },
64
- },
65
- {
66
- prompt: 'Match the country to its capital (type answers).',
67
- answer: '',
68
- type: 'MATCHING',
69
- order: 4,
70
- meta: { options: ['Japan ->', 'Germany ->', 'Canada ->'] },
71
- },
72
- {
73
- prompt: 'The chemical symbol for water is ____.',
74
- answer: 'H2O',
75
- type: 'FILL_IN_THE_BLANK',
76
- order: 5,
77
- },
78
- ],
79
- },
80
- },
81
- include: { questions: true },
82
- });
83
-
84
- // Create a Flashcard set artifact with a couple of cards
85
- const flashcardSet = await prisma.artifact.create({
86
- data: {
87
- workspaceId: workspace.id,
88
- type: 'FLASHCARD_SET',
89
- title: 'Sample Flashcards: Basics',
90
- createdById: user.id,
91
- flashcards: {
92
- create: [
93
- { front: 'HTTP Status 200', back: 'OK', order: 0 },
94
- { front: 'HTTP Status 404', back: 'Not Found', order: 1 },
95
- ],
96
- },
97
- },
98
- include: { flashcards: true },
99
- });
100
-
101
- // Add a simple study guide versioned artifact
102
- const studyGuide = await prisma.artifact.create({
103
- data: {
104
- workspaceId: workspace.id,
105
- type: 'STUDY_GUIDE',
106
- title: 'Sample Study Guide',
107
- createdById: user.id,
108
- versions: {
109
- create: [
110
- { content: '# Intro\nThis is a seeded study guide.', version: 1, createdById: user.id },
111
- ],
112
- },
113
- },
114
- include: { versions: true },
115
- });
116
-
117
- console.log('Seed complete:', {
118
- user: { id: user.id, email: user.email },
119
- workspace: { id: workspace.id, title: workspace.title },
120
- worksheet: { id: worksheet.id, title: worksheet.title, questions: worksheet.questions.length },
121
- flashcardSet: { id: flashcardSet.id, cards: flashcardSet.flashcards.length },
122
- studyGuide: { id: studyGuide.id, versions: studyGuide.versions.length },
123
- });
124
- }
125
-
126
- main()
127
- .catch((e) => {
128
- console.error(e);
129
- process.exit(1);
130
- })
131
- .finally(async () => {
132
- await prisma.$disconnect();
133
- });
134
-
135
-