@openinc/parse-server-opendash 4.24.1 → 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 (43) hide show
  1. package/dist/features/config/helper/getConfig.js +2 -1
  2. package/dist/features/config/types/ConfigKeys.js +8 -26
  3. package/dist/features/openservice/alarms/ticket/AlarmTicketTypes.d.ts +0 -4
  4. package/dist/features/openservice/alarms/ticket/AlarmTicketTypes.js +1 -5
  5. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +6 -5
  6. package/dist/features/openservice/tickets/ticketAccess.d.ts +40 -0
  7. package/dist/features/openservice/tickets/ticketAccess.js +105 -0
  8. package/dist/features/openservice/tickets/ticketCleanup.d.ts +25 -0
  9. package/dist/features/openservice/tickets/ticketCleanup.js +65 -0
  10. package/dist/features/openservice/tickets/ticketNotifications.d.ts +2 -0
  11. package/dist/features/openservice/tickets/ticketNotifications.js +242 -0
  12. package/dist/features/openservice/tickets/ticketNumber.d.ts +12 -0
  13. package/dist/features/openservice/tickets/ticketNumber.js +75 -0
  14. package/dist/features/openservice/tickets/ticketReferences.d.ts +61 -0
  15. package/dist/features/openservice/tickets/ticketReferences.js +229 -0
  16. package/dist/features/permissions/types/Permissions.d.ts +1 -0
  17. package/dist/features/permissions/types/Permissions.js +5 -2
  18. package/dist/features/schema/indexes.js +13 -0
  19. package/dist/functions/openinc-backfill-ticket-sort-keys.d.ts +3 -2
  20. package/dist/functions/openinc-backfill-ticket-sort-keys.js +3 -2
  21. package/dist/helper/getUserLanguage.d.ts +3 -5
  22. package/dist/helper/getUserLanguage.js +7 -16
  23. package/dist/helper/roleNames.d.ts +7 -0
  24. package/dist/helper/roleNames.js +21 -0
  25. package/dist/helper/ticketSortKeys.d.ts +8 -9
  26. package/dist/helper/ticketSortKeys.js +21 -23
  27. package/dist/helper/updateWithoutTriggers.d.ts +22 -0
  28. package/dist/helper/updateWithoutTriggers.js +57 -0
  29. package/dist/hooks/Chat_Message.js +7 -30
  30. package/dist/hooks/Meta_Entry.js +6 -1
  31. package/dist/hooks/Service_Equipment.js +2 -1
  32. package/dist/hooks/Service_FormConfig.js +6 -5
  33. package/dist/hooks/Service_Project.js +2 -1
  34. package/dist/hooks/Service_Status.js +3 -6
  35. package/dist/hooks/Service_Tag.js +51 -11
  36. package/dist/hooks/Service_Ticket.js +22 -701
  37. package/dist/scripts/migration/lib/ptr.d.ts +1 -1
  38. package/dist/scripts/migration/lib/ptr.js +3 -5
  39. package/dist/scripts/migration/lib/ticket.js +3 -2
  40. package/dist/scripts/repair-ticket-acl.js +3 -3
  41. package/package.json +3 -1
  42. package/dist/helper/pointerIds.d.ts +0 -17
  43. package/dist/helper/pointerIds.js +0 -45
@@ -16,8 +16,9 @@ async function getConfig(key) {
16
16
  const result = await new node_1.default.Query(index_js_1.Config).equalTo("key", key).first({
17
17
  useMasterKey: true,
18
18
  });
19
+ // Deliberately not logged: this runs on every push notification and alarm
20
+ // call, and several keys hold secrets (alarm secrets, Outlook credentials).
19
21
  const value = result?.get("value");
20
- console.log("[@openinc/parse-server-opendash][Config]", key, value);
21
22
  return value || "";
22
23
  }
