@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,116 @@
1
+ import { and, asc, eq, isNull } from 'drizzle-orm';
2
+ import { MODULE_ID } from '../../contract/models.js';
3
+ import { assets } from '../schema.js';
4
+ import { membersWithPermission } from './audience.js';
5
+ import { assetUrl } from './search.js';
6
+ /** How many tags fit in one sentence before it stops being readable. */
7
+ const TAGS_IN_BODY = 5;
8
+ /**
9
+ * More than anybody is plausibly holding, and a bound all the same: this reads every live asset of
10
+ * one person, and an unbounded query in an event handler is an unbounded query.
11
+ */
12
+ const MAX_HELD = 200;
13
+ /**
14
+ * Somebody is leaving, and the register still says things are theirs.
15
+ *
16
+ * **This raises a checklist and notifies. It never moves anything.** Custody changes because a
17
+ * person did something — handed an item over, handed it on, took it back — and every one of those
18
+ * writes a period row and a line of history saying who did it. A hook that quietly returned an
19
+ * item on somebody's last day would write a handover nobody performed, into the one record the
20
+ * company later argues from; and the laptop would still be in their bag. So the answer is a message
21
+ * to the people who can take it back, and the register stays exactly as true as it was.
22
+ *
23
+ * **It is inert without HR.** Nothing here imports HR, depends on it, or assumes it is installed:
24
+ * `hr.person.status_changed` simply never arrives in a workspace that has no HR, and the second
25
+ * caller — `core.member.removed` — is core's own event and needs nothing at all. Both paths check
26
+ * the *inventory* module is switched on for the workspace before doing anything, because an event
27
+ * bus is instance-wide and a workspace that has never enabled this module must not be sent its
28
+ * notifications.
29
+ */
30
+ export class OffboardingService {
31
+ kernel;
32
+ notify;
33
+ constructor(kernel, notify) {
34
+ this.kernel = kernel;
35
+ this.notify = notify;
36
+ }
37
+ /**
38
+ * What one person is still recorded as holding.
39
+ *
40
+ * Read from `assets.custodian_user_id` — denormalised inside the transaction that writes the
41
+ * custody period, and indexed — rather than from an open-period join, which is the same choice
42
+ * `custody.byUser` makes and for the same reason. Archived rows cannot appear: an item somebody
43
+ * holds cannot be archived at all, because `assets.archive` refuses it.
44
+ */
45
+ async held(workspaceId, userId) {
46
+ return this.kernel.database.withWorkspace(workspaceId, (tx) => tx
47
+ .select({ id: assets.id, code: assets.code, name: assets.name })
48
+ .from(assets)
49
+ .where(and(eq(assets.workspaceId, workspaceId), eq(assets.custodianUserId, userId), isNull(assets.archivedAt)))
50
+ .orderBy(asc(assets.code))
51
+ .limit(MAX_HELD));
52
+ }
53
+ /**
54
+ * Raise the return list, if there is one.
55
+ *
56
+ * Answers with what it found and who it told, so a test can assert both and a caller can log the
57
+ * count. Doing nothing is the ordinary case — most people leave holding nothing — and it is not
58
+ * an error.
59
+ *
60
+ * Redelivery sends the same message again: an event handler is retried, and `core.notifications
61
+ * .create` has no idempotency key. The two events behind this are rare enough that the cost is a
62
+ * duplicate row rather than a stream, and `groupKey` collapses them where a client groups. That
63
+ * is the same trade `module-tracker`'s `due-soon` makes, written down rather than assumed.
64
+ */
65
+ async raise(workspaceId, userId, departure) {
66
+ if (!(await this.kernel.isModuleEnabled(workspaceId, MODULE_ID).catch(() => false)))
67
+ return { items: [], recipients: [] };
68
+ const items = await this.held(workspaceId, userId);
69
+ if (!items.length)
70
+ return { items: [], recipients: [] };
71
+ // Whoever may take an item back, which is the thing this message is asking for. Not "the
72
+ // admins": a workspace that gave its office manager a custom role did that on purpose.
73
+ const recipients = await membersWithPermission(this.kernel, workspaceId, 'inventory.custody.manage');
74
+ if (!recipients.length) {
75
+ this.kernel.log.warn({ module: MODULE_ID, workspaceId, held: items.length }, 'inventory: somebody left holding items and nobody in the workspace may take them back');
76
+ return { items, recipients: [] };
77
+ }
78
+ const who = await this.nameOf(userId);
79
+ const tags = items.slice(0, TAGS_IN_BODY).map((item) => `${item.code} ${item.name}`);
80
+ const rest = items.length - tags.length;
81
+ await this.notify.notify({
82
+ workspaceId,
83
+ userIds: recipients,
84
+ type: 'inventory.custody.return_due',
85
+ title: departure === 'removed'
86
+ ? `${who} has left the workspace still holding ${items.length === 1 ? 'an item' : `${items.length} items`}`
87
+ : `${who} is leaving and still holds ${items.length === 1 ? 'an item' : `${items.length} items`}`,
88
+ body: rest > 0 ? `${tags.join(', ')} and ${rest} more` : tags.join(', '),
89
+ // One item has an object worth pointing at; several do not, and naming the first would send
90
+ // everybody to one laptop out of five. The URL below is the list either way.
91
+ object: items.length === 1 ? { module: MODULE_ID, type: 'asset', id: items[0].id } : null,
92
+ url: items.length === 1 ? assetUrl(items[0].id) : `/inventory?custodian=${userId}`,
93
+ data: { userId, departure, assetIds: items.map((item) => item.id) },
94
+ // One group per person, so the two events cannot stack two separate piles about one leaver.
95
+ groupKey: `inventory.return_due.${userId}`,
96
+ // Never to the person leaving: they are being *chased*, and on the `removed` path they are no
97
+ // longer a member of this workspace at all.
98
+ exclude: [userId],
99
+ });
100
+ return { items, recipients };
101
+ }
102
+ /**
103
+ * What to call the person in the sentence.
104
+ *
105
+ * Core is asked, and a failure falls back to "a former member" rather than to the uuid: a
106
+ * notification with a uuid in the middle of it is the product admitting it does not know who it
107
+ * is talking about, and this module already refuses to print one on a screen for the same reason.
108
+ */
109
+ async nameOf(userId) {
110
+ const user = await this.kernel
111
+ .call('core.users.get', { id: userId })
112
+ .catch(() => null);
113
+ return user?.name?.trim() || user?.email?.trim() || 'A former member';
114
+ }
115
+ }
116
+ //# sourceMappingURL=offboarding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offboarding.js","sourceRoot":"","sources":["../../../src/server/services/offboarding.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,wEAAwE;AACxE,MAAM,YAAY,GAAG,CAAC,CAAA;AAEtB;;;GAGG;AACH,MAAM,QAAQ,GAAG,GAAG,CAAA;AAepB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,kBAAkB;IAEV;IACA;IAFnB,YACmB,MAAc,EACd,MAAqB;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from '@kernhq/kernel';
2
+ import type { RepairInput, RepairListItem, Repair as RepairModel, RepairPatchInput } from '../../contract/models.js';
3
+ import { assets, repairs } from '../schema.js';
4
+ import type { HistoryInput, NotifyService } from './notify.js';
5
+ type Row = typeof repairs.$inferSelect;
6
+ type AssetRow = typeof assets.$inferSelect;
7
+ /** The wire shape: drizzle gives Date objects for timestamps, the contract promises ISO strings. */
8
+ export declare function toRepair(row: Row): RepairModel;
9
+ /**
10
+ * What one repair mutation wrote, and what may only leave the module once it has committed.
11
+ *
12
+ * The asset comes back beside the repair because sending an item away moves `assets.status`, and a
13
+ * caller that fetched the asset again afterwards would be reading a row somebody else may have
14
+ * changed in between — the panel would then show a repair that has already been completed.
15
+ */
16
+ export interface RepairWritten {
17
+ repair: Row;
18
+ asset: AssetRow;
19
+ /** `null` when nothing happened worth recording, which is what an edit that changed nothing is. */
20
+ activity: HistoryInput | null;
21
+ }
22
+ export interface RepairListInput {
23
+ limit: number;
24
+ cursor?: string;
25
+ assetId?: string;
26
+ /** `true` for still away, `false` for finished, absent for both. */
27
+ open?: boolean;
28
+ }
29
+ /**
30
+ * What went away to be fixed, and what came back.
31
+ *
32
+ * Three things happen in one transaction on every change here, and the point of the class is that
33
+ * they cannot come apart: the repair row moves, `assets.status` is brought into step with it through
34
+ * `deriveStatus`, and an `asset_history` entry records it.
35
+ *
36
+ * **The database is the arbiter of "already away", not this file.** There is deliberately no
37
+ * `select … for update` on the asset *before* the repair row is written:
38
+ * `inventory_repairs_one_open_uq` — a unique index on `(asset_id) where returned_on is null` — is
39
+ * what makes two open repairs impossible, so two people pressing *Send for repair* on the same
40
+ * laptop in the same instant both read "it is here", both insert, and Postgres refuses exactly one
41
+ * of them. Checking first and inserting after is the race, not the fix. What this file owes the
42
+ * loser is a sentence they can act on rather than drizzle's "Failed query: insert into
43
+ * mod_inventory.repairs …".
44
+ *
45
+ * **`restamp` does lock it, afterwards, and that is a different job.** `assets.status` is derived
46
+ * from this module's repair rows *and* from custody, which another service writes, so the winner
47
+ * still has to compute an answer nobody can overwrite from a stale snapshot. See `lockAsset` in
48
+ * `status.ts`: the index decides the contest, the lock orders the bookkeeping that follows it.
49
+ *
50
+ * **Repairs do not touch custody.** An item at the repairer is still somebody's responsibility; see
51
+ * `status.ts`, where that rule is argued in full.
52
+ */
53
+ export declare class RepairService {
54
+ private readonly notify;
55
+ constructor(notify: NotifyService);
56
+ /**
57
+ * Today, as this module means it: the UTC date.
58
+ *
59
+ * Not the browser's date, and not a workspace time zone — a repair is dated to the day, and the
60
+ * two hours a workspace in Istanbul is ahead of UTC would put an evening repair on tomorrow for
61
+ * one reader and today for another. One clock, the server's, the same reasoning that keeps asset
62
+ * tags server-side. A workspace that needs the exact day sends `sentOn` itself.
63
+ */
64
+ private static today;
65
+ /** The one error a lost race produces, in every place a race can be lost. */
66
+ private static alreadyAway;
67
+ /**
68
+ * A repair cannot come back before it was sent — checked on every path that writes either date.
69
+ *
70
+ * `complete` has always refused a return date before the send date, and `update` did not: it took
71
+ * `sentOn` from the patch and wrote it whatever the row already said, so correcting the send date
72
+ * of a *finished* repair could move it past the day the item came back. What that stores is a
73
+ * repair that ended before it started — every "how long was it away" answer negative, the overdue
74
+ * sweep measuring from a date in the future, and nothing anywhere to say which of the two dates is
75
+ * the wrong one.
76
+ *
77
+ * Both are `date` columns, so they read back as `YYYY-MM-DD` and compare correctly as text.
78
+ *
79
+ * The database holds the same rule (`inventory_repairs_returned_after_sent`), because two
80
+ * transactions can each pass this check and still write a pair that fails it: one moving `sent_on`
81
+ * while the other logs the item back. This runs first so the ordinary case gets a sentence rather
82
+ * than a constraint violation; `outOfOrder` is what the loser of that race gets.
83
+ */
84
+ private static requireInOrder;
85
+ private static outOfOrder;
86
+ /**
87
+ * One day past today, which is the whole tolerance a date typed by a person needs.
88
+ *
89
+ * `today()` is UTC — one clock, the server's, for the reason it documents — and a workspace in
90
+ * Auckland is up to fourteen hours ahead of it, so *their* today is UTC's tomorrow for a large
91
+ * part of their working day. Refusing at exactly UTC-today would refuse the ordinary case in half
92
+ * the world's offices. A day is enough for every real time zone and is nowhere near enough to be
93
+ * the defect below.
94
+ */
95
+ private static readonly FUTURE_GRACE_DAYS;
96
+ /**
97
+ * A repair cannot be sent from the future — checked on every path that writes `sent_on`.
98
+ *
99
+ * `sentOn` is a date a person types, and nothing bounded it. A repair dated 2030 is one the
100
+ * overdue sweep can never find: it looks for `sent_on <= today - repairOverdueDays`, so a send
101
+ * date years ahead is permanently outside the window and the chase never fires. Not for a while —
102
+ * **ever**, for the life of that row, and silently, because a sweep that finds nothing looks
103
+ * exactly like a sweep with nothing to do. It also makes every "how long has it been away" answer
104
+ * negative and puts the item at the top of a list ordered by when it left.
105
+ *
106
+ * A typo is the likely cause and a deliberate one is the dangerous case: this is the one field
107
+ * that decides whether anybody is ever reminded that a vendor still has the company's laptop.
108
+ *
109
+ * Bounded on the *server*, not in the contract, and both halves of that are deliberate. The
110
+ * contract is shared with the browser, so a `refine` there would compare against the reader's own
111
+ * clock — and a client whose date is a day ahead would refuse a date the server accepts, or the
112
+ * other way round. And it is a sentence rather than a bare `invalid_string`, because "a repair
113
+ * cannot be sent in the future" is something a person can act on.
114
+ *
115
+ * **A `BAD_REQUEST` with no `reason`, like `checkPhoto`'s refusal and the category check in
116
+ * `AssetService`.** The date is malformed rather than contested — nothing raced, no state
117
+ * changed underneath anybody, the value simply cannot be true — and `CONFLICT` is this module's
118
+ * word for losing a race. The cost is that the sentence reaches a Persian or Turkish reader in
119
+ * English: a translated refusal needs a stable `reason` **and** its five bundles in
120
+ * `src/client/errors.ts`, and the two have to arrive together or `errors.test.ts` fails from
121
+ * whichever side is ahead.
122
+ */
123
+ private static requireNotFuture;
124
+ private asset;
125
+ get(tx: Tx, workspaceId: string, repairId: string): Promise<Row>;
126
+ /**
127
+ * One asset's repairs, or the whole workspace's — one query with one filter, because they are one
128
+ * question asked at two scopes and a second query answering it would be a second one to keep in
129
+ * step.
130
+ *
131
+ * **Paged by id, newest logged first.** An id is uuidv7, so it already carries the clock, and it
132
+ * is unique where `sent_on` is a date two repairs logged on the same day share — a page boundary
133
+ * between two rows that share a sort key repeats one and drops the other. The same reasoning
134
+ * `assets.list` gives for `sort: 'recent'` and `assets.history` gives for ordering on the row id.
135
+ */
136
+ list(tx: Tx, workspaceId: string, input: RepairListInput): Promise<{
137
+ items: RepairListItem[];
138
+ nextCursor: string | null;
139
+ }>;
140
+ /**
141
+ * The currency to store, given what the caller said and what is already there.
142
+ *
143
+ * A cost with no unit is not a cost, so an amount recorded with no currency inherits the asset's.
144
+ * **Inheritance fires in exactly one case** — an amount is being recorded and the repair has no
145
+ * currency at all — and getting that wrong is silent in both directions:
146
+ *
147
+ * - inheriting whenever a cost *exists* rather than whenever one *arrives* means an unrelated
148
+ * edit (correcting a vendor) silently gives the asset's currency back to a repair whose
149
+ * currency somebody deliberately cleared;
150
+ * - inheriting over a currency the repair already has means recording an amount in dollars on an
151
+ * asset priced in euros quietly relabels it as euros.
152
+ *
153
+ * `undefined` means "not mentioned" and an explicit `null` means "no currency", which a workspace
154
+ * that records amounts and not currencies genuinely means. Collapsing the two is the mistake
155
+ * `assets.update` documents one file over.
156
+ */
157
+ private static currencyFor;
158
+ /** Send it away. Refuses when it is already at a repairer — that is what `complete` is for. */
159
+ create(tx: Tx, workspaceId: string, actorId: string | null, assetId: string, input: RepairInput): Promise<RepairWritten>;
160
+ /**
161
+ * Correct what was recorded — a vendor, or a cost that arrived with the invoice a week later.
162
+ *
163
+ * **`returnedOn` is deliberately not patchable.** That one column decides whether the asset reads
164
+ * as `under_repair`, so exactly one procedure moves it and the derived status has one door rather
165
+ * than two. Editing a finished repair is allowed all the same: the invoice usually arrives after
166
+ * the item does.
167
+ *
168
+ * **No `actorId`, because nothing here records one.** This writes no timeline entry — see the
169
+ * bottom of the method — and a parameter kept for symmetry with `create` and `complete` would be
170
+ * a parameter every caller has to supply and nothing reads.
171
+ */
172
+ update(tx: Tx, workspaceId: string, repairId: string, patch: RepairPatchInput): Promise<RepairWritten>;
173
+ /**
174
+ * It came back.
175
+ *
176
+ * `and returned_on is null` in the predicate is the optimistic guard, exactly as
177
+ * `CustodyService.close` uses: under READ COMMITTED a concurrent complete blocks this statement,
178
+ * and when it resumes the row no longer matches, so zero rows come back rather than a second
179
+ * completion silently overwriting the first one's date.
180
+ */
181
+ complete(tx: Tx, workspaceId: string, actorId: string | null, repairId: string, input: {
182
+ returnedOn?: string;
183
+ costMinor?: number | null;
184
+ currency?: string | null;
185
+ }): Promise<RepairWritten>;
186
+ /**
187
+ * Bring `assets.status` back into step with the facts, inside the same transaction.
188
+ *
189
+ * Both facts are **read** rather than assumed — the open repair as it now stands, and the
190
+ * custodian as the asset row carries it — and `deriveStatus` decides. Assuming `under_repair`
191
+ * after an insert and `in_stock` after a completion is the version of this that silently released
192
+ * whoever was still holding the item.
193
+ *
194
+ * **The asset is locked and re-read here, rather than passed in.** It used to take the row the
195
+ * caller had already fetched, which is a snapshot from before the repair was written and before
196
+ * anything else that touched the asset in between: a handover committing in that window was
197
+ * invisible, so this derived a status from a custodian that had stopped being current and wrote it
198
+ * over the handover's answer. Taking the row under the lock is what makes "read both facts, then
199
+ * derive" true rather than merely intended. `lockAsset` argues it in full.
200
+ */
201
+ private restamp;
202
+ }
203
+ export {};
204
+ //# sourceMappingURL=repairs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repairs.d.ts","sourceRoot":"","sources":["../../../src/server/services/repairs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,EAAE,EAAU,MAAM,gBAAgB,CAAA;AAE3D,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,MAAM,IAAI,WAAW,EACrB,gBAAgB,EACjB,MAAM,0BAA0B,CAAA;AACjC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAG9C,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAG9D,KAAK,GAAG,GAAG,OAAO,OAAO,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