@openinc/parse-server-opendash 4.26.0 → 4.28.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 (29) hide show
  1. package/dist/features/notifications/services/sendMails.d.ts +5 -1
  2. package/dist/features/notifications/services/sendMails.js +6 -1
  3. package/dist/features/openservice/schedules/calendarSync/CalendarManager.d.ts +5 -0
  4. package/dist/features/openservice/schedules/calendarSync/CalendarManager.js +30 -0
  5. package/dist/features/openservice/schedules/calendarSync/Event.d.ts +5 -0
  6. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceCalendarSyncPoller.js +10 -1
  7. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceSyncTypes.d.ts +12 -0
  8. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.d.ts +119 -0
  9. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.js +159 -0
  10. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.d.ts +26 -0
  11. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.js +39 -0
  12. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.d.ts +43 -0
  13. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.js +187 -0
  14. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.d.ts +3 -0
  15. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.js +54 -12
  16. package/dist/features/openservice/tickets/ticketFormConfig.d.ts +18 -0
  17. package/dist/features/openservice/tickets/ticketFormConfig.js +27 -0
  18. package/dist/features/openservice/tickets/ticketPriority.d.ts +7 -6
  19. package/dist/features/openservice/tickets/ticketPriority.js +19 -13
  20. package/dist/features/openservice/tickets/ticketRuleTime.d.ts +18 -0
  21. package/dist/features/openservice/tickets/ticketRuleTime.js +68 -0
  22. package/dist/features/openservice/tickets/ticketRules.d.ts +32 -0
  23. package/dist/features/openservice/tickets/ticketRules.js +225 -0
  24. package/dist/functions/openinc-openservice-form-config.d.ts +4 -1
  25. package/dist/functions/openinc-openservice-form-config.js +6 -3
  26. package/dist/functions/openinc-openservice-notify-contacts.d.ts +2 -1
  27. package/dist/functions/openinc-openservice-notify-contacts.js +27 -13
  28. package/dist/hooks/Service_Ticket.js +15 -7
  29. package/package.json +2 -1
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncPlanExceptions = syncPlanExceptions;
4
+ exports.deleteMovedEvents = deleteMovedEvents;
5
+ exports.isMovedEvent = isMovedEvent;
6
+ const planToEvent_js_1 = require("./planToEvent.js");
7
+ const seriesExceptions_js_1 = require("./seriesExceptions.js");
8
+ const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
9
+ /**
10
+ * Bring a plan's moved and skipped dates and its pause into its Outlook series
11
+ * — the Graph half of `seriesExceptions.ts`, which explains the mapping.
12
+ *
13
+ * Called by `syncPlanToCalendar` after the series itself was written. Costs no
14
+ * Graph call for a plan that has no exceptions and never had any.
15
+ *
16
+ * Order matters in two places, both because of the poller, which turns every
17
+ * event it cannot place into a new plan and archives the plan of every series
18
+ * that disappears:
19
+ *
20
+ * - a rebuilt series is linked to the plan **before** the old one is deleted;
21
+ * - a stand-alone event for a moved date is linked right after it is created.
22
+ */
23
+ async function syncPlanExceptions({ manager, meta, series, input, exceptions, pausedUntil, now = new Date(), }) {
24
+ const values = (0, serviceCalendarMeta_js_1.metaValues)(meta);
25
+ const seriesId = values?.microsoftCalendarEventId;
26
+ if (!seriesId)
27
+ return;
28
+ const applied = values?.microsoftCalendarExceptions ?? seriesExceptions_js_1.EMPTY_APPLIED;
29
+ // A single appointment carries its exception itself (`singleEventStart`);
30
+ // whatever a former series left behind is cleaned up as if nothing were
31
+ // wanted.
32
+ const desired = series.recurrence
33
+ ? (0, seriesExceptions_js_1.desiredExceptions)(exceptions, pausedUntil, now)
34
+ : (0, seriesExceptions_js_1.desiredExceptions)(undefined, undefined, now);
35
+ const nothingWanted = desired.cancelDays.size === 0 &&
36
+ !desired.pausedUntil &&
37
+ desired.moved.length === 0;
38
+ if (nothingWanted &&
39
+ applied.cancelled.length === 0 &&
40
+ applied.moved.length === 0) {
41
+ return;
42
+ }
43
+ let eventId = seriesId;
44
+ let cancelled = (0, seriesExceptions_js_1.keptCancellations)(applied, desired, now);
45
+ if (series.recurrence && (0, seriesExceptions_js_1.needsRebuild)(applied, desired, now)) {
46
+ const rebuilt = await manager.createEvent(series);
47
+ if (!rebuilt?.id) {
48
+ console.error(`[ServiceCalendarSync] Could not rebuild series ${seriesId} — removed dates stay removed`);
49
+ }
50
+ else {
51
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
52
+ exceptions: { cancelled: [], moved: applied.moved },
53
+ eventId: rebuilt.id,
54
+ event: rebuilt,
55
+ });
56
+ await manager.deleteEvent(seriesId);
57
+ eventId = rebuilt.id;
58
+ cancelled = [];
59
+ }
60
+ }
61
+ const range = series.recurrence ? (0, seriesExceptions_js_1.cancelRange)(desired, now) : undefined;
62
+ if (range) {
63
+ const listed = await manager.fetchInstances(eventId, range.from, range.to);
64
+ if (!listed) {
65
+ console.error(`[ServiceCalendarSync] Could not list the occurrences of series ${eventId}`);
66
+ }
67
+ else {
68
+ // Whatever is listed exists — also an occurrence removed before, if
69
+ // rewriting the series brought it back — so it goes again.
70
+ const known = new Set(cancelled.map((entry) => entry.start));
71
+ const instances = listed
72
+ .map(toInstance)
73
+ .filter((instance) => !!instance);
74
+ for (const instance of (0, seriesExceptions_js_1.instancesToCancel)(instances, desired, now)) {
75
+ const start = instance.start.toISOString();
76
+ if (!(await manager.deleteEvent(instance.id)))
77
+ continue;
78
+ if (known.has(start))
79
+ continue;
80
+ cancelled.push({ day: (0, seriesExceptions_js_1.utcDay)(instance.start), start });
81
+ known.add(start);
82
+ }
83
+ }
84
+ }
85
+ const changes = (0, seriesExceptions_js_1.movedChanges)(applied.moved, desired.moved, now);
86
+ const moved = [...changes.keep];
87
+ for (const entry of changes.remove) {
88
+ await manager.deleteEvent(entry.eventId);
89
+ }
90
+ for (const { entry, target } of changes.update) {
91
+ const event = movedEvent(input, target);
92
+ const updated = event
93
+ ? await manager.updateEvent(entry.eventId, event)
94
+ : undefined;
95
+ // Kept even when the update failed: dropping the link would leave an event
96
+ // of ours the poller can no longer place. One deleted in Outlook is
97
+ // unlinked by the poller, and written again on the next save.
98
+ moved.push(updated ? { ...entry, moveTo: target.moveTo } : entry);
99
+ }
100
+ for (const target of changes.create) {
101
+ const event = movedEvent(input, target);
102
+ const created = event ? await manager.createEvent(event) : undefined;
103
+ if (!created?.id) {
104
+ console.error(`[ServiceCalendarSync] Could not write the moved date ${target.moveTo} of series ${eventId}`);
105
+ continue;
106
+ }
107
+ moved.push({
108
+ from: target.from,
109
+ moveTo: target.moveTo,
110
+ eventId: created.id,
111
+ });
112
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, { exceptions: { cancelled, moved } });
113
+ }
114
+ // Removing occurrences changed the series master; its new changeKey is ours.
115
+ const master = await manager.fetchEvent(eventId);
116
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
117
+ exceptions: { cancelled, moved },
118
+ event: master ?? undefined,
119
+ });
120
+ }
121
+ /**
122
+ * Delete the stand-alone events of a plan's moved dates — for a plan that
123
+ * leaves the calendar altogether.
124
+ */
125
+ async function deleteMovedEvents(manager, meta) {
126
+ const moved = (0, serviceCalendarMeta_js_1.metaValues)(meta)?.microsoftCalendarExceptions?.moved ?? [];
127
+ for (const entry of moved) {
128
+ await manager.deleteEvent(entry.eventId);
129
+ }
130
+ }
131
+ /**
132
+ * Whether an event stands in for a moved date. One that was deleted in Outlook
133
+ * is unlinked as well, so the next save writes it again instead of failing to
134
+ * update it forever.
135
+ */
136
+ async function isMovedEvent(eventId, options = {}) {
137
+ const meta = await (0, serviceCalendarMeta_js_1.findMetaForMovedEvent)(eventId);
138
+ if (!meta)
139
+ return false;
140
+ if (options.removed) {
141
+ const applied = (0, serviceCalendarMeta_js_1.metaValues)(meta)?.microsoftCalendarExceptions ?? seriesExceptions_js_1.EMPTY_APPLIED;
142
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
143
+ exceptions: {
144
+ cancelled: applied.cancelled,
145
+ moved: applied.moved.filter((entry) => entry.eventId !== eventId),
146
+ },
147
+ });
148
+ }
149
+ return true;
150
+ }
151
+ /**
152
+ * A moved date as its own appointment: the series' subject, reminder and
153
+ * checklist on the new date, with a note saying where it came from.
154
+ */
155
+ function movedEvent(input, target) {
156
+ const event = (0, planToEvent_js_1.planToEvent)({
157
+ ...input,
158
+ cadence: { kind: "rrule", dtstart: target.moveTo },
159
+ });
160
+ if (!event)
161
+ return undefined;
162
+ const [year, month, day] = (0, seriesExceptions_js_1.utcDay)(target.from).split("-");
163
+ const note = [
164
+ `Verschoben vom ${day}.${month}.${year}`,
165
+ target.reason ? `Grund: ${target.reason}` : undefined,
166
+ ]
167
+ .filter(Boolean)
168
+ .join("\n");
169
+ event.body = {
170
+ contentType: "Text",
171
+ content: [note, event.body?.content].filter(Boolean).join("\n\n"),
172
+ };
173
+ return event;
174
+ }
175
+ /** The original start of a listed occurrence. */
176
+ function toInstance(event) {
177
+ const fallback = event.start?.dateTime
178
+ ? event.start.dateTime.endsWith("Z")
179
+ ? event.start.dateTime
180
+ : `${event.start.dateTime.slice(0, 23)}Z`
181
+ : undefined;
182
+ const raw = event.originalStart ?? fallback;
183
+ if (!raw)
184
+ return undefined;
185
+ const start = new Date(raw);
186
+ return Number.isNaN(start.getTime()) ? undefined : { id: event.id, start };
187
+ }
@@ -18,6 +18,9 @@ import type { ServiceSyncConfigValues } from "./ServiceSyncTypes.js";
18
18
  * 3. plan already linked → the event is updated in place, keeping the time of
