@openinc/parse-server-opendash 4.40.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 (197) 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/hooks/Service_Schedule_Execution.js +41 -14
  42. package/dist/index.js +2 -7
  43. package/dist/scripts/backfill-execution-snapshot.d.ts +1 -0
  44. package/dist/scripts/backfill-execution-snapshot.js +124 -0
  45. package/dist/scripts/migration/passes/18-calendar-links.js +6 -2
  46. package/package.json +4 -4
  47. package/pnpm-workspace.yaml +7 -0
  48. package/dist/features/openservice/functions/assignUsersAndRoles.d.ts +0 -13
  49. package/dist/features/openservice/functions/assignUsersAndRoles.js +0 -212
  50. package/dist/features/openservice/functions/getSourceMetaMap.d.ts +0 -13
  51. package/dist/features/openservice/functions/getSourceMetaMap.js +0 -52
  52. package/dist/features/openservice/functions/getTicketObject.d.ts +0 -9
  53. package/dist/features/openservice/functions/getTicketObject.js +0 -31
  54. package/dist/features/openservice/functions/saveDescription.d.ts +0 -9
  55. package/dist/features/openservice/functions/saveDescription.js +0 -12
  56. package/dist/features/openservice/functions/saveDowntime.d.ts +0 -8
  57. package/dist/features/openservice/functions/saveDowntime.js +0 -32
  58. package/dist/features/openservice/functions/saveDuedate.d.ts +0 -13
  59. package/dist/features/openservice/functions/saveDuedate.js +0 -39
  60. package/dist/features/openservice/functions/saveFrequency.d.ts +0 -8
  61. package/dist/features/openservice/functions/saveFrequency.js +0 -32
  62. package/dist/features/openservice/functions/saveIssuecategory.d.ts +0 -14
  63. package/dist/features/openservice/functions/saveIssuecategory.js +0 -53
  64. package/dist/features/openservice/functions/saveMaterial.d.ts +0 -9
  65. package/dist/features/openservice/functions/saveMaterial.js +0 -18
  66. package/dist/features/openservice/functions/saveMessage.d.ts +0 -10
  67. package/dist/features/openservice/functions/saveMessage.js +0 -54
  68. package/dist/features/openservice/functions/savePriority.d.ts +0 -8
  69. package/dist/features/openservice/functions/savePriority.js +0 -32
  70. package/dist/features/openservice/functions/saveProject.d.ts +0 -8
  71. package/dist/features/openservice/functions/saveProject.js +0 -98
  72. package/dist/features/openservice/functions/saveRestriction.d.ts +0 -8
  73. package/dist/features/openservice/functions/saveRestriction.js +0 -32
  74. package/dist/features/openservice/functions/saveSource.d.ts +0 -8
  75. package/dist/features/openservice/functions/saveSource.js +0 -32
  76. package/dist/features/openservice/functions/saveState.d.ts +0 -14
  77. package/dist/features/openservice/functions/saveState.js +0 -52
  78. package/dist/features/openservice/functions/saveTicketMeta.d.ts +0 -9
  79. package/dist/features/openservice/functions/saveTicketMeta.js +0 -32
  80. package/dist/features/openservice/functions/saveTicketTitle.d.ts +0 -8
  81. package/dist/features/openservice/functions/saveTicketTitle.js +0 -28
  82. package/dist/features/openservice/issuecategory/initIssuecategory.d.ts +0 -5
  83. package/dist/features/openservice/issuecategory/initIssuecategory.js +0 -42
  84. package/dist/features/openservice/kanbanState/initKanbanStates.d.ts +0 -21
  85. package/dist/features/openservice/kanbanState/initKanbanStates.js +0 -187
  86. package/dist/features/openservice/messages/initMessages.d.ts +0 -8
  87. package/dist/features/openservice/messages/initMessages.js +0 -466
  88. package/dist/features/openservice/messages/removeLatestMessage.d.ts +0 -9
  89. package/dist/features/openservice/messages/removeLatestMessage.js +0 -30
  90. package/dist/features/openservice/schedules/calendarSync/Access.d.ts +0 -12
  91. package/dist/features/openservice/schedules/calendarSync/CalendarManager.d.ts +0 -49
  92. package/dist/features/openservice/schedules/calendarSync/CalendarManager.js +0 -211
  93. package/dist/features/openservice/schedules/calendarSync/CalendarSyncPoller.d.ts +0 -25
  94. package/dist/features/openservice/schedules/calendarSync/CalendarSyncPoller.js +0 -202
  95. package/dist/features/openservice/schedules/calendarSync/ConfigValues.d.ts +0 -13
  96. package/dist/features/openservice/schedules/calendarSync/ConfigValues.js +0 -2
  97. package/dist/features/openservice/schedules/calendarSync/Event.js +0 -9
  98. package/dist/features/openservice/schedules/calendarSync/calendarMetaHelper.d.ts +0 -76
  99. package/dist/features/openservice/schedules/calendarSync/calendarMetaHelper.js +0 -119
  100. package/dist/features/openservice/schedules/calendarSync/eventToSchedule.d.ts +0 -37
  101. package/dist/features/openservice/schedules/calendarSync/eventToSchedule.js +0 -103
  102. package/dist/features/openservice/schedules/calendarSync/scheduleToEvent.d.ts +0 -9
  103. package/dist/features/openservice/schedules/calendarSync/scheduleToEvent.js +0 -122
  104. package/dist/features/openservice/schedules/checkStatus.d.ts +0 -9
  105. package/dist/features/openservice/schedules/checkStatus.js +0 -31
  106. package/dist/features/openservice/schedules/getScheduleLink.d.ts +0 -10
  107. package/dist/features/openservice/schedules/getScheduleLink.js +0 -32
  108. package/dist/features/openservice/schedules/initSchedulesFeature.d.ts +0 -5
  109. package/dist/features/openservice/schedules/initSchedulesFeature.js +0 -32
  110. package/dist/features/openservice/schedules/reassignScheduleExecutions.d.ts +0 -5
  111. package/dist/features/openservice/schedules/reassignScheduleExecutions.js +0 -39
  112. package/dist/features/openservice/ticket/getTicketLink.d.ts +0 -9
  113. package/dist/features/openservice/ticket/getTicketLink.js +0 -32
  114. package/dist/features/openservice/ticket/initTicket.d.ts +0 -4
  115. package/dist/features/openservice/ticket/initTicket.js +0 -56
  116. package/dist/features/openservice/types/FetchOptions.d.ts +0 -4
  117. package/dist/features/openservice/types/FetchOptions.js +0 -2
  118. package/dist/features/openservice/types/Material.d.ts +0 -10
  119. package/dist/features/openservice/types/OpenserviceTranslationKeys.d.ts +0 -102
  120. package/dist/features/openservice/types/OpenserviceTranslationKeys.js +0 -106
  121. package/dist/features/openservice/types/SaveValues.d.ts +0 -33
  122. package/dist/features/openservice/types/SaveValues.js +0 -2
  123. package/dist/features/openservice/types/TicketData.d.ts +0 -22
  124. package/dist/features/openservice/types/TicketData.js +0 -2
  125. package/dist/features/openware/types/OpenWareTicketObject.d.ts +0 -14
  126. package/dist/features/openware/types/OpenWareTicketObject.js +0 -2
  127. package/dist/functions/openinc-openservice-get-sourcemeta-map.d.ts +0 -1
  128. package/dist/functions/openinc-openservice-get-sourcemeta-map.js +0 -41
  129. package/dist/functions/openinc-openservice-save-ticket-data.d.ts +0 -6
  130. package/dist/functions/openinc-openservice-save-ticket-data.js +0 -517
  131. package/dist/functions/openinc-openservice-ticket-data.d.ts +0 -44
  132. package/dist/functions/openinc-openservice-ticket-data.js +0 -380
  133. package/dist/helper/removeShorltyPreviousEntry.d.ts +0 -2
  134. package/dist/helper/removeShorltyPreviousEntry.js +0 -31
  135. package/dist/hooks/Maintenance_Downtime.d.ts +0 -1
  136. package/dist/hooks/Maintenance_Downtime.js +0 -106
  137. package/dist/hooks/Maintenance_Duedate.d.ts +0 -1
  138. package/dist/hooks/Maintenance_Duedate.js +0 -128
  139. package/dist/hooks/Maintenance_Frequency.d.ts +0 -1
  140. package/dist/hooks/Maintenance_Frequency.js +0 -106
  141. package/dist/hooks/Maintenance_Issuecategory.d.ts +0 -1
  142. package/dist/hooks/Maintenance_Issuecategory.js +0 -19
  143. package/dist/hooks/Maintenance_Item.d.ts +0 -1
  144. package/dist/hooks/Maintenance_Item.js +0 -17
  145. package/dist/hooks/Maintenance_Kanban_State.d.ts +0 -1
  146. package/dist/hooks/Maintenance_Kanban_State.js +0 -17
  147. package/dist/hooks/Maintenance_Media.d.ts +0 -1
  148. package/dist/hooks/Maintenance_Media.js +0 -17
  149. package/dist/hooks/Maintenance_Message.d.ts +0 -1
  150. package/dist/hooks/Maintenance_Message.js +0 -20
  151. package/dist/hooks/Maintenance_Order.d.ts +0 -1
  152. package/dist/hooks/Maintenance_Order.js +0 -17
  153. package/dist/hooks/Maintenance_Priority.d.ts +0 -1
  154. package/dist/hooks/Maintenance_Priority.js +0 -110
  155. package/dist/hooks/Maintenance_Project.d.ts +0 -1
  156. package/dist/hooks/Maintenance_Project.js +0 -30
  157. package/dist/hooks/Maintenance_Restriction.d.ts +0 -1
  158. package/dist/hooks/Maintenance_Restriction.js +0 -113
  159. package/dist/hooks/Maintenance_Schedule.d.ts +0 -1
  160. package/dist/hooks/Maintenance_Schedule.js +0 -146
  161. package/dist/hooks/Maintenance_Schedule_Execution.d.ts +0 -1
  162. package/dist/hooks/Maintenance_Schedule_Execution.js +0 -118
  163. package/dist/hooks/Maintenance_Schedule_Execution_Step.d.ts +0 -1
  164. package/dist/hooks/Maintenance_Schedule_Execution_Step.js +0 -17
  165. package/dist/hooks/Maintenance_Schedule_Step.d.ts +0 -1
  166. package/dist/hooks/Maintenance_Schedule_Step.js +0 -26
  167. package/dist/hooks/Maintenance_Schedule_Template.d.ts +0 -1
  168. package/dist/hooks/Maintenance_Schedule_Template.js +0 -92
  169. package/dist/hooks/Maintenance_Source_File.d.ts +0 -1
  170. package/dist/hooks/Maintenance_Source_File.js +0 -17
  171. package/dist/hooks/Maintenance_Ticket.d.ts +0 -1
  172. package/dist/hooks/Maintenance_Ticket.js +0 -15
  173. package/dist/hooks/Maintenance_Ticket_Assignment.d.ts +0 -1
  174. package/dist/hooks/Maintenance_Ticket_Assignment.js +0 -17
  175. package/dist/hooks/Maintenance_Ticket_FormConfig.d.ts +0 -1
  176. package/dist/hooks/Maintenance_Ticket_FormConfig.js +0 -17
  177. package/dist/hooks/Maintenance_Ticket_Issuecategory.d.ts +0 -1
  178. package/dist/hooks/Maintenance_Ticket_Issuecategory.js +0 -109
  179. package/dist/hooks/Maintenance_Ticket_Kanban_State.d.ts +0 -1
  180. package/dist/hooks/Maintenance_Ticket_Kanban_State.js +0 -134
  181. package/dist/hooks/Maintenance_Ticket_Kanban_State_Current.d.ts +0 -1
  182. package/dist/hooks/Maintenance_Ticket_Kanban_State_Current.js +0 -15
  183. package/dist/hooks/Maintenance_Ticket_Material.d.ts +0 -4
  184. package/dist/hooks/Maintenance_Ticket_Material.js +0 -104
  185. package/dist/hooks/Maintenance_Ticket_Project.d.ts +0 -1
  186. package/dist/hooks/Maintenance_Ticket_Project.js +0 -88
  187. package/dist/hooks/Maintenance_Ticket_QR_Code.d.ts +0 -1
  188. package/dist/hooks/Maintenance_Ticket_QR_Code.js +0 -17
  189. package/dist/hooks/Maintenance_Ticket_Source.d.ts +0 -1
  190. package/dist/hooks/Maintenance_Ticket_Source.js +0 -124
  191. package/dist/hooks/Maintenance_Ticket_Title.d.ts +0 -1
  192. package/dist/hooks/Maintenance_Ticket_Title.js +0 -107
  193. package/dist/i18n/de-DE/maintenance.json +0 -16
  194. package/dist/i18n/en-US/maintenance.json +0 -16
  195. package/dist/scripts/seed-v1-testdata.d.ts +0 -43
  196. package/dist/scripts/seed-v1-testdata.js +0 -982
  197. /package/dist/features/openservice/{schedules → serviceSchedules}/calendarSync/Access.js +0 -0
