@kernhq/module-inventory 0.2.0 → 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 (193) hide show
  1. package/README.md +104 -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 +322 -0
  15. package/dist/contract/models.d.ts.map +1 -1
  16. package/dist/contract/models.js +213 -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 +1052 -0
  27. package/dist/contract/router.d.ts.map +1 -1
  28. package/dist/contract/router.js +225 -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 +1337 -0
  43. package/dist/server/router.d.ts.map +1 -1
  44. package/dist/server/router.js +363 -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 +158 -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 +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 +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/meta/0002_snapshot.json +1054 -0
  117. package/migrations/meta/0003_snapshot.json +1070 -0
  118. package/migrations/meta/0004_snapshot.json +1130 -0
  119. package/migrations/meta/0005_snapshot.json +1135 -0
  120. package/migrations/meta/_journal.json +42 -0
  121. package/package.json +1 -1
  122. package/src/client/api-instance.ts +27 -2
  123. package/src/client/bidi.test.ts +148 -0
  124. package/src/client/bidi.ts +85 -0
  125. package/src/client/components/AssetDetailPanel.svelte +614 -0
  126. package/src/client/components/AssetFormDialog.svelte +71 -22
  127. package/src/client/components/AssetPhoto.svelte +178 -0
  128. package/src/client/components/AttachmentsSection.svelte +327 -0
  129. package/src/client/components/CustodyDialog.svelte +201 -0
  130. package/src/client/components/RepairDialog.svelte +271 -0
  131. package/src/client/components/RepairsSection.svelte +318 -0
  132. package/src/client/components/Timeline.svelte +347 -0
  133. package/src/client/components/TimelineText.svelte +124 -0
  134. package/src/client/core-api.ts +71 -0
  135. package/src/client/custody.test.ts +31 -0
  136. package/src/client/custody.ts +34 -0
  137. package/src/client/errors.test.ts +365 -0
  138. package/src/client/errors.ts +201 -0
  139. package/src/client/links.test.ts +74 -0
  140. package/src/client/links.ts +44 -0
  141. package/src/client/members.test.ts +132 -0
  142. package/src/client/members.ts +116 -0
  143. package/src/client/messages.test.ts +127 -0
  144. package/src/client/messages.ts +1043 -18
  145. package/src/client/mock.test.ts +395 -1
  146. package/src/client/mock.ts +1066 -79
  147. package/src/client/module.ts +54 -0
  148. package/src/client/pages/AssetsPage.svelte +317 -45
  149. package/src/client/permissions.ts +7 -0
  150. package/src/client/price.test.ts +151 -3
  151. package/src/client/price.ts +155 -11
  152. package/src/client/query.ts +36 -0
  153. package/src/client/repairs.test.ts +38 -0
  154. package/src/client/repairs.ts +38 -0
  155. package/src/client/settings/CategoriesSettings.svelte +421 -0
  156. package/src/client/settings/GeneralSettings.svelte +0 -0
  157. package/src/client/status.ts +29 -0
  158. package/src/client/timeline.test.ts +175 -0
  159. package/src/client/timeline.ts +206 -0
  160. package/src/client/widgets/OverviewWidget.svelte +127 -26
  161. package/src/client/widgets/RepairsWidget.svelte +124 -0
  162. package/src/contract/capabilities.ts +53 -9
  163. package/src/contract/events.ts +49 -0
  164. package/src/contract/index.ts +1 -0
  165. package/src/contract/models.ts +237 -0
  166. package/src/contract/notifications.ts +73 -0
  167. package/src/contract/permissions.ts +55 -2
  168. package/src/contract/router.ts +255 -1
  169. package/src/contract/settings.ts +24 -4
  170. package/src/module.test.ts +194 -4
  171. package/src/server/index.ts +311 -4
  172. package/src/server/inventory.int.test.ts +3573 -18
  173. package/src/server/jobs.ts +444 -0
  174. package/src/server/migrations.test.ts +113 -0
  175. package/src/server/router.ts +462 -6
  176. package/src/server/schema.ts +160 -3
  177. package/src/server/services/assets.ts +214 -54
  178. package/src/server/services/attachments.ts +215 -0
  179. package/src/server/services/audience.ts +77 -0
  180. package/src/server/services/categories.ts +136 -0
  181. package/src/server/services/cursor.ts +104 -0
  182. package/src/server/services/custody.ts +471 -0
  183. package/src/server/services/db-errors.ts +42 -0
  184. package/src/server/services/index.ts +34 -1
  185. package/src/server/services/members.ts +54 -0
  186. package/src/server/services/notify.ts +52 -7
  187. package/src/server/services/offboarding.ts +150 -0
  188. package/src/server/services/repairs.ts +567 -0
  189. package/src/server/services/search.ts +166 -0
  190. package/src/server/services/stats.ts +88 -0
  191. package/src/server/services/status.test.ts +34 -0
  192. package/src/server/services/status.ts +143 -0
  193. package/src/client/settings/core-api.ts +0 -32
