@openinc/parse-server-opendash 4.7.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 (33) 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/cadence.d.ts +75 -0
  5. package/dist/scripts/migration/lib/cadence.js +246 -0
  6. package/dist/scripts/migration/lib/env.d.ts +5 -0
  7. package/dist/scripts/migration/lib/env.js +23 -0
  8. package/dist/scripts/migration/lib/schedule.d.ts +306 -0
  9. package/dist/scripts/migration/lib/schedule.js +613 -0
  10. package/dist/scripts/migration/passes/03-equipment.js +11 -4
  11. package/dist/scripts/migration/passes/13-schedule-templates.d.ts +15 -0
  12. package/dist/scripts/migration/passes/13-schedule-templates.js +163 -0
  13. package/dist/scripts/migration/passes/14-schedules.d.ts +30 -0
  14. package/dist/scripts/migration/passes/14-schedules.js +239 -0
  15. package/dist/scripts/migration/passes/15-executions.d.ts +34 -0
  16. package/dist/scripts/migration/passes/15-executions.js +244 -0
  17. package/dist/scripts/migration/passes/16-schedule-meta.d.ts +23 -0
  18. package/dist/scripts/migration/passes/16-schedule-meta.js +308 -0
  19. package/dist/scripts/migration/passes/17-schedule-assets.d.ts +30 -0
  20. package/dist/scripts/migration/passes/17-schedule-assets.js +240 -0
  21. package/dist/scripts/migration/passes/18-calendar-links.d.ts +25 -0
  22. package/dist/scripts/migration/passes/18-calendar-links.js +132 -0
  23. package/dist/scripts/migration/passes/19-schedule-history.d.ts +18 -0
  24. package/dist/scripts/migration/passes/19-schedule-history.js +186 -0
  25. package/dist/scripts/migration/run.js +20 -9
  26. package/dist/scripts/migration/verify.js +294 -11
  27. package/dist/scripts/seed-v1-testdata.d.ts +2 -0
  28. package/dist/scripts/seed-v1-testdata.js +392 -6
  29. package/dist/types/Service_Schedule.d.ts +3 -0
  30. package/dist/types/Service_Schedule.js +6 -0
  31. package/dist/types/Service_Schedule_Execution.d.ts +1 -1
  32. package/package.json +1 -1
  33. package/schema/Service_Schedule.json +4 -0
