@headless-lms/adapter-db 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/client.d.ts +8 -2
  2. package/dist/client.js +10 -2
  3. package/dist/client.js.map +1 -1
  4. package/dist/index.d.ts +10 -4
  5. package/dist/index.js +9 -3
  6. package/dist/repositories/admin.d.ts +12 -4
  7. package/dist/repositories/admin.js +165 -23
  8. package/dist/repositories/admin.js.map +1 -1
  9. package/dist/repositories/assets.d.ts +2 -2
  10. package/dist/repositories/assets.js +11 -5
  11. package/dist/repositories/assets.js.map +1 -1
  12. package/dist/repositories/automations.d.ts +0 -1
  13. package/dist/repositories/automations.js +2 -18
  14. package/dist/repositories/automations.js.map +1 -1
  15. package/dist/repositories/chats.d.ts +14 -5
  16. package/dist/repositories/chats.js +194 -85
  17. package/dist/repositories/chats.js.map +1 -1
  18. package/dist/repositories/content.d.ts +24 -7
  19. package/dist/repositories/content.js +229 -48
  20. package/dist/repositories/content.js.map +1 -1
  21. package/dist/repositories/credentials.js +1 -1
  22. package/dist/repositories/devices.d.ts +17 -0
  23. package/dist/repositories/devices.js +75 -0
  24. package/dist/repositories/devices.js.map +1 -0
  25. package/dist/repositories/digest-runs.d.ts +14 -0
  26. package/dist/repositories/digest-runs.js +39 -0
  27. package/dist/repositories/digest-runs.js.map +1 -0
  28. package/dist/repositories/discussion.d.ts +7 -2
  29. package/dist/repositories/discussion.js +18 -7
  30. package/dist/repositories/discussion.js.map +1 -1
  31. package/dist/repositories/entitlements.d.ts +11 -9
  32. package/dist/repositories/entitlements.js +56 -59
  33. package/dist/repositories/entitlements.js.map +1 -1
  34. package/dist/repositories/event-reports.d.ts +16 -0
  35. package/dist/repositories/event-reports.js +199 -0
  36. package/dist/repositories/event-reports.js.map +1 -0
  37. package/dist/repositories/grant-covers.d.ts +4 -3
  38. package/dist/repositories/grant-covers.js +7 -4
  39. package/dist/repositories/grant-covers.js.map +1 -1
  40. package/dist/repositories/identity.js +1 -1
  41. package/dist/repositories/inserted-row.d.ts +5 -0
  42. package/dist/repositories/inserted-row.js +7 -0
  43. package/dist/repositories/inserted-row.js.map +1 -0
  44. package/dist/repositories/integrations.js +1 -1
  45. package/dist/repositories/member.d.ts +12 -4
  46. package/dist/repositories/member.js +19 -7
  47. package/dist/repositories/member.js.map +1 -1
  48. package/dist/repositories/members.d.ts +2 -5
  49. package/dist/repositories/members.js +39 -94
  50. package/dist/repositories/members.js.map +1 -1
  51. package/dist/repositories/mentions.d.ts +17 -0
  52. package/dist/repositories/mentions.js +55 -0
  53. package/dist/repositories/mentions.js.map +1 -0
  54. package/dist/repositories/notification-settings.d.ts +19 -0
  55. package/dist/repositories/notification-settings.js +67 -0
  56. package/dist/repositories/notification-settings.js.map +1 -0
  57. package/dist/repositories/notifications.d.ts +23 -16
  58. package/dist/repositories/notifications.js +152 -44
  59. package/dist/repositories/notifications.js.map +1 -1
  60. package/dist/repositories/org-user-profile.d.ts +0 -17
  61. package/dist/repositories/org-user-profile.js +0 -1
  62. package/dist/repositories/org-user-profile.js.map +1 -1
  63. package/dist/repositories/organizations.d.ts +4 -4
  64. package/dist/repositories/organizations.js +25 -47
  65. package/dist/repositories/organizations.js.map +1 -1
  66. package/dist/repositories/outbox.d.ts +5 -1
  67. package/dist/repositories/outbox.js +12 -3
  68. package/dist/repositories/outbox.js.map +1 -1
  69. package/dist/repositories/posts.d.ts +4 -8
  70. package/dist/repositories/posts.js +26 -29
  71. package/dist/repositories/posts.js.map +1 -1
  72. package/dist/repositories/progress.js +1 -1
  73. package/dist/repositories/roles.d.ts +35 -0
  74. package/dist/repositories/roles.js +244 -0
  75. package/dist/repositories/roles.js.map +1 -0
  76. package/dist/repositories/settings.js +1 -1
  77. package/dist/repositories/subscriptions.d.ts +18 -0
  78. package/dist/repositories/subscriptions.js +72 -0
  79. package/dist/repositories/subscriptions.js.map +1 -0
  80. package/dist/schema/assets.d.ts +17 -0
  81. package/dist/schema/assets.js +1 -0
  82. package/dist/schema/assets.js.map +1 -1
  83. package/dist/schema/automations.d.ts +524 -19
  84. package/dist/schema/automations.js +73 -7
  85. package/dist/schema/automations.js.map +1 -1
  86. package/dist/schema/content.d.ts +437 -3
  87. package/dist/schema/content.js +70 -3
  88. package/dist/schema/content.js.map +1 -1
  89. package/dist/schema/discussion.d.ts +295 -128
  90. package/dist/schema/discussion.js +63 -26
  91. package/dist/schema/discussion.js.map +1 -1
  92. package/dist/schema/identity.d.ts +109 -109
  93. package/dist/schema/identity.js +28 -70
  94. package/dist/schema/identity.js.map +1 -1
  95. package/dist/schema/index.d.ts +7 -6
  96. package/dist/schema/index.js +16 -7
  97. package/dist/schema/index.js.map +1 -1
  98. package/dist/schema/organizations.d.ts +5 -22
  99. package/dist/schema/organizations.js +1 -13
  100. package/dist/schema/organizations.js.map +1 -1
  101. package/dist/schema/roles.d.ts +369 -0
  102. package/dist/schema/roles.js +71 -0
  103. package/dist/schema/roles.js.map +1 -0
  104. package/drizzle/0011_digest_runs.sql +8 -0
  105. package/drizzle/0012_subscriptions.sql +16 -0
  106. package/drizzle/0013_mentions.sql +10 -0
  107. package/drizzle/0014_notification_settings_devices.sql +36 -0
  108. package/drizzle/0015_automations_drop_source.sql +2 -0
  109. package/drizzle/0016_notifications_automations.sql +48 -0
  110. package/drizzle/0017_configurable_roles.sql +38 -0
  111. package/drizzle/0018_messages_client_id.sql +2 -0
  112. package/drizzle/0019_events.sql +44 -0
  113. package/drizzle/meta/0011_snapshot.json +8868 -0
  114. package/drizzle/meta/0012_snapshot.json +8873 -0
  115. package/drizzle/meta/0013_snapshot.json +8943 -0
  116. package/drizzle/meta/0014_snapshot.json +9305 -0
  117. package/drizzle/meta/0015_snapshot.json +9270 -0
  118. package/drizzle/meta/0016_snapshot.json +9230 -0
  119. package/drizzle/meta/0017_snapshot.json +9518 -0
  120. package/drizzle/meta/0018_snapshot.json +9557 -0
  121. package/drizzle/meta/0019_snapshot.json +9919 -0
  122. package/drizzle/meta/_journal.json +63 -0
  123. package/package.json +2 -2
@@ -1,66 +1,174 @@
1
- import { notificationPreferences, notifications } from "../schema/identity.js";
1
+ import { notificationDeliveries, notifications } from "../schema/automations.js";
2
2
  import "../schema/index.js";
3
3
  import { translateDbErrors } from "./pg-errors.js";
