@openinc/parse-server-opendash 4.24.1 → 4.26.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 (55) hide show
  1. package/dist/features/config/helper/getConfig.js +2 -1
  2. package/dist/features/config/types/ConfigKeys.js +8 -26
  3. package/dist/features/openservice/alarms/ticket/AlarmTicketTypes.d.ts +0 -4
  4. package/dist/features/openservice/alarms/ticket/AlarmTicketTypes.js +1 -5
  5. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +6 -5
  6. package/dist/features/openservice/tickets/ticketAccess.d.ts +40 -0
  7. package/dist/features/openservice/tickets/ticketAccess.js +105 -0
  8. package/dist/features/openservice/tickets/ticketArchive.d.ts +54 -0
  9. package/dist/features/openservice/tickets/ticketArchive.js +112 -0
  10. package/dist/features/openservice/tickets/ticketCleanup.d.ts +25 -0
  11. package/dist/features/openservice/tickets/ticketCleanup.js +65 -0
  12. package/dist/features/openservice/tickets/ticketFormConfig.d.ts +20 -0
  13. package/dist/features/openservice/tickets/ticketFormConfig.js +74 -0
  14. package/dist/features/openservice/tickets/ticketNotifications.d.ts +2 -0
  15. package/dist/features/openservice/tickets/ticketNotifications.js +242 -0
  16. package/dist/features/openservice/tickets/ticketNumber.d.ts +12 -0
  17. package/dist/features/openservice/tickets/ticketNumber.js +75 -0
  18. package/dist/features/openservice/tickets/ticketPriority.d.ts +47 -0
  19. package/dist/features/openservice/tickets/ticketPriority.js +103 -0
  20. package/dist/features/openservice/tickets/ticketReferences.d.ts +61 -0
  21. package/dist/features/openservice/tickets/ticketReferences.js +235 -0
  22. package/dist/features/permissions/types/Permissions.d.ts +1 -0
  23. package/dist/features/permissions/types/Permissions.js +5 -2
  24. package/dist/features/schema/indexes.js +22 -2
  25. package/dist/features/schema/services/ensureIndexes.js +11 -2
  26. package/dist/functions/openinc-backfill-ticket-sort-keys.d.ts +3 -2
  27. package/dist/functions/openinc-backfill-ticket-sort-keys.js +3 -2
  28. package/dist/functions/openinc-openservice-form-config.d.ts +20 -0
  29. package/dist/functions/openinc-openservice-form-config.js +51 -0
  30. package/dist/helper/getUserLanguage.d.ts +3 -5
  31. package/dist/helper/getUserLanguage.js +7 -16
  32. package/dist/helper/roleNames.d.ts +7 -0
  33. package/dist/helper/roleNames.js +21 -0
  34. package/dist/helper/ticketSortKeys.d.ts +8 -9
  35. package/dist/helper/ticketSortKeys.js +21 -23
  36. package/dist/helper/updateWithoutTriggers.d.ts +22 -0
  37. package/dist/helper/updateWithoutTriggers.js +57 -0
  38. package/dist/hooks/Chat_Message.js +7 -30
  39. package/dist/hooks/Meta_Entry.js +6 -1
  40. package/dist/hooks/Service_Equipment.js +2 -1
  41. package/dist/hooks/Service_FormConfig.js +6 -5
  42. package/dist/hooks/Service_Project.js +2 -1
  43. package/dist/hooks/Service_Status.js +3 -6
  44. package/dist/hooks/Service_Tag.js +51 -11
  45. package/dist/hooks/Service_Ticket.js +45 -702
  46. package/dist/scripts/migration/lib/ptr.d.ts +1 -1
  47. package/dist/scripts/migration/lib/ptr.js +3 -5
  48. package/dist/scripts/migration/lib/ticket.js +3 -2
  49. package/dist/scripts/repair-ticket-acl.js +3 -3
  50. package/dist/types/Service_Ticket.d.ts +6 -0
  51. package/dist/types/Service_Ticket.js +12 -0
  52. package/package.json +3 -1
  53. package/schema/Service_Ticket.json +6 -0
  54. package/dist/helper/pointerIds.d.ts +0 -17
  55. package/dist/helper/pointerIds.js +0 -45
