@elevasis/core 0.26.0 → 0.28.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 (49) hide show
  1. package/dist/index.d.ts +162 -105
  2. package/dist/index.js +280 -174
  3. package/dist/knowledge/index.d.ts +43 -43
  4. package/dist/organization-model/index.d.ts +162 -105
  5. package/dist/organization-model/index.js +280 -174
  6. package/dist/test-utils/index.d.ts +20 -20
  7. package/dist/test-utils/index.js +184 -126
  8. package/package.json +3 -3
  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__/define-domain-record.test.ts +289 -0
  25. package/src/organization-model/__tests__/om-spine-doc-contract.test.ts +56 -0
  26. package/src/organization-model/__tests__/published-zero-leak.test.ts +60 -1
  27. package/src/organization-model/__tests__/resolve.test.ts +1 -1
  28. package/src/organization-model/__tests__/schema-refinements.test.ts +72 -0
  29. package/src/organization-model/cross-ref.ts +175 -0
  30. package/src/organization-model/domains/actions.ts +13 -0
  31. package/src/organization-model/domains/branding.ts +6 -6
  32. package/src/organization-model/domains/customers.ts +95 -78
  33. package/src/organization-model/domains/entities.ts +157 -144
  34. package/src/organization-model/domains/goals.ts +100 -83
  35. package/src/organization-model/domains/knowledge.ts +106 -93
  36. package/src/organization-model/domains/offerings.ts +88 -71
  37. package/src/organization-model/domains/policies.ts +115 -102
  38. package/src/organization-model/domains/roles.ts +109 -96
  39. package/src/organization-model/domains/sales.test.ts +104 -218
  40. package/src/organization-model/domains/sales.ts +212 -375
  41. package/src/organization-model/domains/statuses.ts +351 -339
  42. package/src/organization-model/domains/systems.ts +176 -164
  43. package/src/organization-model/helpers.ts +331 -306
  44. package/src/organization-model/index.ts +43 -0
  45. package/src/organization-model/published.ts +27 -2
  46. package/src/organization-model/schema-refinements.ts +667 -0
  47. package/src/organization-model/schema.ts +8 -715
  48. package/src/platform/constants/versions.ts +1 -1
  49. package/src/reference/_generated/contracts.md +1000 -1087
@@ -1,6 +1,9 @@
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'
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ evaluateCrmDealNextAction as evaluateCrmDealNextActionCore,
4
+ resolveCrmNextActionRuleConfig
5
+ } from './crm-next-action'
6
+ import type { CrmNextActionRuleConfig } from '../../organization-model/domains/sales'
4
7
 
5
8
  // ---------------------------------------------------------------------------
6
9
  // Helpers
@@ -10,8 +13,26 @@ function makeEvent(type: string, timestamp: string): Record<string, unknown> {
10
13
  return { type, timestamp }
11
14
  }
12
15
 
13
- const INBOUND = 'reply_received'
14
- const OUTBOUND = 'reply_sent_to_lead'
16
+ const INBOUND = 'reply_received'
17
+ const OUTBOUND = 'reply_sent_to_lead'
18
+ const ELEVASIS_CRM_NEXT_ACTION_RULE_CONFIG: CrmNextActionRuleConfig = {
19
+ mappings: [
20
+ { stateKey: 'discovery_link_sent', ownership: 'them', actionKey: 'send_nudge', requiresStale: true },
21
+ { stateKey: 'discovery_replied', ownership: 'us', actionKey: 'send_reply' },
22
+ { stateKey: 'discovery_nudging', ownership: 'them', actionKey: 'send_nudge' }
23
+ ],
24
+ ownershipUsFallback: 'send_reply'
25
+ }
26
+
27
+ function evaluateCrmDealNextAction(
28
+ input: Parameters<typeof evaluateCrmDealNextActionCore>[0],
29
+ options: Parameters<typeof evaluateCrmDealNextActionCore>[1] = {}
30
+ ): string | null {
31
+ return evaluateCrmDealNextActionCore(input, {
32
+ config: ELEVASIS_CRM_NEXT_ACTION_RULE_CONFIG,
33
+ ...options
34
+ })
35
+ }
15
36
 
16
37
  // ---------------------------------------------------------------------------
17
38
  // Closed deals → null
