@rfc0/patty 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (465) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +214 -2
  3. package/dist/adapters/access-tokens.js +7 -0
  4. package/dist/adapters/accounts.js +37 -0
  5. package/dist/adapters/auth.js +11 -0
  6. package/dist/adapters/bills.js +32 -0
  7. package/dist/adapters/budgets.js +29 -0
  8. package/dist/adapters/categories.js +32 -0
  9. package/dist/adapters/client-grants.js +7 -0
  10. package/dist/adapters/credit-cards.js +33 -0
  11. package/dist/adapters/currencies.js +2 -0
  12. package/dist/adapters/currency-rates.js +18 -0
  13. package/dist/adapters/dashboards.js +43 -0
  14. package/dist/adapters/demo.js +13 -0
  15. package/dist/adapters/instance-settings.js +7 -0
  16. package/dist/adapters/invites.js +7 -0
  17. package/dist/adapters/recurring.js +55 -0
  18. package/dist/adapters/sessions.js +7 -0
  19. package/dist/adapters/settings.js +4 -0
  20. package/dist/adapters/setup-codes.js +7 -0
  21. package/dist/adapters/tags.js +9 -0
  22. package/dist/adapters/transactions.js +95 -0
  23. package/dist/adapters/users.js +7 -0
  24. package/dist/common/build-version.js +5 -0
  25. package/dist/common/errors.js +118 -0
  26. package/dist/common/net.js +71 -0
  27. package/dist/common/result.js +7 -0
  28. package/dist/composition/auth.js +106 -0
  29. package/dist/composition/boot.js +27 -0
  30. package/dist/composition/cli.js +86 -0
  31. package/dist/composition/demo/seed.js +92 -0
  32. package/dist/composition/demo/shell.js +107 -0
  33. package/dist/composition/export.js +89 -0
  34. package/dist/composition/http.js +110 -0
  35. package/dist/composition/import.js +55 -0
  36. package/dist/composition/lazy-modules.js +2 -0
  37. package/dist/composition/runtime.js +115 -0
  38. package/dist/composition/sign-in/interpreter.js +154 -0
  39. package/dist/composition/sign-in/server.js +36 -0
  40. package/dist/composition/sign-in/wiring.js +23 -0
  41. package/dist/composition/stdio.js +69 -0
  42. package/dist/config.js +136 -0
  43. package/dist/controllers/account/account.js +88 -0
  44. package/dist/controllers/account/transaction.js +119 -0
  45. package/dist/controllers/account/transfer.js +34 -0
  46. package/dist/controllers/aggregate.js +40 -0
  47. package/dist/controllers/auth/access-tokens.js +61 -0
  48. package/dist/controllers/auth/grants.js +136 -0
  49. package/dist/controllers/auth/key-export.js +20 -0
  50. package/dist/controllers/auth/owner.js +80 -0
  51. package/dist/controllers/auth/password.js +35 -0
  52. package/dist/controllers/auth/session.js +50 -0
  53. package/dist/controllers/auth/step-up.js +8 -0
  54. package/dist/controllers/auth/users.js +183 -0
  55. package/dist/controllers/budgets.js +87 -0
  56. package/dist/controllers/categories.js +67 -0
  57. package/dist/controllers/correlations.js +112 -0
  58. package/dist/controllers/credit-card/bill.js +105 -0
  59. package/dist/controllers/credit-card/credit-card.js +129 -0
  60. package/dist/controllers/credit-card/transaction.js +181 -0
  61. package/dist/controllers/currencies.js +1 -0
  62. package/dist/controllers/currency-rates.js +40 -0
  63. package/dist/controllers/dashboards.js +68 -0
  64. package/dist/controllers/demo/seed.js +31 -0
  65. package/dist/controllers/demo/tour.js +12 -0
  66. package/dist/controllers/deps.js +6 -0
  67. package/dist/controllers/instance.js +6 -0
  68. package/dist/controllers/merchants.js +12 -0
  69. package/dist/controllers/recurring.js +70 -0
  70. package/dist/controllers/resolve.js +37 -0
  71. package/dist/controllers/settings.js +47 -0
  72. package/dist/controllers/status.js +19 -0
  73. package/dist/controllers/summary.js +21 -0
  74. package/dist/controllers/tags.js +19 -0
  75. package/dist/controllers/transaction/bulk.js +6 -0
  76. package/dist/controllers/transaction/core.js +49 -0
  77. package/dist/controllers/transaction/read.js +28 -0
  78. package/dist/diplomat/auth/credentials.js +58 -0
  79. package/dist/diplomat/auth/sign-in-store.js +18 -0
  80. package/dist/diplomat/cli/commands/auth.js +100 -0
  81. package/dist/diplomat/cli/commands/db.js +72 -0
  82. package/dist/diplomat/cli/commands/demo.js +68 -0
  83. package/dist/diplomat/cli/commands/key.js +119 -0
  84. package/dist/diplomat/cli/commands/login.js +151 -0
  85. package/dist/diplomat/cli/commands/setup.js +132 -0
  86. package/dist/diplomat/cli/commands/users.js +123 -0
  87. package/dist/diplomat/cli/commands.js +61 -0
  88. package/dist/diplomat/cli/export-file.js +37 -0
  89. package/dist/diplomat/cli/import-file.js +44 -0
  90. package/dist/diplomat/cli/io.js +61 -0
  91. package/dist/diplomat/cli/key-export-approval.js +37 -0
  92. package/dist/diplomat/cli/messages.js +96 -0
  93. package/dist/diplomat/cli/prompt.js +74 -0
  94. package/dist/diplomat/cli/terminal.js +81 -0
  95. package/dist/diplomat/client-config/clients.js +150 -0
  96. package/dist/diplomat/client-config/merge.js +41 -0
  97. package/dist/diplomat/db/bootstrap.js +98 -0
  98. package/dist/diplomat/db/database-files.js +147 -0
  99. package/dist/diplomat/db/driver.js +167 -0
  100. package/dist/diplomat/db/effects.js +101 -0
  101. package/dist/diplomat/db/engine.js +9 -0
  102. package/dist/diplomat/db/export.js +22 -0
  103. package/dist/diplomat/db/file-lock.js +82 -0
  104. package/dist/diplomat/db/key-lock.js +14 -0
  105. package/dist/diplomat/db/locale-cache.js +23 -0
  106. package/dist/diplomat/db/migration-barrier.js +57 -0
  107. package/dist/diplomat/db/migration-journal.js +18 -0
  108. package/dist/diplomat/db/migration-lock.js +15 -0
  109. package/dist/diplomat/db/migrations.js +11 -0
  110. package/dist/diplomat/db/present.js +17 -0
  111. package/dist/diplomat/db/queries/aggregate-whitelist.js +35 -0
  112. package/dist/diplomat/db/queries/filters.js +59 -0
  113. package/dist/diplomat/db/queries/fts.js +18 -0
  114. package/dist/diplomat/db/queries/scope.js +8 -0
  115. package/dist/diplomat/db/queries/transaction-select.js +26 -0
  116. package/dist/diplomat/db/queries/tx-predicates.js +13 -0
  117. package/dist/diplomat/db/repos/access-tokens.js +27 -0
  118. package/dist/diplomat/db/repos/accounts.js +91 -0
  119. package/dist/diplomat/db/repos/bills.js +93 -0
  120. package/dist/diplomat/db/repos/budgets.js +72 -0
  121. package/dist/diplomat/db/repos/categories.js +53 -0
  122. package/dist/diplomat/db/repos/client-grants.js +67 -0
  123. package/dist/diplomat/db/repos/correlations.js +66 -0
  124. package/dist/diplomat/db/repos/credit-cards.js +67 -0
  125. package/dist/diplomat/db/repos/currencies.js +8 -0
  126. package/dist/diplomat/db/repos/currency-rates.js +40 -0
  127. package/dist/diplomat/db/repos/dashboards.js +123 -0
  128. package/dist/diplomat/db/repos/health.js +12 -0
  129. package/dist/diplomat/db/repos/instance-settings.js +14 -0
  130. package/dist/diplomat/db/repos/instance.js +58 -0
  131. package/dist/diplomat/db/repos/invites.js +43 -0
  132. package/dist/diplomat/db/repos/merchants.js +121 -0
  133. package/dist/diplomat/db/repos/recurring.js +29 -0
  134. package/dist/diplomat/db/repos/sessions.js +19 -0
  135. package/dist/diplomat/db/repos/settings.js +41 -0
  136. package/dist/diplomat/db/repos/setup-codes.js +28 -0
  137. package/dist/diplomat/db/repos/sub-categories.js +67 -0
  138. package/dist/diplomat/db/repos/tags.js +51 -0
  139. package/dist/diplomat/db/repos/transaction-tags.js +57 -0
  140. package/dist/diplomat/db/repos/transactions.js +163 -0
  141. package/dist/diplomat/db/repos/users.js +47 -0
  142. package/dist/diplomat/db/safety-copy.js +87 -0
  143. package/dist/diplomat/db/schema.js +348 -0
  144. package/dist/diplomat/db/seed/categories.js +112 -0
  145. package/dist/diplomat/db/seed/currencies.js +9 -0
  146. package/dist/diplomat/db/seed/demo/br.js +98 -0
  147. package/dist/diplomat/db/seed/demo/co.js +89 -0
  148. package/dist/diplomat/db/seed/demo/index.js +12 -0
  149. package/dist/diplomat/db/seed/demo/mx.js +90 -0
  150. package/dist/diplomat/db/seed/demo/shared.js +39 -0
  151. package/dist/diplomat/db/seed/demo/us.js +90 -0
  152. package/dist/diplomat/db/seed/merchant-rules.js +188 -0
  153. package/dist/diplomat/db/sqlite-errors.js +40 -0
  154. package/dist/diplomat/db/tenancy-integrity.js +45 -0
  155. package/dist/diplomat/db/version-guard.js +16 -0
  156. package/dist/diplomat/http/auth-pages.js +41 -0
  157. package/dist/diplomat/http/auth-paths.js +46 -0
  158. package/dist/diplomat/http/bearer.js +15 -0
  159. package/dist/diplomat/http/connect-pages.js +51 -0
  160. package/dist/diplomat/http/context.js +17 -0
  161. package/dist/diplomat/http/cookies.js +27 -0
  162. package/dist/diplomat/http/form-pages.js +38 -0
  163. package/dist/diplomat/http/hooks/auth.js +106 -0
  164. package/dist/diplomat/http/hooks/demo-marker.js +59 -0
  165. package/dist/diplomat/http/openapi.js +73 -0
  166. package/dist/diplomat/http/principal.js +1 -0
  167. package/dist/diplomat/http/rate-limiter.js +78 -0
  168. package/dist/diplomat/http/remedy.js +26 -0
  169. package/dist/diplomat/http/respond.js +50 -0
  170. package/dist/diplomat/http/routes/account.js +226 -0
  171. package/dist/diplomat/http/routes/aggregate.js +28 -0
  172. package/dist/diplomat/http/routes/auth.js +105 -0
  173. package/dist/diplomat/http/routes/budget.js +34 -0
  174. package/dist/diplomat/http/routes/category.js +109 -0
  175. package/dist/diplomat/http/routes/connect.js +124 -0
  176. package/dist/diplomat/http/routes/credit-card.js +263 -0
  177. package/dist/diplomat/http/routes/currency-rates.js +60 -0
  178. package/dist/diplomat/http/routes/currency.js +16 -0
  179. package/dist/diplomat/http/routes/dashboard.js +93 -0
  180. package/dist/diplomat/http/routes/invite.js +63 -0
  181. package/dist/diplomat/http/routes/recurring.js +65 -0
  182. package/dist/diplomat/http/routes/settings.js +38 -0
  183. package/dist/diplomat/http/routes/summary.js +23 -0
  184. package/dist/diplomat/http/routes/system.js +29 -0
  185. package/dist/diplomat/http/routes/tag.js +51 -0
  186. package/dist/diplomat/http/routes/tokens.js +72 -0
  187. package/dist/diplomat/http/routes/transaction.js +55 -0
  188. package/dist/diplomat/http/routes/transfer.js +35 -0
  189. package/dist/diplomat/http/routes/ui.js +110 -0
  190. package/dist/diplomat/http/routes/users.js +156 -0
  191. package/dist/diplomat/http/routes/well-known.js +26 -0
  192. package/dist/diplomat/http/routes.js +85 -0
  193. package/dist/diplomat/http/session.js +34 -0
  194. package/dist/diplomat/http/token-pages.js +75 -0
  195. package/dist/diplomat/http/ui-files.js +21 -0
  196. package/dist/diplomat/http/user-pages.js +93 -0
  197. package/dist/diplomat/mcp/annotations.js +8 -0
  198. package/dist/diplomat/mcp/auth-info.js +20 -0
  199. package/dist/diplomat/mcp/context.js +14 -0
  200. package/dist/diplomat/mcp/definition.js +3 -0
  201. package/dist/diplomat/mcp/gate.js +15 -0
  202. package/dist/diplomat/mcp/instructions.js +19 -0
  203. package/dist/diplomat/mcp/prompts.js +125 -0
  204. package/dist/diplomat/mcp/register.js +12 -0
  205. package/dist/diplomat/mcp/remedy.js +17 -0
  206. package/dist/diplomat/mcp/resources.js +93 -0
  207. package/dist/diplomat/mcp/respond.js +20 -0
  208. package/dist/diplomat/mcp/route.js +62 -0
  209. package/dist/diplomat/mcp/scopes.js +53 -0
  210. package/dist/diplomat/mcp/server.js +26 -0
  211. package/dist/diplomat/mcp/shared.js +5 -0
  212. package/dist/diplomat/mcp/stdio-session.js +94 -0
  213. package/dist/diplomat/mcp/stdio.js +23 -0
  214. package/dist/diplomat/mcp/tool-name.js +59 -0
  215. package/dist/diplomat/mcp/tools/account.js +218 -0
  216. package/dist/diplomat/mcp/tools/aggregate.js +32 -0
  217. package/dist/diplomat/mcp/tools/budget.js +99 -0
  218. package/dist/diplomat/mcp/tools/category.js +103 -0
  219. package/dist/diplomat/mcp/tools/correlations.js +70 -0
  220. package/dist/diplomat/mcp/tools/credit-card.js +239 -0
  221. package/dist/diplomat/mcp/tools/currency-rates.js +62 -0
  222. package/dist/diplomat/mcp/tools/dashboard.js +75 -0
  223. package/dist/diplomat/mcp/tools/index.js +31 -0
  224. package/dist/diplomat/mcp/tools/recurring.js +62 -0
  225. package/dist/diplomat/mcp/tools/summary.js +30 -0
  226. package/dist/diplomat/mcp/tools/system.js +83 -0
  227. package/dist/diplomat/mcp/tools/tag.js +48 -0
  228. package/dist/diplomat/mcp/tools/transaction.js +53 -0
  229. package/dist/diplomat/mcp/tools/transfer.js +28 -0
  230. package/dist/diplomat/mcp/tour.js +87 -0
  231. package/dist/logic/account.js +79 -0
  232. package/dist/logic/aggregate.js +37 -0
  233. package/dist/logic/auth/bearer.js +35 -0
  234. package/dist/logic/auth/grant.js +126 -0
  235. package/dist/logic/auth/key-export.js +10 -0
  236. package/dist/logic/auth/keychain.js +3 -0
  237. package/dist/logic/auth/message.js +22 -0
  238. package/dist/logic/auth/origin.js +57 -0
  239. package/dist/logic/auth/owner.js +22 -0
  240. package/dist/logic/auth/password.js +3 -0
  241. package/dist/logic/auth/redact.js +25 -0
  242. package/dist/logic/auth/revoke.js +28 -0
  243. package/dist/logic/auth/scope.js +17 -0
  244. package/dist/logic/auth/session.js +30 -0
  245. package/dist/logic/auth/sign-in-flow.js +305 -0
  246. package/dist/logic/auth/time.js +2 -0
  247. package/dist/logic/auth/token.js +74 -0
  248. package/dist/logic/auth/user-plans.js +84 -0
  249. package/dist/logic/auth/users.js +78 -0
  250. package/dist/logic/balance.js +2 -0
  251. package/dist/logic/bill.js +74 -0
  252. package/dist/logic/budget.js +78 -0
  253. package/dist/logic/category.js +37 -0
  254. package/dist/logic/classify.js +21 -0
  255. package/dist/logic/correlations.js +147 -0
  256. package/dist/logic/credit-card.js +2 -0
  257. package/dist/logic/currency-rate.js +69 -0
  258. package/dist/logic/dashboard.js +40 -0
  259. package/dist/logic/demo/database.js +30 -0
  260. package/dist/logic/demo/plan.js +308 -0
  261. package/dist/logic/demo/tour.js +33 -0
  262. package/dist/logic/export-destination.js +12 -0
  263. package/dist/logic/key-import.js +15 -0
  264. package/dist/logic/locale.js +5 -0
  265. package/dist/logic/localize.js +12 -0
  266. package/dist/logic/merchant.js +31 -0
  267. package/dist/logic/migration.js +1 -0
  268. package/dist/logic/money.js +12 -0
  269. package/dist/logic/period.js +45 -0
  270. package/dist/logic/persistence.js +48 -0
  271. package/dist/logic/recurring.js +51 -0
  272. package/dist/logic/resolve.js +44 -0
  273. package/dist/logic/summary.js +29 -0
  274. package/dist/logic/tag.js +13 -0
  275. package/dist/logic/transaction.js +197 -0
  276. package/dist/main.js +42 -0
  277. package/dist/models/account.js +197 -0
  278. package/dist/models/aggregate.js +61 -0
  279. package/dist/models/auth/bearer.js +11 -0
  280. package/dist/models/auth/entity.js +17 -0
  281. package/dist/models/auth/errors.js +42 -0
  282. package/dist/models/auth/grant.js +58 -0
  283. package/dist/models/auth/key-export.js +11 -0
  284. package/dist/models/auth/message.js +50 -0
  285. package/dist/models/auth/mode.js +7 -0
  286. package/dist/models/auth/origin.js +16 -0
  287. package/dist/models/auth/owner.js +36 -0
  288. package/dist/models/auth/password.js +24 -0
  289. package/dist/models/auth/principal.js +26 -0
  290. package/dist/models/auth/redact.js +4 -0
  291. package/dist/models/auth/scope.js +9 -0
  292. package/dist/models/auth/session.js +19 -0
  293. package/dist/models/auth/sign-in-flow.js +102 -0
  294. package/dist/models/auth/sign-in.js +41 -0
  295. package/dist/models/auth/time.js +5 -0
  296. package/dist/models/auth/token.js +50 -0
  297. package/dist/models/auth/users.js +52 -0
  298. package/dist/models/bill.js +55 -0
  299. package/dist/models/budget.js +106 -0
  300. package/dist/models/category.js +52 -0
  301. package/dist/models/client-config.js +18 -0
  302. package/dist/models/correlations.js +215 -0
  303. package/dist/models/credit-card.js +156 -0
  304. package/dist/models/currency-rate.js +83 -0
  305. package/dist/models/dashboard.js +54 -0
  306. package/dist/models/database.js +16 -0
  307. package/dist/models/date.js +8 -0
  308. package/dist/models/demo/core.js +58 -0
  309. package/dist/models/demo/tour.js +41 -0
  310. package/dist/models/encryption-key.js +2 -0
  311. package/dist/models/error.js +13 -0
  312. package/dist/models/export.js +9 -0
  313. package/dist/models/id.js +2 -0
  314. package/dist/models/instance.js +7 -0
  315. package/dist/models/key-import.js +6 -0
  316. package/dist/models/locale.js +25 -0
  317. package/dist/models/merchant.js +12 -0
  318. package/dist/models/money.js +14 -0
  319. package/dist/models/package.js +12 -0
  320. package/dist/models/page.js +56 -0
  321. package/dist/models/persistence.js +1 -0
  322. package/dist/models/prompts.js +5 -0
  323. package/dist/models/recurring.js +54 -0
  324. package/dist/models/remedy.js +17 -0
  325. package/dist/models/resolution.js +1 -0
  326. package/dist/models/startup.js +7 -0
  327. package/dist/models/summary.js +24 -0
  328. package/dist/models/tag.js +14 -0
  329. package/dist/models/tenancy.js +10 -0
  330. package/dist/models/transaction-tag.js +6 -0
  331. package/dist/models/transaction.js +275 -0
  332. package/dist/wire/db/access-tokens.js +1 -0
  333. package/dist/wire/db/accounts.js +7 -0
  334. package/dist/wire/db/aggregate.js +16 -0
  335. package/dist/wire/db/bills.js +14 -0
  336. package/dist/wire/db/budgets.js +33 -0
  337. package/dist/wire/db/categories.js +14 -0
  338. package/dist/wire/db/client-grants.js +1 -0
  339. package/dist/wire/db/correlations.js +49 -0
  340. package/dist/wire/db/credit-cards.js +1 -0
  341. package/dist/wire/db/currencies.js +1 -0
  342. package/dist/wire/db/currency-rates.js +1 -0
  343. package/dist/wire/db/dashboards.js +1 -0
  344. package/dist/wire/db/instance-settings.js +1 -0
  345. package/dist/wire/db/invites.js +1 -0
  346. package/dist/wire/db/merchants.js +18 -0
  347. package/dist/wire/db/recurring.js +19 -0
  348. package/dist/wire/db/sessions.js +1 -0
  349. package/dist/wire/db/settings.js +1 -0
  350. package/dist/wire/db/setup-codes.js +1 -0
  351. package/dist/wire/db/tags.js +1 -0
  352. package/dist/wire/db/tenancy.js +1 -0
  353. package/dist/wire/db/transactions.js +89 -0
  354. package/dist/wire/db/users.js +1 -0
  355. package/dist/wire/in/accounts.js +26 -0
  356. package/dist/wire/in/aggregate.js +10 -0
  357. package/dist/wire/in/auth.js +107 -0
  358. package/dist/wire/in/bills.js +11 -0
  359. package/dist/wire/in/budgets.js +11 -0
  360. package/dist/wire/in/categories.js +9 -0
  361. package/dist/wire/in/cli.js +106 -0
  362. package/dist/wire/in/coerce.js +6 -0
  363. package/dist/wire/in/common.js +17 -0
  364. package/dist/wire/in/credit-cards.js +16 -0
  365. package/dist/wire/in/currency-rates.js +8 -0
  366. package/dist/wire/in/period.js +7 -0
  367. package/dist/wire/in/recurring.js +6 -0
  368. package/dist/wire/in/settings.js +5 -0
  369. package/dist/wire/in/summary.js +5 -0
  370. package/dist/wire/in/tags.js +2 -0
  371. package/dist/wire/in/transactions.js +31 -0
  372. package/dist/wire/out/bills.js +9 -0
  373. package/dist/wire/out/budgets.js +10 -0
  374. package/dist/wire/out/client-config.js +2 -0
  375. package/dist/wire/out/common.js +4 -0
  376. package/dist/wire/out/credit-cards.js +15 -0
  377. package/dist/wire/out/currency-rates.js +11 -0
  378. package/dist/wire/out/errors.js +58 -0
  379. package/dist/wire/out/recurring.js +6 -0
  380. package/dist/wire/out/status.js +10 -0
  381. package/dist/wire/out/summary.js +9 -0
  382. package/dist/wire/out/transactions.js +52 -0
  383. package/drizzle/0000_futuristic_umar.sql +124 -0
  384. package/drizzle/0001_fts5_search.sql +23 -0
  385. package/drizzle/0002_rename_graph_to_history.sql +7 -0
  386. package/drizzle/0003_lyrical_hairball.sql +2 -0
  387. package/drizzle/0004_misty_ikaris.sql +7 -0
  388. package/drizzle/0005_credit-liability-accounts.sql +14 -0
  389. package/drizzle/0006_smart_aqueduct.sql +1 -0
  390. package/drizzle/0007_add_dashboards.sql +5 -0
  391. package/drizzle/0008_yummy_madripoor.sql +1 -0
  392. package/drizzle/0009_version_groundwork.sql +9 -0
  393. package/drizzle/0010_category_merchant_association_cascade.sql +16 -0
  394. package/drizzle/0011_dashboard_id_normalization.sql +16 -0
  395. package/drizzle/0012_hot_the_spike.sql +12 -0
  396. package/drizzle/0013_recurring_rules_merchant.sql +1 -0
  397. package/drizzle/0014_dashboard_source_discriminator.sql +17 -0
  398. package/drizzle/0015_currencies_decimals.sql +1 -0
  399. package/drizzle/0016_unusual_zaran.sql +13 -0
  400. package/drizzle/0017_premium_blur.sql +1 -0
  401. package/drizzle/0018_auth_identity.sql +39 -0
  402. package/drizzle/0019_access_tokens.sql +16 -0
  403. package/drizzle/0020_stdio_sign_in.sql +27 -0
  404. package/drizzle/0021_tenancy_data.sql +289 -0
  405. package/drizzle/0022_user_management.sql +17 -0
  406. package/drizzle/0023_instance_settings_row.sql +2 -0
  407. package/drizzle/0024_credentials_changed_at.sql +2 -0
  408. package/drizzle/0025_instance_kind.sql +2 -0
  409. package/drizzle/0026_demo_seeded_at.sql +2 -0
  410. package/drizzle/0027_demo_country.sql +2 -0
  411. package/drizzle/0028_reset_sign_ins.sql +2 -0
  412. package/drizzle/meta/0000_snapshot.json +894 -0
  413. package/drizzle/meta/0003_snapshot.json +910 -0
  414. package/drizzle/meta/0004_snapshot.json +951 -0
  415. package/drizzle/meta/0005_snapshot.json +991 -0
  416. package/drizzle/meta/0006_snapshot.json +998 -0
  417. package/drizzle/meta/0007_snapshot.json +1029 -0
  418. package/drizzle/meta/0008_snapshot.json +1049 -0
  419. package/drizzle/meta/0009_snapshot.json +1121 -0
  420. package/drizzle/meta/0010_snapshot.json +1121 -0
  421. package/drizzle/meta/0011_snapshot.json +1136 -0
  422. package/drizzle/meta/0012_snapshot.json +1227 -0
  423. package/drizzle/meta/0013_snapshot.json +1247 -0
  424. package/drizzle/meta/0014_snapshot.json +1267 -0
  425. package/drizzle/meta/0015_snapshot.json +1275 -0
  426. package/drizzle/meta/0016_snapshot.json +1371 -0
  427. package/drizzle/meta/0017_snapshot.json +1392 -0
  428. package/drizzle/meta/0018_snapshot.json +1603 -0
  429. package/drizzle/meta/0019_snapshot.json +1713 -0
  430. package/drizzle/meta/0020_snapshot.json +1904 -0
  431. package/drizzle/meta/0021_snapshot.json +2186 -0
  432. package/drizzle/meta/0022_snapshot.json +2311 -0
  433. package/drizzle/meta/0023_snapshot.json +2311 -0
  434. package/drizzle/meta/0024_snapshot.json +2318 -0
  435. package/drizzle/meta/0025_snapshot.json +2326 -0
  436. package/drizzle/meta/0026_snapshot.json +2333 -0
  437. package/drizzle/meta/0027_snapshot.json +2340 -0
  438. package/drizzle/meta/0028_snapshot.json +2340 -0
  439. package/drizzle/meta/_journal.json +209 -0
  440. package/package.json +106 -4
  441. package/skills/dashboard-building/SKILL.md +201 -0
  442. package/skills/patty-tour/SKILL.md +34 -0
  443. package/ui/app.css +758 -0
  444. package/ui/app.js +543 -0
  445. package/ui/connect-result.html +16 -0
  446. package/ui/connect.html +53 -0
  447. package/ui/dashboards/accounts.html +3189 -0
  448. package/ui/dashboards/budget.html +1734 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2475 -0
  452. package/ui/dashboards/dashboards.html +839 -0
  453. package/ui/dashboards/overview.html +2405 -0
  454. package/ui/dashboards/pending.html +2973 -0
  455. package/ui/dashboards/projections.html +2528 -0
  456. package/ui/dashboards/tags.html +1365 -0
  457. package/ui/invite.html +44 -0
  458. package/ui/login.html +26 -0
  459. package/ui/money.js +175 -0
  460. package/ui/setup.html +29 -0
  461. package/ui/shell.html +96 -0
  462. package/ui/token-created.html +24 -0
  463. package/ui/tokens.html +58 -0
  464. package/ui/user-invited.html +27 -0
  465. package/ui/users.html +60 -0
