@kernhq/module-inventory 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/README.md +134 -9
  2. package/dist/contract/capabilities.d.ts +49 -0
  3. package/dist/contract/capabilities.d.ts.map +1 -0
  4. package/dist/contract/capabilities.js +94 -0
  5. package/dist/contract/capabilities.js.map +1 -0
  6. package/dist/contract/events.d.ts +76 -0
  7. package/dist/contract/events.d.ts.map +1 -0
  8. package/dist/contract/events.js +62 -0
  9. package/dist/contract/events.js.map +1 -0
  10. package/dist/contract/index.d.ts +16 -0
  11. package/dist/contract/index.d.ts.map +1 -0
  12. package/dist/contract/index.js +16 -0
  13. package/dist/contract/index.js.map +1 -0
  14. package/dist/contract/models.d.ts +468 -0
  15. package/dist/contract/models.d.ts.map +1 -0
  16. package/dist/contract/models.js +320 -0
  17. package/dist/contract/models.js.map +1 -0
  18. package/dist/contract/notifications.d.ts +24 -0
  19. package/dist/contract/notifications.d.ts.map +1 -0
  20. package/dist/contract/notifications.js +72 -0
  21. package/dist/contract/notifications.js.map +1 -0
  22. package/dist/contract/permissions.d.ts +72 -0
  23. package/dist/contract/permissions.d.ts.map +1 -0
  24. package/dist/contract/permissions.js +79 -0
  25. package/dist/contract/permissions.js.map +1 -0
  26. package/dist/contract/router.d.ts +1378 -0
  27. package/dist/contract/router.d.ts.map +1 -0
  28. package/dist/contract/router.js +266 -0
  29. package/dist/contract/router.js.map +1 -0
  30. package/dist/contract/settings.d.ts +20 -0
  31. package/dist/contract/settings.d.ts.map +1 -0
  32. package/dist/contract/settings.js +49 -0
  33. package/dist/contract/settings.js.map +1 -0
  34. package/dist/server/index.d.ts +8 -1
  35. package/dist/server/index.d.ts.map +1 -1
  36. package/dist/server/index.js +288 -8
  37. package/dist/server/index.js.map +1 -1
  38. package/dist/server/jobs.d.ts +48 -0
  39. package/dist/server/jobs.d.ts.map +1 -0
  40. package/dist/server/jobs.js +358 -0
  41. package/dist/server/jobs.js.map +1 -0
  42. package/dist/server/router.d.ts +1789 -0
  43. package/dist/server/router.d.ts.map +1 -0
  44. package/dist/server/router.js +439 -0
  45. package/dist/server/router.js.map +1 -0
  46. package/dist/server/schema.d.ts +156 -9
  47. package/dist/server/schema.d.ts.map +1 -1
  48. package/dist/server/schema.js +183 -11
  49. package/dist/server/schema.js.map +1 -1
  50. package/dist/server/services/assets.d.ts +139 -0
  51. package/dist/server/services/assets.d.ts.map +1 -0
  52. package/dist/server/services/assets.js +429 -0
  53. package/dist/server/services/assets.js.map +1 -0
  54. package/dist/server/services/attachments.d.ts +80 -0
  55. package/dist/server/services/attachments.d.ts.map +1 -0
  56. package/dist/server/services/attachments.js +182 -0
  57. package/dist/server/services/attachments.js.map +1 -0
  58. package/dist/server/services/audience.d.ts +15 -0
  59. package/dist/server/services/audience.d.ts.map +1 -0
  60. package/dist/server/services/audience.js +64 -0
  61. package/dist/server/services/audience.js.map +1 -0
  62. package/dist/server/services/categories.d.ts +57 -0
  63. package/dist/server/services/categories.d.ts.map +1 -0
  64. package/dist/server/services/categories.js +124 -0
  65. package/dist/server/services/categories.js.map +1 -0
  66. package/dist/server/services/cursor.d.ts +68 -0
  67. package/dist/server/services/cursor.d.ts.map +1 -0
  68. package/dist/server/services/cursor.js +39 -0
  69. package/dist/server/services/cursor.js.map +1 -0
  70. package/dist/server/services/custody.d.ts +175 -0
  71. package/dist/server/services/custody.d.ts.map +1 -0
  72. package/dist/server/services/custody.js +367 -0
  73. package/dist/server/services/custody.js.map +1 -0
  74. package/dist/server/services/db-errors.d.ts +7 -0
  75. package/dist/server/services/db-errors.d.ts.map +1 -0
  76. package/dist/server/services/db-errors.js +32 -0
  77. package/dist/server/services/db-errors.js.map +1 -0
  78. package/dist/server/services/index.d.ts +26 -0
  79. package/dist/server/services/index.d.ts.map +1 -0
  80. package/dist/server/services/index.js +39 -0
  81. package/dist/server/services/index.js.map +1 -0
  82. package/dist/server/services/members.d.ts +27 -0
  83. package/dist/server/services/members.d.ts.map +1 -0
  84. package/dist/server/services/members.js +39 -0
  85. package/dist/server/services/members.js.map +1 -0
  86. package/dist/server/services/notify.d.ts +105 -0
  87. package/dist/server/services/notify.d.ts.map +1 -0
  88. package/dist/server/services/notify.js +147 -0
  89. package/dist/server/services/notify.js.map +1 -0
  90. package/dist/server/services/offboarding.d.ts +70 -0
  91. package/dist/server/services/offboarding.d.ts.map +1 -0
  92. package/dist/server/services/offboarding.js +116 -0
  93. package/dist/server/services/offboarding.js.map +1 -0
  94. package/dist/server/services/repairs.d.ts +204 -0
  95. package/dist/server/services/repairs.d.ts.map +1 -0
  96. package/dist/server/services/repairs.js +476 -0
  97. package/dist/server/services/repairs.js.map +1 -0
  98. package/dist/server/services/search.d.ts +85 -0
  99. package/dist/server/services/search.d.ts.map +1 -0
  100. package/dist/server/services/search.js +142 -0
  101. package/dist/server/services/search.js.map +1 -0
  102. package/dist/server/services/stats.d.ts +42 -0
  103. package/dist/server/services/stats.d.ts.map +1 -0
  104. package/dist/server/services/stats.js +80 -0
  105. package/dist/server/services/stats.js.map +1 -0
  106. package/dist/server/services/status.d.ts +102 -0
  107. package/dist/server/services/status.d.ts.map +1 -0
  108. package/dist/server/services/status.js +71 -0
  109. package/dist/server/services/status.js.map +1 -0
  110. package/migrations/0000_init.sql +12 -3
  111. package/migrations/0001_rls.sql +24 -0
  112. package/migrations/0002_custody_and_categories.sql +23 -0
  113. package/migrations/0003_repairs.sql +23 -0
  114. package/migrations/0004_platform_surfaces.sql +51 -0
  115. package/migrations/0005_repair_dates.sql +35 -0
  116. package/migrations/0006_workspace_registry_read.sql +50 -0
  117. package/migrations/0007_history_sequence.sql +83 -0
  118. package/migrations/meta/0000_snapshot.json +40 -13
  119. package/migrations/meta/0002_snapshot.json +1054 -0
  120. package/migrations/meta/0003_snapshot.json +1070 -0
  121. package/migrations/meta/0004_snapshot.json +1130 -0
  122. package/migrations/meta/0005_snapshot.json +1135 -0
  123. package/migrations/meta/_journal.json +44 -2
  124. package/package.json +5 -4
  125. package/src/client/api-instance.ts +27 -2
  126. package/src/client/api.ts +1 -1
  127. package/src/client/bidi.test.ts +148 -0
  128. package/src/client/bidi.ts +85 -0
  129. package/src/client/components/AssetDetailPanel.svelte +614 -0
  130. package/src/client/components/AssetFormDialog.svelte +191 -59
  131. package/src/client/components/AssetPhoto.svelte +178 -0
  132. package/src/client/components/AttachmentsSection.svelte +327 -0
  133. package/src/client/components/CustodyDialog.svelte +201 -0
  134. package/src/client/components/RepairDialog.svelte +271 -0
  135. package/src/client/components/RepairsSection.svelte +318 -0
  136. package/src/client/components/Timeline.svelte +347 -0
  137. package/src/client/components/TimelineText.svelte +124 -0
  138. package/src/client/core-api.ts +71 -0
  139. package/src/client/custody.test.ts +31 -0
  140. package/src/client/custody.ts +34 -0
  141. package/src/client/errors.test.ts +365 -0
  142. package/src/client/errors.ts +201 -0
  143. package/src/client/i18n.ts +11 -166
  144. package/src/client/index.ts +8 -1
  145. package/src/client/links.test.ts +74 -0
  146. package/src/client/links.ts +44 -0
  147. package/src/client/members.test.ts +132 -0
  148. package/src/client/members.ts +116 -0
  149. package/src/client/messages.test.ts +296 -0
  150. package/src/client/messages.ts +1424 -0
  151. package/src/client/mock.test.ts +555 -0
  152. package/src/client/mock.ts +1261 -52
  153. package/src/client/module.ts +76 -2
  154. package/src/client/pages/AssetsPage.svelte +638 -145
  155. package/src/client/permissions.ts +8 -1
  156. package/src/client/price.test.ts +254 -0
  157. package/src/client/price.ts +279 -0
  158. package/src/client/query.test.ts +58 -0
  159. package/src/client/query.ts +51 -2
  160. package/src/client/repairs.test.ts +38 -0
  161. package/src/client/repairs.ts +38 -0
  162. package/src/client/settings/CategoriesSettings.svelte +421 -0
  163. package/src/client/settings/GeneralSettings.svelte +403 -0
  164. package/src/client/status.ts +29 -0
  165. package/src/client/timeline.test.ts +175 -0
  166. package/src/client/timeline.ts +206 -0
  167. package/src/client/widgets/OverviewWidget.svelte +140 -26
  168. package/src/client/widgets/RepairsWidget.svelte +124 -0
  169. package/src/contract/capabilities.ts +99 -0
  170. package/src/contract/events.ts +83 -0
  171. package/src/contract/index.ts +16 -0
  172. package/src/contract/models.ts +360 -0
  173. package/src/contract/notifications.ts +73 -0
  174. package/src/contract/permissions.ts +79 -0
  175. package/src/contract/router.ts +300 -0
  176. package/src/contract/settings.ts +50 -0
  177. package/src/module.test.ts +330 -7
  178. package/src/server/index.ts +318 -8
  179. package/src/server/inventory.int.test.ts +4374 -0
  180. package/src/server/jobs.ts +444 -0
  181. package/src/server/migrations.test.ts +251 -0
  182. package/src/server/router.ts +574 -0
  183. package/src/server/schema.ts +184 -10
  184. package/src/server/services/assets.ts +528 -0
  185. package/src/server/services/attachments.ts +215 -0
  186. package/src/server/services/audience.ts +77 -0
  187. package/src/server/services/categories.ts +136 -0
  188. package/src/server/services/cursor.ts +104 -0
  189. package/src/server/services/custody.ts +471 -0
  190. package/src/server/services/db-errors.ts +42 -0
  191. package/src/server/services/index.ts +56 -0
  192. package/src/server/services/members.ts +54 -0
  193. package/src/server/services/notify.ts +196 -0
  194. package/src/server/services/offboarding.ts +150 -0
  195. package/src/server/services/repairs.ts +567 -0
  196. package/src/server/services/search.ts +166 -0
  197. package/src/server/services/stats.ts +88 -0
  198. package/src/server/services/status.test.ts +34 -0
  199. package/src/server/services/status.ts +143 -0
  200. package/tsconfig.base.json +22 -0
  201. package/tsconfig.client.json +1 -1
  202. package/tsconfig.json +1 -1
  203. package/vitest.config.ts +18 -3
  204. package/dist/contract.d.ts +0 -387
  205. package/dist/contract.d.ts.map +0 -1
  206. package/dist/contract.js +0 -119
  207. package/dist/contract.js.map +0 -1
  208. package/dist/server/_impl.d.ts +0 -427
  209. package/dist/server/_impl.d.ts.map +0 -1
  210. package/dist/server/_impl.js +0 -204
  211. package/dist/server/_impl.js.map +0 -1
  212. package/src/contract.ts +0 -143
  213. package/src/server/_impl.ts +0 -275
