@openinc/parse-server-opendash 4.24.0 → 4.24.1

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 (29) hide show
  1. package/dist/features/config/types/ConfigKeys.d.ts +1 -0
  2. package/dist/features/config/types/ConfigKeys.js +3 -0
  3. package/dist/features/openservice/alarms/tenantForSecret.js +3 -1
  4. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +4 -1
  5. package/dist/features/openservice/init.d.ts +12 -6
  6. package/dist/features/openservice/init.js +29 -21
  7. package/dist/features/permissions/helper/hasPermission.d.ts +10 -1
  8. package/dist/features/permissions/helper/hasPermission.js +20 -3
  9. package/dist/features/permissions/helper/requirePermission.d.ts +2 -1
  10. package/dist/features/permissions/helper/requirePermission.js +3 -2
  11. package/dist/features/schema/indexes.js +11 -0
  12. package/dist/features/schema/services/beforeSaveHook.js +54 -0
  13. package/dist/functions/openinc-config.js +2 -22
  14. package/dist/helper/aclAccess.d.ts +19 -0
  15. package/dist/helper/aclAccess.js +57 -0
  16. package/dist/helper/getUserLanguage.d.ts +17 -0
  17. package/dist/helper/getUserLanguage.js +37 -4
  18. package/dist/hooks/Chat_Message.js +113 -12
  19. package/dist/hooks/Config_open_service.js +30 -4
  20. package/dist/hooks/Meta_Entry.js +69 -13
  21. package/dist/hooks/Service_Equipment.js +4 -5
  22. package/dist/hooks/Service_FormConfig.js +13 -2
  23. package/dist/hooks/Service_Project.js +13 -0
  24. package/dist/hooks/Service_Status.js +54 -2
  25. package/dist/hooks/Service_Ticket.js +158 -48
  26. package/dist/index.js +7 -2
  27. package/dist/scripts/repair-ticket-acl.d.ts +1 -0
  28. package/dist/scripts/repair-ticket-acl.js +135 -0
  29. package/package.json +2 -1
@@ -7,27 +7,64 @@ exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const i18next_1 = __importDefault(require("i18next"));
9
9
  const index_js_1 = require("../features/schema/index.js");
10
+ const aclAccess_js_1 = require("../helper/aclAccess.js");
10
11
  const appLinks_js_1 = require("../helper/appLinks.js");
11
12
  const getUserLanguage_js_1 = require("../helper/getUserLanguage.js");
12
13
  const index_js_2 = require("../types/index.js");