@@ -0,0 +1,471 @@
1
+ import { KernError, type Tx, uuidv7 } from '@kernhq/kernel'
2
+ import { and, desc, eq, isNull } from 'drizzle-orm'
3
+ import type { CustodyPeriod as CustodyPeriodModel } from '../../contract/models.js'
4
+ import { assets, custodyPeriods } from '../schema.js'
5
+ import { violated } from './db-errors.js'
6
+ import type { HistoryInput, NotifyService } from './notify.js'
7
+ import { awayForRepair, deriveStatus, lockAsset } from './status.js'
8
+
9
+ type AssetRow = typeof assets.$inferSelect
10
+ type PeriodRow = typeof custodyPeriods.$inferSelect
11
+
12
+ /** The GiST exclusion constraint `0001_rls.sql` added. Two open periods for one asset are it. */
13
+ const NO_OVERLAP = 'inventory_custody_no_overlap'
14
+
15
+ /**
16
+ * One millisecond: the finest a JS `Date` resolves, and therefore the shortest custody period this
17
+ * module is able to write. See `instant` — it is what keeps two changes in the same millisecond
18
+ * from recording a period nobody held the item for.
19
+ */
20
+ const TICK_MS = 1
21
+
22
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
23
+ export function toCustodyPeriod(row: PeriodRow): CustodyPeriodModel {
24
+ return {
25
+ id: row.id,
26
+ workspaceId: row.workspaceId as CustodyPeriodModel['workspaceId'],
27
+ assetId: row.assetId,
28
+ userId: row.userId,
29
+ note: row.note,
30
+ effectiveFrom: row.effectiveFrom.toISOString(),
31
+ effectiveTo: row.effectiveTo?.toISOString() ?? null,
32
+ createdBy: row.createdBy,
33
+ createdAt: row.createdAt.toISOString(),
34
+ }
35
+ }
36
+
37
+ /**
38
+ * What one custody change wrote, and what may only leave the module once it has committed.
39
+ *
40
+ * `previousUserId` and `userId` are what `inventory.custody.changed` carries, and between them they
41
+ * say which of the three verbs happened without a fourth field claiming to: out from stock has no
42
+ * previous, back to stock has no next, a hand-on has both.
43
+ */
44
+ export interface CustodyWritten {
45
+ asset: AssetRow
46
+ /** The period this call opened. Null on a return: something closed, nothing opened. */
47
+ period: PeriodRow | null
48
+ userId: string | null
49
+ previousUserId: string | null
50
+ activity: HistoryInput
51
+ /** Who to tell, which is the recipient and never the person doing the handing. */
52
+ notifyUserId: string | null
53
+ }
54
+
55
+ /**
56
+ * Who is holding what, over time.
57
+ *
58
+ * Effective-dated the way HR keeps employments: **nothing is ever updated in place**. A change
59
+ * closes the open row and inserts a new one, so the answer to "who had this laptop in March" is a
60
+ * row that still exists rather than a value that was overwritten.
61
+ *
62
+ * Three things happen in one transaction on every change, and the whole point of the class is that
63
+ * they cannot come apart: the period rows move, `assets.custodian_user_id`/`custody_since`/`status`
64
+ * are brought into step with them, and an `asset_history` entry records it. The denormalised
65
+ * columns on `assets` are what the list filters and the widget read; they are correct because they
66
+ * are written here, in the same transaction, and never by a job afterwards.
67
+ *
68
+ * **A repair never refuses a handover.** An item at the repairer is still somebody's
69
+ * responsibility, so none of the three verbs looks at repair state to decide whether it may run —
70
+ * refusing `assign` would mean refusing `return` as well, and somebody leaving the company while
71
+ * their laptop is in the workshop has to be able to hand it back. What repair state *does* affect
72
+ * is the status these three write, which is `deriveStatus`'s job and is argued in `status.ts`.
73
+ *
74
+ * **The database is the arbiter of who won, not this file.** There is deliberately no `select … for
75
+ * update` before the period is inserted. `inventory_custody_no_overlap` — a GiST exclusion
76
+ * constraint on `(asset_id =, tstzrange(effective_from, effective_to, '[)') &&)` — is what makes two
77
+ * open periods impossible, so two people pressing *Hand over* on the same laptop in the same instant
78
+ * both read "nobody has it", both insert, and Postgres refuses exactly one of them. Locking the
79
+ * asset first would serialise them into two successful handovers, which is a worse answer wearing
80
+ * the clothes of a safer one. What this file owes the loser is a sentence they can act on rather
81
+ * than drizzle's "Failed query: insert into mod_inventory.custody_periods …", and that is `refuse()`
82
+ * below.
83
+ *
84
+ * **The asset row *is* locked afterwards, and that is a different job.** `stamp` takes it before it
85
+ * reads the repair state, because `status` is derived from two facts two services write and the
86
+ * winner of the race still has to write an answer nobody can overwrite from a stale snapshot. The
87
+ * distinction is argued at `lockAsset` in `status.ts`: the constraint decides the contest, the lock
88
+ * orders the bookkeeping that follows it.
89
+ */
90
+ export class CustodyService {
91
+ constructor(private readonly notify: NotifyService) {}
92
+
93
+ /**
94
+ * The one error a lost race produces, in every place a race can be lost.
95
+ *
96
+ * Actionable rather than apologetic: the reader's screen is now out of date, and the only thing
97
+ * they can do about it is look again. `reason` is stable so a client could eventually say it in
98
+ * the reader's own language; the message is the honest fallback until one does.
99
+ */
100
+ private static refuse(): KernError {
101
+ return KernError.conflict(
102
+ 'Somebody changed who is holding this a moment before you did. Reload to see where it is now.',
103
+ 'inventory.custody.conflict',
104
+ )
105
+ }
106
+
107
+ private async asset(tx: Tx, workspaceId: string, assetId: string): Promise<AssetRow> {
108
+ const [row] = await tx
109
+ .select()
110
+ .from(assets)
111
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
112
+ if (!row) throw KernError.notFound('Asset')
113
+ // An archived asset is one the workspace has said it no longer tracks. Handing it to somebody
114
+ // would make them answerable for something that is not in the register, and the timeline would
115
+ // carry a handover after a retirement.
116
+ if (row.archivedAt)
117
+ throw KernError.conflict(
118
+ 'This item is archived. Restore it before handing it over.',
119
+ 'inventory.custody.archived',
120
+ )
121
+ return row
122
+ }
123
+
124
+ /** The period that has not been closed, if there is one. At most one exists, by construction. */
125
+ async open(tx: Tx, workspaceId: string, assetId: string): Promise<PeriodRow | undefined> {
126
+ const [row] = await tx
127
+ .select()
128
+ .from(custodyPeriods)
129
+ .where(
130
+ and(
131
+ eq(custodyPeriods.workspaceId, workspaceId),
132
+ eq(custodyPeriods.assetId, assetId),
133
+ isNull(custodyPeriods.effectiveTo),
134
+ ),
135
+ )
136
+ .limit(1)
137
+ return row
138
+ }
139
+
140
+ /**
141
+ * Every period for one asset, newest first.
142
+ *
143
+ * Capped rather than paged: the rows are bounded by how many times one item changed hands, which
144
+ * is tens over its life. Ordered by `effective_from` and then by id, because a hand-on closes one
145
+ * row and opens another at the same instant and the two would otherwise have no order between
146
+ * them — the panel would show the handover before the return it replaced, at random.
147
+ */
148
+ async history(tx: Tx, workspaceId: string, assetId: string, limit: number): Promise<PeriodRow[]> {
149
+ return tx
150
+ .select()
151
+ .from(custodyPeriods)
152
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.assetId, assetId)))
153
+ .orderBy(desc(custodyPeriods.effectiveFrom), desc(custodyPeriods.id))
154
+ .limit(limit)
155
+ }
156
+
157
+ /**
158
+ * Close the open period at `at`, or refuse.
159
+ *
160
+ * `and effective_to is null` in the predicate is the optimistic guard: under READ COMMITTED a
161
+ * concurrent close blocks this statement, and when it resumes the row no longer matches, so zero
162
+ * rows come back rather than a second close silently overwriting the first one's timestamp.
163
+ */
164
+ private async close(tx: Tx, workspaceId: string, periodId: string, at: Date): Promise<PeriodRow> {
165
+ const [row] = await tx
166
+ .update(custodyPeriods)
167
+ .set({ effectiveTo: at })
168
+ .where(
169
+ and(
170
+ eq(custodyPeriods.workspaceId, workspaceId),
171
+ eq(custodyPeriods.id, periodId),
172
+ isNull(custodyPeriods.effectiveTo),
173
+ ),
174
+ )
175
+ .returning()
176
+ if (!row) throw CustodyService.refuse()
177
+ return row
178
+ }
179
+
180
+ private async openPeriod(
181
+ tx: Tx,
182
+ workspaceId: string,
183
+ assetId: string,
184
+ userId: string,
185
+ note: string | null,
186
+ actorId: string | null,
187
+ at: Date,
188
+ ): Promise<PeriodRow> {
189
+ try {
190
+ const [row] = await tx
191
+ .insert(custodyPeriods)
192
+ .values({
193
+ id: uuidv7(),
194
+ workspaceId,
195
+ assetId,
196
+ userId,
197
+ note,
198
+ effectiveFrom: at,
199
+ createdBy: actorId,
200
+ })
201
+ .returning()
202
+ return row!
203
+ } catch (err) {
204
+ // The constraint bit: another transaction opened a period for this asset between our read and
205
+ // our insert. Anything else is a real fault and must not be disguised as a lost race.
206
+ if (violated(err, NO_OVERLAP)) throw CustodyService.refuse()
207
+ throw err
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The three denormalised columns, brought into step inside the same transaction.
213
+ *
214
+ * **`status` is not `userId ? 'assigned' : 'in_stock'`, and that line is what this comment is
215
+ * about.** An item can be at a repairer *and* assigned to somebody — the repair does not release
216
+ * whoever is answerable for it — so a handover that wrote `assigned` unconditionally would
217
+ * announce a laptop as back in the office while it was still in the workshop. Both facts are read
218
+ * and `deriveStatus` decides; the rule is argued in full in `status.ts`.
219
+ *
220
+ * **The asset row is locked before the repair state is read, and the order is the point.** Without
221
+ * it a repair completing in another transaction is invisible here and this handover's status is
222
+ * derived from a snapshot that has already stopped being true — the two writes then interleave
223
+ * into a status matching neither. See `lockAsset`.
224
+ *
225
+ * The lock is also what makes `assets.archive`'s refusal real rather than advisory. Archiving
226
+ * reads "nobody is holding it" under the same lock, so a handover racing an archive is ordered
227
+ * against it: whichever gets the lock second sees what the first committed, and the re-check below
228
+ * is what turns that into a refusal instead of an archived asset with an open custody period.
229
+ *
230
+ * @param repairsOn whether the workspace records repairs, read before the transaction opened.
231
+ * A workspace that has switched the capability off has no `under_repair`, because the procedure
232
+ * that would end one answers 404 — `deriveStatus` argues it in full, and this is one of the two
233
+ * write paths that lets an asset out of a status nothing else could move it out of.
234
+ */
235
+ private async stamp(
236
+ tx: Tx,
237
+ workspaceId: string,
238
+ assetId: string,
239
+ userId: string | null,
240
+ at: Date | null,
241
+ repairsOn: boolean,
242
+ ): Promise<AssetRow> {
243
+ const locked = await lockAsset(tx, workspaceId, assetId)
244
+ /**
245
+ * Re-read under the lock, because the check in `asset()` was made against a snapshot an archive
246
+ * committed a moment later could already have replaced.
247
+ *
248
+ * **Only when somebody is being *given* the item, and that is a narrowing rather than an escape
249
+ * hatch.** A return never reaches this branch with an archived row at all: `return` calls
250
+ * `asset()` first, and `asset()` refuses an archived asset outright, whichever verb asked. The
251
+ * condition is here because a *return* has nothing to race — it can only ever leave the asset
252
+ * unheld — so re-checking it would be a refusal with no state behind it. This comment used to
253
+ * claim the opposite, that a return on an archived asset is deliberately allowed so an item that
254
+ * had reached the impossible state could be undone; it is not allowed, it never was, and the
255
+ * lock in `assets.archive` is what makes that state unreachable rather than merely rare.
256
+ */
257
+ if (userId !== null && locked.archivedAt)
258
+ throw KernError.conflict(
259
+ 'This item is archived. Restore it before handing it over.',
260
+ 'inventory.custody.archived',
261
+ )
262
+ const status = deriveStatus({
263
+ custodianUserId: userId,
264
+ awayForRepair: await awayForRepair(tx, workspaceId, assetId, repairsOn),
265
+ })
266
+ const [row] = await tx
267
+ .update(assets)
268
+ .set({
269
+ custodianUserId: userId,
270
+ custodySince: at,
271
+ status,
272
+ updatedAt: new Date(),
273
+ })
274
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
275
+ .returning()
276
+ if (!row) throw KernError.notFound('Asset')
277
+ return row
278
+ }
279
+
280
+ /**
281
+ * The latest instant this asset's custody trail already reaches.
282
+ *
283
+ * The end of the most recent closed period, or the start of the open one. One row answers it
284
+ * because the periods for an asset cannot overlap — that is what `inventory_custody_no_overlap`
285
+ * enforces — so the row that starts last also ends last.
286
+ */
287
+ private async boundary(tx: Tx, workspaceId: string, assetId: string): Promise<Date | null> {
288
+ const [row] = await tx
289
+ .select({ from: custodyPeriods.effectiveFrom, to: custodyPeriods.effectiveTo })
290
+ .from(custodyPeriods)
291
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.assetId, assetId)))
292
+ .orderBy(desc(custodyPeriods.effectiveFrom), desc(custodyPeriods.id))
293
+ .limit(1)
294
+ return row ? (row.to ?? row.from) : null
295
+ }
296
+
297
+ /**
298
+ * The instant this change happens, for both halves of it.
299
+ *
300
+ * One value, so the period that closes and the period that opens abut exactly: `'[)'` ranges
301
+ * `[…, at)` and `[at, …)` do not overlap, where two `now()` calls a microsecond apart would leave
302
+ * a gap during which the asset was held by nobody.
303
+ *
304
+ * **It is a millisecond past the trail's own end, not `now()`, and both halves of that are a
305
+ * defect this replaced.**
306
+ *
307
+ * - `max(now, open.effectiveFrom)` produced a **zero-length period** whenever the two were equal,
308
+ * which two handovers inside one millisecond make them — a JS `Date` resolves no finer. `[t, t)`
309
+ * is empty, an empty range overlaps nothing, so the exclusion constraint waves it through and
310
+ * the trail permanently records somebody holding the item for no time at all. Anybody reading
311
+ * "who had this in March" gets a name that was never true. Strictly after the boundary, there
312
+ * is no such row to write.
313
+ * - `assign` used plain `now()`, which a clock that steps backwards puts *before* the end of the
314
+ * last closed period — so the new period overlapped a finished one, Postgres refused it with
315
+ * `23P01`, and the person was told "somebody changed who is holding this a moment before you
316
+ * did. Reload." Nobody had; reloading changes nothing; the handover is refused again every time.
317
+ * Reading the trail's own end rather than the clock makes that unreachable instead of merely
318
+ * better explained: the next period always starts after the last one ended, whatever the clock
319
+ * says.
320
+ *
321
+ * `now` still wins whenever it is ahead, which is every ordinary case — this only ever moves the
322
+ * instant forward, never back, so it cannot manufacture a period that starts before its asset was
323
+ * bought.
324
+ */
325
+ private async instant(tx: Tx, workspaceId: string, assetId: string): Promise<Date> {
326
+ const boundary = await this.boundary(tx, workspaceId, assetId)
327
+ return new Date(Math.max(Date.now(), boundary ? boundary.getTime() + TICK_MS : 0))
328
+ }
329
+
330
+ /**
331
+ * Hand a free item to a member.
332
+ *
333
+ * Refuses when somebody already has it, rather than quietly taking it off them: `transfer` is the
334
+ * procedure that means "hand it on", and collapsing the two would make a mistyped assignment
335
+ * indistinguishable from a deliberate handover in the timeline everyone reads afterwards.
336
+ */
337
+ async assign(
338
+ tx: Tx,
339
+ workspaceId: string,
340
+ actorId: string | null,
341
+ assetId: string,
342
+ userId: string,
343
+ note: string | null,
344
+ repairsOn: boolean,
345
+ ): Promise<CustodyWritten> {
346
+ // Called for its two refusals — a row in another workspace is a 404, an archived one a
347
+ // conflict — and not for the row, which `stamp` returns below in its post-handover shape.
348
+ await this.asset(tx, workspaceId, assetId)
349
+ const open = await this.open(tx, workspaceId, assetId)
350
+ if (open)
351
+ throw KernError.conflict(
352
+ open.userId === userId
353
+ ? 'They are already holding this item.'
354
+ : 'Somebody else is holding this item. Hand it on, or take it back first.',
355
+ 'inventory.custody.already_held',
356
+ )
357
+
358
+ const at = await this.instant(tx, workspaceId, assetId)
359
+ const period = await this.openPeriod(tx, workspaceId, assetId, userId, note, actorId, at)
360
+ const row = await this.stamp(tx, workspaceId, assetId, userId, at, repairsOn)
361
+
362
+ const activity: HistoryInput = {
363
+ workspaceId,
364
+ assetId,
365
+ actorId,
366
+ action: 'assigned',
367
+ data: { userId, ...(note ? { note } : {}) },
368
+ }
369
+ await this.notify.history(tx, activity)
370
+ return {
371
+ asset: row,
372
+ period,
373
+ userId,
374
+ previousUserId: null,
375
+ activity,
376
+ // Never the person doing the handing: telling somebody what they just did is the notification
377
+ // everybody switches the type off over.
378
+ notifyUserId: userId === actorId ? null : userId,
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Hand it straight on. One transaction, not a return followed by an assign.
384
+ *
385
+ * Two calls would leave the asset `in_stock` with no custodian in between — visible to anybody
386
+ * reading the list at that moment, and permanently visible in the timeline as a return nobody
387
+ * performed and a stock period nobody spent.
388
+ */
389
+ async transfer(
390
+ tx: Tx,
391
+ workspaceId: string,
392
+ actorId: string | null,
393
+ assetId: string,
394
+ userId: string,
395
+ note: string | null,
396
+ repairsOn: boolean,
397
+ ): Promise<CustodyWritten> {
398
+ await this.asset(tx, workspaceId, assetId)
399
+ const open = await this.open(tx, workspaceId, assetId)
400
+ if (!open)
401
+ throw KernError.conflict(
402
+ 'Nobody is holding this item, so there is nothing to hand on. Assign it instead.',
403
+ 'inventory.custody.not_held',
404
+ )
405
+ if (open.userId === userId)
406
+ throw KernError.conflict('They are already holding this item.', 'inventory.custody.already_held')
407
+
408
+ const at = await this.instant(tx, workspaceId, assetId)
409
+ await this.close(tx, workspaceId, open.id, at)
410
+ const period = await this.openPeriod(tx, workspaceId, assetId, userId, note, actorId, at)
411
+ const row = await this.stamp(tx, workspaceId, assetId, userId, at, repairsOn)
412
+
413
+ const activity: HistoryInput = {
414
+ workspaceId,
415
+ assetId,
416
+ actorId,
417
+ action: 'transferred',
418
+ data: { userId, previousUserId: open.userId, ...(note ? { note } : {}) },
419
+ }
420
+ await this.notify.history(tx, activity)
421
+ return {
422
+ asset: row,
423
+ period,
424
+ userId,
425
+ previousUserId: open.userId,
426
+ activity,
427
+ notifyUserId: userId === actorId ? null : userId,
428
+ }
429
+ }
430
+
431
+ /** Take it back. Closes the open period and puts the item back in stock. */
432
+ async return(
433
+ tx: Tx,
434
+ workspaceId: string,
435
+ actorId: string | null,
436
+ assetId: string,
437
+ note: string | null,
438
+ repairsOn: boolean,
439
+ ): Promise<CustodyWritten> {
440
+ await this.asset(tx, workspaceId, assetId)
441
+ const open = await this.open(tx, workspaceId, assetId)
442
+ if (!open)
443
+ throw KernError.conflict(
444
+ 'Nobody is holding this item, so there is nothing to take back.',
445
+ 'inventory.custody.not_held',
446
+ )
447
+
448
+ const at = await this.instant(tx, workspaceId, assetId)
449
+ await this.close(tx, workspaceId, open.id, at)
450
+ const row = await this.stamp(tx, workspaceId, assetId, null, null, repairsOn)
451
+
452
+ const activity: HistoryInput = {
453
+ workspaceId,
454
+ assetId,
455
+ actorId,
456
+ action: 'returned',
457
+ data: { previousUserId: open.userId, ...(note ? { note } : {}) },
458
+ }
459
+ await this.notify.history(tx, activity)
460
+ return {
461
+ asset: row,
462
+ period: null,
463
+ userId: null,
464
+ previousUserId: open.userId,
465
+ activity,
466
+ // A return is not news to anybody: the person who had it knows they handed it back, and the
467
+ // person taking it back is the one making the call.
468
+ notifyUserId: null,
469
+ }
470
+ }
471
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Which constraint Postgres refused a write with, dug out of what drizzle hands back.
3
+ *
4
+ * A database constraint is only half a feature. `inventory_custody_no_overlap` makes two open
5
+ * custody periods for one asset impossible — but two people pressing *Hand over* on the same laptop
6
+ * at the same instant means the loser is shown drizzle's own text, "Failed query: insert into
7
+ * mod_inventory.custody_periods …", which tells a person nothing they can act on and looks like the
8
+ * product broke rather than like somebody else got there first.
9
+ *
10
+ * So the service catches, asks these two questions, and throws a `KernError.conflict` with a
11
+ * sentence. Reaching through `cause` rather than reading the top frame is the load-bearing part:
12
+ * drizzle wraps the driver's error, and the driver's error is the only object carrying `code` and
13
+ * `constraint`. `src/server/inventory.int.test.ts` walks the same chain for the same reason.
14
+ */
15
+ const MAX_DEPTH = 5
16
+
17
+ interface DriverError {
18
+ code?: unknown
19
+ constraint?: unknown
20
+ cause?: unknown
21
+ }
22
+
23
+ function walk(err: unknown, read: (e: DriverError) => string | undefined): string | undefined {
24
+ let cursor: unknown = err
25
+ for (let depth = 0; depth < MAX_DEPTH && cursor; depth++) {
26
+ const found = read(cursor as DriverError)
27
+ if (found) return found
28
+ cursor = (cursor as DriverError).cause
29
+ }
30
+ return undefined
31
+ }
32
+
33
+ /** The constraint's name, if a named one refused the write. */
34
+ export const constraintOf = (err: unknown): string | undefined =>
35
+ walk(err, (e) => (typeof e.constraint === 'string' ? e.constraint : undefined))
36
+
37
+ /** The SQLSTATE, if one reached us. `23P01` is an exclusion violation, `23505` a unique one. */
38
+ export const sqlStateOf = (err: unknown): string | undefined =>
39
+ walk(err, (e) => (typeof e.code === 'string' && /^[0-9A-Z]{5}$/.test(e.code) ? e.code : undefined))
40
+
41
+ /** Did this write lose to `name`, whichever way Postgres reported it? */
42
+ export const violated = (err: unknown, name: string): boolean => constraintOf(err) === name
@@ -1,10 +1,26 @@
1
1
  import type { Kernel } from '@kernhq/kernel'
2
2
  import { AssetService } from './assets.js'
3
+ import { AttachmentService } from './attachments.js'
4
+ import { CategoryService } from './categories.js'
5
+ import { CustodyService } from './custody.js'
3
6
  import { NotifyService } from './notify.js'
7
+ import { OffboardingService } from './offboarding.js'
8
+ import { RepairService } from './repairs.js'
9
+ import { SearchService } from './search.js'
10
+ import { StatsService } from './stats.js'
4
11
 
5
12
  export interface InventoryServices {
6
13
  notify: NotifyService
7
14
  assets: AssetService
15
+ categories: CategoryService
16
+ custody: CustodyService
17
+ repairs: RepairService
18
+ attachments: AttachmentService
19
+ stats: StatsService
20
+ /** The workspace-wide index, and the documents behind `inventory:asset:<id>`. */
21
+ search: SearchService
22
+ /** Somebody left holding company property. Raises a checklist; never moves custody. */
23
+ offboarding: OffboardingService
8
24
  }
9
25
 
10
26
  const cache = new WeakMap<Kernel, InventoryServices>()
@@ -16,8 +32,25 @@ export function inventoryServices(kernel: Kernel): InventoryServices {
16
32
 
17
33
  const notify = new NotifyService(kernel)
18
34
  const assets = new AssetService(kernel, notify)
35
+ const categories = new CategoryService()
36
+ const custody = new CustodyService(notify)
37
+ const repairs = new RepairService(notify)
38
+ const attachments = new AttachmentService(kernel, notify)
39
+ const stats = new StatsService()
40
+ const search = new SearchService(kernel, notify)
41
+ const offboarding = new OffboardingService(kernel, notify)
19
42
 
20
- const services: InventoryServices = { notify, assets }
43
+ const services: InventoryServices = {
44
+ notify,
45
+ assets,
46
+ categories,
47
+ custody,
48
+ repairs,
49
+ attachments,
50
+ stats,
51
+ search,
52
+ offboarding,
53
+ }
21
54
  cache.set(kernel, services)
22
55
  return services
23
56
  }
@@ -0,0 +1,54 @@
1
+ import type { Principal } from '@kernhq/contracts'
2
+ import { KernError, type Kernel } from '@kernhq/kernel'
3
+
4
+ /**
5
+ * Is this person somebody this workspace can hand a laptop to?
6
+ *
7
+ * **`custody.assign` and `custody.transfer` took any uuid.** The id arrives in the request, nothing
8
+ * looked it up, and the module then wrote it into `custody_periods.user_id` and
9
+ * `assets.custodian_user_id` — the two columns that answer "who is answerable for this" for the rest
10
+ * of the item's life — and sent a notification to it. So a member of one workspace could record a
11
+ * *stranger* as holding company property, and the product would then chase that stranger about it.
12
+ * Every screen renders an id it cannot resolve as "a former member", which is the honest thing for a
13
+ * screen to say and exactly what hides this: the register looks plausible and names nobody real.
14
+ *
15
+ * The check is a question for core, because membership is core's fact and this module has no copy of
16
+ * it. `core.users.principal` answers with one person rather than the workspace's whole roll, which
17
+ * matters on an instance where a workspace has thousands of seats and this runs on every handover.
18
+ *
19
+ * **`active`, not merely present.** An invitation nobody has accepted is not somebody who can be
20
+ * handed a thing, and a suspended account is one the workspace has deliberately shut out.
21
+ *
22
+ * **A failure here refuses rather than waves through.** Every other cross-service call this module
23
+ * makes is best-effort, and this one deliberately is not: swallowing the failure would mean the
24
+ * check silently stops existing exactly while core is unwell, which is indistinguishable from not
25
+ * having written it. `UNAVAILABLE` is 503 and says the true thing — the answer is not knowable right
26
+ * now — where a 400 would tell somebody their colleague is not a member.
27
+ */
28
+ export async function requireWorkspaceMember(
29
+ kernel: Kernel,
30
+ workspaceId: string,
31
+ userId: string,
32
+ ): Promise<void> {
33
+ let principal: Principal | null
34
+ try {
35
+ principal = await kernel.call<Principal | null>('core.users.principal', { userId })
36
+ } catch (err) {
37
+ kernel.log.warn(
38
+ { err: err instanceof Error ? err.message : String(err), workspaceId },
39
+ 'inventory: could not check whether the new custodian is a member',
40
+ )
41
+ throw new KernError(
42
+ 'UNAVAILABLE',
43
+ 'Who belongs to this workspace cannot be checked right now. Try again in a moment.',
44
+ )
45
+ }
46
+
47
+ const member = (principal?.memberships ?? []).some(
48
+ (m) => m.workspaceId === workspaceId && m.status === 'active',
49
+ )
50
+ if (!member)
51
+ throw KernError.badRequest(
52
+ 'That person is not a member of this workspace, so nothing can be handed to them.',
53
+ )
54
+ }