@openinc/parse-server-opendash 4.3.2 → 4.4.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 (161) hide show
  1. package/dist/features/openservice/alarms/AlarmEvent.d.ts +40 -0
  2. package/dist/features/openservice/alarms/alarmIdentity.d.ts +39 -0
  3. package/dist/features/openservice/{serviceTickets/alarmActions/functions/alarmTicketFields.js → alarms/alarmIdentity.js} +55 -57
  4. package/dist/features/openservice/alarms/index.d.ts +30 -0
  5. package/dist/features/openservice/alarms/index.js +52 -0
  6. package/dist/features/openservice/alarms/resolveEquipment.d.ts +17 -0
  7. package/dist/features/openservice/alarms/resolveEquipment.js +42 -0
  8. package/dist/features/openservice/alarms/schedule/AlarmScheduleTypes.d.ts +88 -0
  9. package/dist/features/openservice/alarms/schedule/AlarmScheduleTypes.js +29 -0
  10. package/dist/features/openservice/alarms/schedule/alarmScheduleFields.d.ts +27 -0
  11. package/dist/features/openservice/alarms/schedule/alarmScheduleFields.js +56 -0
  12. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.d.ts +37 -0
  13. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.js +181 -0
  14. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.d.ts +22 -0
  15. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.js +127 -0
  16. package/dist/features/openservice/alarms/schedule/listAlarmTriggers.d.ts +41 -0
  17. package/dist/features/openservice/alarms/schedule/listAlarmTriggers.js +137 -0
  18. package/dist/features/openservice/alarms/tenantForSecret.d.ts +13 -0
  19. package/dist/features/openservice/alarms/tenantForSecret.js +45 -0
  20. package/dist/features/openservice/{serviceTickets/alarmActions/types → alarms/ticket}/AlarmTicketTypes.d.ts +0 -26
  21. package/dist/features/openservice/alarms/ticket/alarmTicketFields.d.ts +18 -0
  22. package/dist/features/openservice/alarms/ticket/alarmTicketFields.js +37 -0
  23. package/dist/features/openservice/{serviceTickets/alarmActions/service → alarms/ticket}/createAlarmTicket.d.ts +7 -7
  24. package/dist/features/openservice/{serviceTickets/alarmActions/service → alarms/ticket}/createAlarmTicket.js +15 -69
  25. package/dist/features/openservice/{serviceTickets/alarmActions/service → alarms/ticket}/ensureAlarmTicketAction.js +2 -2
  26. package/dist/features/openservice/functions/assignUsersAndRoles.d.ts +5 -0
  27. package/dist/features/openservice/functions/assignUsersAndRoles.js +5 -0
  28. package/dist/features/openservice/functions/getSourceMetaMap.d.ts +4 -0
  29. package/dist/features/openservice/functions/getSourceMetaMap.js +4 -0
  30. package/dist/features/openservice/functions/getTicketObject.d.ts +5 -0
  31. package/dist/features/openservice/functions/getTicketObject.js +5 -0
  32. package/dist/features/openservice/functions/saveDescription.d.ts +5 -0
  33. package/dist/features/openservice/functions/saveDescription.js +5 -0
  34. package/dist/features/openservice/functions/saveDowntime.d.ts +5 -0
  35. package/dist/features/openservice/functions/saveDowntime.js +5 -0
  36. package/dist/features/openservice/functions/saveDuedate.d.ts +5 -0
  37. package/dist/features/openservice/functions/saveDuedate.js +5 -0
  38. package/dist/features/openservice/functions/saveFrequency.d.ts +5 -0
  39. package/dist/features/openservice/functions/saveFrequency.js +5 -0
  40. package/dist/features/openservice/functions/saveIssuecategory.d.ts +10 -0
  41. package/dist/features/openservice/functions/saveIssuecategory.js +10 -0
  42. package/dist/features/openservice/functions/saveMaterial.d.ts +5 -0
  43. package/dist/features/openservice/functions/saveMaterial.js +5 -0
  44. package/dist/features/openservice/functions/saveMessage.d.ts +5 -0
  45. package/dist/features/openservice/functions/saveMessage.js +5 -0
  46. package/dist/features/openservice/functions/savePriority.d.ts +5 -0
  47. package/dist/features/openservice/functions/savePriority.js +5 -0
  48. package/dist/features/openservice/functions/saveProject.d.ts +5 -0
  49. package/dist/features/openservice/functions/saveProject.js +5 -0
  50. package/dist/features/openservice/functions/saveRestriction.d.ts +5 -0
  51. package/dist/features/openservice/functions/saveRestriction.js +5 -0
  52. package/dist/features/openservice/functions/saveSource.d.ts +5 -0
  53. package/dist/features/openservice/functions/saveSource.js +5 -0
  54. package/dist/features/openservice/functions/saveState.d.ts +10 -0
  55. package/dist/features/openservice/functions/saveState.js +10 -0
  56. package/dist/features/openservice/functions/saveTicketMeta.d.ts +5 -0
  57. package/dist/features/openservice/functions/saveTicketMeta.js +5 -0
  58. package/dist/features/openservice/functions/saveTicketTitle.d.ts +5 -0
  59. package/dist/features/openservice/functions/saveTicketTitle.js +5 -0
  60. package/dist/features/openservice/index.d.ts +15 -0
  61. package/dist/features/openservice/index.js +15 -0
  62. package/dist/features/openservice/init.d.ts +9 -0
  63. package/dist/features/openservice/init.js +15 -3
  64. package/dist/features/openservice/issuecategory/initIssuecategory.d.ts +4 -0
  65. package/dist/features/openservice/issuecategory/initIssuecategory.js +4 -0
  66. package/dist/features/openservice/kanbanState/initKanbanStates.d.ts +10 -0
  67. package/dist/features/openservice/kanbanState/initKanbanStates.js +10 -0
  68. package/dist/features/openservice/messages/initMessages.d.ts +3 -0
  69. package/dist/features/openservice/messages/initMessages.js +3 -0
  70. package/dist/features/openservice/messages/removeLatestMessage.d.ts +2 -0
  71. package/dist/features/openservice/messages/removeLatestMessage.js +2 -0
  72. package/dist/features/openservice/schedules/calendarSync/Access.d.ts +12 -0
  73. package/dist/features/openservice/schedules/calendarSync/{service/CalendarManager.d.ts → CalendarManager.d.ts} +7 -2
  74. package/dist/features/openservice/schedules/calendarSync/{service/CalendarManager.js → CalendarManager.js} +6 -1
  75. package/dist/features/openservice/schedules/calendarSync/{service/CalendarSyncPoller.d.ts → CalendarSyncPoller.d.ts} +6 -1
  76. package/dist/features/openservice/schedules/calendarSync/{service/CalendarSyncPoller.js → CalendarSyncPoller.js} +7 -2
  77. package/dist/features/openservice/schedules/calendarSync/ConfigValues.d.ts +13 -0
  78. package/dist/features/openservice/schedules/calendarSync/{types/Event.d.ts → Event.d.ts} +7 -0
  79. package/dist/features/openservice/schedules/calendarSync/Event.js +9 -0
  80. package/dist/features/openservice/schedules/calendarSync/calendarMetaHelper.d.ts +76 -0
  81. package/dist/features/openservice/schedules/calendarSync/{service/calendarMetaHelper.js → calendarMetaHelper.js} +31 -1
  82. package/dist/features/openservice/schedules/calendarSync/eventToSchedule.d.ts +37 -0
  83. package/dist/features/openservice/schedules/calendarSync/{functions/eventToSchedule.js → eventToSchedule.js} +5 -0
  84. package/dist/features/openservice/schedules/calendarSync/scheduleToEvent.d.ts +9 -0
  85. package/dist/features/openservice/schedules/calendarSync/{functions/scheduleToEvent.js → scheduleToEvent.js} +5 -0
  86. package/dist/features/openservice/schedules/{mappings/checkStatus.d.ts → checkStatus.d.ts} +3 -0
  87. package/dist/features/openservice/schedules/{mappings/checkStatus.js → checkStatus.js} +4 -1
  88. package/dist/features/openservice/schedules/getScheduleLink.d.ts +3 -0
  89. package/dist/features/openservice/schedules/getScheduleLink.js +3 -0
  90. package/dist/features/openservice/schedules/initSchedulesFeature.d.ts +4 -0
  91. package/dist/features/openservice/schedules/initSchedulesFeature.js +5 -1
  92. package/dist/features/openservice/schedules/reassignScheduleExecutions.d.ts +5 -0
  93. package/dist/features/openservice/schedules/{mappings/reassignScheduleExecutions.js → reassignScheduleExecutions.js} +5 -1
  94. package/dist/features/openservice/serviceSchedules/calendarSync/{service/ServiceCalendarSyncPoller.d.ts → ServiceCalendarSyncPoller.d.ts} +26 -1
  95. package/dist/features/openservice/serviceSchedules/calendarSync/{service/ServiceCalendarSyncPoller.js → ServiceCalendarSyncPoller.js} +94 -20
  96. package/dist/features/openservice/serviceSchedules/calendarSync/{functions/eventToPlan.d.ts → eventToPlan.d.ts} +2 -2
  97. package/dist/features/openservice/serviceSchedules/calendarSync/index.d.ts +8 -8
  98. package/dist/features/openservice/serviceSchedules/calendarSync/index.js +7 -7
  99. package/dist/features/openservice/serviceSchedules/calendarSync/{functions/outlookRecurrence.d.ts → outlookRecurrence.d.ts} +2 -2
  100. package/dist/features/openservice/serviceSchedules/calendarSync/{functions/planToEvent.d.ts → planToEvent.d.ts} +3 -3
  101. package/dist/features/openservice/serviceSchedules/calendarSync/{service/serviceCalendarMeta.d.ts → serviceCalendarMeta.d.ts} +3 -3
  102. package/dist/features/openservice/serviceSchedules/calendarSync/{service/serviceCalendarMeta.js → serviceCalendarMeta.js} +1 -1
  103. package/dist/features/openservice/serviceSchedules/calendarSync/{service/syncPlanToCalendar.d.ts → syncPlanToCalendar.d.ts} +3 -3
  104. package/dist/features/openservice/serviceSchedules/calendarSync/{service/syncPlanToCalendar.js → syncPlanToCalendar.js} +5 -5
  105. package/dist/features/openservice/serviceSchedules/initServiceSchedulesFeature.js +2 -2
  106. package/dist/features/openservice/ticket/getTicketLink.d.ts +2 -0
  107. package/dist/features/openservice/ticket/getTicketLink.js +2 -0
  108. package/dist/features/openservice/ticket/initTicket.d.ts +2 -0
  109. package/dist/features/openservice/ticket/initTicket.js +2 -0
  110. package/dist/features/openservice/types/Material.d.ts +4 -0
  111. package/dist/features/openservice/types/MessageData.d.ts +8 -0
  112. package/dist/features/openservice/types/OpenserviceTranslationKeys.d.ts +4 -0
  113. package/dist/features/openservice/types/OpenserviceTranslationKeys.js +4 -0
  114. package/dist/features/openservice/types/SaveValues.d.ts +4 -0
  115. package/dist/features/openservice/types/ScheduleTypes.d.ts +24 -0
  116. package/dist/features/openservice/types/TicketData.d.ts +4 -0
  117. package/dist/features/openservice/types/TicketMeta.d.ts +28 -0
  118. package/dist/features/openservice/types/TicketMeta.js +4 -0
  119. package/dist/functions/openinc-openservice-alarm-create-schedule.d.ts +25 -0
  120. package/dist/functions/openinc-openservice-alarm-create-schedule.js +63 -0
  121. package/dist/functions/openinc-openservice-alarm-create-ticket.js +2 -2
  122. package/dist/functions/openinc-openservice-alarm-triggers.d.ts +13 -0
  123. package/dist/functions/openinc-openservice-alarm-triggers.js +29 -0
  124. package/dist/functions/openinc-openservice-get-sourcemeta-map.js +8 -0
  125. package/dist/functions/openinc-openservice-provider-access.d.ts +1 -0
  126. package/dist/functions/openinc-openservice-provider-access.js +79 -0
  127. package/dist/functions/openinc-openservice-save-ticket-data.js +11 -0
  128. package/dist/functions/openinc-openservice-ticket-data.js +9 -0
  129. package/dist/hooks/Maintenance_Schedule.js +3 -3
  130. package/dist/hooks/Service_Schedule.js +11 -11
  131. package/dist/hooks/Service_Schedule_Template.js +6 -6
  132. package/dist/types/Contact.d.ts +3 -0
  133. package/dist/types/Contact.js +6 -0
  134. package/dist/types/Service_Schedule.d.ts +3 -0
  135. package/dist/types/Service_Schedule.js +6 -0
  136. package/package.json +1 -1
  137. package/schema/Contact.json +5 -0
  138. package/schema/Service_Schedule.json +4 -0
  139. package/dist/features/openservice/schedules/calendarSync/functions/eventToSchedule.d.ts +0 -17
  140. package/dist/features/openservice/schedules/calendarSync/functions/scheduleToEvent.d.ts +0 -4
  141. package/dist/features/openservice/schedules/calendarSync/service/calendarMetaHelper.d.ts +0 -36
  142. package/dist/features/openservice/schedules/calendarSync/types/Access.d.ts +0 -9
  143. package/dist/features/openservice/schedules/calendarSync/types/ConfigValues.d.ts +0 -8
  144. package/dist/features/openservice/schedules/mappings/reassignScheduleExecutions.d.ts +0 -1
  145. package/dist/features/openservice/serviceSchedules/acl/index.d.ts +0 -1
  146. package/dist/features/openservice/serviceSchedules/acl/index.js +0 -6
  147. package/dist/features/openservice/serviceTickets/alarmActions/functions/alarmTicketFields.d.ts +0 -35
  148. package/dist/features/openservice/serviceTickets/alarmActions/index.d.ts +0 -7
  149. package/dist/features/openservice/serviceTickets/alarmActions/index.js +0 -16
  150. /package/dist/features/openservice/{schedules/calendarSync/types/Access.js → alarms/AlarmEvent.js} +0 -0
  151. /package/dist/features/openservice/{serviceTickets/alarmActions/types → alarms/ticket}/AlarmTicketTypes.js +0 -0
  152. /package/dist/features/openservice/{serviceTickets/alarmActions/service → alarms/ticket}/ensureAlarmTicketAction.d.ts +0 -0
  153. /package/dist/features/openservice/schedules/calendarSync/{types/ConfigValues.js → Access.js} +0 -0
  154. /package/dist/features/openservice/schedules/calendarSync/{types/Event.js → ConfigValues.js} +0 -0
  155. /package/dist/features/openservice/serviceSchedules/{acl/assignmentAcl.d.ts → assignmentAcl.d.ts} +0 -0
  156. /package/dist/features/openservice/serviceSchedules/{acl/assignmentAcl.js → assignmentAcl.js} +0 -0
  157. /package/dist/features/openservice/serviceSchedules/calendarSync/{types/ServiceSyncTypes.d.ts → ServiceSyncTypes.d.ts} +0 -0
  158. /package/dist/features/openservice/serviceSchedules/calendarSync/{types/ServiceSyncTypes.js → ServiceSyncTypes.js} +0 -0
  159. /package/dist/features/openservice/serviceSchedules/calendarSync/{functions/eventToPlan.js → eventToPlan.js} +0 -0
  160. /package/dist/features/openservice/serviceSchedules/calendarSync/{functions/outlookRecurrence.js → outlookRecurrence.js} +0 -0
  161. /package/dist/features/openservice/serviceSchedules/calendarSync/{functions/planToEvent.js → planToEvent.js} +0 -0