14
+ /** What a reader who is not the author may change: reacting is an update. */
15
+ const NON_AUTHOR_FIELDS = new Set(["reactions", "ACL"]);
16
+ /** Fixed once a message exists — who wrote it, and where. */
17
+ const IMMUTABLE_FIELDS = ["author", "authorName", "context"];
13
18
  async function init() {
14
19
  (0, index_js_1.beforeSaveHook)(index_js_2.Chat_Message, async (request) => {
20
+ const { object, original, master } = request;
21
+ const user = request.user;
22
+ if (!master)
23
+ assertAuthorship(object, original, user);
15
24
  await (0, index_js_1.defaultHandler)(request);
25
+ // A ticket's comments belong to the ticket (see `ticketOfMessage`).
26
+ const ticket = await ticketOfMessage(object);
27
+ if (ticket && !original && !master) {
28
+ if (!(await (0, aclAccess_js_1.hasAclAccess)(ticket, user, "read"))) {
29
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Not allowed to comment on ticket ${ticket.id}.`);
30
+ }
31
+ }
32
+ // After `defaultHandler`, which files a new row under the writer's own
33
+ // tenant; a tenant change after creation is refused there.
34
+ if (ticket && !original)
35
+ object.set("tenant", ticket.get("tenant"));
16
36
  // `allowTenantUserWrite` because reacting is an update on *someone else's*
17
37
  // 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.
38
+ // tenant admins could react. That every other change is the author's is
39
+ // enforced above (`assertAuthorship`) and in `beforeDelete` below.
20
40
  await (0, index_js_1.defaultAclHandler)(request, { allowTenantUserWrite: true });
41
+ const acl = object.getACL();
21
42
  // 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");
43
+ // looks for a `user` field — never grants the owner anything. Grant it
44
+ // explicitly, so an author can always read, edit and soft-delete their own
45
+ // message, independent of their tenant roles.
46
+ const author = object.get("author");
28
47
  if (author?.id) {
29
- request.object.getACL()?.setWriteAccess(author.id, true);
48
+ acl.setReadAccess(author.id, true);
49
+ acl.setWriteAccess(author.id, true);
30
50
  }
51
+ // Whoever may read the ticket may read its comments — including assignees
52
+ // from another tenant (a service provider's staff), whom the tenant-wide
53
+ // grant does not cover. Taken over on every save, so a message picks up
54
+ // later assignees whenever it is touched again.
55
+ if (ticket)
56
+ grantTicketReaders(acl, ticket);
57
+ });
58
+ // The ACL lets every tenant user write — and so delete — a message, for the
59
+ // sake of reactions. Deleting one is its author's call.
60
+ (0, index_js_1.beforeDeleteHook)(index_js_2.Chat_Message, async (request) => {
61
+ if (request.master)
62
+ return;
63
+ const authorId = request.object.get("author")
64
+ ?.id;
65
+ if (authorId && authorId === request.user?.id)
66
+ return;
67
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, "Only the author may delete a message.");
31
68
  });
32
69
  (0, index_js_1.afterSaveHook)(index_js_2.Chat_Message, async ({ object, original }) => {
33
70
  try {
@@ -38,6 +75,68 @@ async function init() {
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 = getTicketId(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
  *
@@ -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,
@@ -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
@@ -164,8 +206,10 @@ async function init() {
164
206
  }
165
207
  (0, index_js_2.beforeSaveHook)(index_js_3.Meta_Entry, async (request) => {
166
208
  await (0, index_js_2.defaultHandler)(request);
209
+ const linked = await loadLinkedObject(request.object);
210
+ await assertMayWriteAbout(request, linked);
167
211
  // Before the ACL handler: it derives every grant from `tenant`.
168
- await applyLinkedObjectTenant(request);
212
+ applyLinkedObjectTenant(request, linked);
169
213
  await (0, index_js_2.defaultAclHandler)(request, {
170
214
  // Meta entries are collaborative header data: the tenant's users are the
171
215
  // ones filling them in from the ticket/equipment UI, so they need write
@@ -180,6 +224,18 @@ async function init() {
180
224
  });
181
225
  allowSubjectUserWrite(request.object);
182
226
  });
227
+ // The entry's ACL lets every tenant user write — and so delete — it. For a
228
+ // ticket's header data that is the ticket's decision, as on save.
229
+ (0, index_js_2.beforeDeleteHook)(index_js_3.Meta_Entry, async (request) => {
230
+ if (request.master)
231
+ return;
232
+ const linked = await loadLinkedObject(request.object);
233
+ if (linked?.className !== index_js_3.Service_Ticket.className)
234
+ return;
235
+ if (await (0, aclAccess_js_1.hasAclAccess)(linked, request.user, "write"))
236
+ return;
237
+ throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `Not allowed to delete header data of ticket ${linked.id}.`);
238
+ });
183
239
  (0, index_js_2.afterSaveHook)(index_js_3.Meta_Entry, async ({ object }) => {
184
240
  // An entry is the only trace of a context that has no config behind it —
185
241
  // a `customConfig` form leaves `origin` empty and creates no Meta_Config,
@@ -47,9 +47,7 @@ async function init() {
47
47
  return;
48
48
  await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("equipment", "equipmentSortKey", object, (0, ticketSortKeys_js_1.sortKeyOf)(object.get("label")));
49
49
  });
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).
50
+ // Block deleting equipment that tickets still point at.
53
51
  (0, index_js_1.beforeDeleteHook)(index_js_3.Service_Equipment, async (request) => {
54
52
  const { object } = request;
55
53
  // Parse has no delete right of its own — an ACL `write` grant covers update
@@ -58,12 +56,13 @@ async function init() {
58
56
  if (!(0, index_js_1.isMigrationMode)()) {
59
57
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.masterdata_manage, "delete equipment");
60
58
  }
59
+ // Archived tickets count too: they are a machine's history, and a restored
60
+ // one would point at nothing. Archive the equipment instead.
61
61
  const tickets = await new node_1.default.Query(index_js_3.Service_Ticket)
62
62
  .equalTo("equipment", object)
63
- .notEqualTo("deleted", true)
64
63
  .count({ useMasterKey: true });
65
64
  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).`);
65
+ 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
66
  }
68
67
  });
69
68
  }
@@ -6,8 +6,10 @@ 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 index_js_2 = require("../features/permissions/index.js");
10
+ const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
9
11
  const pointerIds_js_1 = require("../helper/pointerIds.js");