4
- import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
4
+ import { and, arrayOverlaps, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
5
5
  //#region src/repositories/notifications.ts
6
+ const n = notifications;
7
+ const d = notificationDeliveries;
8
+ function ref(type, id) {
9
+ return type && id ? {
10
+ type,
11
+ id
12
+ } : null;
13
+ }
14
+ function toStored(row) {
15
+ return {
16
+ id: row.id,
17
+ orgId: row.orgId,
18
+ userId: row.userId,
19
+ type: row.type,
20
+ scope: row.scope,
21
+ reasons: row.reasons,
22
+ matchedReason: row.matchedReason,
23
+ category: row.category,
24
+ communityId: row.communityId,
25
+ spaceId: row.spaceId,
26
+ actorId: row.actorId,
27
+ subject: ref(row.subjectType, row.subjectId),
28
+ parent: ref(row.parentType, row.parentId),
29
+ display: row.display,
30
+ createdAt: row.createdAt
31
+ };
32
+ }
33
+ function toDelivery(row) {
34
+ return {
35
+ id: row.id,
36
+ notificationId: row.notificationId,
37
+ channel: row.channel,
38
+ status: row.status,
39
+ lastError: row.lastError,
40
+ createdAt: row.createdAt,
41
+ sentAt: row.sentAt
42
+ };
43
+ }
44
+ function listed(orgId, userId, filter) {
45
+ const conditions = [
46
+ eq(n.orgId, orgId),
47
+ eq(n.userId, userId),
48
+ eq(n.inApp, true)
49
+ ];
50
+ if (filter.scope === "org") conditions.push(isNull(n.communityId));
51
+ if (filter.scope === "community") conditions.push(isNotNull(n.communityId));
52
+ if (filter.communityId !== void 0) {
53
+ const community = eq(n.communityId, filter.communityId);
54
+ conditions.push(filter.includeOrg ? or(community, isNull(n.communityId)) : community);
55
+ }
56
+ if (filter.category && filter.category.length > 0) conditions.push(inArray(n.category, filter.category));
57
+ if (filter.reason && filter.reason.length > 0) conditions.push(arrayOverlaps(n.reasons, filter.reason));
58
+ if (filter.type && filter.type.length > 0) conditions.push(inArray(n.type, filter.type));
59
+ if (filter.unread === true) conditions.push(isNull(n.readAt));
60
+ return conditions;
61
+ }
6
62
  var DrizzleNotificationsRepository = class {
7
63
  db;
8
64
  constructor(db) {
9
65
  this.db = db;
10
66
  }
11
- async insert(orgId, rows) {
67
+ async insert(orgId, rows, deliveries) {
12
68
  if (rows.length === 0) return;
13
- await this.db.insert(notifications).values(rows.map((row) => ({
14
- ...row,
15
- orgId
16
- })));
69
+ await this.db.transaction(async (tx) => {
70
+ const inserted = await tx.insert(n).values(rows.map((row) => ({
71
+ orgId,
72
+ id: row.id,
73
+ userId: row.userId,
74
+ sourceEventId: row.sourceEventId,
75
+ type: row.type,
76
+ scope: row.scope,
77
+ reasons: row.reasons,
78
+ matchedReason: row.matchedReason,
79
+ category: row.category,
80
+ communityId: row.communityId,
81
+ spaceId: row.spaceId,
82
+ actorId: row.actorId,
83
+ subjectType: row.subject?.type ?? null,
84
+ subjectId: row.subject?.id ?? null,
85
+ parentType: row.parent?.type ?? null,
86
+ parentId: row.parent?.id ?? null,
87
+ display: row.display,
88
+ inApp: row.inApp,
89
+ createdAt: row.createdAt
90
+ }))).onConflictDoNothing().returning({ id: n.id });
91
+ const kept = new Set(inserted.map((row) => row.id));
92
+ const pending = deliveries.filter((delivery) => kept.has(delivery.notificationId));
93
+ if (pending.length === 0) return;
94
+ await tx.insert(d).values(pending.map((delivery) => ({
95
+ orgId,
96
+ id: delivery.id,
97
+ notificationId: delivery.notificationId,
98
+ channel: delivery.channel,
99
+ status: "pending"
100
+ }))).onConflictDoNothing();
101
+ });
102
+ }
103
+ async pendingDeliveriesForEvent(orgId, sourceEventId) {
104
+ return this.db.select({ id: d.id }).from(d).innerJoin(n, and(eq(n.orgId, d.orgId), eq(n.id, d.notificationId))).where(and(eq(n.orgId, orgId), eq(n.sourceEventId, sourceEventId), eq(d.status, "pending"))).orderBy(d.id);
105
+ }
106
+ async findDelivery(orgId, deliveryId) {
107
+ const [row] = await this.db.select({
108
+ delivery: d,
109
+ notification: n
110
+ }).from(d).innerJoin(n, and(eq(n.orgId, d.orgId), eq(n.id, d.notificationId))).where(and(eq(d.orgId, orgId), eq(d.id, deliveryId))).limit(1);
111
+ return row ? {
112
+ delivery: toDelivery(row.delivery),
113
+ notification: toStored(row.notification)
114
+ } : null;
115
+ }
116
+ async markSent(orgId, deliveryId, at) {
117
+ await this.db.update(d).set({
118
+ status: "sent",
119
+ sentAt: at
120
+ }).where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, "pending")));
121
+ }
122
+ async recordError(orgId, deliveryId, error) {
123
+ await this.db.update(d).set({ lastError: error }).where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, "pending")));
17
124
  }
18
- async page(orgId, userId, query) {
19
- const mine = and(eq(notifications.orgId, orgId), eq(notifications.userId, userId));
20
- const [rows, counts] = await Promise.all([this.db.select().from(notifications).where(mine).orderBy(desc(notifications.createdAt), desc(notifications.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize), this.db.select({
125
+ async markFailed(orgId, deliveryId, error) {
126
+ await this.db.update(d).set({
127
+ status: "failed",
128
+ lastError: error
129
+ }).where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, "pending")));
130
+ }
131
+ async page(orgId, userId, filter, page) {
132
+ const where = and(...listed(orgId, userId, filter));
133
+ const [rows, counts] = await Promise.all([this.db.select().from(n).where(where).orderBy(desc(n.createdAt), desc(n.id)).limit(page.pageSize).offset((page.page - 1) * page.pageSize), this.db.select({
21
134
  total: sql`count(*)::int`,
22
- unread: sql`(count(*) filter (where ${notifications.readAt} is null))::int`
23
- }).from(notifications).where(mine)]);
135
+ unread: sql`(count(*) filter (where ${n.readAt} is null))::int`
136
+ }).from(n).where(where)]);
24
137
  return {
25
- rows,
138
+ items: rows.map((row) => ({
139
+ ...toStored(row),
140
+ readAt: row.readAt
141
+ })),
26
142
  total: Number(counts[0]?.total ?? 0),
27
143
  unreadCount: Number(counts[0]?.unread ?? 0)
28
144
  };
29
145
  }
