@elevasis/core 0.15.0 → 0.15.1
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/dist/index.d.ts +60 -0
- package/dist/index.js +198 -1
- package/dist/organization-model/index.d.ts +60 -0
- package/dist/organization-model/index.js +198 -1
- package/dist/test-utils/index.d.ts +399 -363
- package/dist/test-utils/index.js +198 -1
- package/package.json +3 -3
- package/src/_gen/__tests__/__snapshots__/contracts.md.snap +826 -703
- package/src/business/acquisition/activity-events.ts +12 -3
- package/src/business/acquisition/api-schemas.test.ts +315 -4
- package/src/business/acquisition/api-schemas.ts +1192 -1097
- package/src/business/acquisition/build-templates.ts +44 -0
- package/src/business/acquisition/crm-next-action.test.ts +262 -0
- package/src/business/acquisition/crm-next-action.ts +220 -0
- package/src/business/acquisition/crm-priority.test.ts +216 -0
- package/src/business/acquisition/crm-priority.ts +349 -0
- package/src/business/acquisition/crm-state-actions.test.ts +12 -21
- package/src/business/acquisition/deal-ownership.test.ts +351 -0
- package/src/business/acquisition/deal-ownership.ts +120 -0
- package/src/business/acquisition/derive-actions.test.ts +101 -37
- package/src/business/acquisition/derive-actions.ts +102 -87
- package/src/business/acquisition/index.ts +10 -0
- package/src/business/acquisition/types.ts +51 -8
- package/src/execution/engine/index.ts +4 -3
- package/src/execution/engine/tools/lead-service-types.ts +44 -30
- package/src/execution/engine/tools/platform/acquisition/list-tools.ts +6 -5
- package/src/execution/engine/tools/platform/acquisition/types.ts +3 -1
- package/src/execution/engine/tools/registry.ts +4 -3
- package/src/execution/engine/tools/tool-maps.ts +3 -1
- package/src/organization-model/domains/prospecting.ts +204 -1
- package/src/organization-model/domains/sales.test.ts +29 -0
- package/src/organization-model/domains/sales.ts +102 -0
- package/src/organization-model/types.ts +2 -2
- package/src/platform/constants/versions.ts +1 -1
- package/src/reference/_generated/contracts.md +826 -703
- package/src/supabase/database.types.ts +2978 -2958
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { DEFAULT_ORGANIZATION_MODEL_PROSPECTING } from '../../organization-model/domains/prospecting'
|
|
2
|
+
import type { BuildPlanSnapshot, BuildPlanSnapshotStep } from './types'
|
|
3
|
+
|
|
4
|
+
export const PROSPECTING_BUILD_TEMPLATE_OPTIONS = DEFAULT_ORGANIZATION_MODEL_PROSPECTING.buildTemplates.map(
|
|
5
|
+
({ id, label, description }) => ({
|
|
6
|
+
id,
|
|
7
|
+
label,
|
|
8
|
+
description
|
|
9
|
+
})
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_PROSPECTING_BUILD_TEMPLATE_ID = DEFAULT_ORGANIZATION_MODEL_PROSPECTING.defaultBuildTemplateId
|
|
13
|
+
|
|
14
|
+
export function isProspectingBuildTemplateId(value: string): boolean {
|
|
15
|
+
return PROSPECTING_BUILD_TEMPLATE_OPTIONS.some((template) => template.id === value)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createBuildPlanSnapshotFromTemplateId(templateId: string): BuildPlanSnapshot | null {
|
|
19
|
+
const template = DEFAULT_ORGANIZATION_MODEL_PROSPECTING.buildTemplates.find((item) => item.id === templateId)
|
|
20
|
+
if (!template) return null
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
templateId: template.id,
|
|
24
|
+
templateLabel: template.label,
|
|
25
|
+
steps: template.steps.map((step): BuildPlanSnapshotStep => {
|
|
26
|
+
const snapshotStep: BuildPlanSnapshotStep = {
|
|
27
|
+
id: step.id,
|
|
28
|
+
label: step.label,
|
|
29
|
+
primaryEntity: step.primaryEntity,
|
|
30
|
+
outputs: [...step.outputs],
|
|
31
|
+
stageKey: step.stageKey,
|
|
32
|
+
dependencyMode: step.dependencyMode,
|
|
33
|
+
capabilityKey: step.capabilityKey,
|
|
34
|
+
defaultBatchSize: step.defaultBatchSize,
|
|
35
|
+
maxBatchSize: step.maxBatchSize
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (step.description) snapshotStep.description = step.description
|
|
39
|
+
if (step.dependsOn?.length) snapshotStep.dependsOn = [...step.dependsOn]
|
|
40
|
+
|
|
41
|
+
return snapshotStep
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { evaluateCrmDealNextAction, resolveCrmNextActionRuleConfig } from './crm-next-action'
|
|
3
|
+
import { DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG } from '../../organization-model/domains/sales'
|
|
4
|
+
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
// Helpers
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
function makeEvent(type: string, timestamp: string): Record<string, unknown> {
|
|
10
|
+
return { type, timestamp }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const INBOUND = 'reply_received'
|
|
14
|
+
const OUTBOUND = 'reply_sent_to_lead'
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Closed deals → null
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
describe('evaluateCrmDealNextAction — closed deals', () => {
|
|
21
|
+
it('returns null for closed_won regardless of activity', () => {
|
|
22
|
+
expect(
|
|
23
|
+
evaluateCrmDealNextAction({
|
|
24
|
+
stage_key: 'interested',
|
|
25
|
+
state_key: 'closed_won',
|
|
26
|
+
activity_log: [makeEvent(INBOUND, '2026-01-10T10:00:00Z')]
|
|
27
|
+
})
|
|
28
|
+
).toBeNull()
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns null for closed_lost regardless of activity', () => {
|
|
32
|
+
expect(
|
|
33
|
+
evaluateCrmDealNextAction({
|
|
34
|
+
stage_key: 'interested',
|
|
35
|
+
state_key: 'closed_lost',
|
|
36
|
+
activity_log: [makeEvent(INBOUND, '2026-01-10T10:00:00Z')]
|
|
37
|
+
})
|
|
38
|
+
).toBeNull()
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('returns null for closed stages even when state_key is still actionable', () => {
|
|
42
|
+
expect(
|
|
43
|
+
evaluateCrmDealNextAction({
|
|
44
|
+
stage_key: 'closed_won',
|
|
45
|
+
state_key: 'discovery_replied',
|
|
46
|
+
activity_log: [makeEvent(INBOUND, '2026-01-10T10:00:00Z')]
|
|
47
|
+
})
|
|
48
|
+
).toBeNull()
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('returns null when activity_log is empty (ownership null)', () => {
|
|
52
|
+
expect(
|
|
53
|
+
evaluateCrmDealNextAction({
|
|
54
|
+
stage_key: 'interested',
|
|
55
|
+
state_key: 'discovery_replied',
|
|
56
|
+
activity_log: []
|
|
57
|
+
})
|
|
58
|
+
).toBeNull()
|
|
59
|
+
})
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// (state_key, ownership) mapping table
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
describe('evaluateCrmDealNextAction — mapping table', () => {
|
|
67
|
+
it('(discovery_replied, us) → send_reply', () => {
|
|
68
|
+
const result = evaluateCrmDealNextAction({
|
|
69
|
+
stage_key: 'interested',
|
|
70
|
+
state_key: 'discovery_replied',
|
|
71
|
+
activity_log: [makeEvent(INBOUND, '2026-04-20T10:00:00Z')]
|
|
72
|
+
})
|
|
73
|
+
expect(result).toBe('send_reply')
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('(discovery_nudging, them) → send_nudge', () => {
|
|
77
|
+
const result = evaluateCrmDealNextAction({
|
|
78
|
+
stage_key: 'interested',
|
|
79
|
+
state_key: 'discovery_nudging',
|
|
80
|
+
activity_log: [makeEvent(OUTBOUND, '2026-04-20T10:00:00Z')]
|
|
81
|
+
})
|
|
82
|
+
expect(result).toBe('send_nudge')
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('(discovery_link_sent, them) → send_nudge only after staleAfterDays', () => {
|
|
86
|
+
const recentActivity = '2026-04-29T10:00:00Z'
|
|
87
|
+
const now = new Date('2026-04-30T10:00:00Z')
|
|
88
|
+
|
|
89
|
+
// Age = 1 day — below staleAfterDays (14), no mapping fires → null fallback
|
|
90
|
+
// ownership === 'them' and no stale match → falls through to null
|
|
91
|
+
const notStale = evaluateCrmDealNextAction(
|
|
92
|
+
{
|
|
93
|
+
stage_key: 'interested',
|
|
94
|
+
state_key: 'discovery_link_sent',
|
|
95
|
+
activity_log: [makeEvent(OUTBOUND, recentActivity)]
|
|
96
|
+
},
|
|
97
|
+
{ now }
|
|
98
|
+
)
|
|
99
|
+
expect(notStale).toBeNull()
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('(discovery_link_sent, them) → send_nudge when age >= staleAfterDays', () => {
|
|
103
|
+
const oldActivity = '2026-04-01T10:00:00Z'
|
|
104
|
+
const now = new Date('2026-04-30T10:00:00Z') // 29 days later
|
|
105
|
+
|
|
106
|
+
const stale = evaluateCrmDealNextAction(
|
|
107
|
+
{
|
|
108
|
+
stage_key: 'interested',
|
|
109
|
+
state_key: 'discovery_link_sent',
|
|
110
|
+
activity_log: [makeEvent(OUTBOUND, oldActivity)]
|
|
111
|
+
},
|
|
112
|
+
{ now }
|
|
113
|
+
)
|
|
114
|
+
expect(stale).toBe('send_nudge')
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it('(*, us) → ownershipUsFallback send_reply when no explicit mapping matches', () => {
|
|
118
|
+
// reply_sent + inbound → ownership=us, state_key not in explicit mappings
|
|
119
|
+
const result = evaluateCrmDealNextAction({
|
|
120
|
+
stage_key: 'interested',
|
|
121
|
+
state_key: 'reply_sent',
|
|
122
|
+
activity_log: [makeEvent(INBOUND, '2026-04-20T10:00:00Z')]
|
|
123
|
+
})
|
|
124
|
+
expect(result).toBe('send_reply')
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('(followup_1_sent, us) → send_reply via fallback', () => {
|
|
128
|
+
const result = evaluateCrmDealNextAction({
|
|
129
|
+
stage_key: 'interested',
|
|
130
|
+
state_key: 'followup_1_sent',
|
|
131
|
+
activity_log: [makeEvent(INBOUND, '2026-04-20T10:00:00Z')]
|
|
132
|
+
})
|
|
133
|
+
expect(result).toBe('send_reply')
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
it('returns null when ownership is them and no mapping matches and not stale', () => {
|
|
137
|
+
const result = evaluateCrmDealNextAction({
|
|
138
|
+
stage_key: 'interested',
|
|
139
|
+
state_key: 'followup_2_sent',
|
|
140
|
+
activity_log: [makeEvent(OUTBOUND, '2026-04-29T10:00:00Z')]
|
|
141
|
+
})
|
|
142
|
+
expect(result).toBeNull()
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// ageDays option
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
describe('evaluateCrmDealNextAction — ageDays option', () => {
|
|
151
|
+
it('uses supplied ageDays instead of computing from activity_log', () => {
|
|
152
|
+
// discovery_link_sent + them + ageDays=20 (>=14) → send_nudge
|
|
153
|
+
const result = evaluateCrmDealNextAction(
|
|
154
|
+
{
|
|
155
|
+
stage_key: 'interested',
|
|
156
|
+
state_key: 'discovery_link_sent',
|
|
157
|
+
activity_log: [makeEvent(OUTBOUND, '2026-04-29T10:00:00Z')]
|
|
158
|
+
},
|
|
159
|
+
{ ageDays: 20 }
|
|
160
|
+
)
|
|
161
|
+
expect(result).toBe('send_nudge')
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it('requiresStale blocks when ageDays=0', () => {
|
|
165
|
+
const result = evaluateCrmDealNextAction(
|
|
166
|
+
{
|
|
167
|
+
stage_key: 'interested',
|
|
168
|
+
state_key: 'discovery_link_sent',
|
|
169
|
+
activity_log: [makeEvent(OUTBOUND, '2026-04-29T10:00:00Z')]
|
|
170
|
+
},
|
|
171
|
+
{ ageDays: 0 }
|
|
172
|
+
)
|
|
173
|
+
expect(result).toBeNull()
|
|
174
|
+
})
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
// resolveCrmNextActionRuleConfig — defaults
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
describe('resolveCrmNextActionRuleConfig — defaults', () => {
|
|
182
|
+
it('returns default config when called with no input', () => {
|
|
183
|
+
const config = resolveCrmNextActionRuleConfig()
|
|
184
|
+
expect(config.ownershipUsFallback).toBe(DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.ownershipUsFallback)
|
|
185
|
+
expect(config.mappings).toHaveLength(DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.mappings.length)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('returns default config for invalid input', () => {
|
|
189
|
+
const config = resolveCrmNextActionRuleConfig('not-an-object')
|
|
190
|
+
expect(config.ownershipUsFallback).toBe(DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.ownershipUsFallback)
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
it('accepts a full CrmNextActionRuleConfig directly', () => {
|
|
194
|
+
const full = {
|
|
195
|
+
mappings: [{ stateKey: 'foo', ownership: 'us' as const, actionKey: 'bar' }],
|
|
196
|
+
ownershipUsFallback: 'bar'
|
|
197
|
+
}
|
|
198
|
+
const config = resolveCrmNextActionRuleConfig(full)
|
|
199
|
+
expect(config.ownershipUsFallback).toBe('bar')
|
|
200
|
+
expect(config.mappings).toHaveLength(1)
|
|
201
|
+
})
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
// Per-org override merging
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
describe('resolveCrmNextActionRuleConfig — per-org override', () => {
|
|
209
|
+
it('prepends org mappings before defaults (org rules win on first-match)', () => {
|
|
210
|
+
const orgConfig = {
|
|
211
|
+
crm: {
|
|
212
|
+
next_actions: {
|
|
213
|
+
mappings: [{ stateKey: 'discovery_replied', ownership: 'us' as const, actionKey: 'custom_action' }]
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const config = resolveCrmNextActionRuleConfig(orgConfig)
|
|
218
|
+
// Org mapping should appear first
|
|
219
|
+
expect(config.mappings[0].actionKey).toBe('custom_action')
|
|
220
|
+
// Default mappings still present after org ones
|
|
221
|
+
expect(config.mappings.length).toBeGreaterThan(1)
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
it('overrides ownershipUsFallback when supplied', () => {
|
|
225
|
+
const orgConfig = {
|
|
226
|
+
crm: {
|
|
227
|
+
next_actions: {
|
|
228
|
+
ownershipUsFallback: 'org_custom_reply'
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const config = resolveCrmNextActionRuleConfig(orgConfig)
|
|
233
|
+
expect(config.ownershipUsFallback).toBe('org_custom_reply')
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
it('org override fires over default for same (state_key, ownership) pair', () => {
|
|
237
|
+
// Org remaps (discovery_replied, us) → 'org_reply'
|
|
238
|
+
const result = evaluateCrmDealNextAction(
|
|
239
|
+
{
|
|
240
|
+
stage_key: 'interested',
|
|
241
|
+
state_key: 'discovery_replied',
|
|
242
|
+
activity_log: [makeEvent(INBOUND, '2026-04-20T10:00:00Z')]
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
config: {
|
|
246
|
+
crm: {
|
|
247
|
+
next_actions: {
|
|
248
|
+
mappings: [{ stateKey: 'discovery_replied', ownership: 'us', actionKey: 'org_reply' }]
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
)
|
|
254
|
+
expect(result).toBe('org_reply')
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
it('falls back to defaults when org override is empty object', () => {
|
|
258
|
+
const config = resolveCrmNextActionRuleConfig({ crm: { next_actions: {} } })
|
|
259
|
+
expect(config.mappings).toHaveLength(DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.mappings.length)
|
|
260
|
+
expect(config.ownershipUsFallback).toBe(DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.ownershipUsFallback)
|
|
261
|
+
})
|
|
262
|
+
})
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// CRM Next-Action evaluator — mirrors the crm-priority.ts resolver/evaluator
|
|
3
|
+
// pattern. Maps (state_key, ownership) → suggested action key string.
|
|
4
|
+
//
|
|
5
|
+
// Per-org overrides live at organizations.config.crm.next_actions and are
|
|
6
|
+
// merged at evaluator read time via resolveCrmNextActionRuleConfig.
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
import { z } from 'zod'
|
|
10
|
+
import {
|
|
11
|
+
DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG,
|
|
12
|
+
type CrmNextActionRuleConfig,
|
|
13
|
+
type CrmNextActionMapping
|
|
14
|
+
} from '../../organization-model/domains/sales'
|
|
15
|
+
import { getDealOwnership } from './deal-ownership'
|
|
16
|
+
import type { DealOwnership } from './deal-ownership'
|
|
17
|
+
|
|
18
|
+
export interface CrmNextActionInput {
|
|
19
|
+
stage_key: string | null
|
|
20
|
+
state_key: string | null
|
|
21
|
+
activity_log: unknown
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface EvaluateCrmDealNextActionOptions {
|
|
25
|
+
config?: CrmNextActionRuleConfig | unknown
|
|
26
|
+
now?: Date | string
|
|
27
|
+
/** Current age in days — computed from activity_log if not supplied. */
|
|
28
|
+
ageDays?: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Zod schemas for the rule config (used by the resolver)
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
const CrmNextActionMappingSchema = z
|
|
36
|
+
.object({
|
|
37
|
+
stateKey: z.string().trim().min(1).max(120),
|
|
38
|
+
ownership: z.enum(['us', 'them', '*']),
|
|
39
|
+
actionKey: z.string().trim().min(1).max(120),
|
|
40
|
+
requiresStale: z.boolean().optional()
|
|
41
|
+
})
|
|
42
|
+
.strict()
|
|
43
|
+
|
|
44
|
+
const CrmNextActionRuleConfigSchema = z
|
|
45
|
+
.object({
|
|
46
|
+
mappings: z.array(CrmNextActionMappingSchema),
|
|
47
|
+
ownershipUsFallback: z.string().trim().min(1).max(120)
|
|
48
|
+
})
|
|
49
|
+
.strict()
|
|
50
|
+
|
|
51
|
+
// Partial override shape accepted from organizations.config.crm.next_actions
|
|
52
|
+
export const CrmNextActionOverrideSchema = z
|
|
53
|
+
.object({
|
|
54
|
+
mappings: z.array(CrmNextActionMappingSchema).optional(),
|
|
55
|
+
ownershipUsFallback: z.string().trim().min(1).max(120).optional()
|
|
56
|
+
})
|
|
57
|
+
.strict()
|
|
58
|
+
|
|
59
|
+
export type CrmNextActionOverride = z.infer<typeof CrmNextActionOverrideSchema>
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Resolved next-action config. Always has all required fields populated.
|
|
63
|
+
* `mappings` is the merged list: org overrides prepended before defaults so
|
|
64
|
+
* org-specific rules win on first-match evaluation.
|
|
65
|
+
*/
|
|
66
|
+
export type ResolvedCrmNextActionRuleConfig = CrmNextActionRuleConfig
|
|
67
|
+
|
|
68
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
// Public API
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Evaluates the suggested next action for a deal.
|
|
76
|
+
*
|
|
77
|
+
* Returns the action key string (matching a key in DEFAULT_CRM_ACTIONS), or
|
|
78
|
+
* null for closed deals or when no mapping matches.
|
|
79
|
+
*
|
|
80
|
+
* Closed deals (ownership === null due to closed stage_key) return null
|
|
81
|
+
* immediately — ownership derivation short-circuits on closed_won/closed_lost.
|
|
82
|
+
*/
|
|
83
|
+
export function evaluateCrmDealNextAction(
|
|
84
|
+
input: CrmNextActionInput,
|
|
85
|
+
options: EvaluateCrmDealNextActionOptions = {}
|
|
86
|
+
): string | null {
|
|
87
|
+
if (isClosedDeal(input)) return null
|
|
88
|
+
|
|
89
|
+
const config = resolveCrmNextActionRuleConfig(options.config)
|
|
90
|
+
const ownership = getDealOwnership(input)
|
|
91
|
+
|
|
92
|
+
// No ownership signal: staleAfterDays fallback is intentionally not applied here.
|
|
93
|
+
if (ownership === null) return null
|
|
94
|
+
|
|
95
|
+
const ageDays = options.ageDays ?? computeAgeDays(input, options.now)
|
|
96
|
+
|
|
97
|
+
return (
|
|
98
|
+
evaluateMappings(config.mappings, input.state_key, ownership, ageDays, 14) ??
|
|
99
|
+
(ownership === 'us' ? config.ownershipUsFallback : null)
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Resolves the next-action rule config from an org config input.
|
|
105
|
+
*
|
|
106
|
+
* Accepts:
|
|
107
|
+
* - Full CrmNextActionRuleConfig (used directly after validation)
|
|
108
|
+
* - Partial CrmNextActionOverride (merged on top of defaults)
|
|
109
|
+
* - Nested org config: { crm: { next_actions: ... } }
|
|
110
|
+
* - Any other value → falls back to defaults
|
|
111
|
+
*/
|
|
112
|
+
export function resolveCrmNextActionRuleConfig(input?: unknown): ResolvedCrmNextActionRuleConfig {
|
|
113
|
+
const candidate = extractNextActionOverride(input)
|
|
114
|
+
const fullResult = CrmNextActionRuleConfigSchema.safeParse(candidate)
|
|
115
|
+
|
|
116
|
+
if (fullResult.success) return fullResult.data
|
|
117
|
+
|
|
118
|
+
const overrideResult = CrmNextActionOverrideSchema.safeParse(candidate)
|
|
119
|
+
|
|
120
|
+
if (!overrideResult.success) return { ...DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG }
|
|
121
|
+
|
|
122
|
+
return mergeNextActionOverride(overrideResult.data)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
// Internal helpers
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
function evaluateMappings(
|
|
130
|
+
mappings: CrmNextActionMapping[],
|
|
131
|
+
stateKey: string | null,
|
|
132
|
+
ownership: Exclude<DealOwnership, null>,
|
|
133
|
+
ageDays: number,
|
|
134
|
+
staleAfterDays: number
|
|
135
|
+
): string | null {
|
|
136
|
+
for (const mapping of mappings) {
|
|
137
|
+
const stateMatches = mapping.stateKey === '*' || mapping.stateKey === stateKey
|
|
138
|
+
const ownershipMatches = mapping.ownership === '*' || mapping.ownership === ownership
|
|
139
|
+
const staleOk = !mapping.requiresStale || ageDays >= staleAfterDays
|
|
140
|
+
|
|
141
|
+
if (stateMatches && ownershipMatches && staleOk) {
|
|
142
|
+
return mapping.actionKey
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isClosedDeal(input: CrmNextActionInput): boolean {
|
|
150
|
+
return (
|
|
151
|
+
input.stage_key === 'closed_won' ||
|
|
152
|
+
input.stage_key === 'closed_lost' ||
|
|
153
|
+
input.state_key === 'closed_won' ||
|
|
154
|
+
input.state_key === 'closed_lost'
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function mergeNextActionOverride(override: CrmNextActionOverride): ResolvedCrmNextActionRuleConfig {
|
|
159
|
+
// Org mappings are prepended so they win on first-match evaluation.
|
|
160
|
+
const mappings = [...(override.mappings ?? []), ...DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.mappings]
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
mappings,
|
|
164
|
+
ownershipUsFallback: override.ownershipUsFallback ?? DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG.ownershipUsFallback
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function extractNextActionOverride(input: unknown): unknown {
|
|
169
|
+
if (!isPlainRecord(input)) return input
|
|
170
|
+
|
|
171
|
+
const crm = input.crm
|
|
172
|
+
if (isPlainRecord(crm) && Object.prototype.hasOwnProperty.call(crm, 'next_actions')) {
|
|
173
|
+
return crm.next_actions
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return input
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
180
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function computeAgeDays(input: CrmNextActionInput, now?: Date | string): number {
|
|
184
|
+
const nowMs = parseMs(now ?? new Date())
|
|
185
|
+
if (nowMs === null) return 0
|
|
186
|
+
|
|
187
|
+
if (!Array.isArray(input.activity_log) || input.activity_log.length === 0) return 0
|
|
188
|
+
|
|
189
|
+
let latestMs: number | null = null
|
|
190
|
+
|
|
191
|
+
for (const entry of input.activity_log) {
|
|
192
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
|
|
193
|
+
|
|
194
|
+
const record = entry as Record<string, unknown>
|
|
195
|
+
const ms =
|
|
196
|
+
parseMs(record.timestamp) ??
|
|
197
|
+
parseMs(record.occurredAt) ??
|
|
198
|
+
parseMs(record.createdAt) ??
|
|
199
|
+
parseMs(record.updatedAt) ??
|
|
200
|
+
parseMs(record.sentAt)
|
|
201
|
+
|
|
202
|
+
if (ms !== null && (latestMs === null || ms > latestMs)) {
|
|
203
|
+
latestMs = ms
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (latestMs === null) return 0
|
|
208
|
+
|
|
209
|
+
return Math.max(0, (nowMs - latestMs) / MS_PER_DAY)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function parseMs(value: unknown): number | null {
|
|
213
|
+
if (value instanceof Date) {
|
|
214
|
+
const ms = value.getTime()
|
|
215
|
+
return Number.isNaN(ms) ? null : ms
|
|
216
|
+
}
|
|
217
|
+
if (typeof value !== 'string') return null
|
|
218
|
+
const ms = new Date(value).getTime()
|
|
219
|
+
return Number.isNaN(ms) ? null : ms
|
|
220
|
+
}
|