@rfc0/patty 0.0.0-stage → 1.0.2

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 (465) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +214 -2
  3. package/dist/adapters/access-tokens.js +7 -0
  4. package/dist/adapters/accounts.js +37 -0
  5. package/dist/adapters/auth.js +11 -0
  6. package/dist/adapters/bills.js +32 -0
  7. package/dist/adapters/budgets.js +29 -0
  8. package/dist/adapters/categories.js +32 -0
  9. package/dist/adapters/client-grants.js +7 -0
  10. package/dist/adapters/credit-cards.js +33 -0
  11. package/dist/adapters/currencies.js +2 -0
  12. package/dist/adapters/currency-rates.js +18 -0
  13. package/dist/adapters/dashboards.js +43 -0
  14. package/dist/adapters/demo.js +13 -0
  15. package/dist/adapters/instance-settings.js +7 -0
  16. package/dist/adapters/invites.js +7 -0
  17. package/dist/adapters/recurring.js +55 -0
  18. package/dist/adapters/sessions.js +7 -0
  19. package/dist/adapters/settings.js +4 -0
  20. package/dist/adapters/setup-codes.js +7 -0
  21. package/dist/adapters/tags.js +9 -0
  22. package/dist/adapters/transactions.js +95 -0
  23. package/dist/adapters/users.js +7 -0
  24. package/dist/common/build-version.js +5 -0
  25. package/dist/common/errors.js +118 -0
  26. package/dist/common/net.js +71 -0
  27. package/dist/common/result.js +7 -0
  28. package/dist/composition/auth.js +106 -0
  29. package/dist/composition/boot.js +27 -0
  30. package/dist/composition/cli.js +86 -0
  31. package/dist/composition/demo/seed.js +92 -0
  32. package/dist/composition/demo/shell.js +107 -0
  33. package/dist/composition/export.js +89 -0
  34. package/dist/composition/http.js +110 -0
  35. package/dist/composition/import.js +55 -0
  36. package/dist/composition/lazy-modules.js +2 -0
  37. package/dist/composition/runtime.js +115 -0
  38. package/dist/composition/sign-in/interpreter.js +154 -0
  39. package/dist/composition/sign-in/server.js +36 -0
  40. package/dist/composition/sign-in/wiring.js +23 -0
  41. package/dist/composition/stdio.js +69 -0
  42. package/dist/config.js +136 -0
  43. package/dist/controllers/account/account.js +88 -0
  44. package/dist/controllers/account/transaction.js +119 -0
  45. package/dist/controllers/account/transfer.js +34 -0
  46. package/dist/controllers/aggregate.js +40 -0
  47. package/dist/controllers/auth/access-tokens.js +61 -0
  48. package/dist/controllers/auth/grants.js +136 -0
  49. package/dist/controllers/auth/key-export.js +20 -0
  50. package/dist/controllers/auth/owner.js +80 -0
  51. package/dist/controllers/auth/password.js +35 -0
  52. package/dist/controllers/auth/session.js +50 -0
  53. package/dist/controllers/auth/step-up.js +8 -0
  54. package/dist/controllers/auth/users.js +183 -0
  55. package/dist/controllers/budgets.js +87 -0
  56. package/dist/controllers/categories.js +67 -0
  57. package/dist/controllers/correlations.js +112 -0
  58. package/dist/controllers/credit-card/bill.js +105 -0
  59. package/dist/controllers/credit-card/credit-card.js +129 -0
  60. package/dist/controllers/credit-card/transaction.js +181 -0
  61. package/dist/controllers/currencies.js +1 -0
  62. package/dist/controllers/currency-rates.js +40 -0
  63. package/dist/controllers/dashboards.js +68 -0
  64. package/dist/controllers/demo/seed.js +31 -0
  65. package/dist/controllers/demo/tour.js +12 -0
  66. package/dist/controllers/deps.js +6 -0
  67. package/dist/controllers/instance.js +6 -0
  68. package/dist/controllers/merchants.js +12 -0
  69. package/dist/controllers/recurring.js +70 -0
  70. package/dist/controllers/resolve.js +37 -0
  71. package/dist/controllers/settings.js +47 -0
  72. package/dist/controllers/status.js +19 -0
  73. package/dist/controllers/summary.js +21 -0
  74. package/dist/controllers/tags.js +19 -0
  75. package/dist/controllers/transaction/bulk.js +6 -0
  76. package/dist/controllers/transaction/core.js +49 -0
  77. package/dist/controllers/transaction/read.js +28 -0
  78. package/dist/diplomat/auth/credentials.js +58 -0
  79. package/dist/diplomat/auth/sign-in-store.js +18 -0
  80. package/dist/diplomat/cli/commands/auth.js +100 -0
  81. package/dist/diplomat/cli/commands/db.js +72 -0
  82. package/dist/diplomat/cli/commands/demo.js +68 -0
  83. package/dist/diplomat/cli/commands/key.js +119 -0
  84. package/dist/diplomat/cli/commands/login.js +151 -0
  85. package/dist/diplomat/cli/commands/setup.js +132 -0
  86. package/dist/diplomat/cli/commands/users.js +123 -0
  87. package/dist/diplomat/cli/commands.js +61 -0
  88. package/dist/diplomat/cli/export-file.js +37 -0
  89. package/dist/diplomat/cli/import-file.js +44 -0
  90. package/dist/diplomat/cli/io.js +61 -0
  91. package/dist/diplomat/cli/key-export-approval.js +37 -0
  92. package/dist/diplomat/cli/messages.js +96 -0
  93. package/dist/diplomat/cli/prompt.js +74 -0
  94. package/dist/diplomat/cli/terminal.js +81 -0
  95. package/dist/diplomat/client-config/clients.js +150 -0
  96. package/dist/diplomat/client-config/merge.js +41 -0
  97. package/dist/diplomat/db/bootstrap.js +98 -0
  98. package/dist/diplomat/db/database-files.js +147 -0
  99. package/dist/diplomat/db/driver.js +167 -0
  100. package/dist/diplomat/db/effects.js +101 -0
  101. package/dist/diplomat/db/engine.js +9 -0
  102. package/dist/diplomat/db/export.js +22 -0
  103. package/dist/diplomat/db/file-lock.js +82 -0
  104. package/dist/diplomat/db/key-lock.js +14 -0
  105. package/dist/diplomat/db/locale-cache.js +23 -0
  106. package/dist/diplomat/db/migration-barrier.js +57 -0
  107. package/dist/diplomat/db/migration-journal.js +18 -0
  108. package/dist/diplomat/db/migration-lock.js +15 -0
  109. package/dist/diplomat/db/migrations.js +11 -0
  110. package/dist/diplomat/db/present.js +17 -0
  111. package/dist/diplomat/db/queries/aggregate-whitelist.js +35 -0
  112. package/dist/diplomat/db/queries/filters.js +59 -0
  113. package/dist/diplomat/db/queries/fts.js +18 -0
  114. package/dist/diplomat/db/queries/scope.js +8 -0
  115. package/dist/diplomat/db/queries/transaction-select.js +26 -0
  116. package/dist/diplomat/db/queries/tx-predicates.js +13 -0
  117. package/dist/diplomat/db/repos/access-tokens.js +27 -0
  118. package/dist/diplomat/db/repos/accounts.js +91 -0
  119. package/dist/diplomat/db/repos/bills.js +93 -0
  120. package/dist/diplomat/db/repos/budgets.js +72 -0
  121. package/dist/diplomat/db/repos/categories.js +53 -0
  122. package/dist/diplomat/db/repos/client-grants.js +67 -0
  123. package/dist/diplomat/db/repos/correlations.js +66 -0
  124. package/dist/diplomat/db/repos/credit-cards.js +67 -0
  125. package/dist/diplomat/db/repos/currencies.js +8 -0
  126. package/dist/diplomat/db/repos/currency-rates.js +40 -0
  127. package/dist/diplomat/db/repos/dashboards.js +123 -0
  128. package/dist/diplomat/db/repos/health.js +12 -0
  129. package/dist/diplomat/db/repos/instance-settings.js +14 -0
  130. package/dist/diplomat/db/repos/instance.js +58 -0
  131. package/dist/diplomat/db/repos/invites.js +43 -0
  132. package/dist/diplomat/db/repos/merchants.js +121 -0
  133. package/dist/diplomat/db/repos/recurring.js +29 -0
  134. package/dist/diplomat/db/repos/sessions.js +19 -0
  135. package/dist/diplomat/db/repos/settings.js +41 -0
  136. package/dist/diplomat/db/repos/setup-codes.js +28 -0
  137. package/dist/diplomat/db/repos/sub-categories.js +67 -0
  138. package/dist/diplomat/db/repos/tags.js +51 -0
  139. package/dist/diplomat/db/repos/transaction-tags.js +57 -0
  140. package/dist/diplomat/db/repos/transactions.js +163 -0
  141. package/dist/diplomat/db/repos/users.js +47 -0
  142. package/dist/diplomat/db/safety-copy.js +87 -0
  143. package/dist/diplomat/db/schema.js +348 -0
  144. package/dist/diplomat/db/seed/categories.js +112 -0
  145. package/dist/diplomat/db/seed/currencies.js +9 -0
  146. package/dist/diplomat/db/seed/demo/br.js +98 -0
  147. package/dist/diplomat/db/seed/demo/co.js +89 -0
  148. package/dist/diplomat/db/seed/demo/index.js +12 -0
  149. package/dist/diplomat/db/seed/demo/mx.js +90 -0
  150. package/dist/diplomat/db/seed/demo/shared.js +39 -0
  151. package/dist/diplomat/db/seed/demo/us.js +90 -0
  152. package/dist/diplomat/db/seed/merchant-rules.js +188 -0
  153. package/dist/diplomat/db/sqlite-errors.js +40 -0
  154. package/dist/diplomat/db/tenancy-integrity.js +45 -0
  155. package/dist/diplomat/db/version-guard.js +16 -0
  156. package/dist/diplomat/http/auth-pages.js +41 -0
  157. package/dist/diplomat/http/auth-paths.js +46 -0
  158. package/dist/diplomat/http/bearer.js +15 -0
  159. package/dist/diplomat/http/connect-pages.js +51 -0
  160. package/dist/diplomat/http/context.js +17 -0
  161. package/dist/diplomat/http/cookies.js +27 -0
  162. package/dist/diplomat/http/form-pages.js +38 -0
  163. package/dist/diplomat/http/hooks/auth.js +106 -0
  164. package/dist/diplomat/http/hooks/demo-marker.js +59 -0
  165. package/dist/diplomat/http/openapi.js +73 -0
  166. package/dist/diplomat/http/principal.js +1 -0
  167. package/dist/diplomat/http/rate-limiter.js +78 -0
  168. package/dist/diplomat/http/remedy.js +26 -0
  169. package/dist/diplomat/http/respond.js +50 -0
  170. package/dist/diplomat/http/routes/account.js +226 -0
  171. package/dist/diplomat/http/routes/aggregate.js +28 -0
  172. package/dist/diplomat/http/routes/auth.js +105 -0
  173. package/dist/diplomat/http/routes/budget.js +34 -0
  174. package/dist/diplomat/http/routes/category.js +109 -0
  175. package/dist/diplomat/http/routes/connect.js +124 -0
  176. package/dist/diplomat/http/routes/credit-card.js +263 -0
  177. package/dist/diplomat/http/routes/currency-rates.js +60 -0
  178. package/dist/diplomat/http/routes/currency.js +16 -0
  179. package/dist/diplomat/http/routes/dashboard.js +93 -0
  180. package/dist/diplomat/http/routes/invite.js +63 -0
  181. package/dist/diplomat/http/routes/recurring.js +65 -0
  182. package/dist/diplomat/http/routes/settings.js +38 -0
  183. package/dist/diplomat/http/routes/summary.js +23 -0
  184. package/dist/diplomat/http/routes/system.js +29 -0
  185. package/dist/diplomat/http/routes/tag.js +51 -0
  186. package/dist/diplomat/http/routes/tokens.js +72 -0
  187. package/dist/diplomat/http/routes/transaction.js +55 -0
  188. package/dist/diplomat/http/routes/transfer.js +35 -0
  189. package/dist/diplomat/http/routes/ui.js +110 -0
  190. package/dist/diplomat/http/routes/users.js +156 -0
  191. package/dist/diplomat/http/routes/well-known.js +26 -0
  192. package/dist/diplomat/http/routes.js +85 -0
  193. package/dist/diplomat/http/session.js +34 -0
  194. package/dist/diplomat/http/token-pages.js +75 -0
  195. package/dist/diplomat/http/ui-files.js +21 -0
  196. package/dist/diplomat/http/user-pages.js +93 -0
  197. package/dist/diplomat/mcp/annotations.js +8 -0
  198. package/dist/diplomat/mcp/auth-info.js +20 -0
  199. package/dist/diplomat/mcp/context.js +14 -0
  200. package/dist/diplomat/mcp/definition.js +3 -0
  201. package/dist/diplomat/mcp/gate.js +15 -0
  202. package/dist/diplomat/mcp/instructions.js +19 -0
  203. package/dist/diplomat/mcp/prompts.js +125 -0
  204. package/dist/diplomat/mcp/register.js +12 -0
  205. package/dist/diplomat/mcp/remedy.js +17 -0
  206. package/dist/diplomat/mcp/resources.js +93 -0
  207. package/dist/diplomat/mcp/respond.js +20 -0
  208. package/dist/diplomat/mcp/route.js +62 -0
  209. package/dist/diplomat/mcp/scopes.js +53 -0
  210. package/dist/diplomat/mcp/server.js +26 -0
  211. package/dist/diplomat/mcp/shared.js +5 -0
  212. package/dist/diplomat/mcp/stdio-session.js +94 -0
  213. package/dist/diplomat/mcp/stdio.js +23 -0
  214. package/dist/diplomat/mcp/tool-name.js +59 -0
  215. package/dist/diplomat/mcp/tools/account.js +218 -0
  216. package/dist/diplomat/mcp/tools/aggregate.js +32 -0
  217. package/dist/diplomat/mcp/tools/budget.js +99 -0
  218. package/dist/diplomat/mcp/tools/category.js +103 -0
  219. package/dist/diplomat/mcp/tools/correlations.js +70 -0
  220. package/dist/diplomat/mcp/tools/credit-card.js +239 -0
  221. package/dist/diplomat/mcp/tools/currency-rates.js +62 -0
  222. package/dist/diplomat/mcp/tools/dashboard.js +75 -0
  223. package/dist/diplomat/mcp/tools/index.js +31 -0
  224. package/dist/diplomat/mcp/tools/recurring.js +62 -0
  225. package/dist/diplomat/mcp/tools/summary.js +30 -0
  226. package/dist/diplomat/mcp/tools/system.js +83 -0
  227. package/dist/diplomat/mcp/tools/tag.js +48 -0
  228. package/dist/diplomat/mcp/tools/transaction.js +53 -0
  229. package/dist/diplomat/mcp/tools/transfer.js +28 -0
  230. package/dist/diplomat/mcp/tour.js +87 -0
  231. package/dist/logic/account.js +79 -0
  232. package/dist/logic/aggregate.js +37 -0
  233. package/dist/logic/auth/bearer.js +35 -0
  234. package/dist/logic/auth/grant.js +126 -0
  235. package/dist/logic/auth/key-export.js +10 -0
  236. package/dist/logic/auth/keychain.js +3 -0
  237. package/dist/logic/auth/message.js +22 -0
  238. package/dist/logic/auth/origin.js +57 -0
  239. package/dist/logic/auth/owner.js +22 -0
  240. package/dist/logic/auth/password.js +3 -0
  241. package/dist/logic/auth/redact.js +25 -0
  242. package/dist/logic/auth/revoke.js +28 -0
  243. package/dist/logic/auth/scope.js +17 -0
  244. package/dist/logic/auth/session.js +30 -0
  245. package/dist/logic/auth/sign-in-flow.js +305 -0
  246. package/dist/logic/auth/time.js +2 -0
  247. package/dist/logic/auth/token.js +74 -0
  248. package/dist/logic/auth/user-plans.js +84 -0
  249. package/dist/logic/auth/users.js +78 -0
  250. package/dist/logic/balance.js +2 -0
  251. package/dist/logic/bill.js +74 -0
  252. package/dist/logic/budget.js +78 -0
  253. package/dist/logic/category.js +37 -0
  254. package/dist/logic/classify.js +21 -0
  255. package/dist/logic/correlations.js +147 -0
  256. package/dist/logic/credit-card.js +2 -0
  257. package/dist/logic/currency-rate.js +69 -0
  258. package/dist/logic/dashboard.js +40 -0
  259. package/dist/logic/demo/database.js +30 -0
  260. package/dist/logic/demo/plan.js +308 -0
  261. package/dist/logic/demo/tour.js +33 -0
  262. package/dist/logic/export-destination.js +12 -0
  263. package/dist/logic/key-import.js +15 -0
  264. package/dist/logic/locale.js +5 -0
  265. package/dist/logic/localize.js +12 -0
  266. package/dist/logic/merchant.js +31 -0
  267. package/dist/logic/migration.js +1 -0
  268. package/dist/logic/money.js +12 -0
  269. package/dist/logic/period.js +45 -0
  270. package/dist/logic/persistence.js +48 -0
  271. package/dist/logic/recurring.js +51 -0
  272. package/dist/logic/resolve.js +44 -0
  273. package/dist/logic/summary.js +29 -0
  274. package/dist/logic/tag.js +13 -0
  275. package/dist/logic/transaction.js +197 -0
  276. package/dist/main.js +42 -0
  277. package/dist/models/account.js +197 -0
  278. package/dist/models/aggregate.js +61 -0
  279. package/dist/models/auth/bearer.js +11 -0
  280. package/dist/models/auth/entity.js +17 -0
  281. package/dist/models/auth/errors.js +42 -0
  282. package/dist/models/auth/grant.js +58 -0
  283. package/dist/models/auth/key-export.js +11 -0
  284. package/dist/models/auth/message.js +50 -0
  285. package/dist/models/auth/mode.js +7 -0
  286. package/dist/models/auth/origin.js +16 -0
  287. package/dist/models/auth/owner.js +36 -0
  288. package/dist/models/auth/password.js +24 -0
  289. package/dist/models/auth/principal.js +26 -0
  290. package/dist/models/auth/redact.js +4 -0
  291. package/dist/models/auth/scope.js +9 -0
  292. package/dist/models/auth/session.js +19 -0
  293. package/dist/models/auth/sign-in-flow.js +102 -0
  294. package/dist/models/auth/sign-in.js +41 -0
  295. package/dist/models/auth/time.js +5 -0
  296. package/dist/models/auth/token.js +50 -0
  297. package/dist/models/auth/users.js +52 -0
  298. package/dist/models/bill.js +55 -0
  299. package/dist/models/budget.js +106 -0
  300. package/dist/models/category.js +52 -0
  301. package/dist/models/client-config.js +18 -0
  302. package/dist/models/correlations.js +215 -0
  303. package/dist/models/credit-card.js +156 -0
  304. package/dist/models/currency-rate.js +83 -0
  305. package/dist/models/dashboard.js +54 -0
  306. package/dist/models/database.js +16 -0
  307. package/dist/models/date.js +8 -0
  308. package/dist/models/demo/core.js +58 -0
  309. package/dist/models/demo/tour.js +41 -0
  310. package/dist/models/encryption-key.js +2 -0
  311. package/dist/models/error.js +13 -0
  312. package/dist/models/export.js +9 -0
  313. package/dist/models/id.js +2 -0
  314. package/dist/models/instance.js +7 -0
  315. package/dist/models/key-import.js +6 -0
  316. package/dist/models/locale.js +25 -0
  317. package/dist/models/merchant.js +12 -0
  318. package/dist/models/money.js +14 -0
  319. package/dist/models/package.js +12 -0
  320. package/dist/models/page.js +56 -0
  321. package/dist/models/persistence.js +1 -0
  322. package/dist/models/prompts.js +5 -0
  323. package/dist/models/recurring.js +54 -0
  324. package/dist/models/remedy.js +17 -0
  325. package/dist/models/resolution.js +1 -0
  326. package/dist/models/startup.js +7 -0
  327. package/dist/models/summary.js +24 -0
  328. package/dist/models/tag.js +14 -0
  329. package/dist/models/tenancy.js +10 -0
  330. package/dist/models/transaction-tag.js +6 -0
  331. package/dist/models/transaction.js +275 -0
  332. package/dist/wire/db/access-tokens.js +1 -0
  333. package/dist/wire/db/accounts.js +7 -0
  334. package/dist/wire/db/aggregate.js +16 -0
  335. package/dist/wire/db/bills.js +14 -0
  336. package/dist/wire/db/budgets.js +33 -0
  337. package/dist/wire/db/categories.js +14 -0
  338. package/dist/wire/db/client-grants.js +1 -0
  339. package/dist/wire/db/correlations.js +49 -0
  340. package/dist/wire/db/credit-cards.js +1 -0
  341. package/dist/wire/db/currencies.js +1 -0
  342. package/dist/wire/db/currency-rates.js +1 -0
  343. package/dist/wire/db/dashboards.js +1 -0
  344. package/dist/wire/db/instance-settings.js +1 -0
  345. package/dist/wire/db/invites.js +1 -0
  346. package/dist/wire/db/merchants.js +18 -0
  347. package/dist/wire/db/recurring.js +19 -0
  348. package/dist/wire/db/sessions.js +1 -0
  349. package/dist/wire/db/settings.js +1 -0
  350. package/dist/wire/db/setup-codes.js +1 -0
  351. package/dist/wire/db/tags.js +1 -0
  352. package/dist/wire/db/tenancy.js +1 -0
  353. package/dist/wire/db/transactions.js +89 -0
  354. package/dist/wire/db/users.js +1 -0
  355. package/dist/wire/in/accounts.js +26 -0
  356. package/dist/wire/in/aggregate.js +10 -0
  357. package/dist/wire/in/auth.js +107 -0
  358. package/dist/wire/in/bills.js +11 -0
  359. package/dist/wire/in/budgets.js +11 -0
  360. package/dist/wire/in/categories.js +9 -0
  361. package/dist/wire/in/cli.js +106 -0
  362. package/dist/wire/in/coerce.js +6 -0
  363. package/dist/wire/in/common.js +17 -0
  364. package/dist/wire/in/credit-cards.js +16 -0
  365. package/dist/wire/in/currency-rates.js +8 -0
  366. package/dist/wire/in/period.js +7 -0
  367. package/dist/wire/in/recurring.js +6 -0
  368. package/dist/wire/in/settings.js +5 -0
  369. package/dist/wire/in/summary.js +5 -0
  370. package/dist/wire/in/tags.js +2 -0
  371. package/dist/wire/in/transactions.js +31 -0
  372. package/dist/wire/out/bills.js +9 -0
  373. package/dist/wire/out/budgets.js +10 -0
  374. package/dist/wire/out/client-config.js +2 -0
  375. package/dist/wire/out/common.js +4 -0
  376. package/dist/wire/out/credit-cards.js +15 -0
  377. package/dist/wire/out/currency-rates.js +11 -0
  378. package/dist/wire/out/errors.js +58 -0
  379. package/dist/wire/out/recurring.js +6 -0
  380. package/dist/wire/out/status.js +10 -0
  381. package/dist/wire/out/summary.js +9 -0
  382. package/dist/wire/out/transactions.js +52 -0
  383. package/drizzle/0000_futuristic_umar.sql +124 -0
  384. package/drizzle/0001_fts5_search.sql +23 -0
  385. package/drizzle/0002_rename_graph_to_history.sql +7 -0
  386. package/drizzle/0003_lyrical_hairball.sql +2 -0
  387. package/drizzle/0004_misty_ikaris.sql +7 -0
  388. package/drizzle/0005_credit-liability-accounts.sql +14 -0
  389. package/drizzle/0006_smart_aqueduct.sql +1 -0
  390. package/drizzle/0007_add_dashboards.sql +5 -0
  391. package/drizzle/0008_yummy_madripoor.sql +1 -0
  392. package/drizzle/0009_version_groundwork.sql +9 -0
  393. package/drizzle/0010_category_merchant_association_cascade.sql +16 -0
  394. package/drizzle/0011_dashboard_id_normalization.sql +16 -0
  395. package/drizzle/0012_hot_the_spike.sql +12 -0
  396. package/drizzle/0013_recurring_rules_merchant.sql +1 -0
  397. package/drizzle/0014_dashboard_source_discriminator.sql +17 -0
  398. package/drizzle/0015_currencies_decimals.sql +1 -0
  399. package/drizzle/0016_unusual_zaran.sql +13 -0
  400. package/drizzle/0017_premium_blur.sql +1 -0
  401. package/drizzle/0018_auth_identity.sql +39 -0
  402. package/drizzle/0019_access_tokens.sql +16 -0
  403. package/drizzle/0020_stdio_sign_in.sql +27 -0
  404. package/drizzle/0021_tenancy_data.sql +289 -0
  405. package/drizzle/0022_user_management.sql +17 -0
  406. package/drizzle/0023_instance_settings_row.sql +2 -0
  407. package/drizzle/0024_credentials_changed_at.sql +2 -0
  408. package/drizzle/0025_instance_kind.sql +2 -0
  409. package/drizzle/0026_demo_seeded_at.sql +2 -0
  410. package/drizzle/0027_demo_country.sql +2 -0
  411. package/drizzle/0028_reset_sign_ins.sql +2 -0
  412. package/drizzle/meta/0000_snapshot.json +894 -0
  413. package/drizzle/meta/0003_snapshot.json +910 -0
  414. package/drizzle/meta/0004_snapshot.json +951 -0
  415. package/drizzle/meta/0005_snapshot.json +991 -0
  416. package/drizzle/meta/0006_snapshot.json +998 -0
  417. package/drizzle/meta/0007_snapshot.json +1029 -0
  418. package/drizzle/meta/0008_snapshot.json +1049 -0
  419. package/drizzle/meta/0009_snapshot.json +1121 -0
  420. package/drizzle/meta/0010_snapshot.json +1121 -0
  421. package/drizzle/meta/0011_snapshot.json +1136 -0
  422. package/drizzle/meta/0012_snapshot.json +1227 -0
  423. package/drizzle/meta/0013_snapshot.json +1247 -0
  424. package/drizzle/meta/0014_snapshot.json +1267 -0
  425. package/drizzle/meta/0015_snapshot.json +1275 -0
  426. package/drizzle/meta/0016_snapshot.json +1371 -0
  427. package/drizzle/meta/0017_snapshot.json +1392 -0
  428. package/drizzle/meta/0018_snapshot.json +1603 -0
  429. package/drizzle/meta/0019_snapshot.json +1713 -0
  430. package/drizzle/meta/0020_snapshot.json +1904 -0
  431. package/drizzle/meta/0021_snapshot.json +2186 -0
  432. package/drizzle/meta/0022_snapshot.json +2311 -0
  433. package/drizzle/meta/0023_snapshot.json +2311 -0
  434. package/drizzle/meta/0024_snapshot.json +2318 -0
  435. package/drizzle/meta/0025_snapshot.json +2326 -0
  436. package/drizzle/meta/0026_snapshot.json +2333 -0
  437. package/drizzle/meta/0027_snapshot.json +2340 -0
  438. package/drizzle/meta/0028_snapshot.json +2340 -0
  439. package/drizzle/meta/_journal.json +209 -0
  440. package/package.json +106 -4
  441. package/skills/dashboard-building/SKILL.md +201 -0
  442. package/skills/patty-tour/SKILL.md +34 -0
  443. package/ui/app.css +758 -0
  444. package/ui/app.js +543 -0
  445. package/ui/connect-result.html +16 -0
  446. package/ui/connect.html +53 -0
  447. package/ui/dashboards/accounts.html +3189 -0
  448. package/ui/dashboards/budget.html +1734 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2475 -0
  452. package/ui/dashboards/dashboards.html +839 -0
  453. package/ui/dashboards/overview.html +2405 -0
  454. package/ui/dashboards/pending.html +2973 -0
  455. package/ui/dashboards/projections.html +2528 -0
  456. package/ui/dashboards/tags.html +1365 -0
  457. package/ui/invite.html +44 -0
  458. package/ui/login.html +26 -0
  459. package/ui/money.js +175 -0
  460. package/ui/setup.html +29 -0
  461. package/ui/shell.html +96 -0
  462. package/ui/token-created.html +24 -0
  463. package/ui/tokens.html +58 -0
  464. package/ui/user-invited.html +27 -0
  465. package/ui/users.html +60 -0
