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