@@ -0,0 +1,240 @@
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.pass17 = void 0;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ const acl_js_1 = require("../lib/acl.js");
10
+ const latest_js_1 = require("../lib/latest.js");
11
+ const pass_js_1 = require("../lib/pass.js");
12
+ const ptr_js_1 = require("../lib/ptr.js");
13
+ const schedule_js_1 = require("../lib/schedule.js");
14
+ /** v1's asset contexts (`plugins/openservice/.../parse-config.tsx`). */
15
+ const PLAN_PREFIX = "schedule-media-";
16
+ const STEP_PREFIX = "schedule-step-media-";
17
+ const EXECUTION_PREFIX = "schedule-execution-";
18
+ /**
19
+ * Pass 17 — files of plans, steps and executions → the v2 asset contexts.
20
+ *
21
+ * v2 keeps two kinds of file for maintenance, both in `OD3_Assets`:
22
+ *
23
+ * - **machine documents** — manuals, instructions — under the *machine*
24
+ * (`od3-service-equipment-<id>`, per plan when it has no machine). v1's plan
25
+ * documents (`schedule-media-<plan>`) and step attachments
26
+ * (`schedule-step-media-<step>`, and the older `Schedule_Step.media`
27
+ * relation) are instructions, so they go there. v2 has no per-step files.
28
+ * - **execution media** — photos of the work — under the execution
29
+ * (`od3-service-execution-<id>`). v1's `schedule-execution-<id>` and the
30
+ * older `Execution.media` relation.
31
+ *
32
+ * Existing asset rows are re-addressed in place, like pass 11 does for
33
+ * tickets: the file stays where it is, only `context` changes. A
34
+ * `Maintenance_Media` file has no asset row yet and gets one.
35
+ *
36
+ * Not read: `Execution_Step.media`. v1 filled it only by copying the step's
37
+ * own media when a run started (`hooks/Maintenance_Schedule_Execution.ts`),
38
+ * so it holds the step's instructions a second time, not photos.
39
+ *
40
+ * A v1 step can belong to several plans on different machines, but an asset
41
+ * row has one context. It goes to the first plan's machine; the others are
42
+ * named in a warning. Copying the row would not help: deleting an asset
43
+ * destroys its file (`hooks/Assets.ts`), so two rows on one file means one
44
+ * deletion breaks the other.
45
+ */
46
+ exports.pass17 = {
47
+ id: "17",
48
+ title: "schedule-assets",
49
+ needs: ["03", "14", "15"],
50
+ async run({ config, map, report, entry }) {
51
+ const { batchSize } = config;
52
+ // ── targets: plans, and the plans each step belongs to ────────────────
53
+ const plans = await (0, pass_js_1.all)(() => (0, pass_js_1.scopeToTenant)(new node_1.default.Query(index_js_1.Maintenance_Schedule), config.tenantId), batchSize);
54
+ const planTargets = new Map();
55
+ const stepTargets = new Map();
56
+ const stepRows = new Map();
57
+ const steps = new schedule_js_1.StepSource(batchSize);
58
+ for (const plan of plans) {
59
+ const planId = plan.id
60
+ ? map.get(index_js_1.Maintenance_Schedule.className, plan.id)
61
+ : undefined;
62
+ if (!planId)
63
+ continue;
64
+ const v1SourceId = (0, pass_js_1.refId)(plan.get("source"));
65
+ const tenantId = (0, pass_js_1.refId)(plan.get("tenant"));
66
+ const target = {
67
+ context: (0, schedule_js_1.machineDocsContext)({
68
+ equipmentId: v1SourceId
69
+ ? map.get(index_js_1.Source.className, v1SourceId)
70
+ : undefined,
71
+ scheduleId: planId,
72
+ }),
73
+ tenantId,
74
+ creatorId: (0, schedule_js_1.readV1Access)(plan, tenantId).creatorId,
75
+ };
76
+ planTargets.set(plan.id, target);
77
+ for (const row of (await steps.ofPlan(plan)).rows) {
78
+ stepRows.set(row.id, row);
79
+ const list = stepTargets.get(row.id) ?? [];
80
+ if (!list.some((t) => t.context === target.context))
81
+ list.push(target);
82
+ stepTargets.set(row.id, list);
83
+ }
84
+ }
85
+ const executionTarget = (v1ExecutionId) => {
86
+ const id = map.get(index_js_1.Maintenance_Schedule_Execution.className, v1ExecutionId);
87
+ return id ? (0, schedule_js_1.executionMediaContext)(id) : undefined;
88
+ };
89
+ // Steps whose files had more than one machine to go to — noted only when a
90
+ // file actually moves, not for every shared step.
91
+ const shared = new Set();
92
+ const stepTarget = (v1StepId) => stepTargets.get(v1StepId)?.[0];
93
+ const noteShared = (v1StepId) => {
94
+ if ((stepTargets.get(v1StepId)?.length ?? 0) > 1)
95
+ shared.add(v1StepId);
96
+ };
97
+ // ── 1. asset rows on v1 contexts: re-address ──────────────────────────
98
+ // Read completely before writing: rewriting `context` takes a row out of
99
+ // the `startsWith` result, and paging a shrinking result skips rows (see
100
+ // pass 11).
101
+ const assets = await (0, pass_js_1.all)(() => new node_1.default.Query(index_js_1.Assets).startsWith("context", "schedule-"), batchSize);
102
+ let unmapped = 0;
103
+ let rewritten = 0;
104
+ for (const asset of assets) {
105
+ const context = asset.get("context") ?? "";
106
+ let next;
107
+ if (context.startsWith(STEP_PREFIX)) {
108
+ const v1StepId = context.slice(STEP_PREFIX.length);
109
+ next = stepTarget(v1StepId)?.context;
110
+ if (next)
111
+ noteShared(v1StepId);
112
+ }
113
+ else if (context.startsWith(PLAN_PREFIX)) {
114
+ next = planTargets.get(context.slice(PLAN_PREFIX.length))?.context;
115
+ }
116
+ else if (context.startsWith(EXECUTION_PREFIX)) {
117
+ next = executionTarget(context.slice(EXECUTION_PREFIX.length));
118
+ }
119
+ else {
120
+ continue; // some other feature's "schedule-…" context
121
+ }
122
+ if (!next) {
123
+ // Template-only steps, plans or executions outside --tenant, or an
124
+ // execution pass 15 did not migrate (abandoned).
125
+ unmapped += 1;
126
+ entry.skipped++;
127
+ continue;
128
+ }
129
+ if (config.dryRun) {
130
+ entry.updated++;
131
+ rewritten += 1;
132
+ continue;
133
+ }
134
+ asset.set("context", next);
135
+ try {
136
+ // Only the context changes; file, owner, ACL and timestamps stay.
137
+ await asset.save(null, acl_js_1.MIGRATION_SAVE);
138
+ entry.updated++;
139
+ rewritten += 1;
140
+ }
141
+ catch (error) {
142
+ report.error(entry, `asset ${asset.id} context rewrite failed: ${error.message}`);
143
+ }
144
+ }
145
+ // ── 2. Maintenance_Media files: new asset rows ────────────────────────
146
+ let created = 0;
147
+ // One asset per file, also in a dry run (where the map records nothing).
148
+ const handled = new Set();
149
+ const createAsset = async (media, context, owner, label) => {
150
+ if (!media.id || handled.has(media.id))
151
+ return;
152
+ handled.add(media.id);
153
+ if (map.get(index_js_1.Maintenance_Media.className, media.id))
154
+ return;
155
+ const file = media.get("media");
156
+ if (!file?.url()) {
157
+ report.warn(entry, `${label}: media ${media.id} has no file — skipped`);
158
+ return;
159
+ }
160
+ if (!owner.userId) {
161
+ // `OD3_Assets.user` is required.
162
+ report.warn(entry, `${label}: media ${media.id} has nobody to own it (Assets.user is ` +
163
+ `required) — left in OD3_Maintenance_Media`);
164
+ return;
165
+ }
166
+ const tenantId = owner.tenantId ?? (0, pass_js_1.refId)(media.get("tenant"));
167
+ if (config.dryRun) {
168
+ entry.created++;
169
+ created += 1;
170
+ return;
171
+ }
172
+ const asset = new index_js_1.Assets();
173
+ asset.set("context", context);
174
+ asset.set("description", media.get("description") || file.name() || "Datei");
175
+ asset.set("file", file);
176
+ asset.set("user", (0, ptr_js_1.userPtr)(owner.userId));
177
+ if (tenantId)
178
+ asset.set("tenant", (0, ptr_js_1.tenantPtr)(tenantId));
179
+ asset.setACL((0, acl_js_1.migrationAcl)({
180
+ tenantId,
181
+ userId: owner.userId,
182
+ allowTenantUserWrite: true,
183
+ }));
184
+ try {
185
+ const id = await (0, acl_js_1.saveMigrated)(config, asset, {
186
+ className: index_js_1.Assets.className,
187
+ isNew: true,
188
+ createdAt: media.createdAt,
189
+ updatedAt: media.updatedAt,
190
+ });
191
+ await map.record(index_js_1.Maintenance_Media.className, media.id, index_js_1.Assets.className, id);
192
+ entry.created++;
193
+ created += 1;
194
+ }
195
+ catch (error) {
196
+ report.error(entry, `${label}: media ${media.id} failed: ${error.message}`);
197
+ }
198
+ };
199
+ // Step attachments, onto the machine of the (first) plan with the step.
200
+ for (const [v1StepId, row] of stepRows) {
201
+ const target = stepTarget(v1StepId);
202
+ if (!target)
203
+ continue;
204
+ const files = (await (0, latest_js_1.relationObjects)(row, "media", batchSize));
205
+ if (files.length)
206
+ noteShared(v1StepId);
207
+ for (const media of files) {
208
+ await createAsset(media, target.context, { tenantId: target.tenantId, userId: target.creatorId }, `step ${v1StepId}`);
209
+ }
210
+ }
211
+ // Execution photos. The scheduler's `convertMediaToAssets` job moved most
212
+ // of these already and emptied the relation; this is what it left.
213
+ for await (const page of (0, pass_js_1.pages)(() => (0, pass_js_1.scopeToTenant)(new node_1.default.Query(index_js_1.Maintenance_Schedule_Execution), config.tenantId), batchSize)) {
214
+ for (const execution of page) {
215
+ const context = execution.id
216
+ ? executionTarget(execution.id)
217
+ : undefined;
218
+ if (!context)
219
+ continue;
220
+ for (const media of (await (0, latest_js_1.relationObjects)(execution, "media", batchSize))) {
221
+ await createAsset(media, context, {
222
+ tenantId: (0, pass_js_1.refId)(execution.get("tenant")),
223
+ userId: (0, pass_js_1.refId)(execution.get("user")),
224
+ }, `execution ${execution.id}`);
225
+ }
226
+ }
227
+ }
228
+ report.info(entry, `${rewritten} asset(s) re-addressed, ${created} Maintenance_Media file(s) ` +
229
+ `became assets`);
230
+ if (unmapped > 0) {
231
+ report.info(entry, `${unmapped} asset(s) on a v1 schedule context with no migrated owner ` +
232
+ `(template-only steps, other tenants, abandoned runs) — left as they are`);
233
+ }
234
+ if (shared.size > 0) {
235
+ report.warn(entry, `${shared.size} step(s) with files belong to plans on different ` +
236
+ `machines — their files went to the first plan's machine only: ` +
237
+ `${[...shared].slice(0, 10).join(", ")}`);
238
+ }
239
+ },
240
+ };
@@ -0,0 +1,25 @@
1
+ import { type Pass } from "../lib/pass.js";
2
+ /**
3
+ * Pass 18 — hand each v1 plan's Outlook event over to its v2 plan.
4
+ *
5
+ * Both generations remember "this plan is that calendar event" as a
6
+ * `Meta_Entry` — v1 under `["schedule","sync","microsoft"]` for
7
+ * `OD3_Maintenance_Schedule`, v2 under `["service","schedule","sync",
8
+ * "microsoft"]` for `OD3_Service_Schedule`. One Outlook connection serves
9
+ * both, and the event itself stays where it is.
10
+ *
11
+ * Without this pass a migrated plan has no event as far as v2 knows, so the
12
+ * first edit in v2 (`syncPlanToCalendar`) creates a *second* event next to
13
+ * the one v1 made, and the v2 poller, once re-enabled, imports v1's event as
14
+ * a third plan. Carrying the id, the `changeKey` and the event snapshot over
15
+ * makes the next v2 save update the existing event instead.
16
+ *
17
+ * An event already linked to a *different* v2 plan (the v2 poller imported
18
+ * it before this ran) is not relinked: that is a duplicate plan for a human
19
+ * to merge, and it is reported.
20
+ *
21
+ * Must run after the plans exist. Needs `OD_MIGRATION_MODE` on the server
22
+ * like every pass — here also because it keeps the plan afterSave from
23
+ * pushing migrated plans to Outlook before their link arrives.
24
+ */
25
+ export declare const pass18: Pass;
@@ -0,0 +1,132 @@
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.pass18 = void 0;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const calendarMetaHelper_js_1 = require("../../../features/openservice/schedules/calendarSync/calendarMetaHelper.js");
9
+ const serviceCalendarMeta_js_1 = require("../../../features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.js");
10
+ const index_js_1 = require("../../../types/index.js");
11
+ const acl_js_1 = require("../lib/acl.js");
12
+ const pass_js_1 = require("../lib/pass.js");
13
+ const ptr_js_1 = require("../lib/ptr.js");
14
+ /**
15
+ * Pass 18 — hand each v1 plan's Outlook event over to its v2 plan.
16
+ *
17
+ * Both generations remember "this plan is that calendar event" as a
18
+ * `Meta_Entry` — v1 under `["schedule","sync","microsoft"]` for
19
+ * `OD3_Maintenance_Schedule`, v2 under `["service","schedule","sync",
20
+ * "microsoft"]` for `OD3_Service_Schedule`. One Outlook connection serves
21
+ * both, and the event itself stays where it is.
22
+ *
23
+ * Without this pass a migrated plan has no event as far as v2 knows, so the
24
+ * first edit in v2 (`syncPlanToCalendar`) creates a *second* event next to
25
+ * the one v1 made, and the v2 poller, once re-enabled, imports v1's event as
26
+ * a third plan. Carrying the id, the `changeKey` and the event snapshot over
27
+ * makes the next v2 save update the existing event instead.
28
+ *
29
+ * An event already linked to a *different* v2 plan (the v2 poller imported
30
+ * it before this ran) is not relinked: that is a duplicate plan for a human
31
+ * to merge, and it is reported.
32
+ *
33
+ * Must run after the plans exist. Needs `OD_MIGRATION_MODE` on the server
34
+ * like every pass — here also because it keeps the plan afterSave from
35
+ * pushing migrated plans to Outlook before their link arrives.
36
+ */
37
+ exports.pass18 = {
38
+ id: "18",
39
+ title: "calendar-links",
40
+ needs: ["14"],
41
+ async run({ config, map, report, entry }) {
42
+ const byPlan = new Map();
43
+ const planByEvent = new Map();
44
+ for await (const page of (0, pass_js_1.pages)(() => new node_1.default.Query(index_js_1.Meta_Entry)
45
+ .equalTo("context", serviceCalendarMeta_js_1.SERVICE_CALENDAR_SYNC_CONTEXT)
46
+ .equalTo("entryClassName", index_js_1.Service_Schedule.className), config.batchSize)) {
47
+ for (const row of page) {
48
+ const planId = row.get("entryObjectId");
49
+ const eventId = row.get("values")
50
+ ?.microsoftCalendarEventId;
51
+ if (planId)
52
+ byPlan.set(planId, row);
53
+ if (planId && eventId)
54
+ planByEvent.set(eventId, planId);
55
+ }
56
+ }
57
+ let linked = 0;
58
+ let conflicts = 0;
59
+ for await (const page of (0, pass_js_1.pages)(() => new node_1.default.Query(index_js_1.Meta_Entry)
60
+ .equalTo("context", calendarMetaHelper_js_1.CALENDAR_SYNC_CONTEXT)
61
+ .equalTo("entryClassName", index_js_1.Maintenance_Schedule.className), config.batchSize)) {
62
+ for (const legacy of page) {
63
+ const v1PlanId = legacy.get("entryObjectId");
64
+ const values = legacy.get("values");
65
+ const eventId = values?.microsoftCalendarEventId;
66
+ if (!v1PlanId || !eventId)
67
+ continue;
68
+ // Outside --tenant, or a plan pass 14 could not write.
69
+ const planId = map.get(index_js_1.Maintenance_Schedule.className, v1PlanId);
70
+ if (!planId) {
71
+ entry.skipped++;
72
+ continue;
73
+ }
74
+ const owner = planByEvent.get(eventId);
75
+ if (owner && owner !== planId) {
76
+ conflicts += 1;
77
+ report.warn(entry, `event ${eventId} of v1 plan ${v1PlanId} is already linked to v2 plan ` +
78
+ `${owner} (imported by the v2 poller?) — not relinked; plan ` +
79
+ `${planId} is a duplicate to merge by hand`);
80
+ entry.skipped++;
81
+ continue;
82
+ }
83
+ const existing = byPlan.get(planId);
84
+ const tenantId = (0, pass_js_1.refId)(legacy.get("tenant"));
85
+ const target = existing ?? new index_js_1.Meta_Entry();
86
+ target.set("context", serviceCalendarMeta_js_1.SERVICE_CALENDAR_SYNC_CONTEXT);
87
+ target.set("entryClassName", index_js_1.Service_Schedule.className);
88
+ target.set("entryObjectId", planId);
89
+ target.set("config", {});
90
+ target.set("values", {
91
+ microsoftCalendarEventId: eventId,
92
+ ...(values?.microsoftCalendarChangeKey
93
+ ? { microsoftCalendarChangeKey: values.microsoftCalendarChangeKey }
94
+ : {}),
95
+ // The snapshot is what keeps a v2 write from turning someone's
96
+ // 9:00 appointment into an all-day block.
97
+ ...(values?.microsoftCalendarEvent
98
+ ? { microsoftCalendarEvent: values.microsoftCalendarEvent }
99
+ : {}),
100
+ });
101
+ if (tenantId)
102
+ target.set("tenant", (0, ptr_js_1.tenantPtr)(tenantId));
103
+ if (!existing) {
104
+ target.setACL((0, acl_js_1.migrationAcl)({ tenantId, allowTenantUserWrite: true }));
105
+ }
106
+ if (config.dryRun) {
107
+ existing ? entry.updated++ : entry.created++;
108
+ linked += 1;
109
+ continue;
110
+ }
111
+ try {
112
+ await (0, acl_js_1.saveMigrated)(config, target, {
113
+ className: index_js_1.Meta_Entry.className,
114
+ isNew: !existing,
115
+ createdAt: legacy.createdAt,
116
+ updatedAt: legacy.updatedAt,
117
+ });
118
+ existing ? entry.updated++ : entry.created++;
119
+ planByEvent.set(eventId, planId);
120
+ linked += 1;
121
+ }
122
+ catch (error) {
123
+ report.error(entry, `calendar link of v1 plan ${v1PlanId} failed: ${error.message}`);
124
+ }
125
+ }
126
+ }
127
+ if (linked > 0 || conflicts > 0) {
128
+ report.info(entry, `${linked} Outlook event(s) now belong to their v2 plan` +
129
+ (conflicts ? `, ${conflicts} conflict(s) — see warnings` : ""));
130
+ }
131
+ },
132
+ };
@@ -0,0 +1,18 @@
1
+ import { type Pass } from "../lib/pass.js";
2
+ /**
3
+ * Pass 19 — history entries for migrated plans and executions.
4
+ *
5
+ * v2 tells a machine's story from `OD3_Changelog`: the machine book's
6
+ * "Verlauf" and the plan's history tab list what happened by reading entries
7
+ * for `OD3_Service_Schedule` and `OD3_Service_Schedule_Execution`, matching
8
+ * executions to their plan through the `schedule` pointer in the snapshot.
9
+ * Every migration write skips the changelog hook (`skipChangelog`), so
10
+ * without this pass ten years of maintenance would be missing from that view
11
+ * while the calendar and the KPIs show it.
12
+ *
13
+ * v1 kept no edit history for plans or protocols — only its own changelog
14
+ * under the v1 class names, which cannot be re-pointed (MIGRATION_PLAN §6) —
15
+ * so there is nothing to replay: a plan gets its `create`, an execution its
16
+ * start and sign-off, at their historical timestamps and by their v1 authors.
17
+ */
18
+ export declare const pass19: Pass;
@@ -0,0 +1,186 @@
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.pass19 = void 0;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ const acl_js_1 = require("../lib/acl.js");
10
+ const env_js_1 = require("../lib/env.js");
11
+ const pass_js_1 = require("../lib/pass.js");
12
+ const ptr_js_1 = require("../lib/ptr.js");
13
+ /** Fields a v2 execution only gets when it is signed off. */
14
+ const SIGN_OFF_FIELDS = ["completedAt", "performedBy", "signature"];
15
+ /**
16
+ * A v2 row as the changelog hook would have recorded it.
17
+ *
18
+ * `toJSON()` is already the wire form the diff view reads — pointers as
19
+ * `{__type:"Pointer"}`, dates as `{__type:"Date"}` — and carries the ACL,
20
+ * which the entry has to mirror. Relations are left out: the hook never
21
+ * records them either.
22
+ */
23
+ function snapshotOf(row) {
24
+ const json = row.toJSON();
25
+ delete json.className;
26
+ delete json.createdAt;
27
+ delete json.updatedAt;
28
+ for (const [key, value] of Object.entries(json)) {
29
+ if (value?.__type === "Relation") {
30
+ delete json[key];
31
+ }
32
+ }
33
+ return json;
34
+ }
35
+ /**
36
+ * The entries one migrated row gets.
37
+ *
38
+ * A plan: its creation. An execution: its start, and — when it is a protocol
39
+ * — its sign-off, because that is the event the machine book is read for, and
40
+ * v2 records it as its own `update`. The `create` goes last: it is the
41
+ * marker that the row's history is complete (see pass 12).
42
+ */
43
+ function entriesFor(row, isExecution) {
44
+ const createdAt = row.createdAt ?? new Date(0);
45
+ const by = (0, pass_js_1.refId)(row.get("user"));
46
+ const full = snapshotOf(row);
47
+ const completedAt = row.get("completedAt");
48
+ if (!isExecution || !completedAt) {
49
+ return [
50
+ { operation: "create", original: null, value: full, at: createdAt, by },
51
+ ];
52
+ }
53
+ const started = { ...full, stepResults: [] };
54
+ for (const key of SIGN_OFF_FIELDS)
55
+ delete started[key];
56
+ // A direct maintenance can be recorded after the fact with an earlier
57
+ // date; the sign-off cannot precede the record it signs.
58
+ const signedAt = completedAt.getTime() >= createdAt.getTime() ? completedAt : createdAt;
59
+ return [
60
+ {
61
+ operation: "update",
62
+ original: started,
63
+ value: full,
64
+ at: signedAt,
65
+ by: (0, pass_js_1.refId)(row.get("performedBy")) ?? by,
66
+ },
67
+ { operation: "create", original: null, value: started, at: createdAt, by },
68
+ ];
69
+ }
70
+ /**
71
+ * Pass 19 — history entries for migrated plans and executions.
72
+ *
73
+ * v2 tells a machine's story from `OD3_Changelog`: the machine book's
74
+ * "Verlauf" and the plan's history tab list what happened by reading entries
75
+ * for `OD3_Service_Schedule` and `OD3_Service_Schedule_Execution`, matching
76
+ * executions to their plan through the `schedule` pointer in the snapshot.
77
+ * Every migration write skips the changelog hook (`skipChangelog`), so
78
+ * without this pass ten years of maintenance would be missing from that view
79
+ * while the calendar and the KPIs show it.
80
+ *
81
+ * v1 kept no edit history for plans or protocols — only its own changelog
82
+ * under the v1 class names, which cannot be re-pointed (MIGRATION_PLAN §6) —
83
+ * so there is nothing to replay: a plan gets its `create`, an execution its
84
+ * start and sign-off, at their historical timestamps and by their v1 authors.
85
+ */
86
+ exports.pass19 = {
87
+ id: "19",
88
+ title: "schedule-history",
89
+ needs: ["14", "15"],
90
+ async run({ config, map, report, entry }) {
91
+ const { batchSize } = config;
92
+ const alreadyDone = new Set();
93
+ for await (const page of (0, pass_js_1.pages)(() => new node_1.default.Query(index_js_1.Changelog)
94
+ .containedIn("nameOfClass", [
95
+ index_js_1.Service_Schedule.className,
96
+ index_js_1.Service_Schedule_Execution.className,
97
+ ])
98
+ .equalTo("operation", "create"), batchSize)) {
99
+ for (const row of page) {
100
+ const context = row.get("context");
101
+ if (context?.migrated)
102
+ alreadyDone.add(row.get("changedObject"));
103
+ }
104
+ }
105
+ const handle = async (v1, v2Class, isExecution) => {
106
+ const v1Class = v1.className;
107
+ // The v2 ids of what this run migrated, in v1 order.
108
+ const ids = [];
109
+ for await (const page of (0, pass_js_1.pages)(() => (0, pass_js_1.scopeToTenant)(new node_1.default.Query(v1), config.tenantId), batchSize)) {
110
+ for (const row of page) {
111
+ const v2Id = row.id ? map.get(v1Class, row.id) : undefined;
112
+ if (!v2Id)
113
+ continue;
114
+ if (alreadyDone.has(v2Id)) {
115
+ entry.skipped++;
116
+ continue;
117
+ }
118
+ ids.push({ v1Id: row.id, v2Id });
119
+ // A dry run has no v2 rows to read; a finished v1 run is the
120
+ // protocol that gets a second, sign-off entry.
121
+ if (config.dryRun) {
122
+ entry.created += isExecution && row.get("finishedAt") ? 2 : 1;
123
+ }
124
+ }
125
+ }
126
+ if (config.dryRun)
127
+ return;
128
+ for (let i = 0; i < ids.length; i += batchSize) {
129
+ const chunk = ids.slice(i, i + batchSize);
130
+ const rows = await new node_1.default.Query(v2Class)
131
+ .containedIn("objectId", chunk.map((c) => c.v2Id))
132
+ .limit(chunk.length)
133
+ .find(env_js_1.MK);
134
+ const byId = new Map(rows.map((row) => [row.id, row]));
135
+ for (const { v1Id, v2Id } of chunk) {
136
+ const row = byId.get(v2Id);
137
+ if (!row) {
138
+ report.error(entry, `${v2Class.className} ${v2Id} (v1 ${v1Id}) not found`);
139
+ continue;
140
+ }
141
+ for (const item of entriesFor(row, isExecution)) {
142
+ const changelog = new index_js_1.Changelog();
143
+ changelog.set("nameOfClass", v2Class.className);
144
+ changelog.set("changedObject", v2Id);
145
+ changelog.set("operation", item.operation);
146
+ changelog.set("masterkey", false);
147
+ if (item.by)
148
+ changelog.set("actingUser", (0, ptr_js_1.userPtr)(item.by));
149
+ changelog.set("original", item.original);
150
+ changelog.set("value", item.value);
151
+ changelog.set("context", {
152
+ migrated: true,
153
+ run: config.runId,
154
+ legacyClass: v1Class,
155
+ legacyId: v1Id,
156
+ });
157
+ // Whoever can see the row can see its history — what the
158
+ // suppressed `beforeSave(OD3_Changelog)` would have mirrored.
159
+ const acl = row.getACL();
160
+ if (acl)
161
+ changelog.setACL(acl);
162
+ try {
163
+ await (0, acl_js_1.saveMigrated)(config, changelog, {
164
+ className: index_js_1.Changelog.className,
165
+ isNew: true,
166
+ createdAt: item.at,
167
+ updatedAt: item.at,
168
+ });
169
+ entry.created++;
170
+ }
171
+ catch (error) {
172
+ report.error(entry, `history of ${v2Class.className} ${v2Id} failed: ` +
173
+ `${error.message}`);
174
+ }
175
+ }
176
+ }
177
+ }
178
+ };
179
+ await handle(index_js_1.Maintenance_Schedule, index_js_1.Service_Schedule, false);
180
+ await handle(index_js_1.Maintenance_Schedule_Execution, index_js_1.Service_Schedule_Execution, true);
181
+ if (alreadyDone.size > 0) {
182
+ report.info(entry, `${alreadyDone.size} row(s) already had their history`);
183
+ }
184
+ report.info(entry, `${entry.created} changelog entr(ies) written`);
185
+ },
186
+ };
@@ -15,6 +15,13 @@ const _09_ticket_meta_js_1 = require("./passes/09-ticket-meta.js");
15
15
  const _10_chat_js_1 = require("./passes/10-chat.js");