@@ -179,16 +200,17 @@ describe('evaluateCrmDealNextAction — ageDays option', () => {
179
200
  // ---------------------------------------------------------------------------
180
201
 
181
202
  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
- })
203
+ it('returns generic empty config when called with no input', () => {
204
+ const config = resolveCrmNextActionRuleConfig()
205
+ expect(config.ownershipUsFallback).toBeNull()
206
+ expect(config.mappings).toEqual([])
207
+ })
208
+
209
+ it('returns generic empty config for invalid input', () => {
210
+ const config = resolveCrmNextActionRuleConfig('not-an-object')
211
+ expect(config.ownershipUsFallback).toBeNull()
212
+ expect(config.mappings).toEqual([])
213
+ })
192
214
 
193
215
  it('accepts a full CrmNextActionRuleConfig directly', () => {
194
216
  const full = {
@@ -206,7 +228,7 @@ describe('resolveCrmNextActionRuleConfig — defaults', () => {
206
228
  // ---------------------------------------------------------------------------
207
229
 
208
230
  describe('resolveCrmNextActionRuleConfig — per-org override', () => {
209
- it('prepends org mappings before defaults (org rules win on first-match)', () => {
231
+ it('uses org mappings without merging tenant defaults from core', () => {
210
232
  const orgConfig = {
211
233
  crm: {
212
234
  next_actions: {
@@ -215,10 +237,8 @@ describe('resolveCrmNextActionRuleConfig — per-org override', () => {
215
237
  }
216
238
  }
217
239
  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)
240
+ expect(config.mappings[0].actionKey).toBe('custom_action')
241
+ expect(config.mappings).toHaveLength(1)
222
242
  })
223
243
 
224
244
  it('overrides ownershipUsFallback when supplied', () => {
@@ -254,9 +274,9 @@ describe('resolveCrmNextActionRuleConfig — per-org override', () => {
254
274
  expect(result).toBe('org_reply')
255
275
  })
256
276
 
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
- })
277
+ it('falls back to generic empty config when org override is empty object', () => {
278
+ const config = resolveCrmNextActionRuleConfig({ crm: { next_actions: {} } })
279
+ expect(config.mappings).toEqual([])
280
+ expect(config.ownershipUsFallback).toBeNull()
281
+ })
262
282
  })
@@ -1,220 +1,227 @@
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
- }
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 { type CrmNextActionRuleConfig, type CrmNextActionMapping } from '../../organization-model/domains/sales'
11
+ import { getDealOwnership } from './deal-ownership'
12
+ import type { DealOwnership } from './deal-ownership'
13
+
14
+ export interface CrmNextActionInput {
15
+ stage_key: string | null
16
+ state_key: string | null
17
+ activity_log: unknown
18
+ }
19
+
20
+ export interface EvaluateCrmDealNextActionOptions {
21
+ config?: CrmNextActionRuleConfig | unknown
22
+ now?: Date | string
23
+ /** Current age in days — computed from activity_log if not supplied. */
24
+ ageDays?: number
25
+ }
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Zod schemas for the rule config (used by the resolver)
29
+ // ---------------------------------------------------------------------------
30
+
31
+ const CrmNextActionMappingSchema = z
32
+ .object({
33
+ stateKey: z.string().trim().min(1).max(120),
34
+ ownership: z.enum(['us', 'them', '*']),
35
+ actionKey: z.string().trim().min(1).max(120),
36
+ requiresStale: z.boolean().optional()
37
+ })
38
+ .strict()
39
+
40
+ const CrmNextActionRuleConfigSchema = z
41
+ .object({
42
+ mappings: z.array(CrmNextActionMappingSchema),
43
+ ownershipUsFallback: z.string().trim().min(1).max(120).nullable().optional()
44
+ })
45
+ .strict()
46
+
47
+ // Partial override shape accepted from organizations.config.crm.next_actions
48
+ export const CrmNextActionOverrideSchema = z
49
+ .object({
50
+ mappings: z.array(CrmNextActionMappingSchema).optional(),
51
+ ownershipUsFallback: z.string().trim().min(1).max(120).nullable().optional()
52
+ })
53
+ .strict()
54
+
55
+ export type CrmNextActionOverride = z.infer<typeof CrmNextActionOverrideSchema>
56
+
57
+ /**
58
+ * Resolved next-action config. Always has all required fields populated.
59
+ * `mappings` is the merged list: org overrides prepended before defaults so
60
+ * org-specific rules win on first-match evaluation.
61
+ */
62
+ export type ResolvedCrmNextActionRuleConfig = CrmNextActionRuleConfig
63
+
64
+ const MS_PER_DAY = 24 * 60 * 60 * 1000
65
+
66
+ const GENERIC_CRM_NEXT_ACTION_RULE_CONFIG: CrmNextActionRuleConfig = {
67
+ mappings: [],
68
+ ownershipUsFallback: null
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Public API
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /**
76
+ * Evaluates the suggested next action for a deal.
77
+ *
78
+ * Returns the action key string (matching a key in the caller's action catalog), or
79
+ * null for closed deals or when no mapping matches.
80
+ *
81
+ * Closed deals (ownership === null due to closed stage_key) return null
82
+ * immediately — ownership derivation short-circuits on closed_won/closed_lost.
83
+ */
84
+ export function evaluateCrmDealNextAction(
85
+ input: CrmNextActionInput,
86
+ options: EvaluateCrmDealNextActionOptions = {}
87
+ ): string | null {
88
+ if (isClosedDeal(input)) return null
89
+
90
+ const config = resolveCrmNextActionRuleConfig(options.config)
91
+ const ownership = getDealOwnership(input)
92
+
93
+ // No ownership signal: staleAfterDays fallback is intentionally not applied here.
94
+ if (ownership === null) return null
95
+
96
+ const ageDays = options.ageDays ?? computeAgeDays(input, options.now)
97
+
98
+ return (
99
+ evaluateMappings(config.mappings, input.state_key, ownership, ageDays, 14) ??
100
+ (ownership === 'us' ? (config.ownershipUsFallback ?? null) : null)
101
+ )
102
+ }
103
+
104
+ /**
105
+ * Resolves the next-action rule config from an org config input.
106
+ *
107
+ * Accepts:
108
+ * - Full CrmNextActionRuleConfig (used directly after validation)
109
+ * - Partial CrmNextActionOverride (merged on top of defaults)
110
+ * - Nested org config: { crm: { next_actions: ... } }
111
+ * - Any other value → falls back to defaults
112
+ */
113
+ export function resolveCrmNextActionRuleConfig(
114
+ input?: unknown,
115
+ base: CrmNextActionRuleConfig = GENERIC_CRM_NEXT_ACTION_RULE_CONFIG
116
+ ): ResolvedCrmNextActionRuleConfig {
117
+ const candidate = extractNextActionOverride(input)
118
+ const fullResult = CrmNextActionRuleConfigSchema.safeParse(candidate)
119
+
120
+ if (fullResult.success) return fullResult.data
121
+
122
+ const overrideResult = CrmNextActionOverrideSchema.safeParse(candidate)
123
+
124
+ if (!overrideResult.success) return { mappings: [...base.mappings], ownershipUsFallback: base.ownershipUsFallback }
125
+
126
+ return mergeNextActionOverride(overrideResult.data, base)
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Internal helpers
131
+ // ---------------------------------------------------------------------------
132
+
133
+ function evaluateMappings(
134
+ mappings: CrmNextActionMapping[],
135
+ stateKey: string | null,
136
+ ownership: Exclude<DealOwnership, null>,
137
+ ageDays: number,
138
+ staleAfterDays: number
139
+ ): string | null {
140
+ for (const mapping of mappings) {
141
+ const stateMatches = mapping.stateKey === '*' || mapping.stateKey === stateKey
142
+ const ownershipMatches = mapping.ownership === '*' || mapping.ownership === ownership
143
+ const staleOk = !mapping.requiresStale || ageDays >= staleAfterDays
144
+
145
+ if (stateMatches && ownershipMatches && staleOk) {
146
+ return mapping.actionKey
147
+ }
148
+ }
149
+
150
+ return null
151
+ }
152
+
153
+ function isClosedDeal(input: CrmNextActionInput): boolean {
154
+ return (
155
+ input.stage_key === 'closed_won' ||
156
+ input.stage_key === 'closed_lost' ||
157
+ input.state_key === 'closed_won' ||
158
+ input.state_key === 'closed_lost'
159
+ )
160
+ }
161
+
162
+ function mergeNextActionOverride(
163
+ override: CrmNextActionOverride,
164
+ base: CrmNextActionRuleConfig = GENERIC_CRM_NEXT_ACTION_RULE_CONFIG
165
+ ): ResolvedCrmNextActionRuleConfig {
166
+ // Org mappings are prepended so they win on first-match evaluation.
167
+ const mappings = [...(override.mappings ?? []), ...base.mappings]
168
+
169
+ return {
170
+ mappings,
171
+ ownershipUsFallback: override.ownershipUsFallback ?? base.ownershipUsFallback
172
+ }
173
+ }
174
+
175
+ function extractNextActionOverride(input: unknown): unknown {
176
+ if (!isPlainRecord(input)) return input
177
+
178
+ const crm = input.crm
179
+ if (isPlainRecord(crm) && Object.prototype.hasOwnProperty.call(crm, 'next_actions')) {
180
+ return crm.next_actions
181
+ }
182
+
183
+ return input
184
+ }
185
+
186
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
187
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
188
+ }
189
+
190
+ function computeAgeDays(input: CrmNextActionInput, now?: Date | string): number {
191
+ const nowMs = parseMs(now ?? new Date())
192
+ if (nowMs === null) return 0
193
+
194
+ if (!Array.isArray(input.activity_log) || input.activity_log.length === 0) return 0
195
+
196
+ let latestMs: number | null = null
197
+
198
+ for (const entry of input.activity_log) {
199
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
200
+
201
+ const record = entry as Record<string, unknown>
202
+ const ms =
203
+ parseMs(record.timestamp) ??
204
+ parseMs(record.occurredAt) ??
205
+ parseMs(record.createdAt) ??
206
+ parseMs(record.updatedAt) ??
207
+ parseMs(record.sentAt)
208
+
209
+ if (ms !== null && (latestMs === null || ms > latestMs)) {
210
+ latestMs = ms
211
+ }
212
+ }
213
+
214
+ if (latestMs === null) return 0
215
+
216
+ return Math.max(0, (nowMs - latestMs) / MS_PER_DAY)
217
+ }
218
+
219
+ function parseMs(value: unknown): number | null {
220
+ if (value instanceof Date) {
221
+ const ms = value.getTime()
222
+ return Number.isNaN(ms) ? null : ms
223
+ }
224
+ if (typeof value !== 'string') return null
225
+ const ms = new Date(value).getTime()
226
+ return Number.isNaN(ms) ? null : ms
227
+ }
@@ -1,5 +1,9 @@
1
- import { describe, it, expect } from 'vitest'
2
- import { evaluateCrmDealPriority, resolveCrmPriorityRuleConfig } from './crm-priority'
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ evaluateCrmDealPriority as evaluateCrmDealPriorityCore,
4
+ resolveCrmPriorityRuleConfig
5
+ } from './crm-priority'
6
+ import type { CrmPriorityRuleConfig } from '../../organization-model/domains/sales'
3
7
 
4
8
  // ---------------------------------------------------------------------------
5
9
  // Helpers
@@ -9,11 +13,30 @@ function makeEvent(type: string, timestamp: string): Record<string, unknown> {
9
13
  return { type, timestamp }
10
14
  }
11
15
 
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(
16
+ const INBOUND = 'reply_received'
17
+ const OUTBOUND = 'reply_sent_to_lead'
18
+ const NOW = '2026-04-30T12:00:00.000Z'
19
+ const ELEVASIS_CRM_PRIORITY_RULE_CONFIG: CrmPriorityRuleConfig = {
20
+ buckets: [
21
+ { bucketKey: 'needs_response', label: 'Needs Response', rank: 10, color: 'red' },
22
+ { bucketKey: 'follow_up_due', label: 'Follow-up Due', rank: 20, color: 'orange' },
23
+ { bucketKey: 'waiting', label: 'Waiting', rank: 30, color: 'blue' },
24
+ { bucketKey: 'stale', label: 'Stale', rank: 40, color: 'gray' },
25
+ { bucketKey: 'closed_low', label: 'Closed', rank: 50, color: 'dark' }
26
+ ],
27
+ closedStageKeys: ['closed_won', 'closed_lost'],
28
+ followUpAfterDaysByStateKey: {
29
+ discovery_link_sent: 3,
30
+ discovery_nudging: 2,
31
+ reply_sent: 3,
32
+ followup_1_sent: 3,
33
+ followup_2_sent: 5,
34
+ followup_3_sent: 7
35
+ },
36
+ staleAfterDays: 14
37
+ }
38
+
39
+ function makeDeal(
17
40
  overrides: Partial<{
18
41
  stage_key: string | null
19
42
  state_key: string | null
@@ -29,7 +52,17 @@ function makeDeal(
29
52
  updated_at: overrides.updated_at ?? NOW,
30
53
  created_at: overrides.created_at ?? NOW
31
54
  }
32
- }
55
+ }
56
+
57
+ function evaluateCrmDealPriority(
58
+ input: Parameters<typeof evaluateCrmDealPriorityCore>[0],
59
+ options: Parameters<typeof evaluateCrmDealPriorityCore>[1] = {}
60
+ ) {
61
+ return evaluateCrmDealPriorityCore(input, {
62
+ config: ELEVASIS_CRM_PRIORITY_RULE_CONFIG,
63
+ ...options
64
+ })
65
+ }
33
66
 
34
67
  // ---------------------------------------------------------------------------
35
68
  // Closed deals → closed_low