@kernhq/module-inventory 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +106 -25
  2. package/dist/contract/capabilities.d.ts +4 -4
  3. package/dist/contract/capabilities.d.ts.map +1 -1
  4. package/dist/contract/capabilities.js +51 -9
  5. package/dist/contract/capabilities.js.map +1 -1
  6. package/dist/contract/events.d.ts +43 -0
  7. package/dist/contract/events.d.ts.map +1 -1
  8. package/dist/contract/events.js +40 -0
  9. package/dist/contract/events.js.map +1 -1
  10. package/dist/contract/index.d.ts +1 -0
  11. package/dist/contract/index.d.ts.map +1 -1
  12. package/dist/contract/index.js +1 -0
  13. package/dist/contract/index.js.map +1 -1
  14. package/dist/contract/models.d.ts +345 -0
  15. package/dist/contract/models.d.ts.map +1 -1
  16. package/dist/contract/models.js +245 -0
  17. package/dist/contract/models.js.map +1 -1
  18. package/dist/contract/notifications.d.ts +24 -0
  19. package/dist/contract/notifications.d.ts.map +1 -0
  20. package/dist/contract/notifications.js +72 -0
  21. package/dist/contract/notifications.js.map +1 -0
  22. package/dist/contract/permissions.d.ts +52 -2
  23. package/dist/contract/permissions.d.ts.map +1 -1
  24. package/dist/contract/permissions.js +55 -2
  25. package/dist/contract/permissions.js.map +1 -1
  26. package/dist/contract/router.d.ts +1108 -0
  27. package/dist/contract/router.d.ts.map +1 -1
  28. package/dist/contract/router.js +253 -1
  29. package/dist/contract/router.js.map +1 -1
  30. package/dist/contract/settings.d.ts +2 -0
  31. package/dist/contract/settings.d.ts.map +1 -1
  32. package/dist/contract/settings.js +24 -4
  33. package/dist/contract/settings.js.map +1 -1
  34. package/dist/server/index.d.ts +8 -4
  35. package/dist/server/index.d.ts.map +1 -1
  36. package/dist/server/index.js +289 -5
  37. package/dist/server/index.js.map +1 -1
  38. package/dist/server/jobs.d.ts +48 -0
  39. package/dist/server/jobs.d.ts.map +1 -0
  40. package/dist/server/jobs.js +358 -0
  41. package/dist/server/jobs.js.map +1 -0
  42. package/dist/server/router.d.ts +1392 -0
  43. package/dist/server/router.d.ts.map +1 -1
  44. package/dist/server/router.js +385 -7
  45. package/dist/server/router.js.map +1 -1
  46. package/dist/server/schema.d.ts +134 -1
  47. package/dist/server/schema.d.ts.map +1 -1
  48. package/dist/server/schema.js +169 -4
  49. package/dist/server/schema.js.map +1 -1
  50. package/dist/server/services/assets.d.ts +69 -3
  51. package/dist/server/services/assets.d.ts.map +1 -1
  52. package/dist/server/services/assets.js +199 -31
  53. package/dist/server/services/assets.js.map +1 -1
  54. package/dist/server/services/attachments.d.ts +80 -0
  55. package/dist/server/services/attachments.d.ts.map +1 -0
  56. package/dist/server/services/attachments.js +182 -0
  57. package/dist/server/services/attachments.js.map +1 -0
  58. package/dist/server/services/audience.d.ts +15 -0
  59. package/dist/server/services/audience.d.ts.map +1 -0
  60. package/dist/server/services/audience.js +64 -0
  61. package/dist/server/services/audience.js.map +1 -0
  62. package/dist/server/services/categories.d.ts +157 -0
  63. package/dist/server/services/categories.d.ts.map +1 -0
  64. package/dist/server/services/categories.js +309 -0
  65. package/dist/server/services/categories.js.map +1 -0
  66. package/dist/server/services/cursor.d.ts +68 -0
  67. package/dist/server/services/cursor.d.ts.map +1 -0
  68. package/dist/server/services/cursor.js +39 -0
  69. package/dist/server/services/cursor.js.map +1 -0
  70. package/dist/server/services/custody.d.ts +175 -0
  71. package/dist/server/services/custody.d.ts.map +1 -0
  72. package/dist/server/services/custody.js +367 -0
  73. package/dist/server/services/custody.js.map +1 -0
  74. package/dist/server/services/db-errors.d.ts +7 -0
  75. package/dist/server/services/db-errors.d.ts.map +1 -0
  76. package/dist/server/services/db-errors.js +32 -0
  77. package/dist/server/services/db-errors.js.map +1 -0
  78. package/dist/server/services/index.d.ts +16 -0
  79. package/dist/server/services/index.d.ts.map +1 -1
  80. package/dist/server/services/index.js +25 -1
  81. package/dist/server/services/index.js.map +1 -1
  82. package/dist/server/services/members.d.ts +27 -0
  83. package/dist/server/services/members.d.ts.map +1 -0
  84. package/dist/server/services/members.js +39 -0
  85. package/dist/server/services/members.js.map +1 -0
  86. package/dist/server/services/notify.d.ts +43 -1
  87. package/dist/server/services/notify.d.ts.map +1 -1
  88. package/dist/server/services/notify.js +47 -5
  89. package/dist/server/services/notify.js.map +1 -1
  90. package/dist/server/services/offboarding.d.ts +70 -0
  91. package/dist/server/services/offboarding.d.ts.map +1 -0
  92. package/dist/server/services/offboarding.js +116 -0
  93. package/dist/server/services/offboarding.js.map +1 -0
  94. package/dist/server/services/repairs.d.ts +204 -0
  95. package/dist/server/services/repairs.d.ts.map +1 -0
  96. package/dist/server/services/repairs.js +476 -0
  97. package/dist/server/services/repairs.js.map +1 -0
  98. package/dist/server/services/search.d.ts +85 -0
  99. package/dist/server/services/search.d.ts.map +1 -0
  100. package/dist/server/services/search.js +142 -0
  101. package/dist/server/services/search.js.map +1 -0
  102. package/dist/server/services/stats.d.ts +42 -0
  103. package/dist/server/services/stats.d.ts.map +1 -0
  104. package/dist/server/services/stats.js +80 -0
  105. package/dist/server/services/stats.js.map +1 -0
  106. package/dist/server/services/status.d.ts +102 -0
  107. package/dist/server/services/status.d.ts.map +1 -0
  108. package/dist/server/services/status.js +71 -0
  109. package/dist/server/services/status.js.map +1 -0
  110. package/migrations/0002_custody_and_categories.sql +23 -0
  111. package/migrations/0003_repairs.sql +23 -0
  112. package/migrations/0004_platform_surfaces.sql +51 -0
  113. package/migrations/0005_repair_dates.sql +35 -0
  114. package/migrations/0006_workspace_registry_read.sql +50 -0
  115. package/migrations/0007_history_sequence.sql +83 -0
  116. package/migrations/0008_category_order_unique.sql +71 -0
  117. package/migrations/meta/0002_snapshot.json +1054 -0
  118. package/migrations/meta/0003_snapshot.json +1070 -0
  119. package/migrations/meta/0004_snapshot.json +1130 -0
  120. package/migrations/meta/0005_snapshot.json +1135 -0
  121. package/migrations/meta/_journal.json +49 -0
  122. package/package.json +2 -1
  123. package/src/client/api-instance.ts +27 -2
  124. package/src/client/bidi.test.ts +148 -0
  125. package/src/client/bidi.ts +85 -0
  126. package/src/client/components/AssetDetailPanel.svelte +614 -0
  127. package/src/client/components/AssetFormDialog.svelte +71 -22
  128. package/src/client/components/AssetPhoto.svelte +178 -0
  129. package/src/client/components/AttachmentsSection.svelte +327 -0
  130. package/src/client/components/CustodyDialog.svelte +201 -0
  131. package/src/client/components/RepairDialog.svelte +271 -0
  132. package/src/client/components/RepairsSection.svelte +318 -0
  133. package/src/client/components/Timeline.svelte +347 -0
  134. package/src/client/components/TimelineText.svelte +124 -0
  135. package/src/client/core-api.ts +71 -0
  136. package/src/client/custody.test.ts +31 -0
  137. package/src/client/custody.ts +34 -0
  138. package/src/client/errors.test.ts +395 -0
  139. package/src/client/errors.ts +229 -0
  140. package/src/client/links.test.ts +74 -0
  141. package/src/client/links.ts +44 -0
  142. package/src/client/members.test.ts +132 -0
  143. package/src/client/members.ts +116 -0
  144. package/src/client/messages.test.ts +127 -0
  145. package/src/client/messages.ts +1106 -18
  146. package/src/client/mock.test.ts +465 -1
  147. package/src/client/mock.ts +1105 -79
  148. package/src/client/module.ts +73 -1
  149. package/src/client/pages/AssetsPage.svelte +317 -45
  150. package/src/client/permissions.ts +7 -0
  151. package/src/client/price.test.ts +151 -3
  152. package/src/client/price.ts +155 -11
  153. package/src/client/query.ts +36 -0
  154. package/src/client/reorder.test.ts +100 -0
  155. package/src/client/reorder.ts +79 -0
  156. package/src/client/repairs.test.ts +38 -0
  157. package/src/client/repairs.ts +38 -0
  158. package/src/client/sequence.test.ts +248 -0
  159. package/src/client/sequence.ts +185 -0
  160. package/src/client/settings/CategoriesSettings.svelte +746 -0
  161. package/src/client/settings/GeneralSettings.svelte +0 -0
  162. package/src/client/status.ts +29 -0
  163. package/src/client/timeline.test.ts +175 -0
  164. package/src/client/timeline.ts +206 -0
  165. package/src/client/widgets/OverviewWidget.svelte +127 -26
  166. package/src/client/widgets/RepairsWidget.svelte +124 -0
  167. package/src/contract/capabilities.ts +53 -9
  168. package/src/contract/events.ts +49 -0
  169. package/src/contract/index.ts +1 -0
  170. package/src/contract/models.ts +270 -0
  171. package/src/contract/notifications.ts +73 -0
  172. package/src/contract/permissions.ts +55 -2
  173. package/src/contract/router.ts +284 -1
  174. package/src/contract/settings.ts +24 -4
  175. package/src/module.test.ts +217 -4
  176. package/src/server/index.ts +311 -4
  177. package/src/server/inventory.int.test.ts +4109 -19
  178. package/src/server/jobs.ts +444 -0
  179. package/src/server/migrations.test.ts +253 -2
  180. package/src/server/router.ts +486 -6
  181. package/src/server/schema.ts +171 -3
  182. package/src/server/services/assets.ts +214 -54
  183. package/src/server/services/attachments.ts +215 -0
  184. package/src/server/services/audience.ts +77 -0
  185. package/src/server/services/categories.ts +337 -0
  186. package/src/server/services/cursor.ts +104 -0
  187. package/src/server/services/custody.ts +471 -0
  188. package/src/server/services/db-errors.ts +42 -0
  189. package/src/server/services/index.ts +34 -1
  190. package/src/server/services/members.ts +54 -0
  191. package/src/server/services/notify.ts +52 -7
  192. package/src/server/services/offboarding.ts +150 -0
  193. package/src/server/services/repairs.ts +567 -0
  194. package/src/server/services/search.ts +166 -0
  195. package/src/server/services/stats.ts +88 -0
  196. package/src/server/services/status.test.ts +34 -0
  197. package/src/server/services/status.ts +143 -0
  198. package/src/client/settings/core-api.ts +0 -32
