@dizzlkheinz/ynab-mcpb 0.18.4 → 0.19.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.
- package/CLAUDE.md +87 -8
- package/bin/ynab-mcp-server.cjs +2 -2
- package/bin/ynab-mcp-server.js +3 -3
- package/biome.json +39 -0
- package/dist/bundle/index.cjs +67 -67
- package/dist/index.d.ts +1 -1
- package/dist/index.js +27 -27
- package/dist/server/YNABMCPServer.d.ts +3 -4
- package/dist/server/YNABMCPServer.js +111 -116
- package/dist/server/budgetResolver.d.ts +6 -5
- package/dist/server/budgetResolver.js +46 -36
- package/dist/server/cacheKeys.js +6 -6
- package/dist/server/cacheManager.js +14 -11
- package/dist/server/completions.d.ts +2 -2
- package/dist/server/completions.js +20 -15
- package/dist/server/config.d.ts +10 -5
- package/dist/server/config.js +24 -7
- package/dist/server/deltaCache.d.ts +2 -2
- package/dist/server/deltaCache.js +22 -16
- package/dist/server/deltaCache.merge.d.ts +2 -2
- package/dist/server/diagnostics.d.ts +4 -4
- package/dist/server/diagnostics.js +38 -32
- package/dist/server/errorHandler.d.ts +5 -12
- package/dist/server/errorHandler.js +219 -217
- package/dist/server/prompts.d.ts +2 -2
- package/dist/server/prompts.js +45 -45
- package/dist/server/rateLimiter.js +4 -4
- package/dist/server/requestLogger.d.ts +1 -1
- package/dist/server/requestLogger.js +40 -35
- package/dist/server/resources.d.ts +3 -3
- package/dist/server/resources.js +55 -52
- package/dist/server/responseFormatter.js +6 -6
- package/dist/server/securityMiddleware.d.ts +2 -2
- package/dist/server/securityMiddleware.js +22 -20
- package/dist/server/serverKnowledgeStore.js +1 -1
- package/dist/server/toolRegistry.d.ts +3 -3
- package/dist/server/toolRegistry.js +47 -40
- package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
- package/dist/tools/__tests__/deltaTestUtils.js +2 -2
- package/dist/tools/accountTools.d.ts +9 -8
- package/dist/tools/accountTools.js +47 -47
- package/dist/tools/adapters.d.ts +13 -8
- package/dist/tools/adapters.js +21 -11
- package/dist/tools/budgetTools.d.ts +8 -7
- package/dist/tools/budgetTools.js +22 -22
- package/dist/tools/categoryTools.d.ts +9 -8
- package/dist/tools/categoryTools.js +68 -59
- package/dist/tools/compareTransactions/formatter.d.ts +3 -3
- package/dist/tools/compareTransactions/formatter.js +9 -9
- package/dist/tools/compareTransactions/index.d.ts +6 -6
- package/dist/tools/compareTransactions/index.js +58 -43
- package/dist/tools/compareTransactions/matcher.d.ts +1 -1
- package/dist/tools/compareTransactions/matcher.js +28 -15
- package/dist/tools/compareTransactions/parser.d.ts +2 -2
- package/dist/tools/compareTransactions/parser.js +144 -138
- package/dist/tools/compareTransactions/types.d.ts +4 -4
- package/dist/tools/compareTransactions.d.ts +1 -1
- package/dist/tools/compareTransactions.js +1 -1
- package/dist/tools/deltaFetcher.d.ts +2 -2
- package/dist/tools/deltaFetcher.js +16 -15
- package/dist/tools/deltaSupport.d.ts +4 -4
- package/dist/tools/deltaSupport.js +35 -41
- package/dist/tools/exportTransactions.d.ts +5 -4
- package/dist/tools/exportTransactions.js +61 -59
- package/dist/tools/monthTools.d.ts +7 -6
- package/dist/tools/monthTools.js +31 -29
- package/dist/tools/payeeTools.d.ts +7 -6
- package/dist/tools/payeeTools.js +28 -28
- package/dist/tools/reconcileAdapter.d.ts +2 -2
- package/dist/tools/reconcileAdapter.js +19 -12
- package/dist/tools/reconciliation/analyzer.d.ts +4 -4
- package/dist/tools/reconciliation/analyzer.js +73 -59
- package/dist/tools/reconciliation/csvParser.d.ts +3 -3
- package/dist/tools/reconciliation/csvParser.js +128 -104
- package/dist/tools/reconciliation/executor.d.ts +4 -4
- package/dist/tools/reconciliation/executor.js +148 -109
- package/dist/tools/reconciliation/index.d.ts +10 -10
- package/dist/tools/reconciliation/index.js +96 -83
- package/dist/tools/reconciliation/matcher.d.ts +3 -3
- package/dist/tools/reconciliation/matcher.js +17 -16
- package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
- package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
- package/dist/tools/reconciliation/recommendationEngine.js +40 -40
- package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
- package/dist/tools/reconciliation/reportFormatter.js +59 -58
- package/dist/tools/reconciliation/signDetector.d.ts +1 -1
- package/dist/tools/reconciliation/types.d.ts +16 -16
- package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
- package/dist/tools/schemas/common.d.ts +1 -1
- package/dist/tools/schemas/common.js +1 -1
- package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
- package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
- package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
- package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
- package/dist/tools/schemas/outputs/index.d.ts +14 -14
- package/dist/tools/schemas/outputs/index.js +14 -14
- package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
- package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
- package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
- package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
- package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
- package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
- package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
- package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
- package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
- package/dist/tools/schemas/shared/commonOutputs.js +15 -9
- package/dist/tools/transactionReadTools.d.ts +11 -0
- package/dist/tools/transactionReadTools.js +202 -0
- package/dist/tools/transactionSchemas.d.ts +7 -7
- package/dist/tools/transactionSchemas.js +77 -57
- package/dist/tools/transactionTools.d.ts +6 -24
- package/dist/tools/transactionTools.js +7 -1499
- package/dist/tools/transactionUtils.d.ts +6 -6
- package/dist/tools/transactionUtils.js +78 -63
- package/dist/tools/transactionWriteTools.d.ts +20 -0
- package/dist/tools/transactionWriteTools.js +1342 -0
- package/dist/tools/utilityTools.d.ts +5 -4
- package/dist/tools/utilityTools.js +11 -11
- package/dist/types/index.d.ts +7 -7
- package/dist/types/index.js +6 -6
- package/dist/types/reconciliation.d.ts +1 -1
- package/dist/types/toolRegistration.d.ts +14 -12
- package/dist/utils/amountUtils.js +1 -1
- package/dist/utils/dateUtils.js +4 -4
- package/dist/utils/errors.d.ts +3 -3
- package/dist/utils/errors.js +4 -4
- package/dist/utils/money.d.ts +2 -2
- package/dist/utils/money.js +8 -8
- package/dist/utils/validationError.d.ts +1 -1
- package/dist/utils/validationError.js +1 -1
- package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
- package/docs/assets/schemas/reconciliation-v2.json +360 -336
- package/esbuild.config.mjs +53 -50
- package/meta.json +12548 -12548
- package/package.json +98 -111
- package/scripts/analyze-bundle.mjs +33 -30
- package/scripts/create-pr-description.js +169 -120
- package/scripts/run-all-tests.js +178 -169
- package/scripts/run-domain-integration-tests.js +28 -18
- package/scripts/run-generate-mcpb.js +19 -17
- package/scripts/run-throttled-integration-tests.js +92 -83
- package/scripts/test-delta-params.mjs +149 -120
- package/scripts/test-recommendations.ts +36 -32
- package/scripts/tmpTransaction.ts +80 -43
- package/scripts/validate-env.js +98 -91
- package/scripts/verify-build.js +78 -76
- package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
- package/src/__tests__/performance.test.ts +723 -671
- package/src/__tests__/setup.ts +442 -395
- package/src/__tests__/smoke.e2e.test.ts +41 -39
- package/src/__tests__/testRunner.ts +314 -295
- package/src/__tests__/testUtils.ts +456 -364
- package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
- package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
- package/src/index.ts +68 -59
- package/src/server/CLAUDE.md +480 -0
- package/src/server/YNABMCPServer.ts +821 -794
- package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
- package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
- package/src/server/__tests__/budgetResolver.test.ts +466 -423
- package/src/server/__tests__/cacheManager.test.ts +891 -874
- package/src/server/__tests__/completions.integration.test.ts +115 -106
- package/src/server/__tests__/completions.test.ts +334 -313
- package/src/server/__tests__/config.test.ts +98 -86
- package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
- package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
- package/src/server/__tests__/deltaCache.test.ts +946 -759
- package/src/server/__tests__/diagnostics.test.ts +825 -792
- package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
- package/src/server/__tests__/errorHandler.test.ts +402 -397
- package/src/server/__tests__/prompts.test.ts +424 -347
- package/src/server/__tests__/rateLimiter.test.ts +313 -309
- package/src/server/__tests__/requestLogger.test.ts +443 -403
- package/src/server/__tests__/resources.template.test.ts +196 -185
- package/src/server/__tests__/resources.test.ts +294 -288
- package/src/server/__tests__/security.integration.test.ts +487 -421
- package/src/server/__tests__/securityMiddleware.test.ts +519 -444
- package/src/server/__tests__/server-startup.integration.test.ts +509 -490
- package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
- package/src/server/__tests__/toolRegistration.test.ts +239 -210
- package/src/server/__tests__/toolRegistry.test.ts +907 -845
- package/src/server/budgetResolver.ts +221 -181
- package/src/server/cacheKeys.ts +6 -6
- package/src/server/cacheManager.ts +498 -484
- package/src/server/completions.ts +267 -243
- package/src/server/config.ts +35 -14
- package/src/server/deltaCache.merge.ts +146 -128
- package/src/server/deltaCache.ts +352 -309
- package/src/server/diagnostics.ts +257 -242
- package/src/server/errorHandler.ts +747 -744
- package/src/server/prompts.ts +181 -176
- package/src/server/rateLimiter.ts +131 -129
- package/src/server/requestLogger.ts +350 -322
- package/src/server/resources.ts +442 -374
- package/src/server/responseFormatter.ts +41 -37
- package/src/server/securityMiddleware.ts +223 -205
- package/src/server/serverKnowledgeStore.ts +67 -67
- package/src/server/toolRegistry.ts +508 -474
- package/src/tools/CLAUDE.md +604 -0
- package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
- package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
- package/src/tools/__tests__/accountTools.test.ts +685 -638
- package/src/tools/__tests__/adapters.test.ts +142 -108
- package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
- package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
- package/src/tools/__tests__/budgetTools.test.ts +442 -413
- package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
- package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
- package/src/tools/__tests__/categoryTools.test.ts +656 -625
- package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
- package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
- package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
- package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
- package/src/tools/__tests__/compareTransactions.test.ts +352 -332
- package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
- package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
- package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
- package/src/tools/__tests__/deltaSupport.test.ts +211 -184
- package/src/tools/__tests__/deltaTestUtils.ts +37 -33
- package/src/tools/__tests__/exportTransactions.test.ts +205 -200
- package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
- package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
- package/src/tools/__tests__/monthTools.test.ts +561 -512
- package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
- package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
- package/src/tools/__tests__/payeeTools.test.ts +486 -434
- package/src/tools/__tests__/transactionSchemas.test.ts +1202 -1186
- package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
- package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
- package/src/tools/__tests__/transactionUtils.test.ts +1004 -977
- package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
- package/src/tools/__tests__/utilityTools.test.ts +68 -58
- package/src/tools/accountTools.ts +293 -271
- package/src/tools/adapters.ts +120 -63
- package/src/tools/budgetTools.ts +121 -116
- package/src/tools/categoryTools.ts +379 -339
- package/src/tools/compareTransactions/formatter.ts +131 -119
- package/src/tools/compareTransactions/index.ts +249 -214
- package/src/tools/compareTransactions/matcher.ts +259 -209
- package/src/tools/compareTransactions/parser.ts +517 -487
- package/src/tools/compareTransactions/types.ts +38 -38
- package/src/tools/compareTransactions.ts +1 -1
- package/src/tools/deltaFetcher.ts +281 -260
- package/src/tools/deltaSupport.ts +264 -259
- package/src/tools/exportTransactions.ts +230 -218
- package/src/tools/monthTools.ts +180 -165
- package/src/tools/payeeTools.ts +152 -140
- package/src/tools/reconcileAdapter.ts +297 -252
- package/src/tools/reconciliation/CLAUDE.md +506 -0
- package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +133 -124
- package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -230
- package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -400
- package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
- package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
- package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
- package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
- package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
- package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
- package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
- package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -989
- package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
- package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -533
- package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -74
- package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -62
- package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
- package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +56 -55
- package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
- package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
- package/src/tools/reconciliation/analyzer.ts +564 -504
- package/src/tools/reconciliation/csvParser.ts +656 -609
- package/src/tools/reconciliation/executor.ts +1290 -1128
- package/src/tools/reconciliation/index.ts +580 -528
- package/src/tools/reconciliation/matcher.ts +256 -240
- package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
- package/src/tools/reconciliation/recommendationEngine.ts +357 -345
- package/src/tools/reconciliation/reportFormatter.ts +343 -307
- package/src/tools/reconciliation/signDetector.ts +89 -83
- package/src/tools/reconciliation/types.ts +164 -159
- package/src/tools/reconciliation/ynabAdapter.ts +17 -15
- package/src/tools/schemas/CLAUDE.md +546 -0
- package/src/tools/schemas/common.ts +1 -1
- package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
- package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
- package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
- package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
- package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
- package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
- package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
- package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
- package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
- package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
- package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
- package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
- package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
- package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
- package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
- package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
- package/src/tools/schemas/outputs/index.ts +163 -163
- package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
- package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
- package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
- package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
- package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
- package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
- package/src/tools/schemas/shared/commonOutputs.ts +27 -19
- package/src/tools/toolCategories.ts +114 -114
- package/src/tools/transactionReadTools.ts +327 -0
- package/src/tools/transactionSchemas.ts +322 -291
- package/src/tools/transactionTools.ts +84 -2246
- package/src/tools/transactionUtils.ts +507 -422
- package/src/tools/transactionWriteTools.ts +2110 -0
- package/src/tools/utilityTools.ts +46 -41
- package/src/types/CLAUDE.md +477 -0
- package/src/types/__tests__/index.test.ts +51 -51
- package/src/types/index.ts +43 -39
- package/src/types/integration-tests.d.ts +26 -26
- package/src/types/reconciliation.ts +29 -29
- package/src/types/toolAnnotations.ts +30 -30
- package/src/types/toolRegistration.ts +43 -32
- package/src/utils/CLAUDE.md +508 -0
- package/src/utils/__tests__/dateUtils.test.ts +174 -168
- package/src/utils/__tests__/money.test.ts +193 -187
- package/src/utils/amountUtils.ts +5 -5
- package/src/utils/baseError.ts +5 -5
- package/src/utils/dateUtils.ts +29 -26
- package/src/utils/errors.ts +14 -14
- package/src/utils/money.ts +66 -52
- package/src/utils/validationError.ts +1 -1
- package/tsconfig.json +29 -29
- package/tsconfig.prod.json +16 -16
- package/vitest-reporters/split-json-reporter.ts +247 -204
- package/vitest.config.ts +99 -95
- package/.prettierignore +0 -10
- package/.prettierrc.json +0 -10
- package/eslint.config.js +0 -49
|
@@ -1,1501 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { ToolAnnotationPresets } from './toolCategories.js';
|
|
4
|
-
import { responseFormatter } from '../server/responseFormatter.js';
|
|
5
|
-
import { amountToMilliunits, milliunitsToAmount } from '../utils/amountUtils.js';
|
|
6
|
-
import { cacheManager, CACHE_TTLS, CacheManager } from '../server/cacheManager.js';
|
|
7
|
-
import { globalRequestLogger } from '../server/requestLogger.js';
|
|
8
|
-
import { resolveDeltaFetcherArgs, resolveDeltaWriteArgs } from './deltaSupport.js';
|
|
9
|
-
import { handleExportTransactions, ExportTransactionsSchema } from './exportTransactions.js';
|
|
10
|
-
import { ListTransactionsSchema, GetTransactionSchema, CreateTransactionSchema, CreateTransactionsSchema, CreateReceiptSplitTransactionSchema, UpdateTransactionSchema, UpdateTransactionsSchema, DeleteTransactionSchema, } from './transactionSchemas.js';
|
|
11
|
-
import { ensureTransaction, appendCategoryIds, collectCategoryIdsFromSources, setsEqual, invalidateTransactionCaches, correlateResults, finalizeResponse, finalizeBulkUpdateResponse, handleTransactionError, toMonthKey, } from './transactionUtils.js';
|
|
12
|
-
export async function handleListTransactions(ynabAPI, deltaFetcherOrParams, maybeParams) {
|
|
13
|
-
const { deltaFetcher, params } = resolveDeltaFetcherArgs(ynabAPI, deltaFetcherOrParams, maybeParams);
|
|
14
|
-
return await withToolErrorHandling(async () => {
|
|
15
|
-
let transactions;
|
|
16
|
-
let cacheHit = false;
|
|
17
|
-
let usedDelta = false;
|
|
18
|
-
if (params.account_id) {
|
|
19
|
-
const accountsResult = await deltaFetcher.fetchAccounts(params.budget_id);
|
|
20
|
-
const accountExists = accountsResult.data.some((account) => account.id === params.account_id);
|
|
21
|
-
if (!accountExists) {
|
|
22
|
-
throw new Error(`Account ${params.account_id} not found in budget ${params.budget_id}`);
|
|
23
|
-
}
|
|
24
|
-
const result = await deltaFetcher.fetchTransactionsByAccount(params.budget_id, params.account_id, params.since_date);
|
|
25
|
-
transactions = result.data;
|
|
26
|
-
cacheHit = result.wasCached;
|
|
27
|
-
usedDelta = result.usedDelta;
|
|
28
|
-
}
|
|
29
|
-
else if (params.category_id) {
|
|
30
|
-
const response = await ynabAPI.transactions.getTransactionsByCategory(params.budget_id, params.category_id, params.since_date);
|
|
31
|
-
transactions = response.data.transactions;
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
const result = await deltaFetcher.fetchTransactions(params.budget_id, params.since_date, params.type);
|
|
35
|
-
transactions = result.data;
|
|
36
|
-
cacheHit = result.wasCached;
|
|
37
|
-
usedDelta = result.usedDelta;
|
|
38
|
-
}
|
|
39
|
-
const estimatedSize = JSON.stringify(transactions).length;
|
|
40
|
-
const sizeLimit = 90000;
|
|
41
|
-
if (estimatedSize > sizeLimit) {
|
|
42
|
-
const preview = transactions.slice(0, 50);
|
|
43
|
-
return {
|
|
44
|
-
content: [
|
|
45
|
-
{
|
|
46
|
-
type: 'text',
|
|
47
|
-
text: responseFormatter.format({
|
|
48
|
-
message: `Found ${transactions.length} transactions (${Math.round(estimatedSize / 1024)}KB). Too large to display all.`,
|
|
49
|
-
suggestion: "Use 'export_transactions' tool to save all transactions to a file.",
|
|
50
|
-
showing: `First ${preview.length} transactions:`,
|
|
51
|
-
total_count: transactions.length,
|
|
52
|
-
estimated_size_kb: Math.round(estimatedSize / 1024),
|
|
53
|
-
cached: cacheHit,
|
|
54
|
-
cache_info: cacheHit
|
|
55
|
-
? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
|
|
56
|
-
: 'Fresh data retrieved from YNAB API',
|
|
57
|
-
preview_transactions: preview.map((transaction) => ({
|
|
58
|
-
id: transaction.id,
|
|
59
|
-
date: transaction.date,
|
|
60
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
61
|
-
memo: transaction.memo,
|
|
62
|
-
payee_name: transaction.payee_name,
|
|
63
|
-
category_name: transaction.category_name,
|
|
64
|
-
})),
|
|
65
|
-
}),
|
|
66
|
-
},
|
|
67
|
-
],
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
return {
|
|
71
|
-
content: [
|
|
72
|
-
{
|
|
73
|
-
type: 'text',
|
|
74
|
-
text: responseFormatter.format({
|
|
75
|
-
total_count: transactions.length,
|
|
76
|
-
cached: cacheHit,
|
|
77
|
-
cache_info: cacheHit
|
|
78
|
-
? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
|
|
79
|
-
: 'Fresh data retrieved from YNAB API',
|
|
80
|
-
transactions: transactions.map((transaction) => ({
|
|
81
|
-
id: transaction.id,
|
|
82
|
-
date: transaction.date,
|
|
83
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
84
|
-
memo: transaction.memo,
|
|
85
|
-
cleared: transaction.cleared,
|
|
86
|
-
approved: transaction.approved,
|
|
87
|
-
flag_color: transaction.flag_color,
|
|
88
|
-
account_id: transaction.account_id,
|
|
89
|
-
payee_id: transaction.payee_id,
|
|
90
|
-
category_id: transaction.category_id,
|
|
91
|
-
transfer_account_id: transaction.transfer_account_id,
|
|
92
|
-
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
93
|
-
matched_transaction_id: transaction.matched_transaction_id,
|
|
94
|
-
import_id: transaction.import_id,
|
|
95
|
-
deleted: transaction.deleted,
|
|
96
|
-
})),
|
|
97
|
-
}),
|
|
98
|
-
},
|
|
99
|
-
],
|
|
100
|
-
};
|
|
101
|
-
}, 'ynab:list_transactions', 'listing transactions');
|
|
102
|
-
}
|
|
103
|
-
export async function handleGetTransaction(ynabAPI, params) {
|
|
104
|
-
try {
|
|
105
|
-
const useCache = process.env['NODE_ENV'] !== 'test';
|
|
106
|
-
let transaction;
|
|
107
|
-
let cacheHit = false;
|
|
108
|
-
if (useCache) {
|
|
109
|
-
const cacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
110
|
-
cacheHit = cacheManager.has(cacheKey);
|
|
111
|
-
transaction = await cacheManager.wrap(cacheKey, {
|
|
112
|
-
ttl: CACHE_TTLS.TRANSACTIONS,
|
|
113
|
-
loader: async () => {
|
|
114
|
-
const response = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
115
|
-
return ensureTransaction(response.data.transaction, 'Transaction not found');
|
|
116
|
-
},
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
else {
|
|
120
|
-
const response = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
121
|
-
transaction = ensureTransaction(response.data.transaction, 'Transaction not found');
|
|
122
|
-
}
|
|
123
|
-
return {
|
|
124
|
-
content: [
|
|
125
|
-
{
|
|
126
|
-
type: 'text',
|
|
127
|
-
text: responseFormatter.format({
|
|
128
|
-
transaction: {
|
|
129
|
-
id: transaction.id,
|
|
130
|
-
date: transaction.date,
|
|
131
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
132
|
-
memo: transaction.memo,
|
|
133
|
-
cleared: transaction.cleared,
|
|
134
|
-
approved: transaction.approved,
|
|
135
|
-
flag_color: transaction.flag_color,
|
|
136
|
-
account_id: transaction.account_id,
|
|
137
|
-
payee_id: transaction.payee_id,
|
|
138
|
-
category_id: transaction.category_id,
|
|
139
|
-
transfer_account_id: transaction.transfer_account_id,
|
|
140
|
-
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
141
|
-
matched_transaction_id: transaction.matched_transaction_id,
|
|
142
|
-
import_id: transaction.import_id,
|
|
143
|
-
deleted: transaction.deleted,
|
|
144
|
-
account_name: transaction.account_name,
|
|
145
|
-
payee_name: transaction.payee_name,
|
|
146
|
-
category_name: transaction.category_name,
|
|
147
|
-
},
|
|
148
|
-
cached: cacheHit,
|
|
149
|
-
cache_info: cacheHit
|
|
150
|
-
? 'Data retrieved from cache for improved performance'
|
|
151
|
-
: 'Fresh data retrieved from YNAB API',
|
|
152
|
-
}),
|
|
153
|
-
},
|
|
154
|
-
],
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
catch (error) {
|
|
158
|
-
return handleTransactionError(error, 'Failed to get transaction');
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
export async function handleCreateTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
162
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
163
|
-
try {
|
|
164
|
-
if (params.dry_run) {
|
|
165
|
-
return {
|
|
166
|
-
content: [
|
|
167
|
-
{
|
|
168
|
-
type: 'text',
|
|
169
|
-
text: responseFormatter.format({
|
|
170
|
-
dry_run: true,
|
|
171
|
-
action: 'create_transaction',
|
|
172
|
-
request: params,
|
|
173
|
-
}),
|
|
174
|
-
},
|
|
175
|
-
],
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
const transactionData = {
|
|
179
|
-
account_id: params.account_id,
|
|
180
|
-
amount: params.amount,
|
|
181
|
-
date: params.date,
|
|
182
|
-
cleared: params.cleared,
|
|
183
|
-
flag_color: params.flag_color,
|
|
184
|
-
};
|
|
185
|
-
if (params.payee_name !== undefined)
|
|
186
|
-
transactionData.payee_name = params.payee_name;
|
|
187
|
-
if (params.payee_id !== undefined)
|
|
188
|
-
transactionData.payee_id = params.payee_id;
|
|
189
|
-
if (params.category_id !== undefined)
|
|
190
|
-
transactionData.category_id = params.category_id;
|
|
191
|
-
if (params.memo !== undefined)
|
|
192
|
-
transactionData.memo = params.memo;
|
|
193
|
-
if (params.approved !== undefined)
|
|
194
|
-
transactionData.approved = params.approved;
|
|
195
|
-
if (params.import_id !== undefined)
|
|
196
|
-
transactionData.import_id = params.import_id;
|
|
197
|
-
if (params.subtransactions && params.subtransactions.length > 0) {
|
|
198
|
-
const subtransactions = params.subtransactions.map((subtransaction) => {
|
|
199
|
-
const mapped = {
|
|
200
|
-
amount: subtransaction.amount,
|
|
201
|
-
};
|
|
202
|
-
if (subtransaction.payee_name !== undefined)
|
|
203
|
-
mapped.payee_name = subtransaction.payee_name;
|
|
204
|
-
if (subtransaction.payee_id !== undefined)
|
|
205
|
-
mapped.payee_id = subtransaction.payee_id;
|
|
206
|
-
if (subtransaction.category_id !== undefined) {
|
|
207
|
-
mapped.category_id = subtransaction.category_id;
|
|
208
|
-
}
|
|
209
|
-
if (subtransaction.memo !== undefined)
|
|
210
|
-
mapped.memo = subtransaction.memo;
|
|
211
|
-
return mapped;
|
|
212
|
-
});
|
|
213
|
-
transactionData.subtransactions = subtransactions;
|
|
214
|
-
}
|
|
215
|
-
const response = await ynabAPI.transactions.createTransaction(params.budget_id, {
|
|
216
|
-
transaction: transactionData,
|
|
217
|
-
});
|
|
218
|
-
const transaction = ensureTransaction(response.data.transaction, 'Transaction creation failed');
|
|
219
|
-
const affectedAccountIds = new Set([transaction.account_id]);
|
|
220
|
-
const affectedMonths = new Set([toMonthKey(transaction.date)]);
|
|
221
|
-
const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
222
|
-
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
223
|
-
affectedCategoryIds,
|
|
224
|
-
accountTotalsChanged: true,
|
|
225
|
-
invalidateMonths: true,
|
|
226
|
-
});
|
|
227
|
-
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
228
|
-
const account = accountResponse.data.account;
|
|
229
|
-
return {
|
|
230
|
-
content: [
|
|
231
|
-
{
|
|
232
|
-
type: 'text',
|
|
233
|
-
text: responseFormatter.format({
|
|
234
|
-
transaction: {
|
|
235
|
-
id: transaction.id,
|
|
236
|
-
date: transaction.date,
|
|
237
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
238
|
-
memo: transaction.memo,
|
|
239
|
-
cleared: transaction.cleared,
|
|
240
|
-
approved: transaction.approved,
|
|
241
|
-
flag_color: transaction.flag_color,
|
|
242
|
-
account_id: transaction.account_id,
|
|
243
|
-
payee_id: transaction.payee_id,
|
|
244
|
-
category_id: transaction.category_id,
|
|
245
|
-
transfer_account_id: transaction.transfer_account_id,
|
|
246
|
-
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
247
|
-
matched_transaction_id: transaction.matched_transaction_id,
|
|
248
|
-
import_id: transaction.import_id,
|
|
249
|
-
deleted: transaction.deleted,
|
|
250
|
-
account_balance: account.balance,
|
|
251
|
-
account_cleared_balance: account.cleared_balance,
|
|
252
|
-
subtransactions: transaction.subtransactions?.map((subtransaction) => ({
|
|
253
|
-
id: subtransaction.id,
|
|
254
|
-
transaction_id: subtransaction.transaction_id,
|
|
255
|
-
amount: milliunitsToAmount(subtransaction.amount),
|
|
256
|
-
memo: subtransaction.memo,
|
|
257
|
-
payee_id: subtransaction.payee_id,
|
|
258
|
-
payee_name: subtransaction.payee_name,
|
|
259
|
-
category_id: subtransaction.category_id,
|
|
260
|
-
category_name: subtransaction.category_name,
|
|
261
|
-
transfer_account_id: subtransaction.transfer_account_id,
|
|
262
|
-
transfer_transaction_id: subtransaction.transfer_transaction_id,
|
|
263
|
-
deleted: subtransaction.deleted,
|
|
264
|
-
})),
|
|
265
|
-
},
|
|
266
|
-
}),
|
|
267
|
-
},
|
|
268
|
-
],
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
catch (error) {
|
|
272
|
-
return handleTransactionError(error, 'Failed to create transaction');
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
const BIG_TICKET_THRESHOLD_MILLIUNITS = 50000;
|
|
276
|
-
const COLLAPSE_THRESHOLD = 5;
|
|
277
|
-
const MAX_ITEMS_PER_MEMO = 5;
|
|
278
|
-
const MAX_MEMO_LENGTH = 150;
|
|
279
|
-
function truncateToLength(str, maxLength) {
|
|
280
|
-
if (str.length <= maxLength) {
|
|
281
|
-
return str;
|
|
282
|
-
}
|
|
283
|
-
const ellipsis = '...';
|
|
284
|
-
return str.substring(0, maxLength - ellipsis.length) + ellipsis;
|
|
285
|
-
}
|
|
286
|
-
function buildItemMemo(item) {
|
|
287
|
-
const quantitySuffix = item.quantity ? ` (x${item.quantity})` : '';
|
|
288
|
-
let result;
|
|
289
|
-
if (item.memo && item.memo.trim().length > 0) {
|
|
290
|
-
result = `${item.name}${quantitySuffix} - ${item.memo}`;
|
|
291
|
-
}
|
|
292
|
-
else if (quantitySuffix) {
|
|
293
|
-
result = `${item.name}${quantitySuffix}`;
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
result = item.name;
|
|
297
|
-
}
|
|
298
|
-
return truncateToLength(result, MAX_MEMO_LENGTH);
|
|
299
|
-
}
|
|
300
|
-
function applySmartCollapseLogic(categoryCalculations, taxMilliunits) {
|
|
301
|
-
const specialItems = [];
|
|
302
|
-
const remainingItemsByCategory = [];
|
|
303
|
-
for (const category of categoryCalculations) {
|
|
304
|
-
const categorySpecials = [];
|
|
305
|
-
const categoryRemaining = [];
|
|
306
|
-
for (const item of category.items) {
|
|
307
|
-
const isNegative = item.amount_milliunits < 0;
|
|
308
|
-
const unitPrice = item.quantity
|
|
309
|
-
? item.amount_milliunits / item.quantity
|
|
310
|
-
: item.amount_milliunits;
|
|
311
|
-
const isBigTicket = unitPrice > BIG_TICKET_THRESHOLD_MILLIUNITS;
|
|
312
|
-
if (isNegative || isBigTicket) {
|
|
313
|
-
categorySpecials.push(item);
|
|
314
|
-
}
|
|
315
|
-
else {
|
|
316
|
-
categoryRemaining.push(item);
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
for (const item of categorySpecials) {
|
|
320
|
-
specialItems.push({
|
|
321
|
-
item,
|
|
322
|
-
category_id: category.category_id,
|
|
323
|
-
category_name: category.category_name,
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
if (categoryRemaining.length > 0) {
|
|
327
|
-
remainingItemsByCategory.push({
|
|
328
|
-
category_id: category.category_id,
|
|
329
|
-
category_name: category.category_name,
|
|
330
|
-
items: categoryRemaining,
|
|
331
|
-
});
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
const totalRemainingItems = remainingItemsByCategory.reduce((sum, cat) => sum + cat.items.length, 0);
|
|
335
|
-
const shouldCollapse = totalRemainingItems >= COLLAPSE_THRESHOLD;
|
|
336
|
-
const subtransactions = [];
|
|
337
|
-
for (const special of specialItems) {
|
|
338
|
-
const memo = buildItemMemo({
|
|
339
|
-
name: special.item.name,
|
|
340
|
-
quantity: special.item.quantity,
|
|
341
|
-
memo: special.item.memo,
|
|
342
|
-
});
|
|
343
|
-
const payload = {
|
|
344
|
-
amount: -special.item.amount_milliunits,
|
|
345
|
-
category_id: special.category_id,
|
|
346
|
-
};
|
|
347
|
-
if (memo)
|
|
348
|
-
payload.memo = memo;
|
|
349
|
-
subtransactions.push(payload);
|
|
350
|
-
}
|
|
351
|
-
if (shouldCollapse) {
|
|
352
|
-
for (const categoryGroup of remainingItemsByCategory) {
|
|
353
|
-
const collapsedSubtransactions = collapseItemsByCategory(categoryGroup);
|
|
354
|
-
subtransactions.push(...collapsedSubtransactions);
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
else {
|
|
358
|
-
for (const categoryGroup of remainingItemsByCategory) {
|
|
359
|
-
for (const item of categoryGroup.items) {
|
|
360
|
-
const memo = buildItemMemo({
|
|
361
|
-
name: item.name,
|
|
362
|
-
quantity: item.quantity,
|
|
363
|
-
memo: item.memo,
|
|
364
|
-
});
|
|
365
|
-
const payload = {
|
|
366
|
-
amount: -item.amount_milliunits,
|
|
367
|
-
category_id: categoryGroup.category_id,
|
|
368
|
-
};
|
|
369
|
-
if (memo)
|
|
370
|
-
payload.memo = memo;
|
|
371
|
-
subtransactions.push(payload);
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
const taxSubtransactions = allocateTax(categoryCalculations, taxMilliunits);
|
|
376
|
-
subtransactions.push(...taxSubtransactions);
|
|
377
|
-
return subtransactions;
|
|
378
|
-
}
|
|
379
|
-
function collapseItemsByCategory(categoryGroup) {
|
|
380
|
-
const subtransactions = [];
|
|
381
|
-
const items = categoryGroup.items;
|
|
382
|
-
let currentBatch = [];
|
|
383
|
-
let currentBatchTotal = 0;
|
|
384
|
-
for (const item of items) {
|
|
385
|
-
if (currentBatch.length >= MAX_ITEMS_PER_MEMO) {
|
|
386
|
-
const memo = buildCollapsedMemo(currentBatch);
|
|
387
|
-
subtransactions.push({
|
|
388
|
-
amount: -currentBatchTotal,
|
|
389
|
-
category_id: categoryGroup.category_id,
|
|
390
|
-
memo,
|
|
391
|
-
});
|
|
392
|
-
currentBatch = [];
|
|
393
|
-
currentBatchTotal = 0;
|
|
394
|
-
}
|
|
395
|
-
const testBatch = [...currentBatch, item];
|
|
396
|
-
const testMemo = buildCollapsedMemo(testBatch);
|
|
397
|
-
if (testMemo.length <= MAX_MEMO_LENGTH) {
|
|
398
|
-
currentBatch.push(item);
|
|
399
|
-
currentBatchTotal += item.amount_milliunits;
|
|
400
|
-
}
|
|
401
|
-
else {
|
|
402
|
-
if (currentBatch.length > 0) {
|
|
403
|
-
const memo = buildCollapsedMemo(currentBatch);
|
|
404
|
-
subtransactions.push({
|
|
405
|
-
amount: -currentBatchTotal,
|
|
406
|
-
category_id: categoryGroup.category_id,
|
|
407
|
-
memo,
|
|
408
|
-
});
|
|
409
|
-
currentBatch = [item];
|
|
410
|
-
currentBatchTotal = item.amount_milliunits;
|
|
411
|
-
}
|
|
412
|
-
else {
|
|
413
|
-
currentBatch = [item];
|
|
414
|
-
currentBatchTotal = item.amount_milliunits;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
if (currentBatch.length > 0) {
|
|
419
|
-
const memo = buildCollapsedMemo(currentBatch);
|
|
420
|
-
subtransactions.push({
|
|
421
|
-
amount: -currentBatchTotal,
|
|
422
|
-
category_id: categoryGroup.category_id,
|
|
423
|
-
memo,
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
return subtransactions;
|
|
427
|
-
}
|
|
428
|
-
function truncateItemName(name, amountSuffix, maxLength) {
|
|
429
|
-
const ellipsis = '...';
|
|
430
|
-
const availableForName = maxLength - ellipsis.length - amountSuffix.length;
|
|
431
|
-
if (availableForName <= 0) {
|
|
432
|
-
return amountSuffix.substring(0, maxLength);
|
|
433
|
-
}
|
|
434
|
-
return name.substring(0, availableForName) + ellipsis + amountSuffix;
|
|
435
|
-
}
|
|
436
|
-
function buildCollapsedMemo(items) {
|
|
437
|
-
const parts = [];
|
|
438
|
-
let currentLength = 0;
|
|
439
|
-
for (let i = 0; i < items.length; i++) {
|
|
440
|
-
const item = items[i];
|
|
441
|
-
if (!item)
|
|
442
|
-
continue;
|
|
443
|
-
const amount = milliunitsToAmount(item.amount_milliunits);
|
|
444
|
-
const amountSuffix = ` $${amount.toFixed(2)}`;
|
|
445
|
-
let itemStr = `${item.name}${amountSuffix}`;
|
|
446
|
-
const separator = i > 0 ? ', ' : '';
|
|
447
|
-
if (parts.length === 0 && itemStr.length > MAX_MEMO_LENGTH) {
|
|
448
|
-
itemStr = truncateItemName(item.name, amountSuffix, MAX_MEMO_LENGTH);
|
|
449
|
-
}
|
|
450
|
-
const testLength = currentLength + separator.length + itemStr.length;
|
|
451
|
-
if (parts.length > 0 && testLength + 4 > MAX_MEMO_LENGTH) {
|
|
452
|
-
break;
|
|
453
|
-
}
|
|
454
|
-
parts.push(itemStr);
|
|
455
|
-
currentLength = testLength;
|
|
456
|
-
}
|
|
457
|
-
let result = parts.join(', ');
|
|
458
|
-
if (parts.length < items.length) {
|
|
459
|
-
result += '...';
|
|
460
|
-
}
|
|
461
|
-
return result;
|
|
462
|
-
}
|
|
463
|
-
function allocateTax(categoryCalculations, taxMilliunits) {
|
|
464
|
-
const subtransactions = [];
|
|
465
|
-
if (taxMilliunits === 0) {
|
|
466
|
-
return subtransactions;
|
|
467
|
-
}
|
|
468
|
-
if (taxMilliunits < 0) {
|
|
469
|
-
let largestReturnCategory = undefined;
|
|
470
|
-
let largestReturnAmount = 0;
|
|
471
|
-
for (const category of categoryCalculations) {
|
|
472
|
-
const categoryReturnAmount = category.items
|
|
473
|
-
.filter((item) => item.amount_milliunits < 0)
|
|
474
|
-
.reduce((sum, item) => sum + Math.abs(item.amount_milliunits), 0);
|
|
475
|
-
if (categoryReturnAmount > largestReturnAmount) {
|
|
476
|
-
largestReturnAmount = categoryReturnAmount;
|
|
477
|
-
largestReturnCategory = category;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
if (!largestReturnCategory) {
|
|
481
|
-
largestReturnCategory = categoryCalculations[0];
|
|
482
|
-
}
|
|
483
|
-
if (largestReturnCategory) {
|
|
484
|
-
subtransactions.push({
|
|
485
|
-
amount: -taxMilliunits,
|
|
486
|
-
category_id: largestReturnCategory.category_id,
|
|
487
|
-
memo: 'Tax refund',
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
return subtransactions;
|
|
491
|
-
}
|
|
492
|
-
const positiveCategorySubtotals = categoryCalculations
|
|
493
|
-
.map((cat) => ({
|
|
494
|
-
category: cat,
|
|
495
|
-
positiveSubtotal: cat.items
|
|
496
|
-
.filter((item) => item.amount_milliunits > 0)
|
|
497
|
-
.reduce((sum, item) => sum + item.amount_milliunits, 0),
|
|
498
|
-
}))
|
|
499
|
-
.filter((x) => x.positiveSubtotal > 0);
|
|
500
|
-
if (positiveCategorySubtotals.length === 0) {
|
|
501
|
-
return subtransactions;
|
|
502
|
-
}
|
|
503
|
-
const totalPositiveSubtotal = positiveCategorySubtotals.reduce((sum, x) => sum + x.positiveSubtotal, 0);
|
|
504
|
-
let allocatedTax = 0;
|
|
505
|
-
const taxAllocations = [];
|
|
506
|
-
for (let i = 0; i < positiveCategorySubtotals.length; i++) {
|
|
507
|
-
const entry = positiveCategorySubtotals[i];
|
|
508
|
-
if (!entry)
|
|
509
|
-
continue;
|
|
510
|
-
const { category, positiveSubtotal } = entry;
|
|
511
|
-
if (i === positiveCategorySubtotals.length - 1) {
|
|
512
|
-
const taxAmount = taxMilliunits - allocatedTax;
|
|
513
|
-
if (taxAmount > 0) {
|
|
514
|
-
taxAllocations.push({ category, taxAmount });
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
else {
|
|
518
|
-
const taxAmount = Math.round((taxMilliunits * positiveSubtotal) / totalPositiveSubtotal);
|
|
519
|
-
if (taxAmount > 0) {
|
|
520
|
-
taxAllocations.push({ category, taxAmount });
|
|
521
|
-
allocatedTax += taxAmount;
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
for (const { category, taxAmount } of taxAllocations) {
|
|
526
|
-
subtransactions.push({
|
|
527
|
-
amount: -taxAmount,
|
|
528
|
-
category_id: category.category_id,
|
|
529
|
-
memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
|
|
530
|
-
});
|
|
531
|
-
}
|
|
532
|
-
return subtransactions;
|
|
533
|
-
}
|
|
534
|
-
export async function handleCreateReceiptSplitTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
535
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
536
|
-
const date = params.date ?? new Date().toISOString().slice(0, 10);
|
|
537
|
-
const categoryCalculations = params.categories.map((category) => {
|
|
538
|
-
const items = category.items.map((item) => ({
|
|
539
|
-
name: item.name,
|
|
540
|
-
amount_milliunits: amountToMilliunits(item.amount),
|
|
541
|
-
quantity: item.quantity,
|
|
542
|
-
memo: item.memo,
|
|
543
|
-
}));
|
|
544
|
-
const subtotalMilliunits = items.reduce((sum, item) => sum + item.amount_milliunits, 0);
|
|
545
|
-
return {
|
|
546
|
-
category_id: category.category_id,
|
|
547
|
-
category_name: category.category_name,
|
|
548
|
-
subtotal_milliunits: subtotalMilliunits,
|
|
549
|
-
tax_milliunits: 0,
|
|
550
|
-
items,
|
|
551
|
-
};
|
|
552
|
-
});
|
|
553
|
-
const subtotalMilliunits = categoryCalculations.reduce((sum, category) => sum + category.subtotal_milliunits, 0);
|
|
554
|
-
const declaredSubtotalMilliunits = params.receipt_subtotal !== undefined ? amountToMilliunits(params.receipt_subtotal) : undefined;
|
|
555
|
-
if (declaredSubtotalMilliunits !== undefined &&
|
|
556
|
-
Math.abs(declaredSubtotalMilliunits - subtotalMilliunits) > 1) {
|
|
557
|
-
throw new Error(`Categorized items subtotal (${milliunitsToAmount(subtotalMilliunits)}) does not match receipt subtotal (${milliunitsToAmount(declaredSubtotalMilliunits)})`);
|
|
558
|
-
}
|
|
559
|
-
const taxMilliunits = amountToMilliunits(params.receipt_tax);
|
|
560
|
-
const totalMilliunits = amountToMilliunits(params.receipt_total);
|
|
561
|
-
const computedTotal = subtotalMilliunits + taxMilliunits;
|
|
562
|
-
if (Math.abs(computedTotal - totalMilliunits) > 1) {
|
|
563
|
-
throw new Error(`Receipt total (${milliunitsToAmount(totalMilliunits)}) does not equal subtotal plus tax (${milliunitsToAmount(computedTotal)})`);
|
|
564
|
-
}
|
|
565
|
-
const subtransactions = applySmartCollapseLogic(categoryCalculations, taxMilliunits);
|
|
566
|
-
if (taxMilliunits > 0) {
|
|
567
|
-
const positiveSubtotal = categoryCalculations.reduce((sum, cat) => sum + Math.max(0, cat.subtotal_milliunits), 0);
|
|
568
|
-
if (positiveSubtotal > 0) {
|
|
569
|
-
let remainingTax = taxMilliunits;
|
|
570
|
-
const positiveCats = categoryCalculations.filter((cat) => cat.subtotal_milliunits > 0);
|
|
571
|
-
positiveCats.forEach((cat, index) => {
|
|
572
|
-
if (index === positiveCats.length - 1) {
|
|
573
|
-
cat.tax_milliunits = remainingTax;
|
|
574
|
-
}
|
|
575
|
-
else {
|
|
576
|
-
const share = Math.round((cat.subtotal_milliunits / positiveSubtotal) * taxMilliunits);
|
|
577
|
-
cat.tax_milliunits = share;
|
|
578
|
-
remainingTax -= share;
|
|
579
|
-
}
|
|
580
|
-
});
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
const receiptSummary = {
|
|
584
|
-
subtotal: milliunitsToAmount(subtotalMilliunits),
|
|
585
|
-
tax: milliunitsToAmount(taxMilliunits),
|
|
586
|
-
total: milliunitsToAmount(totalMilliunits),
|
|
587
|
-
categories: categoryCalculations.map((category) => ({
|
|
588
|
-
category_id: category.category_id,
|
|
589
|
-
category_name: category.category_name,
|
|
590
|
-
items: category.items.map((item) => ({
|
|
591
|
-
name: item.name,
|
|
592
|
-
quantity: item.quantity,
|
|
593
|
-
amount: milliunitsToAmount(item.amount_milliunits),
|
|
594
|
-
memo: item.memo,
|
|
595
|
-
})),
|
|
596
|
-
subtotal: milliunitsToAmount(category.subtotal_milliunits),
|
|
597
|
-
tax: milliunitsToAmount(category.tax_milliunits),
|
|
598
|
-
total: milliunitsToAmount(category.subtotal_milliunits + category.tax_milliunits),
|
|
599
|
-
})),
|
|
600
|
-
};
|
|
601
|
-
if (params.dry_run) {
|
|
602
|
-
return {
|
|
603
|
-
content: [
|
|
604
|
-
{
|
|
605
|
-
type: 'text',
|
|
606
|
-
text: responseFormatter.format({
|
|
607
|
-
dry_run: true,
|
|
608
|
-
action: 'create_receipt_split_transaction',
|
|
609
|
-
transaction_preview: {
|
|
610
|
-
account_id: params.account_id,
|
|
611
|
-
payee_name: params.payee_name,
|
|
612
|
-
date,
|
|
613
|
-
amount: milliunitsToAmount(totalMilliunits),
|
|
614
|
-
cleared: params.cleared ?? 'uncleared',
|
|
615
|
-
},
|
|
616
|
-
receipt_summary: receiptSummary,
|
|
617
|
-
subtransactions: subtransactions.map((subtransaction) => ({
|
|
618
|
-
amount: milliunitsToAmount(-subtransaction.amount),
|
|
619
|
-
category_id: subtransaction.category_id,
|
|
620
|
-
memo: subtransaction.memo,
|
|
621
|
-
})),
|
|
622
|
-
}),
|
|
623
|
-
},
|
|
624
|
-
],
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
const createTransactionParams = {
|
|
628
|
-
budget_id: params.budget_id,
|
|
629
|
-
account_id: params.account_id,
|
|
630
|
-
amount: -totalMilliunits,
|
|
631
|
-
date,
|
|
632
|
-
payee_name: params.payee_name,
|
|
633
|
-
memo: params.memo,
|
|
634
|
-
cleared: params.cleared ?? 'uncleared',
|
|
635
|
-
flag_color: params.flag_color,
|
|
636
|
-
subtransactions: subtransactions,
|
|
637
|
-
};
|
|
638
|
-
if (params.approved !== undefined) {
|
|
639
|
-
createTransactionParams.approved = params.approved;
|
|
640
|
-
}
|
|
641
|
-
const baseResult = await handleCreateTransaction(ynabAPI, deltaCache, knowledgeStore, createTransactionParams);
|
|
642
|
-
const firstContent = baseResult.content?.[0];
|
|
643
|
-
if (!firstContent || firstContent.type !== 'text') {
|
|
644
|
-
return baseResult;
|
|
645
|
-
}
|
|
646
|
-
try {
|
|
647
|
-
const parsed = JSON.parse(firstContent.text);
|
|
648
|
-
parsed['receipt_summary'] = receiptSummary;
|
|
649
|
-
firstContent.text = responseFormatter.format(parsed);
|
|
650
|
-
}
|
|
651
|
-
catch {
|
|
652
|
-
}
|
|
653
|
-
return baseResult;
|
|
654
|
-
}
|
|
655
|
-
export async function handleUpdateTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
656
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
657
|
-
try {
|
|
658
|
-
if (params.dry_run) {
|
|
659
|
-
return {
|
|
660
|
-
content: [
|
|
661
|
-
{
|
|
662
|
-
type: 'text',
|
|
663
|
-
text: responseFormatter.format({
|
|
664
|
-
dry_run: true,
|
|
665
|
-
action: 'update_transaction',
|
|
666
|
-
request: params,
|
|
667
|
-
}),
|
|
668
|
-
},
|
|
669
|
-
],
|
|
670
|
-
};
|
|
671
|
-
}
|
|
672
|
-
const originalTransactionResponse = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
673
|
-
const originalTransaction = ensureTransaction(originalTransactionResponse.data.transaction, 'Original transaction not found');
|
|
674
|
-
const transactionData = {};
|
|
675
|
-
if (params.account_id !== undefined) {
|
|
676
|
-
transactionData.account_id = params.account_id;
|
|
677
|
-
}
|
|
678
|
-
if (params.amount !== undefined) {
|
|
679
|
-
transactionData.amount = params.amount;
|
|
680
|
-
}
|
|
681
|
-
if (params.date !== undefined) {
|
|
682
|
-
transactionData.date = params.date;
|
|
683
|
-
}
|
|
684
|
-
if (params.payee_name !== undefined) {
|
|
685
|
-
transactionData.payee_name = params.payee_name;
|
|
686
|
-
}
|
|
687
|
-
if (params.payee_id !== undefined) {
|
|
688
|
-
transactionData.payee_id = params.payee_id;
|
|
689
|
-
}
|
|
690
|
-
if (params.category_id !== undefined) {
|
|
691
|
-
transactionData.category_id = params.category_id;
|
|
692
|
-
}
|
|
693
|
-
if (params.memo !== undefined) {
|
|
694
|
-
transactionData.memo = params.memo;
|
|
695
|
-
}
|
|
696
|
-
if (params.cleared !== undefined) {
|
|
697
|
-
transactionData.cleared = params.cleared;
|
|
698
|
-
}
|
|
699
|
-
if (params.approved !== undefined) {
|
|
700
|
-
transactionData.approved = params.approved;
|
|
701
|
-
}
|
|
702
|
-
if (params.flag_color !== undefined) {
|
|
703
|
-
transactionData.flag_color = params.flag_color;
|
|
704
|
-
}
|
|
705
|
-
const response = await ynabAPI.transactions.updateTransaction(params.budget_id, params.transaction_id, {
|
|
706
|
-
transaction: transactionData,
|
|
707
|
-
});
|
|
708
|
-
const transaction = ensureTransaction(response.data.transaction, 'Transaction update failed');
|
|
709
|
-
const specificTransactionCacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
710
|
-
cacheManager.delete(specificTransactionCacheKey);
|
|
711
|
-
const affectedAccountIds = new Set([
|
|
712
|
-
originalTransaction.account_id,
|
|
713
|
-
transaction.account_id,
|
|
714
|
-
]);
|
|
715
|
-
if (originalTransaction.transfer_account_id) {
|
|
716
|
-
affectedAccountIds.add(originalTransaction.transfer_account_id);
|
|
717
|
-
}
|
|
718
|
-
if (transaction.transfer_account_id) {
|
|
719
|
-
affectedAccountIds.add(transaction.transfer_account_id);
|
|
720
|
-
}
|
|
721
|
-
const affectedMonths = new Set([
|
|
722
|
-
toMonthKey(originalTransaction.date),
|
|
723
|
-
toMonthKey(transaction.date),
|
|
724
|
-
]);
|
|
725
|
-
const originalCategoryIds = collectCategoryIdsFromSources(originalTransaction);
|
|
726
|
-
const updatedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
727
|
-
const affectedCategoryIds = new Set([...originalCategoryIds, ...updatedCategoryIds]);
|
|
728
|
-
const categoryChanged = !setsEqual(originalCategoryIds, updatedCategoryIds);
|
|
729
|
-
const amountChanged = transaction.amount !== originalTransaction.amount;
|
|
730
|
-
const accountChanged = transaction.account_id !== originalTransaction.account_id;
|
|
731
|
-
const clearedChanged = transaction.cleared !== originalTransaction.cleared;
|
|
732
|
-
const transferAccountChanged = transaction.transfer_account_id !== originalTransaction.transfer_account_id;
|
|
733
|
-
const transferLinkChanged = transaction.transfer_transaction_id !== originalTransaction.transfer_transaction_id;
|
|
734
|
-
const dateChanged = transaction.date !== originalTransaction.date;
|
|
735
|
-
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
736
|
-
affectedCategoryIds,
|
|
737
|
-
accountTotalsChanged: amountChanged ||
|
|
738
|
-
accountChanged ||
|
|
739
|
-
clearedChanged ||
|
|
740
|
-
transferAccountChanged ||
|
|
741
|
-
transferLinkChanged,
|
|
742
|
-
invalidateMonths: amountChanged || categoryChanged || dateChanged,
|
|
743
|
-
});
|
|
744
|
-
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
745
|
-
const account = accountResponse.data.account;
|
|
746
|
-
return {
|
|
747
|
-
content: [
|
|
748
|
-
{
|
|
749
|
-
type: 'text',
|
|
750
|
-
text: responseFormatter.format({
|
|
751
|
-
transaction: {
|
|
752
|
-
id: transaction.id,
|
|
753
|
-
date: transaction.date,
|
|
754
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
755
|
-
memo: transaction.memo,
|
|
756
|
-
cleared: transaction.cleared,
|
|
757
|
-
approved: transaction.approved,
|
|
758
|
-
flag_color: transaction.flag_color,
|
|
759
|
-
account_id: transaction.account_id,
|
|
760
|
-
payee_id: transaction.payee_id,
|
|
761
|
-
category_id: transaction.category_id,
|
|
762
|
-
transfer_account_id: transaction.transfer_account_id,
|
|
763
|
-
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
764
|
-
matched_transaction_id: transaction.matched_transaction_id,
|
|
765
|
-
import_id: transaction.import_id,
|
|
766
|
-
deleted: transaction.deleted,
|
|
767
|
-
},
|
|
768
|
-
updated_balance: account.balance,
|
|
769
|
-
updated_cleared_balance: account.cleared_balance,
|
|
770
|
-
}),
|
|
771
|
-
},
|
|
772
|
-
],
|
|
773
|
-
};
|
|
774
|
-
}
|
|
775
|
-
catch (error) {
|
|
776
|
-
return handleTransactionError(error, 'Failed to update transaction');
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
export async function handleDeleteTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
780
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
781
|
-
try {
|
|
782
|
-
if (params.dry_run) {
|
|
783
|
-
return {
|
|
784
|
-
content: [
|
|
785
|
-
{
|
|
786
|
-
type: 'text',
|
|
787
|
-
text: responseFormatter.format({
|
|
788
|
-
dry_run: true,
|
|
789
|
-
action: 'delete_transaction',
|
|
790
|
-
request: params,
|
|
791
|
-
}),
|
|
792
|
-
},
|
|
793
|
-
],
|
|
794
|
-
};
|
|
795
|
-
}
|
|
796
|
-
const response = await ynabAPI.transactions.deleteTransaction(params.budget_id, params.transaction_id);
|
|
797
|
-
const transaction = ensureTransaction(response.data.transaction, 'Transaction deletion failed');
|
|
798
|
-
const specificTransactionCacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
799
|
-
cacheManager.delete(specificTransactionCacheKey);
|
|
800
|
-
const affectedAccountIds = new Set([transaction.account_id]);
|
|
801
|
-
if (transaction.transfer_account_id) {
|
|
802
|
-
affectedAccountIds.add(transaction.transfer_account_id);
|
|
803
|
-
}
|
|
804
|
-
const affectedMonths = new Set([toMonthKey(transaction.date)]);
|
|
805
|
-
const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
806
|
-
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
807
|
-
affectedCategoryIds,
|
|
808
|
-
accountTotalsChanged: true,
|
|
809
|
-
invalidateMonths: true,
|
|
810
|
-
});
|
|
811
|
-
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
812
|
-
const account = accountResponse.data.account;
|
|
813
|
-
return {
|
|
814
|
-
content: [
|
|
815
|
-
{
|
|
816
|
-
type: 'text',
|
|
817
|
-
text: responseFormatter.format({
|
|
818
|
-
message: 'Transaction deleted successfully',
|
|
819
|
-
transaction: {
|
|
820
|
-
id: transaction.id,
|
|
821
|
-
deleted: transaction.deleted,
|
|
822
|
-
},
|
|
823
|
-
updated_balance: account.balance,
|
|
824
|
-
updated_cleared_balance: account.cleared_balance,
|
|
825
|
-
}),
|
|
826
|
-
},
|
|
827
|
-
],
|
|
828
|
-
};
|
|
829
|
-
}
|
|
830
|
-
catch (error) {
|
|
831
|
-
return handleTransactionError(error, 'Failed to delete transaction');
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
export async function handleCreateTransactions(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
835
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
836
|
-
return (await withToolErrorHandling(async () => {
|
|
837
|
-
const validationResult = CreateTransactionsSchema.safeParse(params);
|
|
838
|
-
if (!validationResult.success) {
|
|
839
|
-
const issuesByIndex = new Map();
|
|
840
|
-
const validationIssues = validationResult.error.issues ?? [];
|
|
841
|
-
for (const issue of validationIssues) {
|
|
842
|
-
const transactionIndex = issue.path.find((segment) => typeof segment === 'number');
|
|
843
|
-
const message = issue.message;
|
|
844
|
-
const issueIndex = transactionIndex !== undefined ? transactionIndex : null;
|
|
845
|
-
const existing = issuesByIndex.get(issueIndex) ?? [];
|
|
846
|
-
existing.push(message);
|
|
847
|
-
issuesByIndex.set(issueIndex, existing);
|
|
848
|
-
}
|
|
849
|
-
const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
|
|
850
|
-
transaction_index: index,
|
|
851
|
-
errors,
|
|
852
|
-
}));
|
|
853
|
-
throw new ValidationError('Bulk transaction validation failed', JSON.stringify(details, null, 2), ['Ensure each transaction includes required fields', 'Limit batches to 100 items']);
|
|
854
|
-
}
|
|
855
|
-
const { budget_id, transactions, dry_run } = validationResult.data;
|
|
856
|
-
const importIdMap = new Map();
|
|
857
|
-
for (const [index, transaction] of transactions.entries()) {
|
|
858
|
-
if (transaction.import_id && transaction.import_id.trim().length > 0) {
|
|
859
|
-
const existing = importIdMap.get(transaction.import_id);
|
|
860
|
-
if (existing) {
|
|
861
|
-
existing.push(index);
|
|
862
|
-
}
|
|
863
|
-
else {
|
|
864
|
-
importIdMap.set(transaction.import_id, [index]);
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
const duplicates = Array.from(importIdMap.entries())
|
|
869
|
-
.filter(([, indices]) => indices.length > 1)
|
|
870
|
-
.map(([importId, indices]) => ({ import_id: importId, indices }));
|
|
871
|
-
if (duplicates.length > 0) {
|
|
872
|
-
const details = duplicates.map(({ import_id, indices }) => ({
|
|
873
|
-
import_id,
|
|
874
|
-
transaction_indices: indices,
|
|
875
|
-
count: indices.length,
|
|
876
|
-
}));
|
|
877
|
-
throw new ValidationError('Duplicate import_id values detected within batch', JSON.stringify(details, null, 2), [
|
|
878
|
-
'Ensure each transaction has a unique import_id within the batch',
|
|
879
|
-
'Remove duplicate import_id values or omit import_id to use hash-based correlation',
|
|
880
|
-
]);
|
|
881
|
-
}
|
|
882
|
-
if (dry_run) {
|
|
883
|
-
const totalAmount = transactions.reduce((sum, transaction) => sum + transaction.amount, 0);
|
|
884
|
-
const accountsAffected = Array.from(new Set(transactions.map((transaction) => transaction.account_id)));
|
|
885
|
-
const categoriesAffected = Array.from(new Set(transactions
|
|
886
|
-
.map((transaction) => transaction.category_id)
|
|
887
|
-
.filter((id) => id !== undefined)));
|
|
888
|
-
const sortedDates = [...transactions.map((transaction) => transaction.date)].sort();
|
|
889
|
-
const dateRange = sortedDates.length > 0
|
|
890
|
-
? { earliest: sortedDates[0], latest: sortedDates[sortedDates.length - 1] }
|
|
891
|
-
: undefined;
|
|
892
|
-
const transactionsPreview = transactions.slice(0, 10).map((transaction, index) => ({
|
|
893
|
-
request_index: index,
|
|
894
|
-
account_id: transaction.account_id,
|
|
895
|
-
date: transaction.date,
|
|
896
|
-
amount: milliunitsToAmount(transaction.amount),
|
|
897
|
-
memo: transaction.memo,
|
|
898
|
-
payee_id: transaction.payee_id,
|
|
899
|
-
payee_name: transaction.payee_name,
|
|
900
|
-
category_id: transaction.category_id,
|
|
901
|
-
import_id: transaction.import_id,
|
|
902
|
-
}));
|
|
903
|
-
return {
|
|
904
|
-
content: [
|
|
905
|
-
{
|
|
906
|
-
type: 'text',
|
|
907
|
-
text: responseFormatter.format({
|
|
908
|
-
dry_run: true,
|
|
909
|
-
action: 'create_transactions',
|
|
910
|
-
validation: 'passed',
|
|
911
|
-
summary: {
|
|
912
|
-
total_transactions: transactions.length,
|
|
913
|
-
total_amount: milliunitsToAmount(totalAmount),
|
|
914
|
-
accounts_affected: accountsAffected,
|
|
915
|
-
date_range: dateRange,
|
|
916
|
-
categories_affected: categoriesAffected,
|
|
917
|
-
},
|
|
918
|
-
transactions_preview: transactionsPreview,
|
|
919
|
-
note: 'Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated.',
|
|
920
|
-
}),
|
|
921
|
-
},
|
|
922
|
-
],
|
|
923
|
-
};
|
|
924
|
-
}
|
|
925
|
-
const saveTransactions = transactions.map((transaction) => {
|
|
926
|
-
const payload = {
|
|
927
|
-
account_id: transaction.account_id,
|
|
928
|
-
amount: transaction.amount,
|
|
929
|
-
date: transaction.date,
|
|
930
|
-
};
|
|
931
|
-
if (transaction.payee_id !== undefined)
|
|
932
|
-
payload.payee_id = transaction.payee_id;
|
|
933
|
-
if (transaction.payee_name !== undefined)
|
|
934
|
-
payload.payee_name = transaction.payee_name;
|
|
935
|
-
if (transaction.category_id !== undefined)
|
|
936
|
-
payload.category_id = transaction.category_id;
|
|
937
|
-
if (transaction.memo !== undefined)
|
|
938
|
-
payload.memo = transaction.memo;
|
|
939
|
-
if (transaction.cleared !== undefined)
|
|
940
|
-
payload.cleared = transaction.cleared;
|
|
941
|
-
if (transaction.approved !== undefined)
|
|
942
|
-
payload.approved = transaction.approved;
|
|
943
|
-
if (transaction.flag_color !== undefined)
|
|
944
|
-
payload.flag_color = transaction.flag_color;
|
|
945
|
-
if (transaction.import_id !== undefined)
|
|
946
|
-
payload.import_id = transaction.import_id;
|
|
947
|
-
return payload;
|
|
948
|
-
});
|
|
949
|
-
const response = await ynabAPI.transactions.createTransactions(budget_id, {
|
|
950
|
-
transactions: saveTransactions,
|
|
951
|
-
});
|
|
952
|
-
const responseData = response.data;
|
|
953
|
-
const duplicateImportIds = new Set(responseData.duplicate_import_ids ?? []);
|
|
954
|
-
const results = correlateResults(transactions, responseData, duplicateImportIds);
|
|
955
|
-
const summary = {
|
|
956
|
-
total_requested: transactions.length,
|
|
957
|
-
created: responseData.transaction_ids?.length ?? 0,
|
|
958
|
-
duplicates: duplicateImportIds.size,
|
|
959
|
-
failed: results.filter((result) => result.status === 'failed').length,
|
|
960
|
-
};
|
|
961
|
-
const baseResponse = {
|
|
962
|
-
success: summary.failed === 0,
|
|
963
|
-
server_knowledge: responseData.server_knowledge,
|
|
964
|
-
summary,
|
|
965
|
-
results,
|
|
966
|
-
transactions: responseData.transactions ?? [],
|
|
967
|
-
duplicate_import_ids: responseData.duplicate_import_ids ?? [],
|
|
968
|
-
message: `Processed ${summary.total_requested} transactions: ${summary.created} created, ${summary.duplicates} duplicates, ${summary.failed} failed.`,
|
|
969
|
-
};
|
|
970
|
-
const accountIds = new Set(transactions.map((transaction) => transaction.account_id));
|
|
971
|
-
const affectedMonths = new Set(transactions.map((transaction) => toMonthKey(transaction.date)));
|
|
972
|
-
const affectedCategoryIds = new Set();
|
|
973
|
-
for (const created of responseData.transactions ?? []) {
|
|
974
|
-
appendCategoryIds(created, affectedCategoryIds);
|
|
975
|
-
}
|
|
976
|
-
invalidateTransactionCaches(deltaCache, knowledgeStore, budget_id, responseData.server_knowledge, accountIds, affectedMonths, {
|
|
977
|
-
affectedCategoryIds,
|
|
978
|
-
accountTotalsChanged: true,
|
|
979
|
-
invalidateMonths: true,
|
|
980
|
-
});
|
|
981
|
-
const finalizedResponse = finalizeResponse(baseResponse);
|
|
982
|
-
return {
|
|
983
|
-
content: [
|
|
984
|
-
{
|
|
985
|
-
type: 'text',
|
|
986
|
-
text: responseFormatter.format(finalizedResponse),
|
|
987
|
-
},
|
|
988
|
-
],
|
|
989
|
-
};
|
|
990
|
-
}, 'ynab:create_transactions', 'bulk transaction creation'));
|
|
991
|
-
}
|
|
992
|
-
async function resolveMetadata(ynabAPI, budgetId, transactions, options = {}) {
|
|
993
|
-
const metadata = new Map();
|
|
994
|
-
const needsResolution = [];
|
|
995
|
-
const previewIds = new Set(options.previewTransactionIds ?? []);
|
|
996
|
-
const previewDetails = new Map();
|
|
997
|
-
const previewIdsNeedingFetch = new Set(previewIds);
|
|
998
|
-
for (const transaction of transactions) {
|
|
999
|
-
if (transaction.original_account_id && transaction.original_date) {
|
|
1000
|
-
metadata.set(transaction.id, {
|
|
1001
|
-
account_id: transaction.original_account_id,
|
|
1002
|
-
date: transaction.original_date,
|
|
1003
|
-
});
|
|
1004
|
-
}
|
|
1005
|
-
else {
|
|
1006
|
-
needsResolution.push(transaction.id);
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
if (previewIds.size === 0 && needsResolution.length === 0) {
|
|
1010
|
-
return { metadata, unresolvedIds: [], previewDetails };
|
|
1011
|
-
}
|
|
1012
|
-
const needsResolutionSet = new Set(needsResolution);
|
|
1013
|
-
const cacheLookupIds = new Set([...needsResolution, ...previewIds]);
|
|
1014
|
-
for (const transactionId of cacheLookupIds) {
|
|
1015
|
-
const cacheKey = CacheManager.generateKey('transaction', 'get', budgetId, transactionId);
|
|
1016
|
-
const cached = cacheManager.get(cacheKey);
|
|
1017
|
-
if (!cached) {
|
|
1018
|
-
continue;
|
|
1019
|
-
}
|
|
1020
|
-
if (needsResolutionSet.has(transactionId)) {
|
|
1021
|
-
metadata.set(transactionId, {
|
|
1022
|
-
account_id: cached.account_id,
|
|
1023
|
-
date: cached.date,
|
|
1024
|
-
});
|
|
1025
|
-
needsResolutionSet.delete(transactionId);
|
|
1026
|
-
}
|
|
1027
|
-
if (previewIds.has(transactionId) && !previewDetails.has(transactionId)) {
|
|
1028
|
-
previewDetails.set(transactionId, cached);
|
|
1029
|
-
previewIdsNeedingFetch.delete(transactionId);
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
const stillNeedsResolution = Array.from(needsResolutionSet);
|
|
1033
|
-
if (stillNeedsResolution.length === 0 && previewIdsNeedingFetch.size === 0) {
|
|
1034
|
-
return { metadata, unresolvedIds: [], previewDetails };
|
|
1035
|
-
}
|
|
1036
|
-
const MAX_CONCURRENT_FETCHES = 5;
|
|
1037
|
-
const fetchPromises = [];
|
|
1038
|
-
const metadataAwaitingResolution = new Set(stillNeedsResolution);
|
|
1039
|
-
const idsNeedingApiFetch = Array.from(new Set([...stillNeedsResolution, ...previewIdsNeedingFetch]));
|
|
1040
|
-
for (let i = 0; i < idsNeedingApiFetch.length; i += MAX_CONCURRENT_FETCHES) {
|
|
1041
|
-
const batch = idsNeedingApiFetch.slice(i, i + MAX_CONCURRENT_FETCHES);
|
|
1042
|
-
const batchPromises = batch.map(async (transactionId) => {
|
|
1043
|
-
try {
|
|
1044
|
-
const response = await ynabAPI.transactions.getTransactionById(budgetId, transactionId);
|
|
1045
|
-
const transaction = response.data.transaction;
|
|
1046
|
-
if (transaction) {
|
|
1047
|
-
if (metadataAwaitingResolution.has(transactionId)) {
|
|
1048
|
-
metadata.set(transactionId, {
|
|
1049
|
-
account_id: transaction.account_id,
|
|
1050
|
-
date: transaction.date,
|
|
1051
|
-
});
|
|
1052
|
-
metadataAwaitingResolution.delete(transactionId);
|
|
1053
|
-
}
|
|
1054
|
-
if (previewIdsNeedingFetch.has(transactionId) && !previewDetails.has(transactionId)) {
|
|
1055
|
-
previewDetails.set(transactionId, transaction);
|
|
1056
|
-
previewIdsNeedingFetch.delete(transactionId);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
catch {
|
|
1061
|
-
if (metadataAwaitingResolution.has(transactionId)) {
|
|
1062
|
-
globalRequestLogger.logError('ynab:update_transactions', 'resolve_metadata', { transaction_id: transactionId }, 'Failed to resolve transaction metadata');
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
});
|
|
1066
|
-
fetchPromises.push(...batchPromises);
|
|
1067
|
-
}
|
|
1068
|
-
await Promise.all(fetchPromises);
|
|
1069
|
-
return { metadata, unresolvedIds: Array.from(metadataAwaitingResolution), previewDetails };
|
|
1070
|
-
}
|
|
1071
|
-
export async function handleUpdateTransactions(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
1072
|
-
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
1073
|
-
return (await withToolErrorHandling(async () => {
|
|
1074
|
-
const validationResult = UpdateTransactionsSchema.safeParse(params);
|
|
1075
|
-
if (!validationResult.success) {
|
|
1076
|
-
const issuesByIndex = new Map();
|
|
1077
|
-
const validationIssues = validationResult.error.issues ?? [];
|
|
1078
|
-
for (const issue of validationIssues) {
|
|
1079
|
-
const transactionIndex = issue.path.find((segment) => typeof segment === 'number');
|
|
1080
|
-
const message = issue.message;
|
|
1081
|
-
const issueIndex = transactionIndex !== undefined ? transactionIndex : null;
|
|
1082
|
-
const existing = issuesByIndex.get(issueIndex) ?? [];
|
|
1083
|
-
existing.push(message);
|
|
1084
|
-
issuesByIndex.set(issueIndex, existing);
|
|
1085
|
-
}
|
|
1086
|
-
const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
|
|
1087
|
-
transaction_index: index,
|
|
1088
|
-
errors,
|
|
1089
|
-
}));
|
|
1090
|
-
throw new ValidationError('Bulk transaction update validation failed', JSON.stringify(details, null, 2), ['Ensure each transaction includes an id field', 'Limit batches to 100 items']);
|
|
1091
|
-
}
|
|
1092
|
-
const { budget_id, transactions, dry_run } = validationResult.data;
|
|
1093
|
-
if (dry_run) {
|
|
1094
|
-
const previewTransactions = transactions.slice(0, 10);
|
|
1095
|
-
const previewTransactionIds = previewTransactions.map((transaction) => transaction.id);
|
|
1096
|
-
const { metadata, unresolvedIds, previewDetails } = await resolveMetadata(ynabAPI, budget_id, transactions, {
|
|
1097
|
-
previewTransactionIds,
|
|
1098
|
-
});
|
|
1099
|
-
const transactionsPreview = [];
|
|
1100
|
-
const unavailablePreviewIds = [];
|
|
1101
|
-
for (const transaction of previewTransactions) {
|
|
1102
|
-
const currentState = previewDetails.get(transaction.id);
|
|
1103
|
-
if (!currentState) {
|
|
1104
|
-
unavailablePreviewIds.push(transaction.id);
|
|
1105
|
-
transactionsPreview.push({
|
|
1106
|
-
transaction_id: transaction.id,
|
|
1107
|
-
before: 'unavailable',
|
|
1108
|
-
after: transaction,
|
|
1109
|
-
});
|
|
1110
|
-
continue;
|
|
1111
|
-
}
|
|
1112
|
-
const before = {};
|
|
1113
|
-
const after = {};
|
|
1114
|
-
if (transaction.amount !== undefined && transaction.amount !== currentState.amount) {
|
|
1115
|
-
before['amount'] = milliunitsToAmount(currentState.amount);
|
|
1116
|
-
after['amount'] = milliunitsToAmount(transaction.amount);
|
|
1117
|
-
}
|
|
1118
|
-
if (transaction.date !== undefined && transaction.date !== currentState.date) {
|
|
1119
|
-
before['date'] = currentState.date;
|
|
1120
|
-
after['date'] = transaction.date;
|
|
1121
|
-
}
|
|
1122
|
-
if (transaction.memo !== undefined && transaction.memo !== currentState.memo) {
|
|
1123
|
-
before['memo'] = currentState.memo;
|
|
1124
|
-
after['memo'] = transaction.memo;
|
|
1125
|
-
}
|
|
1126
|
-
if (transaction.payee_id !== undefined &&
|
|
1127
|
-
transaction.payee_id !== currentState.payee_id) {
|
|
1128
|
-
before['payee_id'] = currentState.payee_id;
|
|
1129
|
-
after['payee_id'] = transaction.payee_id;
|
|
1130
|
-
}
|
|
1131
|
-
if (transaction.payee_name !== undefined &&
|
|
1132
|
-
transaction.payee_name !== currentState.payee_name) {
|
|
1133
|
-
before['payee_name'] = currentState.payee_name;
|
|
1134
|
-
after['payee_name'] = transaction.payee_name;
|
|
1135
|
-
}
|
|
1136
|
-
if (transaction.category_id !== undefined &&
|
|
1137
|
-
transaction.category_id !== currentState.category_id) {
|
|
1138
|
-
before['category_id'] = currentState.category_id;
|
|
1139
|
-
after['category_id'] = transaction.category_id;
|
|
1140
|
-
}
|
|
1141
|
-
if (transaction.cleared !== undefined && transaction.cleared !== currentState.cleared) {
|
|
1142
|
-
before['cleared'] = currentState.cleared;
|
|
1143
|
-
after['cleared'] = transaction.cleared;
|
|
1144
|
-
}
|
|
1145
|
-
if (transaction.approved !== undefined &&
|
|
1146
|
-
transaction.approved !== currentState.approved) {
|
|
1147
|
-
before['approved'] = currentState.approved;
|
|
1148
|
-
after['approved'] = transaction.approved;
|
|
1149
|
-
}
|
|
1150
|
-
if (transaction.flag_color !== undefined &&
|
|
1151
|
-
transaction.flag_color !== currentState.flag_color) {
|
|
1152
|
-
before['flag_color'] = currentState.flag_color;
|
|
1153
|
-
after['flag_color'] = transaction.flag_color;
|
|
1154
|
-
}
|
|
1155
|
-
transactionsPreview.push({
|
|
1156
|
-
transaction_id: transaction.id,
|
|
1157
|
-
before,
|
|
1158
|
-
after,
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
const warnings = [];
|
|
1162
|
-
if (unavailablePreviewIds.length > 0 || unresolvedIds.length > 0) {
|
|
1163
|
-
const totalMissing = Math.max(unavailablePreviewIds.length, unresolvedIds.length);
|
|
1164
|
-
const sampleIds = unresolvedIds.length > 0
|
|
1165
|
-
? unresolvedIds.slice(0, 10)
|
|
1166
|
-
: unavailablePreviewIds.slice(0, 10);
|
|
1167
|
-
warnings.push({
|
|
1168
|
-
code: 'metadata_unavailable',
|
|
1169
|
-
count: totalMissing,
|
|
1170
|
-
message: `Unable to fetch prior state for ${totalMissing} transactions`,
|
|
1171
|
-
sample_ids: sampleIds,
|
|
1172
|
-
});
|
|
1173
|
-
}
|
|
1174
|
-
const accountsAffected = Array.from(new Set(Array.from(metadata.values()).map((m) => m.account_id)));
|
|
1175
|
-
const fieldsToUpdate = new Set();
|
|
1176
|
-
for (const transaction of transactions) {
|
|
1177
|
-
if (transaction.amount !== undefined)
|
|
1178
|
-
fieldsToUpdate.add('amount');
|
|
1179
|
-
if (transaction.date !== undefined)
|
|
1180
|
-
fieldsToUpdate.add('date');
|
|
1181
|
-
if (transaction.memo !== undefined)
|
|
1182
|
-
fieldsToUpdate.add('memo');
|
|
1183
|
-
if (transaction.payee_id !== undefined)
|
|
1184
|
-
fieldsToUpdate.add('payee_id');
|
|
1185
|
-
if (transaction.payee_name !== undefined)
|
|
1186
|
-
fieldsToUpdate.add('payee_name');
|
|
1187
|
-
if (transaction.category_id !== undefined)
|
|
1188
|
-
fieldsToUpdate.add('category_id');
|
|
1189
|
-
if (transaction.cleared !== undefined)
|
|
1190
|
-
fieldsToUpdate.add('cleared');
|
|
1191
|
-
if (transaction.approved !== undefined)
|
|
1192
|
-
fieldsToUpdate.add('approved');
|
|
1193
|
-
if (transaction.flag_color !== undefined)
|
|
1194
|
-
fieldsToUpdate.add('flag_color');
|
|
1195
|
-
}
|
|
1196
|
-
const response = {
|
|
1197
|
-
dry_run: true,
|
|
1198
|
-
action: 'update_transactions',
|
|
1199
|
-
validation: 'passed',
|
|
1200
|
-
summary: {
|
|
1201
|
-
total_transactions: transactions.length,
|
|
1202
|
-
accounts_affected: accountsAffected,
|
|
1203
|
-
fields_to_update: Array.from(fieldsToUpdate),
|
|
1204
|
-
},
|
|
1205
|
-
transactions_preview: transactionsPreview,
|
|
1206
|
-
note: 'Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated.',
|
|
1207
|
-
};
|
|
1208
|
-
if (warnings.length > 0) {
|
|
1209
|
-
response['warnings'] = warnings;
|
|
1210
|
-
}
|
|
1211
|
-
return {
|
|
1212
|
-
content: [
|
|
1213
|
-
{
|
|
1214
|
-
type: 'text',
|
|
1215
|
-
text: responseFormatter.format(response),
|
|
1216
|
-
},
|
|
1217
|
-
],
|
|
1218
|
-
};
|
|
1219
|
-
}
|
|
1220
|
-
const { metadata, unresolvedIds } = await resolveMetadata(ynabAPI, budget_id, transactions);
|
|
1221
|
-
const missingMetadataRatio = unresolvedIds.length / transactions.length;
|
|
1222
|
-
const METADATA_THRESHOLD = 0.05;
|
|
1223
|
-
if (missingMetadataRatio > METADATA_THRESHOLD) {
|
|
1224
|
-
throw new ValidationError(`METADATA_INCOMPLETE: ${(missingMetadataRatio * 100).toFixed(1)}% of transactions have missing metadata (threshold: ${(METADATA_THRESHOLD * 100).toFixed(0)}%)`, JSON.stringify({
|
|
1225
|
-
unresolved_count: unresolvedIds.length,
|
|
1226
|
-
total_transactions: transactions.length,
|
|
1227
|
-
ratio: (missingMetadataRatio * 100).toFixed(1) + '%',
|
|
1228
|
-
threshold: (METADATA_THRESHOLD * 100).toFixed(0) + '%',
|
|
1229
|
-
sample_unresolved_ids: unresolvedIds.slice(0, 5),
|
|
1230
|
-
}, null, 2), [
|
|
1231
|
-
'Provide original_account_id and original_date for all transactions being updated',
|
|
1232
|
-
'Ensure transactions exist in YNAB before updating them',
|
|
1233
|
-
]);
|
|
1234
|
-
}
|
|
1235
|
-
if (missingMetadataRatio > 0.01) {
|
|
1236
|
-
globalRequestLogger.logRequest('ynab:update_transactions', 'metadata_resolution_warning', {
|
|
1237
|
-
unresolved_count: unresolvedIds.length,
|
|
1238
|
-
total_transactions: transactions.length,
|
|
1239
|
-
ratio: missingMetadataRatio.toFixed(3),
|
|
1240
|
-
sample_ids: unresolvedIds.slice(0, 5),
|
|
1241
|
-
message: 'Metadata resolution incomplete for some transactions',
|
|
1242
|
-
}, true);
|
|
1243
|
-
}
|
|
1244
|
-
const updateTransactions = transactions.map((transaction) => {
|
|
1245
|
-
const transactionData = {};
|
|
1246
|
-
if (transaction.amount !== undefined) {
|
|
1247
|
-
transactionData.amount = transaction.amount;
|
|
1248
|
-
}
|
|
1249
|
-
if (transaction.date !== undefined) {
|
|
1250
|
-
transactionData.date = transaction.date;
|
|
1251
|
-
}
|
|
1252
|
-
if (transaction.payee_name !== undefined) {
|
|
1253
|
-
transactionData.payee_name = transaction.payee_name;
|
|
1254
|
-
}
|
|
1255
|
-
if (transaction.payee_id !== undefined) {
|
|
1256
|
-
transactionData.payee_id = transaction.payee_id;
|
|
1257
|
-
}
|
|
1258
|
-
if (transaction.category_id !== undefined) {
|
|
1259
|
-
transactionData.category_id = transaction.category_id;
|
|
1260
|
-
}
|
|
1261
|
-
if (transaction.memo !== undefined) {
|
|
1262
|
-
transactionData.memo = transaction.memo;
|
|
1263
|
-
}
|
|
1264
|
-
if (transaction.cleared !== undefined) {
|
|
1265
|
-
transactionData.cleared = transaction.cleared;
|
|
1266
|
-
}
|
|
1267
|
-
if (transaction.approved !== undefined) {
|
|
1268
|
-
transactionData.approved = transaction.approved;
|
|
1269
|
-
}
|
|
1270
|
-
if (transaction.flag_color !== undefined) {
|
|
1271
|
-
transactionData.flag_color = transaction.flag_color;
|
|
1272
|
-
}
|
|
1273
|
-
return {
|
|
1274
|
-
id: transaction.id,
|
|
1275
|
-
transaction: transactionData,
|
|
1276
|
-
};
|
|
1277
|
-
});
|
|
1278
|
-
const response = await ynabAPI.transactions.updateTransactions(budget_id, {
|
|
1279
|
-
transactions: updateTransactions,
|
|
1280
|
-
});
|
|
1281
|
-
const responseData = response.data;
|
|
1282
|
-
const updatedTransactions = responseData.transactions ?? [];
|
|
1283
|
-
const results = [];
|
|
1284
|
-
const updatedIds = new Set(updatedTransactions.map((t) => t.id));
|
|
1285
|
-
for (const [index, transaction] of transactions.entries()) {
|
|
1286
|
-
if (updatedIds.has(transaction.id)) {
|
|
1287
|
-
results.push({
|
|
1288
|
-
request_index: index,
|
|
1289
|
-
status: 'updated',
|
|
1290
|
-
transaction_id: transaction.id,
|
|
1291
|
-
correlation_key: transaction.id,
|
|
1292
|
-
});
|
|
1293
|
-
}
|
|
1294
|
-
else {
|
|
1295
|
-
results.push({
|
|
1296
|
-
request_index: index,
|
|
1297
|
-
status: 'failed',
|
|
1298
|
-
transaction_id: transaction.id,
|
|
1299
|
-
correlation_key: transaction.id,
|
|
1300
|
-
error_code: 'update_failed',
|
|
1301
|
-
error: 'Transaction was not updated by YNAB API',
|
|
1302
|
-
});
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
const summary = {
|
|
1306
|
-
total_requested: transactions.length,
|
|
1307
|
-
updated: updatedTransactions.length,
|
|
1308
|
-
failed: results.filter((r) => r.status === 'failed').length,
|
|
1309
|
-
};
|
|
1310
|
-
const baseResponse = {
|
|
1311
|
-
success: summary.failed === 0,
|
|
1312
|
-
server_knowledge: responseData.server_knowledge,
|
|
1313
|
-
summary,
|
|
1314
|
-
results,
|
|
1315
|
-
transactions: updatedTransactions,
|
|
1316
|
-
message: `Processed ${summary.total_requested} transactions: ${summary.updated} updated, ${summary.failed} failed.`,
|
|
1317
|
-
};
|
|
1318
|
-
for (const transaction of transactions) {
|
|
1319
|
-
cacheManager.delete(CacheManager.generateKey('transaction', 'get', budget_id, transaction.id));
|
|
1320
|
-
}
|
|
1321
|
-
const affectedAccountIds = new Set();
|
|
1322
|
-
const affectedMonthKeys = new Set();
|
|
1323
|
-
const affectedCategoryIds = new Set();
|
|
1324
|
-
let invalidateAllCategories = false;
|
|
1325
|
-
let accountTotalsChanged = false;
|
|
1326
|
-
let monthsImpacted = false;
|
|
1327
|
-
for (const transaction of transactions) {
|
|
1328
|
-
const meta = metadata.get(transaction.id);
|
|
1329
|
-
const amountChanged = transaction.amount !== undefined;
|
|
1330
|
-
const clearedChanged = transaction.cleared !== undefined;
|
|
1331
|
-
const categoryChanged = transaction.category_id !== undefined;
|
|
1332
|
-
const dateChanged = transaction.date !== undefined;
|
|
1333
|
-
if ((amountChanged || clearedChanged) && meta) {
|
|
1334
|
-
affectedAccountIds.add(meta.account_id);
|
|
1335
|
-
}
|
|
1336
|
-
if (amountChanged) {
|
|
1337
|
-
monthsImpacted = true;
|
|
1338
|
-
accountTotalsChanged = true;
|
|
1339
|
-
invalidateAllCategories = true;
|
|
1340
|
-
if (meta) {
|
|
1341
|
-
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
if (categoryChanged) {
|
|
1345
|
-
monthsImpacted = true;
|
|
1346
|
-
invalidateAllCategories = true;
|
|
1347
|
-
if (transaction.category_id) {
|
|
1348
|
-
affectedCategoryIds.add(transaction.category_id);
|
|
1349
|
-
}
|
|
1350
|
-
if (meta) {
|
|
1351
|
-
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
if (dateChanged && meta) {
|
|
1355
|
-
monthsImpacted = true;
|
|
1356
|
-
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1357
|
-
}
|
|
1358
|
-
if (dateChanged && transaction.date) {
|
|
1359
|
-
affectedMonthKeys.add(toMonthKey(transaction.date));
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
invalidateTransactionCaches(deltaCache, knowledgeStore, budget_id, responseData.server_knowledge, affectedAccountIds, affectedMonthKeys, {
|
|
1363
|
-
affectedCategoryIds,
|
|
1364
|
-
invalidateAllCategories,
|
|
1365
|
-
accountTotalsChanged,
|
|
1366
|
-
invalidateMonths: monthsImpacted,
|
|
1367
|
-
});
|
|
1368
|
-
const finalizedResponse = finalizeBulkUpdateResponse(baseResponse);
|
|
1369
|
-
return {
|
|
1370
|
-
content: [
|
|
1371
|
-
{
|
|
1372
|
-
type: 'text',
|
|
1373
|
-
text: responseFormatter.format(finalizedResponse),
|
|
1374
|
-
},
|
|
1375
|
-
],
|
|
1376
|
-
};
|
|
1377
|
-
}, 'ynab:update_transactions', 'bulk transaction update'));
|
|
1378
|
-
}
|
|
1
|
+
import { handleGetTransaction, handleListTransactions, registerTransactionReadTools, } from "./transactionReadTools.js";
|
|
2
|
+
import { handleCreateReceiptSplitTransaction, handleCreateTransaction, handleCreateTransactions, handleDeleteTransaction, handleUpdateTransaction, handleUpdateTransactions, registerTransactionWriteTools, } from "./transactionWriteTools.js";
|
|
1379
3
|
export const registerTransactionTools = (registry, context) => {
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
registry.register({
|
|
1383
|
-
name: 'list_transactions',
|
|
1384
|
-
description: 'List transactions for a budget with optional filtering',
|
|
1385
|
-
inputSchema: ListTransactionsSchema,
|
|
1386
|
-
handler: adaptWithDelta(handleListTransactions),
|
|
1387
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1388
|
-
metadata: {
|
|
1389
|
-
annotations: {
|
|
1390
|
-
...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
|
|
1391
|
-
title: 'YNAB: List Transactions',
|
|
1392
|
-
},
|
|
1393
|
-
},
|
|
1394
|
-
});
|
|
1395
|
-
registry.register({
|
|
1396
|
-
name: 'export_transactions',
|
|
1397
|
-
description: 'Export all transactions to a JSON file with descriptive filename',
|
|
1398
|
-
inputSchema: ExportTransactionsSchema,
|
|
1399
|
-
handler: adapt(handleExportTransactions),
|
|
1400
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1401
|
-
metadata: {
|
|
1402
|
-
annotations: {
|
|
1403
|
-
...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
|
|
1404
|
-
title: 'YNAB: Export Transactions',
|
|
1405
|
-
},
|
|
1406
|
-
},
|
|
1407
|
-
});
|
|
1408
|
-
registry.register({
|
|
1409
|
-
name: 'get_transaction',
|
|
1410
|
-
description: 'Get detailed information for a specific transaction',
|
|
1411
|
-
inputSchema: GetTransactionSchema,
|
|
1412
|
-
handler: adapt(handleGetTransaction),
|
|
1413
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1414
|
-
metadata: {
|
|
1415
|
-
annotations: {
|
|
1416
|
-
...ToolAnnotationPresets.READ_ONLY_EXTERNAL,
|
|
1417
|
-
title: 'YNAB: Get Transaction Details',
|
|
1418
|
-
},
|
|
1419
|
-
},
|
|
1420
|
-
});
|
|
1421
|
-
registry.register({
|
|
1422
|
-
name: 'create_transaction',
|
|
1423
|
-
description: 'Create a new transaction in the specified budget and account',
|
|
1424
|
-
inputSchema: CreateTransactionSchema,
|
|
1425
|
-
handler: adaptWrite(handleCreateTransaction),
|
|
1426
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1427
|
-
metadata: {
|
|
1428
|
-
annotations: {
|
|
1429
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
|
|
1430
|
-
title: 'YNAB: Create Transaction',
|
|
1431
|
-
},
|
|
1432
|
-
},
|
|
1433
|
-
});
|
|
1434
|
-
registry.register({
|
|
1435
|
-
name: 'create_transactions',
|
|
1436
|
-
description: 'Create multiple transactions in a single batch (1-100 items) with duplicate detection, dry-run validation, and automatic response size management with correlation metadata.',
|
|
1437
|
-
inputSchema: CreateTransactionsSchema,
|
|
1438
|
-
handler: adaptWrite(handleCreateTransactions),
|
|
1439
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1440
|
-
metadata: {
|
|
1441
|
-
annotations: {
|
|
1442
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
|
|
1443
|
-
title: 'YNAB: Create Multiple Transactions',
|
|
1444
|
-
},
|
|
1445
|
-
},
|
|
1446
|
-
});
|
|
1447
|
-
registry.register({
|
|
1448
|
-
name: 'create_receipt_split_transaction',
|
|
1449
|
-
description: 'Create a split transaction from receipt items with proportional tax allocation',
|
|
1450
|
-
inputSchema: CreateReceiptSplitTransactionSchema,
|
|
1451
|
-
handler: adaptWrite(handleCreateReceiptSplitTransaction),
|
|
1452
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1453
|
-
metadata: {
|
|
1454
|
-
annotations: {
|
|
1455
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_CREATE,
|
|
1456
|
-
title: 'YNAB: Create Split Transaction from Receipt',
|
|
1457
|
-
},
|
|
1458
|
-
},
|
|
1459
|
-
});
|
|
1460
|
-
registry.register({
|
|
1461
|
-
name: 'update_transaction',
|
|
1462
|
-
description: 'Update an existing transaction',
|
|
1463
|
-
inputSchema: UpdateTransactionSchema,
|
|
1464
|
-
handler: adaptWrite(handleUpdateTransaction),
|
|
1465
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1466
|
-
metadata: {
|
|
1467
|
-
annotations: {
|
|
1468
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
|
|
1469
|
-
title: 'YNAB: Update Transaction',
|
|
1470
|
-
},
|
|
1471
|
-
},
|
|
1472
|
-
});
|
|
1473
|
-
registry.register({
|
|
1474
|
-
name: 'update_transactions',
|
|
1475
|
-
description: 'Update multiple transactions in a single batch (1-100 items) with dry-run validation, automatic cache invalidation, and response size management. Supports optional original_account_id and original_date metadata for efficient cache invalidation.',
|
|
1476
|
-
inputSchema: UpdateTransactionsSchema,
|
|
1477
|
-
handler: adaptWrite(handleUpdateTransactions),
|
|
1478
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1479
|
-
metadata: {
|
|
1480
|
-
annotations: {
|
|
1481
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_UPDATE,
|
|
1482
|
-
title: 'YNAB: Update Multiple Transactions',
|
|
1483
|
-
},
|
|
1484
|
-
},
|
|
1485
|
-
});
|
|
1486
|
-
registry.register({
|
|
1487
|
-
name: 'delete_transaction',
|
|
1488
|
-
description: 'Delete a transaction from the specified budget',
|
|
1489
|
-
inputSchema: DeleteTransactionSchema,
|
|
1490
|
-
handler: adaptWrite(handleDeleteTransaction),
|
|
1491
|
-
defaultArgumentResolver: budgetResolver(),
|
|
1492
|
-
metadata: {
|
|
1493
|
-
annotations: {
|
|
1494
|
-
...ToolAnnotationPresets.WRITE_EXTERNAL_DELETE,
|
|
1495
|
-
title: 'YNAB: Delete Transaction',
|
|
1496
|
-
},
|
|
1497
|
-
},
|
|
1498
|
-
});
|
|
4
|
+
registerTransactionReadTools(registry, context);
|
|
5
|
+
registerTransactionWriteTools(registry, context);
|
|
1499
6
|
};
|
|
1500
|
-
export {
|
|
1501
|
-
export {
|
|
7
|
+
export { handleListTransactions, handleGetTransaction, handleCreateTransaction, handleCreateReceiptSplitTransaction, handleUpdateTransaction, handleDeleteTransaction, handleCreateTransactions, handleUpdateTransactions, };
|
|
8
|
+
export { ListTransactionsSchema, GetTransactionSchema, CreateTransactionSchema, CreateTransactionsSchema, CreateReceiptSplitTransactionSchema, UpdateTransactionSchema, UpdateTransactionsSchema, DeleteTransactionSchema, } from "./transactionSchemas.js";
|
|
9
|
+
export { generateCorrelationKey, toCorrelationPayload, correlateResults, estimatePayloadSize, finalizeResponse, finalizeBulkUpdateResponse, handleTransactionError, toMonthKey, ensureTransaction, appendCategoryIds, collectCategoryIdsFromSources, setsEqual, invalidateTransactionCaches, } from "./transactionUtils.js";
|