@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
@@ -1,53 +1,17 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
3
  exports.init = init;
40
- const node_1 = __importStar(require("parse/node"));
41
- const i18next_1 = __importDefault(require("i18next"));
42
4
  const index_js_1 = require("../features/schema/index.js");
43
5
  const index_js_2 = require("../features/permissions/index.js");
44
6
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
45
- const AlarmTicketTypes_js_1 = require("../features/openservice/alarms/ticket/AlarmTicketTypes.js");
46
- const appLinks_js_1 = require("../helper/appLinks.js");
47
- const pointerIds_js_1 = require("../helper/pointerIds.js");
48
- const getUserLanguage_js_1 = require("../helper/getUserLanguage.js");
49
7
  const index_js_3 = require("../types/index.js");
50
- const ruleset_core_1 = require("@opendash/ruleset-core");
8
+ const ticketCleanup_js_1 = require("../features/openservice/tickets/ticketCleanup.js");
9
+ const ticketNumber_js_1 = require("../features/openservice/tickets/ticketNumber.js");
10
+ const ticketReferences_js_1 = require("../features/openservice/tickets/ticketReferences.js");
11
+ const ticketAccess_js_1 = require("../features/openservice/tickets/ticketAccess.js");
12
+ const ticketNotifications_js_1 = require("../features/openservice/tickets/ticketNotifications.js");
13
+ const ticketArchive_js_1 = require("../features/openservice/tickets/ticketArchive.js");
14
+ const ticketPriority_js_1 = require("../features/openservice/tickets/ticketPriority.js");
51
15
  async function init() {
52
16
  // Soft delete: a ticket is referenced by chat messages, meta entries,
53
17
  // notifications and child tickets, so the frontend archives instead of
@@ -73,6 +37,12 @@ async function init() {
73
37
  Boolean(object.get("deleted")) !== Boolean(original.get("deleted"))) {
74
38
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_delete, "archive a ticket", original.get("tenant"));
75
39
  }
40
+ // Whether an archived ticket still feeds the similar-case search is archive
41
+ // management as well (the archive page's switch), so it takes the same
42
+ // capability. Set while archiving, it is covered by the check above.
43
+ if (!(0, index_js_1.isMigrationMode)() && (0, ticketArchive_js_1.changesSimilarCaseUse)(object, original)) {
44
+ await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_delete, "change whether an archived ticket is used for similar cases", original.get("tenant"));
45
+ }
76
46
  if (isNew && !object.get("createdBy") && user)
77
47
  object.set("createdBy", user);
78
48
  await (0, index_js_1.defaultHandler)(request);
@@ -100,15 +70,23 @@ async function init() {
100
70
  // off a ticket kept writing it, and so did any user or role a client had
101
71
  // slipped into the ACL it sent along.
102
72
  await (0, index_js_1.defaultAclHandler)(request);
103
- await assertAssignableRoles(object);
104
- await setTicketACL(object);
73
+ await (0, ticketAccess_js_1.assertAssignableRoles)(object);
74
+ await (0, ticketAccess_js_1.setTicketACL)(object);
105
75
  // Archived tickets miss the sort keys master data pushes down (see
106
76
  // pushSortKeyToTickets), so restoring one re-derives all of them.
107
77
  const restored = !!original?.get("deleted") && !object.get("deleted");
108
- const referenced = await loadReferencedRows(object, restored);
109
- assertSameTenantReferences(object, referenced);
110
- applySortKeys(object, referenced, restored);
111
- applyClosedAt(object, referenced);
78
+ const referenced = await (0, ticketReferences_js_1.loadReferencedRows)(object, restored);
79
+ (0, ticketReferences_js_1.assertSameTenantReferences)(object, referenced);
80
+ (0, ticketReferences_js_1.applySortKeys)(object, referenced, restored);
81
+ (0, ticketReferences_js_1.applyClosedAt)(object, referenced);
82
+ (0, ticketArchive_js_1.applyArchiveReason)(object, original, !!request.master);
83
+ (0, ticketArchive_js_1.applySimilarCaseUse)(object, original);
84
+ // The priority a form config derives from downtime, restriction and
85
+ // frequency. The ticket forms compute it as well, to show it while the
86
+ // user types — here it holds for every other write path (the admin table,
87
+ // the REST API). A migration replays the stored priority as it was.
88
+ if (!(0, index_js_1.isMigrationMode)())
89
+ await (0, ticketPriority_js_1.applyComputedPriority)(object, original, user);
112
90
  // Assign a sequential ticket number on creation. Done here (backend) rather
113
91
  // than in the frontend because every write path — the create form, the
114
92
  // cross-plugin service, and the generic entity admin — funnels through this
@@ -119,7 +97,13 @@ async function init() {
119
97
  // move could collide with an existing number in the new project. Drawing a
120
98
  // fresh number from the destination keeps each project's sequence unique
121
99
  // (the source sequence simply gains a gap, which is fine).
122
- const projectChanged = !isNew && object.dirty("project");
100
+ //
101
+ // Compared against `original`, not taken from `dirty()`: a field the save
102
+ // merely resends counts as dirty, and the admin table resends every field
103
+ // of its form — each edit there used to give the ticket a new number.
104
+ const projectId = (value) => value?.id;
105
+ const projectChanged = !isNew &&
106
+ projectId(object.get("project")) !== projectId(original?.get("project"));
123
107
  // The number is the server's. The REST API and the generic admin let a
124
108
  // client send one, and a caller-chosen number collides with — or poses as
125
109
  // — another ticket's. Master-key writes (alarm tickets) are the server's
@@ -131,671 +115,30 @@ async function init() {
131
115
  object.set("number", original?.get("number"));
132
116
  }
133
117
  if ((isNew && object.get("number") == null) || projectChanged) {
134
- await assignTicketNumber(object);
118
+ await (0, ticketNumber_js_1.assignTicketNumber)(object);
135
119
  }
136
120
  });