23
24
  /**
@@ -1,26 +1,8 @@
1
1
  "use strict";
2
- /**
3
- * Every `OD3_Config` key this server knows, with what it is for and what it
4
- * should hold when nobody has said otherwise.
5
- *
6
- * **Why a catalogue and not just string constants.** Setting an installation up
7
- * used to mean creating rows by hand in the Parse dashboard, from a list that
8
- * existed only in people's heads: the keys were spelled out inline at their
9
- * point of use, some of them in three different files. A key nobody documented
10
- * is a key somebody forgets, and a forgotten key is an endpoint that refuses
11
- * every call for a reason nobody can see.
12
- *
13
- * Entries with a `defaultValue` (or `generate`) are created automatically at
14
- * boot by `ensureConfigs()`. The rest need a human because they need data only
15
- * the customer has — those are listed too, so a setup page can show what is
16
- * still missing instead of leaving it to be discovered in production.
17
- *
18
- * **Never overwritten.** The bootstrap only ever creates; an existing value is
19
- * left exactly as it is, including an empty one somebody set deliberately.
20
- */
21
2
  Object.defineProperty(exports, "__esModule", { value: true });
22
3
  exports.ConfigKeys = exports.ALL_CONFIG_KEYS = exports.OPENSERVICE_CONFIG_KEYS = void 0;
23
4
  exports.configKeyDefinition = configKeyDefinition;
5
+ const openservice_shared_1 = require("@opendash/openservice-shared");
24
6
  /**
25
7
  * The open.SERVICE keys.
26
8
  *
@@ -46,7 +28,7 @@ exports.OPENSERVICE_CONFIG_KEYS = [
46
28
  required: true,
47
29
  },
48
30
  {
49
- key: "OPENSERVICE_ASSIGNMENT_NOTIFICATIONS",
31
+ key: openservice_shared_1.TICKET_CONFIG_KEYS.assignmentNotifications,
50
32
  description: "Conditional rules for who is notified about a ticket beyond its assignees. JSON array, edited in the ticket admin.",
51
33
  scope: "tenant",
52
34
  defaultValue: "[]",
@@ -68,7 +50,7 @@ exports.OPENSERVICE_CONFIG_KEYS = [
68
50
  },
69
51
  {
70
52
  // Read by the scheduler's `archiveIdleTickets` job.
71
- key: "OPENSERVICE_TICKET_ARCHIVE_AFTER_DAYS",
53
+ key: openservice_shared_1.TICKET_CONFIG_KEYS.ticketArchiveAfterDays,
72
54
  description: 'Days a finished ticket (status category done or cancelled) may go without a change, chat message, file or meta entry before it is archived. "0" switches it off.',
73
55
  scope: "tenant",
74
56
  defaultValue: "30",
@@ -86,7 +68,7 @@ exports.OPENSERVICE_CONFIG_KEYS = [
86
68
  scope: "tenant",
87
69
  },
88
70
  {
89
- key: "OPENSERVICE_V2_NOTIFICATION_WATERMARK",
71
+ key: openservice_shared_1.TICKET_CONFIG_KEYS.v2NotificationWatermark,
90
72
  description: "How far the notification worker has got. Written by the scheduler; removing it re-sends or skips reminders.",
91
73
  scope: "global",
92
74
  runtimeState: true,
@@ -111,15 +93,15 @@ exports.ConfigKeys = {
111
93
  OpenService: {
112
94
  alarmScheduleSecret: "OPENSERVICE_ALARM_SCHEDULE_SECRET",
113
95
  alarmTicketSecret: "OPENSERVICE_ALARM_TICKET_SECRET",
114
- assignmentNotifications: "OPENSERVICE_ASSIGNMENT_NOTIFICATIONS",
96
+ assignmentNotifications: openservice_shared_1.TICKET_CONFIG_KEYS.assignmentNotifications,
115
97
  closedTicketsLifetime: "OPENSERVICE_CLOSED_TICKET_LIFETIME",
116
98
  createTicketOnSchedule: "OPENSERVICE_CREATE_TICKET_ON_SCHEDULE",
117
99
  scheduleMetaFields: "OPENSERVICE_SCHEDULE_META_FIELDS",
118
100
  outlookIntegration: "OPENSERVICE_MICROSOFT_OUTLOOK_INTEGRATION",
119
- ticketArchiveAfterDays: "OPENSERVICE_TICKET_ARCHIVE_AFTER_DAYS",
101
+ ticketArchiveAfterDays: openservice_shared_1.TICKET_CONFIG_KEYS.ticketArchiveAfterDays,
120
102
  // Written by the ticket admin page, read by the scheduler. Not catalogued:
121
103
  // an empty rule list is the default, so there is nothing to seed.
122
- ticketDueNotifications: "OPENSERVICE_TICKET_DUE_NOTIFICATIONS",
123
- v2NotificationWatermark: "OPENSERVICE_V2_NOTIFICATION_WATERMARK",
104
+ ticketDueNotifications: openservice_shared_1.TICKET_CONFIG_KEYS.ticketDueNotifications,
105
+ v2NotificationWatermark: openservice_shared_1.TICKET_CONFIG_KEYS.v2NotificationWatermark,
124
106
  },
125
107
  };
@@ -19,10 +19,6 @@ export declare const ALARM_TICKET_ACTION_ID = "openservice-create-ticket";
19
19
  * only answers to the master key.
20
20
  */
