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