dxcomplete 0.2.1 → 0.2.2
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/.env.example +0 -7
- package/README.md +17 -45
- package/dist/cli.js +0 -22
- package/dist/validate.js +10 -26
- package/docs/model.md +3 -3
- package/docs/taxonomy.md +1 -1
- package/package.json +23 -23
- package/templates/process/README.md +1 -1
- package/dist/http/service.d.ts +0 -7
- package/dist/http/service.js +0 -725
- package/dist/mcp/docs.d.ts +0 -114
- package/dist/mcp/docs.js +0 -626
- package/dist/mcp/server.d.ts +0 -20
- package/dist/mcp/server.js +0 -3059
- package/dist/runtime/auth.d.ts +0 -162
- package/dist/runtime/auth.js +0 -394
- package/dist/runtime/check.d.ts +0 -7
- package/dist/runtime/check.js +0 -16
- package/dist/runtime/config.d.ts +0 -17
- package/dist/runtime/config.js +0 -93
- package/dist/runtime/mongo.d.ts +0 -9
- package/dist/runtime/mongo.js +0 -56
- package/dist/runtime/records.d.ts +0 -427
- package/dist/runtime/records.js +0 -2092
- package/scripts/check-env-surface.mjs +0 -136
- package/scripts/check-public-copy.mjs +0 -263
- package/scripts/check-service-boundary.mjs +0 -63
- package/scripts/runtime-work-order.mjs +0 -506
- package/scripts/smoke-mcp-http.mjs +0 -4026
- package/src/cli.ts +0 -268
- package/src/http/server.ts +0 -314
- package/src/http/service.ts +0 -934
- package/src/init.ts +0 -262
- package/src/install-manifest.ts +0 -144
- package/src/mcp/docs.ts +0 -777
- package/src/mcp/server.ts +0 -4580
- package/src/package-root.ts +0 -31
- package/src/runtime/actor.ts +0 -61
- package/src/runtime/auth.ts +0 -673
- package/src/runtime/check.ts +0 -18
- package/src/runtime/config.ts +0 -128
- package/src/runtime/mongo.ts +0 -89
- package/src/runtime/records.ts +0 -3205
- package/src/runtime/workspace.ts +0 -155
- package/src/upgrade.ts +0 -356
- package/src/validate.ts +0 -141
- package/src/version.ts +0 -16
package/dist/runtime/records.js
DELETED
|
@@ -1,2092 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
export const COLLECTION_NAMES = [
|
|
3
|
-
"workspaces",
|
|
4
|
-
"statements",
|
|
5
|
-
"journal_entries",
|
|
6
|
-
"environments",
|
|
7
|
-
"components",
|
|
8
|
-
"estimates",
|
|
9
|
-
"benefits",
|
|
10
|
-
"expectations",
|
|
11
|
-
"requirements",
|
|
12
|
-
"tasks",
|
|
13
|
-
"commitments",
|
|
14
|
-
"deferrals",
|
|
15
|
-
"changes",
|
|
16
|
-
"incidents",
|
|
17
|
-
"problems",
|
|
18
|
-
"maintenance_schedules",
|
|
19
|
-
"support_requests",
|
|
20
|
-
"value_realizations",
|
|
21
|
-
"decisions",
|
|
22
|
-
"risks"
|
|
23
|
-
];
|
|
24
|
-
export const LEGACY_COLLECTION_NAMES = [
|
|
25
|
-
"engagements",
|
|
26
|
-
"initiatives",
|
|
27
|
-
"service_charters",
|
|
28
|
-
"cost_baselines",
|
|
29
|
-
"cost_actuals",
|
|
30
|
-
"benefit_measurements"
|
|
31
|
-
];
|
|
32
|
-
export const DXCOMPLETE_TICKET_COLLECTION_NAME = "dxcomplete_tickets";
|
|
33
|
-
export const LEGACY_INTAKE_COLLECTION_NAME = "intake_items";
|
|
34
|
-
export const LEGACY_PRIVATE_COLLECTION_NAMES = [LEGACY_INTAKE_COLLECTION_NAME];
|
|
35
|
-
export const INDEX_COLLECTION_NAMES = [...COLLECTION_NAMES, DXCOMPLETE_TICKET_COLLECTION_NAME];
|
|
36
|
-
export const LINK_SCAN_COLLECTION_NAMES = [...COLLECTION_NAMES, ...LEGACY_COLLECTION_NAMES];
|
|
37
|
-
export const READABLE_ID_SEQUENCES_COLLECTION = "readable_id_sequences";
|
|
38
|
-
export const READABLE_ID_TYPE_CODES = {
|
|
39
|
-
statements: "STM",
|
|
40
|
-
journal_entries: "JRN",
|
|
41
|
-
environments: "ENV",
|
|
42
|
-
components: "CMP",
|
|
43
|
-
expectations: "EXP",
|
|
44
|
-
requirements: "REQ",
|
|
45
|
-
tasks: "TSK",
|
|
46
|
-
commitments: "CMT",
|
|
47
|
-
deferrals: "DFR",
|
|
48
|
-
decisions: "DEC",
|
|
49
|
-
changes: "CHG",
|
|
50
|
-
incidents: "INC",
|
|
51
|
-
problems: "PRB",
|
|
52
|
-
maintenance_schedules: "MNT",
|
|
53
|
-
support_requests: "SUP",
|
|
54
|
-
value_realizations: "VAL",
|
|
55
|
-
risks: "RSK",
|
|
56
|
-
estimates: "EST",
|
|
57
|
-
benefits: "BFT"
|
|
58
|
-
};
|
|
59
|
-
export const READABLE_ID_COLLECTION_NAMES = Object.keys(READABLE_ID_TYPE_CODES);
|
|
60
|
-
export const RUNTIME_ACTOR_ID = "dxcomplete-runtime";
|
|
61
|
-
const REVIEW_NOTE_RECORD_TYPES = ["expectations", "requirements"];
|
|
62
|
-
const VERSIONED_RECORD_TYPES = [
|
|
63
|
-
"statements",
|
|
64
|
-
"environments",
|
|
65
|
-
"components",
|
|
66
|
-
"expectations",
|
|
67
|
-
"requirements",
|
|
68
|
-
"estimates",
|
|
69
|
-
"benefits",
|
|
70
|
-
"maintenance_schedules",
|
|
71
|
-
"value_realizations"
|
|
72
|
-
];
|
|
73
|
-
const VERSION_HISTORY_FIELD = "versionHistory";
|
|
74
|
-
const CHANGE_MANAGED_FIELDS = [
|
|
75
|
-
"changePlan",
|
|
76
|
-
"executionSteps",
|
|
77
|
-
"rollbackPlan",
|
|
78
|
-
"riskImpact",
|
|
79
|
-
"changeType",
|
|
80
|
-
"impactGrade",
|
|
81
|
-
"emergencyImportance",
|
|
82
|
-
"emergencyImmediacy",
|
|
83
|
-
"emergencyRationaleGaps",
|
|
84
|
-
"plannedFor",
|
|
85
|
-
"events"
|
|
86
|
-
];
|
|
87
|
-
const COMMITMENT_MANAGED_FIELDS = ["commitmentStatement", "reservations"];
|
|
88
|
-
const DEFERRAL_MANAGED_FIELDS = ["reason", "status", "conditions", "conditionEvents"];
|
|
89
|
-
const ESTIMATE_MANAGED_FIELDS = ["lineItems", "rollup"];
|
|
90
|
-
const BENEFITS_MANAGED_FIELDS = ["benefitItems", "rollup"];
|
|
91
|
-
const ENVIRONMENT_MANAGED_FIELDS = ["name", "description"];
|
|
92
|
-
const COMPONENT_MANAGED_FIELDS = [
|
|
93
|
-
"name",
|
|
94
|
-
"environmentId",
|
|
95
|
-
"kind",
|
|
96
|
-
"locator",
|
|
97
|
-
"identifiers",
|
|
98
|
-
"secretPointers",
|
|
99
|
-
"notes"
|
|
100
|
-
];
|
|
101
|
-
const MAINTENANCE_SCHEDULE_MANAGED_FIELDS = [
|
|
102
|
-
"name",
|
|
103
|
-
"kind",
|
|
104
|
-
"cadence",
|
|
105
|
-
"startDate",
|
|
106
|
-
"rationale",
|
|
107
|
-
"notes"
|
|
108
|
-
];
|
|
109
|
-
const SUPPORT_REQUEST_LEDGER_MANAGED_FIELDS = [
|
|
110
|
-
"reporter",
|
|
111
|
-
"kind",
|
|
112
|
-
"reportedExperience",
|
|
113
|
-
"entries",
|
|
114
|
-
"currentStatus",
|
|
115
|
-
"status"
|
|
116
|
-
];
|
|
117
|
-
const VALUE_REALIZATION_MANAGED_FIELDS = ["metrics"];
|
|
118
|
-
const DECISION_LEDGER_MANAGED_FIELDS = [
|
|
119
|
-
"matter",
|
|
120
|
-
"entries",
|
|
121
|
-
"currentDecision",
|
|
122
|
-
"question",
|
|
123
|
-
"decision",
|
|
124
|
-
"decidedBy",
|
|
125
|
-
"rationale",
|
|
126
|
-
"argumentsConsidered",
|
|
127
|
-
"concerns",
|
|
128
|
-
"status"
|
|
129
|
-
];
|
|
130
|
-
const TASK_LEDGER_MANAGED_FIELDS = [
|
|
131
|
-
"description",
|
|
132
|
-
"assignee",
|
|
133
|
-
"assignor",
|
|
134
|
-
"entries",
|
|
135
|
-
"currentStatus",
|
|
136
|
-
"details",
|
|
137
|
-
"status"
|
|
138
|
-
];
|
|
139
|
-
const RISK_LEDGER_MANAGED_FIELDS = [
|
|
140
|
-
"topic",
|
|
141
|
-
"entries",
|
|
142
|
-
"currentStatus",
|
|
143
|
-
"currentAssessment",
|
|
144
|
-
"currentTreatment",
|
|
145
|
-
"likelihood",
|
|
146
|
-
"impact",
|
|
147
|
-
"mitigation"
|
|
148
|
-
];
|
|
149
|
-
const INCIDENT_LEDGER_MANAGED_FIELDS = [
|
|
150
|
-
"description",
|
|
151
|
-
"entries",
|
|
152
|
-
"currentStatus",
|
|
153
|
-
"currentSeverity",
|
|
154
|
-
"status",
|
|
155
|
-
"severity"
|
|
156
|
-
];
|
|
157
|
-
const PROBLEM_LEDGER_MANAGED_FIELDS = [
|
|
158
|
-
"description",
|
|
159
|
-
"entries",
|
|
160
|
-
"currentStatus",
|
|
161
|
-
"currentRootCause",
|
|
162
|
-
"status",
|
|
163
|
-
"rootCause"
|
|
164
|
-
];
|
|
165
|
-
const DECISION_INPUT_MANAGED_FIELDS = ["informedBy", "informedByIds", "inputRecords"];
|
|
166
|
-
const JOURNAL_ENTRY_MANAGED_FIELDS = ["kind", "body", "tag", "covers", "coveredBySummaryId"];
|
|
167
|
-
const JOURNAL_COMPACTION_THRESHOLD = 200;
|
|
168
|
-
const VERSIONED_TYPED_FIELDS = {
|
|
169
|
-
statements: ["statement", "source"],
|
|
170
|
-
expectations: ["statement", "successRecognition", "approvalState", "approvedBy", "approvedAt", "source"],
|
|
171
|
-
requirements: ["statement", "acceptanceCriteria", "priority", "status"],
|
|
172
|
-
estimates: ["lineItems", "rollup"],
|
|
173
|
-
benefits: ["benefitItems", "rollup"],
|
|
174
|
-
environments: ["name", "description"],
|
|
175
|
-
components: ["name", "environmentId", "kind", "locator", "identifiers", "secretPointers", "notes"],
|
|
176
|
-
maintenance_schedules: ["name", "kind", "cadence", "startDate", "rationale", "notes"],
|
|
177
|
-
value_realizations: ["metrics"]
|
|
178
|
-
};
|
|
179
|
-
const RESERVED_RELATIONSHIP_FIELDS = {
|
|
180
|
-
changes: ["requirementId"],
|
|
181
|
-
commitments: ["requirementIds", "expectationIds", "deferralId"],
|
|
182
|
-
deferrals: ["requirementIds", "expectationIds"],
|
|
183
|
-
estimates: ["requirementIds", "expectationIds"],
|
|
184
|
-
benefits: ["requirementIds", "expectationIds"],
|
|
185
|
-
value_realizations: ["requirementIds", "expectationIds", "commitmentIds"],
|
|
186
|
-
expectations: ["statementId"],
|
|
187
|
-
requirements: ["expectationId"],
|
|
188
|
-
tasks: ["requirementId"]
|
|
189
|
-
};
|
|
190
|
-
const REMOVED_INITIATIVE_FIELD_RECORD_TYPES = [
|
|
191
|
-
"changes",
|
|
192
|
-
"estimates",
|
|
193
|
-
"benefits",
|
|
194
|
-
"expectations"
|
|
195
|
-
];
|
|
196
|
-
export function assertCollectionName(value) {
|
|
197
|
-
if (COLLECTION_NAMES.includes(value)) {
|
|
198
|
-
return value;
|
|
199
|
-
}
|
|
200
|
-
throw new Error(`Unsupported record type "${value}".`);
|
|
201
|
-
}
|
|
202
|
-
export async function createRecord(db, recordType, input, actorId) {
|
|
203
|
-
assertNoReservedRelationshipFields(recordType, input.fields);
|
|
204
|
-
if (input.allowManagedFields) {
|
|
205
|
-
assertNoReviewNotesField(recordType, input.fields);
|
|
206
|
-
}
|
|
207
|
-
else {
|
|
208
|
-
assertNoManagedField(recordType, input.fields);
|
|
209
|
-
}
|
|
210
|
-
const now = new Date().toISOString();
|
|
211
|
-
const workspaceId = workspaceIdForCreate(recordType, input.workspaceId);
|
|
212
|
-
if (workspaceId) {
|
|
213
|
-
await assertWorkspaceExists(db, workspaceId);
|
|
214
|
-
}
|
|
215
|
-
const record = {
|
|
216
|
-
_id: input.id ?? randomUUID(),
|
|
217
|
-
recordType,
|
|
218
|
-
...(workspaceId ? { workspaceId } : {}),
|
|
219
|
-
title: input.title,
|
|
220
|
-
summary: input.summary,
|
|
221
|
-
fields: input.fields ?? {},
|
|
222
|
-
links: [],
|
|
223
|
-
createdAt: now,
|
|
224
|
-
createdBy: actorId,
|
|
225
|
-
updatedAt: now,
|
|
226
|
-
updatedBy: actorId
|
|
227
|
-
};
|
|
228
|
-
if (recordTypeSupportsReadableId(recordType)) {
|
|
229
|
-
const session = db.client.startSession();
|
|
230
|
-
try {
|
|
231
|
-
await session.withTransaction(async () => {
|
|
232
|
-
record.readableId = await allocateReadableId(db, recordType, workspaceId, actorId, now, session);
|
|
233
|
-
await db.collection(recordType).insertOne(record, { session });
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
finally {
|
|
237
|
-
await session.endSession();
|
|
238
|
-
}
|
|
239
|
-
return withDerivedRecordFields(db, record);
|
|
240
|
-
}
|
|
241
|
-
await db.collection(recordType).insertOne(record);
|
|
242
|
-
return withDerivedRecordFields(db, record);
|
|
243
|
-
}
|
|
244
|
-
export async function listRecords(db, recordType, limit, options = {}) {
|
|
245
|
-
const filter = {};
|
|
246
|
-
if (recordTypeRequiresWorkspace(recordType)) {
|
|
247
|
-
filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
|
|
248
|
-
}
|
|
249
|
-
if (!options.includeArchived) {
|
|
250
|
-
filter.archivedAt = { $exists: false };
|
|
251
|
-
}
|
|
252
|
-
const records = await db
|
|
253
|
-
.collection(recordType)
|
|
254
|
-
.find(filter)
|
|
255
|
-
.sort({ createdAt: -1 })
|
|
256
|
-
.limit(limit)
|
|
257
|
-
.toArray();
|
|
258
|
-
return Promise.all(records.map((record) => withDerivedRecordFields(db, record)));
|
|
259
|
-
}
|
|
260
|
-
export async function getRecord(db, recordType, id, options = {}) {
|
|
261
|
-
const filter = recordIdentityFilter(recordType, id);
|
|
262
|
-
if (recordTypeRequiresWorkspace(recordType) &&
|
|
263
|
-
!options.allowAnyWorkspace &&
|
|
264
|
-
isCurrentCollection(recordType)) {
|
|
265
|
-
filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
|
|
266
|
-
}
|
|
267
|
-
const record = await db.collection(recordType).findOne(filter);
|
|
268
|
-
return record ? withDerivedRecordFields(db, record) : null;
|
|
269
|
-
}
|
|
270
|
-
export async function listLinkedRecords(db, input) {
|
|
271
|
-
const source = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
|
|
272
|
-
if (!source) {
|
|
273
|
-
throw new Error(`Record not found: ${input.recordType}/${input.id}`);
|
|
274
|
-
}
|
|
275
|
-
const direction = input.direction ?? "both";
|
|
276
|
-
const result = {
|
|
277
|
-
source,
|
|
278
|
-
outbound: [],
|
|
279
|
-
inbound: []
|
|
280
|
-
};
|
|
281
|
-
if (direction === "outbound" || direction === "both") {
|
|
282
|
-
for (const link of source.links.filter((link) => linkMatches(link, input.relationship))) {
|
|
283
|
-
const target = await getRecord(db, link.toType, link.toId, {
|
|
284
|
-
workspaceId: source.workspaceId,
|
|
285
|
-
allowAnyWorkspace: !source.workspaceId
|
|
286
|
-
});
|
|
287
|
-
if (!target ||
|
|
288
|
-
(!input.includeArchived && target.archivedAt) ||
|
|
289
|
-
!recordBelongsToWorkspace(target, source.workspaceId)) {
|
|
290
|
-
continue;
|
|
291
|
-
}
|
|
292
|
-
result.outbound.push({
|
|
293
|
-
edge: {
|
|
294
|
-
fromType: source.recordType,
|
|
295
|
-
fromId: source._id,
|
|
296
|
-
...link
|
|
297
|
-
},
|
|
298
|
-
record: target
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
if (direction === "inbound" || direction === "both") {
|
|
303
|
-
for (const collectionName of LINK_SCAN_COLLECTION_NAMES) {
|
|
304
|
-
const filter = {
|
|
305
|
-
links: {
|
|
306
|
-
$elemMatch: {
|
|
307
|
-
toType: input.recordType,
|
|
308
|
-
toId: source._id,
|
|
309
|
-
...(input.relationship ? { relationship: input.relationship } : {})
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
};
|
|
313
|
-
if (source.workspaceId && recordTypeRequiresWorkspace(collectionName)) {
|
|
314
|
-
filter.workspaceId = source.workspaceId;
|
|
315
|
-
}
|
|
316
|
-
if (!input.includeArchived) {
|
|
317
|
-
filter.archivedAt = { $exists: false };
|
|
318
|
-
}
|
|
319
|
-
const records = await db.collection(collectionName).find(filter).toArray();
|
|
320
|
-
for (const record of records) {
|
|
321
|
-
for (const link of record.links.filter((link) => link.toType === input.recordType &&
|
|
322
|
-
link.toId === source._id &&
|
|
323
|
-
linkMatches(link, input.relationship))) {
|
|
324
|
-
result.inbound.push({
|
|
325
|
-
edge: {
|
|
326
|
-
fromType: record.recordType,
|
|
327
|
-
fromId: record._id,
|
|
328
|
-
...link
|
|
329
|
-
},
|
|
330
|
-
record
|
|
331
|
-
});
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
return result;
|
|
337
|
-
}
|
|
338
|
-
async function withDerivedRecordFields(db, record) {
|
|
339
|
-
if (record.recordType === "maintenance_schedules") {
|
|
340
|
-
return {
|
|
341
|
-
...record,
|
|
342
|
-
derived: await deriveMaintenanceScheduleState(db, record)
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
if (record.recordType === "value_realizations") {
|
|
346
|
-
return {
|
|
347
|
-
...record,
|
|
348
|
-
derived: deriveValueRealizationState(record)
|
|
349
|
-
};
|
|
350
|
-
}
|
|
351
|
-
return record;
|
|
352
|
-
}
|
|
353
|
-
async function deriveMaintenanceScheduleState(db, record) {
|
|
354
|
-
const cadence = parseMaintenanceCadence(record.fields.cadence);
|
|
355
|
-
const startDate = parseDateString(record.fields.startDate);
|
|
356
|
-
const occurrences = await findMaintenanceOccurrences(db, record);
|
|
357
|
-
const latestOccurrence = occurrences[0];
|
|
358
|
-
const latestOccurrenceAt = latestOccurrence?.occurredAt;
|
|
359
|
-
const basis = latestOccurrenceAt ?? startDate?.toISOString();
|
|
360
|
-
const nextDueAt = cadence && basis ? addMaintenanceCadence(new Date(basis), cadence).toISOString() : undefined;
|
|
361
|
-
return compactRuntimeObject({
|
|
362
|
-
occurrenceCount: occurrences.length,
|
|
363
|
-
latestOccurrence,
|
|
364
|
-
cadence: cadence ?? undefined,
|
|
365
|
-
startDate: startDate?.toISOString(),
|
|
366
|
-
nextDueAt,
|
|
367
|
-
overdue: nextDueAt ? new Date() > new Date(nextDueAt) : undefined
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
async function findMaintenanceOccurrences(db, schedule) {
|
|
371
|
-
const workspaceId = schedule.workspaceId;
|
|
372
|
-
if (!workspaceId) {
|
|
373
|
-
return [];
|
|
374
|
-
}
|
|
375
|
-
const linkFilter = {
|
|
376
|
-
workspaceId,
|
|
377
|
-
archivedAt: { $exists: false },
|
|
378
|
-
links: {
|
|
379
|
-
$elemMatch: {
|
|
380
|
-
toType: "maintenance_schedules",
|
|
381
|
-
toId: schedule._id,
|
|
382
|
-
relationship: "assigned_to"
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
const [changes, tasks] = await Promise.all([
|
|
387
|
-
db.collection("changes").find(linkFilter).toArray(),
|
|
388
|
-
db.collection("tasks").find(linkFilter).toArray()
|
|
389
|
-
]);
|
|
390
|
-
const occurrences = [
|
|
391
|
-
...changes.flatMap((record) => occurrenceFromChange(record)),
|
|
392
|
-
...tasks.flatMap((record) => occurrenceFromTask(record))
|
|
393
|
-
];
|
|
394
|
-
return occurrences.sort((left, right) => right.occurredAt.localeCompare(left.occurredAt));
|
|
395
|
-
}
|
|
396
|
-
function occurrenceFromChange(record) {
|
|
397
|
-
const events = Array.isArray(record.fields.events) ? record.fields.events : [];
|
|
398
|
-
const event = [...events]
|
|
399
|
-
.reverse()
|
|
400
|
-
.find((entry) => Boolean(entry &&
|
|
401
|
-
typeof entry === "object" &&
|
|
402
|
-
(entry.eventType === "result_reported" || entry.eventType === "recovery_recorded") &&
|
|
403
|
-
typeof entry.createdAt === "string"));
|
|
404
|
-
const plannedFor = typeof record.fields.plannedFor === "string" ? record.fields.plannedFor : undefined;
|
|
405
|
-
const occurredAt = typeof event?.createdAt === "string" ? event.createdAt : plannedFor ?? record.createdAt;
|
|
406
|
-
return [{ recordType: "changes", id: record._id, readableId: record.readableId, occurredAt }];
|
|
407
|
-
}
|
|
408
|
-
function occurrenceFromTask(record) {
|
|
409
|
-
const entries = Array.isArray(record.fields.entries) ? record.fields.entries : [];
|
|
410
|
-
const doneEntry = [...entries]
|
|
411
|
-
.reverse()
|
|
412
|
-
.find((entry) => Boolean(entry &&
|
|
413
|
-
typeof entry === "object" &&
|
|
414
|
-
entry.entryType === "status_change" &&
|
|
415
|
-
entry.status === "done" &&
|
|
416
|
-
typeof entry.createdAt === "string"));
|
|
417
|
-
const occurredAt = typeof doneEntry?.createdAt === "string" ? doneEntry.createdAt : record.createdAt;
|
|
418
|
-
return [{ recordType: "tasks", id: record._id, readableId: record.readableId, occurredAt }];
|
|
419
|
-
}
|
|
420
|
-
function parseMaintenanceCadence(value) {
|
|
421
|
-
if (!value || typeof value !== "object") {
|
|
422
|
-
return undefined;
|
|
423
|
-
}
|
|
424
|
-
const cadence = value;
|
|
425
|
-
if (Number.isInteger(cadence.count) &&
|
|
426
|
-
(cadence.count ?? 0) > 0 &&
|
|
427
|
-
(cadence.unit === "day" ||
|
|
428
|
-
cadence.unit === "week" ||
|
|
429
|
-
cadence.unit === "month" ||
|
|
430
|
-
cadence.unit === "quarter" ||
|
|
431
|
-
cadence.unit === "year")) {
|
|
432
|
-
return { count: cadence.count, unit: cadence.unit };
|
|
433
|
-
}
|
|
434
|
-
return undefined;
|
|
435
|
-
}
|
|
436
|
-
function parseDateString(value) {
|
|
437
|
-
if (typeof value !== "string") {
|
|
438
|
-
return undefined;
|
|
439
|
-
}
|
|
440
|
-
const date = new Date(value);
|
|
441
|
-
return Number.isNaN(date.getTime()) ? undefined : date;
|
|
442
|
-
}
|
|
443
|
-
function addMaintenanceCadence(date, cadence) {
|
|
444
|
-
const next = new Date(date);
|
|
445
|
-
switch (cadence.unit) {
|
|
446
|
-
case "day":
|
|
447
|
-
next.setUTCDate(next.getUTCDate() + cadence.count);
|
|
448
|
-
return next;
|
|
449
|
-
case "week":
|
|
450
|
-
next.setUTCDate(next.getUTCDate() + cadence.count * 7);
|
|
451
|
-
return next;
|
|
452
|
-
case "month":
|
|
453
|
-
next.setUTCMonth(next.getUTCMonth() + cadence.count);
|
|
454
|
-
return next;
|
|
455
|
-
case "quarter":
|
|
456
|
-
next.setUTCMonth(next.getUTCMonth() + cadence.count * 3);
|
|
457
|
-
return next;
|
|
458
|
-
case "year":
|
|
459
|
-
next.setUTCFullYear(next.getUTCFullYear() + cadence.count);
|
|
460
|
-
return next;
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
function deriveValueRealizationState(record) {
|
|
464
|
-
const metrics = normalizeValueRealizationMetrics(record.fields.metrics);
|
|
465
|
-
const comparisons = metrics.map((metric) => {
|
|
466
|
-
if (!metric.actual) {
|
|
467
|
-
return {
|
|
468
|
-
id: metric.id,
|
|
469
|
-
name: metric.name,
|
|
470
|
-
unit: metric.unit,
|
|
471
|
-
direction: metric.direction,
|
|
472
|
-
status: "open"
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
const absoluteChange = metric.actual.value - metric.baseline.value;
|
|
476
|
-
const ratio = metric.baseline.value === 0 ? null : metric.actual.value / metric.baseline.value;
|
|
477
|
-
const percentChange = ratio === null ? null : (ratio - 1) * 100;
|
|
478
|
-
const outcome = absoluteChange === 0
|
|
479
|
-
? "unchanged"
|
|
480
|
-
: metric.direction === "higher_is_better"
|
|
481
|
-
? absoluteChange > 0
|
|
482
|
-
? "improved"
|
|
483
|
-
: "regressed"
|
|
484
|
-
: absoluteChange < 0
|
|
485
|
-
? "improved"
|
|
486
|
-
: "regressed";
|
|
487
|
-
return {
|
|
488
|
-
id: metric.id,
|
|
489
|
-
name: metric.name,
|
|
490
|
-
unit: metric.unit,
|
|
491
|
-
direction: metric.direction,
|
|
492
|
-
status: "measured",
|
|
493
|
-
absoluteChange,
|
|
494
|
-
percentChange,
|
|
495
|
-
ratio,
|
|
496
|
-
outcome,
|
|
497
|
-
baselineMeasuredAt: metric.baseline.measuredAt,
|
|
498
|
-
actualMeasuredAt: metric.actual.measuredAt
|
|
499
|
-
};
|
|
500
|
-
});
|
|
501
|
-
return {
|
|
502
|
-
metricCount: metrics.length,
|
|
503
|
-
openMetricCount: comparisons.filter((comparison) => comparison.status === "open").length,
|
|
504
|
-
measuredMetricCount: comparisons.filter((comparison) => comparison.status === "measured").length,
|
|
505
|
-
comparisons
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
function normalizeValueRealizationMetrics(value) {
|
|
509
|
-
if (!Array.isArray(value)) {
|
|
510
|
-
return [];
|
|
511
|
-
}
|
|
512
|
-
return value.filter(isValueRealizationMetric);
|
|
513
|
-
}
|
|
514
|
-
function isValueRealizationMetric(value) {
|
|
515
|
-
if (!value || typeof value !== "object") {
|
|
516
|
-
return false;
|
|
517
|
-
}
|
|
518
|
-
const metric = value;
|
|
519
|
-
return (typeof metric.id === "string" &&
|
|
520
|
-
typeof metric.name === "string" &&
|
|
521
|
-
typeof metric.unit === "string" &&
|
|
522
|
-
(metric.direction === "lower_is_better" || metric.direction === "higher_is_better") &&
|
|
523
|
-
isMeasuredValue(metric.baseline) &&
|
|
524
|
-
(metric.actual === undefined || isMeasuredValue(metric.actual)));
|
|
525
|
-
}
|
|
526
|
-
function isMeasuredValue(value) {
|
|
527
|
-
return (Boolean(value) &&
|
|
528
|
-
typeof value === "object" &&
|
|
529
|
-
typeof value.value === "number" &&
|
|
530
|
-
Number.isFinite(value.value) &&
|
|
531
|
-
typeof value.measuredAt === "string");
|
|
532
|
-
}
|
|
533
|
-
function compactRuntimeObject(input) {
|
|
534
|
-
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
|
|
535
|
-
}
|
|
536
|
-
export async function migrateLegacyIntakeItemsToDxcompleteTickets(db) {
|
|
537
|
-
const legacyCollection = db.collection(LEGACY_INTAKE_COLLECTION_NAME);
|
|
538
|
-
const ticketCollection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
|
|
539
|
-
const legacyRecords = await legacyCollection.find({}).toArray();
|
|
540
|
-
let copied = 0;
|
|
541
|
-
let skipped = 0;
|
|
542
|
-
for (const legacyRecord of legacyRecords) {
|
|
543
|
-
const existing = await ticketCollection.findOne({ _id: legacyRecord._id });
|
|
544
|
-
if (existing) {
|
|
545
|
-
skipped += 1;
|
|
546
|
-
continue;
|
|
547
|
-
}
|
|
548
|
-
const migratedRecord = {
|
|
549
|
-
...legacyRecord,
|
|
550
|
-
recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
|
|
551
|
-
fields: {
|
|
552
|
-
...legacyRecord.fields,
|
|
553
|
-
entries: normalizeTicketEntries(legacyRecord.fields.entries)
|
|
554
|
-
}
|
|
555
|
-
};
|
|
556
|
-
await ticketCollection.insertOne(migratedRecord);
|
|
557
|
-
copied += 1;
|
|
558
|
-
}
|
|
559
|
-
return { copied, skipped };
|
|
560
|
-
}
|
|
561
|
-
export async function createDxcompleteTicket(db, input, actor) {
|
|
562
|
-
const now = new Date().toISOString();
|
|
563
|
-
const entry = {
|
|
564
|
-
id: randomUUID(),
|
|
565
|
-
body: input.body,
|
|
566
|
-
createdAt: now,
|
|
567
|
-
createdBy: actor.actorId,
|
|
568
|
-
direction: "submitter_entry"
|
|
569
|
-
};
|
|
570
|
-
const record = {
|
|
571
|
-
_id: randomUUID(),
|
|
572
|
-
recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
|
|
573
|
-
title: input.title,
|
|
574
|
-
fields: {
|
|
575
|
-
ownerActorId: actor.actorId,
|
|
576
|
-
entries: [entry]
|
|
577
|
-
},
|
|
578
|
-
links: [],
|
|
579
|
-
createdAt: now,
|
|
580
|
-
createdBy: actor.actorId,
|
|
581
|
-
updatedAt: now,
|
|
582
|
-
updatedBy: actor.actorId
|
|
583
|
-
};
|
|
584
|
-
await db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME).insertOne(record);
|
|
585
|
-
return record;
|
|
586
|
-
}
|
|
587
|
-
export async function getDxcompleteTicket(db, id, actor) {
|
|
588
|
-
const record = await db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME).findOne(ticketOwnerFilter(id, actor));
|
|
589
|
-
if (!record) {
|
|
590
|
-
throw new Error(`DX Complete Ticket not found: ${id}`);
|
|
591
|
-
}
|
|
592
|
-
return record;
|
|
593
|
-
}
|
|
594
|
-
export async function listDxcompleteTickets(db, actor, limit, options = {}) {
|
|
595
|
-
const filter = {
|
|
596
|
-
"fields.ownerActorId": actor.actorId
|
|
597
|
-
};
|
|
598
|
-
if (!options.includeArchived) {
|
|
599
|
-
filter.archivedAt = { $exists: false };
|
|
600
|
-
}
|
|
601
|
-
return db
|
|
602
|
-
.collection(DXCOMPLETE_TICKET_COLLECTION_NAME)
|
|
603
|
-
.find(filter)
|
|
604
|
-
.sort({ updatedAt: -1 })
|
|
605
|
-
.limit(limit)
|
|
606
|
-
.toArray();
|
|
607
|
-
}
|
|
608
|
-
export async function appendDxcompleteTicket(db, input, actor) {
|
|
609
|
-
const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
|
|
610
|
-
const existing = await collection.findOne({
|
|
611
|
-
...ticketOwnerFilter(input.id, actor),
|
|
612
|
-
archivedAt: { $exists: false }
|
|
613
|
-
});
|
|
614
|
-
if (!existing) {
|
|
615
|
-
throw new Error(`Active DX Complete Ticket not found: ${input.id}`);
|
|
616
|
-
}
|
|
617
|
-
const now = new Date().toISOString();
|
|
618
|
-
const entry = {
|
|
619
|
-
id: randomUUID(),
|
|
620
|
-
body: input.body,
|
|
621
|
-
createdAt: now,
|
|
622
|
-
createdBy: actor.actorId,
|
|
623
|
-
direction: "submitter_entry"
|
|
624
|
-
};
|
|
625
|
-
await collection.updateOne(ticketOwnerFilter(input.id, actor), {
|
|
626
|
-
$push: {
|
|
627
|
-
"fields.entries": entry
|
|
628
|
-
},
|
|
629
|
-
$set: {
|
|
630
|
-
updatedAt: now,
|
|
631
|
-
updatedBy: actor.actorId
|
|
632
|
-
}
|
|
633
|
-
});
|
|
634
|
-
return getDxcompleteTicket(db, input.id, actor);
|
|
635
|
-
}
|
|
636
|
-
export async function appendDxcompleteTicketReply(db, input, actorId = RUNTIME_ACTOR_ID) {
|
|
637
|
-
const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
|
|
638
|
-
const existing = await collection.findOne({
|
|
639
|
-
_id: input.id,
|
|
640
|
-
"fields.ownerActorId": input.addressedToActorId,
|
|
641
|
-
archivedAt: { $exists: false }
|
|
642
|
-
});
|
|
643
|
-
if (!existing) {
|
|
644
|
-
throw new Error(`Active DX Complete Ticket not found for addressed actor: ${input.id}`);
|
|
645
|
-
}
|
|
646
|
-
const now = new Date().toISOString();
|
|
647
|
-
const entry = {
|
|
648
|
-
id: randomUUID(),
|
|
649
|
-
body: input.body,
|
|
650
|
-
createdAt: now,
|
|
651
|
-
createdBy: actorId,
|
|
652
|
-
direction: "dxcomplete_reply",
|
|
653
|
-
addressedToActorId: input.addressedToActorId
|
|
654
|
-
};
|
|
655
|
-
await collection.updateOne({ _id: input.id }, {
|
|
656
|
-
$push: {
|
|
657
|
-
"fields.entries": entry
|
|
658
|
-
},
|
|
659
|
-
$set: {
|
|
660
|
-
updatedAt: now,
|
|
661
|
-
updatedBy: actorId
|
|
662
|
-
}
|
|
663
|
-
});
|
|
664
|
-
const record = await collection.findOne({ _id: input.id });
|
|
665
|
-
if (!record) {
|
|
666
|
-
throw new Error(`DX Complete Ticket not found after reply append: ${input.id}`);
|
|
667
|
-
}
|
|
668
|
-
return record;
|
|
669
|
-
}
|
|
670
|
-
export async function appendJournalNote(db, input, actorId) {
|
|
671
|
-
return createRecord(db, "journal_entries", {
|
|
672
|
-
workspaceId: input.workspaceId,
|
|
673
|
-
title: input.tag ? `Journal note: ${input.tag}` : "Journal note",
|
|
674
|
-
summary: input.body,
|
|
675
|
-
allowManagedFields: true,
|
|
676
|
-
fields: {
|
|
677
|
-
kind: "note",
|
|
678
|
-
body: input.body,
|
|
679
|
-
...(input.tag ? { tag: input.tag } : {})
|
|
680
|
-
}
|
|
681
|
-
}, actorId);
|
|
682
|
-
}
|
|
683
|
-
export async function readJournal(db, input) {
|
|
684
|
-
const limit = clampJournalReadLimit(input.limit);
|
|
685
|
-
const filter = {
|
|
686
|
-
workspaceId: readRequiredWorkspaceId(input.workspaceId, "journal_entries")
|
|
687
|
-
};
|
|
688
|
-
if (!input.includeArchived) {
|
|
689
|
-
filter.archivedAt = { $exists: false };
|
|
690
|
-
filter["fields.kind"] = { $in: ["note", "summary"] };
|
|
691
|
-
}
|
|
692
|
-
const [entries, activeRawNoteCount] = await Promise.all([
|
|
693
|
-
db
|
|
694
|
-
.collection("journal_entries")
|
|
695
|
-
.find(filter)
|
|
696
|
-
.sort({ createdAt: 1 })
|
|
697
|
-
.limit(limit)
|
|
698
|
-
.toArray(),
|
|
699
|
-
db.collection("journal_entries").countDocuments({
|
|
700
|
-
workspaceId: input.workspaceId,
|
|
701
|
-
archivedAt: { $exists: false },
|
|
702
|
-
"fields.kind": "note"
|
|
703
|
-
})
|
|
704
|
-
]);
|
|
705
|
-
return {
|
|
706
|
-
workspaceId: input.workspaceId,
|
|
707
|
-
readTier: input.includeArchived ? "cold" : "hot",
|
|
708
|
-
compaction: {
|
|
709
|
-
activeRawNoteCount,
|
|
710
|
-
threshold: JOURNAL_COMPACTION_THRESHOLD,
|
|
711
|
-
recommended: activeRawNoteCount >= JOURNAL_COMPACTION_THRESHOLD
|
|
712
|
-
},
|
|
713
|
-
entries
|
|
714
|
-
};
|
|
715
|
-
}
|
|
716
|
-
export async function getJournalEntry(db, input) {
|
|
717
|
-
const entry = await getRecord(db, "journal_entries", input.id, { workspaceId: input.workspaceId });
|
|
718
|
-
if (!entry) {
|
|
719
|
-
throw new Error(`Journal entry not found: journal_entries/${input.id}`);
|
|
720
|
-
}
|
|
721
|
-
return entry;
|
|
722
|
-
}
|
|
723
|
-
export async function appendJournalSummary(db, input, actorId) {
|
|
724
|
-
const coveredIds = [...new Set(input.covers.map((id) => id.trim()).filter(Boolean))];
|
|
725
|
-
if (coveredIds.length === 0) {
|
|
726
|
-
throw new Error("append_journal_summary requires at least one covered journal entry id.");
|
|
727
|
-
}
|
|
728
|
-
const coveredEntries = [];
|
|
729
|
-
for (const id of coveredIds) {
|
|
730
|
-
const entry = await getRecord(db, "journal_entries", id, { workspaceId: input.workspaceId });
|
|
731
|
-
if (!entry) {
|
|
732
|
-
throw new Error(`Covered journal entry not found: journal_entries/${id}`);
|
|
733
|
-
}
|
|
734
|
-
const kind = readJournalEntryKind(entry);
|
|
735
|
-
if (!kind) {
|
|
736
|
-
throw new Error(`Covered record is not a journal note or summary: journal_entries/${id}`);
|
|
737
|
-
}
|
|
738
|
-
coveredEntries.push(entry);
|
|
739
|
-
}
|
|
740
|
-
const summary = await createRecord(db, "journal_entries", {
|
|
741
|
-
workspaceId: input.workspaceId,
|
|
742
|
-
title: input.tag ? `Journal summary: ${input.tag}` : "Journal summary",
|
|
743
|
-
summary: input.body,
|
|
744
|
-
allowManagedFields: true,
|
|
745
|
-
fields: {
|
|
746
|
-
kind: "summary",
|
|
747
|
-
body: input.body,
|
|
748
|
-
covers: coveredEntries.map((entry) => entry._id),
|
|
749
|
-
...(input.tag ? { tag: input.tag } : {})
|
|
750
|
-
}
|
|
751
|
-
}, actorId);
|
|
752
|
-
const now = new Date().toISOString();
|
|
753
|
-
await db.collection("journal_entries").updateMany({
|
|
754
|
-
workspaceId: input.workspaceId,
|
|
755
|
-
_id: { $in: coveredEntries.map((entry) => entry._id) },
|
|
756
|
-
archivedAt: { $exists: false }
|
|
757
|
-
}, {
|
|
758
|
-
$set: {
|
|
759
|
-
archivedAt: now,
|
|
760
|
-
archivedBy: actorId,
|
|
761
|
-
archiveReason: `Covered by journal summary ${summary._id}`,
|
|
762
|
-
"fields.coveredBySummaryId": summary._id,
|
|
763
|
-
updatedAt: now,
|
|
764
|
-
updatedBy: actorId
|
|
765
|
-
}
|
|
766
|
-
});
|
|
767
|
-
return summary;
|
|
768
|
-
}
|
|
769
|
-
function clampJournalReadLimit(limit) {
|
|
770
|
-
if (!limit) {
|
|
771
|
-
return 100;
|
|
772
|
-
}
|
|
773
|
-
return Math.min(Math.max(limit, 1), 500);
|
|
774
|
-
}
|
|
775
|
-
function readJournalEntryKind(record) {
|
|
776
|
-
if (record.fields.kind === "note" || record.fields.kind === "summary") {
|
|
777
|
-
return record.fields.kind;
|
|
778
|
-
}
|
|
779
|
-
return undefined;
|
|
780
|
-
}
|
|
781
|
-
export async function appendReviewNote(db, input, actorId) {
|
|
782
|
-
const collection = db.collection(input.recordType);
|
|
783
|
-
const filter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
|
|
784
|
-
const existing = await collection.findOne(filter);
|
|
785
|
-
if (!existing) {
|
|
786
|
-
throw new Error(`Record not found: ${input.recordType}/${input.id}`);
|
|
787
|
-
}
|
|
788
|
-
const now = new Date().toISOString();
|
|
789
|
-
const note = {
|
|
790
|
-
id: randomUUID(),
|
|
791
|
-
body: input.body,
|
|
792
|
-
createdAt: now,
|
|
793
|
-
createdBy: actorId,
|
|
794
|
-
...(input.important ? { important: true } : {})
|
|
795
|
-
};
|
|
796
|
-
await collection.updateOne(filter, {
|
|
797
|
-
$push: {
|
|
798
|
-
"fields.reviewNotes": note
|
|
799
|
-
},
|
|
800
|
-
$set: {
|
|
801
|
-
updatedAt: now,
|
|
802
|
-
updatedBy: actorId
|
|
803
|
-
}
|
|
804
|
-
});
|
|
805
|
-
const updated = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
|
|
806
|
-
if (!updated) {
|
|
807
|
-
throw new Error(`Record not found after review note append: ${input.recordType}/${input.id}`);
|
|
808
|
-
}
|
|
809
|
-
return updated;
|
|
810
|
-
}
|
|
811
|
-
export async function appendChangeEvent(db, input, actorId) {
|
|
812
|
-
const collection = db.collection("changes");
|
|
813
|
-
const filter = scopedRecordFilter("changes", input.changeId, input.workspaceId);
|
|
814
|
-
const existing = await collection.findOne(filter);
|
|
815
|
-
if (!existing) {
|
|
816
|
-
throw new Error(`Record not found: changes/${input.changeId}`);
|
|
817
|
-
}
|
|
818
|
-
const now = new Date().toISOString();
|
|
819
|
-
const event = {
|
|
820
|
-
...input.event,
|
|
821
|
-
id: randomUUID(),
|
|
822
|
-
eventType: input.eventType,
|
|
823
|
-
createdAt: now,
|
|
824
|
-
createdBy: actorId
|
|
825
|
-
};
|
|
826
|
-
await collection.updateOne(filter, {
|
|
827
|
-
$push: {
|
|
828
|
-
"fields.events": event
|
|
829
|
-
},
|
|
830
|
-
$set: {
|
|
831
|
-
updatedAt: now,
|
|
832
|
-
updatedBy: actorId
|
|
833
|
-
}
|
|
834
|
-
});
|
|
835
|
-
const updated = await getRecord(db, "changes", input.changeId, { workspaceId: input.workspaceId });
|
|
836
|
-
if (!updated) {
|
|
837
|
-
throw new Error(`Record not found after change event append: changes/${input.changeId}`);
|
|
838
|
-
}
|
|
839
|
-
return updated;
|
|
840
|
-
}
|
|
841
|
-
export async function appendDeferralEvent(db, input, actorId) {
|
|
842
|
-
const collection = db.collection("deferrals");
|
|
843
|
-
const filter = scopedRecordFilter("deferrals", input.deferralId, input.workspaceId);
|
|
844
|
-
const existing = await collection.findOne(filter);
|
|
845
|
-
if (!existing) {
|
|
846
|
-
throw new Error(`Record not found: deferrals/${input.deferralId}`);
|
|
847
|
-
}
|
|
848
|
-
const now = new Date().toISOString();
|
|
849
|
-
const event = {
|
|
850
|
-
...input.event,
|
|
851
|
-
id: randomUUID(),
|
|
852
|
-
eventType: input.eventType,
|
|
853
|
-
createdAt: now,
|
|
854
|
-
createdBy: actorId
|
|
855
|
-
};
|
|
856
|
-
const { conditions, status } = applyDeferralEventState(existing, event, actorId, now);
|
|
857
|
-
await collection.updateOne(filter, {
|
|
858
|
-
$push: {
|
|
859
|
-
"fields.conditionEvents": event
|
|
860
|
-
},
|
|
861
|
-
$set: {
|
|
862
|
-
"fields.conditions": conditions,
|
|
863
|
-
"fields.status": status,
|
|
864
|
-
updatedAt: now,
|
|
865
|
-
updatedBy: actorId
|
|
866
|
-
}
|
|
867
|
-
});
|
|
868
|
-
const updated = await getRecord(db, "deferrals", input.deferralId, { workspaceId: input.workspaceId });
|
|
869
|
-
if (!updated) {
|
|
870
|
-
throw new Error(`Record not found after deferral event append: deferrals/${input.deferralId}`);
|
|
871
|
-
}
|
|
872
|
-
return updated;
|
|
873
|
-
}
|
|
874
|
-
export async function appendDecisionEntry(db, input, actorId) {
|
|
875
|
-
const collection = db.collection("decisions");
|
|
876
|
-
const filter = scopedRecordFilter("decisions", input.decisionId, input.workspaceId);
|
|
877
|
-
const existing = await collection.findOne(filter);
|
|
878
|
-
if (!existing) {
|
|
879
|
-
throw new Error(`Record not found: decisions/${input.decisionId}`);
|
|
880
|
-
}
|
|
881
|
-
assertDecisionEntryInput(input);
|
|
882
|
-
const now = new Date().toISOString();
|
|
883
|
-
const entry = {
|
|
884
|
-
id: randomUUID(),
|
|
885
|
-
entryType: input.entryType,
|
|
886
|
-
body: input.body,
|
|
887
|
-
createdAt: now,
|
|
888
|
-
createdBy: actorId,
|
|
889
|
-
...(input.decidedBy ? { decidedBy: input.decidedBy } : {}),
|
|
890
|
-
...(input.rationale ? { rationale: input.rationale } : {})
|
|
891
|
-
};
|
|
892
|
-
const update = {
|
|
893
|
-
$push: {
|
|
894
|
-
"fields.entries": entry
|
|
895
|
-
},
|
|
896
|
-
$set: {
|
|
897
|
-
updatedAt: now,
|
|
898
|
-
updatedBy: actorId
|
|
899
|
-
}
|
|
900
|
-
};
|
|
901
|
-
if (entry.entryType === "decision") {
|
|
902
|
-
update.$set["fields.currentDecision"] = decisionEntryToCurrentDecision(entry);
|
|
903
|
-
}
|
|
904
|
-
await collection.updateOne(filter, update);
|
|
905
|
-
const updated = await getRecord(db, "decisions", input.decisionId, { workspaceId: input.workspaceId });
|
|
906
|
-
if (!updated) {
|
|
907
|
-
throw new Error(`Record not found after decision entry append: decisions/${input.decisionId}`);
|
|
908
|
-
}
|
|
909
|
-
return updated;
|
|
910
|
-
}
|
|
911
|
-
export async function appendTaskEntry(db, input, actorId) {
|
|
912
|
-
const collection = db.collection("tasks");
|
|
913
|
-
const filter = scopedRecordFilter("tasks", input.taskId, input.workspaceId);
|
|
914
|
-
const existing = await collection.findOne(filter);
|
|
915
|
-
if (!existing) {
|
|
916
|
-
throw new Error(`Record not found: tasks/${input.taskId}`);
|
|
917
|
-
}
|
|
918
|
-
assertTaskEntryInput(input);
|
|
919
|
-
const now = new Date().toISOString();
|
|
920
|
-
const entry = {
|
|
921
|
-
id: randomUUID(),
|
|
922
|
-
entryType: input.entryType,
|
|
923
|
-
body: input.body,
|
|
924
|
-
createdAt: now,
|
|
925
|
-
createdBy: actorId,
|
|
926
|
-
...(input.status ? { status: input.status } : {})
|
|
927
|
-
};
|
|
928
|
-
const update = {
|
|
929
|
-
$push: {
|
|
930
|
-
"fields.entries": entry
|
|
931
|
-
},
|
|
932
|
-
$set: {
|
|
933
|
-
updatedAt: now,
|
|
934
|
-
updatedBy: actorId
|
|
935
|
-
}
|
|
936
|
-
};
|
|
937
|
-
if (entry.entryType === "status_change") {
|
|
938
|
-
update.$set["fields.currentStatus"] = taskEntryToCurrentStatus(entry);
|
|
939
|
-
}
|
|
940
|
-
await collection.updateOne(filter, update);
|
|
941
|
-
const updated = await getRecord(db, "tasks", input.taskId, { workspaceId: input.workspaceId });
|
|
942
|
-
if (!updated) {
|
|
943
|
-
throw new Error(`Record not found after task entry append: tasks/${input.taskId}`);
|
|
944
|
-
}
|
|
945
|
-
return updated;
|
|
946
|
-
}
|
|
947
|
-
export async function appendRiskEntry(db, input, actorId) {
|
|
948
|
-
const collection = db.collection("risks");
|
|
949
|
-
const filter = scopedRecordFilter("risks", input.riskId, input.workspaceId);
|
|
950
|
-
const existing = await collection.findOne(filter);
|
|
951
|
-
if (!existing) {
|
|
952
|
-
throw new Error(`Record not found: risks/${input.riskId}`);
|
|
953
|
-
}
|
|
954
|
-
assertRiskEntryInput(input);
|
|
955
|
-
const now = new Date().toISOString();
|
|
956
|
-
const entry = {
|
|
957
|
-
id: randomUUID(),
|
|
958
|
-
entryType: input.entryType,
|
|
959
|
-
body: input.body,
|
|
960
|
-
createdAt: now,
|
|
961
|
-
createdBy: actorId,
|
|
962
|
-
...(input.likelihood ? { likelihood: input.likelihood } : {}),
|
|
963
|
-
...(input.impact ? { impact: input.impact } : {}),
|
|
964
|
-
...(input.treatment ? { treatment: input.treatment } : {}),
|
|
965
|
-
...(input.treatmentRationale ? { treatmentRationale: input.treatmentRationale } : {})
|
|
966
|
-
};
|
|
967
|
-
const update = {
|
|
968
|
-
$push: {
|
|
969
|
-
"fields.entries": entry
|
|
970
|
-
},
|
|
971
|
-
$set: {
|
|
972
|
-
updatedAt: now,
|
|
973
|
-
updatedBy: actorId
|
|
974
|
-
}
|
|
975
|
-
};
|
|
976
|
-
if (entry.entryType === "identified" || entry.entryType === "reopened") {
|
|
977
|
-
update.$set["fields.currentStatus"] = riskEntryToCurrentStatus(entry, "open");
|
|
978
|
-
}
|
|
979
|
-
if (entry.entryType === "closed") {
|
|
980
|
-
update.$set["fields.currentStatus"] = riskEntryToCurrentStatus(entry, "closed");
|
|
981
|
-
}
|
|
982
|
-
if (entry.entryType === "assessment") {
|
|
983
|
-
update.$set["fields.currentAssessment"] = riskEntryToCurrentAssessment(entry);
|
|
984
|
-
}
|
|
985
|
-
if (entry.entryType === "treatment") {
|
|
986
|
-
update.$set["fields.currentTreatment"] = riskEntryToCurrentTreatment(entry);
|
|
987
|
-
}
|
|
988
|
-
await collection.updateOne(filter, update);
|
|
989
|
-
const updated = await getRecord(db, "risks", input.riskId, { workspaceId: input.workspaceId });
|
|
990
|
-
if (!updated) {
|
|
991
|
-
throw new Error(`Record not found after risk entry append: risks/${input.riskId}`);
|
|
992
|
-
}
|
|
993
|
-
return updated;
|
|
994
|
-
}
|
|
995
|
-
export async function appendIncidentEntry(db, input, actorId) {
|
|
996
|
-
const collection = db.collection("incidents");
|
|
997
|
-
const filter = scopedRecordFilter("incidents", input.incidentId, input.workspaceId);
|
|
998
|
-
const existing = await collection.findOne(filter);
|
|
999
|
-
if (!existing) {
|
|
1000
|
-
throw new Error(`Record not found: incidents/${input.incidentId}`);
|
|
1001
|
-
}
|
|
1002
|
-
assertIncidentEntryInput(input);
|
|
1003
|
-
const now = new Date().toISOString();
|
|
1004
|
-
const entry = {
|
|
1005
|
-
id: randomUUID(),
|
|
1006
|
-
entryType: input.entryType,
|
|
1007
|
-
body: input.body,
|
|
1008
|
-
createdAt: now,
|
|
1009
|
-
createdBy: actorId,
|
|
1010
|
-
...(input.severity ? { severity: input.severity } : {})
|
|
1011
|
-
};
|
|
1012
|
-
const update = {
|
|
1013
|
-
$push: {
|
|
1014
|
-
"fields.entries": entry
|
|
1015
|
-
},
|
|
1016
|
-
$set: {
|
|
1017
|
-
updatedAt: now,
|
|
1018
|
-
updatedBy: actorId
|
|
1019
|
-
}
|
|
1020
|
-
};
|
|
1021
|
-
if (entry.entryType === "detected" || entry.entryType === "reopened") {
|
|
1022
|
-
update.$set["fields.currentStatus"] = incidentEntryToCurrentStatus(entry, "open");
|
|
1023
|
-
}
|
|
1024
|
-
if (entry.entryType === "resolved") {
|
|
1025
|
-
update.$set["fields.currentStatus"] = incidentEntryToCurrentStatus(entry, "resolved");
|
|
1026
|
-
}
|
|
1027
|
-
if (entry.entryType === "severity") {
|
|
1028
|
-
update.$set["fields.currentSeverity"] = incidentEntryToCurrentSeverity(entry);
|
|
1029
|
-
}
|
|
1030
|
-
await collection.updateOne(filter, update);
|
|
1031
|
-
const updated = await getRecord(db, "incidents", input.incidentId, { workspaceId: input.workspaceId });
|
|
1032
|
-
if (!updated) {
|
|
1033
|
-
throw new Error(`Record not found after incident entry append: incidents/${input.incidentId}`);
|
|
1034
|
-
}
|
|
1035
|
-
return updated;
|
|
1036
|
-
}
|
|
1037
|
-
export async function appendProblemEntry(db, input, actorId) {
|
|
1038
|
-
const collection = db.collection("problems");
|
|
1039
|
-
const filter = scopedRecordFilter("problems", input.problemId, input.workspaceId);
|
|
1040
|
-
const existing = await collection.findOne(filter);
|
|
1041
|
-
if (!existing) {
|
|
1042
|
-
throw new Error(`Record not found: problems/${input.problemId}`);
|
|
1043
|
-
}
|
|
1044
|
-
assertProblemEntryInput(input);
|
|
1045
|
-
const now = new Date().toISOString();
|
|
1046
|
-
const entry = {
|
|
1047
|
-
id: randomUUID(),
|
|
1048
|
-
entryType: input.entryType,
|
|
1049
|
-
body: input.body,
|
|
1050
|
-
createdAt: now,
|
|
1051
|
-
createdBy: actorId,
|
|
1052
|
-
...(input.rootCause ? { rootCause: input.rootCause } : {})
|
|
1053
|
-
};
|
|
1054
|
-
const update = {
|
|
1055
|
-
$push: {
|
|
1056
|
-
"fields.entries": entry
|
|
1057
|
-
},
|
|
1058
|
-
$set: {
|
|
1059
|
-
updatedAt: now,
|
|
1060
|
-
updatedBy: actorId
|
|
1061
|
-
}
|
|
1062
|
-
};
|
|
1063
|
-
if (entry.entryType === "identified" || entry.entryType === "reopened") {
|
|
1064
|
-
update.$set["fields.currentStatus"] = problemEntryToCurrentStatus(entry, "open");
|
|
1065
|
-
}
|
|
1066
|
-
if (entry.entryType === "known_error") {
|
|
1067
|
-
update.$set["fields.currentStatus"] = problemEntryToCurrentStatus(entry, "known_error");
|
|
1068
|
-
}
|
|
1069
|
-
if (entry.entryType === "resolved") {
|
|
1070
|
-
update.$set["fields.currentStatus"] = problemEntryToCurrentStatus(entry, "resolved");
|
|
1071
|
-
}
|
|
1072
|
-
if (entry.entryType === "root_cause") {
|
|
1073
|
-
update.$set["fields.currentRootCause"] = problemEntryToCurrentRootCause(entry);
|
|
1074
|
-
}
|
|
1075
|
-
await collection.updateOne(filter, update);
|
|
1076
|
-
const updated = await getRecord(db, "problems", input.problemId, { workspaceId: input.workspaceId });
|
|
1077
|
-
if (!updated) {
|
|
1078
|
-
throw new Error(`Record not found after problem entry append: problems/${input.problemId}`);
|
|
1079
|
-
}
|
|
1080
|
-
return updated;
|
|
1081
|
-
}
|
|
1082
|
-
export async function appendSupportRequestEntry(db, input, actorId) {
|
|
1083
|
-
const collection = db.collection("support_requests");
|
|
1084
|
-
const filter = scopedRecordFilter("support_requests", input.supportRequestId, input.workspaceId);
|
|
1085
|
-
const existing = await collection.findOne(filter);
|
|
1086
|
-
if (!existing) {
|
|
1087
|
-
throw new Error(`Record not found: support_requests/${input.supportRequestId}`);
|
|
1088
|
-
}
|
|
1089
|
-
assertSupportRequestEntryInput(input);
|
|
1090
|
-
const now = new Date().toISOString();
|
|
1091
|
-
const entry = {
|
|
1092
|
-
id: randomUUID(),
|
|
1093
|
-
entryType: input.entryType,
|
|
1094
|
-
body: input.body,
|
|
1095
|
-
createdAt: now,
|
|
1096
|
-
createdBy: actorId,
|
|
1097
|
-
...(input.incidentId ? { incidentId: input.incidentId } : {})
|
|
1098
|
-
};
|
|
1099
|
-
const update = {
|
|
1100
|
-
$push: {
|
|
1101
|
-
"fields.entries": entry
|
|
1102
|
-
},
|
|
1103
|
-
$set: {
|
|
1104
|
-
updatedAt: now,
|
|
1105
|
-
updatedBy: actorId
|
|
1106
|
-
}
|
|
1107
|
-
};
|
|
1108
|
-
const currentStatus = supportRequestEntryToCurrentStatus(entry, readSupportRequestStatus(existing));
|
|
1109
|
-
if (currentStatus) {
|
|
1110
|
-
update.$set["fields.currentStatus"] = currentStatus;
|
|
1111
|
-
}
|
|
1112
|
-
await collection.updateOne(filter, update);
|
|
1113
|
-
const updated = await getRecord(db, "support_requests", input.supportRequestId, { workspaceId: input.workspaceId });
|
|
1114
|
-
if (!updated) {
|
|
1115
|
-
throw new Error(`Record not found after support request entry append: support_requests/${input.supportRequestId}`);
|
|
1116
|
-
}
|
|
1117
|
-
return updated;
|
|
1118
|
-
}
|
|
1119
|
-
export function decisionEntryToCurrentDecision(entry) {
|
|
1120
|
-
return {
|
|
1121
|
-
entryId: entry.id,
|
|
1122
|
-
body: entry.body,
|
|
1123
|
-
createdAt: entry.createdAt,
|
|
1124
|
-
createdBy: entry.createdBy,
|
|
1125
|
-
...(entry.decidedBy ? { decidedBy: entry.decidedBy } : {}),
|
|
1126
|
-
...(entry.rationale ? { rationale: entry.rationale } : {})
|
|
1127
|
-
};
|
|
1128
|
-
}
|
|
1129
|
-
export function taskEntryToCurrentStatus(entry) {
|
|
1130
|
-
if (entry.entryType !== "status_change" || !entry.status) {
|
|
1131
|
-
throw new Error("Task current status can only derive from a status_change entry.");
|
|
1132
|
-
}
|
|
1133
|
-
return {
|
|
1134
|
-
entryId: entry.id,
|
|
1135
|
-
status: entry.status,
|
|
1136
|
-
body: entry.body,
|
|
1137
|
-
createdAt: entry.createdAt,
|
|
1138
|
-
createdBy: entry.createdBy
|
|
1139
|
-
};
|
|
1140
|
-
}
|
|
1141
|
-
export function riskEntryToCurrentStatus(entry, status) {
|
|
1142
|
-
return {
|
|
1143
|
-
entryId: entry.id,
|
|
1144
|
-
status,
|
|
1145
|
-
body: entry.body,
|
|
1146
|
-
createdAt: entry.createdAt,
|
|
1147
|
-
createdBy: entry.createdBy
|
|
1148
|
-
};
|
|
1149
|
-
}
|
|
1150
|
-
export function riskEntryToCurrentAssessment(entry) {
|
|
1151
|
-
if (entry.entryType !== "assessment" || !entry.likelihood || !entry.impact) {
|
|
1152
|
-
throw new Error("Risk current assessment can only derive from an assessment entry with likelihood and impact.");
|
|
1153
|
-
}
|
|
1154
|
-
return {
|
|
1155
|
-
entryId: entry.id,
|
|
1156
|
-
likelihood: entry.likelihood,
|
|
1157
|
-
impact: entry.impact,
|
|
1158
|
-
body: entry.body,
|
|
1159
|
-
createdAt: entry.createdAt,
|
|
1160
|
-
createdBy: entry.createdBy
|
|
1161
|
-
};
|
|
1162
|
-
}
|
|
1163
|
-
export function riskEntryToCurrentTreatment(entry) {
|
|
1164
|
-
if (entry.entryType !== "treatment" || !entry.treatment) {
|
|
1165
|
-
throw new Error("Risk current treatment can only derive from a treatment entry.");
|
|
1166
|
-
}
|
|
1167
|
-
return {
|
|
1168
|
-
entryId: entry.id,
|
|
1169
|
-
treatment: entry.treatment,
|
|
1170
|
-
body: entry.body,
|
|
1171
|
-
createdAt: entry.createdAt,
|
|
1172
|
-
createdBy: entry.createdBy,
|
|
1173
|
-
...(entry.treatmentRationale ? { treatmentRationale: entry.treatmentRationale } : {})
|
|
1174
|
-
};
|
|
1175
|
-
}
|
|
1176
|
-
export function incidentEntryToCurrentStatus(entry, status) {
|
|
1177
|
-
return {
|
|
1178
|
-
entryId: entry.id,
|
|
1179
|
-
status,
|
|
1180
|
-
body: entry.body,
|
|
1181
|
-
createdAt: entry.createdAt,
|
|
1182
|
-
createdBy: entry.createdBy
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
export function incidentEntryToCurrentSeverity(entry) {
|
|
1186
|
-
if (entry.entryType !== "severity" || !entry.severity) {
|
|
1187
|
-
throw new Error("Incident current severity can only derive from a severity entry.");
|
|
1188
|
-
}
|
|
1189
|
-
return {
|
|
1190
|
-
entryId: entry.id,
|
|
1191
|
-
severity: entry.severity,
|
|
1192
|
-
body: entry.body,
|
|
1193
|
-
createdAt: entry.createdAt,
|
|
1194
|
-
createdBy: entry.createdBy
|
|
1195
|
-
};
|
|
1196
|
-
}
|
|
1197
|
-
export function problemEntryToCurrentStatus(entry, status) {
|
|
1198
|
-
return {
|
|
1199
|
-
entryId: entry.id,
|
|
1200
|
-
status,
|
|
1201
|
-
body: entry.body,
|
|
1202
|
-
createdAt: entry.createdAt,
|
|
1203
|
-
createdBy: entry.createdBy
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
export function problemEntryToCurrentRootCause(entry) {
|
|
1207
|
-
if (entry.entryType !== "root_cause") {
|
|
1208
|
-
throw new Error("Problem current root cause can only derive from a root_cause entry.");
|
|
1209
|
-
}
|
|
1210
|
-
return {
|
|
1211
|
-
entryId: entry.id,
|
|
1212
|
-
rootCause: entry.rootCause ?? entry.body,
|
|
1213
|
-
body: entry.body,
|
|
1214
|
-
createdAt: entry.createdAt,
|
|
1215
|
-
createdBy: entry.createdBy
|
|
1216
|
-
};
|
|
1217
|
-
}
|
|
1218
|
-
export function supportRequestEntryToCurrentStatus(entry, previousStatus) {
|
|
1219
|
-
const status = supportRequestStatusForEntryType(entry.entryType);
|
|
1220
|
-
if (!status) {
|
|
1221
|
-
return previousStatus;
|
|
1222
|
-
}
|
|
1223
|
-
return {
|
|
1224
|
-
entryId: entry.id,
|
|
1225
|
-
status,
|
|
1226
|
-
body: entry.body,
|
|
1227
|
-
createdAt: entry.createdAt,
|
|
1228
|
-
createdBy: entry.createdBy
|
|
1229
|
-
};
|
|
1230
|
-
}
|
|
1231
|
-
function supportRequestStatusForEntryType(entryType) {
|
|
1232
|
-
switch (entryType) {
|
|
1233
|
-
case "raised":
|
|
1234
|
-
case "reopened":
|
|
1235
|
-
return "open";
|
|
1236
|
-
case "triage":
|
|
1237
|
-
return "triaged";
|
|
1238
|
-
case "escalated":
|
|
1239
|
-
return "escalated";
|
|
1240
|
-
case "resolved":
|
|
1241
|
-
return "resolved";
|
|
1242
|
-
case "update":
|
|
1243
|
-
case "note":
|
|
1244
|
-
return undefined;
|
|
1245
|
-
}
|
|
1246
|
-
}
|
|
1247
|
-
function readSupportRequestStatus(record) {
|
|
1248
|
-
return record.fields.currentStatus && typeof record.fields.currentStatus === "object"
|
|
1249
|
-
? record.fields.currentStatus
|
|
1250
|
-
: undefined;
|
|
1251
|
-
}
|
|
1252
|
-
function assertDecisionEntryInput(input) {
|
|
1253
|
-
if (input.entryType !== "decision" && (input.decidedBy || input.rationale)) {
|
|
1254
|
-
throw new Error("decidedBy and rationale are only valid on decision entries.");
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1257
|
-
function assertTaskEntryInput(input) {
|
|
1258
|
-
if (input.entryType === "status_change" && !input.status) {
|
|
1259
|
-
throw new Error("status_change entries require status.");
|
|
1260
|
-
}
|
|
1261
|
-
if (input.entryType !== "status_change" && input.status) {
|
|
1262
|
-
throw new Error("status is only valid on status_change entries.");
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
function assertRiskEntryInput(input) {
|
|
1266
|
-
if (input.entryType === "assessment" && (!input.likelihood || !input.impact)) {
|
|
1267
|
-
throw new Error("assessment entries require likelihood and impact.");
|
|
1268
|
-
}
|
|
1269
|
-
if (input.entryType !== "assessment" && (input.likelihood || input.impact)) {
|
|
1270
|
-
throw new Error("likelihood and impact are only valid on assessment entries.");
|
|
1271
|
-
}
|
|
1272
|
-
if (input.entryType === "treatment" && !input.treatment) {
|
|
1273
|
-
throw new Error("treatment entries require treatment.");
|
|
1274
|
-
}
|
|
1275
|
-
if (input.entryType !== "treatment" && (input.treatment || input.treatmentRationale)) {
|
|
1276
|
-
throw new Error("treatment and treatmentRationale are only valid on treatment entries.");
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
function assertIncidentEntryInput(input) {
|
|
1280
|
-
if (input.entryType === "severity" && !input.severity) {
|
|
1281
|
-
throw new Error("severity entries require severity.");
|
|
1282
|
-
}
|
|
1283
|
-
if (input.entryType !== "severity" && input.severity) {
|
|
1284
|
-
throw new Error("severity is only valid on severity entries.");
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
function assertProblemEntryInput(input) {
|
|
1288
|
-
if (input.entryType !== "root_cause" && input.rootCause) {
|
|
1289
|
-
throw new Error("rootCause is only valid on root_cause entries.");
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
function assertSupportRequestEntryInput(input) {
|
|
1293
|
-
if (input.entryType === "escalated" && !input.incidentId) {
|
|
1294
|
-
throw new Error("escalated support request entries require incidentId.");
|
|
1295
|
-
}
|
|
1296
|
-
if (input.entryType !== "escalated" && input.incidentId) {
|
|
1297
|
-
throw new Error("incidentId is only valid on escalated support request entries.");
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
function applyDeferralEventState(existing, event, actorId, now) {
|
|
1301
|
-
const conditions = normalizeDeferralConditions(existing.fields.conditions);
|
|
1302
|
-
let status = typeof existing.fields.status === "string" ? existing.fields.status : "open";
|
|
1303
|
-
switch (event.eventType) {
|
|
1304
|
-
case "condition_addressed":
|
|
1305
|
-
return {
|
|
1306
|
-
conditions: updateDeferralConditionState(conditions, event, "addressed", actorId, now),
|
|
1307
|
-
status
|
|
1308
|
-
};
|
|
1309
|
-
case "condition_reopened":
|
|
1310
|
-
return {
|
|
1311
|
-
conditions: updateDeferralConditionState(conditions, event, "open", actorId, now),
|
|
1312
|
-
status
|
|
1313
|
-
};
|
|
1314
|
-
case "condition_note_added":
|
|
1315
|
-
assertDeferralConditionExists(conditions, event);
|
|
1316
|
-
return { conditions, status };
|
|
1317
|
-
case "deferral_resolved":
|
|
1318
|
-
status = "resolved";
|
|
1319
|
-
return { conditions, status };
|
|
1320
|
-
case "deferral_abandoned":
|
|
1321
|
-
status = "abandoned";
|
|
1322
|
-
return { conditions, status };
|
|
1323
|
-
}
|
|
1324
|
-
}
|
|
1325
|
-
function normalizeDeferralConditions(value) {
|
|
1326
|
-
if (!Array.isArray(value)) {
|
|
1327
|
-
return [];
|
|
1328
|
-
}
|
|
1329
|
-
return value.filter(isDeferralCondition);
|
|
1330
|
-
}
|
|
1331
|
-
function isDeferralCondition(value) {
|
|
1332
|
-
if (!value || typeof value !== "object") {
|
|
1333
|
-
return false;
|
|
1334
|
-
}
|
|
1335
|
-
const condition = value;
|
|
1336
|
-
return (typeof condition.id === "string" &&
|
|
1337
|
-
typeof condition.statement === "string" &&
|
|
1338
|
-
(condition.state === "open" || condition.state === "addressed") &&
|
|
1339
|
-
typeof condition.createdAt === "string" &&
|
|
1340
|
-
typeof condition.createdBy === "string" &&
|
|
1341
|
-
typeof condition.updatedAt === "string" &&
|
|
1342
|
-
typeof condition.updatedBy === "string");
|
|
1343
|
-
}
|
|
1344
|
-
function updateDeferralConditionState(conditions, event, state, actorId, now) {
|
|
1345
|
-
const conditionId = readRequiredDeferralEventString(event, "conditionId");
|
|
1346
|
-
let found = false;
|
|
1347
|
-
const updated = conditions.map((condition) => {
|
|
1348
|
-
if (condition.id !== conditionId) {
|
|
1349
|
-
return condition;
|
|
1350
|
-
}
|
|
1351
|
-
found = true;
|
|
1352
|
-
return {
|
|
1353
|
-
...condition,
|
|
1354
|
-
state,
|
|
1355
|
-
updatedAt: now,
|
|
1356
|
-
updatedBy: actorId
|
|
1357
|
-
};
|
|
1358
|
-
});
|
|
1359
|
-
if (!found) {
|
|
1360
|
-
throw new Error(`Deferral condition not found: ${conditionId}`);
|
|
1361
|
-
}
|
|
1362
|
-
return updated;
|
|
1363
|
-
}
|
|
1364
|
-
function assertDeferralConditionExists(conditions, event) {
|
|
1365
|
-
const conditionId = readRequiredDeferralEventString(event, "conditionId");
|
|
1366
|
-
if (!conditions.some((condition) => condition.id === conditionId)) {
|
|
1367
|
-
throw new Error(`Deferral condition not found: ${conditionId}`);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
function readRequiredDeferralEventString(event, key) {
|
|
1371
|
-
const value = event[key];
|
|
1372
|
-
if (typeof value !== "string" || !value.trim()) {
|
|
1373
|
-
throw new Error(`${event.eventType} requires ${key}.`);
|
|
1374
|
-
}
|
|
1375
|
-
return value;
|
|
1376
|
-
}
|
|
1377
|
-
export async function listUnreadDxcompleteTicketReplies(db, actor, limit) {
|
|
1378
|
-
const records = await db
|
|
1379
|
-
.collection(DXCOMPLETE_TICKET_COLLECTION_NAME)
|
|
1380
|
-
.find({
|
|
1381
|
-
"fields.ownerActorId": actor.actorId,
|
|
1382
|
-
archivedAt: { $exists: false },
|
|
1383
|
-
"fields.entries": {
|
|
1384
|
-
$elemMatch: {
|
|
1385
|
-
direction: "dxcomplete_reply",
|
|
1386
|
-
addressedToActorId: actor.actorId,
|
|
1387
|
-
readAt: { $exists: false }
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
})
|
|
1391
|
-
.sort({ updatedAt: -1 })
|
|
1392
|
-
.limit(limit)
|
|
1393
|
-
.toArray();
|
|
1394
|
-
return records.map((record) => {
|
|
1395
|
-
const replies = normalizeTicketEntries(record.fields.entries).filter((entry) => entry.direction === "dxcomplete_reply" &&
|
|
1396
|
-
entry.addressedToActorId === actor.actorId &&
|
|
1397
|
-
!entry.readAt);
|
|
1398
|
-
const replySummaries = replies.map((entry) => ({
|
|
1399
|
-
id: entry.id,
|
|
1400
|
-
createdAt: entry.createdAt,
|
|
1401
|
-
createdBy: entry.createdBy,
|
|
1402
|
-
direction: "dxcomplete_reply",
|
|
1403
|
-
...(entry.addressedToActorId ? { addressedToActorId: entry.addressedToActorId } : {})
|
|
1404
|
-
}));
|
|
1405
|
-
const newestReplyAt = replySummaries.reduce((current, entry) => (!current || entry.createdAt > current ? entry.createdAt : current), undefined);
|
|
1406
|
-
return {
|
|
1407
|
-
ticketId: record._id,
|
|
1408
|
-
...(record.title ? { title: record.title } : {}),
|
|
1409
|
-
updatedAt: record.updatedAt,
|
|
1410
|
-
unreadReplyCount: replySummaries.length,
|
|
1411
|
-
...(newestReplyAt ? { newestReplyAt } : {}),
|
|
1412
|
-
replies: replySummaries
|
|
1413
|
-
};
|
|
1414
|
-
});
|
|
1415
|
-
}
|
|
1416
|
-
export async function readDxcompleteTicket(db, input, actor) {
|
|
1417
|
-
const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
|
|
1418
|
-
const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
|
|
1419
|
-
if (!existing) {
|
|
1420
|
-
throw new Error(`DX Complete Ticket not found: ${input.id}`);
|
|
1421
|
-
}
|
|
1422
|
-
const now = new Date().toISOString();
|
|
1423
|
-
const entries = normalizeTicketEntries(existing.fields.entries);
|
|
1424
|
-
let changed = false;
|
|
1425
|
-
const nextEntries = entries.map((entry) => {
|
|
1426
|
-
const shouldMark = entry.direction === "dxcomplete_reply" &&
|
|
1427
|
-
entry.addressedToActorId === actor.actorId &&
|
|
1428
|
-
!entry.readAt;
|
|
1429
|
-
if (!shouldMark) {
|
|
1430
|
-
return entry;
|
|
1431
|
-
}
|
|
1432
|
-
changed = true;
|
|
1433
|
-
return {
|
|
1434
|
-
...entry,
|
|
1435
|
-
readAt: now
|
|
1436
|
-
};
|
|
1437
|
-
});
|
|
1438
|
-
if (!changed) {
|
|
1439
|
-
return existing;
|
|
1440
|
-
}
|
|
1441
|
-
await collection.updateOne(ticketOwnerFilter(input.id, actor), {
|
|
1442
|
-
$set: {
|
|
1443
|
-
"fields.entries": nextEntries,
|
|
1444
|
-
updatedAt: now,
|
|
1445
|
-
updatedBy: actor.actorId
|
|
1446
|
-
}
|
|
1447
|
-
});
|
|
1448
|
-
return getDxcompleteTicket(db, input.id, actor);
|
|
1449
|
-
}
|
|
1450
|
-
export async function archiveDxcompleteTicket(db, input, actor) {
|
|
1451
|
-
const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
|
|
1452
|
-
const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
|
|
1453
|
-
if (!existing) {
|
|
1454
|
-
throw new Error(`DX Complete Ticket not found: ${input.id}`);
|
|
1455
|
-
}
|
|
1456
|
-
if (existing.archivedAt) {
|
|
1457
|
-
return existing;
|
|
1458
|
-
}
|
|
1459
|
-
const now = new Date().toISOString();
|
|
1460
|
-
await collection.updateOne(ticketOwnerFilter(input.id, actor), {
|
|
1461
|
-
$set: {
|
|
1462
|
-
archivedAt: now,
|
|
1463
|
-
updatedAt: now,
|
|
1464
|
-
updatedBy: actor.actorId
|
|
1465
|
-
}
|
|
1466
|
-
});
|
|
1467
|
-
return getDxcompleteTicket(db, input.id, actor);
|
|
1468
|
-
}
|
|
1469
|
-
export async function updateRecord(db, input, actorId) {
|
|
1470
|
-
const collection = db.collection(input.recordType);
|
|
1471
|
-
const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
|
|
1472
|
-
const existing = await collection.findOne(recordFilter);
|
|
1473
|
-
if (!existing) {
|
|
1474
|
-
throw new Error(`Record not found: ${input.recordType}/${input.id}`);
|
|
1475
|
-
}
|
|
1476
|
-
const now = new Date().toISOString();
|
|
1477
|
-
const set = {
|
|
1478
|
-
updatedAt: now,
|
|
1479
|
-
updatedBy: actorId
|
|
1480
|
-
};
|
|
1481
|
-
const unset = {};
|
|
1482
|
-
const versioned = recordTypeSupportsVersionHistory(input.recordType);
|
|
1483
|
-
if (input.title !== undefined) {
|
|
1484
|
-
set.title = input.title;
|
|
1485
|
-
}
|
|
1486
|
-
if (input.summary !== undefined) {
|
|
1487
|
-
set.summary = input.summary;
|
|
1488
|
-
}
|
|
1489
|
-
for (const [key, value] of Object.entries(input.fields ?? {})) {
|
|
1490
|
-
assertFieldName(key);
|
|
1491
|
-
assertNotReservedRelationshipField(input.recordType, key);
|
|
1492
|
-
if (input.allowManagedFields) {
|
|
1493
|
-
assertNotReviewNotesField(input.recordType, key);
|
|
1494
|
-
assertNotVersionHistoryField(input.recordType, key);
|
|
1495
|
-
}
|
|
1496
|
-
else {
|
|
1497
|
-
assertNotManagedField(input.recordType, key);
|
|
1498
|
-
assertNotVersionedTypedField(input.recordType, key);
|
|
1499
|
-
}
|
|
1500
|
-
set[`fields.${key}`] = value;
|
|
1501
|
-
}
|
|
1502
|
-
for (const key of input.unsetFields ?? []) {
|
|
1503
|
-
assertFieldName(key);
|
|
1504
|
-
if (input.allowManagedFields) {
|
|
1505
|
-
assertNotReviewNotesField(input.recordType, key);
|
|
1506
|
-
assertNotVersionHistoryField(input.recordType, key);
|
|
1507
|
-
}
|
|
1508
|
-
else {
|
|
1509
|
-
assertNotManagedField(input.recordType, key);
|
|
1510
|
-
assertNotVersionedTypedField(input.recordType, key);
|
|
1511
|
-
}
|
|
1512
|
-
unset[`fields.${key}`] = "";
|
|
1513
|
-
}
|
|
1514
|
-
if (versioned) {
|
|
1515
|
-
const previousSnapshot = createRecordVersionSnapshot(existing);
|
|
1516
|
-
const nextSnapshot = createRecordVersionSnapshot(applyRecordUpdate(existing, input));
|
|
1517
|
-
const changedFields = listSnapshotChanges(previousSnapshot, nextSnapshot);
|
|
1518
|
-
const existingVersionHistory = normalizeVersionHistory(existing.fields.versionHistory);
|
|
1519
|
-
if (changedFields.length === 0) {
|
|
1520
|
-
return withDerivedRecordFields(db, existing);
|
|
1521
|
-
}
|
|
1522
|
-
set["fields.versionHistory"] = [
|
|
1523
|
-
...existingVersionHistory,
|
|
1524
|
-
createVersionHistoryEntry({
|
|
1525
|
-
existingVersionHistory,
|
|
1526
|
-
previousSnapshot,
|
|
1527
|
-
nextSnapshot,
|
|
1528
|
-
changedFields,
|
|
1529
|
-
actorId,
|
|
1530
|
-
createdAt: now,
|
|
1531
|
-
revisionNote: input.revisionNote
|
|
1532
|
-
})
|
|
1533
|
-
];
|
|
1534
|
-
}
|
|
1535
|
-
const update = Object.keys(unset).length > 0 ? { $set: set, $unset: unset } : { $set: set };
|
|
1536
|
-
await collection.updateOne(recordFilter, update);
|
|
1537
|
-
const updated = await collection.findOne(recordFilter);
|
|
1538
|
-
if (!updated) {
|
|
1539
|
-
throw new Error(`Updated record not found: ${input.recordType}/${input.id}`);
|
|
1540
|
-
}
|
|
1541
|
-
return withDerivedRecordFields(db, updated);
|
|
1542
|
-
}
|
|
1543
|
-
function applyRecordUpdate(record, input) {
|
|
1544
|
-
const fields = { ...record.fields };
|
|
1545
|
-
for (const [key, value] of Object.entries(input.fields ?? {})) {
|
|
1546
|
-
fields[key] = value;
|
|
1547
|
-
}
|
|
1548
|
-
for (const key of input.unsetFields ?? []) {
|
|
1549
|
-
delete fields[key];
|
|
1550
|
-
}
|
|
1551
|
-
return {
|
|
1552
|
-
...record,
|
|
1553
|
-
...(input.title !== undefined ? { title: input.title } : {}),
|
|
1554
|
-
...(input.summary !== undefined ? { summary: input.summary } : {}),
|
|
1555
|
-
fields
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
function createRecordVersionSnapshot(record) {
|
|
1559
|
-
return {
|
|
1560
|
-
...(record.title !== undefined ? { title: record.title } : {}),
|
|
1561
|
-
...(record.summary !== undefined ? { summary: record.summary } : {}),
|
|
1562
|
-
fields: Object.fromEntries(Object.entries(record.fields)
|
|
1563
|
-
.filter(([key]) => key !== VERSION_HISTORY_FIELD && key !== "reviewNotes")
|
|
1564
|
-
.map(([key, value]) => [key, cloneSnapshotValue(value)]))
|
|
1565
|
-
};
|
|
1566
|
-
}
|
|
1567
|
-
function listSnapshotChanges(previousSnapshot, nextSnapshot) {
|
|
1568
|
-
const changedFields = [];
|
|
1569
|
-
if (!valuesEqual(previousSnapshot.title, nextSnapshot.title)) {
|
|
1570
|
-
changedFields.push("title");
|
|
1571
|
-
}
|
|
1572
|
-
if (!valuesEqual(previousSnapshot.summary, nextSnapshot.summary)) {
|
|
1573
|
-
changedFields.push("summary");
|
|
1574
|
-
}
|
|
1575
|
-
const fieldNames = new Set([
|
|
1576
|
-
...Object.keys(previousSnapshot.fields),
|
|
1577
|
-
...Object.keys(nextSnapshot.fields)
|
|
1578
|
-
]);
|
|
1579
|
-
for (const fieldName of [...fieldNames].sort()) {
|
|
1580
|
-
if (!valuesEqual(previousSnapshot.fields[fieldName], nextSnapshot.fields[fieldName])) {
|
|
1581
|
-
changedFields.push(`fields.${fieldName}`);
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
return changedFields;
|
|
1585
|
-
}
|
|
1586
|
-
function normalizeVersionHistory(value) {
|
|
1587
|
-
if (!Array.isArray(value)) {
|
|
1588
|
-
return [];
|
|
1589
|
-
}
|
|
1590
|
-
return value.filter(isVersionHistoryEntry);
|
|
1591
|
-
}
|
|
1592
|
-
function createVersionHistoryEntry(input) {
|
|
1593
|
-
const fromVersion = input.existingVersionHistory.reduce((currentVersion, entry) => Math.max(currentVersion, entry.toVersion), 1);
|
|
1594
|
-
return {
|
|
1595
|
-
id: randomUUID(),
|
|
1596
|
-
fromVersion,
|
|
1597
|
-
toVersion: fromVersion + 1,
|
|
1598
|
-
createdAt: input.createdAt,
|
|
1599
|
-
createdBy: input.actorId,
|
|
1600
|
-
changedFields: input.changedFields,
|
|
1601
|
-
previousSnapshot: input.previousSnapshot,
|
|
1602
|
-
nextSnapshot: input.nextSnapshot,
|
|
1603
|
-
...(input.revisionNote ? { revisionNote: input.revisionNote } : {})
|
|
1604
|
-
};
|
|
1605
|
-
}
|
|
1606
|
-
function isVersionHistoryEntry(value) {
|
|
1607
|
-
if (!value || typeof value !== "object") {
|
|
1608
|
-
return false;
|
|
1609
|
-
}
|
|
1610
|
-
const candidate = value;
|
|
1611
|
-
return (typeof candidate.id === "string" &&
|
|
1612
|
-
typeof candidate.fromVersion === "number" &&
|
|
1613
|
-
typeof candidate.toVersion === "number" &&
|
|
1614
|
-
typeof candidate.createdAt === "string" &&
|
|
1615
|
-
typeof candidate.createdBy === "string" &&
|
|
1616
|
-
Array.isArray(candidate.changedFields) &&
|
|
1617
|
-
typeof candidate.previousSnapshot === "object" &&
|
|
1618
|
-
typeof candidate.nextSnapshot === "object");
|
|
1619
|
-
}
|
|
1620
|
-
function cloneSnapshotValue(value) {
|
|
1621
|
-
if (Array.isArray(value)) {
|
|
1622
|
-
return value.map((entry) => cloneSnapshotValue(entry));
|
|
1623
|
-
}
|
|
1624
|
-
if (value && typeof value === "object") {
|
|
1625
|
-
return Object.fromEntries(Object.entries(value)
|
|
1626
|
-
.sort(([left], [right]) => left.localeCompare(right))
|
|
1627
|
-
.map(([key, entry]) => [key, cloneSnapshotValue(entry)]));
|
|
1628
|
-
}
|
|
1629
|
-
return value;
|
|
1630
|
-
}
|
|
1631
|
-
function valuesEqual(left, right) {
|
|
1632
|
-
return stableStringify(left) === stableStringify(right);
|
|
1633
|
-
}
|
|
1634
|
-
function stableStringify(value) {
|
|
1635
|
-
return JSON.stringify(cloneSnapshotValue(value));
|
|
1636
|
-
}
|
|
1637
|
-
export async function archiveRecord(db, input, actorId) {
|
|
1638
|
-
const collection = db.collection(input.recordType);
|
|
1639
|
-
const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
|
|
1640
|
-
const existing = await collection.findOne(recordFilter);
|
|
1641
|
-
if (!existing) {
|
|
1642
|
-
throw new Error(`Record not found: ${input.recordType}/${input.id}`);
|
|
1643
|
-
}
|
|
1644
|
-
if ((input.supersededByType && !input.supersededById) || (!input.supersededByType && input.supersededById)) {
|
|
1645
|
-
throw new Error("supersededByType and supersededById must be provided together.");
|
|
1646
|
-
}
|
|
1647
|
-
const supersedingRecord = input.supersededByType && input.supersededById
|
|
1648
|
-
? await getRecord(db, input.supersededByType, input.supersededById, {
|
|
1649
|
-
workspaceId: existing.workspaceId
|
|
1650
|
-
})
|
|
1651
|
-
: null;
|
|
1652
|
-
if (input.supersededByType && input.supersededById && !supersedingRecord) {
|
|
1653
|
-
throw new Error(`Superseding record not found: ${input.supersededByType}/${input.supersededById}`);
|
|
1654
|
-
}
|
|
1655
|
-
const now = new Date().toISOString();
|
|
1656
|
-
const links = [...existing.links];
|
|
1657
|
-
if (input.supersededByType && input.supersededById) {
|
|
1658
|
-
links.push({
|
|
1659
|
-
toType: input.supersededByType,
|
|
1660
|
-
toId: supersedingRecord?._id ?? input.supersededById,
|
|
1661
|
-
relationship: "superseded_by",
|
|
1662
|
-
createdAt: now,
|
|
1663
|
-
createdBy: actorId
|
|
1664
|
-
});
|
|
1665
|
-
}
|
|
1666
|
-
await collection.updateOne(recordFilter, {
|
|
1667
|
-
$set: {
|
|
1668
|
-
links,
|
|
1669
|
-
archivedAt: now,
|
|
1670
|
-
archivedBy: actorId,
|
|
1671
|
-
archiveReason: input.reason ?? "Archived",
|
|
1672
|
-
updatedAt: now,
|
|
1673
|
-
updatedBy: actorId
|
|
1674
|
-
}
|
|
1675
|
-
});
|
|
1676
|
-
const updated = await collection.findOne(recordFilter);
|
|
1677
|
-
if (!updated) {
|
|
1678
|
-
throw new Error(`Archived record not found: ${input.recordType}/${input.id}`);
|
|
1679
|
-
}
|
|
1680
|
-
return withDerivedRecordFields(db, updated);
|
|
1681
|
-
}
|
|
1682
|
-
export async function linkRecords(db, input, actorId) {
|
|
1683
|
-
const sourceCollection = db.collection(input.fromType);
|
|
1684
|
-
const source = await getRecord(db, input.fromType, input.fromId, {
|
|
1685
|
-
workspaceId: input.workspaceId
|
|
1686
|
-
});
|
|
1687
|
-
const target = await getRecord(db, input.toType, input.toId, {
|
|
1688
|
-
workspaceId: input.workspaceId
|
|
1689
|
-
});
|
|
1690
|
-
if (!source) {
|
|
1691
|
-
throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
|
|
1692
|
-
}
|
|
1693
|
-
if (!target) {
|
|
1694
|
-
throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
|
|
1695
|
-
}
|
|
1696
|
-
assertLinkWorkspaceBoundary(source, target);
|
|
1697
|
-
const now = new Date().toISOString();
|
|
1698
|
-
const link = {
|
|
1699
|
-
toType: input.toType,
|
|
1700
|
-
toId: target._id,
|
|
1701
|
-
relationship: input.relationship ?? "related_to",
|
|
1702
|
-
createdAt: now,
|
|
1703
|
-
createdBy: actorId
|
|
1704
|
-
};
|
|
1705
|
-
await sourceCollection.updateOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId), {
|
|
1706
|
-
$push: { links: link },
|
|
1707
|
-
$set: {
|
|
1708
|
-
updatedAt: now,
|
|
1709
|
-
updatedBy: actorId
|
|
1710
|
-
}
|
|
1711
|
-
});
|
|
1712
|
-
const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
|
|
1713
|
-
if (!updated) {
|
|
1714
|
-
throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
|
|
1715
|
-
}
|
|
1716
|
-
return withDerivedRecordFields(db, updated);
|
|
1717
|
-
}
|
|
1718
|
-
export async function unlinkRecords(db, input, actorId) {
|
|
1719
|
-
const sourceCollection = db.collection(input.fromType);
|
|
1720
|
-
const source = await getRecord(db, input.fromType, input.fromId, {
|
|
1721
|
-
workspaceId: input.workspaceId
|
|
1722
|
-
});
|
|
1723
|
-
const target = await getRecord(db, input.toType, input.toId, {
|
|
1724
|
-
workspaceId: input.workspaceId
|
|
1725
|
-
});
|
|
1726
|
-
if (!source) {
|
|
1727
|
-
throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
|
|
1728
|
-
}
|
|
1729
|
-
if (!target) {
|
|
1730
|
-
throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
|
|
1731
|
-
}
|
|
1732
|
-
assertLinkWorkspaceBoundary(source, target);
|
|
1733
|
-
const relationship = input.relationship ?? "related_to";
|
|
1734
|
-
const remainingLinks = source.links.filter((link) => !(link.toType === input.toType &&
|
|
1735
|
-
link.toId === target._id &&
|
|
1736
|
-
link.relationship === relationship));
|
|
1737
|
-
if (remainingLinks.length === source.links.length) {
|
|
1738
|
-
return source;
|
|
1739
|
-
}
|
|
1740
|
-
const now = new Date().toISOString();
|
|
1741
|
-
await sourceCollection.updateOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId), {
|
|
1742
|
-
$set: {
|
|
1743
|
-
links: remainingLinks,
|
|
1744
|
-
updatedAt: now,
|
|
1745
|
-
updatedBy: actorId
|
|
1746
|
-
}
|
|
1747
|
-
});
|
|
1748
|
-
const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
|
|
1749
|
-
if (!updated) {
|
|
1750
|
-
throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
|
|
1751
|
-
}
|
|
1752
|
-
return withDerivedRecordFields(db, updated);
|
|
1753
|
-
}
|
|
1754
|
-
function assertFieldName(key) {
|
|
1755
|
-
if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {
|
|
1756
|
-
throw new Error(`Invalid field name "${key}". Field updates only support top-level field names.`);
|
|
1757
|
-
}
|
|
1758
|
-
}
|
|
1759
|
-
function assertNoReservedRelationshipFields(recordType, fields) {
|
|
1760
|
-
for (const key of Object.keys(fields ?? {})) {
|
|
1761
|
-
assertNotReservedRelationshipField(recordType, key);
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1764
|
-
function assertNoReviewNotesField(recordType, fields) {
|
|
1765
|
-
for (const key of Object.keys(fields ?? {})) {
|
|
1766
|
-
assertNotReviewNotesField(recordType, key);
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
function assertNoManagedField(recordType, fields) {
|
|
1770
|
-
for (const key of Object.keys(fields ?? {})) {
|
|
1771
|
-
assertNotManagedField(recordType, key);
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
function assertNotReservedRelationshipField(recordType, key) {
|
|
1775
|
-
if (key === "workspaceId" && recordTypeRequiresWorkspace(recordType)) {
|
|
1776
|
-
throw new Error(`fields.${key} is reserved for the workspace boundary on ${recordType}. Use the top-level ${key} argument instead.`);
|
|
1777
|
-
}
|
|
1778
|
-
if (key === "initiativeId" && REMOVED_INITIATIVE_FIELD_RECORD_TYPES.includes(recordType)) {
|
|
1779
|
-
throw new Error(`fields.${key} belongs to the removed Initiative layer on ${recordType}. Records are scoped directly to workspace now.`);
|
|
1780
|
-
}
|
|
1781
|
-
if ((RESERVED_RELATIONSHIP_FIELDS[recordType] ?? []).includes(key)) {
|
|
1782
|
-
throw new Error(`fields.${key} is reserved for relationships on ${recordType}. Use the typed relationship argument or link_records instead.`);
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
function assertNotManagedField(recordType, key) {
|
|
1786
|
-
assertNotReviewNotesField(recordType, key);
|
|
1787
|
-
assertNotVersionHistoryField(recordType, key);
|
|
1788
|
-
assertNotChangeManagedField(recordType, key);
|
|
1789
|
-
assertNotCommitmentManagedField(recordType, key);
|
|
1790
|
-
assertNotDeferralManagedField(recordType, key);
|
|
1791
|
-
assertNotEstimateManagedField(recordType, key);
|
|
1792
|
-
assertNotBenefitsManagedField(recordType, key);
|
|
1793
|
-
assertNotEnvironmentManagedField(recordType, key);
|
|
1794
|
-
assertNotComponentManagedField(recordType, key);
|
|
1795
|
-
assertNotMaintenanceScheduleManagedField(recordType, key);
|
|
1796
|
-
assertNotSupportRequestLedgerManagedField(recordType, key);
|
|
1797
|
-
assertNotValueRealizationManagedField(recordType, key);
|
|
1798
|
-
assertNotDecisionLedgerManagedField(recordType, key);
|
|
1799
|
-
assertNotTaskLedgerManagedField(recordType, key);
|
|
1800
|
-
assertNotRiskLedgerManagedField(recordType, key);
|
|
1801
|
-
assertNotIncidentLedgerManagedField(recordType, key);
|
|
1802
|
-
assertNotProblemLedgerManagedField(recordType, key);
|
|
1803
|
-
assertNotDecisionInputManagedField(recordType, key);
|
|
1804
|
-
assertNotJournalEntryManagedField(recordType, key);
|
|
1805
|
-
}
|
|
1806
|
-
function assertNotVersionedTypedField(recordType, key) {
|
|
1807
|
-
if (!(VERSIONED_TYPED_FIELDS[recordType] ?? []).includes(key)) {
|
|
1808
|
-
return;
|
|
1809
|
-
}
|
|
1810
|
-
throw new Error(`fields.${key} is managed on ${recordType}. Use ${versionedUpdateToolName(recordType)} to change it.`);
|
|
1811
|
-
}
|
|
1812
|
-
function assertNotReviewNotesField(recordType, key) {
|
|
1813
|
-
if (key !== "reviewNotes" || !recordTypeSupportsReviewNotes(recordType)) {
|
|
1814
|
-
return;
|
|
1815
|
-
}
|
|
1816
|
-
throw new Error(`fields.reviewNotes is append-only on ${recordType}. Use append_review_note instead of setting or unsetting it directly.`);
|
|
1817
|
-
}
|
|
1818
|
-
function assertNotVersionHistoryField(recordType, key) {
|
|
1819
|
-
if (key !== VERSION_HISTORY_FIELD || !recordTypeSupportsVersionHistory(recordType)) {
|
|
1820
|
-
return;
|
|
1821
|
-
}
|
|
1822
|
-
throw new Error(`fields.versionHistory is append-only on ${recordType}. Current content changes record version history automatically.`);
|
|
1823
|
-
}
|
|
1824
|
-
function assertNotChangeManagedField(recordType, key) {
|
|
1825
|
-
if (recordType !== "changes" || !CHANGE_MANAGED_FIELDS.includes(key)) {
|
|
1826
|
-
return;
|
|
1827
|
-
}
|
|
1828
|
-
throw new Error(`fields.${key} is managed on changes. Use create_change for the baseline and append_change_event for event history or plan revisions.`);
|
|
1829
|
-
}
|
|
1830
|
-
function assertNotCommitmentManagedField(recordType, key) {
|
|
1831
|
-
if (recordType !== "commitments" || !COMMITMENT_MANAGED_FIELDS.includes(key)) {
|
|
1832
|
-
return;
|
|
1833
|
-
}
|
|
1834
|
-
throw new Error(`fields.${key} is managed on commitments. Use create_commitment instead of setting or unsetting it directly.`);
|
|
1835
|
-
}
|
|
1836
|
-
function assertNotDeferralManagedField(recordType, key) {
|
|
1837
|
-
if (recordType !== "deferrals" || !DEFERRAL_MANAGED_FIELDS.includes(key)) {
|
|
1838
|
-
return;
|
|
1839
|
-
}
|
|
1840
|
-
throw new Error(`fields.${key} is managed on deferrals. Use create_deferral for the baseline and append_deferral_event for condition history or resolution.`);
|
|
1841
|
-
}
|
|
1842
|
-
function assertNotEstimateManagedField(recordType, key) {
|
|
1843
|
-
if (recordType !== "estimates" || !ESTIMATE_MANAGED_FIELDS.includes(key)) {
|
|
1844
|
-
return;
|
|
1845
|
-
}
|
|
1846
|
-
throw new Error(`fields.${key} is managed on estimates. Use create_estimate or update_estimate instead of setting or unsetting it directly.`);
|
|
1847
|
-
}
|
|
1848
|
-
function assertNotBenefitsManagedField(recordType, key) {
|
|
1849
|
-
if (recordType !== "benefits" || !BENEFITS_MANAGED_FIELDS.includes(key)) {
|
|
1850
|
-
return;
|
|
1851
|
-
}
|
|
1852
|
-
throw new Error(`fields.${key} is managed on benefits. Use create_benefits or update_benefits instead of setting or unsetting it directly.`);
|
|
1853
|
-
}
|
|
1854
|
-
function assertNotEnvironmentManagedField(recordType, key) {
|
|
1855
|
-
if (recordType !== "environments" || !ENVIRONMENT_MANAGED_FIELDS.includes(key)) {
|
|
1856
|
-
return;
|
|
1857
|
-
}
|
|
1858
|
-
throw new Error(`fields.${key} is managed on environments. Use create_environment or update_environment instead of setting or unsetting it directly.`);
|
|
1859
|
-
}
|
|
1860
|
-
function assertNotComponentManagedField(recordType, key) {
|
|
1861
|
-
if (recordType !== "components" || !COMPONENT_MANAGED_FIELDS.includes(key)) {
|
|
1862
|
-
return;
|
|
1863
|
-
}
|
|
1864
|
-
throw new Error(`fields.${key} is managed on components. Use create_component or update_component instead of setting or unsetting it directly.`);
|
|
1865
|
-
}
|
|
1866
|
-
function assertNotMaintenanceScheduleManagedField(recordType, key) {
|
|
1867
|
-
if (recordType !== "maintenance_schedules" || !MAINTENANCE_SCHEDULE_MANAGED_FIELDS.includes(key)) {
|
|
1868
|
-
return;
|
|
1869
|
-
}
|
|
1870
|
-
throw new Error(`fields.${key} is managed on maintenance schedules. Use create_maintenance_schedule or update_maintenance_schedule instead of setting or unsetting it directly.`);
|
|
1871
|
-
}
|
|
1872
|
-
function assertNotSupportRequestLedgerManagedField(recordType, key) {
|
|
1873
|
-
if (recordType !== "support_requests" || !SUPPORT_REQUEST_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1874
|
-
return;
|
|
1875
|
-
}
|
|
1876
|
-
throw new Error(`fields.${key} is managed on support requests. Use create_support_request or append_support_request_entry instead of setting or unsetting it directly.`);
|
|
1877
|
-
}
|
|
1878
|
-
function assertNotValueRealizationManagedField(recordType, key) {
|
|
1879
|
-
if (recordType !== "value_realizations" || !VALUE_REALIZATION_MANAGED_FIELDS.includes(key)) {
|
|
1880
|
-
return;
|
|
1881
|
-
}
|
|
1882
|
-
throw new Error(`fields.${key} is managed on value realizations. Use create_value_realization or update_value_realization instead of setting or unsetting it directly.`);
|
|
1883
|
-
}
|
|
1884
|
-
function assertNotDecisionLedgerManagedField(recordType, key) {
|
|
1885
|
-
if (recordType !== "decisions" || !DECISION_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1886
|
-
return;
|
|
1887
|
-
}
|
|
1888
|
-
throw new Error(`fields.${key} is managed on decisions. Use create_decision or append_decision_entry instead of setting or unsetting it directly.`);
|
|
1889
|
-
}
|
|
1890
|
-
function assertNotTaskLedgerManagedField(recordType, key) {
|
|
1891
|
-
if (recordType !== "tasks" || !TASK_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1892
|
-
return;
|
|
1893
|
-
}
|
|
1894
|
-
throw new Error(`fields.${key} is managed on tasks. Use create_task or append_task_entry instead of setting or unsetting it directly.`);
|
|
1895
|
-
}
|
|
1896
|
-
function assertNotRiskLedgerManagedField(recordType, key) {
|
|
1897
|
-
if (recordType !== "risks" || !RISK_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1898
|
-
return;
|
|
1899
|
-
}
|
|
1900
|
-
throw new Error(`fields.${key} is managed on risks. Use create_risk or append_risk_entry instead of setting or unsetting it directly.`);
|
|
1901
|
-
}
|
|
1902
|
-
function assertNotIncidentLedgerManagedField(recordType, key) {
|
|
1903
|
-
if (recordType !== "incidents" || !INCIDENT_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1904
|
-
return;
|
|
1905
|
-
}
|
|
1906
|
-
throw new Error(`fields.${key} is managed on incidents. Use create_incident or append_incident_entry instead of setting or unsetting it directly.`);
|
|
1907
|
-
}
|
|
1908
|
-
function assertNotProblemLedgerManagedField(recordType, key) {
|
|
1909
|
-
if (recordType !== "problems" || !PROBLEM_LEDGER_MANAGED_FIELDS.includes(key)) {
|
|
1910
|
-
return;
|
|
1911
|
-
}
|
|
1912
|
-
throw new Error(`fields.${key} is managed on problems. Use create_problem or append_problem_entry instead of setting or unsetting it directly.`);
|
|
1913
|
-
}
|
|
1914
|
-
function assertNotDecisionInputManagedField(recordType, key) {
|
|
1915
|
-
if (recordType !== "decisions" || !DECISION_INPUT_MANAGED_FIELDS.includes(key)) {
|
|
1916
|
-
return;
|
|
1917
|
-
}
|
|
1918
|
-
throw new Error(`fields.${key} is managed on decisions. Use link_decision_input to record decision inputs.`);
|
|
1919
|
-
}
|
|
1920
|
-
function assertNotJournalEntryManagedField(recordType, key) {
|
|
1921
|
-
if (recordType !== "journal_entries" || !JOURNAL_ENTRY_MANAGED_FIELDS.includes(key)) {
|
|
1922
|
-
return;
|
|
1923
|
-
}
|
|
1924
|
-
throw new Error(`fields.${key} is managed on journal entries. Use append_journal_note or append_journal_summary instead of setting or unsetting it directly.`);
|
|
1925
|
-
}
|
|
1926
|
-
function linkMatches(link, relationship) {
|
|
1927
|
-
return !relationship || link.relationship === relationship;
|
|
1928
|
-
}
|
|
1929
|
-
function recordTypeSupportsReviewNotes(recordType) {
|
|
1930
|
-
return REVIEW_NOTE_RECORD_TYPES.includes(recordType);
|
|
1931
|
-
}
|
|
1932
|
-
function recordTypeSupportsVersionHistory(recordType) {
|
|
1933
|
-
return VERSIONED_RECORD_TYPES.includes(recordType);
|
|
1934
|
-
}
|
|
1935
|
-
function versionedUpdateToolName(recordType) {
|
|
1936
|
-
if (recordType === "environments") {
|
|
1937
|
-
return "update_environment";
|
|
1938
|
-
}
|
|
1939
|
-
if (recordType === "components") {
|
|
1940
|
-
return "update_component";
|
|
1941
|
-
}
|
|
1942
|
-
if (recordType === "maintenance_schedules") {
|
|
1943
|
-
return "update_maintenance_schedule";
|
|
1944
|
-
}
|
|
1945
|
-
if (recordType === "value_realizations") {
|
|
1946
|
-
return "update_value_realization";
|
|
1947
|
-
}
|
|
1948
|
-
if (recordType === "estimates") {
|
|
1949
|
-
return "update_estimate";
|
|
1950
|
-
}
|
|
1951
|
-
if (recordType === "benefits") {
|
|
1952
|
-
return "update_benefits";
|
|
1953
|
-
}
|
|
1954
|
-
if (recordType === "statements") {
|
|
1955
|
-
return "update_statement";
|
|
1956
|
-
}
|
|
1957
|
-
return recordType === "expectations" ? "update_expectation" : "update_requirement";
|
|
1958
|
-
}
|
|
1959
|
-
function isCurrentCollection(recordType) {
|
|
1960
|
-
return COLLECTION_NAMES.includes(recordType);
|
|
1961
|
-
}
|
|
1962
|
-
function recordTypeRequiresWorkspace(recordType) {
|
|
1963
|
-
return recordType !== "workspaces" && recordType !== DXCOMPLETE_TICKET_COLLECTION_NAME;
|
|
1964
|
-
}
|
|
1965
|
-
function readRequiredWorkspaceId(workspaceId, recordType) {
|
|
1966
|
-
const trimmed = workspaceId?.trim();
|
|
1967
|
-
if (!trimmed) {
|
|
1968
|
-
throw new Error(`${recordType} records require workspaceId.`);
|
|
1969
|
-
}
|
|
1970
|
-
return trimmed;
|
|
1971
|
-
}
|
|
1972
|
-
function workspaceIdForCreate(recordType, workspaceId) {
|
|
1973
|
-
if (!recordTypeRequiresWorkspace(recordType)) {
|
|
1974
|
-
if (workspaceId?.trim()) {
|
|
1975
|
-
throw new Error("Workspace records do not accept workspaceId.");
|
|
1976
|
-
}
|
|
1977
|
-
return undefined;
|
|
1978
|
-
}
|
|
1979
|
-
return readRequiredWorkspaceId(workspaceId, recordType);
|
|
1980
|
-
}
|
|
1981
|
-
async function allocateReadableId(db, recordType, workspaceId, actorId, now, session) {
|
|
1982
|
-
const scopedWorkspaceId = readRequiredWorkspaceId(workspaceId, recordType);
|
|
1983
|
-
const sequenceId = `${scopedWorkspaceId}:${recordType}`;
|
|
1984
|
-
const sequence = await db.collection(READABLE_ID_SEQUENCES_COLLECTION).findOneAndUpdate({ _id: sequenceId }, {
|
|
1985
|
-
$inc: { nextNumber: 1 },
|
|
1986
|
-
$set: {
|
|
1987
|
-
updatedAt: now,
|
|
1988
|
-
updatedBy: actorId
|
|
1989
|
-
},
|
|
1990
|
-
$setOnInsert: {
|
|
1991
|
-
_id: sequenceId,
|
|
1992
|
-
workspaceId: scopedWorkspaceId,
|
|
1993
|
-
recordType,
|
|
1994
|
-
createdAt: now,
|
|
1995
|
-
createdBy: actorId
|
|
1996
|
-
}
|
|
1997
|
-
}, {
|
|
1998
|
-
upsert: true,
|
|
1999
|
-
returnDocument: "after",
|
|
2000
|
-
session
|
|
2001
|
-
});
|
|
2002
|
-
if (!sequence || !Number.isInteger(sequence.nextNumber) || sequence.nextNumber < 1) {
|
|
2003
|
-
throw new Error(`Readable ID sequence was not allocated for ${recordType}.`);
|
|
2004
|
-
}
|
|
2005
|
-
return `${READABLE_ID_TYPE_CODES[recordType]}-${String(sequence.nextNumber).padStart(4, "0")}`;
|
|
2006
|
-
}
|
|
2007
|
-
function recordTypeSupportsReadableId(recordType) {
|
|
2008
|
-
return Object.hasOwn(READABLE_ID_TYPE_CODES, recordType);
|
|
2009
|
-
}
|
|
2010
|
-
function normalizeReadableId(value) {
|
|
2011
|
-
return value.trim().toUpperCase();
|
|
2012
|
-
}
|
|
2013
|
-
function recordIdentityFilter(recordType, id) {
|
|
2014
|
-
if (!recordTypeSupportsReadableId(recordType)) {
|
|
2015
|
-
return { _id: id };
|
|
2016
|
-
}
|
|
2017
|
-
return {
|
|
2018
|
-
$or: [
|
|
2019
|
-
{ _id: id },
|
|
2020
|
-
{ readableId: normalizeReadableId(id) }
|
|
2021
|
-
]
|
|
2022
|
-
};
|
|
2023
|
-
}
|
|
2024
|
-
function scopedRecordFilter(recordType, id, workspaceId) {
|
|
2025
|
-
const filter = recordIdentityFilter(recordType, id);
|
|
2026
|
-
if (recordTypeRequiresWorkspace(recordType)) {
|
|
2027
|
-
filter.workspaceId = readRequiredWorkspaceId(workspaceId, recordType);
|
|
2028
|
-
}
|
|
2029
|
-
return filter;
|
|
2030
|
-
}
|
|
2031
|
-
async function assertWorkspaceExists(db, workspaceId) {
|
|
2032
|
-
const workspace = await db.collection("workspaces").findOne({
|
|
2033
|
-
_id: workspaceId,
|
|
2034
|
-
archivedAt: { $exists: false }
|
|
2035
|
-
});
|
|
2036
|
-
if (!workspace) {
|
|
2037
|
-
throw new Error(`Workspace not found: workspaces/${workspaceId}`);
|
|
2038
|
-
}
|
|
2039
|
-
return workspace;
|
|
2040
|
-
}
|
|
2041
|
-
function recordBelongsToWorkspace(record, workspaceId) {
|
|
2042
|
-
return !workspaceId || record.recordType === "workspaces" || record.workspaceId === workspaceId;
|
|
2043
|
-
}
|
|
2044
|
-
function assertLinkWorkspaceBoundary(source, target) {
|
|
2045
|
-
if (!source.workspaceId || !target.workspaceId) {
|
|
2046
|
-
return;
|
|
2047
|
-
}
|
|
2048
|
-
if (source.workspaceId !== target.workspaceId) {
|
|
2049
|
-
throw new Error(`Cannot link records across workspaces: ${source.recordType}/${source._id} is in ${source.workspaceId}, while ${target.recordType}/${target._id} is in ${target.workspaceId}.`);
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
function ticketOwnerFilter(id, actor) {
|
|
2053
|
-
return {
|
|
2054
|
-
_id: id,
|
|
2055
|
-
"fields.ownerActorId": actor.actorId
|
|
2056
|
-
};
|
|
2057
|
-
}
|
|
2058
|
-
function normalizeTicketEntries(value) {
|
|
2059
|
-
if (!Array.isArray(value)) {
|
|
2060
|
-
return [];
|
|
2061
|
-
}
|
|
2062
|
-
return value.flatMap((entry, index) => normalizeTicketEntry(entry, index));
|
|
2063
|
-
}
|
|
2064
|
-
function normalizeTicketEntry(entry, index) {
|
|
2065
|
-
if (!entry || typeof entry !== "object") {
|
|
2066
|
-
return [];
|
|
2067
|
-
}
|
|
2068
|
-
const candidate = entry;
|
|
2069
|
-
const body = typeof candidate.body === "string" ? candidate.body : "";
|
|
2070
|
-
if (!body) {
|
|
2071
|
-
return [];
|
|
2072
|
-
}
|
|
2073
|
-
const createdAt = typeof candidate.createdAt === "string" ? candidate.createdAt : new Date(0).toISOString();
|
|
2074
|
-
const createdBy = typeof candidate.createdBy === "string" ? candidate.createdBy : RUNTIME_ACTOR_ID;
|
|
2075
|
-
const direction = candidate.direction === "dxcomplete_reply" || candidate.direction === "submitter_entry"
|
|
2076
|
-
? candidate.direction
|
|
2077
|
-
: "submitter_entry";
|
|
2078
|
-
const normalized = {
|
|
2079
|
-
id: typeof candidate.id === "string" && candidate.id ? candidate.id : `legacy-entry-${index + 1}`,
|
|
2080
|
-
body,
|
|
2081
|
-
createdAt,
|
|
2082
|
-
createdBy,
|
|
2083
|
-
direction
|
|
2084
|
-
};
|
|
2085
|
-
if (typeof candidate.addressedToActorId === "string" && candidate.addressedToActorId) {
|
|
2086
|
-
normalized.addressedToActorId = candidate.addressedToActorId;
|
|
2087
|
-
}
|
|
2088
|
-
if (typeof candidate.readAt === "string" && candidate.readAt) {
|
|
2089
|
-
normalized.readAt = candidate.readAt;
|
|
2090
|
-
}
|
|
2091
|
-
return [normalized];
|
|
2092
|
-
}
|