21
21
  export declare const ALARM_TICKET_SECRET_CONFIG_KEY = "OPENSERVICE_ALARM_TICKET_SECRET";
22
- /** Status category a fresh ticket lands in — mirrors the ticket plugin's port. */
23
- export declare const DEFAULT_STATUS_CATEGORY = "inbox";
24
- /** Categories in which a ticket counts as finished (mirrors core's `DONE_CATEGORIES`). */
25
- export declare const DONE_STATUS_CATEGORIES: string[];
26
22
  /**
27
23
  * What the person configuring the alarm filled into the action's form
28
24
  * (`OD3_AlarmAction.formFields`).
@@ -10,7 +10,7 @@
10
10
  * into an `OD3_Service_Ticket`.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.DONE_STATUS_CATEGORIES = exports.DEFAULT_STATUS_CATEGORY = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = void 0;
13
+ exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = void 0;
14
14
  /** Id of the action row, and the marker in a ticket's `origin`. */
15
15
  exports.ALARM_TICKET_ACTION_ID = "openservice-create-ticket";
16
16
  /**
@@ -22,7 +22,3 @@ exports.ALARM_TICKET_ACTION_ID = "openservice-create-ticket";
22
22
  * only answers to the master key.
23
23
  */
24
24
  exports.ALARM_TICKET_SECRET_CONFIG_KEY = "OPENSERVICE_ALARM_TICKET_SECRET";
25
- /** Status category a fresh ticket lands in — mirrors the ticket plugin's port. */
26
- exports.DEFAULT_STATUS_CATEGORY = "inbox";
27
- /** Categories in which a ticket counts as finished (mirrors core's `DONE_CATEGORIES`). */
28
- exports.DONE_STATUS_CATEGORIES = ["done", "cancelled"];
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createAlarmTicket = createAlarmTicket;
7
7
  exports.tenantForAlarmTicket = tenantForAlarmTicket;
8
8
  const node_1 = __importDefault(require("parse/node"));
9
+ const openservice_shared_1 = require("@opendash/openservice-shared");
9
10
  const index_js_1 = require("../../../../types/index.js");
10
11
  const actionParams_js_1 = require("../actionParams.js");
11
12
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
@@ -52,7 +53,7 @@ async function createAlarmTicket(tenant, event, rawParams = {}) {
52
53
  }
53
54
  const status = await resolveDefaultStatus(tenant);
54
55
  if (!status) {
55
- throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `No "${AlarmTicketTypes_js_1.DEFAULT_STATUS_CATEGORY}" status configured for this tenant — cannot create a ticket.`);
56
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `No "${openservice_shared_1.DEFAULT_STATUS_CATEGORY}" status configured for this tenant — cannot create a ticket.`);
56
57
  }
