@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,567 @@
1
+ import { KernError, type Tx, uuidv7 } from '@kernhq/kernel'
2
+ import { and, desc, eq, isNotNull, isNull, lt } from 'drizzle-orm'
3
+ import type {
4
+ RepairInput,
5
+ RepairListItem,
6
+ Repair as RepairModel,
7
+ RepairPatchInput,
8
+ } from '../../contract/models.js'
9
+ import { assets, repairs } from '../schema.js'
10
+ import { decodeMark, encodeMark } from './cursor.js'
11
+ import { violated } from './db-errors.js'
12
+ import type { HistoryInput, NotifyService } from './notify.js'
13
+ import { awayForRepair, deriveStatus, lockAsset } from './status.js'
14
+
15
+ type Row = typeof repairs.$inferSelect
16
+ type AssetRow = typeof assets.$inferSelect
17
+
18
+ /** The partial unique index `0003_repairs.sql` added. Two open repairs for one asset are it. */
19
+ const ONE_OPEN = 'inventory_repairs_one_open_uq'
20
+
21
+ /** The CHECK `0005_repair_dates.sql` added. A repair that came back before it was sent is it. */
22
+ const IN_ORDER = 'inventory_repairs_returned_after_sent'
23
+
24
+ /**
25
+ * The one ordering a repair list has, named rather than left as a literal.
26
+ *
27
+ * The cursor codec binds a bookmark to the sort it was issued under and refuses it under any other,
28
+ * so this list needs a name for its sort even while there is only one — and the day a second one
29
+ * exists, every cursor already in a browser tab is refused rather than misread.
30
+ */
31
+ const REPAIR_SORT = 'recent'
32
+
33
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
34
+ export function toRepair(row: Row): RepairModel {
35
+ return {
36
+ id: row.id,
37
+ workspaceId: row.workspaceId as RepairModel['workspaceId'],
38
+ assetId: row.assetId,
39
+ summary: row.summary,
40
+ detail: row.detail,
41
+ vendor: row.vendor,
42
+ costMinor: row.costMinor,
43
+ currency: row.currency,
44
+ sentOn: row.sentOn,
45
+ returnedOn: row.returnedOn ?? null,
46
+ createdBy: row.createdBy,
47
+ createdAt: row.createdAt.toISOString(),
48
+ updatedAt: row.updatedAt.toISOString(),
49
+ }
50
+ }
51
+
52
+ /**
53
+ * What one repair mutation wrote, and what may only leave the module once it has committed.
54
+ *
55
+ * The asset comes back beside the repair because sending an item away moves `assets.status`, and a
56
+ * caller that fetched the asset again afterwards would be reading a row somebody else may have
57
+ * changed in between — the panel would then show a repair that has already been completed.
58
+ */
59
+ export interface RepairWritten {
60
+ repair: Row
61
+ asset: AssetRow
62
+ /** `null` when nothing happened worth recording, which is what an edit that changed nothing is. */
63
+ activity: HistoryInput | null
64
+ }
65
+
66
+ export interface RepairListInput {
67
+ limit: number
68
+ cursor?: string
69
+ assetId?: string
70
+ /** `true` for still away, `false` for finished, absent for both. */
71
+ open?: boolean
72
+ }
73
+
74
+ /**
75
+ * What went away to be fixed, and what came back.
76
+ *
77
+ * Three things happen in one transaction on every change here, and the point of the class is that
78
+ * they cannot come apart: the repair row moves, `assets.status` is brought into step with it through
79
+ * `deriveStatus`, and an `asset_history` entry records it.
80
+ *
81
+ * **The database is the arbiter of "already away", not this file.** There is deliberately no
82
+ * `select … for update` on the asset *before* the repair row is written:
83
+ * `inventory_repairs_one_open_uq` — a unique index on `(asset_id) where returned_on is null` — is
84
+ * what makes two open repairs impossible, so two people pressing *Send for repair* on the same
85
+ * laptop in the same instant both read "it is here", both insert, and Postgres refuses exactly one
86
+ * of them. Checking first and inserting after is the race, not the fix. What this file owes the
87
+ * loser is a sentence they can act on rather than drizzle's "Failed query: insert into
88
+ * mod_inventory.repairs …".
89
+ *
90
+ * **`restamp` does lock it, afterwards, and that is a different job.** `assets.status` is derived
91
+ * from this module's repair rows *and* from custody, which another service writes, so the winner
92
+ * still has to compute an answer nobody can overwrite from a stale snapshot. See `lockAsset` in
93
+ * `status.ts`: the index decides the contest, the lock orders the bookkeeping that follows it.
94
+ *
95
+ * **Repairs do not touch custody.** An item at the repairer is still somebody's responsibility; see
96
+ * `status.ts`, where that rule is argued in full.
97
+ */
98
+ export class RepairService {
99
+ constructor(private readonly notify: NotifyService) {}
100
+
101
+ /**
102
+ * Today, as this module means it: the UTC date.
103
+ *
104
+ * Not the browser's date, and not a workspace time zone — a repair is dated to the day, and the
105
+ * two hours a workspace in Istanbul is ahead of UTC would put an evening repair on tomorrow for
106
+ * one reader and today for another. One clock, the server's, the same reasoning that keeps asset
107
+ * tags server-side. A workspace that needs the exact day sends `sentOn` itself.
108
+ */
109
+ private static today(): string {
110
+ return new Date().toISOString().slice(0, 10)
111
+ }
112
+
113
+ /** The one error a lost race produces, in every place a race can be lost. */
114
+ private static alreadyAway(): KernError {
115
+ return KernError.conflict(
116
+ 'This item is already away for repair. Log that one as returned first.',
117
+ 'inventory.repair.already_open',
118
+ )
119
+ }
120
+
121
+ /**
122
+ * A repair cannot come back before it was sent — checked on every path that writes either date.
123
+ *
124
+ * `complete` has always refused a return date before the send date, and `update` did not: it took
125
+ * `sentOn` from the patch and wrote it whatever the row already said, so correcting the send date
126
+ * of a *finished* repair could move it past the day the item came back. What that stores is a
127
+ * repair that ended before it started — every "how long was it away" answer negative, the overdue
128
+ * sweep measuring from a date in the future, and nothing anywhere to say which of the two dates is
129
+ * the wrong one.
130
+ *
131
+ * Both are `date` columns, so they read back as `YYYY-MM-DD` and compare correctly as text.
132
+ *
133
+ * The database holds the same rule (`inventory_repairs_returned_after_sent`), because two
134
+ * transactions can each pass this check and still write a pair that fails it: one moving `sent_on`
135
+ * while the other logs the item back. This runs first so the ordinary case gets a sentence rather
136
+ * than a constraint violation; `outOfOrder` is what the loser of that race gets.
137
+ */
138
+ private static requireInOrder(sentOn: string, returnedOn: string | null): void {
139
+ if (returnedOn !== null && returnedOn < sentOn) throw RepairService.outOfOrder()
140
+ }
141
+
142
+ private static outOfOrder(): KernError {
143
+ return KernError.conflict(
144
+ 'A repair cannot come back before it was sent.',
145
+ 'inventory.repair.returned_before_sent',
146
+ )
147
+ }
148
+
149
+ /**
150
+ * One day past today, which is the whole tolerance a date typed by a person needs.
151
+ *
152
+ * `today()` is UTC — one clock, the server's, for the reason it documents — and a workspace in
153
+ * Auckland is up to fourteen hours ahead of it, so *their* today is UTC's tomorrow for a large
154
+ * part of their working day. Refusing at exactly UTC-today would refuse the ordinary case in half
155
+ * the world's offices. A day is enough for every real time zone and is nowhere near enough to be
156
+ * the defect below.
157
+ */
158
+ private static readonly FUTURE_GRACE_DAYS = 1
159
+
160
+ /**
161
+ * A repair cannot be sent from the future — checked on every path that writes `sent_on`.
162
+ *
163
+ * `sentOn` is a date a person types, and nothing bounded it. A repair dated 2030 is one the
164
+ * overdue sweep can never find: it looks for `sent_on <= today - repairOverdueDays`, so a send
165
+ * date years ahead is permanently outside the window and the chase never fires. Not for a while —
166
+ * **ever**, for the life of that row, and silently, because a sweep that finds nothing looks
167
+ * exactly like a sweep with nothing to do. It also makes every "how long has it been away" answer
168
+ * negative and puts the item at the top of a list ordered by when it left.
169
+ *
170
+ * A typo is the likely cause and a deliberate one is the dangerous case: this is the one field
171
+ * that decides whether anybody is ever reminded that a vendor still has the company's laptop.
172
+ *
173
+ * Bounded on the *server*, not in the contract, and both halves of that are deliberate. The
174
+ * contract is shared with the browser, so a `refine` there would compare against the reader's own
175
+ * clock — and a client whose date is a day ahead would refuse a date the server accepts, or the
176
+ * other way round. And it is a sentence rather than a bare `invalid_string`, because "a repair
177
+ * cannot be sent in the future" is something a person can act on.
178
+ *
179
+ * **A `BAD_REQUEST` with no `reason`, like `checkPhoto`'s refusal and the category check in
180
+ * `AssetService`.** The date is malformed rather than contested — nothing raced, no state
181
+ * changed underneath anybody, the value simply cannot be true — and `CONFLICT` is this module's
182
+ * word for losing a race. The cost is that the sentence reaches a Persian or Turkish reader in
183
+ * English: a translated refusal needs a stable `reason` **and** its five bundles in
184
+ * `src/client/errors.ts`, and the two have to arrive together or `errors.test.ts` fails from
185
+ * whichever side is ahead.
186
+ */
187
+ private static requireNotFuture(sentOn: string): void {
188
+ const limit = new Date(`${RepairService.today()}T00:00:00Z`)
189
+ limit.setUTCDate(limit.getUTCDate() + RepairService.FUTURE_GRACE_DAYS)
190
+ if (sentOn > limit.toISOString().slice(0, 10))
191
+ throw KernError.badRequest('A repair cannot be sent in the future.')
192
+ }
193
+
194
+ private async asset(tx: Tx, workspaceId: string, assetId: string): Promise<AssetRow> {
195
+ const [row] = await tx
196
+ .select()
197
+ .from(assets)
198
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
199
+ if (!row) throw KernError.notFound('Asset')
200
+ return row
201
+ }
202
+
203
+ async get(tx: Tx, workspaceId: string, repairId: string): Promise<Row> {
204
+ const [row] = await tx
205
+ .select()
206
+ .from(repairs)
207
+ .where(and(eq(repairs.workspaceId, workspaceId), eq(repairs.id, repairId)))
208
+ if (!row) throw KernError.notFound('Repair')
209
+ return row
210
+ }
211
+
212
+ /**
213
+ * One asset's repairs, or the whole workspace's — one query with one filter, because they are one
214
+ * question asked at two scopes and a second query answering it would be a second one to keep in
215
+ * step.
216
+ *
217
+ * **Paged by id, newest logged first.** An id is uuidv7, so it already carries the clock, and it
218
+ * is unique where `sent_on` is a date two repairs logged on the same day share — a page boundary
219
+ * between two rows that share a sort key repeats one and drops the other. The same reasoning
220
+ * `assets.list` gives for `sort: 'recent'` and `assets.history` gives for ordering on the row id.
221
+ */
222
+ async list(
223
+ tx: Tx,
224
+ workspaceId: string,
225
+ input: RepairListInput,
226
+ ): Promise<{ items: RepairListItem[]; nextCursor: string | null }> {
227
+ const filters = [eq(repairs.workspaceId, workspaceId)]
228
+ if (input.assetId) filters.push(eq(repairs.assetId, input.assetId))
229
+ if (input.open === true) filters.push(isNull(repairs.returnedOn))
230
+ if (input.open === false) filters.push(isNotNull(repairs.returnedOn))
231
+ if (input.cursor) filters.push(lt(repairs.id, decodeMark(input.cursor, REPAIR_SORT).i))
232
+
233
+ /**
234
+ * Joined to the asset for its tag and name — inside one schema, which is the join a module is
235
+ * allowed to make. A workspace-wide list of what is away is unreadable without them, and
236
+ * copying them into `repairs` would be a label that goes stale the first time somebody renames
237
+ * an asset.
238
+ */
239
+ const rows = await tx
240
+ .select({ repair: repairs, code: assets.code, name: assets.name })
241
+ .from(repairs)
242
+ .innerJoin(assets, and(eq(assets.id, repairs.assetId), eq(assets.workspaceId, repairs.workspaceId)))
243
+ .where(and(...filters))
244
+ .orderBy(desc(repairs.id))
245
+ .limit(input.limit + 1)
246
+
247
+ const window = rows.slice(0, input.limit)
248
+ const last = window.at(-1)
249
+ const nextCursor =
250
+ rows.length > input.limit && last ? encodeMark({ i: last.repair.id, s: REPAIR_SORT }) : null
251
+ const items = window.map((row) => ({
252
+ ...toRepair(row.repair),
253
+ assetCode: row.code,
254
+ assetName: row.name,
255
+ }))
256
+ return { items, nextCursor }
257
+ }
258
+
259
+ /**
260
+ * The currency to store, given what the caller said and what is already there.
261
+ *
262
+ * A cost with no unit is not a cost, so an amount recorded with no currency inherits the asset's.
263
+ * **Inheritance fires in exactly one case** — an amount is being recorded and the repair has no
264
+ * currency at all — and getting that wrong is silent in both directions:
265
+ *
266
+ * - inheriting whenever a cost *exists* rather than whenever one *arrives* means an unrelated
267
+ * edit (correcting a vendor) silently gives the asset's currency back to a repair whose
268
+ * currency somebody deliberately cleared;
269
+ * - inheriting over a currency the repair already has means recording an amount in dollars on an
270
+ * asset priced in euros quietly relabels it as euros.
271
+ *
272
+ * `undefined` means "not mentioned" and an explicit `null` means "no currency", which a workspace
273
+ * that records amounts and not currencies genuinely means. Collapsing the two is the mistake
274
+ * `assets.update` documents one file over.
275
+ */
276
+ private static currencyFor(opts: {
277
+ /** What the request said, if it said anything. */
278
+ patch: string | null | undefined
279
+ /** The amount the request is recording, if it is recording one. */
280
+ cost: number | null | undefined
281
+ /** The currency the repair carries now. */
282
+ previous: string | null
283
+ asset: AssetRow
284
+ }): string | null {
285
+ if (opts.patch !== undefined) return opts.patch ?? null
286
+ if (opts.previous !== null) return opts.previous
287
+ return opts.cost === null || opts.cost === undefined ? null : (opts.asset.currency ?? null)
288
+ }
289
+
290
+ /** Send it away. Refuses when it is already at a repairer — that is what `complete` is for. */
291
+ async create(
292
+ tx: Tx,
293
+ workspaceId: string,
294
+ actorId: string | null,
295
+ assetId: string,
296
+ input: RepairInput,
297
+ ): Promise<RepairWritten> {
298
+ const asset = await this.asset(tx, workspaceId, assetId)
299
+ // An archived asset is one the workspace has said it no longer tracks. Paying to fix something
300
+ // that is not in the register is a mistake worth naming rather than recording.
301
+ if (asset.archivedAt)
302
+ throw KernError.conflict(
303
+ 'This item is archived. Restore it before sending it for repair.',
304
+ 'inventory.repair.archived',
305
+ )
306
+
307
+ const sentOn = input.sentOn ?? RepairService.today()
308
+ // Vacuous today, and deliberately here rather than reasoned about: `RepairInput` carries no
309
+ // `returnedOn`, so a new repair is always still away. The day it carries one, this is already
310
+ // the check, instead of being the one write path somebody forgot.
311
+ RepairService.requireInOrder(sentOn, null)
312
+ RepairService.requireNotFuture(sentOn)
313
+
314
+ let row: Row
315
+ try {
316
+ const inserted = await tx
317
+ .insert(repairs)
318
+ .values({
319
+ id: uuidv7(),
320
+ workspaceId,
321
+ assetId,
322
+ summary: input.summary,
323
+ detail: input.detail ?? null,
324
+ vendor: input.vendor ?? null,
325
+ costMinor: input.costMinor ?? null,
326
+ currency: RepairService.currencyFor({
327
+ patch: input.currency,
328
+ cost: input.costMinor,
329
+ previous: null,
330
+ asset,
331
+ }),
332
+ sentOn,
333
+ createdBy: actorId,
334
+ })
335
+ .returning()
336
+ row = inserted[0]!
337
+ } catch (err) {
338
+ // The index bit: another transaction opened a repair for this asset between our read and our
339
+ // insert. Anything else is a real fault and must not be disguised as a lost race.
340
+ if (violated(err, ONE_OPEN)) throw RepairService.alreadyAway()
341
+ throw err
342
+ }
343
+
344
+ const updated = await this.restamp(tx, workspaceId, assetId)
345
+ const activity: HistoryInput = {
346
+ workspaceId,
347
+ assetId,
348
+ actorId,
349
+ action: 'repair_logged',
350
+ data: { repairId: row.id, summary: row.summary, ...(row.vendor ? { vendor: row.vendor } : {}) },
351
+ }
352
+ await this.notify.history(tx, activity)
353
+ return { repair: row, asset: updated, activity }
354
+ }
355
+
356
+ /**
357
+ * Correct what was recorded — a vendor, or a cost that arrived with the invoice a week later.
358
+ *
359
+ * **`returnedOn` is deliberately not patchable.** That one column decides whether the asset reads
360
+ * as `under_repair`, so exactly one procedure moves it and the derived status has one door rather
361
+ * than two. Editing a finished repair is allowed all the same: the invoice usually arrives after
362
+ * the item does.
363
+ *
364
+ * **No `actorId`, because nothing here records one.** This writes no timeline entry — see the
365
+ * bottom of the method — and a parameter kept for symmetry with `create` and `complete` would be
366
+ * a parameter every caller has to supply and nothing reads.
367
+ */
368
+ async update(
369
+ tx: Tx,
370
+ workspaceId: string,
371
+ repairId: string,
372
+ patch: RepairPatchInput,
373
+ ): Promise<RepairWritten> {
374
+ const previous = await this.get(tx, workspaceId, repairId)
375
+ const asset = await this.asset(tx, workspaceId, previous.assetId)
376
+
377
+ // `undefined` means "not mentioned"; `null` means "clear it". Collapsing the two is how an edit
378
+ // of one field quietly wipes the others. `cost` is the patch's own value and not the merged
379
+ // one, so correcting a vendor cannot give the asset's currency back to a repair whose currency
380
+ // somebody deliberately cleared.
381
+ const sentOn = patch.sentOn ?? previous.sentOn
382
+ // `returnedOn` is not patchable, so the row's own value is the one this has to stay behind. An
383
+ // edit that moves the send date past the day the item came back is refused rather than stored.
384
+ RepairService.requireInOrder(sentOn, previous.returnedOn)
385
+ // And the same bound `create` applies, because this is the other door onto the same column —
386
+ // and the more dangerous one: moving `sent_on` forward also clears `overdue_notified_at`, so a
387
+ // correction into the future re-arms a chase that can then never fire.
388
+ RepairService.requireNotFuture(sentOn)
389
+ const values = {
390
+ summary: patch.summary ?? previous.summary,
391
+ detail: patch.detail !== undefined ? (patch.detail ?? null) : previous.detail,
392
+ vendor: patch.vendor !== undefined ? (patch.vendor ?? null) : previous.vendor,
393
+ costMinor: patch.costMinor !== undefined ? (patch.costMinor ?? null) : previous.costMinor,
394
+ currency: RepairService.currencyFor({
395
+ patch: patch.currency,
396
+ cost: patch.costMinor,
397
+ previous: previous.currency,
398
+ asset,
399
+ }),
400
+ sentOn,
401
+ /**
402
+ * Correcting the send date re-arms the overdue notice.
403
+ *
404
+ * `overdue_notified_at` marks that somebody has already been asked to chase this one, and the
405
+ * threshold is measured from `sent_on` — so a repair re-dated a month earlier is overdue for
406
+ * the first time and nobody would ever hear about it if the marker survived. Only when the
407
+ * date actually moved: correcting a vendor must not send the same chase again.
408
+ */
409
+ overdueNotifiedAt: sentOn === previous.sentOn ? previous.overdueNotifiedAt : null,
410
+ updatedAt: new Date(),
411
+ }
412
+
413
+ let row: Row | undefined
414
+ try {
415
+ const written = await tx
416
+ .update(repairs)
417
+ .set(values)
418
+ .where(and(eq(repairs.workspaceId, workspaceId), eq(repairs.id, repairId)))
419
+ .returning()
420
+ row = written[0]
421
+ } catch (err) {
422
+ // The CHECK bit: another transaction logged the item back between the check above and this
423
+ // statement, so the pair being written is out of order after all. A sentence, not a driver
424
+ // dump — the same debt every other constraint in this module is paid.
425
+ if (violated(err, IN_ORDER)) throw RepairService.outOfOrder()
426
+ throw err
427
+ }
428
+
429
+ /**
430
+ * **No timeline entry, and that is a decision.**
431
+ *
432
+ * The asset's timeline records what happened *to the asset*: it went away, and it came back.
433
+ * Correcting a vendor or filling in an invoice a week later did not happen to the asset, and a
434
+ * timeline that reported every such edit would bury the two entries that matter under the
435
+ * paperwork around them. The repair row's own `updated_at` is where "this was edited" lives,
436
+ * and the row is on screen beside it.
437
+ */
438
+ return { repair: row!, asset, activity: null }
439
+ }
440
+
441
+ /**
442
+ * It came back.
443
+ *
444
+ * `and returned_on is null` in the predicate is the optimistic guard, exactly as
445
+ * `CustodyService.close` uses: under READ COMMITTED a concurrent complete blocks this statement,
446
+ * and when it resumes the row no longer matches, so zero rows come back rather than a second
447
+ * completion silently overwriting the first one's date.
448
+ */
449
+ async complete(
450
+ tx: Tx,
451
+ workspaceId: string,
452
+ actorId: string | null,
453
+ repairId: string,
454
+ input: { returnedOn?: string; costMinor?: number | null; currency?: string | null },
455
+ ): Promise<RepairWritten> {
456
+ const previous = await this.get(tx, workspaceId, repairId)
457
+ if (previous.returnedOn)
458
+ throw KernError.conflict(
459
+ 'This repair is already logged as finished.',
460
+ 'inventory.repair.already_complete',
461
+ )
462
+ const asset = await this.asset(tx, workspaceId, previous.assetId)
463
+
464
+ const returnedOn = input.returnedOn ?? RepairService.today()
465
+ // A date is a fact somebody typed, and a person deserves a sentence about it rather than a
466
+ // constraint violation — the database refuses this pair too, and this is what stops it having
467
+ // to.
468
+ RepairService.requireInOrder(previous.sentOn, returnedOn)
469
+
470
+ let row: Row | undefined
471
+ try {
472
+ const written = await tx
473
+ .update(repairs)
474
+ .set({
475
+ returnedOn,
476
+ costMinor: input.costMinor !== undefined ? (input.costMinor ?? null) : previous.costMinor,
477
+ // The invoice usually arrives with the item, so this is where a cost is most often first
478
+ // recorded — and therefore where the currency is most often inherited.
479
+ currency: RepairService.currencyFor({
480
+ patch: input.currency,
481
+ cost: input.costMinor,
482
+ previous: previous.currency,
483
+ asset,
484
+ }),
485
+ updatedAt: new Date(),
486
+ })
487
+ .where(
488
+ and(eq(repairs.workspaceId, workspaceId), eq(repairs.id, repairId), isNull(repairs.returnedOn)),
489
+ )
490
+ .returning()
491
+ row = written[0]
492
+ } catch (err) {
493
+ // Another transaction moved `sent_on` past this return date between the check above and this
494
+ // statement. See `update`, which has the same guard for the same race seen from the other end.
495
+ if (violated(err, IN_ORDER)) throw RepairService.outOfOrder()
496
+ throw err
497
+ }
498
+ if (!row)
499
+ throw KernError.conflict(
500
+ 'Somebody logged this repair as finished a moment before you did. Reload to see where it is now.',
501
+ 'inventory.repair.already_complete',
502
+ )
503
+
504
+ const updated = await this.restamp(tx, workspaceId, previous.assetId)
505
+ const activity: HistoryInput = {
506
+ workspaceId,
507
+ assetId: previous.assetId,
508
+ actorId,
509
+ action: 'repair_completed',
510
+ data: {
511
+ repairId: row.id,
512
+ summary: row.summary,
513
+ ...(row.costMinor !== null ? { costMinor: row.costMinor, currency: row.currency } : {}),
514
+ },
515
+ }
516
+ await this.notify.history(tx, activity)
517
+ return { repair: row, asset: updated, activity }
518
+ }
519
+
520
+ /**
521
+ * Bring `assets.status` back into step with the facts, inside the same transaction.
522
+ *
523
+ * Both facts are **read** rather than assumed — the open repair as it now stands, and the
524
+ * custodian as the asset row carries it — and `deriveStatus` decides. Assuming `under_repair`
525
+ * after an insert and `in_stock` after a completion is the version of this that silently released
526
+ * whoever was still holding the item.
527
+ *
528
+ * **The asset is locked and re-read here, rather than passed in.** It used to take the row the
529
+ * caller had already fetched, which is a snapshot from before the repair was written and before
530
+ * anything else that touched the asset in between: a handover committing in that window was
531
+ * invisible, so this derived a status from a custodian that had stopped being current and wrote it
532
+ * over the handover's answer. Taking the row under the lock is what makes "read both facts, then
533
+ * derive" true rather than merely intended. `lockAsset` argues it in full.
534
+ */
535
+ private async restamp(tx: Tx, workspaceId: string, assetId: string): Promise<AssetRow> {
536
+ const asset = await lockAsset(tx, workspaceId, assetId)
537
+ // `true` rather than a parameter: every caller of this file is behind `requiresCapability
538
+ // ('repairs')`, so a workspace reaching here is a workspace that records repairs by
539
+ // construction. The two paths that are *not* behind it — custody and archive — take the switch
540
+ // as an argument, and `deriveStatus` says why.
541
+ const away = await awayForRepair(tx, workspaceId, assetId, true)
542
+ /**
543
+ * An archived item cannot be away for repair, and this is the other half of the refusal that
544
+ * says so.
545
+ *
546
+ * `assets.archive` reads "nothing open against it" under this same lock, so an archive racing a
547
+ * *new* repair is ordered against it — and whichever arrives second has to lose, or the register
548
+ * ends up holding exactly the state the refusal claims is impossible. Only while the repair is
549
+ * open: logging one back on a row somebody archived anyway has to stay possible, or the item is
550
+ * trapped away for ever.
551
+ */
552
+ if (away && asset.archivedAt)
553
+ throw KernError.conflict(
554
+ 'This item is archived. Restore it before sending it for repair.',
555
+ 'inventory.repair.archived',
556
+ )
557
+ const status = deriveStatus({ custodianUserId: asset.custodianUserId, awayForRepair: away })
558
+ if (status === asset.status) return asset
559
+ const [row] = await tx
560
+ .update(assets)
561
+ .set({ status, updatedAt: new Date() })
562
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
563
+ .returning()
564
+ if (!row) throw KernError.notFound('Asset')
565
+ return row
566
+ }
567
+ }