@openinc/parse-server-opendash 4.33.0 → 4.34.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.
@@ -0,0 +1,51 @@
1
+ export interface DemoStep {
2
+ id: string;
3
+ order: number;
4
+ title: string;
5
+ description: string;
6
+ required: boolean;
7
+ }
8
+ export interface DemoCadence {
9
+ kind: "rrule" | "manual";
10
+ rrule?: string;
11
+ dtstart?: string;
12
+ timezone?: string;
13
+ }
14
+ export interface DemoSchedule {
15
+ title: string;
16
+ /** Index into {@link DEMO_MACHINES}. */
17
+ machine: number;
18
+ cadence: DemoCadence;
19
+ color?: string;
20
+ leadDays?: number;
21
+ graceDays?: number;
22
+ escalationAfterDays?: number;
23
+ pausedUntil?: Date;
24
+ origin?: string;
25
+ asset?: Record<string, unknown>;
26
+ /** Completed executions, in days ago, newest first. */
27
+ history: number[];
28
+ steps: DemoStep[];
29
+ }
30
+ export interface DemoTemplate {
31
+ title: string;
32
+ description: string;
33
+ cadence: DemoCadence;
34
+ steps: DemoStep[];
35
+ }
36
+ export declare const DEMO_HALL = "Halle B";
37
+ export declare const DEMO_MACHINES: string[];
38
+ declare const daysAgo: (n: number) => Date;
39
+ /**
40
+ * Built per call: step ids must be fresh, and every date is relative to now.
41
+ *
42
+ * `history` drives the executions and is what makes the forecast card show
43
+ * four different answers:
44
+ * - a steady rhythm → a date with high confidence
45
+ * - shrinking gaps → a date plus "intervals getting shorter"
46
+ * - erratic gaps → no date, "no dependable rhythm"
47
+ * - fewer than four → no date, "not enough history yet"
48
+ */
49
+ export declare function demoSchedules(): DemoSchedule[];
50
+ export declare function demoTemplates(): DemoTemplate[];
51
+ export { daysAgo as demoDaysAgo };
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.demoDaysAgo = exports.DEMO_MACHINES = exports.DEMO_HALL = void 0;
4
+ exports.demoSchedules = demoSchedules;
5
+ exports.demoTemplates = demoTemplates;
6
+ const crypto_1 = require("crypto");
7
+ /**
8
+ * The open.SERVICE demo data set: Halle B with five machines, ten plans, four
9
+ * templates and a completed history for each plan.
10
+ *
11
+ * The ten plans are not ten variations of the same plan. Each one exists to
12
+ * put a particular state on screen — every cadence kind the editor offers, an
13
+ * overdue plan, a paused one, one created by an alarm, and four different
14
+ * verdicts from the execution forecast (good, trending, unpredictable, not
15
+ * enough history). Every entry names its reason; if a plan stops earning its
16
+ * place, delete it rather than letting the list drift into noise.
17
+ *
18
+ * All dates are relative to *now*, so the data has to be re-seeded every few
19
+ * weeks to keep looking fresh — which is what the button on the setup page is
20
+ * for.
21
+ *
22
+ * Ported from `plugins/openservice-schedule/src/scripts/seed-testdata.mjs` in
23
+ * the opendash repo, which this replaces.
24
+ */
25
+ const TIMEZONE = "Europe/Berlin";
26
+ exports.DEMO_HALL = "Halle B";
27
+ exports.DEMO_MACHINES = [
28
+ "CNC-04",
29
+ "Presse-A",
30
+ "Roboter R-12",
31
+ "Lackierkabine L-1",
32
+ "Kompressor K-3",
33
+ ];
34
+ const [CNC, PRESSE, ROBOTER, LACK, KOMPRESSOR] = [0, 1, 2, 3, 4];
35
+ /**
36
+ * Stands in for an `OD3_Alarm.objectId` on the alarm-created plan. Fixed, so
37
+ * every seed produces the same `origin` marker — which is what the alarm dedup
38
+ * relies on.
39
+ */
40
+ const DEMO_ALARM_ID = "seedAlarmK3";
41
+ // ── Date helpers ──────────────────────────────────────────────────────────────
42
+ const daysAgo = (n) => {
43
+ const d = new Date();
44
+ d.setDate(d.getDate() - n);
45
+ return d;
46
+ };
47
+ exports.demoDaysAgo = daysAgo;
48
+ const daysFromNow = (n) => daysAgo(-n);
49
+ /**
50
+ * `date` at `hour` o'clock Berlin wall time, as an ISO string with the offset
51
+ * that is actually in force on that day.
52
+ *
53
+ * The old script hard-coded `+02:00`, which put every anchor seeded in winter
54
+ * an hour early: the cadence keeps the *wall time* of its dtstart, and 06:00
55
+ * at +02:00 is 05:00 in CET.
56
+ */
57
+ function berlinIso(date, hour) {
58
+ const pad = (n) => String(n).padStart(2, "0");
59
+ const y = date.getFullYear();
60
+ const m = pad(date.getMonth() + 1);
61
+ const d = pad(date.getDate());
62
+ // Noon UTC on that day is safely away from both DST switches (01:00 UTC).
63
+ const probe = new Date(`${y}-${m}-${d}T12:00:00Z`);
64
+ const name = new Intl.DateTimeFormat("en-US", {
65
+ timeZone: TIMEZONE,
66
+ timeZoneName: "longOffset",
67
+ })
68
+ .formatToParts(probe)
69
+ .find((part) => part.type === "timeZoneName")?.value ?? "GMT+01:00";
70
+ const offset = name === "GMT" ? "+00:00" : name.replace("GMT", "");
71
+ return `${y}-${m}-${d}T${pad(hour)}:00:00${offset}`;
72
+ }
73
+ /** A date ~6 weeks back on the given weekday (0 = Mon … 6 = Sun). */
74
+ function pastWeekday(weekdayMon0, hour) {
75
+ const d = daysAgo(42);
76
+ const jsTarget = weekdayMon0 === 6 ? 0 : weekdayMon0 + 1; // JS: 0 = Sun
77
+ while (d.getDay() !== jsTarget)
78
+ d.setDate(d.getDate() + 1);
79
+ return berlinIso(d, hour);
80
+ }
81
+ /** The 15th of the month two months back. */
82
+ function pastMonth15(hour) {
83
+ const d = new Date();
84
+ d.setDate(15);
85
+ d.setMonth(d.getMonth() - 2);
86
+ return berlinIso(d, hour);
87
+ }
88
+ const rrule = (rule, dtstart) => ({
89
+ kind: "rrule",
90
+ rrule: rule,
91
+ dtstart,
92
+ // Zoned like a plan created through the UI, so the plans keep their wall
93
+ // time across daylight saving instead of drifting by an hour.
94
+ timezone: TIMEZONE,
95
+ });
96
+ /**
97
+ * A work step. `required` steps block the sign-off, so every plan has at least
98
+ * one — an execution nobody can fail to complete tests nothing.
99
+ */
100
+ const step = (order, title, description, required = false) => ({ id: (0, crypto_1.randomUUID)(), order, title, description, required });
101
+ // ── The data ─────────────────────────────────────────────────────────────────
102
+ /**
103
+ * Built per call: step ids must be fresh, and every date is relative to now.
104
+ *
105
+ * `history` drives the executions and is what makes the forecast card show
106
+ * four different answers:
107
+ * - a steady rhythm → a date with high confidence
108
+ * - shrinking gaps → a date plus "intervals getting shorter"
109
+ * - erratic gaps → no date, "no dependable rhythm"
110
+ * - fewer than four → no date, "not enough history yet"
111
+ */
112
+ function demoSchedules() {
113
+ return [
114
+ {
115
+ // Steady weekly rhythm → the forecast's best case.
116
+ title: "CNC-04 — Spindel-Inspektion",
117
+ machine: CNC,
118
+ cadence: rrule("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO", pastWeekday(0, 6)),
119
+ color: "#7fbb47",
120
+ history: [2, 9, 16, 23, 30, 37],
121
+ steps: [
122
+ step(0, "Sichtprüfung", "Auf Beschädigungen und Leckagen prüfen.", true),
123
+ step(1, "Schmierung", "Schmiernippel abschmieren."),
124
+ step(2, "Lagerspiel messen", "Axiales/radiales Spiel prüfen.", true),
125
+ ],
126
+ },
127
+ {
128
+ // Tolerance configured: actionable 2 days early, still "on time" 3 late.
129
+ title: "CNC-04 — Kühlmittel prüfen",
130
+ machine: CNC,
131
+ cadence: rrule("FREQ=WEEKLY;INTERVAL=2;BYDAY=WE", pastWeekday(2, 9)),
132
+ leadDays: 2,
133
+ graceDays: 3,
134
+ history: [4, 18, 32],
135
+ steps: [
136
+ step(0, "Konzentration messen", "Refraktometer, Sollwert 8 %.", true),
137
+ step(1, "Nachfüllen", "Bei Bedarf Emulsion ergänzen."),
138
+ ],
139
+ },
140
+ {
141
+ // No rule at all. The forecast is the *only* hint about the next one,
142
+ // which is the case it was built for.
143
+ title: "CNC-04 — Werkzeugwechsel nach Bedarf",
144
+ machine: CNC,
145
+ cadence: { kind: "manual" },
146
+ history: [5, 26, 48, 69, 91],
147
+ steps: [
148
+ step(0, "Werkzeug prüfen", "Schneidkanten auf Verschleiß sichten.", true),
149
+ step(1, "Wechseln", "Werkzeug tauschen und Nullpunkt setzen."),
150
+ step(2, "Probelauf", "Erstes Teil vermessen."),
151
+ ],
152
+ },
153
+ {
154
+ // Shrinking gaps (60 → 20 days): the forecast should warn that the
155
+ // intervals are getting shorter and extrapolate the *next* one.
156
+ title: "Presse-A — Hydraulikfilter",
157
+ machine: PRESSE,
158
+ cadence: rrule("FREQ=MONTHLY;BYMONTHDAY=15", pastMonth15(8)),
159
+ color: "#e8a33d",
160
+ history: [10, 30, 60, 100, 150],
161
+ steps: [
162
+ step(0, "Ölstand prüfen", "Füllstand am Schauglas kontrollieren.", true),
163
+ step(1, "Filter wechseln", "Rücklauffilter tauschen.", true),
164
+ step(2, "Dichtungen kontrollieren", "Auf Undichtigkeiten prüfen."),
165
+ step(3, "Probelauf", "Druck aufbauen, auf Leckagen achten."),
166
+ ],
167
+ },
168
+ {
169
+ // Past due with no execution at all → overdue list and compliance tile.
170
+ title: "Presse-A — Dichtungen prüfen",
171
+ machine: PRESSE,
172
+ cadence: rrule("FREQ=WEEKLY;INTERVAL=1;BYDAY=TH", pastWeekday(3, 13)),
173
+ history: [],
174
+ steps: [
175
+ step(0, "Sichtprüfung Dichtungen", "Auf Risse und Austritt prüfen.", true),
176
+ step(1, "Befund notieren", "Auffälligkeiten dokumentieren."),
177
+ ],
178
+ },
179
+ {
180
+ // Erratic history → the forecast must refuse rather than invent a date.
181
+ title: "Roboter R-12 — Achsen schmieren",
182
+ machine: ROBOTER,
183
+ cadence: rrule("FREQ=WEEKLY;INTERVAL=1;BYDAY=FR", pastWeekday(4, 14)),
184
+ history: [3, 5, 61, 66, 190],
185
+ steps: [
186
+ step(0, "Achsen 1–3 schmieren", "Fett nach Herstellerangabe.", true),
187
+ step(1, "Achsen 4–6 schmieren", "Fett nach Herstellerangabe.", true),
188
+ step(2, "Referenzfahrt", "Alle Achsen referenzieren."),
189
+ ],
190
+ },
191
+ {
192
+ // Paused: no occurrences before `pausedUntil` — the machine is out of use.
193
+ title: "Roboter R-12 — Greifer kalibrieren",
194
+ machine: ROBOTER,
195
+ cadence: rrule("FREQ=MONTHLY;BYDAY=+1TU", pastMonth15(10)),
196
+ pausedUntil: daysFromNow(45),
197
+ history: [40, 72],
198
+ steps: [
199
+ step(0, "Greifkraft messen", "Mit Prüfkörper gegen Sollwert.", true),
200
+ step(1, "Offset korrigieren", "Abweichung in der Steuerung nachführen."),
201
+ ],
202
+ },
203
+ {
204
+ // Escalation configured — stored and shown, but nothing acts on it yet.
205
+ // Seeded so that stays visible instead of theoretical.
206
+ title: "Lackierkabine L-1 — Filterwechsel",
207
+ machine: LACK,
208
+ cadence: rrule("FREQ=WEEKLY;INTERVAL=2;BYDAY=TU", pastWeekday(1, 7)),
209
+ graceDays: 2,
210
+ escalationAfterDays: 5,
211
+ history: [12, 26, 40, 54],
212
+ steps: [
213
+ step(0, "Vorfilter tauschen", "Matten erneuern.", true),
214
+ step(1, "Deckenfilter prüfen", "Bei Sättigung tauschen."),
215
+ step(2, "Druckdifferenz notieren", "Messwert ins Protokoll."),
216
+ ],
217
+ },
218
+ {
219
+ // Daily and dense — the forecast's most confident case, and enough rows
220
+ // to make the machine book and the load widget non-trivial.
221
+ title: "Kompressor K-3 — Kondensat ablassen",
222
+ machine: KOMPRESSOR,
223
+ cadence: rrule("FREQ=DAILY;INTERVAL=1", berlinIso(daysAgo(42), 7)),
224
+ history: [0, 1, 2, 3, 4, 5, 6, 7],
225
+ steps: [
226
+ step(0, "Kondensatablass öffnen", "Bis Luft austritt.", true),
227
+ step(1, "Menge notieren", "Auffälligkeiten melden."),
228
+ ],
229
+ },
230
+ {
231
+ // Created by an alarm: a COUNT=1 one-off carrying the `origin` marker and
232
+ // the firing context under `asset.alarm`. Feeds the "triggered by an
233
+ // alarm" card on the detail page and the trigger overview.
234
+ title: "Kompressor K-3 — Lagerschaden prüfen (Alarm)",
235
+ machine: KOMPRESSOR,
236
+ cadence: rrule("FREQ=DAILY;COUNT=1", berlinIso(daysFromNow(2), 8)),
237
+ color: "#d4564b",
238
+ origin: `alarm:${DEMO_ALARM_ID}`,
239
+ asset: {
240
+ alarm: {
241
+ alarmId: DEMO_ALARM_ID,
242
+ name: "K-3 Lagertemperatur kritisch",
243
+ sensor: "halle-b/kompressor-k3.bearing_temp [0]",
244
+ value: 87.4,
245
+ condition: "> 80",
246
+ firedAt: daysAgo(1).toISOString(),
247
+ actionId: "openservice-create-schedule",
248
+ },
249
+ },
250
+ history: [],
251
+ steps: [
252
+ step(0, "Lagertemperatur messen", "Mit Infrarotthermometer.", true),
253
+ step(1, "Laufgeräusch prüfen", "Auf Mahlen oder Schleifen achten.", true),
254
+ step(2, "Befund dokumentieren", "Bei Auffälligkeit Ticket erstellen."),
255
+ ],
256
+ },
257
+ ];
258
+ }
259
+ function demoTemplates() {
260
+ const today = (rule, hour) => rrule(rule, berlinIso(new Date(), hour));
261
+ return [
262
+ {
263
+ title: "Standard Spindel-Inspektion",
264
+ description: "Wöchentliche Sicht- und Funktionsprüfung der Spindel.",
265
+ cadence: today("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO", 6),
266
+ steps: [
267
+ step(0, "Sichtprüfung", "Auf Beschädigungen und Leckagen prüfen.", true),
268
+ step(1, "Schmierung", "Schmiernippel abschmieren."),
269
+ step(2, "Lagerspiel messen", "Axiales/radiales Spiel prüfen.", true),
270
+ ],
271
+ },
272
+ {
273
+ title: "Monatliche Hydraulik-Wartung",
274
+ description: "Hydraulikaggregat: Ölstand, Filter und Dichtungen.",
275
+ cadence: today("FREQ=MONTHLY;BYMONTHDAY=15", 8),
276
+ steps: [
277
+ step(0, "Ölstand prüfen", "Füllstand am Schauglas kontrollieren.", true),
278
+ step(1, "Filter wechseln", "Rücklauffilter tauschen."),
279
+ step(2, "Dichtungen kontrollieren", "Auf Undichtigkeiten prüfen."),
280
+ ],
281
+ },
282
+ {
283
+ title: "Jährliche Sicherheitsprüfung",
284
+ description: "Gesetzlich vorgeschriebene jährliche Prüfung.",
285
+ cadence: today("FREQ=YEARLY", 7),
286
+ steps: [
287
+ step(0, "Elektrische Prüfung", "DGUV V3 durchführen.", true),
288
+ step(1, "Not-Aus-Test", "Alle Not-Aus-Kreise auslösen.", true),
289
+ step(2, "Protokoll ablegen", "Prüfprotokoll dokumentieren."),
290
+ ],
291
+ },
292
+ {
293
+ // The template an alarm applies. Its title is what a plan created by the
294
+ // "Wartungstermin anlegen" action inherits when no title is configured.
295
+ title: "Lagerschaden-Prüfung (Alarm)",
296
+ description: "Kurzprüfung nach einem Temperatur- oder Vibrationsalarm.",
297
+ cadence: today("FREQ=DAILY;COUNT=1", 8),
298
+ steps: [
299
+ step(0, "Lagertemperatur messen", "Mit Infrarotthermometer.", true),
300
+ step(1, "Laufgeräusch prüfen", "Auf Mahlen oder Schleifen achten.", true),
301
+ step(2, "Befund dokumentieren", "Bei Auffälligkeit Ticket erstellen."),
302
+ ],
303
+ },
304
+ ];
305
+ }
@@ -0,0 +1,82 @@
1
+ import { Tenant, type _User } from "../../../types/index.js";
2
+ /**
3
+ * Where a tenant's demo seed remembers what it created.
4
+ *
5
+ * None of the seeded classes carries a marker column — a demo feature is no
6
+ * reason for a schema change. Instead the ids of everything seeded are kept in
7
+ * one config row per tenant, readable by `od-admin` only. A reset removes
8
+ * exactly those objects (plus what can only go together with them, see
9
+ * {@link resetDemoData}), so a tenant that also holds real data keeps it.
10
+ */
11
+ export declare const DEMO_SEED_CONFIG_KEY = "OPENSERVICE_DEMO_SEED";
12
+ /**
13
+ * Context flag on every write the seed makes. The plan hook skips the Outlook
14
+ * sync for it: demo plans belong to a demo tenant, not in anybody's calendar.
15
+ */
16
+ export declare const DEMO_SEED_CONTEXT_FLAG = "fromDemoSeed";
17
+ export interface DemoSeedTenantStatus {
18
+ tenantId: string;
19
+ label: string;
20
+ seededAt?: string;
21
+ }
22
+ export interface DemoSeedResult {
23
+ tenantId: string;
24
+ removed: {
25
+ executions: number;
26
+ schedules: number;
27
+ templates: number;
28
+ equipment: number;
29
+ /**
30
+ * Equipment that tickets or hand-made equipment still point at —
31
+ * archived instead of deleted.
32
+ */
33
+ archivedEquipment: number;
34
+ };
35
+ created?: {
36
+ equipment: number;
37
+ schedules: number;
38
+ templates: number;
39
+ executions: number;
40
+ };
41
+ }
42
+ /** Every tenant with the date of its last demo seed, if any. */
43
+ export declare function demoSeedStatus(): Promise<DemoSeedTenantStatus[]>;
44
+ export declare function resolveTenant(tenantId: unknown): Promise<Tenant>;
45
+ export interface DemoSeedUser {
46
+ userId: string;
47
+ label: string;
48
+ }
49
+ /** The tenant's users, as candidates for the `user` field of the demo data. */
50
+ export declare function demoSeedUsers(tenant: Tenant): Promise<DemoSeedUser[]>;
51
+ /**
52
+ * The user the demo data is attributed to — only one of the chosen tenant's,
53
+ * otherwise a demo plan would hand a foreign user read+write on it.
54
+ */
55
+ export declare function resolveUser(userId: unknown, tenant: Tenant): Promise<_User | undefined>;
56
+ /**
57
+ * Replace the tenant's demo data with a fresh set.
58
+ *
59
+ * Removes the previous seed first, so pressing the button twice does not
60
+ * leave two copies of Halle B.
61
+ *
62
+ * `user` becomes the `user` of every plan, template and execution: the owner
63
+ * of a plan (the ACL grants them read+write) and the author of the rest —
64
+ * and the `performedBy` of every execution.
65
+ * Without one the fields stay empty, as before.
66
+ */
67
+ export declare function seedDemoData(tenant: Tenant, user?: _User): Promise<DemoSeedResult>;
68
+ /**
69
+ * Remove what the last seed created in this tenant.
70
+ *
71
+ * Beyond the recorded ids, three things go with them because they cannot stay
72
+ * behind on their own:
73
+ * - executions somebody recorded by hand on a demo plan or demo machine — a
74
+ * plan with executions cannot be deleted, and they would point at nothing;
75
+ * - the role/user assignments of the demo plans (Parse leaves relation rows
76
+ * in `_Join:*` behind when the owning object is deleted);
77
+ * - changelog rows about demo objects, written by edits during the demo.
78
+ *
79
+ * Equipment that tickets or non-demo equipment point at is archived rather
80
+ * than deleted.
81
+ */
82
+ export declare function resetDemoData(tenant: Tenant): Promise<DemoSeedResult["removed"]>;
@@ -0,0 +1,424 @@
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.DEMO_SEED_CONTEXT_FLAG = exports.DEMO_SEED_CONFIG_KEY = void 0;
7
+ exports.demoSeedStatus = demoSeedStatus;
8
+ exports.resolveTenant = resolveTenant;
9
+ exports.demoSeedUsers = demoSeedUsers;
10
+ exports.resolveUser = resolveUser;
11
+ exports.seedDemoData = seedDemoData;
12
+ exports.resetDemoData = resetDemoData;
13
+ const node_1 = __importDefault(require("parse/node"));
14
+ const index_js_1 = require("../../../types/index.js");
15
+ const demoData_js_1 = require("./demoData.js");
16
+ /**
17
+ * Where a tenant's demo seed remembers what it created.
18
+ *
19
+ * None of the seeded classes carries a marker column — a demo feature is no
20
+ * reason for a schema change. Instead the ids of everything seeded are kept in
21
+ * one config row per tenant, readable by `od-admin` only. A reset removes
22
+ * exactly those objects (plus what can only go together with them, see
23
+ * {@link resetDemoData}), so a tenant that also holds real data keeps it.
24
+ */
25
+ exports.DEMO_SEED_CONFIG_KEY = "OPENSERVICE_DEMO_SEED";
26
+ /**
27
+ * Context flag on every write the seed makes. The plan hook skips the Outlook
28
+ * sync for it: demo plans belong to a demo tenant, not in anybody's calendar.
29
+ */
30
+ exports.DEMO_SEED_CONTEXT_FLAG = "fromDemoSeed";
31
+ /** Reads. */
32
+ const MK = { useMasterKey: true };
33
+ /**
34
+ * Writes and deletes. `skipChangelog`: the seed's own rows would all read
35
+ * "created by master key, today" — noise in every history view, and rows the
36
+ * reset would have to chase afterwards.
37
+ */
38
+ const WRITE = {
39
+ useMasterKey: true,
40
+ context: { skipChangelog: true, [exports.DEMO_SEED_CONTEXT_FLAG]: true },
41
+ };
42
+ const SEEDED_CLASSES = [
43
+ index_js_1.Service_Equipment.className,
44
+ index_js_1.Service_Schedule.className,
45
+ index_js_1.Service_Schedule_Template.className,
46
+ index_js_1.Service_Schedule_Execution.className,
47
+ ];
48
+ /** Every tenant with the date of its last demo seed, if any. */
49
+ async function demoSeedStatus() {
50
+ const [tenants, rows] = await Promise.all([
51
+ new node_1.default.Query(index_js_1.Tenant).ascending("label").limit(1000).find(MK),
52
+ new node_1.default.Query(index_js_1.Config)
53
+ .equalTo("key", exports.DEMO_SEED_CONFIG_KEY)
54
+ .limit(1000)
55
+ .find(MK),
56
+ ]);
57
+ const seededAt = new Map();
58
+ for (const row of rows) {
59
+ const tenantId = row.get("tenant")?.id;
60
+ const record = parseRecord(row.get("value"));
61
+ if (tenantId && record)
62
+ seededAt.set(tenantId, record.seededAt);
63
+ }
64
+ return tenants.map((tenant) => ({
65
+ tenantId: tenant.id,
66
+ label: tenant.get("label") || tenant.id,
67
+ seededAt: seededAt.get(tenant.id),
68
+ }));
69
+ }
70
+ async function resolveTenant(tenantId) {
71
+ if (typeof tenantId !== "string" || !tenantId) {
72
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, "tenantId is required");
73
+ }
74
+ return new node_1.default.Query(index_js_1.Tenant).get(tenantId, MK);
75
+ }
76
+ /** The tenant's users, as candidates for the `user` field of the demo data. */
77
+ async function demoSeedUsers(tenant) {
78
+ const users = await new node_1.default.Query(node_1.default.User)
79
+ .equalTo("tenant", tenant)
80
+ .notEqualTo("tenantBanned", true)
81
+ .limit(1000)
82
+ .find(MK);
83
+ return users
84
+ .map((user) => ({ userId: user.id, label: userLabel(user) }))
85
+ .sort((a, b) => a.label.localeCompare(b.label));
86
+ }
87
+ /**
88
+ * The user the demo data is attributed to — only one of the chosen tenant's,
89
+ * otherwise a demo plan would hand a foreign user read+write on it.
90
+ */
91
+ async function resolveUser(userId, tenant) {
92
+ if (userId == null || userId === "")
93
+ return undefined;
94
+ if (typeof userId !== "string") {
95
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, "userId must be a string");
96
+ }
97
+ const user = (await new node_1.default.Query(node_1.default.User)
98
+ .equalTo("objectId", userId)
99
+ .equalTo("tenant", tenant)
100
+ .first(MK));
101
+ if (!user) {
102
+ throw new node_1.default.Error(node_1.default.Error.OBJECT_NOT_FOUND, `User ${userId} does not belong to tenant ${tenant.id}`);
103
+ }
104
+ return user;
105
+ }
106
+ function userLabel(user) {
107
+ const full = [user.get("firstname"), user.get("lastname")]
108
+ .filter(Boolean)
109
+ .join(" ");
110
+ return (user.get("name") ||
111
+ full ||
112
+ user.get("username") ||
113
+ user.get("email") ||
114
+ user.id);
115
+ }
116
+ /**
117
+ * Replace the tenant's demo data with a fresh set.
118
+ *
119
+ * Removes the previous seed first, so pressing the button twice does not
120
+ * leave two copies of Halle B.
121
+ *
122
+ * `user` becomes the `user` of every plan, template and execution: the owner
123
+ * of a plan (the ACL grants them read+write) and the author of the rest —
124
+ * and the `performedBy` of every execution.
125
+ * Without one the fields stay empty, as before.
126
+ */
127
+ async function seedDemoData(tenant, user) {
128
+ const removed = await resetDemoData(tenant);
129
+ // Written after every step, so a failure halfway still leaves a record the
130
+ // next reset can clean up from.
131
+ const record = {
132
+ seededAt: new Date().toISOString(),
133
+ equipment: [],
134
+ templates: [],
135
+ schedules: [],
136
+ executions: [],
137
+ };
138
+ // ── Equipment ──────────────────────────────────────────────────────────────
139
+ const hall = new index_js_1.Service_Equipment();
140
+ hall.set("label", demoData_js_1.DEMO_HALL);
141
+ hall.set("deleted", false);
142
+ hall.set("tenant", tenant);
143
+ await hall.save(null, WRITE);
144
+ record.equipment.push(hall.id);
145
+ await writeRecord(tenant, record);
146
+ const machines = demoData_js_1.DEMO_MACHINES.map((label) => {
147
+ const machine = new index_js_1.Service_Equipment();
148
+ machine.set("label", label);
149
+ machine.set("deleted", false);
150
+ machine.set("tenant", tenant);
151
+ machine.set("parent", hall);
152
+ return machine;
153
+ });
154
+ await node_1.default.Object.saveAll(machines, WRITE);
155
+ record.equipment.push(...machines.map((m) => m.id));
156
+ await writeRecord(tenant, record);
157
+ // ── Templates ──────────────────────────────────────────────────────────────
158
+ const templates = (0, demoData_js_1.demoTemplates)().map((data) => {
159
+ const template = new index_js_1.Service_Schedule_Template();
160
+ template.set("title", data.title);
161
+ template.set("description", data.description);
162
+ template.set("cadence", data.cadence);
163
+ template.set("steps", data.steps);
164
+ template.set("serviceProviders", []);
165
+ template.set("tenant", tenant);
166
+ if (user)
167
+ template.set("user", user);
168
+ return template;
169
+ });
170
+ await node_1.default.Object.saveAll(templates, WRITE);
171
+ record.templates = templates.map((t) => t.id);
172
+ await writeRecord(tenant, record);
173
+ // ── Plans ──────────────────────────────────────────────────────────────────
174
+ const plans = (0, demoData_js_1.demoSchedules)();
175
+ const schedules = plans.map((plan) => {
176
+ const schedule = new index_js_1.Service_Schedule();
177
+ schedule.set("title", plan.title);
178
+ schedule.set("active", true);
179
+ schedule.set("cadence", plan.cadence);
180
+ schedule.set("steps", plan.steps);
181
+ schedule.set("serviceProviders", []);
182
+ schedule.set("tenant", tenant);
183
+ if (user)
184
+ schedule.set("user", user);
185
+ schedule.set("equipment", machines[plan.machine]);
186
+ // Optional columns only when used: an explicit undefined would be written
187
+ // as null and muddle "not configured".
188
+ if (plan.color)
189
+ schedule.set("color", plan.color);
190
+ if (plan.leadDays != null)
191
+ schedule.set("leadDays", plan.leadDays);
192
+ if (plan.graceDays != null)
193
+ schedule.set("graceDays", plan.graceDays);
194
+ if (plan.escalationAfterDays != null) {
195
+ schedule.set("escalationAfterDays", plan.escalationAfterDays);
196
+ }
197
+ if (plan.pausedUntil)
198
+ schedule.set("pausedUntil", plan.pausedUntil);
199
+ if (plan.origin)
200
+ schedule.set("origin", plan.origin);
201
+ if (plan.asset)
202
+ schedule.set("asset", plan.asset);
203
+ return schedule;
204
+ });
205
+ await node_1.default.Object.saveAll(schedules, WRITE);
206
+ record.schedules = schedules.map((s) => s.id);
207
+ await writeRecord(tenant, record);
208
+ // Plans are private by default (`denyTenantUserRead`), and a master-key
209
+ // write has no creator to grant. Assigning the tenant's user role is what
210
+ // makes them visible to everybody logging into the demo — the afterSave
211
+ // hook rebuilds the ACL from the relation.
212
+ const userRole = await new node_1.default.Query(node_1.default.Role)
213
+ .equalTo("name", `od-tenant-user-${tenant.id}`)
214
+ .first(MK);
215
+ if (userRole) {
216
+ for (const schedule of schedules) {
217
+ schedule.relation("assignedRoles").add(userRole);
218
+ }
219
+ await node_1.default.Object.saveAll(schedules, WRITE);
220
+ }
221
+ else {
222
+ console.warn(`[DemoSeed] Tenant ${tenant.id} has no od-tenant-user role — demo plans stay visible to admins only`);
223
+ }
224
+ // ── Executions, from each plan's history ───────────────────────────────────
225
+ // Completed executions only: one without `completedAt` is still being worked
226
+ // through, and seeding those would make every plan look like somebody is
227
+ // mid-job on it. Every step is ticked, so the protocols read as complete.
228
+ // The step snapshot (`steps`) is frozen on by the execution hook.
229
+ const executions = plans.flatMap((plan, index) => plan.history.map((completedDaysAgo) => {
230
+ const completedAt = (0, demoData_js_1.demoDaysAgo)(completedDaysAgo);
231
+ const execution = new index_js_1.Service_Schedule_Execution();
232
+ execution.set("schedule", schedules[index]);
233
+ execution.set("tenant", tenant);
234
+ if (user) {
235
+ execution.set("user", user);
236
+ // Who carried it out — what the protocol shows as "durchgeführt von".
237
+ execution.set("performedBy", user);
238
+ }
239
+ execution.set("completedAt", completedAt);
240
+ execution.set("stepResults", plan.steps.map((s) => ({
241
+ stepId: s.id,
242
+ done: true,
243
+ completedAt: completedAt.toISOString(),
244
+ })));
245
+ return execution;
246
+ }));
247
+ await node_1.default.Object.saveAll(executions, WRITE);
248
+ record.executions = executions.map((e) => e.id);
249
+ await writeRecord(tenant, record);
250
+ return {
251
+ tenantId: tenant.id,
252
+ removed,
253
+ created: {
254
+ equipment: record.equipment.length,
255
+ schedules: schedules.length,
256
+ templates: templates.length,
257
+ executions: executions.length,
258
+ },
259
+ };
260
+ }
261
+ /**
262
+ * Remove what the last seed created in this tenant.
263
+ *
264
+ * Beyond the recorded ids, three things go with them because they cannot stay
265
+ * behind on their own:
266
+ * - executions somebody recorded by hand on a demo plan or demo machine — a
267
+ * plan with executions cannot be deleted, and they would point at nothing;
268
+ * - the role/user assignments of the demo plans (Parse leaves relation rows
269
+ * in `_Join:*` behind when the owning object is deleted);
270
+ * - changelog rows about demo objects, written by edits during the demo.
271
+ *
272
+ * Equipment that tickets or non-demo equipment point at is archived rather
273
+ * than deleted.
274
+ */
275
+ async function resetDemoData(tenant) {
276
+ const row = await findRecordRow(tenant);
277
+ const record = parseRecord(row?.get("value"));
278
+ const schedules = await byIds(tenant, index_js_1.Service_Schedule, record?.schedules);
279
+ const templates = await byIds(tenant, index_js_1.Service_Schedule_Template, record?.templates);
280
+ const equipment = await byIds(tenant, index_js_1.Service_Equipment, record?.equipment);
281
+ const recordedExecutions = await byIds(tenant, index_js_1.Service_Schedule_Execution, record?.executions);
282
+ // Executions point at plans (or, for a direct maintenance, at equipment);
283
+ // they have to go before what they point at.
284
+ const executions = uniqueById([
285
+ ...recordedExecutions,
286
+ ...(schedules.length
287
+ ? await new node_1.default.Query(index_js_1.Service_Schedule_Execution)
288
+ .equalTo("tenant", tenant)
289
+ .containedIn("schedule", schedules)
290
+ .limit(10000)
291
+ .find(MK)
292
+ : []),
293
+ ...(equipment.length
294
+ ? await new node_1.default.Query(index_js_1.Service_Schedule_Execution)
295
+ .equalTo("tenant", tenant)
296
+ .containedIn("equipment", equipment)
297
+ .doesNotExist("schedule")
298
+ .limit(10000)
299
+ .find(MK)
300
+ : []),
301
+ ]);
302
+ await node_1.default.Object.destroyAll(executions, WRITE);
303
+ await clearRelations(schedules, [
304
+ "assignedRoles",
305
+ "escalationRoles",
306
+ "assignedUsers",
307
+ ]);
308
+ await clearRelations(templates, ["assignedRoles"]);
309
+ await node_1.default.Object.destroyAll(schedules, WRITE);
310
+ await node_1.default.Object.destroyAll(templates, WRITE);
311
+ // Machines before the hall that is their parent; one at a time, because a
312
+ // refused delete must not take the rest of the batch with it.
313
+ let deletedEquipment = 0;
314
+ let archivedEquipment = 0;
315
+ const childrenFirst = [...equipment].sort((a, b) => Number(!a.get("parent")) - Number(!b.get("parent")));
316
+ for (const item of childrenFirst) {
317
+ // Somebody hung their own equipment under Halle B: deleting it would leave
318
+ // that child pointing at nothing. The equipment hook only checks tickets.
319
+ const children = await new node_1.default.Query(index_js_1.Service_Equipment)
320
+ .equalTo("parent", item)
321
+ .count(MK);
322
+ try {
323
+ if (children > 0)
324
+ throw new Error("has children");
325
+ await item.destroy(WRITE);
326
+ deletedEquipment++;
327
+ }
328
+ catch {
329
+ item.set("deleted", true);
330
+ await item.save(null, WRITE);
331
+ archivedEquipment++;
332
+ }
333
+ }
334
+ // History of edits made during the demo. Only rows about objects that are
335
+ // actually gone — an archived machine keeps its history.
336
+ const goneIds = [
337
+ ...executions,
338
+ ...schedules,
339
+ ...templates,
340
+ ...equipment.filter((item) => !item.get("deleted")),
341
+ ].map((o) => o.id);
342
+ await deleteChangelog(goneIds);
343
+ if (row)
344
+ await row.destroy(WRITE);
345
+ return {
346
+ executions: executions.length,
347
+ schedules: schedules.length,
348
+ templates: templates.length,
349
+ equipment: deletedEquipment,
350
+ archivedEquipment,
351
+ };
352
+ }
353
+ /** Recorded objects that still exist — scoped to the tenant, always. */
354
+ async function byIds(tenant, cls, ids) {
355
+ if (!ids?.length)
356
+ return [];
357
+ return new node_1.default.Query(cls.className)
358
+ .containedIn("objectId", ids)
359
+ .equalTo("tenant", tenant)
360
+ .limit(ids.length)
361
+ .find(MK);
362
+ }
363
+ async function clearRelations(objects, keys) {
364
+ const changed = [];
365
+ for (const object of objects) {
366
+ let dirty = false;
367
+ for (const key of keys) {
368
+ const relation = object.relation(key);
369
+ const members = await relation.query().limit(1000).find(MK);
370
+ if (members.length) {
371
+ relation.remove(members);
372
+ dirty = true;
373
+ }
374
+ }
375
+ if (dirty)
376
+ changed.push(object);
377
+ }
378
+ if (changed.length)
379
+ await node_1.default.Object.saveAll(changed, WRITE);
380
+ }
381
+ async function deleteChangelog(ids) {
382
+ if (!ids.length)
383
+ return;
384
+ const rows = await new node_1.default.Query(index_js_1.Changelog)
385
+ .containedIn("nameOfClass", SEEDED_CLASSES)
386
+ .containedIn("changedObject", ids)
387
+ .limit(10000)
388
+ .find(MK);
389
+ await node_1.default.Object.destroyAll(rows, WRITE);
390
+ }
391
+ function uniqueById(objects) {
392
+ return [...new Map(objects.map((o) => [o.id, o])).values()];
393
+ }
394
+ function findRecordRow(tenant) {
395
+ return new node_1.default.Query(index_js_1.Config)
396
+ .equalTo("key", exports.DEMO_SEED_CONFIG_KEY)
397
+ .equalTo("tenant", tenant)
398
+ .first(MK);
399
+ }
400
+ async function writeRecord(tenant, record) {
401
+ let row = await findRecordRow(tenant);
402
+ if (!row) {
403
+ row = new index_js_1.Config();
404
+ row.set("key", exports.DEMO_SEED_CONFIG_KEY);
405
+ row.set("tenant", tenant);
406
+ row.set("priority", 0);
407
+ const acl = new node_1.default.ACL();
408
+ acl.setRoleReadAccess("od-admin", true);
409
+ acl.setRoleWriteAccess("od-admin", true);
410
+ row.setACL(acl);
411
+ }
412
+ row.set("value", JSON.stringify(record));
413
+ await row.save(null, WRITE);
414
+ }
415
+ function parseRecord(value) {
416
+ if (typeof value !== "string" || !value)
417
+ return undefined;
418
+ try {
419
+ return JSON.parse(value);
420
+ }
421
+ catch {
422
+ return undefined;
423
+ }
424
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Seed or remove the open.SERVICE demo data set (Halle B, ten plans, four
3
+ * templates, their history) in a tenant of the caller's choice.
4
+ *
5
+ * Actions:
6
+ * - `status` (default) — whether the caller may use this at all, and every
7
+ * tenant with the date of its last seed. A caller who may not gets
8
+ * `{ allowed: false }` instead of an error, so the setup page can simply
9
+ * leave the section out.
10
+ * - `users` — the chosen tenant's users, for the `user` field of the data.
11
+ * - `seed` — replace the tenant's demo data with a fresh set, optionally
12
+ * attributed to `userId` (one of that tenant's users). Dates are relative
13
+ * to now, which is why re-seeding is the way to refresh it.
14
+ * - `reset` — remove what the last seed created, and nothing else.
15
+ *
16
+ * **Global admins only (`od-admin`).** Unlike the setup function, the tenant
17
+ * is a parameter here — that is the point of it — so a tenant admin must not
18
+ * be able to call it: they could write into, or wipe the demo data of, a
19
+ * tenant that is not theirs.
20
+ */
21
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,63 @@
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.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const demoSeed_js_1 = require("../features/openservice/demoSeed/demoSeed.js");
9
+ /**
10
+ * Seed or remove the open.SERVICE demo data set (Halle B, ten plans, four
11
+ * templates, their history) in a tenant of the caller's choice.
12
+ *
13
+ * Actions:
14
+ * - `status` (default) — whether the caller may use this at all, and every
15
+ * tenant with the date of its last seed. A caller who may not gets
16
+ * `{ allowed: false }` instead of an error, so the setup page can simply
17
+ * leave the section out.
18
+ * - `users` — the chosen tenant's users, for the `user` field of the data.
19
+ * - `seed` — replace the tenant's demo data with a fresh set, optionally
20
+ * attributed to `userId` (one of that tenant's users). Dates are relative
21
+ * to now, which is why re-seeding is the way to refresh it.
22
+ * - `reset` — remove what the last seed created, and nothing else.
23
+ *
24
+ * **Global admins only (`od-admin`).** Unlike the setup function, the tenant
25
+ * is a parameter here — that is the point of it — so a tenant admin must not
26
+ * be able to call it: they could write into, or wipe the demo data of, a
27
+ * tenant that is not theirs.
28
+ */
29
+ async function init(name) {
30
+ node_1.default.Cloud.define(name, async (request) => {
31
+ const allowed = request.master || (await isGlobalAdmin(request.user));
32
+ const { action, tenantId, userId } = request.params;
33
+ if ((action ?? "status") === "status") {
34
+ return allowed
35
+ ? { allowed: true, tenants: await (0, demoSeed_js_1.demoSeedStatus)() }
36
+ : { allowed: false, tenants: [] };
37
+ }
38
+ if (!allowed) {
39
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `${name}: only global administrators may seed demo data`);
40
+ }
41
+ const tenant = await (0, demoSeed_js_1.resolveTenant)(tenantId);
42
+ switch (action) {
43
+ case "users":
44
+ return (0, demoSeed_js_1.demoSeedUsers)(tenant);
45
+ case "seed":
46
+ return (0, demoSeed_js_1.seedDemoData)(tenant, await (0, demoSeed_js_1.resolveUser)(userId, tenant));
47
+ case "reset":
48
+ return { tenantId: tenant.id, removed: await (0, demoSeed_js_1.resetDemoData)(tenant) };
49
+ default:
50
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name}: unknown action "${action}"`);
51
+ }
52
+ }, { requireUser: true });
53
+ }
54
+ /** Direct member of `od-admin` — the role every ACL in this server grants. */
55
+ async function isGlobalAdmin(user) {
56
+ if (!user)
57
+ return false;
58
+ const role = await new node_1.default.Query(node_1.default.Role)
59
+ .equalTo("name", "od-admin")
60
+ .equalTo("users", user)
61
+ .first({ useMasterKey: true });
62
+ return !!role;
63
+ }
@@ -9,6 +9,7 @@ const index_js_1 = require("../features/schema/index.js");
9
9
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
10
10
  const index_js_2 = require("../features/permissions/index.js");
11
11
  const assignmentAcl_js_1 = require("../features/openservice/serviceSchedules/assignmentAcl.js");
12
+ const demoSeed_js_1 = require("../features/openservice/demoSeed/demoSeed.js");
12
13
  const index_js_3 = require("../features/openservice/serviceSchedules/calendarSync/index.js");
13
14
  const index_js_4 = require("../types/index.js");
14
15
  async function init() {
@@ -80,8 +81,8 @@ async function init() {
80
81
  // poller marks its own writes with this flag.
81
82
  if (context?.[index_js_3.CALENDAR_SYNC_CONTEXT_FLAG])
82
83
  return;
83
- // Seed data belongs to a demo tenant, not in anybody's calendar.
84
- if (object.get("seed"))
84
+ // Demo data belongs to a demo tenant, not in anybody's calendar.
85
+ if (context?.[demoSeed_js_1.DEMO_SEED_CONTEXT_FLAG])
85
86
  return;
86
87
  if (!original || calendarRelevantChange(object, original)) {
87
88
  // Deliberately not awaited: the calendar is a downstream system, and a
@@ -26,7 +26,6 @@ export interface Service_ScheduleAttributes {
26
26
  notifications: any[];
27
27
  origin?: string | undefined;
28
28
  pausedUntil?: Date | undefined;
29
- seed?: boolean | undefined;
30
29
  serviceProviders?: any[] | undefined;
31
30
  steps: any[];
32
31
  tenant: Tenant;
@@ -69,8 +68,6 @@ export declare class Service_Schedule extends Parse.Object<Service_ScheduleAttri
69
68
  set origin(value: string | undefined);
70
69
  get pausedUntil(): Date | undefined;
71
70
  set pausedUntil(value: Date | undefined);
72
- get seed(): boolean | undefined;
73
- set seed(value: boolean | undefined);
74
71
  get serviceProviders(): any[] | undefined;
75
72
  set serviceProviders(value: any[] | undefined);
76
73
  get steps(): any[];
@@ -109,12 +109,6 @@ class Service_Schedule extends node_1.default.Object {
109
109
  set pausedUntil(value) {
110
110
  super.set("pausedUntil", value);
111
111
  }
112
- get seed() {
113
- return super.get("seed");
114
- }
115
- set seed(value) {
116
- super.set("seed", value);
117
- }
118
112
  get serviceProviders() {
119
113
  return super.get("serviceProviders");
120
114
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.33.0",
3
+ "version": "4.34.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.16.1",
6
6
  "keywords": [
@@ -74,9 +74,6 @@
74
74
  "type": "Date",
75
75
  "required": false
76
76
  },
77
- "seed": {
78
- "type": "Boolean"
79
- },
80
77
  "serviceProviders": {
81
78
  "type": "Array"
82
79
  },