@@ -0,0 +1,215 @@
1
+ import type { core } from '@kernhq/contracts'
2
+ import { KernError, type Kernel, type Tx, uuidv7 } from '@kernhq/kernel'
3
+ import { and, asc, eq } from 'drizzle-orm'
4
+ import type { Attachment as AttachmentModel } from '../../contract/models.js'
5
+ import { assets, attachments, repairs } from '../schema.js'
6
+ import type { HistoryInput, NotifyService } from './notify.js'
7
+
8
+ type Row = typeof attachments.$inferSelect
9
+
10
+ /** What this module copies out of core's file record, and all it copies. */
11
+ export interface FileFacts {
12
+ id: string
13
+ name: string
14
+ mimeType: string | null
15
+ size: number | null
16
+ }
17
+
18
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
19
+ export function toAttachment(row: Row): AttachmentModel {
20
+ return {
21
+ id: row.id,
22
+ workspaceId: row.workspaceId as AttachmentModel['workspaceId'],
23
+ assetId: row.assetId,
24
+ repairId: row.repairId,
25
+ fileId: row.fileId,
26
+ name: row.name,
27
+ mimeType: row.mimeType,
28
+ size: row.size,
29
+ uploadedBy: row.uploadedBy,
30
+ createdAt: row.createdAt.toISOString(),
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Files kept against an asset — receipts, warranties, manuals, a repair invoice.
36
+ *
37
+ * **A module does not upload, and this class is what that sentence means in code.** The browser
38
+ * sends the bytes to core's file service and is handed an id; this records that the asset has that
39
+ * file, with the name and size copied at attach time so a list can be drawn without asking core once
40
+ * per row. Nothing here streams, signs, stores or deletes a byte — `remove` detaches, because the
41
+ * same file may be attached elsewhere and a module has no standing to destroy another module's row.
42
+ *
43
+ * The copied name is a snapshot on purpose: renaming a file in core does not rename it here, which
44
+ * is the same trade every module makes when it copies a label rather than joining across a schema
45
+ * boundary. What it buys is a files list that is one query rather than one query plus a call per row.
46
+ */
47
+ export class AttachmentService {
48
+ constructor(
49
+ private readonly kernel: Kernel,
50
+ private readonly notify: NotifyService,
51
+ ) {}
52
+
53
+ /**
54
+ * What core knows about these files — **called before the transaction opens, never inside one.**
55
+ *
56
+ * `kernel.call` is a request to another service over the broker, and awaiting one while holding a
57
+ * pooled connection is the failure `AssetService.codeFormat` documents: the pool starves under
58
+ * concurrent writes, and an attach fails outright whenever core is briefly away. So the router
59
+ * gathers the facts first and hands them to `add`, which does nothing but write.
60
+ *
61
+ * Two checks, and the first one is the one that matters: **a file has to belong to this
62
+ * workspace.** The id arrives in the request, so without this a member of one workspace could
63
+ * attach another workspace's file and read its name and size back out of the list — the module
64
+ * boundary does not help here, because core answers this module as a service.
65
+ */
66
+ async describe(workspaceId: string, fileIds: readonly string[]): Promise<FileFacts[]> {
67
+ const unique = [...new Set(fileIds)]
68
+ const found = await Promise.all(
69
+ unique.map(async (id) => {
70
+ const file = await this.kernel.call<core.FileObject | null>('core.files.get', { id })
71
+ if (!file || file.workspaceId !== workspaceId)
72
+ throw KernError.badRequest('That file is not one this workspace can attach.')
73
+ if (file.status !== 'ready') throw KernError.badRequest('That file has not finished uploading yet.')
74
+ return {
75
+ id: file.id,
76
+ name: file.name,
77
+ mimeType: file.mimeType || null,
78
+ size: typeof file.size === 'number' ? file.size : null,
79
+ }
80
+ }),
81
+ )
82
+ return found
83
+ }
84
+
85
+ /**
86
+ * Every file on one asset, its repairs' included, oldest first.
87
+ *
88
+ * Not paged and not filtered by repair: one asset's files are bounded by how much paperwork one
89
+ * item collects, and the panel groups them in the browser. That is the one case where filtering
90
+ * client-side is right — the list is entirely loaded — and it is the opposite of what a paged
91
+ * asset list may do.
92
+ */
93
+ async list(tx: Tx, workspaceId: string, assetId: string): Promise<AttachmentModel[]> {
94
+ const rows = await tx
95
+ .select()
96
+ .from(attachments)
97
+ .where(and(eq(attachments.workspaceId, workspaceId), eq(attachments.assetId, assetId)))
98
+ .orderBy(asc(attachments.createdAt), asc(attachments.id))
99
+ return rows.map(toAttachment)
100
+ }
101
+
102
+ /**
103
+ * Record that this asset has these files.
104
+ *
105
+ * `onConflictDoNothing` on `(asset_id, file_id)`: attaching the same file to the same asset twice
106
+ * is not an error worth refusing — somebody pressed the button twice, or dropped the same receipt
107
+ * in again — and the second attempt simply adds nothing. The rows that *were* inserted come back,
108
+ * so the caller announces exactly what changed.
109
+ *
110
+ * An archived asset is deliberately allowed: finding the receipt for something you retired last
111
+ * month is a reason to file it, not a reason to be refused.
112
+ */
113
+ async add(
114
+ tx: Tx,
115
+ workspaceId: string,
116
+ actorId: string | null,
117
+ assetId: string,
118
+ repairId: string | null,
119
+ files: readonly FileFacts[],
120
+ ): Promise<{ rows: Row[]; activities: HistoryInput[] }> {
121
+ await this.requireAsset(tx, workspaceId, assetId)
122
+ if (repairId) await this.requireRepair(tx, workspaceId, assetId, repairId)
123
+ if (!files.length) return { rows: [], activities: [] }
124
+
125
+ const inserted = await tx
126
+ .insert(attachments)
127
+ .values(
128
+ files.map((file) => ({
129
+ id: uuidv7(),
130
+ workspaceId,
131
+ assetId,
132
+ repairId,
133
+ fileId: file.id,
134
+ name: file.name,
135
+ mimeType: file.mimeType,
136
+ size: file.size,
137
+ uploadedBy: actorId,
138
+ })),
139
+ )
140
+ .onConflictDoNothing({ target: [attachments.assetId, attachments.fileId] })
141
+ .returning()
142
+
143
+ /**
144
+ * One timeline entry per file, rather than one saying "3 files".
145
+ *
146
+ * A timeline is read to find out what happened to a thing, and "attached the purchase receipt"
147
+ * answers that where "attached 3 files" sends the reader looking. Attaching several at once is
148
+ * rare enough that the extra rows cost nothing.
149
+ */
150
+ const activities: HistoryInput[] = inserted.map((row) => ({
151
+ workspaceId,
152
+ assetId,
153
+ actorId,
154
+ action: 'attachment_added',
155
+ data: {
156
+ attachmentId: row.id,
157
+ name: row.name,
158
+ ...(row.repairId ? { repairId: row.repairId } : {}),
159
+ },
160
+ }))
161
+ for (const activity of activities) await this.notify.history(tx, activity)
162
+ return { rows: inserted, activities }
163
+ }
164
+
165
+ /** Detach one file. Core's copy of it is untouched — see the class docblock. */
166
+ async remove(
167
+ tx: Tx,
168
+ workspaceId: string,
169
+ actorId: string | null,
170
+ attachmentId: string,
171
+ ): Promise<{ row: Row; activity: HistoryInput }> {
172
+ const [row] = await tx
173
+ .select()
174
+ .from(attachments)
175
+ .where(and(eq(attachments.workspaceId, workspaceId), eq(attachments.id, attachmentId)))
176
+ if (!row) throw KernError.notFound('Attachment')
177
+
178
+ // Filtered by workspace as well as by id, like every other write in this module: `core`
179
+ // connects as a superuser with RLS bypassed, so the predicate in the statement is the only
180
+ // barrier there is, and a barrier that holds only because of what an earlier statement happened
181
+ // to do is not one.
182
+ await tx
183
+ .delete(attachments)
184
+ .where(and(eq(attachments.workspaceId, workspaceId), eq(attachments.id, attachmentId)))
185
+
186
+ const activity: HistoryInput = {
187
+ workspaceId,
188
+ assetId: row.assetId,
189
+ actorId,
190
+ action: 'attachment_removed',
191
+ data: { attachmentId: row.id, name: row.name },
192
+ }
193
+ await this.notify.history(tx, activity)
194
+ return { row, activity }
195
+ }
196
+
197
+ private async requireAsset(tx: Tx, workspaceId: string, assetId: string): Promise<void> {
198
+ const [row] = await tx
199
+ .select({ id: assets.id })
200
+ .from(assets)
201
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
202
+ if (!row) throw KernError.notFound('Asset')
203
+ }
204
+
205
+ /** A repair the file is filed under has to be one of *this* asset's, not merely one that exists. */
206
+ private async requireRepair(tx: Tx, workspaceId: string, assetId: string, repairId: string): Promise<void> {
207
+ const [row] = await tx
208
+ .select({ id: repairs.id })
209
+ .from(repairs)
210
+ .where(
211
+ and(eq(repairs.workspaceId, workspaceId), eq(repairs.id, repairId), eq(repairs.assetId, assetId)),
212
+ )
213
+ if (!row) throw KernError.notFound('Repair')
214
+ }
215
+ }
@@ -0,0 +1,77 @@
1
+ import type { BuiltinRole, Principal } from '@kernhq/contracts'
2
+ import type { Kernel } from '@kernhq/kernel'
3
+
4
+ /**
5
+ * Who to tell when the thing that happened belongs to the workspace rather than to a person.
6
+ *
7
+ * Custody notifications have an obvious recipient — the person the item was handed to. A warranty
8
+ * running out on a spare in a cupboard, or a repair nobody has chased, does not: it belongs to
9
+ * whoever looks after the register. There is no "the office manager" field, and inventing one would
10
+ * be a setting somebody has to fill in before the feature works at all, so the question is asked of
11
+ * the permission system instead: **who may actually do the thing this message is asking for.**
12
+ *
13
+ * A warranty notice asks somebody to renew or replace, which is `inventory.asset.manage`. An overdue
14
+ * repair asks somebody to chase the vendor, which is `inventory.repair.manage`. Somebody leaving
15
+ * with a laptop asks somebody to take it back, which is `inventory.custody.manage`. Each message
16
+ * names the key it needs rather than settling for "the admins", because a workspace that gave its
17
+ * office manager a custom role did that on purpose.
18
+ */
19
+
20
+ /** Most senior first, so the cap below keeps the people most likely to act. */
21
+ const ROLE_RANK: Record<BuiltinRole, number> = { owner: 3, admin: 2, member: 1, guest: 0 }
22
+
23
+ /**
24
+ * How many people one workspace-level notification may reach.
25
+ *
26
+ * A message sent to five thousand people is not a notification, it is a mailing list nobody reads —
27
+ * and on a large instance every member holds `inventory.asset.manage` by default, so an uncapped
28
+ * audience would be exactly that. Twenty is well past any real "who looks after the register" group
29
+ * and small enough that the check below stays a handful of calls rather than one per seat.
30
+ *
31
+ * The cap is applied **after** sorting by role, so the people it keeps are the senior ones rather
32
+ * than whichever rows the database happened to return first.
33
+ */
34
+ const RECIPIENT_CAP = 20
35
+
36
+ interface Member {
37
+ userId: string
38
+ role: BuiltinRole
39
+ }
40
+
41
+ /**
42
+ * The members of a workspace who genuinely hold a permission.
43
+ *
44
+ * Genuinely, not "hold the role it defaults to": `kernel.authz.can` reads custom roles and scope
45
+ * bindings as well as the built-in defaults, so a workspace that took `inventory.repair.manage` away
46
+ * from `member` and gave it to one custom role is answered correctly. Guessing from the role would
47
+ * have been one local call instead of a handful, and would have quietly told the wrong people.
48
+ *
49
+ * Every failure here is swallowed: this decides an audience for a best-effort notification, and a
50
+ * member whose principal core cannot produce right now is one fewer recipient, not a reason for a
51
+ * nightly sweep to stop half-way through a workspace.
52
+ */
53
+ export async function membersWithPermission(
54
+ kernel: Kernel,
55
+ workspaceId: string,
56
+ permission: string,
57
+ ): Promise<string[]> {
58
+ const members = await kernel
59
+ .call<Member[]>('core.workspaces.members', { workspaceId })
60
+ .catch(() => [] as Member[])
61
+
62
+ const ordered = [...members].sort((a, b) => (ROLE_RANK[b.role] ?? 0) - (ROLE_RANK[a.role] ?? 0))
63
+
64
+ const allowed: string[] = []
65
+ for (const member of ordered) {
66
+ if (allowed.length >= RECIPIENT_CAP) break
67
+ const principal = await kernel
68
+ .call<Principal | null>('core.users.principal', { userId: member.userId })
69
+ .catch(() => null)
70
+ if (!principal) continue
71
+ const can = await kernel.authz
72
+ .can(principal, permission, { kind: 'workspace', workspaceId })
73
+ .catch(() => false)
74
+ if (can) allowed.push(member.userId)
75
+ }
76
+ return allowed
77
+ }
@@ -0,0 +1,136 @@
1
+ import { KernError, type Tx, uuidv7 } from '@kernhq/kernel'
2
+ import { and, asc, eq, isNull } from 'drizzle-orm'
3
+ import type { Category as CategoryModel } from '../../contract/models.js'
4
+ import { categories } from '../schema.js'
5
+ import { violated } from './db-errors.js'
6
+
7
+ type Row = typeof categories.$inferSelect
8
+
9
+ /** The unique index `0000_init.sql` put on (workspace_id, name). */
10
+ const NAME_TAKEN = 'inventory_categories_ws_name_uq'
11
+
12
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
13
+ export function toCategory(row: Row): CategoryModel {
14
+ return {
15
+ id: row.id,
16
+ workspaceId: row.workspaceId as CategoryModel['workspaceId'],
17
+ name: row.name,
18
+ order: row.order,
19
+ createdAt: row.createdAt.toISOString(),
20
+ updatedAt: row.updatedAt.toISOString(),
21
+ archivedAt: row.archivedAt?.toISOString() ?? null,
22
+ }
23
+ }
24
+
25
+ /**
26
+ * How a workspace groups what it owns.
27
+ *
28
+ * Small on purpose. A category is a name and a position in a list; everything interesting about an
29
+ * asset belongs to the asset. The one thing here worth reading twice is that nothing deletes — see
30
+ * `archive` below.
31
+ */
32
+ export class CategoryService {
33
+ /**
34
+ * Ordered by `order` and then by name, which is what makes a workspace that never touches the
35
+ * order field still get an alphabetical picker rather than an arbitrary one — every row has
36
+ * `order` 0, so the tiebreak is doing all the work and has to be a name rather than an id.
37
+ */
38
+ async list(tx: Tx, workspaceId: string, includeArchived: boolean): Promise<CategoryModel[]> {
39
+ const filters = [eq(categories.workspaceId, workspaceId)]
40
+ if (!includeArchived) filters.push(isNull(categories.archivedAt))
41
+ const rows = await tx
42
+ .select()
43
+ .from(categories)
44
+ .where(and(...filters))
45
+ .orderBy(asc(categories.order), asc(categories.name))
46
+ return rows.map(toCategory)
47
+ }
48
+
49
+ async get(tx: Tx, workspaceId: string, categoryId: string): Promise<Row> {
50
+ const [row] = await tx
51
+ .select()
52
+ .from(categories)
53
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
54
+ if (!row) throw KernError.notFound('Category')
55
+ return row
56
+ }
57
+
58
+ /**
59
+ * A duplicate name is a `CONFLICT` with the name in it, never a 500.
60
+ *
61
+ * The unique index is what actually decides — checking first and inserting after is a race that
62
+ * two people adding "Laptops" at once will find — so the check is the insert, and the driver's
63
+ * 23505 is translated into a sentence rather than shown as "Failed query: insert into
64
+ * mod_inventory.categories …".
65
+ */
66
+ async create(tx: Tx, workspaceId: string, name: string, order: number): Promise<Row> {
67
+ try {
68
+ const [row] = await tx.insert(categories).values({ id: uuidv7(), workspaceId, name, order }).returning()
69
+ return row!
70
+ } catch (err) {
71
+ throw CategoryService.nameTaken(err, name)
72
+ }
73
+ }
74
+
75
+ async update(
76
+ tx: Tx,
77
+ workspaceId: string,
78
+ categoryId: string,
79
+ patch: { name?: string; order?: number },
80
+ ): Promise<Row> {
81
+ const previous = await this.get(tx, workspaceId, categoryId)
82
+ // `undefined` means "not mentioned". Neither field is nullable, so there is no "clear it" here
83
+ // and no reason for the `null`-versus-`undefined` care `assets.update` needs.
84
+ const values = {
85
+ name: patch.name ?? previous.name,
86
+ order: patch.order ?? previous.order,
87
+ updatedAt: new Date(),
88
+ }
89
+ try {
90
+ const [row] = await tx
91
+ .update(categories)
92
+ .set(values)
93
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
94
+ .returning()
95
+ return row!
96
+ } catch (err) {
97
+ throw CategoryService.nameTaken(err, values.name)
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Archive and restore, which are one procedure because they are one column.
103
+ *
104
+ * **Nothing here deletes, and that is the decision this file exists to record.**
105
+ * `assets.category_id` carries no foreign key — a module keeps its ids plain — so a delete would
106
+ * leave every asset filed under this category pointing at a row that is not there: a blank column
107
+ * on the row, a picker that cannot explain what the asset used to be, and an `asset_history`
108
+ * entry saying "category changed to <nothing>". None of it recoverable, all of it caused by a
109
+ * settings screen. An archived category disappears from every picker and every filter and leaves
110
+ * each asset able to say what it is.
111
+ */
112
+ async archive(tx: Tx, workspaceId: string, categoryId: string, archived: boolean): Promise<Row> {
113
+ const [row] = await tx
114
+ .update(categories)
115
+ .set({ archivedAt: archived ? new Date() : null, updatedAt: new Date() })
116
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
117
+ .returning()
118
+ if (!row) throw KernError.notFound('Category')
119
+ return row
120
+ }
121
+
122
+ /**
123
+ * The unique index refused it, or something else did and must not be disguised.
124
+ *
125
+ * Rethrowing the original for anything that is not this constraint matters: turning every failed
126
+ * insert into "that name is taken" would hide a real fault behind a sentence a person would act
127
+ * on by renaming something, for ever.
128
+ */
129
+ private static nameTaken(err: unknown, name: string): unknown {
130
+ if (!violated(err, NAME_TAKEN)) return err
131
+ return KernError.conflict(
132
+ `This workspace already has a category called “${name}”.`,
133
+ 'inventory.category.name_taken',
134
+ )
135
+ }
136
+ }
@@ -0,0 +1,104 @@
1
+ import { KernError } from '@kernhq/kernel'
2
+
3
+ /**
4
+ * The one page boundary this module issues, for every list it pages.
5
+ *
6
+ * **The bookmarked row's id, and the sort it was issued under.** Nothing else — in particular not
7
+ * the sort key itself, which is what it used to carry. That earlier shape (`{k: <sort key>, i:
8
+ * <id>}`) was wrong three separate ways, each of them reachable by anyone who could type into the
9
+ * address bar:
10
+ *
11
+ * - **It could not be trusted.** `decode` checked only that `i` was a *string*, and `i` is
12
+ * interpolated into `(col, id) < ($1, $2::uuid)`. `{"k":"x","i":"not-a-uuid"}` therefore
13
+ * reached Postgres as a 22P02 nobody caught — an unhandled 500 and an error-level log line per
14
+ * request, at the 600-a-minute the rate limiter allows.
15
+ * - **It was not bound to its sort.** A cursor issued under `sort=recent` replayed under
16
+ * `sort=code` compared a uuid against a code, so page two came back equal to page one and
17
+ * "Load more" never ended.
18
+ * - **It was unbounded.** `sort=name` on a 200-character Persian name encoded to 602 characters,
19
+ * and `Cursor` in `@kernhq/contracts` is `max(512)` — so a long enough name broke "Load more"
20
+ * with a validation error, in exactly the locales least likely to be tested.
21
+ *
22
+ * Carrying the id alone and reading the sort key back from that row in SQL answers all three: the
23
+ * cursor is a fixed ~60 characters whatever the name, a value that is not a uuid is refused before
24
+ * it is anywhere near the database, and a cursor whose sort disagrees with the request is refused
25
+ * rather than quietly misread. Base64 so nothing in the product is tempted to read it — it is a
26
+ * bookmark, not an offset, and its shape is this file's business.
27
+ *
28
+ * It lives here rather than in `assets.ts` because the repair list pages too, and a second bookmark
29
+ * format would be a second set of those three bugs. `src/client/mock.ts` mirrors this byte for
30
+ * byte; read them as one pair and change them as one pair.
31
+ *
32
+ * The asset timeline is the one list that does **not** use this one: it is ordered by a sequence
33
+ * rather than by a row id, so its bookmark is `SeqBookmark` below.
34
+ */
35
+ export interface Bookmark<S extends string> {
36
+ i: string
37
+ s: S
38
+ }
39
+
40
+ export const encodeMark = <S extends string>(mark: Bookmark<S>): string =>
41
+ Buffer.from(JSON.stringify(mark), 'utf8').toString('base64url')
42
+
43
+ /** Cheap and total, and it runs before the value can reach a `::uuid` cast. */
44
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
45
+
46
+ export function decodeMark<S extends string>(cursor: string, sort: S): Bookmark<S> {
47
+ const refuse = () => KernError.badRequest('That page marker is not one this list issued')
48
+ let parsed: Partial<Bookmark<S>> | null
49
+ try {
50
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<Bookmark<S>> | null
51
+ } catch {
52
+ throw refuse()
53
+ }
54
+ if (typeof parsed?.i !== 'string' || !UUID.test(parsed.i)) throw refuse()
55
+ // One comparison covers both a sort this list never issues and a sort it issued under a
56
+ // *different* request. Either way the bookmark cannot be read against the ordering asked for,
57
+ // and pretending otherwise is what made "Load more" loop for ever.
58
+ if (parsed.s !== sort) throw refuse()
59
+ return { i: parsed.i, s: sort }
60
+ }
61
+
62
+ /**
63
+ * The other page boundary: a row's **sequence number**, and the sort it was issued under.
64
+ *
65
+ * The asset timeline is ordered by `asset_history.seq` rather than by the row id, because a uuidv7
66
+ * is only ordered to the millisecond and two entries written inside one — an attach and a detach, a
67
+ * create and its first entry — sort by ten random bytes. `schema.ts` argues that at the column. A
68
+ * bookmark into that ordering has to name the sequence value, so it is a number rather than a uuid
69
+ * and needs its own codec: handing `decodeMark` a number would have it refused as "not a uuid", and
70
+ * relaxing `decodeMark` to accept either is how one of the two shapes ends up unvalidated.
71
+ *
72
+ * It keeps all three properties the uuid bookmark has, and for the same reasons:
73
+ *
74
+ * - **bounded** — a base64url of `{"n":<integer>,"s":"recent"}` is around forty characters
75
+ * whatever the row, well inside `Cursor`'s `max(512)` in `@kernhq/contracts`;
76
+ * - **checked before it reaches SQL** — anything that is not a safe positive integer is refused
77
+ * here rather than interpolated into a `bigint` comparison for Postgres to reject as a 22P02;
78
+ * - **bound to its sort** — a bookmark issued under one ordering is meaningless under another,
79
+ * and reading it anyway is what made "Load more" loop for ever.
80
+ *
81
+ * `Number.isSafeInteger` is the upper bound as well as the type check: the column is a `bigint` and
82
+ * the sequence would have to hand out nine quadrillion history rows to reach it, but a cursor
83
+ * arrives from outside and `JSON.parse` will happily produce `1e400`.
84
+ */
85
+ export interface SeqBookmark<S extends string> {
86
+ n: number
87
+ s: S
88
+ }
89
+
90
+ export const encodeSeqMark = <S extends string>(mark: SeqBookmark<S>): string =>
91
+ Buffer.from(JSON.stringify(mark), 'utf8').toString('base64url')
92
+
93
+ export function decodeSeqMark<S extends string>(cursor: string, sort: S): SeqBookmark<S> {
94
+ const refuse = () => KernError.badRequest('That page marker is not one this list issued')
95
+ let parsed: Partial<SeqBookmark<S>> | null
96
+ try {
97
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<SeqBookmark<S>> | null
98
+ } catch {
99
+ throw refuse()
100
+ }
101
+ if (typeof parsed?.n !== 'number' || !Number.isSafeInteger(parsed.n) || parsed.n < 1) throw refuse()
102
+ if (parsed.s !== sort) throw refuse()
103
+ return { n: parsed.n, s: sort }
104
+ }