@openinc/parse-server-opendash 4.38.1 → 4.39.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 (49) hide show
  1. package/dist/features/openservice/alarms/index.d.ts +5 -2
  2. package/dist/features/openservice/alarms/index.js +6 -5
  3. package/dist/features/openservice/alarms/schedule/AlarmScheduleTypes.d.ts +4 -2
  4. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.d.ts +6 -6
  5. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.js +36 -139
  6. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.js +2 -2
  7. package/dist/features/openservice/alarms/ticket/createAlarmTicket.d.ts +7 -4
  8. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +42 -161
  9. package/dist/features/openservice/alarms/ticket/ensureAlarmTicketAction.js +2 -2
  10. package/dist/features/openservice/automation/automationCall.d.ts +56 -0
  11. package/dist/features/openservice/automation/automationCall.js +61 -0
  12. package/dist/features/openservice/automation/createSchedule.d.ts +124 -0
  13. package/dist/features/openservice/automation/createSchedule.js +247 -0
  14. package/dist/features/openservice/automation/createTicket.d.ts +121 -0
  15. package/dist/features/openservice/automation/createTicket.js +212 -0
  16. package/dist/features/openservice/automation/index.d.ts +32 -0
  17. package/dist/features/openservice/automation/index.js +56 -0
  18. package/dist/features/openservice/{alarms/actionParams.d.ts → automation/params.d.ts} +15 -1
  19. package/dist/features/openservice/{alarms/actionParams.js → automation/params.js} +58 -1
  20. package/dist/features/openservice/automation/recordExecution.d.ts +61 -0
  21. package/dist/features/openservice/automation/recordExecution.js +111 -0
  22. package/dist/features/openservice/automation/resolveEquipment.d.ts +16 -0
  23. package/dist/features/openservice/automation/resolveEquipment.js +43 -0
  24. package/dist/features/openservice/automation/resolveStatus.d.ts +20 -0
  25. package/dist/features/openservice/automation/resolveStatus.js +57 -0
  26. package/dist/features/openservice/automation/resolveTenantUser.d.ts +16 -0
  27. package/dist/features/openservice/automation/resolveTenantUser.js +35 -0
  28. package/dist/features/openservice/automation/ticketDefaults.d.ts +34 -0
  29. package/dist/features/openservice/{alarms/ticket/alarmTicketDefaults.js → automation/ticketDefaults.js} +8 -8
  30. package/dist/features/openservice/automation/updateTicket.d.ts +65 -0
  31. package/dist/features/openservice/automation/updateTicket.js +141 -0
  32. package/dist/features/openservice/index.d.ts +2 -0
  33. package/dist/features/openservice/index.js +2 -0
  34. package/dist/functions/openinc-openservice-create-schedule.d.ts +20 -0
  35. package/dist/functions/openinc-openservice-create-schedule.js +41 -0
  36. package/dist/functions/openinc-openservice-create-ticket.d.ts +24 -0
  37. package/dist/functions/openinc-openservice-create-ticket.js +48 -0
  38. package/dist/functions/openinc-openservice-record-execution.d.ts +17 -0
  39. package/dist/functions/openinc-openservice-record-execution.js +38 -0
  40. package/dist/functions/openinc-openservice-update-ticket.d.ts +16 -0
  41. package/dist/functions/openinc-openservice-update-ticket.js +37 -0
  42. package/dist/hooks/Service_Schedule.js +5 -0
  43. package/dist/hooks/Service_Schedule_Execution.js +35 -0
  44. package/package.json +1 -1
  45. package/dist/features/openservice/alarms/resolveAlarmUser.d.ts +0 -16
  46. package/dist/features/openservice/alarms/resolveAlarmUser.js +0 -35
  47. package/dist/features/openservice/alarms/resolveEquipment.d.ts +0 -17
  48. package/dist/features/openservice/alarms/resolveEquipment.js +0 -45
  49. package/dist/features/openservice/alarms/ticket/alarmTicketDefaults.d.ts +0 -34
@@ -7,6 +7,11 @@
7
7
  * called, secured or deduplicated, and the identity helpers in that base
8
8
  * (`alarmKey`, `alarmOrigin`) **must** stay a single implementation: two of
9
9
  * them would silently start creating duplicates. `README.md` has the wiring.
10
+ *
11
+ * What the actions *create* is not decided here: both hand their parameters to
12
+ * `../automation/` (`createTicket`, `createSchedule`), the implementation every
13
+ * machine path shares. An alarm adds only what is its own — the `alarm:`
14
+ * origin, placeholders, the firing's details.
10
15
  */
