@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,84 @@
1
+ import { err, ok } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { authErrors } from '../../models/auth/errors.js';
4
+ import { UserRole } from '../../models/auth/owner.js';
5
+ import { AdminChange, NO_REVOCATIONS, } from '../../models/auth/users.js';
6
+ import { hasCredentials, isNeverClaimed } from './owner.js';
7
+ import { endedCredentials } from './revoke.js';
8
+ import { disabledUser, guardAdminChange, isActiveAdmin, remainingAdmins, withoutPassword, withCredentialsChanged, withRole, } from './users.js';
9
+ const unchanged = (target) => ({
10
+ userWrites: [],
11
+ checks: [],
12
+ sessions: [],
13
+ tokens: [],
14
+ expiredGrants: [],
15
+ removedInvites: [],
16
+ newInvites: [],
17
+ after: target,
18
+ revoked: NO_REVOCATIONS,
19
+ });
20
+ const rosterOf = (facts) => R.map(facts.users, (user) => (facts.acting !== null && user.id === facts.acting.id ? facts.acting : user));
21
+ const standing = (users, target) => isActiveAdmin(target) ? remainingAdmins(users, target) : [];
22
+ const assertedRows = (facts, roster) => R.pipe([facts.target, ...standing(roster, facts.target), ...(facts.acting === null ? [] : [facts.acting])], R.uniqueBy((user) => user.id));
23
+ const rowsOf = (facts, roster, writes) => ({
24
+ userWrites: writes,
25
+ checks: R.differenceWith(assertedRows(facts, roster), writes, (user, written) => user.id === written.id),
26
+ });
27
+ export const planDisable = (facts) => {
28
+ if (facts.target.disabledAt !== null)
29
+ return ok(unchanged(facts.target));
30
+ const roster = rosterOf(facts);
31
+ const refusal = guardAdminChange(AdminChange.enum.disable, { ...facts, users: roster });
32
+ if (refusal !== null)
33
+ return err(refusal);
34
+ const disabled = disabledUser(facts.target, facts.now);
35
+ const ended = endedCredentials(facts.held, facts.now);
36
+ return ok({
37
+ ...rowsOf(facts, roster, [disabled]),
38
+ sessions: ended.sessions,
39
+ tokens: ended.tokens,
40
+ expiredGrants: ended.expiredGrants,
41
+ removedInvites: [...facts.openInvites],
42
+ newInvites: [],
43
+ after: disabled,
44
+ revoked: ended.revoked,
45
+ });
46
+ };
47
+ export const planReissue = (facts) => {
48
+ if (facts.target.disabledAt !== null)
49
+ return err(authErrors.userDisabled);
50
+ if (isNeverClaimed(facts.target))
51
+ return err(authErrors.ownerUnclaimed);
52
+ const roster = rosterOf(facts);
53
+ const refusal = guardAdminChange(AdminChange.enum.reissue, { ...facts, users: roster });
54
+ if (refusal !== null)
55
+ return err(refusal);
56
+ const claimed = hasCredentials(facts.target);
57
+ const after = claimed ? withoutPassword(facts.target, facts.now) : facts.target;
58
+ const ended = claimed
59
+ ? endedCredentials(facts.held, facts.now)
60
+ : { sessions: [], tokens: [], expiredGrants: [], revoked: NO_REVOCATIONS };
61
+ return ok({
62
+ ...rowsOf(facts, roster, [claimed ? after : withCredentialsChanged(after, facts.now)]),
63
+ sessions: ended.sessions,
64
+ tokens: ended.tokens,
65
+ expiredGrants: ended.expiredGrants,
66
+ removedInvites: [...facts.openInvites],
67
+ newInvites: [facts.invite],
68
+ after,
69
+ revoked: ended.revoked,
70
+ });
71
+ };
72
+ export const planRole = (facts) => {
73
+ if (facts.target.role === facts.role)
74
+ return ok(unchanged(facts.target));
75
+ const roster = rosterOf(facts);
76
+ const refusal = facts.role === UserRole.enum.member ? guardAdminChange(AdminChange.enum.demote, { ...facts, users: roster }) : null;
77
+ if (refusal !== null)
78
+ return err(refusal);
79
+ const changed = withRole(facts.target, facts.role);
80
+ return ok({
81
+ ...unchanged(changed),
82
+ ...rowsOf(facts, roster, [changed]),
83
+ });
84
+ };
@@ -0,0 +1,78 @@
1
+ import * as R from 'remeda';
2
+ import { authErrors } from '../../models/auth/errors.js';
3
+ import { USER_ENTITY_TAG } from '../../models/auth/entity.js';
4
+ import { INVITE_PATH, INVITE_CODE_PARAM } from '../../models/auth/origin.js';
5
+ import { UserRole } from '../../models/auth/owner.js';
6
+ import { PrincipalVia } from '../../models/auth/principal.js';
7
+ import { ActorKind, INVITE_TTL_MS, UserStatus, CHANGE_BLOCKS_SELF, } from '../../models/auth/users.js';
8
+ import { hasCredentials, isActiveUser, formatSetupCode, normalizeSetupCode } from './owner.js';
9
+ import { millis, toIso } from './time.js';
10
+ import * as persistence from '../persistence.js';
11
+ export const normalizeInviteCode = normalizeSetupCode;
12
+ export const formatInviteCode = formatSetupCode;
13
+ export const inviteLink = (origin, code) => `${origin}${INVITE_PATH}?${INVITE_CODE_PARAM}=${encodeURIComponent(code)}`;
14
+ export const userStatus = (user) => user.disabledAt !== null
15
+ ? UserStatus.enum.disabled
16
+ : hasCredentials(user)
17
+ ? UserStatus.enum.active
18
+ : UserStatus.enum.invited;
19
+ export const isActiveAdmin = (user) => isActiveUser(user) && user.role === UserRole.enum.admin;
20
+ export const isInviteLive = (invite, now) => invite.usedAt === null && millis(invite.expiresAt) > now.getTime();
21
+ export const isInviteUsable = (invite, now) => invite !== null && isInviteLive(invite, now);
22
+ export const summarizeUser = (user, invites, now) => ({
23
+ id: user.id,
24
+ username: user.username,
25
+ role: user.role,
26
+ status: userStatus(user),
27
+ createdAt: user.createdAt,
28
+ lastLoginAt: user.lastLoginAt,
29
+ inviteExpiresAt: R.find(invites, (invite) => invite.userId === user.id && isInviteLive(invite, now))?.expiresAt ?? null,
30
+ });
31
+ export const newInvitedUser = (fields, now) => ({
32
+ id: fields.id,
33
+ username: fields.username,
34
+ passwordHash: null,
35
+ role: fields.role,
36
+ createdAt: now.toISOString(),
37
+ disabledAt: null,
38
+ lastLoginAt: null,
39
+ credentialsChangedAt: now.toISOString(),
40
+ });
41
+ export const newInvite = (fields, now) => ({
42
+ ...fields,
43
+ createdAt: now.toISOString(),
44
+ expiresAt: toIso(now.getTime() + INVITE_TTL_MS),
45
+ usedAt: null,
46
+ });
47
+ export const spentInvite = (invite, now) => ({
48
+ ...invite,
49
+ usedAt: now.toISOString(),
50
+ });
51
+ export const withCredentialsChanged = (user, now) => ({
52
+ ...user,
53
+ credentialsChangedAt: now.toISOString(),
54
+ });
55
+ export const disabledUser = (user, now) => withCredentialsChanged({ ...user, disabledAt: now.toISOString() }, now);
56
+ export const enabledUser = (user) => ({ ...user, disabledAt: null });
57
+ export const withRole = (user, role) => ({ ...user, role });
58
+ export const withoutPassword = (user, now) => withCredentialsChanged({ ...user, passwordHash: null }, now);
59
+ export const loggedIn = (user, now) => withCredentialsChanged({ ...user, lastLoginAt: now.toISOString() }, now);
60
+ export const claimedByInvite = (user, passwordHash, now) => ({
61
+ ...loggedIn(user, now),
62
+ passwordHash,
63
+ });
64
+ export const authorizeActor = (actor, acting) => {
65
+ if (actor.kind === ActorKind.enum.terminal)
66
+ return null;
67
+ if (actor.principal.via !== PrincipalVia.enum.session)
68
+ return authErrors.sessionRequired;
69
+ return isActiveAdmin(acting) ? null : authErrors.adminRequired;
70
+ };
71
+ export const remainingAdmins = (users, target) => R.filter(users, (user) => user.id !== target.id && isActiveAdmin(user));
72
+ export const guardAdminChange = (change, fields) => {
73
+ if (CHANGE_BLOCKS_SELF[change] && fields.actingUserId === fields.target.id)
74
+ return authErrors.cannotChangeSelf;
75
+ const reduces = isActiveAdmin(fields.target);
76
+ return reduces && remainingAdmins(fields.users, fields.target).length === 0 ? authErrors.lastAdmin : null;
77
+ };
78
+ export const checkUser = (user) => persistence.check({ entity: USER_ENTITY_TAG, id: user.id, version: user.version });
@@ -0,0 +1,2 @@
1
+ export const computeBalance = (p) => p.initialBalance + p.income - p.expenses + p.transfersIn - p.transfersOut;
2
+ export const computeProjectedBalance = (effective, pending) => effective + pending.income - pending.expenses + pending.transfersIn - pending.transfersOut;
@@ -0,0 +1,74 @@
1
+ import { purry } from 'remeda';
2
+ import * as R from 'remeda';
3
+ import { localizeBillStatus } from './localize.js';
4
+ import { BILL_PAYMENT_KEY_PREFIX, BillStatus, } from '../models/bill.js';
5
+ import { TransactionType, UNCLASSIFIED } from '../models/transaction.js';
6
+ import { defaultStatusFor } from './transaction.js';
7
+ const _withStatusLabel = (bill, locale) => ({
8
+ ...bill,
9
+ statusLabel: localizeBillStatus(bill.status, locale),
10
+ });
11
+ export function withStatusLabel(...args) {
12
+ return purry(_withStatusLabel, args);
13
+ }
14
+ export const isBillPaid = (bill) => bill.status === BillStatus.enum.paid;
15
+ export const assertBillPeriodPaired = (input) => (input.billMonth === undefined) === (input.billYear === undefined);
16
+ export const withBillId = (tx, billId) => ({ ...tx, billId });
17
+ export const billEntityFrom = (bill) => ({
18
+ id: bill.id,
19
+ creditCardId: bill.creditCardId,
20
+ month: bill.month,
21
+ year: bill.year,
22
+ closeDate: bill.closeDate,
23
+ dueDate: bill.dueDate,
24
+ status: bill.status,
25
+ paymentTransactionId: bill.paymentTransactionId,
26
+ version: bill.version,
27
+ });
28
+ export const toBillView = (bill) => R.omit(bill, ['creditCardId', 'version']);
29
+ const pad = (n) => String(n).padStart(2, '0');
30
+ export const billPeriodKey = (period) => `${period.month}-${period.year}`;
31
+ const nextMonth = (month, year) => month === 12 ? { month: 1, year: year + 1 } : { month: month + 1, year };
32
+ const periodFor = (month, year, closingDay, dueDay) => {
33
+ const due = dueDay <= closingDay ? nextMonth(month, year) : { month, year };
34
+ return {
35
+ month,
36
+ year,
37
+ closeDate: `${year}-${pad(month)}-${pad(closingDay)}`,
38
+ dueDate: `${due.year}-${pad(due.month)}-${pad(dueDay)}`,
39
+ };
40
+ };
41
+ const signedBillAmount = (t) => {
42
+ if (t.type === TransactionType.enum.expense)
43
+ return t.amount;
44
+ if (t.type === TransactionType.enum.income)
45
+ return -t.amount;
46
+ return 0;
47
+ };
48
+ export const computeBillTotal = (transactions) => R.sumBy(transactions, signedBillAmount);
49
+ export const billPeriodFor = (txDate, closingDay, dueDay) => {
50
+ const [y, m, d] = txDate.split('-').map(Number);
51
+ const bill = d >= closingDay ? nextMonth(m, y) : { month: m, year: y };
52
+ return periodFor(bill.month, bill.year, closingDay, dueDay);
53
+ };
54
+ export const billPeriodForCycle = (month, year, closingDay, dueDay) => periodFor(month, year, closingDay, dueDay);
55
+ export const resolveBillPeriod = (billMonth, billYear, date, closingDay, dueDay) => R.isNonNullish(billMonth) && R.isNonNullish(billYear)
56
+ ? billPeriodForCycle(billMonth, billYear, closingDay, dueDay)
57
+ : billPeriodFor(date, closingDay, dueDay);
58
+ export const billPaymentKey = (billId) => `${BILL_PAYMENT_KEY_PREFIX}${billId}`;
59
+ export const billPaymentDescription = (cardName, month, year) => `Bill payment: ${cardName} ${pad(month)}/${year}`;
60
+ export const planBillPayment = (facts) => ({
61
+ transferEntity: {
62
+ id: facts.id,
63
+ description: billPaymentDescription(facts.card.name, facts.bill.month, facts.bill.year),
64
+ amount: facts.total,
65
+ type: TransactionType.enum.transfer,
66
+ status: defaultStatusFor(facts.date, facts.today),
67
+ date: facts.date,
68
+ currency: facts.card.currency,
69
+ source: facts.source,
70
+ classification: UNCLASSIFIED,
71
+ refs: { accountId: facts.payer.id, toAccountId: facts.card.accountId, billId: facts.bill.id },
72
+ },
73
+ idempotencyKey: billPaymentKey(facts.bill.id),
74
+ });
@@ -0,0 +1,78 @@
1
+ import * as R from 'remeda';
2
+ import { localizeCategoryName } from './category.js';
3
+ import { CategoryKind } from '../models/category.js';
4
+ export const hasCategory = (input) => input.category !== undefined;
5
+ export const hasSubCategory = (input) => input.subCategory !== undefined;
6
+ export const hasExactlyOneTarget = (input) => hasCategory(input) !== hasSubCategory(input);
7
+ export const isExpenseEligible = (kind) => kind !== CategoryKind.enum.income;
8
+ export const toView = (budget, target) => ({
9
+ id: budget.id,
10
+ currency: budget.currency,
11
+ limit: budget.limit,
12
+ period: budget.period,
13
+ category: target.category,
14
+ subCategory: target.subCategory,
15
+ });
16
+ export const isSubCategoryRow = (row) => row.nodeParentId !== null;
17
+ export const resolveTargetNames = (row, locale) => {
18
+ const isSubCategory = isSubCategoryRow(row);
19
+ const nodeName = localizeCategoryName(row.nodeName, row.nodeNames, locale) ?? row.nodeName;
20
+ return {
21
+ category: isSubCategory
22
+ ? (localizeCategoryName(row.parentName, row.parentNames, locale) ?? row.parentName)
23
+ : nodeName,
24
+ subCategory: isSubCategory ? nodeName : undefined,
25
+ };
26
+ };
27
+ export const rowToView = (row, locale) => ({
28
+ id: row.id,
29
+ currency: row.currency,
30
+ limit: row.limit,
31
+ period: row.period,
32
+ ...resolveTargetNames(row, locale),
33
+ });
34
+ export const rowsToViews = (rows, locale) => R.pipe(rows, R.map((row) => rowToView(row, locale)), R.sortBy([(v) => v.category, 'asc'], [(v) => v.subCategory ?? '', 'asc']));
35
+ export const matchesTarget = (spend, isSubCategory, targetId) => isSubCategory ? spend.subCategoryId === targetId : spend.categoryId === targetId;
36
+ const sumMatchedSpend = (spend, row) => {
37
+ const isSubCategory = isSubCategoryRow(row);
38
+ const matched = R.filter(spend, (s) => s.currency === row.currency && matchesTarget(s, isSubCategory, row.targetId));
39
+ return { effective: R.sumBy(matched, (s) => s.effective), pending: R.sumBy(matched, (s) => s.pending) };
40
+ };
41
+ const rowToStatusEntry = (row, spend, locale) => {
42
+ const matched = sumMatchedSpend(spend, row);
43
+ return {
44
+ id: row.id,
45
+ currency: row.currency,
46
+ limit: row.limit,
47
+ period: row.period,
48
+ spentEffective: matched.effective,
49
+ spentPending: matched.pending,
50
+ ...resolveTargetNames(row, locale),
51
+ };
52
+ };
53
+ const toMeasure = (amount, limit) => ({ amount, pct: amount / limit });
54
+ const toStatusLine = (entry) => {
55
+ const committedAmount = entry.spentEffective + entry.spentPending;
56
+ return {
57
+ id: entry.id,
58
+ currency: entry.currency,
59
+ limit: entry.limit,
60
+ period: entry.period,
61
+ subCategory: entry.subCategory,
62
+ effective: toMeasure(entry.spentEffective, entry.limit),
63
+ committed: toMeasure(committedAmount, entry.limit),
64
+ pending: toMeasure(entry.spentPending, entry.limit),
65
+ remaining: entry.limit - committedAmount,
66
+ };
67
+ };
68
+ export const budgetedCommittedByCurrency = (budgets, spend) => R.pipe(spend, R.filter((s) => budgets.some((b) => b.currency === s.currency && matchesTarget(s, isSubCategoryRow(b), b.targetId))), R.groupBy((s) => s.currency), R.entries(), R.map(([currency, rows]) => ({
69
+ currency: currency,
70
+ amount: R.sumBy(rows, (s) => s.effective + s.pending),
71
+ })));
72
+ export const groupStatusByCategory = (budgets, spend, locale) => R.pipe(budgets, R.map((row) => rowToStatusEntry(row, spend, locale)), R.groupBy((e) => e.category), R.entries(), R.map(([category, categoryEntries]) => {
73
+ const lines = R.map(categoryEntries, toStatusLine);
74
+ return {
75
+ category,
76
+ lines: R.sortBy(lines, [(l) => l.subCategory ?? '', 'asc'], [(l) => l.currency, 'asc']),
77
+ };
78
+ }), R.sortBy((group) => group.category));
@@ -0,0 +1,37 @@
1
+ import { purry } from 'remeda';
2
+ import { localizeCategoryKind } from './localize.js';
3
+ import { fold } from './resolve.js';
4
+ const _withKindLabel = (item, locale) => ({
5
+ ...item,
6
+ kindLabel: localizeCategoryKind(item.kind, locale),
7
+ });
8
+ export function withKindLabel(...args) {
9
+ return purry(_withKindLabel, args);
10
+ }
11
+ export const resolveDisplayName = (cat, locale) => ({
12
+ ...cat,
13
+ name: cat.names?.[locale] ?? cat.name,
14
+ });
15
+ export const localizeCategoryName = (name, names, locale) => (name != null ? (names?.[locale] ?? name) : undefined);
16
+ export const allNames = (cat) => [cat.name, ...Object.values(cat.names ?? {})];
17
+ export const hasNameCollision = (categories, name) => {
18
+ const folded = fold(name);
19
+ return categories.some((c) => allNames(c).some((n) => fold(n) === folded));
20
+ };
21
+ export const hasSubCategoryNameCollision = (siblings, name) => siblings.some((s) => s.name.toLowerCase() === name.toLowerCase());
22
+ export const assertCategoryNameAvailable = (categories, name) => !hasNameCollision(categories, name);
23
+ export const assertSubCategoryNameAvailable = (siblings, name) => !hasSubCategoryNameCollision(siblings, name);
24
+ export const isSharedDefault = (row) => row.shared;
25
+ export const isCategoryUnreferenced = (refs) => refs.transactions === 0 && refs.recurring === 0 && refs.subCategories === 0;
26
+ export const resolveAndSort = (categories, locale) => {
27
+ const resolved = categories.map((c) => resolveDisplayName(c, locale));
28
+ const collator = new Intl.Collator(locale, { sensitivity: 'base' });
29
+ return resolved.sort((a, b) => collator.compare(a.name, b.name));
30
+ };
31
+ export const buildSynonyms = (rawCategories) => {
32
+ const canonicalById = new Map(rawCategories.map((c) => [c.id, c.name]));
33
+ return (cat) => [
34
+ ...(canonicalById.has(cat.id) ? [canonicalById.get(cat.id)] : []),
35
+ ...Object.values(cat.names ?? {}),
36
+ ];
37
+ };
@@ -0,0 +1,21 @@
1
+ import * as R from 'remeda';
2
+ import { UNCLASSIFIED } from '../models/transaction.js';
3
+ export const weightToConfidence = (weight) => Math.min(0.95, 0.5 + 0.1 * Math.max(0, weight));
4
+ export const userClassification = (category) => ({
5
+ method: 'user',
6
+ confidence: 1,
7
+ categoryId: category.id,
8
+ categoryName: category.name,
9
+ });
10
+ export const pickClassification = (matches) => {
11
+ const best = R.firstBy(matches, [(m) => m.weight, 'desc']);
12
+ if (!best)
13
+ return UNCLASSIFIED;
14
+ return {
15
+ method: best.origin,
16
+ confidence: weightToConfidence(best.weight),
17
+ categoryId: best.categoryId,
18
+ categoryName: best.categoryName,
19
+ merchantKey: best.merchantKey,
20
+ };
21
+ };
@@ -0,0 +1,147 @@
1
+ import * as R from 'remeda';
2
+ import { localizeCategoryName } from './category.js';
3
+ import { isSubCategoryRow, matchesTarget, resolveTargetNames } from './budget.js';
4
+ import { roundMoney, roundToDecimals } from './money.js';
5
+ import { daysBetween } from './period.js';
6
+ import { nextDue } from './recurring.js';
7
+ import { BudgetFitVerdict, CADENCE_AMOUNT_TOLERANCE_PCT, CADENCE_DAY_TOLERANCE_DAYS, CADENCE_NOMINAL_GAP_DAYS, SpendingShiftDirection, SUGGESTED_LIMIT_MARGIN_PCT, } from '../models/correlations.js';
8
+ import { RecurringPeriod } from '../models/recurring.js';
9
+ import { unknownLabels } from '../models/aggregate.js';
10
+ const shiftMagnitude = (deltaPct) => deltaPct === null ? Number.POSITIVE_INFINITY : Math.abs(deltaPct);
11
+ const passesThreshold = (deltaPct, minDeltaPct) => deltaPct === null || Math.abs(deltaPct) >= minDeltaPct;
12
+ const toSpendingShift = (row, baselineMonths, locale, decimalsFor) => {
13
+ const rawBaseline = row.baselineTotal / baselineMonths;
14
+ const deltaPct = rawBaseline === 0 ? null : roundMoney(((row.current - rawBaseline) / rawBaseline) * 100);
15
+ const direction = deltaPct === null || row.current >= rawBaseline ? SpendingShiftDirection.enum.up : SpendingShiftDirection.enum.down;
16
+ const decimals = decimalsFor(row.currency);
17
+ return {
18
+ category: localizeCategoryName(row.category, row.categoryNames, locale) ?? row.category,
19
+ currency: row.currency,
20
+ current: roundToDecimals(row.current, decimals),
21
+ baseline: roundToDecimals(rawBaseline, decimals),
22
+ deltaPct,
23
+ direction,
24
+ };
25
+ };
26
+ export const shapeSpendingShifts = (rows, baselineMonths, minDeltaPct, locale, decimalsFor) => R.pipe(rows, R.map((row) => toSpendingShift(row, baselineMonths, locale, decimalsFor)), R.filter((shift) => passesThreshold(shift.deltaPct, minDeltaPct)), R.sortBy([(shift) => shiftMagnitude(shift.deltaPct), 'desc']));
27
+ export const currentSpendByCurrency = (rows) => R.pipe(rows, R.groupBy((row) => row.currency), R.entries(), R.map(([currency, group]) => ({
28
+ currency: currency,
29
+ amount: R.sumBy(group, (row) => row.current),
30
+ })));
31
+ const suggestedLimitFor = (baseline, decimals) => roundToDecimals(baseline * (1 + SUGGESTED_LIMIT_MARGIN_PCT / 100), decimals);
32
+ const verdictFor = (baseline, limit, slackPct, overPct) => {
33
+ const ratio = baseline / limit;
34
+ if (ratio > 1 + overPct / 100)
35
+ return BudgetFitVerdict.enum.unrealistic;
36
+ if (ratio < 1 - slackPct / 100)
37
+ return BudgetFitVerdict.enum.generous;
38
+ return BudgetFitVerdict.enum.realistic;
39
+ };
40
+ const sumWindowedSpend = (spend, budget) => {
41
+ const isSubCategory = isSubCategoryRow(budget);
42
+ const matched = R.filter(spend, (s) => s.currency === budget.currency && matchesTarget(s, isSubCategory, budget.targetId));
43
+ return { current: R.sumBy(matched, (s) => s.current), baselineTotal: R.sumBy(matched, (s) => s.baselineTotal) };
44
+ };
45
+ const toBudgetFitLine = (budget, spend, baselineMonths, slackPct, overPct, locale, decimalsFor) => {
46
+ const matched = sumWindowedSpend(spend, budget);
47
+ const rawBaseline = matched.baselineTotal / baselineMonths;
48
+ const decimals = decimalsFor(budget.currency);
49
+ return {
50
+ id: budget.id,
51
+ ...resolveTargetNames(budget, locale),
52
+ currency: budget.currency,
53
+ limit: budget.limit,
54
+ current: roundToDecimals(matched.current, decimals),
55
+ baseline: roundToDecimals(rawBaseline, decimals),
56
+ verdict: verdictFor(rawBaseline, budget.limit, slackPct, overPct),
57
+ suggestedLimit: suggestedLimitFor(rawBaseline, decimals),
58
+ };
59
+ };
60
+ export const shapeBudgetFitLines = (budgets, spend, baselineMonths, slackPct, overPct, locale, decimalsFor) => R.pipe(budgets, R.map((budget) => toBudgetFitLine(budget, spend, baselineMonths, slackPct, overPct, locale, decimalsFor)), R.sortBy([(line) => line.category, 'asc'], [(line) => line.currency, 'asc'], [(line) => line.subCategory ?? '', 'asc']));
61
+ const categoryCurrencyKey = (category, currency) => JSON.stringify([category, currency]);
62
+ export const shapeUnbudgetedSpend = (shiftRows, budgeted, baselineMonths, locale, decimalsFor) => {
63
+ const budgetedKeys = new Set(budgeted.map((line) => categoryCurrencyKey(line.category, line.currency)));
64
+ return R.pipe(shiftRows, R.map((row) => ({
65
+ category: localizeCategoryName(row.category, row.categoryNames, locale) ?? row.category,
66
+ currency: row.currency,
67
+ rawBaseline: row.baselineTotal / baselineMonths,
68
+ })), R.filter((shift) => shift.rawBaseline > 0 && !budgetedKeys.has(categoryCurrencyKey(shift.category, shift.currency))), R.map((shift) => {
69
+ const decimals = decimalsFor(shift.currency);
70
+ return {
71
+ category: shift.category,
72
+ currency: shift.currency,
73
+ baseline: roundToDecimals(shift.rawBaseline, decimals),
74
+ suggestedLimit: suggestedLimitFor(shift.rawBaseline, decimals),
75
+ };
76
+ }), R.sortBy([(entry) => entry.category, 'asc'], [(entry) => entry.currency, 'asc']));
77
+ };
78
+ const roundShare = (value) => Math.round(value * 10000) / 10000;
79
+ const resolveMerchantLabel = (merchantKey, locale) => merchantKey ?? unknownLabels[locale];
80
+ const toMerchantShares = (top, categoryTotal, locale, decimals) => {
81
+ const shares = top.map((row) => (categoryTotal === 0 ? 0 : row.spent / categoryTotal));
82
+ return top.map((row, index) => {
83
+ const share = shares[index];
84
+ const cumulative = shares.slice(0, index + 1).reduce((total, each) => total + each, 0);
85
+ return {
86
+ merchant: resolveMerchantLabel(row.merchantKey, locale),
87
+ spent: roundToDecimals(row.spent, decimals),
88
+ share: roundShare(share),
89
+ cumulativeShare: roundShare(cumulative),
90
+ };
91
+ });
92
+ };
93
+ const toCategoryConcentration = (rows, topN, locale, decimalsFor) => {
94
+ const { category, categoryNames, currency } = rows[0];
95
+ const decimals = decimalsFor(currency);
96
+ const categoryTotal = R.sumBy(rows, (row) => row.spent);
97
+ const top = R.take(R.sortBy(rows, [(row) => row.spent, 'desc']), topN);
98
+ return {
99
+ category: localizeCategoryName(category, categoryNames, locale) ?? category,
100
+ currency,
101
+ categoryTotal: roundToDecimals(categoryTotal, decimals),
102
+ merchants: toMerchantShares(top, categoryTotal, locale, decimals),
103
+ othersSpent: roundToDecimals(categoryTotal - R.sumBy(top, (row) => row.spent), decimals),
104
+ };
105
+ };
106
+ export const shapeMerchantConcentration = (rows, topN, locale, decimalsFor) => R.pipe(rows, R.groupBy((row) => categoryCurrencyKey(row.category, row.currency)), R.values(), R.map((groupRows) => toCategoryConcentration(groupRows, topN, locale, decimalsFor)), R.sortBy([(entry) => entry.category, 'asc'], [(entry) => entry.currency, 'asc']));
107
+ export const merchantSpendByCurrency = (groups) => R.pipe(groups, R.groupBy((group) => group.currency), R.entries(), R.map(([currency, group]) => ({
108
+ currency: currency,
109
+ amount: R.sumBy(group, (g) => g.categoryTotal),
110
+ })));
111
+ const merchantCurrencyKey = (merchantKey, currency) => JSON.stringify([merchantKey, currency]);
112
+ const withinTolerance = (value, target, tolerance) => Math.abs(value - target) <= tolerance;
113
+ export const detectRecurringCadence = (series, minOccurrences, decimals) => {
114
+ const sorted = R.sortBy(series, [(point) => point.date, 'asc']);
115
+ if (sorted.length < minOccurrences)
116
+ return null;
117
+ const gaps = R.zipWith(sorted, sorted.slice(1), (a, b) => daysBetween(a.date, b.date));
118
+ const isConsistentCadence = gaps.every((gap) => withinTolerance(gap, CADENCE_NOMINAL_GAP_DAYS, CADENCE_DAY_TOLERANCE_DAYS));
119
+ if (!isConsistentCadence)
120
+ return null;
121
+ const typicalAmount = R.meanBy(sorted, (point) => point.amount);
122
+ const amountTolerance = typicalAmount * (CADENCE_AMOUNT_TOLERANCE_PCT / 100);
123
+ const isStableAmount = sorted.every((point) => withinTolerance(point.amount, typicalAmount, amountTolerance));
124
+ if (!isStableAmount)
125
+ return null;
126
+ const lastDate = sorted[sorted.length - 1].date;
127
+ return {
128
+ typicalAmount: roundToDecimals(typicalAmount, decimals),
129
+ occurrences: sorted.length,
130
+ lastDate,
131
+ suggestedNextDue: nextDue(lastDate, RecurringPeriod.enum.monthly),
132
+ };
133
+ };
134
+ const toRecurringCandidate = (rows, minOccurrences, locale, decimalsFor) => {
135
+ const { merchantKey, currency } = rows[0];
136
+ const cadence = detectRecurringCadence(rows, minOccurrences, decimalsFor(currency));
137
+ if (!cadence)
138
+ return null;
139
+ const latest = R.firstBy(rows, [(row) => row.date, 'desc']);
140
+ return {
141
+ merchant: merchantKey,
142
+ currency,
143
+ category: localizeCategoryName(latest.category, latest.categoryNames, locale) ?? latest.category,
144
+ ...cadence,
145
+ };
146
+ };
147
+ export const shapeRecurringCandidates = (rows, minOccurrences, locale, decimalsFor) => R.pipe(rows, R.groupBy((row) => merchantCurrencyKey(row.merchantKey, row.currency)), R.values(), R.map((groupRows) => toRecurringCandidate(groupRows, minOccurrences, locale, decimalsFor)), R.filter(R.isNonNull), R.sortBy([(candidate) => candidate.occurrences, 'desc'], [(candidate) => candidate.merchant, 'asc']));
@@ -0,0 +1,2 @@
1
+ export const internalAccountNameFor = (cardName) => `Card: ${cardName}`;
2
+ export const isCardRename = (currentName, newName) => newName !== undefined && newName.toLowerCase() !== currentName.toLowerCase();
@@ -0,0 +1,69 @@
1
+ import * as R from 'remeda';
2
+ import { ExclusionReason, CRYPTO_CURRENCIES, MS_PER_HOUR, } from '../models/currency-rate.js';
3
+ import { roundToDecimals } from './money.js';
4
+ export const toBulkItem = (input, result) => result.match((rate) => ({ status: 'ok', rate }), (error) => ({ status: 'error', from: input.from, to: input.to, error }));
5
+ export const buildBulkResult = (items, outcomes) => R.pipe(R.zip(items, outcomes), R.map(([input, outcome]) => toBulkItem(input, outcome)));
6
+ export const isCryptoPair = (from, to) => CRYPTO_CURRENCIES.has(from) || CRYPTO_CURRENCIES.has(to);
7
+ export const isStale = (asOf, now, thresholdHours) => now.getTime() - new Date(asOf).getTime() > thresholdHours * MS_PER_HOUR;
8
+ export const convert = (amount, from, to, rates, now, options) => {
9
+ if (from === to) {
10
+ return {
11
+ value: roundToDecimals(amount, options.decimals),
12
+ rate: 1,
13
+ asOf: now.toISOString(),
14
+ stale: false,
15
+ noRate: false,
16
+ };
17
+ }
18
+ const match = R.find(rates, (r) => r.fromCode === from && r.toCode === to);
19
+ if (!match)
20
+ return { value: null, rate: null, asOf: null, stale: false, noRate: true };
21
+ const thresholdHours = isCryptoPair(from, to) ? options.thresholds.cryptoHours : options.thresholds.fiatHours;
22
+ return {
23
+ value: roundToDecimals(amount * match.rate, options.decimals),
24
+ rate: match.rate,
25
+ asOf: match.asOf,
26
+ stale: isStale(match.asOf, now, thresholdHours),
27
+ noRate: false,
28
+ };
29
+ };
30
+ export const valueAccount = (account, baseCurrency, rates, now, baseDecimals, thresholds) => {
31
+ const { value, rate, asOf, stale, noRate } = convert(account.balance, account.currency, baseCurrency, rates, now, {
32
+ decimals: baseDecimals,
33
+ thresholds,
34
+ });
35
+ if (noRate || value === null || rate === null || asOf === null)
36
+ return account;
37
+ return { ...account, converted: { baseCurrency, value, rate, asOf, stale } };
38
+ };
39
+ const consolidate = (contributions, decimals) => {
40
+ const [included, excluded] = R.partition(contributions, (c) => c.converted !== undefined);
41
+ const oldest = R.firstBy(included, (c) => new Date(c.converted.asOf).getTime());
42
+ return {
43
+ total: roundToDecimals(R.sumBy(included, (c) => c.converted.value), decimals),
44
+ stale: included.some((c) => c.converted.stale),
45
+ asOf: oldest?.converted.asOf ?? null,
46
+ excludedKeys: excluded.map((c) => c.key),
47
+ };
48
+ };
49
+ export const consolidateNetWorth = (balances, baseCurrency, baseDecimals) => {
50
+ const { total, excludedKeys } = consolidate(balances.map((b) => ({ key: b.id, converted: b.converted })), baseDecimals);
51
+ return { baseCurrency, total, excluded: excludedKeys };
52
+ };
53
+ export const consolidateInCurrency = (amountsByCurrency, target, rates, now, thresholds, targetDecimals) => {
54
+ const contributions = amountsByCurrency
55
+ .filter(({ amount }) => amount !== 0)
56
+ .map(({ currency, amount }) => {
57
+ const result = convert(amount, currency, target, rates, now, { decimals: targetDecimals, thresholds });
58
+ return result.noRate
59
+ ? { key: currency, converted: undefined }
60
+ : { key: currency, converted: { value: result.value, asOf: result.asOf, stale: result.stale } };
61
+ });
62
+ const { total, stale, asOf, excludedKeys } = consolidate(contributions, targetDecimals);
63
+ return {
64
+ total,
65
+ stale,
66
+ asOf,
67
+ excluded: excludedKeys.map((currency) => ({ currency, reason: ExclusionReason.enum.no_rate })),
68
+ };
69
+ };
@@ -0,0 +1,40 @@
1
+ import { Script as VmScript } from 'node:vm';
2
+ import * as R from 'remeda';
3
+ import { HTML_DOCUMENT_ROOT_PATTERN, SKIPPED_SCRIPT_TYPES, SCRIPT_TAG_PATTERN, ATTRIBUTE_PATTERN, EXTERNAL_SCRIPT_ISSUE, } from '../models/dashboard.js';
4
+ export const findHtmlValidationIssues = (html) => [
5
+ ...(isNonEmptyContent(html) ? [] : ['content must not be empty']),
6
+ ...(hasHtmlDocumentRoot(html)
7
+ ? [
8
+ 'content must be a fragment (sections + script) — remove the <!doctype>/<html> root; the shell (GET /ui) now provides it',
9
+ ]
10
+ : []),
11
+ ...findExternalScriptIssues(html),
12
+ ...findScriptSyntaxIssues(html),
13
+ ];
14
+ const isNonEmptyContent = (html) => html.trim().length > 0;
15
+ const hasHtmlDocumentRoot = (html) => HTML_DOCUMENT_ROOT_PATTERN.test(html);
16
+ const parseScriptTag = (match) => ({ attributes: match[1] ?? '', body: match[2] ?? '' });
17
+ const normalizeScriptType = (rawType) => (rawType.split(';')[0] ?? '').trim().toLowerCase();
18
+ const parseAttributes = (attributes) => {
19
+ return new Map(R.pipe([...attributes.matchAll(ATTRIBUTE_PATTERN)], R.filter(([, name]) => !!name), R.map(([, name, doubleQuoted, singleQuoted, unquoted]) => [name.toLowerCase(), (doubleQuoted ?? singleQuoted ?? unquoted ?? true)]), R.uniqueBy(([key]) => key)));
20
+ };
21
+ const isCheckableInlineScript = (script) => {
22
+ const attributes = parseAttributes(script.attributes);
23
+ if (attributes.has('src'))
24
+ return false;
25
+ const rawType = attributes.get('type');
26
+ const type = typeof rawType === 'string' ? normalizeScriptType(rawType) : undefined;
27
+ return !type || !SKIPPED_SCRIPT_TYPES.includes(type);
28
+ };
29
+ const hasExternalSrc = (script) => parseAttributes(script.attributes).has('src');
30
+ const findExternalScriptIssues = (html) => R.pipe([...html.matchAll(SCRIPT_TAG_PATTERN)], R.map(parseScriptTag), R.filter(hasExternalSrc), R.map(R.constant(EXTERNAL_SCRIPT_ISSUE)));
31
+ const findScriptSyntaxError = (script) => {
32
+ try {
33
+ new VmScript(script.body);
34
+ return null;
35
+ }
36
+ catch (error) {
37
+ return `inline <script> has a syntax error: ${error.message}`;
38
+ }
39
+ };
40
+ const findScriptSyntaxIssues = (html) => R.pipe([...html.matchAll(SCRIPT_TAG_PATTERN)], R.map(parseScriptTag), R.filter(isCheckableInlineScript), R.map(findScriptSyntaxError), R.filter(R.isNonNull));