@openinc/parse-server-opendash 4.41.0 → 5.0.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 (194) hide show
  1. package/dist/features/config/helper/customOptions.js +1 -1
  2. package/dist/features/config/types/ConfigKeys.d.ts +0 -3
  3. package/dist/features/config/types/ConfigKeys.js +3 -23
  4. package/dist/features/openservice/index.d.ts +6 -27
  5. package/dist/features/openservice/index.js +7 -44
  6. package/dist/features/openservice/init.d.ts +5 -13
  7. package/dist/features/openservice/init.js +17 -46
  8. package/dist/features/openservice/serviceSchedules/calendarSync/Access.d.ts +9 -0
  9. package/dist/features/openservice/serviceSchedules/calendarSync/CalendarManager.d.ts +71 -0
  10. package/dist/features/openservice/serviceSchedules/calendarSync/CalendarManager.js +300 -0
  11. package/dist/features/openservice/{schedules → serviceSchedules}/calendarSync/Event.d.ts +0 -4
  12. package/dist/features/openservice/{types/Material.js → serviceSchedules/calendarSync/Event.js} +3 -0
  13. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceCalendarSyncPoller.d.ts +37 -53
  14. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceCalendarSyncPoller.js +284 -187
  15. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceSyncTypes.d.ts +17 -15
  16. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceSyncTypes.js +4 -5
  17. package/dist/features/openservice/serviceSchedules/calendarSync/eventToPlan.d.ts +1 -1
  18. package/dist/features/openservice/serviceSchedules/calendarSync/inboundChanges.d.ts +65 -0
  19. package/dist/features/openservice/serviceSchedules/calendarSync/inboundChanges.js +101 -0
  20. package/dist/features/openservice/serviceSchedules/calendarSync/index.d.ts +2 -2
  21. package/dist/features/openservice/serviceSchedules/calendarSync/index.js +3 -1
  22. package/dist/features/openservice/serviceSchedules/calendarSync/outlookRecurrence.d.ts +1 -1
  23. package/dist/features/openservice/serviceSchedules/calendarSync/planLock.d.ts +11 -0
  24. package/dist/features/openservice/serviceSchedules/calendarSync/planLock.js +48 -0
  25. package/dist/features/openservice/serviceSchedules/calendarSync/planToEvent.d.ts +1 -1
  26. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.d.ts +11 -32
  27. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.js +20 -22
  28. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.d.ts +4 -5
  29. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.js +2 -3
  30. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.d.ts +10 -1
  31. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.js +25 -2
  32. package/dist/features/openservice/serviceSchedules/initServiceSchedulesFeature.d.ts +6 -4
  33. package/dist/features/openservice/serviceSchedules/initServiceSchedulesFeature.js +24 -11
  34. package/dist/features/openware/index.d.ts +0 -1
  35. package/dist/features/permissions/types/Permissions.d.ts +0 -14
  36. package/dist/features/permissions/types/Permissions.js +0 -18
  37. package/dist/features/translations/services/initTranslation.js +1 -1
  38. package/dist/hooks/Config_open_service.js +0 -60
  39. package/dist/hooks/Meta_Entry.js +3 -6
  40. package/dist/hooks/Service_Schedule.js +14 -7
  41. package/dist/index.js +2 -7
  42. package/dist/scripts/migration/passes/18-calendar-links.js +6 -2
  43. package/package.json +3 -4
  44. package/pnpm-workspace.yaml +7 -0
  45. package/dist/features/openservice/functions/assignUsersAndRoles.d.ts +0 -13
  46. package/dist/features/openservice/functions/assignUsersAndRoles.js +0 -212
  47. package/dist/features/openservice/functions/getSourceMetaMap.d.ts +0 -13
  48. package/dist/features/openservice/functions/getSourceMetaMap.js +0 -52
  49. package/dist/features/openservice/functions/getTicketObject.d.ts +0 -9
  50. package/dist/features/openservice/functions/getTicketObject.js +0 -31
  51. package/dist/features/openservice/functions/saveDescription.d.ts +0 -9
  52. package/dist/features/openservice/functions/saveDescription.js +0 -12
  53. package/dist/features/openservice/functions/saveDowntime.d.ts +0 -8
  54. package/dist/features/openservice/functions/saveDowntime.js +0 -32
  55. package/dist/features/openservice/functions/saveDuedate.d.ts +0 -13
  56. package/dist/features/openservice/functions/saveDuedate.js +0 -39
  57. package/dist/features/openservice/functions/saveFrequency.d.ts +0 -8
  58. package/dist/features/openservice/functions/saveFrequency.js +0 -32
  59. package/dist/features/openservice/functions/saveIssuecategory.d.ts +0 -14
  60. package/dist/features/openservice/functions/saveIssuecategory.js +0 -53
  61. package/dist/features/openservice/functions/saveMaterial.d.ts +0 -9
  62. package/dist/features/openservice/functions/saveMaterial.js +0 -18
  63. package/dist/features/openservice/functions/saveMessage.d.ts +0 -10
  64. package/dist/features/openservice/functions/saveMessage.js +0 -54
  65. package/dist/features/openservice/functions/savePriority.d.ts +0 -8
  66. package/dist/features/openservice/functions/savePriority.js +0 -32
  67. package/dist/features/openservice/functions/saveProject.d.ts +0 -8
  68. package/dist/features/openservice/functions/saveProject.js +0 -98
  69. package/dist/features/openservice/functions/saveRestriction.d.ts +0 -8
  70. package/dist/features/openservice/functions/saveRestriction.js +0 -32
  71. package/dist/features/openservice/functions/saveSource.d.ts +0 -8
  72. package/dist/features/openservice/functions/saveSource.js +0 -32
  73. package/dist/features/openservice/functions/saveState.d.ts +0 -14
  74. package/dist/features/openservice/functions/saveState.js +0 -52
  75. package/dist/features/openservice/functions/saveTicketMeta.d.ts +0 -9
  76. package/dist/features/openservice/functions/saveTicketMeta.js +0 -32
  77. package/dist/features/openservice/functions/saveTicketTitle.d.ts +0 -8
  78. package/dist/features/openservice/functions/saveTicketTitle.js +0 -28
  79. package/dist/features/openservice/issuecategory/initIssuecategory.d.ts +0 -5
  80. package/dist/features/openservice/issuecategory/initIssuecategory.js +0 -42
  81. package/dist/features/openservice/kanbanState/initKanbanStates.d.ts +0 -21
  82. package/dist/features/openservice/kanbanState/initKanbanStates.js +0 -187
  83. package/dist/features/openservice/messages/initMessages.d.ts +0 -8
  84. package/dist/features/openservice/messages/initMessages.js +0 -466
  85. package/dist/features/openservice/messages/removeLatestMessage.d.ts +0 -9
  86. package/dist/features/openservice/messages/removeLatestMessage.js +0 -30
  87. package/dist/features/openservice/schedules/calendarSync/Access.d.ts +0 -12
  88. package/dist/features/openservice/schedules/calendarSync/CalendarManager.d.ts +0 -49
  89. package/dist/features/openservice/schedules/calendarSync/CalendarManager.js +0 -211
  90. package/dist/features/openservice/schedules/calendarSync/CalendarSyncPoller.d.ts +0 -25
  91. package/dist/features/openservice/schedules/calendarSync/CalendarSyncPoller.js +0 -202
  92. package/dist/features/openservice/schedules/calendarSync/ConfigValues.d.ts +0 -13
  93. package/dist/features/openservice/schedules/calendarSync/ConfigValues.js +0 -2
  94. package/dist/features/openservice/schedules/calendarSync/Event.js +0 -9
  95. package/dist/features/openservice/schedules/calendarSync/calendarMetaHelper.d.ts +0 -76
  96. package/dist/features/openservice/schedules/calendarSync/calendarMetaHelper.js +0 -119
  97. package/dist/features/openservice/schedules/calendarSync/eventToSchedule.d.ts +0 -37
  98. package/dist/features/openservice/schedules/calendarSync/eventToSchedule.js +0 -103
  99. package/dist/features/openservice/schedules/calendarSync/scheduleToEvent.d.ts +0 -9
  100. package/dist/features/openservice/schedules/calendarSync/scheduleToEvent.js +0 -122
  101. package/dist/features/openservice/schedules/checkStatus.d.ts +0 -9
  102. package/dist/features/openservice/schedules/checkStatus.js +0 -31
  103. package/dist/features/openservice/schedules/getScheduleLink.d.ts +0 -10
  104. package/dist/features/openservice/schedules/getScheduleLink.js +0 -32
  105. package/dist/features/openservice/schedules/initSchedulesFeature.d.ts +0 -5
  106. package/dist/features/openservice/schedules/initSchedulesFeature.js +0 -32
  107. package/dist/features/openservice/schedules/reassignScheduleExecutions.d.ts +0 -5
  108. package/dist/features/openservice/schedules/reassignScheduleExecutions.js +0 -39
  109. package/dist/features/openservice/ticket/getTicketLink.d.ts +0 -9
  110. package/dist/features/openservice/ticket/getTicketLink.js +0 -32
  111. package/dist/features/openservice/ticket/initTicket.d.ts +0 -4
  112. package/dist/features/openservice/ticket/initTicket.js +0 -56
  113. package/dist/features/openservice/types/FetchOptions.d.ts +0 -4
  114. package/dist/features/openservice/types/FetchOptions.js +0 -2
  115. package/dist/features/openservice/types/Material.d.ts +0 -10
  116. package/dist/features/openservice/types/OpenserviceTranslationKeys.d.ts +0 -102
  117. package/dist/features/openservice/types/OpenserviceTranslationKeys.js +0 -106
  118. package/dist/features/openservice/types/SaveValues.d.ts +0 -33
  119. package/dist/features/openservice/types/SaveValues.js +0 -2
  120. package/dist/features/openservice/types/TicketData.d.ts +0 -22
  121. package/dist/features/openservice/types/TicketData.js +0 -2
  122. package/dist/features/openware/types/OpenWareTicketObject.d.ts +0 -14
  123. package/dist/features/openware/types/OpenWareTicketObject.js +0 -2
  124. package/dist/functions/openinc-openservice-get-sourcemeta-map.d.ts +0 -1
  125. package/dist/functions/openinc-openservice-get-sourcemeta-map.js +0 -41
  126. package/dist/functions/openinc-openservice-save-ticket-data.d.ts +0 -6
  127. package/dist/functions/openinc-openservice-save-ticket-data.js +0 -517
  128. package/dist/functions/openinc-openservice-ticket-data.d.ts +0 -44
  129. package/dist/functions/openinc-openservice-ticket-data.js +0 -380
  130. package/dist/helper/removeShorltyPreviousEntry.d.ts +0 -2
  131. package/dist/helper/removeShorltyPreviousEntry.js +0 -31
  132. package/dist/hooks/Maintenance_Downtime.d.ts +0 -1
  133. package/dist/hooks/Maintenance_Downtime.js +0 -106
  134. package/dist/hooks/Maintenance_Duedate.d.ts +0 -1
  135. package/dist/hooks/Maintenance_Duedate.js +0 -128
  136. package/dist/hooks/Maintenance_Frequency.d.ts +0 -1
  137. package/dist/hooks/Maintenance_Frequency.js +0 -106
  138. package/dist/hooks/Maintenance_Issuecategory.d.ts +0 -1
  139. package/dist/hooks/Maintenance_Issuecategory.js +0 -19
  140. package/dist/hooks/Maintenance_Item.d.ts +0 -1
  141. package/dist/hooks/Maintenance_Item.js +0 -17
  142. package/dist/hooks/Maintenance_Kanban_State.d.ts +0 -1
  143. package/dist/hooks/Maintenance_Kanban_State.js +0 -17
  144. package/dist/hooks/Maintenance_Media.d.ts +0 -1
  145. package/dist/hooks/Maintenance_Media.js +0 -17
  146. package/dist/hooks/Maintenance_Message.d.ts +0 -1
  147. package/dist/hooks/Maintenance_Message.js +0 -20
  148. package/dist/hooks/Maintenance_Order.d.ts +0 -1
  149. package/dist/hooks/Maintenance_Order.js +0 -17
  150. package/dist/hooks/Maintenance_Priority.d.ts +0 -1
  151. package/dist/hooks/Maintenance_Priority.js +0 -110
  152. package/dist/hooks/Maintenance_Project.d.ts +0 -1
  153. package/dist/hooks/Maintenance_Project.js +0 -30
  154. package/dist/hooks/Maintenance_Restriction.d.ts +0 -1
  155. package/dist/hooks/Maintenance_Restriction.js +0 -113
  156. package/dist/hooks/Maintenance_Schedule.d.ts +0 -1
  157. package/dist/hooks/Maintenance_Schedule.js +0 -146
  158. package/dist/hooks/Maintenance_Schedule_Execution.d.ts +0 -1
  159. package/dist/hooks/Maintenance_Schedule_Execution.js +0 -118
  160. package/dist/hooks/Maintenance_Schedule_Execution_Step.d.ts +0 -1
  161. package/dist/hooks/Maintenance_Schedule_Execution_Step.js +0 -17
  162. package/dist/hooks/Maintenance_Schedule_Step.d.ts +0 -1
  163. package/dist/hooks/Maintenance_Schedule_Step.js +0 -26
  164. package/dist/hooks/Maintenance_Schedule_Template.d.ts +0 -1
  165. package/dist/hooks/Maintenance_Schedule_Template.js +0 -92
  166. package/dist/hooks/Maintenance_Source_File.d.ts +0 -1
  167. package/dist/hooks/Maintenance_Source_File.js +0 -17
  168. package/dist/hooks/Maintenance_Ticket.d.ts +0 -1
  169. package/dist/hooks/Maintenance_Ticket.js +0 -15
  170. package/dist/hooks/Maintenance_Ticket_Assignment.d.ts +0 -1
  171. package/dist/hooks/Maintenance_Ticket_Assignment.js +0 -17
  172. package/dist/hooks/Maintenance_Ticket_FormConfig.d.ts +0 -1
  173. package/dist/hooks/Maintenance_Ticket_FormConfig.js +0 -17
  174. package/dist/hooks/Maintenance_Ticket_Issuecategory.d.ts +0 -1
  175. package/dist/hooks/Maintenance_Ticket_Issuecategory.js +0 -109
  176. package/dist/hooks/Maintenance_Ticket_Kanban_State.d.ts +0 -1
  177. package/dist/hooks/Maintenance_Ticket_Kanban_State.js +0 -134
  178. package/dist/hooks/Maintenance_Ticket_Kanban_State_Current.d.ts +0 -1
  179. package/dist/hooks/Maintenance_Ticket_Kanban_State_Current.js +0 -15
  180. package/dist/hooks/Maintenance_Ticket_Material.d.ts +0 -4
  181. package/dist/hooks/Maintenance_Ticket_Material.js +0 -104
  182. package/dist/hooks/Maintenance_Ticket_Project.d.ts +0 -1
  183. package/dist/hooks/Maintenance_Ticket_Project.js +0 -88
  184. package/dist/hooks/Maintenance_Ticket_QR_Code.d.ts +0 -1
  185. package/dist/hooks/Maintenance_Ticket_QR_Code.js +0 -17
  186. package/dist/hooks/Maintenance_Ticket_Source.d.ts +0 -1
  187. package/dist/hooks/Maintenance_Ticket_Source.js +0 -124
  188. package/dist/hooks/Maintenance_Ticket_Title.d.ts +0 -1
  189. package/dist/hooks/Maintenance_Ticket_Title.js +0 -107
  190. package/dist/i18n/de-DE/maintenance.json +0 -16
  191. package/dist/i18n/en-US/maintenance.json +0 -16
  192. package/dist/scripts/seed-v1-testdata.d.ts +0 -43
  193. package/dist/scripts/seed-v1-testdata.js +0 -982
  194. /package/dist/features/openservice/{schedules → serviceSchedules}/calendarSync/Access.js +0 -0
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CalendarManager = exports.GraphThrottledError = exports.EVENT_SELECT = void 0;
4
+ const GRAPH = "https://graph.microsoft.com/v1.0";
5
+ /** Graph allows at most 20 requests in one `$batch`. */
6
+ const BATCH_SIZE = 20;
7
+ /**
8
+ * The properties the sync reads from an event — everything the plan mapping
9
+ * and the change detection (`inboundChanges.ts`) need, and nothing else.
10
+ */
11
+ exports.EVENT_SELECT = [
12
+ "id",
13
+ "changeKey",
14
+ "type",
15
+ "subject",
16
+ "bodyPreview",
17
+ "start",
18
+ "end",
19
+ "isAllDay",
20
+ "isCancelled",
21
+ "recurrence",
22
+ "isReminderOn",
23
+ "reminderMinutesBeforeStart",
24
+ "categories",
25
+ "lastModifiedDateTime",
26
+ ].join(",");
27
+ /**
28
+ * Graph answered 429. Thrown rather than swallowed: a caller that carries on
29
+ * makes the next request just as throttled — the poller stops its pass and
30
+ * waits `retryAfterSeconds` (Microsoft's documented contract).
31
+ */
32
+ class GraphThrottledError extends Error {
33
+ retryAfterSeconds;
34
+ constructor(retryAfterSeconds) {
35
+ super(`Microsoft Graph throttled the request (retry after ${retryAfterSeconds}s)`);
36
+ this.retryAfterSeconds = retryAfterSeconds;
37
+ this.name = "GraphThrottledError";
38
+ }
39
+ }
40
+ exports.GraphThrottledError = GraphThrottledError;
41
+ /**
42
+ * Tokens by app registration. A client-credentials token is valid for about an
43
+ * hour; asking for a new one before every Graph call (as this class used to)
44
+ * doubled the request count and was the first thing to be throttled.
45
+ */
46
+ const tokenCache = new Map();
47
+ /**
48
+ * Microsoft Graph client for one mailbox's calendar (client credentials).
49
+ *
50
+ * Model-free: it knows Graph events, not maintenance plans. Moved here from
51
+ * the v1 sync (`schedules/calendarSync`) when that was removed.
52
+ *
53
+ * Failures other than throttling are logged and come back as `undefined` /
54
+ * `null` / `false`, as before — the sync treats a failed write as "try again
55
+ * with the next save".
56
+ */
57
+ class CalendarManager {
58
+ tenantID;
59
+ clientID;
60
+ clientSecret;
61
+ userMail;
62
+ constructor(config) {
63
+ this.tenantID = config.tenantId;
64
+ this.clientID = config.clientID;
65
+ this.clientSecret = config.clientSecret;
66
+ this.userMail = config.userMail;
67
+ }
68
+ get isValid() {
69
+ if (!this.tenantID)
70
+ return "Missing Microsoft Tenant ID";
71
+ if (!this.clientID)
72
+ return "Missing Microsoft Client ID";
73
+ if (!this.clientSecret)
74
+ return "Missing Microsoft Client Secret";
75
+ if (!this.userMail)
76
+ return "Missing Microsoft User Email";
77
+ return true;
78
+ }
79
+ get mailbox() {
80
+ return `/users/${encodeURIComponent(this.userMail)}`;
81
+ }
82
+ async getToken() {
83
+ if (this.isValid !== true)
84
+ return null;
85
+ const key = `${this.tenantID}|${this.clientID}`;
86
+ const cached = tokenCache.get(key);
87
+ if (cached && cached.expiresAt > Date.now())
88
+ return cached.token;
89
+ try {
90
+ const params = new URLSearchParams();
91
+ params.append("client_id", this.clientID);
92
+ params.append("client_secret", this.clientSecret);
93
+ params.append("scope", "https://graph.microsoft.com/.default");
94
+ params.append("grant_type", "client_credentials");
95
+ const response = await fetch(`https://login.microsoftonline.com/${this.tenantID}/oauth2/v2.0/token`, {
96
+ method: "POST",
97
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
98
+ body: params.toString(),
99
+ });
100
+ throwIfThrottled(response);
101
+ if (!response.ok) {
102
+ console.error(`[CalendarManager] Failed to obtain access token: HTTP ${response.status}`);
103
+ return null;
104
+ }
105
+ const data = (await response.json());
106
+ // A minute's margin, so a token never expires between check and use.
107
+ tokenCache.set(key, {
108
+ token: data.access_token,
109
+ expiresAt: Date.now() + Math.max(0, data.expires_in - 60) * 1000,
110
+ });
111
+ return data.access_token;
112
+ }
113
+ catch (error) {
114
+ if (error instanceof GraphThrottledError)
115
+ throw error;
116
+ console.error("[CalendarManager] Error fetching access token:", error);
117
+ return null;
118
+ }
119
+ }
120
+ /** A Graph request with the token; `null` when there is no token. */
121
+ async request(path, init = {}) {
122
+ const token = await this.getToken();
123
+ if (!token)
124
+ return null;
125
+ const response = await fetch(path.startsWith("http") ? path : GRAPH + path, {
126
+ ...init,
127
+ headers: {
128
+ Authorization: `Bearer ${token}`,
129
+ ...(init.body ? { "Content-Type": "application/json" } : {}),
130
+ ...(init.headers ?? {}),
131
+ },
132
+ });
133
+ throwIfThrottled(response);
134
+ return response;
135
+ }
136
+ async createEvent(event) {
137
+ const res = await this.request(`${this.mailbox}/events`, {
138
+ method: "POST",
139
+ body: JSON.stringify(event),
140
+ });
141
+ if (!res)
142
+ return;
143
+ if (!res.ok) {
144
+ console.error(`[CalendarManager] Failed to create event: HTTP ${res.status}`);
145
+ return;
146
+ }
147
+ return (await res.json());
148
+ }
149
+ async updateEvent(eventId, event) {
150
+ const res = await this.request(`${this.mailbox}/events/${eventId}`, {
151
+ method: "PATCH",
152
+ body: JSON.stringify(event),
153
+ });
154
+ if (!res)
155
+ return;
156
+ if (!res.ok) {
157
+ console.error(`[CalendarManager] Failed to update event ${eventId}: HTTP ${res.status}`);
158
+ return;
159
+ }
160
+ return (await res.json());
161
+ }
162
+ /** `true` also when the event was already gone — the goal is reached. */
163
+ async deleteEvent(eventId) {
164
+ const res = await this.request(`${this.mailbox}/events/${eventId}`, {
165
+ method: "DELETE",
166
+ });
167
+ if (!res)
168
+ return false;
169
+ if (res.ok || res.status === 404)
170
+ return true;
171
+ console.error(`[CalendarManager] Failed to delete event ${eventId}: HTTP ${res.status}`);
172
+ return false;
173
+ }
174
+ async fetchEvent(eventId) {
175
+ const res = await this.request(`${this.mailbox}/events/${eventId}?$select=${exports.EVENT_SELECT}`);
176
+ if (!res)
177
+ return null;
178
+ if (!res.ok) {
179
+ console.error(`[CalendarManager] Failed to fetch event ${eventId}: HTTP ${res.status}`);
180
+ return null;
181
+ }
182
+ return (await res.json());
183
+ }
184
+ /**
185
+ * Read many events by id, 20 per `$batch` request.
186
+ *
187
+ * The map holds an entry for every id Graph answered: the event, or `null`
188
+ * for one that no longer exists (404). An id missing from the map could not
189
+ * be read (another error) — the caller must not mistake that for a deletion.
190
+ * `null` overall when not even the batch request went through.
191
+ */
192
+ async fetchEventsBatch(eventIds) {
193
+ const results = new Map();
194
+ for (let offset = 0; offset < eventIds.length; offset += BATCH_SIZE) {
195
+ const chunk = eventIds.slice(offset, offset + BATCH_SIZE);
196
+ const res = await this.request("/$batch", {
197
+ method: "POST",
198
+ body: JSON.stringify({
199
+ requests: chunk.map((id, index) => ({
200
+ id: String(index),
201
+ method: "GET",
202
+ url: `${this.mailbox}/events/${id}?$select=${exports.EVENT_SELECT}`,
203
+ })),
204
+ }),
205
+ });
206
+ if (!res)
207
+ return null;
208
+ if (!res.ok) {
209
+ console.error(`[CalendarManager] Batch read failed: HTTP ${res.status}`);
210
+ return null;
211
+ }
212
+ const data = (await res.json());
213
+ for (const response of data.responses ?? []) {
214
+ const eventId = chunk[Number(response.id)];
215
+ if (!eventId)
216
+ continue;
217
+ if (response.status === 429) {
218
+ throw new GraphThrottledError(retryAfter(response.headers?.["Retry-After"] ?? response.headers?.["retry-after"]));
219
+ }
220
+ if (response.status === 404) {
221
+ results.set(eventId, null);
222
+ }
223
+ else if (response.status >= 200 && response.status < 300) {
224
+ results.set(eventId, response.body);
225
+ }
226
+ else {
227
+ console.error(`[CalendarManager] Batch read of event ${eventId}: HTTP ${response.status}`);
228
+ }
229
+ }
230
+ }
231
+ return results;
232
+ }
233
+ /**
234
+ * Series masters and single events carrying an Outlook category — the
235
+ * opt-in for creating a plan from Outlook. `/events` never returns
236
+ * occurrences, so a series comes back once. At most `maxItems`, so a
237
+ * mailbox where thousands of appointments carry the category cannot turn a
238
+ * pass into an unbounded read. `null` when the request failed.
239
+ */
240
+ async listEventsWithCategory(category, maxItems) {
241
+ const params = new URLSearchParams({
242
+ $filter: `categories/any(c:c eq '${category.replace(/'/g, "''")}')`,
243
+ $select: exports.EVENT_SELECT,
244
+ $top: "100",
245
+ });
246
+ let next = `${this.mailbox}/events?${params.toString()}`;
247
+ const events = [];
248
+ while (next && events.length < maxItems) {
249
+ const res = await this.request(next);
250
+ if (!res)
251
+ return null;
252
+ if (!res.ok) {
253
+ console.error(`[CalendarManager] Failed to list events with category "${category}": HTTP ${res.status}`, await res.text().catch(() => ""));
254
+ return null;
255
+ }
256
+ const data = (await res.json());
257
+ events.push(...(data.value ?? []));
258
+ next = data["@odata.nextLink"];
259
+ }
260
+ return events.slice(0, maxItems);
261
+ }
262
+ /**
263
+ * The occurrences of a series between two instants — moved ones (exceptions)
264
+ * included, deleted ones not. `null` when the request failed.
265
+ */
266
+ async fetchInstances(seriesId, from, to) {
267
+ const params = new URLSearchParams({
268
+ startDateTime: from.toISOString(),
269
+ endDateTime: to.toISOString(),
270
+ $select: "id,type,originalStart,start",
271
+ $top: "100",
272
+ });
273
+ let next = `${this.mailbox}/events/${seriesId}/instances?${params.toString()}`;
274
+ const instances = [];
275
+ while (next) {
276
+ const res = await this.request(next);
277
+ if (!res)
278
+ return null;
279
+ if (!res.ok) {
280
+ console.error(`[CalendarManager] Failed to fetch instances of ${seriesId}: HTTP ${res.status}`);
281
+ return null;
282
+ }
283
+ const data = (await res.json());
284
+ instances.push(...(data.value ?? []));
285
+ next = data["@odata.nextLink"];
286
+ }
287
+ return instances;
288
+ }
289
+ }
290
+ exports.CalendarManager = CalendarManager;
291
+ function throwIfThrottled(response) {
292
+ if (response.status === 429) {
293
+ throw new GraphThrottledError(retryAfter(response.headers.get("Retry-After")));
294
+ }
295
+ }
296
+ /** Seconds to wait; a missing or odd header means a conservative minute. */
297
+ function retryAfter(header) {
298
+ const seconds = Number(header);
299
+ return Number.isFinite(seconds) && seconds > 0 ? seconds : 60;
300
+ }
@@ -1,9 +1,5 @@
1
1
  /**
2
2
  * Microsoft Graph calendar types — the wire shapes, not ours.
3
- *
4
- * In the v1 folder for history only, and **not** deprecated with the rest of
5
- * it: `serviceSchedules/calendarSync` reads these same types, because the
6
- * Graph payload is the same whichever class we map it onto.
7
3
  */
