@spekra.in/agent-os 0.0.0-stage → 1.0.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 (114) hide show
  1. package/Booker/README.md +41 -0
  2. package/Booker/package.json +11 -0
  3. package/Booker/src/agent.js +15 -0
  4. package/Booker/src/calendar-adapter.js +75 -0
  5. package/Booker/src/index.js +4 -0
  6. package/Booker/src/intake-parser.js +96 -0
  7. package/Booker/src/validation.js +34 -0
  8. package/Booker/test/booker.test.js +35 -0
  9. package/CashHound/README.md +181 -0
  10. package/CashHound/package.json +21 -0
  11. package/CashHound/src/agent.js +621 -0
  12. package/CashHound/src/bank-reconciler.js +66 -0
  13. package/CashHound/src/dunning.js +380 -0
  14. package/CashHound/src/index.js +32 -0
  15. package/CashHound/src/invoice.js +371 -0
  16. package/CashHound/src/mobile.js +35 -0
  17. package/CashHound/src/npv-optimizer.js +259 -0
  18. package/CashHound/test/advanced.test.js +44 -0
  19. package/CashHound/test/cashhound.test.js +530 -0
  20. package/CashHound/test/mobile.test.js +25 -0
  21. package/CashHound/test/security.test.js +35 -0
  22. package/Clerk/README.md +30 -0
  23. package/Clerk/package.json +11 -0
  24. package/Clerk/src/agent.js +18 -0
  25. package/Clerk/src/index.js +2 -0
  26. package/Clerk/src/reconciliation.js +52 -0
  27. package/Clerk/test/clerk.test.js +39 -0
  28. package/LocalRoar/README.md +37 -0
  29. package/LocalRoar/package.json +13 -0
  30. package/LocalRoar/src/agent.js +70 -0
  31. package/LocalRoar/src/booking-router.js +74 -0
  32. package/LocalRoar/src/feedback-interceptor.js +47 -0
  33. package/LocalRoar/src/index.js +7 -0
  34. package/LocalRoar/src/lead-engine.js +52 -0
  35. package/LocalRoar/src/mobile.js +23 -0
  36. package/LocalRoar/src/review-booster.js +24 -0
  37. package/LocalRoar/src/route-density.js +46 -0
  38. package/LocalRoar/test/advanced.test.js +41 -0
  39. package/LocalRoar/test/localroar.test.js +59 -0
  40. package/LocalRoar/test/mobile.test.js +12 -0
  41. package/OmniLife/README.md +39 -0
  42. package/OmniLife/package.json +13 -0
  43. package/OmniLife/src/agent.js +47 -0
  44. package/OmniLife/src/bill-negotiator.js +43 -0
  45. package/OmniLife/src/browser-cancel.js +28 -0
  46. package/OmniLife/src/conflict-engine.js +49 -0
  47. package/OmniLife/src/index.js +6 -0
  48. package/OmniLife/src/mobile.js +18 -0
  49. package/OmniLife/src/subscription-manager.js +66 -0
  50. package/OmniLife/test/advanced.test.js +29 -0
  51. package/OmniLife/test/mobile.test.js +12 -0
  52. package/OmniLife/test/omnilife.test.js +71 -0
  53. package/PulseMD/README.md +42 -0
  54. package/PulseMD/package.json +13 -0
  55. package/PulseMD/src/agent.js +67 -0
  56. package/PulseMD/src/ambient-scribe.js +46 -0
  57. package/PulseMD/src/auth.js +63 -0
  58. package/PulseMD/src/charting.js +54 -0
  59. package/PulseMD/src/index.js +7 -0
  60. package/PulseMD/src/mobile.js +18 -0
  61. package/PulseMD/src/prior-auth.js +39 -0
  62. package/PulseMD/src/safety-guard.js +88 -0
  63. package/PulseMD/test/advanced.test.js +50 -0
  64. package/PulseMD/test/mobile.test.js +12 -0
  65. package/PulseMD/test/pulsemd.test.js +71 -0
  66. package/README.md +203 -2
  67. package/ResolveX/README.md +274 -0
  68. package/ResolveX/package.json +20 -0
  69. package/ResolveX/src/agent.js +679 -0
  70. package/ResolveX/src/carrier-listener.js +405 -0
  71. package/ResolveX/src/diagnosis.js +315 -0
  72. package/ResolveX/src/index.js +36 -0
  73. package/ResolveX/src/mobile.js +31 -0
  74. package/ResolveX/src/policy.js +325 -0
  75. package/ResolveX/src/vision.js +384 -0
  76. package/ResolveX/test/advanced.test.js +445 -0
  77. package/ResolveX/test/mobile.test.js +15 -0
  78. package/ResolveX/test/resolvex.test.js +428 -0
  79. package/SentinelMesh/README.md +51 -0
  80. package/SentinelMesh/package.json +13 -0
  81. package/SentinelMesh/src/governor.js +61 -0
  82. package/SentinelMesh/src/index.js +4 -0
  83. package/SentinelMesh/src/mobile.js +19 -0
  84. package/SentinelMesh/src/policy.js +63 -0
  85. package/SentinelMesh/src/sandbox.js +152 -0
  86. package/SentinelMesh/test/mobile.test.js +12 -0
  87. package/SentinelMesh/test/sentinel.test.js +135 -0
  88. package/Sidekick/README.md +43 -0
  89. package/Sidekick/package.json +11 -0
  90. package/Sidekick/src/agent.js +15 -0
  91. package/Sidekick/src/evidence.js +45 -0
  92. package/Sidekick/src/index.js +3 -0
  93. package/Sidekick/src/validation.js +15 -0
  94. package/Sidekick/test/sidekick.test.js +33 -0
  95. package/agent-os-mobile/README.md +26 -0
  96. package/agent-os-mobile/src/api.js +97 -0
  97. package/agent-os-mobile/src/biometric.js +41 -0
  98. package/agent-os-mobile/src/components/ApprovalStack.js +207 -0
  99. package/agent-os-mobile/src/components/OutcomeCard.js +98 -0
  100. package/agent-os-mobile/src/memory-graph.js +114 -0
  101. package/agent-os-mobile/src/screens/CashHoundMobileScreen.js +111 -0
  102. package/agent-os-mobile/src/screens/LocalRoarMobileScreen.js +183 -0
  103. package/agent-os-mobile/src/screens/OmniLifeMobileScreen.js +111 -0
  104. package/agent-os-mobile/src/screens/PulseMDMobileScreen.js +55 -0
  105. package/agent-os-mobile/src/screens/ResolveXMobileScreen.js +96 -0
  106. package/agent-os-mobile/src/screens/SentinelMeshMobileScreen.js +199 -0
  107. package/agent-os-mobile/src/self-healer.js +104 -0
  108. package/agent-os-mobile/src/speculative-verifier.js +69 -0
  109. package/agent-os-mobile/src/spekra-bridge.js +216 -0
  110. package/agent-os-mobile/src/swarm.js +72 -0
  111. package/agent-os-mobile/src/voice.js +51 -0
  112. package/bin/agentos.js +260 -0
  113. package/package.json +51 -4
  114. package/src/index.js +91 -0
