|
| 1 | +import { tool } from 'ai'; |
| 2 | +import { z } from 'zod'; |
| 3 | +import type { NeonQueryFunction } from '@neondatabase/serverless'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Create financial tools bound to a Neon SQL connection. |
| 7 | + * Each tool executes read-only or guarded-write queries against cc_* tables. |
| 8 | + */ |
| 9 | +export function createFinancialTools(sql: NeonQueryFunction<false, false>) { |
| 10 | + return { |
| 11 | + get_financial_snapshot: tool({ |
| 12 | + description: 'Get current cash position, overdue bills, and upcoming obligations.', |
| 13 | + inputSchema: z.object({}), |
| 14 | + execute: async () => { |
| 15 | + const [[cash], [overdue], [dueSoon], [activeRecs]] = await Promise.all([ |
| 16 | + sql`SELECT COALESCE(SUM(current_balance), 0) as total, |
| 17 | + COUNT(*) as account_count |
| 18 | + FROM cc_accounts WHERE account_type IN ('checking', 'savings')`, |
| 19 | + sql`SELECT COUNT(*) as count, |
| 20 | + COALESCE(SUM(COALESCE(amount_due::numeric, 0)), 0) as total |
| 21 | + FROM cc_obligations WHERE status = 'overdue'`, |
| 22 | + sql`SELECT COUNT(*) as count |
| 23 | + FROM cc_obligations |
| 24 | + WHERE status = 'pending' AND due_date <= CURRENT_DATE + INTERVAL '7 days'`, |
| 25 | + sql`SELECT COUNT(*) as count |
| 26 | + FROM cc_recommendations WHERE status = 'active'`, |
| 27 | + ]); |
| 28 | + return { |
| 29 | + cash_position: Number(cash.total), |
| 30 | + account_count: Number(cash.account_count), |
| 31 | + overdue_count: Number(overdue.count), |
| 32 | + overdue_total: Number(overdue.total), |
| 33 | + due_this_week: Number(dueSoon.count), |
| 34 | + pending_recommendations: Number(activeRecs.count), |
| 35 | + }; |
| 36 | + }, |
| 37 | + }), |
| 38 | + |
| 39 | + query_obligations: tool({ |
| 40 | + description: 'Search obligations (bills) by status, category, or payee. Returns up to 20 results.', |
| 41 | + inputSchema: z.object({ |
| 42 | + status: z.enum(['pending', 'overdue', 'paid', 'deferred']).optional().describe('Filter by status'), |
| 43 | + category: z.string().optional().describe('Filter by category (e.g., "mortgage", "utility", "insurance")'), |
| 44 | + payee: z.string().optional().describe('Search payee name (partial match)'), |
| 45 | + }), |
| 46 | + execute: async ({ status, category, payee }) => { |
| 47 | + // Build dynamic query with optional filters |
| 48 | + const conditions: string[] = []; |
| 49 | + const params: unknown[] = []; |
| 50 | + let paramIdx = 1; |
| 51 | + |
| 52 | + if (status) { |
| 53 | + conditions.push(`status = $${paramIdx++}`); |
| 54 | + params.push(status); |
| 55 | + } |
| 56 | + if (category) { |
| 57 | + conditions.push(`category ILIKE $${paramIdx++}`); |
| 58 | + params.push(`%${category}%`); |
| 59 | + } |
| 60 | + if (payee) { |
| 61 | + conditions.push(`payee ILIKE $${paramIdx++}`); |
| 62 | + params.push(`%${payee}%`); |
| 63 | + } |
| 64 | + |
| 65 | + const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; |
| 66 | + const rows = await sql( |
| 67 | + `SELECT id, payee, amount_due, due_date, status, category, auto_pay, urgency_score |
| 68 | + FROM cc_obligations ${where} |
| 69 | + ORDER BY due_date ASC NULLS LAST LIMIT 20`, |
| 70 | + params, |
| 71 | + ); |
| 72 | + return { obligations: rows, count: rows.length }; |
| 73 | + }, |
| 74 | + }), |
| 75 | + |
| 76 | + query_disputes: tool({ |
| 77 | + description: 'Search active disputes by status or type.', |
| 78 | + inputSchema: z.object({ |
| 79 | + status: z.enum(['open', 'pending', 'escalated', 'resolved', 'dismissed']).optional(), |
| 80 | + dispute_type: z.string().optional().describe('Filter by dispute type'), |
| 81 | + }), |
| 82 | + execute: async ({ status, dispute_type }) => { |
| 83 | + const conditions: string[] = []; |
| 84 | + const params: unknown[] = []; |
| 85 | + let paramIdx = 1; |
| 86 | + |
| 87 | + if (status) { |
| 88 | + conditions.push(`status = $${paramIdx++}`); |
| 89 | + params.push(status); |
| 90 | + } |
| 91 | + if (dispute_type) { |
| 92 | + conditions.push(`dispute_type ILIKE $${paramIdx++}`); |
| 93 | + params.push(`%${dispute_type}%`); |
| 94 | + } |
| 95 | + |
| 96 | + const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; |
| 97 | + const rows = await sql( |
| 98 | + `SELECT id, title, counterparty, dispute_type, amount_claimed, stage, status, priority, next_action, next_action_date |
| 99 | + FROM cc_disputes ${where} |
| 100 | + ORDER BY priority ASC LIMIT 20`, |
| 101 | + params, |
| 102 | + ); |
| 103 | + return { disputes: rows, count: rows.length }; |
| 104 | + }, |
| 105 | + }), |
| 106 | + |
| 107 | + get_recommendations: tool({ |
| 108 | + description: 'Get active recommendations from the action queue, enriched with obligation details.', |
| 109 | + inputSchema: z.object({ |
| 110 | + limit: z.number().min(1).max(20).optional().describe('Number of results (default 10)'), |
| 111 | + }), |
| 112 | + execute: async ({ limit }) => { |
| 113 | + const n = limit ?? 10; |
| 114 | + const rows = await sql` |
| 115 | + SELECT r.id, r.rec_type, r.priority, r.title, r.reasoning, |
| 116 | + r.action_type, r.estimated_savings, r.confidence, |
| 117 | + r.suggested_amount, r.escalation_risk, |
| 118 | + o.payee, o.amount_due, o.due_date, o.category, o.status as ob_status |
| 119 | + FROM cc_recommendations r |
| 120 | + LEFT JOIN cc_obligations o ON r.obligation_id = o.id |
| 121 | + WHERE r.status = 'active' |
| 122 | + ORDER BY r.priority ASC |
| 123 | + LIMIT ${n} |
| 124 | + `; |
| 125 | + return { recommendations: rows, count: rows.length }; |
| 126 | + }, |
| 127 | + }), |
| 128 | + |
| 129 | + approve_action: tool({ |
| 130 | + description: 'Approve a recommendation from the action queue. This is a WRITE operation that marks the recommendation as completed and logs the action. Use this when the user explicitly asks to approve or execute a recommendation.', |
| 131 | + inputSchema: z.object({ |
| 132 | + recommendation_id: z.string().uuid().describe('The recommendation ID to approve'), |
| 133 | + action_notes: z.string().optional().describe('Optional notes about the action taken'), |
| 134 | + }), |
| 135 | + execute: async ({ recommendation_id, action_notes }) => { |
| 136 | + // Verify the recommendation exists and is active |
| 137 | + const [rec] = await sql` |
| 138 | + SELECT id, title, action_type FROM cc_recommendations |
| 139 | + WHERE id = ${recommendation_id}::uuid AND status = 'active' |
| 140 | + `; |
| 141 | + if (!rec) { |
| 142 | + return { success: false, error: 'Recommendation not found or already completed' }; |
| 143 | + } |
| 144 | + |
| 145 | + // Mark as completed and log the action |
| 146 | + await sql`UPDATE cc_recommendations SET status = 'completed' WHERE id = ${recommendation_id}::uuid`; |
| 147 | + await sql` |
| 148 | + INSERT INTO cc_actions_log (action_type, target_type, target_id, description, status) |
| 149 | + VALUES ('recommendation_acted', 'recommendation', ${recommendation_id}, ${action_notes || rec.title}, 'completed') |
| 150 | + `; |
| 151 | + |
| 152 | + return { success: true, recommendation: rec.title, action_type: rec.action_type }; |
| 153 | + }, |
| 154 | + }), |
| 155 | + |
| 156 | + get_legal_deadlines: tool({ |
| 157 | + description: 'Get upcoming legal deadlines within a specified number of days.', |
| 158 | + inputSchema: z.object({ |
| 159 | + days_ahead: z.number().min(1).max(90).optional().describe('Days to look ahead (default 30)'), |
| 160 | + }), |
| 161 | + execute: async ({ days_ahead }) => { |
| 162 | + const days = days_ahead ?? 30; |
| 163 | + const rows = await sql` |
| 164 | + SELECT id, case_ref, title, deadline_type, deadline_date, status, urgency_score |
| 165 | + FROM cc_legal_deadlines |
| 166 | + WHERE status = 'pending' |
| 167 | + AND deadline_date <= CURRENT_DATE + (${days} || ' days')::interval |
| 168 | + ORDER BY deadline_date ASC |
| 169 | + `; |
| 170 | + return { deadlines: rows, count: rows.length }; |
| 171 | + }, |
| 172 | + }), |
| 173 | + |
| 174 | + get_cashflow_projection: tool({ |
| 175 | + description: 'Get the latest cash flow projection showing expected inflows, outflows, and balance.', |
| 176 | + inputSchema: z.object({}), |
| 177 | + execute: async () => { |
| 178 | + const rows = await sql` |
| 179 | + SELECT projection_date, projected_inflow, projected_outflow, projected_balance, confidence |
| 180 | + FROM cc_cashflow_projections |
| 181 | + ORDER BY projection_date ASC |
| 182 | + LIMIT 30 |
| 183 | + `; |
| 184 | + return { projections: rows, count: rows.length }; |
| 185 | + }, |
| 186 | + }), |
| 187 | + }; |
| 188 | +} |
0 commit comments