137
- // A hard delete takes the ticket's chat, meta entries and notifications with
138
- // it (see the cascade below) — at least the decision archiving is. Parse has
139
- // no delete right of its own: the ACL's write grant covers delete as well.
121
+ // A hard delete takes everything attached to the ticket with it, its history
122
+ // included (see the cascade below), and cannot be undone — so it has a
123
+ // capability of its own, separate from archiving. Parse has no delete right
124
+ // of its own: the ACL's write grant covers delete as well.
140
125
  (0, index_js_1.beforeDeleteHook)(index_js_3.Service_Ticket, async (request) => {
141
126
  if ((0, index_js_1.isMigrationMode)())
142
127
  return;
143
- await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_delete, "delete a ticket", request.object.get("tenant"));
128
+ await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_purge, "delete a ticket permanently", request.object.get("tenant"));
144
129
  });
145
130
  (0, index_js_1.afterDeleteHook)(index_js_3.Service_Ticket, async ({ object }) => {
146
131
  if (object.id)
147
- await cleanupTicketRelations(object.id);
132
+ await (0, ticketCleanup_js_1.cleanupTicketRelations)(object.id);
148
133
  });
149
134
  (0, index_js_1.afterSaveHook)(index_js_3.Service_Ticket, async ({ object, original, user }) => {
150
135
  // A bulk import would otherwise notify every assignee once per migrated
151
136
  // ticket (~10k per tenant). See helper/migrationMode.ts.
152
137
  if ((0, index_js_1.isMigrationMode)())
153
138
  return;
154
- try {
155
- // Shared across the assignee + watcher passes so a user who is both an
156
- // assignee and a matched watcher is notified only once (assignee first).
157
- const notified = new Set();
158
- if (user?.id)
159
- notified.add(user.id); // never notify the acting user
160
- const assignerName = getUsername(user);
161
- await notifyNewAssignees(object, original, notified, assignerName);
162
- // Conditional "watcher" rules are evaluated on ticket creation only for
163
- // now — re-evaluating them on every edit (and tracking who was already
164
- // notified across edits) is deferred.
165
- if (!original) {
166
- await notifyWatchers(object, notified, assignerName);
167
- }
168
- }
169
- catch (error) {
170
- console.error("[@openinc/parse-server-opendash][Service_Ticket] Failed to notify on assignment", error);
171
- }
139
+ // Not awaited: Parse holds the save's response until afterSave returns,
140
+ // and assigning a role means one notification — mail and push included —
141
+ // per member. With 200 members the person saving waited for 200 of them.
142
+ void (0, ticketNotifications_js_1.notifyAboutSave)(object, original, user);
172
143
  });
173
144
  }
