@openinc/parse-server-opendash 4.26.0 → 4.28.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 (29) hide show
  1. package/dist/features/notifications/services/sendMails.d.ts +5 -1
  2. package/dist/features/notifications/services/sendMails.js +6 -1
  3. package/dist/features/openservice/schedules/calendarSync/CalendarManager.d.ts +5 -0
  4. package/dist/features/openservice/schedules/calendarSync/CalendarManager.js +30 -0
  5. package/dist/features/openservice/schedules/calendarSync/Event.d.ts +5 -0
  6. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceCalendarSyncPoller.js +10 -1
  7. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceSyncTypes.d.ts +12 -0
  8. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.d.ts +119 -0
  9. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.js +159 -0
  10. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.d.ts +26 -0
  11. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.js +39 -0
  12. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.d.ts +43 -0
  13. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.js +187 -0
  14. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.d.ts +3 -0
  15. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.js +54 -12
  16. package/dist/features/openservice/tickets/ticketFormConfig.d.ts +18 -0
  17. package/dist/features/openservice/tickets/ticketFormConfig.js +27 -0
  18. package/dist/features/openservice/tickets/ticketPriority.d.ts +7 -6
  19. package/dist/features/openservice/tickets/ticketPriority.js +19 -13
  20. package/dist/features/openservice/tickets/ticketRuleTime.d.ts +18 -0
  21. package/dist/features/openservice/tickets/ticketRuleTime.js +68 -0
  22. package/dist/features/openservice/tickets/ticketRules.d.ts +32 -0
  23. package/dist/features/openservice/tickets/ticketRules.js +225 -0
  24. package/dist/functions/openinc-openservice-form-config.d.ts +4 -1
  25. package/dist/functions/openinc-openservice-form-config.js +6 -3
  26. package/dist/functions/openinc-openservice-notify-contacts.d.ts +2 -1
  27. package/dist/functions/openinc-openservice-notify-contacts.js +27 -13
  28. package/dist/hooks/Service_Ticket.js +15 -7
  29. package/package.json +2 -1
@@ -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
+ }
@@ -3,7 +3,10 @@
3
3
  * the detail edit and the import of `@opendash/plugin-openservice-ticket`.
4
4
  *
5
5
  * Params: `{ tenant?: string }`, the active tenant (default: the caller's
6
- * own). Returns `{ id: string | null }`; `null` means the built-in form.
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`).
7
10
  *
8
11
  * **Why a function.** Resolution goes by the caller's roles, inherited ones
9
12
  * included, and the browser cannot resolve them: it knows its roles by name, a
@@ -12,7 +12,10 @@ const index_js_1 = require("../types/index.js");
12
12
  * the detail edit and the import of `@opendash/plugin-openservice-ticket`.
13
13
  *
14
14
  * Params: `{ tenant?: string }`, the active tenant (default: the caller's
15
- * own). Returns `{ id: string | null }`; `null` means the built-in form.
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`).
16
19
  *
17
20
  * **Why a function.** Resolution goes by the caller's roles, inherited ones
18
21
  * included, and the browser cannot resolve them: it knows its roles by name, a
@@ -42,10 +45,10 @@ async function init(name) {
42
45
  : user.get("tenant");
43
46
  const config = await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, user);
44
47
  if (!config?.id)
45
- return { id: null };
48
+ return { id: null, appliesRules: true };
46
49
  const readable = await new node_1.default.Query(index_js_1.Service_FormConfig)
47
50
  .equalTo("objectId", config.id)
48
51
  .first({ sessionToken });
49
- return { id: readable?.id ?? null };
52
+ return { id: readable?.id ?? null, appliesRules: true };
50
53
  }, { requireUser: true });
51
54
  }
@@ -11,6 +11,7 @@
11
11
  * contacts with arbitrary text.
12
12
  *
13
13
  * Params: `contactIds`, `subject`, `body`, plus `scheduleId` / `ruleId` /
14
- * `occurrence` for the log line. Returns `{ sent, skipped, withoutEmail }`.
14
+ * `occurrence` — which identify the message for deduplication (see
15
+ * `alreadySent`) and the log line. Returns `{ sent, skipped, withoutEmail }`.
15
16
  */
16
17
  export declare function init(name: string): Promise<void>;
@@ -22,7 +22,8 @@ const DEDUP_WINDOW_DAYS = 30;
22
22
  * contacts with arbitrary text.
23
23
  *
24
24
  * Params: `contactIds`, `subject`, `body`, plus `scheduleId` / `ruleId` /
25
- * `occurrence` for the log line. Returns `{ sent, skipped, withoutEmail }`.
25
+ * `occurrence` — which identify the message for deduplication (see
26
+ * `alreadySent`) and the log line. Returns `{ sent, skipped, withoutEmail }`.
26
27
  */