57
58
  const equipment = await (0, resolveEquipment_js_1.resolveEquipment)(tenant, event, params.equipmentId, `[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}]`);
58
59
  const ticket = new index_js_1.Service_Ticket();
@@ -74,8 +75,8 @@ async function createAlarmTicket(tenant, event, rawParams = {}) {
74
75
  project.id = params.projectId;
75
76
  ticket.set("project", project);
76
77
  }
77
- // Assignment arrays hold plain ids in this schema (see the `pointerIds`
78
- // helper in the ticket hook, which accepts both).
78
+ // Assignment arrays hold plain ids in this schema (see `refIds` in
79
+ // `@opendash/openservice-shared`, which reads both).
79
80
  if (params.assignedUserIds?.length) {
80
81
  ticket.set("assignedUsers", params.assignedUserIds);
81
82
  }
@@ -110,7 +111,7 @@ async function findOpenTicket(tenant, origin) {
110
111
  .find({ useMasterKey: true });
111
112
  return tickets.find((ticket) => {
112
113
  const category = ticket.get("status")?.get("category");
113
- return !AlarmTicketTypes_js_1.DONE_STATUS_CATEGORIES.includes(category);
114
+ return !(0, openservice_shared_1.isDoneCategory)(category);
114
115
  });
115
116
  }
116
117
  /** The tenant's inbox status, else a global one — never another tenant's. */
@@ -118,7 +119,7 @@ async function resolveDefaultStatus(tenant) {
118
119
  // Only this tenant's and the global ones: across all tenants a plain `find`
119
120
  // stopped at the default limit (100) and could miss the tenant's own inbox.
120
121
  const statuses = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Service_Status).equalTo("tenant", tenant), new node_1.default.Query(index_js_1.Service_Status).doesNotExist("tenant"))
121
- .equalTo("category", AlarmTicketTypes_js_1.DEFAULT_STATUS_CATEGORY)
122
+ .equalTo("category", openservice_shared_1.DEFAULT_STATUS_CATEGORY)
122
123
  .equalTo("deleted", false)
123
124
  .ascending("order")
