@openinc/parse-server-opendash 4.25.0 → 4.27.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,54 @@
1
+ /**
2
+ * The values of `archiveReason`. Mirrors `TICKET_ARCHIVE_REASONS` in
3
+ * `@opendash/openservice-shared`; import it from there once the installed
4
+ * nightly carries it (it arrived after `0.2.0-nightly.0`).
5
+ */
6
+ export declare const ARCHIVE_REASON: {
7
+ /** The scheduler's `archiveIdleTickets`: finished and idle for a period. */
8
+ readonly auto: "auto";
9
+ /** Everything else — the archive button, the admin table, the REST API. */
10
+ readonly manual: "manual";
11
+ };
12
+ /**
13
+ * Stamps `archiveReason` when a ticket is archived and clears it on restore.
14
+ *
15
+ * What it is for: the archive page shows who archived a ticket — the scheduler
16
+ * or somebody's hand. It decides nothing; whether a ticket feeds the
17
+ * similar-case search is `useForSimilarCases` (see {@link applySimilarCaseUse}).
18
+ *
19
+ * **Only the master key can say "auto".** The scheduler archives with the
20
+ * master key and sends `auto`. A client sending it is overruled. A master-key
21
+ * write without a reason (or with one that is not a known value) counts as
22
+ * `manual`.
23
+ *
24
+ * **Set once, at the moment of archiving.** A later save of an archived ticket
25
+ * keeps the stored reason, whatever it sends. Restoring clears it: a live
26
+ * ticket has no reason to be archived, and the next archive sets a fresh one.
27
+ */
28
+ export declare function applyArchiveReason(object: Parse.Object, original: Parse.Object | undefined, master: boolean): void;
29
+ /**
30
+ * Whether this save changes `useForSimilarCases` of a ticket that was archived
31
+ * before and stays archived — the archive page's switch. That is archive
32
+ * management, so the hook asks for the archiving capability.
33
+ */
34
+ export declare function changesSimilarCaseUse(object: Parse.Object, original: Parse.Object | undefined): boolean;
35
+ /**
36
+ * Keeps `useForSimilarCases` — whether an archived ticket still feeds "Ähnliche
37
+ * Tickets" — to archived tickets.
38
+ *
39
+ * **Why a column of its own.** The similar-case search should find solved
40
+ * problems, and many of them get archived: by the scheduler once they sat idle,
41
+ * by hand when somebody clears the board early. Some archived tickets are
42
+ * noise, though — duplicates, mistakes, tests. Who archived a ticket says
43
+ * nothing about which kind it is, so the person archiving decides (the archive
44
+ * dialog asks, ticked by default), and the archive page can change it later.
45
+ * The RAG source keeps every ticket where it is not `false`.
46
+ *
47
+ * - **Archiving** keeps a boolean the caller sent and sets `true` otherwise —
48
+ * the scheduler, the admin table and the REST API do not ask.
49
+ * - **While archived** a sent boolean is kept (the archive page's switch; the
50
+ * hook checks the capability), anything else is reverted.
51
+ * - **Live** tickets do not carry it: restoring clears it, and a value sent
52
+ * for a live ticket is dropped. A live ticket always feeds the search.
53
+ */
54
+ export declare function applySimilarCaseUse(object: Parse.Object, original: Parse.Object | undefined): void;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ARCHIVE_REASON = void 0;
4
+ exports.applyArchiveReason = applyArchiveReason;
5
+ exports.changesSimilarCaseUse = changesSimilarCaseUse;
6
+ exports.applySimilarCaseUse = applySimilarCaseUse;
7
+ /**
8
+ * The values of `archiveReason`. Mirrors `TICKET_ARCHIVE_REASONS` in
9
+ * `@opendash/openservice-shared`; import it from there once the installed
10
+ * nightly carries it (it arrived after `0.2.0-nightly.0`).
11
+ */
12
+ exports.ARCHIVE_REASON = {
13
+ /** The scheduler's `archiveIdleTickets`: finished and idle for a period. */
14
+ auto: "auto",
15
+ /** Everything else — the archive button, the admin table, the REST API. */
16
+ manual: "manual",
17
+ };
18
+ /**
19
+ * Stamps `archiveReason` when a ticket is archived and clears it on restore.
20
+ *
21
+ * What it is for: the archive page shows who archived a ticket — the scheduler
22
+ * or somebody's hand. It decides nothing; whether a ticket feeds the
23
+ * similar-case search is `useForSimilarCases` (see {@link applySimilarCaseUse}).
24
+ *
25
+ * **Only the master key can say "auto".** The scheduler archives with the
26
+ * master key and sends `auto`. A client sending it is overruled. A master-key
27
+ * write without a reason (or with one that is not a known value) counts as
28
+ * `manual`.
29
+ *
30
+ * **Set once, at the moment of archiving.** A later save of an archived ticket
31
+ * keeps the stored reason, whatever it sends. Restoring clears it: a live
32
+ * ticket has no reason to be archived, and the next archive sets a fresh one.
33
+ */
34
+ function applyArchiveReason(object, original, master) {
35
+ const archived = Boolean(object.get("deleted"));
36
+ const wasArchived = Boolean(original?.get("deleted"));
37
+ if (!archived) {
38
+ if (object.get("archiveReason") != null)
39
+ object.unset("archiveReason");
40
+ return;
41
+ }
42
+ if (wasArchived) {
43
+ if (!object.dirty("archiveReason"))
44
+ return;
45
+ const stored = original?.get("archiveReason");
46
+ if (stored != null)
47
+ object.set("archiveReason", stored);
48
+ else
49
+ object.unset("archiveReason");
50
+ return;
51
+ }
52
+ const sent = object.get("archiveReason");
53
+ object.set("archiveReason", master && sent === exports.ARCHIVE_REASON.auto
54
+ ? exports.ARCHIVE_REASON.auto
55
+ : exports.ARCHIVE_REASON.manual);
56
+ }
57
+ /**
58
+ * Whether this save changes `useForSimilarCases` of a ticket that was archived
59
+ * before and stays archived — the archive page's switch. That is archive
60
+ * management, so the hook asks for the archiving capability.
61
+ */
62
+ function changesSimilarCaseUse(object, original) {
63
+ return (!!original?.get("deleted") &&
64
+ !!object.get("deleted") &&
65
+ object.dirty("useForSimilarCases") &&
66
+ object.get("useForSimilarCases") !== original.get("useForSimilarCases"));
67
+ }
68
+ /**
69
+ * Keeps `useForSimilarCases` — whether an archived ticket still feeds "Ähnliche
70
+ * Tickets" — to archived tickets.
71
+ *
72
+ * **Why a column of its own.** The similar-case search should find solved
73
+ * problems, and many of them get archived: by the scheduler once they sat idle,
74
+ * by hand when somebody clears the board early. Some archived tickets are
75
+ * noise, though — duplicates, mistakes, tests. Who archived a ticket says
76
+ * nothing about which kind it is, so the person archiving decides (the archive
77
+ * dialog asks, ticked by default), and the archive page can change it later.
78
+ * The RAG source keeps every ticket where it is not `false`.
79
+ *
80
+ * - **Archiving** keeps a boolean the caller sent and sets `true` otherwise —
81
+ * the scheduler, the admin table and the REST API do not ask.
82
+ * - **While archived** a sent boolean is kept (the archive page's switch; the
83
+ * hook checks the capability), anything else is reverted.
84
+ * - **Live** tickets do not carry it: restoring clears it, and a value sent
85
+ * for a live ticket is dropped. A live ticket always feeds the search.
86
+ */
87
+ function applySimilarCaseUse(object, original) {
88
+ const archived = Boolean(object.get("deleted"));
89
+ const wasArchived = Boolean(original?.get("deleted"));
90
+ const value = object.get("useForSimilarCases");
91
+ if (!archived) {
92
+ if (value != null)
93
+ object.unset("useForSimilarCases");
94
+ return;
95
+ }
96
+ // On create the Parse SDK reports every attribute as dirty, so only a value
97
+ // counts as sent there.
98
+ const sent = object.isNew()
99
+ ? value != null
100
+ : object.dirty("useForSimilarCases");
101
+ if (wasArchived) {
102
+ if (!sent || typeof value === "boolean")
103
+ return;
104
+ const stored = original?.get("useForSimilarCases");
105
+ if (stored != null)
106
+ object.set("useForSimilarCases", stored);
107
+ else
108
+ object.unset("useForSimilarCases");
109
+ return;
110
+ }
111
+ object.set("useForSimilarCases", sent && value === false ? false : true);
112
+ }
@@ -0,0 +1,38 @@
1
+ import { Service_FormConfig, type Tenant } from "../../../types/index.js";
2
+ /**
3
+ * The form config that applies to `user` in `tenant`, or `undefined` when
4
+ * none does — the frontend then uses its built-in form.
5
+ *
6
+ * Highest `priority` first, and in that order:
7
+ * 1. a config naming the user,
8
+ * 2. a config naming one of the user's roles, inherited ones included,
9
+ * 3. the tenant's global default (a config naming nobody).
10
+ *
11
+ * Read with the master key. The browser cannot do the role step itself: it
12
+ * knows its roles by name, a config names them by id, and a role the user may
13
+ * not read cannot be looked up — comparing the two never matched, so a config
14
+ * for a role silently never applied. Without a user (a master-key write) only
15
+ * the global default can apply.
16
+ *
17
+ * Without a tenant only configs without one are considered: with the master
18
+ * key, "all configs" would be every tenant's.
19
+ */
20
+ export declare function applicableFormConfig(tenant: Tenant | undefined, user: Parse.User | undefined): Promise<Service_FormConfig | undefined>;
21
+ /**
22
+ * The config a save names in its context (`{ formConfig: <id> }`): the one
23
+ * the form that saves was showing — the ticket forms of the frontend send it.
24
+ * `undefined` when the save names none, or one that does not count:
25
+ *
26
+ * - read with the caller's own rights, so only a config the caller may read
27
+ * (its audience, the tenant's global default, an admin) — the same check
28
+ * the QR flow makes in the browser;
29
+ * - of the ticket's own tenant: a cross-tenant admin may read another
30
+ * tenant's configs, which say nothing about this ticket.
31
+ *
32
+ * Read by id rather than resolved: one query, and exactly the config the form
33
+ * showed, in its current version.
34
+ */
35
+ export declare function configFromContext(id: unknown, tenant: Tenant | undefined, { master, sessionToken, }: {
36
+ master: boolean;
37
+ sessionToken: string | undefined;
38
+ }): Promise<Service_FormConfig | undefined>;
@@ -0,0 +1,101 @@
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.applicableFormConfig = applicableFormConfig;
7
+ exports.configFromContext = configFromContext;
8
+ // Which ticket form config applies to a user. The frontend asks this through
9
+ // `openinc-openservice-form-config`, and the ticket hook reads the priority
10
+ // formula out of the same answer, so both always work with the same config.
11
+ const node_1 = __importDefault(require("parse/node"));
12
+ const openservice_shared_1 = require("@opendash/openservice-shared");
13
+ const index_js_1 = require("../../../types/index.js");
14
+ const aclAccess_js_1 = require("../../../helper/aclAccess.js");
15
+ /** More configs per tenant would not be a form any more but a mistake. */
16
+ const MAX_CONFIGS = 1000;
17
+ /**
18
+ * The form config that applies to `user` in `tenant`, or `undefined` when
19
+ * none does — the frontend then uses its built-in form.
20
+ *
21
+ * Highest `priority` first, and in that order:
22
+ * 1. a config naming the user,
23
+ * 2. a config naming one of the user's roles, inherited ones included,
24
+ * 3. the tenant's global default (a config naming nobody).
25
+ *
26
+ * Read with the master key. The browser cannot do the role step itself: it
27
+ * knows its roles by name, a config names them by id, and a role the user may
28
+ * not read cannot be looked up — comparing the two never matched, so a config
29
+ * for a role silently never applied. Without a user (a master-key write) only
30
+ * the global default can apply.
31
+ *
32
+ * Without a tenant only configs without one are considered: with the master
33
+ * key, "all configs" would be every tenant's.
34
+ */
35
+ async function applicableFormConfig(tenant, user) {
36
+ const query = new node_1.default.Query(index_js_1.Service_FormConfig).limit(MAX_CONFIGS);
37
+ if (tenant)
38
+ query.equalTo("tenant", tenant);
39
+ else
40
+ query.doesNotExist("tenant");
41
+ // Stable on equal priority: the older config wins, on every call alike.
42
+ const configs = (await query.ascending("createdAt").find({
43
+ useMasterKey: true,
44
+ })).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
45
+ if (configs.length === 0)
46
+ return undefined;
47
+ const userId = user?.id;
48
+ if (user && userId) {
49
+ const userMatch = configs.find((c) => (0, openservice_shared_1.refIds)(c.users).includes(userId));
50
+ if (userMatch)
51
+ return userMatch;
52
+ const roleMatch = await findRoleMatch(configs, user);
53
+ if (roleMatch)
54
+ return roleMatch;
55
+ }
56
+ return configs.find((c) => (0, openservice_shared_1.refIds)(c.users).length === 0 && (0, openservice_shared_1.refIds)(c.roles).length === 0);
57
+ }
58
+ /** The first config naming one of the user's roles (see `userRoleNames`). */
59
+ async function findRoleMatch(configs, user) {
60
+ const roleIds = [...new Set(configs.flatMap((c) => (0, openservice_shared_1.refIds)(c.roles)))];
61
+ if (roleIds.length === 0)
62
+ return undefined;
63
+ const [held, roles] = await Promise.all([
64
+ (0, aclAccess_js_1.userRoleNames)(user),
65
+ new node_1.default.Query(node_1.default.Role)
66
+ .containedIn("objectId", roleIds)
67
+ .limit(roleIds.length)
68
+ .find({ useMasterKey: true }),
69
+ ]);
70
+ const heldNames = new Set(held);
71
+ const heldIds = new Set(roles
72
+ .filter((role) => heldNames.has(role.getName() ?? ""))
73
+ .map((role) => role.id));
74
+ return configs.find((c) => (0, openservice_shared_1.refIds)(c.roles).some((id) => heldIds.has(id)));
75
+ }
76
+ /**
77
+ * The config a save names in its context (`{ formConfig: <id> }`): the one
78
+ * the form that saves was showing — the ticket forms of the frontend send it.
79
+ * `undefined` when the save names none, or one that does not count:
80
+ *
81
+ * - read with the caller's own rights, so only a config the caller may read
82
+ * (its audience, the tenant's global default, an admin) — the same check
83
+ * the QR flow makes in the browser;
84
+ * - of the ticket's own tenant: a cross-tenant admin may read another
85
+ * tenant's configs, which say nothing about this ticket.
86
+ *
87
+ * Read by id rather than resolved: one query, and exactly the config the form
88
+ * showed, in its current version.
89
+ */
90
+ async function configFromContext(id, tenant, { master, sessionToken, }) {
91
+ if (typeof id !== "string" || !id)
92
+ return undefined;
93
+ if (!master && !sessionToken)
94
+ return undefined;
95
+ const config = await new node_1.default.Query(index_js_1.Service_FormConfig)
96
+ .equalTo("objectId", id)
97
+ .first(master ? { useMasterKey: true } : { sessionToken });
98
+ if (!config)
99
+ return undefined;
100
+ return config.tenant?.id === tenant?.id ? config : undefined;
101
+ }
@@ -0,0 +1,48 @@
1
+ import type { FormulaNode } from "@opendash/ruleset-core";
2
+ import type { Service_FormConfig } from "../../../types/index.js";
3
+ /**
4
+ * The fields a priority formula may read, e.g.
5
+ * `max(downtime, restriction) * 0.7 + frequency * 0.3`. Mirrors
6
+ * `SCALE_FIELD_KEYS` in `@opendash/plugin-openservice-ticket`.
7
+ */
8
+ export declare const PRIORITY_FORMULA_INPUTS: readonly ["downtime", "restriction", "frequency"];
9
+ interface PriorityFormula {
10
+ expression: FormulaNode;
11
+ names: string[];
12
+ }
13
+ /**
14
+ * The formula a config's priority entry asks for, or `undefined` when the
15
+ * priority is entered by hand — or when the stored formula does not parse: the
16
+ * editor refuses to save one, and a broken formula must not block saving
17
+ * tickets. Mirrors `compilePriorityFormula` of the frontend.
18
+ */
19
+ export declare function priorityFormulaOf(config: Service_FormConfig | undefined): PriorityFormula | undefined;
20
+ /**
21
+ * The priority for a ticket's values, or `undefined` when there is nothing to
22
+ * compute from. Mirrors `computePriority` of the frontend:
23
+ *
24
+ * - None of the inputs the formula reads is set: `undefined`, so a ticket
25
+ * nobody has assessed keeps its priority.
26
+ * - Some are set: the rest count as 0, the lowest level.
27
+ * - Clamped to 0–100 and rounded; no number at all (division by zero) is
28
+ * `undefined` as well.
29
+ */
30
+ export declare function computePriority(formula: PriorityFormula, values: (key: string) => unknown): number | undefined;
31
+ /** Whether this save changes one of the inputs a priority formula reads. */
32
+ export declare function changesPriorityInputs(object: Parse.Object, original: Parse.Object | undefined): boolean;
33
+ /**
34
+ * Sets the computed priority on a ticket being saved, under `config` — the
35
+ * form config that applies to the user saving (see `applicableFormConfig`).
36
+ *
37
+ * Only when this save changes one of the inputs — a ticket the save does not
38
+ * reassess keeps its priority, also when the formula has changed since — and
39
+ * only when the caller does not set the priority itself in the same save: an
40
+ * import keeps the priority its file states.
41
+ *
42
+ * "Changes" and "sets" are judged against `original`. The admin table sends
43
+ * every field of its form, the unchanged priority included; counting that as
44
+ * set by hand would leave the old priority after every factor edit there —
45
+ * which is the case this exists for.
46
+ */
47
+ export declare function applyComputedPriority(object: Parse.Object, original: Parse.Object | undefined, config: Service_FormConfig | undefined): void;
48
+ export {};
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PRIORITY_FORMULA_INPUTS = void 0;
4
+ exports.priorityFormulaOf = priorityFormulaOf;
5
+ exports.computePriority = computePriority;
6
+ exports.changesPriorityInputs = changesPriorityInputs;
7
+ exports.applyComputedPriority = applyComputedPriority;
8
+ const ruleset_core_1 = require("@opendash/ruleset-core");
9
+ /**
10
+ * The fields a priority formula may read, e.g.
11
+ * `max(downtime, restriction) * 0.7 + frequency * 0.3`. Mirrors
12
+ * `SCALE_FIELD_KEYS` in `@opendash/plugin-openservice-ticket`.
13
+ */
14
+ exports.PRIORITY_FORMULA_INPUTS = [
15
+ "downtime",
16
+ "restriction",
17
+ "frequency",
18
+ ];
19
+ /**
20
+ * The formula a config's priority entry asks for, or `undefined` when the
21
+ * priority is entered by hand — or when the stored formula does not parse: the
22
+ * editor refuses to save one, and a broken formula must not block saving
23
+ * tickets. Mirrors `compilePriorityFormula` of the frontend.
24
+ */
25
+ function priorityFormulaOf(config) {
26
+ let entries;
27
+ try {
28
+ entries = JSON.parse(config?.fields ?? "[]");
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ if (!Array.isArray(entries))
34
+ return undefined;
35
+ const entry = entries.find((e) => !!e && typeof e === "object" && e.key === "priority");
36
+ if (entry?.computed !== true || typeof entry.formula !== "string")
37
+ return undefined;
38
+ const result = (0, ruleset_core_1.validateFormula)(entry.formula, [...exports.PRIORITY_FORMULA_INPUTS]);
39
+ if (result.ok === false)
40
+ return undefined;
41
+ return { expression: result.expression, names: result.names };
42
+ }
43
+ function asNumber(value) {
44
+ return typeof value === "number" && Number.isFinite(value)
45
+ ? value
46
+ : undefined;
47
+ }
48
+ /**
49
+ * The priority for a ticket's values, or `undefined` when there is nothing to
50
+ * compute from. Mirrors `computePriority` of the frontend:
51
+ *
52
+ * - None of the inputs the formula reads is set: `undefined`, so a ticket
53
+ * nobody has assessed keeps its priority.
54
+ * - Some are set: the rest count as 0, the lowest level.
55
+ * - Clamped to 0–100 and rounded; no number at all (division by zero) is
56
+ * `undefined` as well.
57
+ */
58
+ function computePriority(formula, values) {
59
+ const scope = {};
60
+ let anySet = false;
61
+ for (const name of formula.names) {
62
+ const value = asNumber(values(name));
63
+ if (value !== undefined)
64
+ anySet = true;
65
+ scope[name] = value ?? 0;
66
+ }
67
+ if (!anySet)
68
+ return undefined;
69
+ const result = (0, ruleset_core_1.evaluateFormula)(formula.expression, scope);
70
+ if (Number.isNaN(result))
71
+ return undefined;
72
+ return Math.round(Math.min(100, Math.max(0, result)));
73
+ }
74
+ /** Whether this save changes `key`, judged against the stored ticket. */
75
+ function changes(object, original, key) {
76
+ return original
77
+ ? object.get(key) !== original.get(key)
78
+ : object.get(key) != null;
79
+ }
80
+ /** Whether this save changes one of the inputs a priority formula reads. */
81
+ function changesPriorityInputs(object, original) {
82
+ return exports.PRIORITY_FORMULA_INPUTS.some((key) => changes(object, original, key));
83
+ }
84
+ /**
85
+ * Sets the computed priority on a ticket being saved, under `config` — the
86
+ * form config that applies to the user saving (see `applicableFormConfig`).
87
+ *
88
+ * Only when this save changes one of the inputs — a ticket the save does not
89
+ * reassess keeps its priority, also when the formula has changed since — and
90
+ * only when the caller does not set the priority itself in the same save: an
91
+ * import keeps the priority its file states.
92
+ *
93
+ * "Changes" and "sets" are judged against `original`. The admin table sends
94
+ * every field of its form, the unchanged priority included; counting that as
95
+ * set by hand would leave the old priority after every factor edit there —
96
+ * which is the case this exists for.
97
+ */
98
+ function applyComputedPriority(object, original, config) {
99
+ if (!changesPriorityInputs(object, original))
100
+ return;
101
+ if (changes(object, original, "priority"))
102
+ return;
103
+ const formula = priorityFormulaOf(config);
104
+ if (!formula)
105
+ return;
106
+ const priority = computePriority(formula, (key) => object.get(key));
107
+ if (priority !== undefined)
108
+ object.set("priority", priority);
109
+ }
@@ -53,9 +53,9 @@ export declare function applySortKeys(object: Parse.Object, rows: Map<string, Pa
53
53
  * not closed, and leaving the old date would quietly count it as finished in
54
54
  * every evaluation while it is being worked on again.
55
55
  *
56
- * **A value the caller sent wins.** `object.dirty("closedAt")` means somebody
57
- * named a date in this same save — the migration replaying history, a correction
58
- * in the admin table — and overwriting it with `now` would be this function
59
- * deciding it knows better.
56
+ * **A value the caller sent wins.** A `closedAt` named in this same save — the
57
+ * migration replaying history, an import, a correction in the admin table — is
58
+ * kept; overwriting it with `now` would be this function deciding it knows
59
+ * better.
60
60
  */
61
61
  export declare function applyClosedAt(object: Parse.Object, rows: Map<string, Parse.Object>): void;
@@ -197,18 +197,24 @@ function applySortKeys(object, rows, refresh = false) {
197
197
  * not closed, and leaving the old date would quietly count it as finished in
198
198
  * every evaluation while it is being worked on again.
199
199
  *
200
- * **A value the caller sent wins.** `object.dirty("closedAt")` means somebody
201
- * named a date in this same save — the migration replaying history, a correction
202
- * in the admin table — and overwriting it with `now` would be this function
203
- * deciding it knows better.
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
204
  */
205
205
  function applyClosedAt(object, rows) {
206
206
  // Nothing to react to: the status is unchanged. A ticket whose status stayed
207
207
  // put keeps whatever stamp it has, including none.
208
208
  if (!object.dirty("status"))
209
209
  return;
210
- // Explicitly set in this save — see the note above.
211
- if (object.dirty("closedAt"))
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)
212
218
  return;
213
219
  const status = object.get("status");
214
220
  const row = status?.id ? rows.get(status.id) : undefined;
@@ -0,0 +1,18 @@
1
+ /** The zone ticket rules are evaluated in. */
2
+ export declare const RULE_TIME_ZONE: string;
3
+ /** Units of a relative date value. Mirrors `RelativeUnit` of the frontend. */
4
+ export type RelativeUnit = "minutes" | "hours" | "days" | "weeks";
5
+ /**
6
+ * `instant` as a `Date` whose *local* getters read the zone's wall clock.
7
+ *
8
+ * `@opendash/ruleset-core` compares dates in local time — a rule's
9
+ * "YYYY-MM-DD" is local midnight, "equals" compares local calendar days. Fed
10
+ * these, it compares on the zone's calendar whatever the process runs in.
11
+ */
12
+ export declare function inRuleZone(instant: Date): Date;
13
+ /**
14
+ * `now` moved by a relative rule value, the way dayjs does it in the browser:
15
+ * minutes and hours as elapsed time, days and weeks on the zone's calendar —
16
+ * "in 1 day" across a daylight-saving change keeps the time of day.
17
+ */
18
+ export declare function addRelative(now: Date, amount: number, unit: RelativeUnit): Date;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ // Time for the ticket rules: the browser evaluates and computes them in the
3
+ // user's local time, so the server does the same in the zone the users live
4
+ // in rather than in the container's UTC.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RULE_TIME_ZONE = void 0;
7
+ exports.inRuleZone = inRuleZone;
8
+ exports.addRelative = addRelative;
9
+ /** The zone ticket rules are evaluated in. */
10
+ exports.RULE_TIME_ZONE = process.env.OPENSERVICE_TIME_ZONE || "Europe/Berlin";
11
+ const formatter = new Intl.DateTimeFormat("en-US", {
12
+ timeZone: exports.RULE_TIME_ZONE,
13
+ hourCycle: "h23",
14
+ year: "numeric",
15
+ month: "2-digit",
16
+ day: "2-digit",
17
+ hour: "2-digit",
18
+ minute: "2-digit",
19
+ second: "2-digit",
20
+ });
21
+ /** What a clock in {@link RULE_TIME_ZONE} shows at `instant`. */
22
+ function wallClock(instant) {
23
+ const parts = formatter.formatToParts(instant);
24
+ const part = (type) => Number(parts.find((p) => p.type === type)?.value);
25
+ return {
26
+ year: part("year"),
27
+ month: part("month"),
28
+ day: part("day"),
29
+ hour: part("hour"),
30
+ minute: part("minute"),
31
+ second: part("second"),
32
+ ms: instant.getUTCMilliseconds(),
33
+ };
34
+ }
35
+ /** How far the zone is ahead of UTC at `instant`, in ms. */
36
+ function zoneOffset(instant) {
37
+ const w = wallClock(instant);
38
+ return (Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms) -
39
+ instant.getTime());
40
+ }
41
+ /**
42
+ * `instant` as a `Date` whose *local* getters read the zone's wall clock.
43
+ *
44
+ * `@opendash/ruleset-core` compares dates in local time — a rule's
45
+ * "YYYY-MM-DD" is local midnight, "equals" compares local calendar days. Fed
46
+ * these, it compares on the zone's calendar whatever the process runs in.
47
+ */
48
+ function inRuleZone(instant) {
49
+ const w = wallClock(instant);
50
+ return new Date(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms);
51
+ }
52
+ /**
53
+ * `now` moved by a relative rule value, the way dayjs does it in the browser:
54
+ * minutes and hours as elapsed time, days and weeks on the zone's calendar —
55
+ * "in 1 day" across a daylight-saving change keeps the time of day.
56
+ */
57
+ function addRelative(now, amount, unit) {
58
+ if (unit === "minutes")
59
+ return new Date(now.getTime() + amount * 60_000);
60
+ if (unit === "hours")
61
+ return new Date(now.getTime() + amount * 3_600_000);
62
+ const days = unit === "weeks" ? amount * 7 : amount;
63
+ const w = wallClock(now);
64
+ const target = Date.UTC(w.year, w.month - 1, w.day + days, w.hour, w.minute, w.second, w.ms);
65
+ // The target's offset may differ from today's; one correction settles it.
66
+ const first = target - zoneOffset(new Date(target));
67
+ return new Date(target - zoneOffset(new Date(first)));
68
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * When a rule acts. Mirrors `RuleTrigger` of the frontend.
3
+ *
4
+ * - `create`: when the ticket is created.
5
+ * - `becomes`: when its condition starts to hold — on creation if it holds,
6
+ * later when a save makes it hold that did not before.
7
+ * - `always`: on every save while the condition holds. A rule stored without
8
+ * a trigger predates the choice and keeps this behaviour.
9
+ */
10
+ export type RuleTrigger = "create" | "becomes" | "always";
11
+ /**
12
+ * What a form config does to a ticket on save, in the order the frontend used
13
+ * to apply it: the computed priority, the field value rules, the action rules
14
+ * — so a rule on the priority sees the computed one.
15
+ *
16
+ * Which config: the one the form that saves was showing, when it names it in
17
+ * the save's context (`{ formConfig: <id> }`, see `configFromContext`) — a
18
+ * form opened by QR code shows another config than the user's own, and its
19
+ * rules are what the user saw. Otherwise (the admin table, the REST API, an
20
+ * alarm) the one that applies to the user saving (`applicableFormConfig`).
21
+ *
22
+ * The rules act on a save somebody makes — a person, an integration, an alarm
23
+ * creating a ticket. Not on the server's own bookkeeping: a master-key update
24
+ * (sort keys pushed down, the scheduler archiving) would otherwise re-assign
25
+ * people that were taken off by hand, through an "always" rule. The priority
26
+ * follows its inputs on any save.
27
+ */
28
+ export declare function applyFormConfigRules(object: Parse.Object, original: Parse.Object | undefined, user: Parse.User | undefined, { master, sessionToken, context, }: {
29
+ master: boolean;
30
+ sessionToken: string | undefined;
31
+ context: Record<string, unknown> | undefined;
32
+ }): Promise<void>;
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyFormConfigRules = applyFormConfigRules;
4
+ const openservice_shared_1 = require("@opendash/openservice-shared");
5
+ const ruleset_core_1 = require("@opendash/ruleset-core");
6
+ const index_js_1 = require("../../../types/index.js");
7
+ const ticketFormConfig_js_1 = require("./ticketFormConfig.js");
8
+ const ticketPriority_js_1 = require("./ticketPriority.js");
9
+ const ticketRuleTime_js_1 = require("./ticketRuleTime.js");
10
+ /**
11
+ * Columns a rule never writes: the server's and the archive's own, and the
12
+ * priority a formula computes. Mirrors `PROTECTED_TICKET_FIELDS` of the
13
+ * frontend, plus the derived columns only the server knows about.
14
+ */
15
+ const PROTECTED_FIELDS = new Set([
16
+ "deleted",
17
+ "tenant",
18
+ "number",
19
+ "createdBy",
20
+ "closedAt",
21
+ "archiveReason",
22
+ "useForSimilarCases",
23
+ "origin",
24
+ "statusOrder",
25
+ "projectSortKey",
26
+ "equipmentSortKey",
27
+ ]);
28
+ /** Pointer columns a rule may write, with the class they point at. */
29
+ const POINTER_TARGETS = {
30
+ status: index_js_1.Service_Status,
31
+ project: index_js_1.Service_Project,
32
+ equipment: index_js_1.Service_Equipment,
33
+ parent: index_js_1.Service_Ticket,
34
+ };
35
+ /** Columns holding a list of ids (stored as plain id strings). */
36
+ const REF_LIST_FIELDS = new Set([
37
+ "tags",
38
+ "assignedUsers",
39
+ "assignedRoles",
40
+ ]);
41
+ function parseJson(raw) {
42
+ try {
43
+ const parsed = JSON.parse(raw ?? "[]");
44
+ return Array.isArray(parsed) ? parsed : [];
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ }
50
+ /** A rule set without a single rule always holds — the editor starts empty. */
51
+ function holds(condition, values) {
52
+ if (!condition || !hasRules(condition))
53
+ return true;
54
+ return (0, ruleset_core_1.applyRuleSet)(condition, values);
55
+ }
56
+ function hasRules(group) {
57
+ return (group.kind === "group" &&
58
+ group.rules.some((rule) => rule.kind === "group" ? hasRules(rule) : true));
59
+ }
60
+ /** Reads a ticket's values, dates on the rule zone's calendar. */
61
+ function readerOf(object) {
62
+ return (field) => {
63
+ const value = object.get(field);
64
+ return value instanceof Date ? (0, ticketRuleTime_js_1.inRuleZone)(value) : value;
65
+ };
66
+ }
67
+ function isEmpty(value) {
68
+ if (value == null || value === "")
69
+ return true;
70
+ return Array.isArray(value) && value.length === 0;
71
+ }
72
+ /** Whether a rule with `on` acts in this save. */
73
+ function fires(on, creating, becameTrue) {
74
+ switch (on ?? "always") {
75
+ case "create":
76
+ return creating;
77
+ case "becomes":
78
+ return becameTrue;
79
+ default:
80
+ return true;
81
+ }
82
+ }
83
+ /** The first value rule that has a value and whose condition holds. */
84
+ function firstMatch(entry, values) {
85
+ return entry.valueRules?.find((rule) => isComplete(rule.value) && holds(rule.when, values));
86
+ }
87
+ function isComplete(value) {
88
+ if (!value)
89
+ return false;
90
+ if (value.kind === "relative")
91
+ return typeof value.amount === "number" && !!value.unit;
92
+ return value.value !== undefined;
93
+ }
94
+ /**
95
+ * A rule's value in the column's stored shape — what the frontend's
96
+ * `buildCreateValue` sends: a pointer for a reference, plain id strings for a
97
+ * list of references, a `Date` for a date.
98
+ */
99
+ function storedValue(key, value, now) {
100
+ if (value.kind === "relative") {
101
+ return (0, ticketRuleTime_js_1.addRelative)(now, value.amount, value.unit);
102
+ }
103
+ const raw = value.value;
104
+ if (REF_LIST_FIELDS.has(key))
105
+ return (0, openservice_shared_1.refIds)(raw);
106
+ const target = POINTER_TARGETS[key];
107
+ if (target) {
108
+ const id = (0, openservice_shared_1.refIds)([raw])[0];
109
+ return id ? target.createWithoutData(id) : undefined;
110
+ }
111
+ return raw;
112
+ }
113
+ /**
114
+ * The field value rules of `config`, in form order; each sees what the ones
115
+ * before it wrote. Mirrors `applyValueRules` of the frontend.
116
+ *
117
+ * - `prefill`: on creation, into an empty field.
118
+ * - `set`: by its trigger, overriding. `becomes` acts when the rule becomes
119
+ * the field's first matching rule — so lowering a priority from "critical"
120
+ * to "high" applies the "high" rule's due date.
121
+ */
122
+ function applyValueRules(entries, object, original, now) {
123
+ const creating = !original;
124
+ const after = readerOf(object);
125
+ const before = original ? readerOf(original) : undefined;
126
+ for (const entry of entries) {
127
+ if (!entry?.key || PROTECTED_FIELDS.has(entry.key))
128
+ continue;
129
+ const rule = firstMatch(entry, after);
130
+ if (!rule?.value)
131
+ continue;
132
+ if (rule.mode === "prefill") {
133
+ if (!creating || !isEmpty(object.get(entry.key)))
134
+ continue;
135
+ }
136
+ else {
137
+ // A relative date set on every save would move with each one; the
138
+ // editor does not offer it, and a hand-written config does not get it.
139
+ if (rule.value.kind === "relative" && (rule.on ?? "always") === "always")
140
+ continue;
141
+ const becameTrue = !before || firstMatch(entry, before)?.id !== rule.id;
142
+ if (!fires(rule.on, creating, becameTrue))
143
+ continue;
144
+ }
145
+ const value = storedValue(entry.key, rule.value, now);
146
+ if (value === undefined)
147
+ continue;
148
+ object.set(entry.key, value);
149
+ }
150
+ }
151
+ /** Union of id lists, de-duplicated, in order. */
152
+ function withIds(existing, ids) {
153
+ return [...new Set([...(0, openservice_shared_1.refIds)(existing), ...ids])];
154
+ }
155
+ /**
156
+ * The action rules of `config`. Mirrors `applyTicketRules` and the "assign"
157
+ * handler of the frontend: the users and roles are added to the assignees.
158
+ * Who was assigned this way is notified by the ticket's afterSave like anyone
159
+ * else newly assigned.
160
+ */
161
+ function applyActionRules(rules, object, original) {
162
+ const creating = !original;
163
+ const after = readerOf(object);
164
+ const before = original ? readerOf(original) : undefined;
165
+ for (const rule of rules) {
166
+ if (rule?.function !== "assign" || !rule.ruleset)
167
+ continue;
168
+ if (!holds(rule.ruleset, after))
169
+ continue;
170
+ const becameTrue = !before || !holds(rule.ruleset, before);
171
+ if (!fires(rule.params?.on, creating, becameTrue))
172
+ continue;
173
+ const assignees = Array.isArray(rule.params?.assignees)
174
+ ? rule.params.assignees.filter((a) => typeof a === "string")
175
+ : [];
176
+ const users = assignees
177
+ .filter((a) => a.startsWith("user:"))
178
+ .map((a) => a.slice("user:".length));
179
+ const roles = assignees
180
+ .filter((a) => a.startsWith("role:"))
181
+ .map((a) => a.slice("role:".length));
182
+ if (users.length > 0) {
183
+ const next = withIds(object.get("assignedUsers"), users);
184
+ if (next.length !== (0, openservice_shared_1.refIds)(object.get("assignedUsers")).length)
185
+ object.set("assignedUsers", next);
186
+ }
187
+ if (roles.length > 0) {
188
+ const next = withIds(object.get("assignedRoles"), roles);
189
+ if (next.length !== (0, openservice_shared_1.refIds)(object.get("assignedRoles")).length)
190
+ object.set("assignedRoles", next);
191
+ }
192
+ }
193
+ }
194
+ /**
195
+ * What a form config does to a ticket on save, in the order the frontend used
196
+ * to apply it: the computed priority, the field value rules, the action rules
197
+ * — so a rule on the priority sees the computed one.
198
+ *
199
+ * Which config: the one the form that saves was showing, when it names it in
200
+ * the save's context (`{ formConfig: <id> }`, see `configFromContext`) — a
201
+ * form opened by QR code shows another config than the user's own, and its
202
+ * rules are what the user saw. Otherwise (the admin table, the REST API, an
203
+ * alarm) the one that applies to the user saving (`applicableFormConfig`).
204
+ *
205
+ * The rules act on a save somebody makes — a person, an integration, an alarm
206
+ * creating a ticket. Not on the server's own bookkeeping: a master-key update
207
+ * (sort keys pushed down, the scheduler archiving) would otherwise re-assign
208
+ * people that were taken off by hand, through an "always" rule. The priority
209
+ * follows its inputs on any save.
210
+ */
211
+ async function applyFormConfigRules(object, original, user, { master, sessionToken, context, }) {
212
+ const runRules = !original || !master;
213
+ if (!runRules && !(0, ticketPriority_js_1.changesPriorityInputs)(object, original))
214
+ return;
215
+ const tenant = object.get("tenant");
216
+ const config = (await (0, ticketFormConfig_js_1.configFromContext)(context?.formConfig, tenant, {
217
+ master,
218
+ sessionToken,
219
+ })) ?? (await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user));
220
+ (0, ticketPriority_js_1.applyComputedPriority)(object, original, config);
221
+ if (!runRules || !config)
222
+ return;
223
+ applyValueRules(parseJson(config.fields), object, original, new Date());
224
+ applyActionRules(parseJson(config.rules), object, original);
225
+ }
@@ -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, {
@@ -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
  }
@@ -0,0 +1,23 @@
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, appliesRules: true }`; `null` means the
7
+ * built-in form. `appliesRules` tells the frontend that the ticket hook
8
+ * applies the config's computed priority and save-time rules itself, so the
9
+ * browser must not apply them again on save (see `applyFormConfigRules`).
10
+ *
11
+ * **Why a function.** Resolution goes by the caller's roles, inherited ones
12
+ * included, and the browser cannot resolve them: it knows its roles by name, a
13
+ * config names them by id, and a role the caller may not read cannot be looked
14
+ * up. The ticket hook takes the priority formula from the same resolution
15
+ * (`applicableFormConfig`), so the form and the server never pick different
16
+ * configs.
17
+ *
18
+ * Only an id comes back, and only one of a config the caller can read — its
19
+ * audience ACL grants that to the users and roles it names — so the answer
20
+ * reveals nothing the caller could not list anyway. The browser reads the
21
+ * config itself with its own session.
22
+ */
23
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,54 @@
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, appliesRules: true }`; `null` means the
16
+ * built-in form. `appliesRules` tells the frontend that the ticket hook
17
+ * applies the config's computed priority and save-time rules itself, so the
18
+ * browser must not apply them again on save (see `applyFormConfigRules`).
19
+ *
20
+ * **Why a function.** Resolution goes by the caller's roles, inherited ones
21
+ * included, and the browser cannot resolve them: it knows its roles by name, a
22
+ * config names them by id, and a role the caller may not read cannot be looked
23
+ * up. The ticket hook takes the priority formula from the same resolution
24
+ * (`applicableFormConfig`), so the form and the server never pick different
25
+ * configs.
26
+ *
27
+ * Only an id comes back, and only one of a config the caller can read — its
28
+ * audience ACL grants that to the users and roles it names — so the answer
29
+ * reveals nothing the caller could not list anyway. The browser reads the
30
+ * config itself with its own session.
31
+ */
32
+ async function init(name) {
33
+ node_1.default.Cloud.define(name, async (request) => {
34
+ const user = request.user;
35
+ const sessionToken = user?.getSessionToken();
36
+ if (!user || !sessionToken) {
37
+ throw new node_1.default.Error(node_1.default.Error.INVALID_SESSION_TOKEN, `${name} requires a logged-in user`);
38
+ }
39
+ const requested = request.params?.tenant;
40
+ if (requested !== undefined && typeof requested !== "string") {
41
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name}: tenant must be an object id`);
42
+ }
43
+ const tenant = requested
44
+ ? index_js_1.Tenant.createWithoutData(requested)
45
+ : user.get("tenant");
46
+ const config = await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user);
47
+ if (!config?.id)
48
+ return { id: null, appliesRules: true };
49
+ const readable = await new node_1.default.Query(index_js_1.Service_FormConfig)
50
+ .equalTo("objectId", config.id)
51
+ .first({ sessionToken });
52
+ return { id: readable?.id ?? null, appliesRules: true };
53
+ }, { requireUser: true });
54
+ }
@@ -10,6 +10,8 @@ const ticketNumber_js_1 = require("../features/openservice/tickets/ticketNumber.
10
10
  const ticketReferences_js_1 = require("../features/openservice/tickets/ticketReferences.js");
11
11
  const ticketAccess_js_1 = require("../features/openservice/tickets/ticketAccess.js");
12
12
  const ticketNotifications_js_1 = require("../features/openservice/tickets/ticketNotifications.js");
13
+ const ticketArchive_js_1 = require("../features/openservice/tickets/ticketArchive.js");
14
+ const ticketRules_js_1 = require("../features/openservice/tickets/ticketRules.js");
13
15
  async function init() {
14
16
  // Soft delete: a ticket is referenced by chat messages, meta entries,
15
17
  // notifications and child tickets, so the frontend archives instead of
@@ -35,6 +37,12 @@ async function init() {
35
37
  Boolean(object.get("deleted")) !== Boolean(original.get("deleted"))) {
36
38
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_delete, "archive a ticket", original.get("tenant"));
37
39
  }
40
+ // Whether an archived ticket still feeds the similar-case search is archive
41
+ // management as well (the archive page's switch), so it takes the same
42
+ // capability. Set while archiving, it is covered by the check above.
43
+ if (!(0, index_js_1.isMigrationMode)() && (0, ticketArchive_js_1.changesSimilarCaseUse)(object, original)) {
44
+ await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_delete, "change whether an archived ticket is used for similar cases", original.get("tenant"));
45
+ }
38
46
  if (isNew && !object.get("createdBy") && user)
39
47
  object.set("createdBy", user);
40
48
  await (0, index_js_1.defaultHandler)(request);
@@ -50,6 +58,20 @@ async function init() {
50
58
  if (isNew && !(0, index_js_1.isMigrationMode)()) {
51
59
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_create, "create a ticket", object.get("tenant"));
52
60
  }
61
+ // What the form config does on save — the one the saving form names in
62
+ // the context, else the user's own: the computed priority, the field value
63
+ // rules, the assignment rules. The forms show it live; this is what holds
64
+ // for every write path. Before everything that follows from those values
65
+ // — the assignable-role check and the ACL (a rule assigns), the tenant
66
+ // check and sort keys (a rule sets a status or project), `closedAt`, the
67
+ // number. A migration replays history as it was.
68
+ if (!(0, index_js_1.isMigrationMode)()) {
69
+ await (0, ticketRules_js_1.applyFormConfigRules)(object, original, user, {
70
+ master: !!request.master,
71
+ sessionToken: request.sessionToken ?? undefined,
72
+ context: request.context,
73
+ });
74
+ }
53
75
  // No `allowTenantUserWrite`: who may edit a ticket is decided per record by
54
76
  // `setTicketACL` below — creator, assigned users, assigned roles — and a
55
77
  // blanket write grant for every user in the tenant would make that decision
@@ -71,6 +93,8 @@ async function init() {
71
93
  (0, ticketReferences_js_1.assertSameTenantReferences)(object, referenced);
72
94
  (0, ticketReferences_js_1.applySortKeys)(object, referenced, restored);
73
95
  (0, ticketReferences_js_1.applyClosedAt)(object, referenced);
96
+ (0, ticketArchive_js_1.applyArchiveReason)(object, original, !!request.master);
97
+ (0, ticketArchive_js_1.applySimilarCaseUse)(object, original);
74
98
  // Assign a sequential ticket number on creation. Done here (backend) rather
75
99
  // than in the frontend because every write path — the create form, the
76
100
  // cross-plugin service, and the generic entity admin — funnels through this
@@ -81,7 +105,13 @@ async function init() {
81
105
  // move could collide with an existing number in the new project. Drawing a
82
106
  // fresh number from the destination keeps each project's sequence unique
83
107
  // (the source sequence simply gains a gap, which is fine).
84
- const projectChanged = !isNew && object.dirty("project");
108
+ //
109
+ // Compared against `original`, not taken from `dirty()`: a field the save
110
+ // merely resends counts as dirty, and the admin table resends every field
111
+ // of its form — each edit there used to give the ticket a new number.
112
+ const projectId = (value) => value?.id;
113
+ const projectChanged = !isNew &&
114
+ projectId(object.get("project")) !== projectId(original?.get("project"));
85
115
  // The number is the server's. The REST API and the generic admin let a
86
116
  // client send one, and a caller-chosen number collides with — or poses as
87
117
  // — another ticket's. Master-key writes (alarm tickets) are the server's
@@ -11,6 +11,7 @@ export interface Service_TicketAttributes {
11
11
  createdAt: Date;
12
12
  updatedAt: Date;
13
13
  actualDuration?: number | undefined;
14
+ archiveReason?: string | undefined;
14
15
  assignedRoles?: any[] | undefined;
15
16
  assignedUsers?: any[] | undefined;
16
17
  checklist?: any[] | undefined;
@@ -38,12 +39,15 @@ export interface Service_TicketAttributes {
38
39
  tags?: any[] | undefined;
39
40
  tenant: Tenant;
40
41
  title: string;
42
+ useForSimilarCases?: boolean | undefined;
41
43
  }
42
44
  export declare class Service_Ticket extends Parse.Object<Service_TicketAttributes> {
43
45
  static className: string;
44
46
  constructor(data?: Partial<Service_TicketAttributes>);
45
47
  get actualDuration(): number | undefined;
46
48
  set actualDuration(value: number | undefined);
49
+ get archiveReason(): string | undefined;
50
+ set archiveReason(value: string | undefined);
47
51
  get assignedRoles(): any[] | undefined;
48
52
  set assignedRoles(value: any[] | undefined);
49
53
  get assignedUsers(): any[] | undefined;
@@ -98,4 +102,6 @@ export declare class Service_Ticket extends Parse.Object<Service_TicketAttribute
98
102
  set tenant(value: Tenant);
99
103
  get title(): string;
100
104
  set title(value: string);
105
+ get useForSimilarCases(): boolean | undefined;
106
+ set useForSimilarCases(value: boolean | undefined);
101
107
  }
@@ -16,6 +16,12 @@ class Service_Ticket extends node_1.default.Object {
16
16
  set actualDuration(value) {
17
17
  super.set("actualDuration", value);
18
18
  }
19
+ get archiveReason() {
20
+ return super.get("archiveReason");
21
+ }
22
+ set archiveReason(value) {
23
+ super.set("archiveReason", value);
24
+ }
19
25
  get assignedRoles() {
20
26
  return super.get("assignedRoles");
21
27
  }
@@ -178,6 +184,12 @@ class Service_Ticket extends node_1.default.Object {
178
184
  set title(value) {
179
185
  super.set("title", value);
180
186
  }
187
+ get useForSimilarCases() {
188
+ return super.get("useForSimilarCases");
189
+ }
190
+ set useForSimilarCases(value) {
191
+ super.set("useForSimilarCases", value);
192
+ }
181
193
  }
182
194
  exports.Service_Ticket = Service_Ticket;
183
195
  node_1.default.Object.registerSubclass("OD3_Service_Ticket", Service_Ticket);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.25.0",
3
+ "version": "4.27.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [
@@ -3,6 +3,9 @@
3
3
  "actualDuration": {
4
4
  "type": "Number"
5
5
  },
6
+ "archiveReason": {
7
+ "type": "String"
8
+ },
6
9
  "assignedRoles": {
7
10
  "type": "Array"
8
11
  },
@@ -97,6 +100,9 @@
97
100
  "title": {
98
101
  "type": "String",
99
102
  "required": true
103
+ },
104
+ "useForSimilarCases": {
105
+ "type": "Boolean"
100
106
  }
101
107
  },
102
108
  "classLevelPermissions": {