@elevasis/core 0.14.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.
Files changed (36) hide show
  1. package/dist/index.d.ts +60 -0
  2. package/dist/index.js +198 -1
  3. package/dist/organization-model/index.d.ts +60 -0
  4. package/dist/organization-model/index.js +198 -1
  5. package/dist/test-utils/index.d.ts +399 -363
  6. package/dist/test-utils/index.js +198 -1
  7. package/package.json +3 -3
  8. package/src/_gen/__tests__/__snapshots__/contracts.md.snap +444 -309
  9. package/src/business/acquisition/activity-events.ts +12 -3
  10. package/src/business/acquisition/api-schemas.test.ts +315 -4
  11. package/src/business/acquisition/api-schemas.ts +140 -17
  12. package/src/business/acquisition/build-templates.ts +44 -0
  13. package/src/business/acquisition/crm-next-action.test.ts +262 -0
  14. package/src/business/acquisition/crm-next-action.ts +220 -0
  15. package/src/business/acquisition/crm-priority.test.ts +216 -0
  16. package/src/business/acquisition/crm-priority.ts +349 -0
  17. package/src/business/acquisition/crm-state-actions.test.ts +12 -21
  18. package/src/business/acquisition/deal-ownership.test.ts +351 -0
  19. package/src/business/acquisition/deal-ownership.ts +120 -0
  20. package/src/business/acquisition/derive-actions.test.ts +101 -37
  21. package/src/business/acquisition/derive-actions.ts +49 -24
  22. package/src/business/acquisition/index.ts +163 -149
  23. package/src/business/acquisition/types.ts +48 -4
  24. package/src/execution/engine/index.ts +4 -3
  25. package/src/execution/engine/tools/lead-service-types.ts +68 -51
  26. package/src/execution/engine/tools/platform/acquisition/list-tools.ts +6 -5
  27. package/src/execution/engine/tools/platform/acquisition/types.ts +3 -1
  28. package/src/execution/engine/tools/registry.ts +4 -3
  29. package/src/execution/engine/tools/tool-maps.ts +821 -816
  30. package/src/organization-model/domains/prospecting.ts +204 -1
  31. package/src/organization-model/domains/sales.test.ts +218 -0
  32. package/src/organization-model/domains/sales.ts +558 -366
  33. package/src/organization-model/types.ts +2 -2
  34. package/src/platform/constants/versions.ts +1 -1
  35. package/src/reference/_generated/contracts.md +444 -309
  36. package/src/supabase/database.types.ts +2978 -2958
