@kernhq/module-inventory 0.2.0 → 0.4.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 (198) hide show
  1. package/README.md +106 -25
  2. package/dist/contract/capabilities.d.ts +4 -4
  3. package/dist/contract/capabilities.d.ts.map +1 -1
  4. package/dist/contract/capabilities.js +51 -9
  5. package/dist/contract/capabilities.js.map +1 -1
  6. package/dist/contract/events.d.ts +43 -0
  7. package/dist/contract/events.d.ts.map +1 -1
  8. package/dist/contract/events.js +40 -0
  9. package/dist/contract/events.js.map +1 -1
  10. package/dist/contract/index.d.ts +1 -0
  11. package/dist/contract/index.d.ts.map +1 -1
  12. package/dist/contract/index.js +1 -0
  13. package/dist/contract/index.js.map +1 -1
  14. package/dist/contract/models.d.ts +345 -0
  15. package/dist/contract/models.d.ts.map +1 -1
  16. package/dist/contract/models.js +245 -0
  17. package/dist/contract/models.js.map +1 -1
  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 +52 -2
  23. package/dist/contract/permissions.d.ts.map +1 -1
  24. package/dist/contract/permissions.js +55 -2
  25. package/dist/contract/permissions.js.map +1 -1
  26. package/dist/contract/router.d.ts +1108 -0
  27. package/dist/contract/router.d.ts.map +1 -1
  28. package/dist/contract/router.js +253 -1
  29. package/dist/contract/router.js.map +1 -1
  30. package/dist/contract/settings.d.ts +2 -0
  31. package/dist/contract/settings.d.ts.map +1 -1
  32. package/dist/contract/settings.js +24 -4
  33. package/dist/contract/settings.js.map +1 -1
  34. package/dist/server/index.d.ts +8 -4
  35. package/dist/server/index.d.ts.map +1 -1
  36. package/dist/server/index.js +289 -5
  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 +1392 -0
  43. package/dist/server/router.d.ts.map +1 -1
  44. package/dist/server/router.js +385 -7
  45. package/dist/server/router.js.map +1 -1
  46. package/dist/server/schema.d.ts +134 -1
  47. package/dist/server/schema.d.ts.map +1 -1
  48. package/dist/server/schema.js +169 -4
  49. package/dist/server/schema.js.map +1 -1
  50. package/dist/server/services/assets.d.ts +69 -3
  51. package/dist/server/services/assets.d.ts.map +1 -1
  52. package/dist/server/services/assets.js +199 -31
  53. package/dist/server/services/assets.js.map +1 -1
  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 +157 -0
  63. package/dist/server/services/categories.d.ts.map +1 -0
  64. package/dist/server/services/categories.js +309 -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 +16 -0
  79. package/dist/server/services/index.d.ts.map +1 -1
  80. package/dist/server/services/index.js +25 -1
  81. package/dist/server/services/index.js.map +1 -1
  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 +43 -1
  87. package/dist/server/services/notify.d.ts.map +1 -1
  88. package/dist/server/services/notify.js +47 -5
  89. package/dist/server/services/notify.js.map +1 -1
  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/0002_custody_and_categories.sql +23 -0
  111. package/migrations/0003_repairs.sql +23 -0
  112. package/migrations/0004_platform_surfaces.sql +51 -0
  113. package/migrations/0005_repair_dates.sql +35 -0
  114. package/migrations/0006_workspace_registry_read.sql +50 -0
  115. package/migrations/0007_history_sequence.sql +83 -0
  116. package/migrations/0008_category_order_unique.sql +71 -0
  117. package/migrations/meta/0002_snapshot.json +1054 -0
  118. package/migrations/meta/0003_snapshot.json +1070 -0
  119. package/migrations/meta/0004_snapshot.json +1130 -0
  120. package/migrations/meta/0005_snapshot.json +1135 -0
  121. package/migrations/meta/_journal.json +49 -0
  122. package/package.json +2 -1
  123. package/src/client/api-instance.ts +27 -2
  124. package/src/client/bidi.test.ts +148 -0
  125. package/src/client/bidi.ts +85 -0
  126. package/src/client/components/AssetDetailPanel.svelte +614 -0
  127. package/src/client/components/AssetFormDialog.svelte +71 -22
  128. package/src/client/components/AssetPhoto.svelte +178 -0
  129. package/src/client/components/AttachmentsSection.svelte +327 -0
  130. package/src/client/components/CustodyDialog.svelte +201 -0
  131. package/src/client/components/RepairDialog.svelte +271 -0
  132. package/src/client/components/RepairsSection.svelte +318 -0
  133. package/src/client/components/Timeline.svelte +347 -0
  134. package/src/client/components/TimelineText.svelte +124 -0
  135. package/src/client/core-api.ts +71 -0
  136. package/src/client/custody.test.ts +31 -0
  137. package/src/client/custody.ts +34 -0
  138. package/src/client/errors.test.ts +395 -0
  139. package/src/client/errors.ts +229 -0
  140. package/src/client/links.test.ts +74 -0
  141. package/src/client/links.ts +44 -0
  142. package/src/client/members.test.ts +132 -0
  143. package/src/client/members.ts +116 -0
  144. package/src/client/messages.test.ts +127 -0
  145. package/src/client/messages.ts +1106 -18
  146. package/src/client/mock.test.ts +465 -1
  147. package/src/client/mock.ts +1105 -79
  148. package/src/client/module.ts +73 -1
  149. package/src/client/pages/AssetsPage.svelte +317 -45
  150. package/src/client/permissions.ts +7 -0
  151. package/src/client/price.test.ts +151 -3
  152. package/src/client/price.ts +155 -11
  153. package/src/client/query.ts +36 -0
  154. package/src/client/reorder.test.ts +100 -0
  155. package/src/client/reorder.ts +79 -0
  156. package/src/client/repairs.test.ts +38 -0
  157. package/src/client/repairs.ts +38 -0
  158. package/src/client/sequence.test.ts +248 -0
  159. package/src/client/sequence.ts +185 -0
  160. package/src/client/settings/CategoriesSettings.svelte +746 -0
  161. package/src/client/settings/GeneralSettings.svelte +0 -0
  162. package/src/client/status.ts +29 -0
  163. package/src/client/timeline.test.ts +175 -0
  164. package/src/client/timeline.ts +206 -0
  165. package/src/client/widgets/OverviewWidget.svelte +127 -26
  166. package/src/client/widgets/RepairsWidget.svelte +124 -0
  167. package/src/contract/capabilities.ts +53 -9
  168. package/src/contract/events.ts +49 -0
  169. package/src/contract/index.ts +1 -0
  170. package/src/contract/models.ts +270 -0
  171. package/src/contract/notifications.ts +73 -0
  172. package/src/contract/permissions.ts +55 -2
  173. package/src/contract/router.ts +284 -1
  174. package/src/contract/settings.ts +24 -4
  175. package/src/module.test.ts +217 -4
  176. package/src/server/index.ts +311 -4
  177. package/src/server/inventory.int.test.ts +4109 -19
  178. package/src/server/jobs.ts +444 -0
  179. package/src/server/migrations.test.ts +253 -2
  180. package/src/server/router.ts +486 -6
  181. package/src/server/schema.ts +171 -3
  182. package/src/server/services/assets.ts +214 -54
  183. package/src/server/services/attachments.ts +215 -0
  184. package/src/server/services/audience.ts +77 -0
  185. package/src/server/services/categories.ts +337 -0
  186. package/src/server/services/cursor.ts +104 -0
  187. package/src/server/services/custody.ts +471 -0
  188. package/src/server/services/db-errors.ts +42 -0
  189. package/src/server/services/index.ts +34 -1
  190. package/src/server/services/members.ts +54 -0
  191. package/src/server/services/notify.ts +52 -7
  192. package/src/server/services/offboarding.ts +150 -0
  193. package/src/server/services/repairs.ts +567 -0
  194. package/src/server/services/search.ts +166 -0
  195. package/src/server/services/stats.ts +88 -0
  196. package/src/server/services/status.test.ts +34 -0
  197. package/src/server/services/status.ts +143 -0
  198. package/src/client/settings/core-api.ts +0 -32