10
- const index_js_2 = require("../types/index.js");
12
+ const index_js_3 = require("../types/index.js");
11
13
  /**
12
14
  * Restricts a form config to its audience.
13
15
  *
@@ -38,8 +40,17 @@ async function applyAudienceAcl(object) {
38
40
  object.setACL(acl);
39
41
  }
40
42
  async function init() {
41
- (0, index_js_1.beforeSaveHook)(index_js_2.Service_FormConfig, async (request) => {
43
+ (0, index_js_1.beforeSaveHook)(index_js_3.Service_FormConfig, async (request) => {
42
44
  const { object } = request;
45
+ // Writing a config is a capability — the one that opens the admin page
46
+ // that writes them. The class-level `create` is open to everybody, and a
47
+ // config without an audience is the tenant's default for everyone: without
48
+ // this check any member could rebuild everybody's create form (hide
49
+ // fields, add a rule that assigns every new ticket to themselves) and,
50
+ // through the `allowedRoles` such a config offers, read the members of any
51
+ // role via `openinc-openservice-role-members`. Updates are limited to the
52
+ // admins by the ACL already; checking them too keeps both paths alike.
53
+ 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"));
43
54
  const hasAudience = (0, pointerIds_js_1.pointerIds)(object.get("users")).length > 0 ||
44
55
  (0, pointerIds_js_1.pointerIds)(object.get("roles")).length > 0;
45
56
  await (0, index_js_1.defaultHandler)(request);
@@ -1,6 +1,10 @@
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"));
4
8
  const index_js_1 = require("../features/schema/index.js");
5
9
  const index_js_2 = require("../features/permissions/index.js");
6
10
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
@@ -43,6 +47,15 @@ async function init() {
43
47
  if ((0, index_js_1.isMigrationMode)())
44
48
  return;
45
49
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.masterdata_manage, "delete a project");
50
+ // Like status and equipment: a project tickets still point at — archived
51
+ // ones included — is archived, not destroyed, or those tickets lose their
52
+ // project and the number sequence it holds.
53
+ const tickets = await new node_1.default.Query(index_js_3.Service_Ticket)
54
+ .equalTo("project", request.object)
55
+ .count({ useMasterKey: true });
56
+ if (tickets > 0) {
57
+ 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.`);
58
+ }
46
59
  });
47
60
  // Tickets sort by `projectSortKey`, derived from this label when the ticket was
48
61
  // saved. A rename therefore has to reach them, or they keep sorting under the
@@ -9,6 +9,7 @@ const index_js_1 = require("../features/schema/index.js");
9
9
  const index_js_2 = require("../features/permissions/index.js");
10
10
  const Permissions_js_1 = require("../features/permissions/types/Permissions.js");
11
11
  const ticketSortKeys_js_1 = require("../helper/ticketSortKeys.js");
12
+ const AlarmTicketTypes_js_1 = require("../features/openservice/alarms/ticket/AlarmTicketTypes.js");
12
13
  const index_js_3 = require("../types/index.js");
13
14
  async function init() {
14
15
  // Soft delete: every ticket carries a required `status` pointer, so a status
@@ -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 = isFinished(original.get("category"));
60
+ const finished = isFinished(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,50 @@ 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
+ function isFinished(category) {
88
+ return (typeof category === "string" && AlarmTicketTypes_js_1.DONE_STATUS_CATEGORIES.includes(category));
89
+ }
90
+ /**
91
+ * Brings `closedAt` of the tickets in `status` in line with its category:
92
+ * stamped now when it became a finished one — the moment they count as closed
93
+ * — and cleared when it became an open one.
94
+ *
95
+ * Live tickets only, like the sort keys (see `pushSortKeyToTickets`): the
96
+ * archived ones are what grows without bound, and they were archived as what
97
+ * they were then.
98
+ */
99
+ async function restampClosedAt(status, finished) {
100
+ const query = new node_1.default.Query(index_js_3.Service_Ticket)
101
+ .equalTo("status", status)
102
+ .notEqualTo("deleted", true);
103
+ if (finished)
104
+ query.doesNotExist("closedAt");
105
+ else
106
+ query.exists("closedAt");
107
+ const tenant = status.get("tenant");
108
+ if (tenant)
109
+ query.equalTo("tenant", tenant);
110
+ const tickets = await query.findAll({ useMasterKey: true });
111
+ if (tickets.length === 0)
112
+ return;
113
+ const now = new Date();
114
+ for (const ticket of tickets) {
115
+ if (finished)
116
+ ticket.set("closedAt", now);
117
+ else
118
+ ticket.unset("closedAt");
119
+ }
120
+ await node_1.default.Object.saveAll(tickets, { useMasterKey: true });
121
+ }