@marinoscar/platform-db 0.0.0-stage → 0.1.0-next.4

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 (244) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -2
  4. package/bin/platform.js +28 -0
  5. package/dist/baseline/deps.d.ts +32 -0
  6. package/dist/baseline/deps.d.ts.map +1 -0
  7. package/dist/baseline/deps.js +66 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +36 -0
  10. package/dist/baseline/errors.d.ts.map +1 -0
  11. package/dist/baseline/errors.js +23 -0
  12. package/dist/baseline/errors.js.map +1 -0
  13. package/dist/baseline/fs.d.ts +9 -0
  14. package/dist/baseline/fs.d.ts.map +1 -0
  15. package/dist/baseline/fs.js +39 -0
  16. package/dist/baseline/fs.js.map +1 -0
  17. package/dist/baseline/index.d.ts +8 -0
  18. package/dist/baseline/index.d.ts.map +1 -0
  19. package/dist/baseline/index.js +24 -0
  20. package/dist/baseline/index.js.map +1 -0
  21. package/dist/baseline/mapping.d.ts +43 -0
  22. package/dist/baseline/mapping.d.ts.map +1 -0
  23. package/dist/baseline/mapping.js +80 -0
  24. package/dist/baseline/mapping.js.map +1 -0
  25. package/dist/baseline/normalise.d.ts +42 -0
  26. package/dist/baseline/normalise.d.ts.map +1 -0
  27. package/dist/baseline/normalise.js +133 -0
  28. package/dist/baseline/normalise.js.map +1 -0
  29. package/dist/baseline/plan.d.ts +66 -0
  30. package/dist/baseline/plan.d.ts.map +1 -0
  31. package/dist/baseline/plan.js +105 -0
  32. package/dist/baseline/plan.js.map +1 -0
  33. package/dist/baseline/report.d.ts +127 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +89 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +117 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +358 -0
  40. package/dist/baseline/run.js.map +1 -0
  41. package/dist/bin/db-commands.d.ts +31 -0
  42. package/dist/bin/db-commands.d.ts.map +1 -0
  43. package/dist/bin/db-commands.js +311 -0
  44. package/dist/bin/db-commands.js.map +1 -0
  45. package/dist/bin/fs-io.d.ts +7 -0
  46. package/dist/bin/fs-io.d.ts.map +1 -0
  47. package/dist/bin/fs-io.js +45 -0
  48. package/dist/bin/fs-io.js.map +1 -0
  49. package/dist/bin/platform.d.ts +21 -0
  50. package/dist/bin/platform.d.ts.map +1 -0
  51. package/dist/bin/platform.js +99 -0
  52. package/dist/bin/platform.js.map +1 -0
  53. package/dist/compose/api.d.ts +84 -0
  54. package/dist/compose/api.d.ts.map +1 -0
  55. package/dist/compose/api.js +101 -0
  56. package/dist/compose/api.js.map +1 -0
  57. package/dist/compose/compose.d.ts +51 -0
  58. package/dist/compose/compose.d.ts.map +1 -0
  59. package/dist/compose/compose.js +177 -0
  60. package/dist/compose/compose.js.map +1 -0
  61. package/dist/compose/diff.d.ts +7 -0
  62. package/dist/compose/diff.d.ts.map +1 -0
  63. package/dist/compose/diff.js +68 -0
  64. package/dist/compose/diff.js.map +1 -0
  65. package/dist/compose/errors.d.ts +31 -0
  66. package/dist/compose/errors.d.ts.map +1 -0
  67. package/dist/compose/errors.js +35 -0
  68. package/dist/compose/errors.js.map +1 -0
  69. package/dist/compose/index.d.ts +3 -0
  70. package/dist/compose/index.d.ts.map +1 -0
  71. package/dist/compose/index.js +11 -0
  72. package/dist/compose/index.js.map +1 -0
  73. package/dist/compose/parse.d.ts +65 -0
  74. package/dist/compose/parse.d.ts.map +1 -0
  75. package/dist/compose/parse.js +122 -0
  76. package/dist/compose/parse.js.map +1 -0
  77. package/dist/drift/app-objects.d.ts +107 -0
  78. package/dist/drift/app-objects.d.ts.map +1 -0
  79. package/dist/drift/app-objects.js +193 -0
  80. package/dist/drift/app-objects.js.map +1 -0
  81. package/dist/drift/db-conformance.d.ts +52 -0
  82. package/dist/drift/db-conformance.d.ts.map +1 -0
  83. package/dist/drift/db-conformance.js +89 -0
  84. package/dist/drift/db-conformance.js.map +1 -0
  85. package/dist/drift/index.d.ts +8 -0
  86. package/dist/drift/index.d.ts.map +1 -0
  87. package/dist/drift/index.js +43 -0
  88. package/dist/drift/index.js.map +1 -0
  89. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  90. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-indexes.js +113 -0
  92. package/dist/drift/raw-sql-indexes.js.map +1 -0
  93. package/dist/drift/raw-sql-tripwire.d.ts +191 -0
  94. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  95. package/dist/drift/raw-sql-tripwire.js +422 -0
  96. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  97. package/dist/drift/rls-policies.d.ts +226 -0
  98. package/dist/drift/rls-policies.d.ts.map +1 -0
  99. package/dist/drift/rls-policies.js +317 -0
  100. package/dist/drift/rls-policies.js.map +1 -0
  101. package/dist/drift/run.d.ts +152 -0
  102. package/dist/drift/run.d.ts.map +1 -0
  103. package/dist/drift/run.js +252 -0
  104. package/dist/drift/run.js.map +1 -0
  105. package/dist/drift/sql-expression.d.ts +27 -0
  106. package/dist/drift/sql-expression.d.ts.map +1 -0
  107. package/dist/drift/sql-expression.js +64 -0
  108. package/dist/drift/sql-expression.js.map +1 -0
  109. package/dist/index.d.ts +16 -0
  110. package/dist/index.d.ts.map +1 -0
  111. package/dist/index.js +33 -0
  112. package/dist/index.js.map +1 -0
  113. package/dist/lock/hash.d.ts +13 -0
  114. package/dist/lock/hash.d.ts.map +1 -0
  115. package/dist/lock/hash.js +19 -0
  116. package/dist/lock/hash.js.map +1 -0
  117. package/dist/lock/index.d.ts +5 -0
  118. package/dist/lock/index.d.ts.map +1 -0
  119. package/dist/lock/index.js +20 -0
  120. package/dist/lock/index.js.map +1 -0
  121. package/dist/lock/lock.d.ts +154 -0
  122. package/dist/lock/lock.d.ts.map +1 -0
  123. package/dist/lock/lock.js +151 -0
  124. package/dist/lock/lock.js.map +1 -0
  125. package/dist/lock/manifest.d.ts +68 -0
  126. package/dist/lock/manifest.d.ts.map +1 -0
  127. package/dist/lock/manifest.js +96 -0
  128. package/dist/lock/manifest.js.map +1 -0
  129. package/dist/lock/semver.d.ts +10 -0
  130. package/dist/lock/semver.d.ts.map +1 -0
  131. package/dist/lock/semver.js +13 -0
  132. package/dist/lock/semver.js.map +1 -0
  133. package/dist/seed/index.d.ts +5 -0
  134. package/dist/seed/index.d.ts.map +1 -0
  135. package/dist/seed/index.js +16 -0
  136. package/dist/seed/index.js.map +1 -0
  137. package/dist/seed/input.d.ts +52 -0
  138. package/dist/seed/input.d.ts.map +1 -0
  139. package/dist/seed/input.js +77 -0
  140. package/dist/seed/input.js.map +1 -0
  141. package/dist/seed/seed-platform.d.ts +41 -0
  142. package/dist/seed/seed-platform.d.ts.map +1 -0
  143. package/dist/seed/seed-platform.js +165 -0
  144. package/dist/seed/seed-platform.js.map +1 -0
  145. package/dist/seed/steps.d.ts +172 -0
  146. package/dist/seed/steps.d.ts.map +1 -0
  147. package/dist/seed/steps.js +136 -0
  148. package/dist/seed/steps.js.map +1 -0
  149. package/dist/seed/types.d.ts +287 -0
  150. package/dist/seed/types.d.ts.map +1 -0
  151. package/dist/seed/types.js +5 -0
  152. package/dist/seed/types.js.map +1 -0
  153. package/dist/sync/app-migrations.d.ts +52 -0
  154. package/dist/sync/app-migrations.d.ts.map +1 -0
  155. package/dist/sync/app-migrations.js +62 -0
  156. package/dist/sync/app-migrations.js.map +1 -0
  157. package/dist/sync/apply.d.ts +29 -0
  158. package/dist/sync/apply.d.ts.map +1 -0
  159. package/dist/sync/apply.js +38 -0
  160. package/dist/sync/apply.js.map +1 -0
  161. package/dist/sync/check.d.ts +59 -0
  162. package/dist/sync/check.d.ts.map +1 -0
  163. package/dist/sync/check.js +115 -0
  164. package/dist/sync/check.js.map +1 -0
  165. package/dist/sync/errors.d.ts +32 -0
  166. package/dist/sync/errors.d.ts.map +1 -0
  167. package/dist/sync/errors.js +23 -0
  168. package/dist/sync/errors.js.map +1 -0
  169. package/dist/sync/index.d.ts +10 -0
  170. package/dist/sync/index.d.ts.map +1 -0
  171. package/dist/sync/index.js +27 -0
  172. package/dist/sync/index.js.map +1 -0
  173. package/dist/sync/ledger.d.ts +65 -0
  174. package/dist/sync/ledger.d.ts.map +1 -0
  175. package/dist/sync/ledger.js +49 -0
  176. package/dist/sync/ledger.js.map +1 -0
  177. package/dist/sync/plan.d.ts +63 -0
  178. package/dist/sync/plan.d.ts.map +1 -0
  179. package/dist/sync/plan.js +86 -0
  180. package/dist/sync/plan.js.map +1 -0
  181. package/dist/sync/promote.d.ts +62 -0
  182. package/dist/sync/promote.d.ts.map +1 -0
  183. package/dist/sync/promote.js +95 -0
  184. package/dist/sync/promote.js.map +1 -0
  185. package/dist/sync/timestamps.d.ts +41 -0
  186. package/dist/sync/timestamps.d.ts.map +1 -0
  187. package/dist/sync/timestamps.js +68 -0
  188. package/dist/sync/timestamps.js.map +1 -0
  189. package/dist/sync/version.d.ts +28 -0
  190. package/dist/sync/version.d.ts.map +1 -0
  191. package/dist/sync/version.js +66 -0
  192. package/dist/sync/version.js.map +1 -0
  193. package/migrations/0001_initial/migration.sql +297 -0
  194. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  195. package/migrations/0003_add_credentials/migration.sql +20 -0
  196. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  197. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  198. package/migrations/0006_add_notifications/migration.sql +22 -0
  199. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  200. package/migrations/0008_add_jobs/migration.sql +110 -0
  201. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  202. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  203. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  204. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  205. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  206. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  207. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  208. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  209. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  210. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  211. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  212. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  213. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  214. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  215. package/migrations/0023_add_organizations/migration.sql +142 -0
  216. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  217. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  218. package/migrations/0026_add_groups/migration.sql +165 -0
  219. package/migrations/0027_add_grants/migration.sql +117 -0
  220. package/migrations/0028_add_org_settings/migration.sql +49 -0
  221. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  222. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  223. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  224. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  225. package/migrations/0033_add_android_app/migration.sql +60 -0
  226. package/migrations/0034_open_job_reason/migration.sql +16 -0
  227. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  228. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  229. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  230. package/migrations/manifest.json +379 -0
  231. package/package.json +78 -4
  232. package/raw-sql-indexes.json +94 -0
  233. package/rls-policies.json +74 -0
  234. package/schema/ai.prisma +444 -0
  235. package/schema/android-app.prisma +47 -0
  236. package/schema/base.prisma +11 -0
  237. package/schema/credentials.prisma +170 -0
  238. package/schema/db-backup.prisma +376 -0
  239. package/schema/identity.prisma +439 -0
  240. package/schema/jobs.prisma +760 -0
  241. package/schema/notifications.prisma +649 -0
  242. package/schema/settings.prisma +60 -0
  243. package/schema/sharing.prisma +223 -0
  244. package/schema/storage.prisma +84 -0