30
- async markRead(orgId, userId, notificationId, at) {
31
- const [row] = await this.db.update(notifications).set({ readAt: sql`coalesce(${notifications.readAt}, ${at.toISOString()}::timestamptz)` }).where(and(eq(notifications.orgId, orgId), eq(notifications.userId, userId), eq(notifications.id, notificationId))).returning();
32
- return row ?? null;
146
+ async find(orgId, userId, notificationId) {
147
+ const [row] = await this.db.select().from(n).where(and(eq(n.orgId, orgId), eq(n.userId, userId), eq(n.id, notificationId), eq(n.inApp, true))).limit(1);
148
+ return row ? {
149
+ ...toStored(row),
150
+ readAt: row.readAt
151
+ } : null;
33
152
  }
34
- async markAllRead(orgId, userId, at) {
35
- return (await this.db.update(notifications).set({ readAt: at }).where(and(eq(notifications.orgId, orgId), eq(notifications.userId, userId), isNull(notifications.readAt))).returning({ id: notifications.id })).length;
153
+ async unreadCounts(orgId, userId, communityIds) {
154
+ const unread = and(eq(n.orgId, orgId), eq(n.userId, userId), eq(n.inApp, true), isNull(n.readAt));
155
+ const [org, communities] = await Promise.all([this.db.select({ unread: sql`count(*)::int` }).from(n).where(and(unread, isNull(n.communityId))), communityIds.length === 0 ? Promise.resolve([]) : this.db.select({
156
+ communityId: n.communityId,
157
+ unread: sql`count(*)::int`
158
+ }).from(n).where(and(unread, inArray(n.communityId, communityIds))).groupBy(n.communityId)]);
159
+ return {
160
+ org: Number(org[0]?.unread ?? 0),
161
+ communities: communities.flatMap((row) => row.communityId ? [{
162
+ communityId: row.communityId,
163
+ unread: Number(row.unread)
164
+ }] : [])
165
+ };
36
166
  }
37
- async preferences(orgId, userIds) {
38
- if (userIds.length === 0) return [];
39
- return this.db.select({
40
- userId: notificationPreferences.userId,
41
- kind: notificationPreferences.kind,
42
- inApp: notificationPreferences.inApp,
43
- email: notificationPreferences.email
44
- }).from(notificationPreferences).where(and(eq(notificationPreferences.orgId, orgId), inArray(notificationPreferences.userId, userIds)));
167
+ async markRead(orgId, userId, notificationId, at) {
168
+ return (await this.db.update(n).set({ readAt: sql`coalesce(${n.readAt}, ${at.toISOString()}::timestamptz)` }).where(and(eq(n.orgId, orgId), eq(n.userId, userId), eq(n.id, notificationId), eq(n.inApp, true))).returning({ id: n.id })).length > 0;
45
169
  }
46
- async upsertPreferences(orgId, userId, preferences) {
47
- if (preferences.length === 0) return;
48
- await this.db.insert(notificationPreferences).values(preferences.map((pref) => ({
49
- orgId,
50
- userId,
51
- ...pref
52
- }))).onConflictDoUpdate({
53
- target: [
54
- notificationPreferences.orgId,
55
- notificationPreferences.userId,
56
- notificationPreferences.kind
57
- ],
58
- set: {
59
- inApp: sql`excluded.in_app`,
60
- email: sql`excluded.email`,
61
- updatedAt: sql`now()`
62
- }
63
- });
170
+ async markAllRead(orgId, userId, filter, at) {
171
+ return (await this.db.update(n).set({ readAt: at }).where(and(...listed(orgId, userId, filter), isNull(n.readAt))).returning({ id: n.id })).length;
64
172
  }
65
173
  };
66
174
  translateDbErrors(DrizzleNotificationsRepository);
@@ -1 +1 @@
1
- {"version":3,"file":"notifications.js","names":[],"sources":["../../src/repositories/notifications.ts"],"sourcesContent":["import { and, desc, eq, inArray, isNull, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { NotificationsQuery, NotificationsRepository } from \"@headless-lms/core/identity\";\nimport type { Notification, NotificationPreference } from \"@headless-lms/core/types\";\nimport { notificationPreferences, notifications } from \"../schema/index.js\";\nimport { translateDbErrors } from \"./pg-errors.js\";\n\nexport class DrizzleNotificationsRepository implements NotificationsRepository {\n constructor(private readonly db: NodePgDatabase) {}\n\n async insert(orgId: string, rows: Notification[]): Promise<void> {\n if (rows.length === 0) {\n return;\n }\n await this.db.insert(notifications).values(rows.map((row) => ({ ...row, orgId })));\n }\n\n async page(\n orgId: string,\n userId: string,\n query: NotificationsQuery,\n ): Promise<{ rows: Notification[]; total: number; unreadCount: number }> {\n const mine = and(eq(notifications.orgId, orgId), eq(notifications.userId, userId));\n const [rows, counts] = await Promise.all([\n this.db\n .select()\n .from(notifications)\n .where(mine)\n .orderBy(desc(notifications.createdAt), desc(notifications.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({\n total: sql<number>`count(*)::int`,\n unread: sql<number>`(count(*) filter (where ${notifications.readAt} is null))::int`,\n })\n .from(notifications)\n .where(mine),\n ]);\n return {\n rows,\n total: Number(counts[0]?.total ?? 0),\n unreadCount: Number(counts[0]?.unread ?? 0),\n };\n }\n\n async markRead(\n orgId: string,\n userId: string,\n notificationId: string,\n at: Date,\n ): Promise<Notification | null> {\n const [row] = await this.db\n .update(notifications)\n .set({ readAt: sql`coalesce(${notifications.readAt}, ${at.toISOString()}::timestamptz)` })\n .where(\n and(\n eq(notifications.orgId, orgId),\n eq(notifications.userId, userId),\n eq(notifications.id, notificationId),\n ),\n )\n .returning();\n return row ?? null;\n }\n\n async markAllRead(orgId: string, userId: string, at: Date): Promise<number> {\n const rows = await this.db\n .update(notifications)\n .set({ readAt: at })\n .where(\n and(\n eq(notifications.orgId, orgId),\n eq(notifications.userId, userId),\n isNull(notifications.readAt),\n ),\n )\n .returning({ id: notifications.id });\n return rows.length;\n }\n\n async preferences(\n orgId: string,\n userIds: string[],\n ): Promise<(NotificationPreference & { userId: string })[]> {\n if (userIds.length === 0) {\n return [];\n }\n return this.db\n .select({\n userId: notificationPreferences.userId,\n kind: notificationPreferences.kind,\n inApp: notificationPreferences.inApp,\n email: notificationPreferences.email,\n })\n .from(notificationPreferences)\n .where(\n and(\n eq(notificationPreferences.orgId, orgId),\n inArray(notificationPreferences.userId, userIds),\n ),\n );\n }\n\n async upsertPreferences(\n orgId: string,\n userId: string,\n preferences: NotificationPreference[],\n ): Promise<void> {\n if (preferences.length === 0) {\n return;\n }\n await this.db\n .insert(notificationPreferences)\n .values(preferences.map((pref) => ({ orgId, userId, ...pref })))\n .onConflictDoUpdate({\n target: [\n notificationPreferences.orgId,\n notificationPreferences.userId,\n notificationPreferences.kind,\n ],\n set: {\n inApp: sql`excluded.in_app`,\n email: sql`excluded.email`,\n updatedAt: sql`now()`,\n },\n });\n }\n}\n\ntranslateDbErrors(DrizzleNotificationsRepository);\n"],"mappings":";;;;;AAOA,IAAa,iCAAb,MAA+E;CAChD;CAA7B,YAAY,IAAqC;EAApB,KAAA,KAAA;CAAqB;CAElD,MAAM,OAAO,OAAe,MAAqC;EAC/D,IAAI,KAAK,WAAW,GAClB;EAEF,MAAM,KAAK,GAAG,OAAO,aAAa,CAAC,CAAC,OAAO,KAAK,KAAK,SAAS;GAAE,GAAG;GAAK;EAAM,EAAE,CAAC;CACnF;CAEA,MAAM,KACJ,OACA,QACA,OACuE;EACvE,MAAM,OAAO,IAAI,GAAG,cAAc,OAAO,KAAK,GAAG,GAAG,cAAc,QAAQ,MAAM,CAAC;EACjF,MAAM,CAAC,MAAM,UAAU,MAAM,QAAQ,IAAI,CACvC,KAAK,GACF,OAAO,CAAC,CACR,KAAK,aAAa,CAAC,CACnB,MAAM,IAAI,CAAC,CACX,QAAQ,KAAK,cAAc,SAAS,GAAG,KAAK,cAAc,EAAE,CAAC,CAAC,CAC9D,MAAM,MAAM,QAAQ,CAAC,CACrB,QAAQ,MAAM,OAAO,KAAK,MAAM,QAAQ,GAC3C,KAAK,GACF,OAAO;GACN,OAAO,GAAW;GAClB,QAAQ,GAAW,2BAA2B,cAAc,OAAO;EACrE,CAAC,CAAC,CACD,KAAK,aAAa,CAAC,CACnB,MAAM,IAAI,CACf,CAAC;EACD,OAAO;GACL;GACA,OAAO,OAAO,OAAO,EAAE,EAAE,SAAS,CAAC;GACnC,aAAa,OAAO,OAAO,EAAE,EAAE,UAAU,CAAC;EAC5C;CACF;CAEA,MAAM,SACJ,OACA,QACA,gBACA,IAC8B;EAC9B,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,aAAa,CAAC,CACrB,IAAI,EAAE,QAAQ,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
+ {"version":3,"file":"notifications.js","names":[],"sources":["../../src/repositories/notifications.ts"],"sourcesContent":["import {\n and,\n arrayOverlaps,\n desc,\n eq,\n inArray,\n isNotNull,\n isNull,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport type {\n ListedNotification,\n NewDelivery,\n NewNotification,\n NotificationPage,\n NotificationsRepository,\n UnreadCounts,\n} from \"@headless-lms/core/automations\";\nimport type {\n Delivery,\n NotificationFilter,\n StoredNotification,\n SubjectRef,\n} from \"@headless-lms/core/types\";\nimport type { DbExecutor } from \"../client.js\";\nimport { notificationDeliveries, notifications } from \"../schema/index.js\";\nimport { translateDbErrors } from \"./pg-errors.js\";\n\nconst n = notifications;\nconst d = notificationDeliveries;\n\ntype NotificationRow = typeof notifications.$inferSelect;\ntype DeliveryRow = typeof notificationDeliveries.$inferSelect;\n\nfunction ref(type: string | null, id: string | null): SubjectRef | null {\n return type && id ? { type: type as SubjectRef[\"type\"], id } : null;\n}\n\nfunction toStored(row: NotificationRow): StoredNotification {\n return {\n id: row.id,\n orgId: row.orgId,\n userId: row.userId,\n type: row.type,\n scope: row.scope,\n reasons: row.reasons,\n matchedReason: row.matchedReason,\n category: row.category,\n communityId: row.communityId,\n spaceId: row.spaceId,\n actorId: row.actorId,\n subject: ref(row.subjectType, row.subjectId),\n parent: ref(row.parentType, row.parentId),\n display: row.display,\n createdAt: row.createdAt,\n };\n}\n\nfunction toDelivery(row: DeliveryRow): Delivery {\n return {\n id: row.id,\n notificationId: row.notificationId,\n channel: row.channel,\n status: row.status,\n lastError: row.lastError,\n createdAt: row.createdAt,\n sentAt: row.sentAt,\n };\n}\n\nfunction listed(orgId: string, userId: string, filter: NotificationFilter): SQL[] {\n const conditions: SQL[] = [eq(n.orgId, orgId), eq(n.userId, userId), eq(n.inApp, true)];\n if (filter.scope === \"org\") {\n conditions.push(isNull(n.communityId));\n }\n if (filter.scope === \"community\") {\n conditions.push(isNotNull(n.communityId));\n }\n if (filter.communityId !== undefined) {\n const community = eq(n.communityId, filter.communityId);\n conditions.push(filter.includeOrg ? or(community, isNull(n.communityId))! : community);\n }\n if (filter.category && filter.category.length > 0) {\n conditions.push(inArray(n.category, filter.category));\n }\n if (filter.reason && filter.reason.length > 0) {\n conditions.push(arrayOverlaps(n.reasons, filter.reason));\n }\n if (filter.type && filter.type.length > 0) {\n conditions.push(inArray(n.type, filter.type));\n }\n if (filter.unread === true) {\n conditions.push(isNull(n.readAt));\n }\n return conditions;\n}\n\nexport class DrizzleNotificationsRepository implements NotificationsRepository {\n constructor(private readonly db: DbExecutor) {}\n\n async insert(orgId: string, rows: NewNotification[], deliveries: NewDelivery[]): Promise<void> {\n if (rows.length === 0) {\n return;\n }\n await this.db.transaction(async (tx) => {\n const inserted = await tx\n .insert(n)\n .values(\n rows.map((row) => ({\n orgId,\n id: row.id,\n userId: row.userId,\n sourceEventId: row.sourceEventId,\n type: row.type,\n scope: row.scope,\n reasons: row.reasons,\n matchedReason: row.matchedReason,\n category: row.category,\n communityId: row.communityId,\n spaceId: row.spaceId,\n actorId: row.actorId,\n subjectType: row.subject?.type ?? null,\n subjectId: row.subject?.id ?? null,\n parentType: row.parent?.type ?? null,\n parentId: row.parent?.id ?? null,\n display: row.display,\n inApp: row.inApp,\n createdAt: row.createdAt,\n })),\n )\n .onConflictDoNothing()\n .returning({ id: n.id });\n const kept = new Set(inserted.map((row) => row.id));\n const pending = deliveries.filter((delivery) => kept.has(delivery.notificationId));\n if (pending.length === 0) {\n return;\n }\n await tx\n .insert(d)\n .values(\n pending.map((delivery) => ({\n orgId,\n id: delivery.id,\n notificationId: delivery.notificationId,\n channel: delivery.channel,\n status: \"pending\" as const,\n })),\n )\n .onConflictDoNothing();\n });\n }\n\n async pendingDeliveriesForEvent(orgId: string, sourceEventId: string): Promise<{ id: string }[]> {\n return this.db\n .select({ id: d.id })\n .from(d)\n .innerJoin(n, and(eq(n.orgId, d.orgId), eq(n.id, d.notificationId)))\n .where(and(eq(n.orgId, orgId), eq(n.sourceEventId, sourceEventId), eq(d.status, \"pending\")))\n .orderBy(d.id);\n }\n\n async findDelivery(\n orgId: string,\n deliveryId: string,\n ): Promise<{ delivery: Delivery; notification: StoredNotification } | null> {\n const [row] = await this.db\n .select({ delivery: d, notification: n })\n .from(d)\n .innerJoin(n, and(eq(n.orgId, d.orgId), eq(n.id, d.notificationId)))\n .where(and(eq(d.orgId, orgId), eq(d.id, deliveryId)))\n .limit(1);\n return row\n ? { delivery: toDelivery(row.delivery), notification: toStored(row.notification) }\n : null;\n }\n\n async markSent(orgId: string, deliveryId: string, at: Date): Promise<void> {\n await this.db\n .update(d)\n .set({ status: \"sent\", sentAt: at })\n .where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, \"pending\")));\n }\n\n async recordError(orgId: string, deliveryId: string, error: string): Promise<void> {\n await this.db\n .update(d)\n .set({ lastError: error })\n .where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, \"pending\")));\n }\n\n async markFailed(orgId: string, deliveryId: string, error: string): Promise<void> {\n await this.db\n .update(d)\n .set({ status: \"failed\", lastError: error })\n .where(and(eq(d.orgId, orgId), eq(d.id, deliveryId), eq(d.status, \"pending\")));\n }\n\n async page(\n orgId: string,\n userId: string,\n filter: NotificationFilter,\n page: { page: number; pageSize: number },\n ): Promise<NotificationPage> {\n const where = and(...listed(orgId, userId, filter));\n const [rows, counts] = await Promise.all([\n this.db\n .select()\n .from(n)\n .where(where)\n .orderBy(desc(n.createdAt), desc(n.id))\n .limit(page.pageSize)\n .offset((page.page - 1) * page.pageSize),\n this.db\n .select({\n total: sql<number>`count(*)::int`,\n unread: sql<number>`(count(*) filter (where ${n.readAt} is null))::int`,\n })\n .from(n)\n .where(where),\n ]);\n return {\n items: rows.map((row) => ({ ...toStored(row), readAt: row.readAt })),\n total: Number(counts[0]?.total ?? 0),\n unreadCount: Number(counts[0]?.unread ?? 0),\n };\n }\n\n async find(\n orgId: string,\n userId: string,\n notificationId: string,\n ): Promise<ListedNotification | null> {\n const [row] = await this.db\n .select()\n .from(n)\n .where(\n and(eq(n.orgId, orgId), eq(n.userId, userId), eq(n.id, notificationId), eq(n.inApp, true)),\n )\n .limit(1);\n return row ? { ...toStored(row), readAt: row.readAt } : null;\n }\n\n async unreadCounts(orgId: string, userId: string, communityIds: string[]): Promise<UnreadCounts> {\n const unread = and(\n eq(n.orgId, orgId),\n eq(n.userId, userId),\n eq(n.inApp, true),\n isNull(n.readAt),\n );\n const [org, communities] = await Promise.all([\n this.db\n .select({ unread: sql<number>`count(*)::int` })\n .from(n)\n .where(and(unread, isNull(n.communityId))),\n communityIds.length === 0\n ? Promise.resolve([])\n : this.db\n .select({ communityId: n.communityId, unread: sql<number>`count(*)::int` })\n .from(n)\n .where(and(unread, inArray(n.communityId, communityIds)))\n .groupBy(n.communityId),\n ]);\n return {\n org: Number(org[0]?.unread ?? 0),\n communities: communities.flatMap((row) =>\n row.communityId ? [{ communityId: row.communityId, unread: Number(row.unread) }] : [],\n ),\n };\n }\n\n async markRead(\n orgId: string,\n userId: string,\n notificationId: string,\n at: Date,\n ): Promise<boolean> {\n const rows = await this.db\n .update(n)\n .set({ readAt: sql`coalesce(${n.readAt}, ${at.toISOString()}::timestamptz)` })\n .where(\n and(eq(n.orgId, orgId), eq(n.userId, userId), eq(n.id, notificationId), eq(n.inApp, true)),\n )\n .returning({ id: n.id });\n return rows.length > 0;\n }\n\n async markAllRead(\n orgId: string,\n userId: string,\n filter: NotificationFilter,\n at: Date,\n ): Promise<number> {\n const rows = await this.db\n .update(n)\n .set({ readAt: at })\n .where(and(...listed(orgId, userId, filter), isNull(n.readAt)))\n .returning({ id: n.id });\n return rows.length;\n }\n}\n\ntranslateDbErrors(DrizzleNotificationsRepository);\n"],"mappings":";;;;;AA8BA,MAAM,IAAI;AACV,MAAM,IAAI;AAKV,SAAS,IAAI,MAAqB,IAAsC;CACtE,OAAO,QAAQ,KAAK;EAAQ;EAA4B;CAAG,IAAI;AACjE;AAEA,SAAS,SAAS,KAA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AO,KAAK,GAAG,GAAG,EAAE,QAAQ,MAAM,GAAG,GAAG,EAAE,IAAI,cAAc,GAAG,GAAG,EAAE,OAAO,IAAI,CAAC,CAC3F,CAAC,CACA,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,EAAA,CACb,SAAS;CACvB;CAEA,MAAM,YACJ,OACA,QACA,QACA,IACiB;EAMjB,QAAO,MALY,KAAK,GACrB,OAAO,CAAC,CAAC,CACT,IAAI,EAAE,QAAQ,GAAG,CAAC,CAAC,CACnB,MAAM,IAAI,GAAG,OAAO,OAAO,QAAQ,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAC9D,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,EAAA,CACb;CACd;AACF;AAEA,kBAAkB,8BAA8B"}
@@ -88,23 +88,6 @@ declare const orgUserProfileColumns: {
88
88
  }, {}, {}>;
89
89
  };
90
90
  declare const authorProfileColumns: {
91
- role: import("drizzle-orm/pg-core").PgColumn<{
92
- name: "role";
93
- tableName: "org_users";
94
- dataType: "string";
95
- columnType: "PgText";
96
- data: "student" | "owner" | "admin" | "instructor" | "moderator";
97
- driverParam: string;
98
- notNull: true;
99
- hasDefault: false;
100
- isPrimaryKey: false;
101
- isAutoincrement: false;
102
- hasRuntimeDefault: false;
103
- enumValues: ["owner", "admin", "instructor", "moderator", "student"];
104
- baseColumn: never;
105
- identity: undefined;
106
- generated: undefined;
107
- }, {}, {}>;
108
91
  displayName: import("drizzle-orm/pg-core").PgColumn<{
109
92
  name: "display_name";
110
93
  tableName: "user_profiles";
@@ -13,7 +13,6 @@ const orgUserProfileColumns = {
13
13
  };
14
14
  const authorProfileColumns = {
15
15
  ...orgUserProfileColumns,
16
- role: orgUsers.role,
17
16
  displayName: userProfiles.displayName,
18
17
  headline: userProfiles.headline,
19
18
  imageAssetOrgId: userProfiles.imageAssetOrgId,
@@ -1 +1 @@
1
- {"version":3,"file":"org-user-profile.js","names":[],"sources":["../../src/repositories/org-user-profile.ts"],"sourcesContent":["// The one display join for an org user's profile.\n//\n// The names and email live on the identity `users` row the org_users row links\n// to; the avatar lives on the auth engine's mirrored `user` table, reached\n// through that same identity row. The identity join is INNER (user_id is NOT\n// NULL); the auth join is LEFT, since only the avatar depends on it.\n//\n// Sanctioned by .eslintrc.cjs — \"db repositories read the auth adapter's\n// mirrored `user` table for display joins\".\n//\n// No `joinOrgUserProfile` helper: Drizzle's query builder type narrows on every\n// chained call, so a generic wrapper around `.innerJoin(...).leftJoin(...)`\n// can't be typed without widening it to `unknown` — each repository chains the\n// two joins inline instead.\nimport { sql } from \"drizzle-orm\";\nimport { orgUsers } from \"../schema/organizations.js\";\nimport { userProfiles, users } from \"../schema/identity.js\";\nimport { user } from \"../schema/better-auth.js\";\n\n/** Spread into a `.select({ ... })` to get the profile columns. */\nexport const orgUserProfileColumns = {\n id: orgUsers.id,\n firstName: users.firstName,\n lastName: users.lastName,\n email: users.email,\n image: user.image,\n};\n\nexport const authorProfileColumns = {\n ...orgUserProfileColumns,\n role: orgUsers.role,\n displayName: userProfiles.displayName,\n headline: userProfiles.headline,\n imageAssetOrgId: userProfiles.imageAssetOrgId,\n imageAssetId: userProfiles.imageAssetId,\n};\n\n// A person is shared across organizations. Until an invited student accepts,\n// the inviting org sees the name and avatar only when the profile is its own:\n// no account yet and no other organization.\nconst profileVisible = sql`(${orgUsers.status} <> 'invited' or (${users.externalId} is null and not exists (\n select 1 from org_users other where other.user_id = ${users.id} and other.org_id <> ${orgUsers.orgId}\n)))`;\n\nexport const studentFirstName = sql<\n string | null\n>`case when ${profileVisible} then ${users.firstName} end`;\nexport const studentLastName = sql<\n string | null\n>`case when ${profileVisible} then ${users.lastName} end`;\n\nexport const studentProfileColumns = {\n id: orgUsers.id,\n firstName: studentFirstName,\n lastName: studentLastName,\n email: users.email,\n image: sql<string | null>`case when ${profileVisible} then ${user.image} end`,\n};\n"],"mappings":";;;;;;AAoBA,MAAa,wBAAwB;CACnC,IAAI,SAAS;CACb,WAAW,MAAM;CACjB,UAAU,MAAM;CAChB,OAAO,MAAM;CACb,OAAO,KAAK;AACd;AAEA,MAAa,uBAAuB;CAClC,GAAG;CACH,MAAM,SAAS;CACf,aAAa,aAAa;CAC1B,UAAU,aAAa;CACvB,iBAAiB,aAAa;CAC9B,cAAc,aAAa;AAC7B;AAKA,MAAM,iBAAiB,GAAG,IAAI,SAAS,OAAO,oBAAoB,MAAM,WAAW;wDAC3B,MAAM,GAAG,uBAAuB,SAAS,MAAM;;AAGvG,MAAa,mBAAmB,GAE/B,aAAa,eAAe,QAAQ,MAAM,UAAU;AACrD,MAAa,kBAAkB,GAE9B,aAAa,eAAe,QAAQ,MAAM,SAAS;AAEpD,MAAa,wBAAwB;CACnC,IAAI,SAAS;CACb,WAAW;CACX,UAAU;CACV,OAAO,MAAM;CACb,OAAO,GAAkB,aAAa,eAAe,QAAQ,KAAK,MAAM;AAC1E"}
1
+ {"version":3,"file":"org-user-profile.js","names":[],"sources":["../../src/repositories/org-user-profile.ts"],"sourcesContent":["// The one display join for an org user's profile.\n//\n// The names and email live on the identity `users` row the org_users row links\n// to; the avatar lives on the auth engine's mirrored `user` table, reached\n// through that same identity row. The identity join is INNER (user_id is NOT\n// NULL); the auth join is LEFT, since only the avatar depends on it.\n//\n// Sanctioned by .eslintrc.cjs — \"db repositories read the auth adapter's\n// mirrored `user` table for display joins\".\n//\n// No `joinOrgUserProfile` helper: Drizzle's query builder type narrows on every\n// chained call, so a generic wrapper around `.innerJoin(...).leftJoin(...)`\n// can't be typed without widening it to `unknown` — each repository chains the\n// two joins inline instead.\nimport { sql } from \"drizzle-orm\";\nimport { orgUsers } from \"../schema/organizations.js\";\nimport { userProfiles, users } from \"../schema/identity.js\";\nimport { user } from \"../schema/better-auth.js\";\n\n/** Spread into a `.select({ ... })` to get the profile columns. */\nexport const orgUserProfileColumns = {\n id: orgUsers.id,\n firstName: users.firstName,\n lastName: users.lastName,\n email: users.email,\n image: user.image,\n};\n\nexport const authorProfileColumns = {\n ...orgUserProfileColumns,\n displayName: userProfiles.displayName,\n headline: userProfiles.headline,\n imageAssetOrgId: userProfiles.imageAssetOrgId,\n imageAssetId: userProfiles.imageAssetId,\n};\n\n// A person is shared across organizations. Until an invited student accepts,\n// the inviting org sees the name and avatar only when the profile is its own:\n// no account yet and no other organization.\nconst profileVisible = sql`(${orgUsers.status} <> 'invited' or (${users.externalId} is null and not exists (\n select 1 from org_users other where other.user_id = ${users.id} and other.org_id <> ${orgUsers.orgId}\n)))`;\n\nexport const studentFirstName = sql<\n string | null\n>`case when ${profileVisible} then ${users.firstName} end`;\nexport const studentLastName = sql<\n string | null\n>`case when ${profileVisible} then ${users.lastName} end`;\n\nexport const studentProfileColumns = {\n id: orgUsers.id,\n firstName: studentFirstName,\n lastName: studentLastName,\n email: users.email,\n image: sql<string | null>`case when ${profileVisible} then ${user.image} end`,\n};\n"],"mappings":";;;;;;AAoBA,MAAa,wBAAwB;CACnC,IAAI,SAAS;CACb,WAAW,MAAM;CACjB,UAAU,MAAM;CAChB,OAAO,MAAM;CACb,OAAO,KAAK;AACd;AAEA,MAAa,uBAAuB;CAClC,GAAG;CACH,aAAa,aAAa;CAC1B,UAAU,aAAa;CACvB,iBAAiB,aAAa;CAC9B,cAAc,aAAa;AAC7B;AAKA,MAAM,iBAAiB,GAAG,IAAI,SAAS,OAAO,oBAAoB,MAAM,WAAW;wDAC3B,MAAM,GAAG,uBAAuB,SAAS,MAAM;;AAGvG,MAAa,mBAAmB,GAE/B,aAAa,eAAe,QAAQ,MAAM,UAAU;AACrD,MAAa,kBAAkB,GAE9B,aAAa,eAAe,QAAQ,MAAM,SAAS;AAEpD,MAAa,wBAAwB;CACnC,IAAI,SAAS;CACb,WAAW;CACX,UAAU;CACV,OAAO,MAAM;CACb,OAAO,GAAkB,aAAa,eAAe,QAAQ,KAAK,MAAM;AAC1E"}
@@ -1,5 +1,5 @@
1
1
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
- import { CreateOrgUserInput, Invite, NewInviteRow, NewOrganizationRow, OrgUser, Organization, OrganizationsRepository, Role, UpdateOrgUserInput, UpdateOrganizationInput } from "@headless-lms/core/organizations";
2
+ import { CreateOrgUserInput, Invite, NewInviteRow, NewOrganizationRow, OrgUser, Organization, OrganizationsRepository, UpdateOrgUserInput, UpdateOrganizationInput } from "@headless-lms/core/organizations";
3
3
  import { Logger } from "@headless-lms/core/shared/ports";
4
4
  //#region src/repositories/organizations.d.ts
5
5
  declare class DrizzleOrganizationsRepository implements OrganizationsRepository {
@@ -10,21 +10,21 @@ declare class DrizzleOrganizationsRepository implements OrganizationsRepository
10
10
  update(id: string, input: UpdateOrganizationInput): Promise<Organization | null>;
11
11
  delete(id: string): Promise<Organization>;
12
12
  findById(id: string): Promise<Organization | null>;
13
+ listIds(): Promise<string[]>;
13
14
  findByExternalId(externalId: string): Promise<Organization | null>;
14
15
  findBySlug(slug: string): Promise<Organization | null>;
15
16
  upsertPendingInvite(orgId: string, input: NewInviteRow): Promise<Invite>;
16
17
  setInviteStatus(orgId: string, id: string, status: string): Promise<Invite | null>;
18
+ setInviteRole(orgId: string, id: string, roleKey: string, invitedBy: string): Promise<Invite | null>;
17
19
  findInviteByTokenHash(tokenHash: string): Promise<Invite | null>;
18
20
  findPendingInvite(orgId: string, email: string): Promise<Invite | null>;
19
- setInviteToken(orgId: string, id: string, tokenHash: string, expiresAt: Date): Promise<Invite | null>;
21
+ setInviteToken(orgId: string, id: string, tokenHash: string, expiresAt: Date, invitedBy: string): Promise<Invite | null>;
20
22
  findOrgUser(orgId: string, userId: string): Promise<OrgUser | null>;
21
23
  findOrgUsersByUser(userId: string): Promise<OrgUser[]>;
22
24
  findOrgUserById(orgId: string, id: string): Promise<OrgUser | null>;
23
25
  findOrgUsersByIds(orgId: string, ids: string[]): Promise<OrgUser[]>;
24
- findOrgUserIdsByRole(orgId: string, roles: Role[]): Promise<string[]>;
25
26
  createOrgUser(input: CreateOrgUserInput): Promise<OrgUser>;
26
27
  updateOrgUser(orgId: string, id: string, patch: UpdateOrgUserInput): Promise<OrgUser | null>;
27
- findStudentOrgUsers(userId: string): Promise<OrgUser[]>;
28
28
  deleteOrgUser(orgId: string, id: string): Promise<OrgUser | null>;
29
29
  }
30
30
  //#endregion
@@ -1,9 +1,8 @@
1
1
  import { invites, orgUsers, organizations } from "../schema/organizations.js";
2
2
  import { isUniqueViolation, pgErrorFields, translateDbErrors } from "./pg-errors.js";
3
- import { and, eq, inArray, sql } from "drizzle-orm";
4
- import { ConflictError } from "@headless-lms/core/shared/errors";
5
3
  import { noopLogger } from "@headless-lms/core/shared/logger";
6
- import { parseRole } from "@headless-lms/core/organizations";
4
+ import { and, asc, eq, inArray, sql } from "drizzle-orm";
5
+ import { ConflictError } from "@headless-lms/core/shared/errors";
7
6
  //#region src/repositories/organizations.ts
8
7
  const INVITE_STATUSES = [
9
8
  "pending",
@@ -17,7 +16,7 @@ function toInvite(row) {
17
16
  id: row.id,
18
17
  orgId: row.orgId,
19
18
  email: row.email,
20
- role: row.role,
19
+ roleKey: row.roleKey,
21
20
  status: row.status,
22
21
  invitedBy: row.invitedBy,
23
22
  tokenHash: row.tokenHash,
@@ -60,6 +59,9 @@ var DrizzleOrganizationsRepository = class {
60
59
  const [row] = await this.db.select().from(organizations).where(eq(organizations.id, id));
61
60
  return row ?? null;
62
61
  }
62
+ async listIds() {
63
+ return (await this.db.select({ id: organizations.id }).from(organizations).orderBy(asc(organizations.id))).map((row) => row.id);
64
+ }
63
65
  async findByExternalId(externalId) {
64
66
  const [row] = await this.db.select().from(organizations).where(eq(organizations.externalId, externalId)).limit(1);
65
67
  return row ?? null;
@@ -72,7 +74,7 @@ var DrizzleOrganizationsRepository = class {
72
74
  const [row] = await this.db.insert(invites).values({
73
75
  orgId,
74
76
  email: input.email,
75
- role: input.role,
77
+ roleKey: input.roleKey,
76
78
  status: "pending",
77
79
  invitedBy: input.invitedBy,
78
80
  tokenHash: input.tokenHash,
@@ -81,7 +83,7 @@ var DrizzleOrganizationsRepository = class {
81
83
  target: [invites.orgId, invites.email],
82
84
  targetWhere: sql`${invites.status} = 'pending'`,
83
85
  set: {
84
- role: input.role,
86
+ roleKey: input.roleKey,
85
87
  invitedBy: input.invitedBy,
86
88
  tokenHash: input.tokenHash,
87
89
  expiresAt: input.expiresAt
@@ -94,6 +96,13 @@ var DrizzleOrganizationsRepository = class {
94
96
  const [row] = await this.db.update(invites).set({ status: toStatus(status) }).where(and(eq(invites.orgId, orgId), eq(invites.id, id))).returning();
95
97
  return row ? toInvite(row) : null;
96
98
  }
99
+ async setInviteRole(orgId, id, roleKey, invitedBy) {
100
+ const [row] = await this.db.update(invites).set({
101
+ roleKey,
102
+ invitedBy
103
+ }).where(and(eq(invites.orgId, orgId), eq(invites.id, id), eq(invites.status, "pending"))).returning();
104
+ return row ? toInvite(row) : null;
105
+ }
97
106
  async findInviteByTokenHash(tokenHash) {
98
107
  const [row] = await this.db.select().from(invites).where(eq(invites.tokenHash, tokenHash)).limit(1);
99
108
  return row ? toInvite(row) : null;
@@ -102,77 +111,46 @@ var DrizzleOrganizationsRepository = class {
102
111
  const [row] = await this.db.select().from(invites).where(and(eq(invites.orgId, orgId), sql`lower(${invites.email}) = lower(${email})`, eq(invites.status, "pending"))).limit(1);
103
112
  return row ? toInvite(row) : null;
104
113
  }
105
- async setInviteToken(orgId, id, tokenHash, expiresAt) {
114
+ async setInviteToken(orgId, id, tokenHash, expiresAt, invitedBy) {
106
115
  const [row] = await this.db.update(invites).set({
107
116
  tokenHash,
108
- expiresAt
117
+ expiresAt,
118
+ invitedBy
109
119
  }).where(and(eq(invites.orgId, orgId), eq(invites.id, id), eq(invites.status, "pending"))).returning();
110
120
  return row ? toInvite(row) : null;
111
121
  }
112
122
  async findOrgUser(orgId, userId) {
113
123
  const [row] = await this.db.select().from(orgUsers).where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.userId, userId))).limit(1);
114
- return row ? {
115
- ...row,
116
- role: parseRole(row.role)
117
- } : null;
124
+ return row ?? null;
118
125
  }
119
126
  async findOrgUsersByUser(userId) {
120
- return (await this.db.select().from(orgUsers).where(eq(orgUsers.userId, userId)).orderBy(orgUsers.createdAt)).map((row) => ({
121
- ...row,
122
- role: parseRole(row.role)
123
- }));
127
+ return await this.db.select().from(orgUsers).where(eq(orgUsers.userId, userId)).orderBy(orgUsers.createdAt);
124
128
  }
125
129
  async findOrgUserById(orgId, id) {
126
130
  const [row] = await this.db.select().from(orgUsers).where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id))).limit(1);
127
- return row ? {
128
- ...row,
129
- role: parseRole(row.role)
130
- } : null;
131
+ return row ?? null;
131
132
  }
132
133
  async findOrgUsersByIds(orgId, ids) {
133
134
  if (ids.length === 0) return [];
134
- return (await this.db.select().from(orgUsers).where(and(eq(orgUsers.orgId, orgId), inArray(orgUsers.id, ids)))).map((row) => ({
135
- ...row,
136
- role: parseRole(row.role)
137
- }));
138
- }
139
- async findOrgUserIdsByRole(orgId, roles) {
140
- if (roles.length === 0) return [];
141
- return (await this.db.select({ id: orgUsers.id }).from(orgUsers).where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.status, "active"), inArray(orgUsers.role, roles))).orderBy(orgUsers.id)).map((row) => row.id);
135
+ return await this.db.select().from(orgUsers).where(and(eq(orgUsers.orgId, orgId), inArray(orgUsers.id, ids)));
142
136
  }
143
137
  async createOrgUser(input) {
144
138
  try {
145
139
  const [row] = await this.db.insert(orgUsers).values({
146
140
  orgId: input.orgId,
147
141
  userId: input.userId,
148
- role: input.role,
149
142
  status: input.status ?? "active"
150
143
  }).returning();
151
144
  if (!row) throw new Error("failed to insert org user");
152
- return {
153
- ...row,
154
- role: parseRole(row.role)
155
- };
145
+ return row;
156
146
  } catch (err) {
157
147
  if (isUniqueViolation(err)) throw new ConflictError("That account already belongs to this organization");
158
148
  throw err;
159
149
  }
160
150
  }
161
151
  async updateOrgUser(orgId, id, patch) {
162
- const [row] = await this.db.update(orgUsers).set({
163
- ...patch.role !== void 0 && { role: patch.role },
164
- ...patch.status !== void 0 && { status: patch.status }
165
- }).where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id))).returning();
166
- return row ? {
167
- ...row,
168
- role: parseRole(row.role)
169
- } : null;
170
- }
171
- async findStudentOrgUsers(userId) {
172
- return (await this.db.select().from(orgUsers).where(and(eq(orgUsers.userId, userId), eq(orgUsers.role, "student"))).orderBy(orgUsers.createdAt)).map((row) => ({
173
- ...row,
174
- role: parseRole(row.role)
175
- }));
152
+ const [row] = await this.db.update(orgUsers).set({ ...patch.status !== void 0 && { status: patch.status } }).where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id))).returning();
153
+ return row ?? null;
176
154
  }
177
155
  async deleteOrgUser(orgId, id) {
178
156
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"organizations.js","names":[],"sources":["../../src/repositories/organizations.ts"],"sourcesContent":["// organizations — Drizzle repository (implements the core outbound port).\nimport { and, eq, inArray, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport {\n parseRole,\n type CreateOrgUserInput,\n type Invite,\n type NewInviteRow,\n type NewOrganizationRow,\n type Organization,\n type OrganizationsRepository,\n type OrgUser,\n type Role,\n type UpdateOrganizationInput,\n type UpdateOrgUserInput,\n} from \"@headless-lms/core/organizations\";\nimport { invites, organizations, orgUsers } from \"../schema/organizations.js\";\nimport type { Logger } from \"@headless-lms/core/shared/ports\";\nimport { noopLogger } from \"@headless-lms/core/shared/logger\";\nimport { ConflictError } from \"@headless-lms/core/shared/errors\";\nimport { isUniqueViolation, pgErrorFields, translateDbErrors } from \"./pg-errors.js\";\n\nconst INVITE_STATUSES = [\"pending\", \"accepted\", \"rejected\", \"canceled\"] as const;\ntype InviteStatus = (typeof INVITE_STATUSES)[number];\nconst toStatus = (s: string): InviteStatus =>\n (INVITE_STATUSES as readonly string[]).includes(s) ? (s as InviteStatus) : \"pending\";\n\nfunction toInvite(row: typeof invites.$inferSelect): Invite {\n return {\n id: row.id,\n orgId: row.orgId,\n email: row.email,\n role: row.role,\n status: row.status,\n invitedBy: row.invitedBy,\n tokenHash: row.tokenHash,\n expiresAt: row.expiresAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport class DrizzleOrganizationsRepository implements OrganizationsRepository {\n constructor(\n private readonly db: NodePgDatabase,\n private readonly logger: Logger = noopLogger,\n ) {}\n\n async create(input: NewOrganizationRow): Promise<Organization> {\n const [row] = await this.db\n .insert(organizations)\n .values({\n externalId: input.externalId,\n name: input.name,\n slug: input.slug,\n ownerId: input.ownerId,\n id: input.id,\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to insert organization\");\n }\n return row!;\n }\n\n async update(id: string, input: UpdateOrganizationInput): Promise<Organization | null> {\n const [row] = await this.db\n .update(organizations)\n .set({ name: input.name, slug: input.slug })\n .where(eq(organizations.id, id))\n .returning();\n return row ?? null;\n }\n\n async delete(id: string): Promise<Organization> {\n const [row] = await this.db.delete(organizations).where(eq(organizations.id, id)).returning();\n\n if (!row) {\n throw new Error(\"failed to delete organization\");\n }\n return row;\n }\n\n async findById(id: string): Promise<Organization | null> {\n const [row] = await this.db.select().from(organizations).where(eq(organizations.id, id));\n return row ?? null;\n }\n\n async findByExternalId(externalId: string): Promise<Organization | null> {\n const [row] = await this.db\n .select()\n .from(organizations)\n .where(eq(organizations.externalId, externalId))\n .limit(1);\n return row ?? null;\n }\n\n async findBySlug(slug: string): Promise<Organization | null> {\n const [row] = await this.db\n .select()\n .from(organizations)\n .where(eq(organizations.slug, slug))\n .limit(1);\n return row ?? null;\n }\n\n async upsertPendingInvite(orgId: string, input: NewInviteRow): Promise<Invite> {\n const [row] = await this.db\n .insert(invites)\n .values({\n orgId,\n email: input.email,\n role: input.role,\n status: \"pending\",\n invitedBy: input.invitedBy,\n tokenHash: input.tokenHash,\n expiresAt: input.expiresAt,\n })\n .onConflictDoUpdate({\n target: [invites.orgId, invites.email],\n targetWhere: sql`${invites.status} = 'pending'`,\n set: {\n role: input.role,\n invitedBy: input.invitedBy,\n tokenHash: input.tokenHash,\n expiresAt: input.expiresAt,\n },\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to upsert invite\");\n }\n return toInvite(row);\n }\n\n async setInviteStatus(orgId: string, id: string, status: string): Promise<Invite | null> {\n const [row] = await this.db\n .update(invites)\n .set({ status: toStatus(status) })\n .where(and(eq(invites.orgId, orgId), eq(invites.id, id)))\n .returning();\n return row ? toInvite(row) : null;\n }\n\n async findInviteByTokenHash(tokenHash: string): Promise<Invite | null> {\n const [row] = await this.db\n .select()\n .from(invites)\n .where(eq(invites.tokenHash, tokenHash))\n .limit(1);\n return row ? toInvite(row) : null;\n }\n\n async findPendingInvite(orgId: string, email: string): Promise<Invite | null> {\n const [row] = await this.db\n .select()\n .from(invites)\n .where(\n and(\n eq(invites.orgId, orgId),\n sql`lower(${invites.email}) = lower(${email})`,\n eq(invites.status, \"pending\"),\n ),\n )\n .limit(1);\n return row ? toInvite(row) : null;\n }\n\n async setInviteToken(\n orgId: string,\n id: string,\n tokenHash: string,\n expiresAt: Date,\n ): Promise<Invite | null> {\n const [row] = await this.db\n .update(invites)\n .set({ tokenHash, expiresAt })\n .where(and(eq(invites.orgId, orgId), eq(invites.id, id), eq(invites.status, \"pending\")))\n .returning();\n return row ? toInvite(row) : null;\n }\n\n async findOrgUser(orgId: string, userId: string): Promise<OrgUser | null> {\n const [row] = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.userId, userId)))\n .limit(1);\n return row ? { ...row, role: parseRole(row.role) } : null;\n }\n\n async findOrgUsersByUser(userId: string): Promise<OrgUser[]> {\n const rows = await this.db\n .select()\n .from(orgUsers)\n .where(eq(orgUsers.userId, userId))\n .orderBy(orgUsers.createdAt);\n return rows.map((row) => ({ ...row, role: parseRole(row.role) }));\n }\n\n async findOrgUserById(orgId: string, id: string): Promise<OrgUser | null> {\n const [row] = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .limit(1);\n return row ? { ...row, role: parseRole(row.role) } : null;\n }\n\n async findOrgUsersByIds(orgId: string, ids: string[]): Promise<OrgUser[]> {\n if (ids.length === 0) {\n return [];\n }\n const rows = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), inArray(orgUsers.id, ids)));\n return rows.map((row) => ({ ...row, role: parseRole(row.role) }));\n }\n\n async findOrgUserIdsByRole(orgId: string, roles: Role[]): Promise<string[]> {\n if (roles.length === 0) {\n return [];\n }\n const rows = await this.db\n .select({ id: orgUsers.id })\n .from(orgUsers)\n .where(\n and(\n eq(orgUsers.orgId, orgId),\n eq(orgUsers.status, \"active\"),\n inArray(orgUsers.role, roles),\n ),\n )\n .orderBy(orgUsers.id);\n return rows.map((row) => row.id);\n }\n\n async createOrgUser(input: CreateOrgUserInput): Promise<OrgUser> {\n try {\n const [row] = await this.db\n .insert(orgUsers)\n .values({\n orgId: input.orgId,\n userId: input.userId,\n role: input.role,\n status: input.status ?? \"active\",\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to insert org user\");\n }\n return { ...row, role: parseRole(row.role) };\n } catch (err) {\n if (isUniqueViolation(err)) {\n throw new ConflictError(\"That account already belongs to this organization\");\n }\n throw err;\n }\n }\n\n async updateOrgUser(\n orgId: string,\n id: string,\n patch: UpdateOrgUserInput,\n ): Promise<OrgUser | null> {\n const [row] = await this.db\n .update(orgUsers)\n .set({\n ...(patch.role !== undefined && { role: patch.role }),\n ...(patch.status !== undefined && { status: patch.status }),\n })\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .returning();\n return row ? { ...row, role: parseRole(row.role) } : null;\n }\n\n async findStudentOrgUsers(userId: string): Promise<OrgUser[]> {\n const rows = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.userId, userId), eq(orgUsers.role, \"student\")))\n .orderBy(orgUsers.createdAt);\n return rows.map((row) => ({ ...row, role: parseRole(row.role) }));\n }\n\n async deleteOrgUser(orgId: string, id: string): Promise<OrgUser | null> {\n try {\n const [row] = await this.db\n .delete(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .returning();\n return row ?? null;\n } catch (err) {\n if (pgErrorFields(err)?.code === \"23503\") {\n throw Object.assign(\n new ConflictError(\n \"This person has written posts, comments or messages and cannot be deleted\",\n ),\n { cause: err },\n );\n }\n throw err;\n }\n }\n}\ntranslateDbErrors(DrizzleOrganizationsRepository);\n"],"mappings":";;;;;;;AAsBA,MAAM,kBAAkB;CAAC;CAAW;CAAY;CAAY;AAAU;AAEtE,MAAM,YAAY,MACf,gBAAsC,SAAS,CAAC,IAAK,IAAqB;AAE7E,SAAS,SAAS,KAA0C;CAC1D,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;CACjB;AACF;AAEA,IAAa,iCAAb,MAA+E;CAE1D;CACA;CAFnB,YACE,IACA,SAAkC,YAClC;EAFiB,KAAA,KAAA;EACA,KAAA,SAAA;CAChB;CAEH,MAAM,OAAO,OAAkD;EAC7D,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,aAAa,CAAC,CACrB,OAAO;GACN,YAAY,MAAM;GAClB,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,IAAI,MAAM;EACZ,CAAC,CAAC,CACD,UAAU;EACb,IAAI,CAAC,KACH,MAAM,IAAI,MAAM,+BAA+B;EAEjD,OAAO;CACT;CAEA,MAAM,OAAO,IAAY,OAA8D;EACrF,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,aAAa,CAAC,CACrB,IAAI;GAAE,MAAM,MAAM;GAAM,MAAM,MAAM;EAAK,CAAC,CAAC,CAC3C,MAAM,GAAG,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OAAO,CAAC,CACR,KAAK,QAAQ,CAAC,CACd,MAAM,IAAI,GAAG,SAAS,QAAQ,MAAM,GAAG,GAAG,SAAS,MAAM,SAAS,CAAC,CAAC,CAAC,CACrE,QAAQ,SAAS,SAAS,EAAA,CACjB,KAAK,SAAS;GAAE,GAAG;GAAK,MAAM,UAAU,IAAI,IAAI;EAAE,EAAE;CAClE;CAEA,MAAM,cAAc,OAAe,IAAqC;EACtE,IAAI;GACF,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,QAAQ,CAAC,CAChB,MAAM,IAAI,GAAG,SAAS,OAAO,KAAK,GAAG,GAAG,SAAS,IAAI,EAAE,CAAC,CAAC,CAAC,CAC1D,UAAU;GACb,OAAO,OAAO;EAChB,SAAS,KAAK;GACZ,IAAI,cAAc,GAAG,CAAC,EAAE,SAAS,SAC/B,MAAM,OAAO,OACX,IAAI,cACF,2EACF,GACA,EAAE,OAAO,IAAI,CACf;GAEF,MAAM;EACR;CACF;AACF;AACA,kBAAkB,8BAA8B"}
1
+ {"version":3,"file":"organizations.js","names":[],"sources":["../../src/repositories/organizations.ts"],"sourcesContent":["// organizations — Drizzle repository (implements the core outbound port).\nimport { and, asc, eq, inArray, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type {\n CreateOrgUserInput,\n Invite,\n NewInviteRow,\n NewOrganizationRow,\n Organization,\n OrganizationsRepository,\n OrgUser,\n UpdateOrganizationInput,\n UpdateOrgUserInput,\n} from \"@headless-lms/core/organizations\";\nimport { invites, organizations, orgUsers } from \"../schema/organizations.js\";\nimport type { Logger } from \"@headless-lms/core/shared/ports\";\nimport { noopLogger } from \"@headless-lms/core/shared/logger\";\nimport { ConflictError } from \"@headless-lms/core/shared/errors\";\nimport { isUniqueViolation, pgErrorFields, translateDbErrors } from \"./pg-errors.js\";\n\nconst INVITE_STATUSES = [\"pending\", \"accepted\", \"rejected\", \"canceled\"] as const;\ntype InviteStatus = (typeof INVITE_STATUSES)[number];\nconst toStatus = (s: string): InviteStatus =>\n (INVITE_STATUSES as readonly string[]).includes(s) ? (s as InviteStatus) : \"pending\";\n\nfunction toInvite(row: typeof invites.$inferSelect): Invite {\n return {\n id: row.id,\n orgId: row.orgId,\n email: row.email,\n roleKey: row.roleKey,\n status: row.status,\n invitedBy: row.invitedBy,\n tokenHash: row.tokenHash,\n expiresAt: row.expiresAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport class DrizzleOrganizationsRepository implements OrganizationsRepository {\n constructor(\n private readonly db: NodePgDatabase,\n private readonly logger: Logger = noopLogger,\n ) {}\n\n async create(input: NewOrganizationRow): Promise<Organization> {\n const [row] = await this.db\n .insert(organizations)\n .values({\n externalId: input.externalId,\n name: input.name,\n slug: input.slug,\n ownerId: input.ownerId,\n id: input.id,\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to insert organization\");\n }\n return row!;\n }\n\n async update(id: string, input: UpdateOrganizationInput): Promise<Organization | null> {\n const [row] = await this.db\n .update(organizations)\n .set({ name: input.name, slug: input.slug })\n .where(eq(organizations.id, id))\n .returning();\n return row ?? null;\n }\n\n async delete(id: string): Promise<Organization> {\n const [row] = await this.db.delete(organizations).where(eq(organizations.id, id)).returning();\n\n if (!row) {\n throw new Error(\"failed to delete organization\");\n }\n return row;\n }\n\n async findById(id: string): Promise<Organization | null> {\n const [row] = await this.db.select().from(organizations).where(eq(organizations.id, id));\n return row ?? null;\n }\n\n async listIds(): Promise<string[]> {\n const rows = await this.db\n .select({ id: organizations.id })\n .from(organizations)\n .orderBy(asc(organizations.id));\n return rows.map((row) => row.id);\n }\n\n async findByExternalId(externalId: string): Promise<Organization | null> {\n const [row] = await this.db\n .select()\n .from(organizations)\n .where(eq(organizations.externalId, externalId))\n .limit(1);\n return row ?? null;\n }\n\n async findBySlug(slug: string): Promise<Organization | null> {\n const [row] = await this.db\n .select()\n .from(organizations)\n .where(eq(organizations.slug, slug))\n .limit(1);\n return row ?? null;\n }\n\n async upsertPendingInvite(orgId: string, input: NewInviteRow): Promise<Invite> {\n const [row] = await this.db\n .insert(invites)\n .values({\n orgId,\n email: input.email,\n roleKey: input.roleKey,\n status: \"pending\",\n invitedBy: input.invitedBy,\n tokenHash: input.tokenHash,\n expiresAt: input.expiresAt,\n })\n .onConflictDoUpdate({\n target: [invites.orgId, invites.email],\n targetWhere: sql`${invites.status} = 'pending'`,\n set: {\n roleKey: input.roleKey,\n invitedBy: input.invitedBy,\n tokenHash: input.tokenHash,\n expiresAt: input.expiresAt,\n },\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to upsert invite\");\n }\n return toInvite(row);\n }\n\n async setInviteStatus(orgId: string, id: string, status: string): Promise<Invite | null> {\n const [row] = await this.db\n .update(invites)\n .set({ status: toStatus(status) })\n .where(and(eq(invites.orgId, orgId), eq(invites.id, id)))\n .returning();\n return row ? toInvite(row) : null;\n }\n\n async setInviteRole(\n orgId: string,\n id: string,\n roleKey: string,\n invitedBy: string,\n ): Promise<Invite | null> {\n const [row] = await this.db\n .update(invites)\n .set({ roleKey, invitedBy })\n .where(and(eq(invites.orgId, orgId), eq(invites.id, id), eq(invites.status, \"pending\")))\n .returning();\n return row ? toInvite(row) : null;\n }\n\n async findInviteByTokenHash(tokenHash: string): Promise<Invite | null> {\n const [row] = await this.db\n .select()\n .from(invites)\n .where(eq(invites.tokenHash, tokenHash))\n .limit(1);\n return row ? toInvite(row) : null;\n }\n\n async findPendingInvite(orgId: string, email: string): Promise<Invite | null> {\n const [row] = await this.db\n .select()\n .from(invites)\n .where(\n and(\n eq(invites.orgId, orgId),\n sql`lower(${invites.email}) = lower(${email})`,\n eq(invites.status, \"pending\"),\n ),\n )\n .limit(1);\n return row ? toInvite(row) : null;\n }\n\n async setInviteToken(\n orgId: string,\n id: string,\n tokenHash: string,\n expiresAt: Date,\n invitedBy: string,\n ): Promise<Invite | null> {\n const [row] = await this.db\n .update(invites)\n .set({ tokenHash, expiresAt, invitedBy })\n .where(and(eq(invites.orgId, orgId), eq(invites.id, id), eq(invites.status, \"pending\")))\n .returning();\n return row ? toInvite(row) : null;\n }\n\n async findOrgUser(orgId: string, userId: string): Promise<OrgUser | null> {\n const [row] = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.userId, userId)))\n .limit(1);\n return row ?? null;\n }\n\n async findOrgUsersByUser(userId: string): Promise<OrgUser[]> {\n const rows = await this.db\n .select()\n .from(orgUsers)\n .where(eq(orgUsers.userId, userId))\n .orderBy(orgUsers.createdAt);\n return rows;\n }\n\n async findOrgUserById(orgId: string, id: string): Promise<OrgUser | null> {\n const [row] = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .limit(1);\n return row ?? null;\n }\n\n async findOrgUsersByIds(orgId: string, ids: string[]): Promise<OrgUser[]> {\n if (ids.length === 0) {\n return [];\n }\n const rows = await this.db\n .select()\n .from(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), inArray(orgUsers.id, ids)));\n return rows;\n }\n\n async createOrgUser(input: CreateOrgUserInput): Promise<OrgUser> {\n try {\n const [row] = await this.db\n .insert(orgUsers)\n .values({\n orgId: input.orgId,\n userId: input.userId,\n status: input.status ?? \"active\",\n })\n .returning();\n if (!row) {\n throw new Error(\"failed to insert org user\");\n }\n return row;\n } catch (err) {\n if (isUniqueViolation(err)) {\n throw new ConflictError(\"That account already belongs to this organization\");\n }\n throw err;\n }\n }\n\n async updateOrgUser(\n orgId: string,\n id: string,\n patch: UpdateOrgUserInput,\n ): Promise<OrgUser | null> {\n const [row] = await this.db\n .update(orgUsers)\n .set({\n ...(patch.status !== undefined && { status: patch.status }),\n })\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .returning();\n return row ?? null;\n }\n\n async deleteOrgUser(orgId: string, id: string): Promise<OrgUser | null> {\n try {\n const [row] = await this.db\n .delete(orgUsers)\n .where(and(eq(orgUsers.orgId, orgId), eq(orgUsers.id, id)))\n .returning();\n return row ?? null;\n } catch (err) {\n if (pgErrorFields(err)?.code === \"23503\") {\n throw Object.assign(\n new ConflictError(\n \"This person has written posts, comments or messages and cannot be deleted\",\n ),\n { cause: err },\n );\n }\n throw err;\n }\n }\n}\ntranslateDbErrors(DrizzleOrganizationsRepository);\n"],"mappings":";;;;;;AAoBA,MAAM,kBAAkB;CAAC;CAAW;CAAY;CAAY;AAAU;AAEtE,MAAM,YAAY,MACf,gBAAsC,SAAS,CAAC,IAAK,IAAqB;AAE7E,SAAS,SAAS,KAA0C;CAC1D,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,OAAO,IAAI;EACX,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;EACf,WAAW,IAAI;CACjB;AACF;AAEA,IAAa,iCAAb,MAA+E;CAE1D;CACA;CAFnB,YACE,IACA,SAAkC,YAClC;EAFiB,KAAA,KAAA;EACA,KAAA,SAAA;CAChB;CAEH,MAAM,OAAO,OAAkD;EAC7D,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,aAAa,CAAC,CACrB,OAAO;GACN,YAAY,MAAM;GAClB,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,IAAI,MAAM;EACZ,CAAC,CAAC,CACD,UAAU;EACb,IAAI,CAAC,KACH,MAAM,IAAI,MAAM,+BAA+B;EAEjD,OAAO;CACT;CAEA,MAAM,OAAO,IAAY,OAA8D;EACrF,MAAM,CAAC,OAAO,MAAM,KAAK,GACtB,OAAO,aAAa,CAAC,CACrB,IAAI;GAAE,MAAM,MAAM;GAAM,MAAM,MAAM;EAAK,CAAC,CAAC,CAC3C,MAAM,GAAG,cAAc,IAAI,EAAE,CAAC,CAAC,CAC/B,UAAU;EACb,OAAO,OAAO;CAChB;CAEA,MAAM,OAAO,IAAmC;EAC9C,MAAM,CAA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OutboxMessage, OutboxStore } fr
5
5
  /** A message that fails this many dispatches is parked: fetchBatch stops
6
6
  * claiming it, leaving the row (with its last_error) for inspection. */
7
7
  declare const OUTBOX_MAX_ATTEMPTS = 10;
8
+ /** How long a fetched message stays claimed by the relay that fetched it. Another
9
+ * relay fetches it again only after this, so a relay that dies mid-batch delays
10
+ * its messages by at most this long. */
11
+ declare const OUTBOX_CLAIM_MS = 60000;
8
12
  declare class DrizzleOutboxAppender implements OutboxAppender {
9
13
  private readonly tx;
10
14
  private readonly logger;
@@ -20,5 +24,5 @@ declare class DrizzleOutboxStore implements OutboxStore {
20
24
  markFailed(id: string, error: string, nextAttemptAt: Date): Promise<void>;
21
25
  }
22
26
  //#endregion
23
- export { DrizzleOutboxAppender, DrizzleOutboxStore, OUTBOX_MAX_ATTEMPTS };
27
+ export { DrizzleOutboxAppender, DrizzleOutboxStore, OUTBOX_CLAIM_MS, OUTBOX_MAX_ATTEMPTS };
24
28
  //# sourceMappingURL=outbox.d.ts.map
@@ -1,11 +1,15 @@
1
1
  import { eventOutbox } from "../schema/outbox.js";
2
2
  import { translateDbErrors } from "./pg-errors.js";
3
- import { and, asc, eq, isNull, lt, lte, sql } from "drizzle-orm";
4
3
  import { noopLogger } from "@headless-lms/core/shared/logger";
4
+ import { and, asc, eq, inArray, isNull, lt, lte, sql } from "drizzle-orm";
5
5
  //#region src/repositories/outbox.ts
6
6
  /** A message that fails this many dispatches is parked: fetchBatch stops
7
7
  * claiming it, leaving the row (with its last_error) for inspection. */
8
8
  const OUTBOX_MAX_ATTEMPTS = 10;
9
+ /** How long a fetched message stays claimed by the relay that fetched it. Another
10
+ * relay fetches it again only after this, so a relay that dies mid-batch delays
11
+ * its messages by at most this long. */
12
+ const OUTBOX_CLAIM_MS = 6e4;
9
13
  var DrizzleOutboxAppender = class {
10
14
  tx;
11
15
  logger;
@@ -30,7 +34,12 @@ var DrizzleOutboxStore = class {
30
34
  this.logger = logger;
31
35
  }
32
36
  async fetchBatch(limit) {
33
- return (await this.db.transaction((tx) => tx.select().from(eventOutbox).where(and(isNull(eventOutbox.processedAt), lte(eventOutbox.nextAttemptAt, /* @__PURE__ */ new Date()), lt(eventOutbox.attempts, 10))).orderBy(asc(eventOutbox.id)).limit(limit).for("update", { skipLocked: true }))).map((row) => ({
37
+ const now = /* @__PURE__ */ new Date();
38
+ return (await this.db.transaction(async (tx) => {
39
+ const due = await tx.select().from(eventOutbox).where(and(isNull(eventOutbox.processedAt), lte(eventOutbox.nextAttemptAt, now), lt(eventOutbox.attempts, 10))).orderBy(asc(eventOutbox.id)).limit(limit).for("update", { skipLocked: true });
40
+ if (due.length > 0) await tx.update(eventOutbox).set({ nextAttemptAt: new Date(now.getTime() + OUTBOX_CLAIM_MS) }).where(inArray(eventOutbox.id, due.map((row) => row.id)));
41
+ return due;
42
+ })).map((row) => ({
34
43
  id: row.id,
35
44
  attempts: row.attempts,
36
45
  payload: {
@@ -54,6 +63,6 @@ var DrizzleOutboxStore = class {
54
63
  translateDbErrors(DrizzleOutboxAppender);
55
64
  translateDbErrors(DrizzleOutboxStore);
56
65
  //#endregion
57
- export { DrizzleOutboxAppender, DrizzleOutboxStore, OUTBOX_MAX_ATTEMPTS };
66
+ export { DrizzleOutboxAppender, DrizzleOutboxStore, OUTBOX_CLAIM_MS, OUTBOX_MAX_ATTEMPTS };
58
67
 
59
68
  //# sourceMappingURL=outbox.js.map