@dizzlkheinz/ynab-mcpb 0.12.1
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/.chunkhound.json +11 -0
- package/.code/agents/0427d95e-edca-431f-a214-5e53264e29c4/error.txt +8 -0
- package/.code/agents/0d675174-d1e1-41c3-9975-4c2e275819a9/error.txt +3 -0
- package/.code/agents/0d8c5afd-4787-422b-abf8-2e5943fc7e67/error.txt +3 -0
- package/.code/agents/0ec34a70-ed5d-4b9e-bee4-bb0e4cccbc4b/error.txt +1 -0
- package/.code/agents/0ef51a21-1ab1-49d7-9561-0eaa43875ebc/error.txt +12 -0
- package/.code/agents/15db95d7-abad-4b4d-9c3b-8446089cb61d/error.txt +1 -0
- package/.code/agents/19ab9acb-f675-4ff0-902a-09a5476f8149/error.txt +1 -0
- package/.code/agents/1ef7e12d-f6ff-4897-8a9b-152d523d898e/error.txt +5 -0
- package/.code/agents/2465/exec-call_lroN9KKzJVWC7t5423DK1nT9.txt +1453 -0
- package/.code/agents/28edb6fe-95a9-41a0-ae69-aa0100d26c0c/error.txt +8 -0
- package/.code/agents/2ae40cf5-b4bf-42e2-92bf-7ea350a7755e/error.txt +9 -0
- package/.code/agents/2bfc4e1f-ac4b-45a5-b6df-bf89d4dbb54c/error.txt +1 -0
- package/.code/agents/2e2e1134-eff0-49be-ba25-8e2c3468a564/error.txt +5 -0
- package/.code/agents/3/exec-call_203OC4TNVkLxW7z2HCVEQ1cM.txt +81 -0
- package/.code/agents/3/exec-call_SS5T0XSiXB4LSNzUKTl75wkh.txt +610 -0
- package/.code/agents/3322c003-ce5e-48e3-a342-f5049c5bf9a2/error.txt +1 -0
- package/.code/agents/391e9b08-1ebc-468c-9bcd-6d0cc3193b37/error.txt +1 -0
- package/.code/agents/3ab0aa84-b7bb-4054-afa3-40b8fd7d3be0/error.txt +1 -0
- package/.code/agents/3bed368d-50fe-477e-aee3-a6707eaa1ab9/error.txt +3 -0
- package/.code/agents/3e40b925-db12-442f-8d7a-a25fc69a6672/error.txt +8 -0
- package/.code/agents/414d5776-cf58-41f3-9328-a6daed503a50/error.txt +5 -0
- package/.code/agents/42687751-4565-4610-b240-67835b17d861/error.txt +1 -0
- package/.code/agents/46b98876-1a39-43c9-9e2f-507ca6d47335/error.txt +9 -0
- package/.code/agents/4a7d9491-b26f-43dd-850d-2ecdc49b5d1b/error.txt +1 -0
- package/.code/agents/4e60f00a-1b3e-447f-87f3-7faf9deddec3/error.txt +13 -0
- package/.code/agents/5138fc1c-4d49-4b74-a7da-ccdb3a8e44e7/error.txt +14 -0
- package/.code/agents/521cff39-a7a3-42e5-a557-134f0f7daaa0/error.txt +5 -0
- package/.code/agents/53302dc5-3857-4413-9a47-9e0f64a51dc4/error.txt +5 -0
- package/.code/agents/567c7c2e-6a6f-4761-a08d-d36deeb2e0ac/error.txt +5 -0
- package/.code/agents/57b00845-80dc-47c9-953c-3028d16275d6/error.txt +3 -0
- package/.code/agents/593d9005-c2a5-48fd-8813-ece0d3f2de96/error.txt +1 -0
- package/.code/agents/5a112e66-0e1a-42f9-877c-53af56ea3551/error.txt +1 -0
- package/.code/agents/5b05e8ed-7788-4738-b7ee-9faa8180f992/error.txt +5 -0
- package/.code/agents/5f888d6f-d7ca-4ac8-be23-9ea1bf753951/error.txt +5 -0
- package/.code/agents/607db3ab-e4b0-435b-b497-93e9aa525549/error.txt +8 -0
- package/.code/agents/67dcb2a2-900f-4c78-b3fc-80b5213e0ddf/error.txt +8 -0
- package/.code/agents/69ad848c-4e98-49b3-b16c-0094ac2d1759/error.txt +5 -0
- package/.code/agents/6c9cfc5f-0d0b-445c-b121-9f60082c4f70/error.txt +1 -0
- package/.code/agents/6f6f8f77-4ab0-4f6e-9f30-40e8be0bd8f5/error.txt +1 -0
- package/.code/agents/72a7cde4-fa8a-4024-9038-27faa550539b/error.txt +1 -0
- package/.code/agents/7b48335c-8247-43aa-9949-5f820ba8e199/error.txt +1 -0
- package/.code/agents/80944249-bea9-4ac5-87de-a666c4df306e/error.txt +1 -0
- package/.code/agents/826099df-1b66-4186-a915-7eb59f9db19d/error.txt +5 -0
- package/.code/agents/8291d158-18a8-4a92-b799-4e9a4d9cce88/error.txt +1 -0
- package/.code/agents/82fb71a3-20fb-4341-804a-a2fc900f95bc/error.txt +1 -0
- package/.code/agents/855790ea-54ee-43e4-8209-a66994e37590/error.txt +1 -0
- package/.code/agents/88ce3a2e-04f2-42be-9062-bf97aa798da0/error.txt +3 -0
- package/.code/agents/9a17e398-b6ed-4218-bb55-bc64a8d38ce8/error.txt +8 -0
- package/.code/agents/9a4f4bfc-a2a6-4f40-a896-9335b41a7ed1/error.txt +1 -0
- package/.code/agents/9b633e55-ef84-47d6-94bb-fd3dd172ad97/error.txt +1 -0
- package/.code/agents/9b81f3ab-c72b-4a81-9a8f-28a49ddba84a/error.txt +8 -0
- package/.code/agents/a35daf29-b2d1-4aef-9b42-dad63a76bd47/error.txt +3 -0
- package/.code/agents/a81990cc-69ee-44d2-b907-17403c9bc5d7/error.txt +5 -0
- package/.code/agents/ab56260a-4a83-4ad4-9410-f88a23d6520a/error.txt +1 -0
- package/.code/agents/ad722c31-2d1d-45f7-bae2-3f02ca455b60/error.txt +1 -0
- package/.code/agents/b62e8690-3324-4b97-9309-731bee79416b/error.txt +5 -0
- package/.code/agents/baf60a3a-752b-4ad8-99d6-df32423ed2eb/error.txt +1 -0
- package/.code/agents/be049042-7dcb-4ac8-9beb-c8f1aea67742/error.txt +14 -0
- package/.code/agents/bed1dcb4-bfce-4a9f-8594-0f994962aafd/error.txt +1 -0
- package/.code/agents/c324a6cf-e935-4ede-9529-b3ebc18e8d6b/error.txt +5 -0
- package/.code/agents/c37c06ff-dfe3-43f2-9bbc-3ec73ec8f41d/error.txt +5 -0
- package/.code/agents/c8cd6671-433a-456b-9f88-e51cb2df6bfc/error.txt +11 -0
- package/.code/agents/ca2ccb67-2f24-428e-b27d-9365beadd140/error.txt +1 -0
- package/.code/agents/cf08c0c8-e7f0-423e-93ba-547e8e818340/error.txt +8 -0
- package/.code/agents/d579c74f-874b-40a4-9d56-ced1eb6a701d/error.txt +1 -0
- package/.code/agents/df412c98-7378-4deb-8e1e-76c416931181/error.txt +3 -0
- package/.code/agents/e5134eb3-2af4-45b0-8998-051cb4afdb45/error.txt +3 -0
- package/.code/agents/e6308471-aa45-4e9e-9496-2e9404164d97/error.txt +8 -0
- package/.code/agents/e7bd8bc7-23fb-4f46-98dc-b0dcf11b75a1/error.txt +1 -0
- package/.code/agents/e92bec35-378d-4fe1-8ac0-6e1bb3c86911/error.txt +5 -0
- package/.code/agents/ed918fbf-2dc4-4aa2-bfc5-04b65d9471ea/error.txt +1 -0
- package/.code/agents/ef1d756f-b272-48fc-8729-f05c494674f7/error.txt +1 -0
- package/.code/agents/ef359853-0249-4e41-a804-c0fc459fe456/error.txt +1 -0
- package/.code/agents/effc7b4a-4b90-40a0-8c86-a7a99d2d5fd2/error.txt +1 -0
- package/.code/agents/fa15f8d5-8359-4a8b-83a3-2f2056b3ff40/error.txt +3 -0
- package/.code/agents/fbef4193-eadf-4c8a-83ff-4878a6310f25/error.txt +8 -0
- package/.code/agents/fd0a4b4a-fda4-4964-a6d6-2b8a2da387c6/error.txt +1 -0
- package/.dxtignore +57 -0
- package/.env.example +44 -0
- package/.gemini/settings.json +8 -0
- package/.github/ISSUE_TEMPLATE/bug_report.md +41 -0
- package/.github/ISSUE_TEMPLATE/config.yml +5 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +24 -0
- package/.github/ISSUE_TEMPLATE/release_checklist.md +31 -0
- package/.github/pull_request_template.md +41 -0
- package/.github/workflows/ci-tests.yml +41 -0
- package/.github/workflows/claude-code-review.yml +57 -0
- package/.github/workflows/claude.yml +50 -0
- package/.github/workflows/full-integration.yml +22 -0
- package/.github/workflows/pr-description-check.yml +88 -0
- package/.github/workflows/publish.yml +33 -0
- package/.github/workflows/release.yml +89 -0
- package/.mcpbignore +58 -0
- package/.prettierignore +10 -0
- package/.prettierrc.json +10 -0
- package/ADOS-2-Module-1-Complete-Manual.md +757 -0
- package/AGENTS.md +36 -0
- package/CHANGELOG.md +187 -0
- package/CLAUDE.md +414 -0
- package/CODEREVIEW_RESPONSE.md +128 -0
- package/LICENSE +17 -0
- package/NUL +1 -0
- package/README.md +222 -0
- package/SCHEMA_IMPROVEMENT_SUMMARY.md +120 -0
- package/TESTING_NOTES.md +217 -0
- package/WARP.md +245 -0
- package/accountactivity-merged.csv +149 -0
- package/bin/ynab-mcp-server.cjs +4 -0
- package/bin/ynab-mcp-server.js +8 -0
- package/bundle-analysis.html +13110 -0
- package/dist/bundle/index.cjs +124 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +85 -0
- package/dist/server/YNABMCPServer.d.ts +264 -0
- package/dist/server/YNABMCPServer.js +845 -0
- package/dist/server/budgetResolver.d.ts +15 -0
- package/dist/server/budgetResolver.js +99 -0
- package/dist/server/cacheManager.d.ts +74 -0
- package/dist/server/cacheManager.js +306 -0
- package/dist/server/config.d.ts +3 -0
- package/dist/server/config.js +19 -0
- package/dist/server/deltaCache.d.ts +61 -0
- package/dist/server/deltaCache.js +206 -0
- package/dist/server/deltaCache.merge.d.ts +9 -0
- package/dist/server/deltaCache.merge.js +111 -0
- package/dist/server/diagnostics.d.ts +90 -0
- package/dist/server/diagnostics.js +163 -0
- package/dist/server/errorHandler.d.ts +69 -0
- package/dist/server/errorHandler.js +524 -0
- package/dist/server/prompts.d.ts +31 -0
- package/dist/server/prompts.js +205 -0
- package/dist/server/rateLimiter.d.ts +27 -0
- package/dist/server/rateLimiter.js +82 -0
- package/dist/server/requestLogger.d.ts +62 -0
- package/dist/server/requestLogger.js +190 -0
- package/dist/server/resources.d.ts +39 -0
- package/dist/server/resources.js +85 -0
- package/dist/server/responseFormatter.d.ts +14 -0
- package/dist/server/responseFormatter.js +42 -0
- package/dist/server/securityMiddleware.d.ts +87 -0
- package/dist/server/securityMiddleware.js +117 -0
- package/dist/server/serverKnowledgeStore.d.ts +11 -0
- package/dist/server/serverKnowledgeStore.js +42 -0
- package/dist/server/toolRegistry.d.ts +85 -0
- package/dist/server/toolRegistry.js +272 -0
- package/dist/tools/__tests__/deltaTestUtils.d.ts +18 -0
- package/dist/tools/__tests__/deltaTestUtils.js +26 -0
- package/dist/tools/accountTools.d.ts +37 -0
- package/dist/tools/accountTools.js +175 -0
- package/dist/tools/budgetTools.d.ts +10 -0
- package/dist/tools/budgetTools.js +68 -0
- package/dist/tools/categoryTools.d.ts +27 -0
- package/dist/tools/categoryTools.js +232 -0
- package/dist/tools/compareTransactions/formatter.d.ts +71 -0
- package/dist/tools/compareTransactions/formatter.js +97 -0
- package/dist/tools/compareTransactions/index.d.ts +30 -0
- package/dist/tools/compareTransactions/index.js +160 -0
- package/dist/tools/compareTransactions/matcher.d.ts +12 -0
- package/dist/tools/compareTransactions/matcher.js +140 -0
- package/dist/tools/compareTransactions/parser.d.ts +14 -0
- package/dist/tools/compareTransactions/parser.js +430 -0
- package/dist/tools/compareTransactions/types.d.ts +27 -0
- package/dist/tools/compareTransactions/types.js +1 -0
- package/dist/tools/compareTransactions.d.ts +1 -0
- package/dist/tools/compareTransactions.js +1 -0
- package/dist/tools/deltaFetcher.d.ts +22 -0
- package/dist/tools/deltaFetcher.js +137 -0
- package/dist/tools/deltaSupport.d.ts +20 -0
- package/dist/tools/deltaSupport.js +176 -0
- package/dist/tools/exportTransactions.d.ts +17 -0
- package/dist/tools/exportTransactions.js +191 -0
- package/dist/tools/monthTools.d.ts +16 -0
- package/dist/tools/monthTools.js +107 -0
- package/dist/tools/payeeTools.d.ts +17 -0
- package/dist/tools/payeeTools.js +82 -0
- package/dist/tools/reconcileAdapter.d.ts +25 -0
- package/dist/tools/reconcileAdapter.js +167 -0
- package/dist/tools/reconciliation/analyzer.d.ts +3 -0
- package/dist/tools/reconciliation/analyzer.js +567 -0
- package/dist/tools/reconciliation/executor.d.ts +94 -0
- package/dist/tools/reconciliation/executor.js +611 -0
- package/dist/tools/reconciliation/index.d.ts +54 -0
- package/dist/tools/reconciliation/index.js +249 -0
- package/dist/tools/reconciliation/matcher.d.ts +3 -0
- package/dist/tools/reconciliation/matcher.js +160 -0
- package/dist/tools/reconciliation/payeeNormalizer.d.ts +6 -0
- package/dist/tools/reconciliation/payeeNormalizer.js +77 -0
- package/dist/tools/reconciliation/recommendationEngine.d.ts +2 -0
- package/dist/tools/reconciliation/recommendationEngine.js +273 -0
- package/dist/tools/reconciliation/reportFormatter.d.ts +13 -0
- package/dist/tools/reconciliation/reportFormatter.js +214 -0
- package/dist/tools/reconciliation/types.d.ts +172 -0
- package/dist/tools/reconciliation/types.js +7 -0
- package/dist/tools/schemas/outputs/accountOutputs.d.ts +58 -0
- package/dist/tools/schemas/outputs/accountOutputs.js +24 -0
- package/dist/tools/schemas/outputs/budgetOutputs.d.ts +48 -0
- package/dist/tools/schemas/outputs/budgetOutputs.js +15 -0
- package/dist/tools/schemas/outputs/categoryOutputs.d.ts +93 -0
- package/dist/tools/schemas/outputs/categoryOutputs.js +37 -0
- package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +269 -0
- package/dist/tools/schemas/outputs/comparisonOutputs.js +181 -0
- package/dist/tools/schemas/outputs/index.d.ts +14 -0
- package/dist/tools/schemas/outputs/index.js +14 -0
- package/dist/tools/schemas/outputs/monthOutputs.d.ts +122 -0
- package/dist/tools/schemas/outputs/monthOutputs.js +51 -0
- package/dist/tools/schemas/outputs/payeeOutputs.d.ts +34 -0
- package/dist/tools/schemas/outputs/payeeOutputs.js +16 -0
- package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +1275 -0
- package/dist/tools/schemas/outputs/reconciliationOutputs.js +377 -0
- package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +717 -0
- package/dist/tools/schemas/outputs/transactionMutationOutputs.js +260 -0
- package/dist/tools/schemas/outputs/transactionOutputs.d.ts +98 -0
- package/dist/tools/schemas/outputs/transactionOutputs.js +49 -0
- package/dist/tools/schemas/outputs/utilityOutputs.d.ts +219 -0
- package/dist/tools/schemas/outputs/utilityOutputs.js +120 -0
- package/dist/tools/schemas/shared/commonOutputs.d.ts +24 -0
- package/dist/tools/schemas/shared/commonOutputs.js +27 -0
- package/dist/tools/toolCategories.d.ts +32 -0
- package/dist/tools/toolCategories.js +32 -0
- package/dist/tools/transactionTools.d.ts +315 -0
- package/dist/tools/transactionTools.js +1722 -0
- package/dist/tools/utilityTools.d.ts +10 -0
- package/dist/tools/utilityTools.js +56 -0
- package/dist/types/index.d.ts +20 -0
- package/dist/types/index.js +16 -0
- package/dist/types/toolAnnotations.d.ts +7 -0
- package/dist/types/toolAnnotations.js +1 -0
- package/dist/utils/amountUtils.d.ts +3 -0
- package/dist/utils/amountUtils.js +10 -0
- package/dist/utils/dateUtils.d.ts +9 -0
- package/dist/utils/dateUtils.js +43 -0
- package/dist/utils/money.d.ts +21 -0
- package/dist/utils/money.js +51 -0
- package/docs/README.md +72 -0
- package/docs/assets/examples/reconciliation-with-recommendations.json +68 -0
- package/docs/assets/schemas/reconciliation-v2.json +338 -0
- package/docs/getting-started/CONFIGURATION.md +175 -0
- package/docs/getting-started/INSTALLATION.md +333 -0
- package/docs/getting-started/QUICKSTART.md +282 -0
- package/docs/guides/ARCHITECTURE.md +650 -0
- package/docs/guides/DEPLOYMENT.md +189 -0
- package/docs/guides/INTEGRATION_TESTING.md +730 -0
- package/docs/guides/TESTING.md +591 -0
- package/docs/reconciliation-flow.md +83 -0
- package/docs/reference/API.md +1450 -0
- package/docs/reference/EXAMPLES.md +946 -0
- package/docs/reference/TOOLS.md +348 -0
- package/docs/reference/TROUBLESHOOTING.md +481 -0
- package/esbuild.config.mjs +68 -0
- package/eslint.config.js +49 -0
- package/fix-types.sh +17 -0
- package/meta.json +12550 -0
- package/package.json +105 -0
- package/package.json.tmp +105 -0
- package/scripts/analyze-bundle.mjs +41 -0
- package/scripts/create-pr-description.js +203 -0
- package/scripts/generate-mcpb.ps1 +96 -0
- package/scripts/run-domain-integration-tests.js +33 -0
- package/scripts/run-generate-mcpb.js +29 -0
- package/scripts/run-throttled-integration-tests.js +116 -0
- package/scripts/test-delta-params.mjs +140 -0
- package/scripts/test-recommendations.ts +53 -0
- package/scripts/tmpTransaction.ts +48 -0
- package/scripts/validate-env.js +122 -0
- package/scripts/verify-build.js +105 -0
- package/scripts/watch-and-restart.ps1 +50 -0
- package/src/__tests__/comprehensive.integration.test.ts +1196 -0
- package/src/__tests__/delta.performance.test.ts +80 -0
- package/src/__tests__/performance.test.ts +725 -0
- package/src/__tests__/setup.ts +449 -0
- package/src/__tests__/testRunner.ts +444 -0
- package/src/__tests__/testUtils.ts +563 -0
- package/src/__tests__/workflows.e2e.test.ts +1675 -0
- package/src/index.ts +124 -0
- package/src/server/.gitkeep +1 -0
- package/src/server/YNABMCPServer.ts +1188 -0
- package/src/server/__tests__/YNABMCPServer.integration.test.ts +903 -0
- package/src/server/__tests__/YNABMCPServer.test.ts +894 -0
- package/src/server/__tests__/budgetResolver.test.ts +425 -0
- package/src/server/__tests__/cacheManager.test.ts +880 -0
- package/src/server/__tests__/config.test.ts +166 -0
- package/src/server/__tests__/deltaCache.merge.test.ts +724 -0
- package/src/server/__tests__/deltaCache.swr.test.ts +168 -0
- package/src/server/__tests__/deltaCache.test.ts +774 -0
- package/src/server/__tests__/diagnostics.test.ts +823 -0
- package/src/server/__tests__/errorHandler.integration.test.ts +466 -0
- package/src/server/__tests__/errorHandler.test.ts +416 -0
- package/src/server/__tests__/prompts.test.ts +354 -0
- package/src/server/__tests__/rateLimiter.test.ts +314 -0
- package/src/server/__tests__/requestLogger.test.ts +408 -0
- package/src/server/__tests__/resources.test.ts +299 -0
- package/src/server/__tests__/security.integration.test.ts +426 -0
- package/src/server/__tests__/securityMiddleware.test.ts +449 -0
- package/src/server/__tests__/server-startup.integration.test.ts +477 -0
- package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -0
- package/src/server/__tests__/toolRegistry.test.ts +855 -0
- package/src/server/budgetResolver.ts +235 -0
- package/src/server/cacheManager.ts +503 -0
- package/src/server/config.ts +41 -0
- package/src/server/deltaCache.merge.ts +149 -0
- package/src/server/deltaCache.ts +341 -0
- package/src/server/diagnostics.ts +338 -0
- package/src/server/errorHandler.ts +756 -0
- package/src/server/prompts.ts +291 -0
- package/src/server/rateLimiter.ts +156 -0
- package/src/server/requestLogger.ts +344 -0
- package/src/server/resources.ts +168 -0
- package/src/server/responseFormatter.ts +51 -0
- package/src/server/securityMiddleware.ts +236 -0
- package/src/server/serverKnowledgeStore.ts +91 -0
- package/src/server/toolRegistry.ts +489 -0
- package/src/tools/.gitkeep +1 -0
- package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -0
- package/src/tools/__tests__/accountTools.integration.test.ts +117 -0
- package/src/tools/__tests__/accountTools.test.ts +653 -0
- package/src/tools/__tests__/budgetTools.delta.integration.test.ts +90 -0
- package/src/tools/__tests__/budgetTools.integration.test.ts +134 -0
- package/src/tools/__tests__/budgetTools.test.ts +423 -0
- package/src/tools/__tests__/categoryTools.delta.integration.test.ts +80 -0
- package/src/tools/__tests__/categoryTools.integration.test.ts +295 -0
- package/src/tools/__tests__/categoryTools.test.ts +622 -0
- package/src/tools/__tests__/compareTransactions/formatter.test.ts +486 -0
- package/src/tools/__tests__/compareTransactions/index.test.ts +383 -0
- package/src/tools/__tests__/compareTransactions/matcher.test.ts +410 -0
- package/src/tools/__tests__/compareTransactions/parser.test.ts +764 -0
- package/src/tools/__tests__/compareTransactions.test.ts +342 -0
- package/src/tools/__tests__/compareTransactions.window.test.ts +147 -0
- package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +76 -0
- package/src/tools/__tests__/deltaFetcher.test.ts +270 -0
- package/src/tools/__tests__/deltaSupport.test.ts +188 -0
- package/src/tools/__tests__/deltaTestUtils.ts +46 -0
- package/src/tools/__tests__/exportTransactions.test.ts +213 -0
- package/src/tools/__tests__/monthTools.delta.integration.test.ts +80 -0
- package/src/tools/__tests__/monthTools.integration.test.ts +174 -0
- package/src/tools/__tests__/monthTools.test.ts +523 -0
- package/src/tools/__tests__/payeeTools.delta.integration.test.ts +80 -0
- package/src/tools/__tests__/payeeTools.integration.test.ts +150 -0
- package/src/tools/__tests__/payeeTools.test.ts +445 -0
- package/src/tools/__tests__/transactionTools.integration.test.ts +762 -0
- package/src/tools/__tests__/transactionTools.test.ts +3521 -0
- package/src/tools/__tests__/utilityTools.integration.test.ts +128 -0
- package/src/tools/__tests__/utilityTools.test.ts +205 -0
- package/src/tools/accountTools.ts +283 -0
- package/src/tools/budgetTools.ts +112 -0
- package/src/tools/categoryTools.ts +366 -0
- package/src/tools/compareTransactions/formatter.ts +163 -0
- package/src/tools/compareTransactions/index.ts +228 -0
- package/src/tools/compareTransactions/matcher.ts +240 -0
- package/src/tools/compareTransactions/parser.ts +557 -0
- package/src/tools/compareTransactions/types.ts +60 -0
- package/src/tools/compareTransactions.ts +3 -0
- package/src/tools/deltaFetcher.ts +278 -0
- package/src/tools/deltaSupport.ts +293 -0
- package/src/tools/exportTransactions.ts +273 -0
- package/src/tools/monthTools.ts +164 -0
- package/src/tools/payeeTools.ts +140 -0
- package/src/tools/reconcileAdapter.ts +312 -0
- package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +122 -0
- package/src/tools/reconciliation/__tests__/adapter.test.ts +234 -0
- package/src/tools/reconciliation/__tests__/analyzer.test.ts +406 -0
- package/src/tools/reconciliation/__tests__/executor.integration.test.ts +366 -0
- package/src/tools/reconciliation/__tests__/executor.test.ts +779 -0
- package/src/tools/reconciliation/__tests__/matcher.test.ts +650 -0
- package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +278 -0
- package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +658 -0
- package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1000 -0
- package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +151 -0
- package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +573 -0
- package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +78 -0
- package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +47 -0
- package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +61 -0
- package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +49 -0
- package/src/tools/reconciliation/analyzer.ts +824 -0
- package/src/tools/reconciliation/executor.ts +880 -0
- package/src/tools/reconciliation/index.ts +400 -0
- package/src/tools/reconciliation/matcher.ts +269 -0
- package/src/tools/reconciliation/payeeNormalizer.ts +167 -0
- package/src/tools/reconciliation/recommendationEngine.ts +506 -0
- package/src/tools/reconciliation/reportFormatter.ts +363 -0
- package/src/tools/reconciliation/types.ts +314 -0
- package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +424 -0
- package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +310 -0
- package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +448 -0
- package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +519 -0
- package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +155 -0
- package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +288 -0
- package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +478 -0
- package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +370 -0
- package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +401 -0
- package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +213 -0
- package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +474 -0
- package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +333 -0
- package/src/tools/schemas/outputs/accountOutputs.ts +137 -0
- package/src/tools/schemas/outputs/budgetOutputs.ts +86 -0
- package/src/tools/schemas/outputs/categoryOutputs.ts +194 -0
- package/src/tools/schemas/outputs/comparisonOutputs.ts +600 -0
- package/src/tools/schemas/outputs/index.ts +270 -0
- package/src/tools/schemas/outputs/monthOutputs.ts +243 -0
- package/src/tools/schemas/outputs/payeeOutputs.ts +105 -0
- package/src/tools/schemas/outputs/reconciliationOutputs.ts +796 -0
- package/src/tools/schemas/outputs/transactionMutationOutputs.ts +758 -0
- package/src/tools/schemas/outputs/transactionOutputs.ts +243 -0
- package/src/tools/schemas/outputs/utilityOutputs.ts +411 -0
- package/src/tools/schemas/shared/commonOutputs.ts +140 -0
- package/src/tools/toolCategories.ts +140 -0
- package/src/tools/transactionTools.ts +2509 -0
- package/src/tools/utilityTools.ts +90 -0
- package/src/types/.gitkeep +1 -0
- package/src/types/__tests__/index.test.ts +52 -0
- package/src/types/index.ts +67 -0
- package/src/types/integration-tests.d.ts +35 -0
- package/src/types/toolAnnotations.ts +44 -0
- package/src/utils/__tests__/dateUtils.test.ts +170 -0
- package/src/utils/__tests__/money.test.ts +189 -0
- package/src/utils/amountUtils.ts +32 -0
- package/src/utils/dateUtils.ts +108 -0
- package/src/utils/money.ts +123 -0
- package/test-csv-sample.csv +28 -0
- package/test-exports/sample_bank_statement.csv +7 -0
- package/test-exports/ynab_account_e9ddc2a6_minimal_1items_2025-11-19_09-04-53.json +23 -0
- package/test-exports/ynab_account_e9ddc2a6_minimal_1items_2025-11-19_10-37-42.json +23 -0
- package/test-exports/ynab_account_e9ddc2a6_minimal_4items_2025-11-19_09-02-09.json +44 -0
- package/test-exports/ynab_account_e9ddc2a6_minimal_6items_2025-11-19_10-37-52.json +58 -0
- package/test-exports/ynab_since_2025-11-01_account_4c18e9f0_minimal_14items_2025-11-16_10-07-10.json +115 -0
- package/test-reconcile-autodetect.js +40 -0
- package/test-reconcile-tool.js +152 -0
- package/test-reconcile-with-csv.cjs +89 -0
- package/test-statement.csv +8 -0
- package/test_debug.js +47 -0
- package/test_simple.mjs +16 -0
- package/tsconfig.json +31 -0
- package/tsconfig.prod.json +18 -0
- package/vitest-reporters/split-json-reporter.ts +211 -0
- package/vitest.config.ts +96 -0
|
@@ -0,0 +1,1722 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { createHash } from 'crypto';
|
|
3
|
+
import { ValidationError, withToolErrorHandling } from '../types/index.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
|
+
function ensureTransaction(transaction, errorMessage) {
|
|
10
|
+
if (!transaction) {
|
|
11
|
+
throw new Error(errorMessage);
|
|
12
|
+
}
|
|
13
|
+
return transaction;
|
|
14
|
+
}
|
|
15
|
+
const toMonthKey = (date) => `${date.slice(0, 7)}-01`;
|
|
16
|
+
function appendCategoryIds(source, target) {
|
|
17
|
+
if (!source) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (source.category_id) {
|
|
21
|
+
target.add(source.category_id);
|
|
22
|
+
}
|
|
23
|
+
if (Array.isArray(source.subtransactions)) {
|
|
24
|
+
for (const sub of source.subtransactions) {
|
|
25
|
+
if (sub?.category_id) {
|
|
26
|
+
target.add(sub.category_id);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function collectCategoryIdsFromSources(...sources) {
|
|
32
|
+
const result = new Set();
|
|
33
|
+
for (const source of sources) {
|
|
34
|
+
appendCategoryIds(source, result);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
function setsEqual(a, b) {
|
|
39
|
+
if (a.size !== b.size) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
for (const value of a) {
|
|
43
|
+
if (!b.has(value)) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
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 const ListTransactionsSchema = z
|
|
93
|
+
.object({
|
|
94
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
95
|
+
account_id: z.string().optional(),
|
|
96
|
+
category_id: z.string().optional(),
|
|
97
|
+
since_date: z
|
|
98
|
+
.string()
|
|
99
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
|
|
100
|
+
.optional(),
|
|
101
|
+
type: z.enum(['uncategorized', 'unapproved']).optional(),
|
|
102
|
+
})
|
|
103
|
+
.strict();
|
|
104
|
+
export const GetTransactionSchema = z
|
|
105
|
+
.object({
|
|
106
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
107
|
+
transaction_id: z.string().min(1, 'Transaction ID is required'),
|
|
108
|
+
})
|
|
109
|
+
.strict();
|
|
110
|
+
export const CreateTransactionSchema = z
|
|
111
|
+
.object({
|
|
112
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
113
|
+
account_id: z.string().min(1, 'Account ID is required'),
|
|
114
|
+
amount: z.number().int('Amount must be an integer in milliunits'),
|
|
115
|
+
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)'),
|
|
116
|
+
payee_name: z.string().optional(),
|
|
117
|
+
payee_id: z.string().optional(),
|
|
118
|
+
category_id: z.string().optional(),
|
|
119
|
+
memo: z.string().optional(),
|
|
120
|
+
cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
|
|
121
|
+
approved: z.boolean().optional(),
|
|
122
|
+
flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
|
|
123
|
+
import_id: z.string().min(1, 'Import ID cannot be empty').optional(),
|
|
124
|
+
dry_run: z.boolean().optional(),
|
|
125
|
+
subtransactions: z
|
|
126
|
+
.array(z
|
|
127
|
+
.object({
|
|
128
|
+
amount: z.number().int('Subtransaction amount must be an integer in milliunits'),
|
|
129
|
+
payee_name: z.string().optional(),
|
|
130
|
+
payee_id: z.string().optional(),
|
|
131
|
+
category_id: z.string().optional(),
|
|
132
|
+
memo: z.string().optional(),
|
|
133
|
+
})
|
|
134
|
+
.strict())
|
|
135
|
+
.min(1, 'At least one subtransaction is required when provided')
|
|
136
|
+
.optional(),
|
|
137
|
+
})
|
|
138
|
+
.strict()
|
|
139
|
+
.superRefine((data, ctx) => {
|
|
140
|
+
if (data.subtransactions && data.subtransactions.length > 0) {
|
|
141
|
+
const total = data.subtransactions.reduce((sum, sub) => sum + sub.amount, 0);
|
|
142
|
+
if (total !== data.amount) {
|
|
143
|
+
ctx.addIssue({
|
|
144
|
+
code: z.ZodIssueCode.custom,
|
|
145
|
+
message: 'Amount must equal the sum of subtransaction amounts',
|
|
146
|
+
path: ['amount'],
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const BulkTransactionInputSchemaBase = CreateTransactionSchema.pick({
|
|
152
|
+
account_id: true,
|
|
153
|
+
amount: true,
|
|
154
|
+
date: true,
|
|
155
|
+
payee_name: true,
|
|
156
|
+
payee_id: true,
|
|
157
|
+
category_id: true,
|
|
158
|
+
memo: true,
|
|
159
|
+
cleared: true,
|
|
160
|
+
approved: true,
|
|
161
|
+
flag_color: true,
|
|
162
|
+
import_id: true,
|
|
163
|
+
});
|
|
164
|
+
const BulkTransactionInputSchema = BulkTransactionInputSchemaBase.extend({
|
|
165
|
+
subtransactions: z.any().optional(),
|
|
166
|
+
})
|
|
167
|
+
.strict()
|
|
168
|
+
.superRefine((data, ctx) => {
|
|
169
|
+
if (data.subtransactions !== undefined) {
|
|
170
|
+
ctx.addIssue({
|
|
171
|
+
code: z.ZodIssueCode.custom,
|
|
172
|
+
message: 'Subtransactions are not supported in bulk transaction creation',
|
|
173
|
+
path: ['subtransactions'],
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
.transform((data) => {
|
|
178
|
+
const { subtransactions, ...rest } = data;
|
|
179
|
+
return rest;
|
|
180
|
+
});
|
|
181
|
+
export const CreateTransactionsSchema = z
|
|
182
|
+
.object({
|
|
183
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
184
|
+
transactions: z
|
|
185
|
+
.array(BulkTransactionInputSchema)
|
|
186
|
+
.min(1, 'At least one transaction is required')
|
|
187
|
+
.max(100, 'A maximum of 100 transactions may be created at once'),
|
|
188
|
+
dry_run: z.boolean().optional(),
|
|
189
|
+
})
|
|
190
|
+
.strict();
|
|
191
|
+
const FULL_RESPONSE_THRESHOLD = 64 * 1024;
|
|
192
|
+
const SUMMARY_RESPONSE_THRESHOLD = 96 * 1024;
|
|
193
|
+
const MAX_RESPONSE_BYTES = 100 * 1024;
|
|
194
|
+
export function generateCorrelationKey(transaction) {
|
|
195
|
+
if (transaction.import_id) {
|
|
196
|
+
return transaction.import_id;
|
|
197
|
+
}
|
|
198
|
+
const segments = [
|
|
199
|
+
`account:${transaction.account_id ?? ''}`,
|
|
200
|
+
`date:${transaction.date ?? ''}`,
|
|
201
|
+
`amount:${transaction.amount ?? 0}`,
|
|
202
|
+
`payee:${transaction.payee_id ?? transaction.payee_name ?? ''}`,
|
|
203
|
+
`category:${transaction.category_id ?? ''}`,
|
|
204
|
+
`memo:${transaction.memo ?? ''}`,
|
|
205
|
+
`cleared:${transaction.cleared ?? ''}`,
|
|
206
|
+
`approved:${transaction.approved ?? false}`,
|
|
207
|
+
`flag:${transaction.flag_color ?? ''}`,
|
|
208
|
+
];
|
|
209
|
+
const normalized = segments.join('|');
|
|
210
|
+
const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16);
|
|
211
|
+
return `hash:${hash}`;
|
|
212
|
+
}
|
|
213
|
+
export function toCorrelationPayload(transaction) {
|
|
214
|
+
const payload = {};
|
|
215
|
+
if (transaction.account_id !== undefined) {
|
|
216
|
+
payload.account_id = transaction.account_id;
|
|
217
|
+
}
|
|
218
|
+
if (transaction.date !== undefined) {
|
|
219
|
+
payload.date = transaction.date;
|
|
220
|
+
}
|
|
221
|
+
if (transaction.amount !== undefined) {
|
|
222
|
+
payload.amount = transaction.amount;
|
|
223
|
+
}
|
|
224
|
+
if (transaction.cleared !== undefined) {
|
|
225
|
+
payload.cleared = transaction.cleared;
|
|
226
|
+
}
|
|
227
|
+
if (transaction.approved !== undefined) {
|
|
228
|
+
payload.approved = transaction.approved;
|
|
229
|
+
}
|
|
230
|
+
if (transaction.flag_color !== undefined) {
|
|
231
|
+
payload.flag_color = transaction.flag_color;
|
|
232
|
+
}
|
|
233
|
+
payload.payee_id = transaction.payee_id ?? null;
|
|
234
|
+
payload.payee_name = transaction.payee_name ?? null;
|
|
235
|
+
payload.category_id = transaction.category_id ?? null;
|
|
236
|
+
payload.memo = transaction.memo ?? null;
|
|
237
|
+
payload.import_id = transaction.import_id ?? null;
|
|
238
|
+
return payload;
|
|
239
|
+
}
|
|
240
|
+
export function correlateResults(requests, responseData, duplicateImportIds) {
|
|
241
|
+
const createdByImportId = new Map();
|
|
242
|
+
const createdByHash = new Map();
|
|
243
|
+
const responseTransactions = responseData.transactions ?? [];
|
|
244
|
+
const register = (map, key, transactionId) => {
|
|
245
|
+
const existing = map.get(key);
|
|
246
|
+
if (existing) {
|
|
247
|
+
existing.push(transactionId);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
map.set(key, [transactionId]);
|
|
251
|
+
};
|
|
252
|
+
for (const transaction of responseTransactions) {
|
|
253
|
+
if (!transaction.id) {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const key = generateCorrelationKey(transaction);
|
|
257
|
+
if (key.startsWith('hash:')) {
|
|
258
|
+
register(createdByHash, key, transaction.id);
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
register(createdByImportId, key, transaction.id);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const popId = (map, key) => {
|
|
265
|
+
const bucket = map.get(key);
|
|
266
|
+
if (!bucket || bucket.length === 0) {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
const [transactionId] = bucket.splice(0, 1);
|
|
270
|
+
if (bucket.length === 0) {
|
|
271
|
+
map.delete(key);
|
|
272
|
+
}
|
|
273
|
+
return transactionId;
|
|
274
|
+
};
|
|
275
|
+
const correlatedResults = [];
|
|
276
|
+
for (const [index, transaction] of requests.entries()) {
|
|
277
|
+
const normalizedRequest = toCorrelationPayload(transaction);
|
|
278
|
+
const correlationKey = generateCorrelationKey(normalizedRequest);
|
|
279
|
+
if (transaction.import_id && duplicateImportIds.has(transaction.import_id)) {
|
|
280
|
+
correlatedResults.push({
|
|
281
|
+
request_index: index,
|
|
282
|
+
status: 'duplicate',
|
|
283
|
+
correlation_key: correlationKey,
|
|
284
|
+
});
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
let transactionId;
|
|
288
|
+
if (correlationKey.startsWith('hash:')) {
|
|
289
|
+
transactionId = popId(createdByHash, correlationKey);
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
transactionId = popId(createdByImportId, correlationKey);
|
|
293
|
+
}
|
|
294
|
+
if (!transactionId && !correlationKey.startsWith('hash:')) {
|
|
295
|
+
const hashKey = generateCorrelationKey(toCorrelationPayload({ ...transaction, import_id: undefined }));
|
|
296
|
+
transactionId = popId(createdByHash, hashKey);
|
|
297
|
+
}
|
|
298
|
+
if (transactionId) {
|
|
299
|
+
const successResult = {
|
|
300
|
+
request_index: index,
|
|
301
|
+
status: 'created',
|
|
302
|
+
correlation_key: correlationKey,
|
|
303
|
+
};
|
|
304
|
+
successResult.transaction_id = transactionId;
|
|
305
|
+
correlatedResults.push(successResult);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
globalRequestLogger.logError('ynab:create_transactions', 'correlate_results', {
|
|
309
|
+
request_index: index,
|
|
310
|
+
correlation_key: correlationKey,
|
|
311
|
+
request: {
|
|
312
|
+
account_id: transaction.account_id,
|
|
313
|
+
date: transaction.date,
|
|
314
|
+
amount: transaction.amount,
|
|
315
|
+
import_id: transaction.import_id,
|
|
316
|
+
},
|
|
317
|
+
}, 'correlation_failed');
|
|
318
|
+
correlatedResults.push({
|
|
319
|
+
request_index: index,
|
|
320
|
+
status: 'failed',
|
|
321
|
+
correlation_key: correlationKey,
|
|
322
|
+
error_code: 'correlation_failed',
|
|
323
|
+
error: 'Unable to correlate request transaction with YNAB response',
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
return correlatedResults;
|
|
327
|
+
}
|
|
328
|
+
function estimatePayloadSize(payload) {
|
|
329
|
+
return Buffer.byteLength(JSON.stringify(payload), 'utf8');
|
|
330
|
+
}
|
|
331
|
+
function finalizeResponse(response) {
|
|
332
|
+
const appendMessage = (message, addition) => {
|
|
333
|
+
if (!message) {
|
|
334
|
+
return addition;
|
|
335
|
+
}
|
|
336
|
+
if (message.includes(addition)) {
|
|
337
|
+
return message;
|
|
338
|
+
}
|
|
339
|
+
return `${message} ${addition}`;
|
|
340
|
+
};
|
|
341
|
+
const fullSize = estimatePayloadSize({ ...response, mode: 'full' });
|
|
342
|
+
if (fullSize <= FULL_RESPONSE_THRESHOLD) {
|
|
343
|
+
return { ...response, mode: 'full' };
|
|
344
|
+
}
|
|
345
|
+
const { transactions, ...summaryResponse } = response;
|
|
346
|
+
const summaryPayload = {
|
|
347
|
+
...summaryResponse,
|
|
348
|
+
message: appendMessage(response.message, 'Response downgraded to summary to stay under size limits.'),
|
|
349
|
+
mode: 'summary',
|
|
350
|
+
};
|
|
351
|
+
if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
|
|
352
|
+
return summaryPayload;
|
|
353
|
+
}
|
|
354
|
+
const idsOnlyPayload = {
|
|
355
|
+
...summaryPayload,
|
|
356
|
+
results: summaryResponse.results.map((result) => ({
|
|
357
|
+
request_index: result.request_index,
|
|
358
|
+
status: result.status,
|
|
359
|
+
transaction_id: result.transaction_id,
|
|
360
|
+
correlation_key: result.correlation_key,
|
|
361
|
+
error: result.error,
|
|
362
|
+
})),
|
|
363
|
+
message: appendMessage(summaryResponse.message, 'Response downgraded to ids_only to meet 100KB limit.'),
|
|
364
|
+
mode: 'ids_only',
|
|
365
|
+
};
|
|
366
|
+
if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
|
|
367
|
+
return idsOnlyPayload;
|
|
368
|
+
}
|
|
369
|
+
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']);
|
|
370
|
+
}
|
|
371
|
+
const ReceiptSplitItemSchema = z
|
|
372
|
+
.object({
|
|
373
|
+
name: z.string().min(1, 'Item name is required'),
|
|
374
|
+
amount: z
|
|
375
|
+
.number()
|
|
376
|
+
.finite('Item amount must be a finite number')
|
|
377
|
+
.refine((value) => value >= 0, 'Item amount must be zero or greater'),
|
|
378
|
+
quantity: z
|
|
379
|
+
.number()
|
|
380
|
+
.finite('Quantity must be a finite number')
|
|
381
|
+
.positive('Quantity must be greater than zero')
|
|
382
|
+
.optional(),
|
|
383
|
+
memo: z.string().optional(),
|
|
384
|
+
})
|
|
385
|
+
.strict();
|
|
386
|
+
const ReceiptSplitCategorySchema = z
|
|
387
|
+
.object({
|
|
388
|
+
category_id: z.string().min(1, 'Category ID is required'),
|
|
389
|
+
category_name: z.string().optional(),
|
|
390
|
+
items: z.array(ReceiptSplitItemSchema).min(1, 'Each category must include at least one item'),
|
|
391
|
+
})
|
|
392
|
+
.strict();
|
|
393
|
+
export const CreateReceiptSplitTransactionSchema = z
|
|
394
|
+
.object({
|
|
395
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
396
|
+
account_id: z.string().min(1, 'Account ID is required'),
|
|
397
|
+
payee_name: z.string().min(1, 'Payee name is required'),
|
|
398
|
+
date: z
|
|
399
|
+
.string()
|
|
400
|
+
.regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
|
|
401
|
+
.optional(),
|
|
402
|
+
memo: z.string().optional(),
|
|
403
|
+
receipt_subtotal: z
|
|
404
|
+
.number()
|
|
405
|
+
.finite('Receipt subtotal must be a finite number')
|
|
406
|
+
.refine((value) => value >= 0, 'Receipt subtotal must be zero or greater')
|
|
407
|
+
.optional(),
|
|
408
|
+
receipt_tax: z
|
|
409
|
+
.number()
|
|
410
|
+
.finite('Receipt tax must be a finite number')
|
|
411
|
+
.refine((value) => value >= 0, 'Receipt tax must be zero or greater'),
|
|
412
|
+
receipt_total: z
|
|
413
|
+
.number()
|
|
414
|
+
.finite('Receipt total must be a finite number')
|
|
415
|
+
.refine((value) => value > 0, 'Receipt total must be greater than zero'),
|
|
416
|
+
categories: z
|
|
417
|
+
.array(ReceiptSplitCategorySchema)
|
|
418
|
+
.min(1, 'At least one categorized group is required to create a split transaction'),
|
|
419
|
+
cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
|
|
420
|
+
approved: z.boolean().optional(),
|
|
421
|
+
flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
|
|
422
|
+
dry_run: z.boolean().optional(),
|
|
423
|
+
})
|
|
424
|
+
.strict()
|
|
425
|
+
.superRefine((data, ctx) => {
|
|
426
|
+
const itemsSubtotal = data.categories
|
|
427
|
+
.flatMap((category) => category.items)
|
|
428
|
+
.reduce((sum, item) => sum + item.amount, 0);
|
|
429
|
+
if (data.receipt_subtotal !== undefined) {
|
|
430
|
+
const delta = Math.abs(data.receipt_subtotal - itemsSubtotal);
|
|
431
|
+
if (delta > 0.01) {
|
|
432
|
+
ctx.addIssue({
|
|
433
|
+
code: z.ZodIssueCode.custom,
|
|
434
|
+
message: `Receipt subtotal (${data.receipt_subtotal.toFixed(2)}) does not match categorized items total (${itemsSubtotal.toFixed(2)})`,
|
|
435
|
+
path: ['receipt_subtotal'],
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
const expectedTotal = itemsSubtotal + data.receipt_tax;
|
|
440
|
+
const deltaTotal = Math.abs(expectedTotal - data.receipt_total);
|
|
441
|
+
if (deltaTotal > 0.01) {
|
|
442
|
+
ctx.addIssue({
|
|
443
|
+
code: z.ZodIssueCode.custom,
|
|
444
|
+
message: `Receipt total (${data.receipt_total.toFixed(2)}) does not match subtotal plus tax (${expectedTotal.toFixed(2)})`,
|
|
445
|
+
path: ['receipt_total'],
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
export const UpdateTransactionSchema = z
|
|
450
|
+
.object({
|
|
451
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
452
|
+
transaction_id: z.string().min(1, 'Transaction ID is required'),
|
|
453
|
+
account_id: z.string().optional(),
|
|
454
|
+
amount: z.number().int('Amount must be an integer in milliunits').optional(),
|
|
455
|
+
date: z
|
|
456
|
+
.string()
|
|
457
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
|
|
458
|
+
.optional(),
|
|
459
|
+
payee_name: z.string().optional(),
|
|
460
|
+
payee_id: z.string().optional(),
|
|
461
|
+
category_id: z.string().optional(),
|
|
462
|
+
memo: z.string().optional(),
|
|
463
|
+
cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
|
|
464
|
+
approved: z.boolean().optional(),
|
|
465
|
+
flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
|
|
466
|
+
dry_run: z.boolean().optional(),
|
|
467
|
+
})
|
|
468
|
+
.strict();
|
|
469
|
+
const BulkUpdateTransactionInputSchema = z
|
|
470
|
+
.object({
|
|
471
|
+
id: z.string().min(1, 'Transaction ID is required'),
|
|
472
|
+
amount: z.number().int('Amount must be an integer in milliunits').optional(),
|
|
473
|
+
date: z
|
|
474
|
+
.string()
|
|
475
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
|
|
476
|
+
.optional(),
|
|
477
|
+
payee_name: z.string().optional(),
|
|
478
|
+
payee_id: z.string().optional(),
|
|
479
|
+
category_id: z.string().optional(),
|
|
480
|
+
memo: z.string().optional(),
|
|
481
|
+
cleared: z.enum(['cleared', 'uncleared', 'reconciled']).optional(),
|
|
482
|
+
approved: z.boolean().optional(),
|
|
483
|
+
flag_color: z.enum(['red', 'orange', 'yellow', 'green', 'blue', 'purple']).optional(),
|
|
484
|
+
original_account_id: z.string().optional(),
|
|
485
|
+
original_date: z
|
|
486
|
+
.string()
|
|
487
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in ISO format (YYYY-MM-DD)')
|
|
488
|
+
.optional(),
|
|
489
|
+
})
|
|
490
|
+
.strict();
|
|
491
|
+
export const UpdateTransactionsSchema = z
|
|
492
|
+
.object({
|
|
493
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
494
|
+
transactions: z
|
|
495
|
+
.array(BulkUpdateTransactionInputSchema)
|
|
496
|
+
.min(1, 'At least one transaction is required')
|
|
497
|
+
.max(100, 'A maximum of 100 transactions may be updated at once'),
|
|
498
|
+
dry_run: z.boolean().optional(),
|
|
499
|
+
})
|
|
500
|
+
.strict();
|
|
501
|
+
export const DeleteTransactionSchema = z
|
|
502
|
+
.object({
|
|
503
|
+
budget_id: z.string().min(1, 'Budget ID is required'),
|
|
504
|
+
transaction_id: z.string().min(1, 'Transaction ID is required'),
|
|
505
|
+
dry_run: z.boolean().optional(),
|
|
506
|
+
})
|
|
507
|
+
.strict();
|
|
508
|
+
export async function handleListTransactions(ynabAPI, deltaFetcherOrParams, maybeParams) {
|
|
509
|
+
const { deltaFetcher, params } = resolveDeltaFetcherArgs(ynabAPI, deltaFetcherOrParams, maybeParams);
|
|
510
|
+
return await withToolErrorHandling(async () => {
|
|
511
|
+
let transactions;
|
|
512
|
+
let cacheHit = false;
|
|
513
|
+
let usedDelta = false;
|
|
514
|
+
if (params.account_id) {
|
|
515
|
+
const result = await deltaFetcher.fetchTransactionsByAccount(params.budget_id, params.account_id, params.since_date);
|
|
516
|
+
transactions = result.data;
|
|
517
|
+
cacheHit = result.wasCached;
|
|
518
|
+
usedDelta = result.usedDelta;
|
|
519
|
+
}
|
|
520
|
+
else if (params.category_id) {
|
|
521
|
+
const response = await ynabAPI.transactions.getTransactionsByCategory(params.budget_id, params.category_id, params.since_date);
|
|
522
|
+
transactions = response.data.transactions;
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
const result = await deltaFetcher.fetchTransactions(params.budget_id, params.since_date, params.type);
|
|
526
|
+
transactions = result.data;
|
|
527
|
+
cacheHit = result.wasCached;
|
|
528
|
+
usedDelta = result.usedDelta;
|
|
529
|
+
}
|
|
530
|
+
const estimatedSize = JSON.stringify(transactions).length;
|
|
531
|
+
const sizeLimit = 90000;
|
|
532
|
+
if (estimatedSize > sizeLimit) {
|
|
533
|
+
const preview = transactions.slice(0, 50);
|
|
534
|
+
return {
|
|
535
|
+
content: [
|
|
536
|
+
{
|
|
537
|
+
type: 'text',
|
|
538
|
+
text: responseFormatter.format({
|
|
539
|
+
message: `Found ${transactions.length} transactions (${Math.round(estimatedSize / 1024)}KB). Too large to display all.`,
|
|
540
|
+
suggestion: "Use 'export_transactions' tool to save all transactions to a file.",
|
|
541
|
+
showing: `First ${preview.length} transactions:`,
|
|
542
|
+
total_count: transactions.length,
|
|
543
|
+
estimated_size_kb: Math.round(estimatedSize / 1024),
|
|
544
|
+
preview_transactions: preview.map((transaction) => ({
|
|
545
|
+
id: transaction.id,
|
|
546
|
+
date: transaction.date,
|
|
547
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
548
|
+
memo: transaction.memo,
|
|
549
|
+
payee_name: transaction.payee_name,
|
|
550
|
+
category_name: transaction.category_name,
|
|
551
|
+
})),
|
|
552
|
+
}),
|
|
553
|
+
},
|
|
554
|
+
],
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
content: [
|
|
559
|
+
{
|
|
560
|
+
type: 'text',
|
|
561
|
+
text: responseFormatter.format({
|
|
562
|
+
total_count: transactions.length,
|
|
563
|
+
cached: cacheHit,
|
|
564
|
+
cache_info: cacheHit
|
|
565
|
+
? `Data retrieved from cache for improved performance${usedDelta ? ' (delta merge applied)' : ''}`
|
|
566
|
+
: 'Fresh data retrieved from YNAB API',
|
|
567
|
+
transactions: transactions.map((transaction) => ({
|
|
568
|
+
id: transaction.id,
|
|
569
|
+
date: transaction.date,
|
|
570
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
571
|
+
memo: transaction.memo,
|
|
572
|
+
cleared: transaction.cleared,
|
|
573
|
+
approved: transaction.approved,
|
|
574
|
+
flag_color: transaction.flag_color,
|
|
575
|
+
account_id: transaction.account_id,
|
|
576
|
+
payee_id: transaction.payee_id,
|
|
577
|
+
category_id: transaction.category_id,
|
|
578
|
+
transfer_account_id: transaction.transfer_account_id,
|
|
579
|
+
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
580
|
+
matched_transaction_id: transaction.matched_transaction_id,
|
|
581
|
+
import_id: transaction.import_id,
|
|
582
|
+
deleted: transaction.deleted,
|
|
583
|
+
})),
|
|
584
|
+
}),
|
|
585
|
+
},
|
|
586
|
+
],
|
|
587
|
+
};
|
|
588
|
+
}, 'ynab:list_transactions', 'listing transactions');
|
|
589
|
+
}
|
|
590
|
+
export async function handleGetTransaction(ynabAPI, params) {
|
|
591
|
+
try {
|
|
592
|
+
const useCache = process.env['NODE_ENV'] !== 'test';
|
|
593
|
+
let transaction;
|
|
594
|
+
let cacheHit = false;
|
|
595
|
+
if (useCache) {
|
|
596
|
+
const cacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
597
|
+
cacheHit = cacheManager.has(cacheKey);
|
|
598
|
+
transaction = await cacheManager.wrap(cacheKey, {
|
|
599
|
+
ttl: CACHE_TTLS.TRANSACTIONS,
|
|
600
|
+
loader: async () => {
|
|
601
|
+
const response = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
602
|
+
return ensureTransaction(response.data.transaction, 'Transaction not found');
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
const response = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
608
|
+
transaction = ensureTransaction(response.data.transaction, 'Transaction not found');
|
|
609
|
+
}
|
|
610
|
+
return {
|
|
611
|
+
content: [
|
|
612
|
+
{
|
|
613
|
+
type: 'text',
|
|
614
|
+
text: responseFormatter.format({
|
|
615
|
+
transaction: {
|
|
616
|
+
id: transaction.id,
|
|
617
|
+
date: transaction.date,
|
|
618
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
619
|
+
memo: transaction.memo,
|
|
620
|
+
cleared: transaction.cleared,
|
|
621
|
+
approved: transaction.approved,
|
|
622
|
+
flag_color: transaction.flag_color,
|
|
623
|
+
account_id: transaction.account_id,
|
|
624
|
+
payee_id: transaction.payee_id,
|
|
625
|
+
category_id: transaction.category_id,
|
|
626
|
+
transfer_account_id: transaction.transfer_account_id,
|
|
627
|
+
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
628
|
+
matched_transaction_id: transaction.matched_transaction_id,
|
|
629
|
+
import_id: transaction.import_id,
|
|
630
|
+
deleted: transaction.deleted,
|
|
631
|
+
account_name: transaction.account_name,
|
|
632
|
+
payee_name: transaction.payee_name,
|
|
633
|
+
category_name: transaction.category_name,
|
|
634
|
+
},
|
|
635
|
+
cached: cacheHit,
|
|
636
|
+
cache_info: cacheHit
|
|
637
|
+
? 'Data retrieved from cache for improved performance'
|
|
638
|
+
: 'Fresh data retrieved from YNAB API',
|
|
639
|
+
}),
|
|
640
|
+
},
|
|
641
|
+
],
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
return handleTransactionError(error, 'Failed to get transaction');
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
export async function handleCreateTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
649
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
650
|
+
try {
|
|
651
|
+
if (params.dry_run) {
|
|
652
|
+
return {
|
|
653
|
+
content: [
|
|
654
|
+
{
|
|
655
|
+
type: 'text',
|
|
656
|
+
text: responseFormatter.format({
|
|
657
|
+
dry_run: true,
|
|
658
|
+
action: 'create_transaction',
|
|
659
|
+
request: params,
|
|
660
|
+
}),
|
|
661
|
+
},
|
|
662
|
+
],
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
const transactionData = {
|
|
666
|
+
account_id: params.account_id,
|
|
667
|
+
amount: params.amount,
|
|
668
|
+
date: params.date,
|
|
669
|
+
cleared: params.cleared,
|
|
670
|
+
flag_color: params.flag_color,
|
|
671
|
+
};
|
|
672
|
+
if (params.payee_name !== undefined)
|
|
673
|
+
transactionData.payee_name = params.payee_name;
|
|
674
|
+
if (params.payee_id !== undefined)
|
|
675
|
+
transactionData.payee_id = params.payee_id;
|
|
676
|
+
if (params.category_id !== undefined)
|
|
677
|
+
transactionData.category_id = params.category_id;
|
|
678
|
+
if (params.memo !== undefined)
|
|
679
|
+
transactionData.memo = params.memo;
|
|
680
|
+
if (params.approved !== undefined)
|
|
681
|
+
transactionData.approved = params.approved;
|
|
682
|
+
if (params.import_id !== undefined)
|
|
683
|
+
transactionData.import_id = params.import_id;
|
|
684
|
+
if (params.subtransactions && params.subtransactions.length > 0) {
|
|
685
|
+
const subtransactions = params.subtransactions.map((subtransaction) => {
|
|
686
|
+
const mapped = {
|
|
687
|
+
amount: subtransaction.amount,
|
|
688
|
+
};
|
|
689
|
+
if (subtransaction.payee_name !== undefined)
|
|
690
|
+
mapped.payee_name = subtransaction.payee_name;
|
|
691
|
+
if (subtransaction.payee_id !== undefined)
|
|
692
|
+
mapped.payee_id = subtransaction.payee_id;
|
|
693
|
+
if (subtransaction.category_id !== undefined) {
|
|
694
|
+
mapped.category_id = subtransaction.category_id;
|
|
695
|
+
}
|
|
696
|
+
if (subtransaction.memo !== undefined)
|
|
697
|
+
mapped.memo = subtransaction.memo;
|
|
698
|
+
return mapped;
|
|
699
|
+
});
|
|
700
|
+
transactionData.subtransactions = subtransactions;
|
|
701
|
+
}
|
|
702
|
+
const response = await ynabAPI.transactions.createTransaction(params.budget_id, {
|
|
703
|
+
transaction: transactionData,
|
|
704
|
+
});
|
|
705
|
+
const transaction = ensureTransaction(response.data.transaction, 'Transaction creation failed');
|
|
706
|
+
const affectedAccountIds = new Set([transaction.account_id]);
|
|
707
|
+
const affectedMonths = new Set([toMonthKey(transaction.date)]);
|
|
708
|
+
const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
709
|
+
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
710
|
+
affectedCategoryIds,
|
|
711
|
+
accountTotalsChanged: true,
|
|
712
|
+
invalidateMonths: true,
|
|
713
|
+
});
|
|
714
|
+
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
715
|
+
const account = accountResponse.data.account;
|
|
716
|
+
return {
|
|
717
|
+
content: [
|
|
718
|
+
{
|
|
719
|
+
type: 'text',
|
|
720
|
+
text: responseFormatter.format({
|
|
721
|
+
transaction: {
|
|
722
|
+
id: transaction.id,
|
|
723
|
+
date: transaction.date,
|
|
724
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
725
|
+
memo: transaction.memo,
|
|
726
|
+
cleared: transaction.cleared,
|
|
727
|
+
approved: transaction.approved,
|
|
728
|
+
flag_color: transaction.flag_color,
|
|
729
|
+
account_id: transaction.account_id,
|
|
730
|
+
payee_id: transaction.payee_id,
|
|
731
|
+
category_id: transaction.category_id,
|
|
732
|
+
transfer_account_id: transaction.transfer_account_id,
|
|
733
|
+
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
734
|
+
matched_transaction_id: transaction.matched_transaction_id,
|
|
735
|
+
import_id: transaction.import_id,
|
|
736
|
+
deleted: transaction.deleted,
|
|
737
|
+
account_balance: account.balance,
|
|
738
|
+
account_cleared_balance: account.cleared_balance,
|
|
739
|
+
subtransactions: transaction.subtransactions?.map((subtransaction) => ({
|
|
740
|
+
id: subtransaction.id,
|
|
741
|
+
transaction_id: subtransaction.transaction_id,
|
|
742
|
+
amount: milliunitsToAmount(subtransaction.amount),
|
|
743
|
+
memo: subtransaction.memo,
|
|
744
|
+
payee_id: subtransaction.payee_id,
|
|
745
|
+
payee_name: subtransaction.payee_name,
|
|
746
|
+
category_id: subtransaction.category_id,
|
|
747
|
+
category_name: subtransaction.category_name,
|
|
748
|
+
transfer_account_id: subtransaction.transfer_account_id,
|
|
749
|
+
transfer_transaction_id: subtransaction.transfer_transaction_id,
|
|
750
|
+
deleted: subtransaction.deleted,
|
|
751
|
+
})),
|
|
752
|
+
},
|
|
753
|
+
}),
|
|
754
|
+
},
|
|
755
|
+
],
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
catch (error) {
|
|
759
|
+
return handleTransactionError(error, 'Failed to create transaction');
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function buildItemMemo(item) {
|
|
763
|
+
const quantitySuffix = item.quantity ? ` (x${item.quantity})` : '';
|
|
764
|
+
if (item.memo && item.memo.trim().length > 0) {
|
|
765
|
+
return `${item.name}${quantitySuffix} - ${item.memo}`;
|
|
766
|
+
}
|
|
767
|
+
if (quantitySuffix) {
|
|
768
|
+
return `${item.name}${quantitySuffix}`;
|
|
769
|
+
}
|
|
770
|
+
return item.name;
|
|
771
|
+
}
|
|
772
|
+
function distributeTaxProportionally(subtotalMilliunits, totalTaxMilliunits, categories) {
|
|
773
|
+
if (totalTaxMilliunits === 0) {
|
|
774
|
+
for (const category of categories)
|
|
775
|
+
category.tax_milliunits = 0;
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
if (subtotalMilliunits <= 0) {
|
|
779
|
+
throw new Error('Receipt subtotal must be greater than zero to distribute tax');
|
|
780
|
+
}
|
|
781
|
+
let allocated = 0;
|
|
782
|
+
categories.forEach((category, index) => {
|
|
783
|
+
if (index === categories.length - 1) {
|
|
784
|
+
category.tax_milliunits = totalTaxMilliunits - allocated;
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
const proportionalTax = Math.round((totalTaxMilliunits * category.subtotal_milliunits) / subtotalMilliunits);
|
|
788
|
+
category.tax_milliunits = proportionalTax;
|
|
789
|
+
allocated += proportionalTax;
|
|
790
|
+
}
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
export async function handleCreateReceiptSplitTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
794
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
795
|
+
const date = params.date ?? new Date().toISOString().slice(0, 10);
|
|
796
|
+
const categoryCalculations = params.categories.map((category) => {
|
|
797
|
+
const items = category.items.map((item) => ({
|
|
798
|
+
name: item.name,
|
|
799
|
+
amount_milliunits: amountToMilliunits(item.amount),
|
|
800
|
+
quantity: item.quantity,
|
|
801
|
+
memo: item.memo,
|
|
802
|
+
}));
|
|
803
|
+
const subtotalMilliunits = items.reduce((sum, item) => sum + item.amount_milliunits, 0);
|
|
804
|
+
return {
|
|
805
|
+
category_id: category.category_id,
|
|
806
|
+
category_name: category.category_name,
|
|
807
|
+
subtotal_milliunits: subtotalMilliunits,
|
|
808
|
+
tax_milliunits: 0,
|
|
809
|
+
items,
|
|
810
|
+
};
|
|
811
|
+
});
|
|
812
|
+
const subtotalMilliunits = categoryCalculations.reduce((sum, category) => sum + category.subtotal_milliunits, 0);
|
|
813
|
+
const declaredSubtotalMilliunits = params.receipt_subtotal !== undefined ? amountToMilliunits(params.receipt_subtotal) : undefined;
|
|
814
|
+
if (declaredSubtotalMilliunits !== undefined &&
|
|
815
|
+
Math.abs(declaredSubtotalMilliunits - subtotalMilliunits) > 1) {
|
|
816
|
+
throw new Error(`Categorized items subtotal (${milliunitsToAmount(subtotalMilliunits)}) does not match receipt subtotal (${milliunitsToAmount(declaredSubtotalMilliunits)})`);
|
|
817
|
+
}
|
|
818
|
+
const taxMilliunits = amountToMilliunits(params.receipt_tax);
|
|
819
|
+
const totalMilliunits = amountToMilliunits(params.receipt_total);
|
|
820
|
+
const computedTotal = subtotalMilliunits + taxMilliunits;
|
|
821
|
+
if (Math.abs(computedTotal - totalMilliunits) > 1) {
|
|
822
|
+
throw new Error(`Receipt total (${milliunitsToAmount(totalMilliunits)}) does not equal subtotal plus tax (${milliunitsToAmount(computedTotal)})`);
|
|
823
|
+
}
|
|
824
|
+
distributeTaxProportionally(subtotalMilliunits, taxMilliunits, categoryCalculations);
|
|
825
|
+
const subtransactions = categoryCalculations.flatMap((category) => {
|
|
826
|
+
const itemSubtransactions = category.items.map((item) => {
|
|
827
|
+
const memo = buildItemMemo({ name: item.name, quantity: item.quantity, memo: item.memo });
|
|
828
|
+
const payload = {
|
|
829
|
+
amount: -item.amount_milliunits,
|
|
830
|
+
category_id: category.category_id,
|
|
831
|
+
};
|
|
832
|
+
if (memo)
|
|
833
|
+
payload.memo = memo;
|
|
834
|
+
return payload;
|
|
835
|
+
});
|
|
836
|
+
const taxSubtransaction = category.tax_milliunits > 0
|
|
837
|
+
? [
|
|
838
|
+
{
|
|
839
|
+
amount: -category.tax_milliunits,
|
|
840
|
+
category_id: category.category_id,
|
|
841
|
+
memo: `Tax - ${category.category_name ?? 'Uncategorized'}`,
|
|
842
|
+
},
|
|
843
|
+
]
|
|
844
|
+
: [];
|
|
845
|
+
return [...itemSubtransactions, ...taxSubtransaction];
|
|
846
|
+
});
|
|
847
|
+
const receiptSummary = {
|
|
848
|
+
subtotal: milliunitsToAmount(subtotalMilliunits),
|
|
849
|
+
tax: milliunitsToAmount(taxMilliunits),
|
|
850
|
+
total: milliunitsToAmount(totalMilliunits),
|
|
851
|
+
categories: categoryCalculations.map((category) => ({
|
|
852
|
+
category_id: category.category_id,
|
|
853
|
+
category_name: category.category_name,
|
|
854
|
+
items: category.items.map((item) => ({
|
|
855
|
+
name: item.name,
|
|
856
|
+
quantity: item.quantity,
|
|
857
|
+
amount: milliunitsToAmount(item.amount_milliunits),
|
|
858
|
+
memo: item.memo,
|
|
859
|
+
})),
|
|
860
|
+
subtotal: milliunitsToAmount(category.subtotal_milliunits),
|
|
861
|
+
tax: milliunitsToAmount(category.tax_milliunits),
|
|
862
|
+
total: milliunitsToAmount(category.subtotal_milliunits + category.tax_milliunits),
|
|
863
|
+
})),
|
|
864
|
+
};
|
|
865
|
+
if (params.dry_run) {
|
|
866
|
+
return {
|
|
867
|
+
content: [
|
|
868
|
+
{
|
|
869
|
+
type: 'text',
|
|
870
|
+
text: responseFormatter.format({
|
|
871
|
+
dry_run: true,
|
|
872
|
+
action: 'create_receipt_split_transaction',
|
|
873
|
+
transaction_preview: {
|
|
874
|
+
account_id: params.account_id,
|
|
875
|
+
payee_name: params.payee_name,
|
|
876
|
+
date,
|
|
877
|
+
amount: milliunitsToAmount(totalMilliunits),
|
|
878
|
+
cleared: params.cleared ?? 'uncleared',
|
|
879
|
+
},
|
|
880
|
+
receipt_summary: receiptSummary,
|
|
881
|
+
subtransactions: subtransactions.map((subtransaction) => ({
|
|
882
|
+
amount: milliunitsToAmount(-subtransaction.amount),
|
|
883
|
+
category_id: subtransaction.category_id,
|
|
884
|
+
memo: subtransaction.memo,
|
|
885
|
+
})),
|
|
886
|
+
}),
|
|
887
|
+
},
|
|
888
|
+
],
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
const createTransactionParams = {
|
|
892
|
+
budget_id: params.budget_id,
|
|
893
|
+
account_id: params.account_id,
|
|
894
|
+
amount: -totalMilliunits,
|
|
895
|
+
date,
|
|
896
|
+
payee_name: params.payee_name,
|
|
897
|
+
memo: params.memo,
|
|
898
|
+
cleared: params.cleared ?? 'uncleared',
|
|
899
|
+
flag_color: params.flag_color,
|
|
900
|
+
subtransactions: subtransactions,
|
|
901
|
+
};
|
|
902
|
+
if (params.approved !== undefined) {
|
|
903
|
+
createTransactionParams.approved = params.approved;
|
|
904
|
+
}
|
|
905
|
+
const baseResult = await handleCreateTransaction(ynabAPI, deltaCache, knowledgeStore, createTransactionParams);
|
|
906
|
+
const firstContent = baseResult.content?.[0];
|
|
907
|
+
if (!firstContent || firstContent.type !== 'text') {
|
|
908
|
+
return baseResult;
|
|
909
|
+
}
|
|
910
|
+
try {
|
|
911
|
+
const parsed = JSON.parse(firstContent.text);
|
|
912
|
+
parsed['receipt_summary'] = receiptSummary;
|
|
913
|
+
firstContent.text = responseFormatter.format(parsed);
|
|
914
|
+
}
|
|
915
|
+
catch {
|
|
916
|
+
}
|
|
917
|
+
return baseResult;
|
|
918
|
+
}
|
|
919
|
+
export async function handleUpdateTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
920
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
921
|
+
try {
|
|
922
|
+
if (params.dry_run) {
|
|
923
|
+
return {
|
|
924
|
+
content: [
|
|
925
|
+
{
|
|
926
|
+
type: 'text',
|
|
927
|
+
text: responseFormatter.format({
|
|
928
|
+
dry_run: true,
|
|
929
|
+
action: 'update_transaction',
|
|
930
|
+
request: params,
|
|
931
|
+
}),
|
|
932
|
+
},
|
|
933
|
+
],
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
const originalTransactionResponse = await ynabAPI.transactions.getTransactionById(params.budget_id, params.transaction_id);
|
|
937
|
+
const originalTransaction = ensureTransaction(originalTransactionResponse.data.transaction, 'Original transaction not found');
|
|
938
|
+
const transactionData = {};
|
|
939
|
+
if (params.account_id !== undefined) {
|
|
940
|
+
transactionData.account_id = params.account_id;
|
|
941
|
+
}
|
|
942
|
+
if (params.amount !== undefined) {
|
|
943
|
+
transactionData.amount = params.amount;
|
|
944
|
+
}
|
|
945
|
+
if (params.date !== undefined) {
|
|
946
|
+
transactionData.date = params.date;
|
|
947
|
+
}
|
|
948
|
+
if (params.payee_name !== undefined) {
|
|
949
|
+
transactionData.payee_name = params.payee_name;
|
|
950
|
+
}
|
|
951
|
+
if (params.payee_id !== undefined) {
|
|
952
|
+
transactionData.payee_id = params.payee_id;
|
|
953
|
+
}
|
|
954
|
+
if (params.category_id !== undefined) {
|
|
955
|
+
transactionData.category_id = params.category_id;
|
|
956
|
+
}
|
|
957
|
+
if (params.memo !== undefined) {
|
|
958
|
+
transactionData.memo = params.memo;
|
|
959
|
+
}
|
|
960
|
+
if (params.cleared !== undefined) {
|
|
961
|
+
transactionData.cleared = params.cleared;
|
|
962
|
+
}
|
|
963
|
+
if (params.approved !== undefined) {
|
|
964
|
+
transactionData.approved = params.approved;
|
|
965
|
+
}
|
|
966
|
+
if (params.flag_color !== undefined) {
|
|
967
|
+
transactionData.flag_color = params.flag_color;
|
|
968
|
+
}
|
|
969
|
+
const response = await ynabAPI.transactions.updateTransaction(params.budget_id, params.transaction_id, {
|
|
970
|
+
transaction: transactionData,
|
|
971
|
+
});
|
|
972
|
+
const transaction = ensureTransaction(response.data.transaction, 'Transaction update failed');
|
|
973
|
+
const specificTransactionCacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
974
|
+
cacheManager.delete(specificTransactionCacheKey);
|
|
975
|
+
const affectedAccountIds = new Set([
|
|
976
|
+
originalTransaction.account_id,
|
|
977
|
+
transaction.account_id,
|
|
978
|
+
]);
|
|
979
|
+
if (originalTransaction.transfer_account_id) {
|
|
980
|
+
affectedAccountIds.add(originalTransaction.transfer_account_id);
|
|
981
|
+
}
|
|
982
|
+
if (transaction.transfer_account_id) {
|
|
983
|
+
affectedAccountIds.add(transaction.transfer_account_id);
|
|
984
|
+
}
|
|
985
|
+
const affectedMonths = new Set([
|
|
986
|
+
toMonthKey(originalTransaction.date),
|
|
987
|
+
toMonthKey(transaction.date),
|
|
988
|
+
]);
|
|
989
|
+
const originalCategoryIds = collectCategoryIdsFromSources(originalTransaction);
|
|
990
|
+
const updatedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
991
|
+
const affectedCategoryIds = new Set([...originalCategoryIds, ...updatedCategoryIds]);
|
|
992
|
+
const categoryChanged = !setsEqual(originalCategoryIds, updatedCategoryIds);
|
|
993
|
+
const amountChanged = transaction.amount !== originalTransaction.amount;
|
|
994
|
+
const accountChanged = transaction.account_id !== originalTransaction.account_id;
|
|
995
|
+
const clearedChanged = transaction.cleared !== originalTransaction.cleared;
|
|
996
|
+
const transferAccountChanged = transaction.transfer_account_id !== originalTransaction.transfer_account_id;
|
|
997
|
+
const transferLinkChanged = transaction.transfer_transaction_id !== originalTransaction.transfer_transaction_id;
|
|
998
|
+
const dateChanged = transaction.date !== originalTransaction.date;
|
|
999
|
+
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
1000
|
+
affectedCategoryIds,
|
|
1001
|
+
accountTotalsChanged: amountChanged ||
|
|
1002
|
+
accountChanged ||
|
|
1003
|
+
clearedChanged ||
|
|
1004
|
+
transferAccountChanged ||
|
|
1005
|
+
transferLinkChanged,
|
|
1006
|
+
invalidateMonths: amountChanged || categoryChanged || dateChanged,
|
|
1007
|
+
});
|
|
1008
|
+
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
1009
|
+
const account = accountResponse.data.account;
|
|
1010
|
+
return {
|
|
1011
|
+
content: [
|
|
1012
|
+
{
|
|
1013
|
+
type: 'text',
|
|
1014
|
+
text: responseFormatter.format({
|
|
1015
|
+
transaction: {
|
|
1016
|
+
id: transaction.id,
|
|
1017
|
+
date: transaction.date,
|
|
1018
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
1019
|
+
memo: transaction.memo,
|
|
1020
|
+
cleared: transaction.cleared,
|
|
1021
|
+
approved: transaction.approved,
|
|
1022
|
+
flag_color: transaction.flag_color,
|
|
1023
|
+
account_id: transaction.account_id,
|
|
1024
|
+
payee_id: transaction.payee_id,
|
|
1025
|
+
category_id: transaction.category_id,
|
|
1026
|
+
transfer_account_id: transaction.transfer_account_id,
|
|
1027
|
+
transfer_transaction_id: transaction.transfer_transaction_id,
|
|
1028
|
+
matched_transaction_id: transaction.matched_transaction_id,
|
|
1029
|
+
import_id: transaction.import_id,
|
|
1030
|
+
deleted: transaction.deleted,
|
|
1031
|
+
},
|
|
1032
|
+
updated_balance: account.balance,
|
|
1033
|
+
updated_cleared_balance: account.cleared_balance,
|
|
1034
|
+
}),
|
|
1035
|
+
},
|
|
1036
|
+
],
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
catch (error) {
|
|
1040
|
+
return handleTransactionError(error, 'Failed to update transaction');
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
export async function handleDeleteTransaction(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
1044
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
1045
|
+
try {
|
|
1046
|
+
if (params.dry_run) {
|
|
1047
|
+
return {
|
|
1048
|
+
content: [
|
|
1049
|
+
{
|
|
1050
|
+
type: 'text',
|
|
1051
|
+
text: responseFormatter.format({
|
|
1052
|
+
dry_run: true,
|
|
1053
|
+
action: 'delete_transaction',
|
|
1054
|
+
request: params,
|
|
1055
|
+
}),
|
|
1056
|
+
},
|
|
1057
|
+
],
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
const response = await ynabAPI.transactions.deleteTransaction(params.budget_id, params.transaction_id);
|
|
1061
|
+
const transaction = ensureTransaction(response.data.transaction, 'Transaction deletion failed');
|
|
1062
|
+
const specificTransactionCacheKey = CacheManager.generateKey('transaction', 'get', params.budget_id, params.transaction_id);
|
|
1063
|
+
cacheManager.delete(specificTransactionCacheKey);
|
|
1064
|
+
const affectedAccountIds = new Set([transaction.account_id]);
|
|
1065
|
+
if (transaction.transfer_account_id) {
|
|
1066
|
+
affectedAccountIds.add(transaction.transfer_account_id);
|
|
1067
|
+
}
|
|
1068
|
+
const affectedMonths = new Set([toMonthKey(transaction.date)]);
|
|
1069
|
+
const affectedCategoryIds = collectCategoryIdsFromSources(transaction);
|
|
1070
|
+
invalidateTransactionCaches(deltaCache, knowledgeStore, params.budget_id, response.data.server_knowledge, affectedAccountIds, affectedMonths, {
|
|
1071
|
+
affectedCategoryIds,
|
|
1072
|
+
accountTotalsChanged: true,
|
|
1073
|
+
invalidateMonths: true,
|
|
1074
|
+
});
|
|
1075
|
+
const accountResponse = await ynabAPI.accounts.getAccountById(params.budget_id, transaction.account_id);
|
|
1076
|
+
const account = accountResponse.data.account;
|
|
1077
|
+
return {
|
|
1078
|
+
content: [
|
|
1079
|
+
{
|
|
1080
|
+
type: 'text',
|
|
1081
|
+
text: responseFormatter.format({
|
|
1082
|
+
message: 'Transaction deleted successfully',
|
|
1083
|
+
transaction: {
|
|
1084
|
+
id: transaction.id,
|
|
1085
|
+
deleted: transaction.deleted,
|
|
1086
|
+
},
|
|
1087
|
+
updated_balance: account.balance,
|
|
1088
|
+
updated_cleared_balance: account.cleared_balance,
|
|
1089
|
+
}),
|
|
1090
|
+
},
|
|
1091
|
+
],
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
catch (error) {
|
|
1095
|
+
return handleTransactionError(error, 'Failed to delete transaction');
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
export async function handleCreateTransactions(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
1099
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
1100
|
+
return (await withToolErrorHandling(async () => {
|
|
1101
|
+
const validationResult = CreateTransactionsSchema.safeParse(params);
|
|
1102
|
+
if (!validationResult.success) {
|
|
1103
|
+
const issuesByIndex = new Map();
|
|
1104
|
+
const validationIssues = validationResult.error.issues ?? [];
|
|
1105
|
+
for (const issue of validationIssues) {
|
|
1106
|
+
const transactionIndex = issue.path.find((segment) => typeof segment === 'number');
|
|
1107
|
+
const message = issue.message;
|
|
1108
|
+
const issueIndex = transactionIndex !== undefined ? transactionIndex : null;
|
|
1109
|
+
const existing = issuesByIndex.get(issueIndex) ?? [];
|
|
1110
|
+
existing.push(message);
|
|
1111
|
+
issuesByIndex.set(issueIndex, existing);
|
|
1112
|
+
}
|
|
1113
|
+
const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
|
|
1114
|
+
transaction_index: index,
|
|
1115
|
+
errors,
|
|
1116
|
+
}));
|
|
1117
|
+
throw new ValidationError('Bulk transaction validation failed', JSON.stringify(details, null, 2), ['Ensure each transaction includes required fields', 'Limit batches to 100 items']);
|
|
1118
|
+
}
|
|
1119
|
+
const { budget_id, transactions, dry_run } = validationResult.data;
|
|
1120
|
+
const importIdMap = new Map();
|
|
1121
|
+
for (const [index, transaction] of transactions.entries()) {
|
|
1122
|
+
if (transaction.import_id && transaction.import_id.trim().length > 0) {
|
|
1123
|
+
const existing = importIdMap.get(transaction.import_id);
|
|
1124
|
+
if (existing) {
|
|
1125
|
+
existing.push(index);
|
|
1126
|
+
}
|
|
1127
|
+
else {
|
|
1128
|
+
importIdMap.set(transaction.import_id, [index]);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
const duplicates = Array.from(importIdMap.entries())
|
|
1133
|
+
.filter(([, indices]) => indices.length > 1)
|
|
1134
|
+
.map(([importId, indices]) => ({ import_id: importId, indices }));
|
|
1135
|
+
if (duplicates.length > 0) {
|
|
1136
|
+
const details = duplicates.map(({ import_id, indices }) => ({
|
|
1137
|
+
import_id,
|
|
1138
|
+
transaction_indices: indices,
|
|
1139
|
+
count: indices.length,
|
|
1140
|
+
}));
|
|
1141
|
+
throw new ValidationError('Duplicate import_id values detected within batch', JSON.stringify(details, null, 2), [
|
|
1142
|
+
'Ensure each transaction has a unique import_id within the batch',
|
|
1143
|
+
'Remove duplicate import_id values or omit import_id to use hash-based correlation',
|
|
1144
|
+
]);
|
|
1145
|
+
}
|
|
1146
|
+
if (dry_run) {
|
|
1147
|
+
const totalAmount = transactions.reduce((sum, transaction) => sum + transaction.amount, 0);
|
|
1148
|
+
const accountsAffected = Array.from(new Set(transactions.map((transaction) => transaction.account_id)));
|
|
1149
|
+
const categoriesAffected = Array.from(new Set(transactions
|
|
1150
|
+
.map((transaction) => transaction.category_id)
|
|
1151
|
+
.filter((id) => id !== undefined)));
|
|
1152
|
+
const sortedDates = [...transactions.map((transaction) => transaction.date)].sort();
|
|
1153
|
+
const dateRange = sortedDates.length > 0
|
|
1154
|
+
? { earliest: sortedDates[0], latest: sortedDates[sortedDates.length - 1] }
|
|
1155
|
+
: undefined;
|
|
1156
|
+
const transactionsPreview = transactions.slice(0, 10).map((transaction, index) => ({
|
|
1157
|
+
request_index: index,
|
|
1158
|
+
account_id: transaction.account_id,
|
|
1159
|
+
date: transaction.date,
|
|
1160
|
+
amount: milliunitsToAmount(transaction.amount),
|
|
1161
|
+
memo: transaction.memo,
|
|
1162
|
+
payee_id: transaction.payee_id,
|
|
1163
|
+
payee_name: transaction.payee_name,
|
|
1164
|
+
category_id: transaction.category_id,
|
|
1165
|
+
import_id: transaction.import_id,
|
|
1166
|
+
}));
|
|
1167
|
+
return {
|
|
1168
|
+
content: [
|
|
1169
|
+
{
|
|
1170
|
+
type: 'text',
|
|
1171
|
+
text: responseFormatter.format({
|
|
1172
|
+
dry_run: true,
|
|
1173
|
+
action: 'create_transactions',
|
|
1174
|
+
validation: 'passed',
|
|
1175
|
+
summary: {
|
|
1176
|
+
total_transactions: transactions.length,
|
|
1177
|
+
total_amount: milliunitsToAmount(totalAmount),
|
|
1178
|
+
accounts_affected: accountsAffected,
|
|
1179
|
+
date_range: dateRange,
|
|
1180
|
+
categories_affected: categoriesAffected,
|
|
1181
|
+
},
|
|
1182
|
+
transactions_preview: transactionsPreview,
|
|
1183
|
+
note: 'Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated.',
|
|
1184
|
+
}),
|
|
1185
|
+
},
|
|
1186
|
+
],
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
const saveTransactions = transactions.map((transaction) => {
|
|
1190
|
+
const payload = {
|
|
1191
|
+
account_id: transaction.account_id,
|
|
1192
|
+
amount: transaction.amount,
|
|
1193
|
+
date: transaction.date,
|
|
1194
|
+
};
|
|
1195
|
+
if (transaction.payee_id !== undefined)
|
|
1196
|
+
payload.payee_id = transaction.payee_id;
|
|
1197
|
+
if (transaction.payee_name !== undefined)
|
|
1198
|
+
payload.payee_name = transaction.payee_name;
|
|
1199
|
+
if (transaction.category_id !== undefined)
|
|
1200
|
+
payload.category_id = transaction.category_id;
|
|
1201
|
+
if (transaction.memo !== undefined)
|
|
1202
|
+
payload.memo = transaction.memo;
|
|
1203
|
+
if (transaction.cleared !== undefined)
|
|
1204
|
+
payload.cleared = transaction.cleared;
|
|
1205
|
+
if (transaction.approved !== undefined)
|
|
1206
|
+
payload.approved = transaction.approved;
|
|
1207
|
+
if (transaction.flag_color !== undefined)
|
|
1208
|
+
payload.flag_color = transaction.flag_color;
|
|
1209
|
+
if (transaction.import_id !== undefined)
|
|
1210
|
+
payload.import_id = transaction.import_id;
|
|
1211
|
+
return payload;
|
|
1212
|
+
});
|
|
1213
|
+
const response = await ynabAPI.transactions.createTransactions(budget_id, {
|
|
1214
|
+
transactions: saveTransactions,
|
|
1215
|
+
});
|
|
1216
|
+
const responseData = response.data;
|
|
1217
|
+
const duplicateImportIds = new Set(responseData.duplicate_import_ids ?? []);
|
|
1218
|
+
const results = correlateResults(transactions, responseData, duplicateImportIds);
|
|
1219
|
+
const summary = {
|
|
1220
|
+
total_requested: transactions.length,
|
|
1221
|
+
created: responseData.transaction_ids?.length ?? 0,
|
|
1222
|
+
duplicates: duplicateImportIds.size,
|
|
1223
|
+
failed: results.filter((result) => result.status === 'failed').length,
|
|
1224
|
+
};
|
|
1225
|
+
const baseResponse = {
|
|
1226
|
+
success: summary.failed === 0,
|
|
1227
|
+
server_knowledge: responseData.server_knowledge,
|
|
1228
|
+
summary,
|
|
1229
|
+
results,
|
|
1230
|
+
transactions: responseData.transactions ?? [],
|
|
1231
|
+
duplicate_import_ids: responseData.duplicate_import_ids ?? [],
|
|
1232
|
+
message: `Processed ${summary.total_requested} transactions: ${summary.created} created, ${summary.duplicates} duplicates, ${summary.failed} failed.`,
|
|
1233
|
+
};
|
|
1234
|
+
const accountIds = new Set(transactions.map((transaction) => transaction.account_id));
|
|
1235
|
+
const affectedMonths = new Set(transactions.map((transaction) => toMonthKey(transaction.date)));
|
|
1236
|
+
const affectedCategoryIds = new Set();
|
|
1237
|
+
for (const created of responseData.transactions ?? []) {
|
|
1238
|
+
appendCategoryIds(created, affectedCategoryIds);
|
|
1239
|
+
}
|
|
1240
|
+
invalidateTransactionCaches(deltaCache, knowledgeStore, budget_id, responseData.server_knowledge, accountIds, affectedMonths, {
|
|
1241
|
+
affectedCategoryIds,
|
|
1242
|
+
accountTotalsChanged: true,
|
|
1243
|
+
invalidateMonths: true,
|
|
1244
|
+
});
|
|
1245
|
+
const finalizedResponse = finalizeResponse(baseResponse);
|
|
1246
|
+
return {
|
|
1247
|
+
content: [
|
|
1248
|
+
{
|
|
1249
|
+
type: 'text',
|
|
1250
|
+
text: responseFormatter.format(finalizedResponse),
|
|
1251
|
+
},
|
|
1252
|
+
],
|
|
1253
|
+
};
|
|
1254
|
+
}, 'ynab:create_transactions', 'bulk transaction creation'));
|
|
1255
|
+
}
|
|
1256
|
+
async function resolveMetadata(ynabAPI, budgetId, transactions, options = {}) {
|
|
1257
|
+
const metadata = new Map();
|
|
1258
|
+
const needsResolution = [];
|
|
1259
|
+
const previewIds = new Set(options.previewTransactionIds ?? []);
|
|
1260
|
+
const previewDetails = new Map();
|
|
1261
|
+
const previewIdsNeedingFetch = new Set(previewIds);
|
|
1262
|
+
for (const transaction of transactions) {
|
|
1263
|
+
if (transaction.original_account_id && transaction.original_date) {
|
|
1264
|
+
metadata.set(transaction.id, {
|
|
1265
|
+
account_id: transaction.original_account_id,
|
|
1266
|
+
date: transaction.original_date,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
else {
|
|
1270
|
+
needsResolution.push(transaction.id);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (previewIds.size === 0 && needsResolution.length === 0) {
|
|
1274
|
+
return { metadata, unresolvedIds: [], previewDetails };
|
|
1275
|
+
}
|
|
1276
|
+
const needsResolutionSet = new Set(needsResolution);
|
|
1277
|
+
const cacheLookupIds = new Set([...needsResolution, ...previewIds]);
|
|
1278
|
+
for (const transactionId of cacheLookupIds) {
|
|
1279
|
+
const cacheKey = CacheManager.generateKey('transaction', 'get', budgetId, transactionId);
|
|
1280
|
+
const cached = cacheManager.get(cacheKey);
|
|
1281
|
+
if (!cached) {
|
|
1282
|
+
continue;
|
|
1283
|
+
}
|
|
1284
|
+
if (needsResolutionSet.has(transactionId)) {
|
|
1285
|
+
metadata.set(transactionId, {
|
|
1286
|
+
account_id: cached.account_id,
|
|
1287
|
+
date: cached.date,
|
|
1288
|
+
});
|
|
1289
|
+
needsResolutionSet.delete(transactionId);
|
|
1290
|
+
}
|
|
1291
|
+
if (previewIds.has(transactionId) && !previewDetails.has(transactionId)) {
|
|
1292
|
+
previewDetails.set(transactionId, cached);
|
|
1293
|
+
previewIdsNeedingFetch.delete(transactionId);
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
const stillNeedsResolution = Array.from(needsResolutionSet);
|
|
1297
|
+
if (stillNeedsResolution.length === 0 && previewIdsNeedingFetch.size === 0) {
|
|
1298
|
+
return { metadata, unresolvedIds: [], previewDetails };
|
|
1299
|
+
}
|
|
1300
|
+
const MAX_CONCURRENT_FETCHES = 5;
|
|
1301
|
+
const fetchPromises = [];
|
|
1302
|
+
const metadataAwaitingResolution = new Set(stillNeedsResolution);
|
|
1303
|
+
const idsNeedingApiFetch = Array.from(new Set([...stillNeedsResolution, ...previewIdsNeedingFetch]));
|
|
1304
|
+
for (let i = 0; i < idsNeedingApiFetch.length; i += MAX_CONCURRENT_FETCHES) {
|
|
1305
|
+
const batch = idsNeedingApiFetch.slice(i, i + MAX_CONCURRENT_FETCHES);
|
|
1306
|
+
const batchPromises = batch.map(async (transactionId) => {
|
|
1307
|
+
try {
|
|
1308
|
+
const response = await ynabAPI.transactions.getTransactionById(budgetId, transactionId);
|
|
1309
|
+
const transaction = response.data.transaction;
|
|
1310
|
+
if (transaction) {
|
|
1311
|
+
if (metadataAwaitingResolution.has(transactionId)) {
|
|
1312
|
+
metadata.set(transactionId, {
|
|
1313
|
+
account_id: transaction.account_id,
|
|
1314
|
+
date: transaction.date,
|
|
1315
|
+
});
|
|
1316
|
+
metadataAwaitingResolution.delete(transactionId);
|
|
1317
|
+
}
|
|
1318
|
+
if (previewIdsNeedingFetch.has(transactionId) && !previewDetails.has(transactionId)) {
|
|
1319
|
+
previewDetails.set(transactionId, transaction);
|
|
1320
|
+
previewIdsNeedingFetch.delete(transactionId);
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
catch {
|
|
1325
|
+
if (metadataAwaitingResolution.has(transactionId)) {
|
|
1326
|
+
globalRequestLogger.logError('ynab:update_transactions', 'resolve_metadata', { transaction_id: transactionId }, 'Failed to resolve transaction metadata');
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
fetchPromises.push(...batchPromises);
|
|
1331
|
+
}
|
|
1332
|
+
await Promise.all(fetchPromises);
|
|
1333
|
+
return { metadata, unresolvedIds: Array.from(metadataAwaitingResolution), previewDetails };
|
|
1334
|
+
}
|
|
1335
|
+
function finalizeBulkUpdateResponse(response) {
|
|
1336
|
+
const appendMessage = (message, addition) => {
|
|
1337
|
+
if (!message) {
|
|
1338
|
+
return addition;
|
|
1339
|
+
}
|
|
1340
|
+
if (message.includes(addition)) {
|
|
1341
|
+
return message;
|
|
1342
|
+
}
|
|
1343
|
+
return `${message} ${addition}`;
|
|
1344
|
+
};
|
|
1345
|
+
const fullSize = estimatePayloadSize(response);
|
|
1346
|
+
if (fullSize <= FULL_RESPONSE_THRESHOLD) {
|
|
1347
|
+
return { ...response, mode: 'full' };
|
|
1348
|
+
}
|
|
1349
|
+
const { transactions, ...summaryResponse } = response;
|
|
1350
|
+
const summaryPayload = {
|
|
1351
|
+
...summaryResponse,
|
|
1352
|
+
message: appendMessage(response.message, 'Response downgraded to summary to stay under size limits.'),
|
|
1353
|
+
mode: 'summary',
|
|
1354
|
+
};
|
|
1355
|
+
if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
|
|
1356
|
+
return summaryPayload;
|
|
1357
|
+
}
|
|
1358
|
+
const idsOnlyPayload = {
|
|
1359
|
+
...summaryPayload,
|
|
1360
|
+
results: summaryResponse.results.map((result) => {
|
|
1361
|
+
const simplified = {
|
|
1362
|
+
request_index: result.request_index,
|
|
1363
|
+
status: result.status,
|
|
1364
|
+
transaction_id: result.transaction_id,
|
|
1365
|
+
correlation_key: result.correlation_key,
|
|
1366
|
+
};
|
|
1367
|
+
if (result.error) {
|
|
1368
|
+
simplified.error = result.error;
|
|
1369
|
+
}
|
|
1370
|
+
if (result.error_code) {
|
|
1371
|
+
simplified.error_code = result.error_code;
|
|
1372
|
+
}
|
|
1373
|
+
return simplified;
|
|
1374
|
+
}),
|
|
1375
|
+
message: appendMessage(summaryResponse.message, 'Response downgraded to ids_only to meet 100KB limit.'),
|
|
1376
|
+
mode: 'ids_only',
|
|
1377
|
+
};
|
|
1378
|
+
if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
|
|
1379
|
+
return idsOnlyPayload;
|
|
1380
|
+
}
|
|
1381
|
+
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']);
|
|
1382
|
+
}
|
|
1383
|
+
export async function handleUpdateTransactions(ynabAPI, deltaCacheOrParams, knowledgeStoreOrParams, maybeParams) {
|
|
1384
|
+
const { deltaCache, knowledgeStore, params } = resolveDeltaWriteArgs(deltaCacheOrParams, knowledgeStoreOrParams, maybeParams);
|
|
1385
|
+
return (await withToolErrorHandling(async () => {
|
|
1386
|
+
const validationResult = UpdateTransactionsSchema.safeParse(params);
|
|
1387
|
+
if (!validationResult.success) {
|
|
1388
|
+
const issuesByIndex = new Map();
|
|
1389
|
+
const validationIssues = validationResult.error.issues ?? [];
|
|
1390
|
+
for (const issue of validationIssues) {
|
|
1391
|
+
const transactionIndex = issue.path.find((segment) => typeof segment === 'number');
|
|
1392
|
+
const message = issue.message;
|
|
1393
|
+
const issueIndex = transactionIndex !== undefined ? transactionIndex : null;
|
|
1394
|
+
const existing = issuesByIndex.get(issueIndex) ?? [];
|
|
1395
|
+
existing.push(message);
|
|
1396
|
+
issuesByIndex.set(issueIndex, existing);
|
|
1397
|
+
}
|
|
1398
|
+
const details = Array.from(issuesByIndex.entries()).map(([index, errors]) => ({
|
|
1399
|
+
transaction_index: index,
|
|
1400
|
+
errors,
|
|
1401
|
+
}));
|
|
1402
|
+
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']);
|
|
1403
|
+
}
|
|
1404
|
+
const { budget_id, transactions, dry_run } = validationResult.data;
|
|
1405
|
+
if (dry_run) {
|
|
1406
|
+
const previewTransactions = transactions.slice(0, 10);
|
|
1407
|
+
const previewTransactionIds = previewTransactions.map((transaction) => transaction.id);
|
|
1408
|
+
const { metadata, unresolvedIds, previewDetails } = await resolveMetadata(ynabAPI, budget_id, transactions, {
|
|
1409
|
+
previewTransactionIds,
|
|
1410
|
+
});
|
|
1411
|
+
const transactionsPreview = [];
|
|
1412
|
+
const unavailablePreviewIds = [];
|
|
1413
|
+
for (const transaction of previewTransactions) {
|
|
1414
|
+
const currentState = previewDetails.get(transaction.id);
|
|
1415
|
+
if (!currentState) {
|
|
1416
|
+
unavailablePreviewIds.push(transaction.id);
|
|
1417
|
+
transactionsPreview.push({
|
|
1418
|
+
transaction_id: transaction.id,
|
|
1419
|
+
before: 'unavailable',
|
|
1420
|
+
after: transaction,
|
|
1421
|
+
});
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
const before = {};
|
|
1425
|
+
const after = {};
|
|
1426
|
+
if (transaction.amount !== undefined && transaction.amount !== currentState.amount) {
|
|
1427
|
+
before['amount'] = milliunitsToAmount(currentState.amount);
|
|
1428
|
+
after['amount'] = milliunitsToAmount(transaction.amount);
|
|
1429
|
+
}
|
|
1430
|
+
if (transaction.date !== undefined && transaction.date !== currentState.date) {
|
|
1431
|
+
before['date'] = currentState.date;
|
|
1432
|
+
after['date'] = transaction.date;
|
|
1433
|
+
}
|
|
1434
|
+
if (transaction.memo !== undefined && transaction.memo !== currentState.memo) {
|
|
1435
|
+
before['memo'] = currentState.memo;
|
|
1436
|
+
after['memo'] = transaction.memo;
|
|
1437
|
+
}
|
|
1438
|
+
if (transaction.payee_id !== undefined &&
|
|
1439
|
+
transaction.payee_id !== currentState.payee_id) {
|
|
1440
|
+
before['payee_id'] = currentState.payee_id;
|
|
1441
|
+
after['payee_id'] = transaction.payee_id;
|
|
1442
|
+
}
|
|
1443
|
+
if (transaction.payee_name !== undefined &&
|
|
1444
|
+
transaction.payee_name !== currentState.payee_name) {
|
|
1445
|
+
before['payee_name'] = currentState.payee_name;
|
|
1446
|
+
after['payee_name'] = transaction.payee_name;
|
|
1447
|
+
}
|
|
1448
|
+
if (transaction.category_id !== undefined &&
|
|
1449
|
+
transaction.category_id !== currentState.category_id) {
|
|
1450
|
+
before['category_id'] = currentState.category_id;
|
|
1451
|
+
after['category_id'] = transaction.category_id;
|
|
1452
|
+
}
|
|
1453
|
+
if (transaction.cleared !== undefined && transaction.cleared !== currentState.cleared) {
|
|
1454
|
+
before['cleared'] = currentState.cleared;
|
|
1455
|
+
after['cleared'] = transaction.cleared;
|
|
1456
|
+
}
|
|
1457
|
+
if (transaction.approved !== undefined &&
|
|
1458
|
+
transaction.approved !== currentState.approved) {
|
|
1459
|
+
before['approved'] = currentState.approved;
|
|
1460
|
+
after['approved'] = transaction.approved;
|
|
1461
|
+
}
|
|
1462
|
+
if (transaction.flag_color !== undefined &&
|
|
1463
|
+
transaction.flag_color !== currentState.flag_color) {
|
|
1464
|
+
before['flag_color'] = currentState.flag_color;
|
|
1465
|
+
after['flag_color'] = transaction.flag_color;
|
|
1466
|
+
}
|
|
1467
|
+
transactionsPreview.push({
|
|
1468
|
+
transaction_id: transaction.id,
|
|
1469
|
+
before,
|
|
1470
|
+
after,
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
const warnings = [];
|
|
1474
|
+
if (unavailablePreviewIds.length > 0 || unresolvedIds.length > 0) {
|
|
1475
|
+
const totalMissing = Math.max(unavailablePreviewIds.length, unresolvedIds.length);
|
|
1476
|
+
const sampleIds = unresolvedIds.length > 0
|
|
1477
|
+
? unresolvedIds.slice(0, 10)
|
|
1478
|
+
: unavailablePreviewIds.slice(0, 10);
|
|
1479
|
+
warnings.push({
|
|
1480
|
+
code: 'metadata_unavailable',
|
|
1481
|
+
count: totalMissing,
|
|
1482
|
+
message: `Unable to fetch prior state for ${totalMissing} transactions`,
|
|
1483
|
+
sample_ids: sampleIds,
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
const accountsAffected = Array.from(new Set(Array.from(metadata.values()).map((m) => m.account_id)));
|
|
1487
|
+
const fieldsToUpdate = new Set();
|
|
1488
|
+
for (const transaction of transactions) {
|
|
1489
|
+
if (transaction.amount !== undefined)
|
|
1490
|
+
fieldsToUpdate.add('amount');
|
|
1491
|
+
if (transaction.date !== undefined)
|
|
1492
|
+
fieldsToUpdate.add('date');
|
|
1493
|
+
if (transaction.memo !== undefined)
|
|
1494
|
+
fieldsToUpdate.add('memo');
|
|
1495
|
+
if (transaction.payee_id !== undefined)
|
|
1496
|
+
fieldsToUpdate.add('payee_id');
|
|
1497
|
+
if (transaction.payee_name !== undefined)
|
|
1498
|
+
fieldsToUpdate.add('payee_name');
|
|
1499
|
+
if (transaction.category_id !== undefined)
|
|
1500
|
+
fieldsToUpdate.add('category_id');
|
|
1501
|
+
if (transaction.cleared !== undefined)
|
|
1502
|
+
fieldsToUpdate.add('cleared');
|
|
1503
|
+
if (transaction.approved !== undefined)
|
|
1504
|
+
fieldsToUpdate.add('approved');
|
|
1505
|
+
if (transaction.flag_color !== undefined)
|
|
1506
|
+
fieldsToUpdate.add('flag_color');
|
|
1507
|
+
}
|
|
1508
|
+
const response = {
|
|
1509
|
+
dry_run: true,
|
|
1510
|
+
action: 'update_transactions',
|
|
1511
|
+
validation: 'passed',
|
|
1512
|
+
summary: {
|
|
1513
|
+
total_transactions: transactions.length,
|
|
1514
|
+
accounts_affected: accountsAffected,
|
|
1515
|
+
fields_to_update: Array.from(fieldsToUpdate),
|
|
1516
|
+
},
|
|
1517
|
+
transactions_preview: transactionsPreview,
|
|
1518
|
+
note: 'Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated.',
|
|
1519
|
+
};
|
|
1520
|
+
if (warnings.length > 0) {
|
|
1521
|
+
response['warnings'] = warnings;
|
|
1522
|
+
}
|
|
1523
|
+
return {
|
|
1524
|
+
content: [
|
|
1525
|
+
{
|
|
1526
|
+
type: 'text',
|
|
1527
|
+
text: responseFormatter.format(response),
|
|
1528
|
+
},
|
|
1529
|
+
],
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
const { metadata, unresolvedIds } = await resolveMetadata(ynabAPI, budget_id, transactions);
|
|
1533
|
+
const missingMetadataRatio = unresolvedIds.length / transactions.length;
|
|
1534
|
+
const METADATA_THRESHOLD = 0.05;
|
|
1535
|
+
if (missingMetadataRatio > METADATA_THRESHOLD) {
|
|
1536
|
+
throw new ValidationError(`METADATA_INCOMPLETE: ${(missingMetadataRatio * 100).toFixed(1)}% of transactions have missing metadata (threshold: ${(METADATA_THRESHOLD * 100).toFixed(0)}%)`, JSON.stringify({
|
|
1537
|
+
unresolved_count: unresolvedIds.length,
|
|
1538
|
+
total_transactions: transactions.length,
|
|
1539
|
+
ratio: (missingMetadataRatio * 100).toFixed(1) + '%',
|
|
1540
|
+
threshold: (METADATA_THRESHOLD * 100).toFixed(0) + '%',
|
|
1541
|
+
sample_unresolved_ids: unresolvedIds.slice(0, 5),
|
|
1542
|
+
}, null, 2), [
|
|
1543
|
+
'Provide original_account_id and original_date for all transactions being updated',
|
|
1544
|
+
'Ensure transactions exist in YNAB before updating them',
|
|
1545
|
+
]);
|
|
1546
|
+
}
|
|
1547
|
+
if (missingMetadataRatio > 0.01) {
|
|
1548
|
+
globalRequestLogger.logRequest('ynab:update_transactions', 'metadata_resolution_warning', {
|
|
1549
|
+
unresolved_count: unresolvedIds.length,
|
|
1550
|
+
total_transactions: transactions.length,
|
|
1551
|
+
ratio: missingMetadataRatio.toFixed(3),
|
|
1552
|
+
sample_ids: unresolvedIds.slice(0, 5),
|
|
1553
|
+
message: 'Metadata resolution incomplete for some transactions',
|
|
1554
|
+
}, true);
|
|
1555
|
+
}
|
|
1556
|
+
const updateTransactions = transactions.map((transaction) => {
|
|
1557
|
+
const transactionData = {};
|
|
1558
|
+
if (transaction.amount !== undefined) {
|
|
1559
|
+
transactionData.amount = transaction.amount;
|
|
1560
|
+
}
|
|
1561
|
+
if (transaction.date !== undefined) {
|
|
1562
|
+
transactionData.date = transaction.date;
|
|
1563
|
+
}
|
|
1564
|
+
if (transaction.payee_name !== undefined) {
|
|
1565
|
+
transactionData.payee_name = transaction.payee_name;
|
|
1566
|
+
}
|
|
1567
|
+
if (transaction.payee_id !== undefined) {
|
|
1568
|
+
transactionData.payee_id = transaction.payee_id;
|
|
1569
|
+
}
|
|
1570
|
+
if (transaction.category_id !== undefined) {
|
|
1571
|
+
transactionData.category_id = transaction.category_id;
|
|
1572
|
+
}
|
|
1573
|
+
if (transaction.memo !== undefined) {
|
|
1574
|
+
transactionData.memo = transaction.memo;
|
|
1575
|
+
}
|
|
1576
|
+
if (transaction.cleared !== undefined) {
|
|
1577
|
+
transactionData.cleared = transaction.cleared;
|
|
1578
|
+
}
|
|
1579
|
+
if (transaction.approved !== undefined) {
|
|
1580
|
+
transactionData.approved = transaction.approved;
|
|
1581
|
+
}
|
|
1582
|
+
if (transaction.flag_color !== undefined) {
|
|
1583
|
+
transactionData.flag_color = transaction.flag_color;
|
|
1584
|
+
}
|
|
1585
|
+
return {
|
|
1586
|
+
id: transaction.id,
|
|
1587
|
+
transaction: transactionData,
|
|
1588
|
+
};
|
|
1589
|
+
});
|
|
1590
|
+
const response = await ynabAPI.transactions.updateTransactions(budget_id, {
|
|
1591
|
+
transactions: updateTransactions,
|
|
1592
|
+
});
|
|
1593
|
+
const responseData = response.data;
|
|
1594
|
+
const updatedTransactions = responseData.transactions ?? [];
|
|
1595
|
+
const results = [];
|
|
1596
|
+
const updatedIds = new Set(updatedTransactions.map((t) => t.id));
|
|
1597
|
+
for (const [index, transaction] of transactions.entries()) {
|
|
1598
|
+
if (updatedIds.has(transaction.id)) {
|
|
1599
|
+
results.push({
|
|
1600
|
+
request_index: index,
|
|
1601
|
+
status: 'updated',
|
|
1602
|
+
transaction_id: transaction.id,
|
|
1603
|
+
correlation_key: transaction.id,
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
else {
|
|
1607
|
+
results.push({
|
|
1608
|
+
request_index: index,
|
|
1609
|
+
status: 'failed',
|
|
1610
|
+
transaction_id: transaction.id,
|
|
1611
|
+
correlation_key: transaction.id,
|
|
1612
|
+
error_code: 'update_failed',
|
|
1613
|
+
error: 'Transaction was not updated by YNAB API',
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
const summary = {
|
|
1618
|
+
total_requested: transactions.length,
|
|
1619
|
+
updated: updatedTransactions.length,
|
|
1620
|
+
failed: results.filter((r) => r.status === 'failed').length,
|
|
1621
|
+
};
|
|
1622
|
+
const baseResponse = {
|
|
1623
|
+
success: summary.failed === 0,
|
|
1624
|
+
server_knowledge: responseData.server_knowledge,
|
|
1625
|
+
summary,
|
|
1626
|
+
results,
|
|
1627
|
+
transactions: updatedTransactions,
|
|
1628
|
+
message: `Processed ${summary.total_requested} transactions: ${summary.updated} updated, ${summary.failed} failed.`,
|
|
1629
|
+
};
|
|
1630
|
+
for (const transaction of transactions) {
|
|
1631
|
+
cacheManager.delete(CacheManager.generateKey('transaction', 'get', budget_id, transaction.id));
|
|
1632
|
+
}
|
|
1633
|
+
const affectedAccountIds = new Set();
|
|
1634
|
+
const affectedMonthKeys = new Set();
|
|
1635
|
+
const affectedCategoryIds = new Set();
|
|
1636
|
+
let invalidateAllCategories = false;
|
|
1637
|
+
let accountTotalsChanged = false;
|
|
1638
|
+
let monthsImpacted = false;
|
|
1639
|
+
for (const transaction of transactions) {
|
|
1640
|
+
const meta = metadata.get(transaction.id);
|
|
1641
|
+
const amountChanged = transaction.amount !== undefined;
|
|
1642
|
+
const clearedChanged = transaction.cleared !== undefined;
|
|
1643
|
+
const categoryChanged = transaction.category_id !== undefined;
|
|
1644
|
+
const dateChanged = transaction.date !== undefined;
|
|
1645
|
+
if ((amountChanged || clearedChanged) && meta) {
|
|
1646
|
+
affectedAccountIds.add(meta.account_id);
|
|
1647
|
+
}
|
|
1648
|
+
if (amountChanged) {
|
|
1649
|
+
monthsImpacted = true;
|
|
1650
|
+
accountTotalsChanged = true;
|
|
1651
|
+
invalidateAllCategories = true;
|
|
1652
|
+
if (meta) {
|
|
1653
|
+
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
if (categoryChanged) {
|
|
1657
|
+
monthsImpacted = true;
|
|
1658
|
+
invalidateAllCategories = true;
|
|
1659
|
+
if (transaction.category_id) {
|
|
1660
|
+
affectedCategoryIds.add(transaction.category_id);
|
|
1661
|
+
}
|
|
1662
|
+
if (meta) {
|
|
1663
|
+
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
if (dateChanged && meta) {
|
|
1667
|
+
monthsImpacted = true;
|
|
1668
|
+
affectedMonthKeys.add(toMonthKey(meta.date));
|
|
1669
|
+
}
|
|
1670
|
+
if (dateChanged && transaction.date) {
|
|
1671
|
+
affectedMonthKeys.add(toMonthKey(transaction.date));
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
invalidateTransactionCaches(deltaCache, knowledgeStore, budget_id, responseData.server_knowledge, affectedAccountIds, affectedMonthKeys, {
|
|
1675
|
+
affectedCategoryIds,
|
|
1676
|
+
invalidateAllCategories,
|
|
1677
|
+
accountTotalsChanged,
|
|
1678
|
+
invalidateMonths: monthsImpacted,
|
|
1679
|
+
});
|
|
1680
|
+
const finalizedResponse = finalizeBulkUpdateResponse(baseResponse);
|
|
1681
|
+
return {
|
|
1682
|
+
content: [
|
|
1683
|
+
{
|
|
1684
|
+
type: 'text',
|
|
1685
|
+
text: responseFormatter.format(finalizedResponse),
|
|
1686
|
+
},
|
|
1687
|
+
],
|
|
1688
|
+
};
|
|
1689
|
+
}, 'ynab:update_transactions', 'bulk transaction update'));
|
|
1690
|
+
}
|
|
1691
|
+
function handleTransactionError(error, defaultMessage) {
|
|
1692
|
+
let errorMessage = defaultMessage;
|
|
1693
|
+
if (error instanceof Error) {
|
|
1694
|
+
if (error.message.includes('401') || error.message.includes('Unauthorized')) {
|
|
1695
|
+
errorMessage = 'Invalid or expired YNAB access token';
|
|
1696
|
+
}
|
|
1697
|
+
else if (error.message.includes('403') || error.message.includes('Forbidden')) {
|
|
1698
|
+
errorMessage = 'Insufficient permissions to access YNAB data';
|
|
1699
|
+
}
|
|
1700
|
+
else if (error.message.includes('404') || error.message.includes('Not Found')) {
|
|
1701
|
+
errorMessage = 'Budget, account, category, or transaction not found';
|
|
1702
|
+
}
|
|
1703
|
+
else if (error.message.includes('429') || error.message.includes('Too Many Requests')) {
|
|
1704
|
+
errorMessage = 'Rate limit exceeded. Please try again later';
|
|
1705
|
+
}
|
|
1706
|
+
else if (error.message.includes('500') || error.message.includes('Internal Server Error')) {
|
|
1707
|
+
errorMessage = 'YNAB service is currently unavailable';
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
return {
|
|
1711
|
+
content: [
|
|
1712
|
+
{
|
|
1713
|
+
type: 'text',
|
|
1714
|
+
text: responseFormatter.format({
|
|
1715
|
+
error: {
|
|
1716
|
+
message: errorMessage,
|
|
1717
|
+
},
|
|
1718
|
+
}),
|
|
1719
|
+
},
|
|
1720
|
+
],
|
|
1721
|
+
};
|
|
1722
|
+
}
|