@@ -4,39 +4,65 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ServiceCalendarSyncPoller = exports.CALENDAR_SYNC_CONTEXT_FLAG = void 0;
7
+ const openservice_shared_1 = require("@opendash/openservice-shared");
7
8
  const crypto_1 = require("crypto");
8
9
  const node_1 = __importDefault(require("parse/node"));
9
- const CalendarManager_js_1 = require("../../schedules/calendarSync/CalendarManager.js");
10
10
  const index_js_1 = require("../../../../types/index.js");
11
+ const CalendarManager_js_1 = require("./CalendarManager.js");
11
12
  const eventToPlan_js_1 = require("./eventToPlan.js");
13
+ const inboundChanges_js_1 = require("./inboundChanges.js");
14
+ const planLock_js_1 = require("./planLock.js");
12
15
  const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
16
+ const ServiceSyncTypes_js_1 = require("./ServiceSyncTypes.js");
13
17
  const syncPlanExceptions_js_1 = require("./syncPlanExceptions.js");
14
18
  /**
15
- * Marker on a save that came from the calendar.
16
- *
17
- * The outbound side (`syncPlanToCalendar`, called from the `Service_Schedule`
18
- * afterSave hook) checks it and stays quiet — otherwise every inbound change
19
- * would be written straight back to Outlook, produce a new `changeKey`, come
20
- * back through the delta feed as a foreign change, and loop forever. The stored
21
- * `changeKey` is the second line of defence; this is the first, and unlike v1's
22
- * `!master` check it does not disable outbound sync for every other
23
- * master-key writer (the scheduler pausing a plan, a migration, a script).
19
+ * Marker on a save that came from the calendar. The outbound side (the
20
+ * `Service_Schedule` afterSave hook) checks it and stays quiet, so an Outlook
21
+ * edit is not written straight back to Outlook.
24
22
  */
