@openinc/parse-server-opendash 4.27.0 → 4.29.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 (20) hide show
  1. package/dist/features/notifications/services/sendMails.d.ts +5 -1
  2. package/dist/features/notifications/services/sendMails.js +6 -1
  3. package/dist/features/openservice/schedules/calendarSync/CalendarManager.d.ts +5 -0
  4. package/dist/features/openservice/schedules/calendarSync/CalendarManager.js +30 -0
  5. package/dist/features/openservice/schedules/calendarSync/Event.d.ts +5 -0
  6. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceCalendarSyncPoller.js +10 -1
  7. package/dist/features/openservice/serviceSchedules/calendarSync/ServiceSyncTypes.d.ts +12 -0
  8. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.d.ts +119 -0
  9. package/dist/features/openservice/serviceSchedules/calendarSync/seriesExceptions.js +159 -0
  10. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.d.ts +26 -0
  11. package/dist/features/openservice/serviceSchedules/calendarSync/serviceCalendarMeta.js +39 -0
  12. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.d.ts +43 -0
  13. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanExceptions.js +187 -0
  14. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.d.ts +3 -0
  15. package/dist/features/openservice/serviceSchedules/calendarSync/syncPlanToCalendar.js +54 -12
  16. package/dist/functions/openinc-backfill-source-tags.d.ts +21 -0
  17. package/dist/functions/openinc-backfill-source-tags.js +85 -0
  18. package/dist/functions/openinc-openservice-notify-contacts.d.ts +2 -1
  19. package/dist/functions/openinc-openservice-notify-contacts.js +27 -13
  20. package/package.json +2 -1
@@ -4,9 +4,13 @@ import { Core_Email } from "../../../types/index.js";
4
4
  * @param to The recipient email address
5
5
  * @param subject The subject of the email
6
6
  * @param text The plain text content of the email
7
+ * @param dedupKey Optional marker stored with the mail, for a sender that has
8
+ * to recognise it later (see `openinc-openservice-notify-contacts`). It rides
9
+ * in `payload`, which the `Core_Email` hook hands to nodemailer — that only
10
+ * reads the message fields it knows, so the key never reaches the mail.
7
11
  * @returns The saved email object
8
12
  */
9
- export declare function sendSimpleEmail(to: string, subject: string, text: string): Promise<Core_Email>;
13
+ export declare function sendSimpleEmail(to: string, subject: string, text: string, dedupKey?: string): Promise<Core_Email>;
10
14
  /**
11
15
  * Send a template email
12
16
  * @param param0
@@ -15,14 +15,19 @@ const EmailState_js_1 = require("../states/EmailState.js");
15
15
  * @param to The recipient email address
16
16
  * @param subject The subject of the email
17
17
  * @param text The plain text content of the email
18
+ * @param dedupKey Optional marker stored with the mail, for a sender that has
19
+ * to recognise it later (see `openinc-openservice-notify-contacts`). It rides
20
+ * in `payload`, which the `Core_Email` hook hands to nodemailer — that only
21
+ * reads the message fields it knows, so the key never reaches the mail.
18
22
  * @returns The saved email object
19
23
  */