@@ -0,0 +1,371 @@
1
+ /**
2
+ * CashHound - Invoice Model & Aging Engine
3
+ * Handles invoice state, aging classification, dispute status, and priority scoring.
4
+ */
5
+
6
+ export const AgingBuckets = Object.freeze({
7
+ CURRENT: 'current',
8
+ DAYS_30: '30+',
9
+ DAYS_60: '60+',
10
+ DAYS_90: '90+',
11
+ });
12
+
13
+ export const InvoiceStatus = Object.freeze({
14
+ DRAFT: 'draft',
15
+ ISSUED: 'issued',
16
+ PARTIALLY_PAID: 'partially_paid',
17
+ PAID: 'paid',
18
+ DISPUTED: 'disputed',
19
+ WRITTEN_OFF: 'written_off',
20
+ IN_COLLECTION: 'in_collection',
21
+ });
22
+
23
+ export const CustomerTier = Object.freeze({
24
+ VIP: 'vip',
25
+ STANDARD: 'standard',
26
+ AT_RISK: 'at_risk',
27
+ });
28
+
29
+ export const PriorityLevel = Object.freeze({
30
+ LOW: 'LOW',
31
+ MEDIUM: 'MEDIUM',
32
+ HIGH: 'HIGH',
33
+ CRITICAL: 'CRITICAL',
34
+ });
35
+
36
+ export class Invoice {
37
+ /**
38
+ * @param {Object} params
39
+ * @param {string} params.id - Unique invoice identifier (e.g. 'INV-2024-001')
40
+ * @param {Object} params.customer - Customer details
41
+ * @param {string} params.customer.name - Customer name
42
+ * @param {string} params.customer.email - Customer email
43
+ * @param {string} [params.customer.tier='standard'] - 'vip' | 'standard' | 'at_risk'
44
+ * @param {number} params.amount - Total invoice amount
45
+ * @param {number} [params.amountPaid=0] - Amount collected so far
46
+ * @param {string} [params.currency='USD'] - Currency code
47
+ * @param {string|Date} params.issueDate - Issue date
48
+ * @param {string|Date} params.dueDate - Due date
49
+ * @param {string} [params.status='issued'] - Invoice status
50
+ * @param {Object|null} [params.dispute=null] - Dispute details if any
51
+ * @param {Array} [params.paymentHistory=[]] - Recorded payments
52
+ * @param {Array} [params.communications=[]] - Prior dunning / communication logs
53
+ * @param {Object} [params.metadata={}] - Custom metadata / tags
54
+ */
55
+ constructor({
56
+ id,
57
+ customer,
58
+ amount,
59
+ amountPaid = 0,
60
+ currency = 'USD',
61
+ issueDate,
62
+ dueDate,
63
+ status = InvoiceStatus.ISSUED,
64
+ dispute = null,
65
+ paymentHistory = [],
66
+ communications = [],
67
+ metadata = {},
68
+ }) {
69
+ if (!id) throw new Error('Invoice id is required');
70
+ if (!customer || !customer.name) throw new Error('Customer with name is required');
71
+ if (typeof amount !== 'number' || isNaN(amount) || amount <= 0) {
72
+ throw new Error('Valid positive amount is required');
73
+ }
74
+ if (!dueDate) throw new Error('dueDate is required');
75
+
76
+ this.id = id;
77
+ this.customer = {
78
+ id: customer.id || `CUST-${id}`,
79
+ name: customer.name,
80
+ email: customer.email || '',
81
+ tier: customer.tier || CustomerTier.STANDARD,
82
+ phone: customer.phone || '',
83
+ };
84
+ this.amount = Number(amount.toFixed(2));
85
+ this.amountPaid = Number((amountPaid || 0).toFixed(2));
86
+ this.balance = Number(Math.max(0, this.amount - this.amountPaid).toFixed(2));
87
+ this.currency = currency;
88
+ this.issueDate = issueDate ? new Date(issueDate) : new Date();
89
+ this.dueDate = new Date(dueDate);
90
+ this.status = status;
91
+ this.dispute = dispute ? { ...dispute } : null;
92
+ this.paymentHistory = [...paymentHistory];
93
+ this.communications = [...communications];
94
+ this.metadata = { ...metadata };
95
+ this.createdAt = new Date();
96
+ this.updatedAt = new Date();
97
+
98
+ if (this.balance <= 0 && this.status !== InvoiceStatus.WRITTEN_OFF) {
99
+ this.status = InvoiceStatus.PAID;
100
+ } else if (this.dispute && this.dispute.status === 'open') {
101
+ this.status = InvoiceStatus.DISPUTED;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Calculates days past due relative to reference date.
107
+ * Negative or zero means not yet overdue (current).
108
+ * @param {Date|string} [asOfDate=new Date()]
109
+ * @returns {number}
110
+ */
111
+ getDaysPastDue(asOfDate = new Date()) {
112
+ const asOf = new Date(asOfDate);
113
+ const due = new Date(this.dueDate);
114
+ // Reset time components to compare calendar days cleanly
115
+ asOf.setHours(0, 0, 0, 0);
116
+ due.setHours(0, 0, 0, 0);
117
+
118
+ const diffTime = asOf.getTime() - due.getTime();
119
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
120
+ return diffDays;
121
+ }
122
+
123
+ /**
124
+ * Computes the aging bucket (current, 30+, 60+, 90+ days).
125
+ * @param {Date|string} [asOfDate=new Date()]
126
+ * @returns {string} One of AgingBuckets values ('current', '30+', '60+', '90+')
127
+ */
128
+ getAgingBucket(asOfDate = new Date()) {
129
+ const days = this.getDaysPastDue(asOfDate);
130
+ if (days <= 0) return AgingBuckets.CURRENT;
131
+ if (days <= 30) return AgingBuckets.DAYS_30;
132
+ if (days <= 60) return AgingBuckets.DAYS_60;
133
+ return AgingBuckets.DAYS_90;
134
+ }
135
+
136
+ /**
137
+ * Marks this invoice as disputed.
138
+ * @param {Object} details
139
+ * @param {string} details.reason - Reason for dispute
140
+ * @param {boolean} [details.isLegal=false] - Whether dispute involves legal action / attorney
141
+ * @param {string} [details.notes=''] - Additional contextual notes
142
+ * @param {Date|string} [details.raisedAt=new Date()]
143
+ */
144
+ markDisputed({ reason, isLegal = false, notes = '', raisedAt = new Date() }) {
145
+ if (!reason) throw new Error('Dispute reason is required');
146
+ this.dispute = {
147
+ reason,
148
+ isLegal: Boolean(isLegal),
149
+ notes,
150
+ raisedAt: new Date(raisedAt),
151
+ status: 'open',
152
+ };
153
+ this.status = InvoiceStatus.DISPUTED;
154
+ this.updatedAt = new Date();
155
+ return this;
156
+ }
157
+
158
+ /**
159
+ * Resolves an existing dispute.
160
+ * @param {Object} details
161
+ * @param {string} details.resolution - How the dispute was resolved
162
+ * @param {string} [details.notes=''] - Additional notes
163
+ * @param {Date|string} [details.resolvedAt=new Date()]
164
+ */
165
+ resolveDispute({ resolution, notes = '', resolvedAt = new Date() }) {
166
+ if (!this.dispute) throw new Error('Invoice is not disputed');
167
+ this.dispute = {
168
+ ...this.dispute,
169
+ status: 'resolved',
170
+ resolution,
171
+ notes: notes || this.dispute.notes,
172
+ resolvedAt: new Date(resolvedAt),
173
+ };
174
+ this.status = this.balance <= 0 ? InvoiceStatus.PAID : (this.amountPaid > 0 ? InvoiceStatus.PARTIALLY_PAID : InvoiceStatus.ISSUED);
175
+ this.updatedAt = new Date();
176
+ return this;
177
+ }
178
+
179
+ /**
180
+ * Returns true if there is an active (open) dispute on this invoice.
181
+ * @returns {boolean}
182
+ */
183
+ isDisputed() {
184
+ return Boolean(this.dispute && this.dispute.status === 'open');
185
+ }
186
+
187
+ /**
188
+ * Returns true if this invoice has an open legal dispute.
189
+ * @returns {boolean}
190
+ */
191
+ isLegalDispute() {
192
+ return Boolean(this.isDisputed() && this.dispute.isLegal);
193
+ }
194
+
195
+ /**
196
+ * Applies a payment and recalculates balance and status.
197
+ * @param {Object} params
198
+ * @param {number} params.amount - Payment amount
199
+ * @param {Date|string} [params.date=new Date()]
200
+ * @param {string} [params.method='electronic'] - 'ach', 'card', 'wire', 'check'
201
+ * @param {string} [params.reference=''] - External payment reference or ID
202
+ * @returns {{ invoice: Invoice, remainingBalance: number, isFullyPaid: boolean }}
203
+ */
204
+ applyPayment({ amount, date = new Date(), method = 'electronic', reference = '' }) {
205
+ if (typeof amount !== 'number' || amount <= 0) {
206
+ throw new Error('Payment amount must be a positive number');
207
+ }
208
+ const paymentRecord = {
209
+ id: `PMT-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
210
+ amount: Number(amount.toFixed(2)),
211
+ date: new Date(date),
212
+ method,
213
+ reference,
214
+ };
215
+ this.paymentHistory.push(paymentRecord);
216
+ this.amountPaid = Number((this.amountPaid + paymentRecord.amount).toFixed(2));
217
+ this.balance = Number(Math.max(0, this.amount - this.amountPaid).toFixed(2));
218
+
219
+ if (this.balance === 0) {
220
+ this.status = InvoiceStatus.PAID;
221
+ } else {
222
+ this.status = InvoiceStatus.PARTIALLY_PAID;
223
+ }
224
+ this.updatedAt = new Date();
225
+
226
+ return {
227
+ invoice: this,
228
+ paymentRecord,
229
+ remainingBalance: this.balance,
230
+ isFullyPaid: this.balance === 0,
231
+ };
232
+ }
233
+
234
+ /**
235
+ * Records a communication event (e.g. reminder, notice, settlement offer).
236
+ * @param {Object} communication
237
+ */
238
+ recordCommunication(communication) {
239
+ const record = {
240
+ id: communication.id || `COMM-${Date.now()}`,
241
+ timestamp: communication.timestamp ? new Date(communication.timestamp) : new Date(),
242
+ tier: communication.tier,
243
+ tone: communication.tone,
244
+ subject: communication.subject,
245
+ body: communication.body,
246
+ status: communication.status || 'sent',
247
+ requiresApproval: Boolean(communication.requiresApproval),
248
+ };
249
+ this.communications.push(record);
250
+ this.updatedAt = new Date();
251
+ return record;
252
+ }
253
+
254
+ /**
255
+ * Calculates dynamic recovery priority score and risk tier.
256
+ * Takes into account:
257
+ * 1. Days overdue & aging bucket
258
+ * 2. Outstanding balance value
259
+ * 3. Dispute & legal exposure
260
+ * 4. Customer relationship tier
261
+ *
262
+ * @param {Date|string} [asOfDate=new Date()]
263
+ * @returns {{ score: number, level: string, reasons: string[] }}
264
+ */
265
+ calculatePriority(asOfDate = new Date()) {
266
+ if (this.status === InvoiceStatus.PAID || this.balance <= 0) {
267
+ return { score: 0, level: PriorityLevel.LOW, reasons: ['Invoice is fully paid'] };
268
+ }
269
+
270
+ const days = this.getDaysPastDue(asOfDate);
271
+ const bucket = this.getAgingBucket(asOfDate);
272
+ let score = 0;
273
+ const reasons = [];
274
+
275
+ // 1. Aging factor (0 - 45 pts)
276
+ if (bucket === AgingBuckets.CURRENT) {
277
+ score += 5;
278
+ reasons.push('Current invoice: within normal terms');
279
+ } else if (bucket === AgingBuckets.DAYS_30) {
280
+ score += 25;
281
+ reasons.push(`30+ days overdue (${days} days)`);
282
+ } else if (bucket === AgingBuckets.DAYS_60) {
283
+ score += 40;
284
+ reasons.push(`60+ days overdue (${days} days)`);
285
+ } else {
286
+ score += 55;
287
+ reasons.push(`90+ days severely overdue (${days} days)`);
288
+ }
289
+
290
+ // 2. Outstanding Balance factor (0 - 35 pts)
291
+ if (this.balance >= 10000) {
292
+ score += 35;
293
+ reasons.push(`Very high balance ($${this.balance.toLocaleString()})`);
294
+ } else if (this.balance >= 5000) {
295
+ score += 25;
296
+ reasons.push(`High balance ($${this.balance.toLocaleString()} >= $5,000 threshold)`);
297
+ } else if (this.balance >= 1000) {
298
+ score += 15;
299
+ reasons.push(`Moderate balance ($${this.balance.toLocaleString()})`);
300
+ } else {
301
+ score += 5;
302
+ reasons.push(`Low balance ($${this.balance.toLocaleString()})`);
303
+ }
304
+
305
+ // 3. Customer Tier adjustment
306
+ if (this.customer.tier === CustomerTier.AT_RISK) {
307
+ score += 15;
308
+ reasons.push('Customer flagged as at-risk');
309
+ } else if (this.customer.tier === CustomerTier.VIP) {
310
+ // VIP accounts require sensitive handling
311
+ score -= 5;
312
+ reasons.push('VIP relationship: prioritize relationship preservation');
313
+ }
314
+
315
+ // 4. Dispute status
316
+ if (this.isLegalDispute()) {
317
+ score = Math.max(score, 90);
318
+ reasons.push('Active legal dispute: legal escalation gate active');
319
+ } else if (this.isDisputed()) {
320
+ reasons.push('Commercial dispute pending: resolution needed prior to dunning');
321
+ }
322
+
323
+ // Normalize score
324
+ score = Math.max(0, Math.min(100, score));
325
+
326
+ let level;
327
+ if (score >= 80) level = PriorityLevel.CRITICAL;
328
+ else if (score >= 60) level = PriorityLevel.HIGH;
329
+ else if (score >= 35) level = PriorityLevel.MEDIUM;
330
+ else level = PriorityLevel.LOW;
331
+
332
+ return { score, level, reasons };
333
+ }
334
+
335
+ toJSON() {
336
+ return {
337
+ id: this.id,
338
+ customer: this.customer,
339
+ amount: this.amount,
340
+ amountPaid: this.amountPaid,
341
+ balance: this.balance,
342
+ currency: this.currency,
343
+ issueDate: this.issueDate.toISOString(),
344
+ dueDate: this.dueDate.toISOString(),
345
+ status: this.status,
346
+ dispute: this.dispute,
347
+ paymentHistory: this.paymentHistory,
348
+ communications: this.communications,
349
+ metadata: this.metadata,
350
+ createdAt: this.createdAt.toISOString(),
351
+ updatedAt: this.updatedAt.toISOString(),
352
+ };
353
+ }
354
+
355
+ static fromJSON(data) {
356
+ return new Invoice({
357
+ id: data.id,
358
+ customer: data.customer,
359
+ amount: data.amount,
360
+ amountPaid: data.amountPaid,
361
+ currency: data.currency,
362
+ issueDate: data.issueDate,
363
+ dueDate: data.dueDate,
364
+ status: data.status,
365
+ dispute: data.dispute,
366
+ paymentHistory: data.paymentHistory,
367
+ communications: data.communications,
368
+ metadata: data.metadata,
369
+ });
370
+ }
371
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * CashHound Mobile ViewModel: Formats mobile outcome cards & approval payloads.
3
+ */
4
+
5
+ export class CashHoundMobileAdapter {
6
+ constructor(agent) {
7
+ this.agent = agent;
8
+ }
9
+
10
+ getMobileOutcomeCard() {
11
+ let totalBalance = 0;
12
+ for (const inv of this.agent.invoices.values()) {
13
+ totalBalance += inv.balance;
14
+ }
15
+
16
+ const pending = this.agent.getPendingApprovals();
17
+
18
+ return {
19
+ title: 'CashHound Autonomous Collections',
20
+ outcomeMetric: `$${totalBalance.toFixed(2)} Active Pipeline`,
21
+ approvalsPending: pending.length,
22
+ statusBadge: 'COLLECTING_24_7'
23
+ };
24
+ }
25
+
26
+ getMobileApprovalStack() {
27
+ return this.agent.getPendingApprovals().map(action => ({
28
+ id: action.id,
29
+ title: `Approve Notice: ${action.customerName || 'Customer'}`,
30
+ summary: action.draftMessage?.subject || action.approvalReasons?.join(', ') || 'Pending approval',
31
+ amountFormatted: action.balance ? `$${action.balance.toFixed(2)}` : null,
32
+ urgency: 'HIGH'
33
+ }));
34
+ }
35
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * CashHound Dynamic Settlement NPV Optimizer:
3
+ * Calculates Net Present Value (NPV) comparing immediate discounted cash settlement
4
+ * against prolonged collections risk and cost of capital across 30, 60, and 90-day horizons.
5
+ * Evaluates receivables aging, customer credit risk tiers (ENTERPRISE, STANDARD, HIGH_RISK),
6
+ * and recommends the optimal settlement discount percentage and projected net recovery gain.
7
+ */
8
+
9
+ import { AgingBuckets, Invoice } from './invoice.js';
10
+
11
+ export const CustomerRiskTier = Object.freeze({
12
+ ENTERPRISE: 'ENTERPRISE',
13
+ STANDARD: 'STANDARD',
14
+ HIGH_RISK: 'HIGH_RISK',
15
+ });
16
+
17
+ /**
18
+ * Historical recovery probabilities across aging buckets and customer risk tiers.
19
+ */
20
+ export const RECOVERY_PROBABILITIES = Object.freeze({
21
+ current: Object.freeze({ ENTERPRISE: 0.99, STANDARD: 0.95, HIGH_RISK: 0.85 }),
22
+ '30+': Object.freeze({ ENTERPRISE: 0.92, STANDARD: 0.82, HIGH_RISK: 0.65 }),
23
+ '60+': Object.freeze({ ENTERPRISE: 0.80, STANDARD: 0.65, HIGH_RISK: 0.45 }),
24
+ '90+': Object.freeze({ ENTERPRISE: 0.60, STANDARD: 0.40, HIGH_RISK: 0.20 }),
25
+ });
26
+
27
+ /**
28
+ * Standard horizon recovery probability matrix for 30, 60, and 90 day future wait periods.
29
+ */
30
+ export const HORIZON_RECOVERY_PROBABILITIES = Object.freeze({
31
+ [CustomerRiskTier.ENTERPRISE]: Object.freeze({ 30: 0.98, 60: 0.95, 90: 0.90 }),
32
+ [CustomerRiskTier.STANDARD]: Object.freeze({ 30: 0.90, 60: 0.82, 90: 0.72 }),
33
+ [CustomerRiskTier.HIGH_RISK]: Object.freeze({ 30: 0.78, 60: 0.60, 90: 0.42 }),
34
+ });
35
+
36
+ export class SettlementNpvOptimizer {
37
+ /**
38
+ * @param {number|Object} [config=0.10] - Annual cost of capital (e.g. 0.10 for 10%) or options config
39
+ */
40
+ constructor(config = 0.10) {
41
+ let coc = 0.10;
42
+ if (typeof config === 'number') {
43
+ coc = config;
44
+ } else if (config && typeof config === 'object') {
45
+ coc = config.annualCostOfCapital ?? config.costOfCapital ?? 0.10;
46
+ }
47
+ if (typeof coc === 'number' && coc > 1) {
48
+ coc = coc / 100;
49
+ }
50
+ this.annualCostOfCapital = Number.isFinite(coc) && coc >= 0 ? coc : 0.10;
51
+ this.costOfCapital = this.annualCostOfCapital;
52
+ this.defaultHorizons = [30, 60, 90];
53
+ }
54
+
55
+ /**
56
+ * Normalizes customer risk tier input into ENTERPRISE | STANDARD | HIGH_RISK.
57
+ * @param {string} [tier='STANDARD']
58
+ * @returns {string}
59
+ */
60
+ normalizeRiskTier(tier) {
61
+ if (!tier || typeof tier !== 'string') return CustomerRiskTier.STANDARD;
62
+ const clean = tier.trim().toUpperCase().replace(/[-_\s]+/g, '_');
63
+ if (clean === 'ENTERPRISE' || clean === 'VIP') return CustomerRiskTier.ENTERPRISE;
64
+ if (clean === 'HIGH_RISK' || clean === 'AT_RISK' || clean === 'HIGH') return CustomerRiskTier.HIGH_RISK;
65
+ return CustomerRiskTier.STANDARD;
66
+ }
67
+
68
+ /**
69
+ * Calculates time-value discount factor: 1 / (1 + r)^(days / 365)
70
+ * @param {number} days
71
+ * @param {number} [rate]
72
+ * @returns {number}
73
+ */
74
+ calculateDiscountFactor(days, rate = this.annualCostOfCapital) {
75
+ const r = typeof rate === 'number' && rate > 1 ? rate / 100 : rate;
76
+ const years = Math.max(0, days) / 365;
77
+ return Number((1 / Math.pow(1 + r, years)).toFixed(6));
78
+ }
79
+
80
+ /**
81
+ * Evaluates the NPV of collecting cash today via a settlement discount.
82
+ * @param {number} balance
83
+ * @param {number} discountPercent
84
+ * @returns {{ discountPercent: number, discountAmount: number, settlementCashToday: number, npvToday: number }}
85
+ */
86
+ calculateNpvToday(balance, discountPercent) {
87
+ if (typeof balance !== 'number' || balance <= 0 || !Number.isFinite(balance)) {
88
+ throw new Error('Balance must be a positive finite number');
89
+ }
90
+ const d = Math.max(0, Math.min(80, discountPercent));
91
+ const discountAmount = Number(((balance * d) / 100).toFixed(2));
92
+ const settlementCashToday = Number((balance - discountAmount).toFixed(2));
93
+ return {
94
+ discountPercent: d,
95
+ discountAmount,
96
+ settlementCashToday,
97
+ npvToday: settlementCashToday,
98
+ };
99
+ }
100
+
101
+ /**
102
+ * Calculates the Net Present Value of waiting for recovery over a specified horizon.
103
+ * NPV_wait = balance * recoveryProbability * (1 / (1 + r)^(days / 365))
104
+ *
105
+ * @param {number} balance
106
+ * @param {number} days - Recovery horizon (e.g. 30, 60, 90)
107
+ * @param {string} [customerTier='STANDARD']
108
+ * @param {string} [agingBucket='current']
109
+ * @returns {Object}
110
+ */
111
+ calculateNpvWait(balance, days, customerTier = 'STANDARD', agingBucket = 'current') {
112
+ if (typeof balance !== 'number' || balance <= 0 || !Number.isFinite(balance)) {
113
+ throw new Error('Balance must be a positive finite number');
114
+ }
115
+ const tier = this.normalizeRiskTier(customerTier);
116
+ const discountFactor = this.calculateDiscountFactor(days);
117
+
118
+ // Baseline recovery probability for this horizon
119
+ const horizonTable = HORIZON_RECOVERY_PROBABILITIES[tier] || HORIZON_RECOVERY_PROBABILITIES[CustomerRiskTier.STANDARD];
120
+ let baseRecovery = horizonTable[days];
121
+ if (baseRecovery === undefined) {
122
+ // Linear interpolation between 30 and 90 days
123
+ const r30 = horizonTable[30] || 0.90;
124
+ const r90 = horizonTable[90] || 0.70;
125
+ baseRecovery = r30 - ((r30 - r90) / 60) * Math.max(0, days - 30);
126
+ }
127
+
128
+ // Adjust recovery probability if already in overdue aging bucket
129
+ let agingMultiplier = 1.0;
130
+ if (agingBucket === '30+') agingMultiplier = 0.90;
131
+ else if (agingBucket === '60+') agingMultiplier = 0.75;
132
+ else if (agingBucket === '90+') agingMultiplier = 0.55;
133
+
134
+ const recoveryProbability = Number(Math.max(0.05, Math.min(0.99, baseRecovery * agingMultiplier)).toFixed(4));
135
+ const defaultProbability = Number((1 - recoveryProbability).toFixed(4));
136
+ const expectedRecovery = Number((balance * recoveryProbability).toFixed(2));
137
+ const npvWait = Number((expectedRecovery * discountFactor).toFixed(2));
138
+
139
+ return {
140
+ days,
141
+ discountFactor,
142
+ recoveryProbability,
143
+ defaultProbability,
144
+ expectedRecovery,
145
+ npvWait,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Compares recovery NPV across 30, 60, and 90 day horizons.
151
+ * @param {number} balance
152
+ * @param {string} [customerTier='STANDARD']
153
+ * @param {string} [agingBucket='current']
154
+ * @returns {Object}
155
+ */
156
+ compareHorizons(balance, customerTier = 'STANDARD', agingBucket = 'current') {
157
+ const tier = this.normalizeRiskTier(customerTier);
158
+ const horizons = {};
159
+ for (const d of [30, 60, 90]) {
160
+ horizons[d] = this.calculateNpvWait(balance, d, tier, agingBucket);
161
+ }
162
+ return horizons;
163
+ }
164
+
165
+ /**
166
+ * Evaluates outstanding invoice aging, customer risk tier (ENTERPRISE, STANDARD, HIGH_RISK),
167
+ * and cost of capital to calculate the Net Present Value (NPV) of collecting cash today
168
+ * via a settlement discount vs waiting for full recovery over 30/60/90 days with default probability risk.
169
+ * Recommends optimal settlement discount and projected net recovery gain.
170
+ *
171
+ * @param {number} balance - Outstanding invoice balance
172
+ * @param {number} daysOverdue - Days past due
173
+ * @param {string} [customerTier='STANDARD'] - 'ENTERPRISE' | 'STANDARD' | 'HIGH_RISK'
174
+ * @param {Object} [options={}]
175
+ * @returns {Object} Settlement plan and NPV comparison
176
+ */
177
+ calculateOptimalSettlement(balance, daysOverdue, customerTier = 'STANDARD', options = {}) {
178
+ if (typeof balance !== 'number' || balance <= 0 || !Number.isFinite(balance)) {
179
+ throw new Error('Balance must be a positive number');
180
+ }
181
+
182
+ let bucket = 'current';
183
+ let expectedWaitDays = 15;
184
+ if (daysOverdue > 90) { bucket = '90+'; expectedWaitDays = 90; }
185
+ else if (daysOverdue > 60) { bucket = '60+'; expectedWaitDays = 60; }
186
+ else if (daysOverdue > 30) { bucket = '30+'; expectedWaitDays = 30; }
187
+
188
+ const tierKey = this.normalizeRiskTier(customerTier);
189
+ const bucketTable = RECOVERY_PROBABILITIES[bucket] || RECOVERY_PROBABILITIES.current;
190
+ const probability = bucketTable[tierKey] ?? 0.60;
191
+ const defaultProbability = Number((1 - probability).toFixed(4));
192
+
193
+ // Time discount factor (discounted cash flow)
194
+ const discountFactor = 1 / Math.pow(1 + this.annualCostOfCapital, expectedWaitDays / 365);
195
+ const expectedValueWaiting = balance * probability * discountFactor;
196
+
197
+ // Optimal settlement discount curve based on delinquency aging and risk tier:
198
+ // Base discount: 10% for current, 15% for 30+, 20% for 60+, 25% for 90+
199
+ let recommendedDiscountPercent = 10;
200
+ if (bucket === '90+') recommendedDiscountPercent = 25;
201
+ else if (bucket === '60+') recommendedDiscountPercent = 20;
202
+ else if (bucket === '30+') recommendedDiscountPercent = 15;
203
+
204
+ // High risk customers get higher incentive to settle immediately (+5%)
205
+ if (tierKey === CustomerRiskTier.HIGH_RISK) {
206
+ recommendedDiscountPercent += 5;
207
+ }
208
+
209
+ const settlementCashToday = balance * (1 - (recommendedDiscountPercent / 100));
210
+ const netRecoveryAdvantage = settlementCashToday - expectedValueWaiting;
211
+
212
+ // 30, 60, 90 day recovery horizon breakdown
213
+ const horizons = this.compareHorizons(balance, tierKey, bucket);
214
+
215
+ const plan = {
216
+ balance,
217
+ daysOverdue,
218
+ customerTier: tierKey,
219
+ agingBucket: bucket,
220
+ costOfCapital: this.annualCostOfCapital,
221
+ recoveryProbabilityIfWaiting: probability,
222
+ defaultProbabilityIfWaiting: defaultProbability,
223
+ expectedValueWaiting: Number(expectedValueWaiting.toFixed(2)),
224
+ npvWaiting: Number(expectedValueWaiting.toFixed(2)),
225
+ recommendedDiscountPercent,
226
+ optimalDiscountPercentage: recommendedDiscountPercent,
227
+ settlementCashToday: Number(settlementCashToday.toFixed(2)),
228
+ npvToday: Number(settlementCashToday.toFixed(2)),
229
+ netRecoveryAdvantage: Number(netRecoveryAdvantage.toFixed(2)),
230
+ projectedNetRecoveryGain: Number(netRecoveryAdvantage.toFixed(2)),
231
+ shouldOfferSettlement: netRecoveryAdvantage > 0,
232
+ strategicRationale: netRecoveryAdvantage > 0
233
+ ? `Immediate recovery of $${settlementCashToday.toFixed(2)} beats waiting (NPV $${expectedValueWaiting.toFixed(2)}) given ${(defaultProbability * 100).toFixed(0)}% default risk.`
234
+ : `Customer risk profile supports pursuing full balance recovery without early discount.`,
235
+ horizonsBreakdown: {
236
+ 30: horizons[30],
237
+ 60: horizons[60],
238
+ 90: horizons[90],
239
+ },
240
+ };
241
+
242
+ return plan;
243
+ }
244
+
245
+ /**
246
+ * Convenience evaluation for an Invoice instance.
247
+ * @param {Invoice} invoice
248
+ * @param {Date|string} [asOfDate=new Date()]
249
+ * @returns {Object}
250
+ */
251
+ evaluateInvoice(invoice, asOfDate = new Date()) {
252
+ if (!invoice || typeof invoice.getDaysPastDue !== 'function') {
253
+ throw new Error('Expected Invoice instance with getDaysPastDue()');
254
+ }
255
+ const daysPastDue = Math.max(0, invoice.getDaysPastDue(asOfDate));
256
+ const tier = invoice.customer?.tier || CustomerRiskTier.STANDARD;
257
+ return this.calculateOptimalSettlement(invoice.balance, daysPastDue, tier);
258
+ }
259
+ }