25
23
  exports.CALENDAR_SYNC_CONTEXT_FLAG = "fromCalendarSync";
24
+ /** New plans per pass; the rest follow on the next one. */
25
+ const MAX_IMPORTS_PER_PASS = 20;
26
+ /** Categorised appointments read per pass, linked ones included. */
27
+ const MAX_CATEGORISED_READ = 1000;
28
+ /**
29
+ * Circuit breaker. A pass that wants to write more plans than this is not
30
+ * syncing edits, it is running away — the poller stops itself and says so.
31
+ */
32
+ const MAX_PLAN_WRITES_PER_PASS = 50;
33
+ /**
34
+ * The same plan rewritten from Outlook in this many passes in a row is a loop
35
+ * in the making, not someone editing every few minutes: it is left alone.
36
+ */
37
+ const SUSPECT_STREAK = 3;
38
+ class CircuitBreakerTripped extends Error {
39
+ }
26
40
  /**
27
- * Pulls Outlook changes into open.SERVICE **v2** maintenance plans.
41
+ * Reads Outlook back into open.SERVICE maintenance plans, for one connection.
42
+ *
43
+ * Each pass does two bounded things, both on documented Graph v1.0 endpoints:
44
+ *
45
+ * 1. **Linked events** — every event a plan is linked to is read (20 per
46
+ * `$batch`) and compared with the snapshot of what we last wrote or saw
47
+ * (`inboundChanges.ts`). Only what differs is applied; a deleted or
48
+ * cancelled event archives its plan.
49
+ * 2. **New plans** — appointments carrying the import category (default
50
+ * `open.SERVICE`) that are not linked yet become plans. Nothing else in the
51
+ * mailbox is looked at. Our own events carry no category, so the sync never
52
+ * imports what it wrote itself.
28
53
  *
29
- * One poller per configured connection, driven by the Graph *delta* feed: the
30
- * first call reads the whole calendar, each later call only what changed, and
31
- * the cursor lives in the Config row so a restart resumes instead of
32
- * re-importing. The v1 poller does the same for `Maintenance_Schedule` from the
33
- * same connection — the two keep separate cursors (`delta_link` vs
34
- * `delta_link_v2`) so neither consumes the other's changes.
54
+ * This replaces the delta-feed poller, which read the entire mailbox through
55
+ * an endpoint that is beta-only in Graph (`/events/delta`), imported every
56
+ * appointment in it, and restarted from scratch whenever a pass did not finish.
35
57
  */
