@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -1,857 +1,924 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import type * as ynab from 'ynab';
3
- import type { ReconciliationAnalysis } from '../types.js';
4
- import { executeReconciliation, type AccountSnapshot } from '../executor.js';
5
- import type { NormalizedYnabError } from '../executor.js';
6
- import { normalizeYnabError, shouldPropagateYnabError } from '../executor.js';
7
- import type { ReconcileAccountRequest } from '../index.js';
8
- import { toMoneyValue } from '../../../utils/money.js';
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type * as ynab from "ynab";
3
+ import { toMoneyValue } from "../../../utils/money.js";
4
+ import { type AccountSnapshot, executeReconciliation } from "../executor.js";
5
+ import type { NormalizedYnabError } from "../executor.js";
6
+ import { normalizeYnabError, shouldPropagateYnabError } from "../executor.js";
7
+ import type { ReconcileAccountRequest } from "../index.js";
8
+ import type { ReconciliationAnalysis } from "../types.js";
9
9
 
10
10
  const buildAnalysis = (): ReconciliationAnalysis => ({
11
- success: true,
12
- phase: 'analysis',
13
- summary: {
14
- statement_date_range: '2025-10-01 to 2025-10-31',
15
- bank_transactions_count: 3,
16
- ynab_transactions_count: 3,
17
- auto_matched: 1,
18
- suggested_matches: 0,
19
- unmatched_bank: 1,
20
- unmatched_ynab: 1,
21
- current_cleared_balance: toMoneyValue(-899020, 'USD'),
22
- target_statement_balance: toMoneyValue(-921240, 'USD'),
23
- discrepancy: toMoneyValue(22220, 'USD'),
24
- discrepancy_explanation: 'Need to add 1 missing transaction',
25
- },
26
- auto_matches: [
27
- {
28
- bankTransaction: {
29
- id: 'bank-1',
30
- date: '2025-10-15',
31
- amount: -45230,
32
- payee: 'Shell Gas',
33
- sourceRow: 2,
34
- raw: { date: '2025-10-15', amount: '-45.23', description: 'Shell Gas' },
35
- },
36
- ynabTransaction: {
37
- id: 'ynab-1',
38
- date: '2025-10-14',
39
- amount: -45230,
40
- payee: 'Shell',
41
- categoryName: 'Auto',
42
- cleared: 'uncleared',
43
- approved: true,
44
- memo: null,
45
- },
46
- candidates: [],
47
- confidence: 'high',
48
- confidenceScore: 97,
49
- matchReason: 'exact_amount_and_date',
50
- },
51
- ],
52
- suggested_matches: [],
53
- unmatched_bank: [
54
- {
55
- id: 'bank-2',
56
- date: '2025-10-25',
57
- amount: 22220,
58
- payee: 'EvoCarShare',
59
- sourceRow: 7,
60
- raw: { date: '2025-10-25', amount: '22.22', description: 'EvoCarShare' },
61
- },
62
- ],
63
- unmatched_ynab: [
64
- {
65
- id: 'ynab-2',
66
- date: '2025-10-10',
67
- amount: -15000,
68
- payee: 'Coffee Shop',
69
- categoryName: 'Dining',
70
- cleared: 'cleared',
71
- approved: true,
72
- memo: null,
73
- },
74
- ],
75
- balance_info: {
76
- current_cleared: toMoneyValue(-899020, 'USD'),
77
- current_uncleared: toMoneyValue(-45230, 'USD'),
78
- current_total: toMoneyValue(-944250, 'USD'),
79
- target_statement: toMoneyValue(-921240, 'USD'),
80
- discrepancy: toMoneyValue(22220, 'USD'),
81
- on_track: false,
82
- },
83
- next_steps: ['Review auto matches'],
84
- insights: [],
11
+ success: true,
12
+ phase: "analysis",
13
+ summary: {
14
+ statement_date_range: "2025-10-01 to 2025-10-31",
15
+ bank_transactions_count: 3,
16
+ ynab_transactions_count: 3,
17
+ auto_matched: 1,
18
+ suggested_matches: 0,
19
+ unmatched_bank: 1,
20
+ unmatched_ynab: 1,
21
+ current_cleared_balance: toMoneyValue(-899020, "USD"),
22
+ target_statement_balance: toMoneyValue(-921240, "USD"),
23
+ discrepancy: toMoneyValue(22220, "USD"),
24
+ discrepancy_explanation: "Need to add 1 missing transaction",
25
+ },
26
+ auto_matches: [
27
+ {
28
+ bankTransaction: {
29
+ id: "bank-1",
30
+ date: "2025-10-15",
31
+ amount: -45230,
32
+ payee: "Shell Gas",
33
+ sourceRow: 2,
34
+ raw: { date: "2025-10-15", amount: "-45.23", description: "Shell Gas" },
35
+ },
36
+ ynabTransaction: {
37
+ id: "ynab-1",
38
+ date: "2025-10-14",
39
+ amount: -45230,
40
+ payee: "Shell",
41
+ categoryName: "Auto",
42
+ cleared: "uncleared",
43
+ approved: true,
44
+ memo: null,
45
+ },
46
+ candidates: [],
47
+ confidence: "high",
48
+ confidenceScore: 97,
49
+ matchReason: "exact_amount_and_date",
50
+ },
51
+ ],
52
+ suggested_matches: [],
53
+ unmatched_bank: [
54
+ {
55
+ id: "bank-2",
56
+ date: "2025-10-25",
57
+ amount: 22220,
58
+ payee: "EvoCarShare",
59
+ sourceRow: 7,
60
+ raw: { date: "2025-10-25", amount: "22.22", description: "EvoCarShare" },
61
+ },
62
+ ],
63
+ unmatched_ynab: [
64
+ {
65
+ id: "ynab-2",
66
+ date: "2025-10-10",
67
+ amount: -15000,
68
+ payee: "Coffee Shop",
69
+ categoryName: "Dining",
70
+ cleared: "cleared",
71
+ approved: true,
72
+ memo: null,
73
+ },
74
+ ],
75
+ balance_info: {
76
+ current_cleared: toMoneyValue(-899020, "USD"),
77
+ current_uncleared: toMoneyValue(-45230, "USD"),
78
+ current_total: toMoneyValue(-944250, "USD"),
79
+ target_statement: toMoneyValue(-921240, "USD"),
80
+ discrepancy: toMoneyValue(22220, "USD"),
81
+ on_track: false,
82
+ },
83
+ next_steps: ["Review auto matches"],
84
+ insights: [],
85
85
  });
86
86
 
87
87
  const defaultAccountSnapshot: AccountSnapshot = {
88
- balance: 0,
89
- cleared_balance: 0,
90
- uncleared_balance: 0,
88
+ balance: 0,
89
+ cleared_balance: 0,
90
+ uncleared_balance: 0,
91
91
  };
92
92
 