8
4
  export type DateTimeTimeZone = {
9
5
  dateTime: string;
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
+ /**
3
+ * Microsoft Graph calendar types — the wire shapes, not ours.
4
+ */
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,79 +1,63 @@
1
1
  import { Config } from "../../../../types/index.js";
2
2
  /**
3
- * Marker on a save that came from the calendar.
4
- *
5
- * The outbound side (`syncPlanToCalendar`, called from the `Service_Schedule`
6
- * afterSave hook) checks it and stays quiet — otherwise every inbound change
7
- * would be written straight back to Outlook, produce a new `changeKey`, come
8
- * back through the delta feed as a foreign change, and loop forever. The stored
9
- * `changeKey` is the second line of defence; this is the first, and unlike v1's
10
- * `!master` check it does not disable outbound sync for every other
11
- * master-key writer (the scheduler pausing a plan, a migration, a script).
3
+ * Marker on a save that came from the calendar. The outbound side (the
4
+ * `Service_Schedule` afterSave hook) checks it and stays quiet, so an Outlook
5
+ * edit is not written straight back to Outlook.
12
6
  */
13
7
  export declare const CALENDAR_SYNC_CONTEXT_FLAG = "fromCalendarSync";
14
8
  /**
15
- * Pulls Outlook changes into open.SERVICE **v2** maintenance plans.
9
+ * Reads Outlook back into open.SERVICE maintenance plans, for one connection.
10
+ *
11
+ * Each pass does two bounded things, both on documented Graph v1.0 endpoints:
12
+ *
13
+ * 1. **Linked events** — every event a plan is linked to is read (20 per
14
+ * `$batch`) and compared with the snapshot of what we last wrote or saw
15
+ * (`inboundChanges.ts`). Only what differs is applied; a deleted or
16
+ * cancelled event archives its plan.
17
+ * 2. **New plans** — appointments carrying the import category (default
18
+ * `open.SERVICE`) that are not linked yet become plans. Nothing else in the
19
+ * mailbox is looked at. Our own events carry no category, so the sync never
20
+ * imports what it wrote itself.
16
21
  *
17
- * One poller per configured connection, driven by the Graph *delta* feed: the
18
- * first call reads the whole calendar, each later call only what changed, and
19
- * the cursor lives in the Config row so a restart resumes instead of
20
- * re-importing. The v1 poller does the same for `Maintenance_Schedule` from the
21
- * same connection — the two keep separate cursors (`delta_link` vs
22
- * `delta_link_v2`) so neither consumes the other's changes.
22
+ * This replaces the delta-feed poller, which read the entire mailbox through
23
+ * an endpoint that is beta-only in Graph (`/events/delta`), imported every
24
+ * appointment in it, and restarted from scratch whenever a pass did not finish.
23
25
  */
24
26
  export declare class ServiceCalendarSyncPoller {
25
27
  private timer;
26
28
  private polling;
29
+ private backoffUntil;
27
30
  private config;
31
+ private writes;
32
+ /** Plan id → consecutive passes in which Outlook rewrote it. */
33
+ private streaks;
28
34
  constructor(config: Config);
29
35
  private get values();
30
36
  private get manager();
37
+ private get tenant();
31
38
  start(intervalMs?: number): this;
32
39
  stop(): void;
33
- /**
34
- * One pass over the delta feed — never two at once.
35
- *
36
- * A pass costs a Graph round trip per changed event (and a token request for
37
- * each of them), so it can outlast the interval. A second pass starting on
38
- * top of the first reads the same delta cursor, processes the same events and
39
- * writes the same plans again — which is how a slow calendar turns into a
40
- * stream of saves.
41
- */
42
- private poll;
40
+ /** One pass — never two at once, and not while Graph asked us to wait. */
41
+ poll(): Promise<void>;
43
42
  private runPoll;
44
- private processEvent;
45
- private createPlan;
43
+ private reconcileLinked;
44
+ private applyEvent;
46
45
  /**
47
- * Bring one plan in line with its event — and touch it only if it is not
48
- * already in line.
49
- *
50
- * **Why the comparisons.** `Parse.Object.set()` marks a field dirty whether or
51
- * not the value actually changed, so applying the event's fields
52
- * unconditionally means a save on every pass: a new `updatedAt`, the whole
53
- * `afterSave` chain (ACL sync, calendar check) and a log line — for an event
54
- * nobody touched. Re-reading the same event has to be a no-op, not a write.
55
- *
56
- * `event` is the **full** event, not a delta payload: those are partial, and
57
- * an unchanged subject arrives as `undefined` there, which would wipe the
58
- * plan's title.
46
+ * Apply what changed in Outlook — and only that. A plan field whose
47
+ * counterpart did not change is not touched, so the lossy parts of the
48
+ * mapping (time of day, reminder minutes vs. rule days) never rewrite it.
59
49
  */
60
50
  private updatePlan;
61
51
  /**
62
- * A deleted appointment archives the plan — it never destroys it.
63
- *
64
- * Executions document that work happened; deleting the plan they point at
65
- * would strand that history (the `beforeDelete` hook refuses it, too). The
66
- * meta entry goes, so the same plan can be linked to a new event later.
52
+ * A deleted or cancelled appointment archives the plan — never destroys it:
53
+ * executions document work against it. The link goes, so the plan can be
54
+ * linked to a new event later.
67
55
  */
68
- private handleRemoved;
56
+ private archivePlan;
57
+ private importCategorised;
58
+ private createPlan;
59
+ private countWrite;
69
60
  /** The machine named in the subject, else the configured fallback. */
70
61
  private resolveEquipment;
71
62
  private findEquipmentByLabel;
72
- /**
73
- * The cursor is re-read from the Config row on every tick, and written back
74
- * after it: the row is also the admin form's storage, so it can change
75
- * underneath us.
76
- */
77
- private loadDeltaLink;
78
- private saveDeltaLink;
79
63
  }