@elevasis/core 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/index.d.ts +5 -5
  2. package/dist/index.js +209 -173
  3. package/dist/knowledge/index.d.ts +21 -21
  4. package/dist/organization-model/index.d.ts +5 -5
  5. package/dist/organization-model/index.js +209 -173
  6. package/dist/test-utils/index.d.ts +2 -2
  7. package/dist/test-utils/index.js +182 -126
  8. package/package.json +1 -1
  9. package/src/_gen/__tests__/__snapshots__/contracts.md.snap +976 -1063
  10. package/src/business/acquisition/api-schemas.test.ts +1962 -1841
  11. package/src/business/acquisition/api-schemas.ts +1461 -1464
  12. package/src/business/acquisition/crm-next-action.test.ts +45 -25
  13. package/src/business/acquisition/crm-next-action.ts +227 -220
  14. package/src/business/acquisition/crm-priority.test.ts +41 -8
  15. package/src/business/acquisition/crm-priority.ts +365 -349
  16. package/src/business/acquisition/crm-state-actions.test.ts +208 -153
  17. package/src/business/acquisition/derive-actions.test.ts +90 -13
  18. package/src/business/acquisition/derive-actions.ts +8 -139
  19. package/src/business/acquisition/ontology-validation.ts +72 -158
  20. package/src/business/pdf/sections/investment.ts +1 -1
  21. package/src/business/pdf/sections/summary-investment.ts +1 -1
  22. package/src/execution/engine/tools/tool-maps.ts +872 -831
  23. package/src/organization-model/__tests__/cross-ref.test.ts +167 -0
  24. package/src/organization-model/__tests__/published-zero-leak.test.ts +60 -1
  25. package/src/organization-model/__tests__/resolve.test.ts +1 -1
  26. package/src/organization-model/__tests__/schema-refinements.test.ts +72 -0
  27. package/src/organization-model/cross-ref.ts +175 -0
  28. package/src/organization-model/domains/branding.ts +6 -6
  29. package/src/organization-model/domains/sales.test.ts +104 -218
  30. package/src/organization-model/domains/sales.ts +212 -375
  31. package/src/organization-model/index.ts +1 -0
  32. package/src/organization-model/schema-refinements.ts +667 -0
  33. package/src/organization-model/schema.ts +8 -715
  34. package/src/reference/_generated/contracts.md +976 -1063