@@ -0,0 +1,1734 @@
1
+ <style>
2
+ .dashboard-container {
3
+ max-width: 1400px;
4
+ margin: 0 auto;
5
+ display: flex;
6
+ flex-direction: column;
7
+ gap: 1.5rem;
8
+ }
9
+
10
+ .controls-area {
11
+ display: flex;
12
+ align-items: center;
13
+ justify-content: space-between;
14
+ flex-wrap: wrap;
15
+ gap: 1rem;
16
+ background: var(--panel-bg);
17
+ border: 1px solid var(--panel-border);
18
+ padding: 0.75rem 1.25rem;
19
+ border-radius: 16px;
20
+ backdrop-filter: blur(12px);
21
+ }
22
+
23
+ .controls-group {
24
+ display: flex;
25
+ align-items: center;
26
+ gap: 1rem;
27
+ }
28
+
29
+ .controls-area label {
30
+ font-size: 0.85rem;
31
+ font-weight: 600;
32
+ color: var(--text-muted);
33
+ text-transform: uppercase;
34
+ letter-spacing: 0.05em;
35
+ }
36
+
37
+ .select-custom {
38
+ background: rgba(255, 255, 255, 0.05);
39
+ border: 1px solid var(--panel-border);
40
+ color: var(--text-main);
41
+ padding: 0.5rem 1.5rem 0.5rem 0.75rem;
42
+ border-radius: 8px;
43
+ font-family: var(--font-family);
44
+ font-weight: 500;
45
+ cursor: pointer;
46
+ outline: none;
47
+ transition: var(--transition-smooth);
48
+ appearance: none;
49
+ background-image: url("data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
50
+ background-repeat: no-repeat;
51
+ background-position: right 8px center;
52
+ background-size: 16px;
53
+ }
54
+
55
+ .select-custom:focus {
56
+ border-color: var(--accent-primary);
57
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
58
+ }
59
+
60
+ .refresh-btn {
61
+ background: rgba(255, 255, 255, 0.05);
62
+ border: 1px solid var(--panel-border);
63
+ color: var(--text-main);
64
+ padding: 0.5rem 1rem;
65
+ border-radius: 8px;
66
+ font-weight: 600;
67
+ cursor: pointer;
68
+ display: flex;
69
+ align-items: center;
70
+ gap: 0.5rem;
71
+ transition: var(--transition-smooth);
72
+ }
73
+
74
+ .refresh-btn:hover {
75
+ background: rgba(255, 255, 255, 0.1);
76
+ border-color: var(--accent-primary);
77
+ }
78
+
79
+ /* KPI Summary Cards */
80
+ .kpis-row {
81
+ display: grid;
82
+ grid-template-columns: repeat(3, 1fr);
83
+ gap: 1.5rem;
84
+ }
85
+
86
+ @media (max-width: 1024px) {
87
+ .kpis-row {
88
+ grid-template-columns: 1fr;
89
+ }
90
+ }
91
+
92
+ .kpi-card {
93
+ background: var(--panel-bg);
94
+ border: 1px solid var(--panel-border);
95
+ border-radius: 20px;
96
+ padding: 1.25rem 1.5rem;
97
+ box-shadow: var(--card-shadow);
98
+ backdrop-filter: blur(16px);
99
+ display: flex;
100
+ flex-direction: column;
101
+ gap: 0.75rem;
102
+ position: relative;
103
+ overflow: hidden;
104
+ }
105
+
106
+ .kpi-card::before {
107
+ content: '';
108
+ position: absolute;
109
+ top: 0;
110
+ left: 0;
111
+ width: 4px;
112
+ height: 100%;
113
+ }
114
+
115
+ .kpi-income::before { background: var(--income-color, #10b981); }
116
+ .kpi-expense::before { background: var(--expense-color, #f43f5e); }
117
+ .kpi-balance::before { background: var(--accent-primary, #8b5cf6); }
118
+
119
+ .kpi-title {
120
+ font-size: 0.85rem;
121
+ font-weight: 600;
122
+ color: var(--text-muted);
123
+ text-transform: uppercase;
124
+ letter-spacing: 0.05em;
125
+ display: flex;
126
+ align-items: center;
127
+ gap: 0.5rem;
128
+ }
129
+
130
+ .kpi-value {
131
+ font-size: 1.8rem;
132
+ font-weight: 800;
133
+ color: #fff;
134
+ }
135
+
136
+ .kpi-income .kpi-value { color: var(--income-color, #10b981) !important; }
137
+ .kpi-expense .kpi-value { color: var(--expense-color, #f43f5e) !important; }
138
+ .kpi-balance .kpi-value { color: var(--income-color, #10b981) !important; }
139
+ .kpi-balance.negative .kpi-value { color: var(--expense-color, #f43f5e) !important; }
140
+
141
+ .kpi-details {
142
+ font-size: 0.8rem;
143
+ color: var(--text-muted);
144
+ display: flex;
145
+ gap: 1rem;
146
+ flex-wrap: wrap;
147
+ }
148
+
149
+ .kpi-details span strong { color: #fff; }
150
+
151
+ .kpi-converted {
152
+ font-size: 0.75rem;
153
+ color: var(--text-muted);
154
+ margin-top: 0.5rem;
155
+ padding-top: 0.5rem;
156
+ border-top: 1px dashed var(--panel-border);
157
+ }
158
+
159
+ .kpi-converted strong { color: #fff; }
160
+
161
+ .kpi-converted.stale strong { color: #f59e0b; }
162
+
163
+ .kpi-converted .kpi-converted-excluded {
164
+ display: block;
165
+ margin-top: 0.15rem;
166
+ color: #f59e0b;
167
+ }
168
+
169
+ .kpi-converted .stale-flag {
170
+ background: none;
171
+ border: none;
172
+ padding: 0;
173
+ margin-left: 0.25rem;
174
+ color: inherit;
175
+ font: inherit;
176
+ cursor: help;
177
+ }
178
+
179
+ .kpi-converted .stale-flag:focus-visible {
180
+ outline: 2px solid #f59e0b;
181
+ outline-offset: 2px;
182
+ border-radius: 2px;
183
+ }
184
+
185
+ /* Charts Grid */
186
+ .charts-grid {
187
+ display: grid;
188
+ grid-template-columns: 3fr 5fr;
189
+ gap: 1.5rem;
190
+ }
191
+
192
+ @media (max-width: 1024px) {
193
+ .charts-grid {
194
+ grid-template-columns: 1fr;
195
+ }
196
+ }
197
+
198
+ .chart-card {
199
+ background: var(--panel-bg);
200
+ border: 1px solid var(--panel-border);
201
+ border-radius: 20px;
202
+ padding: 1.5rem;
203
+ box-shadow: var(--card-shadow);
204
+ backdrop-filter: blur(16px);
205
+ display: flex;
206
+ flex-direction: column;
207
+ gap: 1rem;
208
+ min-height: 340px;
209
+ }
210
+
211
+ .chart-card-title {
212
+ font-size: 1rem;
213
+ font-weight: 600;
214
+ color: var(--text-main);
215
+ display: flex;
216
+ align-items: center;
217
+ gap: 0.5rem;
218
+ }
219
+
220
+ .chart-container-inner {
221
+ position: relative;
222
+ flex: 1;
223
+ width: 100%;
224
+ height: 100%;
225
+ min-height: 250px;
226
+ }
227
+
228
+ /* Category Panels */
229
+ .categories-grid {
230
+ display: grid;
231
+ grid-template-columns: 1fr 1fr;
232
+ gap: 1.5rem;
233
+ }
234
+
235
+ @media (max-width: 900px) {
236
+ .categories-grid {
237
+ grid-template-columns: 1fr;
238
+ }
239
+ }
240
+
241
+ .category-panel {
242
+ background: var(--panel-bg);
243
+ border: 1px solid var(--panel-border);
244
+ border-radius: 24px;
245
+ padding: 1.5rem;
246
+ box-shadow: var(--card-shadow);
247
+ backdrop-filter: blur(16px);
248
+ display: flex;
249
+ flex-direction: column;
250
+ gap: 1.25rem;
251
+ }
252
+
253
+ .category-panel-header {
254
+ display: flex;
255
+ justify-content: space-between;
256
+ align-items: center;
257
+ border-bottom: 1px solid var(--panel-border);
258
+ padding-bottom: 0.75rem;
259
+ }
260
+
261
+ .category-panel-title {
262
+ font-size: 1.1rem;
263
+ font-weight: 700;
264
+ display: flex;
265
+ align-items: center;
266
+ gap: 0.5rem;
267
+ }
268
+
269
+ .category-panel-title.income { color: var(--income-color, #10b981); }
270
+ .category-panel-title.expense { color: var(--expense-color, #f43f5e); }
271
+
272
+ .category-total-badge {
273
+ font-size: 1rem;
274
+ font-weight: 800;
275
+ color: #fff;
276
+ background: rgba(255, 255, 255, 0.05);
277
+ padding: 0.25rem 0.75rem;
278
+ border-radius: 12px;
279
+ border: 1px solid var(--panel-border);
280
+ }
281
+
282
+ .categories-list {
283
+ display: flex;
284
+ flex-direction: column;
285
+ gap: 0.75rem;
286
+ }
287
+
288
+ .category-row-container {
289
+ border: 1px solid var(--panel-border);
290
+ border-radius: 14px;
291
+ overflow: hidden;
292
+ background: rgba(0, 0, 0, 0.1);
293
+ transition: var(--transition-smooth);
294
+ }
295
+
296
+ .category-row-container:hover {
297
+ border-color: rgba(255, 255, 255, 0.15);
298
+ }
299
+
300
+
301
+ .category-row-header {
302
+ padding: 1rem;
303
+ cursor: pointer;
304
+ display: flex;
305
+ flex-direction: column;
306
+ gap: 0.5rem;
307
+ user-select: none;
308
+ }
309
+
310
+ .cat-meta-info {
311
+ display: flex;
312
+ justify-content: space-between;
313
+ align-items: center;
314
+ }
315
+
316
+ .cat-name-label {
317
+ font-size: 0.95rem;
318
+ font-weight: 600;
319
+ color: #fff;
320
+ display: flex;
321
+ align-items: center;
322
+ gap: 0.5rem;
323
+ }
324
+
325
+ .cat-name-label i {
326
+ font-size: 0.8rem;
327
+ color: var(--text-muted);
328
+ transition: transform 0.3s ease;
329
+ }
330
+
331
+ .category-row-container.open .cat-name-label i {
332
+ transform: rotate(180deg);
333
+ color: var(--accent-primary, #8b5cf6);
334
+ }
335
+
336
+ .cat-val-label {
337
+ font-size: 0.95rem;
338
+ font-weight: 700;
339
+ color: #fff;
340
+ display: inline-flex;
341
+ align-items: center;
342
+ }
343
+
344
+ .cat-pct-label {
345
+ font-size: 0.72rem;
346
+ color: var(--text-muted);
347
+ margin-left: 0.5rem;
348
+ font-weight: 600;
349
+ background: rgba(255, 255, 255, 0.06);
350
+ padding: 2px 6px;
351
+ border-radius: 4px;
352
+ }
353
+
354
+ .cat-pct-label.over {
355
+ background: rgba(244, 63, 94, 0.2);
356
+ color: #f43f5e;
357
+ }
358
+
359
+ .proportion-bar-container {
360
+ width: 100%;
361
+ height: 8px;
362
+ background: rgba(255, 255, 255, 0.04);
363
+ border-radius: 4px;
364
+ overflow: hidden;
365
+ display: flex;
366
+ }
367
+
368
+ .bar-segment {
369
+ height: 100%;
370
+ transition: width 0.5s ease;
371
+ }
372
+
373
+ .bar-segment.effective-inc { background: var(--income-color, #10b981); }
374
+ .bar-segment.pending-inc {
375
+ background: repeating-linear-gradient(
376
+ 45deg,
377
+ rgba(16, 185, 129, 0.25) 0px,
378
+ rgba(16, 185, 129, 0.25) 8px,
379
+ rgba(16, 185, 129, 0.45) 8px,
380
+ rgba(16, 185, 129, 0.45) 16px
381
+ );
382
+ }
383
+
384
+ .bar-segment.effective-exp { background: var(--expense-color, #f43f5e); }
385
+ .bar-segment.pending-exp {
386
+ background: repeating-linear-gradient(
387
+ 45deg,
388
+ rgba(244, 63, 94, 0.25) 0px,
389
+ rgba(244, 63, 94, 0.25) 8px,
390
+ rgba(244, 63, 94, 0.45) 8px,
391
+ rgba(244, 63, 94, 0.45) 16px
392
+ );
393
+ }
394
+ .bar-segment.budget-ok-eff { background: #10b981; }
395
+ .bar-segment.budget-ok-pend {
396
+ background: repeating-linear-gradient(
397
+ 45deg,
398
+ rgba(16, 185, 129, 0.25) 0px,
399
+ rgba(16, 185, 129, 0.25) 8px,
400
+ rgba(16, 185, 129, 0.45) 8px,
401
+ rgba(16, 185, 129, 0.45) 16px
402
+ );
403
+ }
404
+ .bar-segment.budget-warn-eff { background: #f59e0b; }
405
+ .bar-segment.budget-warn-pend {
406
+ background: repeating-linear-gradient(
407
+ 45deg,
408
+ rgba(245, 158, 11, 0.25) 0px,
409
+ rgba(245, 158, 11, 0.25) 8px,
410
+ rgba(245, 158, 11, 0.45) 8px,
411
+ rgba(245, 158, 11, 0.45) 16px
412
+ );
413
+ }
414
+ .bar-segment.budget-over-eff { background: #f43f5e; }
415
+ .bar-segment.budget-over-pend {
416
+ background: repeating-linear-gradient(
417
+ 45deg,
418
+ rgba(244, 63, 94, 0.25) 0px,
419
+ rgba(244, 63, 94, 0.25) 8px,
420
+ rgba(244, 63, 94, 0.45) 8px,
421
+ rgba(244, 63, 94, 0.45) 16px
422
+ );
423
+ }
424
+
425
+ .cat-breakdown-text {
426
+ display: flex;
427
+ justify-content: space-between;
428
+ font-size: 0.72rem;
429
+ color: var(--text-muted);
430
+ padding: 0 0.1rem;
431
+ }
432
+
433
+ .cat-breakdown-text span strong { color: var(--text-main); }
434
+
435
+ .category-tx-details {
436
+ display: none;
437
+ border-top: 1px solid var(--panel-border);
438
+ background: rgba(0, 0, 0, 0.25);
439
+ padding: 0.75rem 1rem;
440
+ overflow-x: auto;
441
+ }
442
+
443
+ .category-tx-table {
444
+ width: 100%;
445
+ border-collapse: collapse;
446
+ font-size: 0.82rem;
447
+ text-align: left;
448
+ }
449
+
450
+ .category-tx-table th {
451
+ padding: 0.4rem 0.6rem;
452
+ color: var(--text-muted);
453
+ font-weight: 600;
454
+ border-bottom: 1px solid var(--panel-border);
455
+ }
456
+
457
+ .category-tx-table td {
458
+ padding: 0.45rem 0.6rem;
459
+ border-bottom: 1px solid rgba(255, 255, 255, 0.03);
460
+ }
461
+
462
+ .tx-status-icon {
463
+ font-size: 0.85rem;
464
+ }
465
+ .tx-status-icon.effective { color: var(--income-color, #10b981); }
466
+ .tx-status-icon.pending { color: #f59e0b; }
467
+
468
+ .state-container {
469
+ display: flex;
470
+ flex-direction: column;
471
+ align-items: center;
472
+ justify-content: center;
473
+ padding: 2rem;
474
+ gap: 0.75rem;
475
+ color: var(--text-muted);
476
+ text-align: center;
477
+ }
478
+
479
+ .state-container i {
480
+ font-size: 1.8rem;
481
+ }
482
+ </style>
483
+
484
+ <div class="dashboard-container">
485
+ <!-- Header -->
486
+ <header>
487
+ <div class="header-title-area">
488
+ <h1><i class="fa-solid fa-bullseye"></i> <span data-i18n="header_title">Monthly Budget</span></h1>
489
+ <p data-i18n="header_subtitle">Monitor your monthly limits, committed spending, and category balance</p>
490
+ </div>
491
+ <div class="controls-area">
492
+ <div class="controls-group">
493
+ <label for="month-select" data-i18n="reference_label">Reference:</label>
494
+ <select id="month-select" class="select-custom" onchange="onFilterChange()">
495
+ <option value="1">January</option>
496
+ <option value="2">February</option>
497
+ <option value="3">March</option>
498
+ <option value="4">April</option>
499
+ <option value="5">May</option>
500
+ <option value="6">June</option>
501
+ <option value="7">July</option>
502
+ <option value="8" selected>August</option>
503
+ <option value="9">September</option>
504
+ <option value="10">October</option>
505
+ <option value="11">November</option>
506
+ <option value="12">December</option>
507
+ </select>
508
+ <select id="year-select" class="select-custom" onchange="onFilterChange()">
509
+ <option value="2025">2025</option>
510
+ <option value="2026" selected>2026</option>
511
+ <option value="2027">2027</option>
512
+ </select>
513
+ </div>
514
+ <div class="controls-group">
515
+ <label for="currency-select" data-i18n="currency_label">Currency:</label>
516
+ <select id="currency-select" class="select-custom" onchange="onCurrencyChange()">
517
+ <option value="" data-i18n="currency_none">No conversion</option>
518
+ </select>
519
+ </div>
520
+ </div>
521
+ </header>
522
+
523
+ <!-- KPIs Row -->
524
+ <div class="kpis-row">
525
+ <!-- Total Incomes -->
526
+ <div class="kpi-card kpi-income">
527
+ <div class="kpi-title" data-i18n="kpi_income_total">
528
+ <i class="fa-solid fa-circle-arrow-up"></i> Total Incomes
529
+ </div>
530
+ <div class="kpi-value" id="kpi-income-val">$ 0.00</div>
531
+ <div class="kpi-details">
532
+ <span><span data-i18n="kpi_effective">Effective:</span> <strong id="kpi-income-eff" style="color: var(--income-color,#10b981)">$ 0.00</strong></span>
533
+ <span><span data-i18n="kpi_pending">Pending:</span> <strong id="kpi-income-pend" style="color: #f59e0b">$ 0.00</strong></span>
534
+ </div>
535
+ </div>
536
+
537
+ <!-- Budget Limits -->
538
+ <div class="kpi-card kpi-expense">
539
+ <div class="kpi-title" data-i18n="kpi_budget_limits">
540
+ <i class="fa-solid fa-bullseye"></i> Budget Limits
541
+ </div>
542
+ <div class="kpi-value" id="kpi-budget-limit-val">$ 0.00</div>
543
+ <div class="kpi-details">
544
+ <span><span data-i18n="kpi_committed">Committed:</span> <strong id="kpi-budget-comm-val" style="color: var(--expense-color,#f43f5e)">$ 0.00</strong></span>
545
+ <span><span data-i18n="kpi_usage">Usage:</span> <strong id="kpi-budget-pct-val">0%</strong></span>
546
+ </div>
547
+ <div class="kpi-converted" id="kpi-budget-converted" style="display:none;"></div>
548
+ </div>
549
+
550
+ <!-- Planned Balance -->
551
+ <div class="kpi-card kpi-balance" id="kpi-balance-card">
552
+ <div class="kpi-title" data-i18n="kpi_planned_balance">
553
+ <i class="fa-solid fa-scale-balanced"></i> Planned Balance (Income - Budget)
554
+ </div>
555
+ <div class="kpi-value" id="kpi-balance-val">$ 0.00</div>
556
+ <div class="kpi-details">
557
+ <span data-i18n="kpi_balance_desc">Estimated monthly net result based on active budgets</span>
558
+ </div>
559
+ </div>
560
+ </div>
561
+
562
+ <!-- Charts Grid -->
563
+ <div class="charts-grid">
564
+ <!-- Monthly Comparison (Incomes vs Budget) -->
565
+ <div class="chart-card">
566
+ <div class="chart-card-title" data-i18n="chart_compare_title">
567
+ <i class="fa-solid fa-chart-column"></i> Monthly Comparison (Incomes vs Budget)
568
+ </div>
569
+ <div class="chart-container-inner" id="monthly-compare-container">
570
+ <canvas id="monthlyCompareChart"></canvas>
571
+ </div>
572
+ </div>
573
+
574
+ <!-- Projected Cash Flow Trend -->
575
+ <div class="chart-card">
576
+ <div class="chart-card-title" data-i18n="chart_trend_title">
577
+ <i class="fa-solid fa-chart-line"></i> Projected Cash Flow Trend
578
+ </div>
579
+ <div class="chart-container-inner" id="trend-container">
580
+ <canvas id="trendChart"></canvas>
581
+ </div>
582
+ </div>
583
+ </div>
584
+
585
+ <!-- Dual Category Breakdown Panels -->
586
+ <div class="categories-grid">
587
+ <!-- Incomes by Category -->
588
+ <div class="category-panel">
589
+ <div class="category-panel-header">
590
+ <div class="category-panel-title income" data-i18n="panel_income_cat_title">
591
+ <i class="fa-solid fa-circle-arrow-up"></i> Incomes by Category
592
+ </div>
593
+ <div class="category-total-badge" id="income-categories-total">$ 0.00</div>
594
+ </div>
595
+ <div id="income-categories-list" class="categories-list">
596
+ <div class="state-container">
597
+ <i class="fa-solid fa-spinner fa-spin"></i>
598
+ <div data-i18n="loading_incomes">Loading incomes...</div>
599
+ </div>
600
+ </div>
601
+ </div>
602
+
603
+ <!-- Expenses vs Budget by Category -->
604
+ <div class="category-panel">
605
+ <div class="category-panel-header">
606
+ <div class="category-panel-title expense" data-i18n="panel_expense_budget_title">
607
+ <i class="fa-solid fa-bullseye"></i> Expenses vs Budget by Category
608
+ </div>
609
+ <div class="category-total-badge" id="expense-categories-total">$ 0.00</div>
610
+ </div>
611
+ <div id="expense-categories-list" class="categories-list">
612
+ <div class="state-container">
613
+ <i class="fa-solid fa-spinner fa-spin"></i>
614
+ <div data-i18n="loading_budgets">Loading budgets...</div>
615
+ </div>
616
+ </div>
617
+ </div>
618
+ </div>
619
+ </div>
620
+
621
+ <script>
622
+ var TRANSLATIONS = {
623
+ en: {
624
+ reference_label: "Reference:",
625
+ header_title: "Monthly Budget",
626
+ header_subtitle: "Monitor your monthly limits, committed spending, and category balance",
627
+ period_label: "Period:",
628
+ currency_label: "Currency:",
629
+ currency_none: "No conversion",
630
+ kpi_converted_label: "Converted total:",
631
+ kpi_converted_excluded: "{n} currency(ies) excluded (no rate)",
632
+ rate_stale_tooltip: "Outdated exchange rate",
633
+ btn_update: "Update",
634
+ kpi_income_total: "Total Incomes",
635
+ kpi_budget_limits: "Budget Limits",
636
+ kpi_planned_balance: "Planned Balance (Income - Budget)",
637
+ kpi_effective: "Effective:",
638
+ kpi_pending: "Pending:",
639
+ kpi_remaining: "Remaining:",
640
+ kpi_committed: "Committed:",
641
+ kpi_usage: "Usage:",
642
+ kpi_balance_desc: "Estimated monthly net result based on active budgets",
643
+ chart_compare_title: "Monthly Comparison (Incomes vs Budget)",
644
+ chart_trend_title: "Projected Cash Flow Trend",
645
+ panel_income_cat_title: "Incomes by Category",
646
+ panel_expense_budget_title: "Expenses vs Budget by Category",
647
+ cat_no_limit: "No Limit",
648
+ week: "Week",
649
+ day_label: "Day",
650
+ to_range: "to",
651
+ cumulative: "Cumulative",
652
+ col_date: "Date",
653
+ col_description: "Description",
654
+ col_account: "Account",
655
+ col_status: "Status",
656
+ col_value: "Value",
657
+ status_effective: "Effective",
658
+ status_pending: "Pending",
659
+ loading_incomes: "Loading incomes by category...",
660
+ loading_budgets: "Loading budgets and expenses by category...",
661
+ no_incomes_month: "No incomes recorded in this month.",
662
+ no_budgets_period: "No budgets configured for this period.",
663
+ no_txs_period: "No transactions in this period.",
664
+ error_loading_income: "Error loading income data.",
665
+ error_loading_budget: "Error loading budget data.",
666
+ chart_lbl_planned: "Planned / Limit",
667
+ chart_lbl_committed: "Currently Committed",
668
+ chart_lbl_proj_income: "Projected Incomes",
669
+ chart_lbl_budget_exp: "Budgeted Expenses",
670
+ chart_lbl_net_balance: "Projected Net Balance",
671
+ january: "January", february: "February", march: "March", april: "April",
672
+ may: "May", june: "June", july: "July", august: "August",
673
+ september: "September", october: "October", november: "November", december: "December"
674
+ },
675
+ pt: {
676
+ reference_label: "Referência:",
677
+ header_title: "Orçamento Mensal",
678
+ header_subtitle: "Monitore seus limites mensais, despesas comprometidas e saldo por categoria",
679
+ period_label: "Período:",
680
+ currency_label: "Moeda:",
681
+ currency_none: "Sem conversão",
682
+ kpi_converted_label: "Total convertido:",
683
+ kpi_converted_excluded: "{n} moeda(s) excluída(s) (sem cotação)",
684
+ rate_stale_tooltip: "Cotação desatualizada",
685
+ btn_update: "Atualizar",
686
+ kpi_income_total: "Receitas Totais",
687
+ kpi_budget_limits: "Despesas Orçadas (Limites)",
688
+ kpi_planned_balance: "Saldo Planejado (Receita - Orçamento)",
689
+ kpi_effective: "Efetivado:",
690
+ kpi_pending: "Pendente:",
691
+ kpi_remaining: "Restante:",
692
+ kpi_committed: "Comprometido:",
693
+ kpi_usage: "Uso:",
694
+ kpi_balance_desc: "Resultado mensal estimado com base no orçamento estipulado",
695
+ chart_compare_title: "Comparativo Mensal (Receitas x Orçamento)",
696
+ chart_trend_title: "Tendência de Fluxo de Caixa Projetado",
697
+ panel_income_cat_title: "Receitas por Categoria",
698
+ panel_expense_budget_title: "Despesas vs Orçamento por Categoria",
699
+ cat_no_limit: "Sem Limite",
700
+ week: "Semana",
701
+ day_label: "Dia",
702
+ to_range: "a",
703
+ cumulative: "Acumulado",
704
+ col_date: "Data",
705
+ col_description: "Descrição",
706
+ col_account: "Conta",
707
+ col_status: "Status",
708
+ col_value: "Valor",
709
+ status_effective: "Efetivado",
710
+ status_pending: "Pendente",
711
+ loading_incomes: "Carregando receitas por categoria...",
712
+ loading_budgets: "Carregando orçamento e despesas por categoria...",
713
+ no_incomes_month: "Nenhuma receita registrada neste mês.",
714
+ no_budgets_period: "Nenhum orçamento configurado para este período.",
715
+ no_txs_period: "Nenhum lançamento no período.",
716
+ error_loading_income: "Erro ao carregar dados de receita.",
717
+ error_loading_budget: "Erro ao carregar dados de orçamento.",
718
+ chart_lbl_planned: "Planejado / Teto",
719
+ chart_lbl_committed: "Comprometido Atual",
720
+ chart_lbl_proj_income: "Receitas Projetadas",
721
+ chart_lbl_budget_exp: "Despesa Orçada",
722
+ chart_lbl_net_balance: "Saldo Líquido Orçado",
723
+ january: "Janeiro", february: "Fevereiro", march: "Março", april: "Abril",
724
+ may: "Maio", june: "Junho", july: "Julho", august: "Agosto",
725
+ september: "Setembro", october: "Outubro", november: "Novembro", december: "Dezembro"
726
+ },
727
+ es: {
728
+ reference_label: "Referencia:",
729
+ header_title: "Presupuesto Mensual",
730
+ header_subtitle: "Monitoree sus límites mensuales, gastos comprometidos y saldo por categoría",
731
+ period_label: "Período:",
732
+ currency_label: "Moneda:",
733
+ currency_none: "Sin conversión",
734
+ kpi_converted_label: "Total convertido:",
735
+ kpi_converted_excluded: "{n} moneda(s) excluida(s) (sin cotización)",
736
+ rate_stale_tooltip: "Tipo de cambio desactualizado",
737
+ btn_update: "Actualizar",
738
+ kpi_income_total: "Ingresos Totales",
739
+ kpi_budget_limits: "Presupuestos (Límites)",
740
+ kpi_planned_balance: "Saldo Planificado (Ingreso - Presupuesto)",
741
+ kpi_effective: "Efectuado:",
742
+ kpi_pending: "Pendiente:",
743
+ kpi_remaining: "Restante:",
744
+ kpi_committed: "Comprometido:",
745
+ kpi_usage: "Uso:",
746
+ kpi_balance_desc: "Resultado mensual estimado según presupuesto activo",
747
+ chart_compare_title: "Comparativo Mensual (Ingresos vs Presupuesto)",
748
+ chart_trend_title: "Tendencia de Flujo de Caja Proyectado",
749
+ panel_income_cat_title: "Ingresos por Categoría",
750
+ panel_expense_budget_title: "Gastos vs Presupuesto por Categoría",
751
+ cat_no_limit: "Sin Límite",
752
+ week: "Semana",
753
+ day_label: "Día",
754
+ to_range: "a",
755
+ cumulative: "Acumulado",
756
+ col_date: "Fecha",
757
+ col_description: "Descripción",
758
+ col_account: "Cuenta",
759
+ col_status: "Estado",
760
+ col_value: "Valor",
761
+ status_effective: "Efectuado",
762
+ status_pending: "Pendiente",
763
+ loading_incomes: "Cargando ingresos...",
764
+ loading_budgets: "Cargando presupuesto...",
765
+ no_incomes_month: "No hay ingresos registrados en este mes.",
766
+ no_budgets_period: "No hay presupuestos configurados para este período.",
767
+ no_txs_period: "Sin transacciones en este período.",
768
+ error_loading_income: "Error al cargar datos de ingresos.",
769
+ error_loading_budget: "Error al cargar datos de presupuesto.",
770
+ chart_lbl_planned: "Planificado / Límite",
771
+ chart_lbl_committed: "Comprometido Actual",
772
+ chart_lbl_proj_income: "Ingresos Proyectados",
773
+ chart_lbl_budget_exp: "Gasto Presupuestado",
774
+ chart_lbl_net_balance: "Saldo Neto Proyectado",
775
+ january: "Enero", february: "Febrero", march: "Marzo", april: "Abril",
776
+ may: "Mayo", june: "Junio", july: "Julio", august: "Agosto",
777
+ september: "Septiembre", october: "Octubre", november: "Noviembre", december: "Diciembre"
778
+ }
779
+ };
780
+
781
+ var compareChart = null;
782
+ var trendChart = null;
783
+ var currentLocale = 'en';
784
+ var currentDisplayCurrency = '';
785
+ // True once the person picks a currency; until then the selection follows the base currency.
786
+ var displayCurrencyChosen = false;
787
+
788
+ // Sync the reference selectors to ?month&year query params (deep links) or today's date, instead
789
+ // of always loading the HTML's static placeholder selection — mirrors pending.html's pattern.
790
+ (function initDefaultPeriod() {
791
+ var params = new URLSearchParams(window.location.search);
792
+ var now = new Date();
793
+ var defaultMonth = parseInt(params.get('month'), 10) || (now.getMonth() + 1);
794
+ var defaultYear = parseInt(params.get('year'), 10) || now.getFullYear();
795
+ var monthSelect = document.getElementById('month-select');
796
+ var yearSelect = document.getElementById('year-select');
797
+ if (monthSelect) monthSelect.value = String(defaultMonth);
798
+ if (yearSelect) yearSelect.value = String(defaultYear);
799
+ })();
800
+
801
+ function t(key) {
802
+ const dict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
803
+ return dict[key] || key;
804
+ }
805
+
806
+ async function checkLocale() {
807
+ try {
808
+ const res = await fetch('/api/status');
809
+ if (res.ok) {
810
+ const statusData = await res.json();
811
+ if (statusData.locale && TRANSLATIONS[statusData.locale]) {
812
+ currentLocale = statusData.locale;
813
+ }
814
+ }
815
+ } catch (e) {
816
+ console.error('Failed to load status:', e);
817
+ }
818
+ translatePage();
819
+ }
820
+
821
+ function translatePage() {
822
+ const dict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
823
+
824
+ // 1. Static text elements
825
+ document.querySelectorAll('[data-i18n]').forEach(el => {
826
+ const key = el.getAttribute('data-i18n');
827
+ if (dict[key]) {
828
+ const icon = el.querySelector('i');
829
+ if (icon) {
830
+ el.innerHTML = icon.outerHTML + ' ' + dict[key];
831
+ } else {
832
+ el.textContent = dict[key];
833
+ }
834
+ }
835
+ });
836
+
837
+ // 2. Month dropdown options
838
+ const monthSelect = document.getElementById('month-select');
839
+ if (monthSelect) {
840
+ const monthKeys = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
841
+ Array.from(monthSelect.options).forEach((opt, idx) => {
842
+ const key = monthKeys[idx];
843
+ if (dict[key]) {
844
+ opt.textContent = dict[key];
845
+ }
846
+ });
847
+ }
848
+ }
849
+
850
+ // window.__appCurrencies is populated by the shell (ui/app.js) before this script runs.
851
+ // Defaults the selection to the base currency so the converted total shows without an extra click.
852
+ async function initCurrencySelector() {
853
+ const select = document.getElementById('currency-select');
854
+ if (!select) return;
855
+
856
+ const codes = Object.keys(window.__appCurrencies || {}).sort();
857
+ codes.forEach(code => {
858
+ const opt = document.createElement('option');
859
+ opt.value = code;
860
+ opt.textContent = code;
861
+ select.appendChild(opt);
862
+ });
863
+
864
+ try {
865
+ const res = await fetch('/api/preferences');
866
+ if (res.ok) {
867
+ const prefs = await res.json();
868
+ if (prefs.baseCurrency && codes.indexOf(prefs.baseCurrency) !== -1) {
869
+ select.value = prefs.baseCurrency;
870
+ }
871
+ }
872
+ } catch (e) {
873
+ console.error('Failed to load preferences:', e);
874
+ }
875
+
876
+ currentDisplayCurrency = select.value;
877
+ }
878
+
879
+ // addMultiCurrency/valueIn/primaryCurrencyOf/magnitudeOf/mergeCurrencyMaps/formatMultiCurrencyWith/
880
+ // DEFAULT_CURRENCY are shared globals from ui/money.js (loaded before this fragment's script — see
881
+ // docs/ui.md) rather than defined here. formatCurrency stays local — and formatMultiCurrency is
882
+ // just a 1-line delegate to formatMultiCurrencyWith passing it — because they need this fragment's
883
+ // own resolved currentLocale, which the shell-loaded, load-once money.js has no access to.
884
+ function formatMultiCurrency(map, delimiter) {
885
+ return window.formatMultiCurrencyWith(map, formatCurrency, delimiter);
886
+ }
887
+
888
+ function formatCurrency(val, currency = DEFAULT_CURRENCY) {
889
+ const code = currency || DEFAULT_CURRENCY;
890
+ const loc = currentLocale === 'pt' ? 'pt-BR' : (currentLocale === 'es' ? 'es-ES' : 'en-US');
891
+ return window.formatMoney(val || 0, code, { locale: loc });
892
+ }
893
+
894
+ function formatPct(val) {
895
+ return `${((val || 0) * 100).toFixed(1)}%`;
896
+ }
897
+
898
+ function onFilterChange() {
899
+ const currencySelect = document.getElementById('currency-select');
900
+ currentDisplayCurrency = currencySelect ? currencySelect.value : '';
901
+ loadDashboardData();
902
+ }
903
+
904
+ // Only the currency selector counts as a choice; changing the month or year leaves the default following the base.
905
+ function onCurrencyChange() {
906
+ displayCurrencyChosen = true;
907
+ onFilterChange();
908
+ }
909
+
910
+ // The shell has already refreshed window.BASE_CURRENCY when a userSettings event reaches this fragment.
911
+ function followBaseCurrency() {
912
+ const select = document.getElementById('currency-select');
913
+ if (displayCurrencyChosen || !select || !window.BASE_CURRENCY) return;
914
+ if (!Object.prototype.hasOwnProperty.call(window.__appCurrencies || {}, window.BASE_CURRENCY)) return;
915
+ select.value = window.BASE_CURRENCY;
916
+ currentDisplayCurrency = select.value;
917
+ }
918
+
919
+ async function fetchBudgetStatus(month, year, displayCurrency) {
920
+ try {
921
+ const params = new URLSearchParams({ month: String(month), year: String(year) });
922
+ if (displayCurrency) params.set('displayCurrency', displayCurrency);
923
+ const res = await fetch(`/api/budgets/status?${params.toString()}`);
924
+ if (!res.ok) return null;
925
+ return await res.json();
926
+ } catch (err) {
927
+ console.error('Error fetching budget status:', err);
928
+ return null;
929
+ }
930
+ }
931
+
932
+ async function fetchAllTransactionsForMonth(year, month) {
933
+ let items = [];
934
+ let cursor = null;
935
+
936
+ try {
937
+ while (true) {
938
+ const params = new URLSearchParams({
939
+ month: String(month),
940
+ year: String(year),
941
+ sort: 'date',
942
+ dir: 'desc'
943
+ });
944
+ if (cursor) params.set('cursor', cursor);
945
+
946
+ const res = await fetch(`/api/transactions?${params.toString()}`);
947
+ if (!res.ok) break;
948
+ const data = await res.json();
949
+
950
+ if (data && Array.isArray(data.items)) {
951
+ items = items.concat(data.items);
952
+ if (data.nextCursor) {
953
+ cursor = data.nextCursor;
954
+ } else {
955
+ break;
956
+ }
957
+ } else if (Array.isArray(data)) {
958
+ items = data;
959
+ break;
960
+ } else {
961
+ break;
962
+ }
963
+ }
964
+ } catch (err) {
965
+ console.error('Error fetching transactions:', err);
966
+ }
967
+ return items;
968
+ }
969
+
970
+ async function loadDashboardData() {
971
+ const month = parseInt(document.getElementById('month-select').value);
972
+ const year = parseInt(document.getElementById('year-select').value);
973
+
974
+ const incomeListEl = document.getElementById('income-categories-list');
975
+ const expenseListEl = document.getElementById('expense-categories-list');
976
+
977
+ incomeListEl.innerHTML = `
978
+ <div class="state-container">
979
+ <i class="fa-solid fa-spinner fa-spin"></i>
980
+ <div>${t('loading_incomes')}</div>
981
+ </div>`;
982
+ expenseListEl.innerHTML = `
983
+ <div class="state-container">
984
+ <i class="fa-solid fa-spinner fa-spin"></i>
985
+ <div>${t('loading_budgets')}</div>
986
+ </div>`;
987
+
988
+ try {
989
+ const [budgetStatus, txItems] = await Promise.all([
990
+ fetchBudgetStatus(month, year, currentDisplayCurrency),
991
+ fetchAllTransactionsForMonth(year, month)
992
+ ]);
993
+
994
+ // Calculate Income totals and categories
995
+ const incomeTotalEff = {};
996
+ const incomeTotalPend = {};
997
+ const incomeCats = {};
998
+
999
+ txItems.forEach(tx => {
1000
+ if (tx.type === 'income') {
1001
+ const amt = Number(tx.amount) || 0;
1002
+ const curr = tx.currency || DEFAULT_CURRENCY;
1003
+ const catName = tx.categoryName || 'Uncategorized';
1004
+
1005
+ if (!incomeCats[catName]) {
1006
+ incomeCats[catName] = { effective: {}, pending: {}, total: {}, txs: [] };
1007
+ }
1008
+
1009
+ incomeCats[catName].txs.push(tx);
1010
+ addMultiCurrency(incomeCats[catName].total, curr, amt);
1011
+
1012
+ if (tx.status === 'effective') {
1013
+ addMultiCurrency(incomeTotalEff, curr, amt);
1014
+ addMultiCurrency(incomeCats[catName].effective, curr, amt);
1015
+ } else {
1016
+ addMultiCurrency(incomeTotalPend, curr, amt);
1017
+ addMultiCurrency(incomeCats[catName].pending, curr, amt);
1018
+ }
1019
+ }
1020
+ });
1021
+
1022
+ // Compute totalIncome map
1023
+ const totalIncome = {};
1024
+ for (var c in incomeTotalEff) {
1025
+ addMultiCurrency(totalIncome, c, incomeTotalEff[c]);
1026
+ }
1027
+ for (var c in incomeTotalPend) {
1028
+ addMultiCurrency(totalIncome, c, incomeTotalPend[c]);
1029
+ }
1030
+
1031
+ // Process Budget Status (fetched via REST, GET /api/budgets/status) for all currencies
1032
+ const totalBudgetLimit = {};
1033
+ const totalBudgetCommitted = {};
1034
+ const totalBudgetEffective = {};
1035
+ const totalBudgetPending = {};
1036
+
1037
+ const budgetCategoryMap = {};
1038
+
1039
+ if (budgetStatus && Array.isArray(budgetStatus.categories)) {
1040
+ budgetStatus.categories.forEach(catGroup => {
1041
+ const catName = catGroup.category;
1042
+ const lines = catGroup.lines || [];
1043
+
1044
+ lines.forEach(line => {
1045
+ const curr = line.currency || DEFAULT_CURRENCY;
1046
+ const limit = Number(line.limit) || 0;
1047
+ const committed = Number(line.committed?.amount) || 0;
1048
+ const effective = Number(line.effective?.amount) || 0;
1049
+ const pending = Number(line.pending?.amount) || 0;
1050
+ const remaining = Number(line.remaining) || 0;
1051
+
1052
+ addMultiCurrency(totalBudgetLimit, curr, limit);
1053
+ addMultiCurrency(totalBudgetCommitted, curr, committed);
1054
+ addMultiCurrency(totalBudgetEffective, curr, effective);
1055
+ addMultiCurrency(totalBudgetPending, curr, pending);
1056
+
1057
+ if (!budgetCategoryMap[catName]) {
1058
+ budgetCategoryMap[catName] = {
1059
+ limit: {},
1060
+ committed: {},
1061
+ effective: {},
1062
+ pending: {},
1063
+ remaining: {},
1064
+ txs: []
1065
+ };
1066
+ }
1067
+
1068
+ addMultiCurrency(budgetCategoryMap[catName].limit, curr, limit);
1069
+ addMultiCurrency(budgetCategoryMap[catName].committed, curr, committed);
1070
+ addMultiCurrency(budgetCategoryMap[catName].effective, curr, effective);
1071
+ addMultiCurrency(budgetCategoryMap[catName].pending, curr, pending);
1072
+ addMultiCurrency(budgetCategoryMap[catName].remaining, curr, remaining);
1073
+ });
1074
+ });
1075
+ }
1076
+
1077
+ // Add expense transactions and populate txs lists
1078
+ txItems.forEach(tx => {
1079
+ if (tx.type === 'expense') {
1080
+ const catName = tx.categoryName || 'Other';
1081
+ const curr = tx.currency || DEFAULT_CURRENCY;
1082
+ const amt = Number(tx.amount) || 0;
1083
+
1084
+ if (!budgetCategoryMap[catName]) {
1085
+ budgetCategoryMap[catName] = {
1086
+ limit: {},
1087
+ committed: {},
1088
+ effective: {},
1089
+ pending: {},
1090
+ remaining: {},
1091
+ txs: []
1092
+ };
1093
+ }
1094
+
1095
+ budgetCategoryMap[catName].txs.push(tx);
1096
+
1097
+ // If this category didn't have budget lines from budgetStatus, accumulate transaction amounts
1098
+ if (Object.keys(budgetCategoryMap[catName].limit).length === 0) {
1099
+ addMultiCurrency(budgetCategoryMap[catName].committed, curr, amt);
1100
+ if (tx.status === 'effective') {
1101
+ addMultiCurrency(budgetCategoryMap[catName].effective, curr, amt);
1102
+ } else {
1103
+ addMultiCurrency(budgetCategoryMap[catName].pending, curr, amt);
1104
+ }
1105
+ addMultiCurrency(budgetCategoryMap[catName].remaining, curr, -amt);
1106
+ }
1107
+ }
1108
+ });
1109
+
1110
+ // Render KPI Cards
1111
+ document.getElementById('kpi-income-val').textContent = formatMultiCurrency(totalIncome);
1112
+ document.getElementById('kpi-income-eff').textContent = formatMultiCurrency(incomeTotalEff);
1113
+ document.getElementById('kpi-income-pend').textContent = formatMultiCurrency(incomeTotalPend);
1114
+
1115
+ document.getElementById('kpi-budget-limit-val').textContent = formatMultiCurrency(totalBudgetLimit, ' / ');
1116
+ document.getElementById('kpi-budget-comm-val').textContent = formatMultiCurrency(totalBudgetCommitted);
1117
+
1118
+ // "Usage" is a single percentage, so it can only read one real currency's own limit/committed
1119
+ // — never a blended total across currencies.
1120
+ const budgetCurrency = primaryCurrencyOf(totalBudgetLimit);
1121
+ const budgetLimitInCurrency = valueIn(totalBudgetLimit, budgetCurrency);
1122
+ const budgetCommittedInCurrency = valueIn(totalBudgetCommitted, budgetCurrency);
1123
+ const overallBudgetPct = budgetLimitInCurrency > 0 ? (budgetCommittedInCurrency / budgetLimitInCurrency) : 0;
1124
+ document.getElementById('kpi-budget-pct-val').textContent = formatPct(overallBudgetPct);
1125
+
1126
+ renderConvertedTotal(budgetStatus && budgetStatus.converted);
1127
+
1128
+ // Planned Balance (Income map - Limit map), kept per-currency — never combined into one total.
1129
+ const plannedBalance = {};
1130
+ const allCurrs = new Set([...Object.keys(totalIncome), ...Object.keys(totalBudgetLimit)]);
1131
+ allCurrs.forEach(c => {
1132
+ plannedBalance[c] = (totalIncome[c] || 0) - (totalBudgetLimit[c] || 0);
1133
+ });
1134
+
1135
+ const balanceCard = document.getElementById('kpi-balance-card');
1136
+ const balanceValEl = document.getElementById('kpi-balance-val');
1137
+ balanceValEl.textContent = formatMultiCurrency(plannedBalance, ' / ');
1138
+
1139
+ const primaryBalanceCurrency = primaryCurrencyOf(plannedBalance);
1140
+ if (valueIn(plannedBalance, primaryBalanceCurrency) < 0) {
1141
+ balanceCard.classList.add('negative');
1142
+ } else {
1143
+ balanceCard.classList.remove('negative');
1144
+ }
1145
+
1146
+ document.getElementById('income-categories-total').textContent = formatMultiCurrency(totalIncome);
1147
+ document.getElementById('expense-categories-total').textContent = formatMultiCurrency(totalBudgetCommitted);
1148
+
1149
+ // Render Income Categories List
1150
+ renderIncomeCategories(incomeCats, totalIncome);
1151
+
1152
+ // Render Expense vs Budget Categories List
1153
+ renderExpenseBudgetCategories(budgetCategoryMap);
1154
+
1155
+ // Render Charts — Chart.js needs single numeric series, so pick ONE real currency (never a
1156
+ // converted/blended total; the KPI cards above already show every currency correctly).
1157
+ const compareChartCurrency = primaryCurrencyOf(mergeCurrencyMaps(totalIncome, totalBudgetLimit));
1158
+ renderMonthlyCompareChart({
1159
+ currency: compareChartCurrency,
1160
+ effIncome: valueIn(incomeTotalEff, compareChartCurrency),
1161
+ pendIncome: valueIn(incomeTotalPend, compareChartCurrency),
1162
+ limitExpense: valueIn(totalBudgetLimit, compareChartCurrency),
1163
+ effExpense: valueIn(totalBudgetEffective, compareChartCurrency),
1164
+ pendExpense: valueIn(totalBudgetPending, compareChartCurrency)
1165
+ });
1166
+ renderTrendChart(year, month);
1167
+
1168
+ } catch (err) {
1169
+ console.error('Error loading budget dashboard:', err);
1170
+ incomeListEl.innerHTML = `
1171
+ <div class="state-container" style="color: #f43f5e">
1172
+ <i class="fa-solid fa-triangle-exclamation"></i>
1173
+ <div>${t('error_loading_income')}</div>
1174
+ </div>`;
1175
+ expenseListEl.innerHTML = `
1176
+ <div class="state-container" style="color: #f43f5e">
1177
+ <i class="fa-solid fa-triangle-exclamation"></i>
1178
+ <div>${t('error_loading_budget')}</div>
1179
+ </div>`;
1180
+ }
1181
+ }
1182
+
1183
+ // `converted` is a cross-currency grand total — deliberately not a replacement for the per-currency
1184
+ // figures rendered elsewhere on this page, which stay the source of truth.
1185
+ function renderConvertedTotal(converted) {
1186
+ const el = document.getElementById('kpi-budget-converted');
1187
+ if (!el) return;
1188
+ if (!converted) {
1189
+ el.style.display = 'none';
1190
+ el.classList.remove('stale');
1191
+ return;
1192
+ }
1193
+
1194
+ const totalText = formatCurrency(converted.total, converted.displayCurrency);
1195
+ const excludedCount = converted.excluded.length;
1196
+ const staleLabel = escapeHtml(t('rate_stale_tooltip'));
1197
+ // A `title` tooltip alone is invisible to keyboard/screen-reader users (no way to trigger a
1198
+ // hover, and `title` isn't reliably announced) — the warning icon is a real focusable button
1199
+ // with an aria-label carrying the same text, so it's reachable and announced either way.
1200
+ const staleFlag = converted.stale
1201
+ ? ` <button type="button" class="stale-flag" title="${staleLabel}" aria-label="${staleLabel}">` +
1202
+ '<i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i></button>'
1203
+ : '';
1204
+
1205
+ el.classList.toggle('stale', converted.stale);
1206
+ el.innerHTML = `
1207
+ <span>${t('kpi_converted_label')} <strong>${totalText}</strong>${staleFlag}</span>
1208
+ ${excludedCount > 0
1209
+ ? `<span class="kpi-converted-excluded">${t('kpi_converted_excluded').replace('{n}', String(excludedCount))}</span>`
1210
+ : ''}
1211
+ `;
1212
+ el.style.display = 'block';
1213
+ }
1214
+
1215
+ function renderIncomeCategories(incomeCats, totalIncome) {
1216
+ const listEl = document.getElementById('income-categories-list');
1217
+ const sortedCatNames = Object.keys(incomeCats).sort((a, b) => magnitudeOf(incomeCats[b].total) - magnitudeOf(incomeCats[a].total));
1218
+
1219
+ if (sortedCatNames.length === 0) {
1220
+ listEl.innerHTML = `
1221
+ <div class="state-container">
1222
+ <i class="fa-regular fa-folder-open"></i>
1223
+ <div>${t('no_incomes_month')}</div>
1224
+ </div>`;
1225
+ return;
1226
+ }
1227
+
1228
+ let html = '';
1229
+ sortedCatNames.forEach((catName, idx) => {
1230
+ const data = incomeCats[catName];
1231
+ // A displayed percentage can only compare amounts in the same currency — this category's
1232
+ // own share of that same currency's total income, never a blend across currencies.
1233
+ const rowCurrency = primaryCurrencyOf(data.total);
1234
+ const rowTotal = valueIn(data.total, rowCurrency);
1235
+ const rowEffective = valueIn(data.effective, rowCurrency);
1236
+ const rowPending = valueIn(data.pending, rowCurrency);
1237
+ const pct = valueIn(totalIncome, rowCurrency) > 0 ? (rowTotal / valueIn(totalIncome, rowCurrency)) * 100 : 0;
1238
+ const effPct = rowTotal > 0 ? (rowEffective / rowTotal) * 100 : 0;
1239
+ const pendPct = rowTotal > 0 ? (rowPending / rowTotal) * 100 : 0;
1240
+
1241
+ const rowId = `inc-cat-${idx}`;
1242
+
1243
+ html += `
1244
+ <div class="category-row-container" id="${rowId}">
1245
+ <div class="category-row-header" role="button" tabindex="0" aria-expanded="false" onclick="toggleAccordion('${rowId}')" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggleAccordion('${rowId}'); }">
1246
+ <div class="cat-meta-info">
1247
+ <div class="cat-name-label">
1248
+ <i class="fa-solid fa-chevron-down"></i> ${escapeHtml(catName)}
1249
+ </div>
1250
+ <div>
1251
+ <span class="cat-val-label">${formatMultiCurrency(data.total)}</span>
1252
+ <span class="cat-pct-label">${pct.toFixed(1)}%</span>
1253
+ </div>
1254
+ </div>
1255
+ <div class="proportion-bar-container">
1256
+ <div class="bar-segment effective-inc" style="width: ${effPct}%" title="${t('kpi_effective')} ${formatMultiCurrency(data.effective)}"></div>
1257
+ <div class="bar-segment pending-inc" style="width: ${pendPct}%" title="${t('kpi_pending')} ${formatMultiCurrency(data.pending)}"></div>
1258
+ </div>
1259
+ <div class="cat-breakdown-text">
1260
+ <span>${t('kpi_effective')} <strong>${formatMultiCurrency(data.effective)}</strong></span>
1261
+ <span>${t('kpi_pending')} <strong>${formatMultiCurrency(data.pending)}</strong></span>
1262
+ </div>
1263
+ </div>
1264
+ <div class="category-tx-details">
1265
+ ${renderTransactionsTable(data.txs)}
1266
+ </div>
1267
+ </div>`;
1268
+ });
1269
+
1270
+ listEl.innerHTML = html;
1271
+ }
1272
+
1273
+ function renderExpenseBudgetCategories(budgetCategoryMap) {
1274
+ const listEl = document.getElementById('expense-categories-list');
1275
+ const catNames = Object.keys(budgetCategoryMap).sort((a, b) => {
1276
+ const bVal = magnitudeOf(budgetCategoryMap[b].committed) || magnitudeOf(budgetCategoryMap[b].limit);
1277
+ const aVal = magnitudeOf(budgetCategoryMap[a].committed) || magnitudeOf(budgetCategoryMap[a].limit);
1278
+ return bVal - aVal;
1279
+ });
1280
+
1281
+ if (catNames.length === 0) {
1282
+ listEl.innerHTML = `
1283
+ <div class="state-container">
1284
+ <i class="fa-regular fa-folder-open"></i>
1285
+ <div>${t('no_budgets_period')}</div>
1286
+ </div>`;
1287
+ return;
1288
+ }
1289
+
1290
+ let html = '';
1291
+ catNames.forEach((catName, idx) => {
1292
+ const data = budgetCategoryMap[catName];
1293
+ // A displayed pct/over-budget flag/progress bar can only read one real currency's own
1294
+ // limit-vs-committed — never a blended total across currencies (formatMultiCurrency below
1295
+ // still shows every currency correctly as text).
1296
+ const rowCurrency = primaryCurrencyOf(mergeCurrencyMaps(data.limit, data.committed));
1297
+ const rowLimit = valueIn(data.limit, rowCurrency);
1298
+ const rowCommitted = valueIn(data.committed, rowCurrency);
1299
+ const rowRemaining = valueIn(data.remaining, rowCurrency);
1300
+ const isOver = rowLimit > 0 && rowCommitted > rowLimit;
1301
+ const pctUsed = rowLimit > 0 ? (rowCommitted / rowLimit) * 100 : 0;
1302
+
1303
+ const rowEffective = valueIn(data.effective, rowCurrency);
1304
+ const rowPending = valueIn(data.pending, rowCurrency);
1305
+
1306
+ let effPct = rowLimit > 0 ? (rowEffective / rowLimit) * 100 : 0;
1307
+ let pendPct = rowLimit > 0 ? (rowPending / rowLimit) * 100 : 0;
1308
+
1309
+ if (effPct > 100) {
1310
+ effPct = 100;
1311
+ pendPct = 0;
1312
+ } else if (effPct + pendPct > 100) {
1313
+ pendPct = 100 - effPct;
1314
+ }
1315
+
1316
+ let barClass = 'budget-ok';
1317
+ if (pctUsed > 100) barClass = 'budget-over';
1318
+ else if (pctUsed > 80) barClass = 'budget-warn';
1319
+
1320
+ const rowId = `exp-cat-${idx}`;
1321
+ const hasLimit = Object.values(data.limit).some(v => v > 0);
1322
+ const limitStr = hasLimit ? `/ ${formatMultiCurrency(data.limit)}` : '';
1323
+ const valLabel = `${formatMultiCurrency(data.committed)} ${limitStr}`;
1324
+ const pctLabel = hasLimit ? pctUsed.toFixed(1) + '%' : t('cat_no_limit');
1325
+
1326
+ html += `
1327
+ <div class="category-row-container ${isOver ? 'over-budget' : ''}" id="${rowId}">
1328
+ <div class="category-row-header" role="button" tabindex="0" aria-expanded="false" onclick="toggleAccordion('${rowId}')" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggleAccordion('${rowId}'); }">
1329
+ <div class="cat-meta-info">
1330
+ <div class="cat-name-label">
1331
+ <i class="fa-solid fa-chevron-down"></i> ${escapeHtml(catName)}
1332
+ </div>
1333
+ <div>
1334
+ <span class="cat-val-label">${valLabel}</span>
1335
+ <span class="cat-pct-label ${isOver ? 'over' : ''}">${pctLabel}</span>
1336
+ </div>
1337
+ </div>
1338
+ <div class="proportion-bar-container">
1339
+ <div class="bar-segment ${barClass}-eff" style="width: ${hasLimit ? effPct : 0}%" title="${t('kpi_effective')} ${formatMultiCurrency(data.effective)}"></div>
1340
+ <div class="bar-segment ${barClass}-pend" style="width: ${hasLimit ? pendPct : 0}%" title="${t('kpi_pending')} ${formatMultiCurrency(data.pending)}"></div>
1341
+ </div>
1342
+ <div class="cat-breakdown-text">
1343
+ <span>${t('kpi_effective')} <strong>${formatMultiCurrency(data.effective)}</strong></span>
1344
+ <span>${t('kpi_pending')} <strong>${formatMultiCurrency(data.pending)}</strong></span>
1345
+ <span>${t('kpi_remaining')} <strong style="color: ${rowRemaining < 0 ? '#f43f5e' : '#10b981'}">${formatMultiCurrency(data.remaining)}</strong></span>
1346
+ </div>
1347
+ </div>
1348
+ <div class="category-tx-details">
1349
+ ${renderTransactionsTable(data.txs)}
1350
+ </div>
1351
+ </div>`;
1352
+ });
1353
+
1354
+ listEl.innerHTML = html;
1355
+ }
1356
+
1357
+ function renderTransactionsTable(txs) {
1358
+ if (!txs || txs.length === 0) {
1359
+ return `<div style="color: var(--text-muted); font-size: 0.8rem; padding: 0.5rem;">${t('no_txs_period')}</div>`;
1360
+ }
1361
+
1362
+ let rows = '';
1363
+ txs.forEach(tx => {
1364
+ const isEff = tx.status === 'effective';
1365
+ const dateStr = tx.date ? tx.date.split('-').reverse().join('/') : '-';
1366
+ const valStr = formatCurrency(tx.amount, tx.currency || DEFAULT_CURRENCY);
1367
+
1368
+ rows += `
1369
+ <tr>
1370
+ <td>${dateStr}</td>
1371
+ <td>${escapeHtml(tx.description || '-')}</td>
1372
+ <td>${escapeHtml(tx.accountName || '-')}</td>
1373
+ <td>
1374
+ <i class="fa-solid ${isEff ? 'fa-circle-check tx-status-icon effective' : 'fa-clock tx-status-icon pending'}" title="${isEff ? t('status_effective') : t('status_pending')}"></i>
1375
+ </td>
1376
+ <td style="font-weight: 600; text-align: right; color: ${tx.type === 'income' ? 'var(--income-color,#10b981)' : 'var(--expense-color,#f43f5e)'}">
1377
+ ${tx.type === 'expense' ? '-' : '+'}${valStr}
1378
+ </td>
1379
+ </tr>`;
1380
+ });
1381
+
1382
+ return `
1383
+ <table class="category-tx-table">
1384
+ <thead>
1385
+ <tr>
1386
+ <th>${t('col_date')}</th>
1387
+ <th>${t('col_description')}</th>
1388
+ <th>${t('col_account')}</th>
1389
+ <th>${t('col_status')}</th>
1390
+ <th style="text-align: right">${t('col_value')}</th>
1391
+ </tr>
1392
+ </thead>
1393
+ <tbody>
1394
+ ${rows}
1395
+ </tbody>
1396
+ </table>`;
1397
+ }
1398
+
1399
+ function toggleAccordion(rowId) {
1400
+ const el = document.getElementById(rowId);
1401
+ if (!el) return;
1402
+ const isOpen = el.classList.contains('open');
1403
+
1404
+ // Toggle details visibility
1405
+ const details = el.querySelector('.category-tx-details');
1406
+ const header = el.querySelector('.category-row-header');
1407
+ if (isOpen) {
1408
+ el.classList.remove('open');
1409
+ if (details) details.style.display = 'none';
1410
+ if (header) header.setAttribute('aria-expanded', 'false');
1411
+ } else {
1412
+ el.classList.add('open');
1413
+ if (details) details.style.display = 'block';
1414
+ if (header) header.setAttribute('aria-expanded', 'true');
1415
+ }
1416
+ }
1417
+
1418
+ function renderMonthlyCompareChart(data) {
1419
+ const ctx = document.getElementById('monthlyCompareChart');
1420
+ if (!ctx) return;
1421
+
1422
+ if (compareChart) {
1423
+ compareChart.destroy();
1424
+ }
1425
+
1426
+ var remainingExpense = Math.max(0, data.limitExpense - (data.effExpense + data.pendExpense));
1427
+
1428
+ compareChart = new Chart(ctx, {
1429
+ type: 'bar',
1430
+ data: {
1431
+ labels: [t('chart_lbl_proj_income'), t('chart_lbl_budget_exp')],
1432
+ datasets: [
1433
+ {
1434
+ label: t('kpi_effective'),
1435
+ data: [data.effIncome, data.effExpense],
1436
+ backgroundColor: ['#10b981', '#f43f5e'],
1437
+ borderRadius: 8,
1438
+ maxBarThickness: 80
1439
+ },
1440
+ {
1441
+ label: t('kpi_pending'),
1442
+ data: [data.pendIncome, data.pendExpense],
1443
+ backgroundColor: ['#064e3b', '#9f1239'],
1444
+ borderRadius: 8,
1445
+ maxBarThickness: 80
1446
+ },
1447
+ {
1448
+ label: t('kpi_remaining') || 'Restante',
1449
+ data: [null, remainingExpense],
1450
+ backgroundColor: ['rgba(0, 0, 0, 0)', 'rgba(244, 63, 94, 0.25)'],
1451
+ borderRadius: 8,
1452
+ maxBarThickness: 80
1453
+ }
1454
+ ]
1455
+ },
1456
+ options: {
1457
+ responsive: true,
1458
+ maintainAspectRatio: false,
1459
+ plugins: {
1460
+ legend: {
1461
+ onClick: null,
1462
+ labels: {
1463
+ color: '#9ca3af',
1464
+ font: { family: 'Inter, sans-serif' },
1465
+ boxWidth: 12,
1466
+ generateLabels: function(chart) {
1467
+ return [
1468
+ {
1469
+ text: t('kpi_effective'),
1470
+ fillStyle: '#10b981',
1471
+ strokeStyle: '#10b981',
1472
+ lineWidth: 0,
1473
+ hidden: false,
1474
+ fontColor: '#9ca3af',
1475
+ color: '#9ca3af'
1476
+ },
1477
+ {
1478
+ text: t('kpi_pending'),
1479
+ fillStyle: '#064e3b',
1480
+ strokeStyle: '#064e3b',
1481
+ lineWidth: 0,
1482
+ hidden: false,
1483
+ fontColor: '#9ca3af',
1484
+ color: '#9ca3af'
1485
+ },
1486
+ {
1487
+ text: t('kpi_remaining'),
1488
+ fillStyle: 'rgba(244, 63, 94, 0.5)',
1489
+ strokeStyle: 'rgba(244, 63, 94, 0.5)',
1490
+ lineWidth: 0,
1491
+ hidden: false,
1492
+ fontColor: '#9ca3af',
1493
+ color: '#9ca3af'
1494
+ }
1495
+ ];
1496
+ }
1497
+ }
1498
+ },
1499
+ tooltip: {
1500
+ callbacks: {
1501
+ label: function(ctx) {
1502
+ if (ctx.raw === null || ctx.raw === undefined) return '';
1503
+ var val = ctx.raw;
1504
+ var label = ctx.dataset.label || '';
1505
+
1506
+ var dataIndex = ctx.dataIndex;
1507
+ var datasetIndex = ctx.datasetIndex;
1508
+
1509
+ var v0 = ctx.chart.data.datasets[0].data[dataIndex] || 0;
1510
+ var v1 = ctx.chart.data.datasets[1].data[dataIndex] || 0;
1511
+ var v2 = (ctx.chart.data.datasets[2] && ctx.chart.data.datasets[2].data[dataIndex]) || 0;
1512
+
1513
+ var separator = label.endsWith(':') ? ' ' : ': ';
1514
+ var individualStr = label + separator + formatCurrency(val, data.currency);
1515
+
1516
+ var accumLabel = t('cumulative') || 'Acumulado';
1517
+ var accumSeparator = accumLabel.endsWith(':') ? ' ' : ': ';
1518
+
1519
+ if (datasetIndex === 0) {
1520
+ return individualStr;
1521
+ } else if (datasetIndex === 1) {
1522
+ var cum = v0 + v1;
1523
+ return [
1524
+ individualStr,
1525
+ '• ' + accumLabel + accumSeparator + formatCurrency(cum, data.currency)
1526
+ ];
1527
+ } else if (datasetIndex === 2) {
1528
+ var cum = v0 + v1 + v2;
1529
+ return [
1530
+ individualStr,
1531
+ '• ' + accumLabel + accumSeparator + formatCurrency(cum, data.currency)
1532
+ ];
1533
+ }
1534
+ return individualStr;
1535
+ }
1536
+ }
1537
+ }
1538
+ },
1539
+ scales: {
1540
+ x: {
1541
+ stacked: true,
1542
+ grid: { display: false },
1543
+ ticks: { color: '#9ca3af' }
1544
+ },
1545
+ y: {
1546
+ stacked: true,
1547
+ grid: { color: 'rgba(255, 255, 255, 0.05)' },
1548
+ ticks: {
1549
+ color: '#9ca3af',
1550
+ callback: function(val) { return formatCurrency(val, data.currency); }
1551
+ }
1552
+ }
1553
+ }
1554
+ }
1555
+ });
1556
+ }
1557
+
1558
+ async function renderTrendChart(selectedYear, selectedMonth) {
1559
+ const ctx = document.getElementById('trendChart');
1560
+ if (!ctx) return;
1561
+
1562
+ if (trendChart) {
1563
+ trendChart.destroy();
1564
+ }
1565
+
1566
+ // Days in the selected month
1567
+ const daysInMonth = new Date(selectedYear, selectedMonth, 0).getDate();
1568
+ const numWeeks = daysInMonth > 28 ? 5 : 4;
1569
+
1570
+ // Fetch budget status for the selected month to get the monthly budget limit, per currency
1571
+ const bStatus = await fetchBudgetStatus(selectedMonth, selectedYear);
1572
+ const monthlyLimitByCurrency = {};
1573
+ if (bStatus && Array.isArray(bStatus.categories)) {
1574
+ bStatus.categories.forEach(cg => {
1575
+ (cg.lines || []).forEach(l => {
1576
+ addMultiCurrency(monthlyLimitByCurrency, l.currency, Number(l.limit) || 0);
1577
+ });
1578
+ });
1579
+ }
1580
+
1581
+ // Fetch all transactions for the selected month
1582
+ const txs = await fetchAllTransactionsForMonth(selectedYear, selectedMonth);
1583
+ const monthlyIncomeByCurrency = {};
1584
+ txs.forEach(tx => {
1585
+ if (tx.type === 'income') addMultiCurrency(monthlyIncomeByCurrency, tx.currency, Number(tx.amount) || 0);
1586
+ });
1587
+
1588
+ // A line chart needs a single numeric series, so pick ONE real currency (never a
1589
+ // converted/blended total) — weekly figures below only include that currency's own transactions.
1590
+ const trendCurrency = primaryCurrencyOf(mergeCurrencyMaps(monthlyLimitByCurrency, monthlyIncomeByCurrency));
1591
+ const totalMonthlyLimit = valueIn(monthlyLimitByCurrency, trendCurrency);
1592
+
1593
+ const labels = ["1"];
1594
+ const incomeData = [0];
1595
+ const budgetData = [totalMonthlyLimit];
1596
+ const actualExpenseData = [0];
1597
+ const balanceData = [0];
1598
+
1599
+ let accumIncome = 0;
1600
+ let accumExpense = 0;
1601
+
1602
+ for (let w = 1; w <= numWeeks; w++) {
1603
+ const startDay = (w - 1) * 7 + 1;
1604
+ const endDay = w === 5 ? daysInMonth : Math.min(w * 7, daysInMonth);
1605
+
1606
+ labels.push(endDay.toString());
1607
+
1608
+ // Filter transactions for this week, restricted to the chart's single currency
1609
+ const weekTxs = txs.filter(tx => {
1610
+ if (!tx.date) return false;
1611
+ if ((tx.currency || DEFAULT_CURRENCY) !== trendCurrency) return false;
1612
+ const parts = tx.date.split('T')[0].split('-');
1613
+ const day = parseInt(parts[2], 10);
1614
+ return day >= startDay && day <= endDay;
1615
+ });
1616
+
1617
+ const weeklyIncome = weekTxs
1618
+ .filter(t => t.type === 'income')
1619
+ .reduce((sum, t) => sum + (Number(t.amount) || 0), 0);
1620
+
1621
+ const weeklyActualExpense = weekTxs
1622
+ .filter(t => t.type === 'expense')
1623
+ .reduce((sum, t) => sum + (Number(t.amount) || 0), 0);
1624
+
1625
+ accumIncome += weeklyIncome;
1626
+ accumExpense += weeklyActualExpense;
1627
+
1628
+ incomeData.push(accumIncome);
1629
+ budgetData.push(totalMonthlyLimit);
1630
+ actualExpenseData.push(accumExpense);
1631
+ balanceData.push(accumIncome - accumExpense);
1632
+ }
1633
+
1634
+ trendChart = new Chart(ctx, {
1635
+ type: 'line',
1636
+ data: {
1637
+ labels: labels,
1638
+ datasets: [
1639
+ {
1640
+ label: t('chart_lbl_proj_income'),
1641
+ data: incomeData,
1642
+ borderColor: '#10b981',
1643
+ backgroundColor: 'rgba(16, 185, 129, 0.1)',
1644
+ tension: 0.3,
1645
+ fill: false
1646
+ },
1647
+ {
1648
+ label: t('chart_lbl_budget_exp'),
1649
+ data: budgetData,
1650
+ borderColor: '#f43f5e',
1651
+ backgroundColor: 'rgba(244, 63, 94, 0.1)',
1652
+ tension: 0.3,
1653
+ fill: false
1654
+ },
1655
+ {
1656
+ label: t('chart_lbl_committed'),
1657
+ data: actualExpenseData,
1658
+ borderColor: '#f59e0b',
1659
+ backgroundColor: 'rgba(245, 158, 11, 0.1)',
1660
+ tension: 0.3,
1661
+ fill: false
1662
+ },
1663
+ {
1664
+ label: t('chart_lbl_net_balance'),
1665
+ data: balanceData,
1666
+ borderColor: '#8b5cf6',
1667
+ borderDash: [5, 5],
1668
+ tension: 0.3,
1669
+ fill: false
1670
+ }
1671
+ ]
1672
+ },
1673
+ options: {
1674
+ responsive: true,
1675
+ maintainAspectRatio: false,
1676
+ plugins: {
1677
+ legend: {
1678
+ labels: { color: '#9ca3af', font: { family: 'Inter, sans-serif' } }
1679
+ },
1680
+ tooltip: {
1681
+ callbacks: {
1682
+ label: function(ctx) {
1683
+ return `${ctx.dataset.label}: ${formatCurrency(ctx.raw, trendCurrency)}`;
1684
+ }
1685
+ }
1686
+ }
1687
+ },
1688
+ scales: {
1689
+ x: {
1690
+ grid: { color: 'rgba(255, 255, 255, 0.05)' },
1691
+ ticks: { color: '#9ca3af' }
1692
+ },
1693
+ y: {
1694
+ grid: { color: 'rgba(255, 255, 255, 0.05)' },
1695
+ ticks: {
1696
+ color: '#9ca3af',
1697
+ callback: function(val) { return formatCurrency(val, trendCurrency); }
1698
+ }
1699
+ }
1700
+ }
1701
+ }
1702
+ });
1703
+ }
1704
+
1705
+ function escapeHtml(str) {
1706
+ if (!str) return '';
1707
+ return String(str)
1708
+ .replace(/&/g, '&amp;')
1709
+ .replace(/</g, '&lt;')
1710
+ .replace(/>/g, '&gt;')
1711
+ .replace(/"/g, '&quot;')
1712
+ .replace(/'/g, '&#039;');
1713
+ }
1714
+
1715
+ // Initial boot with locale detection
1716
+ (async function init() {
1717
+ await checkLocale();
1718
+ await initCurrencySelector();
1719
+ loadDashboardData();
1720
+ })();
1721
+
1722
+ // ADR-027 Live-update listener
1723
+ window.onAppDataChanged = function(entities) {
1724
+ var affected = entities.some(function(tag) {
1725
+ return ['budget', 'transaction', 'category', 'recurring', 'userSettings', 'account', 'currency_rate'].indexOf(tag) !== -1;
1726
+ });
1727
+ if (affected) {
1728
+ if (entities.indexOf('userSettings') !== -1) followBaseCurrency();
1729
+ console.log("budget refetching due to entity change:", entities);
1730
+ loadDashboardData();
1731
+ }
1732
+ };
1733
+
1734
+ </script>