93
93
  const buildBulkAnalysis = (
94
- count: number,
95
- amount = 10000,
96
- statementMultiplier = count,
94
+ count: number,
95
+ amount = 10000,
96
+ statementMultiplier = count,
97
97
  ): ReconciliationAnalysis => {
98
- const analysis = buildAnalysis();
99
- const baseDate = Date.parse('2025-10-01');
100
- analysis.auto_matches = [];
101
- analysis.summary.auto_matched = 0;
102
- analysis.suggested_matches = [];
103
- analysis.summary.suggested_matches = 0;
104
- analysis.unmatched_ynab = [];
105
- analysis.summary.unmatched_ynab = 0;
106
- analysis.summary.ynab_transactions_count = 0;
107
- analysis.summary.bank_transactions_count = count;
108
- analysis.unmatched_bank = Array.from({ length: count }, (_, index) => {
109
- const date = new Date(baseDate + index * 24 * 60 * 60 * 1000);
110
- return {
111
- id: `bank-bulk-${index}`,
112
- date: date.toISOString().slice(0, 10),
113
- amount,
114
- payee: `Bulk Payee ${index}`,
115
- memo: `Bulk memo ${index}`,
116
- sourceRow: index + 1,
117
- raw: {
118
- date: date.toISOString().slice(0, 10),
119
- amount: String(amount / 1000),
120
- description: `Bulk Payee ${index}`,
121
- },
122
- };
123
- });
124
- analysis.summary.unmatched_bank = analysis.unmatched_bank.length;
125
- const statementBalance = amount * statementMultiplier;
126
- analysis.summary.current_cleared_balance = toMoneyValue(0, 'USD');
127
- analysis.summary.target_statement_balance = toMoneyValue(statementBalance, 'USD');
128
- analysis.summary.discrepancy = toMoneyValue(statementBalance, 'USD');
129
- analysis.summary.discrepancy_explanation = 'Bulk test discrepancy';
130
- analysis.balance_info = {
131
- current_cleared: toMoneyValue(0, 'USD'),
132
- current_uncleared: toMoneyValue(0, 'USD'),
133
- current_total: toMoneyValue(0, 'USD'),
134
- target_statement: toMoneyValue(statementBalance, 'USD'),
135
- discrepancy: toMoneyValue(statementBalance, 'USD'),
136
- on_track: false,
137
- };
138
- analysis.next_steps = [];
139
- analysis.insights = [];
140
- return analysis;
98
+ const analysis = buildAnalysis();
99
+ const baseDate = Date.parse("2025-10-01");
100
+ analysis.auto_matches = [];
101
+ analysis.summary.auto_matched = 0;
102
+ analysis.suggested_matches = [];
103
+ analysis.summary.suggested_matches = 0;
104
+ analysis.unmatched_ynab = [];
105
+ analysis.summary.unmatched_ynab = 0;
106
+ analysis.summary.ynab_transactions_count = 0;
107
+ analysis.summary.bank_transactions_count = count;
108
+ analysis.unmatched_bank = Array.from({ length: count }, (_, index) => {
109
+ const date = new Date(baseDate + index * 24 * 60 * 60 * 1000);
110
+ return {
111
+ id: `bank-bulk-${index}`,
112
+ date: date.toISOString().slice(0, 10),
113
+ amount,
114
+ payee: `Bulk Payee ${index}`,
115
+ memo: `Bulk memo ${index}`,
116
+ sourceRow: index + 1,
117
+ raw: {
118
+ date: date.toISOString().slice(0, 10),
119
+ amount: String(amount / 1000),
120
+ description: `Bulk Payee ${index}`,
121
+ },
122
+ };
123
+ });
124
+ analysis.summary.unmatched_bank = analysis.unmatched_bank.length;
125
+ const statementBalance = amount * statementMultiplier;
126
+ analysis.summary.current_cleared_balance = toMoneyValue(0, "USD");
127
+ analysis.summary.target_statement_balance = toMoneyValue(
128
+ statementBalance,
129
+ "USD",
130
+ );
131
+ analysis.summary.discrepancy = toMoneyValue(statementBalance, "USD");
132
+ analysis.summary.discrepancy_explanation = "Bulk test discrepancy";
133
+ analysis.balance_info = {
134
+ current_cleared: toMoneyValue(0, "USD"),
135
+ current_uncleared: toMoneyValue(0, "USD"),
136
+ current_total: toMoneyValue(0, "USD"),
137
+ target_statement: toMoneyValue(statementBalance, "USD"),
138
+ discrepancy: toMoneyValue(statementBalance, "USD"),
139
+ on_track: false,
140
+ };
141
+ analysis.next_steps = [];
142
+ analysis.insights = [];
143
+ return analysis;
141
144
  };
142
145
 
143
146
  const buildBulkParams = (
144
- statementBalance: MoneyValue, // Expects MoneyValue now from buildBulkAnalysis
145
- overrides: Partial<ReconcileAccountRequest> = {},
147
+ statementBalance: MoneyValue, // Expects MoneyValue now from buildBulkAnalysis
148
+ overrides: Partial<ReconcileAccountRequest> = {},
146
149
  ): ReconcileAccountRequest => ({
147
- budget_id: 'budget-bulk',
148
- account_id: 'account-bulk',
149
- csv_data: 'Date,Payee,Amount',
150
- statement_balance: statementBalance.value, // Use decimal value for params
151
- statement_date: '2025-10-31',
152
- date_tolerance_days: 1,
153
- amount_tolerance_cents: 1,
154
- auto_match_threshold: 90,
155
- suggestion_threshold: 60,
156
- auto_create_transactions: true,
157
- auto_update_cleared_status: false,
158
- auto_unclear_missing: false,
159
- auto_adjust_dates: false,
160
- dry_run: false,
161
- require_exact_match: true,
162
- confidence_threshold: 0.8,
163
- max_resolution_attempts: 3,
164
- ...overrides,
150
+ budget_id: "budget-bulk",
151
+ account_id: "account-bulk",
152
+ csv_data: "Date,Payee,Amount",
153
+ statement_balance: statementBalance.value, // Use decimal value for params
154
+ statement_date: "2025-10-31",
155
+ date_tolerance_days: 1,
156
+ amount_tolerance_cents: 1,
157
+ auto_match_threshold: 90,
158
+ suggestion_threshold: 60,
159
+ auto_create_transactions: true,
160
+ auto_update_cleared_status: false,
161
+ auto_unclear_missing: false,
162
+ auto_adjust_dates: false,
163
+ dry_run: false,
164
+ require_exact_match: true,
165
+ confidence_threshold: 0.8,
166
+ max_resolution_attempts: 3,
167
+ ...overrides,
165
168
  });
166
169
 