@@ -0,0 +1,8 @@
1
+ import { and, eq, isNull, or, sql } from 'drizzle-orm';
2
+ const column = (alias, name) => sql.raw(alias ? `${alias}.${name}` : name);
3
+ export const ownedBy = (userId, alias = '') => sql `${column(alias, 'user_id')} = ${userId}`;
4
+ export const visibleTo = (userId, alias = '') => sql `(${column(alias, 'user_id')} = ${userId} OR ${column(alias, 'user_id')} IS NULL)`;
5
+ export const ownedRows = (userIdColumn, userId) => eq(userIdColumn, userId);
6
+ export const visibleRows = (userIdColumn, userId) => or(eq(userIdColumn, userId), isNull(userIdColumn));
7
+ export const ownedWhere = (userIdColumn, userId, where) => (where ? and(ownedRows(userIdColumn, userId), where) : ownedRows(userIdColumn, userId));
8
+ export const visibleWhere = (userIdColumn, userId, where) => (where ? and(visibleRows(userIdColumn, userId), where) : visibleRows(userIdColumn, userId));
@@ -0,0 +1,26 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { ownedBy } from './scope.js';
3
+ /**
4
+ * Full transaction SELECT with all LEFT JOINs for name resolution and tag aggregation.
5
+ * Shared by transactionsRepo and billsRepo so a joined column added in one place is
6
+ * never missed in the other — both produce rows decoded by adapters/transactions.ts.
7
+ * Always confined to `userId`'s transactions: the predicate is part of the SELECT, so no caller can leave it out.
8
+ */
9
+ export const fullTxSelect = (userId, whereClause) => sql `
10
+ SELECT t.*,
11
+ fa.name AS from_account_name, ta.name AS to_account_name,
12
+ cc.name AS credit_card_name,
13
+ c.name AS category_name, c.names AS category_names,
14
+ sc.name AS subcategory_name, sc.names AS subcategory_names,
15
+ json_group_array(tg.name) FILTER (WHERE tg.name IS NOT NULL) AS tags
16
+ FROM transactions t
17
+ LEFT JOIN accounts fa ON fa.id = t.from_account_id
18
+ LEFT JOIN accounts ta ON ta.id = t.to_account_id
19
+ LEFT JOIN credit_cards cc ON cc.id = t.credit_card_id
20
+ LEFT JOIN categories c ON c.id = t.category_id
21
+ LEFT JOIN categories sc ON sc.id = t.subcategory_id
22
+ LEFT JOIN transaction_tags tt ON tt.transaction_id = t.id
23
+ LEFT JOIN tags tg ON tg.id = tt.tag_id
24
+ WHERE ${ownedBy(userId, 't')} AND (${whereClause})
25
+ GROUP BY t.id
26
+ `;
@@ -0,0 +1,13 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { TransactionStatus, TransactionType } from '../../../models/transaction.js';
3
+ const col = (alias, name) => sql.raw(alias ? `${alias}.${name}` : name);
4
+ /** Transaction "what counts" predicates (ADR-028) — the single home for effective/pending/
5
+ * committed/expense/non-transfer, composed by any transaction-domain query instead of raw SQL.
6
+ * `alias` qualifies the column for a joined/aliased query; defaults to `'t'`. */
7
+ export const txPredicates = {
8
+ effective: (alias = 't') => sql `${col(alias, 'status')} = ${TransactionStatus.enum.effective}`,
9
+ pending: (alias = 't') => sql `${col(alias, 'status')} = ${TransactionStatus.enum.pending}`,
10
+ committed: (alias = 't') => sql `${col(alias, 'status')} IN (${TransactionStatus.enum.effective}, ${TransactionStatus.enum.pending})`,
11
+ expense: (alias = 't') => sql `${col(alias, 'type')} = ${TransactionType.enum.expense}`,
12
+ nonTransfer: (alias = 't') => sql `${col(alias, 'type')} != ${TransactionType.enum.transfer}`,
13
+ };
@@ -0,0 +1,27 @@
1
+ import { and, desc, eq } from 'drizzle-orm';
2
+ import * as accessTokenAdapters from '../../../adapters/access-tokens.js';
3
+ import { accessTokens } from '../schema.js';
4
+ import { versionedTableApplier } from '../effects.js';
5
+ export const accessTokensRepo = (db) => ({
6
+ findByTokenHash: async (tokenHash) => {
7
+ const [row] = await db.select().from(accessTokens).where(eq(accessTokens.tokenHash, tokenHash)).limit(1);
8
+ return row ? accessTokenAdapters.dbToModel(row) : null;
9
+ },
10
+ findById: async (userId, id) => {
11
+ const [row] = await db
12
+ .select()
13
+ .from(accessTokens)
14
+ .where(and(eq(accessTokens.id, id), eq(accessTokens.userId, userId)))
15
+ .limit(1);
16
+ return row ? accessTokenAdapters.dbToModel(row) : null;
17
+ },
18
+ listByUser: async (userId) => {
19
+ const rows = await db
20
+ .select()
21
+ .from(accessTokens)
22
+ .where(eq(accessTokens.userId, userId))
23
+ .orderBy(desc(accessTokens.createdAt));
24
+ return rows.map(accessTokenAdapters.dbToModel);
25
+ },
26
+ });
27
+ export const accessTokenApplier = versionedTableApplier(accessTokens);
@@ -0,0 +1,91 @@
1
+ import { eq, sql } from 'drizzle-orm';
2
+ import * as accountAdapters from '../../../adapters/accounts.js';
3
+ import { TransactionStatus, TransactionType } from '../../../models/transaction.js';
4
+ import { BalancePartsRow } from '../../../wire/db/accounts.js';
5
+ import { accounts, creditCards, recurringRules, transactions } from '../schema.js';
6
+ import { ownedTableApplier } from '../effects.js';
7
+ import { ownedBy, ownedWhere } from '../queries/scope.js';
8
+ const list = async ({ db, userId }) => {
9
+ const rows = await db.select().from(accounts).where(ownedWhere(accounts.userId, userId)).orderBy(accounts.name);
10
+ return rows.map(accountAdapters.dbToModel);
11
+ };
12
+ const findById = async ({ db, userId }, id) => {
13
+ const rows = await db
14
+ .select()
15
+ .from(accounts)
16
+ .where(ownedWhere(accounts.userId, userId, sql `${accounts.id} = ${id}`))
17
+ .limit(1);
18
+ return rows[0] ? accountAdapters.dbToModel(rows[0]) : null;
19
+ };
20
+ const findByName = async ({ db, userId }, name) => {
21
+ const rows = await db
22
+ .select()
23
+ .from(accounts)
24
+ .where(ownedWhere(accounts.userId, userId, sql `lower(${accounts.name}) = lower(${name})`))
25
+ .limit(1);
26
+ return rows[0] ? accountAdapters.dbToModel(rows[0]) : null;
27
+ };
28
+ const findRawById = async ({ db, userId }, id) => {
29
+ const rows = await db
30
+ .select()
31
+ .from(accounts)
32
+ .where(ownedWhere(accounts.userId, userId, sql `${accounts.id} = ${id}`))
33
+ .limit(1);
34
+ return rows[0] ? accountAdapters.dbToEntity(rows[0]) : null;
35
+ };
36
+ const balanceParts = async ({ db, userId }, accountId) => {
37
+ const [row] = await db.all(sql `
38
+ SELECT
39
+ COALESCE(SUM(CASE WHEN t.type = ${TransactionType.enum.income} THEN t.amount ELSE 0 END), 0) AS income,
40
+ COALESCE(SUM(CASE WHEN t.type = ${TransactionType.enum.expense} THEN t.amount ELSE 0 END), 0) AS expenses,
41
+ COALESCE(SUM(CASE WHEN t.type = ${TransactionType.enum.transfer} THEN t.amount ELSE 0 END), 0) AS transfers_out,
42
+ COALESCE((
43
+ SELECT SUM(t2.amount) FROM transactions t2
44
+ WHERE ${ownedBy(userId, 't2')}
45
+ AND t2.to_account_id = ${accountId}
46
+ AND t2.type = ${TransactionType.enum.transfer}
47
+ AND t2.status = ${TransactionStatus.enum.effective}
48
+ ), 0) AS transfers_in
49
+ FROM transactions t
50
+ WHERE ${ownedBy(userId, 't')}
51
+ AND t.from_account_id = ${accountId}
52
+ AND t.status = ${TransactionStatus.enum.effective}
53
+ `);
54
+ return BalancePartsRow.parse({
55
+ income: row?.income ?? 0,
56
+ expenses: row?.expenses ?? 0,
57
+ transfersIn: row?.transfers_in ?? 0,
58
+ transfersOut: row?.transfers_out ?? 0,
59
+ });
60
+ };
61
+ const countReferences = async ({ db, userId }, accountId) => {
62
+ const [txRow] = await db
63
+ .select({ count: sql `count(*)` })
64
+ .from(transactions)
65
+ .where(ownedWhere(transactions.userId, userId, sql `(${transactions.fromAccountId} = ${accountId} OR ${transactions.toAccountId} = ${accountId})`));
66
+ const [recRow] = await db
67
+ .select({ count: sql `count(*)` })
68
+ .from(recurringRules)
69
+ .where(ownedWhere(recurringRules.userId, userId, eq(recurringRules.accountId, accountId)));
70
+ const [cardRow] = await db
71
+ .select({ count: sql `count(*)` })
72
+ .from(creditCards)
73
+ .where(ownedWhere(creditCards.userId, userId, eq(creditCards.paymentAccountId, accountId)));
74
+ return {
75
+ transactions: txRow?.count ?? 0,
76
+ recurring: recRow?.count ?? 0,
77
+ cards: cardRow?.count ?? 0,
78
+ };
79
+ };
80
+ export const accountsRepo = (db, userId) => {
81
+ const scope = { db, userId };
82
+ return {
83
+ list: () => list(scope),
84
+ findById: (id) => findById(scope, id),
85
+ findByName: (name) => findByName(scope, name),
86
+ findRawById: (id) => findRawById(scope, id),
87
+ balanceParts: (accountId) => balanceParts(scope, accountId),
88
+ countReferences: (accountId) => countReferences(scope, accountId),
89
+ };
90
+ };
91
+ export const accountApplier = (userId) => ownedTableApplier(accounts, userId);
@@ -0,0 +1,93 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import * as R from 'remeda';
3
+ import { z } from 'zod';
4
+ import * as transactionAdapters from '../../../adapters/transactions.js';
5
+ import { RawBillSchema } from '../../../models/bill.js';
6
+ import { BillRowSchema } from '../../../wire/db/bills.js';
7
+ import { bills } from '../schema.js';
8
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
9
+ import { fullTxSelect } from '../queries/transaction-select.js';
10
+ import { VersionConflict, ownedTableApplier } from '../effects.js';
11
+ import { ownedBy } from '../queries/scope.js';
12
+ /** Includes `creditCardId`/`version` — for the FC/IS credit-card transaction flows' own
13
+ * read-decide step, which needs them to build a `Persistable`. Every other caller uses `toBill`
14
+ * (below), which never lets those internal fields exist on the returned object in the first
15
+ * place — there is no wire/out zod parsing on the bill read paths to strip them later. */
16
+ const toRawBill = (record) => {
17
+ const row = BillRowSchema.parse(record);
18
+ return RawBillSchema.parse({
19
+ id: row.id,
20
+ creditCardId: row.credit_card_id,
21
+ month: row.month,
22
+ year: row.year,
23
+ closeDate: row.close_date,
24
+ dueDate: row.due_date,
25
+ status: row.status,
26
+ paymentTransactionId: row.payment_transaction_id ?? undefined,
27
+ version: row.version,
28
+ });
29
+ };
30
+ const toBill = (record) => R.omit(toRawBill(record), ['creditCardId', 'version']);
31
+ const fetchBillRow = async (db, userId, billId) => {
32
+ const [row] = await db.all(sql `SELECT * FROM bills WHERE ${ownedBy(userId)} AND id = ${billId}`);
33
+ return row;
34
+ };
35
+ // The bill-with-card SELECT also returns the joined card name.
36
+ const cardNameOf = (record) => z.object({ card_name: z.string() }).parse(record).card_name;
37
+ export const billsRepo = (db, userId) => ({
38
+ get: async (cardId, month, year) => {
39
+ const [billRow] = await db.all(sql `
40
+ SELECT b.*, cc.name AS card_name
41
+ FROM bills b JOIN credit_cards cc ON cc.id = b.credit_card_id
42
+ WHERE ${ownedBy(userId, 'b')} AND b.credit_card_id = ${cardId} AND b.month = ${month} AND b.year = ${year}
43
+ `);
44
+ if (!billRow)
45
+ return null;
46
+ const bill = toBill(billRow);
47
+ const txRows = await db.all(sql `
48
+ ${fullTxSelect(userId, sql `t.bill_id = ${bill.id}`)}
49
+ ORDER BY t.date
50
+ `);
51
+ return {
52
+ bill,
53
+ cardName: cardNameOf(billRow),
54
+ transactions: txRows.map(transactionAdapters.dbToModel),
55
+ };
56
+ },
57
+ findByCycle: async (cardId, month, year) => {
58
+ const [row] = await db.all(sql `
59
+ SELECT * FROM bills WHERE ${ownedBy(userId)} AND credit_card_id = ${cardId} AND month = ${month} AND year = ${year}
60
+ `);
61
+ return row ? toRawBill(row) : null;
62
+ },
63
+ findById: async (billId) => {
64
+ const row = await fetchBillRow(db, userId, billId);
65
+ return row ? toRawBill(row) : null;
66
+ },
67
+ findAllByCard: async (cardId) => {
68
+ const rows = await db.all(sql `SELECT * FROM bills WHERE ${ownedBy(userId)} AND credit_card_id = ${cardId}`);
69
+ return rows.map(toRawBill);
70
+ },
71
+ });
72
+ const versionedBillApplier = (userId) => ownedTableApplier(bills, userId);
73
+ /** A bill is created by cycle (`UNIQUE(creditCardId, month, year)`), not by `id`, so a concurrent
74
+ * first purchase on the same cycle can raise a real unique-constraint error that
75
+ * `versionedTableApplier`'s id-scoped `onConflictDoNothing` doesn't swallow. Rethrown as
76
+ * `VersionConflict` to roll back and retry the flow instead of surfacing a raw 500 or a
77
+ * wrong-id no-op. `update`/`delete` stay plain. */
78
+ export const billApplier = (userId) => {
79
+ const applier = versionedBillApplier(userId);
80
+ return {
81
+ ...applier,
82
+ insert: async (tx, model) => {
83
+ try {
84
+ return await applier.insert(tx, model);
85
+ }
86
+ catch (cause) {
87
+ if (isUniqueConstraintViolation(cause))
88
+ throw new VersionConflict();
89
+ throw cause;
90
+ }
91
+ },
92
+ };
93
+ };
@@ -0,0 +1,72 @@
1
+ import { and, eq, sql } from 'drizzle-orm';
2
+ import * as budgetAdapters from '../../../adapters/budgets.js';
3
+ import { BudgetViewRowSchema } from '../../../wire/db/budgets.js';
4
+ import { budgets } from '../schema.js';
5
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
6
+ import { VersionConflict, ownedTableApplier } from '../effects.js';
7
+ import { ownedBy, ownedWhere } from '../queries/scope.js';
8
+ // Budgets target either a top-level category or a sub-category — both rows in `categories` — so
9
+ // the display projection always joins the node plus its (possibly absent) parent. Mirrors
10
+ // `subCategoriesRepo`'s `SUB_SELECT` (`diplomat/db/repos/sub-categories.ts`): a hand-written raw
11
+ // join, not the query builder, for the same self-referencing-table reason. `node.names`/
12
+ // `parent.names` travel alongside the raw names so the repo itself never has to decide a locale.
13
+ // `node.id` (== `b.category_id`) travels too as `target_id`, needed to match spend against it in
14
+ // `logic/budget.ts` now that this repo no longer joins `transactions` (ADR-028).
15
+ const BUDGET_VIEW_SELECT = (userId) => sql `
16
+ SELECT b.id, b.currency, b.limit_amount, b.period, b.version, node.id AS target_id,
17
+ node.name AS node_name, node.names AS node_names, node.parent_id AS node_parent_id,
18
+ parent.name AS parent_name, parent.names AS parent_names
19
+ FROM budgets b
20
+ JOIN categories node ON node.id = b.category_id
21
+ LEFT JOIN categories parent ON parent.id = node.parent_id
22
+ WHERE ${ownedBy(userId, 'b')}
23
+ `;
24
+ export const budgetsRepo = (db, userId) => ({
25
+ list: async () => {
26
+ const rows = await db.all(sql `
27
+ ${BUDGET_VIEW_SELECT(userId)}
28
+ ORDER BY COALESCE(parent.name, node.name), node.name
29
+ `);
30
+ return rows.map((r) => BudgetViewRowSchema.parse(r));
31
+ },
32
+ findByTarget: async (categoryId, currency, period) => {
33
+ const [row] = await db
34
+ .select({ id: budgets.id })
35
+ .from(budgets)
36
+ .where(ownedWhere(budgets.userId, userId, and(eq(budgets.categoryId, categoryId), eq(budgets.currency, currency), eq(budgets.period, period))))
37
+ .limit(1);
38
+ return row !== undefined;
39
+ },
40
+ findById: async (id) => {
41
+ const [row] = await db
42
+ .select()
43
+ .from(budgets)
44
+ .where(ownedWhere(budgets.userId, userId, eq(budgets.id, id)))
45
+ .limit(1);
46
+ return row ? budgetAdapters.dbToEntity(row) : null;
47
+ },
48
+ });
49
+ const versionedBudgetApplier = (userId) => ownedTableApplier(budgets, userId);
50
+ /** `budgets` has the secondary `UNIQUE(category_id, currency, period)` beyond `createBudget`'s
51
+ * own pre-check (`findByTarget`, which only guards the common case) — a concurrent create of the
52
+ * same target races into a real `SQLITE_CONSTRAINT_UNIQUE` the id-scoped `onConflictDoNothing`
53
+ * doesn't swallow. Recognized and rethrown as `VersionConflict`, rolling back and retrying — the
54
+ * retry's own `findByTarget` then sees the committed row and returns `duplicate_budget` instead of
55
+ * a raw 500. Structurally identical to `tagApplier`/`billApplier` (`update`/`delete` stay plain —
56
+ * neither touches the target/currency/period key). */
57
+ export const budgetApplier = (userId) => {
58
+ const applier = versionedBudgetApplier(userId);
59
+ return {
60
+ ...applier,
61
+ insert: async (tx, model) => {
62
+ try {
63
+ return await applier.insert(tx, model);
64
+ }
65
+ catch (cause) {
66
+ if (isUniqueConstraintViolation(cause))
67
+ throw new VersionConflict();
68
+ throw cause;
69
+ }
70
+ },
71
+ };
72
+ };
@@ -0,0 +1,53 @@
1
+ import { eq, isNull, sql } from 'drizzle-orm';
2
+ import * as categoryAdapters from '../../../adapters/categories.js';
3
+ import { categories, recurringRules, transactions } from '../schema.js';
4
+ import { ownedTableApplier } from '../effects.js';
5
+ import { ownedWhere, visibleWhere } from '../queries/scope.js';
6
+ const list = async ({ db, userId }, options) => {
7
+ const query = db
8
+ .select()
9
+ .from(categories)
10
+ .where(visibleWhere(categories.userId, userId, isNull(categories.parentId)));
11
+ const rows = options?.orderBy === 'name' ? await query.orderBy(categories.name) : await query;
12
+ return rows.map(categoryAdapters.dbToModel);
13
+ };
14
+ const countReferences = async ({ db, userId }, categoryId) => {
15
+ const [byCat] = await db
16
+ .select({ count: sql `count(*)` })
17
+ .from(transactions)
18
+ .where(ownedWhere(transactions.userId, userId, eq(transactions.categoryId, categoryId)));
19
+ const [bySub] = await db
20
+ .select({ count: sql `count(*)` })
21
+ .from(transactions)
22
+ .where(ownedWhere(transactions.userId, userId, eq(transactions.subcategoryId, categoryId)));
23
+ const [recRow] = await db
24
+ .select({ count: sql `count(*)` })
25
+ .from(recurringRules)
26
+ .where(ownedWhere(recurringRules.userId, userId, eq(recurringRules.categoryId, categoryId)));
27
+ const [subRow] = await db
28
+ .select({ count: sql `count(*)` })
29
+ .from(categories)
30
+ .where(visibleWhere(categories.userId, userId, eq(categories.parentId, categoryId)));
31
+ return {
32
+ transactions: (byCat?.count ?? 0) + (bySub?.count ?? 0),
33
+ recurring: recRow?.count ?? 0,
34
+ subCategories: subRow?.count ?? 0,
35
+ };
36
+ };
37
+ const findRawById = async ({ db, userId }, categoryId) => {
38
+ const [row] = await db
39
+ .select({ id: categories.id, version: categories.version, userId: categories.userId })
40
+ .from(categories)
41
+ .where(visibleWhere(categories.userId, userId, eq(categories.id, categoryId)))
42
+ .limit(1);
43
+ return row ? { id: row.id, version: row.version, shared: row.userId === null } : null;
44
+ };
45
+ export const categoriesRepo = (db, userId) => {
46
+ const scope = { db, userId };
47
+ return {
48
+ list: (options) => list(scope, options),
49
+ countReferences: (categoryId) => countReferences(scope, categoryId),
50
+ findRawById: (categoryId) => findRawById(scope, categoryId),
51
+ };
52
+ };
53
+ export const categoryApplier = (userId) => ownedTableApplier(categories, userId);
@@ -0,0 +1,67 @@
1
+ import { and, desc, eq, lte, ne } from 'drizzle-orm';
2
+ import * as clientGrantAdapters from '../../../adapters/client-grants.js';
3
+ import { GrantStatus } from '../../../models/auth/grant.js';
4
+ import { clientGrants } from '../schema.js';
5
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
6
+ import { VersionConflict, versionedTableApplier } from '../effects.js';
7
+ const findByDeviceCodeHash = async (db, deviceCodeHash) => {
8
+ const [row] = await db.select().from(clientGrants).where(eq(clientGrants.deviceCodeHash, deviceCodeHash)).limit(1);
9
+ return row ? clientGrantAdapters.dbToModel(row) : null;
10
+ };
11
+ const findPendingByUserCode = async (db, userCode) => {
12
+ const [row] = await db
13
+ .select()
14
+ .from(clientGrants)
15
+ .where(and(eq(clientGrants.userCode, userCode), eq(clientGrants.status, GrantStatus.enum.pending)))
16
+ .limit(1);
17
+ return row ? clientGrantAdapters.dbToModel(row) : null;
18
+ };
19
+ const lastRedeemed = async (db, userId, profile, clientName) => {
20
+ const [row] = await db
21
+ .select()
22
+ .from(clientGrants)
23
+ .where(and(eq(clientGrants.userId, userId), eq(clientGrants.profile, profile), eq(clientGrants.clientName, clientName), eq(clientGrants.status, GrantStatus.enum.redeemed)))
24
+ .orderBy(desc(clientGrants.approvedAt), desc(clientGrants.id))
25
+ .limit(1);
26
+ return row ? clientGrantAdapters.dbToModel(row) : null;
27
+ };
28
+ const listApprovedByUser = async (db, userId) => {
29
+ const rows = await db
30
+ .select()
31
+ .from(clientGrants)
32
+ .where(and(eq(clientGrants.userId, userId), eq(clientGrants.status, GrantStatus.enum.approved)));
33
+ return rows.map(clientGrantAdapters.dbToModel);
34
+ };
35
+ const listRedeemed = async (db) => {
36
+ const rows = await db.select().from(clientGrants).where(eq(clientGrants.status, GrantStatus.enum.redeemed));
37
+ return rows.map(clientGrantAdapters.dbToModel);
38
+ };
39
+ const listExpired = async (db, nowIso) => {
40
+ const rows = await db
41
+ .select()
42
+ .from(clientGrants)
43
+ .where(and(lte(clientGrants.expiresAt, nowIso), ne(clientGrants.status, GrantStatus.enum.redeemed)));
44
+ return rows.map(clientGrantAdapters.dbToModel);
45
+ };
46
+ export const clientGrantsRepo = (db) => ({
47
+ findByDeviceCodeHash: (deviceCodeHash) => findByDeviceCodeHash(db, deviceCodeHash),
48
+ findPendingByUserCode: (userCode) => findPendingByUserCode(db, userCode),
49
+ lastRedeemed: (userId, profile, clientName) => lastRedeemed(db, userId, profile, clientName),
50
+ listApprovedByUser: (userId) => listApprovedByUser(db, userId),
51
+ listRedeemed: () => listRedeemed(db),
52
+ listExpired: (nowIso) => listExpired(db, nowIso),
53
+ });
54
+ const versionedClientGrantApplier = versionedTableApplier(clientGrants);
55
+ export const clientGrantApplier = {
56
+ ...versionedClientGrantApplier,
57
+ insert: async (tx, model, idempotencyKey) => {
58
+ try {
59
+ return await versionedClientGrantApplier.insert(tx, model, idempotencyKey);
60
+ }
61
+ catch (cause) {
62
+ if (isUniqueConstraintViolation(cause))
63
+ throw new VersionConflict();
64
+ throw cause;
65
+ }
66
+ },
67
+ };
@@ -0,0 +1,66 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { TransactionStatus, TransactionType } from '../../../models/transaction.js';
3
+ import { MerchantSpendDbRowSchema, RecurringCandidateDbRowSchema, SpendingShiftDbRowSchema, } from '../../../wire/db/correlations.js';
4
+ import { ownedBy } from '../queries/scope.js';
5
+ /** One conditional-SUM pass splits `[baselineFrom, currentTo)` into `current`/`baseline_total` —
6
+ * covers a category present in only one window (brand-new or dropped) without a `FULL OUTER JOIN`
7
+ * (unsupported in SQLite). The `JOIN` (not `LEFT JOIN`) excludes uncategorized transactions; a
8
+ * sub-category transaction's `category_id` is always its parent's, so sub-category spend rolls up
9
+ * for free. */
10
+ const SPENDING_SHIFTS_SELECT = (userId, baselineFrom, currentFrom, currentTo) => sql `
11
+ SELECT c.name AS category, c.names AS category_names, t.currency,
12
+ SUM(CASE WHEN t.date >= ${currentFrom} THEN t.amount ELSE 0 END) AS current,
13
+ SUM(CASE WHEN t.date < ${currentFrom} THEN t.amount ELSE 0 END) AS baseline_total
14
+ FROM transactions t
15
+ JOIN categories c ON c.id = t.category_id
16
+ WHERE ${ownedBy(userId, 't')}
17
+ AND t.date >= ${baselineFrom} AND t.date < ${currentTo}
18
+ AND t.status = ${TransactionStatus.enum.effective}
19
+ AND t.type = ${TransactionType.enum.expense}
20
+ GROUP BY t.currency, c.id
21
+ `;
22
+ /** Per-merchant spend within `[from, to)`, optionally narrowed to one category. `categoryId`
23
+ * binds as a parameter when present; the fragment is empty (no string-built clause) when absent,
24
+ * so caller text never reaches the query shape itself. */
25
+ const MERCHANT_CONCENTRATION_SELECT = (userId, from, to, categoryId) => sql `
26
+ SELECT c.name AS category, c.names AS category_names, t.currency, t.merchant_key, SUM(t.amount) AS spent
27
+ FROM transactions t
28
+ JOIN categories c ON c.id = t.category_id
29
+ WHERE ${ownedBy(userId, 't')}
30
+ AND t.date >= ${from} AND t.date < ${to}
31
+ AND t.status = ${TransactionStatus.enum.effective}
32
+ AND t.type = ${TransactionType.enum.expense}
33
+ ${categoryId ? sql `AND t.category_id = ${categoryId}` : sql ``}
34
+ GROUP BY t.currency, c.id, t.merchant_key
35
+ `;
36
+ /** Not pre-aggregated, unlike the queries above — cadence detection needs individual dates/amounts.
37
+ * The exclusion subquery's `IS NOT NULL` matters: `NOT IN` against a subquery that can return NULL
38
+ * would silently match nothing. */
39
+ const RECURRING_CANDIDATES_SELECT = (userId, from, today) => sql `
40
+ SELECT t.merchant_key, t.currency, c.name AS category, c.names AS category_names, t.date, t.amount
41
+ FROM transactions t
42
+ JOIN categories c ON c.id = t.category_id
43
+ WHERE ${ownedBy(userId, 't')}
44
+ AND t.date >= ${from} AND t.date <= ${today}
45
+ AND t.status = ${TransactionStatus.enum.effective}
46
+ AND t.type = ${TransactionType.enum.expense}
47
+ AND t.merchant_key IS NOT NULL
48
+ AND t.merchant_key NOT IN (
49
+ SELECT merchant_key FROM recurring_rules WHERE merchant_key IS NOT NULL AND ${ownedBy(userId)}
50
+ )
51
+ ORDER BY t.merchant_key, t.currency, t.date
52
+ `;
53
+ export const correlationsRepo = (db, userId) => ({
54
+ spendingShifts: async (baselineFrom, currentFrom, currentTo) => {
55
+ const rows = await db.all(SPENDING_SHIFTS_SELECT(userId, baselineFrom, currentFrom, currentTo));
56
+ return rows.map((r) => SpendingShiftDbRowSchema.parse(r));
57
+ },
58
+ merchantConcentration: async (from, to, categoryId) => {
59
+ const rows = await db.all(MERCHANT_CONCENTRATION_SELECT(userId, from, to, categoryId));
60
+ return rows.map((r) => MerchantSpendDbRowSchema.parse(r));
61
+ },
62
+ recurringCandidates: async (from, today) => {
63
+ const rows = await db.all(RECURRING_CANDIDATES_SELECT(userId, from, today));
64
+ return rows.map((r) => RecurringCandidateDbRowSchema.parse(r));
65
+ },
66
+ });
@@ -0,0 +1,67 @@
1
+ import { eq, sql } from 'drizzle-orm';
2
+ import * as creditCardAdapters from '../../../adapters/credit-cards.js';
3
+ import { CreditCardSchema } from '../../../models/credit-card.js';
4
+ import { creditCards } from '../schema.js';
5
+ import { ownedTableApplier } from '../effects.js';
6
+ import { ownedBy, ownedWhere } from '../queries/scope.js';
7
+ import { correlatedToCard } from './transactions.js';
8
+ const toCard = (row) => CreditCardSchema.parse({
9
+ id: row.id,
10
+ name: row.name,
11
+ currency: row.currency,
12
+ closingDay: row.closingDay,
13
+ dueDay: row.dueDay,
14
+ limit: row.limitAmount ?? undefined,
15
+ accountId: row.accountId,
16
+ paymentAccountId: row.paymentAccountId ?? undefined,
17
+ });
18
+ const list = async ({ db, userId }) => {
19
+ const rows = await db
20
+ .select()
21
+ .from(creditCards)
22
+ .where(ownedWhere(creditCards.userId, userId))
23
+ .orderBy(creditCards.name);
24
+ return rows.map(toCard);
25
+ };
26
+ const findByName = async ({ db, userId }, name) => {
27
+ const rows = await db
28
+ .select()
29
+ .from(creditCards)
30
+ .where(ownedWhere(creditCards.userId, userId, sql `lower(${creditCards.name}) = lower(${name})`))
31
+ .limit(1);
32
+ return rows[0] ? toCard(rows[0]) : null;
33
+ };
34
+ const findById = async ({ db, userId }, id) => {
35
+ const rows = await db
36
+ .select()
37
+ .from(creditCards)
38
+ .where(ownedWhere(creditCards.userId, userId, eq(creditCards.id, id)))
39
+ .limit(1);
40
+ return rows[0] ? toCard(rows[0]) : null;
41
+ };
42
+ const findRawById = async ({ db, userId }, id) => {
43
+ const rows = await db
44
+ .select()
45
+ .from(creditCards)
46
+ .where(ownedWhere(creditCards.userId, userId, eq(creditCards.id, id)))
47
+ .limit(1);
48
+ return rows[0] ? creditCardAdapters.dbToEntity(rows[0]) : null;
49
+ };
50
+ const countCorrelated = async ({ db, userId }, cardId, accountId) => {
51
+ const [txRow] = await db.all(sql `SELECT COUNT(*) as count FROM transactions WHERE ${ownedBy(userId)} AND (${correlatedToCard(cardId, accountId)})`);
52
+ const [billRow] = await db.all(sql `
53
+ SELECT COUNT(*) as count FROM bills WHERE ${ownedBy(userId)} AND credit_card_id = ${cardId}
54
+ `);
55
+ return { transactions: txRow?.count ?? 0, bills: billRow?.count ?? 0 };
56
+ };
57
+ export const creditCardsRepo = (db, userId) => {
58
+ const scope = { db, userId };
59
+ return {
60
+ list: () => list(scope),
61
+ findByName: (name) => findByName(scope, name),
62
+ findById: (id) => findById(scope, id),
63
+ findRawById: (id) => findRawById(scope, id),
64
+ countCorrelated: (cardId, accountId) => countCorrelated(scope, cardId, accountId),
65
+ };
66
+ };
67
+ export const creditCardApplier = (userId) => ownedTableApplier(creditCards, userId);
@@ -0,0 +1,8 @@
1
+ import * as currencyAdapters from '../../../adapters/currencies.js';
2
+ import { currencies } from '../schema.js';
3
+ export const currenciesRepo = (db) => ({
4
+ list: async () => {
5
+ const rows = await db.select().from(currencies).orderBy(currencies.code);
6
+ return rows.map(currencyAdapters.dbToModel);
7
+ },
8
+ });
@@ -0,0 +1,40 @@
1
+ import { and, eq } from 'drizzle-orm';
2
+ import * as currencyRateAdapters from '../../../adapters/currency-rates.js';
3
+ import { currencyRates } from '../schema.js';
4
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
5
+ import { VersionConflict, versionedTableApplier } from '../effects.js';
6
+ export const currencyRatesRepo = (db) => ({
7
+ list: async () => {
8
+ const rows = await db.select().from(currencyRates).orderBy(currencyRates.fromCode, currencyRates.toCode);
9
+ return rows.map(currencyRateAdapters.dbToEntity);
10
+ },
11
+ findByPair: async (from, to) => {
12
+ const [row] = await db
13
+ .select()
14
+ .from(currencyRates)
15
+ .where(and(eq(currencyRates.fromCode, from), eq(currencyRates.toCode, to)))
16
+ .limit(1);
17
+ return row ? currencyRateAdapters.dbToEntity(row) : null;
18
+ },
19
+ });
20
+ const versionedCurrencyRateApplier = versionedTableApplier(currencyRates);
21
+ /** `currency_rates` has the secondary `UNIQUE(from_code, to_code)` beyond `setExchangeRate`'s own
22
+ * pre-check (`findByPair`) — a concurrent upsert of the same pair races into a real
23
+ * `SQLITE_CONSTRAINT_UNIQUE` the id-scoped `onConflictDoNothing` doesn't swallow. Recognized and
24
+ * rethrown as `VersionConflict`, rolling back and retrying — the retry's own `findByPair` then
25
+ * sees the committed row and applies as an update instead of a duplicate insert (upsert-latest,
26
+ * ADR-026). Structurally identical to `budgetApplier` (`diplomat/db/repos/budgets.ts`), except a
27
+ * resolved "duplicate" here is never an error — it's the intended upsert-latest outcome. */
28
+ export const currencyRateApplier = {
29
+ ...versionedCurrencyRateApplier,
30
+ insert: async (tx, model) => {
31
+ try {
32
+ return await versionedCurrencyRateApplier.insert(tx, model);
33
+ }
34
+ catch (cause) {
35
+ if (isUniqueConstraintViolation(cause))
36
+ throw new VersionConflict();
37
+ throw cause;
38
+ }
39
+ },
40
+ };