@@ -0,0 +1,649 @@
1
+ // =============================================================================
2
+ // Notification Deliveries (issue #125, epic #109)
3
+ // =============================================================================
4
+ //
5
+ // One row per delivery ATTEMPT of an event (#121, `notification-events.ts`)
6
+ // over a channel, to a recipient. This is the answer to "did the user
7
+ // actually get it?" — the first question asked when something goes wrong,
8
+ // and epic #109's own success criterion 7: a delivery record exists for
9
+ // every attempt, with the provider's message id or error.
10
+ //
11
+ // -----------------------------------------------------------------------------
12
+ // eventKey — plain string, NOT a foreign key
13
+ // -----------------------------------------------------------------------------
14
+ // Events are declared in code (`notification-events.ts`, #121), not in a
15
+ // database table — `findEvent()` there returns `undefined` rather than
16
+ // throwing for a key it doesn't recognize, precisely because callers may be
17
+ // holding a key that came from persisted data written before the event was
18
+ // renamed or removed. An FK into an "events" table would force a migration
19
+ // (and a backfill, or a placeholder row) every time the registry changes,
20
+ // which is exactly the coupling #121 built the registry to avoid. A delivery
21
+ // record must outlive the event definition that produced it.
22
+ //
23
+ // -----------------------------------------------------------------------------
24
+ // channel — ALSO a plain string, not a Prisma enum (deliberately asymmetric
25
+ // with `status` below)
26
+ // -----------------------------------------------------------------------------
27
+ // `NotificationChannel` in `notification-events.ts` is explicitly derived
28
+ // from a plain array (`NOTIFICATION_CHANNELS`) so that adding `'push'` later
29
+ // (epic #109 reserves it) costs one edit to that array, not a migration. A
30
+ // Postgres enum on this column would quietly reintroduce that migration: the
31
+ // set of valid channels would live in two places — the code registry and
32
+ // this column's type — and adding one would require updating both. The
33
+ // registry is the single source of truth for what channels exist; this
34
+ // column just records which one a given attempt used.
35
+ //
36
+ // -----------------------------------------------------------------------------
37
+ // status — IS a Prisma enum
38
+ // -----------------------------------------------------------------------------
39
+ // Unlike eventKey/channel, `status` is not registry data — it is this
40
+ // table's own delivery state machine, owned entirely by the dispatcher, and
41
+ // nothing outside this table grows it. It follows the convention this schema
42
+ // already uses for exactly this shape of field (`DeviceCodeStatus`,
43
+ // `StorageObjectStatus`): a small, closed, code-owned set of states is a
44
+ // Postgres enum here, so the database itself rejects a delivery row written
45
+ // with anything other than queued/sent/failed.
46
+ //
47
+ // -----------------------------------------------------------------------------
48
+ // userId — nullable; recipient — the actual destination used
49
+ // -----------------------------------------------------------------------------
50
+ // `allowlist.invitation` (#121) is sent to an email address with no user
51
+ // account yet (#128) — there is no user row to point to, so `userId` must be
52
+ // nullable. `recipient` is what makes that case complete: it is the actual
53
+ // destination address used for THIS delivery, captured independently of the
54
+ // user relation, so the record stands on its own with `userId` null, and
55
+ // stays historically accurate even if the user's email later changes.
56
+ //
57
+ // -----------------------------------------------------------------------------
58
+ // onDelete: SetNull on the user relation
59
+ // -----------------------------------------------------------------------------
60
+ // Matches the audit-trail precedent this schema already sets for
61
+ // `AuditEvent.actorUserId` and `Credential.updatedByUser`: a delivery record
62
+ // is a history of what the application sent, and deleting a user account
63
+ // should not retroactively erase the evidence of what was sent to them —
64
+ // particularly for `security.*` events (#121), which are exactly the ones an
65
+ // incident review is most likely to need after the account in question no
66
+ // longer exists. Nothing is lost by nulling the FK: `recipient` already
67
+ // carries the actual destination independently of it. A GDPR-style request
68
+ // to purge one user's PII is a deliberate, targeted scrub of these rows (and
69
+ // `recipient` specifically) — not something an ON DELETE clause should do
70
+ // silently and irreversibly as a side effect of an unrelated user-deletion
71
+ // path elsewhere in the app.
72
+ //
73
+ // -----------------------------------------------------------------------------
74
+ // Indexes — exactly the two queries this table is known to serve
75
+ // -----------------------------------------------------------------------------
76
+ // Every index is a write cost on a table that grows with every notification
77
+ // sent, so nothing speculative is added beyond what #125 itself names:
78
+ // - [userId, eventKey]: "did this user get this event?" — an equality
79
+ // filter on both columns, from an account's delivery history view.
80
+ // - [status, createdAt]: "what failed recently?" — status = 'failed'
81
+ // filtered and ordered by recency, for on-call triage.
82
+ // @extensible — back-relations only, added with "extend model NotificationDelivery { ... }" in a
83
+ // fragment (an app's own delivery annotations, for example a provider-specific receipt).
84
+ // The delivery ledger itself (status, error, provider id) stays the platform's.
85
+ model NotificationDelivery {
86
+ id String @id @default(uuid()) @db.Uuid
87
+ eventKey String @map("event_key")
88
+ userId String? @map("user_id") @db.Uuid
89
+ recipient String
90
+ channel String
91
+ status NotificationDeliveryStatus @default(queued)
92
+ providerMessageId String? @map("provider_message_id")
93
+ // Provider errors (SMTP rejections, SES API errors, ...) have no useful
94
+ // length bound — @db.Text, same reasoning as Credential.secret above.
95
+ error String? @db.Text
96
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
97
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
98
+
99
+ // Relations
100
+ user User? @relation("UserNotificationDeliveries", fields: [userId], references: [id], onDelete: SetNull)
101
+
102
+ @@index([userId, eventKey])
103
+ @@index([status, createdAt])
104
+ // The retention sweep (`notifications.deliveries.purge`, #681): "oldest
105
+ // first, older than the cutoff", which the status-leading index above
106
+ // serves only one status at a time.
107
+ @@index([createdAt])
108
+ @@map("notification_deliveries")
109
+ }
110
+
111
+ enum NotificationDeliveryStatus {
112
+ queued
113
+ sent
114
+ failed
115
+ }
116
+
117
+ // =============================================================================
118
+ // Notifications — the in-app notification centre store (issue #127, epic #109)
119
+ // =============================================================================
120
+ //
121
+ // THE PRIMARY SURFACE OF THE BROWSER CHANNEL, NOT A CACHE OF WHAT SSE SENT.
122
+ //
123
+ // That ordering is the whole reason this table exists. `Notification`
124
+ // permission is denied by a large share of users, and once denied it is
125
+ // effectively permanent — the page cannot re-prompt. A browser channel that
126
+ // existed only as an OS toast would therefore not exist at all for those
127
+ // accounts. So the durable, per-user list is the feature; the SSE stream
128
+ // (`notification-stream.service.ts`) makes it live, and the native toast is a
129
+ // decoration on top that degrades to nothing.
130
+ //
131
+ // Read the second consequence too: SSE IS NOT A DELIVERY GUARANTEE. Events
132
+ // published while a tab is disconnected are lost — `EventSource` reconnects
133
+ // but replays nothing, and the per-process subscriber registry does not fan
134
+ // out across replicas. Because rows land here first and the stream is
135
+ // published second, a client that refetches this table on (re)connect sees
136
+ // everything regardless. That is the designed recovery path, and it is why
137
+ // there is no event-replay machinery anywhere in #127.
138
+ //
139
+ // -----------------------------------------------------------------------------
140
+ // HOW THIS DIFFERS FROM `notification_deliveries` (#125), WHICH IS NOT THE SAME
141
+ // TABLE WITH A DIFFERENT NAME
142
+ // -----------------------------------------------------------------------------
143
+ //
144
+ // `notification_deliveries` is the OPERATOR's record: one row per ATTEMPT, per
145
+ // channel, answering "did we try, and what did the provider say?". It records
146
+ // email attempts too, it keeps rows for recipients with no account, and it is
147
+ // never shown to the user it is about.
148
+ //
149
+ // `notifications` is the USER's inbox: one row per thing they should see, only
150
+ // for the browser channel, only for real accounts, with read state they own.
151
+ // An email send writes a delivery row and no row here — there is nothing for
152
+ // the bell to show about a message that went to their mailbox.
153
+ //
154
+ // Merging the two would mean either showing users provider error strings, or
155
+ // filtering an operator table by channel on every bell render. They answer
156
+ // different questions for different audiences and are kept apart.
157
+ // =============================================================================
158
+
159
+ // @extensible — back-relations only, added with "extend model Notification { ... }" in a
160
+ // fragment (an app's own side table keyed by a notification, for example a per-notification
161
+ // follow-up). A user-owned row: the table has no organization column, so a plain foreign
162
+ // key on `id` is the right shape. `onDelete: Cascade` on the app side keeps the retention
163
+ // sweep (`notifications.inbox.purge`) working.
164
+ model Notification {
165
+ id String @id @default(uuid()) @db.Uuid
166
+ // NOT NULL, unlike NotificationDelivery.userId. An inbox belongs to an
167
+ // account by definition; there is no "notification centre" for a recipient
168
+ // with no login (#128's `allowlist.invitation` case), which is exactly why
169
+ // the browser channel's resolveTo returns null for them.
170
+ userId String @map("user_id") @db.Uuid
171
+
172
+ // Plain string, NOT a foreign key — the same reasoning written out at length
173
+ // on NotificationDelivery.eventKey. Events are declared in code
174
+ // (`notification-events.ts`, #121) and `findEvent` returns undefined rather
175
+ // than throwing precisely because persisted rows outlive their definitions.
176
+ // An FK would force a migration every time the registry changed.
177
+ eventKey String @map("event_key")
178
+
179
+ // RENDERED AT WRITE TIME, not at read time. The alternative — store the
180
+ // event payload as JSONB and render in the bell — means an old row renders
181
+ // through today's template, so editing copy silently rewrites history and a
182
+ // removed event's rows become unrenderable. What the user was told is a
183
+ // fact; it is frozen here.
184
+ title String
185
+ // @db.Text for the same reason as Credential.secret and
186
+ // NotificationDelivery.error: a rendered body has no meaningful length
187
+ // bound, and silently truncating what a user was told is worse than storing
188
+ // a long string. (Postgres `text` has no performance penalty over `varchar`.)
189
+ body String @db.Text
190
+
191
+ // Where the bell should send the user, as a ROOT-RELATIVE PATH ("/settings",
192
+ // "/admin/users?id=…"), never an absolute URL.
193
+ //
194
+ // THIS IS A SECURITY BOUNDARY, ENFORCED IN CODE AT WRITE TIME
195
+ // (`browser-notification.channel.ts`). The web client will put this value in
196
+ // an href or a router navigation; an absolute URL makes every notification a
197
+ // potential open redirect, and a `javascript:` scheme makes it script
198
+ // execution in the app's own origin. The column cannot express that
199
+ // constraint, so the writer enforces it and drops a link it cannot vouch
200
+ // for rather than storing it and hoping the client is careful.
201
+ //
202
+ // Nullable: most notifications have nowhere specific to go.
203
+ link String?
204
+
205
+ // A TIMESTAMP, NOT A BOOLEAN. `readAt IS NULL` answers "is it unread?" just
206
+ // as well as `read = false` does, and additionally answers "when did they
207
+ // see it?" — which is the question asked when someone reports acting late on
208
+ // a security alert. A boolean would have to grow this column later anyway.
209
+ readAt DateTime? @map("read_at") @db.Timestamptz
210
+
211
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
212
+
213
+ // NO `updatedAt`. The only mutation this row ever undergoes is being marked
214
+ // read, and `readAt` already timestamps that with more precision than an
215
+ // `updatedAt` would carry. A second, redundant answer to "when did this
216
+ // change?" is a second thing to keep consistent for no reader.
217
+
218
+ // Relations
219
+ //
220
+ // onDelete: Cascade — deliberately the OPPOSITE of
221
+ // NotificationDelivery.user's SetNull, and the contrast is the point. A
222
+ // delivery record is an audit trail that must outlive the account it
223
+ // describes ("did we email this person before they were offboarded?"). An
224
+ // inbox is personal data with no reader once the account is gone: keeping
225
+ // orphaned rows would retain rendered titles and bodies about a deleted user
226
+ // forever, and `userId` is NOT NULL here so SetNull is not even expressible.
227
+ user User @relation("UserNotifications", fields: [userId], references: [id], onDelete: Cascade)
228
+
229
+ // The two queries this table actually serves, and nothing speculative.
230
+ //
231
+ // 1. THE UNREAD BADGE: `where { userId, readAt: null }`, run on every bell
232
+ // render and on every SSE (re)connect — by far the hottest query here.
233
+ // (Ideally a partial index `WHERE read_at IS NULL`, which Prisma cannot
234
+ // express declaratively; the composite covers the same predicate and
235
+ // stays in one place the schema owns.)
236
+ @@index([userId, readAt])
237
+ // 2. THE RECENT LIST: `where { userId } orderBy { createdAt: desc }`.
238
+ // `sort: Desc` matters — a plain ascending index makes Postgres walk it
239
+ // backwards for the newest page, which is the only page anyone loads.
240
+ @@index([userId, createdAt(sort: Desc)])
241
+ // The retention sweep (`notifications.inbox.purge`, #681): "oldest first,
242
+ // older than the cutoff" across every user, which neither index above serves.
243
+ @@index([createdAt])
244
+ @@map("notifications")
245
+ }
246
+
247
+ // =============================================================================
248
+ // Push Subscriptions (issue #229, epic #215)
249
+ // =============================================================================
250
+ //
251
+ // Storage for the browser's `PushSubscription` object — the endpoint URL plus
252
+ // the two keys (`p256dh`, `auth`) needed to encrypt a Web Push payload to that
253
+ // specific device — so the server has something to sign and send to when a
254
+ // notification's `browser` channel wants to reach a tab that isn't open.
255
+ //
256
+ // THIS SHIPS DISABLED BY DEFAULT (per #215). This table, and the endpoints the
257
+ // next pass builds on top of it, exist regardless; what makes push actually
258
+ // fire is a downstream deployment setting `VAPID_PUBLIC_KEY` /
259
+ // `VAPID_PRIVATE_KEY` in its own environment. A repo that never sets those
260
+ // vars has this table sitting empty and unused — generating keys, not writing
261
+ // code, is the enable step. Nothing here should ever require a schema change
262
+ // to turn push on.
263
+ //
264
+ // -----------------------------------------------------------------------------
265
+ // endpoint — @unique, not part of a composite key with userId
266
+ // -----------------------------------------------------------------------------
267
+ // The endpoint URL (assigned by the browser's push service — FCM, Mozilla's
268
+ // autopush, ...) already uniquely identifies one subscribed device/browser
269
+ // instance; it cannot simultaneously be valid for two different users. Making
270
+ // it @unique on its own, rather than @@unique([userId, endpoint]), is what
271
+ // lets the service layer `upsert` on `endpoint` alone (#229's acceptance
272
+ // criterion: "Re-subscribing the same endpoint upserts instead of creating a
273
+ // duplicate row") — including the case where the same browser subscription
274
+ // re-registers under a different signed-in user, which should move the row,
275
+ // not fork it.
276
+ //
277
+ // -----------------------------------------------------------------------------
278
+ // userId — onDelete: Cascade, the OPPOSITE of NotificationDelivery.user's
279
+ // SetNull right above, and deliberately so
280
+ // -----------------------------------------------------------------------------
281
+ // NotificationDelivery keeps its user relation nullable-with-SetNull because a
282
+ // delivery row is an audit trail with standalone value ("did we send this
283
+ // before the account was offboarded?") even once the account is gone — it
284
+ // carries its own `recipient` and stands on its own. A push subscription has
285
+ // no such standalone meaning: it is nothing but a live credential for pushing
286
+ // to one specific person's device. Once that person's account is deleted
287
+ // there is no one left to authorize a push, no one left to act on it, and no
288
+ // audit value in keeping an endpoint + key material around — it is simply
289
+ // dead. Cascade is correct here for the same reason `Notification.user` above
290
+ // is Cascade rather than SetNull: this is live, personal state with no reader
291
+ // once the account is gone, not history.
292
+ //
293
+ // -----------------------------------------------------------------------------
294
+ // failureCount / lastSuccessAt — written by #230, columns exist now
295
+ // -----------------------------------------------------------------------------
296
+ // Web Push endpoints go stale silently (uninstalled browser, revoked
297
+ // permission, expired subscription) and the push service reports this as a
298
+ // 404/410 (gone) or persistent 429/5xx on send, never as an explicit
299
+ // unsubscribe call. `failureCount` is incremented by the not-yet-built sender
300
+ // (#230) on each such failure so a pruning job can drop subscriptions that
301
+ // have stopped working, and `lastSuccessAt` is its complement — updated on
302
+ // every successful send — so "why did this stop working" has an answer
303
+ // (compare `failureCount`'s growth against how long ago `lastSuccessAt` was)
304
+ // without needing delivery-log archaeology. Neither column is written by
305
+ // anything in this migration; they exist now so #230 needs no schema change.
306
+ model PushSubscription {
307
+ id String @id @default(uuid()) @db.Uuid
308
+
309
+ userId String @map("user_id") @db.Uuid
310
+
311
+ // The push service URL the browser gave us (e.g.
312
+ // `https://fcm.googleapis.com/fcm/send/...`). @unique — see block comment
313
+ // above for why this, not a composite key, is what the upsert relies on.
314
+ endpoint String @unique
315
+
316
+ // The two halves of the browser's subscription keys
317
+ // (`PushSubscription.getKey('p256dh'|'auth')`, base64url-encoded), together
318
+ // sufficient to encrypt a payload to this device per the Web Push
319
+ // encryption spec (RFC 8291). Neither is secret in the same sense as
320
+ // `Credential.secret` — they are meaningless without also knowing the
321
+ // corresponding endpoint and the server's VAPID private key — so they are
322
+ // stored plain, matching how every Web Push library (including `web-push`,
323
+ // which the next pass will use) expects to read them back out.
324
+ p256dh String
325
+ auth String
326
+
327
+ // From the browser's `PushSubscription.expirationTime`, when the push
328
+ // service supplies one (most don't). Nullable because absence is the
329
+ // common case, not an error.
330
+ expirationTime DateTime? @map("expiration_time") @db.Timestamptz
331
+
332
+ // For diagnosing "why did this stop working" alongside failureCount/
333
+ // lastSuccessAt below. Nullable: not always available, and never required.
334
+ userAgent String? @map("user_agent")
335
+
336
+ // Incremented by #230's sender on delivery failure (429/5xx from the push
337
+ // service); read by its not-yet-built pruning logic to drop dead
338
+ // subscriptions. Starts at 0 and is reset to 0 on the next successful send.
339
+ failureCount Int @default(0) @map("failure_count")
340
+
341
+ // Updated on every successful send by #230. Nullable: a freshly created
342
+ // subscription has never had one.
343
+ lastSuccessAt DateTime? @map("last_success_at") @db.Timestamptz
344
+
345
+ // Which surface registered this subscription (#746, PP-9.4; harvested from
346
+ // EvoPath #312): `browser` (a browser tab or installed PWA) or `android_app`
347
+ // (the Android companion's Trusted Web Activity). The `android_app`
348
+ // notification channel pushes to these rows alone; `push` keeps meaning
349
+ // every subscription. A re-post of the same endpoint as `android_app`
350
+ // re-tags a `browser` row, a `browser` re-post never downgrades an
351
+ // `android_app` row (push-subscription.service.ts). The CHECK constraint
352
+ // `push_subscriptions_platform_check` lives in the migration SQL only
353
+ // (Prisma cannot express one; see PUSH_SUBSCRIPTION_PLATFORMS in the
354
+ // notifications contract).
355
+ platform String @default("browser")
356
+
357
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
358
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
359
+
360
+ // Relations
361
+ //
362
+ // onDelete: Cascade — see block comment above for why this reverses the
363
+ // SetNull precedent set by NotificationDelivery.user just above.
364
+ user User @relation("UserPushSubscriptions", fields: [userId], references: [id], onDelete: Cascade)
365
+
366
+ // The one query this table is known to serve: "give me this user's
367
+ // subscriptions to push to" (#229's subscribe/unsubscribe endpoints and
368
+ // #230's send fan-out both key off userId; endpoint's own @unique index
369
+ // already covers lookup/upsert by endpoint).
370
+ @@index([userId])
371
+ @@map("push_subscriptions")
372
+ }
373
+
374
+ // =============================================================================
375
+ // Notification Broadcasts (issue #320, epic #319)
376
+ // =============================================================================
377
+ //
378
+ // One row per admin-composed message announced to every user in the
379
+ // deployment — "we're doing maintenance Saturday", "new feature shipped" —
380
+ // scheduled, sent (or canceled), and never re-editable once it has started.
381
+ // This issue is schema only: the compose/schedule/cancel endpoints, the job
382
+ // handler that actually fans a broadcast out over `notify()`, and the admin
383
+ // UI all arrive in later issues of #319. What is here is the row a later
384
+ // issue's job reads from and writes progress back to.
385
+ //
386
+ // -----------------------------------------------------------------------------
387
+ // WHY A TABLE AT ALL — REJECTED: living entirely inside `Job.payload`
388
+ // -----------------------------------------------------------------------------
389
+ // The obvious shortcut is to skip this table and let a broadcast be nothing
390
+ // but the `payload` JSON of a `'broadcast.send'` job (#255 already gives
391
+ // every job a JSONB payload for free). Two things rule that out:
392
+ //
393
+ // - Job history is pruned INDEPENDENTLY of this table's business value.
394
+ // `job-history-purge` (#263) deletes old `jobs` rows on a retention
395
+ // schedule that exists to keep the QUEUE small, not to preserve what an
396
+ // admin once announced. A broadcast composed ninety days ago is still
397
+ // something "what did we tell our users, and when" needs to answer long
398
+ // after the job that sent it has aged out — living only in `payload`
399
+ // means that answer silently disappears on a retention sweep nobody
400
+ // doing the asking even knows runs.
401
+ // - The admin broadcast list page (a later issue in #319) would be
402
+ // QUERYING THE QUEUE FOR BUSINESS DATA — filtering and paging `jobs` by a
403
+ // `type` string and reading business fields back out of an opaque JSONB
404
+ // blob never meant to be a list-page's row shape. `jobs` is
405
+ // infrastructure for background work in general; a broadcast is a
406
+ // first-class thing the product has, with its own status, its own
407
+ // progress counters, and its own list page. It gets its own table for the
408
+ // same reason `notifications` (#127) is not "SSE events kept in a JSONB
409
+ // column somewhere" — the durable record IS the feature, not a
410
+ // side-effect of how the delivery mechanism happens to be implemented.
411
+ //
412
+ // A `'broadcast.send'` job still exists and still references one of these
413
+ // rows (by id, in its `payload`) to actually run the fan-out — this table is
414
+ // not a replacement for the queue, only for using the queue's own history as
415
+ // the system of record.
416
+ //
417
+ // -----------------------------------------------------------------------------
418
+ // channels — String[], not a Prisma enum
419
+ // -----------------------------------------------------------------------------
420
+ // Mirrors `NotificationDelivery.channel`'s deliberate plain-string choice
421
+ // (see that column's own block comment above), one level up: a broadcast can
422
+ // target more than one channel at once, so this is `channels String[]`
423
+ // rather than a single string, but the "why not an enum" reasoning is
424
+ // identical. `NOTIFICATION_CHANNELS` (`notification-events.ts`) is a
425
+ // code-owned, growing array specifically so adding `'push'`-style channels
426
+ // later costs one edit to that array. A Postgres enum on this column would
427
+ // reintroduce exactly the migration that array exists to avoid, and would
428
+ // leave the set of valid channels living in two places that could disagree.
429
+ //
430
+ // -----------------------------------------------------------------------------
431
+ // title / body — composed and frozen at write time, not templated at read
432
+ // time
433
+ // -----------------------------------------------------------------------------
434
+ // Same contract as `Notification.title`/`.body` (#127): what an admin typed
435
+ // (or the compose form rendered from it) is a fact about what was announced,
436
+ // stored as that fact, not as a template reference re-rendered later. The
437
+ // alternative — store a template key plus a data blob and render in the
438
+ // list page — means editing copy elsewhere in the app silently rewrites what
439
+ // this broadcast is remembered as having said, and a broadcast survives any
440
+ // future rename or removal of whatever generated its text.
441
+ //
442
+ // -----------------------------------------------------------------------------
443
+ // status — `NotificationBroadcastStatus`, matching `NotificationDeliveryStatus`'s
444
+ // naming, and carrying one member NOTHING IN THIS EPIC CAN REACH YET
445
+ // -----------------------------------------------------------------------------
446
+ // The enum is prefixed `NotificationBroadcast…` rather than plain
447
+ // `BroadcastStatus` to match the existing `NotificationDeliveryStatus`
448
+ // naming convention on the sibling tables in this section, rather than
449
+ // inventing a shorter name unique to this model.
450
+ //
451
+ // `draft` IS NOT REACHABLE BY ANY ROUTE #319 BUILDS. No compose endpoint in
452
+ // this epic writes a row with that status, and no later issue's handler
453
+ // reads one. It is here anyway, on purpose, because adding a value to a
454
+ // Postgres enum type is a migration, and `ALTER TYPE ... ADD VALUE` cannot
455
+ // run inside the same transaction Prisma wraps a migration in (Postgres
456
+ // forbids using a freshly added enum value in the transaction that added
457
+ // it). A future "save and finish composing later" feature is a one-line
458
+ // product ask that would otherwise cost a migration on a table with live
459
+ // data; paying for the enum slot now, while it is free, buys that escape
460
+ // hatch later for nothing. DO NOT DELETE `draft` AS "unused" — it is
461
+ // deliberately dead code, not leftover code.
462
+ //
463
+ // -----------------------------------------------------------------------------
464
+ // cursorUserId / audienceCutoff — the resume point AND the frozen audience
465
+ // for a chunked, cursor-resumable fan-out
466
+ // -----------------------------------------------------------------------------
467
+ // A broadcast fans out to every user in the deployment, which can be far
468
+ // more than one job execution should hold open in a single transaction or a
469
+ // single lease window. #323's handler processes users in chunks and, after
470
+ // each chunk commits, writes that chunk's last id to `cursorUserId` so a
471
+ // retried or resumed run picks up exactly where the previous attempt left
472
+ // off instead of restarting from user zero (or, worse, re-sending to
473
+ // everyone already done).
474
+ //
475
+ // `audienceCutoff` IS THE MOST IMPORTANT FIELD ON THIS MODEL, because a
476
+ // cursor alone does not define a stable audience to page through — it only
477
+ // defines a position. Stamped ONCE, when the fan-out starts (`status` moves
478
+ // to `sending`), it is the timestamp every chunk's query filters
479
+ // `users.createdAt` against (`createdAt <= audienceCutoff`), combined with
480
+ // `WHERE id > cursorUserId ORDER BY id ASC` for the page itself. That
481
+ // combination buys two things at once, with no new index on `users`:
482
+ //
483
+ // - A FROZEN AUDIENCE. Without a cutoff, a fan-out that takes long enough
484
+ // for new signups to land mid-run would keep discovering new rows to
485
+ // page through — the query keeps changing under it. A broadcast could
486
+ // then fail to terminate under sustained signups, or (worse) a user who
487
+ // signed up during the run could receive it depending on exactly when
488
+ // their row was inserted relative to the currently-processing chunk.
489
+ // Freezing the boundary at start time makes the set of eligible users
490
+ // fixed the moment sending begins.
491
+ // - A REPLAYABLE "WHO GOT THIS" QUERY. `users.id ASC` is the only
492
+ // ordering that is both STABLE and TOTAL — the primary key never
493
+ // changes for a row and no two rows share a value — so re-running
494
+ // `WHERE createdAt <= audienceCutoff ORDER BY id ASC` after the fact
495
+ // reproduces the exact same page sequence the fan-out actually walked,
496
+ // which `cursorUserId` alone (paging on a column with no recorded
497
+ // boundary) cannot promise once the run has finished. `createdAt` is
498
+ // deliberately NOT used as the paging column for this same reason in
499
+ // reverse: two users can share a timestamp (a bulk import, an unlucky
500
+ // race), and a page boundary drawn on a non-unique column can silently
501
+ // skip or repeat a user at that boundary.
502
+ //
503
+ // This defines two windows precisely, and both are intentional, not edge
504
+ // cases to patch later:
505
+ // - A user created between the broadcast's `createdAt` (composed/
506
+ // scheduled) and `startedAt` (fan-out begins) IS INCLUDED — the rule
507
+ // this model implements is "everyone who exists once sending starts",
508
+ // not "everyone who existed when an admin clicked compose".
509
+ // - A user created between `startedAt` and the run's last chunk is
510
+ // EXCLUDED — they signed up after the audience was frozen, and by
511
+ // definition are not behind the cursor a resumed run would recheck.
512
+ //
513
+ // -----------------------------------------------------------------------------
514
+ // createdById — onDelete: SetNull (and the one-line cost of adding this FK)
515
+ // -----------------------------------------------------------------------------
516
+ // Same reasoning as `AuditEvent.actorUserId` (and `NotificationDelivery
517
+ // .user`, and `Credential.updatedByUser`): this column is an audit trail,
518
+ // not a live reference. Deleting the admin who composed a broadcast must not
519
+ // delete the record of what they announced to every user in the deployment
520
+ // — if anything, that is exactly the record an incident review is most
521
+ // likely to need after the admin account in question no longer exists.
522
+ // Nothing about the broadcast's own meaning depends on the admin row still
523
+ // existing, so the FK is nulled, never cascaded. Worth naming plainly: adding
524
+ // a foreign key to `users` takes a brief `ACCESS SHARE`-class lock on that
525
+ // table while the constraint is validated. At this schema's scale that is
526
+ // not something an operator needs to plan a maintenance window around, but
527
+ // it is a real, if trivial, cost of this migration and not a free action.
528
+ //
529
+ // -----------------------------------------------------------------------------
530
+ // Indexes — exactly the two queries this table is known to serve
531
+ // -----------------------------------------------------------------------------
532
+ // - [status, scheduledFor]: "WHAT IS PENDING" — the scheduler's own query,
533
+ // equality on `status = 'scheduled'` ordered/filtered by `scheduledFor`,
534
+ // for finding due broadcasts to start and upcoming ones to display.
535
+ // - [createdAt desc]: the admin list page's default order, "most recently
536
+ // composed first" — same reasoning as `Job`'s and `Notification`'s own
537
+ // `createdAt(sort: Desc)` indexes, for the same reason: a plain ascending
538
+ // index makes Postgres walk it backwards for the only page anyone loads.
539
+ //
540
+ // -----------------------------------------------------------------------------
541
+ // REJECTED: a `notification_broadcast_recipients` join table
542
+ // -----------------------------------------------------------------------------
543
+ // The exact-tracking alternative — one row per (broadcast, user) pair,
544
+ // recording per-recipient delivery outcome the way `notification_deliveries`
545
+ // does per (event, user) — was considered and rejected for this issue. It is
546
+ // UNBOUNDED GROWTH keyed to the size of the user base on every single
547
+ // broadcast sent (a deployment with 50,000 users sending one broadcast a
548
+ // week is 2.6 million new rows a year for that feature alone), for a
549
+ // marginal gain over what `cursorUserId`/`audienceCutoff` plus the two
550
+ // counters below already give: the queue's own at-least-once contract (see
551
+ // `JobHandler`'s own block comment) already bounds a replay to AT MOST ONE
552
+ // CHUNK — the fan-out resumes from the last committed cursor, so
553
+ // re-processing is inherently limited to users near the boundary, not the
554
+ // whole broadcast. `recipientsTargeted`/`recipientsDispatched` answer "how
555
+ // many were meant to get this, how many did we attempt" at the aggregate
556
+ // level a broadcast's own admin view actually needs; per-recipient
557
+ // per-channel success/failure already lives in `notification_deliveries` —
558
+ // this table must not become a second, weaker copy of that record — and
559
+ // per-recipient READ-RECEIPT tracking is a different, much heavier feature
560
+ // that nothing in #319 asks for.
561
+ // =============================================================================
562
+
563
+ model NotificationBroadcast {
564
+ id String @id @default(uuid()) @db.Uuid
565
+ title String
566
+ body String @db.Text
567
+ link String?
568
+ ctaLabel String? @map("cta_label")
569
+ eventKey String @map("event_key")
570
+ channels String[]
571
+
572
+ status NotificationBroadcastStatus @default(scheduled)
573
+
574
+ scheduledFor DateTime? @map("scheduled_for") @db.Timestamptz
575
+ startedAt DateTime? @map("started_at") @db.Timestamptz
576
+ finishedAt DateTime? @map("finished_at") @db.Timestamptz
577
+ canceledAt DateTime? @map("canceled_at") @db.Timestamptz
578
+
579
+ // The frozen audience boundary and the paging cursor into it — see the
580
+ // block comment above for the full mechanism; the two are read together.
581
+ audienceCutoff DateTime? @map("audience_cutoff") @db.Timestamptz
582
+ cursorUserId String? @map("cursor_user_id") @db.Uuid
583
+
584
+ // A snapshot, not a live count: how many users matched `audienceCutoff`
585
+ // the moment the fan-out started. Nullable because it does not exist
586
+ // until sending begins (a `scheduled`/`draft` broadcast has no audience
587
+ // yet). It can legitimately end up HIGHER than `recipientsDispatched` if
588
+ // users are deactivated mid-flight and the handler skips them — this
589
+ // column means "targeted at send time", never "should have received it".
590
+ recipientsTargeted Int? @map("recipients_targeted")
591
+
592
+ // How many recipients the fan-out has ATTEMPTED so far — incremented per
593
+ // dispatch attempt, not per success. Per-channel success/failure is
594
+ // already recorded, per attempt, in `notification_deliveries`; this
595
+ // column exists only so the admin list/detail view has a cheap aggregate
596
+ // progress number without joining or scanning that table, not as a
597
+ // second, weaker copy of what it already tracks.
598
+ recipientsDispatched Int @default(0) @map("recipients_dispatched")
599
+
600
+ lastError String? @map("last_error") @db.Text
601
+
602
+ createdById String? @map("created_by_id") @db.Uuid
603
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
604
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
605
+
606
+ // The audience's organization (#738, PP-8.5). NULL = every active user of
607
+ // the deployment (a system broadcast, as before #738); set = the ACTIVE
608
+ // members of that organization only. Read by the start and chunk handlers
609
+ // from the row (the job payloads carry only the broadcast id, unchanged), so
610
+ // `audienceWhere(cutoff, targetOrgId)` and the keyset cursor stay one query.
611
+ // No row-level security on this table: a system broadcast belongs to no
612
+ // organization, and RLS would hide it from the job that delivers it; the
613
+ // API authorizes `targetOrgId` instead (`broadcasts:*` may name any org,
614
+ // `org_broadcasts:*` only the caller's active org). CASCADE: an
615
+ // organization's broadcasts have no audience once it is deleted.
616
+ targetOrgId String? @map("target_org_id") @db.Uuid
617
+
618
+ // Relations
619
+ createdBy User? @relation("BroadcastAuthor", fields: [createdById], references: [id], onDelete: SetNull)
620
+ targetOrg Organization? @relation("BroadcastTargetOrg", fields: [targetOrgId], references: [id], onDelete: Cascade)
621
+
622
+ @@index([status, scheduledFor])
623
+ @@index([createdAt(sort: Desc)])
624
+ // A holder of only `org_broadcasts:read` lists its organization's broadcasts.
625
+ @@index([targetOrgId])
626
+ @@map("notification_broadcasts")
627
+ }
628
+
629
+ enum NotificationBroadcastStatus {
630
+ // Not reachable by any route in #319 — see the block comment above for why
631
+ // this dead value exists on purpose. Do not remove it as unused.
632
+ draft
633
+ scheduled
634
+ sending
635
+ sent
636
+ canceled
637
+ failed
638
+ }
639
+
640
+ extend model User {
641
+ notificationDeliveries NotificationDelivery[] @relation("UserNotificationDeliveries")
642
+ notifications Notification[] @relation("UserNotifications")
643
+ pushSubscriptions PushSubscription[] @relation("UserPushSubscriptions")
644
+ broadcastsCreated NotificationBroadcast[] @relation("BroadcastAuthor")
645
+ }
646
+
647
+ extend model Organization {
648
+ notificationBroadcasts NotificationBroadcast[] @relation("BroadcastTargetOrg")
649
+ }