19
19
  * day someone gave it in Outlook;
20
20
  * 4. otherwise → a new event, and a meta entry that links the two.
21
+ *
22
+ * After 3 and 4 the plan's moved and skipped dates and its pause follow
23
+ * (`syncPlanExceptions`) — the series alone would show them on their old dates.
21
24
  */
22
25
  export declare function syncPlanToCalendar(plan: Service_Schedule): Promise<void>;
23
26
  export declare function connectionForTenant(tenant: Tenant | undefined): Promise<{
@@ -10,8 +10,10 @@ const CalendarManager_js_1 = require("../../schedules/calendarSync/CalendarManag
10
10
  const index_js_1 = require("../../../../types/index.js");
11
11
  const outlookRecurrence_js_1 = require("./outlookRecurrence.js");
12
12
  const planToEvent_js_1 = require("./planToEvent.js");
13
+ const seriesExceptions_js_1 = require("./seriesExceptions.js");
13
14
  const ServiceSyncTypes_js_1 = require("./ServiceSyncTypes.js");
14
15
  const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
16
+ const syncPlanExceptions_js_1 = require("./syncPlanExceptions.js");
15
17
  /**
16
18
  * Write a maintenance plan into the tenant's Outlook calendar.
17
19
  *
@@ -29,6 +31,9 @@ const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
29
31
  * 3. plan already linked → the event is updated in place, keeping the time of
30
32
  * day someone gave it in Outlook;
31
33
  * 4. otherwise → a new event, and a meta entry that links the two.
34
+ *
35
+ * After 3 and 4 the plan's moved and skipped dates and its pause follow
36
+ * (`syncPlanExceptions`) — the series alone would show them on their old dates.
32
37
  */
33
38
  async function syncPlanToCalendar(plan) {
34
39
  const connection = await connectionForTenant(plan.get("tenant"));
@@ -44,35 +49,72 @@ async function syncPlanToCalendar(plan) {
44
49
  const meta = await (0, serviceCalendarMeta_js_1.findMetaForPlan)(plan.id);
45
50
  const values = meta ? (0, serviceCalendarMeta_js_1.metaValues)(meta) : undefined;
46
51
  const eventId = values?.microsoftCalendarEventId;
52
+ const exceptions = plan.get("cadenceExceptions");
53
+ const pausedUntil = plan.get("pausedUntil") ?? undefined;
54
+ const now = new Date();
47
55
  const retired = !!plan.get("deletedAt") || plan.get("active") === false;
56
+ const input = {
57
+ title: plan.get("title"),
58
+ cadence: plan.get("cadence"),
59
+ steps: plan.get("steps"),
60
+ notifications: plan.get("notifications"),
61
+ equipmentName: await equipmentLabel(plan),
62
+ snapshot: values?.microsoftCalendarEvent,
63
+ };
48
64
  const event = retired
49
65
  ? undefined
50
- : (0, planToEvent_js_1.planToEvent)({
51
- title: plan.get("title"),
52
- cadence: plan.get("cadence"),
53
- steps: plan.get("steps"),
54
- notifications: plan.get("notifications"),
55
- equipmentName: await equipmentLabel(plan),
56
- snapshot: values?.microsoftCalendarEvent,
57
- });
66
+ : planEvent(input, exceptions, pausedUntil, now);
58
67
  if (!event) {
59
68
  if (meta && eventId) {
60
69
  await connection.manager.deleteEvent(eventId);
70
+ await (0, syncPlanExceptions_js_1.deleteMovedEvents)(connection.manager, meta);
61
71
  await meta.destroy({ useMasterKey: true });
62
72
  }
63
73
  return;
64
74
  }
75
+ let entry = meta;
65
76
  if (meta && eventId) {
66
77
  const updated = await connection.manager.updateEvent(eventId, event);
67
78
  if (updated?.changeKey) {
68
79
  await (0, serviceCalendarMeta_js_1.updateChangeKey)(meta, updated.changeKey, updated);
69
80
  }
70
- return;
71
81
  }
72
- const created = await connection.manager.createEvent(event);
73
- if (!created?.id)
82
+ else {
83
+ const created = await connection.manager.createEvent(event);
84
+ if (!created?.id)
85
+ return;
86
+ entry = await (0, serviceCalendarMeta_js_1.saveMeta)(plan.id, created.id, created.changeKey, plan.get("tenant"), created);
87
+ }
88
+ if (!entry)
74
89
  return;
75
- await (0, serviceCalendarMeta_js_1.saveMeta)(plan.id, created.id, created.changeKey, plan.get("tenant"), created);
90
+ await (0, syncPlanExceptions_js_1.syncPlanExceptions)({
91
+ manager: connection.manager,
92
+ meta: entry,
93
+ series: event,
94
+ input,
95
+ exceptions,
96
+ pausedUntil,
97
+ now,
98
+ });
99
+ }
100
+ /**
101
+ * The plan as an event, with a single appointment's own exception applied — it
102
+ * has no series for `syncPlanExceptions` to change. `undefined` when there is
103
+ * nothing to show: no date, or a single date that was skipped or paused.
104
+ */
105
+ function planEvent(input, exceptions, pausedUntil, now) {
106
+ const event = (0, planToEvent_js_1.planToEvent)(input);
107
+ if (!event || event.recurrence || !input.cadence)
108
+ return event;
109
+ const start = (0, seriesExceptions_js_1.singleEventStart)(input.cadence.dtstart, exceptions, pausedUntil, now);
110
+ if (start === null)
111
+ return undefined;
112
+ if (start === undefined)
113
+ return event;
114
+ return (0, planToEvent_js_1.planToEvent)({
115
+ ...input,
116
+ cadence: { ...input.cadence, dtstart: start },
117
+ });
76
118
  }
77
119
  /** The machine's label, for the subject prefix — `undefined` if it has none. */
78
120
  async function equipmentLabel(plan) {
@@ -18,3 +18,21 @@ import { Service_FormConfig, type Tenant } from "../../../types/index.js";
18
18
  * key, "all configs" would be every tenant's.
19
19
  */
20
20
  export declare function applicableFormConfig(tenant: Tenant | undefined, user: Parse.User | undefined): Promise<Service_FormConfig | undefined>;
21
+ /**
22
+ * The config a save names in its context (`{ formConfig: <id> }`): the one
23
+ * the form that saves was showing — the ticket forms of the frontend send it.
24
+ * `undefined` when the save names none, or one that does not count:
25
+ *
26
+ * - read with the caller's own rights, so only a config the caller may read
27
+ * (its audience, the tenant's global default, an admin) — the same check
28
+ * the QR flow makes in the browser;
29
+ * - of the ticket's own tenant: a cross-tenant admin may read another
30
+ * tenant's configs, which say nothing about this ticket.
31
+ *
32
+ * Read by id rather than resolved: one query, and exactly the config the form
33
+ * showed, in its current version.
34
+ */
35
+ export declare function configFromContext(id: unknown, tenant: Tenant | undefined, { master, sessionToken, }: {
36
+ master: boolean;
37
+ sessionToken: string | undefined;
38
+ }): Promise<Service_FormConfig | undefined>;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.applicableFormConfig = applicableFormConfig;
7
+ exports.configFromContext = configFromContext;
7
8
  // Which ticket form config applies to a user. The frontend asks this through
8
9
  // `openinc-openservice-form-config`, and the ticket hook reads the priority
9
10
  // formula out of the same answer, so both always work with the same config.
@@ -72,3 +73,29 @@ async function findRoleMatch(configs, user) {
72
73
  .map((role) => role.id));
73
74
  return configs.find((c) => (0, openservice_shared_1.refIds)(c.roles).some((id) => heldIds.has(id)));
74
75
  }
76
+ /**
77
+ * The config a save names in its context (`{ formConfig: <id> }`): the one
78
+ * the form that saves was showing — the ticket forms of the frontend send it.
79
+ * `undefined` when the save names none, or one that does not count:
80
+ *
81
+ * - read with the caller's own rights, so only a config the caller may read
82
+ * (its audience, the tenant's global default, an admin) — the same check
83
+ * the QR flow makes in the browser;
84
+ * - of the ticket's own tenant: a cross-tenant admin may read another
85
+ * tenant's configs, which say nothing about this ticket.
86
+ *
87
+ * Read by id rather than resolved: one query, and exactly the config the form
88
+ * showed, in its current version.
89
+ */
90
+ async function configFromContext(id, tenant, { master, sessionToken, }) {
91
+ if (typeof id !== "string" || !id)
92
+ return undefined;
93
+ if (!master && !sessionToken)
94
+ return undefined;
95
+ const config = await new node_1.default.Query(index_js_1.Service_FormConfig)
96
+ .equalTo("objectId", id)
97
+ .first(master ? { useMasterKey: true } : { sessionToken });
98
+ if (!config)
99
+ return undefined;
100
+ return config.tenant?.id === tenant?.id ? config : undefined;
101
+ }
@@ -28,20 +28,21 @@ export declare function priorityFormulaOf(config: Service_FormConfig | undefined
28
28
  * `undefined` as well.
29
29
  */
30
30
  export declare function computePriority(formula: PriorityFormula, values: (key: string) => unknown): number | undefined;
31
+ /** Whether this save changes one of the inputs a priority formula reads. */
32
+ export declare function changesPriorityInputs(object: Parse.Object, original: Parse.Object | undefined): boolean;
31
33
  /**
32
- * Sets the computed priority on a ticket being saved, under the form config
33
- * that applies to the user saving it (see `applicableFormConfig`).
34
+ * Sets the computed priority on a ticket being saved, under `config` — the
35
+ * form config that applies to the user saving (see `applicableFormConfig`).
34
36
  *
35
37
  * Only when this save changes one of the inputs — a ticket the save does not
36
38
  * reassess keeps its priority, also when the formula has changed since — and
37
- * only when the caller does not set the priority itself in the same save:
38
- * the ticket forms send the value they computed and showed, and an import
39
- * keeps the priority its file states.
39
+ * only when the caller does not set the priority itself in the same save: an
40
+ * import keeps the priority its file states.
40
41
  *
41
42
  * "Changes" and "sets" are judged against `original`. The admin table sends
42
43
  * every field of its form, the unchanged priority included; counting that as
43
44
  * set by hand would leave the old priority after every factor edit there —
44
45
  * which is the case this exists for.
45
46
  */
46
- export declare function applyComputedPriority(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined): Promise<void>;
47
+ export declare function applyComputedPriority(object: Parse.Object, original: Parse.Object | undefined, config: Service_FormConfig | undefined): void;
47
48
  export {};
@@ -3,9 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PRIORITY_FORMULA_INPUTS = void 0;
4
4
  exports.priorityFormulaOf = priorityFormulaOf;
5
5
  exports.computePriority = computePriority;
6
+ exports.changesPriorityInputs = changesPriorityInputs;
6
7
  exports.applyComputedPriority = applyComputedPriority;
7
8
  const ruleset_core_1 = require("@opendash/ruleset-core");
8
- const ticketFormConfig_js_1 = require("./ticketFormConfig.js");
9
9
  /**
10
10
  * The fields a priority formula may read, e.g.
11
11
  * `max(downtime, restriction) * 0.7 + frequency * 0.3`. Mirrors
@@ -71,30 +71,36 @@ function computePriority(formula, values) {
71
71
  return undefined;
72
72
  return Math.round(Math.min(100, Math.max(0, result)));
73
73
  }
74
+ /** Whether this save changes `key`, judged against the stored ticket. */
75
+ function changes(object, original, key) {
76
+ return original
77
+ ? object.get(key) !== original.get(key)
78
+ : object.get(key) != null;
79
+ }
80
+ /** Whether this save changes one of the inputs a priority formula reads. */
81
+ function changesPriorityInputs(object, original) {
82
+ return exports.PRIORITY_FORMULA_INPUTS.some((key) => changes(object, original, key));
83
+ }
74
84
  /**
75
- * Sets the computed priority on a ticket being saved, under the form config
76
- * that applies to the user saving it (see `applicableFormConfig`).
85
+ * Sets the computed priority on a ticket being saved, under `config` — the
86
+ * form config that applies to the user saving (see `applicableFormConfig`).
77
87
  *
78
88
  * Only when this save changes one of the inputs — a ticket the save does not
79
89
  * reassess keeps its priority, also when the formula has changed since — and
80
- * only when the caller does not set the priority itself in the same save:
81
- * the ticket forms send the value they computed and showed, and an import
82
- * keeps the priority its file states.
90
+ * only when the caller does not set the priority itself in the same save: an
91
+ * import keeps the priority its file states.
83
92
  *
84
93
  * "Changes" and "sets" are judged against `original`. The admin table sends
85
94
  * every field of its form, the unchanged priority included; counting that as
86
95
  * set by hand would leave the old priority after every factor edit there —
87
96
  * which is the case this exists for.
88
97
  */
89
- async function applyComputedPriority(object, original, user) {
90
- const before = (key) => original?.get(key);
91
- const changes = (key) => object.isNew() ? object.get(key) != null : object.get(key) !== before(key);
92
- if (!exports.PRIORITY_FORMULA_INPUTS.some(changes))
98
+ function applyComputedPriority(object, original, config) {
99
+ if (!changesPriorityInputs(object, original))
93
100
  return;
94
- if (changes("priority"))
101
+ if (changes(object, original, "priority"))
95
102
  return;
96
- const tenant = object.get("tenant");
97
- const formula = priorityFormulaOf(await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user));
103
+ const formula = priorityFormulaOf(config);
98
104
  if (!formula)
99
105
  return;
100
106
  const priority = computePriority(formula, (key) => object.get(key));
@@ -0,0 +1,18 @@
1
+ /** The zone ticket rules are evaluated in. */
2
+ export declare const RULE_TIME_ZONE: string;
3
+ /** Units of a relative date value. Mirrors `RelativeUnit` of the frontend. */
4
+ export type RelativeUnit = "minutes" | "hours" | "days" | "weeks";
5
+ /**
6
+ * `instant` as a `Date` whose *local* getters read the zone's wall clock.
7
+ *
8
+ * `@opendash/ruleset-core` compares dates in local time — a rule's
9
+ * "YYYY-MM-DD" is local midnight, "equals" compares local calendar days. Fed
10
+ * these, it compares on the zone's calendar whatever the process runs in.
11
+ */
12
+ export declare function inRuleZone(instant: Date): Date;
13
+ /**
14
+ * `now` moved by a relative rule value, the way dayjs does it in the browser:
15
+ * minutes and hours as elapsed time, days and weeks on the zone's calendar —
16
+ * "in 1 day" across a daylight-saving change keeps the time of day.
17
+ */
18
+ export declare function addRelative(now: Date, amount: number, unit: RelativeUnit): Date;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ // Time for the ticket rules: the browser evaluates and computes them in the
3
+ // user's local time, so the server does the same in the zone the users live
4
+ // in rather than in the container's UTC.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RULE_TIME_ZONE = void 0;
7
+ exports.inRuleZone = inRuleZone;
8
+ exports.addRelative = addRelative;
9
+ /** The zone ticket rules are evaluated in. */
10
+ exports.RULE_TIME_ZONE = process.env.OPENSERVICE_TIME_ZONE || "Europe/Berlin";
11
+ const formatter = new Intl.DateTimeFormat("en-US", {
12
+ timeZone: exports.RULE_TIME_ZONE,
13
+ hourCycle: "h23",
14
+ year: "numeric",
15
+ month: "2-digit",
16
+ day: "2-digit",
17
+ hour: "2-digit",
18
+ minute: "2-digit",
19
+ second: "2-digit",
20
+ });
21
+ /** What a clock in {@link RULE_TIME_ZONE} shows at `instant`. */
22
+ function wallClock(instant) {
23
+ const parts = formatter.formatToParts(instant);
24
+ const part = (type) => Number(parts.find((p) => p.type === type)?.value);
25
+ return {
26
+ year: part("year"),
27
+ month: part("month"),
28
+ day: part("day"),
29
+ hour: part("hour"),
30
+ minute: part("minute"),
31
+ second: part("second"),
32
+ ms: instant.getUTCMilliseconds(),
33
+ };
34
+ }
35
+ /** How far the zone is ahead of UTC at `instant`, in ms. */
36
+ function zoneOffset(instant) {
37
+ const w = wallClock(instant);
38
+ return (Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms) -
39
+ instant.getTime());
40
+ }
41
+ /**
42
+ * `instant` as a `Date` whose *local* getters read the zone's wall clock.
43
+ *
44
+ * `@opendash/ruleset-core` compares dates in local time — a rule's
45
+ * "YYYY-MM-DD" is local midnight, "equals" compares local calendar days. Fed
46
+ * these, it compares on the zone's calendar whatever the process runs in.
47
+ */
48
+ function inRuleZone(instant) {
49
+ const w = wallClock(instant);
50
+ return new Date(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms);
51
+ }
52
+ /**
53
+ * `now` moved by a relative rule value, the way dayjs does it in the browser:
54
+ * minutes and hours as elapsed time, days and weeks on the zone's calendar —
55
+ * "in 1 day" across a daylight-saving change keeps the time of day.
56
+ */
57
+ function addRelative(now, amount, unit) {
58
+ if (unit === "minutes")
59
+ return new Date(now.getTime() + amount * 60_000);
60
+ if (unit === "hours")
61
+ return new Date(now.getTime() + amount * 3_600_000);
62
+ const days = unit === "weeks" ? amount * 7 : amount;
63
+ const w = wallClock(now);
64
+ const target = Date.UTC(w.year, w.month - 1, w.day + days, w.hour, w.minute, w.second, w.ms);
65
+ // The target's offset may differ from today's; one correction settles it.
66
+ const first = target - zoneOffset(new Date(target));
67
+ return new Date(target - zoneOffset(new Date(first)));
68
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * When a rule acts. Mirrors `RuleTrigger` of the frontend.
3
+ *
4
+ * - `create`: when the ticket is created.
5
+ * - `becomes`: when its condition starts to hold — on creation if it holds,
6
+ * later when a save makes it hold that did not before.
7
+ * - `always`: on every save while the condition holds. A rule stored without
8
+ * a trigger predates the choice and keeps this behaviour.
9
+ */
10
+ export type RuleTrigger = "create" | "becomes" | "always";
11
+ /**
12
+ * What a form config does to a ticket on save, in the order the frontend used
13
+ * to apply it: the computed priority, the field value rules, the action rules
14
+ * — so a rule on the priority sees the computed one.
15
+ *
16
+ * Which config: the one the form that saves was showing, when it names it in
17
+ * the save's context (`{ formConfig: <id> }`, see `configFromContext`) — a
18
+ * form opened by QR code shows another config than the user's own, and its
19
+ * rules are what the user saw. Otherwise (the admin table, the REST API, an
20
+ * alarm) the one that applies to the user saving (`applicableFormConfig`).
21
+ *
22
+ * The rules act on a save somebody makes — a person, an integration, an alarm
23
+ * creating a ticket. Not on the server's own bookkeeping: a master-key update
24
+ * (sort keys pushed down, the scheduler archiving) would otherwise re-assign
25
+ * people that were taken off by hand, through an "always" rule. The priority
26
+ * follows its inputs on any save.
27
+ */
28
+ export declare function applyFormConfigRules(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined, { master, sessionToken, context, }: {
29
+ master: boolean;
30
+ sessionToken: string | undefined;
31
+ context: Record<string, unknown> | undefined;
32
+ }): Promise<void>;