11
16
  export { alarmDetailLines, alarmKey, alarmOrigin, firedAt, formatValue, renderTitleTemplate, sensorLabel, } from "./alarmIdentity.js";
12
17
  export { ensureAlarmActionRow } from "./ensureAlarmActionRow.js";
@@ -16,8 +21,6 @@ export { ALARM_WEBHOOK_TOKEN_HEADER, OPENWARE_TEMPLATE_TYPE, OPENWARE_WEBHOOK_PA
16
21
  export type { OpenwareAlarm } from "./openwareAlarm.js";
17
22
  export { readAlarmCall } from "./readAlarmCall.js";
18
23
  export type { AlarmCall } from "./readAlarmCall.js";
19
- export { resolveAlarmUser } from "./resolveAlarmUser.js";
20
- export { resolveEquipment } from "./resolveEquipment.js";
21
24
  export { tenantForSecret } from "./tenantForSecret.js";
22
25
  export type { AlarmEvent } from "./AlarmEvent.js";
23
26
  export { alarmTicketFields } from "./ticket/alarmTicketFields.js";
@@ -8,9 +8,14 @@
8
8
  * called, secured or deduplicated, and the identity helpers in that base
9
9
  * (`alarmKey`, `alarmOrigin`) **must** stay a single implementation: two of
10
10
  * them would silently start creating duplicates. `README.md` has the wiring.
11
+ *
12
+ * What the actions *create* is not decided here: both hand their parameters to
13
+ * `../automation/` (`createTicket`, `createSchedule`), the implementation every
14
+ * machine path shares. An alarm adds only what is its own — the `alarm:`
15
+ * origin, placeholders, the firing's details.
11
16
  */
12
17
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.resolveEquipment = exports.resolveAlarmUser = exports.readAlarmCall = exports.isAlarmWebhookToken = exports.fromOpenwareAlarm = exports.describeTrigger = exports.alarmWebhookToken = exports.OPENWARE_WEBHOOK_PAYLOAD = exports.OPENWARE_TEMPLATE_TYPE = exports.ALARM_WEBHOOK_TOKEN_HEADER = exports.ensureOpenwareWebhook = exports.ensureAlarmActionRow = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
18
+ exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.readAlarmCall = exports.isAlarmWebhookToken = exports.fromOpenwareAlarm = exports.describeTrigger = exports.alarmWebhookToken = exports.OPENWARE_WEBHOOK_PAYLOAD = exports.OPENWARE_TEMPLATE_TYPE = exports.ALARM_WEBHOOK_TOKEN_HEADER = exports.ensureOpenwareWebhook = exports.ensureAlarmActionRow = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
14
19
  // The shared base, here at the root because both actions read it: payload
15
20
  // shape, identity, and the two lookups every action needs.
16
21
  var alarmIdentity_js_1 = require("./alarmIdentity.js");
@@ -35,10 +40,6 @@ Object.defineProperty(exports, "fromOpenwareAlarm", { enumerable: true, get: fun
35
40
  Object.defineProperty(exports, "isAlarmWebhookToken", { enumerable: true, get: function () { return openwareAlarm_js_1.isAlarmWebhookToken; } });
36
41
  var readAlarmCall_js_1 = require("./readAlarmCall.js");
37
42
  Object.defineProperty(exports, "readAlarmCall", { enumerable: true, get: function () { return readAlarmCall_js_1.readAlarmCall; } });
38
- var resolveAlarmUser_js_1 = require("./resolveAlarmUser.js");
39
- Object.defineProperty(exports, "resolveAlarmUser", { enumerable: true, get: function () { return resolveAlarmUser_js_1.resolveAlarmUser; } });
40
- var resolveEquipment_js_1 = require("./resolveEquipment.js");
41
- Object.defineProperty(exports, "resolveEquipment", { enumerable: true, get: function () { return resolveEquipment_js_1.resolveEquipment; } });
42
43
  var tenantForSecret_js_1 = require("./tenantForSecret.js");
43
44
  Object.defineProperty(exports, "tenantForSecret", { enumerable: true, get: function () { return tenantForSecret_js_1.tenantForSecret; } });
44
45
  // `ticket/` — "raise a ticket", an alarm that reports a finding.
@@ -67,8 +67,10 @@ export interface AlarmScheduleParams {
67
67
  *
68
68
  * A plan has no description field, so the context of the firing would
69
69
  * otherwise be lost between the title and the `origin` marker. Structured
70
- * rather than prose because the trigger overview reads it back — and mirrored
71
- * in `openservice-core` (`ScheduleAlarmContext`) so the frontend has the type.
70
+ * rather than prose because the trigger overview reads it back. The frontend
71
+ * reads the shape from `@opendash/openservice-shared` (`ScheduleAlarmContext`,
72
+ * with `alarmOrigin` / `isAlarmOrigin`); this copy has to match it until the
73
+ * server depends on a release of that package which contains it.
72
74
  */
73
75
  export interface ScheduleAlarmContext {
74
76
  /** `OD3_Alarm.objectId`, when the executor reported one. */
@@ -1,4 +1,4 @@
1
- import { Tenant } from "../../../../types/index.js";
1
+ import type { Tenant } from "../../../../types/index.js";
2
2
  import type { AlarmEvent } from "../AlarmEvent.js";
3
3
  import { type AlarmScheduleParams } from "./AlarmScheduleTypes.js";
4
4
  /** Outcome of one fired alarm. */
@@ -21,11 +21,11 @@ export interface AlarmScheduleResult {
21
21
  * fill the calendar with the same job; performing the maintenance arms the
22
22
  * alarm again, which is the behaviour the ticket action already establishes.
23
23
  *
24
- * The plan is a perfectly ordinary `OD3_Service_Schedule` with a `COUNT=1`
25
- * RRULE — the spelling the frontend's `oneOffCadence()` produces and
26
- * `isOneOff()` recognises. Nothing about the calendar, the detail page, the
27
- * execution runner or the notification worker has to know an alarm was
28
- * involved; they all read a plan.
24
+ * The plan itself is created by `createSchedule` (`../../automation/`), the
25
+ * same code every other machine path uses: a `COUNT=1` RRULE, the template's
26
+ * steps and settings copied. What stays here is what is the alarm's own: the
27
+ * `alarm:` origin, the title placeholders, the lead time counted from the
28
+ * firing, and the firing's context on `asset.alarm`.
29
29
  */
30
30
  export declare function createAlarmSchedule(tenant: Tenant, event: AlarmEvent, rawParams?: AlarmScheduleParams): Promise<AlarmScheduleResult>;
31
31
  /**
@@ -6,11 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createAlarmSchedule = createAlarmSchedule;
7
7
  exports.tenantForAlarmSchedule = tenantForAlarmSchedule;
8
8
  const node_1 = __importDefault(require("parse/node"));
9
- const index_js_1 = require("../../../../types/index.js");
10
- const actionParams_js_1 = require("../actionParams.js");
9
+ const index_js_1 = require("../../automation/index.js");
11
10
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
12
- const resolveAlarmUser_js_1 = require("../resolveAlarmUser.js");
13
- const resolveEquipment_js_1 = require("../resolveEquipment.js");
14
11
  const tenantForSecret_js_1 = require("../tenantForSecret.js");
15
12
  const alarmScheduleFields_js_1 = require("./alarmScheduleFields.js");
16
13
  const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
@@ -23,11 +20,11 @@ const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
23
20
  * fill the calendar with the same job; performing the maintenance arms the
24
21
  * alarm again, which is the behaviour the ticket action already establishes.
25
22
  *
26
- * The plan is a perfectly ordinary `OD3_Service_Schedule` with a `COUNT=1`
27
- * RRULE — the spelling the frontend's `oneOffCadence()` produces and
28
- * `isOneOff()` recognises. Nothing about the calendar, the detail page, the
29
- * execution runner or the notification worker has to know an alarm was
30
- * involved; they all read a plan.
23
+ * The plan itself is created by `createSchedule` (`../../automation/`), the
24
+ * same code every other machine path uses: a `COUNT=1` RRULE, the template's
25
+ * steps and settings copied. What stays here is what is the alarm's own: the
26
+ * `alarm:` origin, the title placeholders, the lead time counted from the
27
+ * firing, and the firing's context on `asset.alarm`.
31
28
  */
32
29
  async function createAlarmSchedule(tenant, event, rawParams = {}) {
33
30
  if (!(0, alarmIdentity_js_1.alarmKey)(event)) {
@@ -35,141 +32,41 @@ async function createAlarmSchedule(tenant, event, rawParams = {}) {
35
32
  }
36
33
  // Normalised once, at the door, rather than at each use. The reference
37
34
  // fields arrive as whole objects from alarms configured before the action
38
- // form set a `valueField` (see `actionParams.ts`), and an executor is free to
39
- // send a pointer too — every reader downstream wants a plain id.
35
+ // form set a `valueField` (see `automation/params.ts`), and an executor is
36
+ // free to send a pointer too — every reader downstream wants a plain id.
40
37
  const params = normalizeParams(rawParams);
41
- const template = await resolveTemplate(tenant, params.templateId);
42
- const fields = (0, alarmScheduleFields_js_1.alarmScheduleFields)(event, params, template?.get("title"));
43
- if (!params.duplicate) {
44
- const open = await findOpenSchedule(tenant, fields.origin);
45
- if (open) {
46
- return {
47
- scheduleId: open.id,
48
- created: false,
49
- origin: fields.origin,
50
- due: dueOf(open) ?? fields.due.toISOString(),
51
- equipmentId: open.get("equipment")?.id,
52
- templateId: params.templateId,
53
- };
54
- }
55
- }
56
- const equipment = await (0, resolveEquipment_js_1.resolveEquipment)(tenant, event, params.equipmentId, `[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}]`);
57
- const schedule = new index_js_1.Service_Schedule();
58
- schedule.set("tenant", tenant);
59
- schedule.set("active", true);
60
- schedule.set("title", fields.title);
61
- schedule.set("origin", fields.origin);
62
- schedule.set("cadence", oneOffCadence(fields.due));
63
- schedule.set("steps", template?.get("steps") ?? []);
64
- schedule.set("asset", { alarm: fields.alarmContext });
65
- // Settings a template carries over. Copied, not referenced: applying a
66
- // template is a snapshot everywhere else in this domain, and a later template
67
- // edit must not rewrite an appointment somebody has already been sent to.
68
- if (template?.get("notifications")) {
69
- schedule.set("notifications", template.get("notifications"));
70
- }
71
- if (template?.get("serviceProviders")) {
72
- schedule.set("serviceProviders", template.get("serviceProviders"));
73
- }
74
- if (equipment)
75
- schedule.set("equipment", equipment);
76
- if (params.color)
77
- schedule.set("color", params.color);
38
+ const fields = (0, alarmScheduleFields_js_1.alarmScheduleFields)(event, params);
39
+ const logPrefix = `[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}]`;
78
40
  // Who the plan belongs to. Without it `syncAssignmentAcl` grants nobody but
79
41
  // administrators, so the person who configured the alarm would not see what
80
42
  // it produced.
81
- const owner = await (0, resolveAlarmUser_js_1.resolveAlarmUser)(tenant, event.userId, `[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}]`);
82
- if (owner)
83
- schedule.set("user", owner);
84
- await schedule.save(null, { useMasterKey: true });
85
- // Role assignments are a Parse Relation and can only be written once the
86
- // object exists. The ACL is rebuilt from them in `afterSave`, so this second
87
- // save is what actually makes the plan visible to the template's roles.
88
- const roles = await templateRoles(template);
89
- if (roles.length > 0) {
90
- schedule.relation("assignedRoles").add(roles);
91
- await schedule.save(null, { useMasterKey: true });
92
- }
93
- return {
94
- scheduleId: schedule.id,
95
- created: true,
43
+ const owner = await (0, index_js_1.resolveTenantUser)(tenant, event.userId, logPrefix);
44
+ const result = await (0, index_js_1.createSchedule)(tenant, {
45
+ templateId: params.templateId,
46
+ equipmentId: params.equipmentId,
47
+ sourceTags: [event.item_id, event.item_source],
48
+ due: fields.due,
49
+ color: params.color,
96
50
  origin: fields.origin,
97
- due: fields.due.toISOString(),
98
- equipmentId: equipment?.id,
99
- templateId: template?.id,
100
- };
101
- }
102
- /**
103
- * A `COUNT=1` RRULE at `due` — one appointment, no recurrence.
104
- *
105
- * Must stay identical to the frontend's `oneOffCadence()`
106
- * (`plugins/openservice-schedule/src/features/schedules/utils/cadence.ts`):
107
- * `isOneOff()` decides by parsing the string, and a plan the editor does not
108
- * recognise as one-off would be offered a recurrence editor it has no rule for.
109
- */
110
- function oneOffCadence(due) {
51
+ unique: !params.duplicate,
52
+ // A plan has no room for the firing in its title — the "triggered by"
53
+ // card of the detail page reads it from here.
54
+ asset: { alarm: fields.alarmContext },
55
+ }, {
56
+ auth: { useMasterKey: true },
57
+ actor: owner,
58
+ logPrefix,
59
+ titleFor: (templateTitle) => (0, alarmScheduleFields_js_1.alarmScheduleFields)(event, params, templateTitle).title,
60
+ });
111
61
  return {
112
- kind: "rrule",
113
- rrule: "FREQ=DAILY;COUNT=1",
114
- dtstart: due.toISOString(),
62
+ scheduleId: result.scheduleId,
63
+ created: result.created,
64
+ origin: fields.origin,
65
+ due: result.due ?? fields.due.toISOString(),
66
+ equipmentId: result.equipmentId,
67
+ templateId: result.templateId,
115
68
  };
116
69
  }
117
- /**
118
- * An appointment of this alarm that nobody has performed yet, if there is one.
119
- *
120
- * "Unperformed" means no execution has been **completed** against it. A running
121
- * execution counts as unperformed on purpose: the technician is standing at the
122
- * machine, and a second appointment landing in the calendar mid-job helps
123
- * nobody.
124
- */
125
- async function findOpenSchedule(tenant, origin) {
126
- const schedules = await new node_1.default.Query(index_js_1.Service_Schedule)
127
- .equalTo("tenant", tenant)
128
- .equalTo("origin", origin)
129
- .doesNotExist("deletedAt")
130
- .descending("createdAt")
131
- .limit(20)
132
- .find({ useMasterKey: true });
133
- for (const schedule of schedules) {
134
- const performed = await new node_1.default.Query(index_js_1.Service_Schedule_Execution)
135
- .equalTo("schedule", schedule)
136
- .exists("completedAt")
137
- .count({ useMasterKey: true });
138
- if (performed === 0)
139
- return schedule;
140
- }
141
- return undefined;
142
- }
143
- /** The template's steps and defaults — only within the calling tenant. */
144
- async function resolveTemplate(tenant, templateId) {
145
- if (!templateId)
146
- return undefined;
147
- const template = await new node_1.default.Query(index_js_1.Service_Schedule_Template)
148
- .equalTo("objectId", templateId)
149
- .equalTo("tenant", tenant)
150
- .doesNotExist("deletedAt")
151
- .first({ useMasterKey: true });
152
- if (!template) {
153
- // Not fatal: an appointment with no steps is still a dated entry somebody
154
- // can act on, and refusing the alarm would lose the firing entirely.
155
- console.warn(`[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}] Template ${templateId} not found for this tenant — creating the plan without steps`);
156
- }
157
- return template ?? undefined;
158
- }
159
- /** Roles the template assigns, so the new plan is visible to the same people. */
160
- async function templateRoles(template) {
161
- if (!template)
162
- return [];
163
- return template
164
- .relation("assignedRoles")
165
- .query()
166
- .find({ useMasterKey: true });
167
- }
168
- /** The appointment date of an existing one-off, read back from its cadence. */
169
- function dueOf(schedule) {
170
- const cadence = schedule.get("cadence");
171
- return cadence?.dtstart;
172
- }
173
70
  /**
174
71
  * The tenant a call belongs to, identified by its shared secret.
175
72
  *
@@ -190,8 +87,8 @@ async function tenantForAlarmSchedule(secret) {
190
87
  function normalizeParams(params) {
191
88
  return {
192
89
  ...params,
193
- templateId: (0, actionParams_js_1.paramId)(params.templateId),
194
- equipmentId: (0, actionParams_js_1.paramId)(params.equipmentId),
195
- dueInDays: (0, actionParams_js_1.paramNumber)(params.dueInDays),
90
+ templateId: (0, index_js_1.paramId)(params.templateId),
91
+ equipmentId: (0, index_js_1.paramId)(params.equipmentId),
92
+ dueInDays: (0, index_js_1.paramNumber)(params.dueInDays),
196
93
  };
197
94
  }
@@ -39,7 +39,7 @@ const FORM_FIELDS = [
39
39
  displayField: "title",
40
40
  mode: "single",
41
41
  // Without this the picker stores the whole selected object instead of
42
- // its id — see actionParams.ts.
42
+ // its id — see automation/params.ts.
43
43
  valueField: "objectId",
44
44
  },
45
45
  hint: "Arbeitsschritte und Einstellungen werden beim Auslösen kopiert. Ohne Vorlage entsteht ein Termin ohne Schritte.",
@@ -53,7 +53,7 @@ const FORM_FIELDS = [
53
53
  displayField: "label",
54
54
  mode: "single",
55
55
  // Without this the picker stores the whole selected object instead of
56
- // its id — see actionParams.ts.
56
+ // its id — see automation/params.ts.
57
57
  valueField: "objectId",
58
58
  },
59
59
  hint: "Ohne Angabe wird über die Quellen-Tags der Maschine geraten — oder der Plan bleibt ohne Maschine.",
@@ -1,4 +1,4 @@
1
- import { Tenant } from "../../../../types/index.js";
1
+ import type { Tenant } from "../../../../types/index.js";
2
2
  import type { AlarmEvent } from "../AlarmEvent.js";
3
3
  import { type AlarmTicketParams } from "./AlarmTicketTypes.js";
4
4
  /** Outcome of one fired alarm. */
@@ -19,10 +19,13 @@ export interface AlarmTicketResult {
19
19
  * the ticket arms the alarm again, which is the behaviour people expect from
20
20
  * every other alerting tool.
21
21
  *
22
- * Deliberately thin: number, ACL, assignment notifications and the tenant's
23
- * watcher rules all happen in the `Service_Ticket` hooks, on every write path.
22
+ * The ticket itself is created by `createTicket` (`../../automation/`), the
23
+ * same code every other machine path uses. What stays here is what is the
24
+ * alarm's own: the `alarm:` origin, the placeholders in the title, the details
25
+ * appended to the description, the firing time as start, and the sensor as a
26
+ * hint for the machine.
24
27
  */
25
- export declare function createAlarmTicket(tenant: Tenant, event: AlarmEvent, rawParams?: AlarmTicketParams): Promise<AlarmTicketResult>;
28
+ export declare function createAlarmTicket(tenant: Tenant, event: AlarmEvent, params?: AlarmTicketParams): Promise<AlarmTicketResult>;
26
29
  /**
27
30
  * The tenant a call belongs to, identified by its shared secret.
28
31
  *
@@ -6,16 +6,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createAlarmTicket = createAlarmTicket;
7
7
  exports.tenantForAlarmTicket = tenantForAlarmTicket;
8
8
  const node_1 = __importDefault(require("parse/node"));
9
- const openservice_shared_1 = require("@opendash/openservice-shared");
10
- const index_js_1 = require("../../../../types/index.js");
11
- const ticketFormConfig_js_1 = require("../../tickets/ticketFormConfig.js");
12
- const actionParams_js_1 = require("../actionParams.js");
9
+ const index_js_1 = require("../../automation/index.js");
13
10
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
14
- const resolveAlarmUser_js_1 = require("../resolveAlarmUser.js");
15
- const resolveEquipment_js_1 = require("../resolveEquipment.js");
16
11
  const tenantForSecret_js_1 = require("../tenantForSecret.js");
17
12
  const alarmTicketFields_js_1 = require("./alarmTicketFields.js");
18
- const alarmTicketDefaults_js_1 = require("./alarmTicketDefaults.js");
19
13
  const AlarmTicketTypes_js_1 = require("./AlarmTicketTypes.js");
20
14
  /**
21
15
  * Create the ticket a fired alarm asks for — or return the one that is already
@@ -27,170 +21,57 @@ const AlarmTicketTypes_js_1 = require("./AlarmTicketTypes.js");
27
21
  * the ticket arms the alarm again, which is the behaviour people expect from
28
22
  * every other alerting tool.
29
23
  *
30
- * Deliberately thin: number, ACL, assignment notifications and the tenant's
31
- * watcher rules all happen in the `Service_Ticket` hooks, on every write path.
24
+ * The ticket itself is created by `createTicket` (`../../automation/`), the
25
+ * same code every other machine path uses. What stays here is what is the
26
+ * alarm's own: the `alarm:` origin, the placeholders in the title, the details
27
+ * appended to the description, the firing time as start, and the sensor as a
28
+ * hint for the machine.
32
29
  */
33
- async function createAlarmTicket(tenant, event, rawParams = {}) {
30
+ async function createAlarmTicket(tenant, event, params = {}) {
34
31
  if (!(0, alarmIdentity_js_1.alarmKey)(event)) {
35
32
  throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, "The alarm payload identifies no alarm: pass alarmId, or item_source/item_id.");
36
33
  }
37
- // The ticket is created through a form config, as in the frontend. Per
38
- // field the alarm's template wins (the ticket form in template mode), then
39
- // the flat fields of the generic action form, then the config's defaults.
40
- // Same normalisation as the schedule action for the flat ones: references
41
- // can arrive as whole objects from alarms configured before the form set a
42
- // `valueField` (see `actionParams.ts`).
43
- const config = await alarmFormConfig(tenant, (0, actionParams_js_1.paramId)(rawParams.formConfigId));
44
- const template = (0, alarmTicketDefaults_js_1.readTicketDefaults)(rawParams.ticket);
45
- const defaults = (0, alarmTicketDefaults_js_1.formConfigDefaults)(config?.fields);
46
- const params = {
47
- ...rawParams,
48
- title: template.title ?? (0, actionParams_js_1.paramString)(rawParams.title) ?? defaults.title,
49
- description: template.description ??
50
- (0, actionParams_js_1.paramString)(rawParams.description) ??
51
- defaults.description,
52
- equipmentId: template.equipment ??
53
- (0, actionParams_js_1.paramId)(rawParams.equipmentId) ??
54
- defaults.equipment,
55
- projectId: template.project ?? (0, actionParams_js_1.paramId)(rawParams.projectId) ?? defaults.project,
56
- };
57
- const fields = (0, alarmTicketFields_js_1.alarmTicketFields)(event, params);
58
- if (!params.duplicate) {
59
- const open = await findOpenTicket(tenant, fields.origin);
60
- if (open) {
61
- return {
62
- ticketId: open.id,
63
- created: false,
64
- origin: fields.origin,
65
- equipmentId: open.get("equipment")?.id,
66
- };
67
- }
68
- }
69
- const status = (await presetStatus(tenant, template.status ?? defaults.status)) ??
70
- (await resolveDefaultStatus(tenant));
71
- if (!status) {
72
- throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `No "${openservice_shared_1.DEFAULT_STATUS_CATEGORY}" status configured for this tenant — cannot create a ticket.`);
73
- }
74
- const equipment = await (0, resolveEquipment_js_1.resolveEquipment)(tenant, event, params.equipmentId, `[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}]`);
75
- const ticket = new index_js_1.Service_Ticket();
76
- ticket.set("deleted", false);
77
- ticket.set("tenant", tenant);
78
- ticket.set("status", status);
79
- ticket.set("title", fields.title);
80
- ticket.set("description", fields.description);
81
- ticket.set("origin", fields.origin);
82
- // The moment the alarm fired, not the moment we got the call — a queued or
83
- // retried webhook must not move the incident.
84
- ticket.set("startDate", (0, alarmIdentity_js_1.firedAt)(event));
85
- if (equipment)
86
- ticket.set("equipment", equipment);
34
+ const logPrefix = `[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}]`;
87
35
  // The alarm's owner is the ticket's creator: it shows up as such, and the
88
36
  // ACL gives them write access to what their alarm raised.
89
- const creator = await (0, resolveAlarmUser_js_1.resolveAlarmUser)(tenant, event.userId, `[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}]`);
90
- if (creator)
91
- ticket.set("createdBy", creator);
92
- // The config's remaining defaults first: the flat fields below and the
93
- // template after them override them.
94
- for (const [key, value] of Object.entries(defaults.values)) {
95
- ticket.set(key, value);
96
- }
97
- if (params.priority != null)
98
- ticket.set("priority", params.priority);
99
- if (params.projectId) {
100
- const project = new index_js_1.Service_Project();
101
- project.id = params.projectId;
102
- ticket.set("project", project);
103
- }
104
- // Assignment arrays hold plain ids in this schema (see `refIds` in
105
- // `@opendash/openservice-shared`, which reads both).
106
- if (params.assignedUserIds?.length) {
107
- ticket.set("assignedUsers", params.assignedUserIds);
108
- }
109
- if (params.assignedRoleIds?.length) {
110
- ticket.set("assignedRoles", params.assignedRoleIds);
111
- }
112
- if (params.tagIds?.length)
113
- ticket.set("tags", params.tagIds);
114
- for (const [key, value] of Object.entries(template.values)) {
115
- ticket.set(key, value);
116
- }
117
- // Naming the config makes the `Service_Ticket` hook run exactly its rules
118
- // (priority formula, value rules, action rules). The hook also rejects master
119
- // data of another tenant, as on every other way a ticket is written.
120
- await ticket.save(null, {
121
- useMasterKey: true,
122
- context: { formConfig: config?.id },
37
+ const creator = await (0, index_js_1.resolveTenantUser)(tenant, event.userId, logPrefix);
38
+ const { origin } = (0, alarmTicketFields_js_1.alarmTicketFields)(event);
39
+ const result = await (0, index_js_1.createTicket)(tenant, {
40
+ formConfigId: params.formConfigId,
41
+ ticket: params.ticket,
42
+ title: params.title,
43
+ description: params.description,
44
+ equipmentId: params.equipmentId,
45
+ projectId: params.projectId,
46
+ priority: params.priority,
47
+ assignedUserIds: params.assignedUserIds,
48
+ assignedRoleIds: params.assignedRoleIds,
49
+ tagIds: params.tagIds,
50
+ // The moment the alarm fired, not the moment we got the call — a queued
51
+ // or retried webhook must not move the incident.
52
+ startDate: (0, alarmIdentity_js_1.firedAt)(event),
53
+ sourceTags: [event.item_id, event.item_source],
54
+ origin,
55
+ unique: !params.duplicate,
56
+ }, {
57
+ auth: { useMasterKey: true },
58
+ actor: creator,
59
+ logPrefix,
60
+ // Placeholders and alarm details on top of whatever title and note the
61
+ // template, the action form or the form config supplied.
62
+ finalizeText: (merged) => (0, alarmTicketFields_js_1.alarmTicketFields)(event, {
63
+ ...params,
64
+ title: merged.title,
65
+ description: merged.description,
66
+ }),
123
67
  });
124
68
  return {
125
- ticketId: ticket.id,
126
- created: true,
127
- origin: fields.origin,
128
- equipmentId: equipment?.id,
69
+ ticketId: result.ticketId,
70
+ created: result.created,
71
+ origin,
72
+ equipmentId: result.equipmentId,
129
73
  };
130
74
  }
131
- /**
132
- * An unfinished ticket of this alarm, if there is one.
133
- *
134
- * "Unfinished" is decided by the **status category**, not by `closedAt`: a
135
- * tenant can name its statuses whatever it likes, the category is the contract
136
- * (`done` / `cancelled` — the same list core uses).
137
- */
138
- async function findOpenTicket(tenant, origin) {
139
- const tickets = await new node_1.default.Query(index_js_1.Service_Ticket)
140
- .equalTo("tenant", tenant)
141
- .equalTo("origin", origin)
142
- .equalTo("deleted", false)
143
- .include("status")
144
- .descending("createdAt")
145
- .limit(20)
146
- .find({ useMasterKey: true });
147
- return tickets.find((ticket) => {
148
- const category = ticket.get("status")?.get("category");
149
- return !(0, openservice_shared_1.isDoneCategory)(category);
150
- });
151
- }
152
- /**
153
- * The form config the alarm names, if it is the tenant's — else the tenant's
154
- * default form, the one a save without a user gets (`applicableFormConfig`).
155
- */
156
- async function alarmFormConfig(tenant, id) {
157
- const chosen = await (0, ticketFormConfig_js_1.configFromContext)(id, tenant, {
158
- master: true,
159
- sessionToken: undefined,
160
- });
161
- if (id && !chosen) {
162
- console.warn(`[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}] Form config ${id} is not this tenant's — using the tenant's default form`);
163
- }
164
- return chosen ?? (await (0, ticketFormConfig_js_1.applicableFormConfig)(tenant, undefined));
165
- }
166
- /**
167
- * The status the template or the form config names, if it is the tenant's or
168
- * a global one.
169
- */
170
- async function presetStatus(tenant, statusId) {
171
- if (!statusId)
172
- return undefined;
173
- const status = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Service_Status).equalTo("tenant", tenant), new node_1.default.Query(index_js_1.Service_Status).doesNotExist("tenant"))
174
- .equalTo("objectId", statusId)
175
- .equalTo("deleted", false)
176
- .first({ useMasterKey: true });
177
- if (!status) {
178
- console.warn(`[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}] Preset status ${statusId} is not available — using the inbox`);
179
- }
180
- return status;
181
- }
182
- /** The tenant's inbox status, else a global one — never another tenant's. */
183
- async function resolveDefaultStatus(tenant) {
184
- // Only this tenant's and the global ones: across all tenants a plain `find`
185
- // stopped at the default limit (100) and could miss the tenant's own inbox.
186
- const statuses = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Service_Status).equalTo("tenant", tenant), new node_1.default.Query(index_js_1.Service_Status).doesNotExist("tenant"))
187
- .equalTo("category", openservice_shared_1.DEFAULT_STATUS_CATEGORY)
188
- .equalTo("deleted", false)
189
- .ascending("order")
190
- .limit(1000)
191
- .find({ useMasterKey: true });
192
- return (statuses.find((status) => status.get("tenant")?.id === tenant.id) ?? statuses.find((status) => !status.get("tenant")));
193
- }
194
75
  /**
195
76
  * The tenant a call belongs to, identified by its shared secret.
196
77
  *
@@ -45,7 +45,7 @@ const FORM_FIELDS = [
45
45
  displayField: "label",
46
46
  mode: "single",
47
47
  // Without this the picker stores the whole selected object instead of
48
- // its id — see actionParams.ts.
48
+ // its id — see automation/params.ts.
49
49
  valueField: "objectId",
50
50
  },
51
51
  hint: "Das Ticket entsteht wie über dieses Formular: mit seinen Standardwerten und Regeln. Leer = Standardformular.",
@@ -71,7 +71,7 @@ const FORM_FIELDS = [
71
71
  displayField: "label",
72
72
  mode: "single",
73
73
  // Without this the picker stores the whole selected object instead of
74
- // its id — see actionParams.ts.
74
+ // its id — see automation/params.ts.
75
75
  valueField: "objectId",
76
76
  },
77
77
  hint: "Ohne Angabe die Maschine aus dem Formular, sonst wird über die Quellen-Tags der Maschine geraten.",