167
- const createMockYnabAPI = (snapshot: AccountSnapshot = defaultAccountSnapshot) => {
168
- const createTransactions = vi.fn();
169
- const createTransaction = vi.fn();
170
- const updateTransactions = vi.fn().mockResolvedValue({ data: { transactions: [] } });
171
- const getTransactionsByAccount = vi.fn().mockResolvedValue({ data: { transactions: [] } });
172
- const getAccountById = vi.fn().mockResolvedValue({
173
- data: {
174
- account: {
175
- id: 'account-bulk',
176
- balance: snapshot.balance,
177
- cleared_balance: snapshot.cleared_balance,
178
- uncleared_balance: snapshot.uncleared_balance,
179
- },
180
- },
181
- });
182
-
183
- const api = {
184
- transactions: {
185
- createTransactions,
186
- createTransaction,
187
- updateTransactions,
188
- getTransactionsByAccount,
189
- },
190
- accounts: {
191
- getAccountById,
192
- },
193
- } as unknown as ynab.API;
194
-
195
- return {
196
- api,
197
- mocks: {
198
- createTransactions,
199
- createTransaction,
200
- updateTransactions,
201
- getTransactionsByAccount,
202
- getAccountById,
203
- },
204
- };
170
+ const createMockYnabAPI = (
171
+ snapshot: AccountSnapshot = defaultAccountSnapshot,
172
+ ) => {
173
+ const createTransactions = vi.fn();
174
+ const createTransaction = vi.fn();
175
+ const updateTransactions = vi
176
+ .fn()
177
+ .mockResolvedValue({ data: { transactions: [] } });
178
+ const getTransactionsByAccount = vi
179
+ .fn()
180
+ .mockResolvedValue({ data: { transactions: [] } });
181
+ const getAccountById = vi.fn().mockResolvedValue({
182
+ data: {
183
+ account: {
184
+ id: "account-bulk",
185
+ balance: snapshot.balance,
186
+ cleared_balance: snapshot.cleared_balance,
187
+ uncleared_balance: snapshot.uncleared_balance,
188
+ },
189
+ },
190
+ });
191
+
192
+ const api = {
193
+ transactions: {
194
+ createTransactions,
195
+ createTransaction,
196
+ updateTransactions,
197
+ getTransactionsByAccount,
198
+ },
199
+ accounts: {
200
+ getAccountById,
201
+ },
202
+ } as unknown as ynab.API;
203
+
204
+ return {
205
+ api,
206
+ mocks: {
207
+ createTransactions,
208
+ createTransaction,
209
+ updateTransactions,
210
+ getTransactionsByAccount,
211
+ getAccountById,
212
+ },
213
+ };
205
214
  };
206
215
 
207
- describe('error normalization helpers', () => {
208
- it('normalizes YNAB SDK error objects with status and detail', () => {
209
- const err = normalizeYnabError({ error: { id: '429', detail: 'Too many requests' } });
210
- expect(err.status).toBe(429);
211
- expect(err.message).toContain('Too many requests');
212
- });
213
-
214
- it('retains status from Error-like objects and propagates HTTP code decisions', () => {
215
- const err = normalizeYnabError(Object.assign(new Error('Nope'), { status: 503 }));
216
- expect(err.status).toBe(503);
217
- expect(shouldPropagateYnabError(err as NormalizedYnabError)).toBe(true);
218
- });
216
+ describe("error normalization helpers", () => {
217
+ it("normalizes YNAB SDK error objects with status and detail", () => {
218
+ const err = normalizeYnabError({
219
+ error: { id: "429", detail: "Too many requests" },
220
+ });
221
+ expect(err.status).toBe(429);
222
+ expect(err.message).toContain("Too many requests");
223
+ });
224
+
225
+ it("retains status from Error-like objects and propagates HTTP code decisions", () => {
226
+ const err = normalizeYnabError(
227
+ Object.assign(new Error("Nope"), { status: 503 }),
228
+ );
229
+ expect(err.status).toBe(503);
230
+ expect(shouldPropagateYnabError(err as NormalizedYnabError)).toBe(true);
231
+ });
219
232
  });
220
233
 
221
- describe('executeReconciliation (dry run)', () => {
222
- it('produces action plan without calling YNAB APIs when dry_run=true', async () => {
223
- const analysis = buildAnalysis();
224
- const params = {
225
- budget_id: 'budget-1',
226
- account_id: 'account-1',
227
- csv_data: 'Date,Description,Amount',
228
- statement_balance: -921.24,
229
- date_tolerance_days: 2,
230
- amount_tolerance_cents: 1,
231
- auto_match_threshold: 90,
232
- suggestion_threshold: 60,
233
- auto_create_transactions: true,
234
- auto_update_cleared_status: true,
235
- auto_unclear_missing: true,
236
- auto_adjust_dates: true,
237
- dry_run: true,
238
- require_exact_match: true,
239
- confidence_threshold: 0.8,
240
- max_resolution_attempts: 5,
241
- } satisfies any;
242
-
243
- const initialAccount: AccountSnapshot = {
244
- balance: -899020,
245
- cleared_balance: -899020,
246
- uncleared_balance: 0,
247
- };
248
-
249
- const result = await executeReconciliation({
250
- ynabAPI: {} as ynab.API,
251
- analysis,
252
- params,
253
- budgetId: 'budget-1',
254
- accountId: 'account-1',
255
- initialAccount,
256
- currencyCode: 'USD',
257
- });
258
-
259
- expect(result.summary.transactions_created).toBe(1);
260
- expect(result.summary.transactions_updated).toBe(2);
261
- expect(result.summary.dates_adjusted).toBe(1);
262
- // 3 original actions + 2 diagnostic actions (diagnostic_step3_entry + diagnostic_unmatched_ynab)
263
- expect(result.actions_taken).toHaveLength(5);
264
- expect(result.recommendations).toContain(
265
- 'Dry run only — re-run with dry_run=false to apply these changes',
266
- );
267
- });
234
+ describe("executeReconciliation (dry run)", () => {
235
+ it("produces action plan without calling YNAB APIs when dry_run=true", async () => {
236
+ const analysis = buildAnalysis();
237
+ const params = {
238
+ budget_id: "budget-1",
239
+ account_id: "account-1",
240
+ csv_data: "Date,Description,Amount",
241
+ statement_balance: -921.24,
242
+ date_tolerance_days: 2,
243
+ amount_tolerance_cents: 1,
244
+ auto_match_threshold: 90,
245
+ suggestion_threshold: 60,
246
+ auto_create_transactions: true,
247
+ auto_update_cleared_status: true,
248
+ auto_unclear_missing: true,
249
+ auto_adjust_dates: true,
250
+ dry_run: true,
251
+ require_exact_match: true,
252
+ confidence_threshold: 0.8,
253
+ max_resolution_attempts: 5,
254
+ } satisfies any;
255
+
256
+ const initialAccount: AccountSnapshot = {
257
+ balance: -899020,
258
+ cleared_balance: -899020,
259
+ uncleared_balance: 0,
260
+ };
261
+
262
+ const result = await executeReconciliation({
263
+ ynabAPI: {} as ynab.API,
264
+ analysis,
265
+ params,
266
+ budgetId: "budget-1",
267
+ accountId: "account-1",
268
+ initialAccount,
269
+ currencyCode: "USD",
270
+ });
271
+
272
+ expect(result.summary.transactions_created).toBe(1);
273
+ expect(result.summary.transactions_updated).toBe(2);
274
+ expect(result.summary.dates_adjusted).toBe(1);
275
+ // 3 original actions + 2 diagnostic actions (diagnostic_step3_entry + diagnostic_unmatched_ynab)
276
+ expect(result.actions_taken).toHaveLength(5);
277
+ expect(result.recommendations).toContain(
278
+ "Dry run only — re-run with dry_run=false to apply these changes",
279
+ );
280
+ });
268
281
  });
269
282
 
270
- describe('executeReconciliation (apply mode)', () => {
271
- it('creates, updates, and adjusts when dry_run=false', async () => {
272
- const analysis = buildAnalysis();
273
- const params = {
274
- budget_id: 'budget-apply',
275
- account_id: 'account-apply',
276
- csv_data: 'Date,Description,Amount',
277
- statement_balance: -921.24,
278
- statement_date: '2025-10-31',
279
- date_tolerance_days: 2,
280
- amount_tolerance_cents: 1,
281
- auto_match_threshold: 90,
282
- suggestion_threshold: 60,
283
- auto_create_transactions: true,
284
- auto_update_cleared_status: true,
285
- auto_unclear_missing: true,
286
- auto_adjust_dates: true,
287
- dry_run: false,
288
- require_exact_match: true,
289
- confidence_threshold: 0.8,
290
- max_resolution_attempts: 5,
291
- } satisfies any;
292
-
293
- const initialAccount: AccountSnapshot = {
294
- balance: -899020,
295
- cleared_balance: -899020,
296
- uncleared_balance: 0,
297
- };
298
-
299
- const mockCreate = vi.fn().mockResolvedValue({ data: { transaction: { id: 'created-1' } } });
300
- const mockUpdate = vi.fn().mockResolvedValue({ data: { transaction: { id: 'updated-1' } } });
301
- const mockBatchUpdate = vi.fn().mockResolvedValue({
302
- data: { transactions: [{ id: 'updated-1' }, { id: 'updated-2' }] },
303
- });
304
- const mockGetAccount = vi.fn().mockResolvedValue({
305
- data: { account: { balance: -921240, cleared_balance: -921240, uncleared_balance: 0 } },
306
- });
307
-
308
- const mockTransactionsApi = {
309
- createTransaction: mockCreate,
310
- updateTransaction: mockUpdate,
311
- updateTransactions: mockBatchUpdate,
312
- getTransactionsByAccount: vi.fn().mockResolvedValue({ data: { transactions: [] } }),
313
- } satisfies Partial<ynab.TransactionsApi>;
314
-
315
- const mockAccountsApi = {
316
- getAccountById: mockGetAccount,
317
- } satisfies Partial<ynab.AccountsApi>;
318
-
319
- const ynabAPI = {
320
- transactions: mockTransactionsApi,
321
- accounts: mockAccountsApi,
322
- } as unknown as ynab.API;
323
-
324
- const result = await executeReconciliation({
325
- ynabAPI,
326
- analysis,
327
- params,
328
- budgetId: 'budget-apply',
329
- accountId: 'account-apply',
330
- initialAccount,
331
- currencyCode: 'USD',
332
- });
333
-
334
- expect(mockCreate).toHaveBeenCalledTimes(1);
335
- expect(mockBatchUpdate).toHaveBeenCalled();
336
- expect(mockGetAccount).toHaveBeenCalled();
337
- expect(result.summary.transactions_created).toBe(1);
338
- expect(result.summary.transactions_updated).toBeGreaterThanOrEqual(2);
339
- expect(result.summary.dates_adjusted).toBe(1);
340
- expect(result.actions_taken.length).toBeGreaterThanOrEqual(3);
341
- expect(result.summary.dry_run).toBe(false);
342
- });
283
+ describe("executeReconciliation (apply mode)", () => {
284
+ it("creates, updates, and adjusts when dry_run=false", async () => {
285
+ const analysis = buildAnalysis();
286
+ const params = {
287
+ budget_id: "budget-apply",
288
+ account_id: "account-apply",
289
+ csv_data: "Date,Description,Amount",
290
+ statement_balance: -921.24,
291
+ statement_date: "2025-10-31",
292
+ date_tolerance_days: 2,
293
+ amount_tolerance_cents: 1,
294
+ auto_match_threshold: 90,
295
+ suggestion_threshold: 60,
296
+ auto_create_transactions: true,
297
+ auto_update_cleared_status: true,
298
+ auto_unclear_missing: true,
299
+ auto_adjust_dates: true,
300
+ dry_run: false,
301
+ require_exact_match: true,
302
+ confidence_threshold: 0.8,
303
+ max_resolution_attempts: 5,
304
+ } satisfies any;
305
+
306
+ const initialAccount: AccountSnapshot = {
307
+ balance: -899020,
308
+ cleared_balance: -899020,
309
+ uncleared_balance: 0,
310
+ };
311
+
312
+ const mockCreate = vi
313
+ .fn()
314
+ .mockResolvedValue({ data: { transaction: { id: "created-1" } } });
315
+ const mockUpdate = vi
316
+ .fn()
317
+ .mockResolvedValue({ data: { transaction: { id: "updated-1" } } });
318
+ const mockBatchUpdate = vi.fn().mockResolvedValue({
319
+ data: { transactions: [{ id: "updated-1" }, { id: "updated-2" }] },
320
+ });
321
+ const mockGetAccount = vi.fn().mockResolvedValue({
322
+ data: {
323
+ account: {
324
+ balance: -921240,
325
+ cleared_balance: -921240,
326
+ uncleared_balance: 0,
327
+ },
328
+ },
329
+ });
330
+
331
+ const mockTransactionsApi = {
332
+ createTransaction: mockCreate,
333
+ updateTransaction: mockUpdate,
334
+ updateTransactions: mockBatchUpdate,
335
+ getTransactionsByAccount: vi
336
+ .fn()
337
+ .mockResolvedValue({ data: { transactions: [] } }),
338
+ } satisfies Partial<ynab.TransactionsApi>;
339
+
340
+ const mockAccountsApi = {
341
+ getAccountById: mockGetAccount,
342
+ } satisfies Partial<ynab.AccountsApi>;
343
+
344
+ const ynabAPI = {
345
+ transactions: mockTransactionsApi,
346
+ accounts: mockAccountsApi,
347
+ } as unknown as ynab.API;
348
+
349
+ const result = await executeReconciliation({
350
+ ynabAPI,
351
+ analysis,
352
+ params,
353
+ budgetId: "budget-apply",
354
+ accountId: "account-apply",
355
+ initialAccount,
356
+ currencyCode: "USD",
357
+ });
358
+
359
+ expect(mockCreate).toHaveBeenCalledTimes(1);
360
+ expect(mockBatchUpdate).toHaveBeenCalled();
361
+ expect(mockGetAccount).toHaveBeenCalled();
362
+ expect(result.summary.transactions_created).toBe(1);
363
+ expect(result.summary.transactions_updated).toBeGreaterThanOrEqual(2);
364
+ expect(result.summary.dates_adjusted).toBe(1);
365
+ expect(result.actions_taken.length).toBeGreaterThanOrEqual(3);
366
+ expect(result.summary.dry_run).toBe(false);
367
+ });
343
368
  });
344
369
 
345
- describe('executeReconciliation (ordered halting)', () => {
346
- it('processes newest auto matches first and stops once balances align', async () => {
347
- const analysis: ReconciliationAnalysis = {
348
- success: true,
349
- phase: 'analysis',
350
- summary: {
351
- statement_date_range: '2025-09-01 to 2025-10-31',
352
- bank_transactions_count: 2,
353
- ynab_transactions_count: 2,
354
- auto_matched: 2,
355
- suggested_matches: 0,
356
- unmatched_bank: 0,
357
- unmatched_ynab: 0,
358
- current_cleared_balance: toMoneyValue(90000, 'USD'),
359
- target_statement_balance: toMoneyValue(100000, 'USD'),
360
- discrepancy: toMoneyValue(-10000, 'USD'),
361
- discrepancy_explanation: 'Awaiting cleared transactions',
362
- },
363
- auto_matches: [
364
- {
365
- bankTransaction: {
366
- id: 'bank-older',
367
- date: '2025-09-15',
368
- amount: 5000,
369
- payee: 'Older',
370
- sourceRow: 2,
371
- raw: { date: '2025-09-15', amount: '5.00', description: 'Older' },
372
- },
373
- ynabTransaction: {
374
- id: 'ynab-older',
375
- date: '2025-09-14',
376
- amount: 5000,
377
- payee: 'Older',
378
- categoryName: null,
379
- cleared: 'uncleared',
380
- approved: true,
381
- memo: null,
382
- },
383
- candidates: [],
384
- confidence: 'high',
385
- confidenceScore: 95,
386
- matchReason: 'Exact match',
387
- },
388
- {
389
- bankTransaction: {
390
- id: 'bank-newer',
391
- date: '2025-10-25',
392
- amount: 10000,
393
- payee: 'Newer',
394
- sourceRow: 1,
395
- raw: { date: '2025-10-25', amount: '10.00', description: 'Newer' },
396
- },
397
- ynabTransaction: {
398
- id: 'ynab-newer',
399
- date: '2025-10-24',
400
- amount: 10000,
401
- payee: 'Newer',
402
- categoryName: null,
403
- cleared: 'uncleared',
404
- approved: true,
405
- memo: null,
406
- },
407
- candidates: [],
408
- confidence: 'high',
409
- confidenceScore: 99,
410
- matchReason: 'Exact match',
411
- },
412
- ],
413
- suggested_matches: [],
414
- unmatched_bank: [],
415
- unmatched_ynab: [],
416
- balance_info: {
417
- current_cleared: toMoneyValue(90000, 'USD'),
418
- current_uncleared: toMoneyValue(0, 'USD'),
419
- current_total: toMoneyValue(90000, 'USD'),
420
- target_statement: toMoneyValue(100000, 'USD'),
421
- discrepancy: toMoneyValue(-10000, 'USD'),
422
- on_track: false,
423
- },
424
- next_steps: [],
425
- insights: [],
426
- };
427
-
428
- const params = {
429
- budget_id: 'budget-ordered',
430
- account_id: 'account-ordered',
431
- csv_data: 'Date,Description,Amount',
432
- statement_balance: 100,
433
- date_tolerance_days: 2,
434
- amount_tolerance_cents: 1,
435
- auto_match_threshold: 90,
436
- suggestion_threshold: 60,
437
- auto_create_transactions: false,
438
- auto_update_cleared_status: true,
439
- auto_unclear_missing: false,
440
- auto_adjust_dates: false,
441
- dry_run: true,
442
- require_exact_match: true,
443
- confidence_threshold: 0.8,
444
- max_resolution_attempts: 5,
445
- } satisfies any;
446
-
447
- const initialAccount: AccountSnapshot = {
448
- balance: 90000,
449
- cleared_balance: 90000,
450
- uncleared_balance: 0,
451
- };
452
-
453
- const result = await executeReconciliation({
454
- ynabAPI: {} as ynab.API,
455
- analysis,
456
- params,
457
- budgetId: 'budget-ordered',
458
- accountId: 'account-ordered',
459
- initialAccount,
460
- currencyCode: 'USD',
461
- });
462
-
463
- const updateActions = result.actions_taken.filter(
464
- (action) => action.type === 'update_transaction',
465
- );
466
- expect(updateActions).toHaveLength(1);
467
- expect((updateActions[0]?.transaction as any)?.transaction_id).toBe('ynab-newer');
468
- expect(result.actions_taken.some((action) => action.type === 'balance_checkpoint')).toBe(true);
469
- expect(result.summary.transactions_updated).toBe(1);
470
- expect(result.summary.dates_adjusted).toBe(0);
471
- });
370
+ describe("executeReconciliation (ordered halting)", () => {
371
+ it("processes newest auto matches first and stops once balances align", async () => {
372
+ const analysis: ReconciliationAnalysis = {
373
+ success: true,
374
+ phase: "analysis",
375
+ summary: {
376
+ statement_date_range: "2025-09-01 to 2025-10-31",
377
+ bank_transactions_count: 2,
378
+ ynab_transactions_count: 2,
379
+ auto_matched: 2,
380
+ suggested_matches: 0,
381
+ unmatched_bank: 0,
382
+ unmatched_ynab: 0,
383
+ current_cleared_balance: toMoneyValue(90000, "USD"),
384
+ target_statement_balance: toMoneyValue(100000, "USD"),
385
+ discrepancy: toMoneyValue(-10000, "USD"),
386
+ discrepancy_explanation: "Awaiting cleared transactions",
387
+ },
388
+ auto_matches: [
389
+ {
390
+ bankTransaction: {
391
+ id: "bank-older",
392
+ date: "2025-09-15",
393
+ amount: 5000,
394
+ payee: "Older",
395
+ sourceRow: 2,
396
+ raw: { date: "2025-09-15", amount: "5.00", description: "Older" },
397
+ },
398
+ ynabTransaction: {
399
+ id: "ynab-older",
400
+ date: "2025-09-14",
401
+ amount: 5000,
402
+ payee: "Older",
403
+ categoryName: null,
404
+ cleared: "uncleared",
405
+ approved: true,
406
+ memo: null,
407
+ },
408
+ candidates: [],
409
+ confidence: "high",
410
+ confidenceScore: 95,
411
+ matchReason: "Exact match",
412
+ },
413
+ {
414
+ bankTransaction: {
415
+ id: "bank-newer",
416
+ date: "2025-10-25",
417
+ amount: 10000,
418
+ payee: "Newer",
419
+ sourceRow: 1,
420
+ raw: { date: "2025-10-25", amount: "10.00", description: "Newer" },
421
+ },
422
+ ynabTransaction: {
423
+ id: "ynab-newer",
424
+ date: "2025-10-24",
425
+ amount: 10000,
426
+ payee: "Newer",
427
+ categoryName: null,
428
+ cleared: "uncleared",
429
+ approved: true,
430
+ memo: null,
431
+ },
432
+ candidates: [],
433
+ confidence: "high",
434
+ confidenceScore: 99,
435
+ matchReason: "Exact match",
436
+ },
437
+ ],
438
+ suggested_matches: [],
439
+ unmatched_bank: [],
440
+ unmatched_ynab: [],
441
+ balance_info: {
442
+ current_cleared: toMoneyValue(90000, "USD"),
443
+ current_uncleared: toMoneyValue(0, "USD"),
444
+ current_total: toMoneyValue(90000, "USD"),
445
+ target_statement: toMoneyValue(100000, "USD"),
446
+ discrepancy: toMoneyValue(-10000, "USD"),
447
+ on_track: false,
448
+ },
449
+ next_steps: [],
450
+ insights: [],
451
+ };
452
+
453
+ const params = {
454
+ budget_id: "budget-ordered",
455
+ account_id: "account-ordered",
456
+ csv_data: "Date,Description,Amount",
457
+ statement_balance: 100,
458
+ date_tolerance_days: 2,
459
+ amount_tolerance_cents: 1,
460
+ auto_match_threshold: 90,
461
+ suggestion_threshold: 60,
462
+ auto_create_transactions: false,
463
+ auto_update_cleared_status: true,
464
+ auto_unclear_missing: false,
465
+ auto_adjust_dates: false,
466
+ dry_run: true,
467
+ require_exact_match: true,
468
+ confidence_threshold: 0.8,
469
+ max_resolution_attempts: 5,
470
+ } satisfies any;
471
+
472
+ const initialAccount: AccountSnapshot = {
473
+ balance: 90000,
474
+ cleared_balance: 90000,
475
+ uncleared_balance: 0,
476
+ };
477
+
478
+ const result = await executeReconciliation({
479
+ ynabAPI: {} as ynab.API,
480
+ analysis,
481
+ params,
482
+ budgetId: "budget-ordered",
483
+ accountId: "account-ordered",
484
+ initialAccount,
485
+ currencyCode: "USD",
486
+ });
487
+
488
+ const updateActions = result.actions_taken.filter(
489
+ (action) => action.type === "update_transaction",
490
+ );
491
+ expect(updateActions).toHaveLength(1);
492
+ expect((updateActions[0]?.transaction as any)?.transaction_id).toBe(
493
+ "ynab-newer",
494
+ );
495
+ expect(
496
+ result.actions_taken.some(
497
+ (action) => action.type === "balance_checkpoint",
498
+ ),
499
+ ).toBe(true);
500
+ expect(result.summary.transactions_updated).toBe(1);
501
+ expect(result.summary.dates_adjusted).toBe(0);
502
+ });
472
503
  });
473
504
 
474
- describe('executeReconciliation - bulk create mode', () => {
475
- it('uses bulk create API for batches with multiple transactions', async () => {
476
- const analysis = buildBulkAnalysis(5, 12);
477
- const params = buildBulkParams(analysis.summary.target_statement_balance);
478
- const initialAccount = { ...defaultAccountSnapshot };
479
- const { api, mocks } = createMockYnabAPI(initialAccount);
480
-
481
- mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
482
- const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
483
- id: `bulk-${index}`,
484
- account_id: txn.account_id,
485
- amount: txn.amount,
486
- date: txn.date,
487
- payee_name: txn.payee_name,
488
- memo: txn.memo,
489
- cleared: 'cleared',
490
- approved: true,
491
- }));
492
- return { data: { transactions, duplicate_import_ids: [] } };
493
- });
494
-
495
- const result = await executeReconciliation({
496
- ynabAPI: api,
497
- analysis,
498
- params,
499
- budgetId: params.budget_id,
500
- accountId: params.account_id,
501
- initialAccount,
502
- currencyCode: 'USD',
503
- });
504
-
505
- expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
506
- const payload = mocks.createTransactions.mock.calls[0]?.[1];
507
- expect(payload?.transactions).toHaveLength(5);
508
- const createActions = result.actions_taken.filter(
509
- (action) => action.type === 'create_transaction',
510
- );
511
- expect(createActions).toHaveLength(5);
512
- expect(createActions.every((action) => action.correlation_key)).toBe(true);
513
- expect(result.summary.transactions_created).toBe(5);
514
- expect(result.bulk_operation_details).toEqual(
515
- expect.objectContaining({
516
- chunks_processed: 1,
517
- bulk_successes: 1,
518
- sequential_fallbacks: 0,
519
- bulk_chunk_failures: 0,
520
- transaction_failures: 0,
521
- }),
522
- );
523
- });
524
-
525
- it('falls back to sequential mode for single transaction scenarios', async () => {
526
- const analysis = buildBulkAnalysis(1, 15);
527
- const params = buildBulkParams(analysis.summary.target_statement_balance);
528
- const initialAccount = { ...defaultAccountSnapshot };
529
- const { api, mocks } = createMockYnabAPI(initialAccount);
530
-
531
- mocks.createTransaction.mockResolvedValue({
532
- data: {
533
- transaction: {
534
- id: 'single-txn',
535
- amount: 15000,
536
- date: analysis.unmatched_bank[0]?.date ?? '2025-10-01',
537
- },
538
- },
539
- });
540
-
541
- const result = await executeReconciliation({
542
- ynabAPI: api,
543
- analysis,
544
- params,
545
- budgetId: params.budget_id,
546
- accountId: params.account_id,
547
- initialAccount,
548
- currencyCode: 'USD',
549
- });
550
-
551
- expect(mocks.createTransactions).not.toHaveBeenCalled();
552
- expect(mocks.createTransaction).toHaveBeenCalledTimes(1);
553
- expect(result.summary.transactions_created).toBe(1);
554
- expect(result.bulk_operation_details).toBeUndefined();
555
- });
556
-
557
- it('falls back to sequential creation when bulk request fails', async () => {
558
- const analysis = buildBulkAnalysis(3, 1000);
559
- const params = buildBulkParams(analysis.summary.target_statement_balance);
560
- const initialAccount = { ...defaultAccountSnapshot };
561
- const { api, mocks } = createMockYnabAPI(initialAccount);
562
-
563
- mocks.createTransactions.mockRejectedValue(new Error('500 error'));
564
- mocks.createTransaction.mockImplementation(async (_budgetId, body: any) => {
565
- return {
566
- data: {
567
- transaction: {
568
- id: `seq-${body.transaction?.date}`,
569
- amount: body.transaction?.amount ?? 0,
570
- date: body.transaction?.date ?? '2025-11-01',
571
- cleared: 'cleared',
572
- approved: true,
573
- },
574
- },
575
- };
576
- });
577
-
578
- const result = await executeReconciliation({
579
- ynabAPI: api,
580
- analysis,
581
- params,
582
- budgetId: params.budget_id,
583
- accountId: params.account_id,
584
- initialAccount,
585
- currencyCode: 'USD',
586
- });
587
-
588
- expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
589
- expect(mocks.createTransaction).toHaveBeenCalledTimes(3);
590
- expect(result.actions_taken.some((action) => action.type === 'bulk_create_fallback')).toBe(
591
- true,
592
- );
593
- expect(result.summary.transactions_created).toBe(3);
594
- expect(result.bulk_operation_details).toEqual(
595
- expect.objectContaining({
596
- chunks_processed: 1,
597
- bulk_successes: 0,
598
- sequential_fallbacks: 1,
599
- bulk_chunk_failures: 1,
600
- transaction_failures: 0,
601
- }),
602
- );
603
- });
604
-
605
- it('propagates rate-limit error payloads with status codes from bulk create', async () => {
606
- const analysis = buildBulkAnalysis(3, 7);
607
- const params = buildBulkParams(analysis.summary.target_statement_balance);
608
- const initialAccount = { ...defaultAccountSnapshot };
609
- const { api, mocks } = createMockYnabAPI(initialAccount);
610
-
611
- mocks.createTransactions.mockRejectedValue({
612
- error: { id: '429', name: 'too_many_requests', detail: 'Too many requests' },
613
- });
614
-
615
- await expect(
616
- executeReconciliation({
617
- ynabAPI: api,
618
- analysis,
619
- params,
620
- budgetId: params.budget_id,
621
- accountId: params.account_id,
622
- initialAccount,
623
- currencyCode: 'USD',
624
- }),
625
- ).rejects.toMatchObject({ status: 429 });
626
- });
627
-
628
- it('splits large batches into 100-transaction chunks', async () => {
629
- const analysis = buildBulkAnalysis(150, 1000);
630
- const params = buildBulkParams(analysis.summary.target_statement_balance);
631
- const initialAccount = { ...defaultAccountSnapshot };
632
- const { api, mocks } = createMockYnabAPI(initialAccount);
633
-
634
- let chunkCall = 0;
635
- mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
636
- chunkCall += 1;
637
- const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
638
- id: `chunk-${chunkCall}-${index}`,
639
- account_id: txn.account_id,
640
- amount: txn.amount,
641
- date: txn.date,
642
- payee_name: txn.payee_name,
643
- memo: txn.memo,
644
- cleared: 'cleared',
645
- approved: true,
646
- }));
647
- return { data: { transactions, duplicate_import_ids: [] } };
648
- });
649
-
650
- const result = await executeReconciliation({
651
- ynabAPI: api,
652
- analysis,
653
- params,
654
- budgetId: params.budget_id,
655
- accountId: params.account_id,
656
- initialAccount,
657
- currencyCode: 'USD',
658
- });
659
-
660
- expect(mocks.createTransactions).toHaveBeenCalledTimes(2);
661
- expect(result.summary.transactions_created).toBe(150);
662
- expect(result.bulk_operation_details).toEqual(
663
- expect.objectContaining({
664
- chunks_processed: 2,
665
- bulk_successes: 2,
666
- bulk_chunk_failures: 0,
667
- transaction_failures: 0,
668
- }),
669
- );
670
- });
671
-
672
- it('throws on fatal sequential creation errors surfaced as objects', async () => {
673
- const analysis = buildBulkAnalysis(1, 1000);
674
- const params = buildBulkParams(analysis.summary.target_statement_balance);
675
- const initialAccount = { ...defaultAccountSnapshot };
676
- const { api, mocks } = createMockYnabAPI(initialAccount);
677
-
678
- mocks.createTransaction.mockRejectedValue({
679
- error: { id: '404', name: 'not_found', detail: 'Account not found' },
680
- });
681
-
682
- await expect(
683
- executeReconciliation({
684
- ynabAPI: api,
685
- analysis,
686
- params,
687
- budgetId: params.budget_id,
688
- accountId: params.account_id,
689
- initialAccount,
690
- currencyCode: 'USD',
691
- }),
692
- ).rejects.toMatchObject({ status: 404 });
693
- });
694
-
695
- it('creates all transactions without import_id (no YNAB-side duplicate detection)', async () => {
696
- // Note: import_id is intentionally omitted from reconciliation-created transactions
697
- // so they can match with bank-imported transactions. This means YNAB won't detect
698
- // duplicates via import_id - the reconciliation matcher is responsible for that.
699
- // Use amount of 100 to avoid early balance halting (tolerance is 10 milliunits)
700
- const analysis = buildBulkAnalysis(3, 100);
701
- const params = buildBulkParams(analysis.summary.target_statement_balance);
702
- const initialAccount = { ...defaultAccountSnapshot };
703
- const { api, mocks } = createMockYnabAPI(initialAccount);
704
-
705
- mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
706
- const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
707
- id: `created-${index}`,
708
- account_id: txn.account_id,
709
- amount: txn.amount,
710
- date: txn.date,
711
- payee_name: txn.payee_name,
712
- memo: txn.memo,
713
- cleared: 'cleared',
714
- approved: true,
715
- }));
716
- // Verify no import_id is being sent
717
- for (const txn of body.transactions ?? []) {
718
- expect(txn.import_id).toBeUndefined();
719
- }
720
- return {
721
- data: {
722
- transactions,
723
- duplicate_import_ids: [],
724
- },
725
- };
726
- });
727
-
728
- const result = await executeReconciliation({
729
- ynabAPI: api,
730
- analysis,
731
- params,
732
- budgetId: params.budget_id,
733
- accountId: params.account_id,
734
- initialAccount,
735
- currencyCode: 'USD',
736
- });
737
-
738
- // Without import_id, YNAB creates all transactions (no duplicate detection)
739
- expect(result.bulk_operation_details?.duplicates_detected).toBe(0);
740
- expect(result.summary.transactions_created).toBe(3);
741
- });
742
-
743
- it('honors halting logic when balance aligns mid-batch', async () => {
744
- const analysis = buildBulkAnalysis(10, 1000, 5);
745
- const params = buildBulkParams(analysis.summary.target_statement_balance);
746
- const initialAccount = { ...defaultAccountSnapshot };
747
- const { api, mocks } = createMockYnabAPI(initialAccount);
748
-
749
- mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
750
- const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
751
- id: `halt-${index}`,
752
- account_id: txn.account_id,
753
- amount: txn.amount,
754
- date: txn.date,
755
- payee_name: txn.payee_name,
756
- memo: txn.memo,
757
- cleared: 'cleared',
758
- approved: true,
759
- }));
760
- return { data: { transactions, duplicate_import_ids: [] } };
761
- });
762
-
763
- const result = await executeReconciliation({
764
- ynabAPI: api,
765
- analysis,
766
- params,
767
- budgetId: params.budget_id,
768
- accountId: params.account_id,
769
- initialAccount,
770
- currencyCode: 'USD',
771
- });
772
-
773
- expect(result.summary.transactions_created).toBe(5);
774
- expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
775
- const payload = mocks.createTransactions.mock.calls[0]?.[1];
776
- expect(payload?.transactions).toHaveLength(5);
777
- expect(result.actions_taken.some((action) => action.type === 'balance_checkpoint')).toBe(true);
778
- });
779
-
780
- it('processes multiple chunks and halts at chunk boundaries when balance aligns', async () => {
781
- // Create 120 unmatched bank transactions of $10 each = $1200 total available
782
- // Set target balance to $500 (50 transactions worth)
783
- // This verifies that when >100 transactions exist but balance aligns after ~50,
784
- // the batch-building loop stops early and only processes one chunk (not two)
785
- const count = 120;
786
- const amountPerTxn = 10;
787
- const analysis = buildBulkAnalysis(count, amountPerTxn, 50); // statement multiplier = 50
788
- // This sets target to $500 (50 transactions * $10)
789
- const initialAccount = { ...defaultAccountSnapshot };
790
- const params = buildBulkParams(analysis.summary.target_statement_balance);
791
- const { api, mocks } = createMockYnabAPI(initialAccount);
792
-
793
- let chunkCallCount = 0;
794
- mocks.createTransactions.mockImplementation(async (_budgetId, body: any) => {
795
- chunkCallCount += 1;
796
- const transactions = (body.transactions ?? []).map((txn: any, index: number) => ({
797
- id: `multi-chunk-halt-${chunkCallCount}-${index}`,
798
- account_id: txn.account_id,
799
- amount: txn.amount,
800
- date: txn.date,
801
- payee_name: txn.payee_name,
802
- memo: txn.memo,
803
- cleared: 'cleared',
804
- approved: true,
805
- }));
806
- return { data: { transactions, duplicate_import_ids: [] } };
807
- });
808
-
809
- const result = await executeReconciliation({
810
- ynabAPI: api,
811
- analysis,
812
- params,
813
- budgetId: params.budget_id,
814
- accountId: params.account_id,
815
- initialAccount,
816
- currencyCode: 'USD',
817
- });
818
-
819
- // Verify that only ~50 transactions were created (not all 120)
820
- expect(result.summary.transactions_created).toBeLessThan(count);
821
- expect(result.summary.transactions_created).toBeGreaterThan(0);
822
- // Only 1 chunk should be processed (not 2), since balance aligns before second chunk
823
- expect(chunkCallCount).toBe(1);
824
- expect(result.actions_taken.some((action) => action.type === 'balance_checkpoint')).toBe(true);
825
- expect(result.bulk_operation_details).toEqual(
826
- expect.objectContaining({
827
- chunks_processed: 1,
828
- bulk_successes: 1,
829
- }),
830
- );
831
- });
832
-
833
- it('simulates bulk preview during dry-run mode', async () => {
834
- const analysis = buildBulkAnalysis(5, 9);
835
- const params = buildBulkParams(analysis.summary.target_statement_balance, { dry_run: true });
836
- const initialAccount = { ...defaultAccountSnapshot };
837
- const { api, mocks } = createMockYnabAPI(initialAccount);
838
-
839
- const result = await executeReconciliation({
840
- ynabAPI: api,
841
- analysis,
842
- params,
843
- budgetId: params.budget_id,
844
- accountId: params.account_id,
845
- initialAccount,
846
- currencyCode: 'USD',
847
- });
848
-
849
- expect(mocks.createTransactions).not.toHaveBeenCalled();
850
- const createActions = result.actions_taken.filter(
851
- (action) => action.type === 'create_transaction',
852
- );
853
- expect(createActions).toHaveLength(5);
854
- expect(result.summary.transactions_created).toBe(5);
855
- expect(result.bulk_operation_details).toBeUndefined();
856
- });
505
+ describe("executeReconciliation - bulk create mode", () => {
506
+ it("uses bulk create API for batches with multiple transactions", async () => {
507
+ const analysis = buildBulkAnalysis(5, 12);
508
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
509
+ const initialAccount = { ...defaultAccountSnapshot };
510
+ const { api, mocks } = createMockYnabAPI(initialAccount);
511
+
512
+ mocks.createTransactions.mockImplementation(
513
+ async (_budgetId, body: any) => {
514
+ const transactions = (body.transactions ?? []).map(
515
+ (txn: any, index: number) => ({
516
+ id: `bulk-${index}`,
517
+ account_id: txn.account_id,
518
+ amount: txn.amount,
519
+ date: txn.date,
520
+ payee_name: txn.payee_name,
521
+ memo: txn.memo,
522
+ cleared: "cleared",
523
+ approved: true,
524
+ }),
525
+ );
526
+ return { data: { transactions, duplicate_import_ids: [] } };
527
+ },
528
+ );
529
+
530
+ const result = await executeReconciliation({
531
+ ynabAPI: api,
532
+ analysis,
533
+ params,
534
+ budgetId: params.budget_id,
535
+ accountId: params.account_id,
536
+ initialAccount,
537
+ currencyCode: "USD",
538
+ });
539
+
540
+ expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
541
+ const payload = mocks.createTransactions.mock.calls[0]?.[1];
542
+ expect(payload?.transactions).toHaveLength(5);
543
+ const createActions = result.actions_taken.filter(
544
+ (action) => action.type === "create_transaction",
545
+ );
546
+ expect(createActions).toHaveLength(5);
547
+ expect(createActions.every((action) => action.correlation_key)).toBe(true);
548
+ expect(result.summary.transactions_created).toBe(5);
549
+ expect(result.bulk_operation_details).toEqual(
550
+ expect.objectContaining({
551
+ chunks_processed: 1,
552
+ bulk_successes: 1,
553
+ sequential_fallbacks: 0,
554
+ bulk_chunk_failures: 0,
555
+ transaction_failures: 0,
556
+ }),
557
+ );
558
+ });
559
+
560
+ it("falls back to sequential mode for single transaction scenarios", async () => {
561
+ const analysis = buildBulkAnalysis(1, 15);
562
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
563
+ const initialAccount = { ...defaultAccountSnapshot };
564
+ const { api, mocks } = createMockYnabAPI(initialAccount);
565
+
566
+ mocks.createTransaction.mockResolvedValue({
567
+ data: {
568
+ transaction: {
569
+ id: "single-txn",
570
+ amount: 15000,
571
+ date: analysis.unmatched_bank[0]?.date ?? "2025-10-01",
572
+ },
573
+ },
574
+ });
575
+
576
+ const result = await executeReconciliation({
577
+ ynabAPI: api,
578
+ analysis,
579
+ params,
580
+ budgetId: params.budget_id,
581
+ accountId: params.account_id,
582
+ initialAccount,
583
+ currencyCode: "USD",
584
+ });
585
+
586
+ expect(mocks.createTransactions).not.toHaveBeenCalled();
587
+ expect(mocks.createTransaction).toHaveBeenCalledTimes(1);
588
+ expect(result.summary.transactions_created).toBe(1);
589
+ expect(result.bulk_operation_details).toBeUndefined();
590
+ });
591
+
592
+ it("falls back to sequential creation when bulk request fails", async () => {
593
+ const analysis = buildBulkAnalysis(3, 1000);
594
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
595
+ const initialAccount = { ...defaultAccountSnapshot };
596
+ const { api, mocks } = createMockYnabAPI(initialAccount);
597
+
598
+ mocks.createTransactions.mockRejectedValue(new Error("500 error"));
599
+ mocks.createTransaction.mockImplementation(async (_budgetId, body: any) => {
600
+ return {
601
+ data: {
602
+ transaction: {
603
+ id: `seq-${body.transaction?.date}`,
604
+ amount: body.transaction?.amount ?? 0,
605
+ date: body.transaction?.date ?? "2025-11-01",
606
+ cleared: "cleared",
607
+ approved: true,
608
+ },
609
+ },
610
+ };
611
+ });
612
+
613
+ const result = await executeReconciliation({
614
+ ynabAPI: api,
615
+ analysis,
616
+ params,
617
+ budgetId: params.budget_id,
618
+ accountId: params.account_id,
619
+ initialAccount,
620
+ currencyCode: "USD",
621
+ });
622
+
623
+ expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
624
+ expect(mocks.createTransaction).toHaveBeenCalledTimes(3);
625
+ expect(
626
+ result.actions_taken.some(
627
+ (action) => action.type === "bulk_create_fallback",
628
+ ),
629
+ ).toBe(true);
630
+ expect(result.summary.transactions_created).toBe(3);
631
+ expect(result.bulk_operation_details).toEqual(
632
+ expect.objectContaining({
633
+ chunks_processed: 1,
634
+ bulk_successes: 0,
635
+ sequential_fallbacks: 1,
636
+ bulk_chunk_failures: 1,
637
+ transaction_failures: 0,
638
+ }),
639
+ );
640
+ });
641
+
642
+ it("propagates rate-limit error payloads with status codes from bulk create", async () => {
643
+ const analysis = buildBulkAnalysis(3, 7);
644
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
645
+ const initialAccount = { ...defaultAccountSnapshot };
646
+ const { api, mocks } = createMockYnabAPI(initialAccount);
647
+
648
+ mocks.createTransactions.mockRejectedValue({
649
+ error: {
650
+ id: "429",
651
+ name: "too_many_requests",
652
+ detail: "Too many requests",
653
+ },
654
+ });
655
+
656
+ await expect(
657
+ executeReconciliation({
658
+ ynabAPI: api,
659
+ analysis,
660
+ params,
661
+ budgetId: params.budget_id,
662
+ accountId: params.account_id,
663
+ initialAccount,
664
+ currencyCode: "USD",
665
+ }),
666
+ ).rejects.toMatchObject({ status: 429 });
667
+ });
668
+
669
+ it("splits large batches into 100-transaction chunks", async () => {
670
+ const analysis = buildBulkAnalysis(150, 1000);
671
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
672
+ const initialAccount = { ...defaultAccountSnapshot };
673
+ const { api, mocks } = createMockYnabAPI(initialAccount);
674
+
675
+ let chunkCall = 0;
676
+ mocks.createTransactions.mockImplementation(
677
+ async (_budgetId, body: any) => {
678
+ chunkCall += 1;
679
+ const transactions = (body.transactions ?? []).map(
680
+ (txn: any, index: number) => ({
681
+ id: `chunk-${chunkCall}-${index}`,
682
+ account_id: txn.account_id,
683
+ amount: txn.amount,
684
+ date: txn.date,
685
+ payee_name: txn.payee_name,
686
+ memo: txn.memo,
687
+ cleared: "cleared",
688
+ approved: true,
689
+ }),
690
+ );
691
+ return { data: { transactions, duplicate_import_ids: [] } };
692
+ },
693
+ );
694
+
695
+ const result = await executeReconciliation({
696
+ ynabAPI: api,
697
+ analysis,
698
+ params,
699
+ budgetId: params.budget_id,
700
+ accountId: params.account_id,
701
+ initialAccount,
702
+ currencyCode: "USD",
703
+ });
704
+
705
+ expect(mocks.createTransactions).toHaveBeenCalledTimes(2);
706
+ expect(result.summary.transactions_created).toBe(150);
707
+ expect(result.bulk_operation_details).toEqual(
708
+ expect.objectContaining({
709
+ chunks_processed: 2,
710
+ bulk_successes: 2,
711
+ bulk_chunk_failures: 0,
712
+ transaction_failures: 0,
713
+ }),
714
+ );
715
+ });
716
+
717
+ it("throws on fatal sequential creation errors surfaced as objects", async () => {
718
+ const analysis = buildBulkAnalysis(1, 1000);
719
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
720
+ const initialAccount = { ...defaultAccountSnapshot };
721
+ const { api, mocks } = createMockYnabAPI(initialAccount);
722
+
723
+ mocks.createTransaction.mockRejectedValue({
724
+ error: { id: "404", name: "not_found", detail: "Account not found" },
725
+ });
726
+
727
+ await expect(
728
+ executeReconciliation({
729
+ ynabAPI: api,
730
+ analysis,
731
+ params,
732
+ budgetId: params.budget_id,
733
+ accountId: params.account_id,
734
+ initialAccount,
735
+ currencyCode: "USD",
736
+ }),
737
+ ).rejects.toMatchObject({ status: 404 });
738
+ });
739
+
740
+ it("creates all transactions without import_id (no YNAB-side duplicate detection)", async () => {
741
+ // Note: import_id is intentionally omitted from reconciliation-created transactions
742
+ // so they can match with bank-imported transactions. This means YNAB won't detect
743
+ // duplicates via import_id - the reconciliation matcher is responsible for that.
744
+ // Use amount of 100 to avoid early balance halting (tolerance is 10 milliunits)
745
+ const analysis = buildBulkAnalysis(3, 100);
746
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
747
+ const initialAccount = { ...defaultAccountSnapshot };
748
+ const { api, mocks } = createMockYnabAPI(initialAccount);
749
+
750
+ mocks.createTransactions.mockImplementation(
751
+ async (_budgetId, body: any) => {
752
+ const transactions = (body.transactions ?? []).map(
753
+ (txn: any, index: number) => ({
754
+ id: `created-${index}`,
755
+ account_id: txn.account_id,
756
+ amount: txn.amount,
757
+ date: txn.date,
758
+ payee_name: txn.payee_name,
759
+ memo: txn.memo,
760
+ cleared: "cleared",
761
+ approved: true,
762
+ }),
763
+ );
764
+ // Verify no import_id is being sent
765
+ for (const txn of body.transactions ?? []) {
766
+ expect(txn.import_id).toBeUndefined();
767
+ }
768
+ return {
769
+ data: {
770
+ transactions,
771
+ duplicate_import_ids: [],
772
+ },
773
+ };
774
+ },
775
+ );
776
+
777
+ const result = await executeReconciliation({
778
+ ynabAPI: api,
779
+ analysis,
780
+ params,
781
+ budgetId: params.budget_id,
782
+ accountId: params.account_id,
783
+ initialAccount,
784
+ currencyCode: "USD",
785
+ });
786
+
787
+ // Without import_id, YNAB creates all transactions (no duplicate detection)
788
+ expect(result.bulk_operation_details?.duplicates_detected).toBe(0);
789
+ expect(result.summary.transactions_created).toBe(3);
790
+ });
791
+
792
+ it("honors halting logic when balance aligns mid-batch", async () => {
793
+ const analysis = buildBulkAnalysis(10, 1000, 5);
794
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
795
+ const initialAccount = { ...defaultAccountSnapshot };
796
+ const { api, mocks } = createMockYnabAPI(initialAccount);
797
+
798
+ mocks.createTransactions.mockImplementation(
799
+ async (_budgetId, body: any) => {
800
+ const transactions = (body.transactions ?? []).map(
801
+ (txn: any, index: number) => ({
802
+ id: `halt-${index}`,
803
+ account_id: txn.account_id,
804
+ amount: txn.amount,
805
+ date: txn.date,
806
+ payee_name: txn.payee_name,
807
+ memo: txn.memo,
808
+ cleared: "cleared",
809
+ approved: true,
810
+ }),
811
+ );
812
+ return { data: { transactions, duplicate_import_ids: [] } };
813
+ },
814
+ );
815
+
816
+ const result = await executeReconciliation({
817
+ ynabAPI: api,
818
+ analysis,
819
+ params,
820
+ budgetId: params.budget_id,
821
+ accountId: params.account_id,
822
+ initialAccount,
823
+ currencyCode: "USD",
824
+ });
825
+
826
+ expect(result.summary.transactions_created).toBe(5);
827
+ expect(mocks.createTransactions).toHaveBeenCalledTimes(1);
828
+ const payload = mocks.createTransactions.mock.calls[0]?.[1];
829
+ expect(payload?.transactions).toHaveLength(5);
830
+ expect(
831
+ result.actions_taken.some(
832
+ (action) => action.type === "balance_checkpoint",
833
+ ),
834
+ ).toBe(true);
835
+ });
836
+
837
+ it("processes multiple chunks and halts at chunk boundaries when balance aligns", async () => {
838
+ // Create 120 unmatched bank transactions of $10 each = $1200 total available
839
+ // Set target balance to $500 (50 transactions worth)
840
+ // This verifies that when >100 transactions exist but balance aligns after ~50,
841
+ // the batch-building loop stops early and only processes one chunk (not two)
842
+ const count = 120;
843
+ const amountPerTxn = 10;
844
+ const analysis = buildBulkAnalysis(count, amountPerTxn, 50); // statement multiplier = 50
845
+ // This sets target to $500 (50 transactions * $10)
846
+ const initialAccount = { ...defaultAccountSnapshot };
847
+ const params = buildBulkParams(analysis.summary.target_statement_balance);
848
+ const { api, mocks } = createMockYnabAPI(initialAccount);
849
+
850
+ let chunkCallCount = 0;
851
+ mocks.createTransactions.mockImplementation(
852
+ async (_budgetId, body: any) => {
853
+ chunkCallCount += 1;
854
+ const transactions = (body.transactions ?? []).map(
855
+ (txn: any, index: number) => ({
856
+ id: `multi-chunk-halt-${chunkCallCount}-${index}`,
857
+ account_id: txn.account_id,
858
+ amount: txn.amount,
859
+ date: txn.date,
860
+ payee_name: txn.payee_name,
861
+ memo: txn.memo,
862
+ cleared: "cleared",
863
+ approved: true,
864
+ }),
865
+ );
866
+ return { data: { transactions, duplicate_import_ids: [] } };
867
+ },
868
+ );
869
+
870
+ const result = await executeReconciliation({
871
+ ynabAPI: api,
872
+ analysis,
873
+ params,
874
+ budgetId: params.budget_id,
875
+ accountId: params.account_id,
876
+ initialAccount,
877
+ currencyCode: "USD",
878
+ });
879
+
880
+ // Verify that only ~50 transactions were created (not all 120)
881
+ expect(result.summary.transactions_created).toBeLessThan(count);
882
+ expect(result.summary.transactions_created).toBeGreaterThan(0);
883
+ // Only 1 chunk should be processed (not 2), since balance aligns before second chunk
884
+ expect(chunkCallCount).toBe(1);
885
+ expect(
886
+ result.actions_taken.some(
887
+ (action) => action.type === "balance_checkpoint",
888
+ ),
889
+ ).toBe(true);
890
+ expect(result.bulk_operation_details).toEqual(
891
+ expect.objectContaining({
892
+ chunks_processed: 1,
893
+ bulk_successes: 1,
894
+ }),
895
+ );
896
+ });
897
+
898
+ it("simulates bulk preview during dry-run mode", async () => {
899
+ const analysis = buildBulkAnalysis(5, 9);
900
+ const params = buildBulkParams(analysis.summary.target_statement_balance, {
901
+ dry_run: true,
902
+ });
903
+ const initialAccount = { ...defaultAccountSnapshot };
904
+ const { api, mocks } = createMockYnabAPI(initialAccount);
905
+
906
+ const result = await executeReconciliation({
907
+ ynabAPI: api,
908
+ analysis,
909
+ params,
910
+ budgetId: params.budget_id,
911
+ accountId: params.account_id,
912
+ initialAccount,
913
+ currencyCode: "USD",
914
+ });
915
+
916
+ expect(mocks.createTransactions).not.toHaveBeenCalled();
917
+ const createActions = result.actions_taken.filter(
918
+ (action) => action.type === "create_transaction",
919
+ );
920
+ expect(createActions).toHaveLength(5);
921
+ expect(result.summary.transactions_created).toBe(5);
922
+ expect(result.bulk_operation_details).toBeUndefined();
923
+ });
857
924
  });