@openinc/parse-server-opendash 4.20.0 → 4.22.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.
@@ -25,6 +25,7 @@ export declare namespace Permissions {
25
25
  ticket_access = "openservice-ticket:can-access-ticket-plugin",
26
26
  ticket_create = "openservice-ticket:can-create-ticket",
27
27
  ticket_delete = "openservice-ticket:can-delete-ticket",
28
+ ticket_analytics_view = "openservice-ticket:can-view-analytics",
28
29
  schedule_access = "openservice-schedule:can-access-schedule-plugin",
29
30
  schedule_create = "openservice-schedule:can-create-schedule",
30
31
  schedule_delete = "openservice-schedule:can-delete-schedule",
@@ -54,6 +54,11 @@ var Permissions;
54
54
  SERVICE["ticket_access"] = "openservice-ticket:can-access-ticket-plugin";
55
55
  SERVICE["ticket_create"] = "openservice-ticket:can-create-ticket";
56
56
  SERVICE["ticket_delete"] = "openservice-ticket:can-delete-ticket";
57
+ // The ticket evaluations page. Its own key rather than the schedule
58
+ // plugin's `analytics_view`: a tenant may well want its shift leads to see
59
+ // ticket throughput without opening up maintenance compliance, and the two
60
+ // pages belong to two plugins that are deployed independently.
61
+ SERVICE["ticket_analytics_view"] = "openservice-ticket:can-view-analytics";
57
62
  // Schedule-Plugin
58
63
  //
59
64
  // No `read` or `edit` here on purpose: both are decided per record by the
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The users in the given roles, nested roles included — for the ticket form's
3
+ * "assignable: members of these roles" (`FieldConfigEntry.allowedRoles` in
4
+ * `@opendash/plugin-openservice-ticket`).
5
+ *
6
+ * Params: `{ roleIds: string[] }`. Returns `{ userIds: string[] }`.
7
+ *
8
+ * **Why a function and not a relation query from the browser.** The client
9
+ * reads `_Role.users` with the caller's own session, and Parse answers a
10
+ * `$relatedTo` on a role the caller may not read with an *empty* list, not an
11
+ * error. Exactly the roles worth assigning by are of that kind: a service
12
+ * provider role is readable by administrators only, a tenant admin role by
13
+ * nobody without the master key. A technician opening the form got an empty
14
+ * picker. Here the membership is read with the master key.
15
+ *
16
+ * **Who may ask about which role.** Membership is not public, so a role is
17
+ * resolved only if the caller
18
+ * - may read the role itself (an administrator configuring the form sees the
19
+ * roles they can pick), or
20
+ * - may read a form config that offers the role for assignment — which is the
21
+ * form they are filling in.
22
+ * Other ids are ignored, not refused: the picker then shows fewer people, and
23
+ * the function does not become a way to probe which roles exist.
24
+ *
25
+ * Parse semantics for nesting: a role's `roles` relation lists roles whose
26
+ * users inherit it, so a role's members are its own users plus the members of
27
+ * those roles (the same direction `openinc-config` walks for the caller's own
28
+ * roles).
29
+ *
30
+ * Only ids come back. The browser offers just the users it can read anyway,
31
+ * so this widens nothing beyond "who is in the team".
32
+ */
33
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,123 @@
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.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../types/index.js");
9
+ /** More would not be a picker any more; it caps what one call may resolve. */
10
+ const MAX_ROLES = 50;
11
+ /** Nesting deeper than this is a cycle or a mistake, not an org chart. */
12
+ const MAX_DEPTH = 10;
13
+ /**
14
+ * The users in the given roles, nested roles included — for the ticket form's
15
+ * "assignable: members of these roles" (`FieldConfigEntry.allowedRoles` in
16
+ * `@opendash/plugin-openservice-ticket`).
17
+ *
18
+ * Params: `{ roleIds: string[] }`. Returns `{ userIds: string[] }`.
19
+ *
20
+ * **Why a function and not a relation query from the browser.** The client
21
+ * reads `_Role.users` with the caller's own session, and Parse answers a
22
+ * `$relatedTo` on a role the caller may not read with an *empty* list, not an
23
+ * error. Exactly the roles worth assigning by are of that kind: a service
24
+ * provider role is readable by administrators only, a tenant admin role by
25
+ * nobody without the master key. A technician opening the form got an empty
26
+ * picker. Here the membership is read with the master key.
27
+ *
28
+ * **Who may ask about which role.** Membership is not public, so a role is
29
+ * resolved only if the caller
30
+ * - may read the role itself (an administrator configuring the form sees the
31
+ * roles they can pick), or
32
+ * - may read a form config that offers the role for assignment — which is the
33
+ * form they are filling in.
34
+ * Other ids are ignored, not refused: the picker then shows fewer people, and
35
+ * the function does not become a way to probe which roles exist.
36
+ *
37
+ * Parse semantics for nesting: a role's `roles` relation lists roles whose
38
+ * users inherit it, so a role's members are its own users plus the members of
39
+ * those roles (the same direction `openinc-config` walks for the caller's own
40
+ * roles).
41
+ *
42
+ * Only ids come back. The browser offers just the users it can read anyway,
43
+ * so this widens nothing beyond "who is in the team".
44
+ */
45
+ async function init(name) {
46
+ node_1.default.Cloud.define(name, async (request) => {
47
+ const user = request.user;
48
+ if (!user) {
49
+ throw new node_1.default.Error(node_1.default.Error.INVALID_SESSION_TOKEN, `${name} requires a logged-in user`);
50
+ }
51
+ const requested = request.params?.roleIds;
52
+ if (!Array.isArray(requested) ||
53
+ requested.some((id) => typeof id !== "string")) {
54
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name}: roleIds must be an array of strings`);
55
+ }
56
+ const roleIds = [...new Set(requested)].slice(0, MAX_ROLES);
57
+ if (roleIds.length === 0)
58
+ return { userIds: [] };
59
+ const sessionToken = user.getSessionToken();
60
+ if (!sessionToken) {
61
+ throw new node_1.default.Error(node_1.default.Error.INVALID_SESSION_TOKEN, `${name} requires a session`);
62
+ }
63
+ const allowed = await authorizedRoleIds(roleIds, sessionToken);
64
+ return { userIds: await membersOf([...allowed]) };
65
+ }, { requireUser: true });
66
+ }
67
+ /** The requested roles the caller may ask about (see `init`). */
68
+ async function authorizedRoleIds(roleIds, sessionToken) {
69
+ const readable = await new node_1.default.Query(node_1.default.Role)
70
+ .containedIn("objectId", roleIds)
71
+ .limit(roleIds.length)
72
+ .find({ sessionToken });
73
+ const allowed = new Set(idsOf(readable));
74
+ const rest = roleIds.filter((id) => !allowed.has(id));
75
+ if (rest.length === 0)
76
+ return allowed;
77
+ const configs = await new node_1.default.Query(index_js_1.Service_FormConfig)
78
+ .select("fields")
79
+ .limit(1000)
80
+ .find({ sessionToken });
81
+ const offered = new Set(configs.flatMap(offeredRoleIds));
82
+ for (const id of rest) {
83
+ if (offered.has(id))
84
+ allowed.add(id);
85
+ }
86
+ return allowed;
87
+ }
88
+ function idsOf(objects) {
89
+ return objects.map((object) => object.id).filter((id) => !!id);
90
+ }
91
+ /** Role ids a form config offers for assignment (`allowedRoles` of its fields). */
92
+ function offeredRoleIds(config) {
93
+ try {
94
+ const entries = JSON.parse(config.fields ?? "[]");
95
+ return entries.flatMap((entry) => Array.isArray(entry?.allowedRoles)
96
+ ? entry.allowedRoles.filter((id) => typeof id === "string")
97
+ : []);
98
+ }
99
+ catch {
100
+ return [];
101
+ }
102
+ }
103
+ /** Ids of every user in the roles, nested roles included (master key). */
104
+ async function membersOf(roleIds) {
105
+ const members = new Set();
106
+ const visited = new Set();
107
+ let pending = roleIds;
108
+ for (let depth = 0; pending.length > 0 && depth < MAX_DEPTH; depth++) {
109
+ const batch = pending.filter((id) => !visited.has(id));
110
+ batch.forEach((id) => visited.add(id));
111
+ pending = [];
112
+ for (const id of batch) {
113
+ const role = node_1.default.Role.createWithoutData(id);
114
+ const [users, children] = await Promise.all([
115
+ role.getUsers().query().limit(10000).find({ useMasterKey: true }),
116
+ role.getRoles().query().limit(1000).find({ useMasterKey: true }),
117
+ ]);
118
+ idsOf(users).forEach((id) => members.add(id));
119
+ pending.push(...idsOf(children));
120
+ }
121
+ }
122
+ return [...members].sort();
123
+ }
@@ -42,6 +42,7 @@ const i18next_1 = __importDefault(require("i18next"));
42
42
  const index_js_1 = require("../features/schema/index.js");
43
43
  const index_js_2 = require("../features/permissions/index.js");
44
44
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
45
+ const AlarmTicketTypes_js_1 = require("../features/openservice/alarms/ticket/AlarmTicketTypes.js");
45
46
  const appLinks_js_1 = require("../helper/appLinks.js");
46
47
  const pointerIds_js_1 = require("../helper/pointerIds.js");
47
48
  const getUserLanguage_js_1 = require("../helper/getUserLanguage.js");
@@ -92,6 +93,7 @@ async function init() {
92
93
  const referenced = await loadReferencedRows(object);
93
94
  assertSameTenantReferences(object, referenced);
94
95
  applySortKeys(object, referenced);
96
+ applyClosedAt(object, referenced);
95
97
  // Assign a sequential ticket number on creation. Done here (backend) rather
96
98
  // than in the frontend because every write path — the create form, the
97
99
  // cross-plugin service, and the generic entity admin — funnels through this
@@ -320,8 +322,9 @@ async function loadReferencedRows(object) {
320
322
  for (const [className, ids] of byClass) {
321
323
  const found = await new node_1.default.Query(className)
322
324
  .containedIn("objectId", [...ids])
323
- // `label` and `order` feed the sort keys below; `tenant` the guard.
324
- .select("tenant", "label", "order")
325
+ // `label` and `order` feed the sort keys below, `category` the
326
+ // closing date; `tenant` the guard.
327
+ .select("tenant", "label", "order", "category")
325
328
  .limit(ids.size)
326
329
  .find({ useMasterKey: true });
327
330
  for (const row of found)
@@ -407,6 +410,57 @@ function applySortKeys(object, rows) {
407
410
  object.set(target, value);
408
411
  }
409
412
  }
413
+ /**
414
+ * Stamps and clears `closedAt` from the ticket's status.
415
+ *
416
+ * **Why the server and not the form.** `closedAt` is the only record of when
417
+ * work finished, and every number built on it — throughput, how long a ticket
418
+ * sat open, what a month closed — is wrong if it is missing on some tickets and
419
+ * guessed on others. It was a plain date field nobody filled: the board moves a
420
+ * ticket to "Erledigt" by drag and drop, the detail page by a dropdown, the
421
+ * rules by an action, and none of them went near it. Doing it here covers every
422
+ * one of those paths plus the import and the REST API, which is the whole point
423
+ * of putting it in `beforeSave`.
424
+ *
425
+ * **The status decides, not the field.** A status counts as closing when its
426
+ * `category` is one of {@link DONE_STATUS_CATEGORIES} — the same list the alarm
427
+ * tickets and the frontend read, so "Erledigt", "Abgebrochen" and whatever a
428
+ * tenant calls them agree without anybody configuring it twice.
429
+ *
430
+ * Reopening clears the stamp. A ticket that goes back to "In Bearbeitung" is
431
+ * not closed, and leaving the old date would quietly count it as finished in
432
+ * every evaluation while it is being worked on again.
433
+ *
434
+ * **A value the caller sent wins.** `object.dirty("closedAt")` means somebody
435
+ * named a date in this same save — the migration replaying history, a correction
436
+ * in the admin table — and overwriting it with `now` would be this function
437
+ * deciding it knows better.
438
+ */
439
+ function applyClosedAt(object, rows) {
440
+ // Nothing to react to: the status is unchanged. A ticket whose status stayed
441
+ // put keeps whatever stamp it has, including none.
442
+ if (!object.dirty("status"))
443
+ return;
444
+ // Explicitly set in this save — see the note above.
445
+ if (object.dirty("closedAt"))
446
+ return;
447
+ const status = object.get("status");
448
+ const row = status?.id ? rows.get(status.id) : undefined;
449
+ // The row is only missing when the pointer could not be read. Guessing either
450
+ // way would be worse than leaving the stamp as it is.
451
+ if (!row)
452
+ return;
453
+ const closing = AlarmTicketTypes_js_1.DONE_STATUS_CATEGORIES.includes(row.get("category"));
454
+ if (closing) {
455
+ // Already stamped: the ticket moved between two closing statuses
456
+ // ("Erledigt" → "Abgebrochen"). It closed when it first closed.
457
+ if (!object.get("closedAt"))
458
+ object.set("closedAt", new Date());
459
+ }
460
+ else {
461
+ object.unset("closedAt");
462
+ }
463
+ }
410
464
  /**
411
465
  * Sets the ticket ACL from `createdBy`, `assignedUsers` and `assignedRoles` —
412
466
  * each gets read/write. `assignedUsers`/`assignedRoles` are arrays of Parse
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.20.0",
3
+ "version": "4.22.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [