@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,83 @@
1
+ import { defineEvent, WorkspaceId } from '@kernhq/contracts'
2
+ import { z } from 'zod'
3
+
4
+ /**
5
+ * `<module>.<entity>.<action>`. Anything that emits one declares it here.
6
+ *
7
+ * Payloads carry **ids, never rows**. A subscriber that needs the record asks for it with its own
8
+ * principal, so an event cannot become a way to read data past a permission check.
9
+ */
10
+ export const inventoryEvents = {
11
+ assetCreated: defineEvent(
12
+ 'inventory.asset.created',
13
+ z.object({ assetId: z.uuid(), workspaceId: WorkspaceId }),
14
+ ),
15
+ assetUpdated: defineEvent(
16
+ 'inventory.asset.updated',
17
+ z.object({ assetId: z.uuid(), workspaceId: WorkspaceId }),
18
+ ),
19
+ assetArchived: defineEvent(
20
+ 'inventory.asset.archived',
21
+ z.object({ assetId: z.uuid(), workspaceId: WorkspaceId }),
22
+ ),
23
+ /**
24
+ * The other half of `archive`, which is also the restore path (`archived: false`).
25
+ *
26
+ * One procedure emitting `archived` whichever way the flag pointed told every subscriber that a
27
+ * restored item had just been retired — and the module's own `asset_history` row already knew
28
+ * better, recording `retired` and `restored` separately.
29
+ */
30
+ assetRestored: defineEvent(
31
+ 'inventory.asset.restored',
32
+ z.object({ assetId: z.uuid(), workspaceId: WorkspaceId }),
33
+ ),
34
+ /**
35
+ * One event for all three of assign, transfer and return, because a subscriber cares that the
36
+ * answer to "who has it" moved and not by which verb.
37
+ *
38
+ * `userId` is null when it came back to stock and `previousUserId` is null when it went out from
39
+ * stock, so the pair says which of the three happened without a fourth field claiming to. Both
40
+ * are ids, like everything else here: a subscriber that needs the person asks core with its own
41
+ * principal, so an event cannot become a way to read a name past a permission check.
42
+ *
43
+ * Nothing subscribes to it inside this module. It exists for what is outside — an offboarding
44
+ * automation that asks what somebody still holds, most obviously — which is the whole reason a
45
+ * module emits events rather than only writing its own history row.
46
+ */
47
+ custodyChanged: defineEvent(
48
+ 'inventory.custody.changed',
49
+ z.object({
50
+ assetId: z.uuid(),
51
+ workspaceId: WorkspaceId,
52
+ userId: z.uuid().nullable(),
53
+ previousUserId: z.uuid().nullable(),
54
+ }),
55
+ ),
56
+ /**
57
+ * An item went to a repairer, and an item came back.
58
+ *
59
+ * Two events rather than one, where custody has one for three verbs — because a subscriber to
60
+ * custody cares only that "who has it" moved, while these two are opposite facts with opposite
61
+ * reactions: something outside this module wants to tell the holder their laptop has gone, and
62
+ * something else wants to tell them it is back. A single `repair.changed` would make every
63
+ * subscriber re-read the row to find out which happened.
64
+ *
65
+ * No `repair.updated`: correcting a vendor or filling in an invoice a week later is not a fact
66
+ * anything outside this module reacts to, and the screens that do care are refreshed by
67
+ * `kernel.realtime.change`, which needs no declaration. Declaring one so the set looks symmetrical
68
+ * is the same lie as a capability nothing checks.
69
+ */
70
+ repairOpened: defineEvent(
71
+ 'inventory.repair.opened',
72
+ z.object({ assetId: z.uuid(), repairId: z.uuid(), workspaceId: WorkspaceId }),
73
+ ),
74
+ repairCompleted: defineEvent(
75
+ 'inventory.repair.completed',
76
+ z.object({ assetId: z.uuid(), repairId: z.uuid(), workspaceId: WorkspaceId }),
77
+ ),
78
+ // No category and no attachment events, deliberately. An event is for something outside this
79
+ // module to react to, and nothing outside it has an opinion about a workspace renaming "Laptops"
80
+ // or filing a receipt; the screens that do care are refreshed by `kernel.realtime.change`, which
81
+ // needs no declaration. Declaring one here so the list looks complete is the same lie as a
82
+ // capability nothing checks.
83
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What this module offers, as data.
3
+ *
4
+ * A barrel and nothing else: every symbol is defined in the file beside it. Imported by **both**
5
+ * halves — the server implements the contract, the client calls it — so nothing reachable from here
6
+ * may touch Node. A procedure that exists here and not in the router is a lie that compiles, and
7
+ * `module.test.ts` checks exactly that.
8
+ */
9
+
10
+ export * from './capabilities.js'
11
+ export * from './events.js'
12
+ export * from './models.js'
13
+ export * from './notifications.js'
14
+ export * from './permissions.js'
15
+ export * from './router.js'
16
+ export * from './settings.js'
@@ -0,0 +1,360 @@
1
+ import { WorkspaceId } from '@kernhq/contracts'
2
+ import { z } from 'zod'
3
+
4
+ /**
5
+ * The nouns this module owns, and the shapes that cross the wire.
6
+ *
7
+ * Imported by **both** halves — the server implements against them, the client calls against them —
8
+ * so nothing here may touch Node. Types only; the procedures live in `router.ts`.
9
+ */
10
+
11
+ /** Lowercase, 2-32 characters. Names the API prefix, the Postgres schema `mod_<id>` and every event. */
12
+ export const MODULE_ID = 'inventory'
13
+
14
+ /**
15
+ * An asset's lifecycle. `in_stock` and `assigned` follow custody (an open row in `custody_periods`
16
+ * means assigned); `under_repair` follows an open repair; `reserved` follows a booking that has not
17
+ * been collected; `lost` and `retired` are set by hand when an item stops being usable.
18
+ *
19
+ * Stored rather than derived, because every list filter asks for it — and kept in step inside the
20
+ * same transaction that writes the row it derives from, never by a job afterwards.
21
+ *
22
+ * **`under_repair` belongs to the `repairs` capability**, so a workspace with that switch off never
23
+ * has an asset in it: the procedure that ends a repair answers 404 there, and a status nothing can
24
+ * move an item out of is a register the workspace cannot correct. The one thing a job does here is
25
+ * bring the rows *nobody touches* back into step after that switch moves, in both directions —
26
+ * `deriveStatus` in `src/server/services/status.ts` argues it, and nothing is destroyed either way.
27
+ */
28
+ export const AssetStatus = z.enum(['in_stock', 'assigned', 'reserved', 'under_repair', 'lost', 'retired'])
29
+ export type AssetStatus = z.infer<typeof AssetStatus>
30
+
31
+ /**
32
+ * A value a workspace defined for itself, stored under its `key` in `assets.custom`.
33
+ *
34
+ * `unknown` rather than a union: the field definition says what the type is, and validating a value
35
+ * against a definition the client may not have loaded yet would fail honest input. The server checks
36
+ * it against `field_defs` before writing.
37
+ */
38
+ export const CustomValues = z.record(z.string(), z.unknown())
39
+ export type CustomValues = z.infer<typeof CustomValues>
40
+
41
+ /**
42
+ * A workspace's own grouping of what it owns — Laptops, Furniture, Cameras.
43
+ *
44
+ * Archived rather than deleted, and `archivedAt` is the whole reason: `assets.category_id` is a
45
+ * plain uuid with no foreign key, so a deleted category leaves every asset filed under it pointing
46
+ * at a row that is not there. The list column goes blank and the timeline entry that recorded the
47
+ * move loses the name it recorded. Archiving takes it out of every picker and every filter and
48
+ * leaves each asset able to say what it is.
49
+ */
50
+ export const Category = z.object({
51
+ id: z.uuid(),
52
+ workspaceId: WorkspaceId,
53
+ name: z.string().min(1).max(120),
54
+ /** Where it sits in a picker. Equal orders fall back to the name, so a workspace that never
55
+ * reorders anything still gets an alphabetical list rather than an arbitrary one. */
56
+ order: z.number().int(),
57
+ createdAt: z.string(),
58
+ updatedAt: z.string(),
59
+ archivedAt: z.string().nullable(),
60
+ })
61
+ export type Category = z.infer<typeof Category>
62
+
63
+ export const CategoryInput = z.object({
64
+ name: z.string().trim().min(1).max(120),
65
+ order: z.number().int().min(0).max(9999).optional(),
66
+ })
67
+ export type CategoryInput = z.infer<typeof CategoryInput>
68
+
69
+ /**
70
+ * One stretch of time during which one person held one asset.
71
+ *
72
+ * Effective-dated, exactly as HR keeps employments: nothing is ever updated in place, a change
73
+ * closes the open row and inserts a new one. `effectiveTo === null` means "still holding it", and
74
+ * `inventory_custody_no_overlap` — a GiST exclusion constraint on
75
+ * `(asset_id =, tstzrange(effective_from, effective_to, '[)') &&)` — makes two of those for one
76
+ * asset impossible in the database rather than merely unlikely in the service.
77
+ */
78
+ export const CustodyPeriod = z.object({
79
+ id: z.uuid(),
80
+ workspaceId: WorkspaceId,
81
+ assetId: z.uuid(),
82
+ /**
83
+ * The member who held it. A plain uuid — a cross-schema foreign key is what the module boundary
84
+ * exists to prevent — resolved against core membership at read time, which is also why a person
85
+ * who has since left the workspace still has readable history.
86
+ */
87
+ userId: z.uuid(),
88
+ note: z.string().max(500).nullable(),
89
+ effectiveFrom: z.string(),
90
+ effectiveTo: z.string().nullable(),
91
+ /** Who did the handing over, which is not always who received it. */
92
+ createdBy: z.uuid().nullable(),
93
+ createdAt: z.string(),
94
+ })
95
+ export type CustodyPeriod = z.infer<typeof CustodyPeriod>
96
+
97
+ /**
98
+ * One entry in an asset's timeline.
99
+ *
100
+ * `action` is a **plain string, deliberately not an enum**. The rows are append-only and outlive
101
+ * the image that wrote them: an instance rolled back to a previous release would fail to parse its
102
+ * own history the moment a newer image had written an action the older enum does not list — a
103
+ * timeline that 500s rather than one that says a little less. The client renders a sentence per
104
+ * action it knows and a neutral one for anything else. What is written today is `created`,
105
+ * `updated`, `assigned`, `transferred`, `returned`, `retired`, `restored`, `repair_logged`,
106
+ * `repair_completed`, `attachment_added` and `attachment_removed`.
107
+ */
108
+ export const AssetHistoryEntry = z.object({
109
+ id: z.uuid(),
110
+ assetId: z.uuid(),
111
+ /** Null for anything the platform did rather than a person. */
112
+ actorId: z.uuid().nullable(),
113
+ action: z.string().max(40),
114
+ changes: z.array(z.object({ field: z.string(), from: z.unknown(), to: z.unknown() })),
115
+ /** Action-specific ids — who received an item, who handed it over. Never a row. */
116
+ data: z.record(z.string(), z.unknown()),
117
+ occurredAt: z.string(),
118
+ })
119
+ export type AssetHistoryEntry = z.infer<typeof AssetHistoryEntry>
120
+
121
+ export const Asset = z.object({
122
+ id: z.uuid(),
123
+ workspaceId: WorkspaceId,
124
+ /** Human-facing asset tag (`INV-0001`), assigned by the server, unique per workspace. */
125
+ code: z.string().min(1).max(40),
126
+ name: z.string().min(1).max(200),
127
+ description: z.string().max(4000),
128
+ categoryId: z.uuid().nullable(),
129
+ status: AssetStatus,
130
+ /**
131
+ * The member currently holding the item. A plain uuid — cross-schema foreign keys are what the
132
+ * module boundary exists to prevent — resolved against core membership at read time.
133
+ */
134
+ custodianUserId: z.uuid().nullable(),
135
+ custodySince: z.string().nullable(),
136
+ serialNumber: z.string().max(200).nullable(),
137
+ location: z.string().max(200).nullable(),
138
+ purchasedOn: z.string().nullable(),
139
+ purchasedFrom: z.string().max(200).nullable(),
140
+ /** Minor units (cents), the convention billing established; formatted on the client. */
141
+ priceMinor: z.number().int().nullable(),
142
+ currency: z.string().length(3).nullable(),
143
+ warrantyUntil: z.string().nullable(),
144
+ photoFileId: z.uuid().nullable(),
145
+ custom: CustomValues,
146
+ createdAt: z.string(),
147
+ updatedAt: z.string(),
148
+ archivedAt: z.string().nullable(),
149
+ })
150
+ export type Asset = z.infer<typeof Asset>
151
+
152
+ /**
153
+ * What a custody procedure answers with: the asset as it now stands, and the period this call
154
+ * opened.
155
+ *
156
+ * Both, because a screen needs both and fetching the asset again afterwards is a second round trip
157
+ * that can read a row somebody else has changed in between — the panel would then show a handover
158
+ * that has already been undone. `period` is null on a return: something closed, nothing opened.
159
+ */
160
+ export const CustodyResult = z.object({
161
+ asset: Asset,
162
+ period: CustodyPeriod.nullable(),
163
+ })
164
+ export type CustodyResult = z.infer<typeof CustodyResult>
165
+
166
+ /**
167
+ * One trip an item made to a repairer.
168
+ *
169
+ * `returnedOn === null` means it is still away, and that single fact is what puts the asset in
170
+ * `under_repair` — see `deriveStatus` in `src/server/services/status.ts`, which is the only place
171
+ * the three columns that drive a status are read together.
172
+ *
173
+ * **A repair is not custody, and neither one cancels the other.** A laptop assigned to Dan that goes
174
+ * to the repairer is still Dan's responsibility: the custody period stays open, `custodianUserId`
175
+ * stays set, and only `status` moves. That is why a repair does not touch custody and custody does
176
+ * not refuse a repaired item — the two answer different questions ("who is answerable for it" and
177
+ * "where is it"), and collapsing them would mean an item could not come back to the person who sent
178
+ * it.
179
+ */
180
+ export const Repair = z.object({
181
+ id: z.uuid(),
182
+ workspaceId: WorkspaceId,
183
+ assetId: z.uuid(),
184
+ summary: z.string().min(1).max(200),
185
+ detail: z.string().max(4000).nullable(),
186
+ vendor: z.string().max(200).nullable(),
187
+ /** Minor units, like `Asset.priceMinor` — one convention for money across the module. */
188
+ costMinor: z.number().int().nullable(),
189
+ currency: z.string().length(3).nullable(),
190
+ sentOn: z.string(),
191
+ /** Null while it is still away. Set by `repairs.complete` and by nothing else. */
192
+ returnedOn: z.string().nullable(),
193
+ createdBy: z.uuid().nullable(),
194
+ createdAt: z.string(),
195
+ updatedAt: z.string(),
196
+ })
197
+ export type Repair = z.infer<typeof Repair>
198
+
199
+ /**
200
+ * A repair in a list, with the two things a reader needs to know *which item* it is about.
201
+ *
202
+ * **Joined at read time, never stored here.** `mod_inventory.repairs` holds no asset name, so
203
+ * renaming an asset renames it everywhere at once — a copied label is a label that goes stale, and
204
+ * this module already refuses to copy a person's name for the same reason. The join is inside one
205
+ * schema, which is the kind a module is allowed to make; the kind it is not is a join across the
206
+ * boundary into another module's tables.
207
+ *
208
+ * It extends `Repair` rather than replacing it, so a component that renders a repair renders one of
209
+ * these without knowing the difference. `create`, `update` and `complete` answer with a plain
210
+ * `Repair`: the caller of those already knows which asset it asked about.
211
+ */
212
+ export const RepairListItem = Repair.extend({
213
+ assetCode: z.string().min(1).max(40),
214
+ assetName: z.string().min(1).max(200),
215
+ })
216
+ export type RepairListItem = z.infer<typeof RepairListItem>
217
+
218
+ /**
219
+ * Everything a person can say about a repair.
220
+ *
221
+ * **No field here carries `.default()`, for the reason `AssetInput` spells out**: `update` is built
222
+ * from `.partial()`, and `.partial()` does not strip a default — zod still substitutes it for a key
223
+ * the request never sent, so a patch that renames a repair would silently re-date it. `sentOn` is
224
+ * optional rather than defaulted for the same reason; `repairs.create` fills today's date on the
225
+ * server, which is the only clock this module trusts.
226
+ */
227
+ export const RepairInput = z.object({
228
+ summary: z.string().trim().min(1).max(200),
229
+ detail: z.string().max(4000).nullish(),
230
+ vendor: z.string().max(200).nullish(),
231
+ costMinor: z.number().int().min(0).nullish(),
232
+ currency: z.string().length(3).nullish(),
233
+ /** `sent_on` is `not null` in the database, so this is optional but never nullable. */
234
+ sentOn: z.iso.date().optional(),
235
+ })
236
+ export type RepairInput = z.infer<typeof RepairInput>
237
+
238
+ export const RepairPatchInput = RepairInput.partial()
239
+ export type RepairPatchInput = z.infer<typeof RepairPatchInput>
240
+
241
+ /**
242
+ * What a repair mutation answers with: the repair, and the asset as it now stands.
243
+ *
244
+ * Both, for the reason `CustodyResult` carries both — sending an item away moves `assets.status`,
245
+ * and a screen that had to fetch the asset again afterwards would be reading a row somebody else
246
+ * may have changed in between.
247
+ */
248
+ export const RepairResult = z.object({
249
+ repair: Repair,
250
+ asset: Asset,
251
+ })
252
+ export type RepairResult = z.infer<typeof RepairResult>
253
+
254
+ /**
255
+ * A file recorded against an asset — a receipt, a warranty card, a manual.
256
+ *
257
+ * **The bytes are core's, not this module's.** A module does not upload: the browser uploads through
258
+ * core's file service and hands this module the id it was given, and reading one back is a download
259
+ * URL core signs. All that lives here is the fact that this asset has that file, plus the name and
260
+ * size copied at attach time so a list can be drawn without asking core once per row.
261
+ *
262
+ * `repairId` is what separates "the invoice for the screen replacement" from "the purchase receipt":
263
+ * null means it belongs to the asset itself.
264
+ */
265
+ export const Attachment = z.object({
266
+ id: z.uuid(),
267
+ workspaceId: WorkspaceId,
268
+ assetId: z.uuid(),
269
+ repairId: z.uuid().nullable(),
270
+ fileId: z.uuid(),
271
+ name: z.string().max(300),
272
+ mimeType: z.string().max(200).nullable(),
273
+ /** Bytes, as core reported them when the file was attached. */
274
+ size: z.number().int().nullable(),
275
+ uploadedBy: z.uuid().nullable(),
276
+ createdAt: z.string(),
277
+ })
278
+ export type Attachment = z.infer<typeof Attachment>
279
+
280
+ /**
281
+ * The register in numbers: what a page's count line and a dashboard card need in one request.
282
+ *
283
+ * `total` counts what the list shows by default — live rows — and `archived` is beside it rather
284
+ * than inside it, because a count line that silently included archived rows would disagree with the
285
+ * list under it.
286
+ *
287
+ * **`outForRepair` is null when the workspace does not track repairs.** Zero would be a claim
288
+ * ("nothing is away"), and a workspace with the `repairs` capability off has not made that claim —
289
+ * it has no opinion at all. The screens show the tile only when a number arrives, which is the same
290
+ * rule as hiding the Repairs tab, expressed in the data instead of in a second capability lookup.
291
+ */
292
+ export const InventoryStats = z.object({
293
+ total: z.number().int().nonnegative(),
294
+ archived: z.number().int().nonnegative(),
295
+ /** Every status, zero-filled, so a screen can render the set without knowing which exist. */
296
+ byStatus: z.record(AssetStatus, z.number().int().nonnegative()),
297
+ outForRepair: z.number().int().nonnegative().nullable(),
298
+ /** Live assets nobody is holding — what is actually available to hand out. */
299
+ unassigned: z.number().int().nonnegative(),
300
+ })
301
+ export type InventoryStats = z.infer<typeof InventoryStats>
302
+
303
+ /**
304
+ * How a list is ordered, and therefore what a page cursor is a bookmark *into*.
305
+ *
306
+ * Exported rather than written inline in `router.ts` because the server validates a cursor against
307
+ * this same list: a bookmark issued under one sort is meaningless under another, and the only way
308
+ * to say so is for both halves to read one enum.
309
+ */
310
+ export const AssetSort = z.enum(['recent', 'name', 'code'])
311
+ export type AssetSort = z.infer<typeof AssetSort>
312
+
313
+ /**
314
+ * Everything a person can say about an asset. `create` requires `name`; `update` takes any subset.
315
+ *
316
+ * **No field here carries `.default()`, and that is load-bearing.** `update` is built from
317
+ * `AssetInput.partial()`, and `.partial()` does not strip a default — it only wraps the field in
318
+ * `optional`, so zod still substitutes the default for a key the request never sent. `description`
319
+ * had `.default('')`, so `PATCH {assetId, name}` reached the handler as
320
+ * `{assetId, name, description: ''}`; the service correctly read a present value as "set it" and a
321
+ * rename destroyed the text, writing a bogus `description` diff into `asset_history` as it went.
322
+ * The care the service takes over `undefined` versus `null` is defeated one layer above it, here.
323
+ * A value `create` should fill in belongs on `AssetCreateInput` below, which is never partialled.
324
+ */
325
+ export const AssetInput = z.object({
326
+ name: z.string().min(1).max(200),
327
+ description: z.string().max(4000).optional(),
328
+ categoryId: z.uuid().nullish(),
329
+ serialNumber: z.string().max(200).nullish(),
330
+ location: z.string().max(200).nullish(),
331
+ purchasedFrom: z.string().max(200).nullish(),
332
+ purchasedOn: z.iso.date().nullish(),
333
+ warrantyUntil: z.iso.date().nullish(),
334
+ priceMinor: z.number().int().min(0).nullish(),
335
+ currency: z.string().length(3).nullish(),
336
+ photoFileId: z.uuid().nullish(),
337
+ // `custom` is deliberately absent: there is nothing to validate a value against until
338
+ // `fields.*` exists, and accepting arbitrary JSON into a column a workspace has not defined
339
+ // is how a schemaless field bag becomes permanent. It arrives with the field definitions.
340
+ })
341
+ export type AssetInput = z.infer<typeof AssetInput>
342
+
343
+ /**
344
+ * What `create` accepts: the same fields, with the one value a new row may not go without.
345
+ *
346
+ * `description` is `not null` in the database, so a create with no description needs *something*.
347
+ * Defaulting it here rather than in `AssetInput` is what keeps `update` able to tell "leave it
348
+ * alone" from "clear it" — see the note above.
349
+ */
350
+ export const AssetCreateInput = AssetInput.extend({
351
+ description: z.string().max(4000).default(''),
352
+ })
353
+ export type AssetCreateInput = z.infer<typeof AssetCreateInput>
354
+
355
+ /** What `update` accepts: any subset, and nothing filled in for a key that never arrived. */
356
+ export const AssetPatchInput = AssetInput.partial()
357
+ export type AssetPatchInput = z.infer<typeof AssetPatchInput>
358
+
359
+ /** Shared by every workspace-scoped procedure, which is all of them. */
360
+ export const ws = z.object({ workspaceId: WorkspaceId })
@@ -0,0 +1,73 @@
1
+ import type { core } from '@kernhq/contracts'
2
+
3
+ /**
4
+ * What Inventory will interrupt somebody about.
5
+ *
6
+ * Four things, and each of them changes what somebody has to *do*. That is the test: a rename, a new
7
+ * category, an item coming back — those are facts a screen shows when somebody looks, and a
8
+ * notification type nobody wants is a notification type everybody switches off along with the one
9
+ * that mattered.
10
+ *
11
+ * A type declared here and never sent is the same lie as a permission nothing checks. Each of these
12
+ * names its sender, and every one of them exists:
13
+ *
14
+ * - `custody.assigned` — `CustodyService`, on `assign` and `transfer`.
15
+ * - `warranty.expiring` — the `warranty-sweep` job, once per asset.
16
+ * - `repair.overdue` — the `repair-overdue` job, once per repair.
17
+ * - `custody.return_due` — the offboarding subscription, when HR says somebody has left or core says
18
+ * they have been removed from the workspace.
19
+ *
20
+ * The keys keep their `inventory.custody.*` spelling rather than being renamed to
21
+ * `inventory.asset.*`: a notification type is the key a person's own preferences are stored under,
22
+ * so renaming one silently resets everybody who had switched it off.
23
+ */
24
+ export const inventoryNotificationTypes: core.NotificationTypeDef[] = [
25
+ {
26
+ /**
27
+ * Everybody who has ever found a laptop on their desk with no idea it was now theirs is the
28
+ * reason this is `urgent` and reaches email — an asset register that records a handover the
29
+ * recipient never learns about has recorded an argument for later.
30
+ */
31
+ type: 'inventory.custody.assigned',
32
+ label: 'An item was handed to you',
33
+ description: 'Somebody made you the holder of an asset in the register.',
34
+ defaults: { inapp: true, push: true, email: true },
35
+ urgent: true,
36
+ },
37
+ {
38
+ /**
39
+ * Not urgent, and email is off by default. A warranty running out in a month is a thing to plan
40
+ * for, not a thing to stop for — and it arrives on a schedule rather than because somebody did
41
+ * something, which is exactly the kind of message that trains people to ignore the rest.
42
+ */
43
+ type: 'inventory.warranty.expiring',
44
+ label: 'A warranty is about to run out',
45
+ description: "An item's warranty expires soon. Sent once per item, to whoever is holding it.",
46
+ defaults: { inapp: true, push: false, email: false },
47
+ urgent: false,
48
+ },
49
+ {
50
+ /**
51
+ * Push, because this one is an action somebody has to take — ring the repairer — and nobody
52
+ * goes looking for it. Still not urgent: a laptop that has been away a fortnight can wait until
53
+ * the phone is picked up.
54
+ */
55
+ type: 'inventory.repair.overdue',
56
+ label: 'A repair has been away too long',
57
+ description: 'An item sent for repair has not been logged as returned. Sent once per repair.',
58
+ defaults: { inapp: true, push: true, email: false },
59
+ urgent: false,
60
+ },
61
+ {
62
+ /**
63
+ * Somebody is leaving and still has company property. Email, because it is a list of things to
64
+ * collect from a person who may not be at their desk much longer, and an in-app badge nobody
65
+ * opens until Monday is how a laptop leaves the building.
66
+ */
67
+ type: 'inventory.custody.return_due',
68
+ label: 'Somebody leaving still holds company property',
69
+ description: 'A member has left, or is leaving, and items are still recorded as theirs.',
70
+ defaults: { inapp: true, push: true, email: true },
71
+ urgent: true,
72
+ },
73
+ ]
@@ -0,0 +1,79 @@
1
+ import { definePermissions } from '@kernhq/contracts'
2
+
3
+ /**
4
+ * `<module>.<resource>.<action>`, each with the narrowest scope that works and the roles that hold
5
+ * it by default. A workspace can add or remove any of them afterwards with a custom role.
6
+ *
7
+ * A key with nothing checking it is a role editor full of switches that do nothing, so these arrive
8
+ * with the procedures that enforce them — `field.manage` and the stock and purchasing keys with
9
+ * their own phases.
10
+ *
11
+ * **Reading custody is `asset.view`, and that is a decision rather than an omission.** Who holds an
12
+ * item looks like a privacy question, and it is not one here: `custodianUserId` and `custodySince`
13
+ * are fields of `Asset`, returned by `assets.list` and `assets.get` under `asset.view` since the
14
+ * module existed, and `assets.list` has always taken a `custodianUserId` filter. A separate
15
+ * `custody.view` would be a lock on a door beside an open window — it would refuse the timeline
16
+ * while the row above it named the same person. "Who has the projector" is also the question an
17
+ * asset register exists to answer; a company where a member cannot find that out asks in chat
18
+ * instead, which is worse for whoever is holding it. A workspace that disagrees takes
19
+ * `inventory.asset.view` off `guest`, which is one switch and already there. Writing custody is
20
+ * `custody.manage`, because handing an item over makes somebody answerable for it.
21
+ */
22
+ export const inventoryPermissions = definePermissions([
23
+ {
24
+ key: 'inventory.asset.view',
25
+ label: 'View assets',
26
+ scope: 'workspace',
27
+ defaultRoles: ['owner', 'admin', 'member', 'guest'],
28
+ dangerous: false,
29
+ },
30
+ {
31
+ key: 'inventory.asset.manage',
32
+ label: 'Create and edit assets',
33
+ scope: 'workspace',
34
+ defaultRoles: ['owner', 'admin', 'member'],
35
+ dangerous: false,
36
+ },
37
+ {
38
+ /**
39
+ * Not `asset.manage`: correcting a serial number and making a colleague answerable for a
40
+ * £2,000 laptop are different acts, and plenty of workspaces want the first from everybody and
41
+ * the second from the office manager. Held by `member` by default all the same — an office
42
+ * where only an admin may hand over a charger keeps its register by not using it.
43
+ */
44
+ key: 'inventory.custody.manage',
45
+ label: 'Hand assets over and take them back',
46
+ scope: 'workspace',
47
+ defaultRoles: ['owner', 'admin', 'member'],
48
+ dangerous: false,
49
+ },
50
+ {
51
+ /**
52
+ * Sending an item away and recording what it cost, held by `member` for the same reason
53
+ * `custody.manage` is: the person who notices a broken screen is the person who should be able
54
+ * to log it, and an office where only an admin may do that keeps its repair record by not
55
+ * keeping one. Reading repairs rides `asset.view` — "where is the projector" is the question
56
+ * the register exists to answer, and a repair is one of the two answers.
57
+ *
58
+ * Not folded into `asset.manage`: correcting a serial number and committing the company to a
59
+ * £400 screen replacement are different acts, and the money is why.
60
+ */
61
+ key: 'inventory.repair.manage',
62
+ label: 'Log repairs',
63
+ scope: 'workspace',
64
+ defaultRoles: ['owner', 'admin', 'member'],
65
+ dangerous: false,
66
+ },
67
+ {
68
+ /**
69
+ * Categories are workspace configuration — one list everybody's assets are filed against — so
70
+ * this sits with the people who set the workspace up rather than with everybody who may edit an
71
+ * asset. Reading them rides `asset.view`, because the picker on the asset form needs them.
72
+ */
73
+ key: 'inventory.category.manage',
74
+ label: 'Manage asset categories',
75
+ scope: 'workspace',
76
+ defaultRoles: ['owner', 'admin'],
77
+ dangerous: false,
78
+ },
79
+ ])