@@ -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
+ }
@@ -0,0 +1,216 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { evaluateCrmDealPriority, resolveCrmPriorityRuleConfig } from './crm-priority'
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // Helpers
6
+ // ---------------------------------------------------------------------------
7
+
8
+ function makeEvent(type: string, timestamp: string): Record<string, unknown> {
9
+ return { type, timestamp }
10
+ }
11
+
12
+ const INBOUND = 'reply_received'
13
+ const OUTBOUND = 'reply_sent_to_lead'
14
+ const NOW = '2026-04-30T12:00:00.000Z'
15
+
16
+ function makeDeal(
17
+ overrides: Partial<{
18
+ stage_key: string | null
19
+ state_key: string | null
20
+ activity_log: unknown[]
21
+ updated_at: string
22
+ created_at: string
23
+ }> = {}
24
+ ) {
25
+ return {
26
+ stage_key: overrides.stage_key ?? 'interested',
27
+ state_key: overrides.state_key ?? 'discovery_replied',
28
+ activity_log: overrides.activity_log ?? [],
29
+ updated_at: overrides.updated_at ?? NOW,
30
+ created_at: overrides.created_at ?? NOW
31
+ }
32
+ }
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Closed deals → closed_low
36
+ // ---------------------------------------------------------------------------
37
+
38
+ describe('evaluateCrmDealPriority — closed deals', () => {
39
+ it('returns closed_low for closed_won stage', () => {
40
+ const result = evaluateCrmDealPriority(makeDeal({ stage_key: 'closed_won' }), { now: NOW })
41
+ expect(result.bucketKey).toBe('closed_low')
42
+ })
43
+
44
+ it('returns closed_low for closed_lost stage', () => {
45
+ const result = evaluateCrmDealPriority(makeDeal({ stage_key: 'closed_lost' }), { now: NOW })
46
+ expect(result.bucketKey).toBe('closed_low')
47
+ })
48
+ })
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // needs_response — ownership === 'us'
52
+ // ---------------------------------------------------------------------------
53
+
54
+ describe('evaluateCrmDealPriority — needs_response (ownership === us)', () => {
55
+ it('returns needs_response when lead replied last (inbound after outbound)', () => {
56
+ const result = evaluateCrmDealPriority(
57
+ makeDeal({
58
+ state_key: 'discovery_replied',
59
+ activity_log: [makeEvent(OUTBOUND, '2026-04-28T10:00:00Z'), makeEvent(INBOUND, '2026-04-29T10:00:00Z')]
60
+ }),
61
+ { now: NOW }
62
+ )
63
+ expect(result.bucketKey).toBe('needs_response')
64
+ })
65
+
66
+ it('returns needs_response when only inbound event present', () => {
67
+ const result = evaluateCrmDealPriority(
68
+ makeDeal({
69
+ state_key: 'discovery_replied',
70
+ activity_log: [makeEvent(INBOUND, '2026-04-29T10:00:00Z')]
71
+ }),
72
+ { now: NOW }
73
+ )
74
+ expect(result.bucketKey).toBe('needs_response')
75
+ })
76
+
77
+ it('returns needs_response regardless of state_key when ownership is us', () => {
78
+ // reply_sent is normally a "we acted" state, but if a new inbound arrives ownership flips
79
+ const result = evaluateCrmDealPriority(
80
+ makeDeal({
81
+ state_key: 'reply_sent',
82
+ activity_log: [makeEvent(OUTBOUND, '2026-04-27T10:00:00Z'), makeEvent(INBOUND, '2026-04-29T10:00:00Z')]
83
+ }),
84
+ { now: NOW }
85
+ )
86
+ expect(result.bucketKey).toBe('needs_response')
87
+ })
88
+ })
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // waiting — ownership === 'them' AND age < staleAfterDays
92
+ // ---------------------------------------------------------------------------
93
+
94
+ describe('evaluateCrmDealPriority — waiting (ownership === them, not stale)', () => {
95
+ it('returns waiting when we replied last and age is below staleAfterDays', () => {
96
+ const result = evaluateCrmDealPriority(
97
+ makeDeal({
98
+ state_key: 'reply_sent',
99
+ // No followUpAfterDaysByStateKey entry for reply_sent within window
100
+ activity_log: [makeEvent(OUTBOUND, '2026-04-29T10:00:00Z')]
101
+ }),
102
+ { now: NOW }
103
+ )
104
+ // Age = 1 day, staleAfterDays = 14 → waiting
105
+ // reply_sent has followUpAfterDaysByStateKey=3, nextActionAt is 2026-05-02, not yet due
106
+ expect(result.bucketKey).toBe('waiting')
107
+ })
108
+
109
+ it('returns follow_up_due when follow-up window elapses (ownership them)', () => {
110
+ // discovery_link_sent: followUpAfterDaysByStateKey = 3
111
+ // Activity at 2026-04-26, now = 2026-04-30 → age 4 days → nextActionAt = 2026-04-29 (past)
112
+ // updated_at set before activity so latestActivityAt comes from activity_log
113
+ const result = evaluateCrmDealPriority(
114
+ makeDeal({
115
+ state_key: 'discovery_link_sent',
116
+ activity_log: [makeEvent(OUTBOUND, '2026-04-26T10:00:00Z')],
117
+ updated_at: '2026-04-25T00:00:00Z',
118
+ created_at: '2026-04-25T00:00:00Z'
119
+ }),
120
+ { now: NOW }
121
+ )
122
+ expect(result.bucketKey).toBe('follow_up_due')
123
+ })
124
+ })
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // stale — ownership === 'them' AND age >= staleAfterDays
128
+ // ---------------------------------------------------------------------------
129
+
130
+ describe('evaluateCrmDealPriority — stale (ownership them, age >= staleAfterDays)', () => {
131
+ it('returns stale when we sent last and age >= staleAfterDays', () => {
132
+ // Activity at 2026-04-10, now = 2026-04-30 → age 20 days >= staleAfterDays 14
133
+ // updated_at set before activity so latestActivityAt comes from activity_log
134
+ const result = evaluateCrmDealPriority(
135
+ makeDeal({
136
+ state_key: 'reply_sent',
137
+ activity_log: [makeEvent(OUTBOUND, '2026-04-10T10:00:00Z')],
138
+ updated_at: '2026-04-09T00:00:00Z',
139
+ created_at: '2026-04-09T00:00:00Z'
140
+ }),
141
+ { now: NOW }
142
+ )
143
+ expect(result.bucketKey).toBe('stale')
144
+ })
145
+ })
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // No activity (ownership null)
149
+ // ---------------------------------------------------------------------------
150
+
151
+ describe('evaluateCrmDealPriority — no ownership signal', () => {
152
+ it('returns waiting when no activity log', () => {
153
+ const result = evaluateCrmDealPriority(makeDeal({ activity_log: [] }), { now: NOW })
154
+ expect(result.bucketKey).toBe('waiting')
155
+ })
156
+
157
+ it('returns stale when no activity and updated_at is very old', () => {
158
+ const result = evaluateCrmDealPriority(
159
+ {
160
+ stage_key: 'interested',
161
+ state_key: 'discovery_replied',
162
+ activity_log: [],
163
+ updated_at: '2026-01-01T00:00:00Z',
164
+ created_at: '2026-01-01T00:00:00Z'
165
+ },
166
+ { now: NOW }
167
+ )
168
+ expect(result.bucketKey).toBe('stale')
169
+ })
170
+ })
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // disabled config
174
+ // ---------------------------------------------------------------------------
175
+
176
+ describe('evaluateCrmDealPriority — disabled config', () => {
177
+ it('returns waiting when config.enabled is false', () => {
178
+ const config = resolveCrmPriorityRuleConfig({ enabled: false })
179
+ const result = evaluateCrmDealPriority(makeDeal({ activity_log: [makeEvent(INBOUND, '2026-04-29T10:00:00Z')] }), {
180
+ now: NOW,
181
+ config
182
+ })
183
+ expect(result.bucketKey).toBe('waiting')
184
+ })
185
+ })
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // resolveCrmPriorityRuleConfig — override merging
189
+ // ---------------------------------------------------------------------------
190
+
191
+ describe('resolveCrmPriorityRuleConfig — override merging', () => {
192
+ it('merges staleAfterDays and closedStageKeys from org override', () => {
193
+ const config = resolveCrmPriorityRuleConfig({
194
+ crm: {
195
+ priority: {
196
+ staleAfterDays: 7,
197
+ closedStageKeys: ['custom_closed']
198
+ }
199
+ }
200
+ })
201
+ expect(config.staleAfterDays).toBe(7)
202
+ expect(config.closedStageKeys).toEqual(['custom_closed'])
203
+ })
204
+
205
+ it('falls back to defaults for invalid input', () => {
206
+ const config = resolveCrmPriorityRuleConfig('not-valid')
207
+ expect(config.staleAfterDays).toBe(14)
208
+ expect(config.enabled).toBe(true)
209
+ })
210
+
211
+ it('does not have needsResponseStateKeys or needsResponseActivityTypes', () => {
212
+ const config = resolveCrmPriorityRuleConfig()
213
+ expect(config).not.toHaveProperty('needsResponseStateKeys')
214
+ expect(config).not.toHaveProperty('needsResponseActivityTypes')
215
+ })
216
+ })