@@ -1,349 +1,365 @@
1
- import { z } from 'zod'
2
- import {
3
- DEFAULT_CRM_PRIORITY_RULE_CONFIG,
4
- type CrmPriorityBucketDefinition,
5
- type CrmPriorityBucketKey,
6
- type CrmPriorityRuleConfig
7
- } from '../../organization-model/domains/sales'
8
- import { getDealOwnership } from './deal-ownership'
9
- import type { DealPriority } from './types'
10
-
11
- export interface CrmPriorityInput {
12
- stage_key: string | null
13
- state_key: string | null
14
- activity_log: unknown
15
- updated_at: string
16
- created_at: string
17
- }
18
-
19
- export interface EvaluateCrmDealPriorityOptions {
20
- config?: CrmPriorityRuleConfig | ResolvedCrmPriorityRuleConfig
21
- now?: Date | string
22
- }
23
-
24
- export const CrmPriorityBucketKeySchema = z.enum(['needs_response', 'follow_up_due', 'waiting', 'stale', 'closed_low'])
25
-
26
- export const CrmPriorityBucketOverrideSchema = z
27
- .object({
28
- label: z.string().trim().min(1).max(80).optional(),
29
- color: z.string().trim().min(1).max(40).optional(),
30
- rank: z.number().int().min(0).max(10000).optional()
31
- })
32
- .strict()
33
-
34
- const CrmPriorityBucketDefinitionSchema = z
35
- .object({
36
- bucketKey: CrmPriorityBucketKeySchema,
37
- label: z.string(),
38
- rank: z.number().int(),
39
- color: z.string()
40
- })
41
- .strict()
42
-
43
- const CrmPriorityRuleConfigSchema = z
44
- .object({
45
- enabled: z.boolean().optional(),
46
- buckets: z.array(CrmPriorityBucketDefinitionSchema),
47
- closedStageKeys: z.array(z.string()),
48
- followUpAfterDaysByStateKey: z.record(z.string(), z.number().int()),
49
- staleAfterDays: z.number().int()
50
- })
51
- .strict()
52
-
53
- export const CrmPriorityOverrideSchema = z
54
- .object({
55
- enabled: z.boolean().optional(),
56
- staleAfterDays: z.number().int().min(1).max(365).optional(),
57
- bucketOrder: z.array(CrmPriorityBucketKeySchema).optional(),
58
- buckets: z.partialRecord(CrmPriorityBucketKeySchema, CrmPriorityBucketOverrideSchema).optional(),
59
- followUpAfterDaysByStateKey: z
60
- .record(z.string().trim().min(1).max(120), z.number().int().min(0).max(365))
61
- .optional(),
62
- closedStageKeys: z.array(z.string().trim().min(1).max(120)).optional()
63
- })
64
- .strict()
65
-
66
- export type CrmPriorityBucketOverride = z.infer<typeof CrmPriorityBucketOverrideSchema>
67
- export type CrmPriorityOverride = z.infer<typeof CrmPriorityOverrideSchema>
68
-
69
- /**
70
- * Resolved CRM priority settings used by evaluators.
71
- *
72
- * When enabled is false, priority evaluation is intentionally neutral: all deals
73
- * receive the configured waiting bucket and no follow-up/stale urgency is computed.
74
- */
75
- export type ResolvedCrmPriorityRuleConfig = CrmPriorityRuleConfig & {
76
- enabled: boolean
77
- }
78
-
79
- interface ParsedActivity {
80
- type: string | null
81
- occurredAt: string
82
- }
83
-
84
- const MS_PER_DAY = 24 * 60 * 60 * 1000
85
-
86
- export function evaluateCrmDealPriority(
87
- input: CrmPriorityInput,
88
- options: EvaluateCrmDealPriorityOptions = {}
89
- ): DealPriority {
90
- const config = resolveCrmPriorityRuleConfig(options.config)
91
- const now = parseDate(options.now ?? new Date()) ?? new Date()
92
- const latestActivityAt = getLatestActivityAt(input)
93
- const nextActionAt = getNextActionAt(input.state_key, latestActivityAt, config)
94
-
95
- if (!config.enabled) {
96
- return buildPriority('waiting', config, {
97
- reason: 'CRM priority evaluation is disabled.',
98
- latestActivityAt,
99
- nextActionAt: null
100
- })
101
- }
102
-
103
- if (input.stage_key && config.closedStageKeys.includes(input.stage_key)) {
104
- return buildPriority('closed_low', config, {
105
- reason: `Deal is in ${input.stage_key}.`,
106
- latestActivityAt,
107
- nextActionAt: null
108
- })
109
- }
110
-
111
- const ownership = getDealOwnership(input)
112
-
113
- if (ownership === 'us') {
114
- return buildPriority('needs_response', config, {
115
- reason: 'Lead replied last — we owe the next move.',
116
- latestActivityAt,
117
- nextActionAt
118
- })
119
- }
120
-
121
- // ownership === 'them' or null: check age against staleAfterDays first
122
- if (latestActivityAt) {
123
- const latestActivityDate = parseDate(latestActivityAt)
124
- if (latestActivityDate && now.getTime() - latestActivityDate.getTime() >= config.staleAfterDays * MS_PER_DAY) {
125
- return buildPriority('stale', config, {
126
- reason: `No meaningful activity in ${config.staleAfterDays} days.`,
127
- latestActivityAt,
128
- nextActionAt: null
129
- })
130
- }
131
- }
132
-
133
- if (ownership === 'them') {
134
- if (nextActionAt) {
135
- const nextActionDate = parseDate(nextActionAt)
136
- if (nextActionDate && nextActionDate <= now) {
137
- return buildPriority('follow_up_due', config, {
138
- reason: 'Configured follow-up window has elapsed.',
139
- latestActivityAt,
140
- nextActionAt
141
- })
142
- }
143
- }
144
-
145
- return buildPriority('waiting', config, {
146
- reason: 'Waiting on their reply.',
147
- latestActivityAt,
148
- nextActionAt
149
- })
150
- }
151
-
152
- // ownership === null (no inbound/outbound events): fall back to follow_up/waiting
153
- if (nextActionAt) {
154
- const nextActionDate = parseDate(nextActionAt)
155
- if (nextActionDate && nextActionDate <= now) {
156
- return buildPriority('follow_up_due', config, {
157
- reason: 'Configured follow-up window has elapsed.',
158
- latestActivityAt,
159
- nextActionAt
160
- })
161
- }
162
-
163
- return buildPriority('waiting', config, {
164
- reason: 'Waiting until the configured next action time.',
165
- latestActivityAt,
166
- nextActionAt
167
- })
168
- }
169
-
170
- return buildPriority('waiting', config, {
171
- reason: 'No immediate response or follow-up is due.',
172
- latestActivityAt,
173
- nextActionAt: null
174
- })
175
- }
176
-
177
- export function resolveCrmPriorityRuleConfig(input?: unknown): ResolvedCrmPriorityRuleConfig {
178
- const candidate = extractPriorityOverride(input)
179
- const fullConfigResult = CrmPriorityRuleConfigSchema.safeParse(candidate)
180
-
181
- if (fullConfigResult.success) return buildResolvedConfig(fullConfigResult.data)
182
-
183
- const result = CrmPriorityOverrideSchema.safeParse(candidate)
184
-
185
- if (!result.success) return buildDefaultResolvedConfig()
186
-
187
- return mergeCrmPriorityOverride(result.data)
188
- }
189
-
190
- function mergeCrmPriorityOverride(override: CrmPriorityOverride): ResolvedCrmPriorityRuleConfig {
191
- const defaultConfig = buildDefaultResolvedConfig()
192
- const bucketOverrides = override.buckets ?? {}
193
- const orderedBucketKeys = override.bucketOrder ? [...new Set(override.bucketOrder)] : []
194
- const orderRanks = new Map<CrmPriorityBucketKey, number>()
195
-
196
- orderedBucketKeys.forEach((bucketKey, index) => {
197
- orderRanks.set(bucketKey, (index + 1) * 10)
198
- })
199
-
200
- const buckets = defaultConfig.buckets
201
- .map((bucket) => {
202
- const bucketOverride = bucketOverrides[bucket.bucketKey]
203
-
204
- return {
205
- ...bucket,
206
- rank: bucketOverride?.rank ?? orderRanks.get(bucket.bucketKey) ?? bucket.rank,
207
- label: bucketOverride?.label ?? bucket.label,
208
- color: bucketOverride?.color ?? bucket.color
209
- }
210
- })
211
- .sort((a, b) => a.rank - b.rank)
212
-
213
- return {
214
- enabled: override.enabled ?? defaultConfig.enabled,
215
- buckets,
216
- closedStageKeys: override.closedStageKeys ?? defaultConfig.closedStageKeys,
217
- followUpAfterDaysByStateKey: {
218
- ...defaultConfig.followUpAfterDaysByStateKey,
219
- ...(override.followUpAfterDaysByStateKey ?? {})
220
- },
221
- staleAfterDays: override.staleAfterDays ?? defaultConfig.staleAfterDays
222
- }
223
- }
224
-
225
- function buildDefaultResolvedConfig(): ResolvedCrmPriorityRuleConfig {
226
- return buildResolvedConfig(DEFAULT_CRM_PRIORITY_RULE_CONFIG)
227
- }
228
-
229
- function buildResolvedConfig(config: CrmPriorityRuleConfig & { enabled?: boolean }): ResolvedCrmPriorityRuleConfig {
230
- return {
231
- enabled: config.enabled ?? true,
232
- buckets: config.buckets.map((bucket) => ({ ...bucket })),
233
- closedStageKeys: [...config.closedStageKeys],
234
- followUpAfterDaysByStateKey: { ...config.followUpAfterDaysByStateKey },
235
- staleAfterDays: config.staleAfterDays
236
- }
237
- }
238
-
239
- function extractPriorityOverride(input: unknown): unknown {
240
- if (!isPlainRecord(input)) return input
241
-
242
- const crm = input.crm
243
- if (isPlainRecord(crm) && Object.prototype.hasOwnProperty.call(crm, 'priority')) {
244
- return crm.priority
245
- }
246
-
247
- return input
248
- }
249
-
250
- function isPlainRecord(value: unknown): value is Record<string, unknown> {
251
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
252
- }
253
-
254
- function buildPriority(
255
- bucketKey: CrmPriorityBucketKey,
256
- config: CrmPriorityRuleConfig,
257
- values: Pick<DealPriority, 'reason' | 'latestActivityAt' | 'nextActionAt'>
258
- ): DealPriority {
259
- const bucket = findBucket(config.buckets, bucketKey)
260
-
261
- return {
262
- bucketKey: bucket.bucketKey,
263
- rank: bucket.rank,
264
- label: bucket.label,
265
- color: bucket.color,
266
- reason: values.reason,
267
- latestActivityAt: values.latestActivityAt,
268
- nextActionAt: values.nextActionAt
269
- }
270
- }
271
-
272
- function findBucket(
273
- buckets: CrmPriorityBucketDefinition[],
274
- bucketKey: CrmPriorityBucketKey
275
- ): CrmPriorityBucketDefinition {
276
- const bucket = buckets.find((candidate) => candidate.bucketKey === bucketKey)
277
- if (bucket) return bucket
278
-
279
- return {
280
- bucketKey,
281
- label: bucketKey,
282
- rank: Number.MAX_SAFE_INTEGER,
283
- color: 'gray'
284
- }
285
- }
286
-
287
- function getLatestActivityAt(input: CrmPriorityInput): string | null {
288
- const timestamps = getParsedActivities(input.activity_log).map((activity) => activity.occurredAt)
289
- const fallback = normalizeTimestamp(input.updated_at) ?? normalizeTimestamp(input.created_at)
290
- if (fallback) timestamps.push(fallback)
291
-
292
- return timestamps.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())[0] ?? null
293
- }
294
-
295
- function getParsedActivities(activityLog: unknown): ParsedActivity[] {
296
- if (!Array.isArray(activityLog)) return []
297
-
298
- const parsed: ParsedActivity[] = []
299
-
300
- for (const entry of activityLog) {
301
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
302
-
303
- const record = entry as Record<string, unknown>
304
- const occurredAt =
305
- normalizeTimestamp(record.timestamp) ??
306
- normalizeTimestamp(record.occurredAt) ??
307
- normalizeTimestamp(record.createdAt) ??
308
- normalizeTimestamp(record.updatedAt) ??
309
- normalizeTimestamp(record.sentAt)
310
-
311
- if (!occurredAt) continue
312
-
313
- parsed.push({
314
- type: typeof record.type === 'string' ? record.type : null,
315
- occurredAt
316
- })
317
- }
318
-
319
- return parsed
320
- }
321
-
322
- function getNextActionAt(
323
- stateKey: string | null,
324
- latestActivityAt: string | null,
325
- config: CrmPriorityRuleConfig
326
- ): string | null {
327
- if (!stateKey || !latestActivityAt) return null
328
-
329
- const days = config.followUpAfterDaysByStateKey[stateKey]
330
- if (days === undefined) return null
331
-
332
- const latestActivityDate = parseDate(latestActivityAt)
333
- if (!latestActivityDate) return null
334
-
335
- return new Date(latestActivityDate.getTime() + days * MS_PER_DAY).toISOString()
336
- }
337
-
338
- function normalizeTimestamp(value: unknown): string | null {
339
- const date = parseDate(value)
340
- return date ? date.toISOString() : null
341
- }
342
-
343
- function parseDate(value: unknown): Date | null {
344
- if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
345
- if (typeof value !== 'string') return null
346
-
347
- const date = new Date(value)
348
- return Number.isNaN(date.getTime()) ? null : date
349
- }
1
+ import { z } from 'zod'
2
+ import {
3
+ type CrmPriorityBucketDefinition,
4
+ type CrmPriorityBucketKey,
5
+ type CrmPriorityRuleConfig
6
+ } from '../../organization-model/domains/sales'
7
+ import { getDealOwnership } from './deal-ownership'
8
+ import type { DealPriority } from './types'
9
+
10
+ export interface CrmPriorityInput {
11
+ stage_key: string | null
12
+ state_key: string | null
13
+ activity_log: unknown
14
+ updated_at: string
15
+ created_at: string
16
+ }
17
+
18
+ export interface EvaluateCrmDealPriorityOptions {
19
+ config?: CrmPriorityRuleConfig | ResolvedCrmPriorityRuleConfig
20
+ now?: Date | string
21
+ }
22
+
23
+ export const CrmPriorityBucketKeySchema = z.enum(['needs_response', 'follow_up_due', 'waiting', 'stale', 'closed_low'])
24
+
25
+ export const CrmPriorityBucketOverrideSchema = z
26
+ .object({
27
+ label: z.string().trim().min(1).max(80).optional(),
28
+ color: z.string().trim().min(1).max(40).optional(),
29
+ rank: z.number().int().min(0).max(10000).optional()
30
+ })
31
+ .strict()
32
+
33
+ const CrmPriorityBucketDefinitionSchema = z
34
+ .object({
35
+ bucketKey: CrmPriorityBucketKeySchema,
36
+ label: z.string(),
37
+ rank: z.number().int(),
38
+ color: z.string()
39
+ })
40
+ .strict()
41
+
42
+ const CrmPriorityRuleConfigSchema = z
43
+ .object({
44
+ enabled: z.boolean().optional(),
45
+ buckets: z.array(CrmPriorityBucketDefinitionSchema),
46
+ closedStageKeys: z.array(z.string()),
47
+ followUpAfterDaysByStateKey: z.record(z.string(), z.number().int()),
48
+ staleAfterDays: z.number().int()
49
+ })
50
+ .strict()
51
+
52
+ export const CrmPriorityOverrideSchema = z
53
+ .object({
54
+ enabled: z.boolean().optional(),
55
+ staleAfterDays: z.number().int().min(1).max(365).optional(),
56
+ bucketOrder: z.array(CrmPriorityBucketKeySchema).optional(),
57
+ buckets: z.partialRecord(CrmPriorityBucketKeySchema, CrmPriorityBucketOverrideSchema).optional(),
58
+ followUpAfterDaysByStateKey: z
59
+ .record(z.string().trim().min(1).max(120), z.number().int().min(0).max(365))
60
+ .optional(),
61
+ closedStageKeys: z.array(z.string().trim().min(1).max(120)).optional()
62
+ })
63
+ .strict()
64
+
65
+ export type CrmPriorityBucketOverride = z.infer<typeof CrmPriorityBucketOverrideSchema>
66
+ export type CrmPriorityOverride = z.infer<typeof CrmPriorityOverrideSchema>
67
+
68
+ /**
69
+ * Resolved CRM priority settings used by evaluators.
70
+ *
71
+ * When enabled is false, priority evaluation is intentionally neutral: all deals
72
+ * receive the configured waiting bucket and no follow-up/stale urgency is computed.
73
+ */
74
+ export type ResolvedCrmPriorityRuleConfig = CrmPriorityRuleConfig & {
75
+ enabled: boolean
76
+ }
77
+
78
+ interface ParsedActivity {
79
+ type: string | null
80
+ occurredAt: string
81
+ }
82
+
83
+ const MS_PER_DAY = 24 * 60 * 60 * 1000
84
+
85
+ const DEFAULT_CRM_PRIORITY_BUCKETS: CrmPriorityBucketDefinition[] = [
86
+ { bucketKey: 'needs_response', label: 'Needs Response', rank: 10, color: 'red' },
87
+ { bucketKey: 'follow_up_due', label: 'Follow-up Due', rank: 20, color: 'orange' },
88
+ { bucketKey: 'waiting', label: 'Waiting', rank: 30, color: 'blue' },
89
+ { bucketKey: 'stale', label: 'Stale', rank: 40, color: 'gray' },
90
+ { bucketKey: 'closed_low', label: 'Closed', rank: 50, color: 'dark' }
91
+ ]
92
+
93
+ const GENERIC_CRM_PRIORITY_RULE_CONFIG: CrmPriorityRuleConfig = {
94
+ buckets: DEFAULT_CRM_PRIORITY_BUCKETS,
95
+ closedStageKeys: [],
96
+ followUpAfterDaysByStateKey: {},
97
+ staleAfterDays: 14
98
+ }
99
+
100
+ export function evaluateCrmDealPriority(
101
+ input: CrmPriorityInput,
102
+ options: EvaluateCrmDealPriorityOptions = {}
103
+ ): DealPriority {
104
+ const config = resolveCrmPriorityRuleConfig(options.config)
105
+ const now = parseDate(options.now ?? new Date()) ?? new Date()
106
+ const latestActivityAt = getLatestActivityAt(input)
107
+ const nextActionAt = getNextActionAt(input.state_key, latestActivityAt, config)
108
+
109
+ if (!config.enabled) {
110
+ return buildPriority('waiting', config, {
111
+ reason: 'CRM priority evaluation is disabled.',
112
+ latestActivityAt,
113
+ nextActionAt: null
114
+ })
115
+ }
116
+
117
+ if (input.stage_key && config.closedStageKeys.includes(input.stage_key)) {
118
+ return buildPriority('closed_low', config, {
119
+ reason: `Deal is in ${input.stage_key}.`,
120
+ latestActivityAt,
121
+ nextActionAt: null
122
+ })
123
+ }
124
+
125
+ const ownership = getDealOwnership(input)
126
+
127
+ if (ownership === 'us') {
128
+ return buildPriority('needs_response', config, {
129
+ reason: 'Lead replied last — we owe the next move.',
130
+ latestActivityAt,
131
+ nextActionAt
132
+ })
133
+ }
134
+
135
+ // ownership === 'them' or null: check age against staleAfterDays first
136
+ if (latestActivityAt) {
137
+ const latestActivityDate = parseDate(latestActivityAt)
138
+ if (latestActivityDate && now.getTime() - latestActivityDate.getTime() >= config.staleAfterDays * MS_PER_DAY) {
139
+ return buildPriority('stale', config, {
140
+ reason: `No meaningful activity in ${config.staleAfterDays} days.`,
141
+ latestActivityAt,
142
+ nextActionAt: null
143
+ })
144
+ }
145
+ }
146
+
147
+ if (ownership === 'them') {
148
+ if (nextActionAt) {
149
+ const nextActionDate = parseDate(nextActionAt)
150
+ if (nextActionDate && nextActionDate <= now) {
151
+ return buildPriority('follow_up_due', config, {
152
+ reason: 'Configured follow-up window has elapsed.',
153
+ latestActivityAt,
154
+ nextActionAt
155
+ })
156
+ }
157
+ }
158
+
159
+ return buildPriority('waiting', config, {
160
+ reason: 'Waiting on their reply.',
161
+ latestActivityAt,
162
+ nextActionAt
163
+ })
164
+ }
165
+
166
+ // ownership === null (no inbound/outbound events): fall back to follow_up/waiting
167
+ if (nextActionAt) {
168
+ const nextActionDate = parseDate(nextActionAt)
169
+ if (nextActionDate && nextActionDate <= now) {
170
+ return buildPriority('follow_up_due', config, {
171
+ reason: 'Configured follow-up window has elapsed.',
172
+ latestActivityAt,
173
+ nextActionAt
174
+ })
175
+ }
176
+
177
+ return buildPriority('waiting', config, {
178
+ reason: 'Waiting until the configured next action time.',
179
+ latestActivityAt,
180
+ nextActionAt
181
+ })
182
+ }
183
+
184
+ return buildPriority('waiting', config, {
185
+ reason: 'No immediate response or follow-up is due.',
186
+ latestActivityAt,
187
+ nextActionAt: null
188
+ })
189
+ }
190
+
191
+ export function resolveCrmPriorityRuleConfig(
192
+ input?: unknown,
193
+ base: CrmPriorityRuleConfig = GENERIC_CRM_PRIORITY_RULE_CONFIG
194
+ ): ResolvedCrmPriorityRuleConfig {
195
+ const candidate = extractPriorityOverride(input)
196
+ const fullConfigResult = CrmPriorityRuleConfigSchema.safeParse(candidate)
197
+
198
+ if (fullConfigResult.success) return buildResolvedConfig(fullConfigResult.data)
199
+
200
+ const result = CrmPriorityOverrideSchema.safeParse(candidate)
201
+
202
+ if (!result.success) return buildResolvedConfig(base)
203
+
204
+ return mergeCrmPriorityOverride(result.data, base)
205
+ }
206
+
207
+ function mergeCrmPriorityOverride(
208
+ override: CrmPriorityOverride,
209
+ base: CrmPriorityRuleConfig = GENERIC_CRM_PRIORITY_RULE_CONFIG
210
+ ): ResolvedCrmPriorityRuleConfig {
211
+ const defaultConfig = buildResolvedConfig(base)
212
+ const bucketOverrides = override.buckets ?? {}
213
+ const orderedBucketKeys = override.bucketOrder ? [...new Set(override.bucketOrder)] : []
214
+ const orderRanks = new Map<CrmPriorityBucketKey, number>()
215
+
216
+ orderedBucketKeys.forEach((bucketKey, index) => {
217
+ orderRanks.set(bucketKey, (index + 1) * 10)
218
+ })
219
+
220
+ const buckets = defaultConfig.buckets
221
+ .map((bucket) => {
222
+ const bucketOverride = bucketOverrides[bucket.bucketKey]
223
+
224
+ return {
225
+ ...bucket,
226
+ rank: bucketOverride?.rank ?? orderRanks.get(bucket.bucketKey) ?? bucket.rank,
227
+ label: bucketOverride?.label ?? bucket.label,
228
+ color: bucketOverride?.color ?? bucket.color
229
+ }
230
+ })
231
+ .sort((a, b) => a.rank - b.rank)
232
+
233
+ return {
234
+ enabled: override.enabled ?? defaultConfig.enabled,
235
+ buckets,
236
+ closedStageKeys: override.closedStageKeys ?? defaultConfig.closedStageKeys,
237
+ followUpAfterDaysByStateKey: {
238
+ ...defaultConfig.followUpAfterDaysByStateKey,
239
+ ...(override.followUpAfterDaysByStateKey ?? {})
240
+ },
241
+ staleAfterDays: override.staleAfterDays ?? defaultConfig.staleAfterDays
242
+ }
243
+ }
244
+
245
+ function buildResolvedConfig(config: CrmPriorityRuleConfig & { enabled?: boolean }): ResolvedCrmPriorityRuleConfig {
246
+ return {
247
+ enabled: config.enabled ?? true,
248
+ buckets: config.buckets.map((bucket) => ({ ...bucket })),
249
+ closedStageKeys: [...config.closedStageKeys],
250
+ followUpAfterDaysByStateKey: { ...config.followUpAfterDaysByStateKey },
251
+ staleAfterDays: config.staleAfterDays
252
+ }
253
+ }
254
+
255
+ function extractPriorityOverride(input: unknown): unknown {
256
+ if (!isPlainRecord(input)) return input
257
+
258
+ const crm = input.crm
259
+ if (isPlainRecord(crm) && Object.prototype.hasOwnProperty.call(crm, 'priority')) {
260
+ return crm.priority
261
+ }
262
+
263
+ return input
264
+ }
265
+
266
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
267
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
268
+ }
269
+
270
+ function buildPriority(
271
+ bucketKey: CrmPriorityBucketKey,
272
+ config: CrmPriorityRuleConfig,
273
+ values: Pick<DealPriority, 'reason' | 'latestActivityAt' | 'nextActionAt'>
274
+ ): DealPriority {
275
+ const bucket = findBucket(config.buckets, bucketKey)
276
+
277
+ return {
278
+ bucketKey: bucket.bucketKey,
279
+ rank: bucket.rank,
280
+ label: bucket.label,
281
+ color: bucket.color,
282
+ reason: values.reason,
283
+ latestActivityAt: values.latestActivityAt,
284
+ nextActionAt: values.nextActionAt
285
+ }
286
+ }
287
+
288
+ function findBucket(
289
+ buckets: CrmPriorityBucketDefinition[],
290
+ bucketKey: CrmPriorityBucketKey
291
+ ): CrmPriorityBucketDefinition {
292
+ const bucket = buckets.find((candidate) => candidate.bucketKey === bucketKey)
293
+ if (bucket) return bucket
294
+
295
+ return {
296
+ bucketKey,
297
+ label: bucketKey,
298
+ rank: Number.MAX_SAFE_INTEGER,
299
+ color: 'gray'
300
+ }
301
+ }
302
+
303
+ function getLatestActivityAt(input: CrmPriorityInput): string | null {
304
+ const timestamps = getParsedActivities(input.activity_log).map((activity) => activity.occurredAt)
305
+ const fallback = normalizeTimestamp(input.updated_at) ?? normalizeTimestamp(input.created_at)
306
+ if (fallback) timestamps.push(fallback)
307
+
308
+ return timestamps.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())[0] ?? null
309
+ }
310
+
311
+ function getParsedActivities(activityLog: unknown): ParsedActivity[] {
312
+ if (!Array.isArray(activityLog)) return []
313
+
314
+ const parsed: ParsedActivity[] = []
315
+
316
+ for (const entry of activityLog) {
317
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
318
+
319
+ const record = entry as Record<string, unknown>
320
+ const occurredAt =
321
+ normalizeTimestamp(record.timestamp) ??
322
+ normalizeTimestamp(record.occurredAt) ??
323
+ normalizeTimestamp(record.createdAt) ??
324
+ normalizeTimestamp(record.updatedAt) ??
325
+ normalizeTimestamp(record.sentAt)
326
+
327
+ if (!occurredAt) continue
328
+
329
+ parsed.push({
330
+ type: typeof record.type === 'string' ? record.type : null,
331
+ occurredAt
332
+ })
333
+ }
334
+
335
+ return parsed
336
+ }
337
+
338
+ function getNextActionAt(
339
+ stateKey: string | null,
340
+ latestActivityAt: string | null,
341
+ config: CrmPriorityRuleConfig
342
+ ): string | null {
343
+ if (!stateKey || !latestActivityAt) return null
344
+
345
+ const days = config.followUpAfterDaysByStateKey[stateKey]
346
+ if (days === undefined) return null
347
+
348
+ const latestActivityDate = parseDate(latestActivityAt)
349
+ if (!latestActivityDate) return null
350
+
351
+ return new Date(latestActivityDate.getTime() + days * MS_PER_DAY).toISOString()
352
+ }
353
+
354
+ function normalizeTimestamp(value: unknown): string | null {
355
+ const date = parseDate(value)
356
+ return date ? date.toISOString() : null
357
+ }
358
+
359
+ function parseDate(value: unknown): Date | null {
360
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
361
+ if (typeof value !== 'string') return null
362
+
363
+ const date = new Date(value)
364
+ return Number.isNaN(date.getTime()) ? null : date
365
+ }