@jsb188/schedule 1.1.11 → 1.1.13
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.
- package/LICENSE +21 -0
- package/package.json +34 -14
- package/src/constants/schedule.ts +710 -306
- package/src/modules/Gantt.helpers.ts +11 -30
- package/src/modules/Gantt.tsx +46 -181
- package/src/types/schedule.d.ts +1827 -456
- package/src/ui/ProjectFormUI.tsx +8 -31
- package/src/ui/ScheduleSettingsUI.tsx +21 -23
- package/src/utils/autofill.ts +469 -0
- package/src/utils/availability.ts +167 -0
- package/src/utils/candidates.ts +447 -0
- package/src/utils/coverage.helpers.ts +509 -554
- package/src/utils/coverage.ts +1121 -526
- package/src/utils/cpm.helpers.ts +27 -29
- package/src/utils/cpm.ts +53 -41
- package/src/utils/cpmLeveling.helpers.ts +89 -16
- package/src/utils/cpmLeveling.ts +28 -26
- package/src/utils/cycle.ts +325 -0
- package/src/utils/demand.ts +239 -0
- package/src/utils/eligibility.ts +553 -400
- package/src/utils/ids.ts +47 -0
- package/src/utils/laborRules.ts +740 -0
- package/src/utils/localTime.ts +312 -0
- package/src/utils/offer.ts +300 -0
- package/src/utils/planCsv.ts +73 -19
- package/src/utils/predicate.ts +111 -0
- package/src/utils/request.ts +212 -114
- package/src/utils/resource.ts +412 -112
- package/src/utils/rule.ts +697 -163
- package/src/utils/rulePresets.ts +116 -0
- package/src/utils/run.ts +0 -8
- package/src/utils/scheduleText.ts +4074 -0
- package/src/utils/shiftChange.ts +279 -0
- package/src/utils/standing.ts +730 -0
- package/src/utils/template.ts +619 -0
- package/src/utils/violation.ts +184 -0
- package/src/utils/workTime.ts +341 -120
- package/src/utils/defaults.ts +0 -8
- package/src/utils/recurrence.ts +0 -616
- package/src/utils/series.ts +0 -161
- package/src/utils/slot.ts +0 -208
- package/tests/coverage.fixtures.ts +0 -111
- package/tests/coverage.test.ts +0 -503
- package/tests/cpm.bench.test.ts +0 -154
- package/tests/cpm.test.ts +0 -354
- package/tests/cpmCorrectness.test.ts +0 -327
- package/tests/cpmLeveling.test.ts +0 -471
- package/tests/eligibility.test.ts +0 -320
- package/tests/gantt-geometry.test.ts +0 -367
- package/tests/gantt-histogram.test.ts +0 -78
- package/tests/gantt-keyboard.test.ts +0 -69
- package/tests/helpers/cpmFixtures.ts +0 -101
- package/tests/projectInputs.test.ts +0 -165
- package/tests/recurrence.test.ts +0 -68
- package/tests/request.test.ts +0 -99
- package/tests/resource.test.ts +0 -95
- package/tests/rule.test.ts +0 -98
- package/tests/series.test.ts +0 -120
- package/tests/workTime.test.ts +0 -1007
- package/tests/workTimeContracts.test.ts +0 -111
- package/tsconfig.json +0 -13
- package/vitest.config.ts +0 -8
|
@@ -0,0 +1,4074 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SCHEDULE_ASK_LINE_MAX_LENGTH,
|
|
3
|
+
SCHEDULE_COVERAGE_MAX_WINDOW_DAYS,
|
|
4
|
+
SCHEDULE_PROJECT_DIGEST_LOOKAHEAD_DAYS,
|
|
5
|
+
SCHEDULE_ROTATION_WEEK_LABELS,
|
|
6
|
+
SCHEDULE_TASK_PRIORITY_ENUMS,
|
|
7
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
8
|
+
SCHEDULE_VIOLATION_MESSAGE_MAX_LENGTH,
|
|
9
|
+
} from '../constants/schedule.ts';
|
|
10
|
+
import type {
|
|
11
|
+
CoverageViolationObj,
|
|
12
|
+
ScheduleAskLineInput,
|
|
13
|
+
ScheduleAskOverviewTextInput,
|
|
14
|
+
ScheduleAskReasonEnum,
|
|
15
|
+
ScheduleAskReplyTextInput,
|
|
16
|
+
ScheduleAskTextInput,
|
|
17
|
+
ScheduleCandidateScoreReasonObj,
|
|
18
|
+
ScheduleCandidatesTextInput,
|
|
19
|
+
ScheduleCandidateTextItem,
|
|
20
|
+
ScheduleCoverageFindingsTextInput,
|
|
21
|
+
ScheduleCoverTextItem,
|
|
22
|
+
ScheduleCriticalPathKindEnum,
|
|
23
|
+
ScheduleEligibilityReasonObj,
|
|
24
|
+
ScheduleMyShiftsTextInput,
|
|
25
|
+
ScheduleNotificationEventKindEnum,
|
|
26
|
+
ScheduleOfferStatusEnum,
|
|
27
|
+
ScheduleOfferTextInput,
|
|
28
|
+
SchedulePeriodDiffObj,
|
|
29
|
+
SchedulePeriodSummaryTextInput,
|
|
30
|
+
SchedulePlanSummaryTextInput,
|
|
31
|
+
SchedulePreparePassEditTextInput,
|
|
32
|
+
ScheduleProgressCheckTextInput,
|
|
33
|
+
ScheduleProjectDigestPayloadObj,
|
|
34
|
+
ScheduleProjectDigestTextInput,
|
|
35
|
+
ScheduleProjectSlipPayloadObj,
|
|
36
|
+
ScheduleProjectSlipTextInput,
|
|
37
|
+
ScheduleRepeatTextItem,
|
|
38
|
+
ScheduleRequestKindEnum,
|
|
39
|
+
ScheduleRequestTextInput,
|
|
40
|
+
ScheduleSchedulingTypeEnum,
|
|
41
|
+
ScheduleShiftChangeTextInput,
|
|
42
|
+
ScheduleSpecialDayTextItem,
|
|
43
|
+
ScheduleShiftChangeTextItem,
|
|
44
|
+
ScheduleStandingScheduleTextInput,
|
|
45
|
+
ScheduleStandingTextItem,
|
|
46
|
+
ScheduleTaskStatusEnum,
|
|
47
|
+
ScheduleTextContext,
|
|
48
|
+
ScheduleTextDiagnostic,
|
|
49
|
+
ScheduleTextFinding,
|
|
50
|
+
ScheduleTextPerson,
|
|
51
|
+
ScheduleTextShift,
|
|
52
|
+
ScheduleTimeOffStatusEnum,
|
|
53
|
+
ScheduleTimeOffTextInput,
|
|
54
|
+
ScheduleTodoListTextInput,
|
|
55
|
+
ScheduleTodoTextItem,
|
|
56
|
+
ScheduleViolationMessageNames,
|
|
57
|
+
} from '../types/schedule.d.ts';
|
|
58
|
+
import {
|
|
59
|
+
getScheduleDaysBetween,
|
|
60
|
+
getScheduleLocalClockTime,
|
|
61
|
+
getScheduleLocalDate,
|
|
62
|
+
getScheduleWeekStart,
|
|
63
|
+
getScheduleWeekday,
|
|
64
|
+
isScheduleDateKey,
|
|
65
|
+
parseScheduleClockTime,
|
|
66
|
+
toScheduleTimeMs,
|
|
67
|
+
} from './localTime.ts';
|
|
68
|
+
|
|
69
|
+
// The Phase 4/5 text inputs live with every other text input in the types
|
|
70
|
+
// file; the formatters' callers may import them from here too
|
|
71
|
+
export type {
|
|
72
|
+
SchedulePlanSummaryTextInput,
|
|
73
|
+
ScheduleProgressCheckTextInput,
|
|
74
|
+
ScheduleProjectDigestTextInput,
|
|
75
|
+
ScheduleProjectSlipTextInput,
|
|
76
|
+
ScheduleTodoListTextInput,
|
|
77
|
+
ScheduleTodoTextItem,
|
|
78
|
+
} from '../types/schedule.d.ts';
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Every schedule text (IMPLEMENTATION §1.13), rendered from plain data:
|
|
82
|
+
* a period summary, a diff against the previous period, my shifts, a change
|
|
83
|
+
* notice, a request, a time-off request, a candidate list, coverage
|
|
84
|
+
* findings, the standing schedule, an eligibility reason, a stored violation
|
|
85
|
+
* message, the email subject of a notice, the Phase 2 chat loop (each
|
|
86
|
+
* ask's question, its one-line summary, the reply to its answer, the
|
|
87
|
+
* reminder and closing notes, an offer's progress and the open-ask
|
|
88
|
+
* overview), the Phase 3 preparation (the per-week diff, covers, repeat
|
|
89
|
+
* lines and each edit of the standing-instructions pass), Phase 4 to-dos (a
|
|
90
|
+
* list and the assigned notice) and Phase 5 projects by chat (the plan
|
|
91
|
+
* summary of a review, a progress check-in, the weekly digest and the slip
|
|
92
|
+
* notice). No tool, notice or ask builds its own sentences.
|
|
93
|
+
*
|
|
94
|
+
* - Plain English, no i18n. Every time is rendered in the shift's zone
|
|
95
|
+
* (`shift.timeZone ?? context.timeZone`), a to-do's own zone, or the
|
|
96
|
+
* project's zone, never UTC or the host's zone: `Fri Dec 4, 8pm-2am`; a
|
|
97
|
+
* range crossing midnight shows only the start's day. A finish or deadline
|
|
98
|
+
* instant is an exclusive end: it names the local date of the instant just
|
|
99
|
+
* before it (a deadline at midnight is the day before).
|
|
100
|
+
* - GSM-7 only. Literals use ASCII `-`, `'` and `"`, and typographic
|
|
101
|
+
* punctuation in names and notes is folded to them, because one en dash or
|
|
102
|
+
* curly quote turns an SMS into UCS-2 and halves its capacity.
|
|
103
|
+
* - SMS-bound texts (period summary, my shifts, a change notice, a request to
|
|
104
|
+
* its requester or counterparty, the assigned to-do, a plan review, a
|
|
105
|
+
* check-in, the digest, the slip notice) fit SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS
|
|
106
|
+
* segments: they list exceptions, not every shift, and drop detail lines
|
|
107
|
+
* (never the counts, the blockers or the link) until they fit. Tool-only
|
|
108
|
+
* texts cap their lists instead.
|
|
109
|
+
* - Every ask-style text ends with how to answer it; `context.link` is the
|
|
110
|
+
* last line when set.
|
|
111
|
+
*/
|
|
112
|
+
|
|
113
|
+
const FILE_CONSTANTS = {
|
|
114
|
+
weekdayShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
|
|
115
|
+
weekdayLong: [
|
|
116
|
+
'Sunday',
|
|
117
|
+
'Monday',
|
|
118
|
+
'Tuesday',
|
|
119
|
+
'Wednesday',
|
|
120
|
+
'Thursday',
|
|
121
|
+
'Friday',
|
|
122
|
+
'Saturday',
|
|
123
|
+
],
|
|
124
|
+
monthShort: [
|
|
125
|
+
'Jan',
|
|
126
|
+
'Feb',
|
|
127
|
+
'Mar',
|
|
128
|
+
'Apr',
|
|
129
|
+
'May',
|
|
130
|
+
'Jun',
|
|
131
|
+
'Jul',
|
|
132
|
+
'Aug',
|
|
133
|
+
'Sep',
|
|
134
|
+
'Oct',
|
|
135
|
+
'Nov',
|
|
136
|
+
'Dec',
|
|
137
|
+
],
|
|
138
|
+
numberWords: [
|
|
139
|
+
'zero',
|
|
140
|
+
'one',
|
|
141
|
+
'two',
|
|
142
|
+
'three',
|
|
143
|
+
'four',
|
|
144
|
+
'five',
|
|
145
|
+
'six',
|
|
146
|
+
'seven',
|
|
147
|
+
'eight',
|
|
148
|
+
'nine',
|
|
149
|
+
'ten',
|
|
150
|
+
],
|
|
151
|
+
// GSM 03.38 basic set (without ESC) and extension table (two units each)
|
|
152
|
+
gsmBasic: new Set(
|
|
153
|
+
'@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà',
|
|
154
|
+
),
|
|
155
|
+
gsmExtension: new Set('^{}\\[~]|€\f'),
|
|
156
|
+
// Items listed before "+N more": SMS lists start at this many, tool lists stop at it
|
|
157
|
+
smsListCap: 5,
|
|
158
|
+
toolListCap: 20,
|
|
159
|
+
// No single SMS detail line is longer than one segment
|
|
160
|
+
smsLineMaxLength: 160,
|
|
161
|
+
// Notes and reasons quoted in an SMS
|
|
162
|
+
smsQuoteMaxLength: 300,
|
|
163
|
+
nameListCap: 5,
|
|
164
|
+
// Refusal clauses quoted in an answer reply (with its sentence, two segments)
|
|
165
|
+
replyClausesMaxLength: 240,
|
|
166
|
+
// A reply quoted in the open-ask overview
|
|
167
|
+
overviewReplyMaxLength: 80,
|
|
168
|
+
// Waves named one by one in an offer text before "+N more waves"
|
|
169
|
+
offerWaveCap: 4,
|
|
170
|
+
// Shortening steps (characters) and floors of clipped SMS parts: a
|
|
171
|
+
// check-in's activity names, an assigned to-do's title
|
|
172
|
+
clipStep: 4,
|
|
173
|
+
progressNameMaxLength: 60,
|
|
174
|
+
progressNameMinLength: 15,
|
|
175
|
+
todoTitleMinLength: 30,
|
|
176
|
+
// Activity names quoted in a plan-review reply
|
|
177
|
+
activityNameMaxLength: 40,
|
|
178
|
+
// Email subject of each notice kind (SMS and in-app use the body)
|
|
179
|
+
noticeSubjects: {
|
|
180
|
+
SCHEDULE_PUBLISHED: 'Your schedule was published',
|
|
181
|
+
SHIFTS_CHANGED: 'Your shifts changed',
|
|
182
|
+
REQUEST_OPENED: 'A shift request needs a decision',
|
|
183
|
+
REQUEST_DECIDED: 'Your shift request was updated',
|
|
184
|
+
CALL_OUT: 'Someone called out of a shift',
|
|
185
|
+
OFFER_FILLED: 'An open shift was filled',
|
|
186
|
+
OFFER_UNFILLED: 'An open shift was not filled',
|
|
187
|
+
TIME_OFF_REQUESTED: 'Time off was requested',
|
|
188
|
+
TIME_OFF_DECIDED: 'Time off was updated',
|
|
189
|
+
VIOLATION_RAISED: 'Schedule coverage needs attention',
|
|
190
|
+
TASK_ASSIGNED: 'You have a new to-do',
|
|
191
|
+
SCHEDULE_RUN_COMPLETE: 'Project schedule finished',
|
|
192
|
+
MILESTONE_AT_RISK: 'A milestone is at risk',
|
|
193
|
+
RESOURCE_OVERALLOCATED: 'A resource is overallocated',
|
|
194
|
+
PROJECT_DIGEST: 'Weekly project update',
|
|
195
|
+
} satisfies Record<ScheduleNotificationEventKindEnum, string>,
|
|
196
|
+
// How a request kind is named in a decision line and reply
|
|
197
|
+
requestNouns: {
|
|
198
|
+
CLAIM: 'claim',
|
|
199
|
+
DROP: 'drop',
|
|
200
|
+
CALL_OUT: 'call-out',
|
|
201
|
+
RETIME: 'new hours',
|
|
202
|
+
SWAP: 'swap',
|
|
203
|
+
} satisfies Record<ScheduleRequestKindEnum, string>,
|
|
204
|
+
// What SMS consent is for, by the organization's scheduling type: the
|
|
205
|
+
// question's "about ..." and the texts' name
|
|
206
|
+
consentTopics: {
|
|
207
|
+
STAFF_SCHEDULES: { about: 'your shifts', texts: 'shift texts' },
|
|
208
|
+
PROJECT_MANAGEMENT: { about: 'your project work', texts: 'project texts' },
|
|
209
|
+
} satisfies Record<
|
|
210
|
+
ScheduleSchedulingTypeEnum,
|
|
211
|
+
{ about: string; texts: string }
|
|
212
|
+
>,
|
|
213
|
+
// The title of a plan text's path: the critical activities, or the
|
|
214
|
+
// longest path when none is critical (decision: the path that drives the
|
|
215
|
+
// finish); "newly" heads a digest's additions to it
|
|
216
|
+
criticalPathTitles: {
|
|
217
|
+
CRITICAL: { path: 'Critical path', newly: 'Newly critical' },
|
|
218
|
+
LONGEST: {
|
|
219
|
+
path: 'Path that drives the finish',
|
|
220
|
+
newly: 'Newly driving the finish',
|
|
221
|
+
},
|
|
222
|
+
} satisfies Record<
|
|
223
|
+
ScheduleCriticalPathKindEnum,
|
|
224
|
+
{ path: string; newly: string }
|
|
225
|
+
>,
|
|
226
|
+
// Why an offer candidate was not texted
|
|
227
|
+
askSkipReasons: {
|
|
228
|
+
NO_CONTACT: 'no phone',
|
|
229
|
+
NOT_OPTED_IN: 'no shift-text consent',
|
|
230
|
+
OPTED_OUT: 'opted out of shift texts',
|
|
231
|
+
CHANNEL_OFF: 'texts turned off',
|
|
232
|
+
NO_ACCESS: 'no access',
|
|
233
|
+
BECAME_INELIGIBLE: "can't take it now",
|
|
234
|
+
} as Partial<Record<ScheduleAskReasonEnum, string>>,
|
|
235
|
+
// A to-do's status after its line (OPEN says nothing) and its list group
|
|
236
|
+
// (open first, then done, then canceled)
|
|
237
|
+
todoStatusSuffixes: {
|
|
238
|
+
OPEN: '',
|
|
239
|
+
IN_PROGRESS: ' (in progress)',
|
|
240
|
+
DONE: ' (done)',
|
|
241
|
+
CANCELED: ' (canceled)',
|
|
242
|
+
} satisfies Record<ScheduleTaskStatusEnum, string>,
|
|
243
|
+
todoGroups: {
|
|
244
|
+
OPEN: 0,
|
|
245
|
+
IN_PROGRESS: 0,
|
|
246
|
+
DONE: 1,
|
|
247
|
+
CANCELED: 2,
|
|
248
|
+
} satisfies Record<ScheduleTaskStatusEnum, number>,
|
|
249
|
+
// An offer's status, in its status text
|
|
250
|
+
offerStatuses: {
|
|
251
|
+
OPEN: 'open',
|
|
252
|
+
FILLED: 'filled',
|
|
253
|
+
UNFILLED: 'nobody took it',
|
|
254
|
+
EXPIRED: 'expired',
|
|
255
|
+
CANCELLED: 'closed',
|
|
256
|
+
} satisfies Record<ScheduleOfferStatusEnum, string>,
|
|
257
|
+
// Where a decided time off stands
|
|
258
|
+
timeOffOutcomes: {
|
|
259
|
+
PENDING: 'is waiting for a manager',
|
|
260
|
+
APPROVED: 'was approved',
|
|
261
|
+
DECLINED: 'was declined',
|
|
262
|
+
CANCELLED: 'was canceled',
|
|
263
|
+
} satisfies Record<ScheduleTimeOffStatusEnum, string>,
|
|
264
|
+
// A WARN eligibility code as a short candidate clause
|
|
265
|
+
warningClauses: {
|
|
266
|
+
MAX_HOURS: 'would go over the hours limit',
|
|
267
|
+
UNAVAILABLE: 'marked unavailable then',
|
|
268
|
+
MIN_REST: 'short rest between shifts',
|
|
269
|
+
MAX_CONSECUTIVE_DAYS: 'many days in a row',
|
|
270
|
+
SHIFT_LENGTH: 'outside the shift length limit',
|
|
271
|
+
} as Record<string, string>,
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// A list block of a text: a title, detail lines and how far it may shrink
|
|
275
|
+
interface ScheduleTextSection {
|
|
276
|
+
title: string | null; // null = items render as plain lines
|
|
277
|
+
items: string[];
|
|
278
|
+
shown: number;
|
|
279
|
+
soft: number; // trimmed to this many first, across every section
|
|
280
|
+
min: number; // then to this many
|
|
281
|
+
keepTitle: boolean; // render the title alone once every item is hidden
|
|
282
|
+
join: string | null; // set: one "Title: a<join>b +N more." line instead of "- item" lines
|
|
283
|
+
extraCount: number; // items not given (a capped payload), counted in "+N more"
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
type ScheduleTextPart = string | ScheduleTextSection | null;
|
|
287
|
+
|
|
288
|
+
// A wall-clock reading of an instant in a zone
|
|
289
|
+
interface ScheduleLocalPoint {
|
|
290
|
+
date: string;
|
|
291
|
+
minutes: number;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/*
|
|
295
|
+
* Write a count with its noun: "1 shift", "3 shifts".
|
|
296
|
+
*/
|
|
297
|
+
function pluralize(
|
|
298
|
+
count: number,
|
|
299
|
+
singular: string,
|
|
300
|
+
plural = `${singular}s`,
|
|
301
|
+
): string {
|
|
302
|
+
return `${count} ${count === 1 ? singular : plural}`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/*
|
|
306
|
+
* Write a small count as a word ("three"), larger ones as digits.
|
|
307
|
+
*/
|
|
308
|
+
function formatCountWord(count: number): string {
|
|
309
|
+
return FILE_CONSTANTS.numberWords[count] ?? String(count);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/*
|
|
313
|
+
* Join names as "Ana", "Ana and Ben" or "Ana, Ben and Cam".
|
|
314
|
+
*/
|
|
315
|
+
function formatAndList(names: string[]): string {
|
|
316
|
+
if (names.length <= 1) return names[0] ?? '';
|
|
317
|
+
return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/*
|
|
321
|
+
* Join names with a cap: "Ana, Ben +3 more".
|
|
322
|
+
*/
|
|
323
|
+
function formatNameList(names: string[]): string {
|
|
324
|
+
const shown = names.slice(0, FILE_CONSTANTS.nameListCap);
|
|
325
|
+
const hidden = names.length - shown.length;
|
|
326
|
+
return `${shown.join(', ')}${hidden ? ` +${hidden} more` : ''}`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/*
|
|
330
|
+
* Shorten a line to at most `max` characters, ending in "..." when cut.
|
|
331
|
+
*/
|
|
332
|
+
function clipText(text: string, max: number): string {
|
|
333
|
+
return text.length > max ? `${text.slice(0, max - 3).trimEnd()}...` : text;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/*
|
|
337
|
+
* End a sentence with a period unless it already ends with punctuation.
|
|
338
|
+
*/
|
|
339
|
+
function ensurePeriod(text: string): string {
|
|
340
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/*
|
|
344
|
+
* Order two strings by code unit (deterministic tie-breaks; the text never
|
|
345
|
+
* needs numeric id order).
|
|
346
|
+
*/
|
|
347
|
+
function compareText(a: string, b: string): number {
|
|
348
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/*
|
|
352
|
+
* Replace typographic punctuation (curly quotes, dashes, ellipsis,
|
|
353
|
+
* non-breaking spaces) with its GSM-7 equivalent. Exported for validators
|
|
354
|
+
* that store text a schedule SMS will quote (an offer's message).
|
|
355
|
+
*/
|
|
356
|
+
export function toScheduleGsmText(text: string): string {
|
|
357
|
+
return text
|
|
358
|
+
.replace(/[‘’‚‛′]/g, "'")
|
|
359
|
+
.replace(/[“”„‟″]/g, '"')
|
|
360
|
+
.replace(/[‐-―−]/g, '-')
|
|
361
|
+
.replace(/…/g, '...')
|
|
362
|
+
.replace(/[ ]/g, ' ');
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/*
|
|
366
|
+
* Join a text's lines (empty ones dropped) with GSM-7 punctuation.
|
|
367
|
+
*/
|
|
368
|
+
function joinScheduleText(lines: Array<string | null | undefined>): string {
|
|
369
|
+
return toScheduleGsmText(lines.filter(Boolean).join('\n'));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/*
|
|
373
|
+
* Cap a tool-text list: the first `cap` lines, then "+N more".
|
|
374
|
+
*/
|
|
375
|
+
function capLines(lines: string[], cap: number): string[] {
|
|
376
|
+
const hidden = lines.length - cap;
|
|
377
|
+
return hidden > 0 ? [...lines.slice(0, cap), `+${hidden} more`] : lines;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/*
|
|
381
|
+
* Build a list section showing at most `cap` items. Trimming first brings
|
|
382
|
+
* every section down to `soft` items, then to `min`. Items are clipped to
|
|
383
|
+
* one SMS segment.
|
|
384
|
+
*/
|
|
385
|
+
function createSection(args: {
|
|
386
|
+
title: string | null;
|
|
387
|
+
items: string[];
|
|
388
|
+
cap: number;
|
|
389
|
+
min?: number;
|
|
390
|
+
soft?: number;
|
|
391
|
+
keepTitle?: boolean;
|
|
392
|
+
join?: string;
|
|
393
|
+
extraCount?: number;
|
|
394
|
+
}): ScheduleTextSection {
|
|
395
|
+
const shown = Math.min(args.items.length, args.cap);
|
|
396
|
+
const min = Math.min(shown, args.min ?? 0);
|
|
397
|
+
return {
|
|
398
|
+
title: args.title,
|
|
399
|
+
items: args.items.map((item) =>
|
|
400
|
+
clipText(item, FILE_CONSTANTS.smsLineMaxLength),
|
|
401
|
+
),
|
|
402
|
+
shown,
|
|
403
|
+
soft: Math.max(min, Math.min(shown, args.soft ?? min)),
|
|
404
|
+
min,
|
|
405
|
+
keepTitle: args.keepTitle ?? false,
|
|
406
|
+
join: args.join ?? null,
|
|
407
|
+
extraCount: Math.max(0, args.extraCount ?? 0),
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/*
|
|
412
|
+
* Render a section with its current number of shown items: the title (with
|
|
413
|
+
* ':' when items follow), "- item" lines and "+N more"; a joined section is
|
|
414
|
+
* one line, "Title: a, b +N more.".
|
|
415
|
+
*/
|
|
416
|
+
function renderSection(section: ScheduleTextSection): string[] {
|
|
417
|
+
if (!section.items.length) return [];
|
|
418
|
+
const shown = section.items.slice(0, section.shown);
|
|
419
|
+
if (!shown.length)
|
|
420
|
+
return section.keepTitle && section.title ? [`${section.title}.`] : [];
|
|
421
|
+
const hidden = section.items.length - shown.length + section.extraCount;
|
|
422
|
+
if (section.join !== null) {
|
|
423
|
+
const more = hidden > 0 ? ` +${hidden} more` : '';
|
|
424
|
+
const title = section.title ? `${section.title}: ` : '';
|
|
425
|
+
return [ensurePeriod(`${title}${shown.join(section.join)}${more}`)];
|
|
426
|
+
}
|
|
427
|
+
const lines = section.title
|
|
428
|
+
? [`${section.title}:`, ...shown.map((item) => `- ${item}`)]
|
|
429
|
+
: [...shown];
|
|
430
|
+
if (hidden > 0) lines.push(`+${hidden} more`);
|
|
431
|
+
return lines;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/*
|
|
435
|
+
* Render fixed lines and sections in order into one text.
|
|
436
|
+
*/
|
|
437
|
+
function renderScheduleTextParts(parts: ScheduleTextPart[]): string {
|
|
438
|
+
return joinScheduleText(
|
|
439
|
+
parts.flatMap((part) =>
|
|
440
|
+
part === null
|
|
441
|
+
? []
|
|
442
|
+
: typeof part === 'string'
|
|
443
|
+
? [part]
|
|
444
|
+
: renderSection(part),
|
|
445
|
+
),
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/*
|
|
450
|
+
* Say how many standing shifts preparing skips (their role archived or room
|
|
451
|
+
* retired) and how to fix it; null when there are none.
|
|
452
|
+
*/
|
|
453
|
+
function getUnusableStandingLine(count: number): string | null {
|
|
454
|
+
if (count < 1) return null;
|
|
455
|
+
return `${pluralize(count, 'standing shift')} not made: role archived or room retired. Change the standing schedule.`;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/*
|
|
459
|
+
* Render the parts, hiding one item at a time until the text fits
|
|
460
|
+
* maxSegments SMS segments: first from the first section in dropOrder that
|
|
461
|
+
* is above its soft floor, then from the first one above its minimum.
|
|
462
|
+
* Returns the best effort when nothing more may be dropped.
|
|
463
|
+
*/
|
|
464
|
+
function fitScheduleTextParts(
|
|
465
|
+
parts: ScheduleTextPart[],
|
|
466
|
+
dropOrder: ScheduleTextSection[],
|
|
467
|
+
maxSegments: number,
|
|
468
|
+
): string {
|
|
469
|
+
let text = renderScheduleTextParts(parts);
|
|
470
|
+
while (getScheduleSmsSegmentCount(text) > maxSegments) {
|
|
471
|
+
const section =
|
|
472
|
+
dropOrder.find((entry) => entry.shown > entry.soft) ??
|
|
473
|
+
dropOrder.find((entry) => entry.shown > entry.min);
|
|
474
|
+
if (!section) break;
|
|
475
|
+
section.shown -= 1;
|
|
476
|
+
text = renderScheduleTextParts(parts);
|
|
477
|
+
}
|
|
478
|
+
return text;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/*
|
|
482
|
+
* Format minutes since local midnight on a 12-hour clock: 8am, 8:30pm,
|
|
483
|
+
* 12am (midnight), 12pm (noon).
|
|
484
|
+
*/
|
|
485
|
+
function formatClock(minutes: number): string {
|
|
486
|
+
const hours = Math.floor(minutes / 60);
|
|
487
|
+
const rest = minutes % 60;
|
|
488
|
+
const hour12 = hours % 12 || 12;
|
|
489
|
+
const suffix = hours < 12 ? 'am' : 'pm';
|
|
490
|
+
return rest
|
|
491
|
+
? `${hour12}:${String(rest).padStart(2, '0')}${suffix}`
|
|
492
|
+
: `${hour12}${suffix}`;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/*
|
|
496
|
+
* Format a 'HH:mm' clock range on a 12-hour clock ("8pm-2am"); an end at or
|
|
497
|
+
* before the start is the next day, as everywhere in the engine.
|
|
498
|
+
*/
|
|
499
|
+
function formatClockTextRange(startTime: string, endTime: string): string {
|
|
500
|
+
const start = parseScheduleClockTime(startTime);
|
|
501
|
+
const end = parseScheduleClockTime(endTime);
|
|
502
|
+
if (start === null || end === null) return `${startTime}-${endTime}`;
|
|
503
|
+
return `${formatClock(start)}-${formatClock(end)}`;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/*
|
|
507
|
+
* Format worked or rest minutes: "40h", "7h 30m", "45m".
|
|
508
|
+
*/
|
|
509
|
+
function formatScheduleDuration(minutes: number): string {
|
|
510
|
+
const total = Math.max(0, Math.round(minutes));
|
|
511
|
+
const hours = Math.floor(total / 60);
|
|
512
|
+
const rest = total % 60;
|
|
513
|
+
if (!hours) return `${rest}m`;
|
|
514
|
+
return rest ? `${hours}h ${rest}m` : `${hours}h`;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/*
|
|
518
|
+
* Format a date key as "Dec 4".
|
|
519
|
+
*/
|
|
520
|
+
function formatMonthDay(dateKey: string): string {
|
|
521
|
+
const [, month, day] = dateKey.split('-').map(Number);
|
|
522
|
+
return `${FILE_CONSTANTS.monthShort[month - 1]} ${day}`;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/*
|
|
526
|
+
* Format a date key as "Fri Dec 4".
|
|
527
|
+
*/
|
|
528
|
+
function formatScheduleDay(dateKey: string): string {
|
|
529
|
+
return `${FILE_CONSTANTS.weekdayShort[getScheduleWeekday(dateKey)]} ${formatMonthDay(dateKey)}`;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/*
|
|
533
|
+
* Format an inclusive date range: "Dec 14-20", "Nov 30-Dec 6", or one day
|
|
534
|
+
* as "Fri Dec 18".
|
|
535
|
+
*/
|
|
536
|
+
export function formatScheduleDateRange(
|
|
537
|
+
fromDate: string,
|
|
538
|
+
toDate: string,
|
|
539
|
+
): string {
|
|
540
|
+
if (fromDate === toDate) return formatScheduleDay(fromDate);
|
|
541
|
+
if (fromDate.slice(0, 7) === toDate.slice(0, 7))
|
|
542
|
+
return `${formatMonthDay(fromDate)}-${Number(toDate.slice(8, 10))}`;
|
|
543
|
+
return `${formatMonthDay(fromDate)}-${formatMonthDay(toDate)}`;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/*
|
|
547
|
+
* Read an instant's local date and minutes since midnight in a zone (an
|
|
548
|
+
* unknown zone throws a RangeError, as in localTime.ts).
|
|
549
|
+
*/
|
|
550
|
+
function getLocalPoint(
|
|
551
|
+
at: Date | string,
|
|
552
|
+
timeZone: string,
|
|
553
|
+
): ScheduleLocalPoint {
|
|
554
|
+
return {
|
|
555
|
+
date: getScheduleLocalDate(at, timeZone),
|
|
556
|
+
minutes: parseScheduleClockTime(
|
|
557
|
+
getScheduleLocalClockTime(at, timeZone),
|
|
558
|
+
) as number,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/*
|
|
563
|
+
* Format the clock part of a range from its local start and end: "8pm-2am"
|
|
564
|
+
* when it ends the same day or overnight before its start time, else with
|
|
565
|
+
* the end's day ("8am-Sat 10am", "8am-Sun Dec 6 8am").
|
|
566
|
+
*/
|
|
567
|
+
function formatClockRange(
|
|
568
|
+
start: ScheduleLocalPoint,
|
|
569
|
+
end: ScheduleLocalPoint,
|
|
570
|
+
): string {
|
|
571
|
+
const days = getScheduleDaysBetween(start.date, end.date);
|
|
572
|
+
const startText = formatClock(start.minutes);
|
|
573
|
+
if (days === 0 || (days === 1 && end.minutes < start.minutes))
|
|
574
|
+
return `${startText}-${formatClock(end.minutes)}`;
|
|
575
|
+
const endDay =
|
|
576
|
+
days === 1
|
|
577
|
+
? FILE_CONSTANTS.weekdayShort[getScheduleWeekday(end.date)]
|
|
578
|
+
: formatScheduleDay(end.date);
|
|
579
|
+
return `${startText}-${endDay} ${formatClock(end.minutes)}`;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/*
|
|
583
|
+
* Format the clock part of an instant range in a zone ("8pm-2am"); an empty
|
|
584
|
+
* or inverted range shows its start only.
|
|
585
|
+
*/
|
|
586
|
+
function formatScheduleClockRange(
|
|
587
|
+
startAt: Date | string,
|
|
588
|
+
endAt: Date | string,
|
|
589
|
+
timeZone: string,
|
|
590
|
+
): string {
|
|
591
|
+
const start = getLocalPoint(startAt, timeZone);
|
|
592
|
+
if (!(toScheduleTimeMs(endAt) > toScheduleTimeMs(startAt)))
|
|
593
|
+
return formatClock(start.minutes);
|
|
594
|
+
return formatClockRange(start, getLocalPoint(endAt, timeZone));
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/*
|
|
598
|
+
* Format an instant range in a zone: "Fri Dec 4, 8pm-2am" (the start's day;
|
|
599
|
+
* the end's day only when the clock alone would mislead).
|
|
600
|
+
*/
|
|
601
|
+
export function formatScheduleTimeRange(
|
|
602
|
+
startAt: Date | string,
|
|
603
|
+
endAt: Date | string,
|
|
604
|
+
timeZone: string,
|
|
605
|
+
): string {
|
|
606
|
+
const day = formatScheduleDay(getScheduleLocalDate(startAt, timeZone));
|
|
607
|
+
return `${day}, ${formatScheduleClockRange(startAt, endAt, timeZone)}`;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/*
|
|
611
|
+
* Format one instant in a zone: "Thu Dec 3, 9:12pm" (minutes only when not
|
|
612
|
+
* on the hour).
|
|
613
|
+
*/
|
|
614
|
+
export function formatScheduleInstant(
|
|
615
|
+
at: Date | string,
|
|
616
|
+
timeZone: string,
|
|
617
|
+
): string {
|
|
618
|
+
const point = getLocalPoint(at, timeZone);
|
|
619
|
+
return `${formatScheduleDay(point.date)}, ${formatClock(point.minutes)}`;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/*
|
|
623
|
+
* Read the local date an exclusive end instant (a finish, a deadline) names
|
|
624
|
+
* in a zone: the date of the instant just before it, so an end at local
|
|
625
|
+
* midnight is the day before.
|
|
626
|
+
*/
|
|
627
|
+
function getFinishLocalDate(at: Date | string, timeZone: string): string {
|
|
628
|
+
return getScheduleLocalDate(new Date(toScheduleTimeMs(at) - 1), timeZone);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/*
|
|
632
|
+
* Compare two local dates in whole days with the words for later, earlier
|
|
633
|
+
* and the same day: "5 days after the baseline", "same as last week".
|
|
634
|
+
*/
|
|
635
|
+
function formatDayDifference(
|
|
636
|
+
fromDate: string,
|
|
637
|
+
toDate: string,
|
|
638
|
+
words: { later: string; earlier: string; same: string },
|
|
639
|
+
): string {
|
|
640
|
+
const days = getScheduleDaysBetween(fromDate, toDate);
|
|
641
|
+
if (!days) return words.same;
|
|
642
|
+
return `${pluralize(Math.abs(days), 'day')} ${days > 0 ? words.later : words.earlier}`;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/*
|
|
646
|
+
* Format a new range against an old one: the clock only when both start on
|
|
647
|
+
* the same local day ("9pm-3am"), else the full range.
|
|
648
|
+
*/
|
|
649
|
+
function formatTimeRangeAfter(
|
|
650
|
+
before: { startAt: Date | string },
|
|
651
|
+
startAt: Date | string,
|
|
652
|
+
endAt: Date | string,
|
|
653
|
+
timeZone: string,
|
|
654
|
+
): string {
|
|
655
|
+
return getScheduleLocalDate(before.startAt, timeZone) ===
|
|
656
|
+
getScheduleLocalDate(startAt, timeZone)
|
|
657
|
+
? formatScheduleClockRange(startAt, endAt, timeZone)
|
|
658
|
+
: formatScheduleTimeRange(startAt, endAt, timeZone);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/*
|
|
662
|
+
* Pick the zone a seat is rendered in: its own calendar's, else the
|
|
663
|
+
* context's.
|
|
664
|
+
*/
|
|
665
|
+
function getShiftZone(
|
|
666
|
+
shift: Pick<ScheduleTextShift, 'timeZone'>,
|
|
667
|
+
context: ScheduleTextContext,
|
|
668
|
+
): string {
|
|
669
|
+
return shift.timeZone || context.timeZone;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/*
|
|
673
|
+
* Name what a seat is: "Bartender (close)", "Bartender", "close", or null.
|
|
674
|
+
*/
|
|
675
|
+
function getShiftTitle(
|
|
676
|
+
roleName: string | null,
|
|
677
|
+
label: string | null,
|
|
678
|
+
): string | null {
|
|
679
|
+
if (roleName && label) return `${roleName} (${label})`;
|
|
680
|
+
return roleName || label || null;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/*
|
|
684
|
+
* Describe a seat's role, label, location and calendar: "Bartender (close)
|
|
685
|
+
* at Main bar (Downtown)"; '' when it has none of them.
|
|
686
|
+
*/
|
|
687
|
+
function getShiftDescription(
|
|
688
|
+
shift: Pick<ScheduleTextShift, 'roleName' | 'label' | 'locationName'> & {
|
|
689
|
+
calendarName?: string | null;
|
|
690
|
+
},
|
|
691
|
+
): string {
|
|
692
|
+
return [
|
|
693
|
+
getShiftTitle(shift.roleName, shift.label),
|
|
694
|
+
shift.locationName ? `at ${shift.locationName}` : null,
|
|
695
|
+
shift.calendarName ? `(${shift.calendarName})` : null,
|
|
696
|
+
]
|
|
697
|
+
.filter(Boolean)
|
|
698
|
+
.join(' ');
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/*
|
|
702
|
+
* Name who holds a seat: the assignee, or "open".
|
|
703
|
+
*/
|
|
704
|
+
function getAssigneeText(
|
|
705
|
+
shift: Pick<ScheduleTextShift, 'assigneeResourceId' | 'assigneeName'>,
|
|
706
|
+
): string {
|
|
707
|
+
if (!shift.assigneeResourceId) return 'open';
|
|
708
|
+
return shift.assigneeName || 'assigned';
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/*
|
|
712
|
+
* Render one seat as a line: "Fri Dec 4, 8pm-2am Bartender (close) at Main
|
|
713
|
+
* bar", with " - Ana" / " - open" when asked and " (canceled)" for a
|
|
714
|
+
* canceled seat.
|
|
715
|
+
*/
|
|
716
|
+
export function formatScheduleShiftLine(
|
|
717
|
+
shift: ScheduleTextShift,
|
|
718
|
+
context: ScheduleTextContext,
|
|
719
|
+
options?: { withAssignee?: boolean },
|
|
720
|
+
): string {
|
|
721
|
+
const range = formatScheduleTimeRange(
|
|
722
|
+
shift.startAt,
|
|
723
|
+
shift.endAt,
|
|
724
|
+
getShiftZone(shift, context),
|
|
725
|
+
);
|
|
726
|
+
const description = getShiftDescription(shift);
|
|
727
|
+
let line = description ? `${range} ${description}` : range;
|
|
728
|
+
if (options?.withAssignee) line += ` - ${getAssigneeText(shift)}`;
|
|
729
|
+
if (shift.status === 'CANCELED') line += ' (canceled)';
|
|
730
|
+
return line;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/*
|
|
734
|
+
* Name a rotation week 1..4 as A..D (any other number as itself).
|
|
735
|
+
*/
|
|
736
|
+
export function getScheduleRotationWeekLabel(week: number): string {
|
|
737
|
+
return SCHEDULE_ROTATION_WEEK_LABELS[week - 1] ?? String(week);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/*
|
|
741
|
+
* Build the read-only roster link for one calendar and date
|
|
742
|
+
* (IMPLEMENTATION §1.13).
|
|
743
|
+
*/
|
|
744
|
+
export function getScheduleRosterLink(
|
|
745
|
+
origin: string,
|
|
746
|
+
calendarId: string,
|
|
747
|
+
date: string,
|
|
748
|
+
): string {
|
|
749
|
+
return `${origin.replace(/\/+$/, '')}/app/calendar?cal=${encodeURIComponent(calendarId)}&v=roster&d=${encodeURIComponent(date)}`;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/*
|
|
753
|
+
* Build the "my shifts" link (IMPLEMENTATION §1.13).
|
|
754
|
+
*/
|
|
755
|
+
export function getScheduleMyShiftsLink(origin: string): string {
|
|
756
|
+
return `${origin.replace(/\/+$/, '')}/app/calendar?me=1`;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/*
|
|
760
|
+
* Count the SMS segments a text takes. GSM-7: the basic set is one unit,
|
|
761
|
+
* the extension set (^{}\[~]|€) two; up to 160 units is one segment, else
|
|
762
|
+
* ceil(units / 153). Any other character makes it UCS-2: up to 70 UTF-16
|
|
763
|
+
* units is one segment, else ceil(length / 67).
|
|
764
|
+
*/
|
|
765
|
+
export function getScheduleSmsSegmentCount(text: string): number {
|
|
766
|
+
let units = 0;
|
|
767
|
+
for (const char of text) {
|
|
768
|
+
if (FILE_CONSTANTS.gsmBasic.has(char)) units += 1;
|
|
769
|
+
else if (FILE_CONSTANTS.gsmExtension.has(char)) units += 2;
|
|
770
|
+
else return text.length <= 70 ? 1 : Math.ceil(text.length / 67);
|
|
771
|
+
}
|
|
772
|
+
return units <= 160 ? 1 : Math.ceil(units / 153);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/*
|
|
776
|
+
* Order seats by start, end, then id, so every list reads the same way.
|
|
777
|
+
*/
|
|
778
|
+
function sortTextShifts(shifts: ScheduleTextShift[]): ScheduleTextShift[] {
|
|
779
|
+
return [...shifts].sort(
|
|
780
|
+
(a, b) =>
|
|
781
|
+
toScheduleTimeMs(a.startAt) - toScheduleTimeMs(b.startAt) ||
|
|
782
|
+
toScheduleTimeMs(a.endAt) - toScheduleTimeMs(b.endAt) ||
|
|
783
|
+
compareText(a.id, b.id),
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/*
|
|
788
|
+
* Keep the seats that are not canceled, in reading order.
|
|
789
|
+
*/
|
|
790
|
+
function getLiveTextShifts(shifts: ScheduleTextShift[]): ScheduleTextShift[] {
|
|
791
|
+
return sortTextShifts(shifts.filter((shift) => shift.status !== 'CANCELED'));
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/*
|
|
795
|
+
* Order findings by start, then key.
|
|
796
|
+
*/
|
|
797
|
+
function sortTextFindings(
|
|
798
|
+
findings: ScheduleTextFinding[],
|
|
799
|
+
): ScheduleTextFinding[] {
|
|
800
|
+
return [...findings].sort(
|
|
801
|
+
(a, b) =>
|
|
802
|
+
toScheduleTimeMs(a.startAt) - toScheduleTimeMs(b.startAt) ||
|
|
803
|
+
compareText(a.key, b.key),
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/*
|
|
808
|
+
* Order people by name, then resource id.
|
|
809
|
+
*/
|
|
810
|
+
function sortTextPeople<T extends ScheduleTextPerson>(people: T[]): T[] {
|
|
811
|
+
return [...people].sort(
|
|
812
|
+
(a, b) =>
|
|
813
|
+
compareText(a.name, b.name) || compareText(a.resourceId, b.resourceId),
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/*
|
|
818
|
+
* The heading of a dated text: "Downtown, Dec 14-20" ("Schedule, ..." with
|
|
819
|
+
* no calendar name).
|
|
820
|
+
*/
|
|
821
|
+
function getScheduleTextTitle(
|
|
822
|
+
context: ScheduleTextContext,
|
|
823
|
+
fromDate: string,
|
|
824
|
+
toDate: string,
|
|
825
|
+
): string {
|
|
826
|
+
return `${context.calendarName || 'Schedule'}, ${formatScheduleDateRange(fromDate, toDate)}`;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/*
|
|
830
|
+
* Build the wall-clock signature of a seat: weekday, local start and end,
|
|
831
|
+
* role and location, in the seat's zone.
|
|
832
|
+
*/
|
|
833
|
+
function getSeatSignature(shift: ScheduleTextShift, timeZone: string): string {
|
|
834
|
+
const zone = shift.timeZone || timeZone;
|
|
835
|
+
return [
|
|
836
|
+
getScheduleWeekday(getScheduleLocalDate(shift.startAt, zone)),
|
|
837
|
+
getScheduleLocalClockTime(shift.startAt, zone),
|
|
838
|
+
getScheduleLocalClockTime(shift.endAt, zone),
|
|
839
|
+
shift.roleName ?? '',
|
|
840
|
+
shift.locationName ?? '',
|
|
841
|
+
].join('|');
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/*
|
|
845
|
+
* Group the assigned, live seats of a period by assignee, each list in
|
|
846
|
+
* reading order.
|
|
847
|
+
*/
|
|
848
|
+
function groupSeatsByPerson(
|
|
849
|
+
shifts: ScheduleTextShift[],
|
|
850
|
+
): Map<string, ScheduleTextShift[]> {
|
|
851
|
+
const byPerson = new Map<string, ScheduleTextShift[]>();
|
|
852
|
+
for (const shift of getLiveTextShifts(shifts)) {
|
|
853
|
+
if (!shift.assigneeResourceId) continue;
|
|
854
|
+
const seats = byPerson.get(shift.assigneeResourceId) ?? [];
|
|
855
|
+
seats.push(shift);
|
|
856
|
+
byPerson.set(shift.assigneeResourceId, seats);
|
|
857
|
+
}
|
|
858
|
+
return byPerson;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/*
|
|
862
|
+
* Name the person holding a list of seats (the first name given).
|
|
863
|
+
*/
|
|
864
|
+
function getSeatsPersonName(seats: ScheduleTextShift[]): string {
|
|
865
|
+
return seats.find((seat) => seat.assigneeName)?.assigneeName || 'Someone';
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/*
|
|
869
|
+
* Match one person's seats across two periods: first by template item when
|
|
870
|
+
* both seats have one, then by wall-clock signature (never pairing two
|
|
871
|
+
* different template items). Returns the unmatched seats of each side.
|
|
872
|
+
*/
|
|
873
|
+
function matchPeriodSeats(
|
|
874
|
+
previous: ScheduleTextShift[],
|
|
875
|
+
next: ScheduleTextShift[],
|
|
876
|
+
timeZone: string,
|
|
877
|
+
): { from: ScheduleTextShift[]; to: ScheduleTextShift[] } {
|
|
878
|
+
const unmatched = [...previous];
|
|
879
|
+
const pending: ScheduleTextShift[] = [];
|
|
880
|
+
for (const seat of next) {
|
|
881
|
+
const index = seat.templateItemId
|
|
882
|
+
? unmatched.findIndex(
|
|
883
|
+
(other) => other.templateItemId === seat.templateItemId,
|
|
884
|
+
)
|
|
885
|
+
: -1;
|
|
886
|
+
if (index >= 0) unmatched.splice(index, 1);
|
|
887
|
+
else pending.push(seat);
|
|
888
|
+
}
|
|
889
|
+
const to: ScheduleTextShift[] = [];
|
|
890
|
+
for (const seat of pending) {
|
|
891
|
+
const signature = getSeatSignature(seat, timeZone);
|
|
892
|
+
const index = unmatched.findIndex(
|
|
893
|
+
(other) =>
|
|
894
|
+
!(other.templateItemId && seat.templateItemId) &&
|
|
895
|
+
getSeatSignature(other, timeZone) === signature,
|
|
896
|
+
);
|
|
897
|
+
if (index >= 0) unmatched.splice(index, 1);
|
|
898
|
+
else to.push(seat);
|
|
899
|
+
}
|
|
900
|
+
return { from: unmatched, to };
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/*
|
|
904
|
+
* Collect a person's seats from weeks grouped by person, in week order.
|
|
905
|
+
*/
|
|
906
|
+
function getPersonSeatsOfWeeks(
|
|
907
|
+
weeks: Array<Map<string, ScheduleTextShift[]>>,
|
|
908
|
+
resourceId: string,
|
|
909
|
+
): ScheduleTextShift[] {
|
|
910
|
+
return weeks.flatMap((week) => week.get(resourceId) ?? []);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/*
|
|
914
|
+
* Compare a period with its baseline weeks by person: each
|
|
915
|
+
* week of the period against its own baseline week (the last published week
|
|
916
|
+
* of the same rotation week); weeks without a baseline are left out on both
|
|
917
|
+
* sides, and null when none is left. Seats are matched per person within
|
|
918
|
+
* each week (template item first, then wall clock). Across the compared
|
|
919
|
+
* weeks: who is new (seats in the period, none in any baseline), who is gone
|
|
920
|
+
* (the reverse), with seat counts, and who works different seats (each
|
|
921
|
+
* week's unmatched seats together). Open and canceled seats are not people.
|
|
922
|
+
*/
|
|
923
|
+
export function getSchedulePeriodWeekDiff(args: {
|
|
924
|
+
weeks: Array<{
|
|
925
|
+
previous: ScheduleTextShift[] | null;
|
|
926
|
+
next: ScheduleTextShift[];
|
|
927
|
+
}>;
|
|
928
|
+
timeZone: string;
|
|
929
|
+
}): SchedulePeriodDiffObj | null {
|
|
930
|
+
const compared = args.weeks.filter(
|
|
931
|
+
(
|
|
932
|
+
week,
|
|
933
|
+
): week is { previous: ScheduleTextShift[]; next: ScheduleTextShift[] } =>
|
|
934
|
+
week.previous !== null,
|
|
935
|
+
);
|
|
936
|
+
if (!compared.length) return null;
|
|
937
|
+
const previous = compared.map((week) => groupSeatsByPerson(week.previous));
|
|
938
|
+
const next = compared.map((week) => groupSeatsByPerson(week.next));
|
|
939
|
+
const previousIds = new Set(previous.flatMap((week) => [...week.keys()]));
|
|
940
|
+
const nextIds = new Set(next.flatMap((week) => [...week.keys()]));
|
|
941
|
+
const diff: SchedulePeriodDiffObj = {
|
|
942
|
+
newPeople: [],
|
|
943
|
+
gonePeople: [],
|
|
944
|
+
moved: [],
|
|
945
|
+
};
|
|
946
|
+
for (const resourceId of nextIds) {
|
|
947
|
+
const seats = getPersonSeatsOfWeeks(next, resourceId);
|
|
948
|
+
const name = getSeatsPersonName(seats);
|
|
949
|
+
if (!previousIds.has(resourceId)) {
|
|
950
|
+
diff.newPeople.push({ resourceId, name, shiftCount: seats.length });
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
const from: ScheduleTextShift[] = [];
|
|
954
|
+
const to: ScheduleTextShift[] = [];
|
|
955
|
+
compared.forEach((_, index) => {
|
|
956
|
+
const matched = matchPeriodSeats(
|
|
957
|
+
previous[index].get(resourceId) ?? [],
|
|
958
|
+
next[index].get(resourceId) ?? [],
|
|
959
|
+
args.timeZone,
|
|
960
|
+
);
|
|
961
|
+
from.push(...matched.from);
|
|
962
|
+
to.push(...matched.to);
|
|
963
|
+
});
|
|
964
|
+
if (from.length || to.length)
|
|
965
|
+
diff.moved.push({ resourceId, name, from, to });
|
|
966
|
+
}
|
|
967
|
+
for (const resourceId of previousIds)
|
|
968
|
+
if (!nextIds.has(resourceId)) {
|
|
969
|
+
const seats = getPersonSeatsOfWeeks(previous, resourceId);
|
|
970
|
+
diff.gonePeople.push({
|
|
971
|
+
resourceId,
|
|
972
|
+
name: getSeatsPersonName(seats),
|
|
973
|
+
shiftCount: seats.length,
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
return {
|
|
977
|
+
newPeople: sortTextPeople(diff.newPeople),
|
|
978
|
+
gonePeople: sortTextPeople(diff.gonePeople),
|
|
979
|
+
moved: sortTextPeople(diff.moved),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/*
|
|
984
|
+
* Name the rotation weeks a period covers: " (week B)", " (weeks A, B)", or
|
|
985
|
+
* '' with no rotation.
|
|
986
|
+
*/
|
|
987
|
+
function getRotationSuffix(
|
|
988
|
+
weeks: SchedulePeriodSummaryTextInput['weeks'],
|
|
989
|
+
): string {
|
|
990
|
+
const labels = [
|
|
991
|
+
...new Set(
|
|
992
|
+
weeks
|
|
993
|
+
.map((week) => week.rotationWeek)
|
|
994
|
+
.filter((week): week is number => week != null)
|
|
995
|
+
.map(getScheduleRotationWeekLabel),
|
|
996
|
+
),
|
|
997
|
+
];
|
|
998
|
+
if (!labels.length) return '';
|
|
999
|
+
return labels.length === 1
|
|
1000
|
+
? ` (week ${labels[0]})`
|
|
1001
|
+
: ` (weeks ${labels.join(', ')})`;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/*
|
|
1005
|
+
* The one-line diff of a summary: who is new or not scheduled, then who
|
|
1006
|
+
* works different shifts; "Same people and shifts as last time." when
|
|
1007
|
+
* nothing changed, [] with nothing to compare.
|
|
1008
|
+
*/
|
|
1009
|
+
function getSummaryDiffLines(diff: SchedulePeriodDiffObj | null): string[] {
|
|
1010
|
+
if (!diff) return [];
|
|
1011
|
+
const people: string[] = [];
|
|
1012
|
+
if (diff.newPeople.length)
|
|
1013
|
+
people.push(
|
|
1014
|
+
`New this time: ${formatNameList(diff.newPeople.map((p) => p.name))}.`,
|
|
1015
|
+
);
|
|
1016
|
+
if (diff.gonePeople.length)
|
|
1017
|
+
people.push(
|
|
1018
|
+
`Not scheduled: ${formatNameList(diff.gonePeople.map((p) => p.name))}.`,
|
|
1019
|
+
);
|
|
1020
|
+
const lines = people.length ? [people.join(' ')] : [];
|
|
1021
|
+
if (diff.moved.length)
|
|
1022
|
+
lines.push(
|
|
1023
|
+
`Different shifts: ${formatNameList(diff.moved.map((p) => p.name))}.`,
|
|
1024
|
+
);
|
|
1025
|
+
return lines.length ? lines : ['Same people and shifts as last time.'];
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/*
|
|
1029
|
+
* Name a standing seat by its weekday and label (or role, or hours):
|
|
1030
|
+
* "Friday close".
|
|
1031
|
+
*/
|
|
1032
|
+
function getStandingSlotName(item: ScheduleStandingTextItem): string {
|
|
1033
|
+
const name =
|
|
1034
|
+
item.label ||
|
|
1035
|
+
item.roleName ||
|
|
1036
|
+
formatClockTextRange(item.startTime, item.endTime);
|
|
1037
|
+
return `${FILE_CONSTANTS.weekdayLong[item.weekday] ?? ''} ${name}`.trim();
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/*
|
|
1041
|
+
* Write "twice running" / "three times running".
|
|
1042
|
+
*/
|
|
1043
|
+
function formatTimesRunning(count: number): string {
|
|
1044
|
+
if (count === 1) return 'once';
|
|
1045
|
+
if (count === 2) return 'twice running';
|
|
1046
|
+
return `${formatCountWord(count)} times running`;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/*
|
|
1050
|
+
* Render one repeat-detection line (§1.12): a cover that keeps happening
|
|
1051
|
+
* offers to make it permanent; people alternating a seat offer a rotation,
|
|
1052
|
+
* naming the week week A starts when known (the period the first person
|
|
1053
|
+
* works).
|
|
1054
|
+
*/
|
|
1055
|
+
function formatRepeatLine(repeat: ScheduleRepeatTextItem): string {
|
|
1056
|
+
const slot = getStandingSlotName(repeat.item);
|
|
1057
|
+
if (repeat.kind === 'ALTERNATING') {
|
|
1058
|
+
const weeks = repeat.names
|
|
1059
|
+
.map((_, index) => `week ${getScheduleRotationWeekLabel(index + 1)}`)
|
|
1060
|
+
.join(' / ');
|
|
1061
|
+
const anchor = repeat.weekAStart
|
|
1062
|
+
? `, week A from ${formatMonthDay(repeat.weekAStart)}`
|
|
1063
|
+
: '';
|
|
1064
|
+
return `${formatAndList(repeat.names)} have been alternating ${slot}. Reply to make it ${weeks}${anchor}.`;
|
|
1065
|
+
}
|
|
1066
|
+
const instead = repeat.item.assigneeName
|
|
1067
|
+
? ` instead of ${repeat.item.assigneeName}`
|
|
1068
|
+
: '';
|
|
1069
|
+
return `${repeat.names[0] || 'Someone'} has worked ${slot} ${formatTimesRunning(repeat.count)}${instead}. Reply to make it permanent.`;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/*
|
|
1073
|
+
* A one-line instruction section that is never dropped (the pass did not
|
|
1074
|
+
* apply anything, and the manager must know).
|
|
1075
|
+
*/
|
|
1076
|
+
function createInstructionNotice(text: string): ScheduleTextSection {
|
|
1077
|
+
return createSection({ title: null, items: [text], cap: 1, min: 1 });
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/*
|
|
1081
|
+
* Build the "From your standing instructions" section (Phase 3): the
|
|
1082
|
+
* instructions the pass left unmet ("Not done: ..."), first and never hidden
|
|
1083
|
+
* (the manager must act on them), then the edits it could not make
|
|
1084
|
+
* ("Couldn't: ...") and the edits it applied; or a note that the pass failed
|
|
1085
|
+
* or met a schedule that changed meanwhile, and applied nothing.
|
|
1086
|
+
*/
|
|
1087
|
+
function getInstructionSection(
|
|
1088
|
+
instructions: SchedulePeriodSummaryTextInput['instructions'],
|
|
1089
|
+
): ScheduleTextSection | null {
|
|
1090
|
+
if (!instructions) return null;
|
|
1091
|
+
if (instructions.failed)
|
|
1092
|
+
return createInstructionNotice(
|
|
1093
|
+
'Your standing instructions were not applied.',
|
|
1094
|
+
);
|
|
1095
|
+
if (instructions.stale)
|
|
1096
|
+
return createInstructionNotice(
|
|
1097
|
+
'Your standing instructions were not applied: the schedule changed meanwhile.',
|
|
1098
|
+
);
|
|
1099
|
+
const unmet = instructions.unmet.map((text) => `Not done: ${text}`);
|
|
1100
|
+
const items = [...unmet, ...instructions.refused, ...instructions.applied];
|
|
1101
|
+
if (!items.length)
|
|
1102
|
+
return createSection({
|
|
1103
|
+
title: null,
|
|
1104
|
+
items: ['From your standing instructions: no changes needed.'],
|
|
1105
|
+
cap: 1,
|
|
1106
|
+
});
|
|
1107
|
+
const notDone = unmet.length + instructions.refused.length;
|
|
1108
|
+
const notDoneCount = notDone ? `, ${notDone} not done` : '';
|
|
1109
|
+
return createSection({
|
|
1110
|
+
title: `From your standing instructions (${pluralize(instructions.applied.length, 'change')}${notDoneCount})`,
|
|
1111
|
+
items,
|
|
1112
|
+
cap: Math.max(FILE_CONSTANTS.smsListCap, unmet.length),
|
|
1113
|
+
min: unmet.length,
|
|
1114
|
+
soft: Math.max(1, unmet.length),
|
|
1115
|
+
keepTitle: true,
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/*
|
|
1120
|
+
* Render one cover line of a preparation summary: "Ana off Tue Dec 15 (on
|
|
1121
|
+
* approved time off): Ben covers." or "...: still open.".
|
|
1122
|
+
*/
|
|
1123
|
+
function formatCoverLine(cover: ScheduleCoverTextItem): string {
|
|
1124
|
+
const outcome = cover.shift.assigneeResourceId
|
|
1125
|
+
? `${cover.shift.assigneeName || 'Someone'} covers.`
|
|
1126
|
+
: 'still open.';
|
|
1127
|
+
const reason = cover.reason ? ` (${cover.reason})` : '';
|
|
1128
|
+
return `${cover.fixedName} off ${formatScheduleDay(cover.shift.shiftDate)}${reason}: ${outcome}`;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/*
|
|
1132
|
+
* The counts line of a summary, with how many seats are still drafts:
|
|
1133
|
+
* "38 shifts: 35 filled, 3 open.", "38 shifts (5 drafts): ...", "38 draft
|
|
1134
|
+
* shifts: ...".
|
|
1135
|
+
*/
|
|
1136
|
+
function getShiftCountLine(
|
|
1137
|
+
total: number,
|
|
1138
|
+
open: number,
|
|
1139
|
+
drafts: number,
|
|
1140
|
+
): string {
|
|
1141
|
+
if (!total) return 'No shifts.';
|
|
1142
|
+
const counts = `${total - open} filled, ${open} open.`;
|
|
1143
|
+
if (drafts === total) return `${pluralize(total, 'draft shift')}: ${counts}`;
|
|
1144
|
+
if (drafts)
|
|
1145
|
+
return `${pluralize(total, 'shift')} (${pluralize(drafts, 'draft')}): ${counts}`;
|
|
1146
|
+
return `${pluralize(total, 'shift')}: ${counts}`;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/*
|
|
1150
|
+
* The last line of a summary. A period with drafts or unpublished dates is
|
|
1151
|
+
* a publish review: a yes publishes (accepting the listed warnings); with
|
|
1152
|
+
* blockers, or rules that could not be checked, it cannot be published yet.
|
|
1153
|
+
* A period already published says so and asks nothing.
|
|
1154
|
+
*/
|
|
1155
|
+
function getPeriodStatusLine(input: {
|
|
1156
|
+
toPublish: boolean;
|
|
1157
|
+
incomplete: boolean;
|
|
1158
|
+
blockerCount: number;
|
|
1159
|
+
warningCount: number;
|
|
1160
|
+
}): string {
|
|
1161
|
+
if (!input.toPublish) return 'All published.';
|
|
1162
|
+
if (input.incomplete)
|
|
1163
|
+
return "Tell me what to change. It can't be published until every rule can be checked.";
|
|
1164
|
+
if (input.blockerCount)
|
|
1165
|
+
return `Tell me what to change. It can't be published with ${input.blockerCount === 1 ? 'a blocker' : 'blockers'}.`;
|
|
1166
|
+
if (input.warningCount)
|
|
1167
|
+
return `Reply YES to publish and accept ${input.warningCount === 1 ? 'the warning' : `the ${input.warningCount} warnings`}, or tell me what to change.`;
|
|
1168
|
+
return 'Reply YES to publish, or tell me what to change.';
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/*
|
|
1172
|
+
* Render a period summary (SMS-bound, the PUBLISH_REVIEW text): calendar,
|
|
1173
|
+
* dates and rotation weeks; counts (drafts among them); blockers, rules
|
|
1174
|
+
* that could not be checked, unacknowledged warnings and open seats (first
|
|
1175
|
+
* few, then "+N more"); who covers a fixed person who is off; the diff
|
|
1176
|
+
* against the baseline weeks; repeat-detection lines; standing-instruction
|
|
1177
|
+
* results; how to answer (only while drafts or unpublished dates remain);
|
|
1178
|
+
* the link. Over budget it drops repeats, the diff, covers, open seats,
|
|
1179
|
+
* instruction details, warning details and unchecked details (in that
|
|
1180
|
+
* order) and finally blocker details down to one, never the counts, the
|
|
1181
|
+
* unmet instructions ("Not done") or the link.
|
|
1182
|
+
*/
|
|
1183
|
+
export function formatPeriodSummary(
|
|
1184
|
+
input: SchedulePeriodSummaryTextInput,
|
|
1185
|
+
): string {
|
|
1186
|
+
const { context } = input;
|
|
1187
|
+
const shifts = getLiveTextShifts(input.shifts);
|
|
1188
|
+
const open = shifts.filter((shift) => !shift.assigneeResourceId);
|
|
1189
|
+
const drafts = shifts.filter((shift) => shift.status === 'DRAFT').length;
|
|
1190
|
+
const diagnostics = getDiagnosticLines(input.diagnostics ?? []);
|
|
1191
|
+
const findings = sortTextFindings(input.findings);
|
|
1192
|
+
const blockers = findings.filter((finding) => finding.severity === 'BLOCK');
|
|
1193
|
+
const warnings = findings.filter(
|
|
1194
|
+
(finding) => finding.severity === 'WARN' && !finding.acknowledged,
|
|
1195
|
+
);
|
|
1196
|
+
const blockerSection = createSection({
|
|
1197
|
+
title: pluralize(blockers.length, 'blocker'),
|
|
1198
|
+
items: blockers.map((finding) => finding.message),
|
|
1199
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1200
|
+
min: 1,
|
|
1201
|
+
soft: 3,
|
|
1202
|
+
keepTitle: true,
|
|
1203
|
+
});
|
|
1204
|
+
const warningSection = createSection({
|
|
1205
|
+
title: pluralize(warnings.length, 'warning'),
|
|
1206
|
+
items: warnings.map((finding) => finding.message),
|
|
1207
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1208
|
+
soft: 2,
|
|
1209
|
+
keepTitle: true,
|
|
1210
|
+
});
|
|
1211
|
+
const uncheckedSection = createSection({
|
|
1212
|
+
title: "Couldn't check",
|
|
1213
|
+
items: diagnostics,
|
|
1214
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1215
|
+
soft: 1,
|
|
1216
|
+
keepTitle: true,
|
|
1217
|
+
});
|
|
1218
|
+
const openSection = createSection({
|
|
1219
|
+
title: 'Open shifts',
|
|
1220
|
+
items: open.map((shift) => formatScheduleShiftLine(shift, context)),
|
|
1221
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1222
|
+
soft: 2,
|
|
1223
|
+
});
|
|
1224
|
+
const diffSection = createSection({
|
|
1225
|
+
title: null,
|
|
1226
|
+
items: getSummaryDiffLines(input.diff),
|
|
1227
|
+
cap: 2,
|
|
1228
|
+
soft: 1,
|
|
1229
|
+
});
|
|
1230
|
+
const coverSection = createSection({
|
|
1231
|
+
title: null,
|
|
1232
|
+
items: (input.covers ?? []).map(formatCoverLine),
|
|
1233
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1234
|
+
soft: 1,
|
|
1235
|
+
});
|
|
1236
|
+
const repeatSection = createSection({
|
|
1237
|
+
title: null,
|
|
1238
|
+
items: (input.repeats ?? []).map(formatRepeatLine),
|
|
1239
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1240
|
+
soft: 1,
|
|
1241
|
+
});
|
|
1242
|
+
const instructionSection = getInstructionSection(input.instructions);
|
|
1243
|
+
const specialSection = createSection({
|
|
1244
|
+
title: null,
|
|
1245
|
+
items: (input.specialDays ?? []).map(formatSpecialDayLine),
|
|
1246
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1247
|
+
min: 1,
|
|
1248
|
+
soft: 2,
|
|
1249
|
+
});
|
|
1250
|
+
return fitScheduleTextParts(
|
|
1251
|
+
[
|
|
1252
|
+
`${getScheduleTextTitle(context, input.fromDate, input.toDate)}${getRotationSuffix(input.weeks)}`,
|
|
1253
|
+
getShiftCountLine(shifts.length, open.length, drafts),
|
|
1254
|
+
specialSection,
|
|
1255
|
+
getUnusableStandingLine(input.unusableStandingCount ?? 0),
|
|
1256
|
+
blockerSection,
|
|
1257
|
+
uncheckedSection,
|
|
1258
|
+
warningSection,
|
|
1259
|
+
openSection,
|
|
1260
|
+
coverSection,
|
|
1261
|
+
diffSection,
|
|
1262
|
+
repeatSection,
|
|
1263
|
+
instructionSection,
|
|
1264
|
+
getPeriodStatusLine({
|
|
1265
|
+
toPublish: drafts > 0 || input.unpublishedDates.length > 0,
|
|
1266
|
+
incomplete: diagnostics.length > 0,
|
|
1267
|
+
blockerCount: blockers.length,
|
|
1268
|
+
warningCount: warnings.length,
|
|
1269
|
+
}),
|
|
1270
|
+
context.link,
|
|
1271
|
+
],
|
|
1272
|
+
[
|
|
1273
|
+
repeatSection,
|
|
1274
|
+
diffSection,
|
|
1275
|
+
coverSection,
|
|
1276
|
+
openSection,
|
|
1277
|
+
...(instructionSection ? [instructionSection] : []),
|
|
1278
|
+
warningSection,
|
|
1279
|
+
uncheckedSection,
|
|
1280
|
+
specialSection,
|
|
1281
|
+
blockerSection,
|
|
1282
|
+
],
|
|
1283
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/*
|
|
1288
|
+
* Render one special day of a period: "Closed Thu Nov 26 (2 shifts that
|
|
1289
|
+
* day)" or "Special hours Thu Nov 26: 10am-2pm".
|
|
1290
|
+
*/
|
|
1291
|
+
function formatSpecialDayLine(day: ScheduleSpecialDayTextItem): string {
|
|
1292
|
+
const label = formatScheduleDay(day.date);
|
|
1293
|
+
if (!day.hours.length) {
|
|
1294
|
+
const seats = day.shiftCount
|
|
1295
|
+
? ` (${pluralize(day.shiftCount, 'shift')} that day)`
|
|
1296
|
+
: '';
|
|
1297
|
+
return `Closed ${label}${seats}`;
|
|
1298
|
+
}
|
|
1299
|
+
const ranges = day.hours
|
|
1300
|
+
.map(([start, end]) => formatClockTextRange(start, end))
|
|
1301
|
+
.join(', ');
|
|
1302
|
+
return `Special hours ${label}: ${ranges}`;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/*
|
|
1306
|
+
* The parenthesis of a preparation-pass line: " (reason)", or '' when there
|
|
1307
|
+
* is no reason.
|
|
1308
|
+
*/
|
|
1309
|
+
function getPreparePassParenthesis(text: string | null | undefined): string {
|
|
1310
|
+
const clause = (text ?? '').trim();
|
|
1311
|
+
return clause ? ` (${clause})` : '';
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
/*
|
|
1315
|
+
* The seat line of a retimed seat at its previous hours (the seat as it is
|
|
1316
|
+
* when no previous hours are given).
|
|
1317
|
+
*/
|
|
1318
|
+
function getPreparePassPreviousLine(
|
|
1319
|
+
input: SchedulePreparePassEditTextInput,
|
|
1320
|
+
): string {
|
|
1321
|
+
const previous = input.previous
|
|
1322
|
+
? { ...input.shift, ...input.previous }
|
|
1323
|
+
: input.shift;
|
|
1324
|
+
return formatScheduleShiftLine(previous, input.context);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/*
|
|
1328
|
+
* The new hours of a retimed seat against its previous hours: the clock
|
|
1329
|
+
* alone on the same day ("9pm-2am"), else the full range.
|
|
1330
|
+
*/
|
|
1331
|
+
function getPreparePassNewHours(
|
|
1332
|
+
input: SchedulePreparePassEditTextInput,
|
|
1333
|
+
): string {
|
|
1334
|
+
const { shift } = input;
|
|
1335
|
+
return formatTimeRangeAfter(
|
|
1336
|
+
input.previous ?? shift,
|
|
1337
|
+
shift.startAt,
|
|
1338
|
+
shift.endAt,
|
|
1339
|
+
getShiftZone(shift, input.context),
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/*
|
|
1344
|
+
* One applied edit of the standing-instructions pass: what changed on which
|
|
1345
|
+
* seat, then the model's reason.
|
|
1346
|
+
*/
|
|
1347
|
+
function getPreparePassAppliedLine(
|
|
1348
|
+
input: SchedulePreparePassEditTextInput,
|
|
1349
|
+
): string {
|
|
1350
|
+
const { shift } = input;
|
|
1351
|
+
const line = formatScheduleShiftLine(shift, input.context);
|
|
1352
|
+
const name = shift.assigneeName || 'someone';
|
|
1353
|
+
const reason = getPreparePassParenthesis(input.reason);
|
|
1354
|
+
const was = input.previousAssigneeName;
|
|
1355
|
+
switch (input.kind) {
|
|
1356
|
+
case 'assign':
|
|
1357
|
+
return `${line}: ${name}${was ? ` instead of ${was}` : ''}${reason}`;
|
|
1358
|
+
case 'unassign':
|
|
1359
|
+
return `${line}: opened${getPreparePassParenthesis(was ? `was ${was}` : null)}${reason}`;
|
|
1360
|
+
case 'retime':
|
|
1361
|
+
return input.previous
|
|
1362
|
+
? `${getPreparePassPreviousLine(input)}: now ${getPreparePassNewHours(input)}${reason}`
|
|
1363
|
+
: `${line}: new hours${reason}`;
|
|
1364
|
+
case 'create':
|
|
1365
|
+
return `Added ${line}${shift.assigneeResourceId ? ` for ${name}` : ''}${reason}`;
|
|
1366
|
+
case 'delete':
|
|
1367
|
+
return `Removed ${line}${reason}`;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/*
|
|
1372
|
+
* What a refused edit would have done, after "Couldn't: ".
|
|
1373
|
+
*/
|
|
1374
|
+
function getPreparePassRefusedAction(
|
|
1375
|
+
input: SchedulePreparePassEditTextInput,
|
|
1376
|
+
): string {
|
|
1377
|
+
const { shift } = input;
|
|
1378
|
+
const line = formatScheduleShiftLine(shift, input.context);
|
|
1379
|
+
const name = shift.assigneeName || 'someone';
|
|
1380
|
+
switch (input.kind) {
|
|
1381
|
+
case 'assign':
|
|
1382
|
+
return `${name} on ${line}`;
|
|
1383
|
+
case 'unassign':
|
|
1384
|
+
return input.previousAssigneeName
|
|
1385
|
+
? `take ${input.previousAssigneeName} off ${line}`
|
|
1386
|
+
: `open ${line}`;
|
|
1387
|
+
case 'retime':
|
|
1388
|
+
return input.previous
|
|
1389
|
+
? `move ${getPreparePassPreviousLine(input)} to ${getPreparePassNewHours(input)}`
|
|
1390
|
+
: `change the hours of ${line}`;
|
|
1391
|
+
case 'create':
|
|
1392
|
+
return `add ${line}${shift.assigneeResourceId ? ` for ${name}` : ''}`;
|
|
1393
|
+
case 'delete':
|
|
1394
|
+
return `remove ${line}`;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/*
|
|
1399
|
+
* Render one edit of the standing-instructions pass as one line (no link):
|
|
1400
|
+
* applied ("Fri Dec 4, 8pm-2am Bartender: Dee instead of Cam (never Cam and
|
|
1401
|
+
* Dee on one close)", "...: opened (was Cam) (...)", "...: now 9pm-2am
|
|
1402
|
+
* (...)", "Added Sat Dec 5, 4pm-10pm Barback (...)", "Removed Mon Dec 7,
|
|
1403
|
+
* 9am-1pm (...)"), or refused ("Couldn't: Eve on Sat Dec 5, 4pm-10pm
|
|
1404
|
+
* (already working)", the refusal as the parenthesis). GSM-7 only.
|
|
1405
|
+
*/
|
|
1406
|
+
export function formatPreparePassEdit(
|
|
1407
|
+
input: SchedulePreparePassEditTextInput,
|
|
1408
|
+
): string {
|
|
1409
|
+
if (input.refusal == null)
|
|
1410
|
+
return toScheduleGsmText(getPreparePassAppliedLine(input));
|
|
1411
|
+
return toScheduleGsmText(
|
|
1412
|
+
`Couldn't: ${getPreparePassRefusedAction(input)}${getPreparePassParenthesis(input.refusal)}`,
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/*
|
|
1417
|
+
* Start a second-person text with the name when known: "Ana, y" / "Y".
|
|
1418
|
+
*/
|
|
1419
|
+
function getYouPrefix(name: string | null): string {
|
|
1420
|
+
return name ? `${name}, y` : 'Y';
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/*
|
|
1424
|
+
* Render a person's shifts (SMS-bound): their seats in the range, then the
|
|
1425
|
+
* open seats they may ask for, titled with how to ask. Over budget the open
|
|
1426
|
+
* seats go first (with their title), then their own seats shrink to
|
|
1427
|
+
* "+N more"; the link stays.
|
|
1428
|
+
*/
|
|
1429
|
+
export function formatMyShifts(input: ScheduleMyShiftsTextInput): string {
|
|
1430
|
+
return renderMyShifts(input, null);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
/*
|
|
1434
|
+
* Render a person's shifts with an optional last sentence before the link
|
|
1435
|
+
* (the SHIFTS_CONFIRM ask); see formatMyShifts.
|
|
1436
|
+
*/
|
|
1437
|
+
function renderMyShifts(
|
|
1438
|
+
input: ScheduleMyShiftsTextInput,
|
|
1439
|
+
ask: string | null,
|
|
1440
|
+
): string {
|
|
1441
|
+
const { context } = input;
|
|
1442
|
+
const shifts = getLiveTextShifts(input.shifts);
|
|
1443
|
+
const open = getLiveTextShifts(input.openShifts);
|
|
1444
|
+
const range = formatScheduleDateRange(input.fromDate, input.toDate);
|
|
1445
|
+
const calendar = context.calendarName ? `${context.calendarName} ` : '';
|
|
1446
|
+
const you = getYouPrefix(input.personName);
|
|
1447
|
+
const ownSection = createSection({
|
|
1448
|
+
title: `${you}our ${calendar}shifts ${range}`,
|
|
1449
|
+
items: shifts.map((shift) => formatScheduleShiftLine(shift, context)),
|
|
1450
|
+
cap: shifts.length,
|
|
1451
|
+
min: 1,
|
|
1452
|
+
soft: shifts.length,
|
|
1453
|
+
keepTitle: true,
|
|
1454
|
+
});
|
|
1455
|
+
const openSection = createSection({
|
|
1456
|
+
title: 'Open shifts (to ask for one, reply with its day and time)',
|
|
1457
|
+
items: open.map((shift) => formatScheduleShiftLine(shift, context)),
|
|
1458
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
1459
|
+
soft: 1,
|
|
1460
|
+
});
|
|
1461
|
+
return fitScheduleTextParts(
|
|
1462
|
+
[
|
|
1463
|
+
shifts.length
|
|
1464
|
+
? ownSection
|
|
1465
|
+
: `${you}ou have no ${calendar}shifts ${range}.`,
|
|
1466
|
+
openSection,
|
|
1467
|
+
ask,
|
|
1468
|
+
context.link,
|
|
1469
|
+
],
|
|
1470
|
+
[openSection, ownSection],
|
|
1471
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/*
|
|
1476
|
+
* Name the parts of an edited seat that changed, as they were: " (was
|
|
1477
|
+
* Barback)", " (was at Main bar)", or '' when nothing shown differs.
|
|
1478
|
+
*/
|
|
1479
|
+
function getEditedWasText(
|
|
1480
|
+
before: ScheduleTextShift,
|
|
1481
|
+
after: ScheduleTextShift,
|
|
1482
|
+
): string {
|
|
1483
|
+
const title = getShiftTitle(before.roleName, before.label);
|
|
1484
|
+
const titleChanged = title !== getShiftTitle(after.roleName, after.label);
|
|
1485
|
+
const locationChanged = before.locationName !== after.locationName;
|
|
1486
|
+
const was = [
|
|
1487
|
+
titleChanged ? title || 'no role' : null,
|
|
1488
|
+
locationChanged
|
|
1489
|
+
? before.locationName
|
|
1490
|
+
? `at ${before.locationName}`
|
|
1491
|
+
: 'no location'
|
|
1492
|
+
: null,
|
|
1493
|
+
].filter(Boolean);
|
|
1494
|
+
return was.length ? ` (was ${was.join(' ')})` : '';
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/*
|
|
1498
|
+
* Render one seat's net change for its recipient: added, removed, new hours
|
|
1499
|
+
* (old -> new), changed (with what it was) or canceled.
|
|
1500
|
+
*/
|
|
1501
|
+
function formatShiftChangeLine(
|
|
1502
|
+
item: ScheduleShiftChangeTextItem,
|
|
1503
|
+
context: ScheduleTextContext,
|
|
1504
|
+
): string {
|
|
1505
|
+
const { before, after } = item;
|
|
1506
|
+
switch (item.change) {
|
|
1507
|
+
case 'ADDED':
|
|
1508
|
+
return `Added: ${formatScheduleShiftLine(after, context)}`;
|
|
1509
|
+
case 'REMOVED':
|
|
1510
|
+
return `Removed: ${formatScheduleShiftLine(before, context)}`;
|
|
1511
|
+
case 'CANCELED':
|
|
1512
|
+
return `Canceled: ${formatScheduleShiftLine(before, context)}`;
|
|
1513
|
+
case 'RETIMED': {
|
|
1514
|
+
const zone = getShiftZone(after, context);
|
|
1515
|
+
const description = getShiftDescription(after);
|
|
1516
|
+
return `New hours: ${formatScheduleTimeRange(before.startAt, before.endAt, getShiftZone(before, context))} -> ${formatTimeRangeAfter(before, after.startAt, after.endAt, zone)}${description ? ` ${description}` : ''}`;
|
|
1517
|
+
}
|
|
1518
|
+
default:
|
|
1519
|
+
return `Changed: ${formatScheduleShiftLine(after, context)}${getEditedWasText(before, after)}`;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
/*
|
|
1524
|
+
* Render a change notice (SMS-bound): one line per seat of the recipient's
|
|
1525
|
+
* net change, in seat order; over budget the list ends in "+N more".
|
|
1526
|
+
*/
|
|
1527
|
+
export function formatShiftChange(input: ScheduleShiftChangeTextInput): string {
|
|
1528
|
+
const { context } = input;
|
|
1529
|
+
const calendar = context.calendarName ? `${context.calendarName} ` : '';
|
|
1530
|
+
const you = getYouPrefix(input.recipientName);
|
|
1531
|
+
const changes = [...input.changes].sort(
|
|
1532
|
+
(a, b) =>
|
|
1533
|
+
toScheduleTimeMs(a.after.startAt) - toScheduleTimeMs(b.after.startAt) ||
|
|
1534
|
+
compareText(a.after.id, b.after.id),
|
|
1535
|
+
);
|
|
1536
|
+
if (!changes.length)
|
|
1537
|
+
return joinScheduleText([
|
|
1538
|
+
`${you}our ${calendar}shifts have no changes.`,
|
|
1539
|
+
context.link,
|
|
1540
|
+
]);
|
|
1541
|
+
const section = createSection({
|
|
1542
|
+
title: `${you}our ${calendar}schedule changed`,
|
|
1543
|
+
items: changes.map((item) => formatShiftChangeLine(item, context)),
|
|
1544
|
+
cap: changes.length,
|
|
1545
|
+
min: 1,
|
|
1546
|
+
keepTitle: true,
|
|
1547
|
+
});
|
|
1548
|
+
return fitScheduleTextParts(
|
|
1549
|
+
[section, context.link],
|
|
1550
|
+
[section],
|
|
1551
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/*
|
|
1556
|
+
* Render the proposed hours of a RETIME against its seat ("9pm-3am", or the
|
|
1557
|
+
* full range when the day changes).
|
|
1558
|
+
*/
|
|
1559
|
+
function formatProposedHours(
|
|
1560
|
+
request: ScheduleRequestTextInput['request'],
|
|
1561
|
+
context: ScheduleTextContext,
|
|
1562
|
+
): string {
|
|
1563
|
+
if (!request.proposedStartAt || !request.proposedEndAt) return 'new hours';
|
|
1564
|
+
return formatTimeRangeAfter(
|
|
1565
|
+
request.shift,
|
|
1566
|
+
request.proposedStartAt,
|
|
1567
|
+
request.proposedEndAt,
|
|
1568
|
+
getShiftZone(request.shift, context),
|
|
1569
|
+
);
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/*
|
|
1573
|
+
* The action a request asks for, for "Ana wants to ..." and "Your request
|
|
1574
|
+
* to ...": "give up Fri Dec 18, 8pm-2am Bartender".
|
|
1575
|
+
*/
|
|
1576
|
+
function getRequestVerbPhrase(
|
|
1577
|
+
request: ScheduleRequestTextInput['request'],
|
|
1578
|
+
context: ScheduleTextContext,
|
|
1579
|
+
): string {
|
|
1580
|
+
const shift = formatScheduleShiftLine(request.shift, context);
|
|
1581
|
+
switch (request.kind) {
|
|
1582
|
+
case 'CLAIM':
|
|
1583
|
+
return `take ${shift}`;
|
|
1584
|
+
case 'DROP':
|
|
1585
|
+
return `give up ${shift}`;
|
|
1586
|
+
case 'CALL_OUT':
|
|
1587
|
+
return `call out of ${shift}`;
|
|
1588
|
+
case 'RETIME':
|
|
1589
|
+
return `change ${shift} to ${formatProposedHours(request, context)}`;
|
|
1590
|
+
default: {
|
|
1591
|
+
const target = request.targetShift
|
|
1592
|
+
? `${request.counterpartyName || 'another'}'s ${formatScheduleShiftLine(request.targetShift, context)}`
|
|
1593
|
+
: 'another shift';
|
|
1594
|
+
return `swap ${shift} for ${target}`;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/*
|
|
1600
|
+
* The end of a decided request's sentence: "was approved (automatically)",
|
|
1601
|
+
* "was declined: <note>", "was canceled", "expired".
|
|
1602
|
+
*/
|
|
1603
|
+
function getRequestOutcome(
|
|
1604
|
+
request: ScheduleRequestTextInput['request'],
|
|
1605
|
+
noteMax: number,
|
|
1606
|
+
): string {
|
|
1607
|
+
switch (request.status) {
|
|
1608
|
+
case 'APPROVED':
|
|
1609
|
+
return request.autoApproved
|
|
1610
|
+
? 'was approved automatically'
|
|
1611
|
+
: 'was approved';
|
|
1612
|
+
case 'DECLINED':
|
|
1613
|
+
return request.decisionNote
|
|
1614
|
+
? `was declined: ${clipText(request.decisionNote, noteMax)}`
|
|
1615
|
+
: 'was declined';
|
|
1616
|
+
case 'CANCELLED':
|
|
1617
|
+
return 'was canceled';
|
|
1618
|
+
default:
|
|
1619
|
+
return 'expired';
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
/*
|
|
1624
|
+
* Whether a request is still waiting (PENDING, or a swap the counterparty
|
|
1625
|
+
* accepted).
|
|
1626
|
+
*/
|
|
1627
|
+
function isRequestLive(request: ScheduleRequestTextInput['request']): boolean {
|
|
1628
|
+
return (
|
|
1629
|
+
request.status === 'PENDING' ||
|
|
1630
|
+
request.status === 'ACCEPTED_BY_COUNTERPARTY'
|
|
1631
|
+
);
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/*
|
|
1635
|
+
* Whether a manager decides the request now: PENDING, or for a swap
|
|
1636
|
+
* accepted by the counterparty.
|
|
1637
|
+
*/
|
|
1638
|
+
function isRequestDecidable(
|
|
1639
|
+
request: ScheduleRequestTextInput['request'],
|
|
1640
|
+
): boolean {
|
|
1641
|
+
return request.kind === 'SWAP'
|
|
1642
|
+
? request.status === 'ACCEPTED_BY_COUNTERPARTY'
|
|
1643
|
+
: request.status === 'PENDING';
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/*
|
|
1647
|
+
* Render the distinct eligibility clauses of reasons of one severity.
|
|
1648
|
+
*/
|
|
1649
|
+
function getReasonClauses(
|
|
1650
|
+
reasons: ScheduleEligibilityReasonObj[],
|
|
1651
|
+
severity: ScheduleEligibilityReasonObj['severity'],
|
|
1652
|
+
context: ScheduleTextContext,
|
|
1653
|
+
): string[] {
|
|
1654
|
+
return [
|
|
1655
|
+
...new Set(
|
|
1656
|
+
reasons
|
|
1657
|
+
.filter((reason) => reason.severity === severity)
|
|
1658
|
+
.map((reason) => formatEligibilityReason(reason, context)),
|
|
1659
|
+
),
|
|
1660
|
+
];
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
/*
|
|
1664
|
+
* Render a request's eligibility and impact reasons as one line:
|
|
1665
|
+
* "Blocked: on approved time off. Warning: over the hours limit (...)."
|
|
1666
|
+
*/
|
|
1667
|
+
function formatRequestReasonsLine(
|
|
1668
|
+
reasons: ScheduleEligibilityReasonObj[],
|
|
1669
|
+
context: ScheduleTextContext,
|
|
1670
|
+
): string | null {
|
|
1671
|
+
const blocks = getReasonClauses(reasons, 'BLOCK', context);
|
|
1672
|
+
const warns = getReasonClauses(reasons, 'WARN', context);
|
|
1673
|
+
const parts = [
|
|
1674
|
+
blocks.length ? `Blocked: ${blocks.join('; ')}.` : null,
|
|
1675
|
+
warns.length ? `Warning: ${warns.join('; ')}.` : null,
|
|
1676
|
+
].filter(Boolean);
|
|
1677
|
+
return parts.length ? parts.join(' ') : null;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
/*
|
|
1681
|
+
* What happens to the seat once a request is approved, told to the
|
|
1682
|
+
* requester or the manager ('' when nothing needs saying).
|
|
1683
|
+
*/
|
|
1684
|
+
function getApprovedRequestNote(
|
|
1685
|
+
request: ScheduleRequestTextInput['request'],
|
|
1686
|
+
audience: ScheduleRequestTextInput['audience'],
|
|
1687
|
+
): string {
|
|
1688
|
+
if (request.status !== 'APPROVED') return '';
|
|
1689
|
+
if (audience === 'MANAGER')
|
|
1690
|
+
return request.kind === 'DROP' || request.kind === 'CALL_OUT'
|
|
1691
|
+
? ' The shift is open now.'
|
|
1692
|
+
: '';
|
|
1693
|
+
if (request.kind === 'CLAIM') return ' The shift is yours.';
|
|
1694
|
+
return request.kind === 'DROP' || request.kind === 'CALL_OUT'
|
|
1695
|
+
? " You're off this shift."
|
|
1696
|
+
: '';
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
/*
|
|
1700
|
+
* The third-person line of a request: "Ana wants to give up X." while it is
|
|
1701
|
+
* live (a call-out "is calling out of X"; " Ben agreed." on an accepted
|
|
1702
|
+
* swap), else "Ana's request to X was approved."
|
|
1703
|
+
*/
|
|
1704
|
+
function getRequestStatusLine(
|
|
1705
|
+
input: ScheduleRequestTextInput,
|
|
1706
|
+
prefix: string,
|
|
1707
|
+
noteMax: number,
|
|
1708
|
+
): string {
|
|
1709
|
+
const { request, context } = input;
|
|
1710
|
+
const verb = getRequestVerbPhrase(request, context);
|
|
1711
|
+
if (!isRequestLive(request))
|
|
1712
|
+
return `${prefix}${ensurePeriod(`${request.requesterName}'s request to ${verb} ${getRequestOutcome(request, noteMax)}`)}${getApprovedRequestNote(request, 'MANAGER')}`;
|
|
1713
|
+
const action =
|
|
1714
|
+
request.kind === 'CALL_OUT'
|
|
1715
|
+
? `is calling out of ${formatScheduleShiftLine(request.shift, context)}`
|
|
1716
|
+
: `wants to ${verb}`;
|
|
1717
|
+
const agreed =
|
|
1718
|
+
request.status === 'ACCEPTED_BY_COUNTERPARTY'
|
|
1719
|
+
? ` ${request.counterpartyName || 'The other person'} agreed.`
|
|
1720
|
+
: '';
|
|
1721
|
+
return `${prefix}${request.requesterName} ${action}.${agreed}`;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/*
|
|
1725
|
+
* How a manager answers a live request: YES or NO while it is theirs to
|
|
1726
|
+
* decide ("tell me what to change" when a BLOCK reason stops approval), or
|
|
1727
|
+
* who it still waits for. A notice says to ask the assistant instead: no
|
|
1728
|
+
* reply to a notice is matched to its request yet (Phase 2 asks).
|
|
1729
|
+
*/
|
|
1730
|
+
function getManagerRequestAsk(input: ScheduleRequestTextInput): string {
|
|
1731
|
+
const { request } = input;
|
|
1732
|
+
if (!isRequestDecidable(request))
|
|
1733
|
+
return `Waiting for ${request.counterpartyName || 'the other person'} to agree.`;
|
|
1734
|
+
const blocked = input.reasons.some((reason) => reason.severity === 'BLOCK');
|
|
1735
|
+
if (input.notice)
|
|
1736
|
+
return blocked
|
|
1737
|
+
? `It can't be approved as is. Ask the assistant to decline ${request.requesterName}'s request or to change it.`
|
|
1738
|
+
: `Ask the assistant to approve or decline ${request.requesterName}'s request.`;
|
|
1739
|
+
return blocked
|
|
1740
|
+
? "It can't be approved as is. Reply NO to decline, or tell me what to change."
|
|
1741
|
+
: 'Reply YES to approve or NO to decline.';
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/*
|
|
1745
|
+
* The manager's text: a live request with its reason, its problems and how
|
|
1746
|
+
* to decide it; a decided one with its outcome.
|
|
1747
|
+
*/
|
|
1748
|
+
function getManagerRequestLines(
|
|
1749
|
+
input: ScheduleRequestTextInput,
|
|
1750
|
+
prefix: string,
|
|
1751
|
+
): Array<string | null> {
|
|
1752
|
+
const { request, context } = input;
|
|
1753
|
+
const line = getRequestStatusLine(input, prefix, Number.POSITIVE_INFINITY);
|
|
1754
|
+
if (!isRequestLive(request)) return [line];
|
|
1755
|
+
return [
|
|
1756
|
+
line,
|
|
1757
|
+
request.reason ? `Reason: ${request.reason}` : null,
|
|
1758
|
+
formatRequestReasonsLine(input.reasons, context),
|
|
1759
|
+
getManagerRequestAsk(input),
|
|
1760
|
+
];
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/*
|
|
1764
|
+
* The requester's text: where the request stands, with the manager's words
|
|
1765
|
+
* when it was declined, then its reasons.
|
|
1766
|
+
*/
|
|
1767
|
+
function getRequesterRequestParts(
|
|
1768
|
+
input: ScheduleRequestTextInput,
|
|
1769
|
+
prefix: string,
|
|
1770
|
+
reasons: ScheduleTextSection,
|
|
1771
|
+
): ScheduleTextPart[] {
|
|
1772
|
+
const { request, context } = input;
|
|
1773
|
+
const verb = getRequestVerbPhrase(request, context);
|
|
1774
|
+
const other = request.counterpartyName || 'the other person';
|
|
1775
|
+
const status =
|
|
1776
|
+
request.status === 'PENDING'
|
|
1777
|
+
? `${prefix}Your request to ${verb} is waiting for ${request.kind === 'SWAP' ? `${other} to agree` : 'a manager'}.`
|
|
1778
|
+
: request.status === 'ACCEPTED_BY_COUNTERPARTY'
|
|
1779
|
+
? `${prefix}Your request to ${verb}: ${other} agreed. Waiting for a manager.`
|
|
1780
|
+
: `${prefix}${ensurePeriod(`Your request to ${verb} ${getRequestOutcome(request, FILE_CONSTANTS.smsQuoteMaxLength)}`)}${getApprovedRequestNote(request, 'REQUESTER')}`;
|
|
1781
|
+
return [status, reasons];
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
/*
|
|
1785
|
+
* The swap counterparty's text: the SWAP_CONSENT ask while pending (ending
|
|
1786
|
+
* with how to answer), else where the swap stands. A non-swap request has
|
|
1787
|
+
* no counterparty, so it reads as its third-person status.
|
|
1788
|
+
*/
|
|
1789
|
+
function getCounterpartyRequestParts(
|
|
1790
|
+
input: ScheduleRequestTextInput,
|
|
1791
|
+
prefix: string,
|
|
1792
|
+
reasons: ScheduleTextSection,
|
|
1793
|
+
): ScheduleTextPart[] {
|
|
1794
|
+
const { request, context } = input;
|
|
1795
|
+
if (request.kind !== 'SWAP')
|
|
1796
|
+
return [
|
|
1797
|
+
getRequestStatusLine(input, prefix, FILE_CONSTANTS.smsQuoteMaxLength),
|
|
1798
|
+
reasons,
|
|
1799
|
+
];
|
|
1800
|
+
const theirs = formatScheduleShiftLine(request.shift, context);
|
|
1801
|
+
const yours = request.targetShift
|
|
1802
|
+
? formatScheduleShiftLine(request.targetShift, context)
|
|
1803
|
+
: 'your shift';
|
|
1804
|
+
if (request.status === 'PENDING')
|
|
1805
|
+
return [
|
|
1806
|
+
`${prefix}${request.requesterName} wants to swap shifts: you take their ${theirs}; they take your ${yours}.`,
|
|
1807
|
+
request.reason
|
|
1808
|
+
? `Reason: ${clipText(request.reason, FILE_CONSTANTS.smsQuoteMaxLength)}`
|
|
1809
|
+
: null,
|
|
1810
|
+
reasons,
|
|
1811
|
+
input.notice
|
|
1812
|
+
? `Ask the assistant to accept or decline ${request.requesterName}'s swap.`
|
|
1813
|
+
: 'Reply YES to swap or NO to decline.',
|
|
1814
|
+
];
|
|
1815
|
+
if (request.status === 'ACCEPTED_BY_COUNTERPARTY')
|
|
1816
|
+
return [
|
|
1817
|
+
`${prefix}You agreed to swap with ${request.requesterName}. Waiting for a manager.`,
|
|
1818
|
+
];
|
|
1819
|
+
const approved =
|
|
1820
|
+
request.status === 'APPROVED' ? ` You now work ${theirs}.` : '';
|
|
1821
|
+
return [
|
|
1822
|
+
`${prefix}${ensurePeriod(`The swap with ${request.requesterName} ${getRequestOutcome(request, FILE_CONSTANTS.smsQuoteMaxLength)}`)}${approved}`,
|
|
1823
|
+
];
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
/*
|
|
1827
|
+
* Render a request for its audience. MANAGER: what is asked, the reason,
|
|
1828
|
+
* eligibility and impact, and "Reply YES to approve or NO to decline" while
|
|
1829
|
+
* it is theirs to decide (no segment budget). REQUESTER and COUNTERPARTY
|
|
1830
|
+
* (SMS-bound): where it stands, a decline with its note, and the swap
|
|
1831
|
+
* consent ask; over budget the reasons line is dropped. As a notice
|
|
1832
|
+
* (input.notice), the asks say to ask the assistant instead of replying YES
|
|
1833
|
+
* or NO.
|
|
1834
|
+
*/
|
|
1835
|
+
export function formatRequest(input: ScheduleRequestTextInput): string {
|
|
1836
|
+
const { context } = input;
|
|
1837
|
+
const prefix = context.calendarName ? `${context.calendarName}: ` : '';
|
|
1838
|
+
if (input.audience === 'MANAGER')
|
|
1839
|
+
return joinScheduleText([
|
|
1840
|
+
...getManagerRequestLines(input, prefix),
|
|
1841
|
+
context.link,
|
|
1842
|
+
]);
|
|
1843
|
+
const reasonsLine = formatRequestReasonsLine(input.reasons, context);
|
|
1844
|
+
const reasons = createSection({
|
|
1845
|
+
title: null,
|
|
1846
|
+
items: reasonsLine ? [reasonsLine] : [],
|
|
1847
|
+
cap: 1,
|
|
1848
|
+
});
|
|
1849
|
+
const parts =
|
|
1850
|
+
input.audience === 'REQUESTER'
|
|
1851
|
+
? getRequesterRequestParts(input, prefix, reasons)
|
|
1852
|
+
: getCounterpartyRequestParts(input, prefix, reasons);
|
|
1853
|
+
return fitScheduleTextParts(
|
|
1854
|
+
[...parts, context.link],
|
|
1855
|
+
[reasons],
|
|
1856
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
1857
|
+
);
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
/*
|
|
1861
|
+
* Render one ranking reason as a short clause: "prefers these hours", "12h
|
|
1862
|
+
* under target", "declined 2 offers", "usually works this shift".
|
|
1863
|
+
*/
|
|
1864
|
+
function formatCandidateScoreReason(
|
|
1865
|
+
reason: ScheduleCandidateScoreReasonObj,
|
|
1866
|
+
): string {
|
|
1867
|
+
const { detail } = reason;
|
|
1868
|
+
switch (reason.code) {
|
|
1869
|
+
case 'PREFERRED_TIME':
|
|
1870
|
+
return (readDetailNumber(detail, 'fraction') ?? 0) >= 1
|
|
1871
|
+
? 'prefers these hours'
|
|
1872
|
+
: 'prefers some of these hours';
|
|
1873
|
+
case 'UNDER_TARGET_HOURS': {
|
|
1874
|
+
const week = readDetailNumber(detail, 'weekMinutes');
|
|
1875
|
+
const target = readDetailNumber(detail, 'targetMinutes');
|
|
1876
|
+
return week !== null && target !== null && target > week
|
|
1877
|
+
? `${formatScheduleDuration(target - week)} under target`
|
|
1878
|
+
: 'under their target hours';
|
|
1879
|
+
}
|
|
1880
|
+
case 'OVER_TARGET_HOURS': {
|
|
1881
|
+
const over = readDetailNumber(detail, 'overMinutes');
|
|
1882
|
+
return over
|
|
1883
|
+
? `${formatScheduleDuration(over)} over target`
|
|
1884
|
+
: 'over target';
|
|
1885
|
+
}
|
|
1886
|
+
case 'RULE_WARNING':
|
|
1887
|
+
return (
|
|
1888
|
+
FILE_CONSTANTS.warningClauses[String(detail.code)] ?? 'a rule warning'
|
|
1889
|
+
);
|
|
1890
|
+
case 'RECENT_DECLINES':
|
|
1891
|
+
return `declined ${pluralize(readDetailNumber(detail, 'count') ?? 0, 'offer')}`;
|
|
1892
|
+
case 'FAIRNESS': {
|
|
1893
|
+
const days = readDetailNumber(detail, 'days');
|
|
1894
|
+
return days === null
|
|
1895
|
+
? 'no recent shifts here'
|
|
1896
|
+
: `last shift here ${pluralize(days, 'day')} ago`;
|
|
1897
|
+
}
|
|
1898
|
+
default:
|
|
1899
|
+
return (readDetailNumber(detail, 'count') ?? 0) > 1
|
|
1900
|
+
? 'usually works this shift'
|
|
1901
|
+
: 'worked this shift recently';
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
/*
|
|
1906
|
+
* The top ranking reasons of a candidate as short clauses (at most `limit`).
|
|
1907
|
+
* RULE_WARNING is left out: the eligibility warnings already say it.
|
|
1908
|
+
*/
|
|
1909
|
+
export function formatCandidateScoreClauses(
|
|
1910
|
+
reasons: ScheduleCandidateScoreReasonObj[],
|
|
1911
|
+
limit: number,
|
|
1912
|
+
): string[] {
|
|
1913
|
+
return reasons
|
|
1914
|
+
.filter((reason) => reason.code !== 'RULE_WARNING')
|
|
1915
|
+
.slice(0, Math.max(0, limit))
|
|
1916
|
+
.map(formatCandidateScoreReason);
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/*
|
|
1920
|
+
* Render one candidate: "Ana (score 32): prefers these hours, 12h under
|
|
1921
|
+
* target", "Ben - warning: over the hours limit", "Cam - can't: on approved
|
|
1922
|
+
* time off".
|
|
1923
|
+
*/
|
|
1924
|
+
function formatCandidateLine(
|
|
1925
|
+
candidate: ScheduleCandidateTextItem,
|
|
1926
|
+
context: ScheduleTextContext,
|
|
1927
|
+
): string {
|
|
1928
|
+
const score =
|
|
1929
|
+
candidate.score === null
|
|
1930
|
+
? ''
|
|
1931
|
+
: ` (score ${Math.round(candidate.score * 10) / 10})`;
|
|
1932
|
+
if (!candidate.eligible) {
|
|
1933
|
+
const blocks = getReasonClauses(candidate.reasons, 'BLOCK', context);
|
|
1934
|
+
return `${candidate.name}${score} - can't: ${blocks.join('; ') || 'not eligible'}`;
|
|
1935
|
+
}
|
|
1936
|
+
const why = formatCandidateScoreClauses(candidate.scoreReasons, 2);
|
|
1937
|
+
const warns = getReasonClauses(candidate.reasons, 'WARN', context);
|
|
1938
|
+
return `${candidate.name}${score}${why.length ? `: ${why.join(', ')}` : ''}${warns.length ? ` - warning: ${warns.join('; ')}` : ''}`;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
/*
|
|
1942
|
+
* Render a candidate list for one seat (tool text): how many can work it,
|
|
1943
|
+
* then the candidates in the given order with their reasons, capped.
|
|
1944
|
+
*/
|
|
1945
|
+
export function formatCandidates(input: ScheduleCandidatesTextInput): string {
|
|
1946
|
+
const { context, candidates } = input;
|
|
1947
|
+
const holder = input.shift.assigneeResourceId
|
|
1948
|
+
? `now ${getAssigneeText(input.shift)}`
|
|
1949
|
+
: 'open';
|
|
1950
|
+
const shift = `${formatScheduleShiftLine(input.shift, context)} (${holder})`;
|
|
1951
|
+
if (!candidates.length)
|
|
1952
|
+
return joinScheduleText([`No candidates for ${shift}.`, context.link]);
|
|
1953
|
+
const eligible = candidates.filter((candidate) => candidate.eligible).length;
|
|
1954
|
+
return joinScheduleText([
|
|
1955
|
+
`Candidates for ${shift}: ${eligible} can work it, ${candidates.length - eligible} can't.`,
|
|
1956
|
+
...capLines(
|
|
1957
|
+
candidates.map(
|
|
1958
|
+
(candidate, index) =>
|
|
1959
|
+
`${index + 1}. ${formatCandidateLine(candidate, context)}`,
|
|
1960
|
+
),
|
|
1961
|
+
FILE_CONSTANTS.toolListCap,
|
|
1962
|
+
),
|
|
1963
|
+
context.link,
|
|
1964
|
+
]);
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
/*
|
|
1968
|
+
* Render coverage findings for a range (tool text): counts, blockers, then
|
|
1969
|
+
* warnings (acknowledged ones marked), one cap across both lists, and when
|
|
1970
|
+
* the evaluation was incomplete, each rule that could not be checked with
|
|
1971
|
+
* how to fix it.
|
|
1972
|
+
*/
|
|
1973
|
+
export function formatCoverageFindings(
|
|
1974
|
+
input: ScheduleCoverageFindingsTextInput,
|
|
1975
|
+
): string {
|
|
1976
|
+
const { context } = input;
|
|
1977
|
+
const findings = sortTextFindings(input.findings);
|
|
1978
|
+
const blockers = findings.filter((finding) => finding.severity === 'BLOCK');
|
|
1979
|
+
const warnings = findings.filter((finding) => finding.severity === 'WARN');
|
|
1980
|
+
const accepted = warnings.filter((finding) => finding.acknowledged).length;
|
|
1981
|
+
const counts = findings.length
|
|
1982
|
+
? `${pluralize(blockers.length, 'blocker')}, ${pluralize(warnings.length, 'warning')}${accepted ? ` (${accepted} accepted)` : ''}`
|
|
1983
|
+
: 'no problems found';
|
|
1984
|
+
const blockerShown = Math.min(blockers.length, FILE_CONSTANTS.toolListCap);
|
|
1985
|
+
const warningShown = Math.min(
|
|
1986
|
+
warnings.length,
|
|
1987
|
+
FILE_CONSTANTS.toolListCap - blockerShown,
|
|
1988
|
+
);
|
|
1989
|
+
const hidden = findings.length - blockerShown - warningShown;
|
|
1990
|
+
return joinScheduleText([
|
|
1991
|
+
`${getScheduleTextTitle(context, input.fromDate, input.toDate)}: ${counts}.`,
|
|
1992
|
+
blockerShown ? 'Blockers:' : null,
|
|
1993
|
+
...blockers.slice(0, blockerShown).map((finding) => `- ${finding.message}`),
|
|
1994
|
+
warningShown ? 'Warnings:' : null,
|
|
1995
|
+
...warnings
|
|
1996
|
+
.slice(0, warningShown)
|
|
1997
|
+
.map(
|
|
1998
|
+
(finding) =>
|
|
1999
|
+
`- ${finding.acknowledged ? 'Accepted: ' : ''}${finding.message}`,
|
|
2000
|
+
),
|
|
2001
|
+
hidden > 0 ? `+${hidden} more` : null,
|
|
2002
|
+
...getIncompleteLines(input.diagnostics),
|
|
2003
|
+
context.link,
|
|
2004
|
+
]);
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
/*
|
|
2008
|
+
* The lines of an incomplete check: what could not be checked and how to
|
|
2009
|
+
* fix it, capped; none when the check was complete.
|
|
2010
|
+
*/
|
|
2011
|
+
function getIncompleteLines(diagnostics: ScheduleTextDiagnostic[]): string[] {
|
|
2012
|
+
const lines = getDiagnosticLines(diagnostics);
|
|
2013
|
+
if (!lines.length) return [];
|
|
2014
|
+
return [
|
|
2015
|
+
"Incomplete: these couldn't be checked, and it can't be published until they are fixed:",
|
|
2016
|
+
...capLines(
|
|
2017
|
+
lines.map((line) => `- ${line}`),
|
|
2018
|
+
FILE_CONSTANTS.toolListCap,
|
|
2019
|
+
),
|
|
2020
|
+
];
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
/*
|
|
2024
|
+
* Render diagnostics as distinct sentences, in order.
|
|
2025
|
+
*/
|
|
2026
|
+
function getDiagnosticLines(diagnostics: ScheduleTextDiagnostic[]): string[] {
|
|
2027
|
+
return [...new Set(diagnostics.map(formatCoverageDiagnostic))];
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
/*
|
|
2031
|
+
* Render one evaluation diagnostic as a sentence: the rule and the room or
|
|
2032
|
+
* person it concerns, what is missing and how to fix it ("Children per
|
|
2033
|
+
* adult, Infant room: no ratio for TODDLER. Add one to the rule.").
|
|
2034
|
+
*/
|
|
2035
|
+
export function formatCoverageDiagnostic(
|
|
2036
|
+
diagnostic: ScheduleTextDiagnostic,
|
|
2037
|
+
): string {
|
|
2038
|
+
const { detail } = diagnostic;
|
|
2039
|
+
const subject = [diagnostic.ruleLabel, diagnostic.resourceName]
|
|
2040
|
+
.filter(Boolean)
|
|
2041
|
+
.join(', ');
|
|
2042
|
+
const where = subject ? `${toScheduleGsmText(subject)}: ` : '';
|
|
2043
|
+
const key = typeof detail.key === 'string' ? detail.key : null;
|
|
2044
|
+
switch (diagnostic.code) {
|
|
2045
|
+
case 'OPERATING_HOURS_NOT_CONFIGURED':
|
|
2046
|
+
return `${where}the location has no opening hours. Set them.`;
|
|
2047
|
+
case 'RATIO_NOT_CONFIGURED':
|
|
2048
|
+
return `${where}no ratio for ${key ?? 'an age group'}. Add one to the rule.`;
|
|
2049
|
+
case 'AGE_GROUP_UNKNOWN':
|
|
2050
|
+
return `${where}${key ?? 'an age group'} is not one of the age groups. Add it to the age groups or fix the demand.`;
|
|
2051
|
+
case 'QUALIFICATION_EXPIRY_INVALID':
|
|
2052
|
+
return `${where}the expiry date of ${key ?? 'a qualification'} can't be read. Fix the date.`;
|
|
2053
|
+
case 'UNKNOWN_ROLE':
|
|
2054
|
+
return `${where}it names a role that no longer exists. Fix or remove it.`;
|
|
2055
|
+
case 'UNKNOWN_RESOURCE':
|
|
2056
|
+
return `${where}it names a person or room that no longer exists. Fix or remove it.`;
|
|
2057
|
+
case 'RULE_CONFIG_INVALID':
|
|
2058
|
+
return `${where}its settings are not valid${typeof detail.error === 'string' ? ` (${clipText(toScheduleGsmText(detail.error), FILE_CONSTANTS.smsLineMaxLength)})` : ''}. Fix the rule.`;
|
|
2059
|
+
case 'RULE_SUBJECT_KIND_MISMATCH':
|
|
2060
|
+
return `${where}it is set on the wrong kind of person or room. Fix the rule.`;
|
|
2061
|
+
case 'WINDOW_INVALID':
|
|
2062
|
+
return `The date range is too long to check (at most ${pluralize(readDetailNumber(detail, 'maxDays') ?? SCHEDULE_COVERAGE_MAX_WINDOW_DAYS, 'day')}). Check a shorter range.`;
|
|
2063
|
+
case 'VIOLATION_CAP':
|
|
2064
|
+
return 'Too many problems to list them all. Check a shorter range.';
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
/*
|
|
2069
|
+
* Render one standing item: "7am-3pm Opener at Bar - Ana" / "- open".
|
|
2070
|
+
*/
|
|
2071
|
+
function formatStandingItem(item: ScheduleStandingTextItem): string {
|
|
2072
|
+
const description = getShiftDescription(item);
|
|
2073
|
+
return `${formatClockTextRange(item.startTime, item.endTime)}${description ? ` ${description}` : ''} - ${item.assigneeName || 'open'}`;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
/*
|
|
2077
|
+
* Order standing items of one day by start, end, then their text.
|
|
2078
|
+
*/
|
|
2079
|
+
function sortStandingItems(
|
|
2080
|
+
items: ScheduleStandingTextItem[],
|
|
2081
|
+
): ScheduleStandingTextItem[] {
|
|
2082
|
+
return [...items].sort(
|
|
2083
|
+
(a, b) =>
|
|
2084
|
+
(parseScheduleClockTime(a.startTime) ?? 0) -
|
|
2085
|
+
(parseScheduleClockTime(b.startTime) ?? 0) ||
|
|
2086
|
+
(parseScheduleClockTime(a.endTime) ?? 0) -
|
|
2087
|
+
(parseScheduleClockTime(b.endTime) ?? 0) ||
|
|
2088
|
+
compareText(formatStandingItem(a), formatStandingItem(b)),
|
|
2089
|
+
);
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
/*
|
|
2093
|
+
* The heading of the standing schedule: its name, calendar and rotation
|
|
2094
|
+
* (week A named by the first day of the pay week holding the anchor).
|
|
2095
|
+
*/
|
|
2096
|
+
function getStandingHeader(input: ScheduleStandingScheduleTextInput): string {
|
|
2097
|
+
const calendar = input.context.calendarName
|
|
2098
|
+
? ` for ${input.context.calendarName}`
|
|
2099
|
+
: '';
|
|
2100
|
+
const anchor =
|
|
2101
|
+
input.rotationAnchor && isScheduleDateKey(input.rotationAnchor)
|
|
2102
|
+
? `, week A from ${formatScheduleDay(getScheduleWeekStart(input.rotationAnchor, input.payWeekStart))}`
|
|
2103
|
+
: '';
|
|
2104
|
+
const rotation =
|
|
2105
|
+
input.rotationWeeks > 1
|
|
2106
|
+
? `${input.rotationWeeks}-week rotation${anchor}`
|
|
2107
|
+
: 'repeats every week';
|
|
2108
|
+
return `${input.name}${calendar}: ${rotation}`;
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2111
|
+
/*
|
|
2112
|
+
* Render the lines of one rotation week: one line per weekday (from the
|
|
2113
|
+
* week's first day) listing its items.
|
|
2114
|
+
*/
|
|
2115
|
+
function getStandingWeekLines(
|
|
2116
|
+
items: ScheduleStandingTextItem[],
|
|
2117
|
+
firstWeekday: number,
|
|
2118
|
+
): string[] {
|
|
2119
|
+
const lines: string[] = [];
|
|
2120
|
+
for (let offset = 0; offset < 7; offset++) {
|
|
2121
|
+
const weekday = (firstWeekday + offset) % 7;
|
|
2122
|
+
const dayItems = items.filter((item) => item.weekday === weekday);
|
|
2123
|
+
if (dayItems.length)
|
|
2124
|
+
lines.push(
|
|
2125
|
+
`${FILE_CONSTANTS.weekdayShort[weekday]}: ${sortStandingItems(dayItems).map(formatStandingItem).join('; ')}`,
|
|
2126
|
+
);
|
|
2127
|
+
}
|
|
2128
|
+
return lines;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
/*
|
|
2132
|
+
* Render the standing schedule (tool text): grouped by rotation week (A,
|
|
2133
|
+
* B, ...) then weekday, open seats marked, and which rotation week the next
|
|
2134
|
+
* period starts on. A week's first day is the org's payWeekStart, the same
|
|
2135
|
+
* weeks getRotationWeek counts.
|
|
2136
|
+
*/
|
|
2137
|
+
export function formatStandingSchedule(
|
|
2138
|
+
input: ScheduleStandingScheduleTextInput,
|
|
2139
|
+
): string {
|
|
2140
|
+
const { context } = input;
|
|
2141
|
+
const header = getStandingHeader(input);
|
|
2142
|
+
if (!input.items.length)
|
|
2143
|
+
return joinScheduleText([header, 'No standing shifts yet.', context.link]);
|
|
2144
|
+
const weeks = Math.max(1, input.rotationWeeks);
|
|
2145
|
+
const lines = [`${header}:`];
|
|
2146
|
+
for (let week = 1; week <= weeks; week++) {
|
|
2147
|
+
const weekLines = getStandingWeekLines(
|
|
2148
|
+
input.items.filter((item) => item.week === week),
|
|
2149
|
+
input.payWeekStart,
|
|
2150
|
+
);
|
|
2151
|
+
if (weeks > 1)
|
|
2152
|
+
lines.push(
|
|
2153
|
+
`Week ${getScheduleRotationWeekLabel(week)}:${weekLines.length ? '' : ' no shifts'}`,
|
|
2154
|
+
);
|
|
2155
|
+
lines.push(...weekLines);
|
|
2156
|
+
}
|
|
2157
|
+
if (weeks > 1 && input.nextRotationWeek)
|
|
2158
|
+
lines.push(
|
|
2159
|
+
`The next period starts on week ${getScheduleRotationWeekLabel(input.nextRotationWeek)}.`,
|
|
2160
|
+
);
|
|
2161
|
+
return joinScheduleText([...lines, context.link]);
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
/*
|
|
2165
|
+
* Read a finite number from a detail object.
|
|
2166
|
+
*/
|
|
2167
|
+
function readDetailNumber(
|
|
2168
|
+
detail: Record<string, unknown>,
|
|
2169
|
+
key: string,
|
|
2170
|
+
): number | null {
|
|
2171
|
+
const value = detail[key];
|
|
2172
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
/*
|
|
2176
|
+
* Read a list of strings from a detail object ([] when absent).
|
|
2177
|
+
*/
|
|
2178
|
+
function readDetailStrings(
|
|
2179
|
+
detail: Record<string, unknown>,
|
|
2180
|
+
key: string,
|
|
2181
|
+
): string[] {
|
|
2182
|
+
const value = detail[key];
|
|
2183
|
+
return Array.isArray(value)
|
|
2184
|
+
? value.filter((entry): entry is string => typeof entry === 'string')
|
|
2185
|
+
: [];
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
/*
|
|
2189
|
+
* Render a detail date (a date key or an instant) as "Mon Dec 14" in a
|
|
2190
|
+
* zone; null when it is unreadable.
|
|
2191
|
+
*/
|
|
2192
|
+
function formatDetailDate(value: unknown, timeZone: string): string | null {
|
|
2193
|
+
if (isScheduleDateKey(value)) return formatScheduleDay(value);
|
|
2194
|
+
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value)))
|
|
2195
|
+
return null;
|
|
2196
|
+
return formatScheduleDay(getScheduleLocalDate(value, timeZone));
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
/*
|
|
2200
|
+
* Name a MAX_HOURS period for a clause: "in a day", "in the pay week",
|
|
2201
|
+
* "in 7 days".
|
|
2202
|
+
*/
|
|
2203
|
+
function getMaxHoursPeriodText(detail: Record<string, unknown>): string {
|
|
2204
|
+
if (detail.period === 'DAY') return 'in a day';
|
|
2205
|
+
if (detail.period === 'PAY_WEEK') return 'in the pay week';
|
|
2206
|
+
const days = readDetailNumber(detail, 'days');
|
|
2207
|
+
return days ? `in ${pluralize(days, 'day')}` : 'in the period';
|
|
2208
|
+
}
|
|
2209
|
+
|
|
2210
|
+
/*
|
|
2211
|
+
* The parenthetical of a MAX_HOURS clause: " (42h of 40h in the pay
|
|
2212
|
+
* week)", or '' without the numbers.
|
|
2213
|
+
*/
|
|
2214
|
+
function getMaxHoursDetailText(detail: Record<string, unknown>): string {
|
|
2215
|
+
const worked = readDetailNumber(detail, 'workedMinutes');
|
|
2216
|
+
const max = readDetailNumber(detail, 'maxMinutes');
|
|
2217
|
+
if (worked === null || max === null) return '';
|
|
2218
|
+
return ` (${formatScheduleDuration(worked)} of ${formatScheduleDuration(max)} ${getMaxHoursPeriodText(detail)})`;
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
/*
|
|
2222
|
+
* Compare a seat with its SHIFT_LENGTH bounds from the finding's detail:
|
|
2223
|
+
* "longer than 12h" or "shorter than 4h".
|
|
2224
|
+
*/
|
|
2225
|
+
function getShiftLengthComparison(detail: Record<string, unknown>): string {
|
|
2226
|
+
const duration = readDetailNumber(detail, 'durationMinutes');
|
|
2227
|
+
const min = readDetailNumber(detail, 'minMinutes');
|
|
2228
|
+
const max = readDetailNumber(detail, 'maxMinutes');
|
|
2229
|
+
if (max !== null && (duration === null || duration > max))
|
|
2230
|
+
return `longer than ${formatScheduleDuration(max)}`;
|
|
2231
|
+
if (min !== null) return `shorter than ${formatScheduleDuration(min)}`;
|
|
2232
|
+
return 'outside the length limit';
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
/*
|
|
2236
|
+
* When a TIME_OFF reason or finding falls, in a zone: the day off for a
|
|
2237
|
+
* whole-day time off (detail.allDay: "Mon Nov 23", the local dates of the
|
|
2238
|
+
* overlap), else the time range ("Mon Nov 23, 9am-1pm").
|
|
2239
|
+
*/
|
|
2240
|
+
function formatTimeOffWhen(
|
|
2241
|
+
startAt: Date | string,
|
|
2242
|
+
endAt: Date | string,
|
|
2243
|
+
detail: Record<string, unknown>,
|
|
2244
|
+
timeZone: string,
|
|
2245
|
+
): string {
|
|
2246
|
+
return formatTimeOffRange(
|
|
2247
|
+
{ startAt, endAt, allDay: detail.allDay === true },
|
|
2248
|
+
timeZone,
|
|
2249
|
+
);
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
/*
|
|
2253
|
+
* Render one eligibility reason as a short clause, for lists and requests:
|
|
2254
|
+
* "on approved time off", "over the hours limit (42h of 40h in the pay
|
|
2255
|
+
* week)". Times are in the context's zone.
|
|
2256
|
+
*/
|
|
2257
|
+
export function formatEligibilityReason(
|
|
2258
|
+
reason: ScheduleEligibilityReasonObj,
|
|
2259
|
+
context: ScheduleTextContext,
|
|
2260
|
+
): string {
|
|
2261
|
+
const { detail } = reason;
|
|
2262
|
+
const when =
|
|
2263
|
+
reason.startAt && reason.endAt
|
|
2264
|
+
? ` ${formatScheduleTimeRange(reason.startAt, reason.endAt, context.timeZone)}`
|
|
2265
|
+
: '';
|
|
2266
|
+
const keys = readDetailStrings(detail, 'keys').join(', ');
|
|
2267
|
+
switch (reason.code) {
|
|
2268
|
+
case 'NOT_PERSON':
|
|
2269
|
+
return 'not a staff member';
|
|
2270
|
+
case 'RESOURCE_RETIRED':
|
|
2271
|
+
return 'no longer active';
|
|
2272
|
+
case 'NOT_MEMBER':
|
|
2273
|
+
return 'no longer a member';
|
|
2274
|
+
case 'SHIFT_CANCELED':
|
|
2275
|
+
return 'the shift is canceled';
|
|
2276
|
+
case 'SHIFT_ENDED':
|
|
2277
|
+
return 'the shift is over';
|
|
2278
|
+
case 'ALREADY_ASSIGNED':
|
|
2279
|
+
return 'already on this shift';
|
|
2280
|
+
case 'ROLE_MISSING':
|
|
2281
|
+
return "doesn't have the role";
|
|
2282
|
+
case 'QUALIFICATION_MISSING':
|
|
2283
|
+
return keys ? `missing ${keys}` : 'missing a required qualification';
|
|
2284
|
+
case 'QUALIFICATION_EXPIRED':
|
|
2285
|
+
return keys ? `${keys} expired` : 'a required qualification expired';
|
|
2286
|
+
case 'TIME_OFF':
|
|
2287
|
+
return reason.startAt && reason.endAt
|
|
2288
|
+
? `on approved time off ${formatTimeOffWhen(reason.startAt, reason.endAt, detail, context.timeZone)}`
|
|
2289
|
+
: 'on approved time off';
|
|
2290
|
+
case 'OVERLAP':
|
|
2291
|
+
return `already working${when}`;
|
|
2292
|
+
case 'UNAVAILABLE':
|
|
2293
|
+
return `unavailable${when}`;
|
|
2294
|
+
case 'MAX_HOURS':
|
|
2295
|
+
return `over the hours limit${getMaxHoursDetailText(detail)}`;
|
|
2296
|
+
case 'MIN_REST': {
|
|
2297
|
+
const rest = readDetailNumber(detail, 'restMinutes');
|
|
2298
|
+
const min = readDetailNumber(detail, 'minMinutes');
|
|
2299
|
+
return rest !== null && min !== null
|
|
2300
|
+
? `only ${formatScheduleDuration(rest)} rest between shifts (${formatScheduleDuration(min)} needed)`
|
|
2301
|
+
: 'not enough rest between shifts';
|
|
2302
|
+
}
|
|
2303
|
+
case 'MAX_CONSECUTIVE_DAYS': {
|
|
2304
|
+
const days = readDetailNumber(detail, 'days');
|
|
2305
|
+
return days
|
|
2306
|
+
? `more than ${pluralize(days, 'day')} in a row`
|
|
2307
|
+
: 'too many days in a row';
|
|
2308
|
+
}
|
|
2309
|
+
case 'SHIFT_LENGTH':
|
|
2310
|
+
return `shift ${getShiftLengthComparison(detail)}`;
|
|
2311
|
+
case 'COVERAGE_IMPACT':
|
|
2312
|
+
return 'would leave the schedule short-staffed';
|
|
2313
|
+
default:
|
|
2314
|
+
return String(reason.code).toLowerCase().replace(/_/g, ' ');
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
/*
|
|
2319
|
+
* Name a coverage violation's room, or the location as a whole.
|
|
2320
|
+
*/
|
|
2321
|
+
function getViolationPlace(
|
|
2322
|
+
violation: CoverageViolationObj,
|
|
2323
|
+
names: ScheduleViolationMessageNames,
|
|
2324
|
+
): string {
|
|
2325
|
+
return violation.resourceId
|
|
2326
|
+
? names.resource(violation.resourceId)
|
|
2327
|
+
: 'The location';
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
/*
|
|
2331
|
+
* One sentence for a coverage kind: staffing, ratio, group size, room
|
|
2332
|
+
* capacity or operating hours.
|
|
2333
|
+
*/
|
|
2334
|
+
function formatCoverageViolationSentence(
|
|
2335
|
+
violation: CoverageViolationObj,
|
|
2336
|
+
names: ScheduleViolationMessageNames,
|
|
2337
|
+
when: string,
|
|
2338
|
+
): string {
|
|
2339
|
+
const { detail, degree } = violation;
|
|
2340
|
+
const place = getViolationPlace(violation, names);
|
|
2341
|
+
switch (violation.kind) {
|
|
2342
|
+
case 'STAFFING_REQUIREMENT': {
|
|
2343
|
+
const minCount = readDetailNumber(detail, 'minCount') ?? degree;
|
|
2344
|
+
const roles =
|
|
2345
|
+
readDetailStrings(detail, 'roleIdsAny').map(names.role).join(' or ') ||
|
|
2346
|
+
'staff';
|
|
2347
|
+
const at = violation.resourceId ? ` at ${place}` : '';
|
|
2348
|
+
return `${when}: ${Math.max(0, minCount - degree)} of ${minCount} ${roles} scheduled${at}.`;
|
|
2349
|
+
}
|
|
2350
|
+
case 'RATIO': {
|
|
2351
|
+
if (violation.code === 'GROUP_SIZE') {
|
|
2352
|
+
const keys = readDetailStrings(detail, 'keys').join(', ');
|
|
2353
|
+
return `${place} is over the ${keys || 'group'} group size by ${pluralize(degree, 'child', 'children')}, ${when}.`;
|
|
2354
|
+
}
|
|
2355
|
+
const required = readDetailNumber(detail, 'required');
|
|
2356
|
+
const needs = required === null ? '' : ` (needs ${required})`;
|
|
2357
|
+
return `${place} is ${formatCountWord(degree)} ${degree === 1 ? 'adult' : 'adults'} short${needs}, ${when}.`;
|
|
2358
|
+
}
|
|
2359
|
+
case 'ROOM_CAPACITY':
|
|
2360
|
+
return `${place} is over capacity by ${pluralize(degree, 'child', 'children')}, ${when}.`;
|
|
2361
|
+
default: {
|
|
2362
|
+
const minAdults = readDetailNumber(detail, 'minAdults') ?? degree;
|
|
2363
|
+
const scope =
|
|
2364
|
+
detail.scope === 'ROOM' && violation.resourceId
|
|
2365
|
+
? place
|
|
2366
|
+
: 'The location';
|
|
2367
|
+
return `${scope} has ${Math.max(0, minAdults - degree)} of ${pluralize(minAdults, 'required adult')} while open, ${when}.`;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
/*
|
|
2373
|
+
* One sentence for an ELIGIBILITY finding: "<shift>: Ana is on approved
|
|
2374
|
+
* time off Fri Dec 18, 8pm-2am."
|
|
2375
|
+
*/
|
|
2376
|
+
function formatEligibilityViolationSentence(
|
|
2377
|
+
violation: CoverageViolationObj,
|
|
2378
|
+
names: ScheduleViolationMessageNames,
|
|
2379
|
+
when: string,
|
|
2380
|
+
): string {
|
|
2381
|
+
const shift = violation.shiftId ? names.shift(violation.shiftId) : 'A shift';
|
|
2382
|
+
const person = violation.resourceId
|
|
2383
|
+
? names.resource(violation.resourceId)
|
|
2384
|
+
: 'Someone';
|
|
2385
|
+
const keys = readDetailStrings(violation.detail, 'keys').join(', ');
|
|
2386
|
+
const timeOffWhen = formatTimeOffWhen(
|
|
2387
|
+
violation.startAt,
|
|
2388
|
+
violation.endAt,
|
|
2389
|
+
violation.detail,
|
|
2390
|
+
names.timeZone,
|
|
2391
|
+
);
|
|
2392
|
+
const clauses: Record<string, string> = {
|
|
2393
|
+
NOT_PERSON: 'is not a staff member',
|
|
2394
|
+
RESOURCE_RETIRED: 'is no longer active',
|
|
2395
|
+
NOT_MEMBER: 'is no longer a member',
|
|
2396
|
+
ROLE_MISSING: "doesn't have the shift's role",
|
|
2397
|
+
QUALIFICATION_MISSING: `is missing a qualification${keys ? ` (${keys})` : ''}`,
|
|
2398
|
+
QUALIFICATION_EXPIRED: `has an expired qualification${keys ? ` (${keys})` : ''}`,
|
|
2399
|
+
TIME_OFF: `is on approved time off ${timeOffWhen}`,
|
|
2400
|
+
OVERLAP: `is on another shift ${when}`,
|
|
2401
|
+
UNAVAILABLE: `is unavailable ${when}`,
|
|
2402
|
+
};
|
|
2403
|
+
return `${shift}: ${person} ${clauses[violation.code ?? ''] ?? `is not eligible ${when}`}.`;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
/*
|
|
2407
|
+
* One sentence for a person rule: hours, rest, consecutive days or shift
|
|
2408
|
+
* length, naming the breaking seat.
|
|
2409
|
+
*/
|
|
2410
|
+
function formatPersonRuleViolationSentence(
|
|
2411
|
+
violation: CoverageViolationObj,
|
|
2412
|
+
names: ScheduleViolationMessageNames,
|
|
2413
|
+
): string {
|
|
2414
|
+
const { detail, degree } = violation;
|
|
2415
|
+
const shift = violation.shiftId ? names.shift(violation.shiftId) : 'a shift';
|
|
2416
|
+
const person = violation.resourceId
|
|
2417
|
+
? names.resource(violation.resourceId)
|
|
2418
|
+
: 'Someone';
|
|
2419
|
+
switch (violation.kind) {
|
|
2420
|
+
case 'MAX_HOURS': {
|
|
2421
|
+
const worked = readDetailNumber(detail, 'workedMinutes');
|
|
2422
|
+
const max = readDetailNumber(detail, 'maxMinutes');
|
|
2423
|
+
const start = formatDetailDate(detail.periodStart, names.timeZone);
|
|
2424
|
+
const period =
|
|
2425
|
+
detail.period === 'DAY'
|
|
2426
|
+
? start
|
|
2427
|
+
? `on ${start}`
|
|
2428
|
+
: 'in a day'
|
|
2429
|
+
: detail.period === 'PAY_WEEK'
|
|
2430
|
+
? start
|
|
2431
|
+
? `in the pay week of ${start}`
|
|
2432
|
+
: 'in the pay week'
|
|
2433
|
+
: getMaxHoursPeriodText(detail);
|
|
2434
|
+
if (worked === null || max === null)
|
|
2435
|
+
return `${person} is over the hours limit ${period} (${shift}).`;
|
|
2436
|
+
return `${person} works ${formatScheduleDuration(worked)} ${period}, over the ${formatScheduleDuration(max)} limit (${shift}).`;
|
|
2437
|
+
}
|
|
2438
|
+
case 'MIN_REST': {
|
|
2439
|
+
const rest = readDetailNumber(detail, 'restMinutes') ?? 0;
|
|
2440
|
+
const min = readDetailNumber(detail, 'minMinutes') ?? rest + degree;
|
|
2441
|
+
return `${person} has ${formatScheduleDuration(rest)} of rest before ${shift}; ${formatScheduleDuration(min)} required.`;
|
|
2442
|
+
}
|
|
2443
|
+
case 'MAX_CONSECUTIVE_DAYS': {
|
|
2444
|
+
const days = readDetailNumber(detail, 'days') ?? 0;
|
|
2445
|
+
const start = formatDetailDate(detail.runStartDate, names.timeZone);
|
|
2446
|
+
// A truncated run was only measured back so far: it may be longer
|
|
2447
|
+
const atLeast = detail.truncated === true;
|
|
2448
|
+
return `${shift} makes ${atLeast ? 'at least ' : ''}${days + degree} days in a row for ${person}${start ? ` (from ${start}${atLeast ? ' or earlier' : ''})` : ''}; the limit is ${days}.`;
|
|
2449
|
+
}
|
|
2450
|
+
default: {
|
|
2451
|
+
const duration = readDetailNumber(detail, 'durationMinutes');
|
|
2452
|
+
const length =
|
|
2453
|
+
duration === null ? '' : `${formatScheduleDuration(duration)}, `;
|
|
2454
|
+
return `${shift} is ${length}${getShiftLengthComparison(detail)}.`;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
/*
|
|
2460
|
+
* One sentence for a NOTICE_PERIOD finding: a late publish or changes
|
|
2461
|
+
* inside the notice window.
|
|
2462
|
+
*/
|
|
2463
|
+
function formatNoticeViolationSentence(
|
|
2464
|
+
violation: CoverageViolationObj,
|
|
2465
|
+
names: ScheduleViolationMessageNames,
|
|
2466
|
+
): string {
|
|
2467
|
+
const shift = violation.shiftId ? names.shift(violation.shiftId) : 'A shift';
|
|
2468
|
+
const person = violation.resourceId
|
|
2469
|
+
? names.resource(violation.resourceId)
|
|
2470
|
+
: null;
|
|
2471
|
+
const days = readDetailNumber(violation.detail, 'days') ?? 0;
|
|
2472
|
+
if (violation.code === 'LATE_CHANGE')
|
|
2473
|
+
return `${shift} changed ${pluralize(violation.degree, 'time')} within ${pluralize(days, 'day')} of its start${person ? ` (${person})` : ''}.`;
|
|
2474
|
+
const notice = days === 1 ? "1 day's" : `${days} days'`;
|
|
2475
|
+
return `${shift} gets less than ${notice} notice${person ? ` for ${person}` : ''}.`;
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
/*
|
|
2479
|
+
* Render the stored message of a violation (schedule_violations.message):
|
|
2480
|
+
* one sentence per kind and code from its detail, names resolved through
|
|
2481
|
+
* `names`, times in `names.timeZone`, at most
|
|
2482
|
+
* SCHEDULE_VIOLATION_MESSAGE_MAX_LENGTH characters.
|
|
2483
|
+
*/
|
|
2484
|
+
export function formatViolationMessage(
|
|
2485
|
+
violation: CoverageViolationObj,
|
|
2486
|
+
names: ScheduleViolationMessageNames,
|
|
2487
|
+
): string {
|
|
2488
|
+
const when = formatScheduleTimeRange(
|
|
2489
|
+
violation.startAt,
|
|
2490
|
+
violation.endAt,
|
|
2491
|
+
names.timeZone,
|
|
2492
|
+
);
|
|
2493
|
+
let sentence: string;
|
|
2494
|
+
if (violation.kind === 'ELIGIBILITY')
|
|
2495
|
+
sentence = formatEligibilityViolationSentence(violation, names, when);
|
|
2496
|
+
else if (violation.kind === 'NOTICE_PERIOD')
|
|
2497
|
+
sentence = formatNoticeViolationSentence(violation, names);
|
|
2498
|
+
else if (
|
|
2499
|
+
violation.kind === 'MAX_HOURS' ||
|
|
2500
|
+
violation.kind === 'MIN_REST' ||
|
|
2501
|
+
violation.kind === 'MAX_CONSECUTIVE_DAYS' ||
|
|
2502
|
+
violation.kind === 'SHIFT_LENGTH'
|
|
2503
|
+
)
|
|
2504
|
+
sentence = formatPersonRuleViolationSentence(violation, names);
|
|
2505
|
+
else sentence = formatCoverageViolationSentence(violation, names, when);
|
|
2506
|
+
return clipText(
|
|
2507
|
+
toScheduleGsmText(sentence),
|
|
2508
|
+
SCHEDULE_VIOLATION_MESSAGE_MAX_LENGTH,
|
|
2509
|
+
);
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
/*
|
|
2513
|
+
* Return the email subject of a notice kind (SMS and in-app use the body).
|
|
2514
|
+
*/
|
|
2515
|
+
export function getScheduleNoticeSubject(
|
|
2516
|
+
eventKind: ScheduleNotificationEventKindEnum,
|
|
2517
|
+
): string {
|
|
2518
|
+
return FILE_CONSTANTS.noticeSubjects[eventKind] ?? 'Schedule update';
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
/*
|
|
2522
|
+
* Render the range of a time off in a zone: local dates for an all-day one
|
|
2523
|
+
* ("Dec 20-21", "Sat Dec 20"; its end is the exclusive local midnight),
|
|
2524
|
+
* else the instant range ("Fri Dec 4, 9am-5pm").
|
|
2525
|
+
*/
|
|
2526
|
+
export function formatTimeOffRange(
|
|
2527
|
+
timeOff: { startAt: Date | string; endAt: Date | string; allDay: boolean },
|
|
2528
|
+
timeZone: string,
|
|
2529
|
+
): string {
|
|
2530
|
+
if (!timeOff.allDay)
|
|
2531
|
+
return formatScheduleTimeRange(timeOff.startAt, timeOff.endAt, timeZone);
|
|
2532
|
+
const startMs = toScheduleTimeMs(timeOff.startAt);
|
|
2533
|
+
const lastMs = Math.max(toScheduleTimeMs(timeOff.endAt) - 1, startMs);
|
|
2534
|
+
return formatScheduleDateRange(
|
|
2535
|
+
getScheduleLocalDate(timeOff.startAt, timeZone),
|
|
2536
|
+
getScheduleLocalDate(new Date(lastMs), timeZone),
|
|
2537
|
+
);
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
/*
|
|
2541
|
+
* The title of a time off's seat list for its audience and status ("Approving
|
|
2542
|
+
* takes Ana off 2 shifts", "You're off 2 shifts"), or null when the seats
|
|
2543
|
+
* are not worth listing (declined, canceled).
|
|
2544
|
+
*/
|
|
2545
|
+
function getTimeOffShiftsTitle(
|
|
2546
|
+
input: ScheduleTimeOffTextInput,
|
|
2547
|
+
count: number,
|
|
2548
|
+
): string | null {
|
|
2549
|
+
const { status, personName } = input.timeOff;
|
|
2550
|
+
const shifts = pluralize(count, 'shift');
|
|
2551
|
+
if (status === 'PENDING')
|
|
2552
|
+
return input.audience === 'MANAGER'
|
|
2553
|
+
? `Approving takes ${personName} off ${shifts}`
|
|
2554
|
+
: `If approved, you come off ${shifts}`;
|
|
2555
|
+
if (status !== 'APPROVED') return null;
|
|
2556
|
+
if (input.audience === 'REQUESTER') return `You're off ${shifts}`;
|
|
2557
|
+
return count === 1
|
|
2558
|
+
? `1 of ${personName}'s shifts is open now`
|
|
2559
|
+
: `${count} of ${personName}'s shifts are open now`;
|
|
2560
|
+
}
|
|
2561
|
+
|
|
2562
|
+
/*
|
|
2563
|
+
* The first sentence of a time-off text: who asked and when (to a manager
|
|
2564
|
+
* while pending), else where it stands; a decline carries its note.
|
|
2565
|
+
*/
|
|
2566
|
+
function getTimeOffStatusLine(
|
|
2567
|
+
input: ScheduleTimeOffTextInput,
|
|
2568
|
+
prefix: string,
|
|
2569
|
+
range: string,
|
|
2570
|
+
): string {
|
|
2571
|
+
const { timeOff } = input;
|
|
2572
|
+
const owner =
|
|
2573
|
+
input.audience === 'REQUESTER'
|
|
2574
|
+
? 'Your time off'
|
|
2575
|
+
: `${timeOff.personName}'s time off`;
|
|
2576
|
+
if (timeOff.status === 'PENDING' && input.audience === 'MANAGER')
|
|
2577
|
+
return `${prefix}${timeOff.personName} asked for time off ${range}.`;
|
|
2578
|
+
const outcome =
|
|
2579
|
+
timeOff.status === 'DECLINED' && timeOff.decisionNote
|
|
2580
|
+
? `was declined: ${clipText(timeOff.decisionNote, FILE_CONSTANTS.smsQuoteMaxLength)}`
|
|
2581
|
+
: FILE_CONSTANTS.timeOffOutcomes[timeOff.status];
|
|
2582
|
+
return `${prefix}${ensurePeriod(`${owner} ${range} ${outcome}`)}`;
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
/*
|
|
2586
|
+
* How a manager answers a pending time off: YES or NO, or as a notice, to
|
|
2587
|
+
* ask the assistant; null once decided or for the requester.
|
|
2588
|
+
*/
|
|
2589
|
+
function getTimeOffAsk(input: ScheduleTimeOffTextInput): string | null {
|
|
2590
|
+
if (input.audience !== 'MANAGER' || input.timeOff.status !== 'PENDING')
|
|
2591
|
+
return null;
|
|
2592
|
+
return input.notice
|
|
2593
|
+
? `Ask the assistant to approve or decline ${input.timeOff.personName}'s time off.`
|
|
2594
|
+
: 'Reply YES to approve or NO to decline.';
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
/*
|
|
2598
|
+
* Render a time-off request (SMS-bound) for its audience, in the time off's
|
|
2599
|
+
* zone: MANAGER while pending (who, when, why, the seats an approval would
|
|
2600
|
+
* release, then how to decide: YES or NO, or as a notice, ask the
|
|
2601
|
+
* assistant), REQUESTER where it stands; a decline carries its note and an
|
|
2602
|
+
* approval lists the seats it released. Over budget the seat list shrinks to
|
|
2603
|
+
* its title.
|
|
2604
|
+
*/
|
|
2605
|
+
export function formatTimeOff(input: ScheduleTimeOffTextInput): string {
|
|
2606
|
+
const { context, timeOff } = input;
|
|
2607
|
+
const prefix = context.calendarName ? `${context.calendarName}: ` : '';
|
|
2608
|
+
const range = formatTimeOffRange(timeOff, context.timeZone);
|
|
2609
|
+
const shifts = getLiveTextShifts(input.conflictingShifts);
|
|
2610
|
+
const title = getTimeOffShiftsTitle(input, shifts.length);
|
|
2611
|
+
const shiftSection = createSection({
|
|
2612
|
+
title,
|
|
2613
|
+
items:
|
|
2614
|
+
title && shifts.length
|
|
2615
|
+
? shifts.map((shift) => formatScheduleShiftLine(shift, context))
|
|
2616
|
+
: [],
|
|
2617
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
2618
|
+
soft: 2,
|
|
2619
|
+
keepTitle: true,
|
|
2620
|
+
});
|
|
2621
|
+
const reason =
|
|
2622
|
+
input.audience === 'MANAGER' &&
|
|
2623
|
+
timeOff.status === 'PENDING' &&
|
|
2624
|
+
timeOff.reason
|
|
2625
|
+
? `Reason: ${clipText(timeOff.reason, FILE_CONSTANTS.smsQuoteMaxLength)}`
|
|
2626
|
+
: null;
|
|
2627
|
+
return fitScheduleTextParts(
|
|
2628
|
+
[
|
|
2629
|
+
getTimeOffStatusLine(input, prefix, range),
|
|
2630
|
+
reason,
|
|
2631
|
+
shiftSection,
|
|
2632
|
+
getTimeOffAsk(input),
|
|
2633
|
+
context.link,
|
|
2634
|
+
],
|
|
2635
|
+
[shiftSection],
|
|
2636
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
2637
|
+
);
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
/*
|
|
2641
|
+
* Name a person in a possessive phrase: "Ana's swap", or "the swap" when the
|
|
2642
|
+
* name is unknown.
|
|
2643
|
+
*/
|
|
2644
|
+
function getPossessive(name: string | null | undefined, noun: string): string {
|
|
2645
|
+
return name ? `${name}'s ${noun}` : `the ${noun}`;
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
/*
|
|
2649
|
+
* Render a seat for an ask line with its location's name: "Fri Dec 4,
|
|
2650
|
+
* 8pm-2am Bartender at Main bar (Main St)".
|
|
2651
|
+
*/
|
|
2652
|
+
function formatAskLineShift(
|
|
2653
|
+
shift: ScheduleTextShift,
|
|
2654
|
+
context: ScheduleTextContext,
|
|
2655
|
+
): string {
|
|
2656
|
+
return formatScheduleShiftLine(
|
|
2657
|
+
{ ...shift, calendarName: shift.calendarName ?? context.calendarName },
|
|
2658
|
+
context,
|
|
2659
|
+
);
|
|
2660
|
+
}
|
|
2661
|
+
|
|
2662
|
+
/*
|
|
2663
|
+
* The decision line of a request: "approve Ana's call-out: <seat>", "approve
|
|
2664
|
+
* Ana's new hours: Fri Dec 4, 8pm-9:30pm Bartender (was 8pm-2am)", "approve
|
|
2665
|
+
* Ana's swap: their <seat> for Ben's <seat>".
|
|
2666
|
+
*/
|
|
2667
|
+
function getRequestDecisionLine(input: ScheduleAskLineInput): string {
|
|
2668
|
+
const { context, shift, targetShift, proposed } = input;
|
|
2669
|
+
const person = input.personName || null;
|
|
2670
|
+
const noun = input.requestKind
|
|
2671
|
+
? FILE_CONSTANTS.requestNouns[input.requestKind]
|
|
2672
|
+
: 'request';
|
|
2673
|
+
const head = `approve ${getPossessive(person, noun)}`;
|
|
2674
|
+
if (!shift) return head;
|
|
2675
|
+
if (input.requestKind === 'SWAP' && targetShift)
|
|
2676
|
+
return `${head}: their ${formatScheduleShiftLine(shift, context)} for ${getPossessive(targetShift.assigneeName, formatScheduleShiftLine(targetShift, context))}`;
|
|
2677
|
+
if (input.requestKind === 'RETIME' && proposed) {
|
|
2678
|
+
const zone = getShiftZone(shift, context);
|
|
2679
|
+
const description = getShiftDescription(shift);
|
|
2680
|
+
const was =
|
|
2681
|
+
getScheduleLocalDate(shift.startAt, zone) ===
|
|
2682
|
+
getScheduleLocalDate(proposed.startAt, zone)
|
|
2683
|
+
? formatScheduleClockRange(shift.startAt, shift.endAt, zone)
|
|
2684
|
+
: formatScheduleTimeRange(shift.startAt, shift.endAt, zone);
|
|
2685
|
+
return `${head}: ${formatScheduleTimeRange(proposed.startAt, proposed.endAt, zone)}${description ? ` ${description}` : ''} (was ${was})`;
|
|
2686
|
+
}
|
|
2687
|
+
return `${head}: ${formatAskLineShift(shift, context)}`;
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
/*
|
|
2691
|
+
* What SMS consent is for in an organization of this scheduling type (null
|
|
2692
|
+
* reads as STAFF_SCHEDULES): the question's topic and the texts' name.
|
|
2693
|
+
*/
|
|
2694
|
+
function getConsentTopic(
|
|
2695
|
+
schedulingType: ScheduleSchedulingTypeEnum | null | undefined,
|
|
2696
|
+
): { about: string; texts: string } {
|
|
2697
|
+
return FILE_CONSTANTS.consentTopics[schedulingType ?? 'STAFF_SCHEDULES'];
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
/*
|
|
2701
|
+
* The period part of a publish or confirm line: "Main St, Dec 14-20 (38
|
|
2702
|
+
* shifts, 1 warning)".
|
|
2703
|
+
*/
|
|
2704
|
+
function getAskLinePeriod(input: ScheduleAskLineInput): string {
|
|
2705
|
+
const place = input.context.calendarName
|
|
2706
|
+
? `${input.context.calendarName}, `
|
|
2707
|
+
: '';
|
|
2708
|
+
const period = input.period
|
|
2709
|
+
? formatScheduleDateRange(input.period.fromDate, input.period.toDate)
|
|
2710
|
+
: 'the next period';
|
|
2711
|
+
const counts = [
|
|
2712
|
+
input.shiftCount != null ? pluralize(input.shiftCount, 'shift') : null,
|
|
2713
|
+
input.warningCount ? pluralize(input.warningCount, 'warning') : null,
|
|
2714
|
+
].filter(Boolean);
|
|
2715
|
+
return `${place}${period}${counts.length ? ` (${counts.join(', ')})` : ''}`;
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
/*
|
|
2719
|
+
* Build the line of an ask by kind, before clipping.
|
|
2720
|
+
*/
|
|
2721
|
+
function getAskLine(input: ScheduleAskLineInput): string {
|
|
2722
|
+
const { context, shift, targetShift } = input;
|
|
2723
|
+
const person = input.personName || 'someone';
|
|
2724
|
+
switch (input.kind) {
|
|
2725
|
+
case 'OFFER':
|
|
2726
|
+
return shift
|
|
2727
|
+
? `take the open shift ${formatAskLineShift(shift, context)}`
|
|
2728
|
+
: 'take an open shift';
|
|
2729
|
+
case 'SWAP_CONSENT':
|
|
2730
|
+
return `swap with ${person}: you take their ${targetShift ? formatScheduleShiftLine(targetShift, context) : 'shift'}; they take your ${shift ? formatScheduleShiftLine(shift, context) : 'shift'}`;
|
|
2731
|
+
case 'REQUEST_DECISION':
|
|
2732
|
+
return getRequestDecisionLine(input);
|
|
2733
|
+
case 'TIME_OFF_DECISION': {
|
|
2734
|
+
const range = input.timeOff
|
|
2735
|
+
? `: ${formatTimeOffRange(input.timeOff, context.timeZone)}`
|
|
2736
|
+
: '';
|
|
2737
|
+
const affected = input.affectedShiftCount
|
|
2738
|
+
? ` (${pluralize(input.affectedShiftCount, 'shift')} affected)`
|
|
2739
|
+
: '';
|
|
2740
|
+
return `approve ${person}'s time off${range}${affected}`;
|
|
2741
|
+
}
|
|
2742
|
+
case 'PUBLISH_REVIEW':
|
|
2743
|
+
return `publish ${getAskLinePeriod(input)}`;
|
|
2744
|
+
case 'SHIFTS_CONFIRM':
|
|
2745
|
+
return `confirm your shifts ${context.calendarName ? 'at' : 'for'} ${getAskLinePeriod(input)}`;
|
|
2746
|
+
case 'PLAN_REVIEW':
|
|
2747
|
+
return getPlanReviewAskLine(input);
|
|
2748
|
+
case 'PROGRESS_CHECK':
|
|
2749
|
+
return getProgressCheckAskLine(input);
|
|
2750
|
+
default:
|
|
2751
|
+
return `get ${getConsentTopic(input.schedulingType).texts} from ${input.organizationName || 'your team'}`;
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
/*
|
|
2756
|
+
* The line of a plan review: "accept the plan for Harbor Tower (24
|
|
2757
|
+
* activities, finish Mar 10)".
|
|
2758
|
+
*/
|
|
2759
|
+
function getPlanReviewAskLine(input: ScheduleAskLineInput): string {
|
|
2760
|
+
const name = input.projectName || input.context.calendarName;
|
|
2761
|
+
const counts = [
|
|
2762
|
+
input.activityCount != null
|
|
2763
|
+
? pluralize(input.activityCount, 'activity', 'activities')
|
|
2764
|
+
: null,
|
|
2765
|
+
input.finishAt
|
|
2766
|
+
? `finish ${formatMonthDay(getFinishLocalDate(input.finishAt, input.context.timeZone))}`
|
|
2767
|
+
: null,
|
|
2768
|
+
].filter(Boolean);
|
|
2769
|
+
return `accept the ${name ? `plan for ${name}` : 'proposed plan'}${counts.length ? ` (${counts.join(', ')})` : ''}`;
|
|
2770
|
+
}
|
|
2771
|
+
|
|
2772
|
+
/*
|
|
2773
|
+
* The line of a progress check-in with its numbered items: "report progress
|
|
2774
|
+
* on Harbor Tower: 1 Framing L2; 2 Drywall L1".
|
|
2775
|
+
*/
|
|
2776
|
+
function getProgressCheckAskLine(input: ScheduleAskLineInput): string {
|
|
2777
|
+
const name = input.projectName || input.context.calendarName;
|
|
2778
|
+
const items = (input.items ?? []).map(
|
|
2779
|
+
(item, index) => `${index + 1} ${item.trim()}`,
|
|
2780
|
+
);
|
|
2781
|
+
return `report progress ${name ? `on ${name}` : 'on your work'}${items.length ? `: ${items.join('; ')}` : ''}`;
|
|
2782
|
+
}
|
|
2783
|
+
|
|
2784
|
+
/*
|
|
2785
|
+
* Render one line naming what an ask asks, for chat context and lists
|
|
2786
|
+
* (payload.line): lowercase start, no link, GSM-7, times in the calendar
|
|
2787
|
+
* zone, at most SCHEDULE_ASK_LINE_MAX_LENGTH characters. "take the open
|
|
2788
|
+
* shift Fri Dec 4, 8pm-2am Bartender (Main St)", "approve Ana's time off:
|
|
2789
|
+
* Dec 20-22 (3 shifts affected)", "publish Main St, Dec 14-20 (38 shifts, 1
|
|
2790
|
+
* warning)", "get shift texts from Joe's Bar".
|
|
2791
|
+
*/
|
|
2792
|
+
export function formatAskLine(input: ScheduleAskLineInput): string {
|
|
2793
|
+
return clipText(
|
|
2794
|
+
toScheduleGsmText(getAskLine(input).replace(/\s+/g, ' ').trim()),
|
|
2795
|
+
SCHEDULE_ASK_LINE_MAX_LENGTH,
|
|
2796
|
+
);
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
/*
|
|
2800
|
+
* Render an OFFER ask: which seat, the manager's note, and how to answer (a
|
|
2801
|
+
* yes takes it, or asks for it when a manager confirms).
|
|
2802
|
+
*/
|
|
2803
|
+
function formatOfferAsk(
|
|
2804
|
+
input: Extract<ScheduleAskTextInput, { kind: 'OFFER' }>,
|
|
2805
|
+
): string {
|
|
2806
|
+
const { context } = input;
|
|
2807
|
+
const message = input.message?.trim()
|
|
2808
|
+
? clipText(input.message.trim(), FILE_CONSTANTS.smsQuoteMaxLength)
|
|
2809
|
+
: null;
|
|
2810
|
+
const question = context.calendarName
|
|
2811
|
+
? `${context.calendarName}: can you work`
|
|
2812
|
+
: 'Can you work';
|
|
2813
|
+
return joinScheduleText([
|
|
2814
|
+
`${question} ${formatScheduleShiftLine(input.shift, context)}?`,
|
|
2815
|
+
message,
|
|
2816
|
+
input.autoApprove
|
|
2817
|
+
? 'Reply YES to take it or NO to pass.'
|
|
2818
|
+
: 'Reply YES to ask for it (a manager confirms) or NO to pass.',
|
|
2819
|
+
context.link,
|
|
2820
|
+
]);
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
/*
|
|
2824
|
+
* Render the question an ask sends (SMS or in-app); every one ends with how
|
|
2825
|
+
* to answer it, then the link. OFFER: the seat and the manager's note;
|
|
2826
|
+
* SWAP_CONSENT / REQUEST_DECISION: formatRequest to the counterparty / the
|
|
2827
|
+
* manager; TIME_OFF_DECISION: formatTimeOff to the manager; PUBLISH_REVIEW:
|
|
2828
|
+
* the period summary; SHIFTS_CONFIRM: the person's shifts (no open seats);
|
|
2829
|
+
* SMS_CONSENT: the opt-in question (IMPLEMENTATION §1.9; about shifts or
|
|
2830
|
+
* project work by the organization's scheduling type); PLAN_REVIEW: the
|
|
2831
|
+
* plan summary (audience ASK); PROGRESS_CHECK: the numbered check-in.
|
|
2832
|
+
*/
|
|
2833
|
+
export function formatAskText(input: ScheduleAskTextInput): string {
|
|
2834
|
+
switch (input.kind) {
|
|
2835
|
+
case 'OFFER':
|
|
2836
|
+
return formatOfferAsk(input);
|
|
2837
|
+
case 'SWAP_CONSENT':
|
|
2838
|
+
return formatRequest({
|
|
2839
|
+
...input.request,
|
|
2840
|
+
audience: 'COUNTERPARTY',
|
|
2841
|
+
notice: false,
|
|
2842
|
+
});
|
|
2843
|
+
case 'REQUEST_DECISION':
|
|
2844
|
+
return formatRequest({
|
|
2845
|
+
...input.request,
|
|
2846
|
+
audience: 'MANAGER',
|
|
2847
|
+
notice: false,
|
|
2848
|
+
});
|
|
2849
|
+
case 'TIME_OFF_DECISION':
|
|
2850
|
+
return formatTimeOff({
|
|
2851
|
+
...input.timeOff,
|
|
2852
|
+
audience: 'MANAGER',
|
|
2853
|
+
notice: false,
|
|
2854
|
+
});
|
|
2855
|
+
case 'PUBLISH_REVIEW':
|
|
2856
|
+
return formatPeriodSummary(input.summary);
|
|
2857
|
+
case 'SHIFTS_CONFIRM':
|
|
2858
|
+
return renderMyShifts(
|
|
2859
|
+
{ ...input.myShifts, openShifts: [] },
|
|
2860
|
+
"Reply YES to confirm, or NO if one doesn't work.",
|
|
2861
|
+
);
|
|
2862
|
+
case 'PLAN_REVIEW':
|
|
2863
|
+
return formatPlanSummary({ ...input.summary, audience: 'ASK' });
|
|
2864
|
+
case 'PROGRESS_CHECK':
|
|
2865
|
+
return formatProgressCheck(input.check);
|
|
2866
|
+
default: {
|
|
2867
|
+
const topic = getConsentTopic(input.schedulingType);
|
|
2868
|
+
return joinScheduleText([
|
|
2869
|
+
`${input.organizationName.trim() || 'Your team'} wants to text you about ${topic.about}. Reply YES to get ${topic.texts}, STOP to opt out.`,
|
|
2870
|
+
]);
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
/*
|
|
2876
|
+
* The reply to an answer that came too late, by what closed the ask:
|
|
2877
|
+
* answered already, expired, a newer check-in, a plan already reviewed,
|
|
2878
|
+
* superseded, an offer covered or no longer needed, or anything else
|
|
2879
|
+
* handled.
|
|
2880
|
+
*/
|
|
2881
|
+
function getTooLateReply(input: ScheduleAskReplyTextInput): string {
|
|
2882
|
+
if (input.closed === 'ANSWERED') return 'You already answered that.';
|
|
2883
|
+
if (input.closed === 'EXPIRED') return 'That question has expired.';
|
|
2884
|
+
if (input.kind === 'PROGRESS_CHECK' && input.closed === 'SUPERSEDED')
|
|
2885
|
+
return 'A newer check-in was sent.';
|
|
2886
|
+
if (input.kind === 'PLAN_REVIEW' && input.closed === 'SUBJECT_CLOSED')
|
|
2887
|
+
return 'That plan was already reviewed.';
|
|
2888
|
+
if (input.closed === 'SUPERSEDED')
|
|
2889
|
+
return 'That summary is out of date. A newer one was sent.';
|
|
2890
|
+
if (input.kind === 'OFFER')
|
|
2891
|
+
return input.closed === 'SUBJECT_CLOSED'
|
|
2892
|
+
? 'That shift no longer needs covering. Thanks!'
|
|
2893
|
+
: 'That shift is already covered. Thanks!';
|
|
2894
|
+
return "That's already been handled. Thanks!";
|
|
2895
|
+
}
|
|
2896
|
+
|
|
2897
|
+
/*
|
|
2898
|
+
* Join refusal clauses into one clause list: distinct, trailing periods
|
|
2899
|
+
* dropped, "; " between, clipped.
|
|
2900
|
+
*/
|
|
2901
|
+
function joinRefusalClauses(refusals: string[] | undefined): string {
|
|
2902
|
+
const clauses = [
|
|
2903
|
+
...new Set(
|
|
2904
|
+
(refusals ?? [])
|
|
2905
|
+
.map((clause) => clause.trim().replace(/\.+$/, ''))
|
|
2906
|
+
.filter(Boolean),
|
|
2907
|
+
),
|
|
2908
|
+
];
|
|
2909
|
+
return clipText(clauses.join('; '), FILE_CONSTANTS.replyClausesMaxLength);
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
/*
|
|
2913
|
+
* The reply to a refused answer: a publish with its blockers, a plan that
|
|
2914
|
+
* could not be accepted, an offer the person can't take, or anything else
|
|
2915
|
+
* that could not be done.
|
|
2916
|
+
*/
|
|
2917
|
+
function getRefusedReply(input: ScheduleAskReplyTextInput): string {
|
|
2918
|
+
const clauses = joinRefusalClauses(input.refusals);
|
|
2919
|
+
if (input.kind === 'PUBLISH_REVIEW')
|
|
2920
|
+
return `${ensurePeriod(clauses ? `Not published: ${clauses}` : 'Not published')} Tell me what to change.`;
|
|
2921
|
+
if (input.kind === 'PLAN_REVIEW')
|
|
2922
|
+
return `${ensurePeriod(clauses ? `Not accepted: ${clauses}` : 'Not accepted')} Tell me what to change.`;
|
|
2923
|
+
if (input.kind === 'OFFER') {
|
|
2924
|
+
const subject = input.subjectLabel || 'that shift';
|
|
2925
|
+
return ensurePeriod(
|
|
2926
|
+
clauses
|
|
2927
|
+
? `You can't take ${subject}: ${clauses}`
|
|
2928
|
+
: `You can't take ${subject} now`,
|
|
2929
|
+
);
|
|
2930
|
+
}
|
|
2931
|
+
return ensurePeriod(
|
|
2932
|
+
clauses ? `I couldn't do that: ${clauses}` : "I couldn't do that",
|
|
2933
|
+
);
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
/*
|
|
2937
|
+
* The reply to a request or time-off decision: what was approved or
|
|
2938
|
+
* declined, and that the requester has been told.
|
|
2939
|
+
*/
|
|
2940
|
+
function getDecisionReply(input: ScheduleAskReplyTextInput): string {
|
|
2941
|
+
const person = input.personName || null;
|
|
2942
|
+
if (input.answer === 'NO')
|
|
2943
|
+
return `Declined. ${person ? `${person} has` : 'They have'} been told.`;
|
|
2944
|
+
const noun =
|
|
2945
|
+
input.kind === 'TIME_OFF_DECISION'
|
|
2946
|
+
? 'time off'
|
|
2947
|
+
: input.requestKind
|
|
2948
|
+
? FILE_CONSTANTS.requestNouns[input.requestKind]
|
|
2949
|
+
: 'request';
|
|
2950
|
+
const subject = input.subjectLabel ? ` (${input.subjectLabel})` : '';
|
|
2951
|
+
return `Approved: ${getPossessive(person, noun)}${subject}. They have been told.`;
|
|
2952
|
+
}
|
|
2953
|
+
|
|
2954
|
+
/*
|
|
2955
|
+
* The reply to an applied answer, by kind and answer.
|
|
2956
|
+
*/
|
|
2957
|
+
function getAppliedReply(input: ScheduleAskReplyTextInput): string {
|
|
2958
|
+
const yes = input.answer === 'YES';
|
|
2959
|
+
const from = input.organizationName ? ` from ${input.organizationName}` : '';
|
|
2960
|
+
switch (input.kind) {
|
|
2961
|
+
case 'OFFER': {
|
|
2962
|
+
const subject = input.subjectLabel || 'that shift';
|
|
2963
|
+
if (!yes) return 'OK, thanks for letting me know.';
|
|
2964
|
+
return input.filled
|
|
2965
|
+
? `You've got it: ${subject}. Thanks!`
|
|
2966
|
+
: `Thanks! Your request for ${subject} went to a manager. I'll let you know.`;
|
|
2967
|
+
}
|
|
2968
|
+
case 'SWAP_CONSENT':
|
|
2969
|
+
if (!yes)
|
|
2970
|
+
return `OK, I told ${input.personName || 'them'} you can't swap.`;
|
|
2971
|
+
return input.swapped
|
|
2972
|
+
? `Done: the swap${input.personName ? ` with ${input.personName}` : ''} is approved.`
|
|
2973
|
+
: 'Thanks. The swap goes to a manager now.';
|
|
2974
|
+
case 'REQUEST_DECISION':
|
|
2975
|
+
case 'TIME_OFF_DECISION':
|
|
2976
|
+
return getDecisionReply(input);
|
|
2977
|
+
case 'PUBLISH_REVIEW': {
|
|
2978
|
+
if (!yes) return 'OK, not published. Tell me what to change.';
|
|
2979
|
+
const count =
|
|
2980
|
+
input.publishedCount != null
|
|
2981
|
+
? ` (${pluralize(input.publishedCount, 'shift')})`
|
|
2982
|
+
: '';
|
|
2983
|
+
return `Published ${input.subjectLabel || 'the schedule'}${count}. Everyone gets their shifts.`;
|
|
2984
|
+
}
|
|
2985
|
+
case 'SHIFTS_CONFIRM':
|
|
2986
|
+
return yes
|
|
2987
|
+
? 'Thanks, confirmed.'
|
|
2988
|
+
: "Which shift doesn't work? Tell me and I'll pass it on.";
|
|
2989
|
+
case 'PLAN_REVIEW':
|
|
2990
|
+
return yes ? getPlanAcceptedReply(input) : getPlanNotAcceptedReply(input);
|
|
2991
|
+
case 'PROGRESS_CHECK':
|
|
2992
|
+
return yes
|
|
2993
|
+
? 'Thanks, your progress is noted.'
|
|
2994
|
+
: 'OK, thanks for letting me know.';
|
|
2995
|
+
default: {
|
|
2996
|
+
const texts = getConsentTopic(input.schedulingType).texts;
|
|
2997
|
+
return yes
|
|
2998
|
+
? `Thanks! You'll get ${texts}${from}. Reply STOP anytime to opt out.`
|
|
2999
|
+
: `OK, no ${texts}${from}.`;
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
|
|
3004
|
+
/*
|
|
3005
|
+
* The reply to a PLAN_REVIEW yes: "Accepted the plan for Harbor Tower (24
|
|
3006
|
+
* activities)."
|
|
3007
|
+
*/
|
|
3008
|
+
function getPlanAcceptedReply(input: ScheduleAskReplyTextInput): string {
|
|
3009
|
+
const name = input.projectName || input.subjectLabel;
|
|
3010
|
+
const count =
|
|
3011
|
+
input.acceptedCount != null
|
|
3012
|
+
? ` (${pluralize(input.acceptedCount, 'activity', 'activities')})`
|
|
3013
|
+
: '';
|
|
3014
|
+
return `Accepted the ${name ? `plan for ${name}` : 'proposed plan'}${count}.`;
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
/*
|
|
3018
|
+
* Name some activities with how many there are: "A1010 Framing, A1020
|
|
3019
|
+
* Footings +18 more" ('' with no names).
|
|
3020
|
+
*/
|
|
3021
|
+
function formatCountedNames(names: string[], count: number): string {
|
|
3022
|
+
const shown = names.map((name) =>
|
|
3023
|
+
clipText(name.trim(), FILE_CONSTANTS.activityNameMaxLength),
|
|
3024
|
+
);
|
|
3025
|
+
const hidden = Math.max(0, count - shown.length);
|
|
3026
|
+
return shown.length
|
|
3027
|
+
? `${shown.join(', ')}${hidden ? ` +${hidden} more` : ''}`
|
|
3028
|
+
: '';
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
/*
|
|
3032
|
+
* The reply to a PLAN_REVIEW no: nothing was removed, what rejecting the
|
|
3033
|
+
* proposal would remove (new activities, and existing ones it changed,
|
|
3034
|
+
* named separately), and to say what to change.
|
|
3035
|
+
*/
|
|
3036
|
+
function getPlanNotAcceptedReply(input: ScheduleAskReplyTextInput): string {
|
|
3037
|
+
const preview = input.rejectPreview;
|
|
3038
|
+
const clauses: string[] = [];
|
|
3039
|
+
if (preview?.newCount) {
|
|
3040
|
+
const names = formatCountedNames(preview.newNames, preview.newCount);
|
|
3041
|
+
clauses.push(
|
|
3042
|
+
`${pluralize(preview.newCount, 'new activity', 'new activities')}${names ? ` (${names})` : ''}`,
|
|
3043
|
+
);
|
|
3044
|
+
}
|
|
3045
|
+
if (preview?.changedCount) {
|
|
3046
|
+
const names = formatCountedNames(
|
|
3047
|
+
preview.changedNames,
|
|
3048
|
+
preview.changedCount,
|
|
3049
|
+
);
|
|
3050
|
+
const noun = clauses.length
|
|
3051
|
+
? `${preview.changedCount} existing ${preview.changedCount === 1 ? 'one' : 'ones'}`
|
|
3052
|
+
: pluralize(
|
|
3053
|
+
preview.changedCount,
|
|
3054
|
+
'existing activity',
|
|
3055
|
+
'existing activities',
|
|
3056
|
+
);
|
|
3057
|
+
clauses.push(`${noun} it changed${names ? ` (${names})` : ''}`);
|
|
3058
|
+
}
|
|
3059
|
+
const removal = clauses.length
|
|
3060
|
+
? ` Rejecting it would remove ${clauses.join(' and ')}.`
|
|
3061
|
+
: '';
|
|
3062
|
+
return `OK, not accepted; nothing was removed.${removal} Tell me what to change or remove.`;
|
|
3063
|
+
}
|
|
3064
|
+
|
|
3065
|
+
/*
|
|
3066
|
+
* The reply to a yes that met a changed subject: a plan review's or a
|
|
3067
|
+
* publish review's summary is out of date, and a new one is on its way.
|
|
3068
|
+
*/
|
|
3069
|
+
function getSupersededReply(input: ScheduleAskReplyTextInput): string {
|
|
3070
|
+
return input.kind === 'PLAN_REVIEW'
|
|
3071
|
+
? "The plan changed after that summary, so I didn't accept it. A new summary is on its way."
|
|
3072
|
+
: "The schedule changed after that summary, so I didn't publish. A new summary is on its way.";
|
|
3073
|
+
}
|
|
3074
|
+
|
|
3075
|
+
/*
|
|
3076
|
+
* Render the reply to an answered ask (one SMS segment where possible): what
|
|
3077
|
+
* the answer did (APPLIED), that it came too late (by what closed it), that
|
|
3078
|
+
* the schedule or plan changed after the summary (SUPERSEDED), or why it
|
|
3079
|
+
* could not be done (REFUSED, with the clauses given).
|
|
3080
|
+
*/
|
|
3081
|
+
export function formatAskReply(input: ScheduleAskReplyTextInput): string {
|
|
3082
|
+
const text =
|
|
3083
|
+
input.outcome === 'TOO_LATE'
|
|
3084
|
+
? getTooLateReply(input)
|
|
3085
|
+
: input.outcome === 'SUPERSEDED'
|
|
3086
|
+
? getSupersededReply(input)
|
|
3087
|
+
: input.outcome === 'REFUSED'
|
|
3088
|
+
? getRefusedReply(input)
|
|
3089
|
+
: getAppliedReply(input);
|
|
3090
|
+
return joinScheduleText([text]);
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
/*
|
|
3094
|
+
* Hide the last "- item" line of a text: it joins the "+N more" line right
|
|
3095
|
+
* after it, or becomes "+1 more". False when no item line is left.
|
|
3096
|
+
*/
|
|
3097
|
+
function hideLastListItem(lines: string[]): boolean {
|
|
3098
|
+
let index = lines.length - 1;
|
|
3099
|
+
while (index >= 0 && !lines[index].startsWith('- ')) index -= 1;
|
|
3100
|
+
if (index < 0) return false;
|
|
3101
|
+
const more = /^\+(\d+) more$/.exec(lines[index + 1] ?? '');
|
|
3102
|
+
if (more) lines.splice(index, 2, `+${Number(more[1]) + 1} more`);
|
|
3103
|
+
else lines.splice(index, 1, '+1 more');
|
|
3104
|
+
return true;
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
/*
|
|
3108
|
+
* Render the one reminder of an unanswered ask: "Reminder: " + the text as
|
|
3109
|
+
* sent, kept within SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS by hiding list items
|
|
3110
|
+
* from the bottom up (their counts stay right).
|
|
3111
|
+
*/
|
|
3112
|
+
export function formatAskNudge(text: string): string {
|
|
3113
|
+
const lines = `Reminder: ${text}`.split('\n');
|
|
3114
|
+
let fits =
|
|
3115
|
+
getScheduleSmsSegmentCount(lines.join('\n')) <=
|
|
3116
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS;
|
|
3117
|
+
while (!fits && hideLastListItem(lines))
|
|
3118
|
+
fits =
|
|
3119
|
+
getScheduleSmsSegmentCount(lines.join('\n')) <=
|
|
3120
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS;
|
|
3121
|
+
return joinScheduleText(lines);
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
/*
|
|
3125
|
+
* Render the note sent to a candidate already asked when an offer closes:
|
|
3126
|
+
* covered, canceled, changed or no longer needed.
|
|
3127
|
+
*/
|
|
3128
|
+
export function formatAskClosedNote(args: {
|
|
3129
|
+
subjectLabel: string;
|
|
3130
|
+
cause: 'FILLED' | 'CANCELED' | 'CHANGED' | 'STOPPED';
|
|
3131
|
+
}): string {
|
|
3132
|
+
const subject = args.subjectLabel || 'That shift';
|
|
3133
|
+
const notes = {
|
|
3134
|
+
FILLED: `${subject} is covered now. Thanks!`,
|
|
3135
|
+
CANCELED: `${subject} was canceled. No need to reply.`,
|
|
3136
|
+
CHANGED: `${subject} changed, so that offer is closed.`,
|
|
3137
|
+
STOPPED: `${subject} no longer needs covering. Thanks!`,
|
|
3138
|
+
};
|
|
3139
|
+
return joinScheduleText([notes[args.cause]]);
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
/*
|
|
3143
|
+
* Whether an offer candidate was texted (or shown the ask in the app).
|
|
3144
|
+
*/
|
|
3145
|
+
function isOfferAskSent(ask: ScheduleOfferTextInput['asks'][number]): boolean {
|
|
3146
|
+
return (
|
|
3147
|
+
ask.sentAt != null || ask.status === 'SENT' || ask.status === 'ANSWERED'
|
|
3148
|
+
);
|
|
3149
|
+
}
|
|
3150
|
+
|
|
3151
|
+
/*
|
|
3152
|
+
* When a wave goes out, for an offer text: "now" once due, "at 9:30pm" on
|
|
3153
|
+
* the same local day as `now`, else "at Sat Dec 5, 8am".
|
|
3154
|
+
*/
|
|
3155
|
+
function getWaveTimeLabel(
|
|
3156
|
+
sendAt: Date | string,
|
|
3157
|
+
now: Date | string | null | undefined,
|
|
3158
|
+
timeZone: string,
|
|
3159
|
+
): string {
|
|
3160
|
+
if (now != null && toScheduleTimeMs(sendAt) <= toScheduleTimeMs(now))
|
|
3161
|
+
return 'now';
|
|
3162
|
+
if (
|
|
3163
|
+
now != null &&
|
|
3164
|
+
getScheduleLocalDate(sendAt, timeZone) ===
|
|
3165
|
+
getScheduleLocalDate(now, timeZone)
|
|
3166
|
+
)
|
|
3167
|
+
return `at ${formatClock(getLocalPoint(sendAt, timeZone).minutes)}`;
|
|
3168
|
+
return `at ${formatScheduleInstant(sendAt, timeZone)}`;
|
|
3169
|
+
}
|
|
3170
|
+
|
|
3171
|
+
/*
|
|
3172
|
+
* Group offer asks by wave (ascending), each with its earliest send time and
|
|
3173
|
+
* names in rank order, as "Ben, Cam now; Dee at 9:30pm" (waves past the cap
|
|
3174
|
+
* as "+N more waves").
|
|
3175
|
+
*/
|
|
3176
|
+
function formatOfferWaves(
|
|
3177
|
+
asks: ScheduleOfferTextInput['asks'],
|
|
3178
|
+
input: ScheduleOfferTextInput,
|
|
3179
|
+
): string {
|
|
3180
|
+
const waves = new Map<number, { sendAt: Date | string; names: string[] }>();
|
|
3181
|
+
for (const ask of asks) {
|
|
3182
|
+
const wave = waves.get(ask.wave);
|
|
3183
|
+
if (!wave) waves.set(ask.wave, { sendAt: ask.sendAt, names: [ask.name] });
|
|
3184
|
+
else {
|
|
3185
|
+
wave.names.push(ask.name);
|
|
3186
|
+
if (toScheduleTimeMs(ask.sendAt) < toScheduleTimeMs(wave.sendAt))
|
|
3187
|
+
wave.sendAt = ask.sendAt;
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
const ordered = [...waves.entries()].sort((a, b) => a[0] - b[0]);
|
|
3191
|
+
const shown = ordered
|
|
3192
|
+
.slice(0, FILE_CONSTANTS.offerWaveCap)
|
|
3193
|
+
.map(
|
|
3194
|
+
([, wave]) =>
|
|
3195
|
+
`${formatNameList(wave.names)} ${getWaveTimeLabel(wave.sendAt, input.now, input.context.timeZone)}`,
|
|
3196
|
+
);
|
|
3197
|
+
const hidden = ordered.length - shown.length;
|
|
3198
|
+
return `${shown.join('; ')}${hidden ? `; +${pluralize(hidden, 'more wave')}` : ''}`;
|
|
3199
|
+
}
|
|
3200
|
+
|
|
3201
|
+
/*
|
|
3202
|
+
* The "Not texted: Hal (no shift-text consent)" line of the skipped
|
|
3203
|
+
* candidates, or null when every candidate could be texted.
|
|
3204
|
+
*/
|
|
3205
|
+
function getOfferSkippedLine(
|
|
3206
|
+
asks: ScheduleOfferTextInput['asks'],
|
|
3207
|
+
): string | null {
|
|
3208
|
+
const skipped = asks.filter((ask) => ask.status === 'SKIPPED');
|
|
3209
|
+
if (!skipped.length) return null;
|
|
3210
|
+
return `Not texted: ${formatNameList(
|
|
3211
|
+
skipped.map((ask) => {
|
|
3212
|
+
const why = ask.reason ? FILE_CONSTANTS.askSkipReasons[ask.reason] : null;
|
|
3213
|
+
return why ? `${ask.name} (${why})` : ask.name;
|
|
3214
|
+
}),
|
|
3215
|
+
)}.`;
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
/*
|
|
3219
|
+
* The lines of a new offer: who is texted in which wave and when, and who
|
|
3220
|
+
* could not be texted.
|
|
3221
|
+
*/
|
|
3222
|
+
function getOfferCreatedLines(
|
|
3223
|
+
input: ScheduleOfferTextInput,
|
|
3224
|
+
asks: ScheduleOfferTextInput['asks'],
|
|
3225
|
+
prefix: string,
|
|
3226
|
+
shift: string,
|
|
3227
|
+
): Array<string | null> {
|
|
3228
|
+
const texted = asks.filter((ask) => ask.status !== 'SKIPPED');
|
|
3229
|
+
if (!texted.length)
|
|
3230
|
+
return [
|
|
3231
|
+
`${prefix}Nobody can be texted about ${shift}.`,
|
|
3232
|
+
getOfferSkippedLine(asks),
|
|
3233
|
+
];
|
|
3234
|
+
const waveCount = new Set(texted.map((ask) => ask.wave)).size;
|
|
3235
|
+
return [
|
|
3236
|
+
`${prefix}Offering ${shift} to ${pluralize(texted.length, 'person', 'people')} in ${pluralize(waveCount, 'wave')}: ${formatOfferWaves(texted, input)}.`,
|
|
3237
|
+
getOfferSkippedLine(asks),
|
|
3238
|
+
];
|
|
3239
|
+
}
|
|
3240
|
+
|
|
3241
|
+
/*
|
|
3242
|
+
* The line of an offer nobody took: how many were asked, said no and did
|
|
3243
|
+
* not answer, and that the seat is still open.
|
|
3244
|
+
*/
|
|
3245
|
+
function getOfferUnfilledLine(
|
|
3246
|
+
asks: ScheduleOfferTextInput['asks'],
|
|
3247
|
+
prefix: string,
|
|
3248
|
+
shift: string,
|
|
3249
|
+
): string {
|
|
3250
|
+
const asked = asks.filter(isOfferAskSent);
|
|
3251
|
+
const saidNo = asked.filter((ask) => ask.answer === 'NO').length;
|
|
3252
|
+
const noAnswer = asked.filter((ask) => ask.answer === null).length;
|
|
3253
|
+
const counts = asked.length
|
|
3254
|
+
? [
|
|
3255
|
+
`${asked.length} asked`,
|
|
3256
|
+
saidNo ? `${saidNo} said no` : null,
|
|
3257
|
+
noAnswer ? `${noAnswer} didn't answer` : null,
|
|
3258
|
+
]
|
|
3259
|
+
.filter(Boolean)
|
|
3260
|
+
.join(', ')
|
|
3261
|
+
: 'nobody could be texted';
|
|
3262
|
+
return `${prefix}Nobody took ${shift}: ${counts}. It is still open.`;
|
|
3263
|
+
}
|
|
3264
|
+
|
|
3265
|
+
/*
|
|
3266
|
+
* The lines of an offer's status: where it stands, then who said yes, who
|
|
3267
|
+
* said no, who has not answered yet, who is next (by wave), who never
|
|
3268
|
+
* answered and who could not be texted.
|
|
3269
|
+
*/
|
|
3270
|
+
function getOfferStatusLines(
|
|
3271
|
+
input: ScheduleOfferTextInput,
|
|
3272
|
+
asks: ScheduleOfferTextInput['asks'],
|
|
3273
|
+
prefix: string,
|
|
3274
|
+
shift: string,
|
|
3275
|
+
): Array<string | null> {
|
|
3276
|
+
const status =
|
|
3277
|
+
input.status === 'FILLED' && input.filledByName
|
|
3278
|
+
? `filled by ${input.filledByName}`
|
|
3279
|
+
: FILE_CONSTANTS.offerStatuses[input.status];
|
|
3280
|
+
const names = (filter: (ask: (typeof asks)[number]) => boolean) =>
|
|
3281
|
+
asks.filter(filter).map((ask) => ask.name);
|
|
3282
|
+
const groups: Array<[string, string[]]> = [
|
|
3283
|
+
['Said yes', names((ask) => ask.answer === 'YES')],
|
|
3284
|
+
['Said no', names((ask) => ask.answer === 'NO')],
|
|
3285
|
+
['Waiting for an answer', names((ask) => ask.status === 'SENT')],
|
|
3286
|
+
[
|
|
3287
|
+
"Didn't answer",
|
|
3288
|
+
names(
|
|
3289
|
+
(ask) =>
|
|
3290
|
+
isOfferAskSent(ask) && ask.answer === null && ask.status !== 'SENT',
|
|
3291
|
+
),
|
|
3292
|
+
],
|
|
3293
|
+
];
|
|
3294
|
+
const pending = asks.filter((ask) => ask.status === 'PENDING');
|
|
3295
|
+
return [
|
|
3296
|
+
`${prefix}Offer for ${shift}: ${status}.`,
|
|
3297
|
+
...groups.map(([title, list]) =>
|
|
3298
|
+
list.length ? `${title}: ${formatNameList(list)}.` : null,
|
|
3299
|
+
),
|
|
3300
|
+
pending.length ? `Next: ${formatOfferWaves(pending, input)}.` : null,
|
|
3301
|
+
getOfferSkippedLine(asks),
|
|
3302
|
+
];
|
|
3303
|
+
}
|
|
3304
|
+
|
|
3305
|
+
/*
|
|
3306
|
+
* Render an offer for the manager (tool text and the OFFER_FILLED /
|
|
3307
|
+
* OFFER_UNFILLED notice bodies): CREATED (who is texted in which wave and
|
|
3308
|
+
* when, who could not be texted), FILLED (who took it), UNFILLED (nobody
|
|
3309
|
+
* did, with counts) or STATUS (where it stands and each candidate's answer).
|
|
3310
|
+
*/
|
|
3311
|
+
export function formatOffer(input: ScheduleOfferTextInput): string {
|
|
3312
|
+
const { context } = input;
|
|
3313
|
+
const prefix = context.calendarName ? `${context.calendarName}: ` : '';
|
|
3314
|
+
const shift = formatScheduleShiftLine(input.shift, context);
|
|
3315
|
+
const asks = [...input.asks].sort(
|
|
3316
|
+
(a, b) => a.rank - b.rank || compareText(a.name, b.name),
|
|
3317
|
+
);
|
|
3318
|
+
const lines =
|
|
3319
|
+
input.event === 'CREATED'
|
|
3320
|
+
? getOfferCreatedLines(input, asks, prefix, shift)
|
|
3321
|
+
: input.event === 'FILLED'
|
|
3322
|
+
? [`${prefix}${input.filledByName || 'Someone'} took ${shift}.`]
|
|
3323
|
+
: input.event === 'UNFILLED'
|
|
3324
|
+
? [getOfferUnfilledLine(asks, prefix, shift)]
|
|
3325
|
+
: getOfferStatusLines(input, asks, prefix, shift);
|
|
3326
|
+
return joinScheduleText([...lines, context.link]);
|
|
3327
|
+
}
|
|
3328
|
+
|
|
3329
|
+
/*
|
|
3330
|
+
* One recipient of someone else's open ask: "Ben (asked)", "Cam (said no:
|
|
3331
|
+
* "can't, sorry")".
|
|
3332
|
+
*/
|
|
3333
|
+
function formatAskRecipient(
|
|
3334
|
+
recipient: ScheduleAskOverviewTextInput['others'][number]['recipients'][number],
|
|
3335
|
+
): string {
|
|
3336
|
+
if (recipient.answer) {
|
|
3337
|
+
const reply =
|
|
3338
|
+
recipient.answer === 'NO' && recipient.replyText?.trim()
|
|
3339
|
+
? `: "${clipText(recipient.replyText.trim().replace(/\s+/g, ' '), FILE_CONSTANTS.overviewReplyMaxLength)}"`
|
|
3340
|
+
: '';
|
|
3341
|
+
return `${recipient.name} (said ${recipient.answer === 'YES' ? 'yes' : 'no'}${reply})`;
|
|
3342
|
+
}
|
|
3343
|
+
const states: Partial<Record<string, string>> = {
|
|
3344
|
+
PENDING: 'not sent yet',
|
|
3345
|
+
SENT: 'asked',
|
|
3346
|
+
EXPIRED: 'no answer',
|
|
3347
|
+
SKIPPED: 'not texted',
|
|
3348
|
+
};
|
|
3349
|
+
return `${recipient.name} (${states[recipient.status] ?? 'closed'})`;
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
/*
|
|
3353
|
+
* Render the open schedule questions for list_schedule_requests (tool text):
|
|
3354
|
+
* the viewer's own open asks (id, line, open until), the questions waiting
|
|
3355
|
+
* on others with each recipient's state, and the open offers; each list
|
|
3356
|
+
* capped.
|
|
3357
|
+
*/
|
|
3358
|
+
export function formatAskOverview(input: ScheduleAskOverviewTextInput): string {
|
|
3359
|
+
const { context } = input;
|
|
3360
|
+
if (!input.mine.length && !input.others.length && !input.offers.length)
|
|
3361
|
+
return joinScheduleText(['No open schedule questions.', context.link]);
|
|
3362
|
+
const mine = input.mine.map(
|
|
3363
|
+
(ask) =>
|
|
3364
|
+
`- ${ask.readableId}: ${ask.line} (open until ${formatScheduleInstant(ask.expiresAt, context.timeZone)})`,
|
|
3365
|
+
);
|
|
3366
|
+
const others = input.others.map(
|
|
3367
|
+
(group) =>
|
|
3368
|
+
`- ${group.line || 'a question'}: ${group.recipients.length ? formatNameList(group.recipients.map(formatAskRecipient)) : 'nobody yet'}`,
|
|
3369
|
+
);
|
|
3370
|
+
const offers = input.offers.map(
|
|
3371
|
+
(offer) => `${offer.readableId}: ${offer.text}`,
|
|
3372
|
+
);
|
|
3373
|
+
return joinScheduleText([
|
|
3374
|
+
mine.length ? 'Your open questions:' : null,
|
|
3375
|
+
...capLines(mine, FILE_CONSTANTS.toolListCap),
|
|
3376
|
+
others.length ? 'Waiting on others:' : null,
|
|
3377
|
+
...capLines(others, FILE_CONSTANTS.toolListCap),
|
|
3378
|
+
offers.length ? 'Open offers:' : null,
|
|
3379
|
+
...capLines(offers, FILE_CONSTANTS.toolListCap),
|
|
3380
|
+
context.link,
|
|
3381
|
+
]);
|
|
3382
|
+
}
|
|
3383
|
+
|
|
3384
|
+
/*
|
|
3385
|
+
* Render a text whose parts may shorten: while it is over the SMS budget,
|
|
3386
|
+
* shorten the parts in order, each in steps down to its floor (a part
|
|
3387
|
+
* shorter than one step is dropped). Returns the best effort once every
|
|
3388
|
+
* part is at its floor.
|
|
3389
|
+
*/
|
|
3390
|
+
function fitClippedText(
|
|
3391
|
+
parts: Array<{ text: string | null; floor: number }>,
|
|
3392
|
+
render: (texts: Array<string | null>) => string,
|
|
3393
|
+
): string {
|
|
3394
|
+
const texts = parts.map((part) => part.text);
|
|
3395
|
+
let text = render(texts);
|
|
3396
|
+
for (const [index, part] of parts.entries()) {
|
|
3397
|
+
let length = part.text?.length ?? 0;
|
|
3398
|
+
while (
|
|
3399
|
+
getScheduleSmsSegmentCount(text) > SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS &&
|
|
3400
|
+
length > part.floor
|
|
3401
|
+
) {
|
|
3402
|
+
length = Math.max(part.floor, length - FILE_CONSTANTS.clipStep);
|
|
3403
|
+
texts[index] =
|
|
3404
|
+
length >= FILE_CONSTANTS.clipStep
|
|
3405
|
+
? clipText(part.text ?? '', length)
|
|
3406
|
+
: null;
|
|
3407
|
+
text = render(texts);
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
return text;
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
/*
|
|
3414
|
+
* Whether a to-do is still to be done (OPEN or IN_PROGRESS).
|
|
3415
|
+
*/
|
|
3416
|
+
function isTodoOpen(status: ScheduleTaskStatusEnum): boolean {
|
|
3417
|
+
return FILE_CONSTANTS.todoGroups[status] === 0;
|
|
3418
|
+
}
|
|
3419
|
+
|
|
3420
|
+
/*
|
|
3421
|
+
* Whether an open to-do is past due: an all-day one when its local date is
|
|
3422
|
+
* before today's in its zone, a timed one once its instant has passed.
|
|
3423
|
+
*/
|
|
3424
|
+
function isTodoOverdue(
|
|
3425
|
+
todo: ScheduleTodoTextItem,
|
|
3426
|
+
timeZone: string,
|
|
3427
|
+
now: Date | string,
|
|
3428
|
+
): boolean {
|
|
3429
|
+
if (!todo.dueAt || !isTodoOpen(todo.status)) return false;
|
|
3430
|
+
if (todo.dueAllDay)
|
|
3431
|
+
return (
|
|
3432
|
+
getScheduleLocalDate(todo.dueAt, timeZone) <
|
|
3433
|
+
getScheduleLocalDate(now, timeZone)
|
|
3434
|
+
);
|
|
3435
|
+
return toScheduleTimeMs(todo.dueAt) < toScheduleTimeMs(now);
|
|
3436
|
+
}
|
|
3437
|
+
|
|
3438
|
+
/*
|
|
3439
|
+
* When a to-do is due, in its zone: "Fri Dec 4" (all day) or "Fri Dec 4,
|
|
3440
|
+
* 5pm".
|
|
3441
|
+
*/
|
|
3442
|
+
function formatTodoDue(
|
|
3443
|
+
dueAt: Date | string,
|
|
3444
|
+
allDay: boolean,
|
|
3445
|
+
timeZone: string,
|
|
3446
|
+
): string {
|
|
3447
|
+
return allDay
|
|
3448
|
+
? formatScheduleDay(getScheduleLocalDate(dueAt, timeZone))
|
|
3449
|
+
: formatScheduleInstant(dueAt, timeZone);
|
|
3450
|
+
}
|
|
3451
|
+
|
|
3452
|
+
/*
|
|
3453
|
+
* Whether a to-do's stored priority number is HIGH.
|
|
3454
|
+
*/
|
|
3455
|
+
function isTodoHighPriority(priority: number): boolean {
|
|
3456
|
+
return SCHEDULE_TASK_PRIORITY_ENUMS[priority] === 'HIGH';
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
/*
|
|
3460
|
+
* What a to-do is attached to, as its reader may see it: its seat's line or
|
|
3461
|
+
* its activity; "a shift" for a seat the reader may not see (a draft, or
|
|
3462
|
+
* someone else's under own-shifts-only visibility); null when unattached.
|
|
3463
|
+
*/
|
|
3464
|
+
function getTodoAttachedLabel(todo: ScheduleTodoTextItem): string | null {
|
|
3465
|
+
return todo.seatHidden ? 'a shift' : todo.attachedLabel;
|
|
3466
|
+
}
|
|
3467
|
+
|
|
3468
|
+
/*
|
|
3469
|
+
* Render one to-do of a list: "!Restock ice - due Fri Dec 4 (overdue) - Ana -
|
|
3470
|
+
* Fri Dec 4, 8pm-2am Bartender", in the to-do's zone. "!" marks HIGH; the
|
|
3471
|
+
* title carries its location or project when given (a list spanning
|
|
3472
|
+
* several); the status follows an IN_PROGRESS, DONE or CANCELED one.
|
|
3473
|
+
*/
|
|
3474
|
+
function formatTodoLine(
|
|
3475
|
+
todo: ScheduleTodoTextItem,
|
|
3476
|
+
context: ScheduleTextContext,
|
|
3477
|
+
now: Date | string,
|
|
3478
|
+
): string {
|
|
3479
|
+
const zone = todo.timeZone || context.timeZone;
|
|
3480
|
+
const mark = isTodoHighPriority(todo.priority) ? '!' : '';
|
|
3481
|
+
const scope = todo.scopeName ? ` (${todo.scopeName})` : '';
|
|
3482
|
+
const due = todo.dueAt
|
|
3483
|
+
? `due ${formatTodoDue(todo.dueAt, todo.dueAllDay, zone)}${isTodoOverdue(todo, zone, now) ? ' (overdue)' : ''}`
|
|
3484
|
+
: null;
|
|
3485
|
+
const parts = [
|
|
3486
|
+
`${mark}${todo.title.trim()}${scope}`,
|
|
3487
|
+
due,
|
|
3488
|
+
todo.assigneeName,
|
|
3489
|
+
getTodoAttachedLabel(todo),
|
|
3490
|
+
];
|
|
3491
|
+
return `${parts.filter(Boolean).join(' - ')}${FILE_CONSTANTS.todoStatusSuffixes[todo.status] ?? ''}`;
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/*
|
|
3495
|
+
* The heading of a to-do list with its counts: "To-dos at Main St (3
|
|
3496
|
+
* open):", "Your to-dos (2 open, 1 done):". When the listed to-dos are all
|
|
3497
|
+
* of one group, the unlisted ones (totalCount) count toward it too: one read
|
|
3498
|
+
* filters by status.
|
|
3499
|
+
*/
|
|
3500
|
+
function getTodoListHeading(input: ScheduleTodoListTextInput): string {
|
|
3501
|
+
const counts = [0, 0, 0];
|
|
3502
|
+
for (const todo of input.todos)
|
|
3503
|
+
counts[FILE_CONSTANTS.todoGroups[todo.status] ?? 0] += 1;
|
|
3504
|
+
if (counts.filter(Boolean).length === 1)
|
|
3505
|
+
counts[counts.findIndex(Boolean)] += Math.max(
|
|
3506
|
+
0,
|
|
3507
|
+
input.totalCount - input.todos.length,
|
|
3508
|
+
);
|
|
3509
|
+
const words = ['open', 'done', 'canceled'];
|
|
3510
|
+
const parts = counts.flatMap((count, index) =>
|
|
3511
|
+
count ? [`${count} ${words[index]}`] : [],
|
|
3512
|
+
);
|
|
3513
|
+
return `${input.title?.trim() || 'To-dos'} (${parts.join(', ')}):`;
|
|
3514
|
+
}
|
|
3515
|
+
|
|
3516
|
+
/*
|
|
3517
|
+
* Render a to-do list (tool text): the heading with its counts, one line per
|
|
3518
|
+
* to-do (open first, then done, then canceled; the given order within each),
|
|
3519
|
+
* capped at the tool cap with "+N more" (totalCount), then the link; "No open
|
|
3520
|
+
* to-dos." when there are none.
|
|
3521
|
+
*/
|
|
3522
|
+
function formatTodoListLines(input: ScheduleTodoListTextInput): string {
|
|
3523
|
+
const { context } = input;
|
|
3524
|
+
const title = input.title?.trim();
|
|
3525
|
+
if (!input.todos.length)
|
|
3526
|
+
return joinScheduleText([
|
|
3527
|
+
`${title ? `${title}: no` : 'No'} ${getTodoListEmptyNoun(input.statuses)}.`,
|
|
3528
|
+
context.link,
|
|
3529
|
+
]);
|
|
3530
|
+
const todos = [...input.todos].sort(
|
|
3531
|
+
(a, b) =>
|
|
3532
|
+
FILE_CONSTANTS.todoGroups[a.status] - FILE_CONSTANTS.todoGroups[b.status],
|
|
3533
|
+
);
|
|
3534
|
+
const shown = todos.slice(0, FILE_CONSTANTS.toolListCap);
|
|
3535
|
+
const hidden = Math.max(input.totalCount, todos.length) - shown.length;
|
|
3536
|
+
return joinScheduleText([
|
|
3537
|
+
getTodoListHeading(input),
|
|
3538
|
+
...shown.map((todo) => `- ${formatTodoLine(todo, context, input.now)}`),
|
|
3539
|
+
hidden > 0 ? `+${hidden} more` : null,
|
|
3540
|
+
context.link,
|
|
3541
|
+
]);
|
|
3542
|
+
}
|
|
3543
|
+
|
|
3544
|
+
/*
|
|
3545
|
+
* Name what an empty to-do list has none of, by the statuses it read: "open
|
|
3546
|
+
* to-dos" (the default), "done to-dos" or "to-dos".
|
|
3547
|
+
*/
|
|
3548
|
+
function getTodoListEmptyNoun(
|
|
3549
|
+
statuses: ScheduleTodoListTextInput['statuses'],
|
|
3550
|
+
): string {
|
|
3551
|
+
if (!statuses?.length || statuses.every(isTodoOpen)) return 'open to-dos';
|
|
3552
|
+
return statuses.every((status) => status === 'DONE')
|
|
3553
|
+
? 'done to-dos'
|
|
3554
|
+
: 'to-dos';
|
|
3555
|
+
}
|
|
3556
|
+
|
|
3557
|
+
/*
|
|
3558
|
+
* Render the TASK_ASSIGNED notice for one to-do (SMS-bound): "New to-do from
|
|
3559
|
+
* Jo at Main St: Restock ice (high priority), due Fri Dec 4.", what it is
|
|
3560
|
+
* for, its note (clipped to the SMS quote length), then the link. Over budget
|
|
3561
|
+
* the note shortens and goes first, then what it is for, then the title is
|
|
3562
|
+
* clipped; the first line and the link stay.
|
|
3563
|
+
*/
|
|
3564
|
+
function formatAssignedTodo(input: ScheduleTodoListTextInput): string {
|
|
3565
|
+
const { context } = input;
|
|
3566
|
+
const todo = input.todos[0];
|
|
3567
|
+
if (!todo) return joinScheduleText(['You have a new to-do.', context.link]);
|
|
3568
|
+
const zone = todo.timeZone || context.timeZone;
|
|
3569
|
+
const from = `New to-do${input.assignedByName ? ` from ${input.assignedByName}` : ''}${todo.scopeName ? ` at ${todo.scopeName}` : ''}`;
|
|
3570
|
+
const priority = isTodoHighPriority(todo.priority) ? ' (high priority)' : '';
|
|
3571
|
+
const due = todo.dueAt
|
|
3572
|
+
? `, due ${formatTodoDue(todo.dueAt, todo.dueAllDay, zone)}`
|
|
3573
|
+
: '';
|
|
3574
|
+
const note = todo.note?.trim()
|
|
3575
|
+
? clipText(todo.note.trim(), FILE_CONSTANTS.smsQuoteMaxLength)
|
|
3576
|
+
: null;
|
|
3577
|
+
const attached = getTodoAttachedLabel(todo);
|
|
3578
|
+
return fitClippedText(
|
|
3579
|
+
[
|
|
3580
|
+
{ text: note, floor: 0 },
|
|
3581
|
+
{
|
|
3582
|
+
text: attached ? `For ${attached}.` : null,
|
|
3583
|
+
floor: 0,
|
|
3584
|
+
},
|
|
3585
|
+
{ text: todo.title.trim(), floor: FILE_CONSTANTS.todoTitleMinLength },
|
|
3586
|
+
],
|
|
3587
|
+
([noteText, forText, title]) =>
|
|
3588
|
+
joinScheduleText([
|
|
3589
|
+
ensurePeriod(`${from}: ${title ?? ''}${priority}${due}`),
|
|
3590
|
+
forText,
|
|
3591
|
+
noteText,
|
|
3592
|
+
context.link,
|
|
3593
|
+
]),
|
|
3594
|
+
);
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
/*
|
|
3598
|
+
* Render to-dos (IMPLEMENTATION §1.15): LIST, a tool text with its
|
|
3599
|
+
* heading, counts and one line per to-do (each in its own zone, overdue
|
|
3600
|
+
* marked against `now`); ASSIGNED, the TASK_ASSIGNED notice of todos[0]
|
|
3601
|
+
* (SMS-bound).
|
|
3602
|
+
*/
|
|
3603
|
+
export function formatTodoList(input: ScheduleTodoListTextInput): string {
|
|
3604
|
+
return input.mode === 'ASSIGNED'
|
|
3605
|
+
? formatAssignedTodo(input)
|
|
3606
|
+
: formatTodoListLines(input);
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
/*
|
|
3610
|
+
* Name an activity by its code and name: "A1010 Framing".
|
|
3611
|
+
*/
|
|
3612
|
+
function formatActivityName(activity: { code: string; name: string }): string {
|
|
3613
|
+
return [activity.code.trim(), activity.name.trim()].filter(Boolean).join(' ');
|
|
3614
|
+
}
|
|
3615
|
+
|
|
3616
|
+
/*
|
|
3617
|
+
* Start a project text with the project's name ("Harbor Tower: finish
|
|
3618
|
+
* moved ..."), or capitalize the clause when there is no name.
|
|
3619
|
+
*/
|
|
3620
|
+
function withProjectName(name: string | null, clause: string): string {
|
|
3621
|
+
return name
|
|
3622
|
+
? `${name}: ${clause}`
|
|
3623
|
+
: `${clause.charAt(0).toUpperCase()}${clause.slice(1)}`;
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3626
|
+
/*
|
|
3627
|
+
* Order milestones by finish (none last), then code.
|
|
3628
|
+
*/
|
|
3629
|
+
function sortPlanMilestones(
|
|
3630
|
+
milestones: SchedulePlanSummaryTextInput['milestones'],
|
|
3631
|
+
): SchedulePlanSummaryTextInput['milestones'] {
|
|
3632
|
+
const finishMs = (at: Date | string | null) =>
|
|
3633
|
+
at == null ? Number.MAX_SAFE_INTEGER : toScheduleTimeMs(at);
|
|
3634
|
+
return [...milestones].sort(
|
|
3635
|
+
(a, b) =>
|
|
3636
|
+
finishMs(a.finishAt) - finishMs(b.finishAt) ||
|
|
3637
|
+
compareText(a.code, b.code),
|
|
3638
|
+
);
|
|
3639
|
+
}
|
|
3640
|
+
|
|
3641
|
+
/*
|
|
3642
|
+
* The first line of a plan summary: "Harbor Tower: proposed plan, 24
|
|
3643
|
+
* activities (20 new, 4 changed), 3 milestones."
|
|
3644
|
+
*/
|
|
3645
|
+
function getPlanHeadline(input: SchedulePlanSummaryTextInput): string {
|
|
3646
|
+
const changed = input.changedCount
|
|
3647
|
+
? ` (${input.newCount} new, ${input.changedCount} changed)`
|
|
3648
|
+
: '';
|
|
3649
|
+
const counts = [
|
|
3650
|
+
`${pluralize(input.activityCount, 'activity', 'activities')}${changed}`,
|
|
3651
|
+
input.milestones.length
|
|
3652
|
+
? pluralize(input.milestones.length, 'milestone')
|
|
3653
|
+
: null,
|
|
3654
|
+
].filter(Boolean);
|
|
3655
|
+
return withProjectName(
|
|
3656
|
+
input.context.calendarName,
|
|
3657
|
+
`proposed plan, ${counts.join(', ')}.`,
|
|
3658
|
+
);
|
|
3659
|
+
}
|
|
3660
|
+
|
|
3661
|
+
/*
|
|
3662
|
+
* The line of a plan text whose dates are not calculated: "Dates are being
|
|
3663
|
+
* calculated." while a run is queued or running, else "Dates are not
|
|
3664
|
+
* calculated yet." (automatic scheduling off, or the last run failed).
|
|
3665
|
+
*/
|
|
3666
|
+
function getUncalculatedLine(pending: boolean): string {
|
|
3667
|
+
return pending
|
|
3668
|
+
? 'Dates are being calculated.'
|
|
3669
|
+
: 'Dates are not calculated yet.';
|
|
3670
|
+
}
|
|
3671
|
+
|
|
3672
|
+
/*
|
|
3673
|
+
* The finish line of a plan summary: "Finish Mar 10 (must finish by Mar
|
|
3674
|
+
* 31).", "Finish Mar 10: 4 days past the deadline (Mar 6).", or the
|
|
3675
|
+
* uncalculated line; null when calculated with no finish.
|
|
3676
|
+
*/
|
|
3677
|
+
function getPlanFinishLine(input: SchedulePlanSummaryTextInput): string | null {
|
|
3678
|
+
if (!input.calculated) return getUncalculatedLine(input.pending);
|
|
3679
|
+
if (!input.finishAt) return null;
|
|
3680
|
+
const zone = input.context.timeZone;
|
|
3681
|
+
const finish = getFinishLocalDate(input.finishAt, zone);
|
|
3682
|
+
if (!input.mustFinishByAt) return `Finish ${formatMonthDay(finish)}.`;
|
|
3683
|
+
const deadline = getFinishLocalDate(input.mustFinishByAt, zone);
|
|
3684
|
+
const late = getScheduleDaysBetween(deadline, finish);
|
|
3685
|
+
return late > 0
|
|
3686
|
+
? `Finish ${formatMonthDay(finish)}: ${pluralize(late, 'day')} past the deadline (${formatMonthDay(deadline)}).`
|
|
3687
|
+
: `Finish ${formatMonthDay(finish)} (must finish by ${formatMonthDay(deadline)}).`;
|
|
3688
|
+
}
|
|
3689
|
+
|
|
3690
|
+
/*
|
|
3691
|
+
* Render a proposed plan (IMPLEMENTATION §1.17), in the project's zone:
|
|
3692
|
+
* counts (new and changed), the finish against the deadline (or that dates
|
|
3693
|
+
* are being calculated, or are not calculated yet), the critical path (or,
|
|
3694
|
+
* when nothing is critical, the path that drives the finish), milestones,
|
|
3695
|
+
* what the proposal was unsure of, then (ASK, the PLAN_REVIEW text) how to
|
|
3696
|
+
* answer, then the link. ASK fits the SMS budget by dropping milestones,
|
|
3697
|
+
* then the unsure list, then the path's tail; TOOL caps its lists at the
|
|
3698
|
+
* tool cap and asks nothing.
|
|
3699
|
+
*/
|
|
3700
|
+
export function formatPlanSummary(input: SchedulePlanSummaryTextInput): string {
|
|
3701
|
+
const { context } = input;
|
|
3702
|
+
const ask = input.audience === 'ASK';
|
|
3703
|
+
const cap = ask ? FILE_CONSTANTS.smsListCap : FILE_CONSTANTS.toolListCap;
|
|
3704
|
+
const criticalSection = createSection({
|
|
3705
|
+
title: FILE_CONSTANTS.criticalPathTitles[input.criticalPathKind].path,
|
|
3706
|
+
items: input.criticalPath.map(formatActivityName),
|
|
3707
|
+
cap,
|
|
3708
|
+
min: 1,
|
|
3709
|
+
soft: 1,
|
|
3710
|
+
join: ' > ',
|
|
3711
|
+
});
|
|
3712
|
+
const milestoneSection = createSection({
|
|
3713
|
+
title: 'Milestones',
|
|
3714
|
+
items: sortPlanMilestones(input.milestones).map((milestone) =>
|
|
3715
|
+
milestone.finishAt
|
|
3716
|
+
? `${formatActivityName(milestone)} ${formatMonthDay(getFinishLocalDate(milestone.finishAt, context.timeZone))}`
|
|
3717
|
+
: formatActivityName(milestone),
|
|
3718
|
+
),
|
|
3719
|
+
cap,
|
|
3720
|
+
join: '; ',
|
|
3721
|
+
});
|
|
3722
|
+
const unsureSection = createSection({
|
|
3723
|
+
title: 'Unsure',
|
|
3724
|
+
items: [...input.lowConfidence]
|
|
3725
|
+
.sort(
|
|
3726
|
+
(a, b) => a.confidence - b.confidence || compareText(a.code, b.code),
|
|
3727
|
+
)
|
|
3728
|
+
.map(
|
|
3729
|
+
(activity) =>
|
|
3730
|
+
`${formatActivityName(activity)} (${Math.round(activity.confidence * 100)}%)`,
|
|
3731
|
+
),
|
|
3732
|
+
cap,
|
|
3733
|
+
join: '; ',
|
|
3734
|
+
});
|
|
3735
|
+
const parts: ScheduleTextPart[] = [
|
|
3736
|
+
getPlanHeadline(input),
|
|
3737
|
+
getPlanFinishLine(input),
|
|
3738
|
+
criticalSection,
|
|
3739
|
+
milestoneSection,
|
|
3740
|
+
unsureSection,
|
|
3741
|
+
ask ? 'Reply YES to accept, or tell me what to change.' : null,
|
|
3742
|
+
context.link,
|
|
3743
|
+
];
|
|
3744
|
+
return ask
|
|
3745
|
+
? fitScheduleTextParts(
|
|
3746
|
+
parts,
|
|
3747
|
+
[milestoneSection, unsureSection, criticalSection],
|
|
3748
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
3749
|
+
)
|
|
3750
|
+
: renderScheduleTextParts(parts);
|
|
3751
|
+
}
|
|
3752
|
+
|
|
3753
|
+
/*
|
|
3754
|
+
* The detail of a check-in item, in the project's zone: "(60%, due Thu Mar
|
|
3755
|
+
* 5)", "(started)" for running work at 0%, "(starts Mon Mar 9)", or ''.
|
|
3756
|
+
*/
|
|
3757
|
+
function getProgressItemDetail(
|
|
3758
|
+
item: ScheduleProgressCheckTextInput['items'][number],
|
|
3759
|
+
timeZone: string,
|
|
3760
|
+
): string {
|
|
3761
|
+
if (item.status === 'IN_PROGRESS') {
|
|
3762
|
+
const percent = Math.round(
|
|
3763
|
+
Math.min(100, Math.max(0, item.percentComplete || 0)),
|
|
3764
|
+
);
|
|
3765
|
+
const due = item.finishAt
|
|
3766
|
+
? `, due ${formatScheduleDay(getFinishLocalDate(item.finishAt, timeZone))}`
|
|
3767
|
+
: '';
|
|
3768
|
+
return ` (${percent ? `${percent}%` : 'started'}${due})`;
|
|
3769
|
+
}
|
|
3770
|
+
return item.startAt
|
|
3771
|
+
? ` (starts ${formatScheduleDay(getScheduleLocalDate(item.startAt, timeZone))})`
|
|
3772
|
+
: '';
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
/*
|
|
3776
|
+
* Pick the fullest check-in rendering that fits the SMS budget: names
|
|
3777
|
+
* clipped step by step down to their floor, then the last items hidden into
|
|
3778
|
+
* "+N more" (at least one stays).
|
|
3779
|
+
*/
|
|
3780
|
+
function fitProgressCheck(
|
|
3781
|
+
render: (nameMax: number, shown: number) => string,
|
|
3782
|
+
count: number,
|
|
3783
|
+
): string {
|
|
3784
|
+
const fits = (text: string) =>
|
|
3785
|
+
getScheduleSmsSegmentCount(text) <= SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS;
|
|
3786
|
+
const { clipStep, progressNameMaxLength, progressNameMinLength } =
|
|
3787
|
+
FILE_CONSTANTS;
|
|
3788
|
+
for (
|
|
3789
|
+
let nameMax = progressNameMaxLength;
|
|
3790
|
+
nameMax > progressNameMinLength;
|
|
3791
|
+
nameMax -= clipStep
|
|
3792
|
+
) {
|
|
3793
|
+
const text = render(nameMax, count);
|
|
3794
|
+
if (fits(text)) return text;
|
|
3795
|
+
}
|
|
3796
|
+
for (let shown = count; shown > 1; shown -= 1) {
|
|
3797
|
+
const text = render(progressNameMinLength, shown);
|
|
3798
|
+
if (fits(text)) return text;
|
|
3799
|
+
}
|
|
3800
|
+
return render(progressNameMinLength, Math.min(count, 1));
|
|
3801
|
+
}
|
|
3802
|
+
|
|
3803
|
+
/*
|
|
3804
|
+
* Render a progress check-in (SMS-bound, the PROGRESS_CHECK ask), in the
|
|
3805
|
+
* project's zone: the question, the person's due or running activities
|
|
3806
|
+
* numbered as payload.activityIds, "+N more", then how to answer. Over
|
|
3807
|
+
* budget the names are clipped, then the last items join "+N more" (their
|
|
3808
|
+
* numbers still answer).
|
|
3809
|
+
*/
|
|
3810
|
+
export function formatProgressCheck(
|
|
3811
|
+
input: ScheduleProgressCheckTextInput,
|
|
3812
|
+
): string {
|
|
3813
|
+
const { context } = input;
|
|
3814
|
+
const items = input.items.map((item) => ({
|
|
3815
|
+
name: item.name.trim() || 'Activity',
|
|
3816
|
+
detail: getProgressItemDetail(item, context.timeZone),
|
|
3817
|
+
}));
|
|
3818
|
+
const question = `${context.calendarName ? `${context.calendarName} check-in` : 'Check-in'}. How is your work going?`;
|
|
3819
|
+
return fitProgressCheck((nameMax, shown) => {
|
|
3820
|
+
const hidden = items.length - shown + Math.max(0, input.moreCount);
|
|
3821
|
+
return joinScheduleText([
|
|
3822
|
+
question,
|
|
3823
|
+
...items
|
|
3824
|
+
.slice(0, shown)
|
|
3825
|
+
.map(
|
|
3826
|
+
(item, index) =>
|
|
3827
|
+
`${index + 1}. ${clipText(item.name, nameMax)}${item.detail}`,
|
|
3828
|
+
),
|
|
3829
|
+
hidden > 0 ? `+${hidden} more` : null,
|
|
3830
|
+
'Reply with each number and how far along it is, e.g. "1 done, 2 50%".',
|
|
3831
|
+
context.link,
|
|
3832
|
+
]);
|
|
3833
|
+
}, items.length);
|
|
3834
|
+
}
|
|
3835
|
+
|
|
3836
|
+
/*
|
|
3837
|
+
* The finish line of a digest: the finish against the baseline, the last
|
|
3838
|
+
* digest and the deadline, each when its date exists ("Finish Mar 10: 5 days
|
|
3839
|
+
* after the baseline (Mar 5), 2 days later than last week."); the
|
|
3840
|
+
* uncalculated line while the network is not calculated.
|
|
3841
|
+
*/
|
|
3842
|
+
function getDigestFinishLine(
|
|
3843
|
+
digest: ScheduleProjectDigestPayloadObj,
|
|
3844
|
+
timeZone: string,
|
|
3845
|
+
): string {
|
|
3846
|
+
if (!digest.calculated) return getUncalculatedLine(digest.pending);
|
|
3847
|
+
if (!digest.finishAt) return 'No finish date yet.';
|
|
3848
|
+
const finish = getFinishLocalDate(digest.finishAt, timeZone);
|
|
3849
|
+
const dateOf = (at: string | null) =>
|
|
3850
|
+
at ? getFinishLocalDate(at, timeZone) : null;
|
|
3851
|
+
const baseline = dateOf(digest.baselineFinishAt);
|
|
3852
|
+
const previous = dateOf(digest.previousFinishAt);
|
|
3853
|
+
const deadline = dateOf(digest.mustFinishByAt);
|
|
3854
|
+
const clauses = [
|
|
3855
|
+
baseline
|
|
3856
|
+
? formatDayDifference(baseline, finish, {
|
|
3857
|
+
later: `after the baseline (${formatMonthDay(baseline)})`,
|
|
3858
|
+
earlier: `before the baseline (${formatMonthDay(baseline)})`,
|
|
3859
|
+
same: 'on the baseline',
|
|
3860
|
+
})
|
|
3861
|
+
: null,
|
|
3862
|
+
previous
|
|
3863
|
+
? formatDayDifference(previous, finish, {
|
|
3864
|
+
later: 'later than last week',
|
|
3865
|
+
earlier: 'earlier than last week',
|
|
3866
|
+
same: 'same as last week',
|
|
3867
|
+
})
|
|
3868
|
+
: null,
|
|
3869
|
+
deadline
|
|
3870
|
+
? formatDayDifference(deadline, finish, {
|
|
3871
|
+
later: `past the deadline (${formatMonthDay(deadline)})`,
|
|
3872
|
+
earlier: `before the deadline (${formatMonthDay(deadline)})`,
|
|
3873
|
+
same: 'on the deadline',
|
|
3874
|
+
})
|
|
3875
|
+
: null,
|
|
3876
|
+
].filter(Boolean);
|
|
3877
|
+
return `Finish ${formatMonthDay(finish)}${clauses.length ? `: ${clauses.join(', ')}` : ''}.`;
|
|
3878
|
+
}
|
|
3879
|
+
|
|
3880
|
+
/*
|
|
3881
|
+
* The critical line of a digest: what joined the path since the last digest,
|
|
3882
|
+
* or, with no previous digest (no previous finish), the head of the path;
|
|
3883
|
+
* null when neither applies. The path is the critical one, or the path that
|
|
3884
|
+
* drives the finish when nothing is critical (criticalPathKind).
|
|
3885
|
+
*/
|
|
3886
|
+
function getDigestCriticalSection(
|
|
3887
|
+
digest: ScheduleProjectDigestPayloadObj,
|
|
3888
|
+
): ScheduleTextSection | null {
|
|
3889
|
+
const titles = FILE_CONSTANTS.criticalPathTitles[digest.criticalPathKind];
|
|
3890
|
+
if (digest.newlyCritical.length)
|
|
3891
|
+
return createSection({
|
|
3892
|
+
title: titles.newly,
|
|
3893
|
+
items: digest.newlyCritical.map(formatActivityName),
|
|
3894
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
3895
|
+
soft: 1,
|
|
3896
|
+
join: ', ',
|
|
3897
|
+
extraCount: digest.newlyCriticalCount - digest.newlyCritical.length,
|
|
3898
|
+
});
|
|
3899
|
+
if (digest.previousFinishAt == null && digest.criticalHead.length)
|
|
3900
|
+
return createSection({
|
|
3901
|
+
title: titles.path,
|
|
3902
|
+
items: digest.criticalHead.map(formatActivityName),
|
|
3903
|
+
cap: FILE_CONSTANTS.smsListCap,
|
|
3904
|
+
soft: 1,
|
|
3905
|
+
join: ' > ',
|
|
3906
|
+
});
|
|
3907
|
+
return null;
|
|
3908
|
+
}
|
|
3909
|
+
|
|
3910
|
+
/*
|
|
3911
|
+
* The starting part of a digest, in the project's zone: "Starting in the next
|
|
3912
|
+
* 7 days: Mon Mar 2 A1050 Drywall (Mike); ..." as a section, or one line
|
|
3913
|
+
* when nothing is listed.
|
|
3914
|
+
*/
|
|
3915
|
+
function getDigestStartingPart(
|
|
3916
|
+
digest: ScheduleProjectDigestPayloadObj,
|
|
3917
|
+
timeZone: string,
|
|
3918
|
+
): string | ScheduleTextSection {
|
|
3919
|
+
const days = pluralize(SCHEDULE_PROJECT_DIGEST_LOOKAHEAD_DAYS, 'day');
|
|
3920
|
+
if (!digest.starting.length)
|
|
3921
|
+
return digest.startingCount > 0
|
|
3922
|
+
? `${pluralize(digest.startingCount, 'activity', 'activities')} start in the next ${days}.`
|
|
3923
|
+
: `Nothing starts in the next ${days}.`;
|
|
3924
|
+
const starting = [...digest.starting].sort(
|
|
3925
|
+
(a, b) =>
|
|
3926
|
+
toScheduleTimeMs(a.startAt) - toScheduleTimeMs(b.startAt) ||
|
|
3927
|
+
compareText(a.code, b.code),
|
|
3928
|
+
);
|
|
3929
|
+
return createSection({
|
|
3930
|
+
title: `Starting in the next ${days}`,
|
|
3931
|
+
items: starting.map((activity) => {
|
|
3932
|
+
const names = activity.responsibleNames.length
|
|
3933
|
+
? ` (${formatNameList(activity.responsibleNames)})`
|
|
3934
|
+
: '';
|
|
3935
|
+
return `${formatScheduleDay(getScheduleLocalDate(activity.startAt, timeZone))} ${formatActivityName(activity)}${names}`;
|
|
3936
|
+
}),
|
|
3937
|
+
cap: starting.length,
|
|
3938
|
+
soft: 1,
|
|
3939
|
+
join: '; ',
|
|
3940
|
+
extraCount: digest.startingCount - starting.length,
|
|
3941
|
+
});
|
|
3942
|
+
}
|
|
3943
|
+
|
|
3944
|
+
/*
|
|
3945
|
+
* The check-in line of a digest ("Check-ins: 3 of 4 answered this week."),
|
|
3946
|
+
* or null when check-ins are off.
|
|
3947
|
+
*/
|
|
3948
|
+
function getDigestCheckInLine(
|
|
3949
|
+
checkIns: ScheduleProjectDigestPayloadObj['checkIns'],
|
|
3950
|
+
): string | null {
|
|
3951
|
+
if (!checkIns) return null;
|
|
3952
|
+
if (!checkIns.asked) return 'Check-ins: nobody was asked this week.';
|
|
3953
|
+
return `Check-ins: ${checkIns.answered} of ${checkIns.asked} answered this week.`;
|
|
3954
|
+
}
|
|
3955
|
+
|
|
3956
|
+
/*
|
|
3957
|
+
* Render the weekly digest (SMS-bound, the PROJECT_DIGEST body) from its
|
|
3958
|
+
* stored payload, in the project's zone: the finish against the baseline,
|
|
3959
|
+
* the last digest and the deadline; what became critical (or, first digest,
|
|
3960
|
+
* the critical path's head); what starts within the lookahead and who is
|
|
3961
|
+
* responsible; the check-in answers; the link. Over budget it drops the
|
|
3962
|
+
* starting list's tail, then the critical line's, then both lines, never the
|
|
3963
|
+
* finish line or the link.
|
|
3964
|
+
*/
|
|
3965
|
+
export function formatProjectDigest(
|
|
3966
|
+
input: ScheduleProjectDigestTextInput,
|
|
3967
|
+
): string {
|
|
3968
|
+
const { context, digest } = input;
|
|
3969
|
+
const name = context.calendarName;
|
|
3970
|
+
const critical = getDigestCriticalSection(digest);
|
|
3971
|
+
const starting = getDigestStartingPart(digest, context.timeZone);
|
|
3972
|
+
const dropOrder = [
|
|
3973
|
+
typeof starting === 'string' ? null : starting,
|
|
3974
|
+
critical,
|
|
3975
|
+
].filter((section): section is ScheduleTextSection => section !== null);
|
|
3976
|
+
return fitScheduleTextParts(
|
|
3977
|
+
[
|
|
3978
|
+
`${name ? `${name} weekly update` : 'Weekly project update'}.`,
|
|
3979
|
+
getDigestFinishLine(digest, context.timeZone),
|
|
3980
|
+
critical,
|
|
3981
|
+
starting,
|
|
3982
|
+
getDigestCheckInLine(digest.checkIns),
|
|
3983
|
+
context.link,
|
|
3984
|
+
],
|
|
3985
|
+
dropOrder,
|
|
3986
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
3987
|
+
);
|
|
3988
|
+
}
|
|
3989
|
+
|
|
3990
|
+
/*
|
|
3991
|
+
* The first line of a slip notice: how far the finish moved and between
|
|
3992
|
+
* which dates, against the deadline: "Harbor Tower: finish moved 5 days, Mar
|
|
3993
|
+
* 5 -> Mar 10 (2 days past the deadline, Mar 8)."
|
|
3994
|
+
*/
|
|
3995
|
+
function getSlipFinishLine(
|
|
3996
|
+
slip: ScheduleProjectSlipPayloadObj,
|
|
3997
|
+
context: ScheduleTextContext,
|
|
3998
|
+
): string {
|
|
3999
|
+
const zone = context.timeZone;
|
|
4000
|
+
if (!slip.finishAt)
|
|
4001
|
+
return withProjectName(context.calendarName, 'milestones are at risk.');
|
|
4002
|
+
const finish = getFinishLocalDate(slip.finishAt, zone);
|
|
4003
|
+
const previous = slip.previousFinishAt
|
|
4004
|
+
? getFinishLocalDate(slip.previousFinishAt, zone)
|
|
4005
|
+
: null;
|
|
4006
|
+
const moved = previous ? getScheduleDaysBetween(previous, finish) : 0;
|
|
4007
|
+
const clause = !previous
|
|
4008
|
+
? `finish ${formatMonthDay(finish)}`
|
|
4009
|
+
: moved
|
|
4010
|
+
? `finish moved ${pluralize(Math.abs(moved), 'day')}${moved < 0 ? ' earlier' : ''}, ${formatMonthDay(previous)} -> ${formatMonthDay(finish)}`
|
|
4011
|
+
: `finish still ${formatMonthDay(finish)}`;
|
|
4012
|
+
let against = '';
|
|
4013
|
+
if (slip.mustFinishByAt) {
|
|
4014
|
+
const deadline = getFinishLocalDate(slip.mustFinishByAt, zone);
|
|
4015
|
+
const late = getScheduleDaysBetween(deadline, finish);
|
|
4016
|
+
against =
|
|
4017
|
+
late > 0
|
|
4018
|
+
? ` (${pluralize(late, 'day')} past the deadline, ${formatMonthDay(deadline)})`
|
|
4019
|
+
: ` (deadline ${formatMonthDay(deadline)})`;
|
|
4020
|
+
}
|
|
4021
|
+
return withProjectName(context.calendarName, `${clause}${against}.`);
|
|
4022
|
+
}
|
|
4023
|
+
|
|
4024
|
+
/*
|
|
4025
|
+
* One milestone of a slip notice: how far it moved and whether it is now
|
|
4026
|
+
* late (its float went below zero), with its new date: "M100 Topping out +3
|
|
4027
|
+
* days (Feb 20)", "M200 Handover +2 days, now late (Mar 12)".
|
|
4028
|
+
*/
|
|
4029
|
+
function formatSlipMilestone(
|
|
4030
|
+
milestone: ScheduleProjectSlipPayloadObj['milestones'][number],
|
|
4031
|
+
timeZone: string,
|
|
4032
|
+
): string {
|
|
4033
|
+
const finish = getFinishLocalDate(milestone.finishAt, timeZone);
|
|
4034
|
+
const moved = milestone.previousFinishAt
|
|
4035
|
+
? getScheduleDaysBetween(
|
|
4036
|
+
getFinishLocalDate(milestone.previousFinishAt, timeZone),
|
|
4037
|
+
finish,
|
|
4038
|
+
)
|
|
4039
|
+
: 0;
|
|
4040
|
+
const clauses = [
|
|
4041
|
+
moved
|
|
4042
|
+
? `${moved > 0 ? '+' : '-'}${pluralize(Math.abs(moved), 'day')}`
|
|
4043
|
+
: null,
|
|
4044
|
+
milestone.atRisk ? 'now late' : null,
|
|
4045
|
+
].filter(Boolean);
|
|
4046
|
+
return `${formatActivityName(milestone)}${clauses.length ? ` ${clauses.join(', ')}` : ''} (${formatMonthDay(finish)})`;
|
|
4047
|
+
}
|
|
4048
|
+
|
|
4049
|
+
/*
|
|
4050
|
+
* Render the slip notice (SMS-bound, the MILESTONE_AT_RISK body) from its
|
|
4051
|
+
* stored payload, in the project's zone: how far the finish moved against
|
|
4052
|
+
* the deadline, the milestones that slipped or became late (biggest slip
|
|
4053
|
+
* first, "+N more"), the link. Day counts are calendar days between
|
|
4054
|
+
* project-local dates. Over budget the milestone list shrinks to its first.
|
|
4055
|
+
*/
|
|
4056
|
+
export function formatProjectSlip(input: ScheduleProjectSlipTextInput): string {
|
|
4057
|
+
const { context, slip } = input;
|
|
4058
|
+
const milestoneSection = createSection({
|
|
4059
|
+
title: 'Slipped',
|
|
4060
|
+
items: slip.milestones.map((milestone) =>
|
|
4061
|
+
formatSlipMilestone(milestone, context.timeZone),
|
|
4062
|
+
),
|
|
4063
|
+
cap: slip.milestones.length,
|
|
4064
|
+
min: 1,
|
|
4065
|
+
soft: 1,
|
|
4066
|
+
join: '; ',
|
|
4067
|
+
extraCount: slip.milestoneCount - slip.milestones.length,
|
|
4068
|
+
});
|
|
4069
|
+
return fitScheduleTextParts(
|
|
4070
|
+
[getSlipFinishLine(slip, context), milestoneSection, context.link],
|
|
4071
|
+
[milestoneSection],
|
|
4072
|
+
SCHEDULE_TEXT_SUMMARY_MAX_SEGMENTS,
|
|
4073
|
+
);
|
|
4074
|
+
}
|