@rfc0/patty 0.0.0-stage → 1.0.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 (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 +493 -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 +1716 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2464 -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 +2517 -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,123 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { resolve as resolvePath, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { and, eq, isNull, sql } from 'drizzle-orm';
5
+ import * as R from 'remeda';
6
+ import * as dashboardAdapters from '../../../adapters/dashboards.js';
7
+ import { DashboardSource, } from '../../../models/dashboard.js';
8
+ import { dashboards } from '../schema.js';
9
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
10
+ import { VersionConflict, ownedTableApplier } from '../effects.js';
11
+ import { ownedWhere, visibleRows, visibleWhere } from '../queries/scope.js';
12
+ export const UI_DASHBOARDS_ROOT = fileURLToPath(new URL('../../../../ui/dashboards', import.meta.url));
13
+ export const HTML_FILE_EXTENSION = '.html';
14
+ const fileContentCache = new Map();
15
+ const resolveDashboardFilePath = (path) => {
16
+ const resolved = resolvePath(UI_DASHBOARDS_ROOT, path);
17
+ if (resolved !== UI_DASHBOARDS_ROOT && !resolved.startsWith(UI_DASHBOARDS_ROOT + sep)) {
18
+ throw new Error(`dashboard file path escapes ui/dashboards/: ${path}`);
19
+ }
20
+ return resolved;
21
+ };
22
+ const readDashboardFile = async (path) => {
23
+ const resolved = resolveDashboardFilePath(path);
24
+ const cached = fileContentCache.get(resolved);
25
+ if (cached !== undefined)
26
+ return cached;
27
+ const content = await readFile(resolved, 'utf-8');
28
+ fileContentCache.set(resolved, content);
29
+ return content;
30
+ };
31
+ export const listDefaultDashboardFiles = async () => {
32
+ const entries = await readdir(UI_DASHBOARDS_ROOT, { withFileTypes: true });
33
+ return R.pipe(entries, R.filter((entry) => entry.isFile() && entry.name.endsWith(HTML_FILE_EXTENSION)), R.map((entry) => entry.name), R.sortBy(R.identity()));
34
+ };
35
+ const resolveHtml = (row) => {
36
+ if (row.source === DashboardSource.enum.file) {
37
+ if (row.path === null)
38
+ throw new Error(`dashboard source: file row is missing its path (invariant violation)`);
39
+ return readDashboardFile(row.path);
40
+ }
41
+ if (row.html === null)
42
+ throw new Error(`dashboard source: inline row is missing its html (invariant violation)`);
43
+ return Promise.resolve(row.html);
44
+ };
45
+ const visibleByName = async ({ db, userId }, name) => {
46
+ const [row] = await db
47
+ .select()
48
+ .from(dashboards)
49
+ .where(visibleWhere(dashboards.userId, userId, eq(dashboards.name, name)))
50
+ .orderBy(sql `${dashboards.userId} IS NULL`)
51
+ .limit(1);
52
+ return row;
53
+ };
54
+ const get = async (scope, name) => {
55
+ const row = await visibleByName(scope, name);
56
+ return row ? dashboardAdapters.dbToModel(row, await resolveHtml(row)) : null;
57
+ };
58
+ const findRefByName = async ({ db, userId }, name) => {
59
+ const [row] = await db
60
+ .select({ id: dashboards.id, version: dashboards.version })
61
+ .from(dashboards)
62
+ .where(ownedWhere(dashboards.userId, userId, eq(dashboards.name, name)))
63
+ .limit(1);
64
+ return row ?? null;
65
+ };
66
+ const isDefault = async ({ db }, name) => {
67
+ const [row] = await db
68
+ .select({ id: dashboards.id })
69
+ .from(dashboards)
70
+ .where(and(isNull(dashboards.userId), eq(dashboards.name, name)))
71
+ .limit(1);
72
+ return row !== undefined;
73
+ };
74
+ const findByName = async (scope, name) => {
75
+ const row = await visibleByName(scope, name);
76
+ return row ? dashboardAdapters.dbToEntity(row, await resolveHtml(row), row.userId === null) : null;
77
+ };
78
+ const list = async ({ db, userId }) => {
79
+ const own = db.select({ name: dashboards.name }).from(dashboards).where(ownedWhere(dashboards.userId, userId));
80
+ const rows = await db
81
+ .select({ name: dashboards.name, updatedAt: dashboards.updatedAt, source: dashboards.source })
82
+ .from(dashboards)
83
+ .where(and(visibleRows(dashboards.userId, userId), sql `(${dashboards.userId} IS NOT NULL OR ${dashboards.name} NOT IN (${own}))`))
84
+ .orderBy(dashboards.name);
85
+ return rows.map(dashboardAdapters.dbToListItem);
86
+ };
87
+ export const dashboardsRepo = (db, userId) => {
88
+ const scope = { db, userId };
89
+ return {
90
+ get: (name) => get(scope, name),
91
+ findRefByName: (name) => findRefByName(scope, name),
92
+ isDefault: (name) => isDefault(scope, name),
93
+ findByName: (name) => findByName(scope, name),
94
+ list: () => list(scope),
95
+ };
96
+ };
97
+ const versionedDashboardApplier = (userId) => ownedTableApplier(dashboards, userId);
98
+ export const dashboardApplier = (userId) => {
99
+ const applier = versionedDashboardApplier(userId);
100
+ return {
101
+ ...applier,
102
+ insert: async (tx, model) => {
103
+ try {
104
+ return await applier.insert(tx, model);
105
+ }
106
+ catch (cause) {
107
+ if (isUniqueConstraintViolation(cause))
108
+ throw new VersionConflict();
109
+ throw cause;
110
+ }
111
+ },
112
+ update: async (tx, model) => {
113
+ try {
114
+ return await applier.update(tx, model);
115
+ }
116
+ catch (cause) {
117
+ if (isUniqueConstraintViolation(cause))
118
+ throw new VersionConflict();
119
+ throw cause;
120
+ }
121
+ },
122
+ };
123
+ };
@@ -0,0 +1,12 @@
1
+ import { sql } from 'drizzle-orm';
2
+ export const healthRepo = (db) => ({
3
+ reachable: async () => {
4
+ try {
5
+ await db.all(sql `SELECT 1`);
6
+ return true;
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ },
12
+ });
@@ -0,0 +1,14 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import * as instanceSettingsAdapters from '../../../adapters/instance-settings.js';
3
+ import { INSTANCE_SETTINGS_ID } from '../../../models/auth/users.js';
4
+ import { settings } from '../schema.js';
5
+ import { versionedTableApplier } from '../effects.js';
6
+ export const instanceSettingsRepo = (db) => ({
7
+ get: async () => {
8
+ const [row] = await db.select().from(settings).where(eq(settings.id, INSTANCE_SETTINGS_ID)).limit(1);
9
+ if (!row)
10
+ throw new Error('instance settings: the singleton row is missing');
11
+ return instanceSettingsAdapters.dbToModel(row);
12
+ },
13
+ });
14
+ export const instanceSettingsApplier = versionedTableApplier(settings);
@@ -0,0 +1,58 @@
1
+ import { eq, isNotNull } from 'drizzle-orm';
2
+ import { INSTANCE_SETTINGS_ID } from '../../../models/auth/users.js';
3
+ import { OWNER_USER_ID } from '../../../models/auth/owner.js';
4
+ import { DemoCountry } from '../../../models/demo/core.js';
5
+ import { InstanceKind } from '../../../models/instance.js';
6
+ import { Locale } from '../../../models/locale.js';
7
+ import { accounts, bills, budgets, categories, creditCards, currencyRates, dashboards, merchantCategory, recurringRules, settings, tags, transactions, userSettings, } from '../schema.js';
8
+ const USER_DATA_TABLES = [
9
+ accounts,
10
+ creditCards,
11
+ bills,
12
+ transactions,
13
+ tags,
14
+ budgets,
15
+ recurringRules,
16
+ currencyRates,
17
+ ];
18
+ /** Tables whose rows are shared defaults (no owner) or a user's own: only the owned ones are user data. */
19
+ const SHARED_OR_OWNED_TABLES = [categories, dashboards];
20
+ export const instanceRepo = (db) => ({
21
+ kind: async () => {
22
+ const [row] = await db
23
+ .select({ kind: settings.instanceKind })
24
+ .from(settings)
25
+ .where(eq(settings.id, INSTANCE_SETTINGS_ID))
26
+ .limit(1);
27
+ return InstanceKind.parse(row?.kind);
28
+ },
29
+ country: async () => {
30
+ const [row] = await db
31
+ .select({ country: settings.demoCountry })
32
+ .from(settings)
33
+ .where(eq(settings.id, INSTANCE_SETTINGS_ID))
34
+ .limit(1);
35
+ return DemoCountry.nullable().parse(row?.country ?? null);
36
+ },
37
+ locale: async () => {
38
+ const [row] = await db
39
+ .select({ locale: userSettings.locale })
40
+ .from(userSettings)
41
+ .where(eq(userSettings.userId, OWNER_USER_ID))
42
+ .limit(1);
43
+ return Locale.catch(Locale.enum.en).parse(row?.locale);
44
+ },
45
+ hasUserData: async () => {
46
+ const found = await Promise.all([
47
+ ...USER_DATA_TABLES.map((table) => db.select({ id: table.id }).from(table).limit(1)),
48
+ ...SHARED_OR_OWNED_TABLES.map((table) => db.select({ id: table.id }).from(table).where(isNotNull(table.userId)).limit(1)),
49
+ // Merchant history has no `id`: its own projection; shared rules (no owner) are not user data.
50
+ db
51
+ .select({ key: merchantCategory.merchantKey })
52
+ .from(merchantCategory)
53
+ .where(isNotNull(merchantCategory.userId))
54
+ .limit(1),
55
+ ]);
56
+ return found.some((rows) => rows.length > 0);
57
+ },
58
+ });
@@ -0,0 +1,43 @@
1
+ import { and, desc, eq, isNull, lte } from 'drizzle-orm';
2
+ import * as inviteAdapters from '../../../adapters/invites.js';
3
+ import { invites } from '../schema.js';
4
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
5
+ import { VersionConflict, versionedTableApplier } from '../effects.js';
6
+ export const invitesRepo = (db) => ({
7
+ findByHash: async (codeHash) => {
8
+ const [row] = await db.select().from(invites).where(eq(invites.codeHash, codeHash)).limit(1);
9
+ return row ? inviteAdapters.dbToModel(row) : null;
10
+ },
11
+ listUnclaimed: async () => {
12
+ const rows = await db.select().from(invites).where(isNull(invites.usedAt)).orderBy(desc(invites.createdAt));
13
+ return rows.map(inviteAdapters.dbToModel);
14
+ },
15
+ listExpiredUnclaimed: async (nowIso) => {
16
+ const rows = await db
17
+ .select()
18
+ .from(invites)
19
+ .where(and(isNull(invites.usedAt), lte(invites.expiresAt, nowIso)));
20
+ return rows.map(inviteAdapters.dbToModel);
21
+ },
22
+ listUnclaimedByUser: async (userId) => {
23
+ const rows = await db.select().from(invites).where(eq(invites.userId, userId));
24
+ return rows.filter((row) => row.usedAt === null).map(inviteAdapters.dbToModel);
25
+ },
26
+ });
27
+ const versionedInviteApplier = versionedTableApplier(invites);
28
+ /** `invites_one_open_per_user` is unique among UNCLAIMED invites: two admins reissuing for the same user at once both
29
+ * insert one. The loser's unique violation is rethrown as `VersionConflict`, so the engine rolls back and re-runs the
30
+ * flow, which then sees (and replaces) the winner's invite. */
31
+ export const inviteApplier = {
32
+ ...versionedInviteApplier,
33
+ insert: async (tx, model, idempotencyKey) => {
34
+ try {
35
+ return await versionedInviteApplier.insert(tx, model, idempotencyKey);
36
+ }
37
+ catch (cause) {
38
+ if (isUniqueConstraintViolation(cause))
39
+ throw new VersionConflict();
40
+ throw cause;
41
+ }
42
+ },
43
+ };
@@ -0,0 +1,121 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { z } from 'zod';
3
+ import { ClassificationMethod } from '../../../models/transaction.js';
4
+ import { MerchantTopDbRowSchema } from '../../../wire/db/merchants.js';
5
+ import { merchantCategory, merchants } from '../schema.js';
6
+ import { ownedBy, visibleTo } from '../queries/scope.js';
7
+ import { txPredicates } from '../queries/tx-predicates.js';
8
+ const MatchRow = z.object({
9
+ merchantKey: z.string(),
10
+ categoryId: z.string(),
11
+ categoryName: z.string(),
12
+ weight: z.number(),
13
+ origin: z.enum([ClassificationMethod.enum.rule, ClassificationMethod.enum.history]),
14
+ });
15
+ /** The `limit` merchants with the most effective, non-transfer transactions, plus each one's
16
+ * dominant *classified* category (the category it's most often classified into, among those same
17
+ * transactions) — Feature Design 018. `merchant_totals` picks the merchants first, so
18
+ * `category_counts` only ever aggregates over that already-limited set; it excludes
19
+ * `category_id IS NULL` so an uncategorized transaction never outweighs a real category — a
20
+ * merchant with 2 classified "Food" and 5 uncategorized transactions must still resolve to
21
+ * "Food", not `null`. The dominant-category join breaks ties deterministically via
22
+ * `MIN(c.name)`/`MIN(c.names)` (alphabetically first), rather than relying on SQLite's
23
+ * unspecified bare-column pick; a merchant with *no classified* transactions at all has no rows
24
+ * in `category_counts`, so the `LEFT JOIN` never matches and both `MIN`s come back `NULL` — the
25
+ * "resolves gracefully" case. */
26
+ const MERCHANTS_TOP_SELECT = (userId, limit) => sql `
27
+ WITH merchant_totals AS (
28
+ SELECT t.merchant_key, COUNT(*) AS transaction_count
29
+ FROM transactions t
30
+ WHERE ${ownedBy(userId, 't')}
31
+ AND ${txPredicates.effective()}
32
+ AND ${txPredicates.nonTransfer()}
33
+ AND t.merchant_key IS NOT NULL
34
+ GROUP BY t.merchant_key
35
+ ORDER BY transaction_count DESC
36
+ LIMIT ${limit}
37
+ ),
38
+ category_counts AS (
39
+ SELECT t.merchant_key, t.category_id, COUNT(*) AS category_count
40
+ FROM transactions t
41
+ JOIN merchant_totals mt ON mt.merchant_key = t.merchant_key
42
+ WHERE ${ownedBy(userId, 't')}
43
+ AND ${txPredicates.effective()}
44
+ AND ${txPredicates.nonTransfer()}
45
+ AND t.category_id IS NOT NULL
46
+ GROUP BY t.merchant_key, t.category_id
47
+ )
48
+ SELECT mt.merchant_key AS merchant, mt.transaction_count AS transaction_count,
49
+ MIN(c.name) AS category_name, MIN(c.names) AS category_names
50
+ FROM merchant_totals mt
51
+ LEFT JOIN category_counts cc
52
+ ON cc.merchant_key = mt.merchant_key
53
+ AND cc.category_count = (
54
+ SELECT MAX(cc2.category_count) FROM category_counts cc2 WHERE cc2.merchant_key = mt.merchant_key
55
+ )
56
+ LEFT JOIN categories c ON c.id = cc.category_id
57
+ GROUP BY mt.merchant_key, mt.transaction_count
58
+ ORDER BY mt.transaction_count DESC
59
+ `;
60
+ export const merchantsRepo = (db, userId) => ({
61
+ matchCandidates: async (normalizedDescription) => {
62
+ // Shared `rule` edges plus this user's `history` edges; the same (merchant, category) may have one of each,
63
+ // so weights are summed.
64
+ const rows = await db.all(sql `
65
+ SELECT mc.merchant_key AS "merchantKey", mc.category_id AS "categoryId",
66
+ c.name AS "categoryName", SUM(mc.weight) AS weight,
67
+ CASE WHEN SUM(mc.origin = ${ClassificationMethod.enum.rule}) > 0
68
+ THEN ${ClassificationMethod.enum.rule} ELSE ${ClassificationMethod.enum.history} END AS origin
69
+ FROM merchant_category mc
70
+ JOIN categories c ON c.id = mc.category_id
71
+ WHERE ${visibleTo(userId, 'mc')}
72
+ AND ${visibleTo(userId, 'c')}
73
+ AND ${normalizedDescription} LIKE '%' || mc.merchant_key || '%'
74
+ GROUP BY mc.merchant_key, mc.category_id
75
+ ORDER BY weight DESC, length(mc.merchant_key) DESC
76
+ LIMIT 5
77
+ `);
78
+ return rows.map((r) => MatchRow.parse(r));
79
+ },
80
+ top: async (limit) => {
81
+ const rows = await db.all(MERCHANTS_TOP_SELECT(userId, limit));
82
+ return rows.map((r) => MerchantTopDbRowSchema.parse(r));
83
+ },
84
+ });
85
+ /** Hand-written rather than `versionedTableApplier` because `merchants` keys on `key` with no
86
+ * `version` — like `dashboards`, but simpler: only ever inserted, idempotently. */
87
+ export const merchantApplier = {
88
+ insert: async (tx, model) => {
89
+ const { key } = model;
90
+ const result = await tx.insert(merchants).values({ key }).onConflictDoNothing();
91
+ return { applied: (result.rowsAffected ?? 0) > 0 };
92
+ },
93
+ update: async () => {
94
+ throw new Error('merchantApplier: update is unsupported — a merchant is only ever inserted');
95
+ },
96
+ delete: async () => {
97
+ throw new Error('merchantApplier: delete is unsupported — merchants are never removed');
98
+ },
99
+ };
100
+ /** Always an `insert` (no `id`/`version`) — `update`/`delete` are structurally unreachable. The
101
+ * `set` below deliberately omits `origin`: it must stay insert-only. Writes only the caller's own `history` edge. */
102
+ export const merchantCategoryApplier = (userId) => ({
103
+ insert: async (tx, model) => {
104
+ const { merchantKey, categoryId, weightDelta, origin } = model;
105
+ await tx
106
+ .insert(merchantCategory)
107
+ .values({ merchantKey, categoryId, weight: weightDelta, origin, userId })
108
+ .onConflictDoUpdate({
109
+ target: [merchantCategory.userId, merchantCategory.merchantKey, merchantCategory.categoryId],
110
+ targetWhere: sql `${merchantCategory.userId} IS NOT NULL`,
111
+ set: { weight: sql `${merchantCategory.weight} + ${weightDelta}` },
112
+ });
113
+ return { applied: true };
114
+ },
115
+ update: async () => {
116
+ throw new Error('merchantCategoryApplier: update is unsupported — every write is an insert (upsert-increment)');
117
+ },
118
+ delete: async () => {
119
+ throw new Error('merchantCategoryApplier: delete is unsupported — merchant-category edges are never removed');
120
+ },
121
+ });
@@ -0,0 +1,29 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import * as recurringAdapters from '../../../adapters/recurring.js';
3
+ import { recurringRules } from '../schema.js';
4
+ import { ownedTableApplier } from '../effects.js';
5
+ import { ownedBy } from '../queries/scope.js';
6
+ const RULE_FROM = sql `FROM recurring_rules r`;
7
+ const RULE_SELECT_BARE = (userId) => sql `SELECT r.*, NULL AS account_name, NULL AS category_name ${RULE_FROM} WHERE ${ownedBy(userId, 'r')}`;
8
+ const RULE_SELECT = (userId) => sql `
9
+ SELECT r.*, a.name AS account_name, c.name AS category_name
10
+ ${RULE_FROM}
11
+ LEFT JOIN accounts a ON a.id = r.account_id
12
+ LEFT JOIN categories c ON c.id = r.category_id
13
+ WHERE ${ownedBy(userId, 'r')}
14
+ `;
15
+ export const recurringRepo = (db, userId) => ({
16
+ list: async () => {
17
+ const rows = await db.all(sql `
18
+ ${RULE_SELECT(userId)} ORDER BY r.next_due
19
+ `);
20
+ return rows.map(recurringAdapters.dbToModel);
21
+ },
22
+ due: async (onOrBefore) => {
23
+ const rows = await db.all(sql `
24
+ ${RULE_SELECT_BARE(userId)} AND r.next_due <= ${onOrBefore} ORDER BY r.next_due
25
+ `);
26
+ return rows.map(recurringAdapters.dbToEntity);
27
+ },
28
+ });
29
+ export const recurringRuleApplier = (userId) => ownedTableApplier(recurringRules, userId);
@@ -0,0 +1,19 @@
1
+ import { eq, lte } from 'drizzle-orm';
2
+ import * as sessionAdapters from '../../../adapters/sessions.js';
3
+ import { sessions } from '../schema.js';
4
+ import { versionedTableApplier } from '../effects.js';
5
+ export const sessionsRepo = (db) => ({
6
+ findByTokenHash: async (tokenHash) => {
7
+ const [row] = await db.select().from(sessions).where(eq(sessions.tokenHash, tokenHash)).limit(1);
8
+ return row ? sessionAdapters.dbToModel(row) : null;
9
+ },
10
+ listExpired: async (nowIso) => {
11
+ const rows = await db.select().from(sessions).where(lte(sessions.expiresAt, nowIso));
12
+ return rows.map(sessionAdapters.dbToModel);
13
+ },
14
+ listByUser: async (userId) => {
15
+ const rows = await db.select().from(sessions).where(eq(sessions.userId, userId));
16
+ return rows.map(sessionAdapters.dbToModel);
17
+ },
18
+ });
19
+ export const sessionApplier = versionedTableApplier(sessions);
@@ -0,0 +1,41 @@
1
+ import { and, eq } from 'drizzle-orm';
2
+ import { UserSettingsEntitySchema } from '../../../models/locale.js';
3
+ import { userSettings } from '../schema.js';
4
+ import { VersionConflict } from '../effects.js';
5
+ export const settingsRepo = (db, userId) => ({
6
+ getLocale: async () => {
7
+ const [row] = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
8
+ if (!row)
9
+ return undefined;
10
+ return UserSettingsEntitySchema.parse({
11
+ locale: row.locale,
12
+ localeSource: row.localeSource,
13
+ baseCurrency: row.baseCurrency,
14
+ version: row.version,
15
+ });
16
+ },
17
+ });
18
+ /** Keyed by `user_id`. A collision on insert is the concurrent-first-insert race: retry, don't silently no-op. */
19
+ export const userSettingsApplier = (userId) => ({
20
+ insert: async (tx, model) => {
21
+ const { locale, localeSource, baseCurrency } = model;
22
+ const result = await tx
23
+ .insert(userSettings)
24
+ .values({ userId, locale, localeSource, baseCurrency })
25
+ .onConflictDoNothing({ target: userSettings.userId });
26
+ if ((result.rowsAffected ?? 0) === 0)
27
+ throw new VersionConflict();
28
+ return { applied: true };
29
+ },
30
+ update: async (tx, model) => {
31
+ const { locale, localeSource, baseCurrency, version } = model;
32
+ const result = await tx
33
+ .update(userSettings)
34
+ .set({ locale, localeSource, baseCurrency, version: version + 1 })
35
+ .where(and(eq(userSettings.userId, userId), eq(userSettings.version, version)));
36
+ return { applied: (result.rowsAffected ?? 0) > 0 };
37
+ },
38
+ delete: async () => {
39
+ throw new Error('userSettingsApplier: delete is unsupported — preferences are never removed');
40
+ },
41
+ });
@@ -0,0 +1,28 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import * as setupCodeAdapters from '../../../adapters/setup-codes.js';
3
+ import { SETUP_CODE_ID } from '../../../models/auth/owner.js';
4
+ import { setupCodes } from '../schema.js';
5
+ import { VersionConflict, versionedTableApplier } from '../effects.js';
6
+ export const setupCodesRepo = (db) => ({
7
+ findByHash: async (codeHash) => {
8
+ const [row] = await db.select().from(setupCodes).where(eq(setupCodes.codeHash, codeHash)).limit(1);
9
+ return row ? setupCodeAdapters.dbToModel(row) : null;
10
+ },
11
+ current: async () => {
12
+ const [row] = await db.select().from(setupCodes).where(eq(setupCodes.id, SETUP_CODE_ID)).limit(1);
13
+ return row ? setupCodeAdapters.dbToModel(row) : null;
14
+ },
15
+ });
16
+ const versionedSetupCodeApplier = versionedTableApplier(setupCodes);
17
+ // Singleton row (`SETUP_CODE_ID`): an id collision on insert IS the concurrent-first-issue race (two starters
18
+ // both saw no row). The plain applier would silently no-op the loser, leaving it printing a code that was
19
+ // never stored — so, like `settingsApplier`, a collision retries, and the retry updates the winner's row.
20
+ export const setupCodeApplier = {
21
+ ...versionedSetupCodeApplier,
22
+ insert: async (tx, model) => {
23
+ const outcome = await versionedSetupCodeApplier.insert(tx, model);
24
+ if (!outcome.applied)
25
+ throw new VersionConflict();
26
+ return outcome;
27
+ },
28
+ };
@@ -0,0 +1,67 @@
1
+ import { eq, sql } from 'drizzle-orm';
2
+ import * as categoryAdapters from '../../../adapters/categories.js';
3
+ import { categories, recurringRules, transactions } from '../schema.js';
4
+ import { ownedWhere, visibleTo, visibleWhere } from '../queries/scope.js';
5
+ const SUB_SELECT = (userId) => sql `
6
+ SELECT sc.id, sc.name, sc.parent_id, p.name AS parent_name, p.kind
7
+ FROM categories sc
8
+ JOIN categories p ON p.id = sc.parent_id
9
+ WHERE sc.parent_id IS NOT NULL
10
+ AND ${visibleTo(userId, 'sc')}
11
+ AND ${visibleTo(userId, 'p')}
12
+ `;
13
+ const list = async ({ db, userId }) => {
14
+ const rows = await db.all(sql `
15
+ ${SUB_SELECT(userId)}
16
+ ORDER BY p.name, sc.name
17
+ `);
18
+ return rows.map(categoryAdapters.dbToSubCategory);
19
+ };
20
+ const listByParent = async ({ db, userId }, parentId) => {
21
+ const rows = await db.all(sql `
22
+ ${SUB_SELECT(userId)}
23
+ AND sc.parent_id = ${parentId}
24
+ ORDER BY sc.name
25
+ `);
26
+ return rows.map(categoryAdapters.dbToSubCategory);
27
+ };
28
+ const findByName = async ({ db, userId }, name) => {
29
+ const rows = await db.all(sql `
30
+ ${SUB_SELECT(userId)}
31
+ AND sc.name = ${name}
32
+ LIMIT 1
33
+ `);
34
+ return rows[0] ? categoryAdapters.dbToSubCategory(rows[0]) : null;
35
+ };
36
+ const countReferences = async ({ db, userId }, subCategoryId) => {
37
+ const [byCat] = await db
38
+ .select({ count: sql `count(*)` })
39
+ .from(transactions)
40
+ .where(ownedWhere(transactions.userId, userId, eq(transactions.categoryId, subCategoryId)));
41
+ const [bySub] = await db
42
+ .select({ count: sql `count(*)` })
43
+ .from(transactions)
44
+ .where(ownedWhere(transactions.userId, userId, eq(transactions.subcategoryId, subCategoryId)));
45
+ const [recRow] = await db
46
+ .select({ count: sql `count(*)` })
47
+ .from(recurringRules)
48
+ .where(ownedWhere(recurringRules.userId, userId, eq(recurringRules.categoryId, subCategoryId)));
49
+ const [subRow] = await db
50
+ .select({ count: sql `count(*)` })
51
+ .from(categories)
52
+ .where(visibleWhere(categories.userId, userId, eq(categories.parentId, subCategoryId)));
53
+ return {
54
+ transactions: (byCat?.count ?? 0) + (bySub?.count ?? 0),
55
+ recurring: recRow?.count ?? 0,
56
+ subCategories: subRow?.count ?? 0,
57
+ };
58
+ };
59
+ export const subCategoriesRepo = (db, userId) => {
60
+ const scope = { db, userId };
61
+ return {
62
+ list: () => list(scope),
63
+ listByParent: (parentId) => listByParent(scope, parentId),
64
+ findByName: (name) => findByName(scope, name),
65
+ countReferences: (subCategoryId) => countReferences(scope, subCategoryId),
66
+ };
67
+ };
@@ -0,0 +1,51 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import * as tagAdapters from '../../../adapters/tags.js';
3
+ import { tags } from '../schema.js';
4
+ import { isUniqueConstraintViolation } from '../sqlite-errors.js';
5
+ import { VersionConflict, ownedTableApplier } from '../effects.js';
6
+ import { ownedWhere } from '../queries/scope.js';
7
+ export const tagsRepo = (db, userId) => ({
8
+ list: async () => {
9
+ const rows = await db.select().from(tags).where(ownedWhere(tags.userId, userId)).orderBy(tags.name);
10
+ return rows.map(tagAdapters.dbToModel);
11
+ },
12
+ findByName: async (name) => {
13
+ const [row] = await db
14
+ .select()
15
+ .from(tags)
16
+ .where(ownedWhere(tags.userId, userId, eq(tags.name, name)))
17
+ .limit(1);
18
+ return row ? tagAdapters.dbToModel(row) : null;
19
+ },
20
+ findById: async (id) => {
21
+ const [row] = await db
22
+ .select()
23
+ .from(tags)
24
+ .where(ownedWhere(tags.userId, userId, eq(tags.id, id)))
25
+ .limit(1);
26
+ return row ? tagAdapters.dbToEntity(row) : null;
27
+ },
28
+ });
29
+ const versionedTagApplier = (userId) => ownedTableApplier(tags, userId);
30
+ /** `tags.name` has its own `UNIQUE` constraint beyond `createTag`'s pre-check
31
+ * (`assertTagNameAvailable`, which only guards the common case) — a concurrent same-name insert
32
+ * can raise a real unique-constraint error `versionedTableApplier`'s id-scoped
33
+ * `onConflictDoNothing` doesn't swallow. Recognized and rethrown as `VersionConflict`, rolling
34
+ * back and retrying — the retry's own `assertTagNameAvailable` then sees the committed row and
35
+ * returns `duplicate_name` instead of a raw 500. `update`/`delete` stay plain. */
36
+ export const tagApplier = (userId) => {
37
+ const applier = versionedTagApplier(userId);
38
+ return {
39
+ ...applier,
40
+ insert: async (tx, model) => {
41
+ try {
42
+ return await applier.insert(tx, model);
43
+ }
44
+ catch (cause) {
45
+ if (isUniqueConstraintViolation(cause))
46
+ throw new VersionConflict();
47
+ throw cause;
48
+ }
49
+ },
50
+ };
51
+ };