@openinc/parse-server-opendash 4.6.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/features/schema/helper/migrationMode.js +2 -0
  2. package/dist/hooks/Service_Schedule.js +7 -0
  3. package/dist/hooks/Service_Schedule_Template.js +5 -0
  4. package/dist/scripts/migration/lib/articleMeta.d.ts +34 -10
  5. package/dist/scripts/migration/lib/articleMeta.js +58 -11
  6. package/dist/scripts/migration/lib/cadence.d.ts +75 -0
  7. package/dist/scripts/migration/lib/cadence.js +246 -0
  8. package/dist/scripts/migration/lib/env.d.ts +5 -0
  9. package/dist/scripts/migration/lib/env.js +23 -0
  10. package/dist/scripts/migration/lib/equipmentMeta.d.ts +65 -0
  11. package/dist/scripts/migration/lib/equipmentMeta.js +155 -0
  12. package/dist/scripts/migration/lib/schedule.d.ts +306 -0
  13. package/dist/scripts/migration/lib/schedule.js +613 -0
  14. package/dist/scripts/migration/passes/03-equipment.js +181 -4
  15. package/dist/scripts/migration/passes/05-articles.d.ts +12 -15
  16. package/dist/scripts/migration/passes/05-articles.js +83 -33
  17. package/dist/scripts/migration/passes/13-schedule-templates.d.ts +15 -0
  18. package/dist/scripts/migration/passes/13-schedule-templates.js +163 -0
  19. package/dist/scripts/migration/passes/14-schedules.d.ts +30 -0
  20. package/dist/scripts/migration/passes/14-schedules.js +239 -0
  21. package/dist/scripts/migration/passes/15-executions.d.ts +34 -0
  22. package/dist/scripts/migration/passes/15-executions.js +244 -0
  23. package/dist/scripts/migration/passes/16-schedule-meta.d.ts +23 -0
  24. package/dist/scripts/migration/passes/16-schedule-meta.js +308 -0
  25. package/dist/scripts/migration/passes/17-schedule-assets.d.ts +30 -0
  26. package/dist/scripts/migration/passes/17-schedule-assets.js +240 -0
  27. package/dist/scripts/migration/passes/18-calendar-links.d.ts +25 -0
  28. package/dist/scripts/migration/passes/18-calendar-links.js +132 -0
  29. package/dist/scripts/migration/passes/19-schedule-history.d.ts +18 -0
  30. package/dist/scripts/migration/passes/19-schedule-history.js +186 -0
  31. package/dist/scripts/migration/run.js +20 -9
  32. package/dist/scripts/migration/verify.js +450 -12
  33. package/dist/scripts/seed-v1-testdata.d.ts +2 -0
  34. package/dist/scripts/seed-v1-testdata.js +449 -10
  35. package/dist/types/Service_Schedule.d.ts +3 -0
  36. package/dist/types/Service_Schedule.js +6 -0
  37. package/dist/types/Service_Schedule_Execution.d.ts +1 -1
  38. package/package.json +1 -1
  39. package/schema/Service_Schedule.json +4 -0