16
16
  const _11_assets_js_1 = require("./passes/11-assets.js");
17
17
  const _12_history_js_1 = require("./passes/12-history.js");
18
+ const _13_schedule_templates_js_1 = require("./passes/13-schedule-templates.js");
19
+ const _14_schedules_js_1 = require("./passes/14-schedules.js");
20
+ const _15_executions_js_1 = require("./passes/15-executions.js");
21
+ const _16_schedule_meta_js_1 = require("./passes/16-schedule-meta.js");
22
+ const _17_schedule_assets_js_1 = require("./passes/17-schedule-assets.js");
23
+ const _18_calendar_links_js_1 = require("./passes/18-calendar-links.js");
24
+ const _19_schedule_history_js_1 = require("./passes/19-schedule-history.js");
18
25
  /**
19
26
  * openservice v1 → v2 migration orchestrator.
20
27
  *
@@ -22,6 +29,7 @@ const _12_history_js_1 = require("./passes/12-history.js");
22
29
  * node dist/scripts/migration/run.js --tenant=<id> --dry-run
23
30
  *
24
31
  * Flags: --tenant=<id> --only=01,08 --dry-run --resume=<runId> --batch=500
32
+ * --timezone=Europe/Berlin
25
33
  *
26
34
  * Pass order is a hard dependency chain (equipment before tickets, tickets before
27
35
  * anything needing the new ids), so the chain is declared on each pass and checked
@@ -34,7 +42,9 @@ const _12_history_js_1 = require("./passes/12-history.js");
34
42
  *
35
43
  * The order is not cosmetic: equipment/tags/statuses/projects must exist before
36
44
  * tickets can point at them, and tickets must exist before anything keyed by the
37
- * new ticket id (meta, chat, assets, history).
45
+ * new ticket id (meta, chat, assets, history). The schedule passes follow the
46
+ * same rule: plans before their executions, both before the captured values,
47
+ * files, calendar links and history keyed by their new ids.
38
48
  */