124
125
  .limit(1000)
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Rejects assigned roles that reach beyond the ticket's tenant.
3
+ *
4
+ * An assigned role gets read/write on the ticket (`setTicketACL`) and every
5
+ * member a mail (`notifyNewAssignees`), and nothing else stopped a writer —
6
+ * or an alarm caller passing `assignedRoleIds` — from assigning another
7
+ * tenant's user role, `od-admin`, or `od-user`, which every user belongs to.
8
+ *
9
+ * `_Role` has no tenant column; a role's tenant lives in its name. So:
10
+ *
11
+ * - **`od-` roles** are the platform's. Only the ticket tenant's own are
12
+ * assignable (`od-tenant-user-<tenant>` and its siblings, see
13
+ * `isAssignableRoleName` in `@opendash/openservice-shared` — the frontend's
14
+ * role picker applies the same rule); the global ones (`od-admin`, `od-user`,
15
+ * `od-tenant-verified`, …) and other tenants' are refused.
16
+ * - **Any other name** is a role somebody created for their organisation
17
+ * ("Elektrik", "Schicht A"). Its tenant cannot be told from the name, so it
18
+ * stays assignable.
19
+ *
20
+ * Judged only when `assignedRoles` changes, like the other reference guards,
21
+ * so a ticket that already carries a bad role stays saveable until somebody
22
+ * edits its roles. Not skipped for the master key: the alarm endpoint writes
23
+ * with it on behalf of an outside caller.
24
+ */
25
+ export declare function assertAssignableRoles(object: Parse.Object): Promise<void>;
26
+ /**
27
+ * Sets the ticket ACL from `createdBy`, `assignedUsers` and `assignedRoles` —
28
+ * each gets read/write. `assignedUsers`/`assignedRoles` are arrays of Parse
29
+ * pointers, so we iterate the entries (by object id) rather than the array
30
+ * indices. Parse ACL role grants require the role *name*, not its id, so the
31
+ * assigned role pointers are resolved to names first.
32
+ *
33
+ * This is the authority on who may write a ticket. It builds on the fresh
34
+ * default ACL `defaultAclHandler` has just set (od-admin, the tenant's admins,
35
+ * tenant-wide read), so everything granted here is derived from the ticket's
36
+ * current fields and nothing survives from an earlier save — taking someone
37
+ * off a ticket takes their access with them. The tenant-user write is denied
38
+ * explicitly all the same, to keep the decision readable in one place.
39
+ */
40
+ export declare function setTicketACL(object: Parse.Object): Promise<void>;
@@ -0,0 +1,105 @@
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.assertAssignableRoles = assertAssignableRoles;
7
+ exports.setTicketACL = setTicketACL;
8
+ // Who a ticket belongs to: the roles it may be assigned to, and its ACL.
9
+ const node_1 = __importDefault(require("parse/node"));
10
+ const openservice_shared_1 = require("@opendash/openservice-shared");
11
+ /**
12
+ * Rejects assigned roles that reach beyond the ticket's tenant.
13
+ *
14
+ * An assigned role gets read/write on the ticket (`setTicketACL`) and every
15
+ * member a mail (`notifyNewAssignees`), and nothing else stopped a writer —
16
+ * or an alarm caller passing `assignedRoleIds` — from assigning another
17
+ * tenant's user role, `od-admin`, or `od-user`, which every user belongs to.
18
+ *
19
+ * `_Role` has no tenant column; a role's tenant lives in its name. So:
20
+ *
21
+ * - **`od-` roles** are the platform's. Only the ticket tenant's own are
22
+ * assignable (`od-tenant-user-<tenant>` and its siblings, see
23
+ * `isAssignableRoleName` in `@opendash/openservice-shared` — the frontend's
24
+ * role picker applies the same rule); the global ones (`od-admin`, `od-user`,
25
+ * `od-tenant-verified`, …) and other tenants' are refused.
26
+ * - **Any other name** is a role somebody created for their organisation
27
+ * ("Elektrik", "Schicht A"). Its tenant cannot be told from the name, so it
28
+ * stays assignable.
29
+ *
30
+ * Judged only when `assignedRoles` changes, like the other reference guards,
31
+ * so a ticket that already carries a bad role stays saveable until somebody
32
+ * edits its roles. Not skipped for the master key: the alarm endpoint writes
33
+ * with it on behalf of an outside caller.
34
+ */
35
+ async function assertAssignableRoles(object) {
36
+ if (!object.dirty("assignedRoles"))
37
+ return;
38
+ const roleIds = (0, openservice_shared_1.refIds)(object.get("assignedRoles"));
39
+ if (roleIds.length === 0)
40
+ return;
41
+ const tenantId = object.get("tenant")?.id;
42
+ const roles = await new node_1.default.Query(node_1.default.Role)
43
+ .containedIn("objectId", roleIds)
44
+ .select("name")
45
+ .limit(roleIds.length)
46
+ .find({ useMasterKey: true });
47
+ for (const role of roles) {
48
+ const name = role.getName() ?? "";
49
+ if ((0, openservice_shared_1.isAssignableRoleName)(name, tenantId))
50
+ continue;
51
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot assign role ${name} to a ticket of tenant ${tenantId}.`);
52
+ }
53
+ }
54
+ /**
55
+ * Sets the ticket ACL from `createdBy`, `assignedUsers` and `assignedRoles` —
56
+ * each gets read/write. `assignedUsers`/`assignedRoles` are arrays of Parse
57
+ * pointers, so we iterate the entries (by object id) rather than the array
58
+ * indices. Parse ACL role grants require the role *name*, not its id, so the
59
+ * assigned role pointers are resolved to names first.
60
+ *
61
+ * This is the authority on who may write a ticket. It builds on the fresh
62
+ * default ACL `defaultAclHandler` has just set (od-admin, the tenant's admins,
63
+ * tenant-wide read), so everything granted here is derived from the ticket's
64
+ * current fields and nothing survives from an earlier save — taking someone
65
+ * off a ticket takes their access with them. The tenant-user write is denied
66
+ * explicitly all the same, to keep the decision readable in one place.
67
+ */
68
+ async function setTicketACL(object) {
69
+ const acl = object.getACL() ?? new node_1.default.ACL();
70
+ // deny global read / write
71
+ acl.setPublicReadAccess(false);
72
+ acl.setPublicWriteAccess(false);
73
+ // the tenant reads every ticket, but writes only its own / assigned ones
74
+ const tenantId = object.get("tenant")?.id;
75
+ if (tenantId) {
76
+ acl.setRoleReadAccess(`od-tenant-user-${tenantId}`, true);
77
+ acl.setRoleWriteAccess(`od-tenant-user-${tenantId}`, false);
78
+ }
79
+ // creator read/write
80
+ const creatorId = object.get("createdBy")?.id;
81
+ if (creatorId) {
82
+ acl.setReadAccess(creatorId, true);
83
+ acl.setWriteAccess(creatorId, true);
84
+ }
85
+ // assigned users read/write
86
+ for (const userId of (0, openservice_shared_1.refIds)(object.get("assignedUsers"))) {
87
+ acl.setReadAccess(userId, true);
88
+ acl.setWriteAccess(userId, true);
89
+ }
90
+ // assigned roles read/write (resolve pointer ids → role names)
91
+ const roleIds = (0, openservice_shared_1.refIds)(object.get("assignedRoles"));
92
+ if (roleIds.length > 0) {
93
+ const roles = await new node_1.default.Query(node_1.default.Role)
94
+ .containedIn("objectId", roleIds)
95
+ .find({ useMasterKey: true });
96
+ for (const role of roles) {
97
+ const name = role.getName();
98
+ if (name) {
99
+ acl.setRoleReadAccess(name, true);
100
+ acl.setRoleWriteAccess(name, true);
101
+ }
102
+ }
103
+ }
104
+ object.setACL(acl);
105
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Removes everything attached to a ticket after it is deleted for good — the
3
+ * archive's "delete permanently" promises that nothing of it is left.
4
+ *
5
+ * Parse cannot cascade these on its own: meta head-data ({@link Meta_Entry})
6
+ * and chat messages ({@link Chat_Message}) link to the ticket by a plain string
7
+ * key rather than a pointer, and notifications reference it inside their JSON
8
+ * `data` blob. The ticket's files ({@link Assets}) — its file library and the
9
+ * attachments of its comments — share the chat's context; destroying an asset
10
+ * row also removes its stored file (see the `Assets` hook).
11
+ *
12
+ * **The history goes too**: every {@link Changelog} entry of the ticket — the
13
+ * delete entry the changelog's `beforeDelete` just wrote included — and of each
14
+ * row removed here. The rows are destroyed with `skipChangelog`, or each would
15
+ * write a delete entry holding its content straight back into the history.
16
+ *
17
+ * Left alone: child tickets (their `parent` pointer dangles; they are tickets
18
+ * of their own) and sent mails (`Core_Email` keeps a log of what went out,
19
+ * with no reference to the ticket that could be matched).
20
+ *
21
+ * This is the single cleanup path for both single deletes and the dev
22
+ * "delete all" command, so the frontend no longer needs to delete related data
23
+ * itself.
24
+ */
25
+ export declare function cleanupTicketRelations(ticketId: string): Promise<void>;
@@ -0,0 +1,65 @@
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.cleanupTicketRelations = cleanupTicketRelations;
7
+ // The cascade that removes everything attached to a ticket deleted for good.
8
+ const node_1 = __importDefault(require("parse/node"));
9
+ const index_js_1 = require("../../../types/index.js");
10
+ const openservice_shared_1 = require("@opendash/openservice-shared");
11
+ /**
12
+ * Removes everything attached to a ticket after it is deleted for good — the
13
+ * archive's "delete permanently" promises that nothing of it is left.
14
+ *
15
+ * Parse cannot cascade these on its own: meta head-data ({@link Meta_Entry})
16
+ * and chat messages ({@link Chat_Message}) link to the ticket by a plain string
17
+ * key rather than a pointer, and notifications reference it inside their JSON
18
+ * `data` blob. The ticket's files ({@link Assets}) — its file library and the
19
+ * attachments of its comments — share the chat's context; destroying an asset
20
+ * row also removes its stored file (see the `Assets` hook).
21
+ *
22
+ * **The history goes too**: every {@link Changelog} entry of the ticket — the
23
+ * delete entry the changelog's `beforeDelete` just wrote included — and of each
24
+ * row removed here. The rows are destroyed with `skipChangelog`, or each would
25
+ * write a delete entry holding its content straight back into the history.
26
+ *
27
+ * Left alone: child tickets (their `parent` pointer dangles; they are tickets
28
+ * of their own) and sent mails (`Core_Email` keeps a log of what went out,
29
+ * with no reference to the ticket that could be matched).
30
+ *
31
+ * This is the single cleanup path for both single deletes and the dev
32
+ * "delete all" command, so the frontend no longer needs to delete related data
33
+ * itself.
34
+ */
35
+ async function cleanupTicketRelations(ticketId) {
36
+ const context = (0, openservice_shared_1.ticketContextKey)(ticketId);
37
+ const [metaEntries, chatMessages, assets, notifications] = await Promise.all([
38
+ new node_1.default.Query(index_js_1.Meta_Entry)
39
+ .equalTo("entryClassName", index_js_1.Service_Ticket.className)
40
+ .equalTo("entryObjectId", ticketId)
41
+ .findAll({ useMasterKey: true }),
42
+ new node_1.default.Query(index_js_1.Chat_Message)
43
+ .equalTo("context", context)
44
+ .findAll({ useMasterKey: true }),
45
+ new node_1.default.Query(index_js_1.Assets)
46
+ .equalTo("context", context)
47
+ .findAll({ useMasterKey: true }),
48
+ // `data` is a JSON Object column; Parse supports dot-notation into it. Query
49
+ // by class name (untyped) so the `data.ticketId` path key is accepted.
50
+ new node_1.default.Query(index_js_1.Notification.className)
51
+ .equalTo("data.ticketId", ticketId)
52
+ .findAll({ useMasterKey: true }),
53
+ ]);
54
+ // Both steps run even if one fails: a chat message that could not be removed
55
+ // is no reason to keep the ticket's whole history.
56
+ const failures = [];
57
+ await node_1.default.Object.destroyAll([...metaEntries, ...chatMessages, ...assets, ...notifications], { useMasterKey: true, context: { skipChangelog: true } }).catch((error) => failures.push(error));
58
+ const historyOf = (className, rows) => new node_1.default.Query(index_js_1.Changelog).equalTo("nameOfClass", className).containedIn("changedObject", rows.map((row) => row.id));
59
+ const history = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Changelog)
60
+ .equalTo("nameOfClass", index_js_1.Service_Ticket.className)
61
+ .equalTo("changedObject", ticketId), historyOf(index_js_1.Meta_Entry.className, metaEntries), historyOf(index_js_1.Chat_Message.className, chatMessages), historyOf(index_js_1.Assets.className, assets), historyOf(index_js_1.Notification.className, notifications)).findAll({ useMasterKey: true });
62
+ await node_1.default.Object.destroyAll(history, { useMasterKey: true }).catch((error) => failures.push(error));
63
+ if (failures.length > 0)
64
+ throw failures[0];
65
+ }
@@ -0,0 +1,2 @@
1
+ /** The assignee and watcher notifications of one save. Never throws. */
2
+ export declare function notifyAboutSave(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined): Promise<void>;
@@ -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>;