@jsb188/mday 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,246 +0,0 @@
1
- import {
2
- DEFAULT_TIMEZONE,
3
- isValidTimeZone,
4
- } from '@jsb188/app/utils/timeZone.ts';
5
- import { DateTime } from 'luxon';
6
- import type { ScheduleRecurrenceObj } from '../types/schedule.d.ts';
7
- import { getScheduleRecurrenceRRule } from './schedule.ts';
8
-
9
- /**
10
- * iCalendar (RFC 5545) rendering for schedule subscription feeds.
11
- *
12
- * Pure and stringly-typed on purpose: the output has to be byte-correct for
13
- * clients we cannot debug against — Apple Calendar, Outlook, and Google each
14
- * fail differently on a malformed feed, and mostly by silently showing
15
- * nothing. The three rules that actually matter and are easy to get wrong:
16
- *
17
- * 1. Lines end with CRLF, always. A bare LF makes some parsers drop the feed.
18
- * 2. Lines are folded at 75 OCTETS, not characters, with a leading space on
19
- * each continuation. Folding by character corrupts any title with an emoji
20
- * or an accent, because a multi-byte sequence gets split down the middle.
21
- * 3. Backslash, semicolon, comma and newline are escaped inside text values.
22
- * An unescaped comma in a shift title silently truncates it.
23
- *
24
- * Times are emitted as UTC instants ("...Z") rather than with a TZID, so no
25
- * VTIMEZONE block is needed and no client has to agree with us about a zone's
26
- * history. All-day entries are the exception: they use DATE values in the
27
- * calendar's own zone, because "the 3rd" is a local fact, not an instant.
28
- */
29
-
30
- // RFC 5545 §3.1: content lines are folded so no line exceeds 75 octets
31
- const ICS_MAX_LINE_OCTETS = 75;
32
-
33
- export interface ScheduleICSEvent {
34
- // Stable across every fetch; changing it makes clients duplicate the entry
35
- uid: string;
36
- // Bumped on edit so clients replace rather than duplicate
37
- sequence: number;
38
- summary: string;
39
- description?: string | null;
40
- location?: string | null;
41
- startAt: Date;
42
- endAt: Date;
43
- allDay?: boolean | null;
44
- timeZone?: string | null;
45
- status?: 'CONFIRMED' | 'TENTATIVE' | 'CANCELLED' | null;
46
- // Set on the first instance of a series to export the rule itself
47
- recurrence?: ScheduleRecurrenceObj | null;
48
- lastModified?: Date | null;
49
- url?: string | null;
50
- }
51
-
52
- export interface ScheduleICSCalendar {
53
- name: string;
54
- description?: string | null;
55
- timeZone?: string | null;
56
- // Hint to clients for how often to poll; they treat it as advisory
57
- refreshIntervalMinutes?: number | null;
58
- events: ScheduleICSEvent[];
59
- }
60
-
61
- /*
62
- * Escape one text value per RFC 5545 §3.3.11. Order matters: backslashes are
63
- * escaped first, or the escapes added below would themselves be escaped.
64
- */
65
-
66
- function escapeICSText(value: string): string {
67
- return String(value ?? '')
68
- .replace(/\\/g, '\\\\')
69
- .replace(/;/g, '\\;')
70
- .replace(/,/g, '\\,')
71
- .replace(/\r\n|\r|\n/g, '\\n');
72
- }
73
-
74
- /*
75
- * Fold one content line to the octet limit.
76
- *
77
- * The cut is measured in UTF-8 bytes and never lands inside a multi-byte
78
- * character, so a title with an emoji or an accented name survives folding
79
- * intact — splitting by string index would emit a broken code point and some
80
- * clients reject the whole feed for it.
81
- */
82
-
83
- export function foldICSLine(line: string): string {
84
- const encoder = new TextEncoder();
85
- const bytes = encoder.encode(line);
86
-
87
- if (bytes.length <= ICS_MAX_LINE_OCTETS) {
88
- return line;
89
- }
90
-
91
- const decoder = new TextDecoder();
92
- const folded: string[] = [];
93
- let offset = 0;
94
- // Continuation lines carry a leading space, which counts toward the limit
95
- let limit = ICS_MAX_LINE_OCTETS;
96
-
97
- while (offset < bytes.length) {
98
- let take = Math.min(limit, bytes.length - offset);
99
-
100
- // Walk back off a continuation byte (10xxxxxx) so a character is never
101
- // split across two folded lines
102
- while (take > 1 && (bytes[offset + take] & 0b1100_0000) === 0b1000_0000) {
103
- take--;
104
- }
105
-
106
- const chunk = decoder.decode(bytes.slice(offset, offset + take));
107
- folded.push(folded.length ? ` ${chunk}` : chunk);
108
- offset += take;
109
- limit = ICS_MAX_LINE_OCTETS - 1;
110
- }
111
-
112
- return folded.join('\r\n');
113
- }
114
-
115
- /*
116
- * Format one instant as a UTC date-time value ("20260803T140000Z").
117
- */
118
-
119
- function formatICSInstant(date: Date): string {
120
- return date
121
- .toISOString()
122
- .replace(/[-:]/g, '')
123
- .replace(/\.\d{3}/, '');
124
- }
125
-
126
- /*
127
- * Format one instant as a local DATE value ("20260803") in a given zone.
128
- */
129
-
130
- function formatICSDate(date: Date, timeZone: string): string {
131
- const zone =
132
- timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
133
- const local = DateTime.fromJSDate(date).setZone(zone);
134
-
135
- return local.isValid
136
- ? local.toFormat('yyyyLLdd')
137
- : formatICSInstant(date).slice(0, 8);
138
- }
139
-
140
- /*
141
- * Render one VEVENT block.
142
- */
143
-
144
- function renderICSEvent(
145
- event: ScheduleICSEvent,
146
- calendarTimeZone: string,
147
- dtstamp: string,
148
- ): string[] {
149
- const lines: string[] = ['BEGIN:VEVENT'];
150
- const timeZone = event.timeZone || calendarTimeZone;
151
-
152
- lines.push(`UID:${escapeICSText(event.uid)}`);
153
- lines.push(`DTSTAMP:${dtstamp}`);
154
- lines.push(`SEQUENCE:${Math.max(0, Math.floor(event.sequence || 0))}`);
155
-
156
- if (event.allDay) {
157
- // DTEND is exclusive for DATE values, which is already how the
158
- // occurrence's end instant is stored
159
- lines.push(`DTSTART;VALUE=DATE:${formatICSDate(event.startAt, timeZone)}`);
160
- lines.push(`DTEND;VALUE=DATE:${formatICSDate(event.endAt, timeZone)}`);
161
- } else {
162
- lines.push(`DTSTART:${formatICSInstant(event.startAt)}`);
163
- lines.push(`DTEND:${formatICSInstant(event.endAt)}`);
164
- }
165
-
166
- lines.push(`SUMMARY:${escapeICSText(event.summary)}`);
167
-
168
- if (event.description) {
169
- lines.push(`DESCRIPTION:${escapeICSText(event.description)}`);
170
- }
171
-
172
- if (event.location) {
173
- lines.push(`LOCATION:${escapeICSText(event.location)}`);
174
- }
175
-
176
- if (event.status) {
177
- lines.push(`STATUS:${event.status}`);
178
- }
179
-
180
- if (event.url) {
181
- lines.push(`URL:${escapeICSText(event.url)}`);
182
- }
183
-
184
- if (event.recurrence) {
185
- lines.push(`RRULE:${getScheduleRecurrenceRRule(event.recurrence)}`);
186
- }
187
-
188
- if (event.lastModified) {
189
- lines.push(`LAST-MODIFIED:${formatICSInstant(event.lastModified)}`);
190
- }
191
-
192
- lines.push('END:VEVENT');
193
-
194
- return lines;
195
- }
196
-
197
- /**
198
- * Render one subscription feed.
199
- *
200
- * "now" is a parameter rather than read from the clock so the output is a pure
201
- * function of its input — which is what makes the format testable at all.
202
- */
203
-
204
- export function renderScheduleICS(
205
- calendar: ScheduleICSCalendar,
206
- now: Date,
207
- ): string {
208
- const timeZone =
209
- calendar.timeZone && isValidTimeZone(calendar.timeZone)
210
- ? calendar.timeZone
211
- : DEFAULT_TIMEZONE;
212
- const dtstamp = formatICSInstant(now);
213
- const lines: string[] = [
214
- 'BEGIN:VCALENDAR',
215
- 'VERSION:2.0',
216
- 'PRODID:-//Marketday//Schedule//EN',
217
- 'CALSCALE:GREGORIAN',
218
- // A subscription feed is a published view, not an invitation exchange;
219
- // METHOD:PUBLISH stops clients treating entries as RSVP requests
220
- 'METHOD:PUBLISH',
221
- `X-WR-CALNAME:${escapeICSText(calendar.name)}`,
222
- `X-WR-TIMEZONE:${escapeICSText(timeZone)}`,
223
- ];
224
-
225
- if (calendar.description) {
226
- lines.push(`X-WR-CALDESC:${escapeICSText(calendar.description)}`);
227
- }
228
-
229
- if (calendar.refreshIntervalMinutes) {
230
- const duration = `PT${Math.max(1, Math.floor(calendar.refreshIntervalMinutes))}M`;
231
- // Both spellings: REFRESH-INTERVAL is the standard one, X-PUBLISHED-TTL
232
- // is what Outlook actually reads
233
- lines.push(`REFRESH-INTERVAL;VALUE=DURATION:${duration}`);
234
- lines.push(`X-PUBLISHED-TTL:${duration}`);
235
- }
236
-
237
- for (const event of calendar.events) {
238
- lines.push(...renderICSEvent(event, timeZone, dtstamp));
239
- }
240
-
241
- lines.push('END:VCALENDAR');
242
-
243
- // Folding is applied last so it sees complete content lines, and the feed
244
- // ends with a trailing CRLF as the spec requires
245
- return lines.map(foldICSLine).join('\r\n') + '\r\n';
246
- }
@@ -1,188 +0,0 @@
1
- import {
2
- SCHEDULE_RULE_TEMPLATE_DEFAULTS,
3
- SCHEDULE_RULE_TEMPLATES_BY_OPERATION,
4
- } from '../constants/scheduleRuleTemplates.generated.ts';
5
- import type { ScheduleRuleTemplateObj } from '../types/schedule.d.ts';
6
-
7
- /**
8
- * Rendering constraint violations in an organization's own language.
9
- *
10
- * The evaluator produces facts: kind, severity, and a detail object of raw
11
- * numbers. This module turns one of those into a sentence, using the most
12
- * specific template available — an organization's own wording, then its
13
- * operation type's, then the platform default.
14
- *
15
- * Everything here is pure and synchronous. The organization-scoped templates
16
- * are not in the generated constants (they are one customer's data, not the
17
- * platform's), so callers that have loaded them pass them in; callers that
18
- * have not still get correct operation-level and default wording.
19
- */
20
-
21
- // Renders in place of a token the detail object has no value for. An empty
22
- // string would silently produce "is short", which reads as a rendering bug
23
- // rather than as missing data.
24
- const MISSING_TOKEN_TEXT = '—';
25
-
26
- /**
27
- * Build the composite lookup key for one template.
28
- */
29
-
30
- export function getScheduleRuleTemplateLookupKey(
31
- kind: string,
32
- key: string,
33
- ): string {
34
- return `${kind}:${key}`;
35
- }
36
-
37
- /**
38
- * Resolve the template governing one rule, most specific first.
39
- *
40
- * A rule with no templateKey has no wording of its own — somebody wrote it by
41
- * hand — so it falls through to the first template registered for its kind,
42
- * which is at worst generic and never empty.
43
- */
44
-
45
- export function resolveScheduleRuleTemplate(
46
- kind: string,
47
- templateKey: string | null | undefined,
48
- options?: {
49
- operation?: string | null;
50
- // Organization-scoped rows, keyed by "KIND:KEY"; loaded by the caller
51
- organizationTemplates?: Record<string, ScheduleRuleTemplateObj> | null;
52
- },
53
- ): ScheduleRuleTemplateObj | null {
54
- if (templateKey) {
55
- const lookupKey = getScheduleRuleTemplateLookupKey(kind, templateKey);
56
- const operationTemplates = options?.operation
57
- ? SCHEDULE_RULE_TEMPLATES_BY_OPERATION[options.operation]
58
- : undefined;
59
-
60
- const resolved =
61
- options?.organizationTemplates?.[lookupKey] ||
62
- operationTemplates?.[lookupKey] ||
63
- SCHEDULE_RULE_TEMPLATE_DEFAULTS[lookupKey];
64
-
65
- if (resolved) {
66
- return resolved;
67
- }
68
- }
69
-
70
- return getFirstScheduleRuleTemplateForKind(kind, options);
71
- }
72
-
73
- /*
74
- * Return any template registered for one rule kind, preferring the caller's
75
- * more specific layers. Ordering is by "ordinal" so the answer is stable
76
- * rather than dependent on object key order.
77
- */
78
-
79
- function getFirstScheduleRuleTemplateForKind(
80
- kind: string,
81
- options?: {
82
- operation?: string | null;
83
- organizationTemplates?: Record<string, ScheduleRuleTemplateObj> | null;
84
- },
85
- ): ScheduleRuleTemplateObj | null {
86
- const layers = [
87
- options?.organizationTemplates,
88
- options?.operation
89
- ? SCHEDULE_RULE_TEMPLATES_BY_OPERATION[options.operation]
90
- : null,
91
- SCHEDULE_RULE_TEMPLATE_DEFAULTS,
92
- ];
93
-
94
- for (const layer of layers) {
95
- if (!layer) {
96
- continue;
97
- }
98
-
99
- const matches = Object.values(layer)
100
- .filter((template) => template.kind === kind)
101
- .sort((left, right) => left.ordinal - right.ordinal);
102
-
103
- if (matches.length) {
104
- return matches[0];
105
- }
106
- }
107
-
108
- return null;
109
- }
110
-
111
- /*
112
- * Format one detail value for display. Numbers are trimmed to at most two
113
- * decimals so a rolling-hours total does not render as 37.470000000000006.
114
- */
115
-
116
- function formatScheduleTemplateValue(value: unknown): string {
117
- if (value === null || value === undefined || value === '') {
118
- return MISSING_TOKEN_TEXT;
119
- }
120
-
121
- if (typeof value === 'number') {
122
- return Number.isInteger(value)
123
- ? String(value)
124
- : String(Math.round(value * 100) / 100);
125
- }
126
-
127
- if (Array.isArray(value)) {
128
- return String(value.length);
129
- }
130
-
131
- if (typeof value === 'object') {
132
- return MISSING_TOKEN_TEXT;
133
- }
134
-
135
- return String(value);
136
- }
137
-
138
- /**
139
- * Fill a template's "{token}" placeholders from a violation detail object.
140
- *
141
- * Unknown tokens render as an em dash rather than being left in place: a
142
- * scheduler seeing "{shortfall} short" learns nothing and cannot tell whether
143
- * the number is missing or the rule is broken.
144
- */
145
-
146
- export function renderScheduleRuleTemplateMessage(
147
- messageTemplate: string,
148
- detail: Record<string, unknown> | null | undefined,
149
- ): string {
150
- return messageTemplate.replace(/\{(\w+)\}/g, (_match, token: string) =>
151
- formatScheduleTemplateValue(detail?.[token]),
152
- );
153
- }
154
-
155
- /**
156
- * Render one violation as a sentence in the organization's own language.
157
- *
158
- * Returns null when nothing is registered for the rule's kind at all, which
159
- * lets the caller fall back to its own generic copy rather than printing an
160
- * empty string into the violation strip.
161
- */
162
-
163
- export function getScheduleViolationMessage(
164
- violation: {
165
- kind: string;
166
- templateKey?: string | null;
167
- detail?: Record<string, unknown> | null;
168
- },
169
- options?: {
170
- operation?: string | null;
171
- organizationTemplates?: Record<string, ScheduleRuleTemplateObj> | null;
172
- },
173
- ): string | null {
174
- const template = resolveScheduleRuleTemplate(
175
- violation.kind,
176
- violation.templateKey,
177
- options,
178
- );
179
-
180
- if (!template) {
181
- return null;
182
- }
183
-
184
- return renderScheduleRuleTemplateMessage(
185
- template.messageTemplate,
186
- violation.detail,
187
- );
188
- }