27
28
  async function init(name) {
28
29
  node_1.default.Cloud.define(name, async (request) => {
@@ -36,6 +37,10 @@ async function init(name) {
36
37
  const contacts = await new node_1.default.Query(index_js_2.Contact)
37
38
  .containedIn("objectId", contactIds)
38
39
  .find({ useMasterKey: true });
40
+ // Plan, rule and date name the message; the text only describes it.
41
+ const dedupKey = scheduleId && ruleId && occurrence
42
+ ? `${scheduleId}|${ruleId}|${occurrence}`
43
+ : undefined;
39
44
  let sent = 0;
40
45
  let skipped = 0;
41
46
  let withoutEmail = 0;
@@ -45,11 +50,11 @@ async function init(name) {
45
50
  withoutEmail++;
46
51
  continue;
47
52
  }
48
- if (await alreadySent(to, body)) {
53
+ if (await alreadySent(to, body, dedupKey)) {
49
54
  skipped++;
50
55
  continue;
51
56
  }
52
- await (0, index_js_1.sendSimpleEmail)(to, subject, body);
57
+ await (0, index_js_1.sendSimpleEmail)(to, subject, body, dedupKey);
53
58
  sent++;
54
59
  }
55
60
  console.log(`[${name}] plan ${scheduleId} rule ${ruleId} occurrence ${occurrence}: ` +
@@ -60,22 +65,31 @@ async function init(name) {
60
65
  {});
61
66
  }
62
67
  /**
63
- * Whether this exact message already went to this address recently.
68
+ * Whether this message already went to this address recently.
64
69
  *
65
- * The idempotency key is the **message body**, because it already identifies
66
- * the occurrence (it carries plan, description and the due date) and because
67
- * `Core_Email` has no free column to put a marker in. That makes a restart
68
- * inside the same tick harmless, while a genuinely different occurrence — a
69
- * different date in the text — still goes out.
70
+ * **By key first.** Plan, rule and date (`dedupKey`, stored in the mail's
71
+ * payload) say which reminder a mail was, whatever its wording. The text alone
72
+ * did not: the "upcoming" and "due" texts used to carry no date, so every date
73
+ * of a plan read the same — a weekly plan's provider got one reminder in four,
74
+ * and a moved date's reminder was swallowed as a repeat of the old one. And the
75
+ * scheduler announces dates late now (a date moved inside its reminder lead),
76
+ * which also re-asks for dates whose plan was merely renamed since: by text
77
+ * those would go out a second time.
78
+ *
79
+ * **By text as well.** Mails from before the key existed have none, and the
80
+ * same text to the same address within the window is a repeat whoever sent it.
70
81
  */
71
- async function alreadySent(to, body) {
82
+ async function alreadySent(to, body, dedupKey) {
72
83
  const since = new Date(Date.now() - DEDUP_WINDOW_DAYS * 24 * 3600 * 1000);
73
84
  // Dot access into the `payload` Object column: Mongo resolves it, but the
74
85
  // generated class type only knows top-level columns — hence the untyped
75
- // query handle.
76
- const query = new node_1.default.Query(index_js_2.Core_Email);
86
+ // query handles.
87
+ const byText = new node_1.default.Query(index_js_2.Core_Email);
88
+ byText.equalTo("payload.text", body);
89
+ const byKey = new node_1.default.Query(index_js_2.Core_Email);
90
+ byKey.equalTo("payload.dedupKey", dedupKey);
91
+ const query = dedupKey ? node_1.default.Query.or(byKey, byText) : byText;
77
92
  query.equalTo("payload.to", to);
78
- query.equalTo("payload.text", body);
79
93
  query.greaterThan("createdAt", since);
80
94
  const existing = await query.first({ useMasterKey: true });
81
95
  return !!existing;
@@ -11,7 +11,7 @@ const ticketReferences_js_1 = require("../features/openservice/tickets/ticketRef
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
13
  const ticketArchive_js_1 = require("../features/openservice/tickets/ticketArchive.js");
14
- const ticketPriority_js_1 = require("../features/openservice/tickets/ticketPriority.js");
14
+ const ticketRules_js_1 = require("../features/openservice/tickets/ticketRules.js");
15
15
  async function init() {
16
16
  // Soft delete: a ticket is referenced by chat messages, meta entries,
17
17
  // notifications and child tickets, so the frontend archives instead of
@@ -58,6 +58,20 @@ async function init() {
58
58
  if (isNew && !(0, index_js_1.isMigrationMode)()) {
59
59
  await (0, index_js_2.requirePermission)(request, Permissions_js_1.Permissions.SERVICE.ticket_create, "create a ticket", object.get("tenant"));
60
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
+ }
61
75
  // No `allowTenantUserWrite`: who may edit a ticket is decided per record by
62
76
  // `setTicketACL` below — creator, assigned users, assigned roles — and a
63
77
  // blanket write grant for every user in the tenant would make that decision
@@ -81,12 +95,6 @@ async function init() {
81
95
  (0, ticketReferences_js_1.applyClosedAt)(object, referenced);
82
96
  (0, ticketArchive_js_1.applyArchiveReason)(object, original, !!request.master);
83
97
  (0, ticketArchive_js_1.applySimilarCaseUse)(object, original);
84
- // The priority a form config derives from downtime, restriction and
85
- // frequency. The ticket forms compute it as well, to show it while the
86
- // user types — here it holds for every other write path (the admin table,
87
- // the REST API). A migration replays the stored priority as it was.
88
- if (!(0, index_js_1.isMigrationMode)())
89
- await (0, ticketPriority_js_1.applyComputedPriority)(object, original, user);
90
98
  // Assign a sequential ticket number on creation. Done here (backend) rather
91
99
  // than in the frontend because every write path — the create form, the
92
100
  // cross-plugin service, and the generic entity admin — funnels through this
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.26.0",
3
+ "version": "4.28.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [
@@ -70,6 +70,7 @@
70
70
  "backfill:changelog-search": "node dist/scripts/backfill-changelog-search.js",
71
71
  "repair:ticket-acl": "node dist/scripts/repair-ticket-acl.js",
72
72
  "test:integration": "node --test --test-concurrency=1 \"test/integration/**/*.test.mjs\"",
73
+ "test:unit": "node --test \"test/unit/**/*.test.mjs\"",
73
74
  "seed:v1": "node dist/scripts/seed-v1-testdata.js"
74
75
  },
75
76
  "dependencies": {