@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,2528 @@
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
+ gap: 1rem;
14
+ background: var(--panel-bg);
15
+ border: 1px solid var(--panel-border);
16
+ padding: 0.5rem 1rem;
17
+ border-radius: 14px;
18
+ backdrop-filter: blur(12px);
19
+ }
20
+
21
+ .controls-area label {
22
+ font-size: 0.85rem;
23
+ font-weight: 600;
24
+ color: var(--text-muted);
25
+ text-transform: uppercase;
26
+ letter-spacing: 0.05em;
27
+ }
28
+
29
+ .select-custom {
30
+ background: rgba(255, 255, 255, 0.05);
31
+ border: 1px solid var(--panel-border);
32
+ color: var(--text-main);
33
+ padding: 0.5rem 1.5rem 0.5rem 0.75rem;
34
+ border-radius: 8px;
35
+ font-family: var(--font-family);
36
+ font-weight: 500;
37
+ cursor: pointer;
38
+ outline: none;
39
+ transition: var(--transition-smooth);
40
+ appearance: none;
41
+ 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");
42
+ background-repeat: no-repeat;
43
+ background-position: right 8px center;
44
+ background-size: 16px;
45
+ }
46
+
47
+ .select-custom:focus {
48
+ border-color: var(--accent-primary);
49
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
50
+ }
51
+
52
+ /* KPI summary cards */
53
+ .kpis-row {
54
+ display: grid;
55
+ grid-template-columns: repeat(3, 1fr);
56
+ gap: 1.5rem;
57
+ }
58
+
59
+ /* base: ui/app.css (#164) */
60
+ .kpi-card {
61
+ flex-direction: column;
62
+ gap: 0.75rem;
63
+ position: relative;
64
+ overflow: hidden;
65
+ }
66
+
67
+ .kpi-income::before { background: var(--income-color); }
68
+ .kpi-expense::before { background: var(--expense-color); }
69
+ .kpi-balance::before { background: var(--accent-primary); }
70
+
71
+ .kpi-title {
72
+ font-size: 0.85rem;
73
+ font-weight: 600;
74
+ color: var(--text-muted);
75
+ text-transform: uppercase;
76
+ letter-spacing: 0.05em;
77
+ display: flex;
78
+ align-items: center;
79
+ gap: 0.5rem;
80
+ }
81
+
82
+ .kpi-value {
83
+ font-size: 1.8rem;
84
+ font-weight: 800;
85
+ color: #fff;
86
+ }
87
+
88
+ .kpi-income .kpi-value {
89
+ color: var(--income-color) !important;
90
+ }
91
+
92
+ .kpi-expense .kpi-value {
93
+ color: var(--expense-color) !important;
94
+ }
95
+
96
+ .kpi-income .kpi-details span strong {
97
+ color: var(--income-color);
98
+ }
99
+
100
+ .kpi-expense .kpi-details span strong {
101
+ color: var(--expense-color);
102
+ }
103
+
104
+ .kpi-details {
105
+ font-size: 0.8rem;
106
+ color: var(--text-muted);
107
+ display: flex;
108
+ gap: 1rem;
109
+ }
110
+
111
+ .kpi-details span strong {
112
+ color: #fff;
113
+ }
114
+
115
+ /* Chart grids */
116
+ .charts-grid {
117
+ display: grid;
118
+ grid-template-columns: repeat(3, 1fr);
119
+ gap: 1.5rem;
120
+ }
121
+
122
+ @media (max-width: 1024px) {
123
+ .charts-grid {
124
+ grid-template-columns: 1fr;
125
+ }
126
+ }
127
+
128
+ .chart-card {
129
+ background: var(--panel-bg);
130
+ border: 1px solid var(--panel-border);
131
+ border-radius: 20px;
132
+ padding: 1.5rem;
133
+ box-shadow: var(--card-shadow);
134
+ backdrop-filter: blur(16px);
135
+ display: flex;
136
+ flex-direction: column;
137
+ gap: 1rem;
138
+ min-height: 320px;
139
+ }
140
+
141
+ .chart-card-title {
142
+ font-size: 1rem;
143
+ font-weight: 600;
144
+ color: var(--text-main);
145
+ display: flex;
146
+ align-items: center;
147
+ gap: 0.5rem;
148
+ }
149
+
150
+ .chart-container-inner {
151
+ position: relative;
152
+ flex: 1;
153
+ width: 100%;
154
+ height: 100%;
155
+ min-height: 240px;
156
+ }
157
+
158
+ /* Category panels */
159
+ .categories-grid {
160
+ display: grid;
161
+ grid-template-columns: 1fr 1fr;
162
+ gap: 1.5rem;
163
+ }
164
+
165
+ @media (max-width: 900px) {
166
+ .categories-grid {
167
+ grid-template-columns: 1fr;
168
+ }
169
+ }
170
+
171
+ .category-panel {
172
+ background: var(--panel-bg);
173
+ border: 1px solid var(--panel-border);
174
+ border-radius: 24px;
175
+ padding: 1.5rem;
176
+ box-shadow: var(--card-shadow);
177
+ backdrop-filter: blur(16px);
178
+ display: flex;
179
+ flex-direction: column;
180
+ gap: 1.25rem;
181
+ }
182
+
183
+ .category-panel-header {
184
+ display: flex;
185
+ justify-content: space-between;
186
+ align-items: center;
187
+ border-bottom: 1px solid var(--panel-border);
188
+ padding-bottom: 0.75rem;
189
+ }
190
+
191
+ .category-panel-title {
192
+ font-size: 1.1rem;
193
+ font-weight: 700;
194
+ display: flex;
195
+ align-items: center;
196
+ gap: 0.5rem;
197
+ }
198
+
199
+ .category-panel-title.income { color: var(--income-color); }
200
+ .category-panel-title.expense { color: var(--expense-color); }
201
+
202
+ .category-total-badge {
203
+ font-size: 1rem;
204
+ font-weight: 800;
205
+ color: #fff;
206
+ background: rgba(255, 255, 255, 0.05);
207
+ padding: 0.25rem 0.75rem;
208
+ border-radius: 12px;
209
+ border: 1px solid var(--panel-border);
210
+ }
211
+
212
+ .categories-list {
213
+ display: flex;
214
+ flex-direction: column;
215
+ gap: 0.75rem;
216
+ }
217
+
218
+ /* Category Row Accordion */
219
+ .category-row-container {
220
+ border: 1px solid var(--panel-border);
221
+ border-radius: 14px;
222
+ overflow: hidden;
223
+ background: rgba(0,0,0,0.1);
224
+ transition: var(--transition-smooth);
225
+ }
226
+
227
+ .category-row-container:hover {
228
+ border-color: rgba(255, 255, 255, 0.15);
229
+ }
230
+
231
+ .category-row-header {
232
+ padding: 1rem;
233
+ cursor: pointer;
234
+ display: flex;
235
+ flex-direction: column;
236
+ gap: 0.5rem;
237
+ user-select: none;
238
+ }
239
+
240
+ .cat-meta-info {
241
+ display: flex;
242
+ justify-content: space-between;
243
+ align-items: center;
244
+ }
245
+
246
+ .cat-name-label {
247
+ font-size: 0.95rem;
248
+ font-weight: 600;
249
+ color: #fff;
250
+ display: flex;
251
+ align-items: center;
252
+ gap: 0.5rem;
253
+ }
254
+
255
+ .cat-name-label i {
256
+ font-size: 0.8rem;
257
+ color: var(--text-muted);
258
+ transition: transform 0.3s ease;
259
+ }
260
+
261
+ .category-row-container.open .cat-name-label i {
262
+ transform: rotate(180deg);
263
+ color: var(--accent-primary);
264
+ }
265
+
266
+ .cat-val-label {
267
+ font-size: 0.95rem;
268
+ font-weight: 700;
269
+ color: #fff;
270
+ display: inline-flex;
271
+ align-items: center;
272
+ }
273
+
274
+ .cat-pct-label {
275
+ font-size: 0.72rem;
276
+ color: var(--text-muted);
277
+ margin-left: 0.5rem;
278
+ font-weight: 600;
279
+ background: rgba(255, 255, 255, 0.06);
280
+ padding: 2px 6px;
281
+ border-radius: 4px;
282
+ letter-spacing: 0.02em;
283
+ }
284
+
285
+ /* Progress Bar Proportions styling */
286
+ .proportion-bar-container {
287
+ width: 100%;
288
+ height: 8px;
289
+ background: rgba(255, 255, 255, 0.04);
290
+ border-radius: 4px;
291
+ overflow: hidden;
292
+ display: flex;
293
+ }
294
+
295
+ .bar-segment {
296
+ height: 100%;
297
+ transition: width 0.5s ease;
298
+ }
299
+
300
+ .bar-segment.effective-inc { background: var(--income-color); }
301
+ .bar-segment.pending-inc {
302
+ background: repeating-linear-gradient(
303
+ 45deg,
304
+ rgba(16, 185, 129, 0.25) 0px,
305
+ rgba(16, 185, 129, 0.25) 8px,
306
+ rgba(16, 185, 129, 0.45) 8px,
307
+ rgba(16, 185, 129, 0.45) 16px
308
+ );
309
+ }
310
+
311
+ .bar-segment.effective-exp { background: var(--expense-color); }
312
+ .bar-segment.pending-exp {
313
+ background: repeating-linear-gradient(
314
+ 45deg,
315
+ rgba(244, 63, 94, 0.25) 0px,
316
+ rgba(244, 63, 94, 0.25) 8px,
317
+ rgba(244, 63, 94, 0.45) 8px,
318
+ rgba(244, 63, 94, 0.45) 16px
319
+ );
320
+ }
321
+
322
+ .cat-breakdown-text {
323
+ display: flex;
324
+ justify-content: space-between;
325
+ font-size: 0.72rem;
326
+ color: var(--text-muted);
327
+ padding: 0 0.1rem;
328
+ }
329
+ .cat-breakdown-text span strong {
330
+ color: var(--text-main);
331
+ }
332
+
333
+ /* Expanded transaction list inside categories */
334
+ .category-tx-details {
335
+ display: none;
336
+ border-top: 1px solid var(--panel-border);
337
+ background: rgba(0, 0, 0, 0.25);
338
+ padding: 0.75rem 1rem;
339
+ overflow-x: auto;
340
+ }
341
+
342
+ .category-tx-table {
343
+ width: 100%;
344
+ border-collapse: collapse;
345
+ font-size: 0.82rem;
346
+ text-align: left;
347
+ }
348
+
349
+ .category-tx-table th {
350
+ padding: 0.4rem 0.6rem;
351
+ color: var(--text-dark);
352
+ text-transform: uppercase;
353
+ font-size: 0.7rem;
354
+ border-bottom: 1px solid var(--panel-border);
355
+ }
356
+
357
+ .category-tx-table td {
358
+ padding: 0.5rem 0.6rem;
359
+ border-bottom: 1px solid rgba(255, 255, 255, 0.02);
360
+ color: var(--text-main);
361
+ }
362
+
363
+ .category-tx-table tr:last-child td {
364
+ border-bottom: none;
365
+ }
366
+
367
+ .badge-status {
368
+ padding: 0.15rem 0.4rem;
369
+ border-radius: 4px;
370
+ font-size: 0.7rem;
371
+ font-weight: 600;
372
+ }
373
+ .status-eff {
374
+ background: rgba(16, 185, 129, 0.1);
375
+ color: var(--income-color);
376
+ border: 1px solid rgba(16, 185, 129, 0.2);
377
+ }
378
+ .status-pend {
379
+ background: rgba(245, 158, 11, 0.1);
380
+ color: var(--warning-color);
381
+ border: 1px solid rgba(245, 158, 11, 0.2);
382
+ }
383
+
384
+ /* Projections Heat Map Grid styling */
385
+ .heatmap-card {
386
+ background: var(--panel-bg);
387
+ border: 1px solid var(--panel-border);
388
+ border-radius: 24px;
389
+ padding: 1.75rem;
390
+ box-shadow: var(--card-shadow);
391
+ backdrop-filter: blur(16px);
392
+ display: flex;
393
+ flex-direction: column;
394
+ gap: 1.5rem;
395
+ }
396
+
397
+ .heatmap-title-area {
398
+ display: flex;
399
+ justify-content: space-between;
400
+ align-items: center;
401
+ border-bottom: 1px solid var(--panel-border);
402
+ padding-bottom: 0.75rem;
403
+ }
404
+
405
+ .heatmap-title {
406
+ font-size: 1.1rem;
407
+ font-weight: 700;
408
+ display: flex;
409
+ align-items: center;
410
+ gap: 0.5rem;
411
+ }
412
+
413
+ .heatmap-title i {
414
+ color: var(--accent-primary);
415
+ }
416
+
417
+ .heatmap-table-container {
418
+ overflow-x: auto;
419
+ border-radius: 12px;
420
+ border: 1px solid var(--panel-border);
421
+ background: rgba(0,0,0,0.1);
422
+ }
423
+
424
+ .heatmap-table {
425
+ width: 100%;
426
+ border-collapse: collapse;
427
+ text-align: center;
428
+ font-size: 0.85rem;
429
+ }
430
+
431
+ .heatmap-table th {
432
+ padding: 0.75rem 1rem;
433
+ color: var(--text-muted);
434
+ text-transform: uppercase;
435
+ font-size: 0.75rem;
436
+ letter-spacing: 0.05em;
437
+ border-bottom: 1px solid var(--panel-border);
438
+ background: rgba(255,255,255,0.01);
439
+ }
440
+
441
+ .heatmap-table th:first-child,
442
+ .heatmap-table td:first-child {
443
+ text-align: left;
444
+ font-weight: 600;
445
+ width: 250px;
446
+ }
447
+
448
+ .heatmap-table td {
449
+ padding: 0.75rem 1rem;
450
+ border-bottom: 1px solid rgba(255, 255, 255, 0.03);
451
+ border-right: 1px solid rgba(255, 255, 255, 0.02);
452
+ color: var(--text-main);
453
+ transition: var(--transition-smooth);
454
+ }
455
+
456
+ .heatmap-table td:last-child {
457
+ border-right: none;
458
+ font-weight: 700;
459
+ background: rgba(255, 255, 255, 0.01);
460
+ }
461
+
462
+ .heatmap-cell-value {
463
+ cursor: pointer;
464
+ border-radius: 6px;
465
+ padding: 0.35rem 0.5rem;
466
+ display: block;
467
+ font-weight: 500;
468
+ transition: var(--transition-smooth);
469
+ }
470
+
471
+ .heatmap-cell-value:hover {
472
+ transform: scale(1.05);
473
+ box-shadow: 0 4px 12px rgba(0,0,0,0.25);
474
+ }
475
+
476
+ .heatmap-table tfoot {
477
+ font-weight: 700;
478
+ background: rgba(255, 255, 255, 0.03);
479
+ border-top: 2px solid var(--panel-border);
480
+ }
481
+
482
+ .heatmap-table tfoot td {
483
+ padding: 0.75rem 1rem;
484
+ color: #fff;
485
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
486
+ }
487
+
488
+ .heatmap-empty {
489
+ color: var(--text-dark);
490
+ font-size: 0.8rem;
491
+ font-style: italic;
492
+ }
493
+
494
+ /* Overlay loader (.loading-overlay/.spinner base: ui/app.css, #164) */
495
+ .loading-overlay {
496
+ width: 100%; height: 100%;
497
+ z-index: 100;
498
+ border-radius: 24px;
499
+ opacity: 0; pointer-events: none;
500
+ transition: opacity 0.25s ease;
501
+ }
502
+ .loading-overlay.active { opacity: 1; pointer-events: all; }
503
+
504
+ /* Modal heat map cell details (.modal-overlay/.modal-box/.modal-title base: ui/app.css, #164) */
505
+ .modal-overlay {
506
+ width: 100%; height: 100%;
507
+ }
508
+ .modal-overlay.open {
509
+ display: flex;
510
+ }
511
+
512
+ .modal-box {
513
+ max-width: 600px;
514
+ }
515
+
516
+ .modal-close-btn {
517
+ position: absolute;
518
+ top: 1.25rem;
519
+ right: 1.25rem;
520
+ background: none;
521
+ border: none;
522
+ color: var(--text-dark);
523
+ cursor: pointer;
524
+ font-size: 1.2rem;
525
+ transition: var(--transition-smooth);
526
+ }
527
+ .modal-close-btn:hover {
528
+ color: var(--text-main);
529
+ }
530
+
531
+ .modal-title {
532
+ font-size: 1.2rem;
533
+ margin-bottom: 1.25rem;
534
+ color: #fff;
535
+ }
536
+
537
+ .modal-desc-text {
538
+ color: var(--text-muted);
539
+ font-size: 0.85rem;
540
+ margin-bottom: 1rem;
541
+ }
542
+
543
+ /* base: ui/app.css (#164) */
544
+ .btn-action-primary {
545
+ font-family: var(--font-family);
546
+ display: inline-flex;
547
+ justify-content: center;
548
+ box-shadow: 0 4px 12px var(--accent-primary-glow);
549
+ }
550
+
551
+ .btn-action-primary:hover {
552
+ transform: translateY(-2px);
553
+ background: #9d76fd;
554
+ box-shadow: 0 6px 16px rgba(139, 92, 246, 0.45);
555
+ }
556
+
557
+ /* Custom Select component styling */
558
+ .select-container-custom {
559
+ position: relative;
560
+ display: inline-block;
561
+ min-width: 120px;
562
+ user-select: none;
563
+ }
564
+
565
+ .select-trigger-custom {
566
+ background: rgba(255, 255, 255, 0.05);
567
+ border: 1px solid var(--panel-border);
568
+ color: var(--text-main);
569
+ padding: 0.5rem 2.2rem 0.5rem 0.75rem;
570
+ border-radius: 8px;
571
+ cursor: pointer;
572
+ font-size: 0.85rem;
573
+ font-weight: 600;
574
+ display: flex;
575
+ align-items: center;
576
+ justify-content: space-between;
577
+ transition: var(--transition-smooth);
578
+ min-height: 36px;
579
+ box-sizing: border-box;
580
+ }
581
+
582
+ .select-trigger-custom:hover {
583
+ border-color: rgba(255, 255, 255, 0.15);
584
+ background: rgba(255, 255, 255, 0.08);
585
+ }
586
+
587
+ .select-container-custom.open .select-trigger-custom {
588
+ border-color: var(--accent-primary);
589
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
590
+ }
591
+
592
+ .select-trigger-custom::after {
593
+ content: '\f078';
594
+ font-family: 'Font Awesome 6 Free';
595
+ font-weight: 900;
596
+ font-size: 0.7rem;
597
+ color: var(--text-muted);
598
+ position: absolute;
599
+ right: 12px;
600
+ transition: transform 0.3s ease;
601
+ }
602
+
603
+ .select-container-custom.open .select-trigger-custom::after {
604
+ transform: rotate(180deg);
605
+ color: var(--accent-primary);
606
+ }
607
+
608
+ .select-options-custom {
609
+ display: none;
610
+ position: absolute;
611
+ top: calc(100% + 6px);
612
+ left: 0;
613
+ width: 100%;
614
+ background: rgba(22, 22, 34, 0.98); /* Opaque dark background to prevent bleed-through */
615
+ border: 1px solid var(--panel-border);
616
+ border-radius: 12px;
617
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.6);
618
+ z-index: 1000;
619
+ max-height: 250px;
620
+ overflow-y: auto;
621
+ padding: 4px;
622
+ backdrop-filter: blur(20px);
623
+ box-sizing: border-box;
624
+ animation: selectFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
625
+ }
626
+
627
+ @keyframes selectFadeIn {
628
+ from { opacity: 0; transform: translateY(-8px); }
629
+ to { opacity: 1; transform: translateY(0); }
630
+ }
631
+
632
+ .select-container-custom.open .select-options-custom {
633
+ display: block;
634
+ }
635
+
636
+ .select-option-custom {
637
+ padding: 0.5rem 0.75rem;
638
+ color: var(--text-muted); /* Highly readable text color on dark backgrounds */
639
+ font-size: 0.82rem;
640
+ font-weight: 500;
641
+ border-radius: 6px;
642
+ cursor: pointer;
643
+ transition: var(--transition-smooth);
644
+ }
645
+
646
+ .select-option-custom:hover {
647
+ background: rgba(255, 255, 255, 0.08);
648
+ color: #fff;
649
+ }
650
+
651
+ .select-option-custom.selected {
652
+ background: var(--accent-primary-glow);
653
+ color: var(--accent-primary);
654
+ font-weight: 700;
655
+ }
656
+
657
+ .select-options-custom::-webkit-scrollbar {
658
+ width: 6px;
659
+ }
660
+ .select-options-custom::-webkit-scrollbar-track {
661
+ background: transparent;
662
+ }
663
+ .select-options-custom::-webkit-scrollbar-thumb {
664
+ background: rgba(255, 255, 255, 0.1);
665
+ border-radius: 3px;
666
+ }
667
+ </style>
668
+
669
+ <div class="dashboard-container">
670
+ <!-- Header -->
671
+ <header>
672
+ <div class="header-title-area">
673
+ <h1><i class="fa-solid fa-chart-line"></i> <span data-i18n="projections_title">Recurring & Installment Projections</span></h1>
674
+ <p data-i18n="projections_subtitle">Advanced visual mapping and projection of active recurrences and installments for the next months</p>
675
+ </div>
676
+ <div class="controls-area">
677
+ <label for="month-select" data-i18n="reference_label">Reference:</label>
678
+ <select id="month-select" class="select-custom">
679
+ <option value="1">Janeiro</option>
680
+ <option value="2">Fevereiro</option>
681
+ <option value="3">Março</option>
682
+ <option value="4">Abril</option>
683
+ <option value="5">Maio</option>
684
+ <option value="6">Junho</option>
685
+ <option value="7" selected>Julho</option>
686
+ <option value="8">Agosto</option>
687
+ <option value="9">Setembro</option>
688
+ <option value="10">Outubro</option>
689
+ <option value="11">Novembro</option>
690
+ <option value="12">Dezembro</option>
691
+ </select>
692
+ <select id="year-select" class="select-custom">
693
+ <option value="2025">2025</option>
694
+ <option value="2026" selected>2026</option>
695
+ <option value="2027">2027</option>
696
+ </select>
697
+ </div>
698
+ </header>
699
+
700
+ <!-- Projections cash flow line chart -->
701
+ <div class="chart-card" style="position: relative;">
702
+ <div class="chart-card-title">
703
+ <i class="fa-solid fa-arrow-trend-up" style="color: var(--accent-primary);"></i>
704
+ <span>Tendência de Fluxo de Caixa Projetado</span>
705
+ </div>
706
+ <div class="chart-container-inner" style="height: 280px; position: relative;">
707
+ <canvas id="projectionLineChart"></canvas>
708
+ </div>
709
+ </div>
710
+
711
+ <!-- Heat Map: Recurrings & Installments projection -->
712
+ <div class="heatmap-card" style="position: relative;">
713
+ <div class="loading-overlay" id="heatmap-loading">
714
+ <div class="spinner"></div>
715
+ </div>
716
+ <div class="heatmap-title-area" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem; border-bottom: 1px solid var(--panel-border); padding-bottom: 1rem; margin-bottom: 0.5rem; position: relative; z-index: 15;">
717
+ <div>
718
+ <div class="heatmap-title">
719
+ <i class="fa-solid fa-calendar-days"></i>
720
+ <span>Mapa de Calor: Projeção de Recorrências e Parcelas</span>
721
+ </div>
722
+ <div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.25rem;">
723
+ Clique nas células para ver os lançamentos detalhados.
724
+ </div>
725
+ </div>
726
+ <div style="display:flex; align-items:center; gap:0.5rem;">
727
+ <label for="heatmap-months-select" style="font-size:0.75rem; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.05em;" data-i18n="projection_label">Projection:</label>
728
+ <select id="heatmap-months-select" class="select-custom" style="padding: 0.25rem 1.75rem 0.25rem 0.5rem; font-size:0.8rem; height:32px; border-radius:8px;">
729
+ <option value="3">3 Meses</option>
730
+ <option value="6" selected>6 Meses</option>
731
+ <option value="9">9 Meses</option>
732
+ <option value="12">12 Meses</option>
733
+ </select>
734
+ </div>
735
+ </div>
736
+
737
+ <!-- Incomes Heat Map table -->
738
+ <div>
739
+ <h4 style="font-size: 0.9rem; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:var(--income-color); margin-bottom:0.75rem;">
740
+ <i class="fa-solid fa-angles-up"></i> Receitas Recorrentes / Parceladas
741
+ </h4>
742
+ <div class="heatmap-table-container">
743
+ <table class="heatmap-table" id="heatmap-income-table">
744
+ <thead>
745
+ <tr id="heatmap-income-header-row">
746
+ <th>Categoria</th>
747
+ <th>Total Projetado</th>
748
+ </tr>
749
+ </thead>
750
+ <tbody id="heatmap-income-body">
751
+ <!-- Populated dynamically -->
752
+ </tbody>
753
+ <tfoot id="heatmap-income-foot"></tfoot>
754
+ </table>
755
+ </div>
756
+ </div>
757
+
758
+ <!-- Expenses Heat Map table -->
759
+ <div>
760
+ <h4 style="font-size: 0.9rem; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:var(--expense-color); margin-bottom:0.75rem; margin-top:0.5rem;">
761
+ <i class="fa-solid fa-angles-down"></i> Despesas Recorrentes / Parceladas
762
+ </h4>
763
+ <div class="heatmap-table-container">
764
+ <table class="heatmap-table" id="heatmap-expense-table">
765
+ <thead>
766
+ <tr id="heatmap-expense-header-row">
767
+ <th>Categoria</th>
768
+ <th>Total Projetado</th>
769
+ </tr>
770
+ </thead>
771
+ <tbody id="heatmap-expense-body">
772
+ <!-- Populated dynamically -->
773
+ </tbody>
774
+ <tfoot id="heatmap-expense-foot"></tfoot>
775
+ </table>
776
+ </div>
777
+ </div>
778
+ </div>
779
+ </div>
780
+
781
+ <!-- MODAL: CELL TRANSACTIONS DETAIL -->
782
+ <div class="modal-overlay" id="modal-cell-details">
783
+ <div class="modal-box">
784
+ <button class="modal-close-btn" onclick="closeModal('modal-cell-details')"><i class="fa-solid fa-xmark"></i></button>
785
+ <div class="modal-title">
786
+ <i class="fa-solid fa-list-ul"></i>
787
+ <span id="modal-details-title">Transações Projetadas</span>
788
+ </div>
789
+ <div class="modal-desc-text" id="modal-details-subtitle">Categoria: - | Mês: -</div>
790
+
791
+ <div class="table-container" style="max-height: 300px; overflow-y: auto;">
792
+ <table style="font-size: 0.85rem;">
793
+ <thead>
794
+ <tr>
795
+ <th style="padding: 0.5rem 0.75rem;">Data</th>
796
+ <th style="padding: 0.5rem 0.75rem;">Descrição</th>
797
+ <th style="padding: 0.5rem 0.75rem;">Conta</th>
798
+ <th style="padding: 0.5rem 0.75rem; text-align:right;">Valor</th>
799
+ </tr>
800
+ </thead>
801
+ <tbody id="modal-details-table-body">
802
+ <!-- Dynamic list -->
803
+ </tbody>
804
+ </table>
805
+ </div>
806
+ <div class="modal-footer" style="margin-top:1.25rem;">
807
+ <button type="button" class="btn-action-primary" onclick="closeModal('modal-cell-details')" style="width:auto;">Fechar</button>
808
+ </div>
809
+ </div>
810
+ </div>
811
+
812
+
813
+
814
+ <script>
815
+ // State
816
+ var categories = [];
817
+ var allTransactions = []; // Holds all transactions fetched for the selected year
818
+ var now = new Date();
819
+ var params = new URLSearchParams(window.location.search);
820
+ var queryMonth = parseInt(params.get('month'));
821
+ var queryYear = parseInt(params.get('year'));
822
+ var selectedMonth = !isNaN(queryMonth) ? queryMonth : (now.getMonth() + 1);
823
+ var selectedYear = !isNaN(queryYear) ? queryYear : now.getFullYear();
824
+ var projectionMonths = []; // Holds list of calculated projection months dynamically
825
+
826
+ // Charts references
827
+ var projectionChartInstance = null;
828
+
829
+ // Elements
830
+ var monthSelect = document.getElementById('month-select');
831
+ var yearSelect = document.getElementById('year-select');
832
+ if (monthSelect) monthSelect.value = String(selectedMonth);
833
+ if (yearSelect) yearSelect.value = String(selectedYear);
834
+ var panelsLoading = document.getElementById('panels-loading');
835
+ var heatmapLoading = document.getElementById('heatmap-loading');
836
+
837
+ // Money formatting — per currency, never blended (issue #174 fix). Every accumulator below
838
+ // is keyed by currency; formatMultiCurrency renders each currency's own amount side by side
839
+ // instead of collapsing them into a single mislabeled total. addMultiCurrency/valueIn/
840
+ // primaryCurrencyOf/magnitudeOf/mergeCurrencyMaps/formatMultiCurrencyWith/DEFAULT_CURRENCY
841
+ // are shared globals from ui/money.js (loaded before this fragment's script — see
842
+ // docs/ui.md) rather than defined here. formatCurrency stays local — and formatMultiCurrency
843
+ // is just a 1-line delegate to formatMultiCurrencyWith passing it — because they need this
844
+ // fragment's own resolved currentLocale, which the shell-loaded, load-once money.js has no
845
+ // access to.
846
+ function formatCurrency(val, currency) {
847
+ const loc = currentLocale === 'pt' ? 'pt-BR' : (currentLocale === 'es' ? 'es-ES' : 'en-US');
848
+ return window.formatMoney(val || 0, currency || DEFAULT_CURRENCY, { locale: loc });
849
+ }
850
+
851
+ function formatMultiCurrency(map, delimiter) {
852
+ return window.formatMultiCurrencyWith(map, formatCurrency, delimiter);
853
+ }
854
+
855
+ function escapeHtml(str) {
856
+ if (!str) return '';
857
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
858
+ }
859
+
860
+ function openModal(id) {
861
+ document.getElementById(id).classList.add('open');
862
+ }
863
+
864
+ function closeModal(id) {
865
+ document.getElementById(id).classList.remove('open');
866
+ }
867
+
868
+ // Close modal on ESC key
869
+ document.addEventListener('keydown', (e) => {
870
+ if (e.key === 'Escape') {
871
+ const activeModal = document.querySelector('.modal-overlay.open');
872
+ if (activeModal) {
873
+ closeModal(activeModal.id);
874
+ }
875
+ }
876
+ });
877
+
878
+ // Toggle accordion drawer for category transactions
879
+ function toggleCategoryAccordion(elementId) {
880
+ const container = document.getElementById(elementId);
881
+ if (!container) return;
882
+
883
+ const isOpen = container.classList.contains('open');
884
+
885
+ // Close all others
886
+ document.querySelectorAll('.category-row-container').forEach(el => {
887
+ el.classList.remove('open');
888
+ el.querySelector('.category-tx-details').style.display = 'none';
889
+ });
890
+
891
+ if (!isOpen) {
892
+ container.classList.add('open');
893
+ container.querySelector('.category-tx-details').style.display = 'block';
894
+ }
895
+ }
896
+
897
+ // Bootstrap data fetch
898
+ async function initDashboard() {
899
+ if (panelsLoading) panelsLoading.classList.add('active');
900
+ if (heatmapLoading) heatmapLoading.classList.add('active');
901
+ try {
902
+ // Fetch categories
903
+ const catsRes = await fetch('/api/categories');
904
+ if (catsRes.ok) {
905
+ categories = await catsRes.json();
906
+ }
907
+ categories = Array.isArray(categories) ? categories : [];
908
+
909
+ await loadTransactionsData();
910
+ } catch (err) {
911
+ console.error("Error initializing comparative dashboard:", err);
912
+ } finally {
913
+ if (panelsLoading) panelsLoading.classList.remove('active');
914
+ if (heatmapLoading) heatmapLoading.classList.remove('active');
915
+ }
916
+ }
917
+
918
+
919
+
920
+ // Fetch transactions for calculated projection range in parallel using timezone-safe cursor pagination
921
+ async function loadTransactionsData() {
922
+ if (heatmapLoading) heatmapLoading.classList.add('active');
923
+
924
+ const mSel = document.getElementById('month-select');
925
+ const ySel = document.getElementById('year-select');
926
+ const hmSel = document.getElementById('heatmap-months-select');
927
+
928
+ const startMonth = mSel ? parseInt(mSel.value) : 7;
929
+ const startYear = ySel ? parseInt(ySel.value) : 2026;
930
+ const numMonths = hmSel ? parseInt(hmSel.value) : 6;
931
+
932
+ selectedMonth = startMonth;
933
+ selectedYear = startYear;
934
+
935
+ // Generate projection months list starting from selectedMonth of selectedYear
936
+ projectionMonths = [];
937
+ let currM = startMonth;
938
+ let currY = startYear;
939
+ for (let i = 0; i < numMonths; i++) {
940
+ projectionMonths.push({ month: currM, year: currY });
941
+ currM++;
942
+ if (currM > 12) {
943
+ currM = 1;
944
+ currY++;
945
+ }
946
+ }
947
+
948
+ try {
949
+ async function fetchMonthTransactions(year, month) {
950
+ let allItems = [];
951
+ let cursor = null;
952
+
953
+ while (true) {
954
+ const queryParams = new URLSearchParams({
955
+ month: String(month),
956
+ year: String(year),
957
+ sort: 'date',
958
+ dir: 'desc'
959
+ });
960
+ if (cursor) {
961
+ queryParams.set('cursor', cursor);
962
+ }
963
+
964
+ const url = `/api/transactions?${queryParams.toString()}`;
965
+ const res = await fetch(url);
966
+ if (!res.ok) throw new Error(`HTTP error ${res.status}`);
967
+
968
+ const data = await res.json();
969
+
970
+ let items = [];
971
+ let nextCursor = null;
972
+ if (data && typeof data === 'object') {
973
+ if (Array.isArray(data.items)) {
974
+ items = data.items;
975
+ nextCursor = data.nextCursor;
976
+ } else if (Array.isArray(data)) {
977
+ items = data;
978
+ }
979
+ }
980
+
981
+ allItems.push(...items);
982
+
983
+ if (!nextCursor) {
984
+ break;
985
+ }
986
+ cursor = nextCursor;
987
+ }
988
+
989
+ return allItems;
990
+ }
991
+
992
+ // Fetch all required months in parallel using safe pagination
993
+ const fetchPromises = projectionMonths.map(({ month, year }) => fetchMonthTransactions(year, month));
994
+ const monthlyLists = await Promise.all(fetchPromises);
995
+
996
+ allTransactions = [];
997
+ monthlyLists.forEach(list => {
998
+ if (Array.isArray(list)) {
999
+ allTransactions = allTransactions.concat(list);
1000
+ }
1001
+ });
1002
+
1003
+ calculateAndRenderAll();
1004
+ } catch (err) {
1005
+ console.error("Error loading transactions:", err);
1006
+ } finally {
1007
+ if (heatmapLoading) heatmapLoading.classList.remove('active');
1008
+ }
1009
+ }
1010
+
1011
+ // Core processing function
1012
+ function calculateAndRenderAll() {
1013
+ renderHeatMap();
1014
+ }
1015
+
1016
+ // Render charts via Chart.js
1017
+ function renderComparativeCharts(effInc, pendInc, effExp, pendExp, categorySums) {
1018
+ // Destroy existing charts to prevent hover glitching
1019
+ if (barChartInstance) barChartInstance.destroy();
1020
+ if (incomePieChartInstance) incomePieChartInstance.destroy();
1021
+ if (expensePieChartInstance) expensePieChartInstance.destroy();
1022
+
1023
+ // Bar Chart: Comparative Incomes vs Expenses
1024
+ const ctxBar = document.getElementById('barChart').getContext('2d');
1025
+ barChartInstance = new Chart(ctxBar, {
1026
+ type: 'bar',
1027
+ data: {
1028
+ labels: ['Receitas', 'Despesas'],
1029
+ datasets: [
1030
+ {
1031
+ label: 'Efetivado',
1032
+ data: [effInc, effExp],
1033
+ backgroundColor: ['#10b981', '#f43f5e'],
1034
+ borderRadius: 6
1035
+ },
1036
+ {
1037
+ label: 'Pendente',
1038
+ data: [pendInc, pendExp],
1039
+ backgroundColor: ['rgba(16, 185, 129, 0.45)', 'rgba(244, 63, 94, 0.45)'],
1040
+ borderRadius: 6
1041
+ }
1042
+ ]
1043
+ },
1044
+ options: {
1045
+ responsive: true,
1046
+ maintainAspectRatio: false,
1047
+ plugins: {
1048
+ legend: { labels: { color: '#9ca3af', font: { family: 'Plus Jakarta Sans' } } }
1049
+ },
1050
+ scales: {
1051
+ x: { stacked: true, grid: { color: 'rgba(255,255,255,0.03)' }, ticks: { color: '#9ca3af' } },
1052
+ y: { stacked: true, grid: { color: 'rgba(255,255,255,0.03)' }, ticks: { color: '#9ca3af' } }
1053
+ }
1054
+ }
1055
+ });
1056
+
1057
+ // Parse categories for pies
1058
+ const incomeCategories = [];
1059
+ const expenseCategories = [];
1060
+
1061
+ Object.values(categorySums).forEach(cat => {
1062
+ const total = cat.effective + cat.pending;
1063
+ if (total <= 0) return;
1064
+
1065
+ if (cat.kind === 'income') {
1066
+ incomeCategories.push(cat);
1067
+ } else {
1068
+ expenseCategories.push(cat);
1069
+ }
1070
+ });
1071
+
1072
+ // Donut 1: Incomes by Category
1073
+ const ctxIncPie = document.getElementById('incomePieChart').getContext('2d');
1074
+ incomePieChartInstance = new Chart(ctxIncPie, {
1075
+ type: 'doughnut',
1076
+ data: {
1077
+ labels: incomeCategories.map(c => c.name),
1078
+ datasets: [{
1079
+ data: incomeCategories.map(c => c.effective + c.pending),
1080
+ backgroundColor: ['#10b981', '#34d399', '#6ee7b7', '#a7f3d0', '#047857', '#065f46'],
1081
+ borderWidth: 1,
1082
+ borderColor: '#111322'
1083
+ }]
1084
+ },
1085
+ options: {
1086
+ responsive: true,
1087
+ maintainAspectRatio: false,
1088
+ plugins: {
1089
+ legend: { display: false } // Hide legend to look premium
1090
+ },
1091
+ cutout: '65%'
1092
+ }
1093
+ });
1094
+
1095
+ // Donut 2: Expenses by Category
1096
+ const ctxExpPie = document.getElementById('expensePieChart').getContext('2d');
1097
+ expensePieChartInstance = new Chart(ctxExpPie, {
1098
+ type: 'doughnut',
1099
+ data: {
1100
+ labels: expenseCategories.map(c => c.name),
1101
+ datasets: [{
1102
+ data: expenseCategories.map(c => c.effective + c.pending),
1103
+ backgroundColor: ['#f43f5e', '#fb7185', '#fca5a5', '#ffe4e6', '#be123c', '#9f1239'],
1104
+ borderWidth: 1,
1105
+ borderColor: '#111322'
1106
+ }]
1107
+ },
1108
+ options: {
1109
+ responsive: true,
1110
+ maintainAspectRatio: false,
1111
+ plugins: {
1112
+ legend: { display: false }
1113
+ },
1114
+ cutout: '65%'
1115
+ }
1116
+ });
1117
+ }
1118
+
1119
+ // Render side-by-side categories layout
1120
+ function renderCategoryColumns(categorySums, totalIncome, totalExpense) {
1121
+ const incListEl = document.getElementById('income-categories-list');
1122
+ const expListEl = document.getElementById('expense-categories-list');
1123
+
1124
+ incListEl.innerHTML = '';
1125
+ expListEl.innerHTML = '';
1126
+
1127
+ // Group by category type
1128
+ const listCats = Object.values(categorySums);
1129
+
1130
+ // Add any other categories that exist in DB but have no transactions in current month
1131
+ categories.forEach(c => {
1132
+ const found = listCats.some(lc => lc.id === c.id);
1133
+ if (!found) {
1134
+ listCats.push({
1135
+ id: c.id,
1136
+ name: c.name,
1137
+ kind: c.kind,
1138
+ effective: 0,
1139
+ pending: 0,
1140
+ txs: []
1141
+ });
1142
+ }
1143
+ });
1144
+
1145
+ // Sort lists by total value descending
1146
+ listCats.sort((a,b) => (b.effective + b.pending) - (a.effective + a.pending));
1147
+
1148
+ let incTotalSum = 0;
1149
+ let expTotalSum = 0;
1150
+
1151
+ listCats.forEach(cat => {
1152
+ const total = cat.effective + cat.pending;
1153
+ if (cat.kind === 'income') {
1154
+ incTotalSum += total;
1155
+ } else {
1156
+ expTotalSum += total;
1157
+ }
1158
+
1159
+ if (total === 0) {
1160
+ return;
1161
+ }
1162
+
1163
+ // Render progress bar widths relative to total income/expense of the month
1164
+ let pctEff = 0;
1165
+ let pctPend = 0;
1166
+ if (cat.kind === 'income') {
1167
+ if (totalIncome > 0) {
1168
+ pctEff = (cat.effective / totalIncome) * 100;
1169
+ pctPend = (cat.pending / totalIncome) * 100;
1170
+ }
1171
+ } else {
1172
+ if (totalExpense > 0) {
1173
+ pctEff = (cat.effective / totalExpense) * 100;
1174
+ pctPend = (cat.pending / totalExpense) * 100;
1175
+ }
1176
+ }
1177
+
1178
+ // Create container element
1179
+ const rowId = `cat-row-${cat.id}`;
1180
+ const div = document.createElement('div');
1181
+ div.className = 'category-row-container';
1182
+ div.id = rowId;
1183
+
1184
+ // Sort transactions inside drawer
1185
+ cat.txs.sort((a,b) => b.date.localeCompare(a.date));
1186
+
1187
+ div.innerHTML = `
1188
+ <div class="category-row-header" onclick="toggleCategoryAccordion('${rowId}')">
1189
+ <div class="cat-meta-info">
1190
+ <div class="cat-name-label">
1191
+ <i class="fa-solid fa-chevron-down"></i>
1192
+ ${escapeHtml(cat.name)}
1193
+ </div>
1194
+ <div class="cat-val-label">
1195
+ ${formatCurrency(total, DEFAULT_CURRENCY)}
1196
+ <span class="cat-pct-label">${(pctEff + pctPend).toFixed(1)}%</span>
1197
+ </div>
1198
+ </div>
1199
+
1200
+ <div class="proportion-bar-container">
1201
+ <div class="bar-segment ${cat.kind === 'income' ? 'effective-inc' : 'effective-exp'}" style="width: ${pctEff}%;"></div>
1202
+ <div class="bar-segment ${cat.kind === 'income' ? 'pending-inc' : 'pending-exp'}" style="width: ${pctPend}%;"></div>
1203
+ </div>
1204
+
1205
+ <div class="cat-breakdown-text">
1206
+ <span>Efetivado: <strong>${formatCurrency(cat.effective, DEFAULT_CURRENCY)}</strong></span>
1207
+ <span>Pendente: <strong>${formatCurrency(cat.pending, DEFAULT_CURRENCY)}</strong></span>
1208
+ </div>
1209
+ </div>
1210
+
1211
+ <div class="category-tx-details">
1212
+ ${cat.txs.length === 0 ? '<div style="font-size:0.75rem; color:var(--text-dark); font-style:italic; padding:0.25rem;">Nenhum lançamento no mês.</div>' : `
1213
+ <table class="category-tx-table">
1214
+ <thead>
1215
+ <tr>
1216
+ <th>Data</th>
1217
+ <th>Descrição</th>
1218
+ <th>Conta</th>
1219
+ <th>Status</th>
1220
+ <th style="text-align:right;">Valor</th>
1221
+ </tr>
1222
+ </thead>
1223
+ <tbody>
1224
+ ${cat.txs.map(t => {
1225
+ const dtObj = new Date(t.date + 'T12:00:00');
1226
+ const dtFmt = dtObj.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
1227
+ return `
1228
+ <tr>
1229
+ <td>${dtFmt}</td>
1230
+ <td>${escapeHtml(t.description)}</td>
1231
+ <td>${escapeHtml(t.accountName)}</td>
1232
+ <td>
1233
+ <span class="badge-status ${t.status === 'effective' ? 'status-eff' : 'status-pend'}">
1234
+ ${t.status === 'effective' ? 'Efetivado' : 'Pendente'}
1235
+ </span>
1236
+ </td>
1237
+ <td style="text-align:right; font-weight:700; color:${t.type === 'income' ? 'var(--income-color)' : 'var(--text-main)'}">
1238
+ ${t.type === 'income' ? '+' : '-'} ${formatCurrency(t.amount, DEFAULT_CURRENCY)}
1239
+ </td>
1240
+ </tr>
1241
+ `;
1242
+ }).join('')}
1243
+ </tbody>
1244
+ </table>
1245
+ `}
1246
+ </div>
1247
+ `;
1248
+
1249
+ if (cat.kind === 'income') {
1250
+ incListEl.appendChild(div);
1251
+ } else {
1252
+ expListEl.appendChild(div);
1253
+ }
1254
+ });
1255
+
1256
+ document.getElementById('income-categories-total').textContent = formatCurrency(incTotalSum, DEFAULT_CURRENCY);
1257
+ document.getElementById('expense-categories-total').textContent = formatCurrency(expTotalSum, DEFAULT_CURRENCY);
1258
+ }
1259
+
1260
+ // Sums a list of transactions into a currency -> amount map — never a blended scalar, so a
1261
+ // cell/row/column mixing BRL/USD/BTC recurrences keeps each currency's own total.
1262
+ function sumByCurrency(txs) {
1263
+ const map = {};
1264
+ txs.forEach(tx => addMultiCurrency(map, tx.currency || DEFAULT_CURRENCY, tx.amount));
1265
+ return map;
1266
+ }
1267
+
1268
+ // Render Recurring & Installment Heat Map
1269
+ function renderHeatMap() {
1270
+ // We use global projectionMonths array
1271
+ const monthsNamesShort = {
1272
+ 1: 'Jan', 2: 'Fev', 3: 'Mar', 4: 'Abr', 5: 'Mai', 6: 'Jun',
1273
+ 7: 'Jul', 8: 'Ago', 9: 'Set', 10: 'Out', 11: 'Nov', 12: 'Dez'
1274
+ };
1275
+
1276
+ const incBody = document.getElementById('heatmap-income-body');
1277
+ const expBody = document.getElementById('heatmap-expense-body');
1278
+
1279
+ incBody.innerHTML = '';
1280
+ expBody.innerHTML = '';
1281
+
1282
+ // Render table headers dynamically
1283
+ const incHeadRow = document.getElementById('heatmap-income-header-row');
1284
+ const expHeadRow = document.getElementById('heatmap-expense-header-row');
1285
+
1286
+ const headerHtml = `
1287
+ <th>Categoria</th>
1288
+ ${projectionMonths.map(p => `<th>${monthsNamesShort[p.month]} ${String(p.year).substring(2)}</th>`).join('')}
1289
+ <th>Total Projetado</th>
1290
+ `;
1291
+ if (incHeadRow) incHeadRow.innerHTML = headerHtml;
1292
+ if (expHeadRow) expHeadRow.innerHTML = headerHtml;
1293
+
1294
+ // Group all transactions in the projectionMonths
1295
+ // Row key: categoryId -> { categoryName, kind, monthValues: { "YYYY-MM": [] } }
1296
+ const heatMatrix = {};
1297
+
1298
+ // Initialize all categories in the matrix
1299
+ categories.forEach(c => {
1300
+ heatMatrix[c.id] = {
1301
+ categoryId: c.id,
1302
+ categoryName: c.name,
1303
+ kind: c.kind,
1304
+ months: {}
1305
+ };
1306
+ projectionMonths.forEach(p => {
1307
+ const key = `${p.year}-${p.month}`;
1308
+ heatMatrix[c.id].months[key] = [];
1309
+ });
1310
+ });
1311
+
1312
+ // Filter year transactions that fall in the projection range
1313
+ allTransactions.forEach(t => {
1314
+ // Ignore all transfers (including bill payments)
1315
+ if (t.type === 'transfer') return;
1316
+
1317
+ if (!t.date || typeof t.date !== 'string') return;
1318
+
1319
+ const tDateObj = new Date(t.date + 'T12:00:00');
1320
+ const tYear = tDateObj.getFullYear();
1321
+ const tMonth = tDateObj.getMonth() + 1; // 1-indexed
1322
+
1323
+ // Check if this month/year matches any of the projection months
1324
+ const isInProjection = projectionMonths.some(p => p.month === tMonth && p.year === tYear);
1325
+ if (!isInProjection) return;
1326
+
1327
+ const catId = t.categoryId || 'cat-none';
1328
+ if (!heatMatrix[catId]) {
1329
+ // Fallback create category
1330
+ heatMatrix[catId] = {
1331
+ categoryId: catId,
1332
+ categoryName: t.categoryName || 'Sem Categoria',
1333
+ kind: t.type === 'income' ? 'income' : 'expense',
1334
+ months: {}
1335
+ };
1336
+ projectionMonths.forEach(p => {
1337
+ const key = `${p.year}-${p.month}`;
1338
+ heatMatrix[catId].months[key] = [];
1339
+ });
1340
+ }
1341
+
1342
+ const key = `${tYear}-${tMonth}`;
1343
+ heatMatrix[catId].months[key].push(t);
1344
+ });
1345
+
1346
+ // Determine, PER CURRENCY, the max cell value to calculate color opacity relative
1347
+ // range (heat map effect) — a 0.05 BTC cell and a 10,000 BRL cell aren't comparable in
1348
+ // raw units, so blending them into one cross-currency max would skew the intensity
1349
+ // scale toward whichever currency happens to use larger raw numbers. Each currency
1350
+ // gets its own max, and each cell's opacity is computed against its own currency's max.
1351
+ // No artificial minimum floor here (the old single-scale code used 100, calibrated for
1352
+ // BRL/USD magnitudes) — each currency seen here is only ever compared against its own
1353
+ // real cell values below, so a fixed floor would just crush a naturally small-scale
1354
+ // currency like BTC toward the opacity floor regardless of its own relative intensity.
1355
+ const maxIncomeCellByCurrency = {};
1356
+ const maxExpenseCellByCurrency = {};
1357
+ Object.values(heatMatrix).forEach(row => {
1358
+ const store = row.kind === 'income' ? maxIncomeCellByCurrency : maxExpenseCellByCurrency;
1359
+ projectionMonths.forEach(p => {
1360
+ const key = `${p.year}-${p.month}`;
1361
+ const cellSums = sumByCurrency(row.months[key]);
1362
+ Object.keys(cellSums).forEach(c => {
1363
+ store[c] = Math.max(cellSums[c], store[c] || 0);
1364
+ });
1365
+ });
1366
+ });
1367
+
1368
+ // Accumulators for column totals — currency -> amount maps, never blended scalars.
1369
+ const colSums = {};
1370
+ projectionMonths.forEach(p => {
1371
+ const key = `${p.year}-${p.month}`;
1372
+ colSums[key] = { income: {}, expense: {} };
1373
+ });
1374
+ const totalIncomeSum = {};
1375
+ const totalExpenseSum = {};
1376
+ let hasIncomeData = false;
1377
+ let hasExpenseData = false;
1378
+
1379
+ // Render Rows
1380
+ Object.values(heatMatrix).forEach(row => {
1381
+ // Calculate row total sum, per currency
1382
+ const rowTotal = {};
1383
+ projectionMonths.forEach(p => {
1384
+ const key = `${p.year}-${p.month}`;
1385
+ const cellSums = sumByCurrency(row.months[key]);
1386
+ Object.keys(cellSums).forEach(c => addMultiCurrency(rowTotal, c, cellSums[c]));
1387
+ });
1388
+
1389
+ // Skip category row if it has no recurrings/installments in these months
1390
+ if (magnitudeOf(rowTotal) === 0) return;
1391
+
1392
+ // Update column sums
1393
+ if (row.kind === 'income') {
1394
+ hasIncomeData = true;
1395
+ Object.keys(rowTotal).forEach(c => addMultiCurrency(totalIncomeSum, c, rowTotal[c]));
1396
+ projectionMonths.forEach(p => {
1397
+ const key = `${p.year}-${p.month}`;
1398
+ const cellSums = sumByCurrency(row.months[key]);
1399
+ Object.keys(cellSums).forEach(c => addMultiCurrency(colSums[key].income, c, cellSums[c]));
1400
+ });
1401
+ } else {
1402
+ hasExpenseData = true;
1403
+ Object.keys(rowTotal).forEach(c => addMultiCurrency(totalExpenseSum, c, rowTotal[c]));
1404
+ projectionMonths.forEach(p => {
1405
+ const key = `${p.year}-${p.month}`;
1406
+ const cellSums = sumByCurrency(row.months[key]);
1407
+ Object.keys(cellSums).forEach(c => addMultiCurrency(colSums[key].expense, c, cellSums[c]));
1408
+ });
1409
+ }
1410
+
1411
+ const tr = document.createElement('tr');
1412
+
1413
+ // Column 1: Category Name
1414
+ let cellsHtml = `<td>${escapeHtml(row.categoryName)}</td>`;
1415
+
1416
+ // Columns: Months
1417
+ projectionMonths.forEach(p => {
1418
+ const key = `${p.year}-${p.month}`;
1419
+ const cellSums = sumByCurrency(row.months[key]);
1420
+
1421
+ if (magnitudeOf(cellSums) === 0) {
1422
+ cellsHtml += `<td class="heatmap-empty">-</td>`;
1423
+ } else {
1424
+ // Calculate opacity relative to the max value THIS cell's own currency
1425
+ // reaches anywhere in the matrix (using power scale to increase
1426
+ // sensitivity) — never against another currency's max, see above.
1427
+ const cellCurrency = primaryCurrencyOf(cellSums);
1428
+ const cellVal = valueIn(cellSums, cellCurrency);
1429
+ const maxByCurrency = row.kind === 'income' ? maxIncomeCellByCurrency : maxExpenseCellByCurrency;
1430
+ // Falls back to this cell's own value (never a fixed constant) in the
1431
+ // unreachable case where the tracking pass above somehow missed this
1432
+ // currency — guarantees a 1.0 ratio rather than a division by zero.
1433
+ const maxVal = valueIn(maxByCurrency, cellCurrency) || cellVal;
1434
+ const ratio = Math.pow(cellVal / maxVal, 0.4);
1435
+ const opacity = Math.min(1, Math.max(0.12, ratio));
1436
+ const bgColor = row.kind === 'income'
1437
+ ? `rgba(16, 185, 129, ${opacity})`
1438
+ : `rgba(244, 63, 94, ${opacity})`;
1439
+
1440
+ const textColor = opacity > 0.65 ? '#fff' : 'var(--text-main)';
1441
+
1442
+ const cellId = `hc-${row.categoryId}-${key}`;
1443
+
1444
+ cellsHtml += `
1445
+ <td style="padding:0.4rem;">
1446
+ <span class="heatmap-cell-value" id="${cellId}"
1447
+ style="background:${bgColor}; color:${textColor};"
1448
+ onclick="showHeatmapCellDetails('${row.categoryId}', ${p.month}, ${p.year}, '${escapeJsAttr(row.categoryName)}')">
1449
+ ${formatMultiCurrency(cellSums)}
1450
+ </span>
1451
+ </td>
1452
+ `;
1453
+ }
1454
+ });
1455
+
1456
+ // Row Total
1457
+ cellsHtml += `<td>${formatMultiCurrency(rowTotal)}</td>`;
1458
+ tr.innerHTML = cellsHtml;
1459
+
1460
+ if (row.kind === 'income') {
1461
+ incBody.appendChild(tr);
1462
+ } else {
1463
+ expBody.appendChild(tr);
1464
+ }
1465
+ });
1466
+
1467
+ // Fallback for empty tables
1468
+ const colspan = projectionMonths.length + 2;
1469
+ if (incBody.innerHTML === '') {
1470
+ incBody.innerHTML = `<tr><td colspan="${colspan}" class="heatmap-empty" style="text-align:center;">${t("no_recurrent_incomes")}</td></tr>`;
1471
+ }
1472
+ if (expBody.innerHTML === '') {
1473
+ expBody.innerHTML = `<tr><td colspan="${colspan}" class="heatmap-empty" style="text-align:center;">${t("no_recurrent_expenses")}</td></tr>`;
1474
+ }
1475
+
1476
+ // Render Footers with Column Totals
1477
+ const incFoot = document.getElementById('heatmap-income-foot');
1478
+ if (incFoot) {
1479
+ if (!hasIncomeData) {
1480
+ incFoot.innerHTML = '';
1481
+ } else {
1482
+ let cellsHtml = `<td style="text-align:left; font-weight:700;">TOTAL</td>`;
1483
+ projectionMonths.forEach(p => {
1484
+ const key = `${p.year}-${p.month}`;
1485
+ cellsHtml += `<td style="font-weight:700; color:var(--income-color);">${formatMultiCurrency(colSums[key].income)}</td>`;
1486
+ });
1487
+ cellsHtml += `<td style="font-weight:700; color:var(--income-color);">${formatMultiCurrency(totalIncomeSum)}</td>`;
1488
+ incFoot.innerHTML = `<tr>${cellsHtml}</tr>`;
1489
+ }
1490
+ }
1491
+
1492
+ const expFoot = document.getElementById('heatmap-expense-foot');
1493
+ if (expFoot) {
1494
+ if (!hasExpenseData) {
1495
+ expFoot.innerHTML = '';
1496
+ } else {
1497
+ let cellsHtml = `<td style="text-align:left; font-weight:700;">TOTAL</td>`;
1498
+ projectionMonths.forEach(p => {
1499
+ const key = `${p.year}-${p.month}`;
1500
+ cellsHtml += `<td style="font-weight:700; color:var(--expense-color);">${formatMultiCurrency(colSums[key].expense)}</td>`;
1501
+ });
1502
+ cellsHtml += `<td style="font-weight:700; color:var(--expense-color);">${formatMultiCurrency(totalExpenseSum)}</td>`;
1503
+ expFoot.innerHTML = `<tr>${cellsHtml}</tr>`;
1504
+ }
1505
+ }
1506
+
1507
+ // Render cash flow line chart
1508
+ try {
1509
+ if (typeof Chart !== 'undefined') {
1510
+ renderProjectionLineChart(projectionMonths, colSums);
1511
+ }
1512
+ } catch (e) {
1513
+ console.error("Error rendering projection line chart:", e);
1514
+ }
1515
+ }
1516
+
1517
+ // Show projected details inside modal on cell click
1518
+ function showHeatmapCellDetails(categoryId, month, year, categoryName) {
1519
+ const monthsNames = {
1520
+ 1: 'Janeiro', 2: 'Fevereiro', 3: 'Março', 4: 'Abril', 5: 'Maio', 6: 'Junho',
1521
+ 7: 'Julho', 8: 'Agosto', 9: 'Setembro', 10: 'Outubro', 11: 'Novembro', 12: 'Dezembro'
1522
+ };
1523
+
1524
+ const title = document.getElementById('modal-details-title');
1525
+ const subtitle = document.getElementById('modal-details-subtitle');
1526
+ const body = document.getElementById('modal-details-table-body');
1527
+
1528
+ title.textContent = t("modal_details_title");
1529
+ const monthsKeys = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
1530
+ subtitle.textContent = `${t("label_category")}: ${categoryName} | ${t("month")}: ${t(monthsKeys[month - 1])} | ${year}`;
1531
+ body.innerHTML = '';
1532
+
1533
+ // Filter year transactions in state
1534
+ const currentMonthStr = `${year}-${String(month).padStart(2, '0')}`;
1535
+ const matches = allTransactions.filter(t => {
1536
+ // Ignore all transfers (including bill payments)
1537
+ if (t.type === 'transfer') return false;
1538
+
1539
+ const catMatch = t.categoryId === categoryId || (!t.categoryId && categoryId === 'cat-none');
1540
+ return catMatch && t.date && t.date.startsWith(currentMonthStr);
1541
+ });
1542
+
1543
+ matches.sort((a,b) => a.date.localeCompare(b.date));
1544
+
1545
+ matches.forEach(t => {
1546
+ const tr = document.createElement('tr');
1547
+ const dtObj = new Date(t.date + 'T12:00:00');
1548
+ const dtFmt = dtObj.toLocaleDateString('pt-BR');
1549
+
1550
+ tr.innerHTML = `
1551
+ <td style="padding:0.5rem 0.75rem;">${dtFmt}</td>
1552
+ <td style="padding:0.5rem 0.75rem; font-weight:500;">${escapeHtml(t.description)}</td>
1553
+ <td style="padding:0.5rem 0.75rem;">${escapeHtml(t.accountName)}</td>
1554
+ <td style="padding:0.5rem 0.75rem; text-align:right; font-weight:700; white-space:nowrap; color:${t.type === 'income' ? 'var(--income-color)' : 'var(--expense-color)'}">
1555
+ ${t.type === 'income' ? '+' : '-'} ${formatCurrency(Math.abs(t.amount), t.currency || DEFAULT_CURRENCY)}
1556
+ </td>
1557
+ `;
1558
+ body.appendChild(tr);
1559
+ });
1560
+
1561
+ openModal('modal-cell-details');
1562
+ }
1563
+
1564
+ // JS escaping helper
1565
+ // Escapes a value for safe embedding as a single-quoted JS string literal *inside* an
1566
+ // HTML attribute (e.g. onclick="fn('${escapeJsAttr(value)}')"). JS-escaping backslash+quote
1567
+ // alone is not enough: the outer onclick="..." attribute is double-quoted, and the HTML
1568
+ // parser (which finds the attribute's closing quote before any JS is parsed) doesn't
1569
+ // understand a JS \" escape — a raw '"' still ends the attribute early. HTML-escaping the
1570
+ // JS-escaped result closes that gap too.
1571
+ function escapeJsAttr(str) {
1572
+ if (!str) return '';
1573
+ return escapeHtml(String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'"));
1574
+ }
1575
+
1576
+
1577
+ // Render projected cash flow trend line chart using Chart.js. Chart.js needs a single
1578
+ // numeric series, so the chart shows ONE real currency (never a blended/converted total)
1579
+ // — the heat map tables above already show every currency correctly.
1580
+ function renderProjectionLineChart(months, colSums) {
1581
+ if (projectionChartInstance) {
1582
+ projectionChartInstance.destroy();
1583
+ }
1584
+
1585
+ const labels = months.map(p => {
1586
+ const monthsNamesShort = {
1587
+ 1: 'Jan', 2: 'Fev', 3: 'Mar', 4: 'Abr', 5: 'Mai', 6: 'Jun',
1588
+ 7: 'Jul', 8: 'Ago', 9: 'Set', 10: 'Out', 11: 'Nov', 12: 'Dez'
1589
+ };
1590
+ return `${monthsNamesShort[p.month]} ${String(p.year).substring(2)}`;
1591
+ });
1592
+
1593
+ const chartCurrency = primaryCurrencyOf(
1594
+ mergeCurrencyMaps(...months.map(p => colSums[`${p.year}-${p.month}`]?.income), ...months.map(p => colSums[`${p.year}-${p.month}`]?.expense))
1595
+ );
1596
+
1597
+ const incomeData = [];
1598
+ const expenseData = [];
1599
+ const netData = [];
1600
+
1601
+ months.forEach(p => {
1602
+ const key = `${p.year}-${p.month}`;
1603
+ const inc = valueIn(colSums[key]?.income, chartCurrency);
1604
+ const exp = valueIn(colSums[key]?.expense, chartCurrency);
1605
+ incomeData.push(inc);
1606
+ expenseData.push(exp);
1607
+ netData.push(inc - exp);
1608
+ });
1609
+
1610
+ const ctx = document.getElementById('projectionLineChart').getContext('2d');
1611
+ projectionChartInstance = new Chart(ctx, {
1612
+ type: 'line',
1613
+ data: {
1614
+ labels: labels,
1615
+ datasets: [
1616
+ {
1617
+ label: 'Receitas Projetadas',
1618
+ data: incomeData,
1619
+ borderColor: '#10b981',
1620
+ backgroundColor: 'rgba(16, 185, 129, 0.1)',
1621
+ borderWidth: 2.5,
1622
+ tension: 0.45,
1623
+ fill: false
1624
+ },
1625
+ {
1626
+ label: 'Despesas Projetadas',
1627
+ data: expenseData,
1628
+ borderColor: '#f43f5e',
1629
+ backgroundColor: 'rgba(244, 63, 94, 0.1)',
1630
+ borderWidth: 2.5,
1631
+ tension: 0.45,
1632
+ fill: false
1633
+ },
1634
+ {
1635
+ label: 'Saldo Líquido Projetado',
1636
+ data: netData,
1637
+ borderColor: '#8b5cf6',
1638
+ backgroundColor: 'rgba(139, 92, 246, 0.05)',
1639
+ borderWidth: 2,
1640
+ borderDash: [5, 5],
1641
+ tension: 0.45,
1642
+ fill: false
1643
+ }
1644
+ ]
1645
+ },
1646
+ options: {
1647
+ responsive: true,
1648
+ maintainAspectRatio: false,
1649
+ plugins: {
1650
+ legend: {
1651
+ labels: {
1652
+ color: '#9ca3af',
1653
+ font: { family: 'Plus Jakarta Sans', size: 11 }
1654
+ }
1655
+ },
1656
+ tooltip: {
1657
+ callbacks: {
1658
+ label: function(ctx) {
1659
+ return `${ctx.dataset.label}: ${formatCurrency(ctx.raw, chartCurrency)}`;
1660
+ }
1661
+ }
1662
+ }
1663
+ },
1664
+ scales: {
1665
+ x: {
1666
+ grid: { color: 'rgba(255,255,255,0.03)' },
1667
+ ticks: { color: '#9ca3af', font: { family: 'Plus Jakarta Sans' } }
1668
+ },
1669
+ y: {
1670
+ grid: { color: 'rgba(255,255,255,0.03)' },
1671
+ ticks: {
1672
+ color: '#9ca3af',
1673
+ font: { family: 'Plus Jakarta Sans' },
1674
+ callback: function(value) {
1675
+ return formatCurrency(value, chartCurrency);
1676
+ }
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+ });
1682
+ }
1683
+
1684
+ // Load bootstrap - try direct execution first, and bind to onload as fallback.
1685
+ // Locale must resolve before the first render: formatCurrency reads currentLocale, and
1686
+ // checkLocale() only re-translates static data-i18n text afterward — it never re-renders
1687
+ // the heat-map/chart money values initDashboard() already painted, so those would be stuck
1688
+ // showing en-US formatting for a pt/es user if initDashboard() won the race. The month/year/
1689
+ // heatmap-months change listeners must wait for the same reason: registering them early would
1690
+ // let a user interaction call loadTransactionsData() (and therefore renderHeatMap()'s
1691
+ // formatCurrency calls) before checkLocale() resolves.
1692
+ //
1693
+ // If the user navigates away while checkLocale()'s /api/status request is still in flight,
1694
+ // app.js's renderFragment() tears this fragment's DOM down for the next one — the stale
1695
+ // continuation must not resume into initDashboard() (or attach listeners) afterward, since
1696
+ // document.getElementById(...) calls could reach into whatever dashboard loaded next
1697
+ // (mirrors overview.html's initOverview guard). heatmapLoading itself can't be the marker:
1698
+ // it's a top-level `var`, so it lives on the shared global `window` every fragment script
1699
+ // executes in, and comparative.html declares the very same name — a later-loaded fragment's
1700
+ // script would silently overwrite it out from under this still-pending continuation. Capture
1701
+ // it into a function-local const instead, which no other script can ever reach or reassign.
1702
+ var hasInitialized = false;
1703
+ async function runInit() {
1704
+ if (hasInitialized) return;
1705
+ hasInitialized = true;
1706
+ const ownFragmentMarker = heatmapLoading;
1707
+ projectionsMarker = ownFragmentMarker;
1708
+ await checkLocale();
1709
+ if (!ownFragmentMarker || !ownFragmentMarker.isConnected) return;
1710
+
1711
+ const mSel = document.getElementById('month-select');
1712
+ const ySel = document.getElementById('year-select');
1713
+ const hmSel = document.getElementById('heatmap-months-select');
1714
+ if (mSel) mSel.addEventListener('change', loadTransactionsData);
1715
+ if (ySel) ySel.addEventListener('change', loadTransactionsData);
1716
+ if (hmSel) hmSel.addEventListener('change', loadTransactionsData);
1717
+
1718
+ await initDashboard();
1719
+ projectionsBootDone = true;
1720
+ }
1721
+
1722
+ // Live update: runInit() is one-shot, so an event after boot refetches through initDashboard() directly.
1723
+ // An event while boot is still in flight is dropped (boot fetches current data), as is one for a torn-down fragment.
1724
+ var projectionsBootDone = false;
1725
+ var projectionsMarker = null;
1726
+ function refreshProjections() {
1727
+ if (!projectionsBootDone || !projectionsMarker || !projectionsMarker.isConnected) return Promise.resolve();
1728
+ return initDashboard();
1729
+ }
1730
+
1731
+ // Run immediately since DOM is already parsed (script is at bottom of body)
1732
+ runInit();
1733
+
1734
+ // Fallback for full page loads or wrapper injections
1735
+ runInit();
1736
+
1737
+ // Translation engine and dictionaries
1738
+ var TRANSLATIONS = {
1739
+ en: {
1740
+ // Sidebar Menu
1741
+ tooltip_overview: "Overview",
1742
+ tooltip_pending: "Pending",
1743
+ tooltip_comparative: "Comparative",
1744
+ tooltip_projections: "Projections",
1745
+ tooltip_accounts: "Bank Accounts",
1746
+ tooltip_cards: "Credit Cards",
1747
+ menu_categories: "Categories",
1748
+ menu_dashboards: "Dashboards",
1749
+
1750
+ // Month names
1751
+ january: "January", february: "February", march: "March", april: "April", may: "May", june: "June",
1752
+ july: "July", august: "August", september: "September", october: "October", november: "November", december: "December",
1753
+
1754
+ // General UI terms
1755
+ reference_label: "Reference:",
1756
+ day_sun: "Sun", day_mon: "Mon", day_tue: "Tue", day_wed: "Wed", day_thu: "Thu", day_fri: "Fri", day_sat: "Sat",
1757
+ paid: "Paid", unpaid: "Unpaid", active: "Active", inactive: "Inactive",
1758
+
1759
+ // Overview Dashboard
1760
+ overview_title: "Overview",
1761
+ overview_subtitle: "Monthly financial summary, calendar, and quick shortcuts",
1762
+ accounts_balance: "Accounts Balance",
1763
+ expenses_month: "Expenses this Month",
1764
+ card_bills: "Credit Card Bills",
1765
+ incomes_month: "Incomes this Month",
1766
+ final_projection: "Final Projection:",
1767
+ recent_transactions: "Recent Transactions",
1768
+ due_calendar: "Daily Flow & Dues",
1769
+ expenses_distribution: "Expenses Distribution",
1770
+ quick_shortcuts: "Quick Shortcuts",
1771
+ new_transaction: "New Transaction",
1772
+ new_transfer: "New Transfer",
1773
+ new_category: "New Category",
1774
+ new_card: "New Card",
1775
+ new_account: "New Account",
1776
+ no_expenses_month: "No expenses recorded this month.",
1777
+ no_recent_transactions: "No recent transactions found.",
1778
+ no_dues_period: "No transactions due in this period.",
1779
+ income: "Income",
1780
+ expense: "Expense",
1781
+ paid_reconciled: "Paid / Reconciled",
1782
+
1783
+ // Projections / Heatmap Dashboard
1784
+ projections_title: "Recurring & Installment Projections",
1785
+ projections_subtitle: "Advanced visual mapping and projection of active recurrences and installments for the next months",
1786
+ projection_label: "Projection:",
1787
+ months_3: "3 Months",
1788
+ months_6: "6 Months",
1789
+ months_9: "9 Months",
1790
+ months_12: "12 Months",
1791
+ heatmap_income_title: "Recurrent / Installment Incomes",
1792
+ heatmap_expense_title: "Recurrent / Installment Expenses",
1793
+ total: "Total",
1794
+ no_recurrent_incomes: "No active recurrent or installment incomes in the selected semester.",
1795
+ no_recurrent_expenses: "No active recurrent or installment expenses in the selected semester.",
1796
+ modal_details_title: "Projection Breakdown",
1797
+ modal_details_subtitle: "Details of projected transactions for the category and month",
1798
+ col_date: "Date",
1799
+ col_desc: "Description",
1800
+ col_value: "Value",
1801
+ col_status: "Status",
1802
+ btn_close: "Close",
1803
+
1804
+ // Comparative Dashboard
1805
+ comparative_title: "Comparative Dashboard",
1806
+ comparative_subtitle: "Analysis and comparison of monthly incomes vs expenses, and category limits",
1807
+ month_summary_title: "Month Summary",
1808
+ cat_spending_title: "Spending by Category",
1809
+ card_limits_title: "Category Budgets & Limits",
1810
+ col_category: "Category",
1811
+ col_limit: "Budget Limit",
1812
+ col_spent: "Spent",
1813
+ col_status_limit: "Status",
1814
+ col_percentage: "Percentage",
1815
+ within_limit: "Within Limit",
1816
+ exceeded: "Exceeded",
1817
+ reception: "Incomes",
1818
+ deduction: "Expenses",
1819
+ net_balance: "Net Balance",
1820
+ performance: "Financial Health",
1821
+ no_spending_month: "No category spend recorded this month.",
1822
+
1823
+ // Accounts Dashboard
1824
+ accounts_title: "Bank Accounts",
1825
+ accounts_subtitle: "Manage accounts, checking balances, and reviewing statements",
1826
+ active_account_statement: "Account Statement",
1827
+ btn_new_transaction: "New Transaction",
1828
+ btn_new_transfer: "New Transfer",
1829
+ search_description_placeholder: "Type to search...",
1830
+ filter_type_label: "Type",
1831
+ filter_type_all: "All",
1832
+ filter_type_income: "Incomes",
1833
+ filter_type_expense: "Expenses",
1834
+ col_actions: "Actions",
1835
+ action_confirm: "Confirm",
1836
+ action_edit: "Edit",
1837
+ action_delete: "Delete",
1838
+ no_transactions_account: "No transactions recorded for this account in the selected month.",
1839
+ confirm_delete_title: "Are you sure you want to permanently delete this transaction?",
1840
+ modal_new_tx_title: "New Transaction",
1841
+ modal_new_transfer_title: "New Transfer",
1842
+ label_account: "Account",
1843
+ label_description: "Description",
1844
+ label_value: "Value",
1845
+ label_date: "Date",
1846
+ label_category: "Category / Subcategory",
1847
+ label_type: "Type",
1848
+ label_status: "Status",
1849
+ status_pending: "Pending",
1850
+ status_confirmed: "Paid / Confirmed",
1851
+ btn_cancel: "Cancel",
1852
+ btn_save: "Save",
1853
+ label_origin: "Origin Account",
1854
+ label_destination: "Destination Account",
1855
+
1856
+ // Pending Dashboard
1857
+ pending_title: "Pending Transactions",
1858
+ pending_subtitle: "Monitoring and quick confirmation of pending or future transactions",
1859
+ pending_kpi_total: "Total Pending",
1860
+ pending_kpi_incomes: "Pending Incomes",
1861
+ pending_kpi_expenses: "Pending Expenses",
1862
+ pending_chart_incomes: "Pending Incomes Trend",
1863
+ pending_chart_expenses: "Pending Expenses Trend",
1864
+ btn_confirm: "Confirm",
1865
+ btn_edit: "Edit",
1866
+ btn_delete: "Delete",
1867
+ no_pending_transactions: "No pending transactions found for this period.",
1868
+ toast_success_confirm: "Transaction confirmed successfully!",
1869
+
1870
+ // Categories Dashboard
1871
+ categories_title: "Category Management",
1872
+ categories_subtitle: "Visualize, search, and manage categories and subcategories in a clean tree list",
1873
+ btn_new_category: "New Category",
1874
+ search_category_placeholder: "Search categories...",
1875
+ col_type: "Type",
1876
+ col_actions_cat: "Actions",
1877
+ subcategories_label: "Subcategories",
1878
+ no_subcategories: "No subcategories registered.",
1879
+ modal_new_cat_title: "New Category",
1880
+ modal_new_subcat_title: "New Subcategory",
1881
+ label_name: "Name",
1882
+ label_color: "Color",
1883
+ label_parent_category: "Parent Category (Read-Only)",
1884
+ toast_success_cat: "Category created successfully!",
1885
+ toast_success_subcat: "Subcategory created successfully!",
1886
+
1887
+ // Cards Dashboard
1888
+ cards_title: "Credit Cards",
1889
+ cards_subtitle: "Manage credit cards, credit limits, and statement history",
1890
+ card_bill_details: "Card Bill Details",
1891
+ btn_pay_bill: "Pay Bill",
1892
+ btn_revert_payment: "Revert Payment",
1893
+ bill_status: "Bill Status:",
1894
+ status_open: "Open",
1895
+ status_closed: "Closed",
1896
+ status_paid: "Paid",
1897
+ no_card_transactions: "No transactions recorded for this card bill in the selected cycle.",
1898
+
1899
+ // Dashboards Manager Dashboard
1900
+ dashboards_title: "Dashboards Monitor",
1901
+ dashboards_subtitle: "List, view source, and upload patty dashboards",
1902
+ col_dashboard: "Dashboard",
1903
+ col_last_update: "Last Updated",
1904
+ btn_view_source: "View Source",
1905
+ btn_download: "Download",
1906
+ upload_new_dashboard: "Upload New Dashboard",
1907
+ placeholder_dashboard_name: "Dashboard Name (e.g. pending)",
1908
+ upload_instructions: "Select or drop HTML file here to upload",
1909
+ btn_upload: "Upload",
1910
+ modal_source_title: "HTML Source Code",
1911
+
1912
+ // Tags Management
1913
+ menu_tags: "Tags",
1914
+ tags_title: "Tag Management",
1915
+ tags_subtitle: "Manage tags to label and organize your transactions",
1916
+ panel_title_tags: "Active Tags",
1917
+ btn_new_tag: "New Tag",
1918
+ label_tag_name: "Tag Name",
1919
+ placeholder_tag_name: "E.g. work, travel, refund",
1920
+ empty_tags_message: "No tags registered.",
1921
+ btn_save: "Save",
1922
+ btn_cancel: "Cancel",
1923
+ toast_success_tag_created: 'Tag "{name}" created successfully!',
1924
+ toast_success_tag_deleted: 'Tag "{name}" deleted successfully!',
1925
+ confirm_delete_tag: 'Are you sure you want to delete tag "{name}"?\n(This action will remove the tag from all linked transactions)'
1926
+ },
1927
+ pt: {
1928
+ // Sidebar Menu
1929
+ tooltip_overview: "Visão Geral",
1930
+ tooltip_pending: "Pendentes",
1931
+ tooltip_comparative: "Comparativo",
1932
+ tooltip_projections: "Projeções",
1933
+ tooltip_accounts: "Contas Bancárias",
1934
+ tooltip_cards: "Cartões de Crédito",
1935
+ menu_categories: "Categorias",
1936
+ menu_dashboards: "Dashboards",
1937
+
1938
+ // Month names
1939
+ january: "Janeiro", february: "Fevereiro", march: "Março", april: "Abril", may: "Maio", june: "Junho",
1940
+ july: "Julho", august: "Agosto", september: "Setembro", october: "Outubro", november: "Novembro", december: "Dezembro",
1941
+
1942
+ // General UI terms
1943
+ reference_label: "Referência:",
1944
+ day_sun: "Dom", day_mon: "Seg", day_tue: "Ter", day_wed: "Qua", day_thu: "Qui", day_fri: "Sex", day_sat: "Sáb",
1945
+ paid: "Pago", unpaid: "Não Pago", active: "Ativo", inactive: "Inativo",
1946
+
1947
+ // Overview Dashboard
1948
+ overview_title: "Visão Geral",
1949
+ overview_subtitle: "Consolidado financeiro mensal, calendário e atalhos rápidos",
1950
+ accounts_balance: "Saldo em Contas",
1951
+ expenses_month: "Despesas do Mês",
1952
+ card_bills: "Faturas de Cartão",
1953
+ incomes_month: "Receitas do Mês",
1954
+ final_projection: "Projeção Final:",
1955
+ recent_transactions: "Lançamentos Recentes",
1956
+ due_calendar: "Fluxo Diário",
1957
+ expenses_distribution: "Distribuição de Despesas",
1958
+ quick_shortcuts: "Atalhos Rápidos",
1959
+ new_transaction: "Novo Lançamento",
1960
+ new_transfer: "Nova Transferência",
1961
+ new_category: "Nova Categoria",
1962
+ new_card: "Novo Cartão",
1963
+ new_account: "Nova Conta",
1964
+ no_expenses_month: "Sem despesas registradas neste mês.",
1965
+ no_recent_transactions: "Nenhuma transação recente encontrada.",
1966
+ no_dues_period: "Sem vencimentos neste período.",
1967
+ income: "Receita",
1968
+ expense: "Despesa",
1969
+ paid_reconciled: "Pago / Conciliado",
1970
+
1971
+ // Projections / Heatmap Dashboard
1972
+ projections_title: "Projeção de Recorrências e Parcelas",
1973
+ projections_subtitle: "Mapeamento visual avançado e projeção de recorrências e parcelas ativas para os próximos meses",
1974
+ projection_label: "Projeção:",
1975
+ months_3: "3 Meses",
1976
+ months_6: "6 Meses",
1977
+ months_9: "9 Meses",
1978
+ months_12: "12 Meses",
1979
+ heatmap_income_title: "Receitas Recorrentes / Parceladas",
1980
+ heatmap_expense_title: "Despesas Recorrentes / Parceladas",
1981
+ total: "Total",
1982
+ no_recurrent_incomes: "Nenhuma receita recorrente/parcelada ativa no semestre.",
1983
+ no_recurrent_expenses: "Nenhuma despesa recorrente/parcelada ativa no semestre.",
1984
+ modal_details_title: "Detalhamento de Projeções",
1985
+ modal_details_subtitle: "Detalhes das transações projetadas para a categoria e mês",
1986
+ col_date: "Data",
1987
+ col_desc: "Descrição",
1988
+ col_value: "Valor",
1989
+ col_status: "Status",
1990
+ btn_close: "Fechar",
1991
+
1992
+ // Comparative Dashboard
1993
+ comparative_title: "Dashboard Comparativo",
1994
+ comparative_subtitle: "Análise e comparação mensal de receitas vs despesas e limites por categoria",
1995
+ month_summary_title: "Resumo do Mês",
1996
+ cat_spending_title: "Gastos por Categoria",
1997
+ card_limits_title: "Orçamentos e Limites de Categorias",
1998
+ col_category: "Categoria",
1999
+ col_limit: "Limite de Orçamento",
2000
+ col_spent: "Gasto",
2001
+ col_status_limit: "Status",
2002
+ col_percentage: "Porcentagem",
2003
+ within_limit: "Dentro do Limite",
2004
+ exceeded: "Excedido",
2005
+ reception: "Receitas",
2006
+ deduction: "Despesas",
2007
+ net_balance: "Saldo Líquido",
2008
+ performance: "Saúde Financeira",
2009
+ no_spending_month: "Sem despesas registradas por categoria neste mês.",
2010
+
2011
+ // Accounts Dashboard
2012
+ accounts_title: "Minhas Contas",
2013
+ accounts_subtitle: "Gerencie contas, consulte saldos e revise extratos",
2014
+ active_account_statement: "Extrato de Conta",
2015
+ btn_new_transaction: "Novo Lançamento",
2016
+ btn_new_transfer: "Nova Transferência",
2017
+ search_description_placeholder: "Digite para filtrar...",
2018
+ filter_type_label: "Tipo",
2019
+ filter_type_all: "Todos",
2020
+ filter_type_income: "Receitas",
2021
+ filter_type_expense: "Despesas",
2022
+ col_actions: "Ações",
2023
+ action_confirm: "Confirmar",
2024
+ action_edit: "Editar",
2025
+ action_delete: "Excluir",
2026
+ no_transactions_account: "Nenhum lançamento nesta conta para o mês selecionado.",
2027
+ confirm_delete_title: "Deseja excluir definitivamente a transação?",
2028
+ modal_new_tx_title: "Novo Lançamento",
2029
+ modal_new_transfer_title: "Nova Transferência",
2030
+ label_account: "Conta",
2031
+ label_description: "Descrição",
2032
+ label_value: "Valor",
2033
+ label_date: "Data",
2034
+ label_category: "Categoria / Subcategoria",
2035
+ label_type: "Tipo",
2036
+ label_status: "Status",
2037
+ status_pending: "Pendente",
2038
+ status_confirmed: "Pago / Confirmado",
2039
+ btn_cancel: "Cancelar",
2040
+ btn_save: "Salvar",
2041
+ label_origin: "Conta Origem",
2042
+ label_destination: "Conta Destino",
2043
+
2044
+ // Pending Dashboard
2045
+ pending_title: "Transações Pendentes",
2046
+ pending_subtitle: "Monitoramento e confirmação rápida de lançamentos pendentes ou futuros",
2047
+ pending_kpi_total: "Total Pendente",
2048
+ pending_kpi_incomes: "Receitas Pendentes",
2049
+ pending_kpi_expenses: "Despesas Pendentes",
2050
+ pending_chart_incomes: "Tendência de Receitas Pendentes",
2051
+ pending_chart_expenses: "Tendência de Despesas Pendentes",
2052
+ btn_confirm: "Confirmar",
2053
+ btn_edit: "Editar",
2054
+ btn_delete: "Excluir",
2055
+ no_pending_transactions: "Nenhuma transação pendente encontrada para este período.",
2056
+ toast_success_confirm: "Transação confirmada com sucesso!",
2057
+
2058
+ // Categories Dashboard
2059
+ categories_title: "Gerenciamento de Categorias",
2060
+ categories_subtitle: "Visualize, pesquise e gerencie categorias e subcategorias em árvore",
2061
+ btn_new_category: "Nova Categoria",
2062
+ search_category_placeholder: "Pesquisar categorias...",
2063
+ col_type: "Tipo",
2064
+ col_actions_cat: "Ações",
2065
+ subcategories_label: "Subcategorias",
2066
+ no_subcategories: "Nenhuma subcategoria cadastrada.",
2067
+ modal_new_cat_title: "Nova Categoria",
2068
+ modal_new_subcat_title: "Nova Subcategoria",
2069
+ label_name: "Nome",
2070
+ label_color: "Cor",
2071
+ label_parent_category: "Categoria Pai (Somente Leitura)",
2072
+ toast_success_cat: "Categoria criada com sucesso!",
2073
+ toast_success_subcat: "Subcategoria criada com sucesso!",
2074
+
2075
+ // Cards Dashboard
2076
+ cards_title: "Cartões de Crédito",
2077
+ cards_subtitle: "Gerencie cartões de crédito, limites e histórico de faturas",
2078
+ card_bill_details: "Detalhamento de Fatura",
2079
+ btn_pay_bill: "Pagar Fatura",
2080
+ btn_revert_payment: "Estornar Pagamento",
2081
+ bill_status: "Status da Fatura:",
2082
+ status_open: "Aberta",
2083
+ status_closed: "Fechada",
2084
+ status_paid: "Paga",
2085
+ no_card_transactions: "Nenhuma transação registrada nesta fatura para o ciclo selecionado.",
2086
+
2087
+ // Dashboards Manager Dashboard
2088
+ dashboards_title: "Monitor de Dashboards",
2089
+ dashboards_subtitle: "Liste, visualize o código fonte e envie dashboards para o servidor do patty",
2090
+ col_dashboard: "Dashboard",
2091
+ col_last_update: "Última Atualização",
2092
+ btn_view_source: "Ver Código",
2093
+ btn_download: "Baixar HTML",
2094
+ upload_new_dashboard: "Enviar Novo Dashboard",
2095
+ placeholder_dashboard_name: "Nome do Dashboard (ex: pending)",
2096
+ upload_instructions: "Selecione ou solte o arquivo HTML aqui para upload",
2097
+ btn_upload: "Fazer Upload",
2098
+ modal_source_title: "Código Fonte HTML",
2099
+
2100
+ // Tags Management
2101
+ menu_tags: "Tags",
2102
+ tags_title: "Gerenciar Tags",
2103
+ tags_subtitle: "Gerencie as tags utilizadas para rotular e categorizar suas transações",
2104
+ panel_title_tags: "Tags Ativas",
2105
+ btn_new_tag: "Nova Tag",
2106
+ label_tag_name: "Nome da Tag",
2107
+ placeholder_tag_name: "Ex: trabalho, viagem, reembolso",
2108
+ empty_tags_message: "Nenhuma tag cadastrada.",
2109
+ btn_save: "Salvar",
2110
+ btn_cancel: "Cancelar",
2111
+ toast_success_tag_created: 'Tag "{name}" criada com sucesso!',
2112
+ toast_success_tag_deleted: 'Tag "{name}" excluída com sucesso!',
2113
+ confirm_delete_tag: 'Deseja realmente excluir a tag "{name}"?\n(Esta ação removerá a tag de todas as transações vinculadas)'
2114
+ },
2115
+ es: {
2116
+ // Sidebar Menu
2117
+ tooltip_overview: "Vista General",
2118
+ tooltip_pending: "Pendientes",
2119
+ tooltip_comparative: "Comparativo",
2120
+ tooltip_projections: "Proyecciones",
2121
+ tooltip_accounts: "Cuentas Bancárias",
2122
+ tooltip_cards: "Tarjetas de Crédito",
2123
+ menu_categories: "Categorías",
2124
+ menu_dashboards: "Dashboards",
2125
+
2126
+ // Month names
2127
+ january: "Enero", february: "Febrero", march: "Marzo", april: "Abril", may: "Mayo", june: "Junio",
2128
+ july: "Julio", august: "Agosto", september: "Septiembre", october: "Octubre", november: "Noviembre", december: "Diciembre",
2129
+
2130
+ // General UI terms
2131
+ reference_label: "Referencia:",
2132
+ day_sun: "Dom", day_mon: "Lun", day_tue: "Mar", day_wed: "Mié", day_thu: "Jue", day_fri: "Vie", day_sat: "Sáb",
2133
+ paid: "Pagado", unpaid: "No Pagado", active: "Activo", inactive: "Inactivo",
2134
+
2135
+ // Overview Dashboard
2136
+ overview_title: "Vista General",
2137
+ overview_subtitle: "Resumen financiero mensual, calendario y accesos rápidos",
2138
+ accounts_balance: "Saldo en Cuentas",
2139
+ expenses_month: "Gastos del Mes",
2140
+ card_bills: "Facturas de Tarjeta",
2141
+ incomes_month: "Ingresos del Mes",
2142
+ final_projection: "Proyección Final:",
2143
+ recent_transactions: "Transacciones Recientes",
2144
+ due_calendar: "Calendario de Pagos",
2145
+ expenses_distribution: "Distribución de Gastos",
2146
+ quick_shortcuts: "Accesos Rápidos",
2147
+ new_transaction: "Nueva Transacción",
2148
+ new_transfer: "Nueva Transferencia",
2149
+ new_category: "Nueva Categoría",
2150
+ new_card: "Nueva Tarjeta",
2151
+ new_account: "Nueva Cuenta",
2152
+ no_expenses_month: "No hay gastos registrados este mes.",
2153
+ no_recent_transactions: "No se encontraron transacciones recientes.",
2154
+ no_dues_period: "Sin vencimientos en este período.",
2155
+ income: "Ingreso",
2156
+ expense: "Gasto",
2157
+ paid_reconciled: "Pagado / Conciliado",
2158
+
2159
+ // Projections / Heatmap Dashboard
2160
+ projections_title: "Proyección de Recurrencias y Cuotas",
2161
+ projections_subtitle: "Mapeo visual avanzado y proyección de recurrencias y cuotas activas para los próximos meses",
2162
+ projection_label: "Proyección:",
2163
+ months_3: "3 Meses",
2164
+ months_6: "6 Meses",
2165
+ months_9: "9 Meses",
2166
+ months_12: "12 Meses",
2167
+ heatmap_income_title: "Ingresos Recurrentes / Cuotas",
2168
+ heatmap_expense_title: "Gastos Recurrentes / Cuotas",
2169
+ total: "Total",
2170
+ no_recurrent_incomes: "Ningún ingreso recurrente o en cuotas activo en el semestre seleccionado.",
2171
+ no_recurrent_expenses: "Ningún gasto recurrente o en cuotas activo en el semestre seleccionado.",
2172
+ modal_details_title: "Detalle de Proyecciones",
2173
+ modal_details_subtitle: "Detalles de transacciones proyectadas para la categoría y mes",
2174
+ col_date: "Fecha",
2175
+ col_desc: "Descripción",
2176
+ col_value: "Valor",
2177
+ col_status: "Estado",
2178
+ btn_close: "Cerrar",
2179
+
2180
+ // Comparative Dashboard
2181
+ comparative_title: "Dashboard Comparativo",
2182
+ comparative_subtitle: "Análisis y comparación mensual de ingresos vs gastos y límites por categoría",
2183
+ month_summary_title: "Resumen del Mes",
2184
+ cat_spending_title: "Gastos por Categoría",
2185
+ card_limits_title: "Presupuestos y Límites de Categorías",
2186
+ col_category: "Categoría",
2187
+ col_limit: "Límite de Presupuesto",
2188
+ col_spent: "Gastado",
2189
+ col_status_limit: "Estado",
2190
+ col_percentage: "Porcentaje",
2191
+ within_limit: "Dentro del Límite",
2192
+ exceeded: "Excedido",
2193
+ reception: "Ingresos",
2194
+ deduction: "Gastos",
2195
+ net_balance: "Saldo Neto",
2196
+ performance: "Salud Financiera",
2197
+ no_spending_month: "No hay gastos registrados por categoría este mes.",
2198
+
2199
+ // Accounts Dashboard
2200
+ accounts_title: "Cuentas Bancarias",
2201
+ accounts_subtitle: "Administre cuentas, consulte saldos y revise extractos",
2202
+ active_account_statement: "Extracto de Cuenta",
2203
+ btn_new_transaction: "Nueva Transacción",
2204
+ btn_new_transfer: "Nueva Transferencia",
2205
+ search_description_placeholder: "Escriba para filtrar...",
2206
+ filter_type_label: "Tipo",
2207
+ filter_type_all: "Todos",
2208
+ filter_type_income: "Ingresos",
2209
+ filter_type_expense: "Gastos",
2210
+ col_actions: "Acciones",
2211
+ action_confirm: "Confirmar",
2212
+ action_edit: "Editar",
2213
+ action_delete: "Eliminar",
2214
+ no_transactions_account: "No hay transacciones registradas en esta cuenta en el mes seleccionado.",
2215
+ confirm_delete_title: "¿Está seguro de eliminar definitivamente esta transacción?",
2216
+ modal_new_tx_title: "Nueva Transacción",
2217
+ modal_new_transfer_title: "Nueva Transferencia",
2218
+ label_account: "Cuenta",
2219
+ label_description: "Descripción",
2220
+ label_value: "Valor",
2221
+ label_date: "Fecha",
2222
+ label_category: "Categoría / Subcategoría",
2223
+ label_type: "Tipo",
2224
+ label_status: "Estado",
2225
+ status_pending: "Pendiente",
2226
+ status_confirmed: "Pagado / Confirmado",
2227
+ btn_cancel: "Cancelar",
2228
+ btn_save: "Guardar",
2229
+ label_origin: "Cuenta Origen",
2230
+ label_destination: "Cuenta Destino",
2231
+
2232
+ // Pending Dashboard
2233
+ pending_title: "Transacciones Pendientes",
2234
+ pending_subtitle: "Monitoreo y confirmación rápida de transacciones pendientes o futuras",
2235
+ pending_kpi_total: "Total Pendiente",
2236
+ pending_kpi_incomes: "Ingresos Pendientes",
2237
+ pending_kpi_expenses: "Gastos Pendientes",
2238
+ pending_chart_incomes: "Tendencia de Ingresos Pendientes",
2239
+ pending_chart_expenses: "Tendencia de Gastos Pendientes",
2240
+ btn_confirm: "Confirmar",
2241
+ btn_edit: "Editar",
2242
+ btn_delete: "Eliminar",
2243
+ no_pending_transactions: "No se encontraron transacciones pendientes en este período.",
2244
+ toast_success_confirm: "¡Transacción confirmada con éxito!",
2245
+
2246
+ // Categories Dashboard
2247
+ categories_title: "Gestión de Categorías",
2248
+ categories_subtitle: "Visualice, busque y gestione categorías y subcategorías en árbol",
2249
+ btn_new_category: "Nueva Categoría",
2250
+ search_category_placeholder: "Buscar categorías...",
2251
+ col_type: "Tipo",
2252
+ col_actions_cat: "Acciones",
2253
+ subcategories_label: "Subcategorías",
2254
+ no_subcategories: "Ninguna subcategoría registrada.",
2255
+ modal_new_cat_title: "Nueva Categoría",
2256
+ modal_new_subcat_title: "Nueva Subcategoría",
2257
+ label_name: "Nombre",
2258
+ label_color: "Color",
2259
+ label_parent_category: "Categoría Padre (Solo Lectura)",
2260
+ toast_success_cat: "¡Categoría creada con éxito!",
2261
+ toast_success_subcat: "¡Subcategoría creada con éxito!",
2262
+
2263
+ // Cards Dashboard
2264
+ cards_title: "Tarjetas de Crédito",
2265
+ cards_subtitle: "Gestione tarjetas de crédito, límites y facturas",
2266
+ card_bill_details: "Detalle de Factura",
2267
+ btn_pay_bill: "Pagar Factura",
2268
+ btn_revert_payment: "Revertir Pago",
2269
+ bill_status: "Estado de la Factura:",
2270
+ status_open: "Abierta",
2271
+ status_closed: "Cerrada",
2272
+ status_paid: "Pagada",
2273
+ no_card_transactions: "Ninguna transacción registrada en esta factura para el ciclo seleccionado.",
2274
+
2275
+ // Dashboards Manager Dashboard
2276
+ dashboards_title: "Gestor de Dashboards",
2277
+ dashboards_subtitle: "Liste, vea el código fuente y suba dashboards al servidor de patty",
2278
+ col_dashboard: "Dashboard",
2279
+ col_last_update: "Última Actualización",
2280
+ btn_view_source: "Ver Código",
2281
+ btn_download: "Descargar HTML",
2282
+ upload_new_dashboard: "Subir Nuevo Dashboard",
2283
+ placeholder_dashboard_name: "Nombre del Dashboard (ej: pending)",
2284
+ upload_instructions: "Seleccione o arrastre el archivo HTML aquí para subir",
2285
+ btn_upload: "Subir Dashboard",
2286
+ modal_source_title: "Código Fuente HTML",
2287
+
2288
+ // Tags Management
2289
+ menu_tags: "Etiquetas",
2290
+ tags_title: "Administrar Etiquetas",
2291
+ tags_subtitle: "Administre las etiquetas utilizadas para etiquetar y organizar sus transacciones",
2292
+ panel_title_tags: "Etiquetas Activas",
2293
+ btn_new_tag: "Nueva Etiqueta",
2294
+ label_tag_name: "Nombre de la Etiqueta",
2295
+ placeholder_tag_name: "Ej: trabajo, viaje, reembolso",
2296
+ empty_tags_message: "No hay etiquetas registradas.",
2297
+ btn_save: "Guardar",
2298
+ btn_cancel: "Cancelar",
2299
+ toast_success_tag_created: '¡Etiqueta "{name}" creada con éxito!',
2300
+ toast_success_tag_deleted: '¡Etiqueta "{name}" eliminada con éxito!',
2301
+ confirm_delete_tag: '¿Realmente deseja eliminar la etiqueta "{name}"?\n(Esta acción eliminará la etiqueta de todas las transacciones vinculadas)'
2302
+ }
2303
+ };
2304
+
2305
+ var currentLocale = 'en'; // English as default
2306
+
2307
+ // Helper to translate in JS
2308
+ function t(key) {
2309
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
2310
+ return tDict[key] || key;
2311
+ }
2312
+
2313
+ async function checkLocale() {
2314
+ try {
2315
+ const res = await fetch('/api/status');
2316
+ if (res.ok) {
2317
+ const data = await res.json();
2318
+ if (data.locale && TRANSLATIONS[data.locale]) {
2319
+ currentLocale = data.locale;
2320
+ }
2321
+ }
2322
+ } catch (err) {
2323
+ console.error("Failed to read locale preferences:", err);
2324
+ }
2325
+ translatePage();
2326
+ }
2327
+
2328
+ function translatePage() {
2329
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
2330
+
2331
+ // 1. Static texts
2332
+ document.querySelectorAll('[data-i18n]').forEach(el => {
2333
+ const key = el.getAttribute('data-i18n');
2334
+ if (tDict[key]) {
2335
+ const icon = el.querySelector('i');
2336
+ if (icon) {
2337
+ const iconOuter = icon.outerHTML;
2338
+ el.innerHTML = iconOuter + ' ' + tDict[key];
2339
+ } else {
2340
+ el.textContent = tDict[key];
2341
+ }
2342
+ }
2343
+ });
2344
+
2345
+ // 2. Placeholders
2346
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
2347
+ const key = el.getAttribute('data-i18n-placeholder');
2348
+ if (tDict[key]) {
2349
+ el.placeholder = tDict[key];
2350
+ }
2351
+ });
2352
+
2353
+ // 3. Tooltips
2354
+ document.querySelectorAll('[data-i18n-tooltip]').forEach(el => {
2355
+ const key = el.getAttribute('data-i18n-tooltip');
2356
+ if (tDict[key]) {
2357
+ el.setAttribute('data-tooltip', tDict[key]);
2358
+ }
2359
+ });
2360
+
2361
+ // 4. Document title translation
2362
+ if (tDict['overview_title'] && document.title.includes("Overview") || document.title.includes("Visão")) {
2363
+ // dynamic title update fallback if needed
2364
+ }
2365
+
2366
+ // 5. Translate select months
2367
+ const monthSelects = [
2368
+ document.getElementById('month-select'),
2369
+ document.getElementById('start-month-select')
2370
+ ];
2371
+ monthSelects.forEach(monthSelect => {
2372
+ if (monthSelect) {
2373
+ const monthKeys = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
2374
+ Array.from(monthSelect.options).forEach((opt, idx) => {
2375
+ const key = monthKeys[idx];
2376
+ if (tDict[key]) {
2377
+ opt.textContent = tDict[key];
2378
+ }
2379
+ });
2380
+ }
2381
+ });
2382
+
2383
+ // 6. Translate projection months select options (3, 6, 9, 12 months)
2384
+ const hmSelect = document.getElementById('heatmap-months-select');
2385
+ if (hmSelect) {
2386
+ Array.from(hmSelect.options).forEach(opt => {
2387
+ const val = opt.value;
2388
+ const key = `months_${val}`;
2389
+ if (tDict[key]) {
2390
+ opt.textContent = tDict[key];
2391
+ }
2392
+ });
2393
+ }
2394
+
2395
+ // Automatically initialize/refresh custom selects on all pages
2396
+ if (typeof initCustomSelects === 'function') {
2397
+ initCustomSelects();
2398
+ }
2399
+ }
2400
+
2401
+ // Custom Select Component implementation
2402
+ function initCustomSelects() {
2403
+ document.querySelectorAll('select.select-custom').forEach(select => {
2404
+ if (select.nextElementSibling && select.nextElementSibling.classList.contains('select-container-custom')) {
2405
+ // Already initialized, just sync selected value
2406
+ const container = select.nextElementSibling;
2407
+ const triggerSpan = container.querySelector('.select-trigger-custom span');
2408
+ const selectedOpt = select.options[select.selectedIndex];
2409
+ if (selectedOpt && triggerSpan) {
2410
+ triggerSpan.textContent = selectedOpt.textContent;
2411
+ }
2412
+ return;
2413
+ }
2414
+ select.style.display = 'none';
2415
+ const container = document.createElement('div');
2416
+ container.className = 'select-container-custom';
2417
+
2418
+ // Match specific element custom min-widths
2419
+ if (select.id === 'heatmap-months-select') {
2420
+ container.style.minWidth = '110px';
2421
+ } else if (select.id === 'year-select') {
2422
+ container.style.minWidth = '90px';
2423
+ } else if (select.id === 'filter-type') {
2424
+ container.style.minWidth = '130px';
2425
+ }
2426
+
2427
+ const trigger = document.createElement('div');
2428
+ trigger.className = 'select-trigger-custom';
2429
+ const triggerSpan = document.createElement('span');
2430
+ trigger.appendChild(triggerSpan);
2431
+ container.appendChild(trigger);
2432
+ const optionsContainer = document.createElement('div');
2433
+ optionsContainer.className = 'select-options-custom';
2434
+ container.appendChild(optionsContainer);
2435
+
2436
+ function syncSelected() {
2437
+ const selectedOpt = select.options[select.selectedIndex] || select.options[0];
2438
+ if (selectedOpt) {
2439
+ triggerSpan.textContent = selectedOpt.textContent;
2440
+ Array.from(optionsContainer.children).forEach(child => {
2441
+ if (child.getAttribute('data-value') === select.value) {
2442
+ child.classList.add('selected');
2443
+ } else {
2444
+ child.classList.remove('selected');
2445
+ }
2446
+ });
2447
+ }
2448
+ }
2449
+
2450
+ function populateOptions() {
2451
+ optionsContainer.innerHTML = '';
2452
+ Array.from(select.options).forEach(opt => {
2453
+ const optDiv = document.createElement('div');
2454
+ optDiv.className = 'select-option-custom';
2455
+ optDiv.textContent = opt.textContent;
2456
+ optDiv.setAttribute('data-value', opt.value);
2457
+ optDiv.addEventListener('click', (e) => {
2458
+ e.stopPropagation();
2459
+ select.value = opt.value;
2460
+ select.dispatchEvent(new Event('change'));
2461
+ syncSelected();
2462
+ container.classList.remove('open');
2463
+ });
2464
+ optionsContainer.appendChild(optDiv);
2465
+ });
2466
+ }
2467
+
2468
+ populateOptions();
2469
+ syncSelected();
2470
+
2471
+ trigger.addEventListener('click', (e) => {
2472
+ e.stopPropagation();
2473
+ const isOpen = container.classList.contains('open');
2474
+ document.querySelectorAll('.select-container-custom').forEach(el => {
2475
+ el.classList.remove('open');
2476
+ });
2477
+ if (!isOpen) {
2478
+ populateOptions();
2479
+ syncSelected();
2480
+ container.classList.add('open');
2481
+ setTimeout(() => {
2482
+ const selectedEl = optionsContainer.querySelector('.select-option-custom.selected');
2483
+ if (selectedEl) {
2484
+ const itemHeight = selectedEl.offsetHeight || 36;
2485
+ optionsContainer.scrollTop = Math.max(0, selectedEl.offsetTop - itemHeight);
2486
+ }
2487
+ }, 10);
2488
+ }
2489
+ });
2490
+
2491
+ select.parentNode.insertBefore(container, select.nextSibling);
2492
+ select.addEventListener('change', syncSelected);
2493
+
2494
+ // Watch for dynamic options updates
2495
+ const observer = new MutationObserver(() => {
2496
+ syncSelected();
2497
+ });
2498
+ observer.observe(select, { childList: true, subtree: true });
2499
+
2500
+ setTimeout(syncSelected, 200);
2501
+ setTimeout(syncSelected, 1000);
2502
+ });
2503
+
2504
+ // Global click listener to close options dropdowns when clicking outside
2505
+ if (!window.customSelectGlobalBound) {
2506
+ window.customSelectGlobalBound = true;
2507
+ document.addEventListener('click', () => {
2508
+ document.querySelectorAll('.select-container-custom').forEach(el => {
2509
+ el.classList.remove('open');
2510
+ });
2511
+ });
2512
+ }
2513
+ }
2514
+
2515
+ runInit();
2516
+
2517
+ // ADR-027 Live-update listener
2518
+ window.onAppDataChanged = function(entities) {
2519
+ var affected = entities.some(function(tag) {
2520
+ return ['transaction', 'recurring', 'account', 'category', 'userSettings'].indexOf(tag) !== -1;
2521
+ });
2522
+ if (affected) {
2523
+ console.log("projections refetching due to entity change:", entities);
2524
+ refreshProjections();
2525
+ }
2526
+ };
2527
+
2528
+ </script>