39
49
  const PASSES = [
40
50
  _01_statuses_js_1.pass01,
@@ -49,9 +59,14 @@ const PASSES = [
49
59
  _10_chat_js_1.pass10,
50
60
  _11_assets_js_1.pass11,
51
61
  _12_history_js_1.pass12,
62
+ _13_schedule_templates_js_1.pass13,
63
+ _14_schedules_js_1.pass14,
64
+ _15_executions_js_1.pass15,
65
+ _16_schedule_meta_js_1.pass16,
66
+ _17_schedule_assets_js_1.pass17,
67
+ _18_calendar_links_js_1.pass18,
68
+ _19_schedule_history_js_1.pass19,
52
69
  ];
53
- /** Passes the plan defines but which are deliberately not implemented. */
54
- const PLANNED = ["13 schedules", "14 executions"];
55
70
  function selectPasses(config) {
56
71
  if (!config.only)
57
72
  return PASSES;
@@ -59,8 +74,7 @@ function selectPasses(config) {
59
74
  const unknown = config.only.filter((id) => !PASSES.some((p) => p.id === id));
60
75
  if (unknown.length) {
61
76
  throw new env_js_1.MigrationConfigError(`Unknown pass id(s): ${unknown.join(", ")}.\n` +
62
- ` Implemented: ${PASSES.map((p) => p.id).join(", ")}\n` +
63
- ` Deferred, not implemented: ${PLANNED.join(", ")}`);
77
+ ` Implemented: ${PASSES.map((p) => p.id).join(", ")}`);
64
78
  }
65
79
  // A selected pass whose prerequisite is neither selected nor already recorded in
66
80
  // the map would read a half-built world. Warn rather than block: re-running a
@@ -95,12 +109,9 @@ async function main() {
95
109
  console.log(` tenant ${config.tenantId ?? "(all)"}`);
96
110
  console.log(` run ${config.runId}`);
97
111
  console.log(` passes ${passes.map((p) => p.id).join(", ") || "(none)"}`);
112
+ console.log(` timezone ${config.timezone} (schedule cadences)`);
98
113
  if (config.dryRun)
99
114
  console.log(` MODE DRY RUN — nothing will be written`);
100
- if (PLANNED.length) {
101
- console.log(`
102
- deferred (MIGRATION_PLAN §4.5): ${PLANNED.join(", ")}`);
103
- }
104
115
  (0, env_js_1.initParse)(config);
105
116
  const report = new report_js_1.Report();
106
117
  const map = new map_js_1.MigrationMap(config);