@openinc/parse-server-opendash 4.24.1 → 4.26.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 (55) 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/ticketArchive.d.ts +54 -0
  9. package/dist/features/openservice/tickets/ticketArchive.js +112 -0
  10. package/dist/features/openservice/tickets/ticketCleanup.d.ts +25 -0
  11. package/dist/features/openservice/tickets/ticketCleanup.js +65 -0
  12. package/dist/features/openservice/tickets/ticketFormConfig.d.ts +20 -0
  13. package/dist/features/openservice/tickets/ticketFormConfig.js +74 -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/ticketPriority.d.ts +47 -0
  19. package/dist/features/openservice/tickets/ticketPriority.js +103 -0
  20. package/dist/features/openservice/tickets/ticketReferences.d.ts +61 -0
  21. package/dist/features/openservice/tickets/ticketReferences.js +235 -0
  22. package/dist/features/permissions/types/Permissions.d.ts +1 -0
  23. package/dist/features/permissions/types/Permissions.js +5 -2
  24. package/dist/features/schema/indexes.js +22 -2
  25. package/dist/features/schema/services/ensureIndexes.js +11 -2
  26. package/dist/functions/openinc-backfill-ticket-sort-keys.d.ts +3 -2
  27. package/dist/functions/openinc-backfill-ticket-sort-keys.js +3 -2
  28. package/dist/functions/openinc-openservice-form-config.d.ts +20 -0
  29. package/dist/functions/openinc-openservice-form-config.js +51 -0
  30. package/dist/helper/getUserLanguage.d.ts +3 -5
  31. package/dist/helper/getUserLanguage.js +7 -16
  32. package/dist/helper/roleNames.d.ts +7 -0
  33. package/dist/helper/roleNames.js +21 -0
  34. package/dist/helper/ticketSortKeys.d.ts +8 -9
  35. package/dist/helper/ticketSortKeys.js +21 -23
  36. package/dist/helper/updateWithoutTriggers.d.ts +22 -0
  37. package/dist/helper/updateWithoutTriggers.js +57 -0
  38. package/dist/hooks/Chat_Message.js +7 -30
  39. package/dist/hooks/Meta_Entry.js +6 -1
  40. package/dist/hooks/Service_Equipment.js +2 -1
  41. package/dist/hooks/Service_FormConfig.js +6 -5
  42. package/dist/hooks/Service_Project.js +2 -1
  43. package/dist/hooks/Service_Status.js +3 -6
  44. package/dist/hooks/Service_Tag.js +51 -11
  45. package/dist/hooks/Service_Ticket.js +45 -702
  46. package/dist/scripts/migration/lib/ptr.d.ts +1 -1
  47. package/dist/scripts/migration/lib/ptr.js +3 -5
  48. package/dist/scripts/migration/lib/ticket.js +3 -2
  49. package/dist/scripts/repair-ticket-acl.js +3 -3
  50. package/dist/types/Service_Ticket.d.ts +6 -0
  51. package/dist/types/Service_Ticket.js +12 -0
  52. package/package.json +3 -1
  53. package/schema/Service_Ticket.json +6 -0
  54. package/dist/helper/pointerIds.d.ts +0 -17
  55. package/dist/helper/pointerIds.js +0 -45
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadReferencedRows = loadReferencedRows;
7
+ exports.assertSameTenantReferences = assertSameTenantReferences;
8
+ exports.applySortKeys = applySortKeys;
9
+ exports.applyClosedAt = applyClosedAt;
10
+ // The rows a ticket points at (status, project, equipment, tags): one load,
11
+ // then the tenant check and the values derived from them — sort keys, closedAt.
12
+ const node_1 = __importDefault(require("parse/node"));
13
+ const index_js_1 = require("../../../types/index.js");
14
+ const openservice_shared_1 = require("@opendash/openservice-shared");
15
+ /** Pointer fields on a ticket that must belong to the ticket's own tenant. */
16
+ const TENANT_SCOPED_POINTERS = ["status", "project", "equipment"];
17
+ /**
18
+ * Pointer-array fields whose entries must belong to the ticket's own tenant,
19
+ * with the class the entries point at.
20
+ *
21
+ * The class is spelled out because the entity adapter stores such arrays as
22
+ * plain id **strings** (see `refIds`) — there is no `className` to read
23
+ * off an entry. Reading `.id` off them, as this guard used to, judged nothing.
24
+ *
25
+ * Not `assignedUsers`: people work across tenants — a customer assigns the
26
+ * service provider's staff to its tickets — so an assignee of another tenant
27
+ * is legitimate. Who can be picked is what the assigner may read; the ticket
28
+ * ACL then grants the assignee access. `assignedRoles` has its own guard,
29
+ * {@link assertAssignableRoles}: a role's tenant lives in its name.
30
+ */
31
+ const TENANT_SCOPED_POINTER_ARRAYS = {
32
+ tags: index_js_1.Service_Tag.className,
33
+ };
34
+ /**
35
+ * Shadow columns the ticket carries so the table can sort by a pointer.
36
+ *
37
+ * Parse sorts a pointer column by the stored reference, which is the object id —
38
+ * ordering by it looks random. Sorting by the referenced *label* needs the value
39
+ * on the ticket itself, so these three are kept in step here, where the
40
+ * referenced rows are being read anyway.
41
+ */
42
+ const SORT_KEY_FIELDS = {
43
+ status: "statusOrder",
44
+ project: "projectSortKey",
45
+ equipment: "equipmentSortKey",
46
+ };
47
+ /**
48
+ * Reads the rows a ticket's dirty pointer fields refer to, one query per class.
49
+ *
50
+ * Pointers arrive unfetched, so both the tenant check and the sort keys need a
51
+ * read — doing it once here is what keeps a save at a single extra query.
52
+ * `refreshSortKeys` reads every sort-key pointer, dirty or not.
53
+ */
54
+ async function loadReferencedRows(object, refreshSortKeys = false) {
55
+ const suspects = [];
56
+ for (const field of TENANT_SCOPED_POINTERS) {
57
+ const value = object.get(field);
58
+ if (!value)
59
+ continue;
60
+ // Also read a pointer whose sort key is missing, even when it has not
61
+ // changed: that is what lets a plain re-save fill in a ticket written
62
+ // before those columns existed, with no separate backfill path.
63
+ const hasSortKey = field in SORT_KEY_FIELDS;
64
+ const keyMissing = hasSortKey &&
65
+ object.get(SORT_KEY_FIELDS[field]) ==
66
+ null;
67
+ if (object.dirty(field) || keyMissing || (refreshSortKeys && hasSortKey))
68
+ suspects.push(value);
69
+ }
70
+ const byClass = new Map();
71
+ const add = (className, id) => {
72
+ const ids = byClass.get(className) ?? new Set();
73
+ ids.add(id);
74
+ byClass.set(className, ids);
75
+ };
76
+ for (const suspect of suspects) {
77
+ // A pointer that has not been saved yet has no id — nothing to look up.
78
+ if (suspect.id)
79
+ add(suspect.className, suspect.id);
80
+ }
81
+ for (const [field, className] of Object.entries(TENANT_SCOPED_POINTER_ARRAYS)) {
82
+ if (!object.dirty(field))
83
+ continue;
84
+ for (const id of (0, openservice_shared_1.refIds)(object.get(field)))
85
+ add(className, id);
86
+ }
87
+ const rows = new Map();
88
+ for (const [className, ids] of byClass) {
89
+ const found = await new node_1.default.Query(className)
90
+ .containedIn("objectId", [...ids])
91
+ // `label` and `order` feed the sort keys below, `category` the
92
+ // closing date; `tenant` the guard.
93
+ .select("tenant", "label", "order", "category")
94
+ .limit(ids.size)
95
+ .find({ useMasterKey: true });
96
+ for (const row of found)
97
+ rows.set(row.id, row);
98
+ }
99
+ return rows;
100
+ }
101
+ /**
102
+ * Rejects a ticket that references master data from another tenant.
103
+ *
104
+ * ACLs do not stop an `od-admin` at a tenant boundary, so every picker in the
105
+ * UI used to offer every tenant's statuses, projects, equipment and tags. The
106
+ * frontend now scopes those queries, but the UI is not the only write path —
107
+ * the generic entity admin and the REST API go straight through here — and a
108
+ * ticket pointing at a foreign status is silently broken: it is counted in
109
+ * neither tenant's board, and it blocks deletion of that status
110
+ * (`Service_Status`'s in-use guard does not filter by tenant either).
111
+ *
112
+ * `assignedRoles` is deliberately not checked: `_Role` has no tenant column at
113
+ * all — a role's tenant lives in its name — so there is nothing to compare.
114
+ * Nor is `assignedUsers` (see {@link TENANT_SCOPED_POINTER_ARRAYS}): people are
115
+ * not master data of one tenant.
116
+ */
117
+ function assertSameTenantReferences(object, rows) {
118
+ const tenantId = object.get("tenant")?.id;
119
+ if (!tenantId)
120
+ return; // nothing to compare against
121
+ // Only the dirty references are judged — the loaded set is wider than that
122
+ // (see `loadReferencedRows`), and a ticket that already carries a bad
123
+ // reference has to stay saveable so it can be repaired.
124
+ const judged = [];
125
+ for (const field of TENANT_SCOPED_POINTERS) {
126
+ if (!object.dirty(field))
127
+ continue;
128
+ const value = object.get(field);
129
+ const row = value?.id ? rows.get(value.id) : undefined;
130
+ if (row)
131
+ judged.push(row);
132
+ }
133
+ for (const field of Object.keys(TENANT_SCOPED_POINTER_ARRAYS)) {
134
+ if (!object.dirty(field))
135
+ continue;
136
+ for (const id of (0, openservice_shared_1.refIds)(object.get(field))) {
137
+ const row = rows.get(id);
138
+ if (row)
139
+ judged.push(row);
140
+ }
141
+ }
142
+ for (const row of judged) {
143
+ const refTenantId = row.get("tenant")?.id;
144
+ // No tenant on the referenced row = shared/global master data, allowed.
145
+ if (!refTenantId || refTenantId === tenantId)
146
+ continue;
147
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot reference ${row.className} ${row.id} from tenant ` +
148
+ `${refTenantId} on a ticket of tenant ${tenantId}.`);
149
+ }
150
+ }
151
+ /**
152
+ * Keeps {@link SORT_KEY_FIELDS} in step with the pointers they shadow.
153
+ *
154
+ * Only dirty pointers are touched, so a save that changes the title leaves the
155
+ * keys alone — unless `refresh` asks for all of them. Clearing a pointer clears
156
+ * its key, which sorts the ticket with the other unassigned ones rather than
157
+ * leaving a stale name behind.
158
+ */
159
+ function applySortKeys(object, rows, refresh = false) {
160
+ for (const [field, target] of Object.entries(SORT_KEY_FIELDS)) {
161
+ const pointer = object.get(field);
162
+ const keyMissing = pointer && object.get(target) == null;
163
+ if (!object.dirty(field) && !keyMissing && !refresh)
164
+ continue;
165
+ const row = pointer?.id ? rows.get(pointer.id) : undefined;
166
+ if (!row) {
167
+ object.unset(target);
168
+ continue;
169
+ }
170
+ // Status sorts by its configured workflow position, not by its name: a
171
+ // board reads "Eingang, In Bearbeitung, Erledigt", never alphabetically.
172
+ const value = field === "status" ? row.get("order") : (0, openservice_shared_1.sortKeyOf)(row.get("label"));
173
+ if (value === undefined || value === null)
174
+ object.unset(target);
175
+ else
176
+ object.set(target, value);
177
+ }
178
+ }
179
+ /**
180
+ * Stamps and clears `closedAt` from the ticket's status.
181
+ *
182
+ * **Why the server and not the form.** `closedAt` is the only record of when
183
+ * work finished, and every number built on it — throughput, how long a ticket
184
+ * sat open, what a month closed — is wrong if it is missing on some tickets and
185
+ * guessed on others. It was a plain date field nobody filled: the board moves a
186
+ * ticket to "Erledigt" by drag and drop, the detail page by a dropdown, the
187
+ * rules by an action, and none of them went near it. Doing it here covers every
188
+ * one of those paths plus the import and the REST API, which is the whole point
189
+ * of putting it in `beforeSave`.
190
+ *
191
+ * **The status decides, not the field.** A status counts as closing when its
192
+ * `category` is finished by `isDoneCategory` (`@opendash/openservice-shared`)
193
+ * — the same rule the alarm tickets, the scheduler and the frontend apply, so "Erledigt", "Abgebrochen" and whatever a
194
+ * tenant calls them agree without anybody configuring it twice.
195
+ *
196
+ * Reopening clears the stamp. A ticket that goes back to "In Bearbeitung" is
197
+ * not closed, and leaving the old date would quietly count it as finished in
198
+ * every evaluation while it is being worked on again.
199
+ *
200
+ * **A value the caller sent wins.** A `closedAt` named in this same save — the
201
+ * migration replaying history, an import, a correction in the admin table — is
202
+ * kept; overwriting it with `now` would be this function deciding it knows
203
+ * better.
204
+ */
205
+ function applyClosedAt(object, rows) {
206
+ // Nothing to react to: the status is unchanged. A ticket whose status stayed
207
+ // put keeps whatever stamp it has, including none.
208
+ if (!object.dirty("status"))
209
+ return;
210
+ // Explicitly set in this save — see the note above. A new object is dirty in
211
+ // every attribute (the Parse SDK answers `dirty()` with `true` while there is
212
+ // no id), so on create only a value counts as sent: asking `dirty` there left
213
+ // every ticket created in a finished status without a `closedAt`.
214
+ const sent = object.isNew()
215
+ ? object.get("closedAt") != null
216
+ : object.dirty("closedAt");
217
+ if (sent)
218
+ return;
219
+ const status = object.get("status");
220
+ const row = status?.id ? rows.get(status.id) : undefined;
221
+ // The row is only missing when the pointer could not be read. Guessing either
222
+ // way would be worse than leaving the stamp as it is.
223
+ if (!row)
224
+ return;
225
+ const closing = (0, openservice_shared_1.isDoneCategory)(row.get("category"));
226
+ if (closing) {
227
+ // Already stamped: the ticket moved between two closing statuses
228
+ // ("Erledigt" → "Abgebrochen"). It closed when it first closed.
229
+ if (!object.get("closedAt"))
230
+ object.set("closedAt", new Date());
231
+ }
232
+ else {
233
+ object.unset("closedAt");
234
+ }
235
+ }
@@ -25,6 +25,7 @@ export declare namespace Permissions {
25
25
  ticket_access = "openservice-ticket:can-access-ticket-plugin",
26
26
  ticket_create = "openservice-ticket:can-create-ticket",
27
27
  ticket_delete = "openservice-ticket:can-delete-ticket",
28
+ ticket_purge = "openservice-ticket:can-purge-ticket",
28
29
  ticket_analytics_view = "openservice-ticket:can-view-analytics",
29
30
  schedule_access = "openservice-schedule:can-access-schedule-plugin",
30
31
  schedule_create = "openservice-schedule:can-create-schedule",
@@ -49,11 +49,14 @@ var Permissions;
49
49
  //
50
50
  // No `read`, `edit` or `assign`: the ticket's ACL decides those per
51
51
  // record. `create` has no record yet whose ACL could be asked. `delete`
52
- // covers archiving, which is an update the ACL would grant to everybody
53
- // assigned to the ticket.
52
+ // covers archiving and restoring, which are updates the ACL would grant to
53
+ // everybody assigned to the ticket. `purge` is the hard delete from the
54
+ // archive: it destroys the ticket with everything attached, its history
55
+ // included, and cannot be undone — so it is granted separately.
54
56
  SERVICE["ticket_access"] = "openservice-ticket:can-access-ticket-plugin";
55
57
  SERVICE["ticket_create"] = "openservice-ticket:can-create-ticket";
56
58
  SERVICE["ticket_delete"] = "openservice-ticket:can-delete-ticket";
59
+ SERVICE["ticket_purge"] = "openservice-ticket:can-purge-ticket";
57
60
  // The ticket evaluations page. Its own key rather than the schedule
58
61
  // plugin's `analytics_view`: a tenant may well want its shift leads to see
59
62
  // ticket throughput without opening up maintenance compliance, and the two
@@ -6,7 +6,9 @@ const index_js_1 = require("../../types/index.js");
6
6
  * Declares indexes of `type`, by name. Field names are checked against the
7
7
  * generated class, so renaming a field breaks the build instead of leaving an
8
8
  * index on a column nobody writes. A pointer is indexed by its name — the
9
- * adapter turns it into `_p_<field>`, `createdAt` into `_created_at`.
9
+ * adapter turns it into `_p_<field>`, `createdAt` into `_created_at`. A key
10
+ * inside an `Object` column is indexed by its dotted path, which Mongo indexes
11
+ * as it is.
10
12
  *
11
13
  * Parse's own classes have no generated class, only a type: pass their fixed
12
14
  * name and the attributes type, `defineIndexes<_SessionAttributes>("_Session", …)`.
@@ -67,9 +69,14 @@ exports.INDEXES = [
67
69
  defineIndexes(index_js_1.UserData, {
68
70
  od_user_key: ["user", "key"],
69
71
  }),
70
- // Notification drawer and unread badge.
72
+ // Notification drawer and unread badge. By ticket: deleting a ticket for
73
+ // good removes its notifications, and the scheduler's due reminders look up
74
+ // what they already sent every 5 minutes (`data.ruleId` + `data.ticketId`
75
+ // `$in`). Without it both read every notification ever sent — measured
76
+ // locally at 500 000 rows: ~170 ms per ticket scanning, under 1 ms indexed.
71
77
  defineIndexes(index_js_1.Notification, {
72
78
  od_user_read_createdAt: ["user", "read", "createdAt"],
79
+ od_data_ticketId: ["data.ticketId"],
73
80
  }),
74
81
  // Open chats poll every 5 s.
75
82
  defineIndexes(index_js_1.Chat_Message, {
@@ -118,6 +125,19 @@ exports.INDEXES = [
118
125
  // archived side is the one that keeps growing, so it must not be sorted in
119
126
  // memory.
120
127
  od_tenant_deleted_updatedAt: ["tenant", "deleted", "updatedAt"],
128
+ // Sorting the dashboard table by status, project or equipment: a pointer
129
+ // sorts by its shadow column (`statusOrder`, `projectSortKey`,
130
+ // `equipmentSortKey`), and without these Mongo sorted every live ticket of
131
+ // the tenant in memory for each page. By number: the default "Nr." column
132
+ // and the archive's `#123` lookup.
133
+ od_tenant_deleted_statusOrder: ["tenant", "deleted", "statusOrder"],
134
+ od_tenant_deleted_projectSortKey: ["tenant", "deleted", "projectSortKey"],
135
+ od_tenant_deleted_equipmentSortKey: [
136
+ "tenant",
137
+ "deleted",
138
+ "equipmentSortKey",
139
+ ],
140
+ od_tenant_deleted_number: ["tenant", "deleted", "number"],
121
141
  od_status_dueDate: ["status", "dueDate"],
122
142
  od_equipment_dueDate: ["equipment", "dueDate"],
123
143
  od_project_dueDate: ["project", "dueDate"],
@@ -44,13 +44,22 @@ function storageAdapter() {
44
44
  * a column nobody writes. Two array fields in one index are worse: Mongo
45
45
  * builds it, then refuses every save of a row that has both arrays set
46
46
  * ("cannot index parallel arrays").
47
+ *
48
+ * A dotted field (`data.ticketId`) is a key inside an `Object` column: the
49
+ * column has to exist and be one. What the key holds is up to the writers —
50
+ * the schema does not describe it.
47
51
  */
48
52
  function invalidReason(schema, fields) {
49
- const missing = fields.filter((field) => !schema.fields[field]);
53
+ const column = (field) => field.split(".")[0];
54
+ const missing = fields.filter((field) => !schema.fields[column(field)]);
50
55
  if (missing.length > 0) {
51
56
  return `unknown field(s) ${missing.join(", ")}`;
52
57
  }
53
- const arrays = fields.filter((field) => schema.fields[field].type === "Array");
58
+ const notObjects = fields.filter((field) => field.includes(".") && schema.fields[column(field)].type !== "Object");
59
+ if (notObjects.length > 0) {
60
+ return `path into a column that is not an Object (${notObjects.join(", ")})`;
61
+ }
62
+ const arrays = fields.filter((field) => schema.fields[column(field)].type === "Array");
54
63
  if (arrays.length > 1) {
55
64
  return `more than one array field (${arrays.join(", ")})`;
56
65
  }
@@ -2,8 +2,9 @@
2
2
  * Fills the sort shadow columns of one ticket — a Parse Dashboard script, run
3
3
  * from "Run script on selected row" in the data browser.
4
4
  *
5
- * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived in
6
- * `hooks/Service_Ticket.ts` when a ticket is saved, so every ticket written
5
+ * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived by the
6
+ * ticket's `beforeSave` (`applySortKeys` in
7
+ * `features/openservice/tickets/ticketReferences.ts`) when a ticket is saved, so every ticket written
7
8
  * before those columns existed sorts as empty until it is touched once.
8
9
  *
9
10
  * All this does is re-save the row. The hook fills a missing key even when the
@@ -10,8 +10,9 @@ const index_js_1 = require("../types/index.js");
10
10
  * Fills the sort shadow columns of one ticket — a Parse Dashboard script, run
11
11
  * from "Run script on selected row" in the data browser.
12
12
  *
13
- * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived in
14
- * `hooks/Service_Ticket.ts` when a ticket is saved, so every ticket written
13
+ * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived by the
14
+ * ticket's `beforeSave` (`applySortKeys` in
15
+ * `features/openservice/tickets/ticketReferences.ts`) when a ticket is saved, so every ticket written
15
16
  * before those columns existed sorts as empty until it is touched once.
16
17
  *
17
18
  * All this does is re-save the row. The hook fills a missing key even when the
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The ticket form config that applies to the caller — for the create form,
3
+ * the detail edit and the import of `@opendash/plugin-openservice-ticket`.
4
+ *
5
+ * Params: `{ tenant?: string }`, the active tenant (default: the caller's
6
+ * own). Returns `{ id: string | null }`; `null` means the built-in form.
7
+ *
8
+ * **Why a function.** Resolution goes by the caller's roles, inherited ones
9
+ * included, and the browser cannot resolve them: it knows its roles by name, a
10
+ * config names them by id, and a role the caller may not read cannot be looked
11
+ * up. The ticket hook takes the priority formula from the same resolution
12
+ * (`applicableFormConfig`), so the form and the server never pick different
13
+ * configs.
14
+ *
15
+ * Only an id comes back, and only one of a config the caller can read — its
16
+ * audience ACL grants that to the users and roles it names — so the answer
17
+ * reveals nothing the caller could not list anyway. The browser reads the
18
+ * config itself with its own session.
19
+ */
20
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const ticketFormConfig_js_1 = require("../features/openservice/tickets/ticketFormConfig.js");
9
+ const index_js_1 = require("../types/index.js");
10
+ /**
11
+ * The ticket form config that applies to the caller — for the create form,
12
+ * the detail edit and the import of `@opendash/plugin-openservice-ticket`.
13
+ *
14
+ * Params: `{ tenant?: string }`, the active tenant (default: the caller's
15
+ * own). Returns `{ id: string | null }`; `null` means the built-in form.
16
+ *
17
+ * **Why a function.** Resolution goes by the caller's roles, inherited ones
18
+ * included, and the browser cannot resolve them: it knows its roles by name, a
19
+ * config names them by id, and a role the caller may not read cannot be looked
20
+ * up. The ticket hook takes the priority formula from the same resolution
21
+ * (`applicableFormConfig`), so the form and the server never pick different
22
+ * configs.
23
+ *
24
+ * Only an id comes back, and only one of a config the caller can read — its
25
+ * audience ACL grants that to the users and roles it names — so the answer
26
+ * reveals nothing the caller could not list anyway. The browser reads the
27
+ * config itself with its own session.
28
+ */
29
+ async function init(name) {
30
+ node_1.default.Cloud.define(name, async (request) => {
31
+ const user = request.user;
32
+ const sessionToken = user?.getSessionToken();
33
+ if (!user || !sessionToken) {
34
+ throw new node_1.default.Error(node_1.default.Error.INVALID_SESSION_TOKEN, `${name} requires a logged-in user`);
35
+ }
36
+ const requested = request.params?.tenant;
37
+ if (requested !== undefined && typeof requested !== "string") {
38
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name}: tenant must be an object id`);
39
+ }
40
+ const tenant = requested
41
+ ? index_js_1.Tenant.createWithoutData(requested)
42
+ : user.get("tenant");
43
+ const config = await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user);
44
+ if (!config?.id)
45
+ return { id: null };
46
+ const readable = await new node_1.default.Query(index_js_1.Service_FormConfig)
47
+ .equalTo("objectId", config.id)
48
+ .first({ sessionToken });
49
+ return { id: readable?.id ?? null };
50
+ }, { requireUser: true });
51
+ }
@@ -10,10 +10,8 @@ import { _User } from "../types/index.js";
10
10
  * `preferred_language` off it yields `undefined`. The row is fetched here
11
11
  * when its data is missing.
12
12
  * - **Code format.** The settings store ISO 639-2 codes (`"deu"`, the default
13
- * `ensureSettings` writes; `"eng"`), not the server's locale names. Matched
14
- * leniently on the language, so `"de"`, `"de-DE"` and `"deu"` all work.
15
- *
16
- * A language the server has no translations for (Dutch, Chinese) gets English
17
- * rather than German.
13
+ * `ensureSettings` writes; `"eng"`), not the server's locale names. How a code
14
+ * maps is `toServerLanguage` in `@opendash/openservice-shared`, which the
15
+ * scheduler's reminders use as well.
18
16
  */
19
17
  export declare function getUserLanguage(recipient: _User): Promise<string>;
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getUserLanguage = getUserLanguage;
4
- /** What a recipient gets when nothing says otherwise. */
5
- const DEFAULT_LANGUAGE = "de-DE";
4
+ const openservice_shared_1 = require("@opendash/openservice-shared");
6
5
  /**
7
6
  * The language to write to `recipient` in, as the server's translations are
8
7
  * keyed: `"de-DE"` or `"en-US"` (see `initTranslation`).
@@ -14,29 +13,21 @@ const DEFAULT_LANGUAGE = "de-DE";
14
13
  * `preferred_language` off it yields `undefined`. The row is fetched here
15
14
  * when its data is missing.
16
15
  * - **Code format.** The settings store ISO 639-2 codes (`"deu"`, the default
17
- * `ensureSettings` writes; `"eng"`), not the server's locale names. Matched
18
- * leniently on the language, so `"de"`, `"de-DE"` and `"deu"` all work.
19
- *
20
- * A language the server has no translations for (Dutch, Chinese) gets English
21
- * rather than German.
16
+ * `ensureSettings` writes; `"eng"`), not the server's locale names. How a code
17
+ * maps is `toServerLanguage` in `@opendash/openservice-shared`, which the
18
+ * scheduler's reminders use as well.
22
19
  */
23
20
  async function getUserLanguage(recipient) {
24
21
  let settings = recipient.get("settings");
25
22
  if (!settings)
26
- return DEFAULT_LANGUAGE;
23
+ return openservice_shared_1.DEFAULT_SERVER_LANGUAGE;
27
24
  if (!settings.isDataAvailable()) {
28
25
  try {
29
26
  settings = await settings.fetch({ useMasterKey: true });
30
27
  }
31
28
  catch {
32
- return DEFAULT_LANGUAGE;
29
+ return openservice_shared_1.DEFAULT_SERVER_LANGUAGE;
33
30
  }
34
31
  }
35
- const code = settings.get("preferred_language");
36
- if (typeof code !== "string" || code.trim() === "")
37
- return DEFAULT_LANGUAGE;
38
- const language = code.trim().toLowerCase();
39
- if (language.startsWith("de"))
40
- return "de-DE";
41
- return "en-US";
32
+ return (0, openservice_shared_1.toServerLanguage)(settings.get("preferred_language"));
42
33
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Role **names** for an array-of-ref field holding role pointers.
3
+ *
4
+ * `Parse.ACL` grants roles by name, never by id, so a role reference has to be
5
+ * resolved before it can be written into an ACL.
6
+ */
7
+ export declare function roleNames(Parse: typeof import("parse/node").default, value: unknown): Promise<string[]>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roleNames = roleNames;
4
+ const openservice_shared_1 = require("@opendash/openservice-shared");
5
+ /**
6
+ * Role **names** for an array-of-ref field holding role pointers.
7
+ *
8
+ * `Parse.ACL` grants roles by name, never by id, so a role reference has to be
9
+ * resolved before it can be written into an ACL.
10
+ */
11
+ async function roleNames(Parse, value) {
12
+ const ids = (0, openservice_shared_1.refIds)(value);
13
+ if (ids.length === 0)
14
+ return [];
15
+ const roles = await new Parse.Query(Parse.Role)
16
+ .containedIn("objectId", ids)
17
+ .find({ useMasterKey: true });
18
+ return roles
19
+ .map((role) => role.getName())
20
+ .filter((name) => !!name);
21
+ }
@@ -10,16 +10,10 @@
10
10
  *
11
11
  * Same shape as the tag closure reconciliation in `Service_Tag`: an invariant
12
12
  * that has to hold for every write path, which only a backend trigger can
13
- * guarantee.
13
+ * guarantee. The label keys come from `sortKeyOf` in
14
+ * `@opendash/openservice-shared`, the same function the ticket's own
15
+ * `beforeSave` uses.
14
16
  */
15
- /**
16
- * Comparable form of a label — identical to the one in `hooks/Service_Ticket`.
17
- *
18
- * MongoDB compares strings byte by byte, so "Ökowerk" would sort behind
19
- * "Zementwerk". Folding the diacritics puts it at "O", which is what German
20
- * readers expect (DIN 5007-1).
21
- */
22
- export declare function sortKeyOf(label: unknown): string | undefined;
23
17
  /**
24
18
  * Writes `value` into `targetField` on every live ticket pointing at `row`.
25
19
  *
@@ -32,6 +26,11 @@ export declare function sortKeyOf(label: unknown): string | undefined;
32
26
  * every key then. They are also what grows without bound: finished tickets are
33
27
  * archived automatically, so reordering "Done" would otherwise rewrite every
34
28
  * ticket ever finished.
29
+ *
30
+ * One database update for all of them, without triggers, changelog entries or
31
+ * a new `updatedAt` — see {@link updateWithoutTriggers}. Saving each ticket
32
+ * instead (the fallback) also told the auto-archive they had just been worked
33
+ * on.
35
34
  */
36
35
  export declare function pushSortKeyToTickets(pointerField: "status" | "project" | "equipment", targetField: "statusOrder" | "projectSortKey" | "equipmentSortKey", row: Parse.Object, value: number | string | undefined): Promise<number>;
37
36
  /**
@@ -3,11 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sortKeyOf = sortKeyOf;
7
6
  exports.pushSortKeyToTickets = pushSortKeyToTickets;
8
7
  exports.derivedValueChanged = derivedValueChanged;
9
8
  const node_1 = __importDefault(require("parse/node"));
10
9
  const index_js_1 = require("../types/index.js");
10
+ const updateWithoutTriggers_js_1 = require("./updateWithoutTriggers.js");
11
11
  /**
12
12
  * Keeps the tickets' sort shadow columns in step when the referenced master
13
13
  * data is renamed or reordered.
@@ -20,27 +20,10 @@ const index_js_1 = require("../types/index.js");
20
20
  *
21
21
  * Same shape as the tag closure reconciliation in `Service_Tag`: an invariant
22
22
  * that has to hold for every write path, which only a backend trigger can
23
- * guarantee.
23
+ * guarantee. The label keys come from `sortKeyOf` in
24
+ * `@opendash/openservice-shared`, the same function the ticket's own
25
+ * `beforeSave` uses.
24
26
  */
25
- /**
26
- * Comparable form of a label — identical to the one in `hooks/Service_Ticket`.
27
- *
28
- * MongoDB compares strings byte by byte, so "Ökowerk" would sort behind
29
- * "Zementwerk". Folding the diacritics puts it at "O", which is what German
30
- * readers expect (DIN 5007-1).
31
- */
32
- function sortKeyOf(label) {
33
- if (typeof label !== "string")
34
- return undefined;
35
- const trimmed = label.trim();
36
- if (!trimmed)
37
- return undefined;
38
- return trimmed
39
- .normalize("NFD")
40
- .replace(/\p{Diacritic}/gu, "")
41
- .replace(/ß/g, "ss")
42
- .toLowerCase();
43
- }
44
27
  /**
45
28
  * Writes `value` into `targetField` on every live ticket pointing at `row`.
46
29
  *
@@ -53,12 +36,24 @@ function sortKeyOf(label) {
53
36
  * every key then. They are also what grows without bound: finished tickets are
54
37
  * archived automatically, so reordering "Done" would otherwise rewrite every
55
38
  * ticket ever finished.
39
+ *
40
+ * One database update for all of them, without triggers, changelog entries or
41
+ * a new `updatedAt` — see {@link updateWithoutTriggers}. Saving each ticket
42
+ * instead (the fallback) also told the auto-archive they had just been worked
43
+ * on.
56
44
  */
57
45
  async function pushSortKeyToTickets(pointerField, targetField, row, value) {
46
+ const tenant = row.get("tenant");
47
+ const changed = await (0, updateWithoutTriggers_js_1.updateWithoutTriggers)(index_js_1.Service_Ticket.className, {
48
+ [pointerField]: (0, updateWithoutTriggers_js_1.restPointer)(row),
49
+ deleted: { $ne: true },
50
+ ...(tenant ? { tenant: (0, updateWithoutTriggers_js_1.restPointer)(tenant) } : {}),
51
+ }, { [targetField]: value === undefined ? { __op: "Delete" } : value });
52
+ if (changed !== undefined)
53
+ return changed;
58
54
  const query = new node_1.default.Query(index_js_1.Service_Ticket)
59
55
  .equalTo(pointerField, row)
60
56
  .notEqualTo("deleted", true);
61
- const tenant = row.get("tenant");
62
57
  if (tenant)
63
58
  query.equalTo("tenant", tenant);
64
59
  const affected = await query.findAll({ useMasterKey: true });
@@ -70,7 +65,10 @@ async function pushSortKeyToTickets(pointerField, targetField, row, value) {
70
65
  else
71
66
  ticket.set(targetField, value);
72
67
  }
73
- await node_1.default.Object.saveAll(affected, { useMasterKey: true });
68
+ await node_1.default.Object.saveAll(affected, {
69
+ useMasterKey: true,
70
+ context: { skipChangelog: true },
71
+ });
74
72
  return affected.length;
75
73
  }
76
74
  /**