{{ message }}
Repository navigation
Expand file tree
/
Copy pathschema.prisma
More file actions
706 lines (604 loc) · 22.1 KB
/
Copy pathschema.prisma
File metadata and controls
706 lines (604 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Tenant {
id String @id @default(cuid())
name String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
apiKeys ApiKey[]
courses Course[]
courseVersions CourseVersion[]
learners Learner[]
attempts Attempt[]
xapiStatements XapiStatement[]
xapiStates XapiState[]
xapiProfiles XapiProfile[]
cmi5Courses Cmi5Course[]
cmi5Regs Cmi5Registration[]
cmi5Sessions Cmi5Session[]
webhookEndpoints WebhookEndpoint[]
webhookDeliveries WebhookDelivery[]
certificates Certificate[]
aiConfigs AiProviderConfig[]
aiCalls AiCallLog[]
replayEvents ReplayEvent[]
}
model ApiKey {
id String @id @default(cuid())
tenantId String
name String
hashedKey String @unique
prefix String
createdAt DateTime @default(now())
lastUsedAt DateTime?
revokedAt DateTime?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
@@index([tenantId])
}
enum ScormVersion {
SCORM_12
SCORM_2004_2
SCORM_2004_3
SCORM_2004_4
}
model Course {
id String @id @default(cuid())
tenantId String
title String
description String?
scormVersion ScormVersion
storageKey String
launchUrl String
masteryScore Float?
manifest Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
/// The live release. The columns above mirror it, so readers that predate
/// versioning keep working; rollback only moves this pointer. Null for a
/// course uploaded before versioning existed until its next publish.
currentVersionId String? @unique
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
currentVersion CourseVersion? @relation("CourseCurrentVersion", fields: [currentVersionId], references: [id], onDelete: SetNull, onUpdate: NoAction)
versions CourseVersion[] @relation("CourseVersions")
scos Sco[]
attempts Attempt[]
certificates Certificate[]
@@index([tenantId])
}
/// An immutable release of a course package. Every published upload gets its
/// own storage prefix, so older releases stay launchable for the attempts
/// pinned to them and for rollback. `files` is the per-file SHA-256 inventory
/// the asset diff compares; it is null for a baseline backfilled from a course
/// uploaded before versioning, whose files were never hashed.
model CourseVersion {
id String @id @default(cuid())
tenantId String
courseId String
/// 1, 2, 3… in publish order.
number Int
/// Human release name, e.g. `1.0`, `1.1`, `2.0`. Unique per course.
label String
releaseNotes String?
title String
description String?
scormVersion ScormVersion
storageKey String
launchUrl String
masteryScore Float?
manifest Json
files Json?
fileCount Int @default(0)
sizeBytes BigInt @default(0)
/// SHA-256 of the uploaded ZIP; null for a backfilled baseline.
packageSha256 String?
createdAt DateTime @default(now())
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
course Course @relation("CourseVersions", fields: [courseId], references: [id], onDelete: Cascade)
currentOf Course? @relation("CourseCurrentVersion")
attempts Attempt[]
@@unique([courseId, number])
@@unique([courseId, label])
@@index([tenantId])
}
model Sco {
id String @id @default(cuid())
courseId String
identifier String
title String
launchHref String
parameters String?
order Int
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
attempts Attempt[]
@@unique([courseId, identifier])
@@index([courseId])
}
model Learner {
id String @id @default(cuid())
tenantId String
externalId String
name String?
createdAt DateTime @default(now())
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
attempts Attempt[]
certificates Certificate[]
@@unique([tenantId, externalId])
@@index([tenantId])
}
enum AttemptStatus {
IN_PROGRESS
COMPLETED
TERMINATED
EXPIRED
}
enum LessonStatus {
PASSED
COMPLETED
FAILED
INCOMPLETE
BROWSED
NOT_ATTEMPTED
}
enum CompletionStatus {
COMPLETED
INCOMPLETE
NOT_ATTEMPTED
UNKNOWN
}
enum SuccessStatus {
PASSED
FAILED
UNKNOWN
}
model Attempt {
id String @id @default(cuid())
tenantId String
courseId String
learnerId String
scoId String?
status AttemptStatus @default(IN_PROGRESS)
lessonStatus LessonStatus @default(NOT_ATTEMPTED)
completionStatus CompletionStatus @default(NOT_ATTEMPTED)
successStatus SuccessStatus @default(UNKNOWN)
lessonLocation String?
suspendData String?
scoreRaw Float?
scoreMin Float?
scoreMax Float?
scoreScaled Float?
sessionTimeSeconds Int @default(0)
totalTimeSeconds Int @default(0)
progressMeasure Float?
cmiSnapshot Json @default("{}")
startedAt DateTime @default(now())
lastCommitAt DateTime?
finishedAt DateTime?
/// Highest client commit sequence number applied (offline sync). Commits
/// carrying a `seq` at or below this are acknowledged without re-applying.
lastCommitSeq Int?
/// The course release this attempt launched on. Content keeps being served
/// from it after a newer version is published or the course is rolled back.
courseVersionId String?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
courseVersion CourseVersion? @relation(fields: [courseVersionId], references: [id], onDelete: SetNull)
learner Learner @relation(fields: [learnerId], references: [id], onDelete: Cascade)
sco Sco? @relation(fields: [scoId], references: [id], onDelete: SetNull)
interactions Interaction[]
objectives Objective[]
commits CommitLog[]
replayEvents ReplayEvent[]
certificate Certificate?
@@index([tenantId])
@@index([courseId])
@@index([learnerId])
@@index([tenantId, courseId, learnerId])
}
/// A completion certificate, issued at most once per attempt. Learner name,
/// course title and score are snapshotted at issue time so the certificate
/// keeps reading the same even if the learner or course is later renamed; the
/// PDF is rendered from these columns on demand rather than stored.
model Certificate {
id String @id @default(cuid())
tenantId String
attemptId String @unique
courseId String
learnerId String
/// Public verification code printed on the PDF, e.g. `7KQ2-M9XD-4TPA`.
serial String @unique
learnerName String
courseTitle String
scorePercent Float?
completedAt DateTime
issuedAt DateTime @default(now())
revokedAt DateTime?
revokedReason String?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
attempt Attempt @relation(fields: [attemptId], references: [id], onDelete: Cascade)
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
learner Learner @relation(fields: [learnerId], references: [id], onDelete: Cascade)
@@index([tenantId, issuedAt])
@@index([tenantId, learnerId])
@@index([tenantId, courseId])
}
model Interaction {
id String @id @default(cuid())
attemptId String
index Int
identifier String
type String?
learnerResponse String?
correctResponse String?
result String?
weighting Float?
latencySeconds Float?
description String?
timestamp DateTime @default(now())
attempt Attempt @relation(fields: [attemptId], references: [id], onDelete: Cascade)
@@unique([attemptId, index])
@@index([attemptId])
}
model Objective {
id String @id @default(cuid())
attemptId String
index Int
identifier String
scoreRaw Float?
scoreMin Float?
scoreMax Float?
scoreScaled Float?
successStatus SuccessStatus?
completionStatus CompletionStatus?
progressMeasure Float?
description String?
attempt Attempt @relation(fields: [attemptId], references: [id], onDelete: Cascade)
@@unique([attemptId, index])
@@index([attemptId])
}
model CommitLog {
id String @id @default(cuid())
attemptId String
values Json
/// Client sequence number for offline-synced commits; null for live commits.
seq Int?
/// When the client recorded the commit (offline sync), if it said so.
recordedAt DateTime?
createdAt DateTime @default(now())
attempt Attempt @relation(fields: [attemptId], references: [id], onDelete: Cascade)
@@index([attemptId])
@@index([createdAt])
}
/// An opt-in client-side event captured by the player for session replay
/// (tab hidden, idle, page navigation, media play, pointer position, or a
/// content-defined event). Commits already give the replay timeline its CMI
/// changes; these fill in what the learner did between commits.
model ReplayEvent {
id String @id @default(cuid())
tenantId String
attemptId String
/// Client-generated id, so a retried batch is stored once.
clientId String?
type String
/// Course location (slide / page) the learner was on, if known.
location String?
data Json @default("{}")
at DateTime
createdAt DateTime @default(now())
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
attempt Attempt @relation(fields: [attemptId], references: [id], onDelete: Cascade)
@@unique([attemptId, clientId])
@@index([attemptId, at])
@@index([tenantId])
}
/// A stored xAPI 1.0.3 statement. The authoritative document lives in `statement`
/// (JSON, exactly as the LRS returns it); the scalar columns alongside it are
/// denormalized copies of the fields the Statement query filters match on.
model XapiStatement {
tenantId String
statementId String
/// Canonical inverse-functional identifier for the actor, e.g. `mbox:mailto:a@b.c`.
actorIfi String
verbId String
/// `Activity` | `Agent` | `Group` | `StatementRef` | `SubStatement`.
objectType String
/// Activity IRI, actor IFI, or referenced statement id — whatever identifies the object.
objectId String?
registration String?
/// Every activity IRI the statement touches (object + context activities), for
/// `related_activities=true` queries.
relatedActivities String[]
/// Every actor IFI the statement touches (actor, object, instructor, team,
/// authority), for `related_agents=true` queries.
relatedAgents String[]
/// True once a `voided` statement has targeted this one. Voided statements are
/// excluded from normal queries but stay retrievable by id.
voided Boolean @default(false)
/// Set on a voiding statement: the id of the statement it voids.
voidsStatementId String?
statement Json
timestamp DateTime
stored DateTime @default(now())
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
@@id([tenantId, statementId])
@@index([tenantId, stored])
@@index([tenantId, actorIfi])
@@index([tenantId, verbId])
@@index([tenantId, objectId])
@@index([tenantId, registration])
@@index([tenantId, voidsStatementId])
}
/// An xAPI State API document, keyed by (activity, agent, registration, stateId).
/// `lookupKey` hashes that tuple so the unique index stays inside Postgres' btree
/// key limit even for long activity IRIs.
model XapiState {
id String @id @default(cuid())
tenantId String
lookupKey String
activityId String
agentIfi String
registration String?
stateId String
contentType String @default("application/json")
content Bytes
etag String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
@@unique([tenantId, lookupKey])
@@index([tenantId, activityId, agentIfi])
@@index([tenantId, updatedAt])
}
/// Which of the two Profile resources a document belongs to.
enum XapiProfileScope {
ACTIVITY
AGENT
}
/// An xAPI Activity Profile or Agent Profile document.
///
/// Both resources have identical document semantics and differ only in what
/// identifies the owner — an activity IRI or an agent IFI — so they share one
/// table with a `scope` discriminator. Exactly one of `activityId` / `agentIfi`
/// is set for any row. As with XapiState, `lookupKey` hashes the owning tuple so
/// the unique index stays inside Postgres' btree key limit.
model XapiProfile {
id String @id @default(cuid())
tenantId String
scope XapiProfileScope
lookupKey String
activityId String?
agentIfi String?
profileId String
contentType String @default("application/json")
content Bytes
etag String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
@@unique([tenantId, lookupKey])
@@index([tenantId, scope, activityId])
@@index([tenantId, scope, agentIfi])
@@index([tenantId, updatedAt])
}
/// A cmi5 course, imported from a `cmi5.xml` course structure. Kept apart from
/// `Course` because a cmi5 course is driven entirely through the LRS — it has no
/// SCORM runtime, CMI snapshot, or SCO launch semantics.
model Cmi5Course {
id String @id @default(cuid())
tenantId String
/// The course `id` from the course structure (the publisher's IRI).
publisherId String
/// LMS-generated activity IRI the engine uses as the object of course-level
/// statements (`satisfied`).
activityId String
title String
description String?
/// Storage prefix of the extracted package, or null for a structure-only
/// import whose AUs are all hosted elsewhere.
storageKey String?
/// Parsed course structure (blocks + AU ids), as returned by the parser.
structure Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
aus Cmi5Au[]
registrations Cmi5Registration[]
@@index([tenantId])
}
/// One Assignable Unit of a cmi5 course.
model Cmi5Au {
id String @id @default(cuid())
courseId String
/// The AU `id` from the course structure; sent as the `publisherid` grouping activity.
publisherId String
/// LMS-generated activity IRI — the `activityId` launch parameter and the
/// object of every cmi5 defined statement for this AU.
activityId String
title String
description String?
url String
/// `AnyWindow` | `OwnWindow`.
launchMethod String @default("AnyWindow")
/// `Passed` | `Completed` | `CompletedAndPassed` | `CompletedOrPassed` | `NotApplicable`.
moveOn String @default("NotApplicable")
masteryScore Float?
activityType String?
launchParameters String?
entitlementKey String?
order Int
course Cmi5Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
sessions Cmi5Session[]
@@unique([courseId, publisherId])
@@index([courseId])
}
/// A learner's enrolment in a cmi5 course. `id` is the xAPI `registration` UUID.
model Cmi5Registration {
id String @id
tenantId String
courseId String
actor Json
actorIfi String
/// Per-AU progress keyed by AU publisher id:
/// `{ completed, passed, failed, waived, satisfied }`.
auState Json @default("{}")
/// Blocks the learner has satisfied, keyed by block publisher id → ISO time
/// the engine recorded the block's `satisfied` statement.
blockState Json @default("{}")
satisfiedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
course Cmi5Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
sessions Cmi5Session[]
@@index([tenantId, courseId, actorIfi])
}
enum Cmi5SessionStatus {
LAUNCHED
INITIALIZED
TERMINATED
ABANDONED
}
/// One AU launch. `id` is the cmi5 `sessionid` context extension.
model Cmi5Session {
id String @id
tenantId String
registrationId String
auId String
/// `Normal` | `Browse` | `Review`.
launchMode String @default("Normal")
status Cmi5SessionStatus @default(LAUNCHED)
/// SHA-256 of the one-time secret embedded in the fetch URL.
fetchKeyHash String
fetchedAt DateTime?
expiresAt DateTime
launchedAt DateTime @default(now())
initializedAt DateTime?
endedAt DateTime?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
registration Cmi5Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
au Cmi5Au @relation(fields: [auId], references: [id], onDelete: Cascade)
@@index([registrationId, auId])
@@index([tenantId])
}
// ---------------------------------------------------------------------------
// Webhooks
// ---------------------------------------------------------------------------
/// A tenant-registered HTTPS receiver for engine events.
model WebhookEndpoint {
id String @id @default(cuid())
tenantId String
url String
description String?
/// Event types delivered to this endpoint; `*` subscribes to every event.
events String[]
/// HMAC-SHA256 signing secret (`whsec_…`). Kept retrievable: the engine
/// needs the plaintext to sign each delivery.
secret String
enabled Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
deliveries WebhookDelivery[]
@@index([tenantId])
}
enum WebhookDeliveryStatus {
/// Waiting for its first attempt or a retry at `nextAttemptAt`.
PENDING
SUCCEEDED
/// Out of retries — the dead-letter state. Requeue with the retry endpoint.
FAILED
}
/// One event bound for one endpoint, with its delivery history.
model WebhookDelivery {
id String @id @default(cuid())
tenantId String
endpointId String
/// Shared by every delivery of the same event, so receivers can dedupe.
eventId String
eventType String
/// The exact JSON body sent on every attempt.
payload Json
status WebhookDeliveryStatus @default(PENDING)
attempts Int @default(0)
/// When the next attempt is due. Also doubles as the claim lease while an
/// attempt is in flight, so concurrent workers never double-send.
nextAttemptAt DateTime?
lastAttemptAt DateTime?
lastStatusCode Int?
lastError String?
/// Start of the receiver's last response body, for the delivery log.
lastResponse String?
deliveredAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
endpoint WebhookEndpoint @relation(fields: [endpointId], references: [id], onDelete: Cascade)
@@index([status, nextAttemptAt])
@@index([endpointId, createdAt])
}
// ---------------------------------------------------------------------------
// AI analytics (bring your own provider + key)
// ---------------------------------------------------------------------------
/// A tenant's AI provider settings for one feature (`insights`, `summary`,
/// `recommendations`) or `default`, used by features without their own.
model AiProviderConfig {
id String @id @default(cuid())
tenantId String
feature String
/// openai | anthropic | gemini | mistral | ollama | openai_compatible | groq | together
/// | azure_openai | bedrock | custom_http
provider String
model String
baseUrl String?
/// The provider key, AES-256-GCM under a random data key (`v1.<iv>.<tag>.<ct>`).
encryptedKey String?
/// That data key, wrapped by the tenant key derived from AI_MASTER_KEY.
wrappedKey String?
/// Last four characters of the key, for display.
keyHint String?
redactPii Boolean @default(true)
/// Kill-switch: when false, calls are refused.
enabled Boolean @default(true)
/// Input + output tokens allowed per calendar month (UTC); null = unlimited.
monthlyTokenCap Int?
/// Fraction of the cap at which `ai.budget.alert` fires.
alertThreshold Float @default(0.8)
/// USD per million tokens, set by the tenant, for cost reporting.
inputCostPerMTok Float?
outputCostPerMTok Float?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
calls AiCallLog[]
@@unique([tenantId, feature])
}
/// Audit log of every AI call: what was asked of which provider, what it cost.
/// The prompt itself is not stored, only its SHA-256.
model AiCallLog {
id String @id @default(cuid())
tenantId String
configId String?
feature String
kind String
provider String
model String
courseId String?
/// succeeded | failed | blocked (over budget)
status String
promptHash String
inputTokens Int @default(0)
outputTokens Int @default(0)
costUsd Float?
redactions Int @default(0)
latencyMs Int @default(0)
error String?
createdAt DateTime @default(now())
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
config AiProviderConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
@@index([tenantId, createdAt])
@@index([configId, createdAt])
}
You can’t perform that action at this time.
