@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
@@ -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,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.** `object.dirty("closedAt")` means somebody
57
+ * named a date in this same save — the migration replaying history, a correction
58
+ * in the admin table — and overwriting it with `now` would be this function
59
+ * deciding it knows better.
60
+ */
61
+ export declare function applyClosedAt(object: Parse.Object, rows: Map<string, Parse.Object>): void;
@@ -0,0 +1,229 @@
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.loadReferencedRows = loadReferencedRows;
7
+ exports.assertSameTenantReferences = assertSameTenantReferences;
8
+ exports.applySortKeys = applySortKeys;
9
+ exports.applyClosedAt = applyClosedAt;
10
+ // The rows a ticket points at (status, project, equipment, tags): one load,
11
+ // then the tenant check and the values derived from them — sort keys, closedAt.
12
+ const node_1 = __importDefault(require("parse/node"));
13
+ const index_js_1 = require("../../../types/index.js");
14
+ const openservice_shared_1 = require("@opendash/openservice-shared");
15
+ /** Pointer fields on a ticket that must belong to the ticket's own tenant. */
16
+ const TENANT_SCOPED_POINTERS = ["status", "project", "equipment"];
17
+ /**
18
+ * Pointer-array fields whose entries must belong to the ticket's own tenant,
19
+ * with the class the entries point at.
20
+ *
21
+ * The class is spelled out because the entity adapter stores such arrays as
22
+ * plain id **strings** (see `refIds`) — there is no `className` to read
23
+ * off an entry. Reading `.id` off them, as this guard used to, judged nothing.
24
+ *
25
+ * Not `assignedUsers`: people work across tenants — a customer assigns the
26
+ * service provider's staff to its tickets — so an assignee of another tenant
27
+ * is legitimate. Who can be picked is what the assigner may read; the ticket
28
+ * ACL then grants the assignee access. `assignedRoles` has its own guard,
29
+ * {@link assertAssignableRoles}: a role's tenant lives in its name.
30
+ */
31
+ const TENANT_SCOPED_POINTER_ARRAYS = {
32
+ tags: index_js_1.Service_Tag.className,
33
+ };
34
+ /**
35
+ * Shadow columns the ticket carries so the table can sort by a pointer.
36
+ *
37
+ * Parse sorts a pointer column by the stored reference, which is the object id —
38
+ * ordering by it looks random. Sorting by the referenced *label* needs the value
39
+ * on the ticket itself, so these three are kept in step here, where the
40
+ * referenced rows are being read anyway.
41
+ */
42
+ const SORT_KEY_FIELDS = {
43
+ status: "statusOrder",
44
+ project: "projectSortKey",
45
+ equipment: "equipmentSortKey",
46
+ };
47
+ /**
48
+ * Reads the rows a ticket's dirty pointer fields refer to, one query per class.
49
+ *
50
+ * Pointers arrive unfetched, so both the tenant check and the sort keys need a
51
+ * read — doing it once here is what keeps a save at a single extra query.
52
+ * `refreshSortKeys` reads every sort-key pointer, dirty or not.
53
+ */
54
+ async function loadReferencedRows(object, refreshSortKeys = false) {
55
+ const suspects = [];
56
+ for (const field of TENANT_SCOPED_POINTERS) {
57
+ const value = object.get(field);
58
+ if (!value)
59
+ continue;
60
+ // Also read a pointer whose sort key is missing, even when it has not
61
+ // changed: that is what lets a plain re-save fill in a ticket written
62
+ // before those columns existed, with no separate backfill path.
63
+ const hasSortKey = field in SORT_KEY_FIELDS;
64
+ const keyMissing = hasSortKey &&
65
+ object.get(SORT_KEY_FIELDS[field]) ==
66
+ null;
67
+ if (object.dirty(field) || keyMissing || (refreshSortKeys && hasSortKey))
68
+ suspects.push(value);
69
+ }
70
+ const byClass = new Map();
71
+ const add = (className, id) => {
72
+ const ids = byClass.get(className) ?? new Set();
73
+ ids.add(id);
74
+ byClass.set(className, ids);
75
+ };
76
+ for (const suspect of suspects) {
77
+ // A pointer that has not been saved yet has no id — nothing to look up.
78
+ if (suspect.id)
79
+ add(suspect.className, suspect.id);
80
+ }
81
+ for (const [field, className] of Object.entries(TENANT_SCOPED_POINTER_ARRAYS)) {
82
+ if (!object.dirty(field))
83
+ continue;
84
+ for (const id of (0, openservice_shared_1.refIds)(object.get(field)))
85
+ add(className, id);
86
+ }
87
+ const rows = new Map();
88
+ for (const [className, ids] of byClass) {
89
+ const found = await new node_1.default.Query(className)
90
+ .containedIn("objectId", [...ids])
91
+ // `label` and `order` feed the sort keys below, `category` the
92
+ // closing date; `tenant` the guard.
93
+ .select("tenant", "label", "order", "category")
94
+ .limit(ids.size)
95
+ .find({ useMasterKey: true });
96
+ for (const row of found)
97
+ rows.set(row.id, row);
98
+ }
99
+ return rows;
100
+ }
101
+ /**
102
+ * Rejects a ticket that references master data from another tenant.
103
+ *
104
+ * ACLs do not stop an `od-admin` at a tenant boundary, so every picker in the
105
+ * UI used to offer every tenant's statuses, projects, equipment and tags. The
106
+ * frontend now scopes those queries, but the UI is not the only write path —
107
+ * the generic entity admin and the REST API go straight through here — and a
108
+ * ticket pointing at a foreign status is silently broken: it is counted in
109
+ * neither tenant's board, and it blocks deletion of that status
110
+ * (`Service_Status`'s in-use guard does not filter by tenant either).
111
+ *
112
+ * `assignedRoles` is deliberately not checked: `_Role` has no tenant column at
113
+ * all — a role's tenant lives in its name — so there is nothing to compare.
114
+ * Nor is `assignedUsers` (see {@link TENANT_SCOPED_POINTER_ARRAYS}): people are
115
+ * not master data of one tenant.
116
+ */
117
+ function assertSameTenantReferences(object, rows) {
118
+ const tenantId = object.get("tenant")?.id;
119
+ if (!tenantId)
120
+ return; // nothing to compare against
121
+ // Only the dirty references are judged — the loaded set is wider than that
122
+ // (see `loadReferencedRows`), and a ticket that already carries a bad
123
+ // reference has to stay saveable so it can be repaired.
124
+ const judged = [];
125
+ for (const field of TENANT_SCOPED_POINTERS) {
126
+ if (!object.dirty(field))
127
+ continue;
128
+ const value = object.get(field);
129
+ const row = value?.id ? rows.get(value.id) : undefined;
130
+ if (row)
131
+ judged.push(row);
132
+ }
133
+ for (const field of Object.keys(TENANT_SCOPED_POINTER_ARRAYS)) {
134
+ if (!object.dirty(field))
135
+ continue;
136
+ for (const id of (0, openservice_shared_1.refIds)(object.get(field))) {
137
+ const row = rows.get(id);
138
+ if (row)
139
+ judged.push(row);
140
+ }
141
+ }
142
+ for (const row of judged) {
143
+ const refTenantId = row.get("tenant")?.id;
144
+ // No tenant on the referenced row = shared/global master data, allowed.
145
+ if (!refTenantId || refTenantId === tenantId)
146
+ continue;
147
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot reference ${row.className} ${row.id} from tenant ` +
148
+ `${refTenantId} on a ticket of tenant ${tenantId}.`);
149
+ }
150
+ }
151
+ /**
152
+ * Keeps {@link SORT_KEY_FIELDS} in step with the pointers they shadow.
153
+ *
154
+ * Only dirty pointers are touched, so a save that changes the title leaves the
155
+ * keys alone — unless `refresh` asks for all of them. Clearing a pointer clears
156
+ * its key, which sorts the ticket with the other unassigned ones rather than
157
+ * leaving a stale name behind.
158
+ */
159
+ function applySortKeys(object, rows, refresh = false) {
160
+ for (const [field, target] of Object.entries(SORT_KEY_FIELDS)) {
161
+ const pointer = object.get(field);
162
+ const keyMissing = pointer && object.get(target) == null;
163
+ if (!object.dirty(field) && !keyMissing && !refresh)
164
+ continue;
165
+ const row = pointer?.id ? rows.get(pointer.id) : undefined;
166
+ if (!row) {
167
+ object.unset(target);
168
+ continue;
169
+ }
170
+ // Status sorts by its configured workflow position, not by its name: a
171
+ // board reads "Eingang, In Bearbeitung, Erledigt", never alphabetically.
172
+ const value = field === "status" ? row.get("order") : (0, openservice_shared_1.sortKeyOf)(row.get("label"));
173
+ if (value === undefined || value === null)
174
+ object.unset(target);
175
+ else
176
+ object.set(target, value);
177
+ }
178
+ }
179
+ /**
180
+ * Stamps and clears `closedAt` from the ticket's status.
181
+ *
182
+ * **Why the server and not the form.** `closedAt` is the only record of when
183
+ * work finished, and every number built on it — throughput, how long a ticket
184
+ * sat open, what a month closed — is wrong if it is missing on some tickets and
185
+ * guessed on others. It was a plain date field nobody filled: the board moves a
186
+ * ticket to "Erledigt" by drag and drop, the detail page by a dropdown, the
187
+ * rules by an action, and none of them went near it. Doing it here covers every
188
+ * one of those paths plus the import and the REST API, which is the whole point
189
+ * of putting it in `beforeSave`.
190
+ *
191
+ * **The status decides, not the field.** A status counts as closing when its
192
+ * `category` is finished by `isDoneCategory` (`@opendash/openservice-shared`)
193
+ * — the same rule the alarm tickets, the scheduler and the frontend apply, so "Erledigt", "Abgebrochen" and whatever a
194
+ * tenant calls them agree without anybody configuring it twice.
195
+ *
196
+ * Reopening clears the stamp. A ticket that goes back to "In Bearbeitung" is
197
+ * not closed, and leaving the old date would quietly count it as finished in
198
+ * every evaluation while it is being worked on again.
199
+ *
200
+ * **A value the caller sent wins.** `object.dirty("closedAt")` means somebody
201
+ * named a date in this same save — the migration replaying history, a correction
202
+ * in the admin table — and overwriting it with `now` would be this function
203
+ * deciding it knows better.
204
+ */
205
+ function applyClosedAt(object, rows) {
206
+ // Nothing to react to: the status is unchanged. A ticket whose status stayed
207
+ // put keeps whatever stamp it has, including none.
208
+ if (!object.dirty("status"))
209
+ return;
210
+ // Explicitly set in this save — see the note above.
211
+ if (object.dirty("closedAt"))
212
+ return;
213
+ const status = object.get("status");
214
+ const row = status?.id ? rows.get(status.id) : undefined;
215
+ // The row is only missing when the pointer could not be read. Guessing either
216
+ // way would be worse than leaving the stamp as it is.
217
+ if (!row)
218
+ return;
219
+ const closing = (0, openservice_shared_1.isDoneCategory)(row.get("category"));
220
+ if (closing) {
221
+ // Already stamped: the ticket moved between two closing statuses
222
+ // ("Erledigt" → "Abgebrochen"). It closed when it first closed.
223
+ if (!object.get("closedAt"))
224
+ object.set("closedAt", new Date());
225
+ }
226
+ else {
227
+ object.unset("closedAt");
228
+ }
229
+ }
@@ -1,8 +1,17 @@
1
1
  import { SessionTokenType } from "../../schema/index.js";
2
2
  /**
3
3
  * Checks if a user has a specific permission in OD3_Permission.
4
+ *
5
+ * A permission is held by whoever can read its row, and there is one row per
6
+ * key **and tenant** — a tenant admin reads every row of their own tenant.
7
+ * Without `tenant` any readable row counts, whichever tenant it belongs to.
8
+ * Pass the tenant of the object being acted on to ask the real question: may
9
+ * this user do that *there*? Then only that tenant's row counts, or a global
10
+ * row without a tenant. An od-admin reads every row and passes either way.
11
+ *
4
12
  * @param sessionToken - The session token of the user.
5
13
  * @param key - The key of the permission to check.
14
+ * @param tenant - The tenant the operation concerns, if it concerns one.
6
15
  * @returns A promise that resolves to a boolean indicating whether the user has the permission.
7
16
  */
8
- export declare function hasPermission(sessionToken: SessionTokenType, key: string): Promise<boolean>;
17
+ export declare function hasPermission(sessionToken: SessionTokenType, key: string, tenant?: Parse.Object | null): Promise<boolean>;
@@ -8,13 +8,30 @@ const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../../../types/index.js");
9
9
  /**
10
10
  * Checks if a user has a specific permission in OD3_Permission.
11
+ *
12
+ * A permission is held by whoever can read its row, and there is one row per
13
+ * key **and tenant** — a tenant admin reads every row of their own tenant.
14
+ * Without `tenant` any readable row counts, whichever tenant it belongs to.
15
+ * Pass the tenant of the object being acted on to ask the real question: may
16
+ * this user do that *there*? Then only that tenant's row counts, or a global
17
+ * row without a tenant. An od-admin reads every row and passes either way.
18
+ *
11
19
  * @param sessionToken - The session token of the user.
12
20
  * @param key - The key of the permission to check.
21
+ * @param tenant - The tenant the operation concerns, if it concerns one.
13
22
  * @returns A promise that resolves to a boolean indicating whether the user has the permission.
14
23
  */
15
- async function hasPermission(sessionToken, key) {
16
- const result = await new node_1.default.Query(index_js_1.Permission)
24
+ async function hasPermission(sessionToken, key, tenant) {
25
+ const options = { sessionToken: sessionToken || undefined };
26
+ if (!tenant?.id) {
27
+ const result = await new node_1.default.Query(index_js_1.Permission)
28
+ .equalTo("key", key)
29
+ .first(options);
30
+ return !!result;
31
+ }
32
+ const tenantPointer = index_js_1.Tenant.createWithoutData(tenant.id);
33
+ const result = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Permission)
17
34
  .equalTo("key", key)
18
- .first({ sessionToken: sessionToken || undefined });
35
+ .equalTo("tenant", tenantPointer), new node_1.default.Query(index_js_1.Permission).equalTo("key", key).doesNotExist("tenant")).first(options);
19
36
  return !!result;
20
37
  }