174
- /** Upper bound on related records deleted per ticket — far above any realistic
175
- * meta/chat/notification count for a single ticket. */
176
- const RELATED_DELETE_LIMIT = 10000;
177
- /**
178
- * Removes the data attached to a ticket after it is deleted. Parse cannot
179
- * cascade these on its own: meta head-data ({@link Meta_Entry}) and chat
180
- * messages ({@link Chat_Message}) link to the ticket by a plain string key
181
- * rather than a pointer, and notifications reference it inside their JSON `data`
182
- * blob. Without this hook all three would be orphaned.
183
- *
184
- * So would the ticket's files ({@link Assets}): its file library and the
185
- * attachments of its comments share the chat's context. Destroying an asset
186
- * row also removes its stored file (see the `Assets` hook) — the archive's
187
- * "delete for good" promises exactly that.
188
- *
189
- * Child tickets (the `parent` self-pointer) are intentionally left untouched.
190
- *
191
- * This is the single cleanup path for both single deletes and the dev
192
- * "delete all" command, so the frontend no longer needs to delete related data
193
- * itself.
194
- */
195
- async function cleanupTicketRelations(ticketId) {
196
- // Chat and files are addressed as `contextToString(["service","ticket",id])`,
197
- // i.e. a JSON.stringify of the tuple — match it exactly.
198
- const context = JSON.stringify(["service", "ticket", ticketId]);
199
- const [metaEntries, chatMessages, assets, notifications] = await Promise.all([
200
- new node_1.default.Query(index_js_3.Meta_Entry)
201
- .equalTo("entryClassName", index_js_3.Service_Ticket.className)
202
- .equalTo("entryObjectId", ticketId)
203
- .limit(RELATED_DELETE_LIMIT)
204
- .find({ useMasterKey: true }),
205
- new node_1.default.Query(index_js_3.Chat_Message)
206
- .equalTo("context", context)
207
- .limit(RELATED_DELETE_LIMIT)
208
- .find({ useMasterKey: true }),
209
- new node_1.default.Query(index_js_3.Assets)
210
- .equalTo("context", context)
211
- .limit(RELATED_DELETE_LIMIT)
212
- .find({ useMasterKey: true }),
213
- // `data` is a JSON Object column; Parse supports dot-notation into it. Query
214
- // by class name (untyped) so the `data.ticketId` path key is accepted.
215
- new node_1.default.Query(index_js_3.Notification.className)
216
- .equalTo("data.ticketId", ticketId)
217
- .limit(RELATED_DELETE_LIMIT)
218
- .find({ useMasterKey: true }),
219
- ]);
220
- await node_1.default.Object.destroyAll([...metaEntries, ...chatMessages, ...assets, ...notifications], { useMasterKey: true });
221
- }
222
- /**
223
- * Assigns a sequential `number` to a new ticket.
224
- *
225
- * - With a project: atomically increments that project's `ticketCounter` and
226
- * uses the result, so numbers are per-project sequences.
227
- * - Without a project: falls back to a per-tenant counter
228
- * (`OD3_Service_TicketCounter`, one row per tenant), so every ticket still
229
- * gets a number.
230
- *
231
- * The increments use Parse's atomic `$inc`, so concurrent creates never collide.
232
- */
233
- async function assignTicketNumber(ticket) {
234
- const project = ticket.get("project");
235
- if (project) {
236
- await project.fetch({ useMasterKey: true });
237
- project.increment("ticketCounter", 1);
238
- await project.save(null, { useMasterKey: true });
239
- ticket.set("number", project.get("ticketCounter"));
240
- return;
241
- }
242
- const tenant = ticket.get("tenant");
243
- if (!tenant)
244
- return; // no scope to count within — leave unnumbered
245
- ticket.set("number", await nextTenantTicketNumber(tenant));
246
- }
247
- /**
248
- * Find-or-create the tenant's ticket counter and return the next value.
249
- *
250
- * Counters are server-internal — only this hook and the migration ever touch
251
- * them — so every row gets an empty ACL: nobody but the master/maintenance key
252
- * reads or writes it. The class CLP says the same (`Service_TicketCounter.json`);
253
- * this is the per-row half of it, and it also repairs rows written before either
254
- * existed, which carried the Parse default of public read *and write*. A client
255
- * that could set `value` could hand another tenant duplicate ticket numbers.
256
- *
257
- * Serialised per tenant: the increment is atomic, but the find-or-create is
258
- * not — two first tickets of a tenant arriving together each found no counter,
259
- * each created one, and both became #1. The lock only spans this process, which
260
- * is what runs the hooks.
261
- */
262
- function nextTenantTicketNumber(tenant) {
263
- const key = tenant.id;
264
- const run = (counterLocks.get(key) ?? Promise.resolve()).then(() => incrementTenantCounter(tenant));
265
- // The chain must survive a failed increment, or every later one would fail.
266
- counterLocks.set(key, run.catch(() => undefined));
267
- return run;
268
- }
269
- /** Per-tenant tail of the counter chain, see {@link nextTenantTicketNumber}. */
270
- const counterLocks = new Map();
271
- async function incrementTenantCounter(tenant) {
272
- const existing = await new node_1.default.Query("OD3_Service_TicketCounter")
273
- .equalTo("tenant", tenant)
274
- .first({ useMasterKey: true });
275
- if (existing) {
276
- existing.increment("value", 1);
277
- existing.setACL(new node_1.default.ACL());
278
- await existing.save(null, { useMasterKey: true });
279
- return existing.get("value");
280
- }
281
- const Counter = node_1.default.Object.extend("OD3_Service_TicketCounter");
282
- const counter = new Counter();
283
- counter.set("tenant", tenant);
284
- counter.set("value", 1);
285
- counter.setACL(new node_1.default.ACL());
286
- await counter.save(null, { useMasterKey: true });
287
- return 1;
288
- }
289
- /** Pointer fields on a ticket that must belong to the ticket's own tenant. */
290
- const TENANT_SCOPED_POINTERS = ["status", "project", "equipment"];
291
- /**
292
- * Pointer-array fields whose entries must belong to the ticket's own tenant,
293
- * with the class the entries point at.
294
- *
295
- * The class is spelled out because the entity adapter stores such arrays as
296
- * plain id **strings** (see `pointerIds`) — there is no `className` to read
297
- * off an entry. Reading `.id` off them, as this guard used to, judged nothing.
298
- *
299
- * Not `assignedUsers`: people work across tenants — a customer assigns the
300
- * service provider's staff to its tickets — so an assignee of another tenant
301
- * is legitimate. Who can be picked is what the assigner may read; the ticket
302
- * ACL then grants the assignee access. `assignedRoles` has its own guard,
303
- * {@link assertAssignableRoles}: a role's tenant lives in its name.
304
- */
305
- const TENANT_SCOPED_POINTER_ARRAYS = {
306
- tags: index_js_3.Service_Tag.className,
307
- };
308
- /**
309
- * Role-name prefixes that end in a tenant id (`od-tenant-user-<tenantId>`).
310
- */
311
- const TENANT_ROLE_PREFIXES = [
312
- "od-tenant-user-",
313
- "od-tenant-admin-",
314
- "od-service-provider-",
315
- ];
316
- /**
317
- * Shadow columns the ticket carries so the table can sort by a pointer.
318
- *
319
- * Parse sorts a pointer column by the stored reference, which is the object id —
320
- * ordering by it looks random. Sorting by the referenced *label* needs the value
321
- * on the ticket itself, so these three are kept in step here, where the
322
- * referenced rows are being read anyway.
323
- */
324
- const SORT_KEY_FIELDS = {
325
- status: "statusOrder",
326
- project: "projectSortKey",
327
- equipment: "equipmentSortKey",
328
- };
329
- /**
330
- * Comparable form of a label.
331
- *
332
- * MongoDB compares strings byte by byte, so "Ökowerk" would sort behind
333
- * "Zementwerk". Folding the diacritics puts it at "O", which is what German
334
- * readers expect (DIN 5007-1), and lower-casing keeps the order independent of
335
- * how someone capitalised the name.
336
- */
337
- function sortKeyOf(label) {
338
- if (typeof label !== "string")
339
- return undefined;
340
- const trimmed = label.trim();
341
- if (!trimmed)
342
- return undefined;
343
- return trimmed
344
- .normalize("NFD")
345
- .replace(/\p{Diacritic}/gu, "")
346
- .replace(/ß/g, "ss")
347
- .toLowerCase();
348
- }
349
- /**
350
- * Reads the rows a ticket's dirty pointer fields refer to, one query per class.
351
- *
352
- * Pointers arrive unfetched, so both the tenant check and the sort keys need a
353
- * read — doing it once here is what keeps a save at a single extra query.
354
- * `refreshSortKeys` reads every sort-key pointer, dirty or not.
355
- */
356
- async function loadReferencedRows(object, refreshSortKeys = false) {
357
- const suspects = [];
358
- for (const field of TENANT_SCOPED_POINTERS) {
359
- const value = object.get(field);
360
- if (!value)
361
- continue;
362
- // Also read a pointer whose sort key is missing, even when it has not
363
- // changed: that is what lets a plain re-save fill in a ticket written
364
- // before those columns existed, with no separate backfill path.
365
- const hasSortKey = field in SORT_KEY_FIELDS;
366
- const keyMissing = hasSortKey &&
367
- object.get(SORT_KEY_FIELDS[field]) ==
368
- null;
369
- if (object.dirty(field) || keyMissing || (refreshSortKeys && hasSortKey))
370
- suspects.push(value);
371
- }
372
- const byClass = new Map();
373
- const add = (className, id) => {
374
- const ids = byClass.get(className) ?? new Set();
375
- ids.add(id);
376
- byClass.set(className, ids);
377
- };
378
- for (const suspect of suspects) {
379
- // A pointer that has not been saved yet has no id — nothing to look up.
380
- if (suspect.id)
381
- add(suspect.className, suspect.id);
382
- }
383
- for (const [field, className] of Object.entries(TENANT_SCOPED_POINTER_ARRAYS)) {
384
- if (!object.dirty(field))
385
- continue;
386
- for (const id of (0, pointerIds_js_1.pointerIds)(object.get(field)))
387
- add(className, id);
388
- }
389
- const rows = new Map();
390
- for (const [className, ids] of byClass) {
391
- const found = await new node_1.default.Query(className)
392
- .containedIn("objectId", [...ids])
393
- // `label` and `order` feed the sort keys below, `category` the
394
- // closing date; `tenant` the guard.
395
- .select("tenant", "label", "order", "category")
396
- .limit(ids.size)
397
- .find({ useMasterKey: true });
398
- for (const row of found)
399
- rows.set(row.id, row);
400
- }
401
- return rows;
402
- }
403
- /**
404
- * Rejects a ticket that references master data from another tenant.
405
- *
406
- * ACLs do not stop an `od-admin` at a tenant boundary, so every picker in the
407
- * UI used to offer every tenant's statuses, projects, equipment and tags. The
408
- * frontend now scopes those queries, but the UI is not the only write path —
409
- * the generic entity admin and the REST API go straight through here — and a
410
- * ticket pointing at a foreign status is silently broken: it is counted in
411
- * neither tenant's board, and it blocks deletion of that status
412
- * (`Service_Status`'s in-use guard does not filter by tenant either).
413
- *
414
- * `assignedRoles` is deliberately not checked: `_Role` has no tenant column at
415
- * all — a role's tenant lives in its name — so there is nothing to compare.
416
- * Nor is `assignedUsers` (see {@link TENANT_SCOPED_POINTER_ARRAYS}): people are
417
- * not master data of one tenant.
418
- */
419
- function assertSameTenantReferences(object, rows) {
420
- const tenantId = object.get("tenant")?.id;
421
- if (!tenantId)
422
- return; // nothing to compare against
423
- // Only the dirty references are judged — the loaded set is wider than that
424
- // (see `loadReferencedRows`), and a ticket that already carries a bad
425
- // reference has to stay saveable so it can be repaired.
426
- const judged = [];
427
- for (const field of TENANT_SCOPED_POINTERS) {
428
- if (!object.dirty(field))
429
- continue;
430
- const value = object.get(field);
431
- const row = value?.id ? rows.get(value.id) : undefined;
432
- if (row)
433
- judged.push(row);
434
- }
435
- for (const field of Object.keys(TENANT_SCOPED_POINTER_ARRAYS)) {
436
- if (!object.dirty(field))
437
- continue;
438
- for (const id of (0, pointerIds_js_1.pointerIds)(object.get(field))) {
439
- const row = rows.get(id);
440
- if (row)
441
- judged.push(row);
442
- }
443
- }
444
- for (const row of judged) {
445
- const refTenantId = row.get("tenant")?.id;
446
- // No tenant on the referenced row = shared/global master data, allowed.
447
- if (!refTenantId || refTenantId === tenantId)
448
- continue;
449
- throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot reference ${row.className} ${row.id} from tenant ` +
450
- `${refTenantId} on a ticket of tenant ${tenantId}.`);
451
- }
452
- }
453
- /**
454
- * Rejects assigned roles that reach beyond the ticket's tenant.
455
- *
456
- * An assigned role gets read/write on the ticket (`setTicketACL`) and every
457
- * member a mail (`notifyNewAssignees`), and nothing else stopped a writer —
458
- * or an alarm caller passing `assignedRoleIds` — from assigning another
459
- * tenant's user role, `od-admin`, or `od-user`, which every user belongs to.
460
- *
461
- * `_Role` has no tenant column; a role's tenant lives in its name. So:
462
- *
463
- * - **`od-` roles** are the platform's. Only the ticket tenant's own are
464
- * assignable (`od-tenant-user-<tenant>` and its siblings, see
465
- * {@link TENANT_ROLE_PREFIXES}); the global ones (`od-admin`, `od-user`,
466
- * `od-tenant-verified`, …) and other tenants' are refused.
467
- * - **Any other name** is a role somebody created for their organisation
468
- * ("Elektrik", "Schicht A"). Its tenant cannot be told from the name, so it
469
- * stays assignable.
470
- *
471
- * Judged only when `assignedRoles` changes, like the other reference guards,
472
- * so a ticket that already carries a bad role stays saveable until somebody
473
- * edits its roles. Not skipped for the master key: the alarm endpoint writes
474
- * with it on behalf of an outside caller.
475
- */
476
- async function assertAssignableRoles(object) {
477
- if (!object.dirty("assignedRoles"))
478
- return;
479
- const roleIds = (0, pointerIds_js_1.pointerIds)(object.get("assignedRoles"));
480
- if (roleIds.length === 0)
481
- return;
482
- const tenantId = object.get("tenant")?.id;
483
- const roles = await new node_1.default.Query(node_1.default.Role)
484
- .containedIn("objectId", roleIds)
485
- .select("name")
486
- .limit(roleIds.length)
487
- .find({ useMasterKey: true });
488
- for (const role of roles) {
489
- const name = role.getName() ?? "";
490
- if (!name.startsWith("od-"))
491
- continue;
492
- const prefix = TENANT_ROLE_PREFIXES.find((p) => name.startsWith(p));
493
- if (prefix && tenantId && name.slice(prefix.length) === tenantId)
494
- continue;
495
- throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot assign role ${name} to a ticket of tenant ${tenantId}.`);
496
- }
497
- }
498
- /**
499
- * Keeps {@link SORT_KEY_FIELDS} in step with the pointers they shadow.
500
- *
501
- * Only dirty pointers are touched, so a save that changes the title leaves the
502
- * keys alone — unless `refresh` asks for all of them. Clearing a pointer clears
503
- * its key, which sorts the ticket with the other unassigned ones rather than
504
- * leaving a stale name behind.
505
- */
506
- function applySortKeys(object, rows, refresh = false) {
507
- for (const [field, target] of Object.entries(SORT_KEY_FIELDS)) {
508
- const pointer = object.get(field);
509
- const keyMissing = pointer && object.get(target) == null;
510
- if (!object.dirty(field) && !keyMissing && !refresh)
511
- continue;
512
- const row = pointer?.id ? rows.get(pointer.id) : undefined;
513
- if (!row) {
514
- object.unset(target);
515
- continue;
516
- }
517
- // Status sorts by its configured workflow position, not by its name: a
518
- // board reads "Eingang, In Bearbeitung, Erledigt", never alphabetically.
519
- const value = field === "status" ? row.get("order") : sortKeyOf(row.get("label"));
520
- if (value === undefined || value === null)
521
- object.unset(target);
522
- else
523
- object.set(target, value);
524
- }
525
- }
526
- /**
527
- * Stamps and clears `closedAt` from the ticket's status.
528
- *
529
- * **Why the server and not the form.** `closedAt` is the only record of when
530
- * work finished, and every number built on it — throughput, how long a ticket
531
- * sat open, what a month closed — is wrong if it is missing on some tickets and
532
- * guessed on others. It was a plain date field nobody filled: the board moves a
533
- * ticket to "Erledigt" by drag and drop, the detail page by a dropdown, the
534
- * rules by an action, and none of them went near it. Doing it here covers every
535
- * one of those paths plus the import and the REST API, which is the whole point
536
- * of putting it in `beforeSave`.
537
- *
538
- * **The status decides, not the field.** A status counts as closing when its
539
- * `category` is one of {@link DONE_STATUS_CATEGORIES} — the same list the alarm
540
- * tickets and the frontend read, so "Erledigt", "Abgebrochen" and whatever a
541
- * tenant calls them agree without anybody configuring it twice.
542
- *
543
- * Reopening clears the stamp. A ticket that goes back to "In Bearbeitung" is
544
- * not closed, and leaving the old date would quietly count it as finished in
545
- * every evaluation while it is being worked on again.
546
- *
547
- * **A value the caller sent wins.** `object.dirty("closedAt")` means somebody
548
- * named a date in this same save — the migration replaying history, a correction
549
- * in the admin table — and overwriting it with `now` would be this function
550
- * deciding it knows better.
551
- */
552
- function applyClosedAt(object, rows) {
553
- // Nothing to react to: the status is unchanged. A ticket whose status stayed
554
- // put keeps whatever stamp it has, including none.
555
- if (!object.dirty("status"))
556
- return;
557
- // Explicitly set in this save — see the note above.
558
- if (object.dirty("closedAt"))
559
- return;
560
- const status = object.get("status");
561
- const row = status?.id ? rows.get(status.id) : undefined;
562
- // The row is only missing when the pointer could not be read. Guessing either
563
- // way would be worse than leaving the stamp as it is.
564
- if (!row)
565
- return;
566
- const closing = AlarmTicketTypes_js_1.DONE_STATUS_CATEGORIES.includes(row.get("category"));
567
- if (closing) {
568
- // Already stamped: the ticket moved between two closing statuses
569
- // ("Erledigt" → "Abgebrochen"). It closed when it first closed.
570
- if (!object.get("closedAt"))
571
- object.set("closedAt", new Date());
572
- }
573
- else {
574
- object.unset("closedAt");
575
- }
576
- }
577
- /**
578
- * Sets the ticket ACL from `createdBy`, `assignedUsers` and `assignedRoles` —
579
- * each gets read/write. `assignedUsers`/`assignedRoles` are arrays of Parse
580
- * pointers, so we iterate the entries (by object id) rather than the array
581
- * indices. Parse ACL role grants require the role *name*, not its id, so the
582
- * assigned role pointers are resolved to names first.
583
- *
584
- * This is the authority on who may write a ticket. It builds on the fresh
585
- * default ACL `defaultAclHandler` has just set (od-admin, the tenant's admins,
586
- * tenant-wide read), so everything granted here is derived from the ticket's
587
- * current fields and nothing survives from an earlier save — taking someone
588
- * off a ticket takes their access with them. The tenant-user write is denied
589
- * explicitly all the same, to keep the decision readable in one place.
590
- */
591
- async function setTicketACL(object) {
592
- const acl = object.getACL() ?? new node_1.default.ACL();
593
- // deny global read / write
594
- acl.setPublicReadAccess(false);
595
- acl.setPublicWriteAccess(false);
596
- // the tenant reads every ticket, but writes only its own / assigned ones
597
- const tenantId = object.get("tenant")?.id;
598
- if (tenantId) {
599
- acl.setRoleReadAccess(`od-tenant-user-${tenantId}`, true);
600
- acl.setRoleWriteAccess(`od-tenant-user-${tenantId}`, false);
601
- }
602
- // creator read/write
603
- const creatorId = object.get("createdBy")?.id;
604
- if (creatorId) {
605
- acl.setReadAccess(creatorId, true);
606
- acl.setWriteAccess(creatorId, true);
607
- }
608
- // assigned users read/write
609
- for (const userId of (0, pointerIds_js_1.pointerIds)(object.get("assignedUsers"))) {
610
- acl.setReadAccess(userId, true);
611
- acl.setWriteAccess(userId, true);
612
- }
613
- // assigned roles read/write (resolve pointer ids → role names)
614
- const roleIds = (0, pointerIds_js_1.pointerIds)(object.get("assignedRoles"));
615
- if (roleIds.length > 0) {
616
- const roles = await new node_1.default.Query(node_1.default.Role)
617
- .containedIn("objectId", roleIds)
618
- .find({ useMasterKey: true });
619
- for (const role of roles) {
620
- const name = role.getName();
621
- if (name) {
622
- acl.setRoleReadAccess(name, true);
623
- acl.setRoleWriteAccess(name, true);
624
- }
625
- }
626
- }
627
- object.setACL(acl);
628
- }
629
- /**
630
- * Notifies the users and roles that were newly assigned to a ticket.
631
- *
632
- * Runs on every save and diffs the current `assignedUsers`/`assignedRoles`
633
- * (arrays of pointers) against the previous version (`original`). On creation
634
- * `original` is undefined, so everyone assigned is new; on an edit only the
635
- * added assignees are notified, so re-saving a ticket never re-notifies people
636
- * who were already assigned.
637
- *
638
- * Dedup + precedence mirror the chat-mention feature: one notification per user,
639
- * directly assigned users win over role membership (`users` > `roles`), and the
640
- * acting user (whoever performed the save) is never notified.
641
- */
642
- async function notifyNewAssignees(ticket, original, notified, assignerName) {
643
- const newUserIds = addedIds(ticket.get("assignedUsers"), original?.get("assignedUsers"));
644
- const newRoleIds = addedIds(ticket.get("assignedRoles"), original?.get("assignedRoles"));
645
- if (newUserIds.length === 0 && newRoleIds.length === 0)
646
- return;
647
- await notifyRecipients(newUserIds, newRoleIds, notified, ticket, {
648
- variant: "assigned",
649
- assignerName,
650
- });
651
- }
652
- /** OD3_Config key holding the per-tenant assignment-notification rules. */
653
- const ASSIGNMENT_NOTIFICATION_CONFIG_KEY = "OPENSERVICE_ASSIGNMENT_NOTIFICATIONS";
654
- /**
655
- * Notifies the configured "watchers": users/roles that a conditional ruleset
656
- * says should hear about a ticket, independent of assignment. The rules live in
657
- * a per-tenant {@link Config} row (`OPENSERVICE_ASSIGNMENT_NOTIFICATIONS`) as a
658
- * JSON array of RuleSet function entries authored in the frontend admin. Each
659
- * matching rule's assignees (`user:<id>` / `role:<id>`) are notified, deduped
660
- * against the shared `notified` set (so assignees already handled win).
661
- */
662
- async function notifyWatchers(ticket, notified, assignerName) {
663
- const rules = await loadWatcherRules(ticket.get("tenant"));
664
- if (rules.length === 0)
665
- return;
666
- const getValue = (field) => ticket.get(field);
667
- for (const rule of rules) {
668
- if (rule.function !== "notify" || !rule.ruleset)
669
- continue;
670
- if (!(0, ruleset_core_1.applyRuleSet)(rule.ruleset, getValue))
671
- continue;
672
- const assignees = Array.isArray(rule.params?.assignees)
673
- ? rule.params.assignees
674
- : [];
675
- const userIds = assignees
676
- .filter((a) => a.startsWith("user:"))
677
- .map((a) => a.slice(5));
678
- const roleIds = assignees
679
- .filter((a) => a.startsWith("role:"))
680
- .map((a) => a.slice(5));
681
- await notifyRecipients(userIds, roleIds, notified, ticket, {
682
- variant: "watcher",
683
- assignerName,
684
- frontpage: rule.params?.frontpage === true,
685
- });
686
- }
687
- }
688
- /** Loads and parses the tenant's assignment-notification rules. */
689
- async function loadWatcherRules(tenant) {
690
- if (!tenant)
691
- return [];
692
- const config = await new node_1.default.Query(index_js_3.Config)
693
- .equalTo("key", ASSIGNMENT_NOTIFICATION_CONFIG_KEY)
694
- .equalTo("tenant", tenant)
695
- .first({ useMasterKey: true });
696
- const raw = config?.get("value");
697
- if (typeof raw !== "string")
698
- return [];
699
- try {
700
- const parsed = JSON.parse(raw);
701
- return Array.isArray(parsed) ? parsed : [];
702
- }
703
- catch {
704
- return [];
705
- }
706
- }
707
- /**
708
- * Resolves a set of user ids + role ids to concrete recipients and sends one
709
- * notification each, skipping anyone already in `notified`. Directly listed
710
- * users take precedence over users reached via a role. `notified` is mutated so
711
- * callers can chain multiple passes (assignees, then watchers) with shared
712
- * de-duplication.
713
- */
714
- async function notifyRecipients(userIds, roleIds, notified, ticket, options) {
715
- const users = userIds.length
716
- ? await new node_1.default.Query(node_1.default.User)
717
- .containedIn("objectId", userIds)
718
- .findAll({ useMasterKey: true })
719
- : [];
720
- for (const user of users) {
721
- if (!user.id || notified.has(user.id))
722
- continue;
723
- notified.add(user.id);
724
- await sendAssignmentNotification(user, ticket, options);
725
- }
726
- const roles = roleIds.length
727
- ? await new node_1.default.Query(node_1.Role)
728
- .containedIn("objectId", roleIds)
729
- .findAll({ useMasterKey: true })
730
- : [];
731
- for (const role of roles) {
732
- const members = await role
733
- .relation("users")
734
- .query()
735
- .findAll({ useMasterKey: true });
736
- for (const member of members) {
737
- if (!member.id || notified.has(member.id))
738
- continue;
739
- notified.add(member.id);
740
- await sendAssignmentNotification(member, ticket, options);
741
- }
742
- }
743
- }
744
- /**
745
- * Builds and saves a single assignment notification, translated into the
746
- * recipient's preferred language. Delivery (email + web push) is handled
747
- * automatically by the {@link Notification} afterSave hook.
748
- *
749
- * The deep link lives in `data.url` rather than inside the description text:
750
- * the frontend opens the ticket from `data.ticketId` (see
751
- * `TicketNotificationActionAdapter`) and would only render a raw URL as noise,
752
- * while the notification email appends `data.url` — resolved against the
753
- * recipient's tenant host — to the body.
754
- */
755
- async function sendAssignmentNotification(user, ticket, options) {
756
- // A translator fixed to the recipient's language rather than
757
- // `i18next.changeLanguage`, which is global: two notifications in flight at
758
- // once could each end up in the other's language.
759
- const t = i18next_1.default.getFixedT(await (0, getUserLanguage_js_1.getUserLanguage)(user));
760
- const base = `openservice:ticket.assignment.${options.variant}`;
761
- const ticketName = ticket.get("title");
762
- await new index_js_3.Notification({
763
- title: t(`${base}.title`),
764
- description: t(`${base}.description`, {
765
- username: options.assignerName,
766
- ticketName,
767
- }),
768
- type: options.frontpage ? "frontpage" : "mailbox",
769
- data: {
770
- ticketId: ticket.id,
771
- url: (0, appLinks_js_1.ticketPath)(ticket.id),
772
- translation: {
773
- username: options.assignerName,
774
- ticketName,
775
- ticketId: ticket.id,
776
- },
777
- },
778
- user: user,
779
- isSent: false,
780
- }).save(null, { useMasterKey: true });
781
- }
782
- /** Ids present in `current` (array of pointers) but not in `previous`. */
783
- function addedIds(current, previous) {
784
- const previousIds = new Set((0, pointerIds_js_1.pointerIds)(previous));
785
- return (0, pointerIds_js_1.pointerIds)(current).filter((id) => !previousIds.has(id));
786
- }
787
- function getUsername(user) {
788
- if (!user)
789
- return "System";
790
- let username = "";
791
- if (user?.get("firstname") && user?.get("lastname")) {
792
- username = user?.get("firstname") + " " + user?.get("lastname");
793
- }
794
- else if (user?.get("name")) {
795
- username = user.get("name");
796
- }
797
- else if (user?.getUsername()) {
798
- username = user?.getUsername();
799
- }
800
- return username ?? "System";
801
- }