@@ -0,0 +1,39 @@
1
+ import { KernError } from '@kernhq/kernel';
2
+ export const encodeMark = (mark) => Buffer.from(JSON.stringify(mark), 'utf8').toString('base64url');
3
+ /** Cheap and total, and it runs before the value can reach a `::uuid` cast. */
4
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
+ export function decodeMark(cursor, sort) {
6
+ const refuse = () => KernError.badRequest('That page marker is not one this list issued');
7
+ let parsed;
8
+ try {
9
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
10
+ }
11
+ catch {
12
+ throw refuse();
13
+ }
14
+ if (typeof parsed?.i !== 'string' || !UUID.test(parsed.i))
15
+ throw refuse();
16
+ // One comparison covers both a sort this list never issues and a sort it issued under a
17
+ // *different* request. Either way the bookmark cannot be read against the ordering asked for,
18
+ // and pretending otherwise is what made "Load more" loop for ever.
19
+ if (parsed.s !== sort)
20
+ throw refuse();
21
+ return { i: parsed.i, s: sort };
22
+ }
23
+ export const encodeSeqMark = (mark) => Buffer.from(JSON.stringify(mark), 'utf8').toString('base64url');
24
+ export function decodeSeqMark(cursor, sort) {
25
+ const refuse = () => KernError.badRequest('That page marker is not one this list issued');
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
29
+ }
30
+ catch {
31
+ throw refuse();
32
+ }
33
+ if (typeof parsed?.n !== 'number' || !Number.isSafeInteger(parsed.n) || parsed.n < 1)
34
+ throw refuse();
35
+ if (parsed.s !== sort)
36
+ throw refuse();
37
+ return { n: parsed.n, s: sort };
38
+ }
39
+ //# sourceMappingURL=cursor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../../../src/server/services/cursor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAuC1C,MAAM,CAAC,MAAM,UAAU,GAAG,CAAmB,IAAiB,EAAU,EAAE,CACxE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;AAEjE,+EAA+E;AAC/E,MAAM,IAAI,GAAG,iEAAiE,CAAA;AAE9E,MAAM,UAAU,UAAU,CAAmB,MAAc,EAAE,IAAO;IAClE,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,SAAS,CAAC,UAAU,CAAC,8CAA8C,CAAC,CAAA;IACzF,IAAI,MAAmC,CAAA;IACvC,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,M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QAAE,MAAM,MAAM,EAAE,CAAA;IACpG,IAAI,MAAM,CAAC,CAAC,KAAK,IAAI;QAAE,MAAM,MAAM,EAAE,CAAA;IACrC,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAA;AACjC,CAAC"}
@@ -0,0 +1,175 @@
1
+ import { type Tx } from '@kernhq/kernel';
2
+ import type { CustodyPeriod as CustodyPeriodModel } from '../../contract/models.js';
3
+ import { assets, custodyPeriods } from '../schema.js';
4
+ import type { HistoryInput, NotifyService } from './notify.js';
5
+ type AssetRow = typeof assets.$inferSelect;
6
+ type PeriodRow = typeof custodyPeriods.$inferSelect;
7
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
8
+ export declare function toCustodyPeriod(row: PeriodRow): CustodyPeriodModel;
9
+ /**
10
+ * What one custody change wrote, and what may only leave the module once it has committed.
11
+ *
12
+ * `previousUserId` and `userId` are what `inventory.custody.changed` carries, and between them they
13
+ * say which of the three verbs happened without a fourth field claiming to: out from stock has no
14
+ * previous, back to stock has no next, a hand-on has both.
15
+ */
16
+ export interface CustodyWritten {
17
+ asset: AssetRow;
18
+ /** The period this call opened. Null on a return: something closed, nothing opened. */
19
+ period: PeriodRow | null;
20
+ userId: string | null;
21
+ previousUserId: string | null;
22
+ activity: HistoryInput;
23
+ /** Who to tell, which is the recipient and never the person doing the handing. */
24
+ notifyUserId: string | null;
25
+ }
26
+ /**
27
+ * Who is holding what, over time.
28
+ *
29
+ * Effective-dated the way HR keeps employments: **nothing is ever updated in place**. A change
30
+ * closes the open row and inserts a new one, so the answer to "who had this laptop in March" is a
31
+ * row that still exists rather than a value that was overwritten.
32
+ *
33
+ * Three things happen in one transaction on every change, and the whole point of the class is that
34
+ * they cannot come apart: the period rows move, `assets.custodian_user_id`/`custody_since`/`status`
35
+ * are brought into step with them, and an `asset_history` entry records it. The denormalised
36
+ * columns on `assets` are what the list filters and the widget read; they are correct because they
37
+ * are written here, in the same transaction, and never by a job afterwards.
38
+ *
39
+ * **A repair never refuses a handover.** An item at the repairer is still somebody's
40
+ * responsibility, so none of the three verbs looks at repair state to decide whether it may run —
41
+ * refusing `assign` would mean refusing `return` as well, and somebody leaving the company while
42
+ * their laptop is in the workshop has to be able to hand it back. What repair state *does* affect
43
+ * is the status these three write, which is `deriveStatus`'s job and is argued in `status.ts`.
44
+ *
45
+ * **The database is the arbiter of who won, not this file.** There is deliberately no `select … for
46
+ * update` before the period is inserted. `inventory_custody_no_overlap` — a GiST exclusion
47
+ * constraint on `(asset_id =, tstzrange(effective_from, effective_to, '[)') &&)` — is what makes two
48
+ * open periods impossible, so two people pressing *Hand over* on the same laptop in the same instant
49
+ * both read "nobody has it", both insert, and Postgres refuses exactly one of them. Locking the
50
+ * asset first would serialise them into two successful handovers, which is a worse answer wearing
51
+ * the clothes of a safer one. What this file owes the loser is a sentence they can act on rather
52
+ * than drizzle's "Failed query: insert into mod_inventory.custody_periods …", and that is `refuse()`
53
+ * below.
54
+ *
55
+ * **The asset row *is* locked afterwards, and that is a different job.** `stamp` takes it before it
56
+ * reads the repair state, because `status` is derived from two facts two services write and the
57
+ * winner of the race still has to write an answer nobody can overwrite from a stale snapshot. The
58
+ * distinction is argued at `lockAsset` in `status.ts`: the constraint decides the contest, the lock
59
+ * orders the bookkeeping that follows it.
60
+ */
61
+ export declare class CustodyService {
62
+ private readonly notify;
63
+ constructor(notify: NotifyService);
64
+ /**
65
+ * The one error a lost race produces, in every place a race can be lost.
66
+ *
67
+ * Actionable rather than apologetic: the reader's screen is now out of date, and the only thing
68
+ * they can do about it is look again. `reason` is stable so a client could eventually say it in
69
+ * the reader's own language; the message is the honest fallback until one does.
70
+ */
71
+ private static refuse;
72
+ private asset;
73
+ /** The period that has not been closed, if there is one. At most one exists, by construction. */
74
+ open(tx: Tx, workspaceId: string, assetId: string): Promise<PeriodRow | undefined>;
75
+ /**
76
+ * Every period for one asset, newest first.
77
+ *
78
+ * Capped rather than paged: the rows are bounded by how many times one item changed hands, which
79
+ * is tens over its life. Ordered by `effective_from` and then by id, because a hand-on closes one
80
+ * row and opens another at the same instant and the two would otherwise have no order between
81
+ * them — the panel would show the handover before the return it replaced, at random.
82
+ */
83
+ history(tx: Tx, workspaceId: string, assetId: string, limit: number): Promise<PeriodRow[]>;
84
+ /**
85
+ * Close the open period at `at`, or refuse.
86
+ *
87
+ * `and effective_to is null` in the predicate is the optimistic guard: under READ COMMITTED a
88
+ * concurrent close blocks this statement, and when it resumes the row no longer matches, so zero
89
+ * rows come back rather than a second close silently overwriting the first one's timestamp.
90
+ */
91
+ private close;
92
+ private openPeriod;
93
+ /**
94
+ * The three denormalised columns, brought into step inside the same transaction.
95
+ *
96
+ * **`status` is not `userId ? 'assigned' : 'in_stock'`, and that line is what this comment is
97
+ * about.** An item can be at a repairer *and* assigned to somebody — the repair does not release
98
+ * whoever is answerable for it — so a handover that wrote `assigned` unconditionally would
99
+ * announce a laptop as back in the office while it was still in the workshop. Both facts are read
100
+ * and `deriveStatus` decides; the rule is argued in full in `status.ts`.
101
+ *
102
+ * **The asset row is locked before the repair state is read, and the order is the point.** Without
103
+ * it a repair completing in another transaction is invisible here and this handover's status is
104
+ * derived from a snapshot that has already stopped being true — the two writes then interleave
105
+ * into a status matching neither. See `lockAsset`.
106
+ *
107
+ * The lock is also what makes `assets.archive`'s refusal real rather than advisory. Archiving
108
+ * reads "nobody is holding it" under the same lock, so a handover racing an archive is ordered
109
+ * against it: whichever gets the lock second sees what the first committed, and the re-check below
110
+ * is what turns that into a refusal instead of an archived asset with an open custody period.
111
+ *
112
+ * @param repairsOn whether the workspace records repairs, read before the transaction opened.
113
+ * A workspace that has switched the capability off has no `under_repair`, because the procedure
114
+ * that would end one answers 404 — `deriveStatus` argues it in full, and this is one of the two
115
+ * write paths that lets an asset out of a status nothing else could move it out of.
116
+ */
117
+ private stamp;
118
+ /**
119
+ * The latest instant this asset's custody trail already reaches.
120
+ *
121
+ * The end of the most recent closed period, or the start of the open one. One row answers it
122
+ * because the periods for an asset cannot overlap — that is what `inventory_custody_no_overlap`
123
+ * enforces — so the row that starts last also ends last.
124
+ */
125
+ private boundary;
126
+ /**
127
+ * The instant this change happens, for both halves of it.
128
+ *
129
+ * One value, so the period that closes and the period that opens abut exactly: `'[)'` ranges
130
+ * `[…, at)` and `[at, …)` do not overlap, where two `now()` calls a microsecond apart would leave
131
+ * a gap during which the asset was held by nobody.
132
+ *
133
+ * **It is a millisecond past the trail's own end, not `now()`, and both halves of that are a
134
+ * defect this replaced.**
135
+ *
136
+ * - `max(now, open.effectiveFrom)` produced a **zero-length period** whenever the two were equal,
137
+ * which two handovers inside one millisecond make them — a JS `Date` resolves no finer. `[t, t)`
138
+ * is empty, an empty range overlaps nothing, so the exclusion constraint waves it through and
139
+ * the trail permanently records somebody holding the item for no time at all. Anybody reading
140
+ * "who had this in March" gets a name that was never true. Strictly after the boundary, there
141
+ * is no such row to write.
142
+ * - `assign` used plain `now()`, which a clock that steps backwards puts *before* the end of the
143
+ * last closed period — so the new period overlapped a finished one, Postgres refused it with
144
+ * `23P01`, and the person was told "somebody changed who is holding this a moment before you
145
+ * did. Reload." Nobody had; reloading changes nothing; the handover is refused again every time.
146
+ * Reading the trail's own end rather than the clock makes that unreachable instead of merely
147
+ * better explained: the next period always starts after the last one ended, whatever the clock
148
+ * says.
149
+ *
150
+ * `now` still wins whenever it is ahead, which is every ordinary case — this only ever moves the
151
+ * instant forward, never back, so it cannot manufacture a period that starts before its asset was
152
+ * bought.
153
+ */
154
+ private instant;
155
+ /**
156
+ * Hand a free item to a member.
157
+ *
158
+ * Refuses when somebody already has it, rather than quietly taking it off them: `transfer` is the
159
+ * procedure that means "hand it on", and collapsing the two would make a mistyped assignment
160
+ * indistinguishable from a deliberate handover in the timeline everyone reads afterwards.
161
+ */
162
+ assign(tx: Tx, workspaceId: string, actorId: string | null, assetId: string, userId: string, note: string | null, repairsOn: boolean): Promise<CustodyWritten>;
163
+ /**
164
+ * Hand it straight on. One transaction, not a return followed by an assign.
165
+ *
166
+ * Two calls would leave the asset `in_stock` with no custodian in between — visible to anybody
167
+ * reading the list at that moment, and permanently visible in the timeline as a return nobody
168
+ * performed and a stock period nobody spent.
169
+ */
170
+ transfer(tx: Tx, workspaceId: string, actorId: string | null, assetId: string, userId: string, note: string | null, repairsOn: boolean): Promise<CustodyWritten>;
171
+ /** Take it back. Closes the open period and puts the item back in stock. */
172
+ return(tx: Tx, workspaceId: string, actorId: string | null, assetId: string, note: string | null, repairsOn: boolean): Promise<CustodyWritten>;
173
+ }
174
+ export {};
175
+ //# sourceMappingURL=custody.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custody.d.ts","sourceRoot":"","sources":["../../../src/server/services/custody.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,EAAE,EAAU,MAAM,gBAAgB,CAAA;AAE3D,OAAO,KAAK,EAAE,aAAa,IAAI,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AACnF,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAErD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAG9D,KAAK,QAAQ,GAAG,OAAO,MAAM,CAAC,YAAY,CAAA;AAC1C,KAAK,SAAS,GAAG,OAAO,cAAc,CAAC,YAAY,CAAA;AAYnD,oGAAoG;AACpG,wBAAgB,eAAe,CAAC,GAAG,EAAE,SAAS,GAAG,kBAAkB,CAYlE;AAED;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,QAAQ,CAAA;IACf,uFAAuF;IACvF,MAAM,EAAE,SAAS,GAAG,IAAI,CAAA;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,QAAQ,EAAE,YAAY,CAAA;IACtB,kFAAkF;IAClF,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;CAC5B;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EAAE,EACN,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,SAAS,EAAE,OAAO,GACjB,OAAO,CAAC,cAAc,CAAC;CAgC3B"}
@@ -0,0 +1,367 @@
1
+ import { KernError, uuidv7 } from '@kernhq/kernel';
2
+ import { and, desc, eq, isNull } from 'drizzle-orm';
3
+ import { assets, custodyPeriods } from '../schema.js';
4
+ import { violated } from './db-errors.js';
5
+ import { awayForRepair, deriveStatus, lockAsset } from './status.js';
6
+ /** The GiST exclusion constraint `0001_rls.sql` added. Two open periods for one asset are it. */
7
+ const NO_OVERLAP = 'inventory_custody_no_overlap';
8
+ /**
9
+ * One millisecond: the finest a JS `Date` resolves, and therefore the shortest custody period this
10
+ * module is able to write. See `instant` — it is what keeps two changes in the same millisecond
11
+ * from recording a period nobody held the item for.
12
+ */
13
+ const TICK_MS = 1;
14
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
15
+ export function toCustodyPeriod(row) {
16
+ return {
17
+ id: row.id,
18
+ workspaceId: row.workspaceId,
19
+ assetId: row.assetId,
20
+ userId: row.userId,
21
+ note: row.note,
22
+ effectiveFrom: row.effectiveFrom.toISOString(),
23
+ effectiveTo: row.effectiveTo?.toISOString() ?? null,
24
+ createdBy: row.createdBy,
25
+ createdAt: row.createdAt.toISOString(),
26
+ };
27
+ }
28
+ /**
29
+ * Who is holding what, over time.
30
+ *
31
+ * Effective-dated the way HR keeps employments: **nothing is ever updated in place**. A change
32
+ * closes the open row and inserts a new one, so the answer to "who had this laptop in March" is a
33
+ * row that still exists rather than a value that was overwritten.
34
+ *
35
+ * Three things happen in one transaction on every change, and the whole point of the class is that
36
+ * they cannot come apart: the period rows move, `assets.custodian_user_id`/`custody_since`/`status`
37
+ * are brought into step with them, and an `asset_history` entry records it. The denormalised
38
+ * columns on `assets` are what the list filters and the widget read; they are correct because they
39
+ * are written here, in the same transaction, and never by a job afterwards.
40
+ *
41
+ * **A repair never refuses a handover.** An item at the repairer is still somebody's
42
+ * responsibility, so none of the three verbs looks at repair state to decide whether it may run —
43
+ * refusing `assign` would mean refusing `return` as well, and somebody leaving the company while
44
+ * their laptop is in the workshop has to be able to hand it back. What repair state *does* affect
45
+ * is the status these three write, which is `deriveStatus`'s job and is argued in `status.ts`.
46
+ *
47
+ * **The database is the arbiter of who won, not this file.** There is deliberately no `select … for
48
+ * update` before the period is inserted. `inventory_custody_no_overlap` — a GiST exclusion
49
+ * constraint on `(asset_id =, tstzrange(effective_from, effective_to, '[)') &&)` — is what makes two
50
+ * open periods impossible, so two people pressing *Hand over* on the same laptop in the same instant
51
+ * both read "nobody has it", both insert, and Postgres refuses exactly one of them. Locking the
52
+ * asset first would serialise them into two successful handovers, which is a worse answer wearing
53
+ * the clothes of a safer one. What this file owes the loser is a sentence they can act on rather
54
+ * than drizzle's "Failed query: insert into mod_inventory.custody_periods …", and that is `refuse()`
55
+ * below.
56
+ *
57
+ * **The asset row *is* locked afterwards, and that is a different job.** `stamp` takes it before it
58
+ * reads the repair state, because `status` is derived from two facts two services write and the
59
+ * winner of the race still has to write an answer nobody can overwrite from a stale snapshot. The
60
+ * distinction is argued at `lockAsset` in `status.ts`: the constraint decides the contest, the lock
61
+ * orders the bookkeeping that follows it.
62
+ */
63
+ export class CustodyService {
64
+ notify;
65
+ constructor(notify) {
66
+ this.notify = notify;
67
+ }
68
+ /**
69
+ * The one error a lost race produces, in every place a race can be lost.
70
+ *
71
+ * Actionable rather than apologetic: the reader's screen is now out of date, and the only thing
72
+ * they can do about it is look again. `reason` is stable so a client could eventually say it in
73
+ * the reader's own language; the message is the honest fallback until one does.
74
+ */
75
+ static refuse() {
76
+ return KernError.conflict('Somebody changed who is holding this a moment before you did. Reload to see where it is now.', 'inventory.custody.conflict');
77
+ }
78
+ async asset(tx, workspaceId, assetId) {
79
+ const [row] = await tx
80
+ .select()
81
+ .from(assets)
82
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)));
83
+ if (!row)
84
+ throw KernError.notFound('Asset');
85
+ // An archived asset is one the workspace has said it no longer tracks. Handing it to somebody
86
+ // would make them answerable for something that is not in the register, and the timeline would
87
+ // carry a handover after a retirement.
88
+ if (row.archivedAt)
89
+ throw KernError.conflict('This item is archived. Restore it before handing it over.', 'inventory.custody.archived');
90
+ return row;
91
+ }
92
+ /** The period that has not been closed, if there is one. At most one exists, by construction. */
93
+ async open(tx, workspaceId, assetId) {
94
+ const [row] = await tx
95
+ .select()
96
+ .from(custodyPeriods)
97
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.assetId, assetId), isNull(custodyPeriods.effectiveTo)))
98
+ .limit(1);
99
+ return row;
100
+ }
101
+ /**
102
+ * Every period for one asset, newest first.
103
+ *
104
+ * Capped rather than paged: the rows are bounded by how many times one item changed hands, which
105
+ * is tens over its life. Ordered by `effective_from` and then by id, because a hand-on closes one
106
+ * row and opens another at the same instant and the two would otherwise have no order between
107
+ * them — the panel would show the handover before the return it replaced, at random.
108
+ */
109
+ async history(tx, workspaceId, assetId, limit) {
110
+ return tx
111
+ .select()
112
+ .from(custodyPeriods)
113
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.assetId, assetId)))
114
+ .orderBy(desc(custodyPeriods.effectiveFrom), desc(custodyPeriods.id))
115
+ .limit(limit);
116
+ }
117
+ /**
118
+ * Close the open period at `at`, or refuse.
119
+ *
120
+ * `and effective_to is null` in the predicate is the optimistic guard: under READ COMMITTED a
121
+ * concurrent close blocks this statement, and when it resumes the row no longer matches, so zero
122
+ * rows come back rather than a second close silently overwriting the first one's timestamp.
123
+ */
124
+ async close(tx, workspaceId, periodId, at) {
125
+ const [row] = await tx
126
+ .update(custodyPeriods)
127
+ .set({ effectiveTo: at })
128
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.id, periodId), isNull(custodyPeriods.effectiveTo)))
129
+ .returning();
130
+ if (!row)
131
+ throw CustodyService.refuse();
132
+ return row;
133
+ }
134
+ async openPeriod(tx, workspaceId, assetId, userId, note, actorId, at) {
135
+ try {
136
+ const [row] = await tx
137
+ .insert(custodyPeriods)
138
+ .values({
139
+ id: uuidv7(),
140
+ workspaceId,
141
+ assetId,
142
+ userId,
143
+ note,
144
+ effectiveFrom: at,
145
+ createdBy: actorId,
146
+ })
147
+ .returning();
148
+ return row;
149
+ }
150
+ catch (err) {
151
+ // The constraint bit: another transaction opened a period for this asset between our read and
152
+ // our insert. Anything else is a real fault and must not be disguised as a lost race.
153
+ if (violated(err, NO_OVERLAP))
154
+ throw CustodyService.refuse();
155
+ throw err;
156
+ }
157
+ }
158
+ /**
159
+ * The three denormalised columns, brought into step inside the same transaction.
160
+ *
161
+ * **`status` is not `userId ? 'assigned' : 'in_stock'`, and that line is what this comment is
162
+ * about.** An item can be at a repairer *and* assigned to somebody — the repair does not release
163
+ * whoever is answerable for it — so a handover that wrote `assigned` unconditionally would
164
+ * announce a laptop as back in the office while it was still in the workshop. Both facts are read
165
+ * and `deriveStatus` decides; the rule is argued in full in `status.ts`.
166
+ *
167
+ * **The asset row is locked before the repair state is read, and the order is the point.** Without
168
+ * it a repair completing in another transaction is invisible here and this handover's status is
169
+ * derived from a snapshot that has already stopped being true — the two writes then interleave
170
+ * into a status matching neither. See `lockAsset`.
171
+ *
172
+ * The lock is also what makes `assets.archive`'s refusal real rather than advisory. Archiving
173
+ * reads "nobody is holding it" under the same lock, so a handover racing an archive is ordered
174
+ * against it: whichever gets the lock second sees what the first committed, and the re-check below
175
+ * is what turns that into a refusal instead of an archived asset with an open custody period.
176
+ *
177
+ * @param repairsOn whether the workspace records repairs, read before the transaction opened.
178
+ * A workspace that has switched the capability off has no `under_repair`, because the procedure
179
+ * that would end one answers 404 — `deriveStatus` argues it in full, and this is one of the two
180
+ * write paths that lets an asset out of a status nothing else could move it out of.
181
+ */
182
+ async stamp(tx, workspaceId, assetId, userId, at, repairsOn) {
183
+ const locked = await lockAsset(tx, workspaceId, assetId);
184
+ /**
185
+ * Re-read under the lock, because the check in `asset()` was made against a snapshot an archive
186
+ * committed a moment later could already have replaced.
187
+ *
188
+ * **Only when somebody is being *given* the item, and that is a narrowing rather than an escape
189
+ * hatch.** A return never reaches this branch with an archived row at all: `return` calls
190
+ * `asset()` first, and `asset()` refuses an archived asset outright, whichever verb asked. The
191
+ * condition is here because a *return* has nothing to race — it can only ever leave the asset
192
+ * unheld — so re-checking it would be a refusal with no state behind it. This comment used to
193
+ * claim the opposite, that a return on an archived asset is deliberately allowed so an item that
194
+ * had reached the impossible state could be undone; it is not allowed, it never was, and the
195
+ * lock in `assets.archive` is what makes that state unreachable rather than merely rare.
196
+ */
197
+ if (userId !== null && locked.archivedAt)
198
+ throw KernError.conflict('This item is archived. Restore it before handing it over.', 'inventory.custody.archived');
199
+ const status = deriveStatus({
200
+ custodianUserId: userId,
201
+ awayForRepair: await awayForRepair(tx, workspaceId, assetId, repairsOn),
202
+ });
203
+ const [row] = await tx
204
+ .update(assets)
205
+ .set({
206
+ custodianUserId: userId,
207
+ custodySince: at,
208
+ status,
209
+ updatedAt: new Date(),
210
+ })
211
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.id, assetId)))
212
+ .returning();
213
+ if (!row)
214
+ throw KernError.notFound('Asset');
215
+ return row;
216
+ }
217
+ /**
218
+ * The latest instant this asset's custody trail already reaches.
219
+ *
220
+ * The end of the most recent closed period, or the start of the open one. One row answers it
221
+ * because the periods for an asset cannot overlap — that is what `inventory_custody_no_overlap`
222
+ * enforces — so the row that starts last also ends last.
223
+ */
224
+ async boundary(tx, workspaceId, assetId) {
225
+ const [row] = await tx
226
+ .select({ from: custodyPeriods.effectiveFrom, to: custodyPeriods.effectiveTo })
227
+ .from(custodyPeriods)
228
+ .where(and(eq(custodyPeriods.workspaceId, workspaceId), eq(custodyPeriods.assetId, assetId)))
229
+ .orderBy(desc(custodyPeriods.effectiveFrom), desc(custodyPeriods.id))
230
+ .limit(1);
231
+ return row ? (row.to ?? row.from) : null;
232
+ }
233
+ /**
234
+ * The instant this change happens, for both halves of it.
235
+ *
236
+ * One value, so the period that closes and the period that opens abut exactly: `'[)'` ranges
237
+ * `[…, at)` and `[at, …)` do not overlap, where two `now()` calls a microsecond apart would leave
238
+ * a gap during which the asset was held by nobody.
239
+ *
240
+ * **It is a millisecond past the trail's own end, not `now()`, and both halves of that are a
241
+ * defect this replaced.**
242
+ *
243
+ * - `max(now, open.effectiveFrom)` produced a **zero-length period** whenever the two were equal,
244
+ * which two handovers inside one millisecond make them — a JS `Date` resolves no finer. `[t, t)`
245
+ * is empty, an empty range overlaps nothing, so the exclusion constraint waves it through and
246
+ * the trail permanently records somebody holding the item for no time at all. Anybody reading
247
+ * "who had this in March" gets a name that was never true. Strictly after the boundary, there
248
+ * is no such row to write.
249
+ * - `assign` used plain `now()`, which a clock that steps backwards puts *before* the end of the
250
+ * last closed period — so the new period overlapped a finished one, Postgres refused it with
251
+ * `23P01`, and the person was told "somebody changed who is holding this a moment before you
252
+ * did. Reload." Nobody had; reloading changes nothing; the handover is refused again every time.
253
+ * Reading the trail's own end rather than the clock makes that unreachable instead of merely
254
+ * better explained: the next period always starts after the last one ended, whatever the clock
255
+ * says.
256
+ *
257
+ * `now` still wins whenever it is ahead, which is every ordinary case — this only ever moves the
258
+ * instant forward, never back, so it cannot manufacture a period that starts before its asset was
259
+ * bought.
260
+ */
261
+ async instant(tx, workspaceId, assetId) {
262
+ const boundary = await this.boundary(tx, workspaceId, assetId);
263
+ return new Date(Math.max(Date.now(), boundary ? boundary.getTime() + TICK_MS : 0));
264
+ }
265
+ /**
266
+ * Hand a free item to a member.
267
+ *
268
+ * Refuses when somebody already has it, rather than quietly taking it off them: `transfer` is the
269
+ * procedure that means "hand it on", and collapsing the two would make a mistyped assignment
270
+ * indistinguishable from a deliberate handover in the timeline everyone reads afterwards.
271
+ */
272
+ async assign(tx, workspaceId, actorId, assetId, userId, note, repairsOn) {
273
+ // Called for its two refusals — a row in another workspace is a 404, an archived one a
274
+ // conflict — and not for the row, which `stamp` returns below in its post-handover shape.
275
+ await this.asset(tx, workspaceId, assetId);
276
+ const open = await this.open(tx, workspaceId, assetId);
277
+ if (open)
278
+ throw KernError.conflict(open.userId === userId
279
+ ? 'They are already holding this item.'
280
+ : 'Somebody else is holding this item. Hand it on, or take it back first.', 'inventory.custody.already_held');
281
+ const at = await this.instant(tx, workspaceId, assetId);
282
+ const period = await this.openPeriod(tx, workspaceId, assetId, userId, note, actorId, at);
283
+ const row = await this.stamp(tx, workspaceId, assetId, userId, at, repairsOn);
284
+ const activity = {
285
+ workspaceId,
286
+ assetId,
287
+ actorId,
288
+ action: 'assigned',
289
+ data: { userId, ...(note ? { note } : {}) },
290
+ };
291
+ await this.notify.history(tx, activity);
292
+ return {
293
+ asset: row,
294
+ period,
295
+ userId,
296
+ previousUserId: null,
297
+ activity,
298
+ // Never the person doing the handing: telling somebody what they just did is the notification
299
+ // everybody switches the type off over.
300
+ notifyUserId: userId === actorId ? null : userId,
301
+ };
302
+ }
303
+ /**
304
+ * Hand it straight on. One transaction, not a return followed by an assign.
305
+ *
306
+ * Two calls would leave the asset `in_stock` with no custodian in between — visible to anybody
307
+ * reading the list at that moment, and permanently visible in the timeline as a return nobody
308
+ * performed and a stock period nobody spent.
309
+ */
310
+ async transfer(tx, workspaceId, actorId, assetId, userId, note, repairsOn) {
311
+ await this.asset(tx, workspaceId, assetId);
312
+ const open = await this.open(tx, workspaceId, assetId);
313
+ if (!open)
314
+ throw KernError.conflict('Nobody is holding this item, so there is nothing to hand on. Assign it instead.', 'inventory.custody.not_held');
315
+ if (open.userId === userId)
316
+ throw KernError.conflict('They are already holding this item.', 'inventory.custody.already_held');
317
+ const at = await this.instant(tx, workspaceId, assetId);
318
+ await this.close(tx, workspaceId, open.id, at);
319
+ const period = await this.openPeriod(tx, workspaceId, assetId, userId, note, actorId, at);
320
+ const row = await this.stamp(tx, workspaceId, assetId, userId, at, repairsOn);
321
+ const activity = {
322
+ workspaceId,
323
+ assetId,
324
+ actorId,
325
+ action: 'transferred',
326
+ data: { userId, previousUserId: open.userId, ...(note ? { note } : {}) },
327
+ };
328
+ await this.notify.history(tx, activity);
329
+ return {
330
+ asset: row,
331
+ period,
332
+ userId,
333
+ previousUserId: open.userId,
334
+ activity,
335
+ notifyUserId: userId === actorId ? null : userId,
336
+ };
337
+ }
338
+ /** Take it back. Closes the open period and puts the item back in stock. */
339
+ async return(tx, workspaceId, actorId, assetId, note, repairsOn) {
340
+ await this.asset(tx, workspaceId, assetId);
341
+ const open = await this.open(tx, workspaceId, assetId);
342
+ if (!open)
343
+ throw KernError.conflict('Nobody is holding this item, so there is nothing to take back.', 'inventory.custody.not_held');
344
+ const at = await this.instant(tx, workspaceId, assetId);
345
+ await this.close(tx, workspaceId, open.id, at);
346
+ const row = await this.stamp(tx, workspaceId, assetId, null, null, repairsOn);
347
+ const activity = {
348
+ workspaceId,
349
+ assetId,
350
+ actorId,
351
+ action: 'returned',
352
+ data: { previousUserId: open.userId, ...(note ? { note } : {}) },
353
+ };
354
+ await this.notify.history(tx, activity);
355
+ return {
356
+ asset: row,
357
+ period: null,
358
+ userId: null,
359
+ previousUserId: open.userId,
360
+ activity,
361
+ // A return is not news to anybody: the person who had it knows they handed it back, and the
362
+ // person taking it back is the one making the call.
363
+ notifyUserId: null,
364
+ };
365
+ }
366
+ }
367
+ //# sourceMappingURL=custody.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custody.js","sourceRoot":"","sources":["../../../src/server/services/custody.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAW,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAC3D,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEnD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AACrD,OAAO,EAAE,QAAQ,EAA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 -0,0 +1,7 @@
1
+ /** The constraint's name, if a named one refused the write. */
2
+ export declare const constraintOf: (err: unknown) => string | undefined;
3
+ /** The SQLSTATE, if one reached us. `23P01` is an exclusion violation, `23505` a unique one. */
4
+ export declare const sqlStateOf: (err: unknown) => string | undefined;
5
+ /** Did this write lose to `name`, whichever way Postgres reported it? */
6
+ export declare const violated: (err: unknown, name: string) => boolean;
7
+ //# sourceMappingURL=db-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db-errors.d.ts","sourceRoot":"","sources":["../../../src/server/services/db-errors.ts"],"names":[],"mappings":"AAgCA,+DAA+D;AAC/D,eAAO,MAAM,YAAY,GAAI,KAAK,OAAO,KAAG,MAAM,GAAG,SAC4B,CAAA;AAEjF,gGAAgG;AAChG,eAAO,MAAM,UAAU,GAAI,KAAK,OAAO,KAAG,MAAM,GAAG,SACkD,CAAA;AAErG,yEAAyE;AACzE,eAAO,MAAM,QAAQ,GAAI,KAAK,OAAO,EAAE,MAAM,MAAM,KAAG,OAAqC,CAAA"}