20
- async function sendSimpleEmail(to, subject, text) {
24
+ async function sendSimpleEmail(to, subject, text, dedupKey) {
21
25
  const email = new index_js_1.Core_Email({
22
26
  payload: {
23
27
  to,
24
28
  subject,
25
29
  text,
30
+ ...(dedupKey ? { dedupKey } : {}),
26
31
  },
27
32
  });
28
33
  await email.save(null, { useMasterKey: true });
@@ -24,6 +24,11 @@ export declare class CalendarManager {
24
24
  updateEvent(eventId: string, event: Partial<GraphEvent>): Promise<GraphEventResponse | undefined>;
25
25
  deleteEvent(eventId: string): Promise<boolean | undefined>;
26
26
  fetchEvent(eventId: string): Promise<GraphEventResponse | null>;
27
+ /**
28
+ * The occurrences of a series between two instants — moved ones (exceptions)
29
+ * included, deleted ones not. `null` when the request failed.
30
+ */
31
+ fetchInstances(seriesId: string, from: Date, to: Date): Promise<GraphEventResponse[] | null>;
27
32
  fetchEvents(): Promise<{
28
33
  value: GraphEventResponse[];
29
34
  } | undefined>;
@@ -127,6 +127,36 @@ class CalendarManager {
127
127
  }
128
128
  return (await res.json());
129
129
  }
130
+ /**
131
+ * The occurrences of a series between two instants — moved ones (exceptions)
132
+ * included, deleted ones not. `null` when the request failed.
133
+ */
134
+ async fetchInstances(seriesId, from, to) {
135
+ const accessData = await this.getAccess();
136
+ if (!accessData?.access_token)
137
+ return null;
138
+ const params = new URLSearchParams({
139
+ startDateTime: from.toISOString(),
140
+ endDateTime: to.toISOString(),
141
+ $select: "id,type,originalStart,start",
142
+ $top: "100",
143
+ });
144
+ let nextUrl = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(this.userMail)}/events/${seriesId}/instances?${params.toString()}`;
145
+ const instances = [];
146
+ while (nextUrl) {
147
+ const res = await fetch(nextUrl, {
148
+ headers: { Authorization: `Bearer ${accessData.access_token}` },
149
+ });
150
+ if (!res.ok) {
151
+ console.error(`[CalendarManager] Failed to fetch instances of ${seriesId}: HTTP ${res.status}`);
152
+ return null;
153
+ }
154
+ const data = (await res.json());
155
+ instances.push(...(data.value ?? []));
156
+ nextUrl = data["@odata.nextLink"];
157
+ }
158
+ return instances;
159
+ }
130
160
  async fetchEvents() {
131
161
  const accessData = await this.getAccess();
132
162
  if (!accessData?.access_token)
@@ -120,6 +120,11 @@ export type GraphEventResponse = {
120
120
  onlineMeetingProvider?: "unknown" | "skypeForBusiness" | "skypeForConsumer" | "teamsForBusiness" | string;
121
121
  allowNewTimeProposals?: boolean;
122
122
  occurrenceId?: string | null;
123
+ /**
124
+ * For an occurrence or exception of a series: where it was scheduled before
125
+ * anyone moved it (`DateTimeOffset`, e.g. `2026-11-19T08:00:00Z`).
126
+ */
127
+ originalStart?: string | null;
123
128
  isDraft?: boolean;
124
129
  hideAttendees?: boolean;
125
130
  responseStatus?: {
@@ -10,6 +10,7 @@ const CalendarManager_js_1 = require("../../schedules/calendarSync/CalendarManag
10
10
  const index_js_1 = require("../../../../types/index.js");
11
11
  const eventToPlan_js_1 = require("./eventToPlan.js");
12
12
  const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
13
+ const syncPlanExceptions_js_1 = require("./syncPlanExceptions.js");
13
14
  /**
14
15
  * Marker on a save that came from the calendar.
15
16
  *
@@ -120,6 +121,11 @@ class ServiceCalendarSyncPoller {
120
121
  return;
121
122
  const meta = await (0, serviceCalendarMeta_js_1.findMetaForEvent)(event.id);
122
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;
123
129
  // Delta payloads are partial — fetch the whole event before creating.
124
130
  const full = await this.manager.fetchEvent(event.id);
125
131
  if (full)
@@ -241,8 +247,11 @@ class ServiceCalendarSyncPoller {
241
247
  */
242
248
  async handleRemoved(eventId) {
243
249
  const meta = await (0, serviceCalendarMeta_js_1.findMetaForEvent)(eventId);
244
- if (!meta)
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 });
245
253
  return;
254
+ }
246
255
  const planId = meta.get("entryObjectId");
247
256
  if (planId) {
248
257
  try {
@@ -42,6 +42,18 @@ export type ServiceCadence = {
42
42
  /** ISO timestamp the series ends at (inclusive). */
43
43
  until?: string;
44
44
  };
45
+ /**
46
+ * A single date of a plan moved or skipped (`cadenceExceptions`). Mirrored from
47
+ * the frontend's `CadenceException`.
48
+ */
49
+ export type ServiceCadenceException = {
50
+ /** ISO of the original occurrence — the match key. */
51
+ date: string;
52
+ /** ISO of the date it was moved to. */
53
+ moveTo?: string;
54
+ skip?: boolean;
55
+ reason?: string;
56
+ };
45
57
  /** A notification rule of a plan (`notifications`), as far as the sync needs it. */
46
58
  export type ServiceNotificationRule = {
47
59
  id: string;
@@ -0,0 +1,119 @@
1
+ import type { ServiceCadenceException } from "./ServiceSyncTypes.js";
2
+ /**
3
+ * Moved and skipped single dates and pauses of a plan, as changes to its
4
+ * Outlook series — the pure half: what should be, measured against what was
5
+ * written last time. `syncPlanExceptions` does the Graph calls.
6
+ *
7
+ * **How a plan's exceptions look in Outlook.**
8
+ *
9
+ * - A skipped date, the original of a moved date, and every date inside a pause
10
+ * are **removed from the series** (the occurrence is deleted).
11
+ * - A moved date becomes a **stand-alone event** on its new date. Moving the
12
+ * occurrence itself would be the obvious way, but Outlook refuses to move one
13
+ * onto or past a neighbouring occurrence (`ErrorOccurrenceCrossingBoundary`),
14
+ * which a monthly plan pulled forward by three weeks, or any daily plan, does
15
+ * all the time.
16
+ *
17
+ * **Why a rebuild.** A deleted occurrence cannot be brought back. When a skip
18
+ * is undone, a move reset or a pause ended early, the series is written anew
19
+ * and every removal still wanted applied to the new one. That is rare (it takes
20
+ * undoing something), and it is the only way back.
21
+ *
22
+ * **Matching by UTC day.** The series is written in UTC and the plan's dates
23
+ * keep their wall time in the plan's zone, so across a DST switch the two lie
24
+ * an hour apart. The day is what they agree on.
25
+ */
26
+ /** A plan's exception state as last written to Outlook (stored in the meta entry). */
27
+ export interface AppliedExceptions {
28
+ /** Occurrences removed from the series: their UTC day and original start. */
29
+ cancelled: {
30
+ day: string;
31
+ start: string;
32
+ }[];
33
+ /**
34
+ * Stand-alone events standing in for moved dates, keyed by the original
35
+ * date's ISO (`cadenceExceptions[].date`). Kept for as long as the event
36
+ * exists — the poller recognises them by this list, and an event it does not
37
+ * recognise becomes a new plan.
38
+ */
39
+ moved: {
40
+ from: string;
41
+ moveTo: string;
42
+ eventId: string;
43
+ }[];
44
+ }
45
+ /** One occurrence of the Outlook series, as the instances endpoint lists it. */
46
+ export interface SeriesInstance {
47
+ id: string;
48
+ /** The occurrence's original start — before anyone moved it in Outlook. */
49
+ start: Date;
50
+ }
51
+ /** A moved date that should exist as a stand-alone event. */
52
+ export interface MovedDate {
53
+ /** ISO of the original occurrence. */
54
+ from: string;
55
+ /** ISO of the date it was moved to. */
56
+ moveTo: string;
57
+ reason?: string;
58
+ }
59
+ /** What the plan says the calendar should look like from today on. */
60
+ export interface DesiredExceptions {
61
+ /** UTC days whose occurrence has to leave the series (skips, moved originals). */
62
+ cancelDays: Set<string>;
63
+ /** Occurrences before this instant are paused — only set while it is ahead. */
64
+ pausedUntil?: Date;
65
+ moved: MovedDate[];
66
+ }
67
+ export declare const EMPTY_APPLIED: AppliedExceptions;
68
+ /** `YYYY-MM-DD` of an instant, in UTC. */
69
+ export declare function utcDay(date: Date | string): string;
70
+ /**
71
+ * The plan's exceptions and pause, reduced to what matters from today on.
72
+ *
73
+ * The past is left alone: a calendar is read forwards, and rewriting last
74
+ * month to match a plan edited today helps nobody.
75
+ */
76
+ export declare function desiredExceptions(exceptions: ServiceCadenceException[] | undefined, pausedUntil: Date | undefined, now: Date): DesiredExceptions;
77
+ /**
78
+ * Whether an occurrence removed earlier has to come back — which only a
79
+ * rebuilt series can do. Past removals do not count.
80
+ */
81
+ export declare function needsRebuild(applied: AppliedExceptions, desired: DesiredExceptions, now: Date): boolean;
82
+ /** The removals still wanted, past ones dropped. */
83
+ export declare function keptCancellations(applied: AppliedExceptions, desired: DesiredExceptions, now: Date): AppliedExceptions["cancelled"];
84
+ /**
85
+ * The span of the series to list, or `undefined` when nothing has to be
86
+ * removed from it — then no Graph call is needed at all.
87
+ */
88
+ export declare function cancelRange(desired: DesiredExceptions, now: Date): {
89
+ from: Date;
90
+ to: Date;
91
+ } | undefined;
92
+ /** The listed occurrences the plan wants out of the series. */
93
+ export declare function instancesToCancel(instances: SeriesInstance[], desired: DesiredExceptions, now: Date): SeriesInstance[];
94
+ /**
95
+ * How the stand-alone events of moved dates have to change.
96
+ *
97
+ * - `create`: moved dates without an event yet;
98
+ * - `update`: events whose date still stands — rewritten every time, so they
99
+ * follow the plan's title and steps — or whose target changed;
100
+ * - `remove`: events of moves that were undone or turned into a skip;
101
+ * - `keep`: events of moves that now lie in the past, left as they are.
102
+ */
103
+ export declare function movedChanges(applied: AppliedExceptions["moved"], desired: MovedDate[], now: Date): {
104
+ create: MovedDate[];
105
+ update: {
106
+ entry: AppliedExceptions["moved"][number];
107
+ target: MovedDate;
108
+ }[];
109
+ remove: AppliedExceptions["moved"];
110
+ keep: AppliedExceptions["moved"];
111
+ };
112
+ /**
113
+ * The start a single appointment (a plan that fires once) should have — it has
114
+ * no series to take exceptions, so it carries its own.
115
+ *
116
+ * `undefined`: unchanged. `null`: no appointment at all (skipped, or paused
117
+ * past its date). Otherwise the ISO of the date it was moved to.
118
+ */
119
+ export declare function singleEventStart(dtstart: string | undefined, exceptions: ServiceCadenceException[] | undefined, pausedUntil: Date | undefined, now: Date): string | null | undefined;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EMPTY_APPLIED = void 0;
4
+ exports.utcDay = utcDay;
5
+ exports.desiredExceptions = desiredExceptions;
6
+ exports.needsRebuild = needsRebuild;
7
+ exports.keptCancellations = keptCancellations;
8
+ exports.cancelRange = cancelRange;
9
+ exports.instancesToCancel = instancesToCancel;
10
+ exports.movedChanges = movedChanges;
11
+ exports.singleEventStart = singleEventStart;
12
+ exports.EMPTY_APPLIED = { cancelled: [], moved: [] };
13
+ /** `YYYY-MM-DD` of an instant, in UTC. */
14
+ function utcDay(date) {
15
+ return new Date(date).toISOString().slice(0, 10);
16
+ }
17
+ function startOfUtcDay(now) {
18
+ return new Date(`${utcDay(now)}T00:00:00.000Z`);
19
+ }
20
+ /**
21
+ * The plan's exceptions and pause, reduced to what matters from today on.
22
+ *
23
+ * The past is left alone: a calendar is read forwards, and rewriting last
24
+ * month to match a plan edited today helps nobody.
25
+ */
26
+ function desiredExceptions(exceptions, pausedUntil, now) {
27
+ const today = startOfUtcDay(now).getTime();
28
+ const pause = pausedUntil && pausedUntil.getTime() > now.getTime()
29
+ ? pausedUntil
30
+ : undefined;
31
+ const cancelDays = new Set();
32
+ const moved = [];
33
+ for (const exception of exceptions ?? []) {
34
+ const original = new Date(exception.date);
35
+ if (Number.isNaN(original.getTime()))
36
+ continue;
37
+ if (!exception.skip && !exception.moveTo)
38
+ continue;
39
+ if (original.getTime() >= today)
40
+ cancelDays.add(utcDay(original));
41
+ if (exception.skip || !exception.moveTo)
42
+ continue;
43
+ const target = new Date(exception.moveTo);
44
+ if (Number.isNaN(target.getTime()) || target.getTime() < today)
45
+ continue;
46
+ // A date moved into a pause is paused with it — as the plan computes it.
47
+ if (pause && target.getTime() < pause.getTime())
48
+ continue;
49
+ moved.push({
50
+ from: exception.date,
51
+ moveTo: exception.moveTo,
52
+ reason: exception.reason,
53
+ });
54
+ }
55
+ return { cancelDays, pausedUntil: pause, moved };
56
+ }
57
+ /** Whether the plan still wants an occurrence out of the series. */
58
+ function stillCancelled(day, start, desired) {
59
+ if (desired.cancelDays.has(day))
60
+ return true;
61
+ return (!!desired.pausedUntil && start.getTime() < desired.pausedUntil.getTime());
62
+ }
63
+ /**
64
+ * Whether an occurrence removed earlier has to come back — which only a
65
+ * rebuilt series can do. Past removals do not count.
66
+ */
67
+ function needsRebuild(applied, desired, now) {
68
+ return applied.cancelled.some((entry) => {
69
+ const start = new Date(entry.start);
70
+ if (start.getTime() < now.getTime())
71
+ return false;
72
+ return !stillCancelled(entry.day, start, desired);
73
+ });
74
+ }
75
+ /** The removals still wanted, past ones dropped. */
76
+ function keptCancellations(applied, desired, now) {
77
+ return applied.cancelled.filter((entry) => {
78
+ const start = new Date(entry.start);
79
+ return (start.getTime() >= now.getTime() &&
80
+ stillCancelled(entry.day, start, desired));
81
+ });
82
+ }
83
+ /**
84
+ * The span of the series to list, or `undefined` when nothing has to be
85
+ * removed from it — then no Graph call is needed at all.
86
+ */
87
+ function cancelRange(desired, now) {
88
+ const ends = [];
89
+ for (const day of desired.cancelDays) {
90
+ ends.push(new Date(`${day}T00:00:00.000Z`).getTime() + 86_400_000);
91
+ }
92
+ if (desired.pausedUntil)
93
+ ends.push(desired.pausedUntil.getTime());
94
+ if (ends.length === 0)
95
+ return undefined;
96
+ return { from: startOfUtcDay(now), to: new Date(Math.max(...ends)) };
97
+ }
98
+ /** The listed occurrences the plan wants out of the series. */
99
+ function instancesToCancel(instances, desired, now) {
100
+ const today = startOfUtcDay(now).getTime();
101
+ return instances.filter((instance) => instance.start.getTime() >= today &&
102
+ stillCancelled(utcDay(instance.start), instance.start, desired));
103
+ }
104
+ /**
105
+ * How the stand-alone events of moved dates have to change.
106
+ *
107
+ * - `create`: moved dates without an event yet;
108
+ * - `update`: events whose date still stands — rewritten every time, so they
109
+ * follow the plan's title and steps — or whose target changed;
110
+ * - `remove`: events of moves that were undone or turned into a skip;
111
+ * - `keep`: events of moves that now lie in the past, left as they are.
112
+ */
113
+ function movedChanges(applied, desired, now) {
114
+ const today = startOfUtcDay(now).getTime();
115
+ const wanted = new Map(desired.map((target) => [target.from, target]));
116
+ const known = new Set(applied.map((entry) => entry.from));
117
+ const update = [];
118
+ const remove = [];
119
+ const keep = [];
120
+ for (const entry of applied) {
121
+ const target = wanted.get(entry.from);
122
+ if (target)
123
+ update.push({ entry, target });
124
+ else if (new Date(entry.moveTo).getTime() < today)
125
+ keep.push(entry);
126
+ else
127
+ remove.push(entry);
128
+ }
129
+ return {
130
+ create: desired.filter((target) => !known.has(target.from)),
131
+ update,
132
+ remove,
133
+ keep,
134
+ };
135
+ }
136
+ /**
137
+ * The start a single appointment (a plan that fires once) should have — it has
138
+ * no series to take exceptions, so it carries its own.
139
+ *
140
+ * `undefined`: unchanged. `null`: no appointment at all (skipped, or paused
141
+ * past its date). Otherwise the ISO of the date it was moved to.
142
+ */
143
+ function singleEventStart(dtstart, exceptions, pausedUntil, now) {
144
+ if (!dtstart)
145
+ return undefined;
146
+ const day = utcDay(dtstart);
147
+ const exception = (exceptions ?? []).find((candidate) => !Number.isNaN(new Date(candidate.date).getTime()) &&
148
+ utcDay(candidate.date) === day);
149
+ if (exception?.skip)
150
+ return null;
151
+ const moved = exception?.moveTo;
152
+ const effective = new Date(moved ?? dtstart);
153
+ if (pausedUntil &&
154
+ pausedUntil.getTime() > now.getTime() &&
155
+ effective.getTime() < pausedUntil.getTime()) {
156
+ return null;
157
+ }
158
+ return moved;
159
+ }
@@ -1,6 +1,7 @@
1
1
  import type { MetaConfig } from "../../../../types/custom/MetaField.js";
2
2
  import { Meta_Entry, Tenant } from "../../../../types/index.js";
3
3
  import type { GraphEventResponse } from "../../schedules/calendarSync/Event.js";
4
+ import type { AppliedExceptions } from "./seriesExceptions.js";
4
5
  /**
5
6
  * Which calendar event belongs to which v2 maintenance plan.
6
7
  *
@@ -38,11 +39,23 @@ export interface ServiceCalendarMetaValues {
38
39
  microsoftCalendarEventId: string;
39
40
  microsoftCalendarChangeKey?: string;
40
41
  microsoftCalendarEvent?: ServiceCalendarEventSnapshot;
42
+ /**
43
+ * The plan's moved and skipped dates and its pause, as last written to the
44
+ * series — see `seriesExceptions.ts`. Absent until a plan has any.
45
+ */
46
+ microsoftCalendarExceptions?: AppliedExceptions;
41
47
  }
42
48
  /** Shown by the meta plugin when the entry is inspected in the frontend. */
43
49
  export declare const ServiceCalendarMetaConfig: MetaConfig;
44
50
  export declare function findMetaForPlan(scheduleId: string): Promise<Meta_Entry | null>;
45
51
  export declare function findMetaForEvent(eventId: string): Promise<Meta_Entry | null>;
52
+ /**
53
+ * The plan whose moved date the event stands in for.
54
+ *
55
+ * Such an event is ours, but it is not the plan's series — the poller must
56
+ * neither import it as a new plan nor archive the plan when it is deleted.
57
+ */
58
+ export declare function findMetaForMovedEvent(eventId: string): Promise<Meta_Entry | null>;
46
59
  export declare function saveMeta(scheduleId: string, eventId: string, changeKey?: string, tenant?: Tenant, event?: GraphEventResponse): Promise<Meta_Entry>;
47
60
  /**
48
61
  * Remember the `changeKey` of the version we just wrote.
@@ -52,4 +65,17 @@ export declare function saveMeta(scheduleId: string, eventId: string, changeKey?
52
65
  * extra round trip; writing the wrong one means an endless echo.
53
66
  */
54
67
  export declare function updateChangeKey(entry: Meta_Entry, changeKey: string, event?: GraphEventResponse): Promise<void>;
68
+ /**
69
+ * Remember what `syncPlanExceptions` wrote: the exception state, and — after a
70
+ * rebuild — the new series with its `changeKey`.
71
+ *
72
+ * The `changeKey` matters as much here as in `updateChangeKey`: removing an
73
+ * occurrence changes the series master, and a master change the poller does
74
+ * not recognise as ours is read back as an edit made in Outlook.
75
+ */
76
+ export declare function updateExceptionsState(entry: Meta_Entry, state: {
77
+ exceptions: AppliedExceptions;
78
+ eventId?: string;
79
+ event?: GraphEventResponse;
80
+ }): Promise<void>;
55
81
  export declare function metaValues(entry: Meta_Entry): ServiceCalendarMetaValues | undefined;
@@ -6,8 +6,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ServiceCalendarMetaConfig = exports.SERVICE_CALENDAR_SYNC_CONTEXT = void 0;
7
7
  exports.findMetaForPlan = findMetaForPlan;
8
8
  exports.findMetaForEvent = findMetaForEvent;
9
+ exports.findMetaForMovedEvent = findMetaForMovedEvent;
9
10
  exports.saveMeta = saveMeta;
10
11
  exports.updateChangeKey = updateChangeKey;
12
+ exports.updateExceptionsState = updateExceptionsState;
11
13
  exports.metaValues = metaValues;
12
14
  const node_1 = __importDefault(require("parse/node"));
13
15
  const index_js_1 = require("../../../../types/index.js");
@@ -69,6 +71,22 @@ async function findMetaForEvent(eventId) {
69
71
  .equalTo("values.microsoftCalendarEventId", eventId)
70
72
  .first({ useMasterKey: true })) ?? null);
71
73
  }
74
+ /**
75
+ * The plan whose moved date the event stands in for.
76
+ *
77
+ * Such an event is ours, but it is not the plan's series — the poller must
78
+ * neither import it as a new plan nor archive the plan when it is deleted.
79
+ */
80
+ async function findMetaForMovedEvent(eventId) {
81
+ return ((await new node_1.default.Query(index_js_1.Meta_Entry)
82
+ .equalTo("context", exports.SERVICE_CALENDAR_SYNC_CONTEXT)
83
+ .equalTo("entryClassName", index_js_1.Service_Schedule.className)
84
+ // Matches any element of the `moved` array — Mongo semantics for a dot
85
+ // path through an array of objects.
86
+ // @ts-expect-error
87
+ .equalTo("values.microsoftCalendarExceptions.moved.eventId", eventId)
88
+ .first({ useMasterKey: true })) ?? null);
89
+ }
72
90
  async function saveMeta(scheduleId, eventId, changeKey, tenant, event) {
73
91
  let entry = await findMetaForPlan(scheduleId);
74
92
  if (!entry) {
@@ -104,6 +122,27 @@ async function updateChangeKey(entry, changeKey, event) {
104
122
  });
105
123
  await entry.save(null, { useMasterKey: true });
106
124
  }
125
+ /**
126
+ * Remember what `syncPlanExceptions` wrote: the exception state, and — after a
127
+ * rebuild — the new series with its `changeKey`.
128
+ *
129
+ * The `changeKey` matters as much here as in `updateChangeKey`: removing an
130
+ * occurrence changes the series master, and a master change the poller does
131
+ * not recognise as ours is read back as an edit made in Outlook.
132
+ */
133
+ async function updateExceptionsState(entry, state) {
134
+ const values = entry.get("values");
135
+ entry.set("values", {
136
+ ...values,
137
+ ...(state.eventId ? { microsoftCalendarEventId: state.eventId } : {}),
138
+ ...(state.event?.changeKey
139
+ ? { microsoftCalendarChangeKey: state.event.changeKey }
140
+ : {}),
141
+ ...(state.event ? { microsoftCalendarEvent: toSnapshot(state.event) } : {}),
142
+ microsoftCalendarExceptions: state.exceptions,
143
+ });
144
+ await entry.save(null, { useMasterKey: true });
145
+ }
107
146
  function metaValues(entry) {
108
147
  return entry.get("values");
109
148
  }
@@ -0,0 +1,43 @@
1
+ import type { CalendarManager } from "../../schedules/calendarSync/CalendarManager.js";
2
+ import type { GraphEvent } from "../../schedules/calendarSync/Event.js";
3
+ import type { Meta_Entry } from "../../../../types/index.js";
4
+ import { type PlanEventInput } from "./planToEvent.js";
5
+ import type { ServiceCadenceException } from "./ServiceSyncTypes.js";
6
+ /**
7
+ * Bring a plan's moved and skipped dates and its pause into its Outlook series
8
+ * — the Graph half of `seriesExceptions.ts`, which explains the mapping.
9
+ *
10
+ * Called by `syncPlanToCalendar` after the series itself was written. Costs no
11
+ * Graph call for a plan that has no exceptions and never had any.
12
+ *
13
+ * Order matters in two places, both because of the poller, which turns every
14
+ * event it cannot place into a new plan and archives the plan of every series
15
+ * that disappears:
16
+ *
17
+ * - a rebuilt series is linked to the plan **before** the old one is deleted;
18
+ * - a stand-alone event for a moved date is linked right after it is created.
19
+ */
20
+ export declare function syncPlanExceptions({ manager, meta, series, input, exceptions, pausedUntil, now, }: {
21
+ manager: CalendarManager;
22
+ meta: Meta_Entry;
23
+ /** The series as just written — written again when it has to be rebuilt. */
24
+ series: GraphEvent;
25
+ /** What the series was built from; moved dates are built from it too. */
26
+ input: PlanEventInput;
27
+ exceptions?: ServiceCadenceException[];
28
+ pausedUntil?: Date;
29
+ now?: Date;
30
+ }): Promise<void>;
31
+ /**
32
+ * Delete the stand-alone events of a plan's moved dates — for a plan that
33
+ * leaves the calendar altogether.
34
+ */
35
+ export declare function deleteMovedEvents(manager: CalendarManager, meta: Meta_Entry): Promise<void>;
36
+ /**
37
+ * Whether an event stands in for a moved date. One that was deleted in Outlook
38
+ * is unlinked as well, so the next save writes it again instead of failing to
39
+ * update it forever.
40
+ */
41
+ export declare function isMovedEvent(eventId: string, options?: {
42
+ removed?: boolean;
43
+ }): Promise<boolean>;
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncPlanExceptions = syncPlanExceptions;
4
+ exports.deleteMovedEvents = deleteMovedEvents;
5
+ exports.isMovedEvent = isMovedEvent;
6
+ const planToEvent_js_1 = require("./planToEvent.js");
7
+ const seriesExceptions_js_1 = require("./seriesExceptions.js");
8
+ const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
9
+ /**
10
+ * Bring a plan's moved and skipped dates and its pause into its Outlook series
11
+ * — the Graph half of `seriesExceptions.ts`, which explains the mapping.
12
+ *
13
+ * Called by `syncPlanToCalendar` after the series itself was written. Costs no
14
+ * Graph call for a plan that has no exceptions and never had any.
15
+ *
16
+ * Order matters in two places, both because of the poller, which turns every
17
+ * event it cannot place into a new plan and archives the plan of every series
18
+ * that disappears:
19
+ *
20
+ * - a rebuilt series is linked to the plan **before** the old one is deleted;
21
+ * - a stand-alone event for a moved date is linked right after it is created.
22
+ */
23
+ async function syncPlanExceptions({ manager, meta, series, input, exceptions, pausedUntil, now = new Date(), }) {
24
+ const values = (0, serviceCalendarMeta_js_1.metaValues)(meta);
25
+ const seriesId = values?.microsoftCalendarEventId;
26
+ if (!seriesId)
27
+ return;
28
+ const applied = values?.microsoftCalendarExceptions ?? seriesExceptions_js_1.EMPTY_APPLIED;
29
+ // A single appointment carries its exception itself (`singleEventStart`);
30
+ // whatever a former series left behind is cleaned up as if nothing were
31
+ // wanted.
32
+ const desired = series.recurrence
33
+ ? (0, seriesExceptions_js_1.desiredExceptions)(exceptions, pausedUntil, now)
34
+ : (0, seriesExceptions_js_1.desiredExceptions)(undefined, undefined, now);
35
+ const nothingWanted = desired.cancelDays.size === 0 &&
36
+ !desired.pausedUntil &&
37
+ desired.moved.length === 0;
38
+ if (nothingWanted &&
39
+ applied.cancelled.length === 0 &&
40
+ applied.moved.length === 0) {
41
+ return;
42
+ }
43
+ let eventId = seriesId;
44
+ let cancelled = (0, seriesExceptions_js_1.keptCancellations)(applied, desired, now);
45
+ if (series.recurrence && (0, seriesExceptions_js_1.needsRebuild)(applied, desired, now)) {
46
+ const rebuilt = await manager.createEvent(series);
47
+ if (!rebuilt?.id) {
48
+ console.error(`[ServiceCalendarSync] Could not rebuild series ${seriesId} — removed dates stay removed`);
49
+ }
50
+ else {
51
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
52
+ exceptions: { cancelled: [], moved: applied.moved },
53
+ eventId: rebuilt.id,
54
+ event: rebuilt,
55
+ });
56
+ await manager.deleteEvent(seriesId);
57
+ eventId = rebuilt.id;
58
+ cancelled = [];
59
+ }
60
+ }
61
+ const range = series.recurrence ? (0, seriesExceptions_js_1.cancelRange)(desired, now) : undefined;
62
+ if (range) {
63
+ const listed = await manager.fetchInstances(eventId, range.from, range.to);
64
+ if (!listed) {
65
+ console.error(`[ServiceCalendarSync] Could not list the occurrences of series ${eventId}`);
66
+ }
67
+ else {
68
+ // Whatever is listed exists — also an occurrence removed before, if
69
+ // rewriting the series brought it back — so it goes again.
70
+ const known = new Set(cancelled.map((entry) => entry.start));
71
+ const instances = listed
72
+ .map(toInstance)
73
+ .filter((instance) => !!instance);
74
+ for (const instance of (0, seriesExceptions_js_1.instancesToCancel)(instances, desired, now)) {
75
+ const start = instance.start.toISOString();
76
+ if (!(await manager.deleteEvent(instance.id)))
77
+ continue;
78
+ if (known.has(start))
79
+ continue;
80
+ cancelled.push({ day: (0, seriesExceptions_js_1.utcDay)(instance.start), start });
81
+ known.add(start);
82
+ }
83
+ }
84
+ }
85
+ const changes = (0, seriesExceptions_js_1.movedChanges)(applied.moved, desired.moved, now);
86
+ const moved = [...changes.keep];
87
+ for (const entry of changes.remove) {
88
+ await manager.deleteEvent(entry.eventId);
89
+ }
90
+ for (const { entry, target } of changes.update) {
91
+ const event = movedEvent(input, target);
92
+ const updated = event
93
+ ? await manager.updateEvent(entry.eventId, event)
94
+ : undefined;
95
+ // Kept even when the update failed: dropping the link would leave an event
96
+ // of ours the poller can no longer place. One deleted in Outlook is
97
+ // unlinked by the poller, and written again on the next save.
98
+ moved.push(updated ? { ...entry, moveTo: target.moveTo } : entry);
99
+ }
100
+ for (const target of changes.create) {
101
+ const event = movedEvent(input, target);
102
+ const created = event ? await manager.createEvent(event) : undefined;
103
+ if (!created?.id) {
104
+ console.error(`[ServiceCalendarSync] Could not write the moved date ${target.moveTo} of series ${eventId}`);
105
+ continue;
106
+ }
107
+ moved.push({
108
+ from: target.from,
109
+ moveTo: target.moveTo,
110
+ eventId: created.id,
111
+ });
112
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, { exceptions: { cancelled, moved } });
113
+ }
114
+ // Removing occurrences changed the series master; its new changeKey is ours.
115
+ const master = await manager.fetchEvent(eventId);
116
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
117
+ exceptions: { cancelled, moved },
118
+ event: master ?? undefined,
119
+ });
120
+ }
121
+ /**
122
+ * Delete the stand-alone events of a plan's moved dates — for a plan that
123
+ * leaves the calendar altogether.
124
+ */
125
+ async function deleteMovedEvents(manager, meta) {
126
+ const moved = (0, serviceCalendarMeta_js_1.metaValues)(meta)?.microsoftCalendarExceptions?.moved ?? [];
127
+ for (const entry of moved) {
128
+ await manager.deleteEvent(entry.eventId);
129
+ }
130
+ }
131
+ /**
132
+ * Whether an event stands in for a moved date. One that was deleted in Outlook
133
+ * is unlinked as well, so the next save writes it again instead of failing to
134
+ * update it forever.
135
+ */
136
+ async function isMovedEvent(eventId, options = {}) {
137
+ const meta = await (0, serviceCalendarMeta_js_1.findMetaForMovedEvent)(eventId);
138
+ if (!meta)
139
+ return false;
140
+ if (options.removed) {
141
+ const applied = (0, serviceCalendarMeta_js_1.metaValues)(meta)?.microsoftCalendarExceptions ?? seriesExceptions_js_1.EMPTY_APPLIED;
142
+ await (0, serviceCalendarMeta_js_1.updateExceptionsState)(meta, {
143
+ exceptions: {
144
+ cancelled: applied.cancelled,
145
+ moved: applied.moved.filter((entry) => entry.eventId !== eventId),
146
+ },
147
+ });
148
+ }
149
+ return true;
150
+ }
151
+ /**
152
+ * A moved date as its own appointment: the series' subject, reminder and
153
+ * checklist on the new date, with a note saying where it came from.
154
+ */
155
+ function movedEvent(input, target) {
156
+ const event = (0, planToEvent_js_1.planToEvent)({
157
+ ...input,
158
+ cadence: { kind: "rrule", dtstart: target.moveTo },
159
+ });
160
+ if (!event)
161
+ return undefined;
162
+ const [year, month, day] = (0, seriesExceptions_js_1.utcDay)(target.from).split("-");
163
+ const note = [
164
+ `Verschoben vom ${day}.${month}.${year}`,
165
+ target.reason ? `Grund: ${target.reason}` : undefined,
166
+ ]
167
+ .filter(Boolean)
168
+ .join("\n");
169
+ event.body = {
170
+ contentType: "Text",
171
+ content: [note, event.body?.content].filter(Boolean).join("\n\n"),
172
+ };
173
+ return event;
174
+ }
175
+ /** The original start of a listed occurrence. */
176
+ function toInstance(event) {
177
+ const fallback = event.start?.dateTime
178
+ ? event.start.dateTime.endsWith("Z")
179
+ ? event.start.dateTime
180
+ : `${event.start.dateTime.slice(0, 23)}Z`
181
+ : undefined;
182
+ const raw = event.originalStart ?? fallback;
183
+ if (!raw)
184
+ return undefined;
185
+ const start = new Date(raw);
186
+ return Number.isNaN(start.getTime()) ? undefined : { id: event.id, start };
187
+ }
@@ -18,6 +18,9 @@ import type { ServiceSyncConfigValues } from "./ServiceSyncTypes.js";
18
18
  * 3. plan already linked → the event is updated in place, keeping the time of
19
19
  * day someone gave it in Outlook;
20
20
  * 4. otherwise → a new event, and a meta entry that links the two.
21
+ *
22
+ * After 3 and 4 the plan's moved and skipped dates and its pause follow
23
+ * (`syncPlanExceptions`) — the series alone would show them on their old dates.
21
24
  */
22
25
  export declare function syncPlanToCalendar(plan: Service_Schedule): Promise<void>;
23
26
  export declare function connectionForTenant(tenant: Tenant | undefined): Promise<{
@@ -10,8 +10,10 @@ const CalendarManager_js_1 = require("../../schedules/calendarSync/CalendarManag
10
10
  const index_js_1 = require("../../../../types/index.js");
11
11
  const outlookRecurrence_js_1 = require("./outlookRecurrence.js");
12
12
  const planToEvent_js_1 = require("./planToEvent.js");
13
+ const seriesExceptions_js_1 = require("./seriesExceptions.js");
13
14
  const ServiceSyncTypes_js_1 = require("./ServiceSyncTypes.js");
14
15
  const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
16
+ const syncPlanExceptions_js_1 = require("./syncPlanExceptions.js");
15
17
  /**
16
18
  * Write a maintenance plan into the tenant's Outlook calendar.
17
19
  *
@@ -29,6 +31,9 @@ const serviceCalendarMeta_js_1 = require("./serviceCalendarMeta.js");
29
31
  * 3. plan already linked → the event is updated in place, keeping the time of
30
32
  * day someone gave it in Outlook;
31
33
  * 4. otherwise → a new event, and a meta entry that links the two.
34
+ *
35
+ * After 3 and 4 the plan's moved and skipped dates and its pause follow
36
+ * (`syncPlanExceptions`) — the series alone would show them on their old dates.
32
37
  */
33
38
  async function syncPlanToCalendar(plan) {
34
39
  const connection = await connectionForTenant(plan.get("tenant"));
@@ -44,35 +49,72 @@ async function syncPlanToCalendar(plan) {
44
49
  const meta = await (0, serviceCalendarMeta_js_1.findMetaForPlan)(plan.id);
45
50
  const values = meta ? (0, serviceCalendarMeta_js_1.metaValues)(meta) : undefined;
46
51
  const eventId = values?.microsoftCalendarEventId;
52
+ const exceptions = plan.get("cadenceExceptions");
53
+ const pausedUntil = plan.get("pausedUntil") ?? undefined;
54
+ const now = new Date();
47
55
  const retired = !!plan.get("deletedAt") || plan.get("active") === false;
56
+ const input = {
57
+ title: plan.get("title"),
58
+ cadence: plan.get("cadence"),
59
+ steps: plan.get("steps"),
60
+ notifications: plan.get("notifications"),
61
+ equipmentName: await equipmentLabel(plan),
62
+ snapshot: values?.microsoftCalendarEvent,
63
+ };
48
64
  const event = retired
49
65
  ? undefined
50
- : (0, planToEvent_js_1.planToEvent)({
51
- title: plan.get("title"),
52
- cadence: plan.get("cadence"),
53
- steps: plan.get("steps"),
54
- notifications: plan.get("notifications"),
55
- equipmentName: await equipmentLabel(plan),
56
- snapshot: values?.microsoftCalendarEvent,
57
- });
66
+ : planEvent(input, exceptions, pausedUntil, now);
58
67
  if (!event) {
59
68
  if (meta && eventId) {
60
69
  await connection.manager.deleteEvent(eventId);
70
+ await (0, syncPlanExceptions_js_1.deleteMovedEvents)(connection.manager, meta);
61
71
  await meta.destroy({ useMasterKey: true });
62
72
  }
63
73
  return;
64
74
  }
75
+ let entry = meta;
65
76
  if (meta && eventId) {
66
77
  const updated = await connection.manager.updateEvent(eventId, event);
67
78
  if (updated?.changeKey) {
68
79
  await (0, serviceCalendarMeta_js_1.updateChangeKey)(meta, updated.changeKey, updated);
69
80
  }
70
- return;
71
81
  }
72
- const created = await connection.manager.createEvent(event);
73
- if (!created?.id)
82
+ else {
83
+ const created = await connection.manager.createEvent(event);
84
+ if (!created?.id)
85
+ return;
86
+ entry = await (0, serviceCalendarMeta_js_1.saveMeta)(plan.id, created.id, created.changeKey, plan.get("tenant"), created);
87
+ }
88
+ if (!entry)
74
89
  return;
75
- await (0, serviceCalendarMeta_js_1.saveMeta)(plan.id, created.id, created.changeKey, plan.get("tenant"), created);
90
+ await (0, syncPlanExceptions_js_1.syncPlanExceptions)({
91
+ manager: connection.manager,
92
+ meta: entry,
93
+ series: event,
94
+ input,
95
+ exceptions,
96
+ pausedUntil,
97
+ now,
98
+ });
99
+ }
100
+ /**
101
+ * The plan as an event, with a single appointment's own exception applied — it
102
+ * has no series for `syncPlanExceptions` to change. `undefined` when there is
103
+ * nothing to show: no date, or a single date that was skipped or paused.
104
+ */
105
+ function planEvent(input, exceptions, pausedUntil, now) {
106
+ const event = (0, planToEvent_js_1.planToEvent)(input);
107
+ if (!event || event.recurrence || !input.cadence)
108
+ return event;
109
+ const start = (0, seriesExceptions_js_1.singleEventStart)(input.cadence.dtstart, exceptions, pausedUntil, now);
110
+ if (start === null)
111
+ return undefined;
112
+ if (start === undefined)
113
+ return event;
114
+ return (0, planToEvent_js_1.planToEvent)({
115
+ ...input,
116
+ cadence: { ...input.cadence, dtstart: start },
117
+ });
76
118
  }
77
119
  /** The machine's label, for the subject prefix — `undefined` if it has none. */
78
120
  async function equipmentLabel(plan) {
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Gives every source without a tag one — a Parse Dashboard job, run from
3
+ * Jobs → "Schedule a job", then "Run now" on the scheduled entry.
4
+ *
5
+ * Some instances have `OD3_Source` rows whose `tag` was never set. The job sets
6
+ * it to `tenant-<tenant id>-<source id>`, which is unique by construction, so
7
+ * the duplicate check in `hooks/Source.ts` never has anything to object to.
8
+ *
9
+ * Saved with the master key, so the tag permission checks in that hook pass,
10
+ * and its afterSave creates the `AccessPermissions` row a tagged source gets —
11
+ * exactly as if the tag had been entered by hand.
12
+ *
13
+ * A source that already has a tag is left alone, so the job is safe to repeat.
14
+ * A source without a tenant is skipped and its id logged: there is nothing to
15
+ * build the tag from.
16
+ *
17
+ * Parameters (optional): `{"dryRun": true}` only counts what would change.
18
+ *
19
+ * @param name The job name, derived from the file name.
20
+ */
21
+ export declare function init(name: string): Promise<void>;
@@ -0,0 +1,85 @@
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.init = init;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../types/index.js");
9
+ /**
10
+ * Gives every source without a tag one — a Parse Dashboard job, run from
11
+ * Jobs → "Schedule a job", then "Run now" on the scheduled entry.
12
+ *
13
+ * Some instances have `OD3_Source` rows whose `tag` was never set. The job sets
14
+ * it to `tenant-<tenant id>-<source id>`, which is unique by construction, so
15
+ * the duplicate check in `hooks/Source.ts` never has anything to object to.
16
+ *
17
+ * Saved with the master key, so the tag permission checks in that hook pass,
18
+ * and its afterSave creates the `AccessPermissions` row a tagged source gets —
19
+ * exactly as if the tag had been entered by hand.
20
+ *
21
+ * A source that already has a tag is left alone, so the job is safe to repeat.
22
+ * A source without a tenant is skipped and its id logged: there is nothing to
23
+ * build the tag from.
24
+ *
25
+ * Parameters (optional): `{"dryRun": true}` only counts what would change.
26
+ *
27
+ * @param name The job name, derived from the file name.
28
+ */
29
+ async function init(name) {
30
+ node_1.default.Cloud.job(name, async function (request) {
31
+ // "Run now" in the dashboard posts the schedule's parameters as `input`,
32
+ // next to its own bookkeeping fields; a direct `POST /jobs/<name>` sends
33
+ // them as the body itself.
34
+ const params = request.params.input ?? request.params;
35
+ const dryRun = params?.dryRun === true;
36
+ const verb = dryRun ? "would be tagged" : "tagged";
37
+ let checked = 0;
38
+ let tagged = 0;
39
+ const withoutTenant = [];
40
+ const failed = [];
41
+ await new node_1.default.Query(index_js_1.Source).each(async (source) => {
42
+ checked++;
43
+ // An empty string counts as missing too — the Source hooks treat it
44
+ // the same way.
45
+ if (source.get("tag"))
46
+ return;
47
+ const tenant = source.get("tenant");
48
+ if (!tenant?.id) {
49
+ withoutTenant.push(source.id);
50
+ return;
51
+ }
52
+ if (!dryRun) {
53
+ try {
54
+ source.set("tag", `tenant-${tenant.id}-${source.id}`);
55
+ await source.save(null, { useMasterKey: true });
56
+ }
57
+ catch (error) {
58
+ // One bad row must not stop the rest; it is reported at the end.
59
+ failed.push(source.id);
60
+ console.error(`[@openinc/parse-server-opendash][${name}] Could not tag source ${source.id}:`, error);
61
+ return;
62
+ }
63
+ }
64
+ tagged++;
65
+ if (tagged % 100 === 0) {
66
+ request.message(`${tagged} sources ${verb} so far…`);
67
+ }
68
+ }, { useMasterKey: true });
69
+ if (withoutTenant.length > 0) {
70
+ console.warn(`[@openinc/parse-server-opendash][${name}] Sources without tag and tenant, skipped: ${withoutTenant.join(", ")}`);
71
+ }
72
+ const summary = `${dryRun ? "Dry run — nothing saved. " : ""}` +
73
+ `${checked} sources checked, ` +
74
+ `${tagged} ${verb}, ` +
75
+ `${withoutTenant.length} skipped without tenant, ` +
76
+ `${failed.length} failed.`;
77
+ console.log(`[@openinc/parse-server-opendash][${name}] ${summary}`);
78
+ // Thrown so the job status reads "failed" in the dashboard; the message of
79
+ // a native Error ends up in the status row just like a returned string.
80
+ if (failed.length > 0) {
81
+ throw new Error(`${summary} Failed ids: ${failed.join(", ")}`);
82
+ }
83
+ return summary;
84
+ });
85
+ }
@@ -11,6 +11,7 @@
11
11
  * contacts with arbitrary text.
12
12
  *
13
13
  * Params: `contactIds`, `subject`, `body`, plus `scheduleId` / `ruleId` /
14
- * `occurrence` for the log line. Returns `{ sent, skipped, withoutEmail }`.
14
+ * `occurrence` — which identify the message for deduplication (see
15
+ * `alreadySent`) and the log line. Returns `{ sent, skipped, withoutEmail }`.
15
16
  */
16
17
  export declare function init(name: string): Promise<void>;
@@ -22,7 +22,8 @@ const DEDUP_WINDOW_DAYS = 30;
22
22
  * contacts with arbitrary text.
23
23
  *
24
24
  * Params: `contactIds`, `subject`, `body`, plus `scheduleId` / `ruleId` /
25
- * `occurrence` for the log line. Returns `{ sent, skipped, withoutEmail }`.
25
+ * `occurrence` — which identify the message for deduplication (see
26
+ * `alreadySent`) and the log line. Returns `{ sent, skipped, withoutEmail }`.
26
27
  */
27
28
  async function init(name) {
28
29
  node_1.default.Cloud.define(name, async (request) => {
@@ -36,6 +37,10 @@ async function init(name) {
36
37
  const contacts = await new node_1.default.Query(index_js_2.Contact)
37
38
  .containedIn("objectId", contactIds)
38
39
  .find({ useMasterKey: true });
40
+ // Plan, rule and date name the message; the text only describes it.
41
+ const dedupKey = scheduleId && ruleId && occurrence
42
+ ? `${scheduleId}|${ruleId}|${occurrence}`
43
+ : undefined;
39
44
  let sent = 0;
40
45
  let skipped = 0;
41
46
  let withoutEmail = 0;
@@ -45,11 +50,11 @@ async function init(name) {
45
50
  withoutEmail++;
46
51
  continue;
47
52
  }
48
- if (await alreadySent(to, body)) {
53
+ if (await alreadySent(to, body, dedupKey)) {
49
54
  skipped++;
50
55
  continue;
51
56
  }
52
- await (0, index_js_1.sendSimpleEmail)(to, subject, body);
57
+ await (0, index_js_1.sendSimpleEmail)(to, subject, body, dedupKey);
53
58
  sent++;
54
59
  }
55
60
  console.log(`[${name}] plan ${scheduleId} rule ${ruleId} occurrence ${occurrence}: ` +
@@ -60,22 +65,31 @@ async function init(name) {
60
65
  {});
61
66
  }
62
67
  /**
63
- * Whether this exact message already went to this address recently.
68
+ * Whether this message already went to this address recently.
64
69
  *
65
- * The idempotency key is the **message body**, because it already identifies
66
- * the occurrence (it carries plan, description and the due date) and because
67
- * `Core_Email` has no free column to put a marker in. That makes a restart
68
- * inside the same tick harmless, while a genuinely different occurrence — a
69
- * different date in the text — still goes out.
70
+ * **By key first.** Plan, rule and date (`dedupKey`, stored in the mail's
71
+ * payload) say which reminder a mail was, whatever its wording. The text alone
72
+ * did not: the "upcoming" and "due" texts used to carry no date, so every date
73
+ * of a plan read the same — a weekly plan's provider got one reminder in four,
74
+ * and a moved date's reminder was swallowed as a repeat of the old one. And the
75
+ * scheduler announces dates late now (a date moved inside its reminder lead),
76
+ * which also re-asks for dates whose plan was merely renamed since: by text
77
+ * those would go out a second time.
78
+ *
79
+ * **By text as well.** Mails from before the key existed have none, and the
80
+ * same text to the same address within the window is a repeat whoever sent it.
70
81
  */
71
- async function alreadySent(to, body) {
82
+ async function alreadySent(to, body, dedupKey) {
72
83
  const since = new Date(Date.now() - DEDUP_WINDOW_DAYS * 24 * 3600 * 1000);
73
84
  // Dot access into the `payload` Object column: Mongo resolves it, but the
74
85
  // generated class type only knows top-level columns — hence the untyped
75
- // query handle.
76
- const query = new node_1.default.Query(index_js_2.Core_Email);
86
+ // query handles.
87
+ const byText = new node_1.default.Query(index_js_2.Core_Email);
88
+ byText.equalTo("payload.text", body);
89
+ const byKey = new node_1.default.Query(index_js_2.Core_Email);
90
+ byKey.equalTo("payload.dedupKey", dedupKey);
91
+ const query = dedupKey ? node_1.default.Query.or(byKey, byText) : byText;
77
92
  query.equalTo("payload.to", to);
78
- query.equalTo("payload.text", body);
79
93
  query.greaterThan("createdAt", since);
80
94
  const existing = await query.first({ useMasterKey: true });
81
95
  return !!existing;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.27.0",
3
+ "version": "4.29.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [
@@ -70,6 +70,7 @@
70
70
  "backfill:changelog-search": "node dist/scripts/backfill-changelog-search.js",
71
71
  "repair:ticket-acl": "node dist/scripts/repair-ticket-acl.js",
72
72
  "test:integration": "node --test --test-concurrency=1 \"test/integration/**/*.test.mjs\"",
73
+ "test:unit": "node --test \"test/unit/**/*.test.mjs\"",
73
74
  "seed:v1": "node dist/scripts/seed-v1-testdata.js"
74
75
  },
75
76
  "dependencies": {