@@ -0,0 +1,74 @@
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.applicableFormConfig = applicableFormConfig;
7
+ // Which ticket form config applies to a user. The frontend asks this through
8
+ // `openinc-openservice-form-config`, and the ticket hook reads the priority
9
+ // formula out of the same answer, so both always work with the same config.
10
+ const node_1 = __importDefault(require("parse/node"));
11
+ const openservice_shared_1 = require("@opendash/openservice-shared");
12
+ const index_js_1 = require("../../../types/index.js");
13
+ const aclAccess_js_1 = require("../../../helper/aclAccess.js");
14
+ /** More configs per tenant would not be a form any more but a mistake. */
15
+ const MAX_CONFIGS = 1000;
16
+ /**
17
+ * The form config that applies to `user` in `tenant`, or `undefined` when
18
+ * none does — the frontend then uses its built-in form.
19
+ *
20
+ * Highest `priority` first, and in that order:
21
+ * 1. a config naming the user,
22
+ * 2. a config naming one of the user's roles, inherited ones included,
23
+ * 3. the tenant's global default (a config naming nobody).
24
+ *
25
+ * Read with the master key. The browser cannot do the role step itself: it
26
+ * knows its roles by name, a config names them by id, and a role the user may
27
+ * not read cannot be looked up — comparing the two never matched, so a config
28
+ * for a role silently never applied. Without a user (a master-key write) only
29
+ * the global default can apply.
30
+ *
31
+ * Without a tenant only configs without one are considered: with the master
32
+ * key, "all configs" would be every tenant's.
33
+ */
34
+ async function applicableFormConfig(tenant, user) {
35
+ const query = new node_1.default.Query(index_js_1.Service_FormConfig).limit(MAX_CONFIGS);
36
+ if (tenant)
37
+ query.equalTo("tenant", tenant);
38
+ else
39
+ query.doesNotExist("tenant");
40
+ // Stable on equal priority: the older config wins, on every call alike.
41
+ const configs = (await query.ascending("createdAt").find({
42
+ useMasterKey: true,
43
+ })).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
44
+ if (configs.length === 0)
45
+ return undefined;
46
+ const userId = user?.id;
47
+ if (user && userId) {
48
+ const userMatch = configs.find((c) => (0, openservice_shared_1.refIds)(c.users).includes(userId));
49
+ if (userMatch)
50
+ return userMatch;
51
+ const roleMatch = await findRoleMatch(configs, user);
52
+ if (roleMatch)
53
+ return roleMatch;
54
+ }
55
+ return configs.find((c) => (0, openservice_shared_1.refIds)(c.users).length === 0 && (0, openservice_shared_1.refIds)(c.roles).length === 0);
56
+ }
57
+ /** The first config naming one of the user's roles (see `userRoleNames`). */
58
+ async function findRoleMatch(configs, user) {
59
+ const roleIds = [...new Set(configs.flatMap((c) => (0, openservice_shared_1.refIds)(c.roles)))];
60
+ if (roleIds.length === 0)
61
+ return undefined;
62
+ const [held, roles] = await Promise.all([
63
+ (0, aclAccess_js_1.userRoleNames)(user),
64
+ new node_1.default.Query(node_1.default.Role)
65
+ .containedIn("objectId", roleIds)
66
+ .limit(roleIds.length)
67
+ .find({ useMasterKey: true }),
68
+ ]);
69
+ const heldNames = new Set(held);
70
+ const heldIds = new Set(roles
71
+ .filter((role) => heldNames.has(role.getName() ?? ""))
72
+ .map((role) => role.id));
73
+ return configs.find((c) => (0, openservice_shared_1.refIds)(c.roles).some((id) => heldIds.has(id)));
74
+ }
@@ -0,0 +1,2 @@
1
+ /** The assignee and watcher notifications of one save. Never throws. */
2
+ export declare function notifyAboutSave(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined): Promise<void>;
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.notifyAboutSave = notifyAboutSave;
40
+ // The notifications a ticket save sends: to new assignees, and to the
41
+ // watchers the tenant's rules name.
42
+ const node_1 = __importStar(require("parse/node"));
43
+ const i18next_1 = __importDefault(require("i18next"));
44
+ const appLinks_js_1 = require("../../../helper/appLinks.js");
45
+ const getUserLanguage_js_1 = require("../../../helper/getUserLanguage.js");
46
+ const index_js_1 = require("../../../types/index.js");
47
+ const openservice_shared_1 = require("@opendash/openservice-shared");
48
+ const ruleset_core_1 = require("@opendash/ruleset-core");
49
+ /** The assignee and watcher notifications of one save. Never throws. */
50
+ async function notifyAboutSave(object, original, user) {
51
+ try {
52
+ // Shared across the assignee + watcher passes so a user who is both an
53
+ // assignee and a matched watcher is notified only once (assignee first).
54
+ const notified = new Set();
55
+ if (user?.id)
56
+ notified.add(user.id); // never notify the acting user
57
+ const assignerName = getUsername(user);
58
+ await notifyNewAssignees(object, original, notified, assignerName);
59
+ // Conditional "watcher" rules are evaluated on ticket creation only for
60
+ // now — re-evaluating them on every edit (and tracking who was already
61
+ // notified across edits) is deferred.
62
+ if (!original) {
63
+ await notifyWatchers(object, notified, assignerName);
64
+ }
65
+ }
66
+ catch (error) {
67
+ console.error("[@openinc/parse-server-opendash][Service_Ticket] Failed to notify on assignment", error);
68
+ }
69
+ }
70
+ /**
71
+ * Notifies the users and roles that were newly assigned to a ticket.
72
+ *
73
+ * Runs on every save and diffs the current `assignedUsers`/`assignedRoles`
74
+ * (arrays of pointers) against the previous version (`original`). On creation
75
+ * `original` is undefined, so everyone assigned is new; on an edit only the
76
+ * added assignees are notified, so re-saving a ticket never re-notifies people
77
+ * who were already assigned.
78
+ *
79
+ * Dedup + precedence mirror the chat-mention feature: one notification per user,
80
+ * directly assigned users win over role membership (`users` > `roles`), and the
81
+ * acting user (whoever performed the save) is never notified.
82
+ */
83
+ async function notifyNewAssignees(ticket, original, notified, assignerName) {
84
+ const newUserIds = addedIds(ticket.get("assignedUsers"), original?.get("assignedUsers"));
85
+ const newRoleIds = addedIds(ticket.get("assignedRoles"), original?.get("assignedRoles"));
86
+ if (newUserIds.length === 0 && newRoleIds.length === 0)
87
+ return;
88
+ await notifyRecipients(newUserIds, newRoleIds, notified, ticket, {
89
+ variant: "assigned",
90
+ assignerName,
91
+ });
92
+ }
93
+ /** OD3_Config key holding the per-tenant assignment-notification rules. */
94
+ const ASSIGNMENT_NOTIFICATION_CONFIG_KEY = openservice_shared_1.TICKET_CONFIG_KEYS.assignmentNotifications;
95
+ /**
96
+ * Notifies the configured "watchers": users/roles that a conditional ruleset
97
+ * says should hear about a ticket, independent of assignment. The rules live in
98
+ * a per-tenant {@link Config} row (`OPENSERVICE_ASSIGNMENT_NOTIFICATIONS`) as a
99
+ * JSON array of RuleSet function entries authored in the frontend admin. Each
100
+ * matching rule's assignees (`user:<id>` / `role:<id>`) are notified, deduped
101
+ * against the shared `notified` set (so assignees already handled win).
102
+ */
103
+ async function notifyWatchers(ticket, notified, assignerName) {
104
+ const rules = await loadWatcherRules(ticket.get("tenant"));
105
+ if (rules.length === 0)
106
+ return;
107
+ const getValue = (field) => ticket.get(field);
108
+ for (const rule of rules) {
109
+ if (rule.function !== "notify" || !rule.ruleset)
110
+ continue;
111
+ if (!(0, ruleset_core_1.applyRuleSet)(rule.ruleset, getValue))
112
+ continue;
113
+ const assignees = Array.isArray(rule.params?.assignees)
114
+ ? rule.params.assignees
115
+ : [];
116
+ const userIds = assignees
117
+ .filter((a) => a.startsWith("user:"))
118
+ .map((a) => a.slice(5));
119
+ const roleIds = assignees
120
+ .filter((a) => a.startsWith("role:"))
121
+ .map((a) => a.slice(5));
122
+ await notifyRecipients(userIds, roleIds, notified, ticket, {
123
+ variant: "watcher",
124
+ assignerName,
125
+ frontpage: rule.params?.frontpage === true,
126
+ });
127
+ }
128
+ }
129
+ /** Loads and parses the tenant's assignment-notification rules. */
130
+ async function loadWatcherRules(tenant) {
131
+ if (!tenant)
132
+ return [];
133
+ const config = await new node_1.default.Query(index_js_1.Config)
134
+ .equalTo("key", ASSIGNMENT_NOTIFICATION_CONFIG_KEY)
135
+ .equalTo("tenant", tenant)
136
+ .first({ useMasterKey: true });
137
+ const raw = config?.get("value");
138
+ if (typeof raw !== "string")
139
+ return [];
140
+ try {
141
+ const parsed = JSON.parse(raw);
142
+ return Array.isArray(parsed) ? parsed : [];
143
+ }
144
+ catch {
145
+ return [];
146
+ }
147
+ }
148
+ /**
149
+ * Resolves a set of user ids + role ids to concrete recipients and sends one
150
+ * notification each, skipping anyone already in `notified`. Directly listed
151
+ * users take precedence over users reached via a role. `notified` is mutated so
152
+ * callers can chain multiple passes (assignees, then watchers) with shared
153
+ * de-duplication.
154
+ */
155
+ async function notifyRecipients(userIds, roleIds, notified, ticket, options) {
156
+ const users = userIds.length
157
+ ? await new node_1.default.Query(node_1.default.User)
158
+ .containedIn("objectId", userIds)
159
+ .findAll({ useMasterKey: true })
160
+ : [];
161
+ for (const user of users) {
162
+ if (!user.id || notified.has(user.id))
163
+ continue;
164
+ notified.add(user.id);
165
+ await sendAssignmentNotification(user, ticket, options);
166
+ }
167
+ const roles = roleIds.length
168
+ ? await new node_1.default.Query(node_1.Role)
169
+ .containedIn("objectId", roleIds)
170
+ .findAll({ useMasterKey: true })
171
+ : [];
172
+ for (const role of roles) {
173
+ const members = await role
174
+ .relation("users")
175
+ .query()
176
+ .findAll({ useMasterKey: true });
177
+ for (const member of members) {
178
+ if (!member.id || notified.has(member.id))
179
+ continue;
180
+ notified.add(member.id);
181
+ await sendAssignmentNotification(member, ticket, options);
182
+ }
183
+ }
184
+ }
185
+ /**
186
+ * Builds and saves a single assignment notification, translated into the
187
+ * recipient's preferred language. Delivery (email + web push) is handled
188
+ * automatically by the {@link Notification} afterSave hook.
189
+ *
190
+ * The deep link lives in `data.url` rather than inside the description text:
191
+ * the frontend opens the ticket from `data.ticketId` (see
192
+ * `TicketNotificationActionAdapter`) and would only render a raw URL as noise,
193
+ * while the notification email appends `data.url` — resolved against the
194
+ * recipient's tenant host — to the body.
195
+ */
196
+ async function sendAssignmentNotification(user, ticket, options) {
197
+ // A translator fixed to the recipient's language rather than
198
+ // `i18next.changeLanguage`, which is global: two notifications in flight at
199
+ // once could each end up in the other's language.
200
+ const t = i18next_1.default.getFixedT(await (0, getUserLanguage_js_1.getUserLanguage)(user));
201
+ const base = `openservice:ticket.assignment.${options.variant}`;
202
+ const ticketName = ticket.get("title");
203
+ await new index_js_1.Notification({
204
+ title: t(`${base}.title`),
205
+ description: t(`${base}.description`, {
206
+ username: options.assignerName,
207
+ ticketName,
208
+ }),
209
+ type: options.frontpage ? "frontpage" : "mailbox",
210
+ data: {
211
+ ticketId: ticket.id,
212
+ url: (0, appLinks_js_1.ticketPath)(ticket.id),
213
+ translation: {
214
+ username: options.assignerName,
215
+ ticketName,
216
+ ticketId: ticket.id,
217
+ },
218
+ },
219
+ user: user,
220
+ isSent: false,
221
+ }).save(null, { useMasterKey: true });
222
+ }
223
+ /** Ids present in `current` (array of pointers) but not in `previous`. */
224
+ function addedIds(current, previous) {
225
+ const previousIds = new Set((0, openservice_shared_1.refIds)(previous));
226
+ return (0, openservice_shared_1.refIds)(current).filter((id) => !previousIds.has(id));
227
+ }
228
+ function getUsername(user) {
229
+ if (!user)
230
+ return "System";
231
+ let username = "";
232
+ if (user?.get("firstname") && user?.get("lastname")) {
233
+ username = user?.get("firstname") + " " + user?.get("lastname");
234
+ }
235
+ else if (user?.get("name")) {
236
+ username = user.get("name");
237
+ }
238
+ else if (user?.getUsername()) {
239
+ username = user?.getUsername();
240
+ }
241
+ return username ?? "System";
242
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Assigns a sequential `number` to a new ticket.
3
+ *
4
+ * - With a project: atomically increments that project's `ticketCounter` and
5
+ * uses the result, so numbers are per-project sequences.
6
+ * - Without a project: falls back to a per-tenant counter
7
+ * (`OD3_Service_TicketCounter`, one row per tenant), so every ticket still
8
+ * gets a number.
9
+ *
10
+ * The increments use Parse's atomic `$inc`, so concurrent creates never collide.
11
+ */
12
+ export declare function assignTicketNumber(ticket: Parse.Object): Promise<void>;
@@ -0,0 +1,75 @@
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.assignTicketNumber = assignTicketNumber;
7
+ // Ticket numbers: a sequence per project, or per tenant without one.
8
+ const node_1 = __importDefault(require("parse/node"));
9
+ /**
10
+ * Assigns a sequential `number` to a new ticket.
11
+ *
12
+ * - With a project: atomically increments that project's `ticketCounter` and
13
+ * uses the result, so numbers are per-project sequences.
14
+ * - Without a project: falls back to a per-tenant counter
15
+ * (`OD3_Service_TicketCounter`, one row per tenant), so every ticket still
16
+ * gets a number.
17
+ *
18
+ * The increments use Parse's atomic `$inc`, so concurrent creates never collide.
19
+ */
20
+ async function assignTicketNumber(ticket) {
21
+ const project = ticket.get("project");
22
+ if (project) {
23
+ await project.fetch({ useMasterKey: true });
24
+ project.increment("ticketCounter", 1);
25
+ await project.save(null, { useMasterKey: true });
26
+ ticket.set("number", project.get("ticketCounter"));
27
+ return;
28
+ }
29
+ const tenant = ticket.get("tenant");
30
+ if (!tenant)
31
+ return; // no scope to count within — leave unnumbered
32
+ ticket.set("number", await nextTenantTicketNumber(tenant));
33
+ }
34
+ /**
35
+ * Find-or-create the tenant's ticket counter and return the next value.
36
+ *
37
+ * Counters are server-internal — only this hook and the migration ever touch
38
+ * them — so every row gets an empty ACL: nobody but the master/maintenance key
39
+ * reads or writes it. The class CLP says the same (`Service_TicketCounter.json`);
40
+ * this is the per-row half of it, and it also repairs rows written before either
41
+ * existed, which carried the Parse default of public read *and write*. A client
42
+ * that could set `value` could hand another tenant duplicate ticket numbers.
43
+ *
44
+ * Serialised per tenant: the increment is atomic, but the find-or-create is
45
+ * not — two first tickets of a tenant arriving together each found no counter,
46
+ * each created one, and both became #1. The lock only spans this process, which
47
+ * is what runs the hooks.
48
+ */
49
+ function nextTenantTicketNumber(tenant) {
50
+ const key = tenant.id;
51
+ const run = (counterLocks.get(key) ?? Promise.resolve()).then(() => incrementTenantCounter(tenant));
52
+ // The chain must survive a failed increment, or every later one would fail.
53
+ counterLocks.set(key, run.catch(() => undefined));
54
+ return run;
55
+ }
56
+ /** Per-tenant tail of the counter chain, see {@link nextTenantTicketNumber}. */
57
+ const counterLocks = new Map();
58
+ async function incrementTenantCounter(tenant) {
59
+ const existing = await new node_1.default.Query("OD3_Service_TicketCounter")
60
+ .equalTo("tenant", tenant)
61
+ .first({ useMasterKey: true });
62
+ if (existing) {
63
+ existing.increment("value", 1);
64
+ existing.setACL(new node_1.default.ACL());
65
+ await existing.save(null, { useMasterKey: true });
66
+ return existing.get("value");
67
+ }
68
+ const Counter = node_1.default.Object.extend("OD3_Service_TicketCounter");
69
+ const counter = new Counter();
70
+ counter.set("tenant", tenant);
71
+ counter.set("value", 1);
72
+ counter.setACL(new node_1.default.ACL());
73
+ await counter.save(null, { useMasterKey: true });
74
+ return 1;
75
+ }
@@ -0,0 +1,47 @@
1
+ import type { FormulaNode } from "@opendash/ruleset-core";
2
+ import type { Service_FormConfig } from "../../../types/index.js";
3
+ /**
4
+ * The fields a priority formula may read, e.g.
5
+ * `max(downtime, restriction) * 0.7 + frequency * 0.3`. Mirrors
6
+ * `SCALE_FIELD_KEYS` in `@opendash/plugin-openservice-ticket`.
7
+ */
8
+ export declare const PRIORITY_FORMULA_INPUTS: readonly ["downtime", "restriction", "frequency"];
9
+ interface PriorityFormula {
10
+ expression: FormulaNode;
11
+ names: string[];
12
+ }
13
+ /**
14
+ * The formula a config's priority entry asks for, or `undefined` when the
15
+ * priority is entered by hand — or when the stored formula does not parse: the
16
+ * editor refuses to save one, and a broken formula must not block saving
17
+ * tickets. Mirrors `compilePriorityFormula` of the frontend.
18
+ */
19
+ export declare function priorityFormulaOf(config: Service_FormConfig | undefined): PriorityFormula | undefined;
20
+ /**
21
+ * The priority for a ticket's values, or `undefined` when there is nothing to
22
+ * compute from. Mirrors `computePriority` of the frontend:
23
+ *
24
+ * - None of the inputs the formula reads is set: `undefined`, so a ticket
25
+ * nobody has assessed keeps its priority.
26
+ * - Some are set: the rest count as 0, the lowest level.
27
+ * - Clamped to 0–100 and rounded; no number at all (division by zero) is
28
+ * `undefined` as well.
29
+ */
30
+ export declare function computePriority(formula: PriorityFormula, values: (key: string) => unknown): number | undefined;
31
+ /**
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
+ *
35
+ * Only when this save changes one of the inputs — a ticket the save does not
36
+ * 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.
40
+ *
41
+ * "Changes" and "sets" are judged against `original`. The admin table sends
42
+ * every field of its form, the unchanged priority included; counting that as
43
+ * set by hand would leave the old priority after every factor edit there —
44
+ * which is the case this exists for.
45
+ */
46
+ export declare function applyComputedPriority(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined): Promise<void>;
47
+ export {};
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PRIORITY_FORMULA_INPUTS = void 0;
4
+ exports.priorityFormulaOf = priorityFormulaOf;
5
+ exports.computePriority = computePriority;
6
+ exports.applyComputedPriority = applyComputedPriority;
7
+ const ruleset_core_1 = require("@opendash/ruleset-core");
8
+ const ticketFormConfig_js_1 = require("./ticketFormConfig.js");
9
+ /**
10
+ * The fields a priority formula may read, e.g.
11
+ * `max(downtime, restriction) * 0.7 + frequency * 0.3`. Mirrors
12
+ * `SCALE_FIELD_KEYS` in `@opendash/plugin-openservice-ticket`.
13
+ */
14
+ exports.PRIORITY_FORMULA_INPUTS = [
15
+ "downtime",
16
+ "restriction",
17
+ "frequency",
18
+ ];
19
+ /**
20
+ * The formula a config's priority entry asks for, or `undefined` when the
21
+ * priority is entered by hand — or when the stored formula does not parse: the
22
+ * editor refuses to save one, and a broken formula must not block saving
23
+ * tickets. Mirrors `compilePriorityFormula` of the frontend.
24
+ */
25
+ function priorityFormulaOf(config) {
26
+ let entries;
27
+ try {
28
+ entries = JSON.parse(config?.fields ?? "[]");
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ if (!Array.isArray(entries))
34
+ return undefined;
35
+ const entry = entries.find((e) => !!e && typeof e === "object" && e.key === "priority");
36
+ if (entry?.computed !== true || typeof entry.formula !== "string")
37
+ return undefined;
38
+ const result = (0, ruleset_core_1.validateFormula)(entry.formula, [...exports.PRIORITY_FORMULA_INPUTS]);
39
+ if (result.ok === false)
40
+ return undefined;
41
+ return { expression: result.expression, names: result.names };
42
+ }
43
+ function asNumber(value) {
44
+ return typeof value === "number" && Number.isFinite(value)
45
+ ? value
46
+ : undefined;
47
+ }
48
+ /**
49
+ * The priority for a ticket's values, or `undefined` when there is nothing to
50
+ * compute from. Mirrors `computePriority` of the frontend:
51
+ *
52
+ * - None of the inputs the formula reads is set: `undefined`, so a ticket
53
+ * nobody has assessed keeps its priority.
54
+ * - Some are set: the rest count as 0, the lowest level.
55
+ * - Clamped to 0–100 and rounded; no number at all (division by zero) is
56
+ * `undefined` as well.
57
+ */
58
+ function computePriority(formula, values) {
59
+ const scope = {};
60
+ let anySet = false;
61
+ for (const name of formula.names) {
62
+ const value = asNumber(values(name));
63
+ if (value !== undefined)
64
+ anySet = true;
65
+ scope[name] = value ?? 0;
66
+ }
67
+ if (!anySet)
68
+ return undefined;
69
+ const result = (0, ruleset_core_1.evaluateFormula)(formula.expression, scope);
70
+ if (Number.isNaN(result))
71
+ return undefined;
72
+ return Math.round(Math.min(100, Math.max(0, result)));
73
+ }
74
+ /**
75
+ * Sets the computed priority on a ticket being saved, under the form config
76
+ * that applies to the user saving it (see `applicableFormConfig`).
77
+ *
78
+ * Only when this save changes one of the inputs — a ticket the save does not
79
+ * 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.
83
+ *
84
+ * "Changes" and "sets" are judged against `original`. The admin table sends
85
+ * every field of its form, the unchanged priority included; counting that as
86
+ * set by hand would leave the old priority after every factor edit there —
87
+ * which is the case this exists for.
88
+ */
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))
93
+ return;
94
+ if (changes("priority"))
95
+ return;
96
+ const tenant = object.get("tenant");
97
+ const formula = priorityFormulaOf(await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user));
98
+ if (!formula)
99
+ return;
100
+ const priority = computePriority(formula, (key) => object.get(key));
101
+ if (priority !== undefined)
102
+ object.set("priority", priority);
103
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Reads the rows a ticket's dirty pointer fields refer to, one query per class.
3
+ *
4
+ * Pointers arrive unfetched, so both the tenant check and the sort keys need a
5
+ * read — doing it once here is what keeps a save at a single extra query.
6
+ * `refreshSortKeys` reads every sort-key pointer, dirty or not.
7
+ */
8
+ export declare function loadReferencedRows(object: Parse.Object, refreshSortKeys?: boolean): Promise<Map<string, Parse.Object>>;
9
+ /**
10
+ * Rejects a ticket that references master data from another tenant.
11
+ *
12
+ * ACLs do not stop an `od-admin` at a tenant boundary, so every picker in the
13
+ * UI used to offer every tenant's statuses, projects, equipment and tags. The
14
+ * frontend now scopes those queries, but the UI is not the only write path —
15
+ * the generic entity admin and the REST API go straight through here — and a
16
+ * ticket pointing at a foreign status is silently broken: it is counted in
17
+ * neither tenant's board, and it blocks deletion of that status
18
+ * (`Service_Status`'s in-use guard does not filter by tenant either).
19
+ *
20
+ * `assignedRoles` is deliberately not checked: `_Role` has no tenant column at
21
+ * all — a role's tenant lives in its name — so there is nothing to compare.
22
+ * Nor is `assignedUsers` (see {@link TENANT_SCOPED_POINTER_ARRAYS}): people are
23
+ * not master data of one tenant.
24
+ */
25
+ export declare function assertSameTenantReferences(object: Parse.Object, rows: Map<string, Parse.Object>): void;
26
+ /**
27
+ * Keeps {@link SORT_KEY_FIELDS} in step with the pointers they shadow.
28
+ *
29
+ * Only dirty pointers are touched, so a save that changes the title leaves the
30
+ * keys alone — unless `refresh` asks for all of them. Clearing a pointer clears
31
+ * its key, which sorts the ticket with the other unassigned ones rather than
32
+ * leaving a stale name behind.
33
+ */
34
+ export declare function applySortKeys(object: Parse.Object, rows: Map<string, Parse.Object>, refresh?: boolean): void;
35
+ /**
36
+ * Stamps and clears `closedAt` from the ticket's status.
37
+ *
38
+ * **Why the server and not the form.** `closedAt` is the only record of when
39
+ * work finished, and every number built on it — throughput, how long a ticket
40
+ * sat open, what a month closed — is wrong if it is missing on some tickets and
41
+ * guessed on others. It was a plain date field nobody filled: the board moves a
42
+ * ticket to "Erledigt" by drag and drop, the detail page by a dropdown, the
43
+ * rules by an action, and none of them went near it. Doing it here covers every
44
+ * one of those paths plus the import and the REST API, which is the whole point
45
+ * of putting it in `beforeSave`.
46
+ *
47
+ * **The status decides, not the field.** A status counts as closing when its
48
+ * `category` is finished by `isDoneCategory` (`@opendash/openservice-shared`)
49
+ * — the same rule the alarm tickets, the scheduler and the frontend apply, so "Erledigt", "Abgebrochen" and whatever a
50
+ * tenant calls them agree without anybody configuring it twice.
51
+ *
52
+ * Reopening clears the stamp. A ticket that goes back to "In Bearbeitung" is
53
+ * not closed, and leaving the old date would quietly count it as finished in
54
+ * every evaluation while it is being worked on again.
55
+ *
56
+ * **A value the caller sent wins.** A `closedAt` named in this same save — the
57
+ * migration replaying history, an import, a correction in the admin table — is
58
+ * kept; overwriting it with `now` would be this function deciding it knows
59
+ * better.
60
+ */
61
+ export declare function applyClosedAt(object: Parse.Object, rows: Map<string, Parse.Object>): void;