@dizzlkheinz/ynab-mcpb 0.18.3 → 0.18.4
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/CHANGELOG.md +17 -0
- package/dist/bundle/index.cjs +40 -40
- package/dist/tools/reconcileAdapter.js +3 -0
- package/dist/tools/reconciliation/analyzer.js +72 -7
- package/dist/tools/reconciliation/reportFormatter.js +26 -2
- package/dist/tools/reconciliation/types.d.ts +3 -0
- package/dist/tools/transactionSchemas.d.ts +309 -0
- package/dist/tools/transactionSchemas.js +215 -0
- package/dist/tools/transactionTools.d.ts +3 -281
- package/dist/tools/transactionTools.js +4 -559
- package/dist/tools/transactionUtils.d.ts +31 -0
- package/dist/tools/transactionUtils.js +349 -0
- package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
- package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
- package/package.json +4 -2
- package/scripts/run-all-tests.js +196 -0
- package/src/tools/__tests__/transactionSchemas.test.ts +1188 -0
- package/src/tools/__tests__/transactionUtils.test.ts +989 -0
- package/src/tools/reconcileAdapter.ts +6 -0
- package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +22 -8
- package/src/tools/reconciliation/__tests__/adapter.test.ts +3 -0
- package/src/tools/reconciliation/__tests__/analyzer.test.ts +65 -0
- package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +3 -0
- package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +4 -1
- package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +3 -0
- package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +5 -1
- package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +22 -8
- package/src/tools/reconciliation/analyzer.ts +127 -11
- package/src/tools/reconciliation/reportFormatter.ts +39 -2
- package/src/tools/reconciliation/types.ts +6 -0
- package/src/tools/transactionSchemas.ts +453 -0
- package/src/tools/transactionTools.ts +102 -823
- package/src/tools/transactionUtils.ts +536 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { ValidationError } from '../types/index.js';
|
|
3
|
+
import { responseFormatter } from '../server/responseFormatter.js';
|
|
4
|
+
import { cacheManager, CacheManager } from '../server/cacheManager.js';
|
|
5
|
+
import { globalRequestLogger } from '../server/requestLogger.js';
|
|
6
|
+
const FULL_RESPONSE_THRESHOLD = 64 * 1024;
|
|
7
|
+
const SUMMARY_RESPONSE_THRESHOLD = 96 * 1024;
|
|
8
|
+
const MAX_RESPONSE_BYTES = 100 * 1024;
|
|
9
|
+
export function ensureTransaction(transaction, errorMessage) {
|
|
10
|
+
if (!transaction) {
|
|
11
|
+
throw new Error(errorMessage);
|
|
12
|
+
}
|
|
13
|
+
return transaction;
|
|
14
|
+
}
|
|
15
|
+
export function appendCategoryIds(source, target) {
|
|
16
|
+
if (!source) {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (source.category_id) {
|
|
20
|
+
target.add(source.category_id);
|
|
21
|
+
}
|
|
22
|
+
if (Array.isArray(source.subtransactions)) {
|
|
23
|
+
for (const sub of source.subtransactions) {
|
|
24
|
+
if (sub?.category_id) {
|
|
25
|
+
target.add(sub.category_id);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function collectCategoryIdsFromSources(...sources) {
|
|
31
|
+
const result = new Set();
|
|
32
|
+
for (const source of sources) {
|
|
33
|
+
appendCategoryIds(source, result);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
export function setsEqual(a, b) {
|
|
38
|
+
if (a.size !== b.size) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
for (const value of a) {
|
|
42
|
+
if (!b.has(value)) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
export const toMonthKey = (date) => `${date.slice(0, 7)}-01`;
|
|
49
|
+
export function invalidateTransactionCaches(deltaCache, knowledgeStore, budgetId, serverKnowledge, affectedAccountIds, affectedMonths, options = {}) {
|
|
50
|
+
deltaCache.invalidate(budgetId, 'transactions');
|
|
51
|
+
cacheManager.delete(CacheManager.generateKey('transactions', 'list', budgetId));
|
|
52
|
+
for (const accountId of affectedAccountIds) {
|
|
53
|
+
const accountPrefix = CacheManager.generateKey('transactions', 'account', budgetId, accountId);
|
|
54
|
+
cacheManager.deleteByPrefix(accountPrefix);
|
|
55
|
+
}
|
|
56
|
+
const invalidateAccountsList = options.accountTotalsChanged ?? true;
|
|
57
|
+
if (invalidateAccountsList) {
|
|
58
|
+
cacheManager.delete(CacheManager.generateKey('accounts', 'list', budgetId));
|
|
59
|
+
}
|
|
60
|
+
for (const accountId of affectedAccountIds) {
|
|
61
|
+
cacheManager.delete(CacheManager.generateKey('account', 'get', budgetId, accountId));
|
|
62
|
+
}
|
|
63
|
+
const affectedCategoryIds = options.affectedCategoryIds ?? new Set();
|
|
64
|
+
const shouldInvalidateCategories = options.invalidateAllCategories || affectedCategoryIds.size > 0;
|
|
65
|
+
if (shouldInvalidateCategories) {
|
|
66
|
+
cacheManager.delete(CacheManager.generateKey('categories', 'list', budgetId));
|
|
67
|
+
for (const categoryId of affectedCategoryIds) {
|
|
68
|
+
cacheManager.delete(CacheManager.generateKey('category', 'get', budgetId, categoryId));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const shouldInvalidateMonths = options.invalidateMonths ?? affectedMonths.size > 0;
|
|
72
|
+
if (shouldInvalidateMonths) {
|
|
73
|
+
cacheManager.delete(CacheManager.generateKey('months', 'list', budgetId));
|
|
74
|
+
deltaCache.invalidate(budgetId, 'months');
|
|
75
|
+
for (const month of affectedMonths) {
|
|
76
|
+
cacheManager.delete(CacheManager.generateKey('month', 'get', budgetId, month));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (serverKnowledge !== undefined) {
|
|
80
|
+
const transactionCacheKey = CacheManager.generateKey('transactions', 'list', budgetId);
|
|
81
|
+
knowledgeStore.update(transactionCacheKey, serverKnowledge);
|
|
82
|
+
if (invalidateAccountsList) {
|
|
83
|
+
const accountsCacheKey = CacheManager.generateKey('accounts', 'list', budgetId);
|
|
84
|
+
knowledgeStore.update(accountsCacheKey, serverKnowledge);
|
|
85
|
+
}
|
|
86
|
+
if (shouldInvalidateMonths && affectedMonths.size > 0) {
|
|
87
|
+
const monthsCacheKey = CacheManager.generateKey('months', 'list', budgetId);
|
|
88
|
+
knowledgeStore.update(monthsCacheKey, serverKnowledge);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function generateCorrelationKey(transaction) {
|
|
93
|
+
if (transaction.import_id) {
|
|
94
|
+
return transaction.import_id;
|
|
95
|
+
}
|
|
96
|
+
const segments = [
|
|
97
|
+
`account:${transaction.account_id ?? ''}`,
|
|
98
|
+
`date:${transaction.date ?? ''}`,
|
|
99
|
+
`amount:${transaction.amount ?? 0}`,
|
|
100
|
+
`payee:${transaction.payee_id ?? transaction.payee_name ?? ''}`,
|
|
101
|
+
`category:${transaction.category_id ?? ''}`,
|
|
102
|
+
`memo:${transaction.memo ?? ''}`,
|
|
103
|
+
`cleared:${transaction.cleared ?? ''}`,
|
|
104
|
+
`approved:${transaction.approved ?? false}`,
|
|
105
|
+
`flag:${transaction.flag_color ?? ''}`,
|
|
106
|
+
];
|
|
107
|
+
const normalized = segments.join('|');
|
|
108
|
+
const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16);
|
|
109
|
+
return `hash:${hash}`;
|
|
110
|
+
}
|
|
111
|
+
export function toCorrelationPayload(transaction) {
|
|
112
|
+
const payload = {};
|
|
113
|
+
if (transaction.account_id !== undefined) {
|
|
114
|
+
payload.account_id = transaction.account_id;
|
|
115
|
+
}
|
|
116
|
+
if (transaction.date !== undefined) {
|
|
117
|
+
payload.date = transaction.date;
|
|
118
|
+
}
|
|
119
|
+
if (transaction.amount !== undefined) {
|
|
120
|
+
payload.amount = transaction.amount;
|
|
121
|
+
}
|
|
122
|
+
if (transaction.cleared !== undefined) {
|
|
123
|
+
payload.cleared = transaction.cleared;
|
|
124
|
+
}
|
|
125
|
+
if (transaction.approved !== undefined) {
|
|
126
|
+
payload.approved = transaction.approved;
|
|
127
|
+
}
|
|
128
|
+
if (transaction.flag_color !== undefined) {
|
|
129
|
+
payload.flag_color = transaction.flag_color;
|
|
130
|
+
}
|
|
131
|
+
payload.payee_id = transaction.payee_id ?? null;
|
|
132
|
+
payload.payee_name = transaction.payee_name ?? null;
|
|
133
|
+
payload.category_id = transaction.category_id ?? null;
|
|
134
|
+
payload.memo = transaction.memo ?? null;
|
|
135
|
+
payload.import_id = transaction.import_id ?? null;
|
|
136
|
+
return payload;
|
|
137
|
+
}
|
|
138
|
+
export function correlateResults(requests, responseData, duplicateImportIds) {
|
|
139
|
+
const createdByImportId = new Map();
|
|
140
|
+
const createdByHash = new Map();
|
|
141
|
+
const responseTransactions = responseData.transactions ?? [];
|
|
142
|
+
const register = (map, key, transactionId) => {
|
|
143
|
+
const existing = map.get(key);
|
|
144
|
+
if (existing) {
|
|
145
|
+
existing.push(transactionId);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
map.set(key, [transactionId]);
|
|
149
|
+
};
|
|
150
|
+
for (const transaction of responseTransactions) {
|
|
151
|
+
if (!transaction.id) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const key = generateCorrelationKey(transaction);
|
|
155
|
+
if (key.startsWith('hash:')) {
|
|
156
|
+
register(createdByHash, key, transaction.id);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
register(createdByImportId, key, transaction.id);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const popId = (map, key) => {
|
|
163
|
+
const bucket = map.get(key);
|
|
164
|
+
if (!bucket || bucket.length === 0) {
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
const [transactionId] = bucket.splice(0, 1);
|
|
168
|
+
if (bucket.length === 0) {
|
|
169
|
+
map.delete(key);
|
|
170
|
+
}
|
|
171
|
+
return transactionId;
|
|
172
|
+
};
|
|
173
|
+
const correlatedResults = [];
|
|
174
|
+
for (const [index, transaction] of requests.entries()) {
|
|
175
|
+
const normalizedRequest = toCorrelationPayload(transaction);
|
|
176
|
+
const correlationKey = generateCorrelationKey(normalizedRequest);
|
|
177
|
+
if (transaction.import_id && duplicateImportIds.has(transaction.import_id)) {
|
|
178
|
+
correlatedResults.push({
|
|
179
|
+
request_index: index,
|
|
180
|
+
status: 'duplicate',
|
|
181
|
+
correlation_key: correlationKey,
|
|
182
|
+
});
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
let transactionId;
|
|
186
|
+
if (correlationKey.startsWith('hash:')) {
|
|
187
|
+
transactionId = popId(createdByHash, correlationKey);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
transactionId = popId(createdByImportId, correlationKey);
|
|
191
|
+
}
|
|
192
|
+
if (!transactionId && !correlationKey.startsWith('hash:')) {
|
|
193
|
+
const hashKey = generateCorrelationKey(toCorrelationPayload({ ...transaction, import_id: undefined }));
|
|
194
|
+
transactionId = popId(createdByHash, hashKey);
|
|
195
|
+
}
|
|
196
|
+
if (transactionId) {
|
|
197
|
+
const successResult = {
|
|
198
|
+
request_index: index,
|
|
199
|
+
status: 'created',
|
|
200
|
+
correlation_key: correlationKey,
|
|
201
|
+
};
|
|
202
|
+
successResult.transaction_id = transactionId;
|
|
203
|
+
correlatedResults.push(successResult);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
globalRequestLogger.logError('ynab:create_transactions', 'correlate_results', {
|
|
207
|
+
request_index: index,
|
|
208
|
+
correlation_key: correlationKey,
|
|
209
|
+
request: {
|
|
210
|
+
account_id: transaction.account_id,
|
|
211
|
+
date: transaction.date,
|
|
212
|
+
amount: transaction.amount,
|
|
213
|
+
import_id: transaction.import_id,
|
|
214
|
+
},
|
|
215
|
+
}, 'correlation_failed');
|
|
216
|
+
correlatedResults.push({
|
|
217
|
+
request_index: index,
|
|
218
|
+
status: 'failed',
|
|
219
|
+
correlation_key: correlationKey,
|
|
220
|
+
error_code: 'correlation_failed',
|
|
221
|
+
error: 'Unable to correlate request transaction with YNAB response',
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return correlatedResults;
|
|
225
|
+
}
|
|
226
|
+
export function estimatePayloadSize(payload) {
|
|
227
|
+
return Buffer.byteLength(JSON.stringify(payload), 'utf8');
|
|
228
|
+
}
|
|
229
|
+
export function finalizeResponse(response) {
|
|
230
|
+
const appendMessage = (message, addition) => {
|
|
231
|
+
if (!message) {
|
|
232
|
+
return addition;
|
|
233
|
+
}
|
|
234
|
+
if (message.includes(addition)) {
|
|
235
|
+
return message;
|
|
236
|
+
}
|
|
237
|
+
return `${message} ${addition}`;
|
|
238
|
+
};
|
|
239
|
+
const fullSize = estimatePayloadSize({ ...response, mode: 'full' });
|
|
240
|
+
if (fullSize <= FULL_RESPONSE_THRESHOLD) {
|
|
241
|
+
return { ...response, mode: 'full' };
|
|
242
|
+
}
|
|
243
|
+
const { transactions, ...summaryResponse } = response;
|
|
244
|
+
const summaryPayload = {
|
|
245
|
+
...summaryResponse,
|
|
246
|
+
message: appendMessage(response.message, 'Response downgraded to summary to stay under size limits.'),
|
|
247
|
+
mode: 'summary',
|
|
248
|
+
};
|
|
249
|
+
if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
|
|
250
|
+
return summaryPayload;
|
|
251
|
+
}
|
|
252
|
+
const idsOnlyPayload = {
|
|
253
|
+
...summaryPayload,
|
|
254
|
+
results: summaryResponse.results.map((result) => ({
|
|
255
|
+
request_index: result.request_index,
|
|
256
|
+
status: result.status,
|
|
257
|
+
transaction_id: result.transaction_id,
|
|
258
|
+
correlation_key: result.correlation_key,
|
|
259
|
+
error: result.error,
|
|
260
|
+
})),
|
|
261
|
+
message: appendMessage(summaryResponse.message, 'Response downgraded to ids_only to meet 100KB limit.'),
|
|
262
|
+
mode: 'ids_only',
|
|
263
|
+
};
|
|
264
|
+
if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
|
|
265
|
+
return idsOnlyPayload;
|
|
266
|
+
}
|
|
267
|
+
throw new ValidationError('RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit', `Batch size: ${response.summary.total_requested} transactions`, ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches']);
|
|
268
|
+
}
|
|
269
|
+
export function finalizeBulkUpdateResponse(response) {
|
|
270
|
+
const appendMessage = (message, addition) => {
|
|
271
|
+
if (!message) {
|
|
272
|
+
return addition;
|
|
273
|
+
}
|
|
274
|
+
if (message.includes(addition)) {
|
|
275
|
+
return message;
|
|
276
|
+
}
|
|
277
|
+
return `${message} ${addition}`;
|
|
278
|
+
};
|
|
279
|
+
const fullSize = estimatePayloadSize(response);
|
|
280
|
+
if (fullSize <= FULL_RESPONSE_THRESHOLD) {
|
|
281
|
+
return { ...response, mode: 'full' };
|
|
282
|
+
}
|
|
283
|
+
const { transactions, ...summaryResponse } = response;
|
|
284
|
+
const summaryPayload = {
|
|
285
|
+
...summaryResponse,
|
|
286
|
+
message: appendMessage(response.message, 'Response downgraded to summary to stay under size limits.'),
|
|
287
|
+
mode: 'summary',
|
|
288
|
+
};
|
|
289
|
+
if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
|
|
290
|
+
return summaryPayload;
|
|
291
|
+
}
|
|
292
|
+
const idsOnlyPayload = {
|
|
293
|
+
...summaryPayload,
|
|
294
|
+
results: summaryResponse.results.map((result) => {
|
|
295
|
+
const simplified = {
|
|
296
|
+
request_index: result.request_index,
|
|
297
|
+
status: result.status,
|
|
298
|
+
transaction_id: result.transaction_id,
|
|
299
|
+
correlation_key: result.correlation_key,
|
|
300
|
+
};
|
|
301
|
+
if (result.error) {
|
|
302
|
+
simplified.error = result.error;
|
|
303
|
+
}
|
|
304
|
+
if (result.error_code) {
|
|
305
|
+
simplified.error_code = result.error_code;
|
|
306
|
+
}
|
|
307
|
+
return simplified;
|
|
308
|
+
}),
|
|
309
|
+
message: appendMessage(summaryResponse.message, 'Response downgraded to ids_only to meet 100KB limit.'),
|
|
310
|
+
mode: 'ids_only',
|
|
311
|
+
};
|
|
312
|
+
if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
|
|
313
|
+
return idsOnlyPayload;
|
|
314
|
+
}
|
|
315
|
+
throw new ValidationError('RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit', `Batch size: ${response.summary.total_requested} transactions`, ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches']);
|
|
316
|
+
}
|
|
317
|
+
export function handleTransactionError(error, defaultMessage) {
|
|
318
|
+
let errorMessage = defaultMessage;
|
|
319
|
+
if (error instanceof Error) {
|
|
320
|
+
if (error.message.includes('401') || error.message.includes('Unauthorized')) {
|
|
321
|
+
errorMessage = 'Invalid or expired YNAB access token';
|
|
322
|
+
}
|
|
323
|
+
else if (error.message.includes('403') || error.message.includes('Forbidden')) {
|
|
324
|
+
errorMessage = 'Insufficient permissions to access YNAB data';
|
|
325
|
+
}
|
|
326
|
+
else if (error.message.includes('404') || error.message.includes('Not Found')) {
|
|
327
|
+
errorMessage = 'Budget, account, category, or transaction not found';
|
|
328
|
+
}
|
|
329
|
+
else if (error.message.includes('429') || error.message.includes('Too Many Requests')) {
|
|
330
|
+
errorMessage = 'Rate limit exceeded. Please try again later';
|
|
331
|
+
}
|
|
332
|
+
else if (error.message.includes('500') || error.message.includes('Internal Server Error')) {
|
|
333
|
+
errorMessage = 'YNAB service is currently unavailable';
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
isError: true,
|
|
338
|
+
content: [
|
|
339
|
+
{
|
|
340
|
+
type: 'text',
|
|
341
|
+
text: responseFormatter.format({
|
|
342
|
+
error: {
|
|
343
|
+
message: errorMessage,
|
|
344
|
+
},
|
|
345
|
+
}),
|
|
346
|
+
},
|
|
347
|
+
],
|
|
348
|
+
};
|
|
349
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# TransactionTools Refactoring Design
|
|
2
|
+
|
|
3
|
+
**Date:** 2025-12-25
|
|
4
|
+
**Status:** Completed
|
|
5
|
+
**Reviewed by:** Claude (Opus 4.5), Gemini CLI
|
|
6
|
+
|
|
7
|
+
## Problem Statement
|
|
8
|
+
|
|
9
|
+
`src/tools/transactionTools.ts` was 2,995 lines - the largest file in the codebase by 3x. It mixed multiple concerns:
|
|
10
|
+
- Zod schemas and type definitions
|
|
11
|
+
- Cache invalidation utilities
|
|
12
|
+
- Correlation logic for bulk operations
|
|
13
|
+
- 7 CRUD handler functions
|
|
14
|
+
- Receipt split transaction logic
|
|
15
|
+
|
|
16
|
+
This made the file difficult to navigate and maintain.
|
|
17
|
+
|
|
18
|
+
## Goals
|
|
19
|
+
|
|
20
|
+
1. ✅ Reduce `transactionTools.ts` to ~2,000 lines (30% reduction) - **Actual: 2,274 lines (24% reduction)**
|
|
21
|
+
2. ✅ Separate concerns into logical modules
|
|
22
|
+
3. ✅ Maintain backward compatibility (single consumer: `YNABMCPServer.ts`)
|
|
23
|
+
4. ✅ Preserve existing test coverage (5,212 lines of tests)
|
|
24
|
+
5. ✅ Avoid circular dependencies
|
|
25
|
+
|
|
26
|
+
## Non-Goals
|
|
27
|
+
|
|
28
|
+
- Full modular directory structure (e.g., `src/tools/transactions/`)
|
|
29
|
+
- Extracting receipt split logic (creates circular dependency with `handleCreateTransaction`)
|
|
30
|
+
- Moving schemas to `src/tools/schemas/` (existing pattern keeps tool-specific schemas near tools)
|
|
31
|
+
|
|
32
|
+
## Design
|
|
33
|
+
|
|
34
|
+
### File Structure
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
src/tools/
|
|
38
|
+
├── transactionTools.ts # Handlers + registration (2,274 lines)
|
|
39
|
+
├── transactionSchemas.ts # Schemas + types + interfaces (453 lines)
|
|
40
|
+
└── transactionUtils.ts # Cache utils + correlation + finalizeResponse (536 lines)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### File Contents
|
|
44
|
+
|
|
45
|
+
#### `transactionSchemas.ts` (453 lines)
|
|
46
|
+
|
|
47
|
+
All Zod schemas and their inferred types:
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
// Schemas
|
|
51
|
+
export const ListTransactionsSchema = z.object({...});
|
|
52
|
+
export const GetTransactionSchema = z.object({...});
|
|
53
|
+
export const CreateTransactionSchema = z.object({...});
|
|
54
|
+
export const CreateTransactionsSchema = z.object({...});
|
|
55
|
+
export const CreateReceiptSplitTransactionSchema = z.object({...});
|
|
56
|
+
export const UpdateTransactionSchema = z.object({...});
|
|
57
|
+
export const UpdateTransactionsSchema = z.object({...});
|
|
58
|
+
export const DeleteTransactionSchema = z.object({...});
|
|
59
|
+
export const BulkUpdateTransactionInputSchema = z.object({...});
|
|
60
|
+
|
|
61
|
+
// Inferred types
|
|
62
|
+
export type ListTransactionsParams = z.infer<typeof ListTransactionsSchema>;
|
|
63
|
+
export type GetTransactionParams = z.infer<typeof GetTransactionSchema>;
|
|
64
|
+
// ... etc
|
|
65
|
+
|
|
66
|
+
// Interfaces
|
|
67
|
+
export interface BulkTransactionResult {...}
|
|
68
|
+
export interface BulkCreateResponse {...}
|
|
69
|
+
export interface BulkUpdateResult {...}
|
|
70
|
+
export interface BulkUpdateResponse {...}
|
|
71
|
+
export interface CorrelationPayload {...}
|
|
72
|
+
export interface CorrelationPayloadInput {...}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
#### `transactionUtils.ts` (536 lines)
|
|
76
|
+
|
|
77
|
+
Cache invalidation, correlation, and response utilities:
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
// Cache invalidation
|
|
81
|
+
export function invalidateTransactionCaches(
|
|
82
|
+
deltaCache: DeltaCache,
|
|
83
|
+
knowledgeStore: ServerKnowledgeStore,
|
|
84
|
+
budgetId: string,
|
|
85
|
+
serverKnowledge: number | undefined,
|
|
86
|
+
affectedAccountIds: Set<string>,
|
|
87
|
+
affectedMonths: Set<string>,
|
|
88
|
+
options: TransactionCacheInvalidationOptions = {},
|
|
89
|
+
): void;
|
|
90
|
+
|
|
91
|
+
// Category helpers
|
|
92
|
+
export function appendCategoryIds(source: CategorySource, target: Set<string>): void;
|
|
93
|
+
export function collectCategoryIdsFromSources(...sources: CategorySource[]): Set<string>;
|
|
94
|
+
export function setsEqual<T>(a: Set<T>, b: Set<T>): boolean;
|
|
95
|
+
|
|
96
|
+
// Correlation for bulk operations
|
|
97
|
+
export function generateCorrelationKey(transaction: {...}): string;
|
|
98
|
+
export function toCorrelationPayload(transaction: CorrelationPayloadInput): CorrelationPayload;
|
|
99
|
+
export function correlateResults(inputs: CorrelationPayloadInput[], results: BulkTransactionResult[]): Map<string, ...>;
|
|
100
|
+
|
|
101
|
+
// Response utilities
|
|
102
|
+
export function estimatePayloadSize(payload: BulkCreateResponse | BulkUpdateResponse): number;
|
|
103
|
+
export function finalizeResponse(response: BulkCreateResponse): BulkCreateResponse;
|
|
104
|
+
export function finalizeBulkUpdateResponse(response: BulkUpdateResponse): BulkUpdateResponse;
|
|
105
|
+
|
|
106
|
+
// Error handling
|
|
107
|
+
export function handleTransactionError(error: unknown, defaultMessage: string): CallToolResult;
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
#### `transactionTools.ts` (2,274 lines)
|
|
111
|
+
|
|
112
|
+
All handler functions + tool registration:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import {
|
|
116
|
+
ListTransactionsSchema,
|
|
117
|
+
CreateTransactionSchema,
|
|
118
|
+
// ... all schemas
|
|
119
|
+
} from './transactionSchemas.js';
|
|
120
|
+
|
|
121
|
+
import {
|
|
122
|
+
invalidateTransactionCaches,
|
|
123
|
+
correlateResults,
|
|
124
|
+
// ... all utils
|
|
125
|
+
} from './transactionUtils.js';
|
|
126
|
+
|
|
127
|
+
// Handler functions (keep all together to avoid circular deps)
|
|
128
|
+
export async function handleListTransactions(...);
|
|
129
|
+
export async function handleGetTransaction(...);
|
|
130
|
+
export async function handleCreateTransaction(...);
|
|
131
|
+
export async function handleCreateReceiptSplitTransaction(...); // Calls handleCreateTransaction
|
|
132
|
+
export async function handleUpdateTransaction(...);
|
|
133
|
+
export async function handleCreateTransactions(...);
|
|
134
|
+
export async function handleUpdateTransactions(...);
|
|
135
|
+
export async function handleDeleteTransaction(...);
|
|
136
|
+
|
|
137
|
+
// Receipt split helpers (pure functions, stay here due to tight coupling)
|
|
138
|
+
function truncateToLength(str: string, maxLength: number): string;
|
|
139
|
+
function buildItemMemo(item: {...}): string;
|
|
140
|
+
function applySmartCollapseLogic(...): SaveSubTransaction[];
|
|
141
|
+
function collapseItemsByCategory(...): SaveSubTransaction[];
|
|
142
|
+
function truncateItemName(...): string;
|
|
143
|
+
function buildCollapsedMemo(...): string;
|
|
144
|
+
function allocateTax(...): void;
|
|
145
|
+
|
|
146
|
+
// Tool registration
|
|
147
|
+
export const registerTransactionTools: ToolFactory = (registry, context) => {...};
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Import Graph
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
transactionSchemas.ts ←──┐
|
|
154
|
+
↓ │
|
|
155
|
+
transactionUtils.ts ──────┤ (imports types from schemas)
|
|
156
|
+
↓ │
|
|
157
|
+
transactionTools.ts ──────┘ (imports both, no cycles)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Circular Dependency Avoidance
|
|
161
|
+
|
|
162
|
+
`handleCreateReceiptSplitTransaction` calls `handleCreateTransaction` at line 1665:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
const baseResult = await handleCreateTransaction(
|
|
166
|
+
ynabAPI,
|
|
167
|
+
deltaCache,
|
|
168
|
+
knowledgeStore,
|
|
169
|
+
createTransactionParams,
|
|
170
|
+
);
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
If receipt split were extracted to its own file, it would need to import `handleCreateTransaction`, while `transactionTools.ts` would import the receipt split handler for registration - creating a cycle.
|
|
174
|
+
|
|
175
|
+
**Solution:** Keep all handlers in `transactionTools.ts`.
|
|
176
|
+
|
|
177
|
+
## Migration Strategy
|
|
178
|
+
|
|
179
|
+
1. Create `transactionSchemas.ts` with all schemas and types
|
|
180
|
+
2. Create `transactionUtils.ts` with cache/correlation utilities
|
|
181
|
+
3. Update `transactionTools.ts` imports
|
|
182
|
+
4. Run tests to verify no regressions
|
|
183
|
+
5. Update any imports in `YNABMCPServer.ts` if needed
|
|
184
|
+
|
|
185
|
+
## Test Impact
|
|
186
|
+
|
|
187
|
+
- Existing tests import from `transactionTools.ts`
|
|
188
|
+
- Most tests should continue working with re-exports
|
|
189
|
+
- May need to update imports for tests that directly use schemas/utils
|
|
190
|
+
- No logic changes = no new test requirements
|
|
191
|
+
|
|
192
|
+
## Rollback Plan
|
|
193
|
+
|
|
194
|
+
If issues arise, revert the 3-file split back to single file. Git makes this trivial.
|
|
195
|
+
|
|
196
|
+
## Success Criteria
|
|
197
|
+
|
|
198
|
+
- [x] `transactionTools.ts` reduced to ~2,000 lines (Actual: 2,274 lines, 24% reduction from 2,995)
|
|
199
|
+
- [x] All 5,212 lines of tests pass
|
|
200
|
+
- [x] No circular dependency warnings
|
|
201
|
+
- [x] Build succeeds with no type errors
|
|
202
|
+
- [x] `npm run lint` passes
|
|
203
|
+
|
|
204
|
+
## Final Outcome
|
|
205
|
+
|
|
206
|
+
The refactoring successfully split the 2,995-line file into three focused modules:
|
|
207
|
+
- **transactionTools.ts**: 2,274 lines (handlers and registration)
|
|
208
|
+
- **transactionSchemas.ts**: 453 lines (Zod schemas and types)
|
|
209
|
+
- **transactionUtils.ts**: 536 lines (utilities and helpers)
|
|
210
|
+
|
|
211
|
+
Total: 3,263 lines (268-line overhead from imports/exports, 9% overhead which is acceptable for improved maintainability)
|