@@ -0,0 +1,613 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PlanIndex = exports.StepSource = exports.materialStepId = exports.templateStepId = exports.planStepId = exports.executionMediaContext = exports.LEGACY_STEP_META_PREFIX = exports.STEP_META_PREFIX = exports.legacyStepMetaContext = exports.stepMetaContext = void 0;
7
+ exports.stepIdOfContext = stepIdOfContext;
8
+ exports.machineDocsContext = machineDocsContext;
9
+ exports.mintId = mintId;
10
+ exports.executionStepIds = executionStepIds;
11
+ exports.byV1Order = byV1Order;
12
+ exports.isStaticField = isStaticField;
13
+ exports.withStaticFields = withStaticFields;
14
+ exports.toV2Step = toV2Step;
15
+ exports.readV1Access = readV1Access;
16
+ exports.assignedRoleNames = assignedRoleNames;
17
+ exports.privateAcl = privateAcl;
18
+ exports.addAssignments = addAssignments;
19
+ exports.serviceProviders = serviceProviders;
20
+ exports.resolveRoles = resolveRoles;
21
+ exports.effectiveNotifyBeforeDue = effectiveNotifyBeforeDue;
22
+ exports.leadTimeMs = leadTimeMs;
23
+ exports.v1Recipients = v1Recipients;
24
+ exports.notificationRules = notificationRules;
25
+ exports.classifyExecution = classifyExecution;
26
+ exports.executionStepsByExecution = executionStepsByExecution;
27
+ const node_crypto_1 = require("node:crypto");
28
+ const node_1 = __importDefault(require("parse/node"));
29
+ const index_js_1 = require("../../../types/index.js");
30
+ const acl_js_1 = require("./acl.js");
31
+ const cadence_js_1 = require("./cadence.js");
32
+ const latest_js_1 = require("./latest.js");
33
+ const pass_js_1 = require("./pass.js");
34
+ const ptr_js_1 = require("./ptr.js");
35
+ /**
36
+ * What the schedule passes (13–19) share.
37
+ *
38
+ * Several passes have to agree on the same derived facts — which v2 step id a
39
+ * v1 step became, which plan a v1 execution belongs to, whether a v1 run
40
+ * counts as done. Each of those is decided **here, once**, the way
41
+ * `lib/material.ts` is shared by the ticket fold and replay: two passes that
42
+ * derived a step id differently would write captured values nobody can find.
43
+ */
44
+ // ── Contexts the v2 frontend reads ─────────────────────────────────────────
45
+ /**
46
+ * Where a step's capture fields (`OD3_Meta_Config`) and captured values
47
+ * (`OD3_Meta_Entry`) live. Mirrors `stepMetaContext` in openservice-core
48
+ * (`models/embedded/ScheduleStep.ts`).
49
+ */
50
+ const stepMetaContext = (stepId) => [
51
+ "openservice",
52
+ "schedule",
53
+ "step",
54
+ stepId,
55
+ ];
56
+ exports.stepMetaContext = stepMetaContext;
57
+ /** v1's own step meta context (written since 2026-02), keyed by v1 step id. */
58
+ const legacyStepMetaContext = (v1StepId) => [
59
+ "schedule",
60
+ "step",
61
+ "meta",
62
+ v1StepId,
63
+ ];
64
+ exports.legacyStepMetaContext = legacyStepMetaContext;
65
+ /**
66
+ * What every stringified context of the kind starts with, for `startsWith`
67
+ * queries: `["openservice","schedule","step",` — the context minus its id.
68
+ */
69
+ const prefixOf = (context) => (0, ptr_js_1.contextToString)(context).replace(/""]$/, "");
70
+ exports.STEP_META_PREFIX = prefixOf((0, exports.stepMetaContext)(""));
71
+ exports.LEGACY_STEP_META_PREFIX = prefixOf((0, exports.legacyStepMetaContext)(""));
72
+ /** The step id inside a stringified step meta context, v1 or v2. */
73
+ function stepIdOfContext(context) {
74
+ try {
75
+ const parts = JSON.parse(context);
76
+ return typeof parts[3] === "string" ? parts[3] : undefined;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ /**
83
+ * Photos and files of one execution. Mirrors `executionMediaContext` in
84
+ * openservice-schedule (`features/schedules/utils/documents.ts`) — a plain
85
+ * string, not a stringified array like the ticket context.
86
+ */
87
+ const executionMediaContext = (executionId) => `od3-service-execution-${executionId}`;
88
+ exports.executionMediaContext = executionMediaContext;
89
+ /**
90
+ * Machine documents: shared by every plan of one equipment, per plan when it
91
+ * has none. Mirrors `machineDocsContext` in the same file.
92
+ */
93
+ function machineDocsContext(options) {
94
+ return options.equipmentId
95
+ ? `od3-service-equipment-${options.equipmentId}`
96
+ : `od3-service-schedule-${options.scheduleId}`;
97
+ }
98
+ // ── Step identity ──────────────────────────────────────────────────────────
99
+ /**
100
+ * A deterministic, UUID-shaped id.
101
+ *
102
+ * v2 step ids are opaque UUIDs, and several things hang off one: the step's
103
+ * `Meta_Config`, every execution's step result, every captured `Meta_Entry`.
104
+ * A random id would make a re-run mint a second set and orphan the first, so
105
+ * the id is a hash of what the step *is* — which is also what lets pass 15
106
+ * and pass 16 arrive at the same id without talking to each other.
107
+ */
108
+ function mintId(...parts) {
109
+ const hash = (0, node_crypto_1.createHash)("sha1")
110
+ .update(["openservice-v1-migration", ...parts].join("\u0000"))
111
+ .digest();
112
+ const bytes = Buffer.from(hash.subarray(0, 16));
113
+ bytes[6] = (bytes[6] & 0x0f) | 0x50; // version 5 (name-based, SHA-1)
114
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
115
+ const hex = bytes.toString("hex");
116
+ return [
117
+ hex.slice(0, 8),
118
+ hex.slice(8, 12),
119
+ hex.slice(12, 16),
120
+ hex.slice(16, 20),
121
+ hex.slice(20),
122
+ ].join("-");
123
+ }
124
+ /**
125
+ * The id a v1 step gets inside one v2 plan.
126
+ *
127
+ * Minted **per plan**, not per v1 step: v1 step rows are shared — a template's
128
+ * steps are added to every plan created from it — while a v2 step belongs to
129
+ * one plan, and its capture fields are keyed by its id. Two plans sharing one
130
+ * id would share one `Meta_Config`, and editing the fields of one would edit
131
+ * the other.
132
+ */
133
+ const planStepId = (v1PlanId, v1StepId) => mintId(index_js_1.Maintenance_Schedule.className, v1PlanId, v1StepId);
134
+ exports.planStepId = planStepId;
135
+ /** The same for a template's steps. */
136
+ const templateStepId = (v1TemplateId, v1StepId) => mintId(index_js_1.Maintenance_Schedule_Template.className, v1TemplateId, v1StepId);
137
+ exports.templateStepId = templateStepId;
138
+ /** The synthetic step an execution's material hangs off — see pass 15. */
139
+ const materialStepId = (v1ExecutionId) => mintId(index_js_1.Maintenance_Schedule_Execution.className, v1ExecutionId, "material");
140
+ exports.materialStepId = materialStepId;
141
+ /**
142
+ * The v2 step id of each step of one v1 execution, keyed by execution-step id.
143
+ *
144
+ * A step that points at its plan step (`step`, written since 2026-02) takes
145
+ * that plan step's id, so the protocol, the plan and the captured values all
146
+ * agree on it. Older rows have no such pointer and get an id of their own —
147
+ * matching them to a plan step by title would be a guess, and a wrong guess
148
+ * files a measurement under the wrong step.
149
+ */
150
+ function executionStepIds(steps, v1PlanId) {
151
+ const ids = new Map();
152
+ const used = new Set();
153
+ for (const step of steps) {
154
+ if (!step.id)
155
+ continue;
156
+ const own = mintId(index_js_1.Maintenance_Schedule_Execution_Step.className, step.id);
157
+ const v1StepId = (0, pass_js_1.refId)(step.get("step"));
158
+ let id = v1PlanId && v1StepId ? (0, exports.planStepId)(v1PlanId, v1StepId) : own;
159
+ // One step twice in the same run: the second keeps its own id, because a
160
+ // step id has to be unique within the execution.
161
+ if (used.has(id))
162
+ id = own;
163
+ used.add(id);
164
+ ids.set(step.id, id);
165
+ }
166
+ return ids;
167
+ }
168
+ /**
169
+ * v1 order: by `order`, then by age.
170
+ *
171
+ * `order` is global across the whole v1 class rather than per plan, and rows
172
+ * from before 2025-08 all carry 0 — so it sorts, but only the position in the
173
+ * result means anything. v2 renumbers from 0.
174
+ */
175
+ function byV1Order(rows) {
176
+ return [...rows].sort((a, b) => {
177
+ const byOrder = Number(a.get("order") ?? 0) -
178
+ Number(b.get("order") ?? 0);
179
+ if (byOrder !== 0)
180
+ return byOrder;
181
+ return (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0);
182
+ });
183
+ }
184
+ /**
185
+ * The step rows of v1 plans and templates, read once per owner.
186
+ *
187
+ * A relation cannot be batch-loaded, so every owner costs a query — and the
188
+ * same template's steps are asked for once per plan made from it.
189
+ */
190
+ class StepSource {
191
+ batchSize;
192
+ cache = new Map();
193
+ constructor(batchSize) {
194
+ this.batchSize = batchSize;
195
+ }
196
+ /** The rows in an owner's `steps` relation, in v1 order. */
197
+ async of(owner) {
198
+ const key = `${owner.className}|${owner.id}`;
199
+ const cached = this.cache.get(key);
200
+ if (cached)
201
+ return cached;
202
+ const rows = byV1Order((await (0, latest_js_1.relationObjects)(owner, "steps", this.batchSize)));
203
+ this.cache.set(key, rows);
204
+ return rows;
205
+ }
206
+ /**
207
+ * The steps a v1 execution of this plan was built from: the plan's own, or
208
+ * — when it has none — its template's
209
+ * (`hooks/Maintenance_Schedule_Execution.ts`). That is what the plan meant
210
+ * to a technician, so it is what the v2 plan carries.
211
+ */
212
+ async ofPlan(plan) {
213
+ const own = await this.of(plan);
214
+ const template = plan.get("template");
215
+ if (own.length > 0 || !template?.id)
216
+ return { rows: own, inherited: false };
217
+ return { rows: await this.of(template), inherited: true };
218
+ }
219
+ }
220
+ exports.StepSource = StepSource;
221
+ /**
222
+ * Whether a v1 step field is an era-A *static* field.
223
+ *
224
+ * `Schedule_Step.fields` meant three things over time:
225
+ * - **A** (≈ 2024-12 – 2025-08): `{ metafield: {label, …}, value }` — a value an
226
+ * admin set on the step, shown to the technician, never captured.
227
+ * - **B** (2025-08 – 2026-02): a meta field *config* (`{ name, type, … }`) whose
228
+ * values were captured per execution into `Execution_Step.meta`.
229
+ * - **C** (since 2026-02): not written; the config is an `OD3_Meta_Config`.
230
+ */
231
+ function isStaticField(field) {
232
+ return !!field && typeof field === "object" && "metafield" in field;
233
+ }
234
+ /** An era-A value as text: a string, a list, or `{ value, label }`. */
235
+ function valueText(value) {
236
+ if (value === undefined || value === null)
237
+ return "";
238
+ if (typeof value === "string")
239
+ return value.trim();
240
+ if (typeof value === "number" || typeof value === "boolean") {
241
+ return String(value);
242
+ }
243
+ if (Array.isArray(value)) {
244
+ return value.map(valueText).filter(Boolean).join(", ");
245
+ }
246
+ if (typeof value === "object") {
247
+ const labelled = value;
248
+ return valueText(labelled.label) || valueText(labelled.value);
249
+ }
250
+ return "";
251
+ }
252
+ /**
253
+ * A step description with its era-A static fields appended.
254
+ *
255
+ * v2 has no per-step properties an admin fills in — only capture fields, which
256
+ * are the technician's. What an era-A field said ("PSA: Handschuhe") is an
257
+ * instruction, and the description is where v2 keeps instructions, so it moves
258
+ * there rather than being dropped.
259
+ */
260
+ function withStaticFields(description, fields) {
261
+ const lines = (Array.isArray(fields) ? fields : [])
262
+ .filter(isStaticField)
263
+ .map((field) => {
264
+ const label = valueText(field.metafield?.label);
265
+ const text = valueText(field.value);
266
+ return label && text ? `${label}: ${text}` : "";
267
+ })
268
+ .filter(Boolean);
269
+ const own = typeof description === "string" ? description.trim() : "";
270
+ const text = [own, lines.join("\n")].filter(Boolean).join("\n\n");
271
+ return text || undefined;
272
+ }
273
+ /** A v1 step (or execution step) as a v2 step. */
274
+ function toV2Step(row, id, order, required) {
275
+ const title = String(row.get("title") ?? "").trim();
276
+ const description = withStaticFields(row.get("description"), row.get("fields"));
277
+ return {
278
+ id,
279
+ order,
280
+ title: title || `Schritt ${order + 1}`,
281
+ ...(description ? { description } : {}),
282
+ required,
283
+ };
284
+ }
285
+ function readV1Access(object, tenantId) {
286
+ const acl = object.getACL();
287
+ const grants = (acl?.toJSON() ?? {});
288
+ const always = new Set([
289
+ "od-admin",
290
+ ...(tenantId ? [`od-tenant-admin-${tenantId}`] : []),
291
+ ]);
292
+ const access = {
293
+ readerUserIds: [],
294
+ readerRoleNames: [],
295
+ demotedWriterIds: [],
296
+ unrestricted: !acl,
297
+ };
298
+ for (const [key, grant] of Object.entries(grants)) {
299
+ if (key === "*") {
300
+ if (grant.read === true)
301
+ access.unrestricted = true;
302
+ }
303
+ else if (key.startsWith("role:")) {
304
+ const name = key.slice("role:".length);
305
+ if (grant.read && !always.has(name))
306
+ access.readerRoleNames.push(name);
307
+ }
308
+ else if (grant.write && !access.creatorId) {
309
+ access.creatorId = key;
310
+ }
311
+ else if (grant.read || grant.write) {
312
+ access.readerUserIds.push(key);
313
+ if (grant.write)
314
+ access.demotedWriterIds.push(key);
315
+ }
316
+ }
317
+ return access;
318
+ }
319
+ /**
320
+ * The roles a migrated plan or template is assigned to: the ones its ACL
321
+ * named, plus the tenant's user role when everybody could read it.
322
+ */
323
+ function assignedRoleNames(access, tenantId) {
324
+ const tenantUsers = `od-tenant-user-${tenantId}`;
325
+ return access.unrestricted && !access.readerRoleNames.includes(tenantUsers)
326
+ ? [...access.readerRoleNames, tenantUsers]
327
+ : access.readerRoleNames;
328
+ }
329
+ /**
330
+ * The ACL of a private v2 plan or template.
331
+ *
332
+ * Mirrors `syncAssignmentAcl` (`features/openservice/serviceSchedules/
333
+ * assignmentAcl.ts`) exactly: administrators, the creator read+write, the
334
+ * assigned roles and users read. That hook derives the ACL from the
335
+ * assignments on every save — so an ACL written here that the assignments do
336
+ * not explain would be silently narrowed by the first edit in v2. Anything
337
+ * v1 granted therefore has to arrive as an *assignment*, and this is the ACL
338
+ * those assignments imply. Tenant users get no read: plans are private.
339
+ */
340
+ function privateAcl(options) {
341
+ const acl = new node_1.default.ACL();
342
+ acl.setRoleReadAccess("od-admin", true);
343
+ acl.setRoleWriteAccess("od-admin", true);
344
+ acl.setRoleReadAccess(`od-tenant-admin-${options.tenantId}`, true);
345
+ acl.setRoleWriteAccess(`od-tenant-admin-${options.tenantId}`, true);
346
+ if (options.creatorId) {
347
+ acl.setReadAccess(options.creatorId, true);
348
+ acl.setWriteAccess(options.creatorId, true);
349
+ }
350
+ for (const name of options.roleNames)
351
+ acl.setRoleReadAccess(name, true);
352
+ for (const userId of options.userIds)
353
+ acl.setReadAccess(userId, true);
354
+ return acl;
355
+ }
356
+ /**
357
+ * Write the assignment relations of a plan or template that already exists.
358
+ *
359
+ * Relations cannot be part of a create body — Parse rejects an array where
360
+ * the schema says Relation — so they follow as an update. In migration mode
361
+ * the afterSave that would re-derive the ACL from them is off, which is why
362
+ * the create already carried the ACL they imply ({@link privateAcl}).
363
+ */
364
+ async function addAssignments(className, objectId, assignments) {
365
+ const userIds = assignments.userIds ?? [];
366
+ if (assignments.roleIds.length === 0 && userIds.length === 0)
367
+ return;
368
+ const target = new node_1.default.Object(className);
369
+ target.id = objectId;
370
+ const pointer = (cls, id) => {
371
+ const object = new node_1.default.Object(cls);
372
+ object.id = id;
373
+ return object;
374
+ };
375
+ if (assignments.roleIds.length) {
376
+ target
377
+ .relation("assignedRoles")
378
+ .add(assignments.roleIds.map((id) => pointer("_Role", id)));
379
+ }
380
+ if (userIds.length) {
381
+ target
382
+ .relation("assignedUsers")
383
+ .add(userIds.map((id) => pointer("_User", id)));
384
+ }
385
+ await target.save(null, acl_js_1.MIGRATION_SAVE);
386
+ }
387
+ /**
388
+ * v1 plan contacts as v2 service providers.
389
+ *
390
+ * `notify: false` on purpose: v1 only *listed* contacts on a plan and never
391
+ * mailed them — the scheduler notified users. Sending external service
392
+ * providers mail from the first v2 tick onwards would be new behaviour
393
+ * nobody switched on; the flag is the provider's consent, and the plan editor
394
+ * turns it on per provider. `notifyOffsetDays` is the editor's default.
395
+ */
396
+ function serviceProviders(contactIds) {
397
+ return contactIds.map((contactId) => ({
398
+ contactId,
399
+ notify: false,
400
+ notifyOffsetDays: 7,
401
+ }));
402
+ }
403
+ /**
404
+ * Role names → ids for the roles a v1 ACL named.
405
+ *
406
+ * ACLs grant by name, assignment relations by id. A name with no role behind
407
+ * it any more is returned separately: it cannot become an assignment, and a
408
+ * grant without one would not survive the first save in v2.
409
+ */
410
+ function resolveRoles(names, roleIdByName) {
411
+ const ids = [];
412
+ const known = [];
413
+ const unknown = [];
414
+ for (const name of names) {
415
+ const id = roleIdByName.get(name);
416
+ if (id) {
417
+ ids.push(id);
418
+ known.push(name);
419
+ }
420
+ else
421
+ unknown.push(name);
422
+ }
423
+ return { ids, names: known, unknown };
424
+ }
425
+ // ── Notifications ──────────────────────────────────────────────────────────
426
+ /** dayjs' duration constants — v1 converted with `dayjs.duration(value, unit)`. */
427
+ const UNIT_MS = {
428
+ millisecond: 1,
429
+ second: 1_000,
430
+ minute: 60_000,
431
+ hour: 3_600_000,
432
+ day: 86_400_000,
433
+ week: 604_800_000,
434
+ month: 2_592_000_000, // 30 days
435
+ year: 31_536_000_000, // 365 days
436
+ };
437
+ /**
438
+ * The plan's `notifyBeforeDue`, or its template's.
439
+ *
440
+ * `||`, not `??`, because that is what the v1 scheduler did: any object —
441
+ * including the `{ value: 0, unit: "milliseconds" }` the admin form writes on
442
+ * mount — hides the template's value.
443
+ */
444
+ function effectiveNotifyBeforeDue(plan, template) {
445
+ return (plan.get("notifyBeforeDue") ||
446
+ template?.get("notifyBeforeDue"));
447
+ }
448
+ /** v1's lead time in milliseconds, or undefined for "no reminder". */
449
+ function leadTimeMs(notifyBeforeDue) {
450
+ let ms;
451
+ if (typeof notifyBeforeDue === "number")
452
+ ms = notifyBeforeDue;
453
+ else if (notifyBeforeDue && typeof notifyBeforeDue === "object") {
454
+ const { value, unit } = notifyBeforeDue;
455
+ const key = String(unit ?? "")
456
+ .toLowerCase()
457
+ .replace(/s$/, "");
458
+ if (typeof value === "number" && UNIT_MS[key])
459
+ ms = value * UNIT_MS[key];
460
+ }
461
+ return ms && Number.isFinite(ms) && ms > 0 ? ms : undefined;
462
+ }
463
+ /**
464
+ * Who v1 notified about a plan, in v2 terms.
465
+ *
466
+ * v1 notified exactly the users the plan's ACL let read it, directly or
467
+ * through a role (`getRecipientsFromACL` in the scheduler) — and nobody for a
468
+ * plan without an ACL. The users go into `userIds`. The roles are the plan's
469
+ * assignments now, so the rules notify its assigned roles — except on an
470
+ * unrestricted plan, whose tenant-user assignment is there for visibility
471
+ * only: notifying it would mail the whole tenant about a plan v1 mailed
472
+ * nobody about. Its explicit roles, if any, are named instead.
473
+ *
474
+ * Members of `od-admin` read every plan and were therefore notified of every
475
+ * plan; that is deliberately not carried over.
476
+ */
477
+ function v1Recipients(access, explicitRoleIds) {
478
+ const userIds = [
479
+ ...(access.creatorId ? [access.creatorId] : []),
480
+ ...access.readerUserIds,
481
+ ];
482
+ return {
483
+ assignedRoles: !access.unrestricted,
484
+ ...(userIds.length ? { userIds } : {}),
485
+ ...(access.unrestricted && explicitRoleIds.length
486
+ ? { roleIds: explicitRoleIds }
487
+ : {}),
488
+ };
489
+ }
490
+ /**
491
+ * v1's notifications as v2 rules.
492
+ *
493
+ * v1 notified at every occurrence (the scheduler's `on` job, for every enabled
494
+ * plan) and, with a `notifyBeforeDue`, once more ahead of it. Both become a
495
+ * rule, with the recipients of {@link v1Recipients}.
496
+ *
497
+ * Ids are minted, not random: they are the dedup key of a sent message.
498
+ */
499
+ function notificationRules(key, notifyBeforeDue, who) {
500
+ const recipients = { ...who, serviceProviders: true };
501
+ const rules = [
502
+ { id: mintId(key, "due"), trigger: "due", ...recipients },
503
+ ];
504
+ const ms = leadTimeMs(notifyBeforeDue);
505
+ if (ms === undefined)
506
+ return { rules };
507
+ const days = ms / UNIT_MS.day;
508
+ if (days < 1) {
509
+ return {
510
+ rules,
511
+ deviation: `reminder ${Math.round(ms / UNIT_MS.minute)} min before due — v2 ` +
512
+ `counts reminders in days, so only the due notification remains`,
513
+ };
514
+ }
515
+ const offsetDays = Math.round(days);
516
+ rules.unshift({
517
+ id: mintId(key, "before"),
518
+ trigger: "before",
519
+ offsetDays,
520
+ ...recipients,
521
+ });
522
+ return {
523
+ rules,
524
+ ...(offsetDays !== days
525
+ ? {
526
+ deviation: `reminder of ${days.toFixed(2)} days rounded to ${offsetDays}`,
527
+ }
528
+ : {}),
529
+ };
530
+ }
531
+ /**
532
+ * Whether a v1 execution is a protocol, a run still in progress, or a run
533
+ * somebody gave up on.
534
+ *
535
+ * v2 has no status column — `completedAt` is the whole state. An abandoned
536
+ * run therefore has no faithful v2 form: without `completedAt` it would come
537
+ * back as a resumable run ("Durchführung starten" picks up any open one), and
538
+ * with it, it would claim maintenance nobody did. It is not migrated.
539
+ *
540
+ * `status` alone cannot tell, because v1 rewrites it at every server start:
541
+ * every execution with a `finishedAt` becomes `completed`, including the
542
+ * `terminated` ones a re-run closed. For a plan's execution the runner only
543
+ * ever completed one with all steps done, so a finished plan run with an open
544
+ * step is one of those terminated runs. A direct maintenance may legitimately
545
+ * finish with skipped steps, so the inference is not made there.
546
+ */
547
+ function classifyExecution(execution, steps, forPlan) {
548
+ const status = execution.get("status");
549
+ if (status === "terminated" || status === "failed") {
550
+ return { fate: "abandoned", reason: `status "${status}"` };
551
+ }
552
+ const finishedAt = (0, cadence_js_1.asDate)(execution.get("finishedAt"));
553
+ if (!finishedAt)
554
+ return { fate: "open" };
555
+ if (forPlan && steps.some((step) => step.get("done") !== true)) {
556
+ return {
557
+ fate: "abandoned",
558
+ reason: "finished with open steps (a terminated re-run)",
559
+ };
560
+ }
561
+ return { fate: "completed", completedAt: finishedAt };
562
+ }
563
+ /** The execution-step rows of every execution, in v1 order. */
564
+ async function executionStepsByExecution(config) {
565
+ const grouped = await (0, latest_js_1.groupByTicket)(() => (0, pass_js_1.scopeToTenant)(new node_1.default.Query(index_js_1.Maintenance_Schedule_Execution_Step), config.tenantId), config.batchSize, "scheduleexecution");
566
+ for (const [id, rows] of grouped)
567
+ grouped.set(id, byV1Order(rows));
568
+ return grouped;
569
+ }
570
+ /**
571
+ * Which v1 plan an execution belongs to.
572
+ *
573
+ * Executions from before 2025-08 name their template and source but no plan;
574
+ * v1 links them at every boot to the plan with that template and source
575
+ * (`features/openservice/schedules/reassignScheduleExecutions.ts`). The
576
+ * migration applies the same rule rather than turning them into direct
577
+ * maintenances.
578
+ */
579
+ class PlanIndex {
580
+ byTemplateAndSource = new Map();
581
+ plans = new Map();
582
+ static async load(config) {
583
+ const index = new PlanIndex();
584
+ for (const plan of await (0, pass_js_1.all)(() => (0, pass_js_1.scopeToTenant)(new node_1.default.Query(index_js_1.Maintenance_Schedule), config.tenantId), config.batchSize)) {
585
+ if (!plan.id)
586
+ continue;
587
+ index.plans.set(plan.id, plan);
588
+ const templateId = (0, pass_js_1.refId)(plan.get("template"));
589
+ const sourceId = (0, pass_js_1.refId)(plan.get("source"));
590
+ const key = `${templateId}|${sourceId}`;
591
+ // Oldest first (`all` pages by createdAt), so the oldest plan wins.
592
+ if (templateId && sourceId && !index.byTemplateAndSource.has(key)) {
593
+ index.byTemplateAndSource.set(key, plan.id);
594
+ }
595
+ }
596
+ return index;
597
+ }
598
+ plan(v1PlanId) {
599
+ return this.plans.get(v1PlanId);
600
+ }
601
+ /** The v1 plan id an execution belongs to, if any. */
602
+ resolve(execution) {
603
+ const direct = (0, pass_js_1.refId)(execution.get("schedule"));
604
+ if (direct)
605
+ return direct;
606
+ const templateId = (0, pass_js_1.refId)(execution.get("origin"));
607
+ const sourceId = (0, pass_js_1.refId)(execution.get("source"));
608
+ if (!templateId || !sourceId)
609
+ return undefined;
610
+ return this.byTemplateAndSource.get(`${templateId}|${sourceId}`);
611
+ }
612
+ }
613
+ exports.PlanIndex = PlanIndex;