@@ -0,0 +1,181 @@
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.createAlarmSchedule = createAlarmSchedule;
7
+ exports.tenantForAlarmSchedule = tenantForAlarmSchedule;
8
+ const node_1 = __importDefault(require("parse/node"));
9
+ const index_js_1 = require("../../../../types/index.js");
10
+ const alarmIdentity_js_1 = require("../alarmIdentity.js");
11
+ const resolveEquipment_js_1 = require("../resolveEquipment.js");
12
+ const tenantForSecret_js_1 = require("../tenantForSecret.js");
13
+ const alarmScheduleFields_js_1 = require("./alarmScheduleFields.js");
14
+ const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
15
+ /**
16
+ * Create the one-off appointment a fired alarm asks for — or return the one
17
+ * that is already waiting.
18
+ *
19
+ * **One open appointment per alarm** is the default (`params.duplicate` opts
20
+ * out). A sensor that crosses its threshold every few minutes would otherwise
21
+ * fill the calendar with the same job; performing the maintenance arms the
22
+ * alarm again, which is the behaviour the ticket action already establishes.
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.
29
+ */
30
+ async function createAlarmSchedule(tenant, event, params = {}) {
31
+ if (!(0, alarmIdentity_js_1.alarmKey)(event)) {
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.");
33
+ }
34
+ const template = await resolveTemplate(tenant, params.templateId);
35
+ const fields = (0, alarmScheduleFields_js_1.alarmScheduleFields)(event, params, template?.get("title"));
36
+ if (!params.duplicate) {
37
+ const open = await findOpenSchedule(tenant, fields.origin);
38
+ if (open) {
39
+ return {
40
+ scheduleId: open.id,
41
+ created: false,
42
+ origin: fields.origin,
43
+ due: dueOf(open) ?? fields.due.toISOString(),
44
+ equipmentId: open.get("equipment")?.id,
45
+ templateId: params.templateId,
46
+ };
47
+ }
48
+ }
49
+ const equipment = await (0, resolveEquipment_js_1.resolveEquipment)(tenant, event, params.equipmentId, `[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}]`);
50
+ const schedule = new index_js_1.Service_Schedule();
51
+ schedule.set("tenant", tenant);
52
+ schedule.set("active", true);
53
+ schedule.set("title", fields.title);
54
+ schedule.set("origin", fields.origin);
55
+ schedule.set("cadence", oneOffCadence(fields.due));
56
+ schedule.set("steps", template?.get("steps") ?? []);
57
+ schedule.set("asset", { alarm: fields.alarmContext });
58
+ // Settings a template carries over. Copied, not referenced: applying a
59
+ // template is a snapshot everywhere else in this domain, and a later template
60
+ // edit must not rewrite an appointment somebody has already been sent to.
61
+ if (template?.get("notifications")) {
62
+ schedule.set("notifications", template.get("notifications"));
63
+ }
64
+ if (template?.get("serviceProviders")) {
65
+ schedule.set("serviceProviders", template.get("serviceProviders"));
66
+ }
67
+ if (equipment)
68
+ schedule.set("equipment", equipment);
69
+ if (params.color)
70
+ schedule.set("color", params.color);
71
+ // Who the plan belongs to. Without it `syncAssignmentAcl` grants nobody but
72
+ // administrators, so the person who configured the alarm would not see what
73
+ // it produced.
74
+ const owner = await resolveUser(event.userId);
75
+ if (owner)
76
+ schedule.set("user", owner);
77
+ await schedule.save(null, { useMasterKey: true });
78
+ // Role assignments are a Parse Relation and can only be written once the
79
+ // object exists. The ACL is rebuilt from them in `afterSave`, so this second
80
+ // save is what actually makes the plan visible to the template's roles.
81
+ const roles = await templateRoles(template);
82
+ if (roles.length > 0) {
83
+ schedule.relation("assignedRoles").add(roles);
84
+ await schedule.save(null, { useMasterKey: true });
85
+ }
86
+ return {
87
+ scheduleId: schedule.id,
88
+ created: true,
89
+ origin: fields.origin,
90
+ due: fields.due.toISOString(),
91
+ equipmentId: equipment?.id,
92
+ templateId: template?.id,
93
+ };
94
+ }
95
+ /**
96
+ * A `COUNT=1` RRULE at `due` — one appointment, no recurrence.
97
+ *
98
+ * Must stay identical to the frontend's `oneOffCadence()`
99
+ * (`plugins/openservice-schedule/src/features/schedules/utils/cadence.ts`):
100
+ * `isOneOff()` decides by parsing the string, and a plan the editor does not
101
+ * recognise as one-off would be offered a recurrence editor it has no rule for.
102
+ */
103
+ function oneOffCadence(due) {
104
+ return {
105
+ kind: "rrule",
106
+ rrule: "FREQ=DAILY;COUNT=1",
107
+ dtstart: due.toISOString(),
108
+ };
109
+ }
110
+ /**
111
+ * An appointment of this alarm that nobody has performed yet, if there is one.
112
+ *
113
+ * "Unperformed" means no execution has been **completed** against it. A running
114
+ * execution counts as unperformed on purpose: the technician is standing at the
115
+ * machine, and a second appointment landing in the calendar mid-job helps
116
+ * nobody.
117
+ */
118
+ async function findOpenSchedule(tenant, origin) {
119
+ const schedules = await new node_1.default.Query(index_js_1.Service_Schedule)
120
+ .equalTo("tenant", tenant)
121
+ .equalTo("origin", origin)
122
+ .doesNotExist("deletedAt")
123
+ .descending("createdAt")
124
+ .limit(20)
125
+ .find({ useMasterKey: true });
126
+ for (const schedule of schedules) {
127
+ const performed = await new node_1.default.Query(index_js_1.Service_Schedule_Execution)
128
+ .equalTo("schedule", schedule)
129
+ .exists("completedAt")
130
+ .count({ useMasterKey: true });
131
+ if (performed === 0)
132
+ return schedule;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** The template's steps and defaults — only within the calling tenant. */
137
+ async function resolveTemplate(tenant, templateId) {
138
+ if (!templateId)
139
+ return undefined;
140
+ const template = await new node_1.default.Query(index_js_1.Service_Schedule_Template)
141
+ .equalTo("objectId", templateId)
142
+ .equalTo("tenant", tenant)
143
+ .doesNotExist("deletedAt")
144
+ .first({ useMasterKey: true });
145
+ if (!template) {
146
+ // Not fatal: an appointment with no steps is still a dated entry somebody
147
+ // can act on, and refusing the alarm would lose the firing entirely.
148
+ console.warn(`[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}] Template ${templateId} not found for this tenant — creating the plan without steps`);
149
+ }
150
+ return template ?? undefined;
151
+ }
152
+ /** Roles the template assigns, so the new plan is visible to the same people. */
153
+ async function templateRoles(template) {
154
+ if (!template)
155
+ return [];
156
+ return template
157
+ .relation("assignedRoles")
158
+ .query()
159
+ .find({ useMasterKey: true });
160
+ }
161
+ async function resolveUser(userId) {
162
+ if (!userId)
163
+ return undefined;
164
+ return ((await new node_1.default.Query("_User")
165
+ .equalTo("objectId", userId)
166
+ .first({ useMasterKey: true })) ?? undefined);
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
+ /**
174
+ * The tenant a call belongs to, identified by its shared secret.
175
+ *
176
+ * Its own config key, deliberately: enabling alarm tickets must not also let
177
+ * alarms write into the maintenance plan.
178
+ */
179
+ async function tenantForAlarmSchedule(secret) {
180
+ return (0, tenantForSecret_js_1.tenantForSecret)(AlarmScheduleTypes_js_1.ALARM_SCHEDULE_SECRET_CONFIG_KEY, secret);
181
+ }
@@ -0,0 +1,22 @@
1
+ export declare function ensureAlarmScheduleWebhook(): Promise<void>;
2
+ /**
3
+ * Make "schedule a maintenance appointment" selectable in the alarm dialog.
4
+ *
5
+ * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
6
+ * monitoring adapter loads into the frontend, where the chosen row's
7
+ * `formFields` are rendered as the action's settings form (see
8
+ * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
9
+ * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
10
+ * like the ticket action and the other open.SERVICE bootstraps.
11
+ *
12
+ * The row is **global** (no tenant): the action makes sense for every tenant,
13
+ * and the tenant of a fired alarm is established by its secret, not by this row.
14
+ *
15
+ * **How it is carried out.** `type: "webhook"` means the executor runs an
16
+ * `OD3_AlarmWebhook` row, which POSTs to a URL. That row is created by hand for
17
+ * now (an admin UI can come later) and must point at
18
+ * `/parse/functions/openinc-openservice-alarm-create-schedule` with the payload
19
+ * below. The `target` here names the same path so the two are readable side by
20
+ * side, and so a webhook-less executor that reads `target` directly still works.
21
+ */
22
+ export declare function ensureAlarmScheduleAction(): Promise<void>;
@@ -0,0 +1,127 @@
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.ensureAlarmScheduleWebhook = ensureAlarmScheduleWebhook;
7
+ exports.ensureAlarmScheduleAction = ensureAlarmScheduleAction;
8
+ const node_1 = __importDefault(require("parse/node"));
9
+ const index_js_1 = require("../../../../types/index.js");
10
+ const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
11
+ async function ensureAlarmScheduleWebhook() {
12
+ }
13
+ /**
14
+ * Make "schedule a maintenance appointment" selectable in the alarm dialog.
15
+ *
16
+ * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
17
+ * monitoring adapter loads into the frontend, where the chosen row's
18
+ * `formFields` are rendered as the action's settings form (see
19
+ * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
20
+ * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
21
+ * like the ticket action and the other open.SERVICE bootstraps.
22
+ *
23
+ * The row is **global** (no tenant): the action makes sense for every tenant,
24
+ * and the tenant of a fired alarm is established by its secret, not by this row.
25
+ *
26
+ * **How it is carried out.** `type: "webhook"` means the executor runs an
27
+ * `OD3_AlarmWebhook` row, which POSTs to a URL. That row is created by hand for
28
+ * now (an admin UI can come later) and must point at
29
+ * `/parse/functions/openinc-openservice-alarm-create-schedule` with the payload
30
+ * below. The `target` here names the same path so the two are readable side by
31
+ * side, and so a webhook-less executor that reads `target` directly still works.
32
+ */
33
+ async function ensureAlarmScheduleAction() {
34
+ const existing = await new node_1.default.Query(index_js_1.AlarmAction)
35
+ .equalTo("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
36
+ .first({ useMasterKey: true });
37
+ if (existing)
38
+ return;
39
+ const action = new index_js_1.AlarmAction();
40
+ action.set("label", "Wartungstermin anlegen (open.SERVICE)");
41
+ action.set("type", "webhook");
42
+ action.set("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID);
43
+ action.set("target", "/parse/functions/openinc-openservice-alarm-create-schedule");
44
+ action.set("templateType", "json");
45
+ action.set("payload", JSON.stringify({
46
+ secret: "{{secret}}",
47
+ event: {
48
+ alarmId: "{{alarm.id}}",
49
+ name: "{{alarm.name}}",
50
+ userId: "{{alarm.user}}",
51
+ item_id: "{{item.id}}",
52
+ item_source: "{{item.source}}",
53
+ item_dimension: "{{item.dimension}}",
54
+ value: "{{value}}",
55
+ condition: "{{condition}}",
56
+ firedAt: "{{timestamp}}",
57
+ },
58
+ params: "{{action}}",
59
+ }));
60
+ // Wear is not only a number: a boolean "filter clogged" or a string state
61
+ // code is just as good a reason to schedule maintenance.
62
+ action.set("supportedTypes", [
63
+ "Number",
64
+ "String",
65
+ "Boolean",
66
+ "Geo",
67
+ "Object",
68
+ ]);
69
+ action.set("formFields", FORM_FIELDS);
70
+ await action.save(null, { useMasterKey: true });
71
+ console.log(`[AlarmSchedule] Registered alarm action "${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}"`);
72
+ }
73
+ /**
74
+ * What the person configuring an alarm gets to fill in.
75
+ *
76
+ * Field types are the ones `FormGenerator` (in `@opendash/core`) understands;
77
+ * `select.parse` renders an object picker for a Parse class. Keys match
78
+ * `AlarmScheduleParams` — the executor hands the form's values back as `params`.
79
+ *
80
+ * The **template** is the point of the whole action: picking "Filterwechsel"
81
+ * is what turns a threshold into a job somebody can actually carry out. It is
82
+ * first in the form for that reason, and everything below it is a refinement.
83
+ */
84
+ const FORM_FIELDS = [
85
+ {
86
+ key: "templateId",
87
+ label: "Wartungsvorlage",
88
+ type: "select.parse",
89
+ settings: {
90
+ className: "OD3_Service_Schedule_Template",
91
+ displayField: "title",
92
+ mode: "single",
93
+ },
94
+ hint: "Arbeitsschritte und Einstellungen werden beim Auslösen kopiert. Ohne Vorlage entsteht ein Termin ohne Schritte.",
95
+ },
96
+ {
97
+ key: "equipmentId",
98
+ label: "Maschine",
99
+ type: "select.parse",
100
+ settings: {
101
+ className: "OD3_Service_Equipment",
102
+ displayField: "label",
103
+ mode: "single",
104
+ },
105
+ hint: "Ohne Angabe wird über die Quellen-Tags der Maschine geraten — oder der Plan bleibt ohne Maschine.",
106
+ },
107
+ {
108
+ key: "dueInDays",
109
+ label: "Fällig in (Tagen)",
110
+ type: "input.number",
111
+ defaultValue: 0,
112
+ hint: "0 = sofort fällig. Vorlauf für Verschleiß, der sich ankündigt.",
113
+ },
114
+ {
115
+ key: "title",
116
+ label: "Titel des Wartungsplans",
117
+ type: "input",
118
+ hint: "Platzhalter: {{alarm}}, {{sensor}}, {{value}}. Leer = Titel der Vorlage, sonst Name des Alarms.",
119
+ },
120
+ {
121
+ key: "duplicate",
122
+ label: "Bei jedem Auslösen einen neuen Termin",
123
+ type: "switch",
124
+ defaultValue: false,
125
+ hint: "Aus (Standard): solange der Termin nicht durchgeführt ist, entsteht kein zweiter.",
126
+ },
127
+ ];
@@ -0,0 +1,41 @@
1
+ import { type _User } from "../../../../types/index.js";
2
+ /** One configured maintenance trigger, as the overview shows it. */
3
+ export interface AlarmTriggerRow {
4
+ alarmId: string;
5
+ name?: string;
6
+ /** `source/id [dimension]` — the sensor being watched. */
7
+ sensor?: string;
8
+ item_source?: string;
9
+ item_id?: string;
10
+ item_dimension?: number;
11
+ /** Username of whoever configured the alarm. */
12
+ owner?: string;
13
+ /** The template the action will apply, as configured on the alarm. */
14
+ templateId?: string;
15
+ templateTitle?: string;
16
+ equipmentId?: string;
17
+ dueInDays?: number;
18
+ /** Plans this alarm has produced so far, newest first. */
19
+ schedules: {
20
+ id: string;
21
+ title: string;
22
+ /** ISO of the appointment. */
23
+ due?: string;
24
+ /** ISO of the firing that produced it. */
25
+ firedAt?: string;
26
+ }[];
27
+ }
28
+ /**
29
+ * Every alarm in this tenant whose action creates a maintenance plan.
30
+ *
31
+ * **Why the server has to answer this.** `Alarm.beforeSave` applies
32
+ * `denyTenantUserRead`, so alarms are private to the user who configured them.
33
+ * A maintenance manager asking "what triggers maintenance in this plant" would
34
+ * otherwise see only their own — which is the one answer that is never useful.
35
+ * The query therefore runs with the master key and is scoped to the caller's
36
+ * tenant by the server, never by a parameter.
37
+ *
38
+ * Read-only and deliberately narrow: it returns what the overview renders and
39
+ * nothing that would let a caller walk into another tenant's alarms.
40
+ */
41
+ export declare function listAlarmTriggers(user: _User): Promise<AlarmTriggerRow[]>;
@@ -0,0 +1,137 @@
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.listAlarmTriggers = listAlarmTriggers;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../../types/index.js");
9
+ const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
10
+ /**
11
+ * Every alarm in this tenant whose action creates a maintenance plan.
12
+ *
13
+ * **Why the server has to answer this.** `Alarm.beforeSave` applies
14
+ * `denyTenantUserRead`, so alarms are private to the user who configured them.
15
+ * A maintenance manager asking "what triggers maintenance in this plant" would
16
+ * otherwise see only their own — which is the one answer that is never useful.
17
+ * The query therefore runs with the master key and is scoped to the caller's
18
+ * tenant by the server, never by a parameter.
19
+ *
20
+ * Read-only and deliberately narrow: it returns what the overview renders and
21
+ * nothing that would let a caller walk into another tenant's alarms.
22
+ */
23
+ async function listAlarmTriggers(user) {
24
+ const tenant = user.get("tenant");
25
+ if (!tenant)
26
+ return [];
27
+ const alarms = await new node_1.default.Query(index_js_1.Alarm)
28
+ .equalTo("tenant", tenant)
29
+ // `action` is an Object column; Mongo reads the dotted path into it. The
30
+ // generated type only knows `any`, hence the cast.
31
+ .equalTo("action.actionId", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
32
+ .include("user")
33
+ .limit(500)
34
+ .find({ useMasterKey: true });
35
+ if (alarms.length === 0)
36
+ return [];
37
+ const plansByOrigin = await schedulesByOrigin(tenant, alarms);
38
+ const templateTitles = await titlesFor(alarms
39
+ .map((alarm) => templateIdOf(alarm))
40
+ .filter((id) => !!id));
41
+ return alarms.map((alarm) => {
42
+ const action = (alarm.get("action") ?? {});
43
+ const templateId = templateIdOf(alarm);
44
+ const source = alarm.get("item_source");
45
+ const id = alarm.get("item_id");
46
+ const dimension = alarm.get("item_dimension");
47
+ return {
48
+ alarmId: alarm.id,
49
+ name: alarm.get("name"),
50
+ sensor: sensorLabel(source, id, dimension),
51
+ item_source: source,
52
+ item_id: id,
53
+ item_dimension: dimension,
54
+ owner: alarm.get("user")?.get("username"),
55
+ templateId,
56
+ templateTitle: templateId ? templateTitles.get(templateId) : undefined,
57
+ equipmentId: stringField(action, "equipmentId"),
58
+ dueInDays: numberField(action, "dueInDays"),
59
+ schedules: plansByOrigin.get(`alarm:${alarm.id}`) ?? [],
60
+ };
61
+ });
62
+ }
63
+ /**
64
+ * Plans grouped by their `origin` marker.
65
+ *
66
+ * One query for all alarms rather than one per alarm: a plant with fifty
67
+ * triggers would otherwise open fifty round trips to render one table.
68
+ */
69
+ async function schedulesByOrigin(tenant, alarms) {
70
+ const origins = alarms.map((alarm) => `alarm:${alarm.id}`);
71
+ const schedules = await new node_1.default.Query(index_js_1.Service_Schedule)
72
+ .equalTo("tenant", tenant)
73
+ .containedIn("origin", origins)
74
+ .doesNotExist("deletedAt")
75
+ .descending("createdAt")
76
+ .limit(1000)
77
+ .find({ useMasterKey: true });
78
+ const byOrigin = new Map();
79
+ for (const schedule of schedules) {
80
+ const origin = schedule.get("origin");
81
+ if (!origin)
82
+ continue;
83
+ const cadence = schedule.get("cadence");
84
+ const asset = schedule.get("asset");
85
+ const rows = byOrigin.get(origin) ?? [];
86
+ rows.push({
87
+ id: schedule.id,
88
+ title: schedule.get("title"),
89
+ due: cadence?.dtstart,
90
+ firedAt: asset?.alarm?.firedAt,
91
+ });
92
+ byOrigin.set(origin, rows);
93
+ }
94
+ return byOrigin;
95
+ }
96
+ /** Titles of the referenced templates, so the table can name them. */
97
+ async function titlesFor(templateIds) {
98
+ const unique = [...new Set(templateIds)];
99
+ if (unique.length === 0)
100
+ return new Map();
101
+ const templates = await new node_1.default.Query("OD3_Service_Schedule_Template")
102
+ .containedIn("objectId", unique)
103
+ .limit(unique.length)
104
+ .find({ useMasterKey: true });
105
+ return new Map(templates.map((template) => [
106
+ template.id,
107
+ template.get("title"),
108
+ ]));
109
+ }
110
+ /**
111
+ * The template id out of the alarm's action settings.
112
+ *
113
+ * The alarm dialog prefixes each field with the action id
114
+ * (`<actionId>__<key>`, see `AlarmCreate.tsx`), so both spellings are accepted:
115
+ * the plain key is what the executor forwards as `params`.
116
+ */
117
+ function templateIdOf(alarm) {
118
+ const action = (alarm.get("action") ?? {});
119
+ return (stringField(action, "templateId") ??
120
+ stringField(action, `${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}__templateId`));
121
+ }
122
+ function stringField(source, key) {
123
+ const value = source[key];
124
+ return typeof value === "string" && value ? value : undefined;
125
+ }
126
+ function numberField(source, key) {
127
+ const value = source[key];
128
+ return typeof value === "number" && Number.isFinite(value)
129
+ ? value
130
+ : undefined;
131
+ }
132
+ function sensorLabel(source, id, dimension) {
133
+ const sensor = [source, id].filter(Boolean).join("/");
134
+ if (!sensor)
135
+ return undefined;
136
+ return dimension != null ? `${sensor} [${dimension}]` : sensor;
137
+ }
@@ -0,0 +1,13 @@
1
+ import { Tenant } from "../../../types/index.js";
2
+ /**
3
+ * The tenant a call belongs to, identified by its shared secret.
4
+ *
5
+ * An alarm executor lives outside this server and is not trusted to name a
6
+ * tenant — so the secret does it. One `OD3_Config` row per tenant and per
7
+ * action (`configKey`); no row means the tenant has not switched that endpoint
8
+ * on, and the call is refused.
9
+ *
10
+ * Shared by every alarm action so there is exactly **one** implementation of
11
+ * the secret comparison to review.
12
+ */
13
+ export declare function tenantForSecret(configKey: string, secret: string): Promise<Tenant | undefined>;
@@ -0,0 +1,45 @@
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.tenantForSecret = tenantForSecret;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ /**
10
+ * The tenant a call belongs to, identified by its shared secret.
11
+ *
12
+ * An alarm executor lives outside this server and is not trusted to name a
13
+ * tenant — so the secret does it. One `OD3_Config` row per tenant and per
14
+ * action (`configKey`); no row means the tenant has not switched that endpoint
15
+ * on, and the call is refused.
16
+ *
17
+ * Shared by every alarm action so there is exactly **one** implementation of
18
+ * the secret comparison to review.
19
+ */
20
+ async function tenantForSecret(configKey, secret) {
21
+ if (!secret)
22
+ return undefined;
23
+ const configs = await new node_1.default.Query(index_js_1.Config)
24
+ .equalTo("key", configKey)
25
+ .include("tenant")
26
+ .find({ useMasterKey: true });
27
+ const match = configs.find((config) => {
28
+ const value = config.get("value");
29
+ return typeof value === "string" && constantTimeEqual(value.trim(), secret);
30
+ });
31
+ return match?.get("tenant") ?? undefined;
32
+ }
33
+ /**
34
+ * Compare without leaking the answer through timing — the caller controls one
35
+ * side of this comparison and may try many.
36
+ */
37
+ function constantTimeEqual(a, b) {
38
+ if (a.length !== b.length)
39
+ return false;
40
+ let diff = 0;
41
+ for (let i = 0; i < a.length; i++) {
42
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
43
+ }
44
+ return diff === 0;
45
+ }
@@ -23,32 +23,6 @@ export declare const ALARM_TICKET_SECRET_CONFIG_KEY = "OPENSERVICE_ALARM_TICKET_
23
23
  export declare const DEFAULT_STATUS_CATEGORY = "inbox";
24
24
  /** Categories in which a ticket counts as finished (mirrors core's `DONE_CATEGORIES`). */
25
25
  export declare const DONE_STATUS_CATEGORIES: string[];
26
- /**
27
- * What the executor reports about the alarm that fired.
28
- *
29
- * Field names follow `OD3_Alarm` so a payload can be assembled from the alarm
30
- * row without renaming: `item_id` / `item_source` / `item_dimension` identify
31
- * the sensor, the rest is context for the ticket text. Everything is optional
32
- * except that *something* must identify the alarm — see `alarmKey`.
33
- */
34
- export interface AlarmEvent {
35
- /** `OD3_Alarm.objectId`, if the executor knows it. */
36
- alarmId?: string;
37
- /** The alarm's name, used in the ticket title when no template is given. */
38
- name?: string;
39
- /** Sensor id, e.g. `cnc04.spindle`. */
40
- item_id?: string;
41
- /** Source (site/tenant hierarchy) the sensor belongs to. */
42
- item_source?: string;
43
- /** Which dimension of the sensor tripped. */
44
- item_dimension?: number;
45
- /** The value that broke the rule. */
46
- value?: number | string | boolean;
47
- /** Human-readable rule, e.g. `> 80`. */
48
- condition?: string;
49
- /** When it fired (ISO). Defaults to now. */
50
- firedAt?: string;
51
- }
52
26
  /**
53
27
  * What the person configuring the alarm filled into the action's form
54
28
  * (`OD3_AlarmAction.formFields`).
@@ -0,0 +1,18 @@
1
+ import type { AlarmEvent } from "../AlarmEvent.js";
2
+ import { type AlarmTicketParams } from "./AlarmTicketTypes.js";
3
+ /**
4
+ * Alarm + action parameters → the text fields of a ticket.
5
+ *
6
+ * Pure, so the wording and — more importantly — the `origin` marker can be
7
+ * checked without a database. Identity, the marker and the placeholder
8
+ * rendering are shared with every other alarm action
9
+ * (`alarmIdentity.ts`); what stays here is what a *ticket*
10
+ * makes of them.
11
+ */
12
+ /** Title, description and origin of the ticket a fired alarm produces. */
13
+ export interface AlarmTicketFields {
14
+ title: string;
15
+ description: string;
16
+ origin: string;
17
+ }
18
+ export declare function alarmTicketFields(event: AlarmEvent, params?: AlarmTicketParams): AlarmTicketFields;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.alarmTicketFields = alarmTicketFields;
4
+ const alarmIdentity_js_1 = require("../alarmIdentity.js");
5
+ const AlarmTicketTypes_js_1 = require("./AlarmTicketTypes.js");
6
+ function alarmTicketFields(event, params = {}) {
7
+ return {
8
+ title: renderTitle(event, params),
9
+ description: renderDescription(event, params),
10
+ origin: (0, alarmIdentity_js_1.alarmOrigin)(event),
11
+ };
12
+ }
13
+ /** `{{alarm}}` / `{{sensor}}` / `{{value}}` in the configured title. */
14
+ function renderTitle(event, params) {
15
+ const rendered = (0, alarmIdentity_js_1.renderTitleTemplate)(params.title, event);
16
+ if (rendered)
17
+ return rendered;
18
+ // No template: the alarm's own name is the most recognisable thing there is,
19
+ // and a ticket must have a title.
20
+ const sensor = (0, alarmIdentity_js_1.sensorLabel)(event);
21
+ return event.name || (sensor ? `Alarm: ${sensor}` : "Alarm");
22
+ }
23
+ /**
24
+ * The configured note plus what the alarm actually reported.
25
+ *
26
+ * The details are appended rather than templated, because the person handling
27
+ * the ticket needs to know which sensor, which value and when — and forgetting
28
+ * a placeholder in the form should not lose that.
29
+ */
30
+ function renderDescription(event, params) {
31
+ const lines = [];
32
+ const note = params.description?.trim();
33
+ if (note)
34
+ lines.push(note, "");
35
+ lines.push(...(0, alarmIdentity_js_1.alarmDetailLines)(event, AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID));
36
+ return lines.join("\n");
37
+ }