@openinc/parse-server-opendash 4.11.1 → 4.13.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.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Fills the sort shadow columns of one ticket — a Parse Dashboard script, run
3
+ * from "Run script on selected row" in the data browser.
4
+ *
5
+ * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived in
6
+ * `hooks/Service_Ticket.ts` when a ticket is saved, so every ticket written
7
+ * before those columns existed sorts as empty until it is touched once.
8
+ *
9
+ * All this does is re-save the row. The hook fills a missing key even when the
10
+ * pointer has not changed, so a plain save is the whole repair — and running it
11
+ * on a ticket that already has its keys changes nothing but `updatedAt`.
12
+ *
13
+ * Select the rows in the data browser (the whole page at a time works) and run
14
+ * it; it is safe to repeat.
15
+ *
16
+ * @param name The function name, derived from the file name.
17
+ */
18
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../types/index.js");
9
+ /**
10
+ * Fills the sort shadow columns of one ticket — a Parse Dashboard script, run
11
+ * from "Run script on selected row" in the data browser.
12
+ *
13
+ * `statusOrder`, `projectSortKey` and `equipmentSortKey` are derived in
14
+ * `hooks/Service_Ticket.ts` when a ticket is saved, so every ticket written
15
+ * before those columns existed sorts as empty until it is touched once.
16
+ *
17
+ * All this does is re-save the row. The hook fills a missing key even when the
18
+ * pointer has not changed, so a plain save is the whole repair — and running it
19
+ * on a ticket that already has its keys changes nothing but `updatedAt`.
20
+ *
21
+ * Select the rows in the data browser (the whole page at a time works) and run
22
+ * it; it is safe to repeat.
23
+ *
24
+ * @param name The function name, derived from the file name.
25
+ */
26
+ async function init(name) {
27
+ node_1.default.Cloud.define(name, async function (request) {
28
+ const object = request.params.object;
29
+ // Thrown rather than returned: the dashboard surfaces a rejection as an
30
+ // error toast, while any resolved value reads as success.
31
+ if (!object) {
32
+ throw new node_1.default.Error(node_1.default.Error.INVALID_JSON, "No object was passed. Run this from the data browser on a selected row.");
33
+ }
34
+ if (object.className !== index_js_1.Service_Ticket.className) {
35
+ throw new node_1.default.Error(node_1.default.Error.INVALID_CLASS_NAME, `Expected a ${index_js_1.Service_Ticket.className} row, got ${object.className}.`);
36
+ }
37
+ await object.save(null, { useMasterKey: true });
38
+ return {
39
+ success: true,
40
+ id: object.id,
41
+ // Reported back so the dashboard shows what the row ended up with,
42
+ // rather than just "done". A ticket without a project legitimately has
43
+ // no project key.
44
+ statusOrder: object.get("statusOrder") ?? null,
45
+ projectSortKey: object.get("projectSortKey") ?? null,
46
+ equipmentSortKey: object.get("equipmentSortKey") ?? null,
47
+ };
48
+ }, {
49
+ // Parse Dashboard runs scripts with the master key.
50
+ requireMaster: true,
51
+ });
52
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Extracts the object ids from an array-of-ref field, tolerating undefined and
3
+ * malformed entries.
4
+ *
5
+ * The entity adapter stores array-of-ref fields as plain id **strings**, not as
6
+ * `Parse.Object`s. Reading `.id` off them returned undefined, so an ACL built
7
+ * from such a field granted nobody anything — silently. Every consumer of
8
+ * `assignedUsers`, `assignedRoles`, `users` or `roles` has to go through here.
9
+ */
10
+ export declare function pointerIds(value: unknown): string[];
11
+ /**
12
+ * Role **names** for an array-of-ref field holding role pointers.
13
+ *
14
+ * `Parse.ACL` grants roles by name, never by id, so a role reference has to be
15
+ * resolved before it can be written into an ACL.
16
+ */
17
+ export declare function roleNames(Parse: typeof import("parse/node").default, value: unknown): Promise<string[]>;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pointerIds = pointerIds;
4
+ exports.roleNames = roleNames;
5
+ /**
6
+ * Extracts the object ids from an array-of-ref field, tolerating undefined and
7
+ * malformed entries.
8
+ *
9
+ * The entity adapter stores array-of-ref fields as plain id **strings**, not as
10
+ * `Parse.Object`s. Reading `.id` off them returned undefined, so an ACL built
11
+ * from such a field granted nobody anything — silently. Every consumer of
12
+ * `assignedUsers`, `assignedRoles`, `users` or `roles` has to go through here.
13
+ */
14
+ function pointerIds(value) {
15
+ if (!Array.isArray(value))
16
+ return [];
17
+ return value
18
+ .map((entry) => {
19
+ if (typeof entry === "string")
20
+ return entry;
21
+ if (entry && typeof entry === "object") {
22
+ const o = entry;
23
+ return o.id ?? o.objectId;
24
+ }
25
+ return undefined;
26
+ })
27
+ .filter((id) => typeof id === "string");
28
+ }
29
+ /**
30
+ * Role **names** for an array-of-ref field holding role pointers.
31
+ *
32
+ * `Parse.ACL` grants roles by name, never by id, so a role reference has to be
33
+ * resolved before it can be written into an ACL.
34
+ */
35
+ async function roleNames(Parse, value) {
36
+ const ids = pointerIds(value);
37
+ if (ids.length === 0)
38
+ return [];
39
+ const roles = await new Parse.Query(Parse.Role)
40
+ .containedIn("objectId", ids)
41
+ .find({ useMasterKey: true });
42
+ return roles
43
+ .map((role) => role.getName())
44
+ .filter((name) => !!name);
45
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Keeps the tickets' sort shadow columns in step when the referenced master
3
+ * data is renamed or reordered.
4
+ *
5
+ * `Service_Ticket`'s `beforeSave` derives `statusOrder`, `projectSortKey` and
6
+ * `equipmentSortKey` from the row a ticket points at — but only at the moment
7
+ * the ticket is saved. Renaming a project afterwards would leave every ticket
8
+ * sorting under the old name, so the owning class pushes the new value down
9
+ * from its own `afterSave`.
10
+ *
11
+ * Same shape as the tag closure reconciliation in `Service_Tag`: an invariant
12
+ * that has to hold for every write path, which only a backend trigger can
13
+ * guarantee.
14
+ */
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
+ /**
24
+ * Writes `value` into `targetField` on every ticket pointing at `row`.
25
+ *
26
+ * Narrowed to the row's own tenant where it has one: a referenced object can
27
+ * only be used by tickets of the same tenant, so there is no reason to scan
28
+ * — let alone touch — anybody else's data.
29
+ */
30
+ export declare function pushSortKeyToTickets(pointerField: "status" | "project" | "equipment", targetField: "statusOrder" | "projectSortKey" | "equipmentSortKey", row: Parse.Object, value: number | string | undefined): Promise<number>;
31
+ /**
32
+ * Did the value a sort key is derived from change with this save?
33
+ *
34
+ * `original` is undefined on create, where the ticket's own `beforeSave` has
35
+ * already set the key — so a create needs no push and this returns false.
36
+ */
37
+ export declare function derivedValueChanged(object: Parse.Object, original: Parse.Object | undefined, field: string): boolean;
@@ -0,0 +1,78 @@
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.sortKeyOf = sortKeyOf;
7
+ exports.pushSortKeyToTickets = pushSortKeyToTickets;
8
+ exports.derivedValueChanged = derivedValueChanged;
9
+ const node_1 = __importDefault(require("parse/node"));
10
+ const index_js_1 = require("../types/index.js");
11
+ /**
12
+ * Keeps the tickets' sort shadow columns in step when the referenced master
13
+ * data is renamed or reordered.
14
+ *
15
+ * `Service_Ticket`'s `beforeSave` derives `statusOrder`, `projectSortKey` and
16
+ * `equipmentSortKey` from the row a ticket points at — but only at the moment
17
+ * the ticket is saved. Renaming a project afterwards would leave every ticket
18
+ * sorting under the old name, so the owning class pushes the new value down
19
+ * from its own `afterSave`.
20
+ *
21
+ * Same shape as the tag closure reconciliation in `Service_Tag`: an invariant
22
+ * that has to hold for every write path, which only a backend trigger can
23
+ * guarantee.
24
+ */
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
+ /**
45
+ * Writes `value` into `targetField` on every ticket pointing at `row`.
46
+ *
47
+ * Narrowed to the row's own tenant where it has one: a referenced object can
48
+ * only be used by tickets of the same tenant, so there is no reason to scan
49
+ * — let alone touch — anybody else's data.
50
+ */
51
+ async function pushSortKeyToTickets(pointerField, targetField, row, value) {
52
+ const query = new node_1.default.Query(index_js_1.Service_Ticket).equalTo(pointerField, row);
53
+ const tenant = row.get("tenant");
54
+ if (tenant)
55
+ query.equalTo("tenant", tenant);
56
+ const affected = await query.findAll({ useMasterKey: true });
57
+ if (affected.length === 0)
58
+ return 0;
59
+ for (const ticket of affected) {
60
+ if (value === undefined)
61
+ ticket.unset(targetField);
62
+ else
63
+ ticket.set(targetField, value);
64
+ }
65
+ await node_1.default.Object.saveAll(affected, { useMasterKey: true });
66
+ return affected.length;
67
+ }
68
+ /**
69
+ * Did the value a sort key is derived from change with this save?
70
+ *
71
+ * `original` is undefined on create, where the ticket's own `beforeSave` has
72
+ * already set the key — so a create needs no push and this returns false.
73
+ */
74
+ function derivedValueChanged(object, original, field) {
75
+ if (!original)
76
+ return false;
77
+ return object.get(field) !== original.get(field);
78
+ }
@@ -6,6 +6,7 @@ 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 ticketSortKeys_js_1 = require("../helper/ticketSortKeys.js");
9
10
  const index_js_2 = require("../types/index.js");
10
11
  async function init() {
11
12
  // Soft delete: tickets and meter readings point at equipment, so it is
@@ -18,9 +19,13 @@ async function init() {
18
19
  await (0, index_js_1.defaultAclHandler)(request);
19
20
  // TODO
20
21
  });
21
- (0, index_js_1.afterSaveHook)(index_js_2.Service_Equipment, async (request) => {
22
- const { object, original, user } = request;
23
- // TODO
22
+ // Tickets sort by `equipmentSortKey`, derived from this label when the ticket
23
+ // was saved. A rename therefore has to reach them, or they keep sorting under
24
+ // the old name until each one is touched by hand.
25
+ (0, index_js_1.afterSaveHook)(index_js_2.Service_Equipment, async ({ object, original }) => {
26
+ if (!(0, ticketSortKeys_js_1.derivedValueChanged)(object, original, "label"))
27
+ return;
28
+ await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("equipment", "equipmentSortKey", object, (0, ticketSortKeys_js_1.sortKeyOf)(object.get("label")));
24
29
  });
25
30
  // Block deleting equipment that is still referenced where it matters:
26
31
  // active tickets, and meter readings (whose `equipment` pointer is required,
@@ -1,17 +1,51 @@
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");
9
+ const pointerIds_js_1 = require("../helper/pointerIds.js");
5
10
  const index_js_2 = require("../types/index.js");
11
+ /**
12
+ * Restricts a form config to its audience.
13
+ *
14
+ * A config names the roles and users it applies to, and until now every member
15
+ * of the tenant could read all of them — so a config written for one department
16
+ * was visible to everyone, and the frontend was the only thing deciding who it
17
+ * actually applied to.
18
+ *
19
+ * A config **without** any roles or users is the tenant's global default: it
20
+ * has to stay readable tenant-wide, because it is what everyone falls back to
21
+ * when nothing more specific matches (see `useTicketFormConfig`). Narrowing
22
+ * that one would leave users with no config at all.
23
+ *
24
+ * Write access is unchanged — `defaultAclHandler` keeps it with `od-admin` and
25
+ * the tenant admins. Being the audience of a config does not mean being allowed
26
+ * to change it.
27
+ */
28
+ async function applyAudienceAcl(object) {
29
+ const userIds = (0, pointerIds_js_1.pointerIds)(object.get("users"));
30
+ const roles = await (0, pointerIds_js_1.roleNames)(node_1.default, object.get("roles"));
31
+ if (userIds.length === 0 && roles.length === 0)
32
+ return; // global default
33
+ const acl = object.getACL() ?? new node_1.default.ACL();
34
+ for (const userId of userIds)
35
+ acl.setReadAccess(userId, true);
36
+ for (const role of roles)
37
+ acl.setRoleReadAccess(role, true);
38
+ object.setACL(acl);
39
+ }
6
40
  async function init() {
7
41
  (0, index_js_1.beforeSaveHook)(index_js_2.Service_FormConfig, async (request) => {
8
- const { object, original, user } = request;
42
+ const { object } = request;
43
+ const hasAudience = (0, pointerIds_js_1.pointerIds)(object.get("users")).length > 0 ||
44
+ (0, pointerIds_js_1.pointerIds)(object.get("roles")).length > 0;
9
45
  await (0, index_js_1.defaultHandler)(request);
10
- await (0, index_js_1.defaultAclHandler)(request);
11
- // TODO
12
- });
13
- (0, index_js_1.afterSaveHook)(index_js_2.Service_FormConfig, async (request) => {
14
- const { object, original, user } = request;
15
- // TODO
46
+ // A config addressed at specific roles or users is not the tenant's
47
+ // business — only its audience (granted below) and the admins may read it.
48
+ await (0, index_js_1.defaultAclHandler)(request, { denyTenantUserRead: hasAudience });
49
+ await applyAudienceAcl(object);
16
50
  });
17
51
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.init = init;
4
4
  const index_js_1 = require("../features/schema/index.js");
5
+ const ticketSortKeys_js_1 = require("../helper/ticketSortKeys.js");
5
6
  const index_js_2 = require("../types/index.js");
6
7
  async function init() {
7
8
  // Soft delete: tickets point at their project and draw their number from its
@@ -14,8 +15,12 @@ async function init() {
14
15
  await (0, index_js_1.defaultAclHandler)(request);
15
16
  // TODO
16
17
  });
17
- (0, index_js_1.afterSaveHook)(index_js_2.Service_Project, async (request) => {
18
- const { object, original, user } = request;
19
- // TODO
18
+ // Tickets sort by `projectSortKey`, derived from this label when the ticket was
19
+ // saved. A rename therefore has to reach them, or they keep sorting under the
20
+ // old name until each one is touched by hand.
21
+ (0, index_js_1.afterSaveHook)(index_js_2.Service_Project, async ({ object, original }) => {
22
+ if (!(0, ticketSortKeys_js_1.derivedValueChanged)(object, original, "label"))
23
+ return;
24
+ await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("project", "projectSortKey", object, (0, ticketSortKeys_js_1.sortKeyOf)(object.get("label")));
20
25
  });
21
26
  }
@@ -6,6 +6,7 @@ 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 ticketSortKeys_js_1 = require("../helper/ticketSortKeys.js");
9
10
  const index_js_2 = require("../types/index.js");
10
11
  async function init() {
11
12
  // Soft delete: every ticket carries a required `status` pointer, so a status
@@ -18,9 +19,13 @@ async function init() {
18
19
  await (0, index_js_1.defaultAclHandler)(request);
19
20
  // TODO
20
21
  });
21
- (0, index_js_1.afterSaveHook)(index_js_2.Service_Status, async (request) => {
22
- const { object, original, user } = request;
23
- // TODO
22
+ // A ticket sorts by its status's workflow position, which it carries as
23
+ // `statusOrder`. Reordering the workflow has to reach the tickets, or the
24
+ // board keeps the old order until each one is touched by hand.
25
+ (0, index_js_1.afterSaveHook)(index_js_2.Service_Status, async ({ object, original }) => {
26
+ if (!(0, ticketSortKeys_js_1.derivedValueChanged)(object, original, "order"))
27
+ return;
28
+ await (0, ticketSortKeys_js_1.pushSortKeyToTickets)("status", "statusOrder", object, object.get("order"));
24
29
  });
25
30
  // A ticket's `status` is required — deleting a status still in use by active
26
31
  // tickets would orphan that required pointer. Block it.
@@ -41,6 +41,7 @@ const node_1 = __importStar(require("parse/node"));
41
41
  const i18next_1 = __importDefault(require("i18next"));
42
42
  const index_js_1 = require("../features/schema/index.js");
43
43
  const appLinks_js_1 = require("../helper/appLinks.js");
44
+ const pointerIds_js_1 = require("../helper/pointerIds.js");
44
45
  const getUserLanguage_js_1 = require("../helper/getUserLanguage.js");
45
46
  const index_js_2 = require("../types/index.js");
46
47
  const ruleset_core_1 = require("@opendash/ruleset-core");
@@ -65,6 +66,9 @@ async function init() {
65
66
  // showing every ticket.
66
67
  await (0, index_js_1.defaultAclHandler)(request, { allowCustomACL: true });
67
68
  await setTicketACL(object);
69
+ const referenced = await loadReferencedRows(object);
70
+ assertSameTenantReferences(object, referenced);
71
+ applySortKeys(object, referenced);
68
72
  // Assign a sequential ticket number on creation. Done here (backend) rather
69
73
  // than in the frontend because every write path — the create form, the
70
74
  // cross-plugin service, and the generic entity admin — funnels through this
@@ -200,6 +204,169 @@ async function nextTenantTicketNumber(tenant) {
200
204
  await counter.save(null, { useMasterKey: true });
201
205
  return 1;
202
206
  }
207
+ /** Pointer fields on a ticket that must belong to the ticket's own tenant. */
208
+ const TENANT_SCOPED_POINTERS = ["status", "project", "equipment"];
209
+ /** Pointer-array fields whose entries must belong to the ticket's own tenant. */
210
+ const TENANT_SCOPED_POINTER_ARRAYS = ["tags", "assignedUsers"];
211
+ /**
212
+ * Shadow columns the ticket carries so the table can sort by a pointer.
213
+ *
214
+ * Parse sorts a pointer column by the stored reference, which is the object id —
215
+ * ordering by it looks random. Sorting by the referenced *label* needs the value
216
+ * on the ticket itself, so these three are kept in step here, where the
217
+ * referenced rows are being read anyway.
218
+ */
219
+ const SORT_KEY_FIELDS = {
220
+ status: "statusOrder",
221
+ project: "projectSortKey",
222
+ equipment: "equipmentSortKey",
223
+ };
224
+ /**
225
+ * Comparable form of a label.
226
+ *
227
+ * MongoDB compares strings byte by byte, so "Ökowerk" would sort behind
228
+ * "Zementwerk". Folding the diacritics puts it at "O", which is what German
229
+ * readers expect (DIN 5007-1), and lower-casing keeps the order independent of
230
+ * how someone capitalised the name.
231
+ */
232
+ function sortKeyOf(label) {
233
+ if (typeof label !== "string")
234
+ return undefined;
235
+ const trimmed = label.trim();
236
+ if (!trimmed)
237
+ return undefined;
238
+ return trimmed
239
+ .normalize("NFD")
240
+ .replace(/\p{Diacritic}/gu, "")
241
+ .replace(/ß/g, "ss")
242
+ .toLowerCase();
243
+ }
244
+ /**
245
+ * Reads the rows a ticket's dirty pointer fields refer to, one query per class.
246
+ *
247
+ * Pointers arrive unfetched, so both the tenant check and the sort keys need a
248
+ * read — doing it once here is what keeps a save at a single extra query.
249
+ */
250
+ async function loadReferencedRows(object) {
251
+ const suspects = [];
252
+ for (const field of TENANT_SCOPED_POINTERS) {
253
+ const value = object.get(field);
254
+ if (!value)
255
+ continue;
256
+ // Also read a pointer whose sort key is missing, even when it has not
257
+ // changed: that is what lets a plain re-save fill in a ticket written
258
+ // before those columns existed, with no separate backfill path.
259
+ const keyMissing = field in SORT_KEY_FIELDS &&
260
+ object.get(SORT_KEY_FIELDS[field]) ==
261
+ null;
262
+ if (object.dirty(field) || keyMissing)
263
+ suspects.push(value);
264
+ }
265
+ for (const field of TENANT_SCOPED_POINTER_ARRAYS) {
266
+ if (!object.dirty(field))
267
+ continue;
268
+ const value = object.get(field);
269
+ if (Array.isArray(value))
270
+ suspects.push(...value.filter(Boolean));
271
+ }
272
+ const byClass = new Map();
273
+ for (const suspect of suspects) {
274
+ // A pointer that has not been saved yet has no id — nothing to look up.
275
+ if (!suspect.id)
276
+ continue;
277
+ const ids = byClass.get(suspect.className) ?? new Set();
278
+ ids.add(suspect.id);
279
+ byClass.set(suspect.className, ids);
280
+ }
281
+ const rows = new Map();
282
+ for (const [className, ids] of byClass) {
283
+ const found = await new node_1.default.Query(className)
284
+ .containedIn("objectId", [...ids])
285
+ // `label` and `order` feed the sort keys below; `tenant` the guard.
286
+ .select("tenant", "label", "order")
287
+ .limit(ids.size)
288
+ .find({ useMasterKey: true });
289
+ for (const row of found)
290
+ rows.set(row.id, row);
291
+ }
292
+ return rows;
293
+ }
294
+ /**
295
+ * Rejects a ticket that references master data from another tenant.
296
+ *
297
+ * ACLs do not stop an `od-admin` at a tenant boundary, so every picker in the
298
+ * UI used to offer every tenant's statuses, projects, equipment and tags. The
299
+ * frontend now scopes those queries, but the UI is not the only write path —
300
+ * the generic entity admin and the REST API go straight through here — and a
301
+ * ticket pointing at a foreign status is silently broken: it is counted in
302
+ * neither tenant's board, and it blocks deletion of that status
303
+ * (`Service_Status`'s in-use guard does not filter by tenant either).
304
+ *
305
+ * `assignedRoles` is deliberately not checked: `_Role` has no tenant column at
306
+ * all — a role's tenant lives in its name — so there is nothing to compare.
307
+ */
308
+ function assertSameTenantReferences(object, rows) {
309
+ const tenantId = object.get("tenant")?.id;
310
+ if (!tenantId)
311
+ return; // nothing to compare against
312
+ // Only the dirty references are judged — the loaded set is wider than that
313
+ // (see `loadReferencedRows`), and a ticket that already carries a bad
314
+ // reference has to stay saveable so it can be repaired.
315
+ const judged = [];
316
+ for (const field of TENANT_SCOPED_POINTERS) {
317
+ if (!object.dirty(field))
318
+ continue;
319
+ const value = object.get(field);
320
+ const row = value?.id ? rows.get(value.id) : undefined;
321
+ if (row)
322
+ judged.push(row);
323
+ }
324
+ for (const field of TENANT_SCOPED_POINTER_ARRAYS) {
325
+ if (!object.dirty(field))
326
+ continue;
327
+ const value = object.get(field);
328
+ for (const entry of value ?? []) {
329
+ const row = entry?.id ? rows.get(entry.id) : undefined;
330
+ if (row)
331
+ judged.push(row);
332
+ }
333
+ }
334
+ for (const row of judged) {
335
+ const refTenantId = row.get("tenant")?.id;
336
+ // No tenant on the referenced row = shared/global master data, allowed.
337
+ if (!refTenantId || refTenantId === tenantId)
338
+ continue;
339
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `Cannot reference ${row.className} ${row.id} from tenant ` +
340
+ `${refTenantId} on a ticket of tenant ${tenantId}.`);
341
+ }
342
+ }
343
+ /**
344
+ * Keeps {@link SORT_KEY_FIELDS} in step with the pointers they shadow.
345
+ *
346
+ * Only dirty pointers are touched, so a save that changes the title leaves the
347
+ * keys alone. Clearing a pointer clears its key, which sorts the ticket with
348
+ * the other unassigned ones rather than leaving a stale name behind.
349
+ */
350
+ function applySortKeys(object, rows) {
351
+ for (const [field, target] of Object.entries(SORT_KEY_FIELDS)) {
352
+ const pointer = object.get(field);
353
+ const keyMissing = pointer && object.get(target) == null;
354
+ if (!object.dirty(field) && !keyMissing)
355
+ continue;
356
+ const row = pointer?.id ? rows.get(pointer.id) : undefined;
357
+ if (!row) {
358
+ object.unset(target);
359
+ continue;
360
+ }
361
+ // Status sorts by its configured workflow position, not by its name: a
362
+ // board reads "Eingang, In Bearbeitung, Erledigt", never alphabetically.
363
+ const value = field === "status" ? row.get("order") : sortKeyOf(row.get("label"));
364
+ if (value === undefined || value === null)
365
+ object.unset(target);
366
+ else
367
+ object.set(target, value);
368
+ }
369
+ }
203
370
  /**
204
371
  * Sets the ticket ACL from `createdBy`, `assignedUsers` and `assignedRoles` —
205
372
  * each gets read/write. `assignedUsers`/`assignedRoles` are arrays of Parse
@@ -232,12 +399,12 @@ async function setTicketACL(object) {
232
399
  acl.setWriteAccess(creatorId, true);
233
400
  }
234
401
  // assigned users read/write
235
- for (const userId of pointerIds(object.get("assignedUsers"))) {
402
+ for (const userId of (0, pointerIds_js_1.pointerIds)(object.get("assignedUsers"))) {
236
403
  acl.setReadAccess(userId, true);
237
404
  acl.setWriteAccess(userId, true);
238
405
  }
239
406
  // assigned roles read/write (resolve pointer ids → role names)
240
- const roleIds = pointerIds(object.get("assignedRoles"));
407
+ const roleIds = (0, pointerIds_js_1.pointerIds)(object.get("assignedRoles"));
241
408
  if (roleIds.length > 0) {
242
409
  const roles = await new node_1.default.Query(node_1.default.Role)
243
410
  .containedIn("objectId", roleIds)
@@ -404,29 +571,8 @@ async function sendAssignmentNotification(user, ticket, options) {
404
571
  }
405
572
  /** Ids present in `current` (array of pointers) but not in `previous`. */
406
573
  function addedIds(current, previous) {
407
- const previousIds = new Set(pointerIds(previous));
408
- return pointerIds(current).filter((id) => !previousIds.has(id));
409
- }
410
- /** Extracts the object ids from an array of Parse pointers, tolerating
411
- * undefined / malformed entries. */
412
- function pointerIds(value) {
413
- if (!Array.isArray(value))
414
- return [];
415
- return value
416
- .map((entry) => {
417
- // The entity adapter stores array-of-ref fields as plain id
418
- // STRINGS, not Parse.Objects. Reading `.id` off them returned
419
- // undefined, so setTicketACL granted assignees nothing and
420
- // notifyNewAssignees found nobody — silently, for every ticket.
421
- if (typeof entry === "string")
422
- return entry;
423
- if (entry && typeof entry === "object") {
424
- const o = entry;
425
- return o.id ?? o.objectId;
426
- }
427
- return undefined;
428
- })
429
- .filter((id) => typeof id === "string");
574
+ const previousIds = new Set((0, pointerIds_js_1.pointerIds)(previous));
575
+ return (0, pointerIds_js_1.pointerIds)(current).filter((id) => !previousIds.has(id));
430
576
  }
431
577
  function getUsername(user) {
432
578
  if (!user)
@@ -21,6 +21,7 @@ export interface Service_TicketAttributes {
21
21
  downtime?: number | undefined;
22
22
  dueDate?: Date | undefined;
23
23
  equipment?: Service_Equipment | undefined;
24
+ equipmentSortKey?: string | undefined;
24
25
  estimatedDuration?: number | undefined;
25
26
  frequency?: number | undefined;
26
27
  material?: TicketMaterial[] | undefined;
@@ -29,8 +30,10 @@ export interface Service_TicketAttributes {
29
30
  parent?: Service_Ticket | undefined;
30
31
  priority?: number | undefined;
31
32
  project?: Service_Project | undefined;
33
+ projectSortKey?: string | undefined;
32
34
  restriction?: number | undefined;
33
35
  startDate?: Date | undefined;
36
+ statusOrder?: number | undefined;
34
37
  status: Service_Status;
35
38
  tags?: any[] | undefined;
36
39
  tenant: Tenant;
@@ -79,6 +82,12 @@ export declare class Service_Ticket extends Parse.Object<Service_TicketAttribute
79
82
  set project(value: Service_Project | undefined);
80
83
  get restriction(): number | undefined;
81
84
  set restriction(value: number | undefined);
85
+ get equipmentSortKey(): string | undefined;
86
+ set equipmentSortKey(value: string | undefined);
87
+ get projectSortKey(): string | undefined;
88
+ set projectSortKey(value: string | undefined);
89
+ get statusOrder(): number | undefined;
90
+ set statusOrder(value: number | undefined);
82
91
  get startDate(): Date | undefined;
83
92
  set startDate(value: Date | undefined);
84
93
  get status(): Service_Status;
@@ -130,6 +130,24 @@ class Service_Ticket extends node_1.default.Object {
130
130
  set restriction(value) {
131
131
  super.set("restriction", value);
132
132
  }
133
+ get equipmentSortKey() {
134
+ return super.get("equipmentSortKey");
135
+ }
136
+ set equipmentSortKey(value) {
137
+ super.set("equipmentSortKey", value);
138
+ }
139
+ get projectSortKey() {
140
+ return super.get("projectSortKey");
141
+ }
142
+ set projectSortKey(value) {
143
+ super.set("projectSortKey", value);
144
+ }
145
+ get statusOrder() {
146
+ return super.get("statusOrder");
147
+ }
148
+ set statusOrder(value) {
149
+ super.set("statusOrder", value);
150
+ }
133
151
  get startDate() {
134
152
  return super.get("startDate");
135
153
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.11.1",
3
+ "version": "4.13.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [
@@ -37,6 +37,10 @@
37
37
  "type": "Pointer",
38
38
  "targetClass": "{{PREFIX}}Service_Equipment"
39
39
  },
40
+ "equipmentSortKey": {
41
+ "type": "String",
42
+ "required": false
43
+ },
40
44
  "estimatedDuration": {
41
45
  "type": "Number"
42
46
  },
@@ -63,6 +67,10 @@
63
67
  "type": "Pointer",
64
68
  "targetClass": "{{PREFIX}}Service_Project"
65
69
  },
70
+ "projectSortKey": {
71
+ "type": "String",
72
+ "required": false
73
+ },
66
74
  "restriction": {
67
75
  "type": "Number"
68
76
  },
@@ -74,6 +82,10 @@
74
82
  "targetClass": "{{PREFIX}}Service_Status",
75
83
  "required": true
76
84
  },
85
+ "statusOrder": {
86
+ "type": "Number",
87
+ "required": false
88
+ },
77
89
  "tags": {
78
90
  "type": "Array"
79
91
  },