@@ -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,337 @@
1
+ import { KernError, type Tx, uuidv7 } from '@kernhq/kernel'
2
+ import { and, asc, count, eq, isNull, sql } from 'drizzle-orm'
3
+ import { type Category as CategoryModel, MAX_LIVE_CATEGORIES } 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
+ /** What `reorder` returns: the live sequence as it now stands, and which rows actually moved. */
13
+ export interface Reordered {
14
+ rows: Row[]
15
+ /** Only the ids whose `order` changed — a change event for a row that did not move is a lie. */
16
+ moved: string[]
17
+ }
18
+
19
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
20
+ export function toCategory(row: Row): CategoryModel {
21
+ return {
22
+ id: row.id,
23
+ workspaceId: row.workspaceId as CategoryModel['workspaceId'],
24
+ name: row.name,
25
+ order: row.order,
26
+ createdAt: row.createdAt.toISOString(),
27
+ updatedAt: row.updatedAt.toISOString(),
28
+ archivedAt: row.archivedAt?.toISOString() ?? null,
29
+ }
30
+ }
31
+
32
+ /**
33
+ * How a workspace groups what it owns.
34
+ *
35
+ * Small on purpose. A category is a name and a position in a list; everything interesting about an
36
+ * asset belongs to the asset. The one thing here worth reading twice is that nothing deletes — see
37
+ * `archive` below.
38
+ */
39
+ export class CategoryService {
40
+ /**
41
+ * Ordered by `order` and then by name.
42
+ *
43
+ * `order` is the sequence somebody dragged their categories into, and no two **live** categories
44
+ * share a number: `inventory_categories_ws_order_live_uq` is what makes that true rather than
45
+ * intended. So for the live set the tiebreak never fires.
46
+ *
47
+ * It stays because `list` also reads the archived rows, and those are outside the index: an
48
+ * archived category keeps the number it had when it left, and the very next reorder renumbers a
49
+ * live row onto it. A duplicate must sort the same way twice, and a name is the only column a
50
+ * person could predict.
51
+ */
52
+ async list(tx: Tx, workspaceId: string, includeArchived: boolean): Promise<CategoryModel[]> {
53
+ const filters = [eq(categories.workspaceId, workspaceId)]
54
+ if (!includeArchived) filters.push(isNull(categories.archivedAt))
55
+ const rows = await tx
56
+ .select()
57
+ .from(categories)
58
+ .where(and(...filters))
59
+ .orderBy(asc(categories.order), asc(categories.name))
60
+ return rows.map(toCategory)
61
+ }
62
+
63
+ async get(tx: Tx, workspaceId: string, categoryId: string): Promise<Row> {
64
+ const [row] = await tx
65
+ .select()
66
+ .from(categories)
67
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
68
+ if (!row) throw KernError.notFound('Category')
69
+ return row
70
+ }
71
+
72
+ /**
73
+ * A new category joins the **end** of the sequence, and a duplicate name is a `CONFLICT` with the
74
+ * name in it, never a 500.
75
+ *
76
+ * The unique index is what actually decides the name — checking first and inserting after is a
77
+ * race that two people adding "Laptops" at once will find — so the check is the insert, and the
78
+ * driver's 23505 is translated into a sentence rather than shown as "Failed query: insert into
79
+ * mod_inventory.categories …".
80
+ *
81
+ * The position is decided the same way, in the statement rather than around it. It used to be an
82
+ * optional number the caller passed and defaulted to 0, so every category anybody added landed at
83
+ * the *front*, tied with whatever was already there, and the list resolved the tie by name — a
84
+ * new category appearing in the middle of a sequence somebody had arranged by hand.
85
+ *
86
+ * **The subquery is not what makes the number unique — the lock above it is.** This used to say
87
+ * that a subquery inside the insert stopped two creates in flight from taking the same maximum,
88
+ * and that is false: under READ COMMITTED each statement takes its own snapshot, so both read a
89
+ * list without the other's row in it and both appended to the same place. `lockAppends` is what
90
+ * serialises them, and `inventory_categories_ws_order_live_uq` is what refuses the pair if
91
+ * anything ever reaches the table around it.
92
+ */
93
+ async create(tx: Tx, workspaceId: string, name: string): Promise<Row> {
94
+ await CategoryService.lockAppends(tx, workspaceId)
95
+ await CategoryService.roomForOneMore(tx, workspaceId)
96
+ try {
97
+ const [row] = await tx
98
+ .insert(categories)
99
+ .values({ id: uuidv7(), workspaceId, name, order: CategoryService.appended(workspaceId) })
100
+ .returning()
101
+ return row!
102
+ } catch (err) {
103
+ throw CategoryService.nameTaken(err, name)
104
+ }
105
+ }
106
+
107
+ /** A rename, and nothing else — the sequence is `reorder`'s to write. */
108
+ async update(tx: Tx, workspaceId: string, categoryId: string, patch: { name?: string }): Promise<Row> {
109
+ const previous = await this.get(tx, workspaceId, categoryId)
110
+ // `undefined` means "not mentioned". The column is not nullable, so there is no "clear it" here
111
+ // and no reason for the `null`-versus-`undefined` care `assets.update` needs.
112
+ const values = {
113
+ name: patch.name ?? previous.name,
114
+ updatedAt: new Date(),
115
+ }
116
+ try {
117
+ const [row] = await tx
118
+ .update(categories)
119
+ .set(values)
120
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
121
+ .returning()
122
+ return row!
123
+ } catch (err) {
124
+ throw CategoryService.nameTaken(err, values.name)
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Archive and restore, which are one procedure because they are one column.
130
+ *
131
+ * **Nothing here deletes, and that is the decision this file exists to record.**
132
+ * `assets.category_id` carries no foreign key — a module keeps its ids plain — so a delete would
133
+ * leave every asset filed under this category pointing at a row that is not there: a blank column
134
+ * on the row, a picker that cannot explain what the asset used to be, and an `asset_history`
135
+ * entry saying "category changed to <nothing>". None of it recoverable, all of it caused by a
136
+ * settings screen. An archived category disappears from every picker and every filter and leaves
137
+ * each asset able to say what it is.
138
+ *
139
+ * **A restore appends**, for the reason `create` appends. The row kept the position it had when
140
+ * it left, and every live category has been renumbered since — so putting it back where its old
141
+ * number points lands it in the middle of somebody's arrangement, tied with whatever is there
142
+ * now. The end of the list is the one place a person can find it again. Archiving leaves the
143
+ * number alone: it is out of every list that reads it, and it is about to be overwritten anyway.
144
+ *
145
+ * A restore appends, so it races exactly as `create` does and is serialised the same way — and it
146
+ * is the one place other than `create` where the live set grows, so it is the other place the
147
+ * limit is enforced. Archiving needs neither: it takes a row out of the live set, and out of the
148
+ * partial index with it.
149
+ */
150
+ async archive(tx: Tx, workspaceId: string, categoryId: string, archived: boolean): Promise<Row> {
151
+ if (!archived) {
152
+ await CategoryService.lockAppends(tx, workspaceId)
153
+ await CategoryService.roomForOneMore(tx, workspaceId)
154
+ }
155
+ const [row] = await tx
156
+ .update(categories)
157
+ .set({
158
+ archivedAt: archived ? new Date() : null,
159
+ ...(archived ? {} : { order: CategoryService.appended(workspaceId) }),
160
+ updatedAt: new Date(),
161
+ })
162
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
163
+ .returning()
164
+ if (!row) throw KernError.notFound('Category')
165
+ return row
166
+ }
167
+
168
+ /**
169
+ * The sequence, rewritten from the ids somebody put it in — the only thing that writes `order`.
170
+ *
171
+ * Three refusals before a single row is touched, and all three are the same idea: this call
172
+ * describes the whole live list, so a list that does not match the workspace is not a partial
173
+ * instruction to be completed, it is an ordering of something else.
174
+ *
175
+ * - **an id twice** — arithmetic that cannot be carried out, `BAD_REQUEST`;
176
+ * - **an id that is not this workspace's** — `NOT_FOUND`, the answer `update` and `archive`
177
+ * already give for one, and the answer that does not confirm the row exists elsewhere;
178
+ * - **a live category the list does not name, or an archived one it does** — somebody added,
179
+ * archived or restored a category while this page was open. Renumbering what was named would
180
+ * put the missing one wherever its stale number happened to land, silently. `CONFLICT` with
181
+ * `inventory.category.order_stale`, which the client turns into "reload and try again".
182
+ *
183
+ * All of it inside one transaction, opened by the router, so a refusal writes nothing and a
184
+ * renumbering is never half-applied. The `for update` is what makes two reorders arriving at once
185
+ * queue rather than interleave — without it both read the same list, both pass the check, and the
186
+ * writes of one land between the writes of the other, which is how a sequence ends up being
187
+ * neither of the two orders anybody asked for. Locking in id order is what stops two of them
188
+ * taking the same rows in opposite orders and deadlocking.
189
+ */
190
+ async reorder(tx: Tx, workspaceId: string, categoryIds: string[]): Promise<Reordered> {
191
+ const named = new Set(categoryIds)
192
+ if (named.size !== categoryIds.length)
193
+ throw KernError.badRequest('That list of categories names the same one more than once.')
194
+
195
+ const current = await tx
196
+ .select()
197
+ .from(categories)
198
+ .where(eq(categories.workspaceId, workspaceId))
199
+ .orderBy(asc(categories.id))
200
+ .for('update')
201
+ const known = new Map(current.map((row) => [row.id, row]))
202
+
203
+ if (categoryIds.some((id) => !known.has(id))) throw KernError.notFound('Category')
204
+ const live = current.filter((row) => !row.archivedAt)
205
+ if (live.some((row) => !named.has(row.id)) || categoryIds.some((id) => known.get(id)?.archivedAt))
206
+ throw KernError.conflict(
207
+ 'The categories changed while this list was open, so this order was not saved. Reload the list and arrange it again.',
208
+ 'inventory.category.order_stale',
209
+ )
210
+
211
+ // Only the rows that actually move are touched — a workspace has tens of categories, they are
212
+ // already locked, and a change event for a row whose position did not change would tell every
213
+ // screen in the workspace about a write that did not happen. `moved` is settled here, before a
214
+ // single write, so it stays the honest list whatever the two passes below do.
215
+ const now = new Date()
216
+ const going = categoryIds
217
+ .map((id, index) => ({ id, index }))
218
+ .filter(({ id, index }) => known.get(id)?.order !== index)
219
+ const moved = going.map(({ id }) => id)
220
+
221
+ /**
222
+ * Parked out of the way first, and only then put down where they belong.
223
+ *
224
+ * `inventory_categories_ws_order_live_uq` is a plain unique index, and Postgres checks one of
225
+ * those row by row rather than at the end of the statement. There is no deferrable form to reach
226
+ * for either: a unique *constraint* can be deferred and cannot be partial, and this one has to be
227
+ * partial. So the single-pass loop writes a collision the moment two rows swap — putting the
228
+ * first on 1 while the second still holds 1 — and a swap is the commonest reorder there is.
229
+ *
230
+ * `park` sits above both the highest number any row in this workspace holds **and** the last
231
+ * place in the new sequence. That is what makes the two passes safe: the parked values are
232
+ * distinct from one another and from every row staying put, and the `0…n-1` the second pass
233
+ * writes into is empty, because every live row that could have been sitting there is either
234
+ * parked or already on the number it is being given.
235
+ *
236
+ * Only the rows that actually move are written, so a reorder that shifts one row does not stamp
237
+ * `updated_at` across the whole list — and `updated_at` is left off the parking pass, which is
238
+ * bookkeeping rather than a change anybody made.
239
+ */
240
+ if (going.length > 0) {
241
+ const park = Math.max(...current.map((row) => row.order), categoryIds.length - 1) + 1
242
+ for (const [offset, { id }] of going.entries()) {
243
+ await tx
244
+ .update(categories)
245
+ .set({ order: park + offset })
246
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, id)))
247
+ }
248
+ for (const { id, index } of going) {
249
+ await tx
250
+ .update(categories)
251
+ .set({ order: index, updatedAt: now })
252
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, id)))
253
+ }
254
+ }
255
+
256
+ const rows = await tx
257
+ .select()
258
+ .from(categories)
259
+ .where(and(eq(categories.workspaceId, workspaceId), isNull(categories.archivedAt)))
260
+ .orderBy(asc(categories.order), asc(categories.name))
261
+ return { rows, moved }
262
+ }
263
+
264
+ /**
265
+ * One past the highest position this workspace has used, archived rows counted.
266
+ *
267
+ * Archived rows count because one of them can be restored, and a restored category landing on a
268
+ * live one's number is the tie this whole change exists to remove.
269
+ *
270
+ * **Only correct under `lockAppends`.** A subquery inside the write saves a round trip and settles
271
+ * nothing about concurrency: under READ COMMITTED it is evaluated against the snapshot its own
272
+ * statement started with, so two transactions appending at the same instant read the same maximum
273
+ * and take the same number. That is the defect `0008` exists for.
274
+ */
275
+ private static appended(workspaceId: string) {
276
+ return sql<number>`(select coalesce(max(${categories.order}), -1) + 1 from ${categories} where ${categories.workspaceId} = ${workspaceId})`
277
+ }
278
+
279
+ /**
280
+ * Hold the right to append to this workspace's list until the transaction ends.
281
+ *
282
+ * An advisory lock rather than `select … for update`, because the thing being protected is the
283
+ * *next* number rather than any row that exists: a workspace with no categories at all has no row
284
+ * to lock, and two creates against it would still collide. Taken per workspace, so two workspaces
285
+ * adding a category at the same moment never wait for each other.
286
+ *
287
+ * The first key is a constant for this list, so another module taking an advisory lock on the same
288
+ * workspace does not queue behind this one by accident.
289
+ *
290
+ * It cannot deadlock against `reorder`, which takes row locks and never asks for this one — so
291
+ * there is no pair of waits pointing at each other.
292
+ */
293
+ private static async lockAppends(tx: Tx, workspaceId: string): Promise<void> {
294
+ await tx.execute(
295
+ sql`select pg_advisory_xact_lock(hashtext('mod_inventory.categories.order'), hashtext(${workspaceId}))`,
296
+ )
297
+ }
298
+
299
+ /**
300
+ * Refuse the one that would take a workspace past `MAX_LIVE_CATEGORIES`, and say so.
301
+ *
302
+ * The number exists because `categories.reorder` is handed every live category at once and that
303
+ * array needs a bound. Leaving the bound only on the array is a silent ceiling: a workspace could
304
+ * pass it one category at a time and then discover that the only procedure that can order them is
305
+ * the one it can no longer call. Enforced here, the array can always name every live category a
306
+ * workspace is allowed to have.
307
+ *
308
+ * **Live rows, not every row ever made**, so that archiving one frees a place — which is what the
309
+ * refusal tells the reader to do, and the advice has to be true.
310
+ */
311
+ private static async roomForOneMore(tx: Tx, workspaceId: string): Promise<void> {
312
+ const [row] = await tx
313
+ .select({ n: count() })
314
+ .from(categories)
315
+ .where(and(eq(categories.workspaceId, workspaceId), isNull(categories.archivedAt)))
316
+ if ((row?.n ?? 0) < MAX_LIVE_CATEGORIES) return
317
+ throw KernError.conflict(
318
+ `This workspace already has ${MAX_LIVE_CATEGORIES} categories, which is as many as Inventory keeps in one order. Archive one it no longer uses to make room.`,
319
+ 'inventory.category.limit_reached',
320
+ )
321
+ }
322
+
323
+ /**
324
+ * The unique index refused it, or something else did and must not be disguised.
325
+ *
326
+ * Rethrowing the original for anything that is not this constraint matters: turning every failed
327
+ * insert into "that name is taken" would hide a real fault behind a sentence a person would act
328
+ * on by renaming something, for ever.
329
+ */
330
+ private static nameTaken(err: unknown, name: string): unknown {
331
+ if (!violated(err, NAME_TAKEN)) return err
332
+ return KernError.conflict(
333
+ `This workspace already has a category called “${name}”.`,
334
+ 'inventory.category.name_taken',
335
+ )
336
+ }
337
+ }