@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,528 @@
1
+ import { KernError, type Kernel, type Tx, uuidv7 } from '@kernhq/kernel'
2
+ import { and, asc, desc, eq, ilike, isNull, lt, or, sql } from 'drizzle-orm'
3
+ import { alias, type PgColumn } from 'drizzle-orm/pg-core'
4
+ import type {
5
+ AssetCreateInput,
6
+ AssetHistoryEntry,
7
+ Asset as AssetModel,
8
+ AssetPatchInput,
9
+ AssetSort,
10
+ } from '../../contract/models.js'
11
+ import { InventorySettings } from '../../contract/settings.js'
12
+ import { assetHistory, assets, categories, counters } from '../schema.js'
13
+ import { decodeMark, decodeSeqMark, encodeMark, encodeSeqMark } from './cursor.js'
14
+ import type { HistoryInput, NotifyService } from './notify.js'
15
+ import { openRepairId } from './status.js'
16
+
17
+ type Row = typeof assets.$inferSelect
18
+
19
+ /**
20
+ * What a mutation wrote, and what may only leave the module once it has committed.
21
+ *
22
+ * `asset_history` is written inside the caller's transaction and is authoritative; the mirror of it
23
+ * in core's activity feed is not, and used to be fired off with `void` while the transaction was
24
+ * still open. A rollback then left the workspace's feed showing an event for an id that does not
25
+ * exist. Everything else this module announces — the event, the realtime change — already waits for
26
+ * the commit, so the activity record is handed back here and flushed beside them.
27
+ */
28
+ export interface Written {
29
+ row: Row
30
+ /** `null` when nothing happened worth recording, which is what an update that changed nothing is. */
31
+ activity: HistoryInput | null
32
+ }
33
+
34
+ /** How this workspace spells an asset tag. Read before the transaction opens — see `codeFormat`. */
35
+ export interface CodeFormat {
36
+ prefix: string
37
+ pad: number
38
+ }
39
+
40
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
41
+ export function toAsset(row: Row): AssetModel {
42
+ return {
43
+ id: row.id,
44
+ workspaceId: row.workspaceId as AssetModel['workspaceId'],
45
+ code: row.code,
46
+ name: row.name,
47
+ description: row.description,
48
+ categoryId: row.categoryId,
49
+ status: row.status as AssetModel['status'],
50
+ custodianUserId: row.custodianUserId,
51
+ custodySince: row.custodySince?.toISOString() ?? null,
52
+ serialNumber: row.serialNumber,
53
+ location: row.location,
54
+ purchasedOn: row.purchasedOn ?? null,
55
+ purchasedFrom: row.purchasedFrom,
56
+ priceMinor: row.priceMinor,
57
+ currency: row.currency,
58
+ warrantyUntil: row.warrantyUntil ?? null,
59
+ photoFileId: row.photoFileId,
60
+ custom: row.custom ?? {},
61
+ createdAt: row.createdAt.toISOString(),
62
+ updatedAt: row.updatedAt.toISOString(),
63
+ archivedAt: row.archivedAt?.toISOString() ?? null,
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The wire shape of one timeline entry. Drizzle's `jsonb` columns are nullable in the row and never
69
+ * null in the contract — `changes: []` and `data: {}` are what "nothing to say" looks like to a
70
+ * screen, where `null` is one more thing every caller has to remember to handle.
71
+ */
72
+ export function toHistoryEntry(row: typeof assetHistory.$inferSelect): AssetHistoryEntry {
73
+ return {
74
+ id: row.id,
75
+ assetId: row.assetId,
76
+ actorId: row.actorId,
77
+ action: row.action,
78
+ changes: row.changes ?? [],
79
+ data: (row.data as Record<string, unknown> | null) ?? {},
80
+ occurredAt: row.occurredAt.toISOString(),
81
+ }
82
+ }
83
+
84
+ /**
85
+ * `%`, `_` and `\` are pattern syntax to `ilike`, not text.
86
+ *
87
+ * Unescaped, a search for `50%` matched every row in the workspace and a search for `_hair` matched
88
+ * "Chair" — both of which read as a broken search rather than as a clever one. Escaped rather than
89
+ * stripped: somebody typing a per-cent sign means the character.
90
+ */
91
+ const contains = (q: string) => `%${q.replace(/[\\%_]/g, '\\$&')}%`
92
+
93
+ /**
94
+ * The one ordering a timeline has, named rather than left as a literal.
95
+ *
96
+ * The cursor codec binds a bookmark to the sort it was issued under and refuses it under any other,
97
+ * so a timeline needs a name for its sort even while there is only one — and the day a second one
98
+ * exists, every cursor already in a browser tab is refused rather than misread.
99
+ */
100
+ const HISTORY_SORT = 'recent'
101
+
102
+ /** Which column an ordering sorts on, for the list itself and for the bookmarked row alike. */
103
+ const sortKey = <T extends { id: PgColumn; name: PgColumn; code: PgColumn }>(t: T, sort: AssetSort) =>
104
+ sort === 'name' ? t.name : sort === 'code' ? t.code : t.id
105
+
106
+ export interface ListInput {
107
+ workspaceId: string
108
+ limit: number
109
+ cursor?: string
110
+ q?: string
111
+ categoryId?: string
112
+ status?: string
113
+ custodianUserId?: string
114
+ archived: boolean
115
+ sort: AssetSort
116
+ }
117
+
118
+ export class AssetService {
119
+ constructor(
120
+ private readonly kernel: Kernel,
121
+ private readonly notify: NotifyService,
122
+ ) {}
123
+
124
+ /**
125
+ * How this workspace spells an asset tag.
126
+ *
127
+ * **Called before the transaction opens, never inside one.** `kernel.settings.module` is a
128
+ * `core.settings.getModule` call over the broker, and awaiting a remote service while holding a
129
+ * pooled connection *and* the counter row lock is two failures waiting: the pool starves under
130
+ * concurrent creates, and a create fails outright whenever core is briefly away — which is the
131
+ * one thing `NotifyService`'s own docblock says a mutation here must never do.
132
+ */
133
+ async codeFormat(workspaceId: string): Promise<CodeFormat> {
134
+ const settings = await this.kernel.settings.module(workspaceId, 'inventory', InventorySettings)
135
+ return { prefix: settings.assetCodePrefix, pad: settings.assetCodePad }
136
+ }
137
+
138
+ /**
139
+ * The next asset tag for a workspace.
140
+ *
141
+ * One narrow row per workspace and key, incremented under the insert's conflict lock — two
142
+ * concurrent creates each read the value their own statement returned, so codes stay unique
143
+ * without a retry loop. `INV-0042`, because people say asset tags out loud. Nothing in here
144
+ * leaves the database, which is what keeps the lock short.
145
+ */
146
+ async nextCode(tx: Tx, workspaceId: string, format: CodeFormat): Promise<string> {
147
+ const [row] = await tx
148
+ .insert(counters)
149
+ .values({ workspaceId, key: 'asset_code', value: 1 })
150
+ .onConflictDoUpdate({
151
+ target: [counters.workspaceId, counters.key],
152
+ set: { value: sql`${counters.value} + 1` },
153
+ })
154
+ .returning()
155
+ return `${format.prefix}${String(row!.value).padStart(format.pad, '0')}`
156
+ }
157
+
158
+ async list(tx: Tx, input: ListInput): Promise<{ items: AssetModel[]; nextCursor: string | null }> {
159
+ const filters = [eq(assets.workspaceId, input.workspaceId)]
160
+ if (input.q) {
161
+ // A code is something somebody reads off a sticker; matching name, code and serial loosely
162
+ // matters more than word-splitting here. Full-text arrives with the core indexer.
163
+ const pattern = contains(input.q)
164
+ filters.push(
165
+ or(
166
+ ilike(assets.name, pattern),
167
+ ilike(assets.code, pattern),
168
+ ilike(sql`coalesce(${assets.serialNumber}, '')`, pattern),
169
+ )!,
170
+ )
171
+ }
172
+ if (input.categoryId) filters.push(eq(assets.categoryId, input.categoryId))
173
+ if (input.status) filters.push(eq(assets.status, input.status))
174
+ if (input.custodianUserId) filters.push(eq(assets.custodianUserId, input.custodianUserId))
175
+ if (!input.archived) filters.push(isNull(assets.archivedAt))
176
+
177
+ /**
178
+ * `recent` sorts by id rather than by `created_at`: ids are uuidv7, so they carry the clock, and
179
+ * one indexed unique column is a cheaper and unambiguous page boundary than a timestamp two rows
180
+ * can share. Ordered to the millisecond and no finer — the kernel's `uuidv7()` fills its last
181
+ * ten bytes from `randomUUID()` with no counter — so two assets created inside one millisecond
182
+ * come back in a stable but arbitrary order relative to each other.
183
+ *
184
+ * **The timeline deliberately stopped accepting that and this list has not**, so the difference
185
+ * is worth stating rather than leaving as an inconsistency. `asset_history` is a record somebody
186
+ * argues from, and a millisecond there holds a create and its own first entry, so an arbitrary
187
+ * order is a lie about causation — it has a sequence of its own now (`schema.ts`, `seq`). A list
188
+ * is an ordering of things a person is browsing: nothing hangs on which of two assets imported
189
+ * in the same millisecond is shown first, and paging stays gapless either way because the id is
190
+ * unique. If that ever stops being true — a bulk import whose order somebody relies on — the
191
+ * fix is the same sequence, not a timestamp: `created_at` defaults to the *transaction's*
192
+ * `now()`, so one import shares it exactly.
193
+ *
194
+ * It is fatal for a test that expects creation order; see `inventory.int.test.ts`.
195
+ */
196
+ const column = sortKey(assets, input.sort)
197
+ const descending = input.sort === 'recent'
198
+
199
+ if (input.cursor) {
200
+ const mark = decodeMark(input.cursor, input.sort)
201
+ /**
202
+ * The sort key comes back out of the bookmarked row rather than out of the cursor, which is
203
+ * what keeps the cursor small and stops it disagreeing with the row it names. Scoped by
204
+ * `workspace_id` as well as by id, so a cursor cannot be used to probe another workspace's
205
+ * ordering — this module reaches the database as a superuser in `core`, with RLS bypassed.
206
+ *
207
+ * A row deleted between two pages leaves the subquery empty, the row comparison NULL and the
208
+ * page empty: the list simply ends. That is deliberate, and preferred to a 400 — somebody
209
+ * else archiving a row while you read is an ordinary race, not a malformed request, and an
210
+ * error toast on "Load more" would be a worse answer than a list that has run out.
211
+ */
212
+ const marker = alias(assets, 'page_marker')
213
+ const bookmarked = tx
214
+ .select({ key: sortKey(marker, input.sort), id: marker.id })
215
+ .from(marker)
216
+ .where(and(eq(marker.id, mark.i), eq(marker.workspaceId, input.workspaceId)))
217
+ filters.push(
218
+ descending
219
+ ? sql`(${column}, ${assets.id}) < (${bookmarked})`
220
+ : sql`(${column}, ${assets.id}) > (${bookmarked})`,
221
+ )
222
+ }
223
+
224
+ const order = descending ? [desc(column), desc(assets.id)] : [asc(column), asc(assets.id)]
225
+
226
+ const rows = await tx
227
+ .select()
228
+ .from(assets)
229
+ .where(and(...filters))
230
+ .orderBy(...order)
231
+ .limit(input.limit + 1)
232
+
233
+ const items = rows.slice(0, input.limit)
234
+ const last = items.at(-1)
235
+ const nextCursor = rows.length > input.limit && last ? encodeMark({ i: last.id, s: input.sort }) : null
236
+ return { items: items.map(toAsset), nextCursor }
237
+ }
238
+
239
+ /**
240
+ * The asset's own timeline, newest first, paged on the sequence the entries carry.
241
+ *
242
+ * **The ordering is `seq`, not `occurred_at` and not the id**, and the middle one of those three
243
+ * is the interesting correction.
244
+ *
245
+ * `occurred_at` was never a candidate: it defaults to `now()`, which is the *transaction*
246
+ * timestamp, so `create` writes the asset and its `created` entry with the same value and a page
247
+ * boundary between two entries that share a sort key repeats one and drops the other.
248
+ *
249
+ * The id looked like the answer and was only half of one. A uuidv7 is unique, so paging on it is
250
+ * gapless — but the kernel's `uuidv7()` carries the clock only to the millisecond and fills the
251
+ * rest from `randomUUID()` with no counter, so two entries written inside one millisecond sort by
252
+ * ten random bytes. Stable, so nothing was ever dropped or repeated; and arbitrary, so a timeline
253
+ * could show "Bruno removed the file" above "Bruno added the file". `seq` is a sequence: strictly
254
+ * increasing whatever the clock does, at whatever rate. `schema.ts` argues it at the column.
255
+ *
256
+ * The comparison is a single column because the sort key *is* the bookmark, so there is no
257
+ * bookmarked-row subquery here. The bookmark is still checked as a bounded positive integer and
258
+ * still bound to the sort it was issued under, because that is the codec's job and not this
259
+ * query's.
260
+ */
261
+ async history(
262
+ tx: Tx,
263
+ workspaceId: string,
264
+ assetId: string,
265
+ input: { limit: number; cursor?: string },
266
+ ): Promise<{ items: AssetHistoryEntry[]; nextCursor: string | null }> {
267
+ // 404 before paging: a timeline for an asset in another workspace must not answer with an
268
+ // empty list, which reads as "nothing has happened to it" rather than "it is not yours".
269
+ await this.get(tx, workspaceId, assetId)
270
+
271
+ const filters = [eq(assetHistory.workspaceId, workspaceId), eq(assetHistory.assetId, assetId)]
272
+ if (input.cursor) filters.push(lt(assetHistory.seq, decodeSeqMark(input.cursor, HISTORY_SORT).n))
273
+
274
+ const rows = await tx
275
+ .select()
276
+ .from(assetHistory)
277
+ .where(and(...filters))
278
+ .orderBy(desc(assetHistory.seq))
279
+ .limit(input.limit + 1)
280
+
281
+ const items = rows.slice(0, input.limit)
282
+ const last = items.at(-1)
283
+ const nextCursor =
284
+ rows.length > input.limit && last ? encodeSeqMark({ n: last.seq, s: HISTORY_SORT }) : null
285
+ return { items: items.map(toHistoryEntry), nextCursor }
286
+ }
287
+
288
+ /**
289
+ * A category id in a request is a claim about a row in this workspace, and it is checked before
290
+ * it is stored.
291
+ *
292
+ * The same defect `photoFileId` had, one field over: `assets.create` and `assets.update` took
293
+ * `categoryId` on trust, so any uuid at all went into the column. Two things follow from that,
294
+ * and neither is theoretical. An id belonging to **another workspace** files an asset under a
295
+ * category this one cannot see, name or unfile — the picker resolves names from its own
296
+ * `categories.list`, so the field renders blank and the filter it sits behind matches nothing
297
+ * anybody can select. An id belonging to **nobody** does the same thing with no other workspace
298
+ * involved. Either way the register holds a reference to a row that is not there, which is
299
+ * exactly the state `categories.archive` exists to prevent from the other end.
300
+ *
301
+ * **Checked inside the caller's transaction, unlike `checkPhoto`.** A file lives in core and has
302
+ * to be asked for over the broker, so that check happens before a connection is taken — the rule
303
+ * `codeFormat` documents. A category is this module's own table one join away, so the honest
304
+ * place for it is the transaction that writes the row: it costs one indexed read, and it cannot
305
+ * be raced by somebody deleting the category, because nothing deletes one.
306
+ *
307
+ * An **archived** category is deliberately allowed. Archiving takes it out of every picker and
308
+ * leaves every asset already filed under it still naming it; refusing it here would mean an edit
309
+ * to an asset's location failed because of a category somebody tidied away last year, and it
310
+ * would make re-filing a batch of assets under an old category impossible for no gain.
311
+ */
312
+ private async requireCategory(tx: Tx, workspaceId: string, categoryId: string): Promise<void> {
313
+ const [row] = await tx
314
+ .select({ id: categories.id })
315
+ .from(categories)
316
+ .where(and(eq(categories.workspaceId, workspaceId), eq(categories.id, categoryId)))
317
+ if (!row) throw KernError.badRequest('That category is not one this workspace has.')
318
+ }
319
+
320
+ async get(tx: Tx, workspaceId: string, assetId: string): Promise<Row> {
321
+ const [row] = await tx
322
+ .select()
323
+ .from(assets)
324
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
325
+ if (!row) throw KernError.notFound('Asset')
326
+ return row
327
+ }
328
+
329
+ async create(
330
+ tx: Tx,
331
+ workspaceId: string,
332
+ actorId: string | null,
333
+ input: AssetCreateInput,
334
+ format: CodeFormat,
335
+ ): Promise<Written> {
336
+ if (input.categoryId) await this.requireCategory(tx, workspaceId, input.categoryId)
337
+ const [row] = await tx
338
+ .insert(assets)
339
+ .values({
340
+ id: uuidv7(),
341
+ workspaceId,
342
+ code: await this.nextCode(tx, workspaceId, format),
343
+ name: input.name,
344
+ description: input.description,
345
+ categoryId: input.categoryId ?? null,
346
+ serialNumber: input.serialNumber ?? null,
347
+ location: input.location ?? null,
348
+ purchasedFrom: input.purchasedFrom ?? null,
349
+ purchasedOn: input.purchasedOn ?? null,
350
+ warrantyUntil: input.warrantyUntil ?? null,
351
+ priceMinor: input.priceMinor ?? null,
352
+ currency: input.currency ?? null,
353
+ photoFileId: input.photoFileId ?? null,
354
+ })
355
+ .returning()
356
+ const activity: HistoryInput = { workspaceId, assetId: row!.id, actorId, action: 'created' }
357
+ await this.notify.history(tx, activity)
358
+ return { row: row!, activity }
359
+ }
360
+
361
+ /** Fields a person edits directly, and therefore the fields the timeline reports a diff for. */
362
+ private static readonly EDITABLE = [
363
+ 'name',
364
+ 'description',
365
+ 'categoryId',
366
+ 'serialNumber',
367
+ 'location',
368
+ 'purchasedFrom',
369
+ 'purchasedOn',
370
+ 'warrantyUntil',
371
+ 'priceMinor',
372
+ 'currency',
373
+ 'photoFileId',
374
+ ] as const
375
+
376
+ async update(
377
+ tx: Tx,
378
+ workspaceId: string,
379
+ actorId: string | null,
380
+ assetId: string,
381
+ input: AssetPatchInput,
382
+ ): Promise<Written> {
383
+ // Before the row is locked, because a refusal here has nothing to do with this asset and
384
+ // holding a row lock across a check that can throw is a lock held for no reason. `undefined`
385
+ // means the patch never mentioned a category and `null` means "unfile it"; neither is an id.
386
+ if (input.categoryId) await this.requireCategory(tx, workspaceId, input.categoryId)
387
+
388
+ const [prev] = await tx
389
+ .select()
390
+ .from(assets)
391
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
392
+ .for('update')
393
+ if (!prev) throw KernError.notFound('Asset')
394
+
395
+ // `undefined` means "not mentioned"; `null` means "clear it". Collapsing the two is how an
396
+ // edit of one field quietly wipes the others.
397
+ const patch: Record<string, unknown> = { updatedAt: new Date() }
398
+ for (const field of AssetService.EDITABLE) {
399
+ const value = (input as Record<string, unknown>)[field]
400
+ patch[field] = value !== undefined ? (value ?? null) : prev[field]
401
+ }
402
+
403
+ /**
404
+ * A new warranty date earns a new notice.
405
+ *
406
+ * `warranty_notified_at` is the marker that stops the sweep saying the same thing every morning
407
+ * for a month; left alone here, extending a warranty by two years would mean nobody is ever told
408
+ * about the new date, because the row is already marked. Cleared only when the date itself
409
+ * moved — an edit to the name must not re-arm a notice somebody has already had.
410
+ */
411
+ if (patch.warrantyUntil !== prev.warrantyUntil) patch.warrantyNotifiedAt = null
412
+
413
+ // Filtered by workspace as well as by id. The `select … for update` three statements up already
414
+ // carries the predicate, so this is not reachable today — but `core` connects as a superuser
415
+ // with RLS bypassed, which makes the predicate in the statement the only barrier there is. A
416
+ // barrier that holds only because of what another statement happens to do is not one.
417
+ const [row] = await tx
418
+ .update(assets)
419
+ .set(patch)
420
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
421
+ .returning()
422
+
423
+ const iso = (v: unknown) => (v instanceof Date ? v.toISOString() : v) ?? null
424
+ const changes = AssetService.EDITABLE.filter((f) => iso(patch[f]) !== iso(prev[f])).map((f) => ({
425
+ field: f,
426
+ from: iso(prev[f]),
427
+ to: iso(patch[f]),
428
+ }))
429
+ if (changes.length === 0) return { row: row!, activity: null }
430
+
431
+ const activity: HistoryInput = { workspaceId, assetId, actorId, action: 'updated', changes }
432
+ await this.notify.history(tx, activity)
433
+ return { row: row!, activity }
434
+ }
435
+
436
+ /**
437
+ * @param repairsOn whether the workspace records repairs, read before the transaction opened.
438
+ * The "it is away for repair" refusal below tells somebody to go and use `repairs.complete`, and
439
+ * that procedure answers 404 in a workspace with the capability off — so the refusal would be an
440
+ * instruction to open a door that is not there, and the asset could never leave the register.
441
+ */
442
+ async archive(
443
+ tx: Tx,
444
+ workspaceId: string,
445
+ actorId: string | null,
446
+ assetId: string,
447
+ archived: boolean,
448
+ repairsOn: boolean,
449
+ ): Promise<Written> {
450
+ /**
451
+ * **Locked before either refusal is decided, because both of them are about a race.**
452
+ *
453
+ * The two checks below used to read the facts with a plain select, so the state they call
454
+ * impossible was reachable by simply doing the two things at once: an archive and a handover
455
+ * each read "nobody is holding it", both were allowed, and the register was left with an
456
+ * archived asset and an open custody period — the timeline showing a handover that never ended,
457
+ * and "what is Ada still holding?" quietly not counting it, because that question excludes
458
+ * archived rows. A check whose answer another transaction may already have changed is not a
459
+ * check; it is a comment.
460
+ *
461
+ * The lock is the same one `CustodyService.stamp` and `RepairService.restamp` take before they
462
+ * write `status`, which is what makes the ordering complete rather than one-sided: whichever
463
+ * transaction gets it second re-reads what the first committed, so an archive that arrives
464
+ * first makes the handover refuse, and a handover that arrives first makes the archive refuse.
465
+ * `lockAsset` in `status.ts` argues it in full.
466
+ */
467
+ const [locked] = await tx
468
+ .select()
469
+ .from(assets)
470
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
471
+ .for('update')
472
+ if (!locked) throw KernError.notFound('Asset')
473
+
474
+ if (archived) {
475
+ /**
476
+ * An item somebody is holding cannot leave the register.
477
+ *
478
+ * Somebody is answerable for the thing; taking it out of the register does not make them not
479
+ * answerable, it only stops anybody being able to find out. Two steps instead of one, and
480
+ * both of them mean something.
481
+ */
482
+ if (locked.custodianUserId)
483
+ throw KernError.conflict(
484
+ 'Somebody is still holding this item. Take it back before archiving it.',
485
+ 'inventory.asset.still_held',
486
+ )
487
+
488
+ /**
489
+ * An item that is at a repairer cannot leave the register either, and for the same reason as
490
+ * custody: money is committed and the thing is out of the building, so taking it out of the
491
+ * register does not settle that — it only stops anybody being able to find out.
492
+ *
493
+ * It also keeps two counts that must agree from drifting. `stats.summary` reports
494
+ * `byStatus.under_repair` from the cached status column, over live rows only, and
495
+ * `outForRepair` from the repair rows themselves; an archived asset with an open repair
496
+ * would appear in one and not the other, and neither number would be wrong.
497
+ *
498
+ * **Only while the workspace records repairs.** With the `repairs` capability off, this
499
+ * refusal names a procedure that answers 404 — so it was not a two-step instruction, it was a
500
+ * dead end: the repair could not be completed, so the asset could not be archived, so the
501
+ * item was stuck in the register for as long as the capability stayed off. A refusal that
502
+ * points at a door has to be withdrawn when the door is taken away. `stats.away` counts only
503
+ * live assets for the same reason, so the two counts still cannot disagree.
504
+ */
505
+ const open = repairsOn ? await openRepairId(tx, workspaceId, assetId) : undefined
506
+ if (open)
507
+ throw KernError.conflict(
508
+ 'This item is away for repair. Log the repair as returned before archiving it.',
509
+ 'inventory.asset.under_repair',
510
+ )
511
+ }
512
+
513
+ const [row] = await tx
514
+ .update(assets)
515
+ .set({ archivedAt: archived ? new Date() : null, updatedAt: new Date() })
516
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
517
+ .returning()
518
+ if (!row) throw KernError.notFound('Asset')
519
+ const activity: HistoryInput = {
520
+ workspaceId,
521
+ assetId,
522
+ actorId,
523
+ action: archived ? 'retired' : 'restored',
524
+ }
525
+ await this.notify.history(tx, activity)
526
+ return { row, activity }
527
+ }
528
+ }