36
58
  class ServiceCalendarSyncPoller {
37
59
  timer = null;
38
60
  polling = false;
61
+ backoffUntil = 0;
39
62
  config;
63
+ writes = 0;
64
+ /** Plan id → consecutive passes in which Outlook rewrote it. */
65
+ streaks = new Map();
40
66
  constructor(config) {
41
67
  this.config = config;
42
68
  }
@@ -52,6 +78,9 @@ class ServiceCalendarSyncPoller {
52
78
  userMail: values.user_email,
53
79
  });
54
80
  }
81
+ get tenant() {
82
+ return this.config.get("tenant");
83
+ }
55
84
  start(intervalMs = 5 * 60 * 1000) {
56
85
  const valid = this.manager.isValid;
57
86
  if (valid !== true) {
@@ -67,85 +96,248 @@ class ServiceCalendarSyncPoller {
67
96
  clearInterval(this.timer);
68
97
  this.timer = null;
69
98
  }
70
- /**
71
- * One pass over the delta feed — never two at once.
72
- *
73
- * A pass costs a Graph round trip per changed event (and a token request for
74
- * each of them), so it can outlast the interval. A second pass starting on
75
- * top of the first reads the same delta cursor, processes the same events and
76
- * writes the same plans again — which is how a slow calendar turns into a
77
- * stream of saves.
78
- */
99
+ /** One pass — never two at once, and not while Graph asked us to wait. */
79
100
  async poll() {
80
- if (this.polling) {
81
- console.warn("[ServiceCalendarSync] Previous pass still running — skipping this tick");
101
+ if (this.polling || Date.now() < this.backoffUntil)
82
102
  return;
83
- }
84
103
  this.polling = true;
85
104
  try {
86
105
  await this.runPoll();
87
106
  }
107
+ catch (error) {
108
+ if (error instanceof CalendarManager_js_1.GraphThrottledError) {
109
+ this.backoffUntil = Date.now() + error.retryAfterSeconds * 1000;
110
+ console.warn(`[ServiceCalendarSync] Throttled by Graph — pausing for ${error.retryAfterSeconds}s`);
111
+ }
112
+ else if (error instanceof CircuitBreakerTripped) {
113
+ this.stop();
114
+ console.error(`[ServiceCalendarSync] STOPPED for config ${this.config.id}: ${error.message} ` +
115
+ "Inbound sync stays off until the next server start. Plans are still written to Outlook.");
116
+ }
117
+ else {
118
+ throw error;
119
+ }
120
+ }
88
121
  finally {
89
122
  this.polling = false;
90
123
  }
91
124
  }
92
125
  async runPoll() {
93
- const result = await this.manager.fetchDelta(await this.loadDeltaLink());
94
- if (!result) {
95
- console.error("[ServiceCalendarSync] Could not fetch the calendar delta");
126
+ // The row is also the admin form's storage: re-read for the kill switch
127
+ // and for changed credentials.
128
+ this.config = await this.config.fetch({ useMasterKey: true });
129
+ const values = this.values;
130
+ if (values.inbound_disabled)
131
+ return;
132
+ const manager = this.manager;
133
+ if (manager.isValid !== true)
134
+ return;
135
+ // Without a tenant the meta lookup below is not scoped: this mailbox would
136
+ // be checked for every tenant's events, and their absence read as
137
+ // deletions.
138
+ if (!this.tenant) {
139
+ console.error(`[ServiceCalendarSync] Config ${this.config.id} has no tenant — inbound sync skipped`);
96
140
  return;
97
141
  }
98
- for (const event of result.events) {
99
- try {
100
- await this.processEvent(event);
101
- }
102
- catch (error) {
103
- // One unusable event must not cost us the whole batch — and not the
104
- // delta cursor either, or it would be retried forever.
105
- console.error("[ServiceCalendarSync] Event could not be processed:", event.id, error);
142
+ this.writes = 0;
143
+ const rewritten = new Set();
144
+ await this.reconcileLinked(manager, rewritten);
145
+ await this.importCategorised(manager, values);
146
+ for (const planId of [...this.streaks.keys()]) {
147
+ if (!rewritten.has(planId))
148
+ this.streaks.delete(planId);
149
+ }
150
+ }
151
+ // --- 1. linked events ------------------------------------------------------
152
+ async reconcileLinked(manager, rewritten) {
153
+ const metas = await (0, serviceCalendarMeta_js_1.findMetasForTenant)(this.tenant);
154
+ if (metas.length === 0)
155
+ return;
156
+ const series = new Map(); // event id → plan id
157
+ const moved = new Map(); // stand-in event id → plan id
158
+ for (const meta of metas) {
159
+ const planId = meta.get("entryObjectId");
160
+ const values = (0, serviceCalendarMeta_js_1.metaValues)(meta);
161
+ if (!planId || !values?.microsoftCalendarEventId)
162
+ continue;
163
+ series.set(values.microsoftCalendarEventId, planId);
164
+ for (const entry of values.microsoftCalendarExceptions?.moved ?? []) {
165
+ moved.set(entry.eventId, planId);
106
166
  }
107
167
  }
108
- await this.saveDeltaLink(result.deltaLink);
168
+ const readAt = new Date();
169
+ const results = await manager.fetchEventsBatch([
170
+ ...series.keys(),
171
+ ...moved.keys(),
172
+ ]);
173
+ if (!results) {
174
+ console.error("[ServiceCalendarSync] Could not read the linked events");
175
+ return;
176
+ }
177
+ // Most linked events gone at once is not a user tidying up their
178
+ // calendar — it is a changed mailbox (`user_email`) or app permission.
179
+ // Archiving on that would retire the tenant's plans wholesale.
180
+ const missing = [...series.keys()].filter((id) => results.get(id) === null);
181
+ if (missing.length >= 10 && missing.length > series.size / 2) {
182
+ console.error(`[ServiceCalendarSync] ${missing.length} of ${series.size} linked events not found in ` +
183
+ `${this.values.user_email} — nothing archived. Check the mailbox in config ${this.config.id}.`);
184
+ return;
185
+ }
186
+ for (const [eventId, planId] of series) {
187
+ if (!results.has(eventId))
188
+ continue; // unreadable, not deleted
189
+ await (0, planLock_js_1.withPlanLock)(planId, () => this.applyEvent(planId, eventId, results.get(eventId), readAt, rewritten));
190
+ }
191
+ // A moved date's stand-in deleted in Outlook says nothing about the plan;
192
+ // it is unlinked, so the next save writes it again.
193
+ for (const [eventId, planId] of moved) {
194
+ if (results.get(eventId) !== null)
195
+ continue;
196
+ await (0, planLock_js_1.withPlanLock)(planId, () => (0, syncPlanExceptions_js_1.isMovedEvent)(eventId, { removed: true }));
197
+ }
109
198
  }
110
- async processEvent(event) {
111
- if (event["@removed"]) {
112
- await this.handleRemoved(event.id);
199
+ async applyEvent(planId, eventId, event, readAt, rewritten) {
200
+ // Re-read under the lock: the outbound side may have relinked or rewritten
201
+ // the entry since the batch went out. If it did, what we read is older
202
+ // than what it wrote — applying it would revert the user's change. The
203
+ // next pass reads the event again.
204
+ const meta = await (0, serviceCalendarMeta_js_1.findMetaForEvent)(eventId);
205
+ if (!meta || meta.get("entryObjectId") !== planId)
206
+ return;
207
+ if (meta.updatedAt && meta.updatedAt > readAt)
208
+ return;
209
+ if (!event || event.isCancelled) {
210
+ await this.archivePlan(meta, eventId);
113
211
  return;
114
212
  }
115
- // An "exception" is a single moved or edited occurrence of a series. The
116
- // plan's own `cadenceExceptions` could hold that, but Graph does not tell
117
- // us *which* occurrence was moved in a form we can map back reliably — and
118
- // a wrong exception silently moves a maintenance date. The series master
119
- // carries the recurrence; exceptions are left to Outlook.
120
- if (event.type === "exception")
213
+ const values = (0, serviceCalendarMeta_js_1.metaValues)(meta);
214
+ const knownKey = values?.microsoftCalendarChangeKey;
215
+ if (event.changeKey && event.changeKey === knownKey)
121
216
  return;
122
- const meta = await (0, serviceCalendarMeta_js_1.findMetaForEvent)(event.id);
123
- if (!meta) {
124
- // The stand-in for a moved date (`syncPlanExceptions`): ours, but not a
125
- // plan's series — importing it would duplicate the plan. What happens to
126
- // it in Outlook stays in Outlook, like a moved occurrence.
127
- if (await (0, syncPlanExceptions_js_1.isMovedEvent)(event.id))
128
- return;
129
- // Delta payloads are partial — fetch the whole event before creating.
130
- const full = await this.manager.fetchEvent(event.id);
131
- if (full)
132
- await this.createPlan(full);
217
+ const changes = (0, inboundChanges_js_1.inboundChanges)(values?.microsoftCalendarEvent, event);
218
+ if ((0, inboundChanges_js_1.hasChanges)(changes)) {
219
+ const streak = (this.streaks.get(planId) ?? 0) + 1;
220
+ this.streaks.set(planId, streak);
221
+ rewritten.add(planId);
222
+ if (streak >= SUSPECT_STREAK) {
223
+ console.error(`[ServiceCalendarSync] Plan ${planId} changed from Outlook in ${streak} passes in a row — ` +
224
+ `not applied (loop suspected). Event ${eventId}, changes: ${JSON.stringify(changes)}`);
225
+ }
226
+ else {
227
+ await this.updatePlan(planId, event, changes);
228
+ }
229
+ }
230
+ // The event as it is now becomes the base for the next comparison —
231
+ // also when nothing was applied, or the same change would be seen again.
232
+ await (0, serviceCalendarMeta_js_1.updateChangeKey)(meta, event.changeKey ?? knownKey ?? "", event);
233
+ }
234
+ /**
235
+ * Apply what changed in Outlook — and only that. A plan field whose
236
+ * counterpart did not change is not touched, so the lossy parts of the
237
+ * mapping (time of day, reminder minutes vs. rule days) never rewrite it.
238
+ */
239
+ async updatePlan(planId, event, changes) {
240
+ const fields = (0, eventToPlan_js_1.eventToPlanFields)(event);
241
+ if (!fields)
133
242
  return;
243
+ const plan = await new node_1.default.Query(index_js_1.Service_Schedule)
244
+ .include("equipment")
245
+ .get(planId, { useMasterKey: true });
246
+ if (changes.subject) {
247
+ if (plan.get("title") !== fields.title)
248
+ plan.set("title", fields.title);
249
+ // A subject that names a different machine moves the plan; one without
250
+ // the prefix leaves the assignment alone.
251
+ const current = plan.get("equipment");
252
+ if (fields.equipmentName && current?.get("label") !== fields.equipmentName) {
253
+ const equipment = await this.findEquipmentByLabel(fields.equipmentName);
254
+ if (equipment && equipment.id !== current?.id) {
255
+ plan.set("equipment", equipment);
256
+ }
257
+ }
258
+ }
259
+ if (changes.timing && !sameValue(plan.get("cadence"), fields.cadence)) {
260
+ plan.set("cadence", fields.cadence);
134
261
  }
135
- const knownChangeKey = (0, serviceCalendarMeta_js_1.metaValues)(meta)?.microsoftCalendarChangeKey;
136
- if (event.changeKey && knownChangeKey === event.changeKey) {
137
- return; // Our own write, echoed back by the delta feed.
262
+ if (changes.reminder) {
263
+ const notifications = (0, eventToPlan_js_1.mergeReminderRule)(plan.get("notifications"), fields.notification);
264
+ if (!sameValue(plan.get("notifications"), notifications)) {
265
+ plan.set("notifications", notifications);
266
+ }
138
267
  }
139
- // Delta payloads are partial, and `changeKey` is one of the properties they
140
- // may leave out. Without it the check above cannot recognise our own write,
141
- // and the one at the end of `updatePlan` stores nothing either — so the
142
- // stored key never advances and the plan is rewritten on every pass, for as
143
- // long as the feed keeps mentioning the event. The full event always
144
- // carries the key, and `updatePlan` needs the full event anyway.
145
- const full = (await this.manager.fetchEvent(event.id)) ?? event;
146
- if (full.changeKey && knownChangeKey === full.changeKey)
268
+ if (!plan.dirty())
147
269
  return;
148
- await this.updatePlan(meta, full);
270
+ this.countWrite();
271
+ await plan.save(null, {
272
+ useMasterKey: true,
273
+ context: { [exports.CALENDAR_SYNC_CONTEXT_FLAG]: true },
274
+ });
275
+ console.log(`[ServiceCalendarSync] Plan ${planId} updated from Outlook (${Object.entries(changes)
276
+ .filter(([, changed]) => changed)
277
+ .map(([aspect]) => aspect)
278
+ .join(", ")})`);
279
+ }
280
+ /**
281
+ * A deleted or cancelled appointment archives the plan — never destroys it:
282
+ * executions document work against it. The link goes, so the plan can be
283
+ * linked to a new event later.
284
+ */
285
+ async archivePlan(meta, eventId) {
286
+ const planId = meta.get("entryObjectId");
287
+ if (planId) {
288
+ try {
289
+ const plan = await new node_1.default.Query(index_js_1.Service_Schedule).get(planId, {
290
+ useMasterKey: true,
291
+ });
292
+ if (!plan.get("deletedAt")) {
293
+ this.countWrite();
294
+ plan.set("active", false);
295
+ plan.set("deletedAt", new Date());
296
+ await plan.save(null, {
297
+ useMasterKey: true,
298
+ context: { [exports.CALENDAR_SYNC_CONTEXT_FLAG]: true },
299
+ });
300
+ console.log(`[ServiceCalendarSync] Plan ${planId} archived — its event ${eventId} is gone from Outlook`);
301
+ }
302
+ }
303
+ catch (error) {
304
+ if (error instanceof CircuitBreakerTripped)
305
+ throw error;
306
+ console.error(`[ServiceCalendarSync] Could not archive plan ${planId} of deleted event ${eventId}:`, error);
307
+ }
308
+ }
309
+ await meta.destroy({ useMasterKey: true });
310
+ }
311
+ // --- 2. new plans from categorised appointments -----------------------------
312
+ async importCategorised(manager, values) {
313
+ const category = values.import_category ?? ServiceSyncTypes_js_1.DEFAULT_IMPORT_CATEGORY;
314
+ if (!category)
315
+ return;
316
+ const events = await manager.listEventsWithCategory(category, MAX_CATEGORISED_READ);
317
+ if (!events)
318
+ return;
319
+ let imported = 0;
320
+ for (const event of events) {
321
+ if (imported >= MAX_IMPORTS_PER_PASS)
322
+ break;
323
+ if (!event.id || event.isCancelled)
324
+ continue;
325
+ if (event.type === "occurrence" || event.type === "exception")
326
+ continue;
327
+ if (await (0, serviceCalendarMeta_js_1.findMetaForEvent)(event.id))
328
+ continue;
329
+ if (await (0, syncPlanExceptions_js_1.isMovedEvent)(event.id))
330
+ continue;
331
+ try {
332
+ await this.createPlan(event);
333
+ imported++;
334
+ }
335
+ catch (error) {
336
+ if (error instanceof CircuitBreakerTripped)
337
+ throw error;
338
+ console.error(`[ServiceCalendarSync] Event ${event.id} could not be imported:`, error);
339
+ }
340
+ }
149
341
  }
150
342
  async createPlan(event) {
151
343
  const fields = (0, eventToPlan_js_1.eventToPlanFields)(event);
@@ -153,18 +345,20 @@ class ServiceCalendarSyncPoller {
153
345
  console.warn(`[ServiceCalendarSync] Event ${event.id} has no usable start — skipped`);
154
346
  return;
155
347
  }
156
- const tenant = this.config.get("tenant");
157
- const equipment = await this.resolveEquipment(fields.equipmentName, tenant);
348
+ const tenant = this.tenant;
349
+ const equipment = await this.resolveEquipment(fields.equipmentName);
158
350
  const plan = new index_js_1.Service_Schedule();
159
351
  plan.set("title", fields.title);
160
352
  plan.set("active", true);
161
353
  plan.set("tenant", tenant);
162
354
  plan.set("cadence", fields.cadence);
355
+ // Only here, on import: later syncs, unlinking or a rebuilt series (new
356
+ // event id) leave it as it is — it says where the plan came from.
357
+ plan.set("origin", (0, openservice_shared_1.outlookOrigin)(event.id));
163
358
  if (equipment)
164
359
  plan.set("equipment", equipment);
165
360
  // A plan needs at least one step to be executable. The event's note becomes
166
- // its description, so what someone wrote in Outlook is not lost — the
167
- // checklist proper is then built in the plan editor.
361
+ // its description, so what someone wrote in Outlook is not lost.
168
362
  plan.set("steps", [
169
363
  {
170
364
  id: (0, crypto_1.randomUUID)(),
@@ -175,6 +369,7 @@ class ServiceCalendarSyncPoller {
175
369
  },
176
370
  ]);
177
371
  plan.set("notifications", (0, eventToPlan_js_1.mergeReminderRule)([], fields.notification));
372
+ this.countWrite();
178
373
  await plan.save(null, {
179
374
  useMasterKey: true,
180
375
  context: { [exports.CALENDAR_SYNC_CONTEXT_FLAG]: true },
@@ -183,98 +378,17 @@ class ServiceCalendarSyncPoller {
183
378
  console.log(`[ServiceCalendarSync] Created plan ${plan.id} from event ${event.id}` +
184
379
  (equipment ? ` (machine ${equipment.id})` : " (no machine)"));
185
380
  }
186
- /**
187
- * Bring one plan in line with its event — and touch it only if it is not
188
- * already in line.
189
- *
190
- * **Why the comparisons.** `Parse.Object.set()` marks a field dirty whether or
191
- * not the value actually changed, so applying the event's fields
192
- * unconditionally means a save on every pass: a new `updatedAt`, the whole
193
- * `afterSave` chain (ACL sync, calendar check) and a log line — for an event
194
- * nobody touched. Re-reading the same event has to be a no-op, not a write.
195
- *
196
- * `event` is the **full** event, not a delta payload: those are partial, and
197
- * an unchanged subject arrives as `undefined` there, which would wipe the
198
- * plan's title.
199
- */
200
- async updatePlan(meta, event) {
201
- const planId = meta.get("entryObjectId");
202
- if (!planId)
203
- return;
204
- const fields = (0, eventToPlan_js_1.eventToPlanFields)(event);
205
- if (!fields)
206
- return;
207
- const plan = await new node_1.default.Query(index_js_1.Service_Schedule)
208
- .include("equipment")
209
- .get(planId, { useMasterKey: true });
210
- if (plan.get("title") !== fields.title)
211
- plan.set("title", fields.title);
212
- if (!sameValue(plan.get("cadence"), fields.cadence)) {
213
- plan.set("cadence", fields.cadence);
214
- }
215
- const notifications = (0, eventToPlan_js_1.mergeReminderRule)(plan.get("notifications"), fields.notification);
216
- if (!sameValue(plan.get("notifications"), notifications)) {
217
- plan.set("notifications", notifications);
381
+ // --- helpers -----------------------------------------------------------------
382
+ countWrite() {
383
+ this.writes++;
384
+ if (this.writes > MAX_PLAN_WRITES_PER_PASS) {
385
+ throw new CircuitBreakerTripped(`more than ${MAX_PLAN_WRITES_PER_PASS} plan writes in one pass.`);
218
386
  }
219
- // The machine only changes if the subject actually names a different one —
220
- // a subject without the prefix leaves the existing assignment alone rather
221
- // than falling back to the configured default and moving the plan.
222
- const current = plan.get("equipment");
223
- if (fields.equipmentName &&
224
- current?.get("label") !== fields.equipmentName) {
225
- const equipment = await this.findEquipmentByLabel(fields.equipmentName, this.config.get("tenant"));
226
- if (equipment && equipment.id !== current?.id) {
227
- plan.set("equipment", equipment);
228
- }
229
- }
230
- if (plan.dirty()) {
231
- await plan.save(null, {
232
- useMasterKey: true,
233
- context: { [exports.CALENDAR_SYNC_CONTEXT_FLAG]: true },
234
- });
235
- }
236
- // Stored even when nothing changed: this is what tells the next pass that
237
- // this version of the event has been seen.
238
- if (event.changeKey)
239
- await (0, serviceCalendarMeta_js_1.updateChangeKey)(meta, event.changeKey, event);
240
- }
241
- /**
242
- * A deleted appointment archives the plan — it never destroys it.
243
- *
244
- * Executions document that work happened; deleting the plan they point at
245
- * would strand that history (the `beforeDelete` hook refuses it, too). The
246
- * meta entry goes, so the same plan can be linked to a new event later.
247
- */
248
- async handleRemoved(eventId) {
249
- const meta = await (0, serviceCalendarMeta_js_1.findMetaForEvent)(eventId);
250
- if (!meta) {
251
- // A moved date's stand-in going away says nothing about the plan.
252
- await (0, syncPlanExceptions_js_1.isMovedEvent)(eventId, { removed: true });
253
- return;
254
- }
255
- const planId = meta.get("entryObjectId");
256
- if (planId) {
257
- try {
258
- const plan = await new node_1.default.Query(index_js_1.Service_Schedule).get(planId, {
259
- useMasterKey: true,
260
- });
261
- plan.set("active", false);
262
- plan.set("deletedAt", new Date());
263
- await plan.save(null, {
264
- useMasterKey: true,
265
- context: { [exports.CALENDAR_SYNC_CONTEXT_FLAG]: true },
266
- });
267
- }
268
- catch (error) {
269
- console.error(`[ServiceCalendarSync] Could not archive plan ${planId} of deleted event ${eventId}:`, error);
270
- }
271
- }
272
- await meta.destroy({ useMasterKey: true });
273
387
  }
274
388
  /** The machine named in the subject, else the configured fallback. */
275
- async resolveEquipment(label, tenant) {
389
+ async resolveEquipment(label) {
276
390
  if (label) {
277
- const found = await this.findEquipmentByLabel(label, tenant);
391
+ const found = await this.findEquipmentByLabel(label);
278
392
  if (found)
279
393
  return found;
280
394
  console.warn(`[ServiceCalendarSync] No machine named "${label}" — falling back to the default`);
@@ -286,37 +400,20 @@ class ServiceCalendarSyncPoller {
286
400
  .equalTo("objectId", defaultId)
287
401
  .first({ useMasterKey: true })) ?? undefined);
288
402
  }
289
- async findEquipmentByLabel(label, tenant) {
403
+ async findEquipmentByLabel(label) {
290
404
  const query = new node_1.default.Query(index_js_1.Service_Equipment).equalTo("label", label);
405
+ const tenant = this.tenant;
291
406
  if (tenant)
292
407
  query.equalTo("tenant", tenant);
293
408
  query.notEqualTo("deleted", true);
294
409
  return (await query.first({ useMasterKey: true })) ?? undefined;
295
410
  }
296
- /**
297
- * The cursor is re-read from the Config row on every tick, and written back
298
- * after it: the row is also the admin form's storage, so it can change
299
- * underneath us.
300
- */
301
- async loadDeltaLink() {
302
- this.config = await this.config.fetch({ useMasterKey: true });
303
- return this.values.delta_link_v2;
304
- }
305
- async saveDeltaLink(link) {
306
- this.config = await this.config.fetch({ useMasterKey: true });
307
- const values = this.values;
308
- values.delta_link_v2 = link;
309
- this.config.set("value", JSON.stringify(values));
310
- await this.config.save(null, { useMasterKey: true });
311
- }
312
411
  }
313
412
  exports.ServiceCalendarSyncPoller = ServiceCalendarSyncPoller;
314
413
  /**
315
- * Whether two stored values are the same, compared by value.
316
- *
317
- * A plan's JSON columns come back from Parse as fresh objects, so identity says
318
- * nothing about them. Keys are sorted first, so an object that differs only in
319
- * the order Mongo hands it back does not read as a change.
414
+ * Whether two stored values are the same, compared by value. Keys are sorted
415
+ * first, so an object that differs only in the order Mongo hands it back does
416
+ * not read as a change.
320
417
  */
321
418
  function sameValue(a, b) {
322
419
  return stableJson(a) === stableJson(b);
@@ -1,29 +1,31 @@
1
- /**
2
- * Config key of the Outlook integration. Shared with v1 — one calendar
3
- * connection per tenant serves both generations.
4
- */
1
+ /** Config key of a tenant's Outlook connection (one `OD3_Config` row each). */
5
2
  export declare const OUTLOOK_CONFIG_KEY = "OPENSERVICE_MICROSOFT_OUTLOOK_INTEGRATION";
3
+ /** Outlook category that asks for a new appointment to become a plan. */
4
+ export declare const DEFAULT_IMPORT_CATEGORY = "open.SERVICE";
6
5
  /**
7
6
  * The stored configuration of one tenant's calendar connection.
8
7
  *
9
- * `default_source_id` is v1's fallback (a `Maintenance_Source`);
10
- * `default_equipment_id` is its v2 counterpart (`OD3_Service_Equipment`). Both
11
- * live in the same row because the connection is the same — the poller for each
12
- * generation reads the key it understands.
8
+ * Rows written for v1 may still carry `default_source_id` and the delta
9
+ * cursors (`delta_link`, `delta_link_v2`); nothing reads them any more.
13
10
  */
14
11
  export type ServiceSyncConfigValues = {
15
12
  tenant_id: string;
16
13
  client_id: string;
17
14
  client_secret: string;
18
15
  user_email: string;
19
- /** v1 fallback source. */
20
- default_source_id?: string;
21
- /** v2 fallback machine for events that name none. */
16
+ /** Fallback machine for imported events that name none. */
22
17
  default_equipment_id?: string;
23
- /** Delta cursor of the v1 poller. */
24
- delta_link?: string;
25
- /** Delta cursor of the v2 poller — separate, so the two never steal each other's. */
26
- delta_link_v2?: string;
18
+ /**
19
+ * Outlook category that turns an appointment into a new plan. Default
20
+ * `open.SERVICE`; an empty string switches importing off.
21
+ */
22
+ import_category?: string;
23
+ /**
24
+ * Kill switch for the Outlook → open.SERVICE direction. Plans are still
25
+ * written to the calendar; nothing is read back. Re-read every pass, so it
26
+ * takes effect without a restart.
27
+ */
28
+ inbound_disabled?: boolean;
27
29
  };
28
30
  /**
29
31
  * The recurrence of a v2 maintenance plan, as stored in
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OUTLOOK_CONFIG_KEY = void 0;
4
- /**
5
- * Config key of the Outlook integration. Shared with v1 — one calendar
6
- * connection per tenant serves both generations.
7
- */
3
+ exports.DEFAULT_IMPORT_CATEGORY = exports.OUTLOOK_CONFIG_KEY = void 0;
4
+ /** Config key of a tenant's Outlook connection (one `OD3_Config` row each). */
8
5
  exports.OUTLOOK_CONFIG_KEY = "OPENSERVICE_MICROSOFT_OUTLOOK_INTEGRATION";
6
+ /** Outlook category that asks for a new appointment to become a plan. */
7
+ exports.DEFAULT_IMPORT_CATEGORY = "open.SERVICE";
@@ -1,4 +1,4 @@
1
- import type { GraphEventResponse } from "../../schedules/calendarSync/Event.js";
1
+ import type { GraphEventResponse } from "./Event.js";
2
2
  import type { ServiceCadence, ServiceNotificationRule } from "./ServiceSyncTypes.js";
3
3
  /**
4
4
  * The rule id the sync owns.