@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
@@ -5,39 +5,138 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
+ const openservice_shared_1 = require("@opendash/openservice-shared");
8
9
  const i18next_1 = __importDefault(require("i18next"));
9
10
  const index_js_1 = require("../features/schema/index.js");
11
+ const aclAccess_js_1 = require("../helper/aclAccess.js");
10
12
  const appLinks_js_1 = require("../helper/appLinks.js");
11
13
  const getUserLanguage_js_1 = require("../helper/getUserLanguage.js");
12
14
  const index_js_2 = require("../types/index.js");
15
+ /** What a reader who is not the author may change: reacting is an update. */
16
+ const NON_AUTHOR_FIELDS = new Set(["reactions", "ACL"]);
17
+ /** Fixed once a message exists — who wrote it, and where. */
18
+ const IMMUTABLE_FIELDS = ["author", "authorName", "context"];
13
19
  async function init() {
14
20
  (0, index_js_1.beforeSaveHook)(index_js_2.Chat_Message, async (request) => {
21
+ const { object, original, master } = request;
22
+ const user = request.user;
23
+ if (!master)
24
+ assertAuthorship(object, original, user);
15
25
  await (0, index_js_1.defaultHandler)(request);
26
+ // A ticket's comments belong to the ticket (see `ticketOfMessage`).
27
+ const ticket = await ticketOfMessage(object);
28
+ if (ticket && !original && !master) {
29
+ if (!(await (0, aclAccess_js_1.hasAclAccess)(ticket, user, "read"))) {
30
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Not allowed to comment on ticket ${ticket.id}.`);
31
+ }
32
+ }
33
+ // After `defaultHandler`, which files a new row under the writer's own
34
+ // tenant; a tenant change after creation is refused there.
35
+ if (ticket && !original)
36
+ object.set("tenant", ticket.get("tenant"));
16
37
  // `allowTenantUserWrite` because reacting is an update on *someone else's*
17
38
  // message (see `useToggleReaction` in the chat plugin) — without it only
18
- // tenant admins could react. Who may edit or delete what is enforced in the
19
- // UI (`isOwn`); the ACL only has to let the write through.
39
+ // tenant admins could react. That every other change is the author's is
40
+ // enforced above (`assertAuthorship`) and in `beforeDelete` below.
20
41
  await (0, index_js_1.defaultAclHandler)(request, { allowTenantUserWrite: true });
42
+ const acl = object.getACL();
21
43
  // Chat_Message carries `author`, not `user`, so `defaultAclHandler` — which
22
- // looks for a `user` field — never grants the owner write access. Grant it
23
- // explicitly, so an author can always edit and soft-delete their own
24
- // message, independent of their tenant roles. This mirrors the ACL the v1
25
- // migration already writes for chat messages (see
26
- // `scripts/migration/passes/10-chat.ts`).
27
- const author = request.object.get("author");
44
+ // looks for a `user` field — never grants the owner anything. Grant it
45
+ // explicitly, so an author can always read, edit and soft-delete their own
46
+ // message, independent of their tenant roles.
47
+ const author = object.get("author");
28
48
  if (author?.id) {
29
- request.object.getACL()?.setWriteAccess(author.id, true);
49
+ acl.setReadAccess(author.id, true);
50
+ acl.setWriteAccess(author.id, true);
30
51
  }
52
+ // Whoever may read the ticket may read its comments — including assignees
53
+ // from another tenant (a service provider's staff), whom the tenant-wide
54
+ // grant does not cover. Taken over on every save, so a message picks up
55
+ // later assignees whenever it is touched again.
56
+ if (ticket)
57
+ grantTicketReaders(acl, ticket);
58
+ });
59
+ // The ACL lets every tenant user write — and so delete — a message, for the
60
+ // sake of reactions. Deleting one is its author's call.
61
+ (0, index_js_1.beforeDeleteHook)(index_js_2.Chat_Message, async (request) => {
62
+ if (request.master)
63
+ return;
64
+ const authorId = request.object.get("author")
65
+ ?.id;
66
+ if (authorId && authorId === request.user?.id)
67
+ return;
68
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, "Only the author may delete a message.");
31
69
  });
70
+ // Not awaited: Parse holds the save's response until afterSave returns, and
71
+ // mentioning a role notifies — mail and push included — every member.
32
72
  (0, index_js_1.afterSaveHook)(index_js_2.Chat_Message, async ({ object, original }) => {
33
- try {
34
- await notifyMentions(object, original);
35
- }
36
- catch (error) {
73
+ void notifyMentions(object, original).catch((error) => {
37
74
  console.error("[@openinc/parse-server-opendash][Chat_Message] Failed to notify mentioned users", error);
38
- }
75
+ });
39
76
  });
40
77
  }
78
+ /**
79
+ * Keeps a message the work of the user who wrote it.
80
+ *
81
+ * `author` and `authorName` used to come straight from the client, so anybody
82
+ * could post — and send mention notifications — as somebody else; and since
83
+ * the ACL lets every tenant user write (for reactions), anybody could also
84
+ * rewrite or soft-delete anybody's message. Only the UI held back.
85
+ *
86
+ * - **Created:** the author is the caller, named as the chat plugin names them
87
+ * (`name`, else `username`).
88
+ * - **Updated:** author, name and context stay as they are, and whoever is not
89
+ * the author may only react.
90
+ *
91
+ * Not applied to master-key writes (hooks, migrations, imports).
92
+ */
93
+ function assertAuthorship(object, original, user) {
94
+ if (!user?.id) {
95
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, "A chat message needs a logged-in author.");
96
+ }
97
+ if (!original) {
98
+ object.set("author", user);
99
+ object.set("authorName", user.get("name") || user.getUsername());
100
+ return;
101
+ }
102
+ for (const field of IMMUTABLE_FIELDS) {
103
+ if (object.dirty(field)) {
104
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `The ${field} of a chat message cannot be changed.`);
105
+ }
106
+ }
107
+ const authorId = original.get("author")?.id;
108
+ if (authorId === user.id)
109
+ return;
110
+ const changed = object
111
+ .dirtyKeys()
112
+ .filter((key) => !NON_AUTHOR_FIELDS.has(key));
113
+ if (changed.length > 0) {
114
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, "Only the author may change a message.");
115
+ }
116
+ }
117
+ /**
118
+ * The ticket a message is a comment on, read with the master key — or
119
+ * `undefined` for any other chat, or a ticket that does not exist.
120
+ */
121
+ async function ticketOfMessage(object) {
122
+ const ticketId = (0, openservice_shared_1.ticketIdFromContext)(object.get("context"));
123
+ if (!ticketId)
124
+ return undefined;
125
+ return new node_1.default.Query(index_js_2.Service_Ticket)
126
+ .equalTo("objectId", ticketId)
127
+ .first({ useMasterKey: true });
128
+ }
129
+ /** Grants read on the message to everybody the ticket's ACL lets read it. */
130
+ function grantTicketReaders(acl, ticket) {
131
+ for (const [key, permissions] of Object.entries(ticket.getACL()?.toJSON() ?? {})) {
132
+ if (!permissions?.read || key === "*")
133
+ continue;
134
+ if (key.startsWith("role:"))
135
+ acl.setRoleReadAccess(key.slice(5), true);
136
+ else
137
+ acl.setReadAccess(key, true);
138
+ }
139
+ }
41
140
  /**
42
141
  * Notifies the users and roles mentioned in a chat message.
43
142
  *
@@ -65,7 +164,7 @@ async function notifyMentions(object, original) {
65
164
  const username = object.get("authorName") || "System";
66
165
  const messageText = messageSnippet(object.get("text"));
67
166
  // The only linkable chat context today is a service ticket's comment section.
68
- const ticketId = getTicketId(object.get("context"));
167
+ const ticketId = (0, openservice_shared_1.ticketIdFromContext)(object.get("context"));
69
168
  // Users already handled — seeded with the author so they never self-notify.
70
169
  const notified = new Set();
71
170
  const authorId = object.get("author")?.id;
@@ -129,11 +228,13 @@ async function notifyMentions(object, original) {
129
228
  * notifications use, so a mention behaves like any other ticket notification.
130
229
  */
131
230
  async function sendMentionNotification(user, kind, message, vars) {
132
- await i18next_1.default.changeLanguage(await (0, getUserLanguage_js_1.getUserLanguage)(user));
231
+ // Fixed to the recipient's language — `i18next.changeLanguage` is global,
232
+ // so concurrent notifications could swap languages.
233
+ const t = i18next_1.default.getFixedT(await (0, getUserLanguage_js_1.getUserLanguage)(user));
133
234
  const base = `chat:message.mention.${kind}.notification`;
134
235
  await new index_js_2.Notification({
135
- title: i18next_1.default.t(`${base}.title`),
136
- description: i18next_1.default.t(`${base}.description`, {
236
+ title: t(`${base}.title`),
237
+ description: t(`${base}.description`, {
137
238
  username: vars.username,
138
239
  messageText: vars.messageText,
139
240
  role: vars.role,
@@ -166,29 +267,6 @@ function normalizeMentions(value) {
166
267
  function mentionKey(mention) {
167
268
  return `${mention.className}:${mention.id}`;
168
269
  }
169
- /**
170
- * Extracts the ticket a chat belongs to from its `context`. The context is the
171
- * JSON-stringified address tuple (e.g. `["service","ticket","<id>"]`). Only the
172
- * service-ticket context is linkable today; anything else yields no ticket.
173
- */
174
- function getTicketId(context) {
175
- if (typeof context !== "string")
176
- return undefined;
177
- try {
178
- const parts = JSON.parse(context);
179
- if (Array.isArray(parts) &&
180
- parts[0] === "service" &&
181
- parts[1] === "ticket" &&
182
- typeof parts[2] === "string" &&
183
- parts[2]) {
184
- return parts[2];
185
- }
186
- }
187
- catch {
188
- // context is not a JSON tuple — not ticket-bound
189
- }
190
- return undefined;
191
- }
192
270
  const SNIPPET_MAX_LENGTH = 140;
193
271
  /** Inline mention token: `[label](#mention:_User:<id>)` → keep just `label`. */
194
272
  const MENTION_TOKEN = /\[([^\]]*)\]\(#mention:[^)]*\)/g;
@@ -7,14 +7,40 @@ exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../features/schema/index.js");
9
9
  const index_js_2 = require("../features/config/index.js");
10
+ const index_js_3 = require("../features/permissions/index.js");
11
+ const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
10
12
  const catchError_js_1 = require("../helper/catchError.js");
11
- const index_js_3 = require("../types/index.js");
13
+ const index_js_4 = require("../types/index.js");
14
+ /**
15
+ * The rules and policies the v2 ticket admin page edits.
16
+ *
17
+ * The row ACL below lets every tenant member write the `OPENSERVICE_*`
18
+ * settings, because the page saves from their browser. On its own that would
19
+ * let any member, straight through the REST API, mail every new ticket to
20
+ * whomever they like or have the scheduler archive the tenant's finished
21
+ * tickets within the hour. The page asks for `admin_access`, so the save does
22
+ * too.
23
+ */
24
+ const ADMIN_PAGE_KEYS = new Set([
25
+ index_js_2.ConfigKeys.OpenService.assignmentNotifications,
26
+ index_js_2.ConfigKeys.OpenService.ticketDueNotifications,
27
+ index_js_2.ConfigKeys.OpenService.ticketArchiveAfterDays,
28
+ ]);
12
29
  /**
13
30
  * This handles all config changes for a key starting with 'OPENSERVICE_' in class OD3_Config
14
31
  */
15
32
  async function init() {
16
- (0, index_js_1.beforeSaveHook)(index_js_3.Config, async (request) => {
33
+ (0, index_js_1.beforeSaveHook)(index_js_4.Config, async (request) => {
17
34
  const { object, original, user } = request;
35
+ // Checked against `original` too, so a row cannot be renamed out of the
36
+ // set either. The bootstrap writes with the master key and passes.
37
+ if (ADMIN_PAGE_KEYS.has(object.get("key")) ||
38
+ ADMIN_PAGE_KEYS.has(original?.get("key") ?? "")) {
39
+ await (0, index_js_3.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.admin_access, "change the ticket settings",
40
+ // The tenant the setting is for, as stored — a row cannot be moved to
41
+ // a tenant it was not written for.
42
+ original?.get("tenant") ?? object.get("tenant"));
43
+ }
18
44
  await (0, index_js_1.defaultHandler)(request);
19
45
  // The ACL of every `OPENSERVICE_*` row, rebuilt on each save so a row can
20
46
  // never keep a grant it should not have.
@@ -48,7 +74,7 @@ async function init() {
48
74
  object.setACL(acl);
49
75
  }
50
76
  });
51
- (0, index_js_1.afterSaveHook)(index_js_3.Config, async ({ object, original, user }) => {
77
+ (0, index_js_1.afterSaveHook)(index_js_4.Config, async ({ object, original, user }) => {
52
78
  if (object.get("key").startsWith("OPENSERVICE_")) {
53
79
  console.log("Config changed: ", object.get("key"));
54
80
  console.log("Check Meta Fields in Maintenance_Schedule_Step...");
@@ -71,7 +97,7 @@ async function init() {
71
97
  }
72
98
  if (!Array.isArray(metafieldsconfig))
73
99
  return;
74
- const [maintenanceStepQueryError, maintenanceStepQuery] = await (0, catchError_js_1.catchError)(new node_1.default.Query(index_js_3.Maintenance_Schedule_Step).find({
100
+ const [maintenanceStepQueryError, maintenanceStepQuery] = await (0, catchError_js_1.catchError)(new node_1.default.Query(index_js_4.Maintenance_Schedule_Step).find({
75
101
  useMasterKey: true,
76
102
  }));
77
103
  if (maintenanceStepQueryError) {
@@ -7,6 +7,7 @@ exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../features/meta/index.js");
9
9
  const index_js_2 = require("../features/schema/index.js");
10
+ const aclAccess_js_1 = require("../helper/aclAccess.js");
10
11
  const index_js_3 = require("../types/index.js");
11
12
  /**
12
13
  * Grant the user an entry is *about* write access to it.
@@ -61,28 +62,69 @@ function allowSubjectUserWrite(object) {
61
62
  * does not exist, a class without a tenant column, an entry that names no
62
63
  * object at all. The tenant is never cleared, only corrected.
63
64
  */
64
- async function applyLinkedObjectTenant(request) {
65
+ function applyLinkedObjectTenant(request, linked) {
65
66
  if (request.original && !request.master)
66
67
  return;
67
- const className = request.object.entryClassName;
68
- const objectId = request.object.entryObjectId;
69
- if (!className || !objectId)
68
+ const tenant = linked?.get("tenant");
69
+ if (!tenant)
70
+ return;
71
+ if (request.object.tenant?.id === tenant.id)
70
72
  return;
73
+ request.object.tenant = tenant;
74
+ }
75
+ /**
76
+ * The object an entry is *about*, read with the master key — `undefined` when
77
+ * the entry names none, or names one that does not exist (any more).
78
+ */
79
+ async function loadLinkedObject(object) {
80
+ const className = object.entryClassName;
81
+ const objectId = object.entryObjectId;
82
+ if (!className || !objectId)
83
+ return undefined;
71
84
  try {
72
- const linked = await new node_1.default.Query(className)
85
+ return await new node_1.default.Query(className)
73
86
  .equalTo("objectId", objectId)
74
87
  .first({ useMasterKey: true });
75
- const tenant = linked?.get("tenant");
76
- if (!tenant)
77
- return;
78
- if (request.object.tenant?.id === tenant.id)
79
- return;
80
- request.object.tenant = tenant;
81
88
  }
82
89
  catch (error) {
83
- console.error("[@openinc/parse-server-opendash][Meta_Entry] Failed to resolve the linked object's tenant", className, objectId, error);
90
+ console.error("[@openinc/parse-server-opendash][Meta_Entry] Failed to load the linked object", className, objectId, error);
91
+ return undefined;
84
92
  }
85
93
  }
94
+ /**
95
+ * Refuses a writer who may not work on the object the entry is about.
96
+ *
97
+ * `applyLinkedObjectTenant` files a new entry under the linked object's tenant,
98
+ * and the ACL then lets that tenant's users read and write it. Unchecked, that
99
+ * let anybody who knew an object id file header data under a tenant they have
100
+ * nothing to do with.
101
+ *
102
+ * - **A ticket's** header data is part of the ticket and is edited with it, so
103
+ * every write takes write access to the ticket — creator, assignees, the
104
+ * tenant's admins (see `setTicketACL`). The entry itself is writable
105
+ * tenant-wide (below), which on its own let every colleague rewrite any
106
+ * ticket's header data.
107
+ * - **Anything else** — equipment, sources, users — is filled in
108
+ * collaboratively by whoever works with it, so read access to the object is
109
+ * enough, checked when the entry is created or re-addressed.
110
+ *
111
+ * Master-key writes pass. So does an entry whose object does not exist: there
112
+ * is nothing to protect, and no tenant to borrow either.
113
+ */
114
+ async function assertMayWriteAbout(request, linked) {
115
+ if (request.master || !linked)
116
+ return;
117
+ const aboutTicket = linked.className === index_js_3.Service_Ticket.className;
118
+ const readdressed = !request.original ||
119
+ request.object.dirty("entryClassName") ||
120
+ request.object.dirty("entryObjectId");
121
+ if (!aboutTicket && !readdressed)
122
+ return;
123
+ const access = aboutTicket ? "write" : "read";
124
+ if (await (0, aclAccess_js_1.hasAclAccess)(linked, request.user, access))
125
+ return;
126
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Not allowed to write header data about ${linked.className} ${linked.id}.`);
127
+ }
86
128
  /**
87
129
  * The classes a meta entry can be *about*, i.e. every class some context
88
130
  * addresses by `entryClassName`. Kept here rather than spread over the ten
@@ -95,12 +137,17 @@ async function applyLinkedObjectTenant(request) {
95
137
  * `SCHEDULE_VIEWS_META_CONTEXT` (openservice v2), `stepMetaContext()`, and the
96
138
  * literals the v1 openservice plugin still uses. Adding a context for a class
97
139
  * that is not in here leaves its entries behind on delete.
140
+ *
141
+ * Not `Service_Ticket`: deleting a ticket for good removes its entries in the
142
+ * ticket's own cascade (`cleanupTicketRelations` in
143
+ * `features/openservice/tickets/ticketCleanup.ts`),
144
+ * together with their change history. A second cleanup here would race it and
145
+ * write that history back.
98
146
  */
99
147
  const META_SUBJECT_CLASSES = [
100
148
  node_1.default.User,
101
149
  index_js_3.Source,
102
150
  index_js_3.BDE_Article,
103
- index_js_3.Service_Ticket,
104
151
  index_js_3.Service_Equipment,
105
152
  index_js_3.Service_Schedule_Execution,
106
153
  index_js_3.Tenant,
@@ -164,8 +211,10 @@ async function init() {
164
211
  }
165
212
  (0, index_js_2.beforeSaveHook)(index_js_3.Meta_Entry, async (request) => {
166
213
  await (0, index_js_2.defaultHandler)(request);
214
+ const linked = await loadLinkedObject(request.object);
215
+ await assertMayWriteAbout(request, linked);
167
216
  // Before the ACL handler: it derives every grant from `tenant`.
168
- await applyLinkedObjectTenant(request);
217
+ applyLinkedObjectTenant(request, linked);
169
218
  await (0, index_js_2.defaultAclHandler)(request, {
170
219
  // Meta entries are collaborative header data: the tenant's users are the
171
220
  // ones filling them in from the ticket/equipment UI, so they need write
@@ -180,6 +229,18 @@ async function init() {
180
229
  });
181
230
  allowSubjectUserWrite(request.object);
182
231
  });
232
+ // The entry's ACL lets every tenant user write — and so delete — it. For a
233
+ // ticket's header data that is the ticket's decision, as on save.
234
+ (0, index_js_2.beforeDeleteHook)(index_js_3.Meta_Entry, async (request) => {
235
+ if (request.master)
236
+ return;
237
+ const linked = await loadLinkedObject(request.object);
238
+ if (linked?.className !== index_js_3.Service_Ticket.className)
239
+ return;
240
+ if (await (0, aclAccess_js_1.hasAclAccess)(linked, request.user, "write"))
241
+ return;
242
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Not allowed to delete header data of ticket ${linked.id}.`);
243
+ });
183
244
  (0, index_js_2.afterSaveHook)(index_js_3.Meta_Entry, async ({ object }) => {
184
245
  // An entry is the only trace of a context that has no config behind it —
185
246
  // a `customConfig` form leaves `origin` empty and creates no Meta_Config,
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
+ const openservice_shared_1 = require("@opendash/openservice-shared");
8
9
  const index_js_1 = require("../features/schema/index.js");
9
10
  const index_js_2 = require("../features/permissions/index.js");
10
11
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
@@ -45,11 +46,9 @@ async function init() {
45
46
  (0, index_js_1.afterSaveHook)(index_js_3.Service_Equipment, async ({ object, original }) => {
46
47
  if (!(0, ticketSortKeys_js_1.derivedValueChanged)(object, original, "label"))
47
48
  return;
48
- await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("equipment", "equipmentSortKey", object, (0, ticketSortKeys_js_1.sortKeyOf)(object.get("label")));
49
+ await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("equipment", "equipmentSortKey", object, (0, openservice_shared_1.sortKeyOf)(object.get("label")));
49
50
  });
50
- // Block deleting equipment that is still referenced where it matters:
51
- // active tickets, and meter readings (whose `equipment` pointer is required,
52
- // so orphaning it would break them).
51
+ // Block deleting equipment that tickets still point at.
53
52
  (0, index_js_1.beforeDeleteHook)(index_js_3.Service_Equipment, async (request) => {
54
53
  const { object } = request;
55
54
  // Parse has no delete right of its own — an ACL `write` grant covers update
@@ -58,12 +57,13 @@ async function init() {
58
57
  if (!(0, index_js_1.isMigrationMode)()) {
59
58
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.masterdata_manage, "delete equipment");
60
59
  }
60
+ // Archived tickets count too: they are a machine's history, and a restored
61
+ // one would point at nothing. Archive the equipment instead.
61
62
  const tickets = await new node_1.default.Query(index_js_3.Service_Ticket)
62
63
  .equalTo("equipment", object)
63
- .notEqualTo("deleted", true)
64
64
  .count({ useMasterKey: true });
65
65
  if (tickets > 0) {
66
- throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Cannot delete equipment: referenced by ${tickets} active ticket(s).`);
66
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Cannot delete equipment: referenced by ${tickets} ticket(s), archived ones included. Archive it instead.`);
67
67
  }
68
68
  });
69
69
  }
@@ -6,8 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../features/schema/index.js");
9
- const pointerIds_js_1 = require("../helper/pointerIds.js");
10
- const index_js_2 = require("../types/index.js");
9
+ const index_js_2 = require("../features/permissions/index.js");
10
+ const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
11
+ const openservice_shared_1 = require("@opendash/openservice-shared");
12
+ const roleNames_js_1 = require("../helper/roleNames.js");
13
+ const index_js_3 = require("../types/index.js");
11
14
  /**
12
15
  * Restricts a form config to its audience.
13
16
  *
@@ -26,8 +29,8 @@ const index_js_2 = require("../types/index.js");
26
29
  * to change it.
27
30
  */
28
31
  async function applyAudienceAcl(object) {
29
- const userIds = (0, pointerIds_js_1.pointerIds)(object.get("users"));
30
- const roles = await (0, pointerIds_js_1.roleNames)(node_1.default, object.get("roles"));
32
+ const userIds = (0, openservice_shared_1.refIds)(object.get("users"));
33
+ const roles = await (0, roleNames_js_1.roleNames)(node_1.default, object.get("roles"));
31
34
  if (userIds.length === 0 && roles.length === 0)
32
35
  return; // global default
33
36
  const acl = object.getACL() ?? new node_1.default.ACL();
@@ -38,10 +41,19 @@ async function applyAudienceAcl(object) {
38
41
  object.setACL(acl);
39
42
  }
40
43
  async function init() {
41
- (0, index_js_1.beforeSaveHook)(index_js_2.Service_FormConfig, async (request) => {
44
+ (0, index_js_1.beforeSaveHook)(index_js_3.Service_FormConfig, async (request) => {
42
45
  const { object } = request;
43
- const hasAudience = (0, pointerIds_js_1.pointerIds)(object.get("users")).length > 0 ||
44
- (0, pointerIds_js_1.pointerIds)(object.get("roles")).length > 0;
46
+ // Writing a config is a capability — the one that opens the admin page
47
+ // that writes them. The class-level `create` is open to everybody, and a
48
+ // config without an audience is the tenant's default for everyone: without
49
+ // this check any member could rebuild everybody's create form (hide
50
+ // fields, add a rule that assigns every new ticket to themselves) and,
51
+ // through the `allowedRoles` such a config offers, read the members of any
52
+ // role via `openinc-openservice-role-members`. Updates are limited to the
53
+ // admins by the ACL already; checking them too keeps both paths alike.
54
+ await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.admin_access, "change a ticket form config", request.original?.get("tenant") ?? object.get("tenant"));
55
+ const hasAudience = (0, openservice_shared_1.refIds)(object.get("users")).length > 0 ||
56
+ (0, openservice_shared_1.refIds)(object.get("roles")).length > 0;
45
57
  await (0, index_js_1.defaultHandler)(request);
46
58
  // A config addressed at specific roles or users is not the tenant's
47
59
  // business — only its audience (granted below) and the admins may read it.
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const openservice_shared_1 = require("@opendash/openservice-shared");
4
9
  const index_js_1 = require("../features/schema/index.js");
5
10
  const index_js_2 = require("../features/permissions/index.js");
6
11
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
@@ -43,6 +48,15 @@ async function init() {
43
48
  if ((0, index_js_1.isMigrationMode)())
44
49
  return;
45
50
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.masterdata_manage, "delete a project");
51
+ // Like status and equipment: a project tickets still point at — archived
52
+ // ones included — is archived, not destroyed, or those tickets lose their
53
+ // project and the number sequence it holds.
54
+ const tickets = await new node_1.default.Query(index_js_3.Service_Ticket)
55
+ .equalTo("project", request.object)
56
+ .count({ useMasterKey: true });
57
+ if (tickets > 0) {
58
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Cannot delete project: referenced by ${tickets} ticket(s), archived ones included. Archive it instead.`);
59
+ }
46
60
  });
47
61
  // Tickets sort by `projectSortKey`, derived from this label when the ticket was
48
62
  // saved. A rename therefore has to reach them, or they keep sorting under the
@@ -50,6 +64,6 @@ async function init() {
50
64
  (0, index_js_1.afterSaveHook)(index_js_3.Service_Project, async ({ object, original }) => {
51
65
  if (!(0, ticketSortKeys_js_1.derivedValueChanged)(object, original, "label"))
52
66
  return;
53
- await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("project", "projectSortKey", object, (0, ticketSortKeys_js_1.sortKeyOf)(object.get("label")));
67
+ await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("project", "projectSortKey", object, (0, openservice_shared_1.sortKeyOf)(object.get("label")));
54
68
  });
55
69
  }
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
+ const openservice_shared_1 = require("@opendash/openservice-shared");
8
9
  const index_js_1 = require("../features/schema/index.js");
9
10
  const index_js_2 = require("../features/permissions/index.js");
10
11
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
@@ -48,6 +49,19 @@ async function init() {
48
49
  return;
49
50
  await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("status", "statusOrder", object, object.get("order"));
50
51
  });
52
+ // A ticket's `closedAt` follows its status's category (`applyClosedAt` in
53
+ // the ticket hook), but that only runs when a ticket changes status. Moving
54
+ // the status itself between open and finished has to reach its tickets too,
55
+ // or the analytics keep counting them by the old category.
56
+ (0, index_js_1.afterSaveHook)(index_js_3.Service_Status, async ({ object, original }) => {
57
+ if (!original)
58
+ return;
59
+ const wasFinished = (0, openservice_shared_1.isDoneCategory)(original.get("category"));
60
+ const finished = (0, openservice_shared_1.isDoneCategory)(object.get("category"));
61
+ if (wasFinished === finished)
62
+ return;
63
+ await restampClosedAt(object, finished);
64
+ });
51
65
  // A ticket's `status` is required — deleting a status still in use by active
52
66
  // tickets would orphan that required pointer. Block it.
53
67
  (0, index_js_1.beforeDeleteHook)(index_js_3.Service_Status, async (request) => {
@@ -58,12 +72,47 @@ async function init() {
58
72
  if (!(0, index_js_1.isMigrationMode)()) {
59
73
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.masterdata_manage, "delete a ticket status");
60
74
  }
75
+ // Archived tickets count too: `status` is required, and finished tickets
76
+ // are archived automatically — deleting "Done" would leave every one of
77
+ // them pointing at nothing, and none could be restored cleanly. Archive the
78
+ // status instead; that keeps the references intact.
61
79
  const inUse = await new node_1.default.Query(index_js_3.Service_Ticket)
62
80
  .equalTo("status", object)
63
- .notEqualTo("deleted", true)
64
81
  .count({ useMasterKey: true });
65
82
  if (inUse > 0) {
66
- throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Cannot delete status: still used by ${inUse} active ticket(s).`);
83
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Cannot delete status: still used by ${inUse} ticket(s), archived ones included. Archive it instead.`);
67
84
  }
68
85
  });
69
86
  }
87
+ /**
88
+ * Brings `closedAt` of the tickets in `status` in line with its category:
89
+ * stamped now when it became a finished one — the moment they count as closed
90
+ * — and cleared when it became an open one.
91
+ *
92
+ * Live tickets only, like the sort keys (see `pushSortKeyToTickets`): the
93
+ * archived ones are what grows without bound, and they were archived as what
94
+ * they were then.
95
+ */
96
+ async function restampClosedAt(status, finished) {
97
+ const query = new node_1.default.Query(index_js_3.Service_Ticket)
98
+ .equalTo("status", status)
99
+ .notEqualTo("deleted", true);
100
+ if (finished)
101
+ query.doesNotExist("closedAt");
102
+ else
103
+ query.exists("closedAt");
104
+ const tenant = status.get("tenant");
105
+ if (tenant)
106
+ query.equalTo("tenant", tenant);
107
+ const tickets = await query.findAll({ useMasterKey: true });
108
+ if (tickets.length === 0)
109
+ return;
110
+ const now = new Date();
111
+ for (const ticket of tickets) {
112
+ if (finished)
113
+ ticket.set("closedAt", now);
114
+ else
115
+ ticket.unset("closedAt");
116
+ }
117
+ await node_1.default.Object.saveAll(tickets, { useMasterKey: true });
118
+ }